| 1 |
import time |
| 2 |
from http import HTTPStatus |
| 3 |
|
| 4 |
from django.conf import settings |
| 5 |
from django.urls import reverse |
| 6 |
|
| 7 |
import pytest |
| 8 |
|
| 9 |
from allauth.mfa import app_settings |
| 10 |
from allauth.mfa.internal.flows import trust |
| 11 |
|
| 12 |
|
| 13 |
def test_encode_decode(rf): |
| 14 |
request = rf.get("/") |
| 15 |
value = trust.encode_trust_cookie( |
| 16 |
[ |
| 17 |
trust.IssuedTrust(fingerprint="dated", at=2024), |
| 18 |
trust.IssuedTrust(fingerprint="good", at=time.time()), |
| 19 |
] |
| 20 |
) |
| 21 |
request.COOKIES[app_settings.TRUST_COOKIE_NAME] = value |
| 22 |
trusts = trust.decode_trust_cookie(request) |
| 23 |
assert len(trusts) == 1 |
| 24 |
assert trusts[0].fingerprint == "good" |
| 25 |
|
| 26 |
|
| 27 |
def test_decode_invalid_value(rf): |
| 28 |
request = rf.get("/") |
| 29 |
request.COOKIES[app_settings.TRUST_COOKIE_NAME] = "bad" |
| 30 |
trusts = trust.decode_trust_cookie(request) |
| 31 |
assert len(trusts) == 0 |
| 32 |
|
| 33 |
|
| 34 |
@pytest.mark.parametrize("action", ["", "trust"]) |
| 35 |
def test_trust_flow( |
| 36 |
client, |
| 37 |
user_with_totp, |
| 38 |
user_password, |
| 39 |
totp_validation_bypass, |
| 40 |
settings_impacting_urls, |
| 41 |
action, |
| 42 |
): |
| 43 |
with settings_impacting_urls(MFA_TRUST_ENABLED=True): |
| 44 |
# Login |
| 45 |
resp = client.post( |
| 46 |
reverse("account_login"), |
| 47 |
{"login": user_with_totp.username, "password": user_password}, |
| 48 |
) |
| 49 |
assert resp.status_code == HTTPStatus.FOUND |
| 50 |
|
| 51 |
# Complete TOTP |
| 52 |
assert resp["location"] == reverse("mfa_authenticate") |
| 53 |
with totp_validation_bypass(): |
| 54 |
resp = client.post( |
| 55 |
reverse("mfa_authenticate"), |
| 56 |
{"code": "123"}, |
| 57 |
) |
| 58 |
assert resp.status_code == HTTPStatus.FOUND |
| 59 |
|
| 60 |
# Indicate trust |
| 61 |
assert resp["location"] == reverse("mfa_trust") |
| 62 |
resp = client.post( |
| 63 |
reverse("mfa_trust"), |
| 64 |
{"action": action}, |
| 65 |
) |
| 66 |
assert resp["location"] == settings.LOGIN_REDIRECT_URL |
| 67 |
|
| 68 |
# Sign out |
| 69 |
resp = client.post( |
| 70 |
reverse("account_logout"), |
| 71 |
) |
| 72 |
assert resp.status_code == HTTPStatus.FOUND |
| 73 |
|
| 74 |
# Sign in |
| 75 |
resp = client.post( |
| 76 |
reverse("account_login"), |
| 77 |
{"login": user_with_totp.username, "password": user_password}, |
| 78 |
) |
| 79 |
assert resp.status_code == HTTPStatus.FOUND |
| 80 |
assert resp["location"] == ( |
| 81 |
settings.LOGIN_REDIRECT_URL |
| 82 |
if action == "trust" |
| 83 |
else reverse("mfa_authenticate") |
| 84 |
) |