"""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 # ---- verify-email rate-limit ---- 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_invite_not_burned_on_existing_email(a, monkeypatch): auth, db = a calls = {"used": []} monkeypatch.setattr("db.use_invite", lambda tok, email: calls["used"].append(tok) or True) db.create_user("dup@x.com", auth.hash_password("Secret123")) r = auth.register_user("dup@x.com", "Secret123", "invite-xyz") assert not r["ok"] and "уже существует" in r["error"] assert calls["used"] == [] # инвайт НЕ тронут