Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
7b5ee28
audit logs finally _organised_
emyller Nov 6, 2026
d00efb9
first, red
emyller Nov 9, 2026
f84b187
Merge remote-tracking branch 'github/main' into feat/org-level-audit-…
emyller Nov 9, 2026
5e649af
`select_related` needs a foreign key
emyller Nov 9, 2026
d91ac03
tests go happy
emyller Nov 9, 2026
2b63d2f
fix `is_system_event` filter 😬
emyller Nov 9, 2026
591595e
also in ALL logs
emyller Nov 9, 2026
f0156eb
all paths covered
emyller Nov 9, 2026
e56f943
tighten up org logs in the all view
emyller Nov 10, 2026
0b47b94
chore: Update documentation artefacts
flagsmith-engineering[bot] Nov 10, 2026
a142bac
404
emyller Nov 10, 2026
c1ccfd6
accurate api spec
emyller Nov 10, 2026
41fee7b
split migrations
emyller Nov 10, 2026
e144ed7
chore: Update documentation artefacts
flagsmith-engineering[bot] Nov 10, 2026
d711624
tdd parkour
emyller Nov 10, 2026
3f1b1cf
docs
emyller Nov 10, 2026
bfafb82
logout audit log
emyller Nov 10, 2026
d8f26c8
better index management
emyller Nov 11, 2026
edd4e62
looks good and reads nice
emyller Nov 11, 2026
7a05088
Merge remote-tracking branch 'github/main' into feat/org-level-audit-…
emyller Nov 11, 2026
765fad9
chore: Update documentation artefacts
flagsmith-engineering[bot] Nov 11, 2026
090696c
Merge remote-tracking branch 'github/feat/org-level-audit-logs-pt1' i…
emyller Nov 11, 2026
6600f2d
password change
emyller Nov 11, 2026
640fbde
Merge remote-tracking branch 'github/main' into feat/auth-audit-logs
emyller Nov 13, 2026
0c740b9
fix test module name
emyller Nov 13, 2026
af53f26
login audit logs
emyller Nov 13, 2026
d4d26b2
2fa toggle audit logs
emyller Nov 13, 2026
f280735
better name + saml
emyller Nov 13, 2026
076a51d
audit log when resetting a password
emyller Nov 16, 2026
a84cfba
for the sake of clarity
emyller Nov 16, 2026
eebf059
refactor
emyller Nov 16, 2026
c07ee81
improve events doc
emyller Nov 16, 2026
284a40c
locked out
emyller Nov 16, 2026
756750d
it doesnt work if you retry
emyller Nov 16, 2026
c79ea8a
oauth login
emyller Nov 16, 2026
b0c99b6
oauth logout
emyller Nov 16, 2026
eb13eeb
move out
emyller Nov 16, 2026
c9ec50a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Nov 16, 2026
84174c5
chore: Update documentation artefacts
flagsmith-engineering[bot] Nov 16, 2026
babcf47
Merge remote-tracking branch 'github/main' into feat/auth-audit-logs
emyller Nov 17, 2026
cf2c835
ldap
emyller Nov 17, 2026
5aa8382
prevent field error
emyller Nov 17, 2026
8507021
why would anybody revoke a session token
emyller Nov 17, 2026
2410ac7
move to flagsmith-private
emyller Nov 17, 2026
36f2d29
fix coverage
emyller Nov 17, 2026
17cccbc
more, mOArrrr
emyller Nov 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion api/app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from oauth2_metadata.views import (
DynamicClientRegistrationView,
OAuthAuthorizeView,
OAuthRevokeTokenView,
authorization_server_metadata,
)
from users.views import password_reset_redirect
Expand Down Expand Up @@ -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(
Expand Down
1 change: 1 addition & 0 deletions api/audit/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ class AuditConfig(AppConfig):

def ready(self): # type: ignore[no-untyped-def]
from . import signals # noqa
from .signals import authentication # noqa
22 changes: 22 additions & 0 deletions api/audit/constants.py
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -90,3 +92,23 @@
FEATURE_DEPENDENCY_DELETED_MESSAGE = (
"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_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",
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."
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."
USER_PASSWORD_CHANGED_MESSAGE = "User `%s` changed their password."
File renamed without changes.
190 changes: 190 additions & 0 deletions api/audit/signals/authentication.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
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:
try:
user = FFAdminUser.objects.get_by_natural_key(username)
except FFAdminUser.DoesNotExist:
return
message = (
USER_LOGIN_WHILE_LOCKED_OUT_MESSAGE
if request.axes_failures_since_start > settings.AXES_FAILURE_LIMIT
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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)
6 changes: 5 additions & 1 deletion api/audit/types.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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
3 changes: 3 additions & 0 deletions api/custom_auth/mfa/trench/views/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]

Expand Down Expand Up @@ -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})


Expand All @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions api/custom_auth/oauth/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from rest_framework import serializers
from rest_framework.authtoken.models import Token

from custom_auth.signals import user_login_sso_completed
from integrations.lead_tracking.hubspot.services import (
register_hubspot_tracker_and_track_user,
)
Expand Down Expand Up @@ -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_sso_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]
Expand Down
42 changes: 20 additions & 22 deletions api/custom_auth/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -34,33 +35,30 @@ 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._raise_if_awaiting_activation(attrs)
except ValidationError as error:
if not (username := attrs.get(djoser_settings.LOGIN_FIELD)):
raise # pragma: no cover
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
):
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 _raise_if_awaiting_activation(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 "")
):
raise ValidationError(
{EMAIL_NOT_VERIFIED_ERROR_KEY: [EMAIL_NOT_VERIFIED_ERROR]}
)


class InviteLinkValidationMixin:
invite_hash = serializers.CharField(required=False, write_only=True)
Expand Down
Loading
Loading