authentik.enterprise.agents.models

 1from typing import Self
 2
 3from django.db.models import QuerySet
 4from django.utils.translation import gettext_lazy as _
 5
 6from authentik.core.models import (
 7    USER_PATH_SYSTEM_PREFIX,
 8    USERNAME_MAX_LENGTH,
 9    Actor,
10    ActorPolicyInheritance,
11    User,
12    UserTypes,
13)
14from authentik.lib.generators import generate_id
15
16USER_PATH_AGENTS = f"{USER_PATH_SYSTEM_PREFIX}/agents"
17
18
19class AgentUserQuerySet(QuerySet):
20    """Select users by their agent relationship."""
21
22    def filter_agents(self) -> Self:
23        """Include only agent users."""
24        return self.filter(actor__agent__isnull=False)
25
26    def exclude_agents(self) -> Self:
27        """Exclude agent users."""
28        return self.filter(actor__agent__isnull=True)
29
30
31class Agent(Actor):
32
33    class Meta(Actor.Meta):
34        verbose_name = _("Agent")
35        verbose_name_plural = _("Agents")
36        # expires/expiring live on the parent Actor table under multi-table inheritance, so the
37        # indexes inherited from Actor.Meta (via ExpiringModel.Meta) don't apply to Agent itself.
38        indexes = []
39        permissions = [
40            ("add_agent_self_service", _("Add an agent user (self-service)")),
41        ]
42
43    @classmethod
44    def create_for_user(
45        cls,
46        user: User,
47        name: str = "",
48        expiring: bool = False,
49        expires=None,
50        policy_behavior: str = ActorPolicyInheritance.MIRROR,
51    ) -> Agent:
52        # An agent is a machine identity, not a login user: mark it as a service account
53        # and disable password auth. It authenticates through its issued API token. By default
54        # it MIRRORs its parent, so it can never exceed the access of the user it acts for.
55        name_prefix = "authentik:system"
56        if user:
57            name_prefix = user.username
58        agent = cls.objects.create(
59            username=f"{name_prefix}-agent-{generate_id()}"[:USERNAME_MAX_LENGTH],
60            name=name,
61            parent=user,
62            policy_behavior=policy_behavior,
63            type=UserTypes.SERVICE_ACCOUNT,
64            path=USER_PATH_AGENTS,
65            expiring=expiring,
66            expires=expires,
67        )
68        if policy_behavior == ActorPolicyInheritance.COPY:
69            agent.copy_parent_policy_bindings()
70        return agent
71
72    @property
73    def serializer(self):
74        from authentik.enterprise.agents.api import AgentSerializer
75
76        return AgentSerializer
77
78    def __str__(self):
79        return f"Agent {self.username} for {self.parent_id}"
USER_PATH_AGENTS = 'goauthentik.io/agents'
class AgentUserQuerySet(django.db.models.query.QuerySet):
20class AgentUserQuerySet(QuerySet):
21    """Select users by their agent relationship."""
22
23    def filter_agents(self) -> Self:
24        """Include only agent users."""
25        return self.filter(actor__agent__isnull=False)
26
27    def exclude_agents(self) -> Self:
28        """Exclude agent users."""
29        return self.filter(actor__agent__isnull=True)

Select users by their agent relationship.

def filter_agents(self) -> Self:
23    def filter_agents(self) -> Self:
24        """Include only agent users."""
25        return self.filter(actor__agent__isnull=False)

Include only agent users.

def exclude_agents(self) -> Self:
27    def exclude_agents(self) -> Self:
28        """Exclude agent users."""
29        return self.filter(actor__agent__isnull=True)

Exclude agent users.

class Agent(authentik.core.models.Actor):
32class Agent(Actor):
33
34    class Meta(Actor.Meta):
35        verbose_name = _("Agent")
36        verbose_name_plural = _("Agents")
37        # expires/expiring live on the parent Actor table under multi-table inheritance, so the
38        # indexes inherited from Actor.Meta (via ExpiringModel.Meta) don't apply to Agent itself.
39        indexes = []
40        permissions = [
41            ("add_agent_self_service", _("Add an agent user (self-service)")),
42        ]
43
44    @classmethod
45    def create_for_user(
46        cls,
47        user: User,
48        name: str = "",
49        expiring: bool = False,
50        expires=None,
51        policy_behavior: str = ActorPolicyInheritance.MIRROR,
52    ) -> Agent:
53        # An agent is a machine identity, not a login user: mark it as a service account
54        # and disable password auth. It authenticates through its issued API token. By default
55        # it MIRRORs its parent, so it can never exceed the access of the user it acts for.
56        name_prefix = "authentik:system"
57        if user:
58            name_prefix = user.username
59        agent = cls.objects.create(
60            username=f"{name_prefix}-agent-{generate_id()}"[:USERNAME_MAX_LENGTH],
61            name=name,
62            parent=user,
63            policy_behavior=policy_behavior,
64            type=UserTypes.SERVICE_ACCOUNT,
65            path=USER_PATH_AGENTS,
66            expiring=expiring,
67            expires=expires,
68        )
69        if policy_behavior == ActorPolicyInheritance.COPY:
70            agent.copy_parent_policy_bindings()
71        return agent
72
73    @property
74    def serializer(self):
75        from authentik.enterprise.agents.api import AgentSerializer
76
77        return AgentSerializer
78
79    def __str__(self):
80        return f"Agent {self.username} for {self.parent_id}"

Agent(id, last_login, username, first_name, last_name, email, is_active, date_joined, attributes, uuid, name, path, type, last_updated, user_ptr, expires, expiring, parent, policy_behavior, actor_ptr)

@classmethod
def create_for_user( cls, user: authentik.core.models.User, name: str = '', expiring: bool = False, expires=None, policy_behavior: str = ActorPolicyInheritance.MIRROR) -> Agent:
44    @classmethod
45    def create_for_user(
46        cls,
47        user: User,
48        name: str = "",
49        expiring: bool = False,
50        expires=None,
51        policy_behavior: str = ActorPolicyInheritance.MIRROR,
52    ) -> Agent:
53        # An agent is a machine identity, not a login user: mark it as a service account
54        # and disable password auth. It authenticates through its issued API token. By default
55        # it MIRRORs its parent, so it can never exceed the access of the user it acts for.
56        name_prefix = "authentik:system"
57        if user:
58            name_prefix = user.username
59        agent = cls.objects.create(
60            username=f"{name_prefix}-agent-{generate_id()}"[:USERNAME_MAX_LENGTH],
61            name=name,
62            parent=user,
63            policy_behavior=policy_behavior,
64            type=UserTypes.SERVICE_ACCOUNT,
65            path=USER_PATH_AGENTS,
66            expiring=expiring,
67            expires=expires,
68        )
69        if policy_behavior == ActorPolicyInheritance.COPY:
70            agent.copy_parent_policy_bindings()
71        return agent
serializer
73    @property
74    def serializer(self):
75        from authentik.enterprise.agents.api import AgentSerializer
76
77        return AgentSerializer

Get serializer for this model

actor_ptr_id
actor_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

Inherited Members
authentik.lib.models.ExpiringModel
Meta
objects
expire_action
filter_not_expired
is_expired
authentik.core.models.Actor
parent
policy_behavior
save
from_db
copy_parent_policy_bindings
for_user
expires
expiring
parent_id
get_policy_behavior_display
user_ptr_id
user_ptr
agent
authentik.core.models.User
user_permissions
uuid
name
path
type
sources
groups
roles
last_updated
default_path
all_groups
all_roles
get_managed_role
get_all_model_perms_on_managed_role
get_all_obj_perms_on_managed_role
assign_perms_to_managed_role
remove_perms_from_managed_role
remove_all_perms_from_managed_role
group_attributes
app_entitlements
all_app_entitlements
app_entitlements_attributes
is_superuser
is_staff
ak_groups
password
password_change_date
check_password
acheck_password
set_password
set_unusable_password
uid
locale
avatar
attributes
username
first_name
last_name
email
is_active
date_joined
last_login
get_type_display
get_next_by_last_updated
get_previous_by_last_updated
get_next_by_date_joined
get_previous_by_date_joined
id
policybinding_set
usersourceconnection_set
userrole_set
usergroup_set
authenticatedsession_set
actors
actor
activity
notification_set
password_device
deviceauthenticationtoken_set
appleauthorizationcode_set
appleindependentsecureenclave_set
invitation_set
authorizationcode_set
actor_for_authorizationcodes
accesstoken_set
actor_for_accesstokens
refreshtoken_set
actor_for_refreshtokens
devicetoken_set
samlsession_set
scimprovideruser_set
scimprovider_set
staticdevice_set
duodevice_set
emaildevice_set
smsdevice_set
webauthndevice_set
scimsourceuser_set
totpdevice_set
userconsent_set
lifecyclerule_set
lifecyclerulereviewer_set
review_set
offboardings
old_passwords
googleworkspaceprovideruser_set
microsoftentraprovideruser_set
dataexport_set
grant_requests_created
grant_requests_fulfilled
grant_requests_revoked
agent_grant_requests
grantrequestapproval_set
endpointdevice_set
authentik.core.models.AttributesMixin
update_attributes
update_or_create_attributes
class Agent.DoesNotExist(authentik.core.models.Actor.DoesNotExist):

The requested object does not exist

class Agent.MultipleObjectsReturned(authentik.core.models.Actor.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.