feat(register): поле Телефон/Telegram (в TG, не в БД) + тумблер регистрации + согласие ПДн

Самостоятельная регистрация по email+капча (как была), доработки: опц. поле контакта
(уходит в TG-алерт оператору, в БД не пишется), kill-switch регистрации в админке
(registration_enabled, при выкл /register и /verify-email → 403), обязательный чекбокс
согласия на обработку ПДн (без него → 400) + черновик static/privacy.html (баннер
«проверить у юриста»). Анти-бот переиспользован. +11 тестов.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
anor
2026-07-23 19:04:46 +10:00
co-authored by Claude Opus 4.8
parent 6a8529d432
commit 163d3ad2f8
7 changed files with 406 additions and 7 deletions
+2 -1
View File
@@ -267,7 +267,8 @@ def test_verify_endpoint_grants_bonus_and_audits(client_env, monkeypatch):
db.create_user("hinv@x.ru", "h")
db.create_invite("http-tok", "hinv@x.ru")
r = client.post("/api/register", json={
"email": "hreg@x.ru", "password": "secret1", "invite": "http-tok"})
"email": "hreg@x.ru", "password": "secret1", "invite": "http-tok",
"consent": True})
assert r.status_code == 200
with sqlite3.connect(os.environ["DB_PATH"]) as c:
code = c.execute("SELECT verify_code FROM users WHERE email='hreg@x.ru'").fetchone()[0]
+5 -5
View File
@@ -111,7 +111,7 @@ def client_env(tmp_path, monkeypatch):
def test_register_disposable_400(client_env, monkeypatch):
db, auth, client, invite = client_env
r = client.post("/api/register", json={
"email": "bot@mailinator.com", "password": "secret1", "invite": invite})
"email": "bot@mailinator.com", "password": "secret1", "invite": invite, "consent": True})
assert r.status_code == 400
assert "почт" in r.json()["detail"].lower() or "email" in r.json()["detail"].lower()
assert db.get_user_by_email("bot@mailinator.com") is None
@@ -122,7 +122,7 @@ def test_register_normal_ok_without_captcha_keys(client_env, monkeypatch):
db, auth, client, invite = client_env
monkeypatch.setattr("email_service.send_verification_code", lambda e, c: True)
r = client.post("/api/register", json={
"email": "human@yandex.ru", "password": "secret1", "invite": invite})
"email": "human@yandex.ru", "password": "secret1", "invite": invite, "consent": True})
assert r.status_code == 200
assert db.get_user_by_email("human@yandex.ru") is not None
@@ -137,7 +137,7 @@ def test_register_sends_tg_notification(client_env, monkeypatch):
import alerts
monkeypatch.setattr(alerts, "send_tg", lambda text: sent.append(text) or True)
r = client.post("/api/register", json={
"email": "newbie@yandex.ru", "password": "secret1", "invite": invite})
"email": "newbie@yandex.ru", "password": "secret1", "invite": invite, "consent": True})
assert r.status_code == 200
assert len(sent) == 1 # ровно один алерт на регистрацию
assert "newbie@yandex.ru" in sent[0] # с email нового юзера
@@ -150,7 +150,7 @@ def test_register_normalizes_email_case_in_audit(client_env, monkeypatch):
db, auth, client, invite = client_env
monkeypatch.setattr("email_service.send_verification_code", lambda e, c: True)
r = client.post("/api/register", json={
"email": "Shelemetevay@MAIL.ru", "password": "secret1", "invite": invite})
"email": "Shelemetevay@MAIL.ru", "password": "secret1", "invite": invite, "consent": True})
assert r.status_code == 200
users = {row["username"] for row in db.get_audit_log(action="register") if row.get("username")}
assert "shelemetevay@mail.ru" in users
@@ -178,6 +178,6 @@ def test_failed_register_no_tg_notification(client_env, monkeypatch):
import alerts
monkeypatch.setattr(alerts, "send_tg", lambda text: sent.append(text) or True)
r = client.post("/api/register", json={
"email": "bot@mailinator.com", "password": "secret1", "invite": invite})
"email": "bot@mailinator.com", "password": "secret1", "invite": invite, "consent": True})
assert r.status_code == 400
assert sent == []
+203
View File
@@ -0,0 +1,203 @@
"""Саморегистрация: контакт (телефон/TG) → только в Telegram-алерт, согласие ПДн (152-ФЗ),
kill-switch регистрации в админке.
Решения Юрия (2026-07-23):
- контакт — ОДНО опциональное поле, НЕ хранится в БД (только текст TG-алерта оператору);
- согласие на обработку ПДн обязательно: consent=true в теле, иначе 400 (и на фронте чекбокс);
- app_settings.registration_enabled (дефолт вкл): ВЫКЛ → /api/register и /api/verify-email
отвечают вежливым отказом, новые аккаунты не заводятся; тумблер — админ-only эндпоинт.
Паттерн изоляции — как test_register_antibot.client_env. Red-green: написано ДО реализации.
"""
import importlib
import os
import sys
import pytest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
# Уникальный маркер: ищем его в тексте алерта и в СЫРЫХ байтах файлов БД
CONTACT = "+7-999-123-45-67 (@unique_marker_tg)"
@pytest.fixture()
def env(tmp_path, monkeypatch):
db_path = tmp_path / "t.db"
monkeypatch.setenv("DB_PATH", str(db_path))
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
monkeypatch.setenv("AI_BACKEND", "claude")
monkeypatch.setenv("SESSION_SECRET", "test-secret")
monkeypatch.delenv("SMARTCAPTCHA_SERVER_KEY", raising=False)
monkeypatch.chdir(ROOT)
import db, auth, antibot, claude_bridge, main
importlib.reload(db)
importlib.reload(auth)
importlib.reload(antibot)
importlib.reload(claude_bridge)
importlib.reload(main)
db.init_db()
db.create_user("admin@x", "h", role="admin")
db.create_user("nobody@x", "h", role="user") # non-admin для RBAC-403
import secrets as _s
tok = _s.token_urlsafe(16)
db.create_invite(tok, "admin@x")
monkeypatch.setattr("email_service.send_verification_code", lambda e, c: True)
sent = []
import alerts
monkeypatch.setattr(alerts, "send_tg", lambda text: sent.append(text) or True)
from fastapi.testclient import TestClient
return db, auth, TestClient(main.app), tok, sent, db_path
def _reg_body(invite, **over):
body = {"email": "human@yandex.ru", "password": "secret1",
"invite": invite, "consent": True}
body.update(over)
return body
def _admin_h(auth):
return {"Authorization": "Bearer " + auth._make_token("admin@x", "admin")}
def _db_bytes(db_path) -> bytes:
"""Все файлы БД (t.db + -wal/-shm): контакт не должен быть НИГДЕ на диске."""
blob = b""
for p in db_path.parent.glob(db_path.name + "*"):
blob += p.read_bytes()
return blob
# --- 1. Согласие на обработку ПДн обязательно ---
def test_register_without_consent_400(env):
"""Нет consent → 400, аккаунт НЕ создан, алерт НЕ ушёл.
Mutation: убрать проверку consent в хендлере → 200 → упадёт."""
db, auth, client, invite, sent, _ = env
body = _reg_body(invite)
del body["consent"]
r = client.post("/api/register", json=body)
assert r.status_code == 400
assert "согласие" in r.json()["detail"].lower()
assert db.get_user_by_email("human@yandex.ru") is None
assert sent == []
def test_register_consent_false_400(env):
db, auth, client, invite, sent, _ = env
r = client.post("/api/register", json=_reg_body(invite, consent=False))
assert r.status_code == 400
assert db.get_user_by_email("human@yandex.ru") is None
def test_register_with_consent_ok(env):
"""consent=true → регистрация проходит как раньше (гейт не ломает happy-path)."""
db, auth, client, invite, sent, _ = env
r = client.post("/api/register", json=_reg_body(invite))
assert r.status_code == 200
assert db.get_user_by_email("human@yandex.ru") is not None
# --- 2. Контакт: в TG-алерт уходит, в БД НЕ попадает ---
def test_contact_in_tg_alert_not_in_db(env):
"""Телефон/TG из формы → в тексте send_tg, но НИ В ОДНОМ файле БД (решение Юрия:
«только в Telegram»). Mutation: не передать contact в текст алерта → упадёт;
записать contact в users/audit → упадёт скан сырых байтов БД."""
db, auth, client, invite, sent, db_path = env
r = client.post("/api/register", json=_reg_body(invite, contact=CONTACT))
assert r.status_code == 200
assert len(sent) == 1
assert CONTACT in sent[0]
assert "human@yandex.ru" in sent[0]
assert CONTACT.encode() not in _db_bytes(db_path)
def test_no_contact_dash_in_alert(env):
"""Поле пустое → в алерте «контакт=—» (оператор видит, что связи нет)."""
db, auth, client, invite, sent, _ = env
r = client.post("/api/register", json=_reg_body(invite))
assert r.status_code == 200
assert len(sent) == 1
assert "контакт=—" in sent[0]
# --- 3. Kill-switch регистрации ---
def test_registration_disabled_polite_refusal(env):
"""registration_enabled=off → 403 с вежливым текстом, аккаунт не создан, алерта нет.
Mutation: убрать гейт в /api/register → 200 → упадёт."""
db, auth, client, invite, sent, _ = env
db.set_app_setting("registration_enabled", "off")
r = client.post("/api/register", json=_reg_body(invite))
assert r.status_code == 403
assert "закрыта" in r.json()["detail"].lower()
assert db.get_user_by_email("human@yandex.ru") is None
assert sent == []
def test_verify_email_disabled_too(env):
"""ВЫКЛ закрывает и verify-email: зарегистрированный до выключения аккаунт
не активируется (смысл kill-switch — «новые аккаунты не заводятся»)."""
db, auth, client, invite, sent, _ = env
r = client.post("/api/register", json=_reg_body(invite))
assert r.status_code == 200
db.set_app_setting("registration_enabled", "off")
code = db.get_user_by_email("human@yandex.ru")["verify_code"]
r = client.post("/api/verify-email", json={"email": "human@yandex.ru", "code": code})
assert r.status_code == 403
assert db.get_user_by_email("human@yandex.ru")["verified"] == 0
# --- 4. Админ-тумблер ---
def test_admin_toggle_default_on(env):
db, auth, client, *_ = env
r = client.get("/api/admin/registration", headers=_admin_h(auth))
assert r.status_code == 200
assert r.json()["state"] == "on"
def test_admin_toggle_flips_flag_and_audits(env):
"""POST off → флаг в app_settings + запись в audit. Mutation: убрать set_app_setting
→ get_app_setting останется 'on' → упадёт."""
db, auth, client, *_ = env
r = client.post("/api/admin/registration", headers=_admin_h(auth),
json={"state": "off"})
assert r.status_code == 200
assert db.get_app_setting("registration_enabled", "on") == "off"
assert client.get("/api/admin/registration",
headers=_admin_h(auth)).json()["state"] == "off"
rows = db.get_audit_log(action="registration_toggle")
assert any("off" in (row.get("detail") or "") for row in rows)
# обратно on — тумблер, не одноразовый рубильник
r = client.post("/api/admin/registration", headers=_admin_h(auth),
json={"state": "on"})
assert r.status_code == 200
assert db.get_app_setting("registration_enabled", "on") == "on"
def test_privacy_page_served_with_draft_banner(env):
"""Чекбокс согласия ссылается на /static/privacy.html — страница обязана отдаваться
и явно помечена как ЧЕРНОВИК (не выдаём за готовый юр-документ)."""
db, auth, client, *_ = env
r = client.get("/static/privacy.html")
assert r.status_code == 200
assert "ЧЕРНОВИК" in r.text
assert "персональных данных" in r.text
def test_admin_toggle_rbac_and_validation(env):
db, auth, client, *_ = env
user_h = {"Authorization": "Bearer " + auth._make_token("nobody@x", "user")}
assert client.get("/api/admin/registration", headers=user_h).status_code == 403
r = client.post("/api/admin/registration", headers=user_h, json={"state": "off"})
assert r.status_code == 403
assert db.get_app_setting("registration_enabled", "on") == "on" # не изменился
r = client.post("/api/admin/registration", headers=_admin_h(auth),
json={"state": "banana"})
assert r.status_code == 400