From 7b5ee28ccb511309eb67b708fc522bd35ac1a77b Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Fri, 6 Nov 2026 18:37:27 -0300 Subject: [PATCH 01/41] audit logs finally _organised_ --- .../migrations/0016_add_organisation_id.py | 43 +++++++++++++++++++ api/audit/models.py | 9 +++- 2 files changed, 50 insertions(+), 2 deletions(-) create mode 100644 api/audit/migrations/0016_add_organisation_id.py diff --git a/api/audit/migrations/0016_add_organisation_id.py b/api/audit/migrations/0016_add_organisation_id.py new file mode 100644 index 000000000000..70096978ac5e --- /dev/null +++ b/api/audit/migrations/0016_add_organisation_id.py @@ -0,0 +1,43 @@ +# Generated by Django 5.2.17 on 2026-11-06 21:08 + +from django.db import migrations, models +from django.db.backends import utils as backend_utils + +# Matches the name Django generates for a `db_index=True` index on this column +ORGANISATION_ID_INDEX_NAME = "audit_auditlog_organisation_id_" + ( + backend_utils.names_digest( # type: ignore[attr-defined] # Missing from django-stubs + "audit_auditlog", "organisation_id", length=8 + ) +) + + +class Migration(migrations.Migration): + atomic = False + + dependencies = [ + ("audit", "0015_add_log_trigram_index"), + ] + + operations = [ + migrations.SeparateDatabaseAndState( + database_operations=[ + migrations.AddField( + model_name="auditlog", + name="organisation_id", + field=models.IntegerField(null=True), + ), + migrations.RunSQL( + f"CREATE INDEX CONCURRENTLY IF NOT EXISTS {ORGANISATION_ID_INDEX_NAME} " + "ON audit_auditlog (organisation_id)", + reverse_sql=f"DROP INDEX CONCURRENTLY IF EXISTS {ORGANISATION_ID_INDEX_NAME}", + ), + ], + state_operations=[ + migrations.AddField( + model_name="auditlog", + name="organisation_id", + field=models.IntegerField(db_index=True, null=True), + ), + ], + ), + ] diff --git a/api/audit/models.py b/api/audit/models.py index e86c191d0358..c3b0043817fa 100644 --- a/api/audit/models.py +++ b/api/audit/models.py @@ -17,6 +17,7 @@ from api_keys.models import MasterAPIKey from audit.related_object_type import RelatedObjectType +from organisations.models import Organisation from projects.models import Project if typing.TYPE_CHECKING: @@ -28,6 +29,9 @@ class AuditLog(LifecycleModel): # type: ignore[misc] created_date = models.DateTimeField("DateCreated") # type: ignore[var-annotated] + organisation_id = models.IntegerField[int | None, int | None]( + null=True, db_index=True + ) project = models.ForeignKey( # type: ignore[var-annotated] Project, related_name="audit_logs", null=True, on_delete=models.DO_NOTHING ) @@ -85,8 +89,9 @@ class Meta: @property def organisation(self) -> "Organisation | None": - # TODO properly implement organisation relation - # maybe the relation list should not be _that_ exhaustive... + if self.organisation_id is not None: + return Organisation.objects.get(id=self.organisation_id) # type: ignore[no-any-return] + for relation in ( "project", "environment", From d00efb9c385a6581861fcef4efcc28748315fafd Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 9 Nov 2026 16:17:14 -0300 Subject: [PATCH 02/41] first, red --- .../test_organisation_level_audit_logs.py | 330 ++++++++++++++++++ 1 file changed, 330 insertions(+) create mode 100644 api/tests/integration/audit/test_organisation_level_audit_logs.py diff --git a/api/tests/integration/audit/test_organisation_level_audit_logs.py b/api/tests/integration/audit/test_organisation_level_audit_logs.py new file mode 100644 index 000000000000..6ab236edf47e --- /dev/null +++ b/api/tests/integration/audit/test_organisation_level_audit_logs.py @@ -0,0 +1,330 @@ +import json +from unittest import mock + +import pytest +import responses +from pytest_django import DjangoAssertNumQueries +from pytest_mock import MockerFixture +from rest_framework.test import APIClient + +from audit.models import AuditLog +from environments.models import Environment +from organisations.models import Organisation +from organisations.subscriptions.metadata import BaseSubscriptionMetadata +from projects.models import Project +from users.models import FFAdminUser + + +@pytest.fixture(autouse=True) +def _subscription_metadata(mocker: MockerFixture) -> None: + """Lift the free plan's audit log visibility limit, which hides all past logs.""" + mocker.patch( + "organisations.models.Subscription.get_subscription_metadata", + return_value=BaseSubscriptionMetadata(audit_log_visibility_days=None), + ) + + +@pytest.fixture +def project(organisation: int) -> int: + """Create a project outside the API, so it records no audit log.""" + return Project.objects.create( # type: ignore[no-any-return] # Removable once django-softdelete is typed + name="Orangify website", organisation_id=organisation + ).id + + +@pytest.fixture +def environment(project: int) -> int: + """Create an environment outside the API, so it records no audit log.""" + return Environment.objects.create( # type: ignore[no-any-return] # Removable once django-softdelete is typed + name="Production", project_id=project + ).id + + +def test_get_logs__logs_directly_associated_with_organisation__responds_200_with_them( + admin_client: APIClient, + organisation: int, +) -> None: + # Given + other_organisation = Organisation.objects.create(name="Bananas Inc") + AuditLog.objects.create( + organisation_id=other_organisation.id, + log="User `bob@example.com` joined the organisation", + ) + audit_log = AuditLog.objects.create( + organisation_id=organisation, + log="User `alice@example.com` joined the organisation", + ) + + # When + response = admin_client.get(f"/api/v1/organisations/{organisation}/audit/") + + # Then + assert response.status_code == 200 + assert response.json() == { + "count": 1, + "next": None, + "previous": None, + "results": [ + { + "id": audit_log.id, + "created_date": mock.ANY, + "log": "User `alice@example.com` joined the organisation", + "author": None, + "organisation": organisation, + "environment": None, + "project": None, + "related_object_id": None, + "related_object_uuid": None, + "related_object_type": None, + "is_system_event": False, + } + ], + } + + +def test_get_logs__logs_indirectly_associated_with_organisation__responds_200_with_them( + admin_client: APIClient, + environment: int, + organisation: int, + project: int, +) -> None: + # Given + other_organisation = Organisation.objects.create(name="Bananas Inc") + other_project = Project.objects.create( + name="Winged Bananas Website", organisation=other_organisation + ) + AuditLog.objects.create(project=other_project, log="Flag `peel` created") + AuditLog.objects.create(project_id=project, log="Flag `squeeze` created") + AuditLog.objects.create(environment_id=environment, log="Flag `squeeze` enabled") + + # When + response = admin_client.get(f"/api/v1/organisations/{organisation}/audit/") + + # Then + assert response.status_code == 200 + assert [result["log"] for result in response.json()["results"]] == [ + "Flag `squeeze` enabled", + "Flag `squeeze` created", + ] + + +@pytest.mark.parametrize( + ["filter_args", "expected"], + [ + ( + {"project": "project"}, + [ + "Flag `squeeze` enabled", + "Project `Orangify website` created", + ], + ), + ( + {"environments": "environment"}, + [ + "Flag `squeeze` enabled", + ], + ), + ( + {"project": "project", "environments": "environment"}, + [ + "Flag `squeeze` enabled", + ], + ), + ], +) +def test_get_logs__mixed_logs_with_filter__responds_200_with_filtered_logs( + admin_client: APIClient, + environment: int, + expected: list[str], + filter_args: dict[str, str], + organisation: int, + project: int, + request: pytest.FixtureRequest, +) -> None: + # Given + AuditLog.objects.create( + organisation_id=organisation, + log="User `alice@example.com` joined the organisation", + ) + AuditLog.objects.create( + project_id=project, + log="Project `Orangify website` created", + ) + AuditLog.objects.create( + environment_id=environment, + log="Flag `squeeze` enabled", + ) + + # When + response = admin_client.get( + f"/api/v1/organisations/{organisation}/audit/", + {name: request.getfixturevalue(value) for name, value in filter_args.items()}, + ) + + # Then + assert response.status_code == 200 + assert [result["log"] for result in response.json()["results"]] == expected + + +@pytest.mark.parametrize( + ["is_organisation_level", "expected"], + [ + ( + True, + [ + "User `alice@example.com` joined the organisation", + ], + ), + ( + False, + [ + "Flag `squeeze` enabled", + "Project `Orangify website` created", + ], + ), + ], +) +def test_get_logs__mixed_logs_filtered_by_is_organisation_level__responds_200_with_filtered_logs( + admin_client: APIClient, + environment: int, + expected: list[str], + is_organisation_level: bool, + organisation: int, + project: int, +) -> None: + # Given + AuditLog.objects.create( + organisation_id=organisation, + log="User `alice@example.com` joined the organisation", + ) + AuditLog.objects.create( + project_id=project, + log="Project `Orangify website` created", + ) + AuditLog.objects.create( + environment_id=environment, + log="Flag `squeeze` enabled", + ) + + # When + response = admin_client.get( + f"/api/v1/organisations/{organisation}/audit/", + {"is_organisation_level": is_organisation_level}, + ) + + # Then + assert response.status_code == 200 + assert [result["log"] for result in response.json()["results"]] == expected + + +def test_get_logs__mixed_logs__makes_expected_queries( + admin_client: APIClient, + admin_user: FFAdminUser, + django_assert_num_queries: DjangoAssertNumQueries, + environment: int, + organisation: int, + project: int, +) -> None: + # Given + AuditLog.objects.create( + organisation_id=organisation, + author=admin_user, + log="User `alice@example.com` joined the organisation", + ) + AuditLog.objects.create( + organisation_id=organisation, + author=admin_user, + log="User `bob@example.com` joined the organisation", + ) + AuditLog.objects.create( + project_id=project, + author=admin_user, + log="Flag `squeeze` created", + ) + AuditLog.objects.create( + project_id=project, + author=admin_user, + log="Flag `peel` created", + ) + AuditLog.objects.create( + environment_id=environment, + author=admin_user, + log="Flag `squeeze` enabled", + ) + AuditLog.objects.create( + environment_id=environment, + author=admin_user, + log="Flag `peel` enabled", + ) + + # When + with django_assert_num_queries(5): + response = admin_client.get(f"/api/v1/organisations/{organisation}/audit/") + + # Then + assert response.status_code == 200 + + +def test_get_logs__member_but_not_admin__responds_403( + non_admin_client: APIClient, + organisation: int, +) -> None: + # Given / When + response = non_admin_client.get(f"/api/v1/organisations/{organisation}/audit/") + + # Then + assert response.status_code == 403 + assert response.json() == { + "detail": "You do not have permission to perform this action." + } + + +def test_get_logs__non_member__responds_404( + organisation: int, + staff_client: APIClient, +) -> None: + # Given / When + response = staff_client.get(f"/api/v1/organisations/{organisation}/audit/") + + # Then + assert response.status_code == 404 + assert response.json() == {"detail": "Not found."} + + +@responses.activate +def test_webhook_dispatch__organisation_log__sends_webhook( + admin_client: APIClient, + organisation: int, +) -> None: + # Given + admin_client.post( + f"/api/v1/organisations/{organisation}/webhooks/", + {"url": "https://example.com/audit-hook", "enabled": True}, + format="json", + ) + responses.post("https://example.com/audit-hook", status=200) + + # When + audit_log = AuditLog.objects.create( + organisation_id=organisation, + log="User `alice@example.com` joined the organisation", + ) + + # Then + [webhook_call] = responses.calls + assert json.loads(webhook_call.request.body) == { + "event_type": "AUDIT_LOG_CREATED", + "data": { + "id": audit_log.id, + "created_date": mock.ANY, + "log": "User `alice@example.com` joined the organisation", + "author": None, + "organisation": organisation, + "environment": None, + "project": None, + "related_object_id": None, + "related_object_uuid": None, + "related_object_type": None, + "is_system_event": False, + }, + } From 5e649af85429affed804dbf5da7b6ddee84ecbb7 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 9 Nov 2026 19:49:11 -0300 Subject: [PATCH 03/41] `select_related` needs a foreign key --- .../migrations/0016_add_organisation_id.py | 12 +++++++-- api/audit/models.py | 27 +++++-------------- 2 files changed, 16 insertions(+), 23 deletions(-) diff --git a/api/audit/migrations/0016_add_organisation_id.py b/api/audit/migrations/0016_add_organisation_id.py index 70096978ac5e..512de4fcad13 100644 --- a/api/audit/migrations/0016_add_organisation_id.py +++ b/api/audit/migrations/0016_add_organisation_id.py @@ -1,5 +1,6 @@ # Generated by Django 5.2.17 on 2026-11-06 21:08 +import django.db.models.deletion from django.db import migrations, models from django.db.backends import utils as backend_utils @@ -16,6 +17,7 @@ class Migration(migrations.Migration): dependencies = [ ("audit", "0015_add_log_trigram_index"), + ("organisations", "0061_add_user_organisation_is_active"), ] operations = [ @@ -35,8 +37,14 @@ class Migration(migrations.Migration): state_operations=[ migrations.AddField( model_name="auditlog", - name="organisation_id", - field=models.IntegerField(db_index=True, null=True), + name="organisation", + field=models.ForeignKey( + db_constraint=False, + null=True, + on_delete=django.db.models.deletion.DO_NOTHING, + related_name="audit_logs", + to="organisations.organisation", + ), ), ], ), diff --git a/api/audit/models.py b/api/audit/models.py index c3b0043817fa..e3d92f1fdc09 100644 --- a/api/audit/models.py +++ b/api/audit/models.py @@ -20,17 +20,18 @@ from organisations.models import Organisation from projects.models import Project -if typing.TYPE_CHECKING: - from organisations.models import Organisation - RELATED_OBJECT_TYPES = ((tag.name, tag.value) for tag in RelatedObjectType) class AuditLog(LifecycleModel): # type: ignore[misc] created_date = models.DateTimeField("DateCreated") # type: ignore[var-annotated] - organisation_id = models.IntegerField[int | None, int | None]( - null=True, db_index=True + organisation = models.ForeignKey[Organisation | None, Organisation | None]( + Organisation, + related_name="audit_logs", + null=True, + on_delete=models.DO_NOTHING, + db_constraint=False, # Logs survive on deletion ) project = models.ForeignKey( # type: ignore[var-annotated] Project, related_name="audit_logs", null=True, on_delete=models.DO_NOTHING @@ -87,22 +88,6 @@ class Meta: ), ] - @property - def organisation(self) -> "Organisation | None": - if self.organisation_id is not None: - return Organisation.objects.get(id=self.organisation_id) # type: ignore[no-any-return] - - for relation in ( - "project", - "environment", - "author", - "master_api_key", - "history_record", - ): - if hasattr(related_instance := getattr(self, relation), "organisation"): - return related_instance.organisation # type: ignore[no-any-return] - return None - @property def environment_document_updated(self) -> bool: if self.related_object_type == RelatedObjectType.CHANGE_REQUEST.name: From d91ac03bea96b8c0754ab7fb848a8344895b3325 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 9 Nov 2026 20:01:28 -0300 Subject: [PATCH 04/41] tests go happy --- api/audit/permissions.py | 10 ++++- api/audit/serializers.py | 19 ++++++++- api/audit/signals.py | 27 ++++++------ api/audit/types.py | 8 ++++ api/audit/views.py | 9 +++- .../test_organisation_level_audit_logs.py | 41 ++++++++++++++++++- 6 files changed, 95 insertions(+), 19 deletions(-) diff --git a/api/audit/permissions.py b/api/audit/permissions.py index f4d17dcbeee4..83d0cc69d254 100644 --- a/api/audit/permissions.py +++ b/api/audit/permissions.py @@ -1,5 +1,7 @@ from common.projects.permissions import VIEW_AUDIT_LOG +from django.contrib.auth.models import AnonymousUser from django.views import View +from rest_framework.exceptions import NotFound from rest_framework.permissions import BasePermission from rest_framework.request import Request @@ -15,7 +17,13 @@ def has_permission(self, request: Request, view: View): # type: ignore[no-untyp except (Organisation.DoesNotExist, KeyError): return False - return request.user.is_organisation_admin(organisation) # type: ignore[union-attr] + user = request.user + assert not isinstance(user, AnonymousUser) + if user.is_organisation_admin(organisation): + return True + if not user.belongs_to(organisation.id): + raise NotFound() + return False class ProjectAuditLogPermissions(BasePermission): diff --git a/api/audit/serializers.py b/api/audit/serializers.py index a2e8110236a0..b660c21a88b4 100644 --- a/api/audit/serializers.py +++ b/api/audit/serializers.py @@ -2,14 +2,16 @@ from rest_framework import serializers from audit.models import AuditLog -from audit.types import AuditLogChangeDetail, ChangeType +from audit.types import AuditLogChangeDetail, AuditLogsQueryParams, ChangeType from environments.serializers import EnvironmentSerializerLight +from organisations.serializers import OrganisationSerializerBasic from projects.serializers import ProjectListSerializer from users.serializers import UserListSerializer class AuditLogListSerializer(serializers.ModelSerializer): # type: ignore[type-arg] author = UserListSerializer() + organisation = OrganisationSerializerBasic() environment = EnvironmentSerializerLight() project = ProjectListSerializer() @@ -20,6 +22,7 @@ class Meta: "created_date", "log", "author", + "organisation", "environment", "project", "related_object_id", @@ -37,6 +40,7 @@ class AuditLogChangeDetailsSerializer(serializers.Serializer[AuditLogChangeDetai class AuditLogRetrieveSerializer(serializers.ModelSerializer): # type: ignore[type-arg] author = UserListSerializer() + organisation = OrganisationSerializerBasic() environment = EnvironmentSerializerLight() project = ProjectListSerializer() change_details = serializers.SerializerMethodField() @@ -49,6 +53,7 @@ class Meta: "created_date", "log", "author", + "organisation", "environment", "project", "related_object_id", @@ -102,4 +107,16 @@ class AuditLogsQueryParamSerializer(serializers.Serializer): # type: ignore[typ is_system_event = serializers.BooleanField( required=False, allow_null=True, default=None ) + is_organisation_level = serializers.BooleanField( + required=False, allow_null=True, default=None + ) search = serializers.CharField(min_length=3, max_length=256, required=False) + + def validate(self, attrs: AuditLogsQueryParams) -> AuditLogsQueryParams: + if attrs.get("is_organisation_level") and ( + attrs.get("project") or attrs.get("environments") + ): + raise serializers.ValidationError( + "Organisation-level logs cannot be filtered by project or environment." + ) + return attrs diff --git a/api/audit/signals.py b/api/audit/signals.py index d77fd68448fa..c125fcb0cbe1 100644 --- a/api/audit/signals.py +++ b/api/audit/signals.py @@ -56,11 +56,12 @@ def _get_integration_config( instance: AuditLog, integration_name: AuditLogIntegrationAttrName, ) -> IntegrationsModel | None: - for relation_name in ("project", "environment", "organisation"): - if hasattr( - related_object := getattr(instance, relation_name), - integration_name, - ): + for related_object in ( + instance.project, + instance.environment, + instance.organisation or getattr(instance.project, "organisation", None), + ): + if hasattr(related_object, integration_name): integration_config: IntegrationsModel = getattr( related_object, integration_name, @@ -75,16 +76,16 @@ def call_webhooks(sender, instance, **kwargs): # type: ignore[no-untyped-def] if settings.DISABLE_WEBHOOKS: return - if not (instance.project_id or instance.environment_id): - logger.warning("Audit log without project or environment. Not sending webhook.") + if instance.organisation_id: + organisation_id = instance.organisation_id + elif instance.project: + organisation_id = instance.project.organisation_id + elif instance.environment: + organisation_id = instance.environment.project.organisation_id + else: + logger.warning("Audit log without organisation. Not sending webhook.") return - organisation_id = ( - instance.project.organisation_id - if instance.project - else instance.environment.project.organisation_id - ) - if OrganisationWebhook.objects.filter( organisation_id=organisation_id, enabled=True ).exists(): diff --git a/api/audit/types.py b/api/audit/types.py index 45790502894b..019c8f7c143e 100644 --- a/api/audit/types.py +++ b/api/audit/types.py @@ -7,3 +7,11 @@ class AuditLogChangeDetail(TypedDict): field: str old: int | float | str | bool | None new: int | float | str | bool | None + + +class AuditLogsQueryParams(TypedDict, total=False): + project: int + environments: list[int] + is_system_event: bool | None + is_organisation_level: bool | None + search: str diff --git a/api/audit/views.py b/api/audit/views.py index e5a9ef447a43..3defb38d509e 100644 --- a/api/audit/views.py +++ b/api/audit/views.py @@ -42,6 +42,8 @@ def get_queryset(self) -> QuerySet[AuditLog]: serializer = AuditLogsQueryParamSerializer(data=self.request.GET) serializer.is_valid(raise_exception=True) + if (is_org_level := serializer.data.get("is_organisation_level")) is not None: + q = q & Q(organisation__isnull=not is_org_level) if project_id := serializer.data.get("project"): q = q & Q(project__id=project_id) if environment_ids := serializer.data.get("environments"): @@ -54,7 +56,7 @@ def get_queryset(self) -> QuerySet[AuditLog]: q = q & Q(log__icontains=search) queryset = AuditLog.objects.filter(q).select_related( - "project", "environment", "author" + "organisation", "project", "environment", "author" ) return self._apply_visibility_limits(queryset) @@ -120,7 +122,10 @@ class OrganisationAuditLogViewSet(_BaseAuditLogViewSet): permission_classes = [IsAuthenticated, OrganisationAuditLogPermissions] def _get_base_filters(self) -> Q: - return Q(project__organisation__id=self.kwargs["organisation_pk"]) + organisation_id = self.kwargs["organisation_pk"] + directly_related = Q(organisation__id=organisation_id) + indirectly_related = Q(project__organisation__id=organisation_id) + return directly_related | indirectly_related def _get_organisation(self) -> Organisation | None: return ( # type: ignore[no-any-return] diff --git a/api/tests/integration/audit/test_organisation_level_audit_logs.py b/api/tests/integration/audit/test_organisation_level_audit_logs.py index 6ab236edf47e..7c39382e7927 100644 --- a/api/tests/integration/audit/test_organisation_level_audit_logs.py +++ b/api/tests/integration/audit/test_organisation_level_audit_logs.py @@ -70,7 +70,7 @@ def test_get_logs__logs_directly_associated_with_organisation__responds_200_with "created_date": mock.ANY, "log": "User `alice@example.com` joined the organisation", "author": None, - "organisation": organisation, + "organisation": {"id": organisation, "name": "Test org"}, "environment": None, "project": None, "related_object_id": None, @@ -217,6 +217,43 @@ def test_get_logs__mixed_logs_filtered_by_is_organisation_level__responds_200_wi assert [result["log"] for result in response.json()["results"]] == expected +@pytest.mark.parametrize( + "filter_args", + [ + {"project": "project"}, + {"environments": "environment"}, + {"project": "project", "environments": "environment"}, + ], +) +def test_get_logs__filters_by_both_is_organisation_level_and_project_or_environment__responds_400( + admin_client: APIClient, + environment: int, + filter_args: dict[str, str], + organisation: int, + project: int, + request: pytest.FixtureRequest, +) -> None: + # Given / When + response = admin_client.get( + f"/api/v1/organisations/{organisation}/audit/", + { + "is_organisation_level": True, + **{ + name: request.getfixturevalue(value) + for name, value in filter_args.items() + }, + }, + ) + + # Then + assert response.status_code == 400 + assert response.json() == { + "non_field_errors": [ + "Organisation-level logs cannot be filtered by project or environment." + ] + } + + def test_get_logs__mixed_logs__makes_expected_queries( admin_client: APIClient, admin_user: FFAdminUser, @@ -319,7 +356,7 @@ def test_webhook_dispatch__organisation_log__sends_webhook( "created_date": mock.ANY, "log": "User `alice@example.com` joined the organisation", "author": None, - "organisation": organisation, + "organisation": {"id": organisation, "name": "Test org"}, "environment": None, "project": None, "related_object_id": None, From 2b63d2f4e11bab211566767e697681d43087a8ab Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 9 Nov 2026 20:05:26 -0300 Subject: [PATCH 05/41] =?UTF-8?q?fix=20`is=5Fsystem=5Fevent`=20filter=20?= =?UTF-8?q?=F0=9F=98=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/audit/views.py | 2 +- api/tests/unit/audit/test_unit_audit_views.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/api/audit/views.py b/api/audit/views.py index 3defb38d509e..2af5e5675640 100644 --- a/api/audit/views.py +++ b/api/audit/views.py @@ -48,7 +48,7 @@ def get_queryset(self) -> QuerySet[AuditLog]: q = q & Q(project__id=project_id) if environment_ids := serializer.data.get("environments"): q = q & Q(environment__id__in=environment_ids) - if is_system_event := serializer.data.get("is_system_event") is not None: + if (is_system_event := serializer.data.get("is_system_event")) is not None: q = q & Q(is_system_event=is_system_event) search = serializer.data.get("search") diff --git a/api/tests/unit/audit/test_unit_audit_views.py b/api/tests/unit/audit/test_unit_audit_views.py index 75e613bea673..41cf6d1982f7 100644 --- a/api/tests/unit/audit/test_unit_audit_views.py +++ b/api/tests/unit/audit/test_unit_audit_views.py @@ -122,11 +122,13 @@ def test_list_audit_log__filter_by_project__returns_matching_logs( assert response.json()["results"][1]["project"]["id"] == project.id +@pytest.mark.parametrize("is_system_event", [True, False]) def test_list_audit_log__filter_by_is_system_event__returns_matching_logs( admin_client: APIClient, project: Project, environment: Environment, organisation: Organisation, + is_system_event: bool, ) -> None: # Given AuditLog.objects.create(project=project, is_system_event=True) @@ -134,15 +136,13 @@ def test_list_audit_log__filter_by_is_system_event__returns_matching_logs( project=project, environment=environment, is_system_event=False ) - url = reverse("api-v1:audit-list") - # When - response = admin_client.get(url, {"is_system_event": True}) + response = admin_client.get("/api/v1/audit/", {"is_system_event": is_system_event}) # Then assert response.json()["count"] == 1 assert response.status_code == status.HTTP_200_OK - assert response.json()["results"][0]["is_system_event"] is True + assert response.json()["results"][0]["is_system_event"] is is_system_event def test_list_audit_log__regular_user__returns_empty( From 591595eb80deefb58f3409e0cf622fa5030820b9 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 9 Nov 2026 20:17:08 -0300 Subject: [PATCH 06/41] also in ALL logs --- api/audit/views.py | 8 ++++- api/tests/integration/audit/conftest.py | 13 ++++++++ .../integration/audit/test_all_audit_logs.py | 30 +++++++++++++++++++ .../integration/audit/test_audit_logs.py | 13 -------- .../test_organisation_level_audit_logs.py | 11 ------- 5 files changed, 50 insertions(+), 25 deletions(-) create mode 100644 api/tests/integration/audit/conftest.py create mode 100644 api/tests/integration/audit/test_all_audit_logs.py diff --git a/api/audit/views.py b/api/audit/views.py index 2af5e5675640..6e75a0f3df1e 100644 --- a/api/audit/views.py +++ b/api/audit/views.py @@ -94,11 +94,17 @@ def _get_organisation(self) -> Organisation | None: class AllAuditLogViewSet(_BaseAuditLogViewSet): def _get_base_filters(self) -> Q: - return Q( + directly_related = Q( + organisation__userorganisation__user=self.request.user, + organisation__userorganisation__role=OrganisationRole.ADMIN, + organisation__userorganisation__is_active=True, + ) + indirectly_related = Q( project__organisation__userorganisation__user=self.request.user, project__organisation__userorganisation__role=OrganisationRole.ADMIN, project__organisation__userorganisation__is_active=True, ) + return directly_related | indirectly_related def _get_organisation(self) -> Organisation | None: """ diff --git a/api/tests/integration/audit/conftest.py b/api/tests/integration/audit/conftest.py new file mode 100644 index 000000000000..824f2d78f5fa --- /dev/null +++ b/api/tests/integration/audit/conftest.py @@ -0,0 +1,13 @@ +import pytest +from pytest_mock import MockerFixture + +from organisations.subscriptions.metadata import BaseSubscriptionMetadata + + +@pytest.fixture(autouse=True) +def _subscription_metadata(mocker: MockerFixture) -> None: + """Lift the free plan's audit log visibility limit, which hides all past logs.""" + mocker.patch( + "organisations.models.Subscription.get_subscription_metadata", + return_value=BaseSubscriptionMetadata(audit_log_visibility_days=None), + ) diff --git a/api/tests/integration/audit/test_all_audit_logs.py b/api/tests/integration/audit/test_all_audit_logs.py new file mode 100644 index 000000000000..fcdf31f8a942 --- /dev/null +++ b/api/tests/integration/audit/test_all_audit_logs.py @@ -0,0 +1,30 @@ +from rest_framework.test import APIClient + +from audit.models import AuditLog + + +def test_get_logs__mixed_direct_and_indirect_relation_to_organisation__responds_200_with_all_logs( + admin_client: APIClient, + environment: int, + organisation: int, + project: int, +) -> None: + # Given + AuditLog.objects.create( + organisation_id=organisation, + log="User `alice@example.com` joined the organisation", + ) + AuditLog.objects.create(project_id=project, log="Flag `squeeze` created") + AuditLog.objects.create(environment_id=environment, log="Flag `squeeze` enabled") + + # When + response = admin_client.get("/api/v1/audit/") + + # Then + assert response.status_code == 200 + assert [result["log"] for result in response.json()["results"]] == [ + "Flag `squeeze` enabled", + "Flag `squeeze` created", + "User `alice@example.com` joined the organisation", + "New Environment created: Test Environment", + ] diff --git a/api/tests/integration/audit/test_audit_logs.py b/api/tests/integration/audit/test_audit_logs.py index 9fcc5fa04e22..2aec7dd3f766 100644 --- a/api/tests/integration/audit/test_audit_logs.py +++ b/api/tests/integration/audit/test_audit_logs.py @@ -6,7 +6,6 @@ from django.utils import timezone from freezegun import freeze_time from pytest_django.fixtures import SettingsWrapper -from pytest_mock import MockerFixture from rest_framework import status from rest_framework.test import APIClient @@ -14,21 +13,9 @@ from core.signals import create_audit_log_from_historical_record from features.models import FeatureState from features.workflows.core.models import ChangeRequest -from organisations.subscriptions.metadata import BaseSubscriptionMetadata from users.models import FFAdminUser -@pytest.fixture(autouse=True) -def _subscription_metadata(mocker: MockerFixture) -> None: - metadata = BaseSubscriptionMetadata( - audit_log_visibility_days=None, - ) - mocker.patch( - "organisations.models.Subscription.get_subscription_metadata", - return_value=metadata, - ) - - def test_list_audit_logs__with_project_filter__makes_expected_queries( # type: ignore[no-untyped-def] admin_client, project, diff --git a/api/tests/integration/audit/test_organisation_level_audit_logs.py b/api/tests/integration/audit/test_organisation_level_audit_logs.py index 7c39382e7927..05f666ea9a36 100644 --- a/api/tests/integration/audit/test_organisation_level_audit_logs.py +++ b/api/tests/integration/audit/test_organisation_level_audit_logs.py @@ -4,26 +4,15 @@ import pytest import responses from pytest_django import DjangoAssertNumQueries -from pytest_mock import MockerFixture from rest_framework.test import APIClient from audit.models import AuditLog from environments.models import Environment from organisations.models import Organisation -from organisations.subscriptions.metadata import BaseSubscriptionMetadata from projects.models import Project from users.models import FFAdminUser -@pytest.fixture(autouse=True) -def _subscription_metadata(mocker: MockerFixture) -> None: - """Lift the free plan's audit log visibility limit, which hides all past logs.""" - mocker.patch( - "organisations.models.Subscription.get_subscription_metadata", - return_value=BaseSubscriptionMetadata(audit_log_visibility_days=None), - ) - - @pytest.fixture def project(organisation: int) -> int: """Create a project outside the API, so it records no audit log.""" From f0156eb7de5f222a7ad6a067db963a6551c11c76 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 9 Nov 2026 20:56:23 -0300 Subject: [PATCH 07/41] all paths covered --- api/tests/unit/audit/test_unit_audit_signals.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/api/tests/unit/audit/test_unit_audit_signals.py b/api/tests/unit/audit/test_unit_audit_signals.py index 5ddf4e671396..5180a288e59e 100644 --- a/api/tests/unit/audit/test_unit_audit_signals.py +++ b/api/tests/unit/audit/test_unit_audit_signals.py @@ -1,6 +1,7 @@ import json from datetime import timedelta +import pytest import responses from django.utils import timezone from pytest_django.fixtures import SettingsWrapper @@ -76,14 +77,16 @@ def test_call_webhooks__organisation_has_no_webhooks__does_not_create_task( mocked_call_organisation_webhooks.delay.assert_not_called() +@pytest.mark.parametrize("related_object", ["project", "environment"]) def test_call_webhooks__organisation_has_webhooks__creates_task( organisation: Organisation, - project: Project, + related_object: str, + request: pytest.FixtureRequest, settings: SettingsWrapper, mocker: MockerFixture, ) -> None: # Given - audit_log = AuditLog.objects.create(project=project) + audit_log = AuditLog(**{related_object: request.getfixturevalue(related_object)}) OrganisationWebhook.objects.create( organisation=organisation, name="Example webhook", From e56f943aab1f112201e11daeb098c920d7e46f87 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 9 Nov 2026 21:19:58 -0300 Subject: [PATCH 08/41] tighten up org logs in the all view --- api/audit/serializers.py | 1 + api/audit/types.py | 1 + api/audit/views.py | 4 + .../integration/audit/test_all_audit_logs.py | 104 ++++++++++++++++++ 4 files changed, 110 insertions(+) diff --git a/api/audit/serializers.py b/api/audit/serializers.py index b660c21a88b4..7f9865f4e6ca 100644 --- a/api/audit/serializers.py +++ b/api/audit/serializers.py @@ -100,6 +100,7 @@ def get_change_type(self, instance: AuditLog) -> ChangeType: class AuditLogsQueryParamSerializer(serializers.Serializer): # type: ignore[type-arg] + organisation = serializers.IntegerField(required=False) project = serializers.IntegerField(required=False) environments = serializers.ListField( child=serializers.IntegerField(min_value=0), required=False diff --git a/api/audit/types.py b/api/audit/types.py index 019c8f7c143e..d2f29dc0ed33 100644 --- a/api/audit/types.py +++ b/api/audit/types.py @@ -10,6 +10,7 @@ class AuditLogChangeDetail(TypedDict): class AuditLogsQueryParams(TypedDict, total=False): + organisation: int project: int environments: list[int] is_system_event: bool | None diff --git a/api/audit/views.py b/api/audit/views.py index 6e75a0f3df1e..af4e6264f8ce 100644 --- a/api/audit/views.py +++ b/api/audit/views.py @@ -44,6 +44,10 @@ def get_queryset(self) -> QuerySet[AuditLog]: if (is_org_level := serializer.data.get("is_organisation_level")) is not None: q = q & Q(organisation__isnull=not is_org_level) + if organisation_id := serializer.data.get("organisation"): + directly_related = Q(organisation__id=organisation_id) + indirectly_related = Q(project__organisation__id=organisation_id) + q = q & (directly_related | indirectly_related) if project_id := serializer.data.get("project"): q = q & Q(project__id=project_id) if environment_ids := serializer.data.get("environments"): diff --git a/api/tests/integration/audit/test_all_audit_logs.py b/api/tests/integration/audit/test_all_audit_logs.py index fcdf31f8a942..d48bf320c8c9 100644 --- a/api/tests/integration/audit/test_all_audit_logs.py +++ b/api/tests/integration/audit/test_all_audit_logs.py @@ -1,6 +1,7 @@ from rest_framework.test import APIClient from audit.models import AuditLog +from organisations.models import Organisation def test_get_logs__mixed_direct_and_indirect_relation_to_organisation__responds_200_with_all_logs( @@ -28,3 +29,106 @@ def test_get_logs__mixed_direct_and_indirect_relation_to_organisation__responds_ "User `alice@example.com` joined the organisation", "New Environment created: Test Environment", ] + + +def test_get_logs__multiple_organisations__responds_200_with_all_logs( + admin_client: APIClient, + organisation: int, +) -> None: + # Given + other_organisation = admin_client.post( + "/api/v1/organisations/", {"name": "Bananas Inc"} + ).json()["id"] + AuditLog.objects.create( + organisation_id=organisation, + log="User `alice@example.com` joined the organisation", + ) + AuditLog.objects.create( + organisation_id=other_organisation, + log="User `bob@example.com` joined the organisation", + ) + + # When + response = admin_client.get("/api/v1/audit/") + + # Then + assert response.status_code == 200 + assert [result["log"] for result in response.json()["results"]] == [ + "User `bob@example.com` joined the organisation", + "User `alice@example.com` joined the organisation", + ] + + +def test_get_logs__unrelated_organisation__responds_200_with_logs_from_organisations_user_is_related_to( + admin_client: APIClient, + organisation: int, +) -> None: + # Given + unrelated_organisation = Organisation.objects.create(name="Bananas Inc") + AuditLog.objects.create( + organisation_id=organisation, + log="User `alice@example.com` joined the organisation", + ) + AuditLog.objects.create( + organisation=unrelated_organisation, + log="User `bob@example.com` joined the organisation", + ) + + # When + response = admin_client.get("/api/v1/audit/") + + # Then + assert response.status_code == 200 + assert [result["log"] for result in response.json()["results"]] == [ + "User `alice@example.com` joined the organisation", + ] + + +def test_get_logs__organisation_filter__responds_200_with_only_logs_for_that_organisation( + admin_client: APIClient, + organisation: int, + project: int, +) -> None: + # Given + other_organisation = admin_client.post( + "/api/v1/organisations/", {"name": "Bananas Inc"} + ).json()["id"] + AuditLog.objects.create( + organisation_id=organisation, + log="User `alice@example.com` joined the organisation", + ) + AuditLog.objects.create(project_id=project, log="Flag `squeeze` created") + AuditLog.objects.create( + organisation_id=other_organisation, + log="User `bob@example.com` joined the organisation", + ) + + # When + response = admin_client.get("/api/v1/audit/", {"organisation": organisation}) + + # Then + assert response.status_code == 200 + assert [result["log"] for result in response.json()["results"]] == [ + "Flag `squeeze` created", + "User `alice@example.com` joined the organisation", + ] + + +def test_get_logs__non_admin_user__responds_200_with_no_logs( + non_admin_client: APIClient, + organisation: int, + project: int, +) -> None: + # Given + AuditLog.objects.create( + organisation_id=organisation, + log="User `alice@example.com` joined the organisation", + ) + AuditLog.objects.create(project_id=project, log="Flag `squeeze` created") + + # When + response = non_admin_client.get("/api/v1/audit/") + + # Then + assert response.status_code == 200 + assert response.json()["results"] == [] From 0b47b94b4024804a9a13041aff8a0fe24646ac74 Mon Sep 17 00:00:00 2001 From: "flagsmith-engineering[bot]" Date: Tue, 10 Nov 2026 00:27:27 +0000 Subject: [PATCH 09/41] chore: Update documentation artefacts --- openapi.yaml | 44 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) diff --git a/openapi.yaml b/openapi.yaml index c2f765241d65..3e8a112b7ecc 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -260,12 +260,22 @@ paths: items: type: integer minimum: 0 + - name: is_organisation_level + in: query + schema: + type: + - boolean + - 'null' - name: is_system_event in: query schema: type: - boolean - 'null' + - name: organisation + in: query + schema: + type: integer - name: page in: query description: A page number within the paginated result set. @@ -9761,17 +9771,29 @@ paths: items: type: integer minimum: 0 + - name: is_organisation_level + in: query + schema: + type: + - boolean + - 'null' - name: is_system_event in: query schema: type: - boolean - 'null' + - name: organisation + in: query + schema: + type: integer - name: organisation_pk in: path required: true schema: - type: string + type: + - integer + - 'null' - name: page in: query description: A page number within the paginated result set. @@ -9820,7 +9842,9 @@ paths: in: path required: true schema: - type: string + type: + - integer + - 'null' responses: '200': description: '' @@ -14912,12 +14936,22 @@ paths: items: type: integer minimum: 0 + - name: is_organisation_level + in: query + schema: + type: + - boolean + - 'null' - name: is_system_event in: query schema: type: - boolean - 'null' + - name: organisation + in: query + schema: + type: integer - name: page in: query description: A page number within the paginated result set. @@ -19215,6 +19249,8 @@ components: type: string author: $ref: '#/components/schemas/UserList' + organisation: + $ref: '#/components/schemas/OrganisationSerializerBasic' environment: $ref: '#/components/schemas/EnvironmentSerializerLight' project: @@ -19242,6 +19278,7 @@ components: - created_date - environment - log + - organisation - project AuditLogRetrieve: type: object @@ -19257,6 +19294,8 @@ components: type: string author: $ref: '#/components/schemas/UserList' + organisation: + $ref: '#/components/schemas/OrganisationSerializerBasic' environment: $ref: '#/components/schemas/EnvironmentSerializerLight' project: @@ -19308,6 +19347,7 @@ components: - created_date - environment - log + - organisation - project BaseEdgeIdentityFeatureState: type: object From a142bacf313160da61b5464060887316e818287b Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 10 Nov 2026 14:03:48 -0300 Subject: [PATCH 10/41] 404 --- api/audit/permissions.py | 7 +++-- ...ogs.py => test_organisation_audit_logs.py} | 14 +++++++++ .../audit/test_project_level_audit_logs.py | 31 +++++++++++++++++++ 3 files changed, 50 insertions(+), 2 deletions(-) rename api/tests/integration/audit/{test_organisation_level_audit_logs.py => test_organisation_audit_logs.py} (96%) create mode 100644 api/tests/integration/audit/test_project_level_audit_logs.py diff --git a/api/audit/permissions.py b/api/audit/permissions.py index 83d0cc69d254..cace2fa3a6c1 100644 --- a/api/audit/permissions.py +++ b/api/audit/permissions.py @@ -15,14 +15,17 @@ def has_permission(self, request: Request, view: View): # type: ignore[no-untyp organisation_id = view.kwargs["organisation_pk"] organisation = Organisation.objects.get(id=organisation_id) except (Organisation.DoesNotExist, KeyError): - return False + raise NotFound() user = request.user assert not isinstance(user, AnonymousUser) + if user.is_organisation_admin(organisation): return True + if not user.belongs_to(organisation.id): raise NotFound() + return False @@ -32,6 +35,6 @@ def has_permission(self, request: Request, view: View): # type: ignore[no-untyp project_id = view.kwargs["project_pk"] project = Project.objects.get(id=project_id) except (Project.DoesNotExist, KeyError): - return False + raise NotFound() return request.user.has_project_permission(VIEW_AUDIT_LOG, project) # type: ignore[union-attr] diff --git a/api/tests/integration/audit/test_organisation_level_audit_logs.py b/api/tests/integration/audit/test_organisation_audit_logs.py similarity index 96% rename from api/tests/integration/audit/test_organisation_level_audit_logs.py rename to api/tests/integration/audit/test_organisation_audit_logs.py index 05f666ea9a36..741754fd8f82 100644 --- a/api/tests/integration/audit/test_organisation_level_audit_logs.py +++ b/api/tests/integration/audit/test_organisation_audit_logs.py @@ -317,6 +317,20 @@ def test_get_logs__non_member__responds_404( assert response.json() == {"detail": "Not found."} +def test_get_logs__organisation_not_found__responds_404( + admin_client: APIClient, +) -> None: + # Given + Organisation.objects.filter(id=999999).delete() # 🤷 + + # When + response = admin_client.get("/api/v1/organisations/999999/audit/") + + # Then + assert response.status_code == 404 + assert response.json() == {"detail": "Not found."} + + @responses.activate def test_webhook_dispatch__organisation_log__sends_webhook( admin_client: APIClient, diff --git a/api/tests/integration/audit/test_project_level_audit_logs.py b/api/tests/integration/audit/test_project_level_audit_logs.py new file mode 100644 index 000000000000..56d08802051e --- /dev/null +++ b/api/tests/integration/audit/test_project_level_audit_logs.py @@ -0,0 +1,31 @@ +from rest_framework.test import APIClient + +from projects.models import Project + + +def test_get_logs__member_but_not_admin__responds_403( + non_admin_client: APIClient, + project: int, +) -> None: + # Given / When + response = non_admin_client.get(f"/api/v1/projects/{project}/audit/") + + # Then + assert response.status_code == 403 + assert response.json() == { + "detail": "You do not have permission to perform this action." + } + + +def test_get_logs__project_not_found__responds_404( + admin_client: APIClient, +) -> None: + # Given + Project.objects.filter(id=999999).delete() # 🤷 + + # When + response = admin_client.get("/api/v1/projects/999999/audit/") + + # Then + assert response.status_code == 404 + assert response.json() == {"detail": "Not found."} From c1ccfd66a120157d9ec177db563cb9d8c3b27a59 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 10 Nov 2026 10:44:06 -0300 Subject: [PATCH 11/41] accurate api spec --- api/audit/serializers.py | 12 ++++++------ api/audit/views.py | 8 +++++++- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/api/audit/serializers.py b/api/audit/serializers.py index 7f9865f4e6ca..029a882772d5 100644 --- a/api/audit/serializers.py +++ b/api/audit/serializers.py @@ -11,9 +11,9 @@ class AuditLogListSerializer(serializers.ModelSerializer): # type: ignore[type-arg] author = UserListSerializer() - organisation = OrganisationSerializerBasic() - environment = EnvironmentSerializerLight() - project = ProjectListSerializer() + organisation = OrganisationSerializerBasic(allow_null=True) + environment = EnvironmentSerializerLight(allow_null=True) + project = ProjectListSerializer(allow_null=True) class Meta: model = AuditLog @@ -40,9 +40,9 @@ class AuditLogChangeDetailsSerializer(serializers.Serializer[AuditLogChangeDetai class AuditLogRetrieveSerializer(serializers.ModelSerializer): # type: ignore[type-arg] author = UserListSerializer() - organisation = OrganisationSerializerBasic() - environment = EnvironmentSerializerLight() - project = ProjectListSerializer() + organisation = OrganisationSerializerBasic(allow_null=True) + environment = EnvironmentSerializerLight(allow_null=True) + project = ProjectListSerializer(allow_null=True) change_details = serializers.SerializerMethodField() change_type = serializers.SerializerMethodField() diff --git a/api/audit/views.py b/api/audit/views.py index af4e6264f8ce..85ad961ec14b 100644 --- a/api/audit/views.py +++ b/api/audit/views.py @@ -4,7 +4,8 @@ from django.db.models import Q, QuerySet from django.utils import timezone from django.utils.decorators import method_decorator -from drf_spectacular.utils import extend_schema +from drf_spectacular.types import OpenApiTypes +from drf_spectacular.utils import OpenApiParameter, extend_schema from rest_framework import mixins, viewsets from rest_framework.permissions import IsAuthenticated @@ -128,6 +129,11 @@ def _get_organisation(self) -> Organisation | None: ) +@extend_schema( + parameters=[ + OpenApiParameter("organisation_pk", OpenApiTypes.INT, OpenApiParameter.PATH), + ], +) class OrganisationAuditLogViewSet(_BaseAuditLogViewSet): permission_classes = [IsAuthenticated, OrganisationAuditLogPermissions] From 41fee7b32c79f84152291e257cc85001460f3f6c Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 10 Nov 2026 12:09:56 -0300 Subject: [PATCH 12/41] split migrations --- .../migrations/0016_add_organisation_id.py | 15 ----------- .../0017_add_organisation_id_index.py | 25 +++++++++++++++++++ 2 files changed, 25 insertions(+), 15 deletions(-) create mode 100644 api/audit/migrations/0017_add_organisation_id_index.py diff --git a/api/audit/migrations/0016_add_organisation_id.py b/api/audit/migrations/0016_add_organisation_id.py index 512de4fcad13..4ae8432d5a45 100644 --- a/api/audit/migrations/0016_add_organisation_id.py +++ b/api/audit/migrations/0016_add_organisation_id.py @@ -2,19 +2,9 @@ import django.db.models.deletion from django.db import migrations, models -from django.db.backends import utils as backend_utils - -# Matches the name Django generates for a `db_index=True` index on this column -ORGANISATION_ID_INDEX_NAME = "audit_auditlog_organisation_id_" + ( - backend_utils.names_digest( # type: ignore[attr-defined] # Missing from django-stubs - "audit_auditlog", "organisation_id", length=8 - ) -) class Migration(migrations.Migration): - atomic = False - dependencies = [ ("audit", "0015_add_log_trigram_index"), ("organisations", "0061_add_user_organisation_is_active"), @@ -28,11 +18,6 @@ class Migration(migrations.Migration): name="organisation_id", field=models.IntegerField(null=True), ), - migrations.RunSQL( - f"CREATE INDEX CONCURRENTLY IF NOT EXISTS {ORGANISATION_ID_INDEX_NAME} " - "ON audit_auditlog (organisation_id)", - reverse_sql=f"DROP INDEX CONCURRENTLY IF EXISTS {ORGANISATION_ID_INDEX_NAME}", - ), ], state_operations=[ migrations.AddField( diff --git a/api/audit/migrations/0017_add_organisation_id_index.py b/api/audit/migrations/0017_add_organisation_id_index.py new file mode 100644 index 000000000000..49ac810c2f92 --- /dev/null +++ b/api/audit/migrations/0017_add_organisation_id_index.py @@ -0,0 +1,25 @@ +from django.db import migrations +from django.db.backends import utils as backend_utils + +# Matches the name Django generates for a `db_index=True` index on this column +ORGANISATION_ID_INDEX_NAME = "audit_auditlog_organisation_id_" + ( + backend_utils.names_digest( # type: ignore[attr-defined] # Missing from django-stubs + "audit_auditlog", "organisation_id", length=8 + ) +) + + +class Migration(migrations.Migration): + atomic = False + + dependencies = [ + ("audit", "0016_add_organisation_id"), + ] + + operations = [ + migrations.RunSQL( + f"CREATE INDEX CONCURRENTLY IF NOT EXISTS {ORGANISATION_ID_INDEX_NAME} " + "ON audit_auditlog (organisation_id)", + reverse_sql=f"DROP INDEX CONCURRENTLY IF EXISTS {ORGANISATION_ID_INDEX_NAME}", + ), + ] From e144ed7a01884e98295be31d354ca5cae0bc58a7 Mon Sep 17 00:00:00 2001 From: "flagsmith-engineering[bot]" Date: Tue, 10 Nov 2026 17:06:41 +0000 Subject: [PATCH 13/41] chore: Update documentation artefacts --- openapi.yaml | 32 ++++++++++++++++++++------------ 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/openapi.yaml b/openapi.yaml index 3e8a112b7ecc..4d062089e3c6 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -9791,9 +9791,7 @@ paths: in: path required: true schema: - type: - - integer - - 'null' + type: integer - name: page in: query description: A page number within the paginated result set. @@ -9842,9 +9840,7 @@ paths: in: path required: true schema: - type: - - integer - - 'null' + type: integer responses: '200': description: '' @@ -19250,11 +19246,17 @@ components: author: $ref: '#/components/schemas/UserList' organisation: - $ref: '#/components/schemas/OrganisationSerializerBasic' + oneOf: + - $ref: '#/components/schemas/OrganisationSerializerBasic' + - type: 'null' environment: - $ref: '#/components/schemas/EnvironmentSerializerLight' + oneOf: + - $ref: '#/components/schemas/EnvironmentSerializerLight' + - type: 'null' project: - $ref: '#/components/schemas/ProjectList' + oneOf: + - $ref: '#/components/schemas/ProjectList' + - type: 'null' related_object_id: type: - integer @@ -19295,11 +19297,17 @@ components: author: $ref: '#/components/schemas/UserList' organisation: - $ref: '#/components/schemas/OrganisationSerializerBasic' + oneOf: + - $ref: '#/components/schemas/OrganisationSerializerBasic' + - type: 'null' environment: - $ref: '#/components/schemas/EnvironmentSerializerLight' + oneOf: + - $ref: '#/components/schemas/EnvironmentSerializerLight' + - type: 'null' project: - $ref: '#/components/schemas/ProjectList' + oneOf: + - $ref: '#/components/schemas/ProjectList' + - type: 'null' related_object_id: type: - integer From d711624adedae4e9e06acf829f19927111a32bc3 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 10 Nov 2026 17:39:28 -0300 Subject: [PATCH 14/41] tdd parkour --- .../audit/events/test_authentication_logs.py | 369 ++++++++++++++++++ 1 file changed, 369 insertions(+) create mode 100644 api/tests/integration/audit/events/test_authentication_logs.py diff --git a/api/tests/integration/audit/events/test_authentication_logs.py b/api/tests/integration/audit/events/test_authentication_logs.py new file mode 100644 index 000000000000..34429ae9570f --- /dev/null +++ b/api/tests/integration/audit/events/test_authentication_logs.py @@ -0,0 +1,369 @@ +import pyotp +import pytest +from django.contrib.auth.hashers import make_password +from rest_framework.authtoken.models import Token +from rest_framework.test import APIClient + +from audit.models import AuditLog +from custom_auth.mfa.trench.models import MFAMethod +from organisations.models import Organisation +from users.models import FFAdminUser + + +@pytest.fixture +def user(db: None) -> FFAdminUser: + return FFAdminUser.objects.create( # type: ignore[no-any-return] + email="alice@example.com", + password=make_password("password"), + ) + + +@pytest.fixture +def organisation(user: FFAdminUser) -> Organisation: + organisation = Organisation.objects.create(name="Test org") + user.add_organisation(organisation) + return organisation # type: ignore[no-any-return] + + +@pytest.fixture +def other_organisation(user: FFAdminUser) -> Organisation: + organisation = Organisation.objects.create(name="Bananas Inc") + user.add_organisation(organisation) + return organisation # type: ignore[no-any-return] + + +@pytest.fixture(autouse=True) +def unrelated_organisation(db: None) -> Organisation: + return Organisation.objects.create(name="Grapes Ltd") # type: ignore[no-any-return] + + +@pytest.fixture +def user_totp(user: FFAdminUser) -> pyotp.TOTP: + """Enable 2FA outside the API, so it records no audit log.""" + secret = pyotp.random_base32() + MFAMethod.objects.create( + user=user, + name="app", + secret=secret, + is_primary=True, + is_active=True, + ) + return pyotp.TOTP(secret) + + +@pytest.fixture +def user_client(api_client: APIClient, user: FFAdminUser) -> APIClient: + """Authenticate outside the API, so it records no audit log.""" + token = Token.objects.create(user=user) + api_client.credentials(HTTP_AUTHORIZATION=f"Token {token.key}") + return api_client + + +def test_login__correct_credentials_2fa_disabled__creates_audit_log( + api_client: APIClient, + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, +) -> None: + # Given / When + response = api_client.post( + "/api/v1/auth/login/", + {"email": "alice@example.com", "password": "password"}, + format="json", + ) + + # Then + assert response.status_code == 200 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged in without 2FA.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged in without 2FA.", + }, + ] + + +def test_login__correct_credentials_2fa_enabled__creates_audit_log( + api_client: APIClient, + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, + user_totp: pyotp.TOTP, +) -> None: + # Given + ephemeral_token = api_client.post( + "/api/v1/auth/login/", + {"email": "alice@example.com", "password": "password"}, + format="json", + ).json()["ephemeral_token"] + + # When + response = api_client.post( + "/api/v1/auth/login/code/", + {"ephemeral_token": ephemeral_token, "code": user_totp.now()}, + format="json", + ) + + # Then + assert response.status_code == 200 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` has entered their password but needs 2FA.", + }, + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged in with 2FA.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` has entered their password but needs 2FA.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged in with 2FA.", + }, + ] + + +def test_login__incorrect_password__creates_audit_log( + api_client: APIClient, + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, +) -> None: + # Given / When + response = api_client.post( + "/api/v1/auth/login/", + {"email": "alice@example.com", "password": "incorrect"}, + format="json", + ) + + # Then + assert response.status_code == 400 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` failed to log in: incorrect password.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` failed to log in: incorrect password.", + }, + ] + + +def test_login__incorrect_2fa_code__creates_audit_log( + api_client: APIClient, + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, + user_totp: pyotp.TOTP, +) -> None: + # Given + ephemeral_token = api_client.post( + "/api/v1/auth/login/", + {"email": "alice@example.com", "password": "password"}, + format="json", + ).json()["ephemeral_token"] + + # When + response = api_client.post( + "/api/v1/auth/login/code/", + {"ephemeral_token": ephemeral_token, "code": "incorrect"}, + format="json", + ) + + # Then + assert response.status_code == 401 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` has entered their password but needs 2FA.", + }, + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` failed to log in: incorrect 2FA code.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` has entered their password but needs 2FA.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` failed to log in: incorrect 2FA code.", + }, + ] + + +def test_logout__completed__creates_audit_log( + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, + user_client: APIClient, +) -> None: + # Given / When + response = user_client.post("/api/v1/auth/logout/") + + # Then + assert response.status_code == 204 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged out.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged out.", + }, + ] + + +def test_change_password__completed__creates_audit_log( + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, + user_client: APIClient, +) -> None: + # Given / When + response = user_client.post( + "/api/v1/auth/users/set_password/", + { + "current_password": "password", + "new_password": "correct-horse-battery-staple", + "re_new_password": "correct-horse-battery-staple", + }, + format="json", + ) + + # Then + assert response.status_code == 204 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` changed their password.", + }, + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged out.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` changed their password.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged out.", + }, + ] + + +def test_enable_2fa__completed__creates_audit_log( + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, + user_client: APIClient, +) -> None: + # Given + secret = user_client.post("/api/v1/auth/app/activate/").json()["secret"] + + # When + response = user_client.post( + "/api/v1/auth/app/activate/confirm/", + {"code": pyotp.TOTP(secret).now()}, + format="json", + ) + + # Then + assert response.status_code == 200 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` enabled 2FA.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` enabled 2FA.", + }, + ] + + +def test_disable_2fa__completed__creates_audit_log( + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, + user_client: APIClient, + user_totp: pyotp.TOTP, +) -> None: + # Given / When + response = user_client.post("/api/v1/auth/app/deactivate/") + + # Then + assert response.status_code == 204 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` disabled 2FA.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` disabled 2FA.", + }, + ] From 3f1b1cf53e953e7364fcf3712e9f31cec69f0642 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 10 Nov 2026 17:43:34 -0300 Subject: [PATCH 15/41] docs --- .../governance-and-compliance/audit-logs.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md b/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md index d301f560daea..c30e65ca2445 100644 --- a/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md +++ b/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md @@ -109,3 +109,14 @@ The following sections describe the types of events that are recorded in the Aud ### Identities - Identity feature state overridden + +### Authentication + +These events are recorded in every organisation the user belongs to. + +- User logged in, with or without 2FA +- User entered their password, pending 2FA +- User failed to log in due to an incorrect password or 2FA code +- User logged out +- User changed their password +- User enabled or disabled 2FA From bfafb82f6f96e4ea62e659f4e400c17a7e3db58b Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 10 Nov 2026 18:33:49 -0300 Subject: [PATCH 16/41] logout audit log --- api/audit/constants.py | 2 ++ api/audit/signals.py | 19 +++++++++++++++++++ .../unit/audit/test_unit_audit_signals.py | 11 +++++++++++ 3 files changed, 32 insertions(+) diff --git a/api/audit/constants.py b/api/audit/constants.py index 38a58d091eb5..b2320ffc0592 100644 --- a/api/audit/constants.py +++ b/api/audit/constants.py @@ -90,3 +90,5 @@ FEATURE_DEPENDENCY_DELETED_MESSAGE = ( "Feature '%s' removed as a dependency for feature '%s'." ) + +USER_LOGGED_OUT_MESSAGE = "User `%s` logged out." diff --git a/api/audit/signals.py b/api/audit/signals.py index c125fcb0cbe1..a79ad3bf231d 100644 --- a/api/audit/signals.py +++ b/api/audit/signals.py @@ -2,9 +2,11 @@ from typing import TYPE_CHECKING, Any, Callable, Literal, Protocol, Type from django.conf import settings +from django.contrib.auth.signals import user_logged_out from django.db.models.signals import post_save from django.dispatch import receiver +from audit.constants import USER_LOGGED_OUT_MESSAGE from audit.models import AuditLog from audit.related_object_type import RelatedObjectType from audit.serializers import AuditLogListSerializer @@ -21,6 +23,7 @@ from integrations.sentry.models import SentryChangeTrackingConfiguration from integrations.slack.slack import SlackWrapper from organisations.models import OrganisationWebhook +from users.models import FFAdminUser from webhooks.tasks import call_organisation_webhooks from webhooks.webhooks import WebhookEventType @@ -231,6 +234,22 @@ def send_feature_flag_went_live_signal(sender, instance, **kwargs): # type: ign feature_state_change_went_live.send(feature_state) +@receiver(user_logged_out) +def create_user_logged_out_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser | None, + **kwargs: Any, +) -> None: + if user is None: + return + for organisation in user.organisations.all(): + AuditLog.objects.create( + organisation=organisation, + author=user, + log=USER_LOGGED_OUT_MESSAGE % user.email, + ) + + @receiver(feature_state_change_went_live) def send_audit_log_event_to_sentry(sender: FeatureState, **kwargs: Any) -> None: config = SentryChangeTrackingConfiguration.objects.filter( diff --git a/api/tests/unit/audit/test_unit_audit_signals.py b/api/tests/unit/audit/test_unit_audit_signals.py index 5180a288e59e..f79a1fedbec7 100644 --- a/api/tests/unit/audit/test_unit_audit_signals.py +++ b/api/tests/unit/audit/test_unit_audit_signals.py @@ -11,6 +11,7 @@ from audit.related_object_type import RelatedObjectType from audit.signals import ( call_webhooks, + create_user_logged_out_audit_logs, send_audit_log_event_to_dynatrace, send_audit_log_event_to_grafana, send_feature_flag_went_live_signal, @@ -577,6 +578,16 @@ def test_send_feature_flag_went_live_signal__scheduled_feature_state__skips_sign mock_signal_send.assert_not_called() +def test_create_user_logged_out_audit_logs__anonymous_user__creates_no_audit_log( + organisation: Organisation, +) -> None: + # Given / When + create_user_logged_out_audit_logs(sender=FFAdminUser, user=None) + + # Then + assert not AuditLog.objects.exists() + + def test_send_feature_flag_went_live_signal__non_feature_state_instance__skips_signal( project: Project, feature: Feature, From d8f26c8938f25a7ff62b6f80ce7b8a105d836ad4 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Wed, 11 Nov 2026 15:18:05 -0300 Subject: [PATCH 17/41] better index management --- .../migrations/0016_add_organisation_id.py | 1 + .../0017_add_organisation_id_index.py | 18 +++++------------- api/audit/models.py | 2 ++ 3 files changed, 8 insertions(+), 13 deletions(-) diff --git a/api/audit/migrations/0016_add_organisation_id.py b/api/audit/migrations/0016_add_organisation_id.py index 4ae8432d5a45..426e0290a0f5 100644 --- a/api/audit/migrations/0016_add_organisation_id.py +++ b/api/audit/migrations/0016_add_organisation_id.py @@ -25,6 +25,7 @@ class Migration(migrations.Migration): name="organisation", field=models.ForeignKey( db_constraint=False, + db_index=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name="audit_logs", diff --git a/api/audit/migrations/0017_add_organisation_id_index.py b/api/audit/migrations/0017_add_organisation_id_index.py index 49ac810c2f92..095e04f57d7f 100644 --- a/api/audit/migrations/0017_add_organisation_id_index.py +++ b/api/audit/migrations/0017_add_organisation_id_index.py @@ -1,12 +1,5 @@ -from django.db import migrations -from django.db.backends import utils as backend_utils - -# Matches the name Django generates for a `db_index=True` index on this column -ORGANISATION_ID_INDEX_NAME = "audit_auditlog_organisation_id_" + ( - backend_utils.names_digest( # type: ignore[attr-defined] # Missing from django-stubs - "audit_auditlog", "organisation_id", length=8 - ) -) +from django.contrib.postgres.operations import AddIndexConcurrently +from django.db import migrations, models class Migration(migrations.Migration): @@ -17,9 +10,8 @@ class Migration(migrations.Migration): ] operations = [ - migrations.RunSQL( - f"CREATE INDEX CONCURRENTLY IF NOT EXISTS {ORGANISATION_ID_INDEX_NAME} " - "ON audit_auditlog (organisation_id)", - reverse_sql=f"DROP INDEX CONCURRENTLY IF EXISTS {ORGANISATION_ID_INDEX_NAME}", + AddIndexConcurrently( + model_name="auditlog", + index=models.Index(fields=["organisation"], name="audit_organisation_idx"), ), ] diff --git a/api/audit/models.py b/api/audit/models.py index e3d92f1fdc09..b34457cd37f4 100644 --- a/api/audit/models.py +++ b/api/audit/models.py @@ -32,6 +32,7 @@ class AuditLog(LifecycleModel): # type: ignore[misc] null=True, on_delete=models.DO_NOTHING, db_constraint=False, # Logs survive on deletion + db_index=False, # Indexed in `Meta.indexes` ) project = models.ForeignKey( # type: ignore[var-annotated] Project, related_name="audit_logs", null=True, on_delete=models.DO_NOTHING @@ -78,6 +79,7 @@ class Meta: verbose_name_plural = "Audit Logs" ordering = ("-created_date",) indexes = [ + models.Index(fields=["organisation"], name="audit_organisation_idx"), models.Index( fields=["project", "-created_date"], name="audit_project_created_idx", From edd4e620d06cf36a081c2accbd4579c1eece2c4f Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Wed, 11 Nov 2026 16:37:08 -0300 Subject: [PATCH 18/41] looks good and reads nice --- api/audit/serializers.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/api/audit/serializers.py b/api/audit/serializers.py index 029a882772d5..da96f8bf5f38 100644 --- a/api/audit/serializers.py +++ b/api/audit/serializers.py @@ -109,7 +109,10 @@ class AuditLogsQueryParamSerializer(serializers.Serializer): # type: ignore[typ required=False, allow_null=True, default=None ) is_organisation_level = serializers.BooleanField( - required=False, allow_null=True, default=None + required=False, + allow_null=True, + default=None, + help_text="Filter on events unrelated to projects or environments.", ) search = serializers.CharField(min_length=3, max_length=256, required=False) From 765fad9cea18da2e5140b8c1454a47e06475816f Mon Sep 17 00:00:00 2001 From: "flagsmith-engineering[bot]" Date: Wed, 11 Nov 2026 19:44:23 +0000 Subject: [PATCH 19/41] chore: Update documentation artefacts --- openapi.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/openapi.yaml b/openapi.yaml index 4d062089e3c6..82298c729991 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -262,6 +262,7 @@ paths: minimum: 0 - name: is_organisation_level in: query + description: Filter on events unrelated to projects or environments. schema: type: - boolean @@ -9773,6 +9774,7 @@ paths: minimum: 0 - name: is_organisation_level in: query + description: Filter on events unrelated to projects or environments. schema: type: - boolean @@ -14934,6 +14936,7 @@ paths: minimum: 0 - name: is_organisation_level in: query + description: Filter on events unrelated to projects or environments. schema: type: - boolean From 6600f2d422a4e2b7b33063ab952779a15289ac20 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Wed, 11 Nov 2026 19:57:46 -0300 Subject: [PATCH 20/41] password change --- api/audit/constants.py | 1 + api/audit/signals.py | 20 ++++++++++++++++++- api/custom_auth/signals.py | 4 +++- api/custom_auth/views.py | 2 ++ .../audit/events/test_authentication_logs.py | 8 ++++---- 5 files changed, 29 insertions(+), 6 deletions(-) diff --git a/api/audit/constants.py b/api/audit/constants.py index b2320ffc0592..03da151ed5cb 100644 --- a/api/audit/constants.py +++ b/api/audit/constants.py @@ -92,3 +92,4 @@ ) USER_LOGGED_OUT_MESSAGE = "User `%s` logged out." +USER_PASSWORD_CHANGED_MESSAGE = "User `%s` changed their password." diff --git a/api/audit/signals.py b/api/audit/signals.py index a79ad3bf231d..bd819b78f003 100644 --- a/api/audit/signals.py +++ b/api/audit/signals.py @@ -6,11 +6,15 @@ from django.db.models.signals import post_save from django.dispatch import receiver -from audit.constants import USER_LOGGED_OUT_MESSAGE +from audit.constants import ( + USER_LOGGED_OUT_MESSAGE, + USER_PASSWORD_CHANGED_MESSAGE, +) from audit.models import AuditLog from audit.related_object_type import RelatedObjectType from audit.serializers import AuditLogListSerializer from audit.services import get_audited_instance_from_audit_log_record +from custom_auth.signals import user_password_changed from features.models import FeatureState, FeatureStateValue from features.multivariate.models import MultivariateFeatureStateValue from features.signals import feature_state_change_went_live @@ -250,6 +254,20 @@ def create_user_logged_out_audit_logs( ) +@receiver(user_password_changed) +def create_user_password_changed_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + for organisation in user.organisations.all(): + AuditLog.objects.create( + organisation=organisation, + author=user, + log=USER_PASSWORD_CHANGED_MESSAGE % user.email, + ) + + @receiver(feature_state_change_went_live) def send_audit_log_event_to_sentry(sender: FeatureState, **kwargs: Any) -> None: config = SentryChangeTrackingConfiguration.objects.filter( diff --git a/api/custom_auth/signals.py b/api/custom_auth/signals.py index ad4d088bb414..2da435801bfe 100644 --- a/api/custom_auth/signals.py +++ b/api/custom_auth/signals.py @@ -2,7 +2,7 @@ from typing import Any from django.conf import settings -from django.dispatch import receiver +from django.dispatch import Signal, receiver from djoser.signals import user_activated # type: ignore[import-untyped] from openfeature.evaluation_context import EvaluationContext @@ -12,6 +12,8 @@ ) from users.models import FFAdminUser +user_password_changed = Signal() + @receiver(user_activated) def create_hubspot_contact_on_activation( diff --git a/api/custom_auth/views.py b/api/custom_auth/views.py index b7380b22f588..7f6d3250d4ad 100644 --- a/api/custom_auth/views.py +++ b/api/custom_auth/views.py @@ -31,6 +31,7 @@ from custom_auth.mfa.trench.serializers import CodeLoginSerializer from custom_auth.mfa.trench.utils import user_token_generator from custom_auth.serializers import CustomUserDelete +from custom_auth.signals import user_password_changed from integrations.lead_tracking.hubspot.client import HubspotClient from integrations.lead_tracking.hubspot.services import ( register_hubspot_tracker_and_track_user, @@ -238,6 +239,7 @@ def set_password(self, request: Request, *args: Any, **kwargs: Any) -> Response: assert isinstance(user, FFAdminUser) response: Response = super().set_password(request, *args, **kwargs) blacklist_user_tokens(user) + user_password_changed.send(sender=user.__class__, request=request, user=user) return response @action(["post"], detail=False) diff --git a/api/tests/integration/audit/events/test_authentication_logs.py b/api/tests/integration/audit/events/test_authentication_logs.py index 34429ae9570f..a02d05c34054 100644 --- a/api/tests/integration/audit/events/test_authentication_logs.py +++ b/api/tests/integration/audit/events/test_authentication_logs.py @@ -283,22 +283,22 @@ def test_change_password__completed__creates_audit_log( { "organisation_id": organisation.id, "author_id": user.id, - "log": "User `alice@example.com` changed their password.", + "log": "User `alice@example.com` logged out.", }, { "organisation_id": organisation.id, "author_id": user.id, - "log": "User `alice@example.com` logged out.", + "log": "User `alice@example.com` changed their password.", }, { "organisation_id": other_organisation.id, "author_id": user.id, - "log": "User `alice@example.com` changed their password.", + "log": "User `alice@example.com` logged out.", }, { "organisation_id": other_organisation.id, "author_id": user.id, - "log": "User `alice@example.com` logged out.", + "log": "User `alice@example.com` changed their password.", }, ] From 0c740b942eb372c2d761e06aa4e86e6c2c6447f6 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Fri, 13 Nov 2026 17:18:53 -0300 Subject: [PATCH 21/41] fix test module name --- ...est_project_level_audit_logs.py => test_project_audit_logs.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename api/tests/integration/audit/{test_project_level_audit_logs.py => test_project_audit_logs.py} (100%) diff --git a/api/tests/integration/audit/test_project_level_audit_logs.py b/api/tests/integration/audit/test_project_audit_logs.py similarity index 100% rename from api/tests/integration/audit/test_project_level_audit_logs.py rename to api/tests/integration/audit/test_project_audit_logs.py From af53f26d0915d8d315f84433de4dc08623d782c2 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Fri, 13 Nov 2026 18:58:48 -0300 Subject: [PATCH 22/41] login audit logs --- api/audit/constants.py | 9 ++ api/audit/signals.py | 92 ++++++++++++++++--- .../command/authenticate_second_factor.py | 11 ++- api/custom_auth/oauth/serializers.py | 4 + api/custom_auth/serializers.py | 16 ++-- api/custom_auth/signals.py | 5 + api/custom_auth/views.py | 8 +- .../audit/events/test_authentication_logs.py | 89 ++++++++++++++++++ .../oauth/test_unit_oauth_serializers.py | 11 +-- 9 files changed, 215 insertions(+), 30 deletions(-) diff --git a/api/audit/constants.py b/api/audit/constants.py index 03da151ed5cb..63ccb7ed94f7 100644 --- a/api/audit/constants.py +++ b/api/audit/constants.py @@ -1,3 +1,5 @@ +from users.auth_type import AuthType + FEATURE_CREATED_MESSAGE = "New Flag / Remote Config created: %s" FEATURE_DELETED_MESSAGE = "Flag / Remote Config Deleted: %s" FEATURE_UPDATED_MESSAGE = "Flag / Remote Config updated: %s" @@ -91,5 +93,12 @@ "Feature '%s' removed as a dependency for feature '%s'." ) +USER_LOGGED_IN_WITHOUT_2FA_MESSAGE = "User `%s` logged in without 2FA." +USER_LOGGED_IN_WITH_2FA_MESSAGE = "User `%s` logged in with 2FA." +USER_LOGGED_IN_WITH_OAUTH_MESSAGE = "User `%s` logged in with %s." +OAUTH_PROVIDER_NAMES = {AuthType.GOOGLE: "Google", AuthType.GITHUB: "GitHub"} +USER_LOGIN_REQUIRES_2FA_MESSAGE = "User `%s` has entered their password but needs 2FA." +USER_LOGIN_PASSWORD_REJECTED_MESSAGE = "User `%s` failed to log in: incorrect password." +USER_LOGIN_2FA_CODE_REJECTED_MESSAGE = "User `%s` failed to log in: incorrect 2FA code." USER_LOGGED_OUT_MESSAGE = "User `%s` logged out." USER_PASSWORD_CHANGED_MESSAGE = "User `%s` changed their password." diff --git a/api/audit/signals.py b/api/audit/signals.py index bd819b78f003..c2fcb46fd656 100644 --- a/api/audit/signals.py +++ b/api/audit/signals.py @@ -7,14 +7,28 @@ from django.dispatch import receiver from audit.constants import ( + OAUTH_PROVIDER_NAMES, + USER_LOGGED_IN_WITH_2FA_MESSAGE, + USER_LOGGED_IN_WITH_OAUTH_MESSAGE, + USER_LOGGED_IN_WITHOUT_2FA_MESSAGE, USER_LOGGED_OUT_MESSAGE, + USER_LOGIN_2FA_CODE_REJECTED_MESSAGE, + USER_LOGIN_PASSWORD_REJECTED_MESSAGE, + USER_LOGIN_REQUIRES_2FA_MESSAGE, USER_PASSWORD_CHANGED_MESSAGE, ) from audit.models import AuditLog from audit.related_object_type import RelatedObjectType from audit.serializers import AuditLogListSerializer from audit.services import get_audited_instance_from_audit_log_record -from custom_auth.signals import user_password_changed +from custom_auth.signals import ( + user_login_2fa_code_rejected, + user_login_2fa_code_verified, + user_login_oauth_completed, + user_login_password_rejected, + user_login_password_verified, + user_password_changed, +) from features.models import FeatureState, FeatureStateValue from features.multivariate.models import MultivariateFeatureStateValue from features.signals import feature_state_change_went_live @@ -27,6 +41,7 @@ from integrations.sentry.models import SentryChangeTrackingConfiguration from integrations.slack.slack import SlackWrapper from organisations.models import OrganisationWebhook +from users.auth_type import AuthType from users.models import FFAdminUser from webhooks.tasks import call_organisation_webhooks from webhooks.webhooks import WebhookEventType @@ -238,6 +253,67 @@ def send_feature_flag_went_live_signal(sender, instance, **kwargs): # type: ign feature_state_change_went_live.send(feature_state) +def _create_user_audit_logs(user: FFAdminUser, log: str) -> None: + # We don't bulk_create because we need the post_save signal triggered + for organisation in user.organisations.all(): + AuditLog.objects.create(organisation=organisation, author=user, log=log) + + +@receiver(user_login_password_verified) +def create_user_login_password_verified_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + is_2fa_required: bool, + **kwargs: Any, +) -> None: + message = ( + USER_LOGIN_REQUIRES_2FA_MESSAGE + if is_2fa_required + else USER_LOGGED_IN_WITHOUT_2FA_MESSAGE + ) + _create_user_audit_logs(user, message % user.email) + + +@receiver(user_login_password_rejected) +def create_user_login_password_rejected_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + _create_user_audit_logs(user, USER_LOGIN_PASSWORD_REJECTED_MESSAGE % user.email) + + +@receiver(user_login_2fa_code_verified) +def create_user_login_2fa_code_verified_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + _create_user_audit_logs(user, USER_LOGGED_IN_WITH_2FA_MESSAGE % user.email) + + +@receiver(user_login_2fa_code_rejected) +def create_user_login_2fa_code_rejected_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + _create_user_audit_logs(user, USER_LOGIN_2FA_CODE_REJECTED_MESSAGE % user.email) + + +@receiver(user_login_oauth_completed) +def create_user_login_oauth_completed_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + auth_type: AuthType, + **kwargs: Any, +) -> None: + provider_name = OAUTH_PROVIDER_NAMES[auth_type] + _create_user_audit_logs( + user, USER_LOGGED_IN_WITH_OAUTH_MESSAGE % (user.email, provider_name) + ) + + @receiver(user_logged_out) def create_user_logged_out_audit_logs( sender: type[FFAdminUser], @@ -246,12 +322,7 @@ def create_user_logged_out_audit_logs( ) -> None: if user is None: return - for organisation in user.organisations.all(): - AuditLog.objects.create( - organisation=organisation, - author=user, - log=USER_LOGGED_OUT_MESSAGE % user.email, - ) + _create_user_audit_logs(user, USER_LOGGED_OUT_MESSAGE % user.email) @receiver(user_password_changed) @@ -260,12 +331,7 @@ def create_user_password_changed_audit_logs( user: FFAdminUser, **kwargs: Any, ) -> None: - for organisation in user.organisations.all(): - AuditLog.objects.create( - organisation=organisation, - author=user, - log=USER_PASSWORD_CHANGED_MESSAGE % user.email, - ) + _create_user_audit_logs(user, USER_PASSWORD_CHANGED_MESSAGE % user.email) @receiver(feature_state_change_went_live) diff --git a/api/custom_auth/mfa/trench/command/authenticate_second_factor.py b/api/custom_auth/mfa/trench/command/authenticate_second_factor.py index 35912eb5cd4f..646d29c109c6 100644 --- a/api/custom_auth/mfa/trench/command/authenticate_second_factor.py +++ b/api/custom_auth/mfa/trench/command/authenticate_second_factor.py @@ -10,6 +10,10 @@ ) from custom_auth.mfa.trench.models import MFAMethod from custom_auth.mfa.trench.utils import get_mfa_handler, user_token_generator +from custom_auth.signals import ( + user_login_2fa_code_rejected, + user_login_2fa_code_verified, +) from users.models import FFAdminUser @@ -32,5 +36,10 @@ def authenticate_second_step_command(code: str, ephemeral_token: str) -> FFAdmin user = user_token_generator.check_token(user=None, token=ephemeral_token) if user is None: raise InvalidTokenError() - is_authenticated(user_id=user.id, code=code) + try: + is_authenticated(user_id=user.id, code=code) + except InvalidCodeError: + user_login_2fa_code_rejected.send(sender=user.__class__, user=user) + raise + user_login_2fa_code_verified.send(sender=user.__class__, user=user) return user diff --git a/api/custom_auth/oauth/serializers.py b/api/custom_auth/oauth/serializers.py index 7d504f9f9676..5c66af3e04a1 100644 --- a/api/custom_auth/oauth/serializers.py +++ b/api/custom_auth/oauth/serializers.py @@ -7,6 +7,7 @@ from rest_framework import serializers from rest_framework.authtoken.models import Token +from custom_auth.signals import user_login_oauth_completed from integrations.lead_tracking.hubspot.services import ( register_hubspot_tracker_and_track_user, ) @@ -69,6 +70,9 @@ def create(self, validated_data): # type: ignore[no-untyped-def] user_logged_in.send( sender=UserModel, request=self.context.get("request"), user=user ) + user_login_oauth_completed.send( + sender=UserModel, user=user, auth_type=self.get_auth_type() + ) return Token.objects.get_or_create(user=user)[0] def _get_user(self, user_data: dict): # type: ignore[type-arg,no-untyped-def] diff --git a/api/custom_auth/serializers.py b/api/custom_auth/serializers.py index 2382601e70ef..2ed3c1eb409a 100644 --- a/api/custom_auth/serializers.py +++ b/api/custom_auth/serializers.py @@ -12,6 +12,7 @@ from rest_framework.authtoken.models import Token from rest_framework.exceptions import PermissionDenied, ValidationError +from custom_auth.signals import user_login_password_rejected from e2etests.helpers import is_e2e_request from organisations.invites.models import Invite, InviteLink from users.auth_type import AuthType @@ -46,17 +47,18 @@ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]: try: return super().validate(attrs) # type: ignore[no-any-return] except ValidationError: - self._raise_if_awaiting_activation(attrs) + self._handle_invalid_credentials(attrs) raise - def _raise_if_awaiting_activation(self, attrs: dict[str, Any]) -> None: + def _handle_invalid_credentials(self, attrs: dict[str, Any]) -> None: email = attrs.get(djoser_settings.LOGIN_FIELD) or "" user = FFAdminUser.objects.filter(email__iexact=email).first() - if ( - user - and not user.is_active - and user.check_password(attrs.get("password") or "") - ): + if not user: + return + if not user.check_password(attrs.get("password") or ""): + user_login_password_rejected.send(sender=user.__class__, user=user) + return + if not user.is_active: raise ValidationError( {EMAIL_NOT_VERIFIED_ERROR_KEY: [EMAIL_NOT_VERIFIED_ERROR]} ) diff --git a/api/custom_auth/signals.py b/api/custom_auth/signals.py index 2da435801bfe..ef69ce8881ee 100644 --- a/api/custom_auth/signals.py +++ b/api/custom_auth/signals.py @@ -13,6 +13,11 @@ from users.models import FFAdminUser user_password_changed = Signal() +user_login_password_verified = Signal() +user_login_password_rejected = Signal() +user_login_2fa_code_verified = Signal() +user_login_2fa_code_rejected = Signal() +user_login_oauth_completed = Signal() @receiver(user_activated) diff --git a/api/custom_auth/views.py b/api/custom_auth/views.py index 7f6d3250d4ad..7e3c21149c9b 100644 --- a/api/custom_auth/views.py +++ b/api/custom_auth/views.py @@ -31,7 +31,7 @@ from custom_auth.mfa.trench.serializers import CodeLoginSerializer from custom_auth.mfa.trench.utils import user_token_generator from custom_auth.serializers import CustomUserDelete -from custom_auth.signals import user_password_changed +from custom_auth.signals import user_login_password_verified, user_password_changed from integrations.lead_tracking.hubspot.client import HubspotClient from integrations.lead_tracking.hubspot.services import ( register_hubspot_tracker_and_track_user, @@ -62,6 +62,9 @@ def post(self, request: Request) -> Response: conf = settings.TRENCH_AUTH["MFA_METHODS"]["app"] # type: ignore[index] mfa_handler = CustomApplicationBackend(mfa_method=mfa_method, config=conf) mfa_handler.dispatch_message() # type: ignore[no-untyped-call] + user_login_password_verified.send( + sender=user.__class__, user=user, is_2fa_required=True + ) return Response( data={ "ephemeral_token": user_token_generator.make_token(user), @@ -69,6 +72,9 @@ def post(self, request: Request) -> Response: } ) except MFAMethodDoesNotExistError: + user_login_password_verified.send( + sender=user.__class__, user=user, is_2fa_required=False + ) if settings.COOKIE_AUTH_ENABLED: return authorise_response(user, Response(status=HTTP_204_NO_CONTENT)) return self._action(serializer) # type: ignore[no-any-return] diff --git a/api/tests/integration/audit/events/test_authentication_logs.py b/api/tests/integration/audit/events/test_authentication_logs.py index a02d05c34054..9347f9e5811e 100644 --- a/api/tests/integration/audit/events/test_authentication_logs.py +++ b/api/tests/integration/audit/events/test_authentication_logs.py @@ -1,5 +1,6 @@ import pyotp import pytest +import responses from django.contrib.auth.hashers import make_password from rest_framework.authtoken.models import Token from rest_framework.test import APIClient @@ -227,6 +228,94 @@ def test_login__incorrect_2fa_code__creates_audit_log( ] +@responses.activate +def test_login__with_google_sso__creates_audit_log( + api_client: APIClient, + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, +) -> None: + # Given + responses.get( + "https://www.googleapis.com/oauth2/v1/userinfo", + json={"id": "google-user-id", "email": "alice@example.com"}, + ) + + # When + response = api_client.post( + "/api/v1/auth/oauth/google/", + {"access_token": "google-access-token"}, + format="json", + ) + + # Then + assert response.status_code == 200 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged in with Google.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged in with Google.", + }, + ] + + +@responses.activate +def test_login__with_github_sso__creates_audit_log( + api_client: APIClient, + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, +) -> None: + # Given + responses.post( + "https://github.com/login/oauth/access_token", + body="access_token=github-access-token&token_type=bearer", + ) + responses.get( + "https://api.github.com/user", + json={"id": 12345, "name": "Alice Example"}, + ) + responses.get( + "https://api.github.com/user/emails", + json=[{"email": "alice@example.com", "primary": True, "verified": True}], + ) + + # When + response = api_client.post( + "/api/v1/auth/oauth/github/", + {"access_token": "github-code"}, + format="json", + ) + + # Then + assert response.status_code == 200 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged in with GitHub.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged in with GitHub.", + }, + ] + + def test_logout__completed__creates_audit_log( organisation: Organisation, other_organisation: Organisation, diff --git a/api/tests/unit/custom_auth/oauth/test_unit_oauth_serializers.py b/api/tests/unit/custom_auth/oauth/test_unit_oauth_serializers.py index a4b668f513e0..53c5bbd519ed 100644 --- a/api/tests/unit/custom_auth/oauth/test_unit_oauth_serializers.py +++ b/api/tests/unit/custom_auth/oauth/test_unit_oauth_serializers.py @@ -60,7 +60,7 @@ def test_oauth_login_serializer__valid_access_token__creates_user_and_returns_to "last_name": last_name, "google_user_id": google_user_id, } - serializer = OAuthLoginSerializer(data=data, context={"request": request}) # type: ignore[abstract] + serializer = GoogleLoginSerializer(data=data, context={"request": request}) mock_create_hubspot_contact_for_user = mocker.patch( "integrations.lead_tracking.hubspot.services.create_hubspot_contact_for_user" ) @@ -147,9 +147,7 @@ def test_oauth_login_serializer__auth_controller_installed__calls_is_authenticat "sys.modules", {"auth_controller.controller": mocked_auth_controller} ) - serializer = OAuthLoginSerializer( # type: ignore[abstract] - data=data, context={"request": request} - ) + serializer = GoogleLoginSerializer(data=data, context={"request": request}) # monkey patch the get_user_info method to return the mock user data serializer.get_user_info = lambda: {"email": user_email} # type: ignore[method-assign] @@ -189,10 +187,7 @@ def test_oauth_login_serializer__sign_up_type_invite_link__allows_registration( request = Request(django_request, parsers=[JSONParser()]) user_email = "test_user@test.com" - serializer = OAuthLoginSerializer( # type: ignore[abstract] - data=data, - context={"request": request}, - ) + serializer = GoogleLoginSerializer(data=data, context={"request": request}) # monkey patch the get_user_info method to return the mock user data serializer.get_user_info = lambda: {"email": user_email} # type: ignore[method-assign] From d4d26b2764e20a22022be1a67e7b43a105e280c4 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Fri, 13 Nov 2026 19:01:22 -0300 Subject: [PATCH 23/41] 2fa toggle audit logs --- api/audit/constants.py | 2 ++ api/audit/signals.py | 22 ++++++++++++++++++++++ api/custom_auth/mfa/trench/views/base.py | 3 +++ api/custom_auth/signals.py | 2 ++ 4 files changed, 29 insertions(+) diff --git a/api/audit/constants.py b/api/audit/constants.py index 63ccb7ed94f7..1a5003f321de 100644 --- a/api/audit/constants.py +++ b/api/audit/constants.py @@ -101,4 +101,6 @@ USER_LOGIN_PASSWORD_REJECTED_MESSAGE = "User `%s` failed to log in: incorrect password." USER_LOGIN_2FA_CODE_REJECTED_MESSAGE = "User `%s` failed to log in: incorrect 2FA code." USER_LOGGED_OUT_MESSAGE = "User `%s` logged out." +USER_2FA_ENABLED_MESSAGE = "User `%s` enabled 2FA." +USER_2FA_DISABLED_MESSAGE = "User `%s` disabled 2FA." USER_PASSWORD_CHANGED_MESSAGE = "User `%s` changed their password." diff --git a/api/audit/signals.py b/api/audit/signals.py index c2fcb46fd656..6c6e433cb544 100644 --- a/api/audit/signals.py +++ b/api/audit/signals.py @@ -8,6 +8,8 @@ from audit.constants import ( OAUTH_PROVIDER_NAMES, + USER_2FA_DISABLED_MESSAGE, + USER_2FA_ENABLED_MESSAGE, USER_LOGGED_IN_WITH_2FA_MESSAGE, USER_LOGGED_IN_WITH_OAUTH_MESSAGE, USER_LOGGED_IN_WITHOUT_2FA_MESSAGE, @@ -22,6 +24,8 @@ from audit.serializers import AuditLogListSerializer from audit.services import get_audited_instance_from_audit_log_record from custom_auth.signals import ( + user_2fa_disabled, + user_2fa_enabled, user_login_2fa_code_rejected, user_login_2fa_code_verified, user_login_oauth_completed, @@ -314,6 +318,24 @@ def create_user_login_oauth_completed_audit_logs( ) +@receiver(user_2fa_enabled) +def create_user_2fa_enabled_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + _create_user_audit_logs(user, USER_2FA_ENABLED_MESSAGE % user.email) + + +@receiver(user_2fa_disabled) +def create_user_2fa_disabled_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + _create_user_audit_logs(user, USER_2FA_DISABLED_MESSAGE % user.email) + + @receiver(user_logged_out) def create_user_logged_out_audit_logs( sender: type[FFAdminUser], diff --git a/api/custom_auth/mfa/trench/views/base.py b/api/custom_auth/mfa/trench/views/base.py index 8078e74b258d..2fdcb7781d79 100644 --- a/api/custom_auth/mfa/trench/views/base.py +++ b/api/custom_auth/mfa/trench/views/base.py @@ -24,6 +24,7 @@ UserMFAMethodSerializer, ) from custom_auth.mfa.trench.utils import get_mfa_handler +from custom_auth.signals import user_2fa_disabled, user_2fa_enabled User: AbstractUser = get_user_model() # type: ignore[assignment] @@ -61,6 +62,7 @@ def post(request: Request, method: str) -> Response: name=method, code=serializer.validated_data["code"], ) + user_2fa_enabled.send(sender=request.user.__class__, user=request.user) return Response({"backup_codes": backup_codes}) @@ -74,6 +76,7 @@ def post(request: Request, method: str) -> Response: mfa_method_name=method, user_id=request.user.id, # type: ignore[arg-type] ) + user_2fa_disabled.send(sender=request.user.__class__, user=request.user) return Response(status=HTTP_204_NO_CONTENT) except MFAValidationError as cause: return ErrorResponse(error=cause) diff --git a/api/custom_auth/signals.py b/api/custom_auth/signals.py index ef69ce8881ee..f6ae854407fc 100644 --- a/api/custom_auth/signals.py +++ b/api/custom_auth/signals.py @@ -18,6 +18,8 @@ user_login_2fa_code_verified = Signal() user_login_2fa_code_rejected = Signal() user_login_oauth_completed = Signal() +user_2fa_enabled = Signal() +user_2fa_disabled = Signal() @receiver(user_activated) From f280735c792d291ec7d7cb22eea513b38dc2a470 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Fri, 13 Nov 2026 19:45:46 -0300 Subject: [PATCH 24/41] better name + saml --- api/audit/constants.py | 8 ++++++-- api/audit/signals.py | 14 +++++++------- api/custom_auth/oauth/serializers.py | 4 ++-- api/custom_auth/signals.py | 2 +- api/users/auth_type.py | 1 + 5 files changed, 17 insertions(+), 12 deletions(-) diff --git a/api/audit/constants.py b/api/audit/constants.py index 1a5003f321de..f167929a5751 100644 --- a/api/audit/constants.py +++ b/api/audit/constants.py @@ -95,8 +95,12 @@ USER_LOGGED_IN_WITHOUT_2FA_MESSAGE = "User `%s` logged in without 2FA." USER_LOGGED_IN_WITH_2FA_MESSAGE = "User `%s` logged in with 2FA." -USER_LOGGED_IN_WITH_OAUTH_MESSAGE = "User `%s` logged in with %s." -OAUTH_PROVIDER_NAMES = {AuthType.GOOGLE: "Google", AuthType.GITHUB: "GitHub"} +USER_LOGGED_IN_WITH_SSO_MESSAGE = "User `%s` logged in with %s." +SSO_PROVIDER_NAMES = { + AuthType.GOOGLE: "Google", + AuthType.GITHUB: "GitHub", + AuthType.SAML: "SAML", +} USER_LOGIN_REQUIRES_2FA_MESSAGE = "User `%s` has entered their password but needs 2FA." USER_LOGIN_PASSWORD_REJECTED_MESSAGE = "User `%s` failed to log in: incorrect password." USER_LOGIN_2FA_CODE_REJECTED_MESSAGE = "User `%s` failed to log in: incorrect 2FA code." diff --git a/api/audit/signals.py b/api/audit/signals.py index 6c6e433cb544..083886c519df 100644 --- a/api/audit/signals.py +++ b/api/audit/signals.py @@ -7,11 +7,11 @@ from django.dispatch import receiver from audit.constants import ( - OAUTH_PROVIDER_NAMES, + SSO_PROVIDER_NAMES, USER_2FA_DISABLED_MESSAGE, USER_2FA_ENABLED_MESSAGE, USER_LOGGED_IN_WITH_2FA_MESSAGE, - USER_LOGGED_IN_WITH_OAUTH_MESSAGE, + USER_LOGGED_IN_WITH_SSO_MESSAGE, USER_LOGGED_IN_WITHOUT_2FA_MESSAGE, USER_LOGGED_OUT_MESSAGE, USER_LOGIN_2FA_CODE_REJECTED_MESSAGE, @@ -28,9 +28,9 @@ user_2fa_enabled, user_login_2fa_code_rejected, user_login_2fa_code_verified, - user_login_oauth_completed, user_login_password_rejected, user_login_password_verified, + user_login_sso_completed, user_password_changed, ) from features.models import FeatureState, FeatureStateValue @@ -305,16 +305,16 @@ def create_user_login_2fa_code_rejected_audit_logs( _create_user_audit_logs(user, USER_LOGIN_2FA_CODE_REJECTED_MESSAGE % user.email) -@receiver(user_login_oauth_completed) -def create_user_login_oauth_completed_audit_logs( +@receiver(user_login_sso_completed) +def create_user_login_sso_completed_audit_logs( sender: type[FFAdminUser], user: FFAdminUser, auth_type: AuthType, **kwargs: Any, ) -> None: - provider_name = OAUTH_PROVIDER_NAMES[auth_type] + provider_name = SSO_PROVIDER_NAMES[auth_type] _create_user_audit_logs( - user, USER_LOGGED_IN_WITH_OAUTH_MESSAGE % (user.email, provider_name) + user, USER_LOGGED_IN_WITH_SSO_MESSAGE % (user.email, provider_name) ) diff --git a/api/custom_auth/oauth/serializers.py b/api/custom_auth/oauth/serializers.py index 5c66af3e04a1..051c4c501363 100644 --- a/api/custom_auth/oauth/serializers.py +++ b/api/custom_auth/oauth/serializers.py @@ -7,7 +7,7 @@ from rest_framework import serializers from rest_framework.authtoken.models import Token -from custom_auth.signals import user_login_oauth_completed +from custom_auth.signals import user_login_sso_completed from integrations.lead_tracking.hubspot.services import ( register_hubspot_tracker_and_track_user, ) @@ -70,7 +70,7 @@ def create(self, validated_data): # type: ignore[no-untyped-def] user_logged_in.send( sender=UserModel, request=self.context.get("request"), user=user ) - user_login_oauth_completed.send( + user_login_sso_completed.send( sender=UserModel, user=user, auth_type=self.get_auth_type() ) return Token.objects.get_or_create(user=user)[0] diff --git a/api/custom_auth/signals.py b/api/custom_auth/signals.py index f6ae854407fc..0069b9014da1 100644 --- a/api/custom_auth/signals.py +++ b/api/custom_auth/signals.py @@ -17,7 +17,7 @@ user_login_password_rejected = Signal() user_login_2fa_code_verified = Signal() user_login_2fa_code_rejected = Signal() -user_login_oauth_completed = Signal() +user_login_sso_completed = Signal() user_2fa_enabled = Signal() user_2fa_disabled = Signal() diff --git a/api/users/auth_type.py b/api/users/auth_type.py index 7824932665ae..4a0dd8b0e284 100644 --- a/api/users/auth_type.py +++ b/api/users/auth_type.py @@ -5,3 +5,4 @@ class AuthType(Enum): GOOGLE = "GOOGLE" GITHUB = "GITHUB" EMAIL = "EMAIL" + SAML = "SAML" From 076a51dc74787d85f5ba9b516777e29042efdcab Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 16 Nov 2026 15:23:00 -0300 Subject: [PATCH 25/41] audit log when resetting a password --- api/custom_auth/views.py | 1 + 1 file changed, 1 insertion(+) diff --git a/api/custom_auth/views.py b/api/custom_auth/views.py index 7e3c21149c9b..5907ab4916d6 100644 --- a/api/custom_auth/views.py +++ b/api/custom_auth/views.py @@ -258,4 +258,5 @@ def reset_password_confirm( response: Response = super().reset_password_confirm(request, *args, **kwargs) Token.objects.filter(user=user).delete() blacklist_user_tokens(user) + user_password_changed.send(sender=user.__class__, request=request, user=user) return response From a84cfba2100f0cbd2a9c467879a1d854f78dbe27 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 16 Nov 2026 15:31:25 -0300 Subject: [PATCH 26/41] for the sake of clarity --- api/custom_auth/views.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/api/custom_auth/views.py b/api/custom_auth/views.py index 5907ab4916d6..97566afb024a 100644 --- a/api/custom_auth/views.py +++ b/api/custom_auth/views.py @@ -228,8 +228,19 @@ def hubspot_chat_token( return Response({"token": token, "email": user.email}) + @action(["post"], detail=False) + def set_password(self, request: Request, *args: Any, **kwargs: Any) -> Response: + """Update the user password""" + user = request.user + assert isinstance(user, FFAdminUser) + response: Response = super().set_password(request, *args, **kwargs) + blacklist_user_tokens(user) + user_password_changed.send(sender=user.__class__, request=request, user=user) + return response + @action(["post"], detail=False) def reset_password(self, request: Request, *args: Any, **kwargs: Any) -> Response: + """Request a password reset email""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.get_user() @@ -239,19 +250,11 @@ def reset_password(self, request: Request, *args: Any, **kwargs: Any) -> Respons return Response(status=status.HTTP_204_NO_CONTENT) - @action(["post"], detail=False) - def set_password(self, request: Request, *args: Any, **kwargs: Any) -> Response: - user = request.user - assert isinstance(user, FFAdminUser) - response: Response = super().set_password(request, *args, **kwargs) - blacklist_user_tokens(user) - user_password_changed.send(sender=user.__class__, request=request, user=user) - return response - @action(["post"], detail=False) def reset_password_confirm( self, request: Request, *args: Any, **kwargs: Any ) -> Response: + """Update the user password from a password reset URL""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.user From eebf0595f77c11c1f9950b519d06b8f0c9c50418 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 16 Nov 2026 16:56:32 -0300 Subject: [PATCH 27/41] refactor --- api/custom_auth/serializers.py | 36 ++++++++++++++-------------------- 1 file changed, 15 insertions(+), 21 deletions(-) diff --git a/api/custom_auth/serializers.py b/api/custom_auth/serializers.py index 2ed3c1eb409a..eb5be064bc8e 100644 --- a/api/custom_auth/serializers.py +++ b/api/custom_auth/serializers.py @@ -35,34 +35,28 @@ class Meta: class CustomTokenCreateSerializer(TokenCreateSerializer): # type: ignore[misc] - """ - Tells a user with correct credentials that their account is not yet - activated, instead of the generic invalid credentials error. - - The password is verified first, so an address cannot be probed for its - activation state by anyone who does not already know the password. - """ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]: + """Validate credentials input. + + Overrides djoser so that activation state can't be probed without a valid password.""" try: return super().validate(attrs) # type: ignore[no-any-return] except ValidationError: - self._handle_invalid_credentials(attrs) + if not (email := attrs.get(djoser_settings.LOGIN_FIELD)): + raise + user = FFAdminUser.objects.filter(email__iexact=email).first() + if not user: + raise + if not (password := attrs.get("password")) or not user.check_password(password): + user_login_password_rejected.send(sender=user.__class__, user=user) + raise + if not user.is_active: + raise ValidationError( + {EMAIL_NOT_VERIFIED_ERROR_KEY: [EMAIL_NOT_VERIFIED_ERROR]} + ) raise - def _handle_invalid_credentials(self, attrs: dict[str, Any]) -> None: - email = attrs.get(djoser_settings.LOGIN_FIELD) or "" - user = FFAdminUser.objects.filter(email__iexact=email).first() - if not user: - return - if not user.check_password(attrs.get("password") or ""): - user_login_password_rejected.send(sender=user.__class__, user=user) - return - if not user.is_active: - raise ValidationError( - {EMAIL_NOT_VERIFIED_ERROR_KEY: [EMAIL_NOT_VERIFIED_ERROR]} - ) - class InviteLinkValidationMixin: invite_hash = serializers.CharField(required=False, write_only=True) From c07ee813908083e5992de0603a201515489406c9 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 16 Nov 2026 17:34:52 -0300 Subject: [PATCH 28/41] improve events doc --- .../governance-and-compliance/audit-logs.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md b/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md index c30e65ca2445..eb59a23cf24b 100644 --- a/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md +++ b/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md @@ -114,9 +114,11 @@ The following sections describe the types of events that are recorded in the Aud These events are recorded in every organisation the user belongs to. -- User logged in, with or without 2FA +- User logged in with a password - User entered their password, pending 2FA +- User logged in with 2FA - User failed to log in due to an incorrect password or 2FA code +- User logged in with SSO - User logged out - User changed their password - User enabled or disabled 2FA From 284a40cadfeecc8415e3f21a4afbda1c51da8e5d Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 16 Nov 2026 18:01:40 -0300 Subject: [PATCH 29/41] locked out --- api/audit/constants.py | 1 + api/audit/signals.py | 12 ++++ .../audit/events/test_authentication_logs.py | 68 +++++++++++++++++++ 3 files changed, 81 insertions(+) diff --git a/api/audit/constants.py b/api/audit/constants.py index f167929a5751..5565758b0017 100644 --- a/api/audit/constants.py +++ b/api/audit/constants.py @@ -104,6 +104,7 @@ USER_LOGIN_REQUIRES_2FA_MESSAGE = "User `%s` has entered their password but needs 2FA." USER_LOGIN_PASSWORD_REJECTED_MESSAGE = "User `%s` failed to log in: incorrect password." USER_LOGIN_2FA_CODE_REJECTED_MESSAGE = "User `%s` failed to log in: incorrect 2FA code." +USER_LOCKED_OUT_MESSAGE = "User `%s` was locked out after too many failed logins." USER_LOGGED_OUT_MESSAGE = "User `%s` logged out." USER_2FA_ENABLED_MESSAGE = "User `%s` enabled 2FA." USER_2FA_DISABLED_MESSAGE = "User `%s` disabled 2FA." diff --git a/api/audit/signals.py b/api/audit/signals.py index 083886c519df..77d0ea0440d1 100644 --- a/api/audit/signals.py +++ b/api/audit/signals.py @@ -1,6 +1,7 @@ import logging from typing import TYPE_CHECKING, Any, Callable, Literal, Protocol, Type +from axes.signals import user_locked_out # type: ignore[import-untyped] from django.conf import settings from django.contrib.auth.signals import user_logged_out from django.db.models.signals import post_save @@ -10,6 +11,7 @@ SSO_PROVIDER_NAMES, USER_2FA_DISABLED_MESSAGE, USER_2FA_ENABLED_MESSAGE, + USER_LOCKED_OUT_MESSAGE, USER_LOGGED_IN_WITH_2FA_MESSAGE, USER_LOGGED_IN_WITH_SSO_MESSAGE, USER_LOGGED_IN_WITHOUT_2FA_MESSAGE, @@ -305,6 +307,16 @@ def create_user_login_2fa_code_rejected_audit_logs( _create_user_audit_logs(user, USER_LOGIN_2FA_CODE_REJECTED_MESSAGE % user.email) +@receiver(user_locked_out) +def create_user_locked_out_audit_logs( + sender: str, + username: str, + **kwargs: Any, +) -> None: + if user := FFAdminUser.objects.filter(email__iexact=username).first(): + _create_user_audit_logs(user, USER_LOCKED_OUT_MESSAGE % user.email) + + @receiver(user_login_sso_completed) def create_user_login_sso_completed_audit_logs( sender: type[FFAdminUser], diff --git a/api/tests/integration/audit/events/test_authentication_logs.py b/api/tests/integration/audit/events/test_authentication_logs.py index 9347f9e5811e..012a87ed4da7 100644 --- a/api/tests/integration/audit/events/test_authentication_logs.py +++ b/api/tests/integration/audit/events/test_authentication_logs.py @@ -2,6 +2,7 @@ import pytest import responses from django.contrib.auth.hashers import make_password +from pytest_django.fixtures import SettingsWrapper from rest_framework.authtoken.models import Token from rest_framework.test import APIClient @@ -456,3 +457,70 @@ def test_disable_2fa__completed__creates_audit_log( "log": "User `alice@example.com` disabled 2FA.", }, ] + + +def test_login__locked_out__creates_audit_log( + api_client: APIClient, + organisation: Organisation, + other_organisation: Organisation, + settings: SettingsWrapper, + user: FFAdminUser, +) -> None: + # Given + settings.AXES_FAILURE_LIMIT = 1 + + # When + response = api_client.post( + "/api/v1/auth/login/", + {"email": "alice@example.com", "password": "incorrect"}, + format="json", + ) + + # Then + assert response.status_code == 400 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` was locked out after too many failed logins.", + }, + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` failed to log in: incorrect password.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` was locked out after too many failed logins.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` failed to log in: incorrect password.", + }, + ] + + +def test_login__attempt_while_locked_out__creates_audit_log(): + raise NotImplementedError + + +def test_cli_login__correct_credentials__creates_audit_log(): + raise NotImplementedError + + +def test_mcp_login__correct_credentials__creates_audit_log(): + raise NotImplementedError + + +def test_cli_logout__completed__creates_audit_log(): + raise NotImplementedError + + +def test_revoke_token__completed__creates_audit_log(): + raise NotImplementedError From 756750d52ccf246f963826d2cd6b2b5a858c2b62 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 16 Nov 2026 18:44:45 -0300 Subject: [PATCH 30/41] it doesnt work if you retry --- api/audit/constants.py | 1 + api/audit/signals.py | 13 +++++- api/audit/types.py | 6 ++- .../audit/events/test_authentication_logs.py | 41 ++++++++++++++++++- 4 files changed, 56 insertions(+), 5 deletions(-) diff --git a/api/audit/constants.py b/api/audit/constants.py index 5565758b0017..8d793c7ed6d4 100644 --- a/api/audit/constants.py +++ b/api/audit/constants.py @@ -105,6 +105,7 @@ USER_LOGIN_PASSWORD_REJECTED_MESSAGE = "User `%s` failed to log in: incorrect password." USER_LOGIN_2FA_CODE_REJECTED_MESSAGE = "User `%s` failed to log in: incorrect 2FA code." USER_LOCKED_OUT_MESSAGE = "User `%s` was locked out after too many failed logins." +USER_LOGIN_WHILE_LOCKED_OUT_MESSAGE = "User `%s` failed to log in: locked out." USER_LOGGED_OUT_MESSAGE = "User `%s` logged out." USER_2FA_ENABLED_MESSAGE = "User `%s` enabled 2FA." USER_2FA_DISABLED_MESSAGE = "User `%s` disabled 2FA." diff --git a/api/audit/signals.py b/api/audit/signals.py index 77d0ea0440d1..c622895e7336 100644 --- a/api/audit/signals.py +++ b/api/audit/signals.py @@ -19,12 +19,14 @@ USER_LOGIN_2FA_CODE_REJECTED_MESSAGE, USER_LOGIN_PASSWORD_REJECTED_MESSAGE, USER_LOGIN_REQUIRES_2FA_MESSAGE, + USER_LOGIN_WHILE_LOCKED_OUT_MESSAGE, USER_PASSWORD_CHANGED_MESSAGE, ) from audit.models import AuditLog from audit.related_object_type import RelatedObjectType from audit.serializers import AuditLogListSerializer from audit.services import get_audited_instance_from_audit_log_record +from audit.types import AxesLoginRequest from custom_auth.signals import ( user_2fa_disabled, user_2fa_enabled, @@ -310,11 +312,18 @@ def create_user_login_2fa_code_rejected_audit_logs( @receiver(user_locked_out) def create_user_locked_out_audit_logs( sender: str, + request: AxesLoginRequest, username: str, **kwargs: Any, ) -> None: - if user := FFAdminUser.objects.filter(email__iexact=username).first(): - _create_user_audit_logs(user, USER_LOCKED_OUT_MESSAGE % user.email) + if not (user := FFAdminUser.objects.filter(email__iexact=username).first()): + return + message = ( + USER_LOGIN_WHILE_LOCKED_OUT_MESSAGE + if request.axes_failures_since_start > settings.AXES_FAILURE_LIMIT + else USER_LOCKED_OUT_MESSAGE + ) + _create_user_audit_logs(user, message % user.email) @receiver(user_login_sso_completed) diff --git a/api/audit/types.py b/api/audit/types.py index d2f29dc0ed33..ff0763deb16d 100644 --- a/api/audit/types.py +++ b/api/audit/types.py @@ -1,8 +1,12 @@ -from typing import Literal, TypedDict +from typing import Literal, Protocol, TypedDict ChangeType = Literal["CREATE", "UPDATE", "DELETE", "UNKNOWN"] +class AxesLoginRequest(Protocol): + axes_failures_since_start: int + + class AuditLogChangeDetail(TypedDict): field: str old: int | float | str | bool | None diff --git a/api/tests/integration/audit/events/test_authentication_logs.py b/api/tests/integration/audit/events/test_authentication_logs.py index 012a87ed4da7..a95fca2b5b06 100644 --- a/api/tests/integration/audit/events/test_authentication_logs.py +++ b/api/tests/integration/audit/events/test_authentication_logs.py @@ -1,6 +1,7 @@ import pyotp import pytest import responses +from axes.models import AccessAttempt # type: ignore[import-untyped] from django.contrib.auth.hashers import make_password from pytest_django.fixtures import SettingsWrapper from rest_framework.authtoken.models import Token @@ -506,8 +507,44 @@ def test_login__locked_out__creates_audit_log( ] -def test_login__attempt_while_locked_out__creates_audit_log(): - raise NotImplementedError +def test_login__attempt_while_locked_out__creates_audit_log( + api_client: APIClient, + organisation: Organisation, + other_organisation: Organisation, + settings: SettingsWrapper, + user: FFAdminUser, +) -> None: + # Given + AccessAttempt.objects.create( + username="alice@example.com", + failures_since_start=settings.AXES_FAILURE_LIMIT, + ) + + # When + response = api_client.post( + "/api/v1/auth/login/", + {"email": "alice@example.com", "password": "password"}, + format="json", + ) + + # Then + assert response.status_code == 400 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` failed to log in: locked out.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` failed to log in: locked out.", + }, + ] def test_cli_login__correct_credentials__creates_audit_log(): From c79ea8ab787e360273ef7637062a9f7613f526b5 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 16 Nov 2026 19:19:37 -0300 Subject: [PATCH 31/41] oauth login --- api/audit/constants.py | 1 + api/audit/signals.py | 21 +++++ .../audit/events/test_authentication_logs.py | 77 ++++++++++++++++++- 3 files changed, 95 insertions(+), 4 deletions(-) diff --git a/api/audit/constants.py b/api/audit/constants.py index 8d793c7ed6d4..a1fb46890688 100644 --- a/api/audit/constants.py +++ b/api/audit/constants.py @@ -96,6 +96,7 @@ USER_LOGGED_IN_WITHOUT_2FA_MESSAGE = "User `%s` logged in without 2FA." USER_LOGGED_IN_WITH_2FA_MESSAGE = "User `%s` logged in with 2FA." USER_LOGGED_IN_WITH_SSO_MESSAGE = "User `%s` logged in with %s." +USER_LOGGED_IN_TO_OAUTH_APPLICATION_MESSAGE = "User `%s` logged in to %s." SSO_PROVIDER_NAMES = { AuthType.GOOGLE: "Google", AuthType.GITHUB: "GitHub", diff --git a/api/audit/signals.py b/api/audit/signals.py index c622895e7336..8fc28a5b3089 100644 --- a/api/audit/signals.py +++ b/api/audit/signals.py @@ -6,12 +6,16 @@ from django.contrib.auth.signals import user_logged_out from django.db.models.signals import post_save from django.dispatch import receiver +from django.http import HttpRequest +from oauth2_provider.models import AccessToken +from oauth2_provider.signals import app_authorized from audit.constants import ( SSO_PROVIDER_NAMES, USER_2FA_DISABLED_MESSAGE, USER_2FA_ENABLED_MESSAGE, USER_LOCKED_OUT_MESSAGE, + USER_LOGGED_IN_TO_OAUTH_APPLICATION_MESSAGE, USER_LOGGED_IN_WITH_2FA_MESSAGE, USER_LOGGED_IN_WITH_SSO_MESSAGE, USER_LOGGED_IN_WITHOUT_2FA_MESSAGE, @@ -339,6 +343,23 @@ def create_user_login_sso_completed_audit_logs( ) +@receiver(app_authorized) +def create_user_oauth_login_audit_logs( + sender: object, + request: HttpRequest, + token: AccessToken, + **kwargs: Any, +) -> None: + if request.POST.get("grant_type") != "authorization_code": + return # pragma: no cover + user: FFAdminUser = token.user + _create_user_audit_logs( + user, + USER_LOGGED_IN_TO_OAUTH_APPLICATION_MESSAGE + % (user.email, token.application.name), + ) + + @receiver(user_2fa_enabled) def create_user_2fa_enabled_audit_logs( sender: type[FFAdminUser], diff --git a/api/tests/integration/audit/events/test_authentication_logs.py b/api/tests/integration/audit/events/test_authentication_logs.py index a95fca2b5b06..81e33011bed8 100644 --- a/api/tests/integration/audit/events/test_authentication_logs.py +++ b/api/tests/integration/audit/events/test_authentication_logs.py @@ -1,8 +1,13 @@ +import base64 +import hashlib +from urllib.parse import parse_qs, urlparse + import pyotp import pytest import responses from axes.models import AccessAttempt # type: ignore[import-untyped] from django.contrib.auth.hashers import make_password +from oauth2_provider.models import Application from pytest_django.fixtures import SettingsWrapper from rest_framework.authtoken.models import Token from rest_framework.test import APIClient @@ -54,6 +59,17 @@ def user_totp(user: FFAdminUser) -> pyotp.TOTP: return pyotp.TOTP(secret) +@pytest.fixture +def oauth_application(db: None) -> Application: + return Application.objects.create( + client_id="acme-agent", + name="Acme Agent", + client_type=Application.CLIENT_PUBLIC, + authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE, + redirect_uris="http://127.0.0.1:53682/callback", + ) + + @pytest.fixture def user_client(api_client: APIClient, user: FFAdminUser) -> APIClient: """Authenticate outside the API, so it records no audit log.""" @@ -547,12 +563,65 @@ def test_login__attempt_while_locked_out__creates_audit_log( ] -def test_cli_login__correct_credentials__creates_audit_log(): - raise NotImplementedError +def test_oauth_login__authorised__creates_audit_log( + api_client: APIClient, + oauth_application: Application, + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, + user_client: APIClient, +) -> None: + # Given + code_verifier = "pkce-code-verifier-of-at-least-43-characters" + code_challenge = ( + base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()) + .rstrip(b"=") + .decode() + ) + redirect_uri = user_client.post( + "/api/v1/oauth/authorize/", + { + "allow": True, + "client_id": oauth_application.client_id, + "response_type": "code", + "redirect_uri": "http://127.0.0.1:53682/callback", + "code_challenge": code_challenge, + "code_challenge_method": "S256", + }, + format="json", + ).json()["redirect_uri"] + code = parse_qs(urlparse(redirect_uri).query)["code"][0] + # When + response = api_client.post( + "/o/token/", + { + "grant_type": "authorization_code", + "code": code, + "redirect_uri": "http://127.0.0.1:53682/callback", + "client_id": oauth_application.client_id, + "code_verifier": code_verifier, + }, + ) -def test_mcp_login__correct_credentials__creates_audit_log(): - raise NotImplementedError + # Then + assert response.status_code == 200 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged in to Acme Agent.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged in to Acme Agent.", + }, + ] def test_cli_logout__completed__creates_audit_log(): From b0c99b6ef944f7fe4b07008ceff8d38f4e33c83d Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 16 Nov 2026 19:55:17 -0300 Subject: [PATCH 32/41] oauth logout --- api/app/urls.py | 3 +- api/audit/constants.py | 1 + api/audit/signals.py | 17 +++++- api/oauth2_metadata/signals.py | 3 ++ api/oauth2_metadata/views.py | 40 +++++++++++++- .../audit/events/test_authentication_logs.py | 54 +++++++++++++++++-- 6 files changed, 109 insertions(+), 9 deletions(-) create mode 100644 api/oauth2_metadata/signals.py diff --git a/api/app/urls.py b/api/app/urls.py index 239c6c36185e..1d978eee8eb9 100644 --- a/api/app/urls.py +++ b/api/app/urls.py @@ -11,6 +11,7 @@ from oauth2_metadata.views import ( DynamicClientRegistrationView, OAuthAuthorizeView, + OAuthRevokeTokenView, authorization_server_metadata, ) from users.views import password_reset_redirect @@ -76,7 +77,7 @@ path("token/", oauth2_views.TokenView.as_view(), name="token"), path( "revoke_token/", - oauth2_views.RevokeTokenView.as_view(), + OAuthRevokeTokenView.as_view(), name="revoke-token", ), path( diff --git a/api/audit/constants.py b/api/audit/constants.py index a1fb46890688..c61518233992 100644 --- a/api/audit/constants.py +++ b/api/audit/constants.py @@ -97,6 +97,7 @@ USER_LOGGED_IN_WITH_2FA_MESSAGE = "User `%s` logged in with 2FA." USER_LOGGED_IN_WITH_SSO_MESSAGE = "User `%s` logged in with %s." USER_LOGGED_IN_TO_OAUTH_APPLICATION_MESSAGE = "User `%s` logged in to %s." +USER_LOGGED_OUT_OF_OAUTH_APPLICATION_MESSAGE = "User `%s` logged out of %s." SSO_PROVIDER_NAMES = { AuthType.GOOGLE: "Google", AuthType.GITHUB: "GitHub", diff --git a/api/audit/signals.py b/api/audit/signals.py index 8fc28a5b3089..2495d0833ce5 100644 --- a/api/audit/signals.py +++ b/api/audit/signals.py @@ -7,7 +7,7 @@ from django.db.models.signals import post_save from django.dispatch import receiver from django.http import HttpRequest -from oauth2_provider.models import AccessToken +from oauth2_provider.models import AccessToken, Application from oauth2_provider.signals import app_authorized from audit.constants import ( @@ -20,6 +20,7 @@ USER_LOGGED_IN_WITH_SSO_MESSAGE, USER_LOGGED_IN_WITHOUT_2FA_MESSAGE, USER_LOGGED_OUT_MESSAGE, + USER_LOGGED_OUT_OF_OAUTH_APPLICATION_MESSAGE, USER_LOGIN_2FA_CODE_REJECTED_MESSAGE, USER_LOGIN_PASSWORD_REJECTED_MESSAGE, USER_LOGIN_REQUIRES_2FA_MESSAGE, @@ -52,6 +53,7 @@ from integrations.sentry.change_tracking import SentryChangeTracking from integrations.sentry.models import SentryChangeTrackingConfiguration from integrations.slack.slack import SlackWrapper +from oauth2_metadata.signals import oauth_session_revoked from organisations.models import OrganisationWebhook from users.auth_type import AuthType from users.models import FFAdminUser @@ -360,6 +362,19 @@ def create_user_oauth_login_audit_logs( ) +@receiver(oauth_session_revoked) +def create_user_oauth_logout_audit_logs( + sender: object, + user: FFAdminUser, + application: Application, + **kwargs: Any, +) -> None: + _create_user_audit_logs( + user, + USER_LOGGED_OUT_OF_OAUTH_APPLICATION_MESSAGE % (user.email, application.name), + ) + + @receiver(user_2fa_enabled) def create_user_2fa_enabled_audit_logs( sender: type[FFAdminUser], diff --git a/api/oauth2_metadata/signals.py b/api/oauth2_metadata/signals.py new file mode 100644 index 000000000000..f0d332c817fc --- /dev/null +++ b/api/oauth2_metadata/signals.py @@ -0,0 +1,3 @@ +from django.dispatch import Signal + +oauth_session_revoked = Signal() diff --git a/api/oauth2_metadata/views.py b/api/oauth2_metadata/views.py index 2819d2589e80..cd42537c2296 100644 --- a/api/oauth2_metadata/views.py +++ b/api/oauth2_metadata/views.py @@ -1,12 +1,14 @@ +import hashlib from typing import Any from urllib.parse import urlencode, urlparse, urlunparse import structlog -from django.http import HttpRequest, JsonResponse, QueryDict +from django.http import HttpRequest, HttpResponse, JsonResponse, QueryDict from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_GET from oauth2_provider.exceptions import OAuthToolkitError -from oauth2_provider.models import get_application_model +from oauth2_provider.models import RefreshToken, get_application_model +from oauth2_provider.views import RevokeTokenView from oauth2_provider.views.mixins import OAuthLibMixin from rest_framework import status from rest_framework import status as drf_status @@ -28,6 +30,7 @@ OAuthConsentSerializer, ) from oauth2_metadata.services import create_oauth2_application +from oauth2_metadata.signals import oauth_session_revoked logger = structlog.get_logger("oauth2_metadata") @@ -219,3 +222,36 @@ def _count_registration(self, auth_method: Any, outcome: str) -> None: flagsmith_oauth2_dcr_registrations_total.labels( token_endpoint_auth_method=auth_method, outcome=outcome ).inc() + + +class OAuthRevokeTokenView(RevokeTokenView): # type: ignore[misc] + """Revoke an OAuth 2.0 token, per RFC 7009.""" + + def post(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: + session_refresh_token = self._get_session_refresh_token(request) + response: HttpResponse = super().post(request, *args, **kwargs) + if session_refresh_token and self._is_revoked(session_refresh_token): + oauth_session_revoked.send( + sender=self.__class__, + user=session_refresh_token.user, + application=session_refresh_token.application, + ) + return response + + def _get_session_refresh_token(self, request: HttpRequest) -> RefreshToken | None: + """Identify the session to end, as revocation requests carry no user.""" + token: str = request.POST.get("token", "") + refresh_token: RefreshToken | None = ( + RefreshToken.objects.filter( + token_checksum=hashlib.sha256(token.encode("utf-8")).hexdigest(), + revoked__isnull=True, + ) + .select_related("user", "application") + .first() + ) + return refresh_token + + def _is_revoked(self, refresh_token: RefreshToken) -> bool: + """Confirm revocation, as RFC 7009 responds 200 to tokens it did not revoke.""" + refresh_token.refresh_from_db(fields=["revoked"]) + return refresh_token.revoked is not None diff --git a/api/tests/integration/audit/events/test_authentication_logs.py b/api/tests/integration/audit/events/test_authentication_logs.py index 81e33011bed8..cb2eb708a8e3 100644 --- a/api/tests/integration/audit/events/test_authentication_logs.py +++ b/api/tests/integration/audit/events/test_authentication_logs.py @@ -1,5 +1,6 @@ import base64 import hashlib +from datetime import timedelta from urllib.parse import parse_qs, urlparse import pyotp @@ -7,7 +8,8 @@ import responses from axes.models import AccessAttempt # type: ignore[import-untyped] from django.contrib.auth.hashers import make_password -from oauth2_provider.models import Application +from django.utils import timezone +from oauth2_provider.models import AccessToken, Application, RefreshToken from pytest_django.fixtures import SettingsWrapper from rest_framework.authtoken.models import Token from rest_framework.test import APIClient @@ -624,9 +626,51 @@ def test_oauth_login__authorised__creates_audit_log( ] -def test_cli_logout__completed__creates_audit_log(): - raise NotImplementedError +def test_oauth_logout__token_revoked__creates_audit_log( + api_client: APIClient, + oauth_application: Application, + organisation: Organisation, + other_organisation: Organisation, + user: FFAdminUser, +) -> None: + # Given + RefreshToken.objects.create( + user=user, + application=oauth_application, + token="refresh-token", + access_token=AccessToken.objects.create( + user=user, + application=oauth_application, + token="access-token", + expires=timezone.now() + timedelta(minutes=15), + ), + ) + # When + response = api_client.post( + "/o/revoke_token/", + { + "token": "refresh-token", + "token_type_hint": "refresh_token", + "client_id": oauth_application.client_id, + }, + ) -def test_revoke_token__completed__creates_audit_log(): - raise NotImplementedError + # Then + assert response.status_code == 200 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged out of Acme Agent.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` logged out of Acme Agent.", + }, + ] From eb13eeb65d793693cd25f11b91783c5ba1d9aa84 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Mon, 16 Nov 2026 20:09:16 -0300 Subject: [PATCH 33/41] move out --- api/audit/apps.py | 1 + api/audit/{signals.py => signals/__init__.py} | 184 +---------------- api/audit/signals/authentication.py | 188 ++++++++++++++++++ .../unit/audit/test_unit_audit_signals.py | 2 +- 4 files changed, 191 insertions(+), 184 deletions(-) rename api/audit/{signals.py => signals/__init__.py} (65%) create mode 100644 api/audit/signals/authentication.py diff --git a/api/audit/apps.py b/api/audit/apps.py index fa61af01172d..d5cfa5a86356 100644 --- a/api/audit/apps.py +++ b/api/audit/apps.py @@ -8,3 +8,4 @@ class AuditConfig(AppConfig): def ready(self): # type: ignore[no-untyped-def] from . import signals # noqa + from .signals import authentication # noqa diff --git a/api/audit/signals.py b/api/audit/signals/__init__.py similarity index 65% rename from api/audit/signals.py rename to api/audit/signals/__init__.py index 2495d0833ce5..c125fcb0cbe1 100644 --- a/api/audit/signals.py +++ b/api/audit/signals/__init__.py @@ -1,47 +1,14 @@ import logging from typing import TYPE_CHECKING, Any, Callable, Literal, Protocol, Type -from axes.signals import user_locked_out # type: ignore[import-untyped] from django.conf import settings -from django.contrib.auth.signals import user_logged_out from django.db.models.signals import post_save from django.dispatch import receiver -from django.http import HttpRequest -from oauth2_provider.models import AccessToken, Application -from oauth2_provider.signals import app_authorized - -from audit.constants import ( - SSO_PROVIDER_NAMES, - USER_2FA_DISABLED_MESSAGE, - USER_2FA_ENABLED_MESSAGE, - USER_LOCKED_OUT_MESSAGE, - USER_LOGGED_IN_TO_OAUTH_APPLICATION_MESSAGE, - USER_LOGGED_IN_WITH_2FA_MESSAGE, - USER_LOGGED_IN_WITH_SSO_MESSAGE, - USER_LOGGED_IN_WITHOUT_2FA_MESSAGE, - USER_LOGGED_OUT_MESSAGE, - USER_LOGGED_OUT_OF_OAUTH_APPLICATION_MESSAGE, - USER_LOGIN_2FA_CODE_REJECTED_MESSAGE, - USER_LOGIN_PASSWORD_REJECTED_MESSAGE, - USER_LOGIN_REQUIRES_2FA_MESSAGE, - USER_LOGIN_WHILE_LOCKED_OUT_MESSAGE, - USER_PASSWORD_CHANGED_MESSAGE, -) + from audit.models import AuditLog from audit.related_object_type import RelatedObjectType from audit.serializers import AuditLogListSerializer from audit.services import get_audited_instance_from_audit_log_record -from audit.types import AxesLoginRequest -from custom_auth.signals import ( - user_2fa_disabled, - user_2fa_enabled, - user_login_2fa_code_rejected, - user_login_2fa_code_verified, - user_login_password_rejected, - user_login_password_verified, - user_login_sso_completed, - user_password_changed, -) from features.models import FeatureState, FeatureStateValue from features.multivariate.models import MultivariateFeatureStateValue from features.signals import feature_state_change_went_live @@ -53,10 +20,7 @@ from integrations.sentry.change_tracking import SentryChangeTracking from integrations.sentry.models import SentryChangeTrackingConfiguration from integrations.slack.slack import SlackWrapper -from oauth2_metadata.signals import oauth_session_revoked from organisations.models import OrganisationWebhook -from users.auth_type import AuthType -from users.models import FFAdminUser from webhooks.tasks import call_organisation_webhooks from webhooks.webhooks import WebhookEventType @@ -267,152 +231,6 @@ def send_feature_flag_went_live_signal(sender, instance, **kwargs): # type: ign feature_state_change_went_live.send(feature_state) -def _create_user_audit_logs(user: FFAdminUser, log: str) -> None: - # We don't bulk_create because we need the post_save signal triggered - for organisation in user.organisations.all(): - AuditLog.objects.create(organisation=organisation, author=user, log=log) - - -@receiver(user_login_password_verified) -def create_user_login_password_verified_audit_logs( - sender: type[FFAdminUser], - user: FFAdminUser, - is_2fa_required: bool, - **kwargs: Any, -) -> None: - message = ( - USER_LOGIN_REQUIRES_2FA_MESSAGE - if is_2fa_required - else USER_LOGGED_IN_WITHOUT_2FA_MESSAGE - ) - _create_user_audit_logs(user, message % user.email) - - -@receiver(user_login_password_rejected) -def create_user_login_password_rejected_audit_logs( - sender: type[FFAdminUser], - user: FFAdminUser, - **kwargs: Any, -) -> None: - _create_user_audit_logs(user, USER_LOGIN_PASSWORD_REJECTED_MESSAGE % user.email) - - -@receiver(user_login_2fa_code_verified) -def create_user_login_2fa_code_verified_audit_logs( - sender: type[FFAdminUser], - user: FFAdminUser, - **kwargs: Any, -) -> None: - _create_user_audit_logs(user, USER_LOGGED_IN_WITH_2FA_MESSAGE % user.email) - - -@receiver(user_login_2fa_code_rejected) -def create_user_login_2fa_code_rejected_audit_logs( - sender: type[FFAdminUser], - user: FFAdminUser, - **kwargs: Any, -) -> None: - _create_user_audit_logs(user, USER_LOGIN_2FA_CODE_REJECTED_MESSAGE % user.email) - - -@receiver(user_locked_out) -def create_user_locked_out_audit_logs( - sender: str, - request: AxesLoginRequest, - username: str, - **kwargs: Any, -) -> None: - if not (user := FFAdminUser.objects.filter(email__iexact=username).first()): - return - message = ( - USER_LOGIN_WHILE_LOCKED_OUT_MESSAGE - if request.axes_failures_since_start > settings.AXES_FAILURE_LIMIT - else USER_LOCKED_OUT_MESSAGE - ) - _create_user_audit_logs(user, message % user.email) - - -@receiver(user_login_sso_completed) -def create_user_login_sso_completed_audit_logs( - sender: type[FFAdminUser], - user: FFAdminUser, - auth_type: AuthType, - **kwargs: Any, -) -> None: - provider_name = SSO_PROVIDER_NAMES[auth_type] - _create_user_audit_logs( - user, USER_LOGGED_IN_WITH_SSO_MESSAGE % (user.email, provider_name) - ) - - -@receiver(app_authorized) -def create_user_oauth_login_audit_logs( - sender: object, - request: HttpRequest, - token: AccessToken, - **kwargs: Any, -) -> None: - if request.POST.get("grant_type") != "authorization_code": - return # pragma: no cover - user: FFAdminUser = token.user - _create_user_audit_logs( - user, - USER_LOGGED_IN_TO_OAUTH_APPLICATION_MESSAGE - % (user.email, token.application.name), - ) - - -@receiver(oauth_session_revoked) -def create_user_oauth_logout_audit_logs( - sender: object, - user: FFAdminUser, - application: Application, - **kwargs: Any, -) -> None: - _create_user_audit_logs( - user, - USER_LOGGED_OUT_OF_OAUTH_APPLICATION_MESSAGE % (user.email, application.name), - ) - - -@receiver(user_2fa_enabled) -def create_user_2fa_enabled_audit_logs( - sender: type[FFAdminUser], - user: FFAdminUser, - **kwargs: Any, -) -> None: - _create_user_audit_logs(user, USER_2FA_ENABLED_MESSAGE % user.email) - - -@receiver(user_2fa_disabled) -def create_user_2fa_disabled_audit_logs( - sender: type[FFAdminUser], - user: FFAdminUser, - **kwargs: Any, -) -> None: - _create_user_audit_logs(user, USER_2FA_DISABLED_MESSAGE % user.email) - - -@receiver(user_logged_out) -def create_user_logged_out_audit_logs( - sender: type[FFAdminUser], - user: FFAdminUser | None, - **kwargs: Any, -) -> None: - if user is None: - return - _create_user_audit_logs(user, USER_LOGGED_OUT_MESSAGE % user.email) - - -@receiver(user_password_changed) -def create_user_password_changed_audit_logs( - sender: type[FFAdminUser], - user: FFAdminUser, - **kwargs: Any, -) -> None: - _create_user_audit_logs(user, USER_PASSWORD_CHANGED_MESSAGE % user.email) - - @receiver(feature_state_change_went_live) def send_audit_log_event_to_sentry(sender: FeatureState, **kwargs: Any) -> None: config = SentryChangeTrackingConfiguration.objects.filter( diff --git a/api/audit/signals/authentication.py b/api/audit/signals/authentication.py new file mode 100644 index 000000000000..a4ff80801af0 --- /dev/null +++ b/api/audit/signals/authentication.py @@ -0,0 +1,188 @@ +from typing import Any + +from axes.signals import user_locked_out # type: ignore[import-untyped] +from django.conf import settings +from django.contrib.auth.signals import user_logged_out +from django.dispatch import receiver +from django.http import HttpRequest +from oauth2_provider.models import AccessToken, Application +from oauth2_provider.signals import app_authorized + +from audit.constants import ( + SSO_PROVIDER_NAMES, + USER_2FA_DISABLED_MESSAGE, + USER_2FA_ENABLED_MESSAGE, + USER_LOCKED_OUT_MESSAGE, + USER_LOGGED_IN_TO_OAUTH_APPLICATION_MESSAGE, + USER_LOGGED_IN_WITH_2FA_MESSAGE, + USER_LOGGED_IN_WITH_SSO_MESSAGE, + USER_LOGGED_IN_WITHOUT_2FA_MESSAGE, + USER_LOGGED_OUT_MESSAGE, + USER_LOGGED_OUT_OF_OAUTH_APPLICATION_MESSAGE, + USER_LOGIN_2FA_CODE_REJECTED_MESSAGE, + USER_LOGIN_PASSWORD_REJECTED_MESSAGE, + USER_LOGIN_REQUIRES_2FA_MESSAGE, + USER_LOGIN_WHILE_LOCKED_OUT_MESSAGE, + USER_PASSWORD_CHANGED_MESSAGE, +) +from audit.models import AuditLog +from audit.types import AxesLoginRequest +from custom_auth.signals import ( + user_2fa_disabled, + user_2fa_enabled, + user_login_2fa_code_rejected, + user_login_2fa_code_verified, + user_login_password_rejected, + user_login_password_verified, + user_login_sso_completed, + user_password_changed, +) +from oauth2_metadata.signals import oauth_session_revoked +from users.auth_type import AuthType +from users.models import FFAdminUser + + +def _create_user_audit_logs(user: FFAdminUser, log: str) -> None: + # We don't bulk_create because we need the post_save signal triggered + for organisation in user.organisations.all(): + AuditLog.objects.create(organisation=organisation, author=user, log=log) + + +@receiver(user_login_password_verified) +def create_user_login_password_verified_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + is_2fa_required: bool, + **kwargs: Any, +) -> None: + message = ( + USER_LOGIN_REQUIRES_2FA_MESSAGE + if is_2fa_required + else USER_LOGGED_IN_WITHOUT_2FA_MESSAGE + ) + _create_user_audit_logs(user, message % user.email) + + +@receiver(user_login_password_rejected) +def create_user_login_password_rejected_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + _create_user_audit_logs(user, USER_LOGIN_PASSWORD_REJECTED_MESSAGE % user.email) + + +@receiver(user_login_2fa_code_verified) +def create_user_login_2fa_code_verified_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + _create_user_audit_logs(user, USER_LOGGED_IN_WITH_2FA_MESSAGE % user.email) + + +@receiver(user_login_2fa_code_rejected) +def create_user_login_2fa_code_rejected_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + _create_user_audit_logs(user, USER_LOGIN_2FA_CODE_REJECTED_MESSAGE % user.email) + + +@receiver(user_locked_out) +def create_user_locked_out_audit_logs( + sender: str, + request: AxesLoginRequest, + username: str, + **kwargs: Any, +) -> None: + if not (user := FFAdminUser.objects.filter(email__iexact=username).first()): + return + message = ( + USER_LOGIN_WHILE_LOCKED_OUT_MESSAGE + if request.axes_failures_since_start > settings.AXES_FAILURE_LIMIT + else USER_LOCKED_OUT_MESSAGE + ) + _create_user_audit_logs(user, message % user.email) + + +@receiver(user_login_sso_completed) +def create_user_login_sso_completed_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + auth_type: AuthType, + **kwargs: Any, +) -> None: + provider_name = SSO_PROVIDER_NAMES[auth_type] + _create_user_audit_logs( + user, USER_LOGGED_IN_WITH_SSO_MESSAGE % (user.email, provider_name) + ) + + +@receiver(app_authorized) +def create_user_oauth_login_audit_logs( + sender: object, + request: HttpRequest, + token: AccessToken, + **kwargs: Any, +) -> None: + if request.POST.get("grant_type") != "authorization_code": + return # pragma: no cover + user: FFAdminUser = token.user + _create_user_audit_logs( + user, + USER_LOGGED_IN_TO_OAUTH_APPLICATION_MESSAGE + % (user.email, token.application.name), + ) + + +@receiver(oauth_session_revoked) +def create_user_oauth_logout_audit_logs( + sender: object, + user: FFAdminUser, + application: Application, + **kwargs: Any, +) -> None: + _create_user_audit_logs( + user, + USER_LOGGED_OUT_OF_OAUTH_APPLICATION_MESSAGE % (user.email, application.name), + ) + + +@receiver(user_2fa_enabled) +def create_user_2fa_enabled_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + _create_user_audit_logs(user, USER_2FA_ENABLED_MESSAGE % user.email) + + +@receiver(user_2fa_disabled) +def create_user_2fa_disabled_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + _create_user_audit_logs(user, USER_2FA_DISABLED_MESSAGE % user.email) + + +@receiver(user_logged_out) +def create_user_logged_out_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser | None, + **kwargs: Any, +) -> None: + if user is None: + return + _create_user_audit_logs(user, USER_LOGGED_OUT_MESSAGE % user.email) + + +@receiver(user_password_changed) +def create_user_password_changed_audit_logs( + sender: type[FFAdminUser], + user: FFAdminUser, + **kwargs: Any, +) -> None: + _create_user_audit_logs(user, USER_PASSWORD_CHANGED_MESSAGE % user.email) diff --git a/api/tests/unit/audit/test_unit_audit_signals.py b/api/tests/unit/audit/test_unit_audit_signals.py index f79a1fedbec7..16030488aa22 100644 --- a/api/tests/unit/audit/test_unit_audit_signals.py +++ b/api/tests/unit/audit/test_unit_audit_signals.py @@ -11,12 +11,12 @@ from audit.related_object_type import RelatedObjectType from audit.signals import ( call_webhooks, - create_user_logged_out_audit_logs, send_audit_log_event_to_dynatrace, send_audit_log_event_to_grafana, send_feature_flag_went_live_signal, trigger_feature_state_change_webhooks, ) +from audit.signals.authentication import create_user_logged_out_audit_logs from environments.models import Environment from features.models import Feature, FeatureState from features.versioning.models import EnvironmentFeatureVersion From c9ec50ac27e770290d9eda1d2c268ec04400f789 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:09:49 +0000 Subject: [PATCH 34/41] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- api/custom_auth/serializers.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/api/custom_auth/serializers.py b/api/custom_auth/serializers.py index eb5be064bc8e..5b71d09e0dbb 100644 --- a/api/custom_auth/serializers.py +++ b/api/custom_auth/serializers.py @@ -35,7 +35,6 @@ class Meta: class CustomTokenCreateSerializer(TokenCreateSerializer): # type: ignore[misc] - def validate(self, attrs: dict[str, Any]) -> dict[str, Any]: """Validate credentials input. @@ -48,7 +47,9 @@ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]: user = FFAdminUser.objects.filter(email__iexact=email).first() if not user: raise - if not (password := attrs.get("password")) or not user.check_password(password): + if not (password := attrs.get("password")) or not user.check_password( + password + ): user_login_password_rejected.send(sender=user.__class__, user=user) raise if not user.is_active: From 84174c541907a143fb98d51b02dfbaa9c8274152 Mon Sep 17 00:00:00 2001 From: "flagsmith-engineering[bot]" Date: Mon, 16 Nov 2026 23:15:57 +0000 Subject: [PATCH 35/41] chore: Update documentation artefacts --- .../observability/_events-catalogue.md | 2 +- openapi.yaml | 9 +++------ 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/docs/docs/deployment-self-hosting/observability/_events-catalogue.md b/docs/docs/deployment-self-hosting/observability/_events-catalogue.md index c6086f9aec22..b4c02ac862d6 100644 --- a/docs/docs/deployment-self-hosting/observability/_events-catalogue.md +++ b/docs/docs/deployment-self-hosting/observability/_events-catalogue.md @@ -641,7 +641,7 @@ Attributes: ### `oauth2_metadata.registration.rejected` Logged at `error` from: - - `api/oauth2_metadata/views.py:171` + - `api/oauth2_metadata/views.py:174` Attributes: - `client.name` diff --git a/openapi.yaml b/openapi.yaml index 82298c729991..b2ca9cd8e1e5 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -1394,6 +1394,7 @@ paths: /api/v1/auth/users/reset_password/: post: operationId: api_v1_auth_users_reset_password_create + description: Request a password reset email requestBody: required: true content: @@ -1422,6 +1423,7 @@ paths: /api/v1/auth/users/reset_password_confirm/: post: operationId: api_v1_auth_users_reset_password_confirm_create + description: Update the user password from a password reset URL requestBody: required: true content: @@ -1477,6 +1479,7 @@ paths: /api/v1/auth/users/set_password/: post: operationId: api_v1_auth_users_set_password_create + description: Update the user password requestBody: required: true content: @@ -20577,12 +20580,6 @@ components: required: - feature_state_value CustomTokenCreate: - description: |- - Tells a user with correct credentials that their account is not yet - activated, instead of the generic invalid credentials error. - - The password is verified first, so an address cannot be probed for its - activation state by anyone who does not already know the password. type: object properties: password: From cf2c835487c8908e70749ace1759bee2bd126651 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 17 Nov 2026 11:47:39 -0300 Subject: [PATCH 36/41] ldap --- api/audit/signals/authentication.py | 4 +- api/custom_auth/serializers.py | 11 ++-- api/tests/conftest.py | 13 +++++ .../audit/events/test_authentication_logs.py | 50 +++++++++++++++++++ .../test_unit_custom_auth_serializer.py | 14 ------ api/users/models.py | 10 ++-- 6 files changed, 79 insertions(+), 23 deletions(-) diff --git a/api/audit/signals/authentication.py b/api/audit/signals/authentication.py index a4ff80801af0..dbb4b1601c50 100644 --- a/api/audit/signals/authentication.py +++ b/api/audit/signals/authentication.py @@ -97,7 +97,9 @@ def create_user_locked_out_audit_logs( username: str, **kwargs: Any, ) -> None: - if not (user := FFAdminUser.objects.filter(email__iexact=username).first()): + try: + user = FFAdminUser.objects.get_by_natural_key(username) + except FFAdminUser.DoesNotExist: return message = ( USER_LOGIN_WHILE_LOCKED_OUT_MESSAGE diff --git a/api/custom_auth/serializers.py b/api/custom_auth/serializers.py index 5b71d09e0dbb..a63ca3478898 100644 --- a/api/custom_auth/serializers.py +++ b/api/custom_auth/serializers.py @@ -41,12 +41,13 @@ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]: Overrides djoser so that activation state can't be probed without a valid password.""" try: return super().validate(attrs) # type: ignore[no-any-return] - except ValidationError: - if not (email := attrs.get(djoser_settings.LOGIN_FIELD)): - raise - user = FFAdminUser.objects.filter(email__iexact=email).first() - if not user: + except ValidationError as error: + if not (username := attrs.get(djoser_settings.LOGIN_FIELD)): raise + try: + user = FFAdminUser.objects.get_by_natural_key(username) + except FFAdminUser.DoesNotExist: + raise error from None if not (password := attrs.get("password")) or not user.check_password( password ): diff --git a/api/tests/conftest.py b/api/tests/conftest.py index cfc3f05a3f42..c4daf9df4d1d 100644 --- a/api/tests/conftest.py +++ b/api/tests/conftest.py @@ -282,6 +282,19 @@ def staff_user(django_user_model): # type: ignore[no-untyped-def] return django_user_model.objects.create(email="staff@example.com") +@pytest.fixture() +def django_ldap_username_field( + django_user_model: type[FFAdminUser], + monkeypatch: pytest.MonkeyPatch, + settings: SettingsWrapper, +) -> str: + """Mirror `LDAP_ENABLED`, where users log in with their LDAP username.""" + ldap_username_field = "username" + monkeypatch.setattr(django_user_model, "USERNAME_FIELD", ldap_username_field) + settings.AXES_USERNAME_FORM_FIELD = ldap_username_field + return ldap_username_field + + @pytest.fixture() def staff_client(staff_user): # type: ignore[no-untyped-def] client = APIClient() diff --git a/api/tests/integration/audit/events/test_authentication_logs.py b/api/tests/integration/audit/events/test_authentication_logs.py index cb2eb708a8e3..b19b76a9c5b1 100644 --- a/api/tests/integration/audit/events/test_authentication_logs.py +++ b/api/tests/integration/audit/events/test_authentication_logs.py @@ -525,6 +525,56 @@ def test_login__locked_out__creates_audit_log( ] +@pytest.mark.usefixtures("django_ldap_username_field") +def test_login__ldap_user_locked_out__creates_audit_log( + api_client: APIClient, + organisation: Organisation, + other_organisation: Organisation, + settings: SettingsWrapper, + user: FFAdminUser, +) -> None: + # Given + settings.AXES_FAILURE_LIMIT = 1 + user.username = "alice" + user.save() + + # When + response = api_client.post( + "/api/v1/auth/login/", + {"email": "Alice", "password": "incorrect"}, + format="json", + ) + + # Then + assert response.status_code == 400 + assert list( + AuditLog.objects.order_by("organisation_id", "created_date").values( + "organisation_id", "author_id", "log" + ) + ) == [ + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` was locked out after too many failed logins.", + }, + { + "organisation_id": organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` failed to log in: incorrect password.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` was locked out after too many failed logins.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` failed to log in: incorrect password.", + }, + ] + + def test_login__attempt_while_locked_out__creates_audit_log( api_client: APIClient, organisation: Organisation, diff --git a/api/tests/unit/custom_auth/test_unit_custom_auth_serializer.py b/api/tests/unit/custom_auth/test_unit_custom_auth_serializer.py index 24f6935f3ed4..0f417336c7bd 100644 --- a/api/tests/unit/custom_auth/test_unit_custom_auth_serializer.py +++ b/api/tests/unit/custom_auth/test_unit_custom_auth_serializer.py @@ -1,7 +1,4 @@ -import typing - import pytest -from django.contrib.auth.models import AbstractUser from django.test import RequestFactory from djoser.serializers import TokenCreateSerializer # type: ignore[import-untyped] from pytest_django.fixtures import SettingsWrapper @@ -174,17 +171,6 @@ def test_invite_link_validation__invalid_hash__raises_permission_denied( assert exc_info.value.detail == USER_REGISTRATION_WITHOUT_INVITE_ERROR_MESSAGE -@pytest.fixture -def django_ldap_username_field( - django_user_model: type[AbstractUser], -) -> typing.Generator[str, None, None]: - ldap_username_field = "username" - username_field = django_user_model.USERNAME_FIELD - django_user_model.USERNAME_FIELD = ldap_username_field - yield ldap_username_field - django_user_model.USERNAME_FIELD = username_field - - # Previously, Djoser's default `TokenCreateSerializer` only respected the # Djoser `LOGIN_FIELD` setting so it was impossible to grab the email from # serializer and send it as a username to the login backend — which is required for LDAP to work. diff --git a/api/users/models.py b/api/users/models.py index 5af1d830178d..ada0f08b00cb 100644 --- a/api/users/models.py +++ b/api/users/models.py @@ -104,9 +104,13 @@ def create_superuser(self, email, password, **extra_fields): # type: ignore[no- return self._create_user(email, password, **extra_fields) # type: ignore[no-untyped-call] - def get_by_natural_key(self, email): # type: ignore[no-untyped-def] - # Used to allow case insensitive login - return self.get(email__iexact=email) + def get_by_natural_key(self, username: str | None) -> "FFAdminUser": + """Get a user by the identifier they log in with, ignoring case.""" + if username is None: + raise self.model.DoesNotExist # pragma: no cover + username_lookup = f"{self.model.USERNAME_FIELD}__iexact" + user: FFAdminUser = self.get(**{username_lookup: username}) + return user def make_random_password( self, From 5aa8382302330ab670d92ee8da81576dbc5f1ca1 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 17 Nov 2026 12:52:02 -0300 Subject: [PATCH 37/41] prevent field error --- api/pyproject.toml | 2 +- api/uv.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/api/pyproject.toml b/api/pyproject.toml index f2ee6c703c1b..206a211900ca 100644 --- a/api/pyproject.toml +++ b/api/pyproject.toml @@ -82,7 +82,7 @@ dependencies = [ "structlog>=24.4.0,<25.0.0", "prometheus-client>=0.21.1,<0.22.0", "django-cockroachdb>=4.2,<4.3.0", - "django-oauth-toolkit>=3.0.1,<4.0.0", + "django-oauth-toolkit>=3.4.0,<4.0.0", "jsonpath-rfc9535>=0.2.0,<0.3.0", ] diff --git a/api/uv.lock b/api/uv.lock index ebbb7bfefe97..cf34630d91bc 100644 --- a/api/uv.lock +++ b/api/uv.lock @@ -1474,7 +1474,7 @@ requires-dist = [ { name = "django-filter", specifier = ">=2.4.0,<2.5.0" }, { name = "django-health-check", specifier = ">=3.18.2,<3.19.0" }, { name = "django-lifecycle", specifier = ">=1.2.4,<1.2.5" }, - { name = "django-oauth-toolkit", specifier = ">=3.0.1,<4.0.0" }, + { name = "django-oauth-toolkit", specifier = ">=3.4.0,<4.0.0" }, { name = "django-ordered-model", specifier = ">=3.4.1,<3.5.0" }, { name = "django-redis", specifier = ">=5.4.0,<6.0.0" }, { name = "django-ses", specifier = ">=3.5.0,<3.6.0" }, From 8507021603fbdff223bd2d373460f95eff87b441 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 17 Nov 2026 13:22:29 -0300 Subject: [PATCH 38/41] why would anybody revoke a session token --- api/oauth2_metadata/views.py | 9 +++++++-- .../audit/events/test_authentication_logs.py | 13 +++++++++++-- .../observability/_events-catalogue.md | 2 +- 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/api/oauth2_metadata/views.py b/api/oauth2_metadata/views.py index cd42537c2296..5a4dbc0448d5 100644 --- a/api/oauth2_metadata/views.py +++ b/api/oauth2_metadata/views.py @@ -3,6 +3,7 @@ from urllib.parse import urlencode, urlparse, urlunparse import structlog +from django.db.models import Q from django.http import HttpRequest, HttpResponse, JsonResponse, QueryDict from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_GET @@ -240,10 +241,14 @@ def post(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: def _get_session_refresh_token(self, request: HttpRequest) -> RefreshToken | None: """Identify the session to end, as revocation requests carry no user.""" - token: str = request.POST.get("token", "") + token = request.POST.get("token") + if not token: + return None # pragma: no cover + token_checksum = hashlib.sha256(token.encode("utf-8")).hexdigest() refresh_token: RefreshToken | None = ( RefreshToken.objects.filter( - token_checksum=hashlib.sha256(token.encode("utf-8")).hexdigest(), + Q(token_checksum=token_checksum) + | Q(access_token__token_checksum=token_checksum), revoked__isnull=True, ) .select_related("user", "application") diff --git a/api/tests/integration/audit/events/test_authentication_logs.py b/api/tests/integration/audit/events/test_authentication_logs.py index b19b76a9c5b1..05bc7f13a927 100644 --- a/api/tests/integration/audit/events/test_authentication_logs.py +++ b/api/tests/integration/audit/events/test_authentication_logs.py @@ -676,12 +676,21 @@ def test_oauth_login__authorised__creates_audit_log( ] +@pytest.mark.parametrize( + "token, token_type_hint", + [ + ("access-token", "access_token"), + ("refresh-token", "refresh_token"), + ], +) def test_oauth_logout__token_revoked__creates_audit_log( api_client: APIClient, oauth_application: Application, organisation: Organisation, other_organisation: Organisation, user: FFAdminUser, + token: str, + token_type_hint: str, ) -> None: # Given RefreshToken.objects.create( @@ -700,8 +709,8 @@ def test_oauth_logout__token_revoked__creates_audit_log( response = api_client.post( "/o/revoke_token/", { - "token": "refresh-token", - "token_type_hint": "refresh_token", + "token": token, + "token_type_hint": token_type_hint, "client_id": oauth_application.client_id, }, ) diff --git a/docs/docs/deployment-self-hosting/observability/_events-catalogue.md b/docs/docs/deployment-self-hosting/observability/_events-catalogue.md index 693ff1a317a2..3a2cd944daea 100644 --- a/docs/docs/deployment-self-hosting/observability/_events-catalogue.md +++ b/docs/docs/deployment-self-hosting/observability/_events-catalogue.md @@ -737,7 +737,7 @@ Attributes: ### `oauth2_metadata.registration.rejected` Logged at `error` from: - - `api/oauth2_metadata/views.py:174` + - `api/oauth2_metadata/views.py:175` Attributes: - `client.name` From 2410ac76c72a2e1b85fc0105e2a2b602fd4244a6 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 17 Nov 2026 13:53:01 -0300 Subject: [PATCH 39/41] move to flagsmith-private --- api/tests/conftest.py | 13 ----- .../audit/events/test_authentication_logs.py | 50 ------------------- .../test_unit_custom_auth_serializer.py | 14 ++++++ 3 files changed, 14 insertions(+), 63 deletions(-) diff --git a/api/tests/conftest.py b/api/tests/conftest.py index c4daf9df4d1d..cfc3f05a3f42 100644 --- a/api/tests/conftest.py +++ b/api/tests/conftest.py @@ -282,19 +282,6 @@ def staff_user(django_user_model): # type: ignore[no-untyped-def] return django_user_model.objects.create(email="staff@example.com") -@pytest.fixture() -def django_ldap_username_field( - django_user_model: type[FFAdminUser], - monkeypatch: pytest.MonkeyPatch, - settings: SettingsWrapper, -) -> str: - """Mirror `LDAP_ENABLED`, where users log in with their LDAP username.""" - ldap_username_field = "username" - monkeypatch.setattr(django_user_model, "USERNAME_FIELD", ldap_username_field) - settings.AXES_USERNAME_FORM_FIELD = ldap_username_field - return ldap_username_field - - @pytest.fixture() def staff_client(staff_user): # type: ignore[no-untyped-def] client = APIClient() diff --git a/api/tests/integration/audit/events/test_authentication_logs.py b/api/tests/integration/audit/events/test_authentication_logs.py index 05bc7f13a927..8a433883664a 100644 --- a/api/tests/integration/audit/events/test_authentication_logs.py +++ b/api/tests/integration/audit/events/test_authentication_logs.py @@ -525,56 +525,6 @@ def test_login__locked_out__creates_audit_log( ] -@pytest.mark.usefixtures("django_ldap_username_field") -def test_login__ldap_user_locked_out__creates_audit_log( - api_client: APIClient, - organisation: Organisation, - other_organisation: Organisation, - settings: SettingsWrapper, - user: FFAdminUser, -) -> None: - # Given - settings.AXES_FAILURE_LIMIT = 1 - user.username = "alice" - user.save() - - # When - response = api_client.post( - "/api/v1/auth/login/", - {"email": "Alice", "password": "incorrect"}, - format="json", - ) - - # Then - assert response.status_code == 400 - assert list( - AuditLog.objects.order_by("organisation_id", "created_date").values( - "organisation_id", "author_id", "log" - ) - ) == [ - { - "organisation_id": organisation.id, - "author_id": user.id, - "log": "User `alice@example.com` was locked out after too many failed logins.", - }, - { - "organisation_id": organisation.id, - "author_id": user.id, - "log": "User `alice@example.com` failed to log in: incorrect password.", - }, - { - "organisation_id": other_organisation.id, - "author_id": user.id, - "log": "User `alice@example.com` was locked out after too many failed logins.", - }, - { - "organisation_id": other_organisation.id, - "author_id": user.id, - "log": "User `alice@example.com` failed to log in: incorrect password.", - }, - ] - - def test_login__attempt_while_locked_out__creates_audit_log( api_client: APIClient, organisation: Organisation, diff --git a/api/tests/unit/custom_auth/test_unit_custom_auth_serializer.py b/api/tests/unit/custom_auth/test_unit_custom_auth_serializer.py index 0f417336c7bd..24f6935f3ed4 100644 --- a/api/tests/unit/custom_auth/test_unit_custom_auth_serializer.py +++ b/api/tests/unit/custom_auth/test_unit_custom_auth_serializer.py @@ -1,4 +1,7 @@ +import typing + import pytest +from django.contrib.auth.models import AbstractUser from django.test import RequestFactory from djoser.serializers import TokenCreateSerializer # type: ignore[import-untyped] from pytest_django.fixtures import SettingsWrapper @@ -171,6 +174,17 @@ def test_invite_link_validation__invalid_hash__raises_permission_denied( assert exc_info.value.detail == USER_REGISTRATION_WITHOUT_INVITE_ERROR_MESSAGE +@pytest.fixture +def django_ldap_username_field( + django_user_model: type[AbstractUser], +) -> typing.Generator[str, None, None]: + ldap_username_field = "username" + username_field = django_user_model.USERNAME_FIELD + django_user_model.USERNAME_FIELD = ldap_username_field + yield ldap_username_field + django_user_model.USERNAME_FIELD = username_field + + # Previously, Djoser's default `TokenCreateSerializer` only respected the # Djoser `LOGIN_FIELD` setting so it was impossible to grab the email from # serializer and send it as a username to the login backend — which is required for LDAP to work. From 36f2d2948b8c24d9e81f0f25461f9b59faa4962f Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 17 Nov 2026 13:55:53 -0300 Subject: [PATCH 40/41] fix coverage --- api/custom_auth/serializers.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/custom_auth/serializers.py b/api/custom_auth/serializers.py index a63ca3478898..bb638eb0f12a 100644 --- a/api/custom_auth/serializers.py +++ b/api/custom_auth/serializers.py @@ -43,7 +43,7 @@ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]: return super().validate(attrs) # type: ignore[no-any-return] except ValidationError as error: if not (username := attrs.get(djoser_settings.LOGIN_FIELD)): - raise + raise # pragma: no cover try: user = FFAdminUser.objects.get_by_natural_key(username) except FFAdminUser.DoesNotExist: From 17cccbc7c77f8017fe9e7e5bed73a078807f0564 Mon Sep 17 00:00:00 2001 From: Evandro Myller Date: Tue, 17 Nov 2026 14:15:18 -0300 Subject: [PATCH 41/41] more, mOArrrr --- .../governance-and-compliance/audit-logs.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md b/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md index eb59a23cf24b..d9f18f99fa25 100644 --- a/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md +++ b/docs/docs/administration-and-security/governance-and-compliance/audit-logs.md @@ -118,7 +118,11 @@ These events are recorded in every organisation the user belongs to. - User entered their password, pending 2FA - User logged in with 2FA - User failed to log in due to an incorrect password or 2FA code +- User was locked out after too many failed login attempts +- User attempted to log in while locked out - User logged in with SSO - User logged out +- User logged in to an OAuth application +- User logged out of an OAuth application - User changed their password - User enabled or disabled 2FA