authentik.enterprise.agents.api
1from django.utils.translation import gettext_lazy as _ 2from drf_spectacular.utils import extend_schema 3from rest_framework.exceptions import PermissionDenied 4from rest_framework.fields import ( 5 BooleanField, 6 CharField, 7 ChoiceField, 8 DateTimeField, 9 SerializerMethodField, 10) 11from rest_framework.mixins import ( 12 DestroyModelMixin, 13 ListModelMixin, 14 RetrieveModelMixin, 15 UpdateModelMixin, 16) 17from rest_framework.relations import PrimaryKeyRelatedField 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.core.api.groups import PartialUserSerializer 24from authentik.core.api.utils import PassiveSerializer 25from authentik.core.models import ( 26 ActorPolicyInheritance, 27 Token, 28 TokenIntents, 29 User, 30 UserTypes, 31 default_token_duration, 32) 33from authentik.enterprise.agents.models import Agent 34from authentik.enterprise.api import EnterpriseRequiredMixin, enterprise_action 35 36 37class AgentSerializer(EnterpriseRequiredMixin, PartialUserSerializer): 38 39 parent = PartialUserSerializer(read_only=True) 40 # Chosen at creation only; immutable afterwards. 41 policy_behavior = ChoiceField(choices=ActorPolicyInheritance.choices, read_only=True) 42 token_identifier = SerializerMethodField() 43 44 def get_token_identifier(self, agent: Agent) -> str | None: 45 """Identifier of the agent's API token, so its key can be retrieved/copied later.""" 46 token = Token.objects.filter(user=agent, intent=TokenIntents.INTENT_API).first() 47 return token.identifier if token else None 48 49 class Meta: 50 model = Agent 51 fields = PartialUserSerializer.Meta.fields + [ 52 "uuid", 53 "expiring", 54 "expires", 55 "parent", 56 "policy_behavior", 57 "token_identifier", 58 ] 59 60 61class AgentCreatedSerializer(PassiveSerializer): 62 """Response returned once when an agent is created, carrying the one-time API token.""" 63 64 agent = AgentSerializer(read_only=True) 65 token = CharField(read_only=True) 66 67 68class AgentViewSet( 69 RetrieveModelMixin, 70 UpdateModelMixin, 71 DestroyModelMixin, 72 ListModelMixin, 73 GenericViewSet, 74): 75 """Admin-provisioned delegate identities. An admin creates a Agent for a given 76 parent user, then grants it access the same way as any other User -- ordinary 77 PolicyBindings pointed at whatever it needs.""" 78 79 queryset = Agent.objects.all() 80 serializer_class = AgentSerializer 81 owner_field = "parent" 82 rbac_allow_create_without_perm = True 83 filterset_fields = ["parent"] 84 85 class AgentCreateSerializer(PassiveSerializer): 86 87 parent = PrimaryKeyRelatedField( 88 queryset=User.objects.all(), required=False, default=None, allow_null=True 89 ) 90 label = CharField(required=False, allow_blank=True) 91 expiring = BooleanField(required=False, default=False) 92 expires = DateTimeField(required=False, allow_null=True, default=None) 93 policy_behavior = ChoiceField( 94 choices=ActorPolicyInheritance.choices, 95 default=ActorPolicyInheritance.MIRROR, 96 required=False, 97 ) 98 99 @extend_schema(request=AgentCreateSerializer, responses={201: AgentCreatedSerializer}) 100 @validate(AgentCreateSerializer) 101 @enterprise_action 102 def create(self, request: Request, body: AgentCreateSerializer) -> Response: 103 parent: User | None = body.validated_data.get("parent") 104 self_service_perm = request.user.has_perm("authentik_agents.add_agent_self_service") 105 admin_perm = request.user.has_perm("authentik_agents.add_agent") 106 # Self-service = creating an agent for yourself; provisioning for another user is an 107 # admin action. The distinction is ownership, not merely holding the permission. 108 self_service = parent == request.user 109 110 if not admin_perm: 111 if not self_service: 112 raise PermissionDenied(_("You can only create agents for yourself.")) 113 if not self_service_perm: 114 raise PermissionDenied(_("Self-service agent creation is not enabled.")) 115 if request.user.type != UserTypes.INTERNAL: 116 raise PermissionDenied(_("Only internal user accounts can create agents.")) 117 118 if self_service: 119 # Self-service agents are least-privilege by construction: they always expire with the 120 # tenant default and inherit NO access from their owner. They earn access the same way 121 # a human does -- by filing a grant request their owner approves (see 122 # authentik.enterprise.requests). 123 expiring = True 124 expires = default_token_duration() 125 policy_behavior = ActorPolicyInheritance.NONE 126 else: 127 # Provisioning for another user may set a custom/standing expiry and policy behavior. 128 expiring = body.validated_data["expiring"] 129 expires = body.validated_data["expires"] 130 policy_behavior = body.validated_data["policy_behavior"] 131 agent = Agent.create_for_user( 132 user=parent, 133 name=body.validated_data.get("label", ""), 134 expiring=expiring, 135 expires=expires, 136 policy_behavior=policy_behavior, 137 ) 138 # Issue an API token so a harness can authenticate as the agent (Bearer auth). 139 token = Token.objects.create( 140 identifier=agent.username, 141 intent=TokenIntents.INTENT_API, 142 user=agent, 143 expiring=True, 144 expires=default_token_duration(), 145 ) 146 if self_service: 147 parent.assign_perms_to_managed_role( 148 [ 149 "authentik_agents.view_agent", 150 "authentik_agents.change_agent", 151 "authentik_agents.delete_agent", 152 ], 153 agent, 154 ) 155 # Grant the owner access to the token key so it stays retrievable after creation. 156 parent.assign_perms_to_managed_role("authentik_core.view_token_key", token) 157 return Response( 158 AgentCreatedSerializer({"agent": agent, "token": token.key}).data, status=201 159 )
class
AgentSerializer(authentik.enterprise.api.EnterpriseRequiredMixin, authentik.core.api.groups.PartialUserSerializer):
38class AgentSerializer(EnterpriseRequiredMixin, PartialUserSerializer): 39 40 parent = PartialUserSerializer(read_only=True) 41 # Chosen at creation only; immutable afterwards. 42 policy_behavior = ChoiceField(choices=ActorPolicyInheritance.choices, read_only=True) 43 token_identifier = SerializerMethodField() 44 45 def get_token_identifier(self, agent: Agent) -> str | None: 46 """Identifier of the agent's API token, so its key can be retrieved/copied later.""" 47 token = Token.objects.filter(user=agent, intent=TokenIntents.INTENT_API).first() 48 return token.identifier if token else None 49 50 class Meta: 51 model = Agent 52 fields = PartialUserSerializer.Meta.fields + [ 53 "uuid", 54 "expiring", 55 "expires", 56 "parent", 57 "policy_behavior", 58 "token_identifier", 59 ]
Mixin to validate that a valid enterprise license exists before allowing to save the object
45 def get_token_identifier(self, agent: Agent) -> str | None: 46 """Identifier of the agent's API token, so its key can be retrieved/copied later.""" 47 token = Token.objects.filter(user=agent, intent=TokenIntents.INTENT_API).first() 48 return token.identifier if token else None
Identifier of the agent's API token, so its key can be retrieved/copied later.
class
AgentSerializer.Meta:
50 class Meta: 51 model = Agent 52 fields = PartialUserSerializer.Meta.fields + [ 53 "uuid", 54 "expiring", 55 "expires", 56 "parent", 57 "policy_behavior", 58 "token_identifier", 59 ]
model =
<class 'authentik.enterprise.agents.models.Agent'>
62class AgentCreatedSerializer(PassiveSerializer): 63 """Response returned once when an agent is created, carrying the one-time API token.""" 64 65 agent = AgentSerializer(read_only=True) 66 token = CharField(read_only=True)
Response returned once when an agent is created, carrying the one-time API token.
Inherited Members
class
AgentViewSet(rest_framework.mixins.RetrieveModelMixin, rest_framework.mixins.UpdateModelMixin, rest_framework.mixins.DestroyModelMixin, rest_framework.mixins.ListModelMixin, rest_framework.viewsets.GenericViewSet):
69class AgentViewSet( 70 RetrieveModelMixin, 71 UpdateModelMixin, 72 DestroyModelMixin, 73 ListModelMixin, 74 GenericViewSet, 75): 76 """Admin-provisioned delegate identities. An admin creates a Agent for a given 77 parent user, then grants it access the same way as any other User -- ordinary 78 PolicyBindings pointed at whatever it needs.""" 79 80 queryset = Agent.objects.all() 81 serializer_class = AgentSerializer 82 owner_field = "parent" 83 rbac_allow_create_without_perm = True 84 filterset_fields = ["parent"] 85 86 class AgentCreateSerializer(PassiveSerializer): 87 88 parent = PrimaryKeyRelatedField( 89 queryset=User.objects.all(), required=False, default=None, allow_null=True 90 ) 91 label = CharField(required=False, allow_blank=True) 92 expiring = BooleanField(required=False, default=False) 93 expires = DateTimeField(required=False, allow_null=True, default=None) 94 policy_behavior = ChoiceField( 95 choices=ActorPolicyInheritance.choices, 96 default=ActorPolicyInheritance.MIRROR, 97 required=False, 98 ) 99 100 @extend_schema(request=AgentCreateSerializer, responses={201: AgentCreatedSerializer}) 101 @validate(AgentCreateSerializer) 102 @enterprise_action 103 def create(self, request: Request, body: AgentCreateSerializer) -> Response: 104 parent: User | None = body.validated_data.get("parent") 105 self_service_perm = request.user.has_perm("authentik_agents.add_agent_self_service") 106 admin_perm = request.user.has_perm("authentik_agents.add_agent") 107 # Self-service = creating an agent for yourself; provisioning for another user is an 108 # admin action. The distinction is ownership, not merely holding the permission. 109 self_service = parent == request.user 110 111 if not admin_perm: 112 if not self_service: 113 raise PermissionDenied(_("You can only create agents for yourself.")) 114 if not self_service_perm: 115 raise PermissionDenied(_("Self-service agent creation is not enabled.")) 116 if request.user.type != UserTypes.INTERNAL: 117 raise PermissionDenied(_("Only internal user accounts can create agents.")) 118 119 if self_service: 120 # Self-service agents are least-privilege by construction: they always expire with the 121 # tenant default and inherit NO access from their owner. They earn access the same way 122 # a human does -- by filing a grant request their owner approves (see 123 # authentik.enterprise.requests). 124 expiring = True 125 expires = default_token_duration() 126 policy_behavior = ActorPolicyInheritance.NONE 127 else: 128 # Provisioning for another user may set a custom/standing expiry and policy behavior. 129 expiring = body.validated_data["expiring"] 130 expires = body.validated_data["expires"] 131 policy_behavior = body.validated_data["policy_behavior"] 132 agent = Agent.create_for_user( 133 user=parent, 134 name=body.validated_data.get("label", ""), 135 expiring=expiring, 136 expires=expires, 137 policy_behavior=policy_behavior, 138 ) 139 # Issue an API token so a harness can authenticate as the agent (Bearer auth). 140 token = Token.objects.create( 141 identifier=agent.username, 142 intent=TokenIntents.INTENT_API, 143 user=agent, 144 expiring=True, 145 expires=default_token_duration(), 146 ) 147 if self_service: 148 parent.assign_perms_to_managed_role( 149 [ 150 "authentik_agents.view_agent", 151 "authentik_agents.change_agent", 152 "authentik_agents.delete_agent", 153 ], 154 agent, 155 ) 156 # Grant the owner access to the token key so it stays retrievable after creation. 157 parent.assign_perms_to_managed_role("authentik_core.view_token_key", token) 158 return Response( 159 AgentCreatedSerializer({"agent": agent, "token": token.key}).data, status=201 160 )
Admin-provisioned delegate identities. An admin creates a Agent for a given parent user, then grants it access the same way as any other User -- ordinary PolicyBindings pointed at whatever it needs.
serializer_class =
<class 'AgentSerializer'>
@extend_schema(request=AgentCreateSerializer, responses={201: AgentCreatedSerializer})
@validate(AgentCreateSerializer)
@enterprise_action
def
create( self, request: rest_framework.request.Request, body: AgentViewSet.AgentCreateSerializer) -> rest_framework.response.Response:
100 @extend_schema(request=AgentCreateSerializer, responses={201: AgentCreatedSerializer}) 101 @validate(AgentCreateSerializer) 102 @enterprise_action 103 def create(self, request: Request, body: AgentCreateSerializer) -> Response: 104 parent: User | None = body.validated_data.get("parent") 105 self_service_perm = request.user.has_perm("authentik_agents.add_agent_self_service") 106 admin_perm = request.user.has_perm("authentik_agents.add_agent") 107 # Self-service = creating an agent for yourself; provisioning for another user is an 108 # admin action. The distinction is ownership, not merely holding the permission. 109 self_service = parent == request.user 110 111 if not admin_perm: 112 if not self_service: 113 raise PermissionDenied(_("You can only create agents for yourself.")) 114 if not self_service_perm: 115 raise PermissionDenied(_("Self-service agent creation is not enabled.")) 116 if request.user.type != UserTypes.INTERNAL: 117 raise PermissionDenied(_("Only internal user accounts can create agents.")) 118 119 if self_service: 120 # Self-service agents are least-privilege by construction: they always expire with the 121 # tenant default and inherit NO access from their owner. They earn access the same way 122 # a human does -- by filing a grant request their owner approves (see 123 # authentik.enterprise.requests). 124 expiring = True 125 expires = default_token_duration() 126 policy_behavior = ActorPolicyInheritance.NONE 127 else: 128 # Provisioning for another user may set a custom/standing expiry and policy behavior. 129 expiring = body.validated_data["expiring"] 130 expires = body.validated_data["expires"] 131 policy_behavior = body.validated_data["policy_behavior"] 132 agent = Agent.create_for_user( 133 user=parent, 134 name=body.validated_data.get("label", ""), 135 expiring=expiring, 136 expires=expires, 137 policy_behavior=policy_behavior, 138 ) 139 # Issue an API token so a harness can authenticate as the agent (Bearer auth). 140 token = Token.objects.create( 141 identifier=agent.username, 142 intent=TokenIntents.INTENT_API, 143 user=agent, 144 expiring=True, 145 expires=default_token_duration(), 146 ) 147 if self_service: 148 parent.assign_perms_to_managed_role( 149 [ 150 "authentik_agents.view_agent", 151 "authentik_agents.change_agent", 152 "authentik_agents.delete_agent", 153 ], 154 agent, 155 ) 156 # Grant the owner access to the token key so it stays retrievable after creation. 157 parent.assign_perms_to_managed_role("authentik_core.view_token_key", token) 158 return Response( 159 AgentCreatedSerializer({"agent": agent, "token": token.key}).data, status=201 160 )
86 class AgentCreateSerializer(PassiveSerializer): 87 88 parent = PrimaryKeyRelatedField( 89 queryset=User.objects.all(), required=False, default=None, allow_null=True 90 ) 91 label = CharField(required=False, allow_blank=True) 92 expiring = BooleanField(required=False, default=False) 93 expires = DateTimeField(required=False, allow_null=True, default=None) 94 policy_behavior = ChoiceField( 95 choices=ActorPolicyInheritance.choices, 96 default=ActorPolicyInheritance.MIRROR, 97 required=False, 98 )
Base serializer class which doesn't implement create/update methods