Skip to content

feat(Audit logs): Emit authentication audit logs - #8931

Open
emyller wants to merge 39 commits into
mainfrom
feat/auth-audit-logs
Open

emyller wants to merge 39 commits into
mainfrom
feat/auth-audit-logs

Conversation

@emyller

@emyller emyller commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for submitting a PR! Please check the boxes below:

  • I have read the Contributing Guide.
  • I have added information to docs/ if required so people know about the feature.
  • I have filled in the "Changes" section below.
  • I have filled in the "How did you test this code" section below.

Changes

Closes #7569

Introduces audit logging for authentication events.

We expand further from the original scope, and also add audit logs for:

  • Getting locked out
  • Attempting to authenticate while locked out
  • Login via OAuth — e.g. MCP, CLI
  • Logout via OAuth — i.e. revoke a token

Review effort: 4/5

How did you test this code?

Functional tests.

@emyller emyller self-assigned this Nov 10, 2026
@vercel

vercel Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
docs Ready Ready Preview Nov 16, 2026 11:16pm UTC
2 Skipped Deployments
Project Deployment Actions Updated
flagsmith-frontend-preview Ignored Ignored Preview Nov 16, 2026 11:16pm UTC
flagsmith-frontend-staging Ignored Ignored Preview Nov 16, 2026 11:16pm UTC

Request Review

@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The change adds authentication audit events for password and 2FA outcomes, SSO, OAuth application login and logout, account lockouts, user logout, password changes, and 2FA setting changes. Receivers create audit records for each organisation associated with a user. Authentication workflows emit the corresponding signals. OAuth token revocation uses a custom view that emits a signal after confirming that a refresh token was revoked. Integration tests and audit-log documentation cover the events.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Merge Risk: Moderate · up to 84174

Authentication audit logging is mostly in place. Several gaps remain: lockout and incorrect-password events can be missed for LDAP username logins, access-token revocation records no logout, and a null failure count in the lockout receiver can raise an error. The declared OAuth toolkit minimum also admits a version that would break token revocation. These should be addressed or explicitly accepted before merging.

- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 5ffc355e-41e3-48c9-97c0-6fc0ceae3c92
Commits

Reviewing files that changed from the base of the PR and between c9ec50a and 84174c5.

Files selected for processing: 2

  • docs/docs/deployment-self-hosting/observability/_events-catalogue.md
  • openapi.yaml

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

@emyller
emyller changed the base branch from main to feat/org-level-audit-logs-pt1 November 10, 2026 20:44
@github-actions github-actions Bot added api Issue related to the REST API feature New feature or request labels Nov 10, 2026
@github-actions github-actions Bot added docs Documentation updates feature New feature or request and removed feature New feature or request docs Documentation updates labels Nov 10, 2026
@github-actions github-actions Bot added feature New feature or request and removed feature New feature or request docs Documentation updates labels Nov 16, 2026
@flagsmith-engineering
flagsmith-engineering Bot requested a review from a team as a code owner November 16, 2026 19:57
@flagsmith-engineering
flagsmith-engineering Bot requested review from gagantrivedi and removed request for a team November 16, 2026 19:57
@github-actions github-actions Bot added the docs Documentation updates label Nov 16, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 3 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 2 unresolved issues from previous reviews.

Turn on auto-fix | Re-trigger cubic

@emyller
emyller force-pushed the feat/auth-audit-logs branch from 3a87c78 to eb13eeb Compare November 16, 2026 23:09
@github-actions github-actions Bot added feature New feature or request and removed feature New feature or request docs Documentation updates labels Nov 16, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 1 file (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 2 unresolved issues from previous reviews.

Turn on auto-fix | Re-trigger cubic

@emyller

emyller commented Nov 16, 2026

Copy link
Copy Markdown
Contributor Author
  • The axes lockouts, and login attempts under lockout, are not logged. Should they?

It's a bit of scope explosion, but I don't mind: 284a40c + 756750d.

  • Users with no org leave no trace anywhere. Should they?

No. The interested party in seeing organisation audit logs is an organisation.

  • CLI and MCP logins aren't logged at all. Neither flagsmith login, the MCP OAuth consent and token exchange, flagsmith logout, nor revoking a token creates a log.

I've added c79ea8a and b0c99b6 which should cover authentication via OAuth.

Thanks!

@emyller
emyller requested a review from khvn26 November 16, 2026 23:14

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 2 unresolved issues from previous reviews.

Turn on auto-fix | Re-trigger cubic

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 27f6fdf3-9ad8-409b-8465-946ae7911d4e
Commits

Reviewing files that changed from the base of the PR and between 3a87c78 and c9ec50a.

Files selected for processing: 20

  • api/app/urls.py
  • api/audit/apps.py
  • api/audit/constants.py
  • api/audit/signals/__init__.py
  • api/audit/signals/authentication.py
  • api/audit/types.py
  • api/custom_auth/mfa/trench/command/authenticate_second_factor.py
  • api/custom_auth/mfa/trench/views/base.py
  • api/custom_auth/oauth/serializers.py
  • api/custom_auth/serializers.py
  • api/custom_auth/signals.py
  • api/custom_auth/views.py
  • api/oauth2_metadata/signals.py
  • api/oauth2_metadata/views.py
  • api/tests/integration/audit/events/test_authentication_logs.py
  • api/tests/integration/audit/test_project_audit_logs.py
  • api/tests/unit/audit/test_unit_audit_signals.py
  • api/tests/unit/custom_auth/oauth/test_unit_oauth_serializers.py
  • api/users/auth_type.py
  • docs/docs/administration-and-security/governance-and-compliance/audit-logs.md
Files with no reviewable changes: 2

  • api/audit/signals/init.py
  • api/tests/integration/audit/test_project_audit_logs.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

username: str,
**kwargs: Any,
) -> None:
if not (user := FFAdminUser.objects.filter(email__iexact=username).first()):

@coderabbitai coderabbitai Bot Nov 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Data Integrity & Integration · Quick win

Resolve lockout users through the configured login field.

When LDAP is enabled, FFAdminUser.USERNAME_FIELD is username. Axes uses that field by default. For username alice and email alice@example.com, this lookup searches for email alice and returns without creating any lockout audit records. Both lockout event types are lost for this user. (raw.githubusercontent.com)

Resolve the user through the configured login field instead of always using email.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked this, and it seems to be true. custom_auth serializer needs fixing too.

Also, see related comment in flagsmith-private#375.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Analysis chain

Script executed:

#!/bin/bash
for endpoint in \
  "repos/Flagsmith/flagsmith/pulls/comments/4593071179" \
  "repos/Flagsmith/flagsmith-private/pulls/comments/4599053968"
do
  printf '\n--- %s ---\n' "$endpoint"
  gh api "$endpoint" --jq '{html_url, path, line, body, author: .user.login}' || printf 'Could not read this comment.\n'
done

printf '\n--- Relevant code outlines ---\n'
ast-grep outline api/custom_auth/serializers.py --match 'CustomTokenCreateSerializer' --view expanded
ast-grep outline api/audit/signals/authentication.py --match 'create_user_locked_out_audit_logs' --view expanded

printf '\n--- Login-field declarations and settings ---\n'
rg -n -C 3 'USERNAME_FIELD|AXES_USERNAME' api

printf '\n--- Serializer credential lookup ---\n'
rg -n -C 8 'email__iexact|class CustomTokenCreateSerializer|def validate\(' api/custom_auth/serializers.py

printf '\n--- Lockout lookup ---\n'
cat -n api/audit/signals/authentication.py | sed -n '88,110p'

Length of output: 9575


Script executed:

#!/bin/bash
printf '%s\n' '--- Relevant test outline ---'
ast-grep outline api/tests/unit/custom_auth/test_unit_custom_auth_serializer.py --match 'djoser|username' --view expanded
printf '%s\n' '--- Djoser login-field test ---'
cat -n api/tests/unit/custom_auth/test_unit_custom_auth_serializer.py | sed -n '165,250p'
printf '%s\n' '--- Authentication configuration ---'
rg -n -C 4 'LOGIN_FIELD|AXES_USERNAME|AXES_FAILURE|AUTHENTICATION_BACKENDS|LDAP_ENABLED' api -g '*.py'
printf '%s\n' '--- Dependency versions ---'
rg -n -i -C 2 'django-axes|djoser' api -g '*lock*' -g '*toml' -g '*requirements*' -g '*txt' | head -180

Length of output: 17618


@khvn26 The serializer has the same email-only lookup. The LDAP serializer test also shows that the email input can contain a username. Both paths should handle a username that differs from the user’s email.

I could not read the private comment: GitHub returned 404. Could you share its text here? I’m not marking this finding as addressed because no fix has been confirmed.

You are interacting with an AI system.

Comment thread api/audit/signals/authentication.py Resolved
self._raise_if_awaiting_activation(attrs)
if not (email := attrs.get(djoser_settings.LOGIN_FIELD)):
raise
user = FFAdminUser.objects.filter(email__iexact=email).first()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Data Integrity & Integration · Quick win

Use the authentication identity for rejection audits.

When LDAP is enabled, Djoser authenticates the supplied login value through User.USERNAME_FIELD, which is username. For username alice and email alice@example.com, an incorrect password reaches this lookup with alice. The email lookup finds no user, so validation re-raises without sending user_login_password_rejected. The required audit records are missing from every organisation of that user. (raw.githubusercontent.com)

Resolve the user through the configured authentication identity rather than always through email.

Comment thread api/oauth2_metadata/views.py Resolved
Comment on lines +245 to +246
RefreshToken.objects.filter(
token_checksum=hashlib.sha256(token.encode("utf-8")).hexdigest(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Data Integrity & Integration · Quick win

Record logout when an access token revokes its session.

If a client submits an access token, this lookup searches for its checksum among refresh tokens and returns None. The locked django-oauth-toolkit 3.4.1 implementation also revokes the bound refresh token when it revokes that access token. The session ends, but Line 233 suppresses the logout audit record. Resolve the bound refresh token before delegation and cover this input alongside the existing refresh-token test. (raw.githubusercontent.com)

token: str = request.POST.get("token", "")
refresh_token: RefreshToken | None = (
RefreshToken.objects.filter(
token_checksum=hashlib.sha256(token.encode("utf-8")).hexdigest(),

@coderabbitai coderabbitai Bot Nov 16, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Stability & Availability · Quick win

Raise the django-oauth-toolkit minimum to 3.4.0.

The declared range admits 3.0.1. That version's RefreshToken model has no token_checksum field; the field was added in 3.4.0. OAuthRevokeTokenView._get_session_refresh_token filters on that field before the base revocation runs. An installation that resolves 3.0.1 therefore fails every revocation request with a FieldError, and no token is revoked. The lock file pins 3.4.1, but it protects only installations that use it, so the declared minimum must exclude 3.0.1.

Suggested fix

--- a/api/pyproject.toml
+++ b/api/pyproject.toml
@@ -85 +85 @@
-    "django-oauth-toolkit>=3.0.1,<4.0.0",
+    "django-oauth-toolkit>=3.4.0,<4.0.0",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed here.

@khvn26 khvn26 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ready to approve once CR's threads are resolved.

This branch was successfully deployed

3 active (2 outdated) deployments
Preview – docs — 84174c54 Deployed Nov 16, 2026 by vercel[bot]
Preview – flagsmith-frontend-staging — 090696c5 Deployed Nov 11, 2026 by vercel[bot]
Preview – flagsmith-frontend-preview — 090696c5 Deployed Nov 11, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Issue related to the REST API docs Documentation updates feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Organisation-Level Audit Log Records - User Authentication Events

4 participants