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/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/constants.py b/api/audit/constants.py index 38a58d091eb5..c61518233992 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" @@ -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." diff --git a/api/audit/signals.py b/api/audit/signals/__init__.py similarity index 100% rename from api/audit/signals.py rename to api/audit/signals/__init__.py diff --git a/api/audit/signals/authentication.py b/api/audit/signals/authentication.py new file mode 100644 index 000000000000..dbb4b1601c50 --- /dev/null +++ b/api/audit/signals/authentication.py @@ -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 + 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/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/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/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/oauth/serializers.py b/api/custom_auth/oauth/serializers.py index 7d504f9f9676..051c4c501363 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_sso_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_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] diff --git a/api/custom_auth/serializers.py b/api/custom_auth/serializers.py index 2382601e70ef..bb638eb0f12a 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 @@ -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) diff --git a/api/custom_auth/signals.py b/api/custom_auth/signals.py index ad4d088bb414..0069b9014da1 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,15 @@ ) 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_sso_completed = Signal() +user_2fa_enabled = Signal() +user_2fa_disabled = 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..97566afb024a 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_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, @@ -61,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), @@ -68,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] @@ -221,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() @@ -232,22 +250,16 @@ 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) - 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 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 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..5a4dbc0448d5 100644 --- a/api/oauth2_metadata/views.py +++ b/api/oauth2_metadata/views.py @@ -1,12 +1,15 @@ +import hashlib from typing import Any from urllib.parse import urlencode, urlparse, urlunparse import structlog -from django.http import HttpRequest, JsonResponse, QueryDict +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 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 +31,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 +223,40 @@ 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 = 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( + Q(token_checksum=token_checksum) + | Q(access_token__token_checksum=token_checksum), + 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/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/tests/integration/audit/events/test_authentication_logs.py b/api/tests/integration/audit/events/test_authentication_logs.py new file mode 100644 index 000000000000..8a433883664a --- /dev/null +++ b/api/tests/integration/audit/events/test_authentication_logs.py @@ -0,0 +1,685 @@ +import base64 +import hashlib +from datetime import timedelta +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 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 + +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 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.""" + 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.", + }, + ] + + +@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, + 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` logged out.", + }, + { + "organisation_id": 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.", + }, + { + "organisation_id": other_organisation.id, + "author_id": user.id, + "log": "User `alice@example.com` changed their password.", + }, + ] + + +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.", + }, + ] + + +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( + 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_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, + }, + ) + + # 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.", + }, + ] + + +@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( + 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": token, + "token_type_hint": token_type_hint, + "client_id": oauth_application.client_id, + }, + ) + + # 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.", + }, + ] 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 diff --git a/api/tests/unit/audit/test_unit_audit_signals.py b/api/tests/unit/audit/test_unit_audit_signals.py index 5180a288e59e..16030488aa22 100644 --- a/api/tests/unit/audit/test_unit_audit_signals.py +++ b/api/tests/unit/audit/test_unit_audit_signals.py @@ -16,6 +16,7 @@ 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 @@ -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, 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] 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" 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, 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" }, 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..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 @@ -109,3 +109,20 @@ 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 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 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 diff --git a/docs/docs/deployment-self-hosting/observability/_events-catalogue.md b/docs/docs/deployment-self-hosting/observability/_events-catalogue.md index 1baf8e4662e3..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:171` + - `api/oauth2_metadata/views.py:175` 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: