Files
smeta-web/tests/test_auth_hardening.py
T
anorandClaude Opus 4.8 427d92fcb0 fix(security): правки по финальному Fable-sweep (регрессий нет, добиты латентные)
Fable подтвердил: явных регрессий от сессии нет. Добиты найденные им дефекты,
в т.ч. прошедшие ровно по только что тронутому коду:

- auth refresh (P1): роль и КАНОН email теперь из свежей записи БД, не из клиентского
  токена. Было: демоутнутый admin оставался админом до 7 дней; refresh со смешанным
  регистром email уводил work_dir/историю в другую папку (тихая пропажа файлов).
- /api/chat (P2): валидация tab_id ДО стрима/save_message → чистый 400 вместо
  грязного обрыва генератора с мусорной строкой в БД.
- search_engine (P2): лок на _morph.parse — после выноса поиска в to_thread
  pymorphy2 дёргается конкурентно (не гарантированно потокобезопасен).
- долг: удалены мёртвые _ssr_jobs/_require_job_owner/_auth_dep/_import_ssr_scripts,
  устаревшие записи _AUDIT_MAP, сломанные scripts/test_*batch.py (импортили удалённый batch).

Тесты: +демоут-admin, +канон-email, +chat-bad-tab-400. 306 passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 21:05:02 +10:00

134 lines
5.6 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_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"] == [] # инвайт НЕ тронут