authentik.enterprise.providers.ssf.signals

  1from hashlib import sha256
  2
  3from django.db.models import Model
  4from django.db.models.signals import post_delete, post_save
  5from django.dispatch import receiver
  6from django.http import HttpRequest
  7
  8from authentik.core.models import (
  9    USER_PATH_SYSTEM_PREFIX,
 10    AuthenticatedSession,
 11    Token,
 12    TokenIntents,
 13    User,
 14    UserTypes,
 15)
 16from authentik.core.signals import (
 17    admin_authenticated_session_deleted,
 18    password_changed,
 19    password_hash_changed,
 20)
 21from authentik.enterprise.providers.ssf.models import (
 22    EventTypes,
 23    SSFProvider,
 24)
 25from authentik.enterprise.providers.ssf.tasks import send_ssf_events
 26from authentik.events.middleware import audit_ignore, is_audit_ignored
 27from authentik.stages.authenticator.models import Device
 28from authentik.stages.authenticator_duo.models import DuoDevice
 29from authentik.stages.authenticator_static.models import StaticDevice
 30from authentik.stages.authenticator_totp.models import TOTPDevice
 31from authentik.stages.authenticator_webauthn.models import (
 32    UNKNOWN_DEVICE_TYPE_AAGUID,
 33    WebAuthnDevice,
 34)
 35from authentik.stages.password.models import PasswordDevice
 36
 37USER_PATH_PROVIDERS_SSF = USER_PATH_SYSTEM_PREFIX + "/providers/ssf"
 38
 39
 40@receiver(post_save, sender=SSFProvider)
 41def ssf_providers_post_save(sender: type[Model], instance: SSFProvider, created: bool, **_):
 42    """Create service account before provider is saved"""
 43    identifier = instance.service_account_identifier
 44    user, _ = User.objects.update_or_create(
 45        username=identifier,
 46        defaults={
 47            "name": f"SSF Provider {instance.name} Service-Account",
 48            "type": UserTypes.INTERNAL_SERVICE_ACCOUNT,
 49            "path": USER_PATH_PROVIDERS_SSF,
 50        },
 51    )
 52    user.assign_perms_to_managed_role("authentik_providers_ssf.add_stream", instance)
 53    token, token_created = Token.objects.update_or_create(
 54        identifier=identifier,
 55        defaults={
 56            "user": user,
 57            "intent": TokenIntents.INTENT_API,
 58            "expiring": False,
 59            "managed": f"goauthentik.io/providers/ssf/{instance.pk}",
 60        },
 61    )
 62    if created or token_created:
 63        with audit_ignore():
 64            instance.token = token
 65            instance.save()
 66
 67
 68@receiver(admin_authenticated_session_deleted)
 69def ssf_user_session_delete_session_revoked(
 70    sender, instance: AuthenticatedSession, request: HttpRequest, **_
 71):
 72    """Session revoked trigger (users' session has been deleted)
 73
 74    As this signal is also triggered with a regular logout, we can't be sure
 75    if the session has been deleted by an admin or by the user themselves."""
 76    send_ssf_events(
 77        EventTypes.CAEP_SESSION_REVOKED,
 78        {
 79            "initiating_entity": "user",
 80        },
 81        request=request,
 82        sub_id={
 83            "format": "complex",
 84            "session": {
 85                "format": "opaque",
 86                "id": sha256(instance.session.session_key.encode("ascii")).hexdigest(),
 87            },
 88            "user": {
 89                "format": "email",
 90                "email": instance.user.email,
 91            },
 92        },
 93    )
 94
 95
 96def _send_password_credential_change(user: User, change_type: str):
 97    """Credential change trigger (password changed)"""
 98    send_ssf_events(
 99        EventTypes.CAEP_CREDENTIAL_CHANGE,
100        {
101            "credential_type": "password",
102            "change_type": change_type,
103        },
104        sub_id={
105            "format": "complex",
106            "user": {
107                "format": "email",
108                "email": user.email,
109            },
110        },
111    )
112
113
114@receiver(password_hash_changed)
115@receiver(password_changed)
116def ssf_password_changed_cred_change(signal, sender, user: User, password: str | None = None, **_):
117    """Credential change trigger (password changed)"""
118    if signal is password_hash_changed:
119        _send_password_credential_change(user, "update")
120        return
121    _send_password_credential_change(user, "revoke" if password is None else "update")
122
123
124device_type_map = {
125    StaticDevice: "pin",
126    TOTPDevice: "pin",
127    WebAuthnDevice: "fido-u2f",
128    DuoDevice: "app",
129}
130
131
132@receiver(post_save)
133def ssf_device_post_save(sender: type[Model], instance: Device, created: bool, **_):
134    # Password changes are emitted by ssf_password_changed_cred_change.
135    if not isinstance(instance, Device) or isinstance(instance, PasswordDevice):
136        return
137    # authentication using an authenticator device might modify the device (for example
138    # with TOTP last_t is updated, and with WebAuthn the sign_count)
139    # We don't want to send an event for that since most SSF clients expect this event to
140    # be an actual user-initiated modification to a credential
141    if is_audit_ignored():
142        return
143    if not instance.confirmed:
144        return
145    device_type = device_type_map.get(instance.__class__)
146    data = {
147        "credential_type": device_type,
148        "change_type": "create" if created else "update",
149        "friendly_name": instance.name,
150    }
151    if isinstance(instance, WebAuthnDevice) and instance.aaguid != UNKNOWN_DEVICE_TYPE_AAGUID:
152        data["fido2_aaguid"] = instance.aaguid
153    send_ssf_events(
154        EventTypes.CAEP_CREDENTIAL_CHANGE,
155        data,
156        sub_id={
157            "format": "complex",
158            "user": {
159                "format": "email",
160                "email": instance.user.email,
161            },
162        },
163    )
164
165
166@receiver(post_delete)
167def ssf_device_post_delete(sender: type[Model], instance: Device, **_):
168    if not isinstance(instance, Device) or isinstance(instance, PasswordDevice):
169        return
170    if not instance.confirmed:
171        return
172    device_type = device_type_map.get(instance.__class__)
173    data = {
174        "credential_type": device_type,
175        "change_type": "delete",
176        "friendly_name": instance.name,
177    }
178    if isinstance(instance, WebAuthnDevice) and instance.aaguid != UNKNOWN_DEVICE_TYPE_AAGUID:
179        data["fido2_aaguid"] = instance.aaguid
180    send_ssf_events(
181        EventTypes.CAEP_CREDENTIAL_CHANGE,
182        data,
183        sub_id={
184            "format": "complex",
185            "user": {
186                "format": "email",
187                "email": instance.user.email,
188            },
189        },
190    )
USER_PATH_PROVIDERS_SSF = 'goauthentik.io/providers/ssf'
@receiver(post_save, sender=SSFProvider)
def ssf_providers_post_save( sender: type[django.db.models.base.Model], instance: authentik.enterprise.providers.ssf.models.SSFProvider, created: bool, **_):
41@receiver(post_save, sender=SSFProvider)
42def ssf_providers_post_save(sender: type[Model], instance: SSFProvider, created: bool, **_):
43    """Create service account before provider is saved"""
44    identifier = instance.service_account_identifier
45    user, _ = User.objects.update_or_create(
46        username=identifier,
47        defaults={
48            "name": f"SSF Provider {instance.name} Service-Account",
49            "type": UserTypes.INTERNAL_SERVICE_ACCOUNT,
50            "path": USER_PATH_PROVIDERS_SSF,
51        },
52    )
53    user.assign_perms_to_managed_role("authentik_providers_ssf.add_stream", instance)
54    token, token_created = Token.objects.update_or_create(
55        identifier=identifier,
56        defaults={
57            "user": user,
58            "intent": TokenIntents.INTENT_API,
59            "expiring": False,
60            "managed": f"goauthentik.io/providers/ssf/{instance.pk}",
61        },
62    )
63    if created or token_created:
64        with audit_ignore():
65            instance.token = token
66            instance.save()

Create service account before provider is saved

@receiver(admin_authenticated_session_deleted)
def ssf_user_session_delete_session_revoked( sender, instance: authentik.core.models.AuthenticatedSession, request: django.http.request.HttpRequest, **_):
69@receiver(admin_authenticated_session_deleted)
70def ssf_user_session_delete_session_revoked(
71    sender, instance: AuthenticatedSession, request: HttpRequest, **_
72):
73    """Session revoked trigger (users' session has been deleted)
74
75    As this signal is also triggered with a regular logout, we can't be sure
76    if the session has been deleted by an admin or by the user themselves."""
77    send_ssf_events(
78        EventTypes.CAEP_SESSION_REVOKED,
79        {
80            "initiating_entity": "user",
81        },
82        request=request,
83        sub_id={
84            "format": "complex",
85            "session": {
86                "format": "opaque",
87                "id": sha256(instance.session.session_key.encode("ascii")).hexdigest(),
88            },
89            "user": {
90                "format": "email",
91                "email": instance.user.email,
92            },
93        },
94    )

Session revoked trigger (users' session has been deleted)

As this signal is also triggered with a regular logout, we can't be sure if the session has been deleted by an admin or by the user themselves.

@receiver(password_hash_changed)
@receiver(password_changed)
def ssf_password_changed_cred_change( signal, sender, user: authentik.core.models.User, password: str | None = None, **_):
115@receiver(password_hash_changed)
116@receiver(password_changed)
117def ssf_password_changed_cred_change(signal, sender, user: User, password: str | None = None, **_):
118    """Credential change trigger (password changed)"""
119    if signal is password_hash_changed:
120        _send_password_credential_change(user, "update")
121        return
122    _send_password_credential_change(user, "revoke" if password is None else "update")

Credential change trigger (password changed)

@receiver(post_save)
def ssf_device_post_save( sender: type[django.db.models.base.Model], instance: authentik.stages.authenticator.models.Device, created: bool, **_):
133@receiver(post_save)
134def ssf_device_post_save(sender: type[Model], instance: Device, created: bool, **_):
135    # Password changes are emitted by ssf_password_changed_cred_change.
136    if not isinstance(instance, Device) or isinstance(instance, PasswordDevice):
137        return
138    # authentication using an authenticator device might modify the device (for example
139    # with TOTP last_t is updated, and with WebAuthn the sign_count)
140    # We don't want to send an event for that since most SSF clients expect this event to
141    # be an actual user-initiated modification to a credential
142    if is_audit_ignored():
143        return
144    if not instance.confirmed:
145        return
146    device_type = device_type_map.get(instance.__class__)
147    data = {
148        "credential_type": device_type,
149        "change_type": "create" if created else "update",
150        "friendly_name": instance.name,
151    }
152    if isinstance(instance, WebAuthnDevice) and instance.aaguid != UNKNOWN_DEVICE_TYPE_AAGUID:
153        data["fido2_aaguid"] = instance.aaguid
154    send_ssf_events(
155        EventTypes.CAEP_CREDENTIAL_CHANGE,
156        data,
157        sub_id={
158            "format": "complex",
159            "user": {
160                "format": "email",
161                "email": instance.user.email,
162            },
163        },
164    )
@receiver(post_delete)
def ssf_device_post_delete( sender: type[django.db.models.base.Model], instance: authentik.stages.authenticator.models.Device, **_):
167@receiver(post_delete)
168def ssf_device_post_delete(sender: type[Model], instance: Device, **_):
169    if not isinstance(instance, Device) or isinstance(instance, PasswordDevice):
170        return
171    if not instance.confirmed:
172        return
173    device_type = device_type_map.get(instance.__class__)
174    data = {
175        "credential_type": device_type,
176        "change_type": "delete",
177        "friendly_name": instance.name,
178    }
179    if isinstance(instance, WebAuthnDevice) and instance.aaguid != UNKNOWN_DEVICE_TYPE_AAGUID:
180        data["fido2_aaguid"] = instance.aaguid
181    send_ssf_events(
182        EventTypes.CAEP_CREDENTIAL_CHANGE,
183        data,
184        sub_id={
185            "format": "complex",
186            "user": {
187                "format": "email",
188                "email": instance.user.email,
189            },
190        },
191    )