"""Block ⑤ auth hardening (Fable audit 2026-07-18): PBKDF2 + обратная совместимость, прозрачный апгрейд, блокировка при refresh, rate-limit verify-email, инвайт не сгорает на существующем email. """ import hashlib import importlib import os import sys from pathlib import Path import pytest ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) @pytest.fixture() def a(monkeypatch, tmp_path): monkeypatch.setenv("SESSION_SECRET", "test-secret") monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db")) monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "ext")) import auth, db importlib.reload(db) importlib.reload(auth) db.init_db() auth._login_attempts.clear() return auth, db # ---- PBKDF2 + обратная совместимость ---- def test_new_hash_is_pbkdf2_and_verifies(a): auth, _ = a h = auth.hash_password("Secret123") assert h.startswith("pbkdf2_sha256$") assert auth.check_password("Secret123", h) assert not auth.check_password("wrong", h) assert not auth.needs_rehash(h) def test_legacy_sha256_still_verifies_and_flags_rehash(a): auth, _ = a salt = "abcd1234" legacy = f"{salt}:{hashlib.sha256((salt + 'Secret123').encode()).hexdigest()}" assert auth.check_password("Secret123", legacy) # старый вход не сломан assert not auth.check_password("wrong", legacy) assert auth.needs_rehash(legacy) # помечен на апгрейд def test_login_upgrades_legacy_hash_transparently(a): auth, db = a salt = "abcd1234" legacy = f"{salt}:{hashlib.sha256((salt + 'Secret123').encode()).hexdigest()}" db.create_user("u@x.com", legacy) db.get_user_by_email("u@x.com") # ensure exists with db._conn() as c: c.execute("UPDATE users SET verified=1 WHERE email='u@x.com'") tok = auth.authenticate("u@x.com", "Secret123", client_ip="1.2.3.4") assert tok # вход прошёл stored = db.get_user_by_email("u@x.com")["password_hash"] assert stored.startswith("pbkdf2_sha256$") # хэш апгрейднут в БД # ---- блокировка реально действует при refresh ---- def test_blocked_user_cannot_refresh(a): auth, db = a db.create_user("b@x.com", auth.hash_password("Secret123")) with db._conn() as c: c.execute("UPDATE users SET verified=1 WHERE email='b@x.com'") rt = auth._make_refresh_token("b@x.com", "user") assert auth.refresh_access_token(rt) # пока не заблокирован — ок db.block_user("b@x.com", True) assert auth.refresh_access_token(rt) is None # заблокирован → refresh мёртв def test_deleted_user_cannot_refresh(a): auth, db = a rt = auth._make_refresh_token("ghost@x.com", "user") assert auth.refresh_access_token(rt) is None # нет в БД → None def test_refresh_reads_role_from_db_not_token(a): """Fable P1: демоутнутый admin не должен оставаться админом до 7 дней.""" import jose.jwt as _jwt auth, db = a db.create_user("adm@x.com", auth.hash_password("Secret123"), role="admin") with db._conn() as c: c.execute("UPDATE users SET verified=1 WHERE email='adm@x.com'") rt = auth._make_refresh_token("adm@x.com", "admin") # старый admin-refresh with db._conn() as c: # админа демоутнули в user c.execute("UPDATE users SET role='user' WHERE email='adm@x.com'") new = auth.refresh_access_token(rt) assert new payload = _jwt.decode(new, auth.SECRET, algorithms=[auth.ALGORITHM]) assert payload["role"] == "user" # роль из БД, не из токена def test_refresh_canonicalizes_email_case(a): """Fable P1/P2: refresh со смешанным регистром sub → канон email (иначе work_dir уезжает).""" import jose.jwt as _jwt auth, db = a db.create_user("mixed@x.com", auth.hash_password("Secret123")) with db._conn() as c: c.execute("UPDATE users SET verified=1 WHERE email='mixed@x.com'") rt = auth._make_refresh_token("Mixed@X.com", "user") # неканоничный регистр new = auth.refresh_access_token(rt) payload = _jwt.decode(new, auth.SECRET, algorithms=[auth.ALGORITHM]) assert payload["sub"] == "mixed@x.com" # канон, а не Mixed@X.com # ---- verify-email rate-limit ---- def test_login_constant_time_for_missing_user(a, monkeypatch): """ENUM-01: check_password прогоняется даже для несуществующего email (dummy-hash) — постоянное время, тайминг не выдаёт существование аккаунта.""" auth, db = a assert auth._DUMMY_HASH.startswith("pbkdf2_sha256$") # dummy = та же PBKDF2-стоимость calls = [] real = auth.check_password monkeypatch.setattr(auth, "check_password", lambda pw, h: calls.append(h) or real(pw, h)) assert auth.authenticate("ghost-nobody@x.com", "whatever", client_ip="9.9.9.9") is None assert calls and calls[0] == auth._DUMMY_HASH # проверка прогнана против dummy def test_verify_email_rate_limited(a): auth, db = a db.create_user("v@x.com", auth.hash_password("Secret123")) db.set_verify_code("v@x.com", "111111") for _ in range(10): auth.verify_email("v@x.com", "000000") # неверные коды r = auth.verify_email("v@x.com", "111111") # даже верный — залочен assert not r["ok"] and "попыток" in r["error"] # ---- инвайт не сгорает на существующем email ---- def test_email_control_chars_rejected(a): """SMTP-01: email с ВНУТРЕННИМ \\r\\n/табом/пробелом → header-инъекция в письмо, отвергается. (краевые пробелы .strip() чистит — не инъекция.)""" auth, _ = a for bad in ["a@x.com\r\nBcc: victim@x.com", "a\t@x.com", "a@x\ncom", "a b@x.com", 'x"@e.com', "x@e.com", "x'>@e.com", "a>b@x.com"]: r = auth.register_user(bad, "Secret123", "inv") assert not r["ok"] and "email" in r["error"].lower(), f"{bad!r} → {r}" def test_invite_not_burned_on_existing_email(a, monkeypatch): """Приглашение не сжигается при повторной регистрации на существующий адрес — ни на подтверждённый (там отказ), ни на неподтверждённый (там с 08.09.2026 регистрация ПРОДОЛЖАЕТСЯ, чтобы человек не оказался заперт). Mutation: перенести работу с приглашением выше проверки существующего адреса → список использованных станет непустым в обоих случаях.""" auth, db = a calls = {"used": []} monkeypatch.setattr("db.use_invite", lambda tok, email: calls["used"].append(tok) or True) # 1. Неподтверждённая учётка: регистрация продолжается, приглашение не тронуто. db.create_user("dup@x.com", auth.hash_password("Secret123")) r = auth.register_user("dup@x.com", "Secret123", "invite-xyz") assert r["ok"], "неподтверждённую регистрацию нужно продолжать, а не отбивать" assert calls["used"] == [] # 2. Подтверждённая учётка: отказ, приглашение тоже не тронуто. db.admin_verify_user("dup@x.com") r2 = auth.register_user("dup@x.com", "Secret123", "invite-xyz") assert not r2["ok"] and "уже существует" in r2["error"] assert calls["used"] == []