Files
smeta-web/tests/test_auth_hardening.py
T
anorandClaude Opus 4.8 33c71eeb30 fix(security): постоянное время логина (пентест ENUM-01, account enumeration)
Для несуществующего email check_password не вызывался → по таймингу можно было
перечислить валидные аккаунты. Теперь проверка прогоняется всегда (dummy-PBKDF2
той же стоимости). Тест: check_password вызван против _DUMMY_HASH для ghost-юзера.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 13:39:31 +10:00

146 lines
6.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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_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"] == [] # инвайт НЕ тронут