"""Double authentification : 2fa/setup, enable, verify, disable, recovery-codes ; mot de passe.""" import pytest from django.core import mail from django_otp.oath import TOTP from django_otp.plugins.otp_totp.models import TOTPDevice from rest_framework.test import APIClient from accounts.models import RecoveryCode, User PASSWORD = "un-mot-de-passe-solide" AUTH = "/api/v1/auth" pytestmark = pytest.mark.django_db def current_code(device: TOTPDevice, offset: int = 0) -> str: totp = TOTP(device.bin_key, device.step, device.t0, device.digits, device.drift) totp.time = totp.time + offset * device.step return f"{totp.token():06d}" def login(client, email="medecin@exemple.be", password=PASSWORD): return client.post(f"{AUTH}/login/", {"email": email, "password": password}, format="json") @pytest.fixture def logged_in(user): client = APIClient() login(client) return client @pytest.fixture def with_mfa(user, logged_in, django_capture_on_commit_callbacks): """Active la 2FA pour `user` ; renvoie (appareil, codes de secours).""" logged_in.post(f"{AUTH}/2fa/setup/") device = TOTPDevice.objects.get(user=user) with django_capture_on_commit_callbacks(execute=True): response = logged_in.post( f"{AUTH}/2fa/enable/", {"code": current_code(device)}, format="json" ) device.refresh_from_db() return device, response.json()["recovery_codes"] # Activation ------------------------------------------------------------------------ def test_setup_returns_secret_and_qr_code(user, logged_in): response = logged_in.post(f"{AUTH}/2fa/setup/") assert response.status_code == 200 body = response.json() assert body["otpauth_url"].startswith("otpauth://totp/") assert "issuer=PRISM" in body["otpauth_url"] assert body["qr_code"].startswith("data:image/svg+xml;base64,") assert len(body["secret"].replace(" ", "")) == 32 assert not TOTPDevice.objects.get(user=user).confirmed def test_setup_replaces_previous_attempt(user, logged_in): logged_in.post(f"{AUTH}/2fa/setup/") logged_in.post(f"{AUTH}/2fa/setup/") assert TOTPDevice.objects.filter(user=user).count() == 1 def test_setup_requires_authentication(): assert APIClient().post(f"{AUTH}/2fa/setup/").status_code == 403 def test_enable_with_valid_code(user, with_mfa): device, codes = with_mfa assert device.confirmed assert len(codes) == 8 assert all(len(code) == 9 and code[4] == "-" for code in codes) assert RecoveryCode.objects.filter(user=user).count() == 8 # Les codes ne sont stockés qu'en empreinte. stored = set(RecoveryCode.objects.values_list("code_hash", flat=True)) assert not {c.replace("-", "") for c in codes} & stored assert mail.outbox[-1].subject == "[PRISM] Double authentification modifiée" assert "activée" in mail.outbox[-1].body def test_enable_with_wrong_code(user, logged_in): logged_in.post(f"{AUTH}/2fa/setup/") response = logged_in.post(f"{AUTH}/2fa/enable/", {"code": "000000"}, format="json") assert response.status_code == 400 assert response.json()["code"] == "invalid_code" assert not TOTPDevice.objects.get(user=user).confirmed def test_enable_without_setup(logged_in): response = logged_in.post(f"{AUTH}/2fa/enable/", {"code": "123456"}, format="json") assert response.status_code == 400 def test_setup_refused_when_already_enabled(logged_in, with_mfa): response = logged_in.post(f"{AUTH}/2fa/setup/") assert response.status_code == 400 assert response.json()["code"] == "mfa_enabled" def test_me_reports_mfa(logged_in, with_mfa): assert logged_in.get(f"{AUTH}/me/").json()["mfa_enabled"] is True # Connexion en deux étapes ------------------------------------------------------------ def test_login_requires_second_step(with_mfa): client = APIClient() response = login(client) assert response.status_code == 200 assert response.json() == {"mfa_required": True, "user": None} # Pas de session ouverte avant le second facteur. assert client.get(f"{AUTH}/me/").status_code == 403 def test_login_with_totp_code(with_mfa): device, _ = with_mfa client = APIClient() login(client) response = client.post( f"{AUTH}/2fa/verify/", {"code": current_code(device, offset=1)}, format="json" ) assert response.status_code == 200 assert response.json()["user"]["email"] == "medecin@exemple.be" assert client.get(f"{AUTH}/me/").status_code == 200 def test_login_with_recovery_code_works_once(with_mfa): _, codes = with_mfa client = APIClient() login(client) lowercase_without_dash = codes[0].replace("-", "").lower() assert ( client.post( f"{AUTH}/2fa/verify/", {"code": lowercase_without_dash}, format="json" ).status_code == 200 ) other = APIClient() login(other) response = other.post(f"{AUTH}/2fa/verify/", {"code": codes[0]}, format="json") assert response.status_code == 400 assert response.json()["code"] == "invalid_code" def test_wrong_code_keeps_session_closed(with_mfa): client = APIClient() login(client) response = client.post(f"{AUTH}/2fa/verify/", {"code": "000000"}, format="json") assert response.status_code == 400 assert response.json() == {"detail": "Code incorrect ou expiré.", "code": "invalid_code"} assert client.get(f"{AUTH}/me/").status_code == 403 def test_verify_without_first_step(with_mfa): device, _ = with_mfa response = APIClient().post( f"{AUTH}/2fa/verify/", {"code": current_code(device)}, format="json" ) assert response.status_code == 400 assert response.json()["code"] == "mfa_expired" def test_second_step_expires(with_mfa, settings): device, _ = with_mfa settings.MFA_STEP_MAX_AGE = -1 client = APIClient() login(client) response = client.post(f"{AUTH}/2fa/verify/", {"code": current_code(device)}, format="json") assert response.json()["code"] == "mfa_expired" def test_totp_code_cannot_be_replayed(with_mfa): device, _ = with_mfa code = current_code(device, offset=1) first = APIClient() login(first) assert first.post(f"{AUTH}/2fa/verify/", {"code": code}, format="json").status_code == 200 second = APIClient() login(second) assert second.post(f"{AUTH}/2fa/verify/", {"code": code}, format="json").status_code == 400 def test_second_step_throttling(with_mfa, monkeypatch): from rest_framework.throttling import ScopedRateThrottle monkeypatch.setattr(ScopedRateThrottle, "THROTTLE_RATES", {"mfa": "2/minute", "login": None}) client = APIClient() login(client) for _ in range(2): client.post(f"{AUTH}/2fa/verify/", {"code": "000000"}, format="json") assert client.post(f"{AUTH}/2fa/verify/", {"code": "000000"}, format="json").status_code == 429 # Désactivation et régénération ----------------------------------------------------------- def test_disable_requires_password_and_code( user, logged_in, with_mfa, django_capture_on_commit_callbacks ): device, codes = with_mfa bad_password = logged_in.post( f"{AUTH}/2fa/disable/", {"password": "faux", "code": codes[0]}, format="json" ) assert bad_password.json()["code"] == "invalid_password" bad_code = logged_in.post( f"{AUTH}/2fa/disable/", {"password": PASSWORD, "code": "000000"}, format="json" ) assert bad_code.json()["code"] == "invalid_code" with django_capture_on_commit_callbacks(execute=True): response = logged_in.post( f"{AUTH}/2fa/disable/", {"password": PASSWORD, "code": codes[1]}, format="json" ) assert response.status_code == 204 assert not TOTPDevice.objects.filter(user=user).exists() assert not RecoveryCode.objects.filter(user=user).exists() assert "désactivée" in mail.outbox[-1].body def test_staff_cannot_disable_mfa(user, logged_in, with_mfa): _, codes = with_mfa User.objects.filter(pk=user.pk).update(is_staff=True) response = logged_in.post( f"{AUTH}/2fa/disable/", {"password": PASSWORD, "code": codes[0]}, format="json" ) assert response.json()["code"] == "mfa_mandatory" def test_regenerate_recovery_codes(user, logged_in, with_mfa): device, old_codes = with_mfa response = logged_in.post( f"{AUTH}/2fa/recovery-codes/", {"code": current_code(device, offset=1)}, format="json" ) assert response.status_code == 200 new_codes = response.json()["recovery_codes"] assert len(new_codes) == 8 assert not set(new_codes) & set(old_codes) client = APIClient() login(client) assert ( client.post(f"{AUTH}/2fa/verify/", {"code": old_codes[2]}, format="json").status_code == 400 ) def test_regenerate_refuses_recovery_code(logged_in, with_mfa): _, codes = with_mfa response = logged_in.post(f"{AUTH}/2fa/recovery-codes/", {"code": codes[0]}, format="json") assert response.status_code == 400 # Mot de passe --------------------------------------------------------------------------- def test_change_password(user, logged_in, django_capture_on_commit_callbacks): with django_capture_on_commit_callbacks(execute=True): response = logged_in.post( f"{AUTH}/password/change/", {"current_password": PASSWORD, "new_password": "un-autre-mot-de-passe"}, format="json", ) assert response.status_code == 204 # La session reste ouverte. assert logged_in.get(f"{AUTH}/me/").status_code == 200 user.refresh_from_db() assert user.check_password("un-autre-mot-de-passe") assert mail.outbox[-1].subject == "[PRISM] Votre mot de passe a été modifié" @pytest.mark.parametrize( ("payload", "field"), [ ({"current_password": "faux", "new_password": "un-autre-mot-de-passe"}, "current_password"), ({"current_password": PASSWORD, "new_password": "court"}, "new_password"), ], ) def test_change_password_validation(logged_in, payload, field): response = logged_in.post(f"{AUTH}/password/change/", payload, format="json") assert response.status_code == 400 assert field in response.json()