| 1 |
import importlib |
| 2 |
import json |
| 3 |
import os |
| 4 |
import random |
| 5 |
import re |
| 6 |
import sys |
| 7 |
import time |
| 8 |
import uuid |
| 9 |
from contextlib import contextmanager |
| 10 |
from pathlib import Path |
| 11 |
from unittest.mock import Mock, PropertyMock, patch |
| 12 |
|
| 13 |
from django.contrib.auth import get_user_model |
| 14 |
from django.contrib.messages.middleware import MessageMiddleware |
| 15 |
from django.contrib.sessions.middleware import SessionMiddleware |
| 16 |
from django.urls import clear_url_caches, set_urlconf |
| 17 |
|
| 18 |
import pytest |
| 19 |
|
| 20 |
from allauth.account.models import EmailAddress |
| 21 |
from allauth.account.utils import user_email, user_pk_to_url_str, user_username |
| 22 |
from allauth.core import context |
| 23 |
from allauth.socialaccount.internal import statekit |
| 24 |
from allauth.socialaccount.providers.base.constants import AuthProcess |
| 25 |
|
| 26 |
|
| 27 |
def pytest_collection_modifyitems(config, items): |
| 28 |
if config.getoption("--ds") == "tests.projects.headless_only.settings": |
| 29 |
removed_items = [] |
| 30 |
for item in items: |
| 31 |
if not item.location[0].startswith("tests/apps/headless"): |
| 32 |
removed_items.append(item) |
| 33 |
for item in removed_items: |
| 34 |
items.remove(item) |
| 35 |
|
| 36 |
|
| 37 |
@pytest.fixture |
| 38 |
def user(user_factory): |
| 39 |
return user_factory() |
| 40 |
|
| 41 |
|
| 42 |
@pytest.fixture |
| 43 |
def auth_client(client, user): |
| 44 |
client.force_login(user) |
| 45 |
return client |
| 46 |
|
| 47 |
|
| 48 |
@pytest.fixture |
| 49 |
def password_factory(): |
| 50 |
def f(): |
| 51 |
return str(uuid.uuid4()) |
| 52 |
|
| 53 |
return f |
| 54 |
|
| 55 |
|
| 56 |
@pytest.fixture |
| 57 |
def user_password(password_factory): |
| 58 |
return password_factory() |
| 59 |
|
| 60 |
|
| 61 |
@pytest.fixture |
| 62 |
def email_verified(): |
| 63 |
return True |
| 64 |
|
| 65 |
|
| 66 |
@pytest.fixture |
| 67 |
def user_factory(email_factory, db, user_password, email_verified): |
| 68 |
def factory( |
| 69 |
email=None, |
| 70 |
username=None, |
| 71 |
commit=True, |
| 72 |
with_email=True, |
| 73 |
email_verified=email_verified, |
| 74 |
password=None, |
| 75 |
phone=None, |
| 76 |
phone_verified=False, |
| 77 |
with_emailaddress=True, |
| 78 |
with_totp=False, |
| 79 |
): |
| 80 |
from allauth.account.adapter import get_adapter |
| 81 |
|
| 82 |
if not username: |
| 83 |
username = uuid.uuid4().hex |
| 84 |
|
| 85 |
if not email and with_email: |
| 86 |
email = email_factory(username=username) |
| 87 |
|
| 88 |
User = get_user_model() |
| 89 |
user = User() |
| 90 |
if password == "!": # nosec |
| 91 |
user.password = password |
| 92 |
else: |
| 93 |
user.set_password(user_password if password is None else password) |
| 94 |
user_username(user, username) |
| 95 |
user_email(user, email or "") |
| 96 |
if commit: |
| 97 |
user.save() |
| 98 |
if email and with_emailaddress: |
| 99 |
EmailAddress.objects.create( |
| 100 |
user=user, |
| 101 |
email=email.lower(), |
| 102 |
verified=email_verified, |
| 103 |
primary=True, |
| 104 |
) |
| 105 |
if with_totp: |
| 106 |
from allauth.mfa.totp.internal import auth |
| 107 |
|
| 108 |
auth.TOTP.activate(user, auth.generate_totp_secret()) |
| 109 |
if phone: |
| 110 |
get_adapter().set_phone(user, phone, phone_verified) |
| 111 |
return user |
| 112 |
|
| 113 |
return factory |
| 114 |
|
| 115 |
|
| 116 |
@pytest.fixture |
| 117 |
def email_factory(): |
| 118 |
def factory(username=None, email=None, mixed_case=False): |
| 119 |
if email is None: |
| 120 |
if not username: |
| 121 |
username = uuid.uuid4().hex |
| 122 |
email = f"{username}@{uuid.uuid4().hex}.org" |
| 123 |
if mixed_case: |
| 124 |
email = "".join( |
| 125 |
[random.choice([c.upper(), c.lower()]) for c in email] # nosec |
| 126 |
) |
| 127 |
else: |
| 128 |
email = email.lower() |
| 129 |
return email |
| 130 |
|
| 131 |
return factory |
| 132 |
|
| 133 |
|
| 134 |
@pytest.fixture |
| 135 |
def reauthentication_bypass(): |
| 136 |
@contextmanager |
| 137 |
def f(): |
| 138 |
with patch( |
| 139 |
"allauth.account.internal.flows.reauthentication.did_recently_authenticate" |
| 140 |
) as m: |
| 141 |
m.return_value = True |
| 142 |
yield |
| 143 |
|
| 144 |
return f |
| 145 |
|
| 146 |
|
| 147 |
@pytest.fixture |
| 148 |
def webauthn_authentication_bypass(): |
| 149 |
@contextmanager |
| 150 |
def f(authenticator): |
| 151 |
from fido2.utils import websafe_encode |
| 152 |
|
| 153 |
from allauth.mfa.adapter import get_adapter |
| 154 |
|
| 155 |
with patch( |
| 156 |
"allauth.mfa.webauthn.internal.auth.WebAuthn.authenticator_data", |
| 157 |
new_callable=PropertyMock, |
| 158 |
) as ad_m: |
| 159 |
with patch("fido2.server.Fido2Server.authenticate_begin") as ab_m: |
| 160 |
ab_m.return_value = ({}, {"state": "dummy"}) |
| 161 |
with patch("fido2.server.Fido2Server.authenticate_complete") as ac_m: |
| 162 |
with patch( |
| 163 |
"allauth.mfa.webauthn.internal.auth.parse_authentication_response" |
| 164 |
) as m: |
| 165 |
user_handle = ( |
| 166 |
get_adapter().get_public_key_credential_user_entity( |
| 167 |
authenticator.user |
| 168 |
)["id"] |
| 169 |
) |
| 170 |
authenticator_data = Mock() |
| 171 |
authenticator_data.credential_data.credential_id = ( |
| 172 |
"credential_id" |
| 173 |
) |
| 174 |
ad_m.return_value = authenticator_data |
| 175 |
m.return_value = Mock() |
| 176 |
binding = Mock() |
| 177 |
binding.credential_id = "credential_id" |
| 178 |
ac_m.return_value = binding |
| 179 |
yield json.dumps( |
| 180 |
{"response": {"userHandle": websafe_encode(user_handle)}} |
| 181 |
) |
| 182 |
|
| 183 |
return f |
| 184 |
|
| 185 |
|
| 186 |
@pytest.fixture |
| 187 |
def webauthn_registration_bypass(): |
| 188 |
@contextmanager |
| 189 |
def f(user, passwordless): |
| 190 |
with patch("fido2.server.Fido2Server.register_complete") as rc_m: |
| 191 |
with patch( |
| 192 |
"allauth.mfa.webauthn.internal.auth.parse_registration_response" |
| 193 |
) as m: |
| 194 |
m.return_value = Mock() |
| 195 |
|
| 196 |
class FakeAuthenticatorData(bytes): |
| 197 |
def is_user_verified(self): |
| 198 |
return passwordless |
| 199 |
|
| 200 |
binding = FakeAuthenticatorData(b"binding") |
| 201 |
rc_m.return_value = binding |
| 202 |
yield json.dumps( |
| 203 |
{ |
| 204 |
"authenticatorAttachment": "cross-platform", |
| 205 |
"clientExtensionResults": {"credProps": {"rk": passwordless}}, |
| 206 |
"id": "123", |
| 207 |
"rawId": "456", |
| 208 |
"response": { |
| 209 |
"attestationObject": "ao", |
| 210 |
"clientDataJSON": "cdj", |
| 211 |
"transports": ["usb"], |
| 212 |
}, |
| 213 |
"type": "public-key", |
| 214 |
} |
| 215 |
) |
| 216 |
|
| 217 |
return f |
| 218 |
|
| 219 |
|
| 220 |
@pytest.fixture(autouse=True) |
| 221 |
def clear_context_request(): |
| 222 |
context._request_var.set(None) |
| 223 |
|
| 224 |
|
| 225 |
@pytest.fixture |
| 226 |
def enable_cache(settings): |
| 227 |
from django.core.cache import cache |
| 228 |
|
| 229 |
settings.CACHES = { |
| 230 |
"default": { |
| 231 |
"BACKEND": "django.core.cache.backends.locmem.LocMemCache", |
| 232 |
} |
| 233 |
} |
| 234 |
cache.clear() |
| 235 |
yield |
| 236 |
|
| 237 |
|
| 238 |
@pytest.fixture |
| 239 |
def totp_validation_bypass(): |
| 240 |
@contextmanager |
| 241 |
def f(): |
| 242 |
with patch("allauth.mfa.totp.internal.auth.validate_totp_code") as m: |
| 243 |
m.return_value = True |
| 244 |
yield |
| 245 |
|
| 246 |
return f |
| 247 |
|
| 248 |
|
| 249 |
@pytest.fixture |
| 250 |
def provider_id(): |
| 251 |
return "unittest-server" |
| 252 |
|
| 253 |
|
| 254 |
@pytest.fixture |
| 255 |
def openid_connect_provider_id(): |
| 256 |
return "unittest-server" |
| 257 |
|
| 258 |
|
| 259 |
@pytest.fixture |
| 260 |
def password_reset_key_generator(): |
| 261 |
def f(user): |
| 262 |
from allauth.account import app_settings |
| 263 |
|
| 264 |
token_generator = app_settings.PASSWORD_RESET_TOKEN_GENERATOR() |
| 265 |
uid = user_pk_to_url_str(user) |
| 266 |
temp_key = token_generator.make_token(user) |
| 267 |
key = f"{uid}-{temp_key}" |
| 268 |
return key |
| 269 |
|
| 270 |
return f |
| 271 |
|
| 272 |
|
| 273 |
@pytest.fixture |
| 274 |
def google_provider_settings(settings): |
| 275 |
gsettings = {"APPS": [{"client_id": "client_id", "secret": "secret"}]} |
| 276 |
settings.SOCIALACCOUNT_PROVIDERS = {"google": gsettings} |
| 277 |
return gsettings |
| 278 |
|
| 279 |
|
| 280 |
@pytest.fixture |
| 281 |
def twitter_provider_settings(settings): |
| 282 |
tsettings = {"APPS": [{"client_id": "client_id", "secret": "secret"}]} |
| 283 |
settings.SOCIALACCOUNT_PROVIDERS = {"twitter": tsettings} |
| 284 |
return tsettings |
| 285 |
|
| 286 |
|
| 287 |
@pytest.fixture |
| 288 |
def user_with_totp(user): |
| 289 |
from allauth.mfa.totp.internal import auth |
| 290 |
|
| 291 |
auth.TOTP.activate(user, auth.generate_totp_secret()) |
| 292 |
return user |
| 293 |
|
| 294 |
|
| 295 |
@pytest.fixture |
| 296 |
def user_with_recovery_codes(user_with_totp): |
| 297 |
from allauth.mfa.recovery_codes.internal import auth |
| 298 |
|
| 299 |
auth.RecoveryCodes.activate(user_with_totp) |
| 300 |
return user_with_totp |
| 301 |
|
| 302 |
|
| 303 |
@pytest.fixture |
| 304 |
def passkey(user): |
| 305 |
from allauth.mfa.models import Authenticator |
| 306 |
|
| 307 |
authenticator = Authenticator.objects.create( |
| 308 |
user=user, |
| 309 |
type=Authenticator.Type.WEBAUTHN, |
| 310 |
data={ |
| 311 |
"name": "Test passkey", |
| 312 |
"passwordless": True, |
| 313 |
"credential": {}, |
| 314 |
}, |
| 315 |
) |
| 316 |
return authenticator |
| 317 |
|
| 318 |
|
| 319 |
@pytest.fixture |
| 320 |
def user_with_passkey(user, passkey): |
| 321 |
return user |
| 322 |
|
| 323 |
|
| 324 |
@pytest.fixture |
| 325 |
def sociallogin_setup_state(): |
| 326 |
def setup(client, process=None, next_url=None, **kwargs): |
| 327 |
state_id = "id321" |
| 328 |
session = client.session |
| 329 |
state = {"process": process or AuthProcess.LOGIN, **kwargs} |
| 330 |
if next_url: |
| 331 |
state["next"] = next_url |
| 332 |
states = {} |
| 333 |
states[state_id] = [state, time.time()] |
| 334 |
session[statekit.STATES_SESSION_KEY] = states |
| 335 |
session.save() |
| 336 |
return state_id |
| 337 |
|
| 338 |
return setup |
| 339 |
|
| 340 |
|
| 341 |
@pytest.fixture |
| 342 |
def request_factory(rf): |
| 343 |
class RequestFactory: |
| 344 |
def get(self, path): |
| 345 |
request = rf.get(path) |
| 346 |
SessionMiddleware(lambda request: None).process_request(request) |
| 347 |
MessageMiddleware(lambda request: None).process_request(request) |
| 348 |
return request |
| 349 |
|
| 350 |
return RequestFactory() |
| 351 |
|
| 352 |
|
| 353 |
@pytest.fixture |
| 354 |
def get_last_email_verification_code(): |
| 355 |
from allauth.account.internal.flows import email_verification_by_code |
| 356 |
|
| 357 |
def f(client, mailoutbox): |
| 358 |
code = re.search( |
| 359 |
"\n[0-9a-z-]{6,12}\n", mailoutbox[-1].body, re.I | re.DOTALL | re.MULTILINE |
| 360 |
)[0].strip() |
| 361 |
if hasattr(client, "headless_session"): |
| 362 |
session = client.headless_session() |
| 363 |
else: |
| 364 |
session = client.session |
| 365 |
assert ( |
| 366 |
session[email_verification_by_code.EMAIL_VERIFICATION_CODE_SESSION_KEY][ |
| 367 |
"code" |
| 368 |
] |
| 369 |
== code |
| 370 |
) |
| 371 |
return code |
| 372 |
|
| 373 |
return f |
| 374 |
|
| 375 |
|
| 376 |
@pytest.fixture |
| 377 |
def get_last_password_reset_code(): |
| 378 |
from allauth.account.internal.flows import password_reset_by_code |
| 379 |
|
| 380 |
def f(client, mailoutbox): |
| 381 |
code = re.search( |
| 382 |
"\n[0-9a-z-]{8,12}\n", mailoutbox[-1].body, re.I | re.DOTALL | re.MULTILINE |
| 383 |
)[0].strip() |
| 384 |
if hasattr(client, "headless_session"): |
| 385 |
session = client.headless_session() |
| 386 |
else: |
| 387 |
session = client.session |
| 388 |
assert ( |
| 389 |
session[password_reset_by_code.PASSWORD_RESET_VERIFICATION_SESSION_KEY][ |
| 390 |
"code" |
| 391 |
] |
| 392 |
== code |
| 393 |
) |
| 394 |
return code |
| 395 |
|
| 396 |
return f |
| 397 |
|
| 398 |
|
| 399 |
@pytest.fixture |
| 400 |
def settings_impacting_urls(settings): |
| 401 |
@contextmanager |
| 402 |
def f(**kv): |
| 403 |
def reload_urlconf(): |
| 404 |
clear_url_caches() |
| 405 |
for urlconf in [ |
| 406 |
settings.ROOT_URLCONF, |
| 407 |
"allauth.account.urls", |
| 408 |
"allauth.urls", |
| 409 |
"allauth.mfa.urls", |
| 410 |
"allauth.mfa.base.urls", |
| 411 |
"allauth.headless.urls", |
| 412 |
"allauth.headless.base.urls", |
| 413 |
"allauth.headless.socialaccount.urls", |
| 414 |
"allauth.headless.usersessions.urls", |
| 415 |
"allauth.headless.mfa.urls", |
| 416 |
"allauth.idp.urls", |
| 417 |
"allauth.idp.oidc.urls", |
| 418 |
]: |
| 419 |
if urlconf in sys.modules: |
| 420 |
importlib.reload(sys.modules[urlconf]) |
| 421 |
set_urlconf(None) |
| 422 |
|
| 423 |
old_values = {} |
| 424 |
for k, v in kv.items(): |
| 425 |
if hasattr(settings, k): |
| 426 |
old_values[k] = getattr(settings, k) |
| 427 |
setattr(settings, k, v) |
| 428 |
reload_urlconf() |
| 429 |
yield |
| 430 |
for k, v in kv.items(): |
| 431 |
if k in old_values: |
| 432 |
setattr(settings, k, old_values[k]) |
| 433 |
else: |
| 434 |
delattr(settings, k) |
| 435 |
reload_urlconf() |
| 436 |
|
| 437 |
return f |
| 438 |
|
| 439 |
|
| 440 |
@pytest.fixture(autouse=True) |
| 441 |
def clear_phone_stub(): |
| 442 |
from tests.projects.common import phone_stub |
| 443 |
|
| 444 |
yield |
| 445 |
phone_stub.clear() |
| 446 |
|
| 447 |
|
| 448 |
@pytest.fixture |
| 449 |
def sms_outbox(): |
| 450 |
from tests.projects.common import phone_stub |
| 451 |
|
| 452 |
return phone_stub.sms_outbox |
| 453 |
|
| 454 |
|
| 455 |
@pytest.fixture |
| 456 |
def phone_factory(): |
| 457 |
def f(): |
| 458 |
return f"+31{random.randint(1, 10**10):010}" |
| 459 |
|
| 460 |
return f |
| 461 |
|
| 462 |
|
| 463 |
@pytest.fixture |
| 464 |
def phone(phone_factory): |
| 465 |
return phone_factory() |
| 466 |
|
| 467 |
|
| 468 |
@pytest.fixture |
| 469 |
def user_with_phone(user, phone): |
| 470 |
from allauth.account.adapter import get_adapter |
| 471 |
|
| 472 |
get_adapter().set_phone(user, phone, True) |
| 473 |
return user |
| 474 |
|
| 475 |
|
| 476 |
def pytest_ignore_collect(collection_path, config): |
| 477 |
from tests.projects.common.settings import INSTALLED_SOCIALACCOUNT_APPS |
| 478 |
|
| 479 |
if "allauth.socialaccount.providers.saml" not in INSTALLED_SOCIALACCOUNT_APPS: |
| 480 |
if ( |
| 481 |
Path(__file__).parent / "apps" / "socialaccount" / "providers" / "saml" |
| 482 |
in collection_path.parents |
| 483 |
): |
| 484 |
return True |
| 485 |
|
| 486 |
tests_to_skip = { |
| 487 |
"tests.projects.account_only.settings": ( |
| 488 |
"headless", |
| 489 |
"mfa", |
| 490 |
"usersessions", |
| 491 |
"socialaccount", |
| 492 |
"idp", |
| 493 |
), |
| 494 |
"tests.projects.headless_only.settings": ("idp",), |
| 495 |
} |
| 496 |
dsm = os.getenv("DJANGO_SETTINGS_MODULE") |
| 497 |
skipped_paths = tests_to_skip.get(dsm) |
| 498 |
if not skipped_paths: |
| 499 |
return False |
| 500 |
for skipped_path in skipped_paths: |
| 501 |
abs_skipped_path = Path(__file__).parent / "apps" / skipped_path |
| 502 |
if ( |
| 503 |
abs_skipped_path == collection_path |
| 504 |
or abs_skipped_path in collection_path.parents |
| 505 |
): |
| 506 |
return True |
| 507 |
return False |
| 508 |
|
| 509 |
|
| 510 |
@pytest.fixture() |
| 511 |
def messagesoutbox(): |
| 512 |
from tests.projects.common import adapters |
| 513 |
|
| 514 |
adapters.messagesoutbox = [] |
| 515 |
yield adapters.messagesoutbox |
| 516 |
|
| 517 |
|
| 518 |
@pytest.fixture |
| 519 |
def request_context(rf): |
| 520 |
request = rf.get("/") |
| 521 |
with context.request_context(request): |
| 522 |
yield request |