feat(вход): TOTP и recovery
This commit is contained in:
@@ -17,6 +17,10 @@ from jose import jwt
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TOTPRequired(Exception):
|
||||
"""Пароль верный, но нужен второй фактор — не ошибка пароля."""
|
||||
|
||||
SECRET = os.environ.get("SESSION_SECRET", "")
|
||||
if not SECRET:
|
||||
logger.warning("SESSION_SECRET not set!")
|
||||
@@ -144,6 +148,12 @@ def refresh_access_token(refresh_token: str) -> str | None:
|
||||
except Exception:
|
||||
return None
|
||||
if LEGACY_USER and sub == LEGACY_USER:
|
||||
try:
|
||||
import db as _db
|
||||
if _db.has_totp_admin():
|
||||
return None
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
return _issue_access(sub, role)
|
||||
from db import get_user_by_email, get_auth_session
|
||||
u = get_user_by_email(sub)
|
||||
@@ -162,7 +172,8 @@ def refresh_access_token(refresh_token: str) -> str | None:
|
||||
return _make_token(u["email"], u["role"])
|
||||
|
||||
|
||||
def authenticate(username: str, password: str, client_ip: str = "") -> str | None:
|
||||
def authenticate(username: str, password: str, client_ip: str = "",
|
||||
code: str = "", recovery: str = "") -> str | None:
|
||||
"""Authenticate user. Tries legacy env user first, then SQLite.
|
||||
|
||||
Returns JWT token or None.
|
||||
@@ -176,8 +187,15 @@ def authenticate(username: str, password: str, client_ip: str = "") -> str | Non
|
||||
if email_key and _is_locked(email_key, MAX_ATTEMPTS_EMAIL, LOCKOUT_SECONDS_EMAIL):
|
||||
return None
|
||||
|
||||
# 1. Legacy admin user from env vars
|
||||
# 1. Legacy admin user from env vars; при включённом 2FA дверь закрыта.
|
||||
if LEGACY_USER and LEGACY_PASS:
|
||||
try:
|
||||
import db as _db
|
||||
if _db.has_totp_admin():
|
||||
logger.warning("env-admin отключён: у админов включён 2FA")
|
||||
return None
|
||||
except Exception: # noqa: BLE001 — сбой проверки не должен открывать дверь
|
||||
return None
|
||||
# Сравниваем БАЙТЫ: строковое сравнение падает на кириллице
|
||||
# («comparing strings with non-ASCII characters is not supported»), и вход с русским
|
||||
# паролем или адресом отдавал человеку маску сбоя вместо ответа (живой прогон
|
||||
@@ -199,6 +217,28 @@ def authenticate(username: str, password: str, client_ip: str = "") -> str | Non
|
||||
update_password_hash(user["email"], hash_password(password))
|
||||
except Exception: # noqa: BLE001 — апгрейд не должен ломать вход
|
||||
logger.exception("password rehash failed")
|
||||
if user.get("totp_enabled"):
|
||||
if not code and not recovery:
|
||||
raise TOTPRequired()
|
||||
key = f"totp:{user['email']}"
|
||||
if _is_locked(key, 5, 300):
|
||||
return None
|
||||
import json as _json
|
||||
import totp as _totp
|
||||
ok = False
|
||||
if recovery:
|
||||
hashes = _json.loads(user.get("totp_recovery") or "[]")
|
||||
idx = _totp.verify_recovery(recovery, hashes)
|
||||
if idx is not None:
|
||||
hashes.pop(int(idx))
|
||||
from db import consume_recovery
|
||||
consume_recovery(user["email"], _json.dumps(hashes))
|
||||
ok = True
|
||||
else:
|
||||
ok = _totp.verify(user.get("totp_secret") or "", code)
|
||||
if not ok:
|
||||
_record_attempt(key)
|
||||
return None
|
||||
return _issue_access(user["email"], user["role"], client_ip)
|
||||
|
||||
if ip_key:
|
||||
|
||||
@@ -199,7 +199,8 @@ def init_db():
|
||||
if _колонки_нет(conn, "feedback", _col):
|
||||
conn.execute(f"ALTER TABLE feedback ADD COLUMN {_col} {_decl}")
|
||||
for _col, _decl in (("token_version", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("totp_enabled", "INTEGER NOT NULL DEFAULT 0")):
|
||||
("totp_enabled", "INTEGER NOT NULL DEFAULT 0"),
|
||||
("totp_secret", "TEXT"), ("totp_recovery", "TEXT")):
|
||||
if _колонки_нет(conn, "users", _col):
|
||||
conn.execute(f"ALTER TABLE users ADD COLUMN {_col} {_decl}")
|
||||
# Migration: add blocked column if missing
|
||||
@@ -1739,6 +1740,47 @@ def drop_idempotency(key: str) -> None:
|
||||
conn.execute("DELETE FROM admin_idempotency WHERE key = ?", (key,))
|
||||
|
||||
|
||||
def has_totp_admin() -> bool:
|
||||
with _conn() as conn:
|
||||
return bool(conn.execute("SELECT 1 FROM users WHERE role='admin' AND totp_enabled=1 "
|
||||
"AND deleted_at IS NULL LIMIT 1").fetchone())
|
||||
|
||||
|
||||
def set_totp_secret(email: str, secret: str) -> bool:
|
||||
with _conn() as conn:
|
||||
return conn.execute("UPDATE users SET totp_secret = ?, totp_enabled = 0 "
|
||||
"WHERE email = ?", (secret, email.lower().strip())).rowcount > 0
|
||||
|
||||
|
||||
def enable_totp(email: str, recovery_json: str) -> bool:
|
||||
with _conn() as conn:
|
||||
cur = conn.execute("UPDATE users SET totp_enabled = 1, totp_recovery = ?, "
|
||||
"token_version = token_version + 1 WHERE email = ?",
|
||||
(recovery_json, email.lower().strip()))
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def disable_totp(email: str) -> bool:
|
||||
with _conn() as conn:
|
||||
cur = conn.execute("UPDATE users SET totp_enabled = 0, totp_secret = NULL, "
|
||||
"totp_recovery = NULL, token_version = token_version + 1 "
|
||||
"WHERE email = ?", (email.lower().strip(),))
|
||||
return cur.rowcount > 0
|
||||
|
||||
|
||||
def consume_recovery(email: str, recovery_json: str) -> None:
|
||||
with _conn() as conn:
|
||||
conn.execute("UPDATE users SET totp_recovery = ? WHERE email = ?",
|
||||
(recovery_json, email.lower().strip()))
|
||||
|
||||
|
||||
def revoke_user_sessions(email: str) -> int:
|
||||
with _conn() as conn:
|
||||
return conn.execute("UPDATE auth_sessions SET revoked_at = ? "
|
||||
"WHERE username = ? AND revoked_at IS NULL",
|
||||
(time.time(), email.lower().strip())).rowcount
|
||||
|
||||
|
||||
def create_auth_session(jti: str, username: str, role: str, expires_at: float,
|
||||
ip: str | None = None, user_agent: str | None = None,
|
||||
ver: int = 0) -> None:
|
||||
|
||||
@@ -311,6 +311,14 @@
|
||||
- Login выдаёт refresh с jti/ver; тесты: 4 passed; auth suites 23.
|
||||
- P4.5b: TOTP/recovery/env-дверь/2FA-форма — остаток.
|
||||
|
||||
## 4.41. P4.5b — TOTP
|
||||
|
||||
- `totp.py` без зависимости: secret, HOTP/TOTP, provisioning URI, recovery-хэши.
|
||||
- `/api/admin/2fa/setup|enable|disable`; enable отзывает сессии и повышает `token_version`; пароль для disable.
|
||||
- Login: `totp_required` без пароля-ошибки; код/recovery; rate limit 5/5 мин; поле в чате.
|
||||
- Env-админ закрыт, если есть админ с 2FA; env-refresh тоже.
|
||||
- Тесты: `tests/test_totp.py` — 3; RFC 287082.
|
||||
|
||||
## 5. Следующий шаг
|
||||
|
||||
P0.0 design-gate → P0.1 backup/restore → P0.2 (release `feat/topup` отдельно, не в рамках выравнивания).
|
||||
|
||||
@@ -1059,7 +1059,13 @@ async def login(request: Request):
|
||||
username = _as_text(body.get("username"))
|
||||
password = _as_text(body.get("password"))
|
||||
client_ip = _client_ip(request)
|
||||
token = authenticate(username, password, client_ip)
|
||||
from auth import TOTPRequired
|
||||
try:
|
||||
token = authenticate(username, password, client_ip,
|
||||
code=_as_text(body.get("code") or body.get("totp_code")),
|
||||
recovery=_as_text(body.get("recovery")))
|
||||
except TOTPRequired:
|
||||
return {"totp_required": True, "username": username.strip().lower()}
|
||||
# Канон-идентичность (нижний регистр) для аудита/refresh/ответа — совпадает с sub в JWT и
|
||||
# строкой в users; иначе «Shelemetevay@» в журнале != «shelemetevay@» из токена (косяк 07-22).
|
||||
# В authenticate передаём СЫРОЙ ввод (его нормализацию/легаси-сравнение не трогаем).
|
||||
@@ -2804,6 +2810,57 @@ async def admin_feedback(request: Request):
|
||||
return get_feedback(limit)
|
||||
|
||||
|
||||
@app.post("/api/admin/2fa/setup")
|
||||
async def totp_setup(request: Request):
|
||||
_require_admin(request)
|
||||
user = _get_user(request)
|
||||
import totp
|
||||
secret = totp.new_secret()
|
||||
from db import set_totp_secret
|
||||
if not set_totp_secret(user, secret):
|
||||
raise HTTPException(404, "Учётка не найдена")
|
||||
log_action(user, "totp_setup", "POST", "/api/admin/2fa/setup", None, None, 200)
|
||||
return {"secret": secret, "uri": totp.provisioning_uri(secret, user)}
|
||||
|
||||
|
||||
@app.post("/api/admin/2fa/enable")
|
||||
async def totp_enable(request: Request):
|
||||
_require_admin(request)
|
||||
user = _get_user(request)
|
||||
body = await _тело(request)
|
||||
code = _as_text(body.get("code")).strip()
|
||||
from db import get_user_by_email, enable_totp, revoke_user_sessions
|
||||
import totp, json
|
||||
u = get_user_by_email(user)
|
||||
if not u or not u.get("totp_secret"):
|
||||
raise HTTPException(400, "Сначала получите секрет")
|
||||
if not totp.verify(u["totp_secret"], code):
|
||||
raise HTTPException(400, "Неверный код")
|
||||
codes = totp.new_recovery_codes()
|
||||
hashes = [totp.hash_recovery(c) for c in codes]
|
||||
if not enable_totp(user, json.dumps(hashes)):
|
||||
raise HTTPException(404, "Учётка не найдена")
|
||||
revoke_user_sessions(user)
|
||||
log_action(user, "totp_enabled", "POST", "/api/admin/2fa/enable", None, None, 200)
|
||||
return {"ok": True, "recovery_codes": codes, "reauthenticate": True}
|
||||
|
||||
|
||||
@app.post("/api/admin/2fa/disable")
|
||||
async def totp_disable(request: Request):
|
||||
_require_admin(request)
|
||||
user = _get_user(request)
|
||||
body = await _тело(request)
|
||||
from auth import check_password
|
||||
from db import get_user_by_email, disable_totp, revoke_user_sessions
|
||||
u = get_user_by_email(user)
|
||||
if not u or not check_password(_as_text(body.get("password")), u["password_hash"]):
|
||||
raise HTTPException(401, "Пароль неверный")
|
||||
disable_totp(user)
|
||||
revoke_user_sessions(user)
|
||||
log_action(user, "totp_disabled", "POST", "/api/admin/2fa/disable", None, None, 200)
|
||||
return {"ok": True, "reauthenticate": True}
|
||||
|
||||
|
||||
@app.post("/api/admin/feedback/{feedback_id}/status")
|
||||
async def admin_feedback_status(feedback_id: int, request: Request):
|
||||
_require_admin(request)
|
||||
|
||||
+20
-1
@@ -420,6 +420,7 @@ html { color-scheme: light; }
|
||||
<div id="login-error" role="alert"></div>
|
||||
<input type="text" id="login-user" aria-describedby="dev-banner" placeholder="Email или логин" aria-label="Email или логин" autocomplete="username" required>
|
||||
<input type="password" id="login-pass" placeholder="Пароль" aria-label="Пароль" autocomplete="current-password" required>
|
||||
<input type="text" id="login-totp" placeholder="Код 2FA или recovery-код" aria-label="Код 2FA" autocomplete="one-time-code" inputmode="numeric" style="display:none">
|
||||
<button type="submit">Войти</button>
|
||||
<p class="register-link">Нет аккаунта? <a href="/register">Зарегистрироваться</a></p>
|
||||
<p class="register-link"><a href="#" id="forgot-link" onclick="return openReset(event)">Забыли пароль?</a></p>
|
||||
@@ -1154,19 +1155,31 @@ async function doLogin(e) {
|
||||
e.preventDefault();
|
||||
const user = document.getElementById('login-user').value;
|
||||
const pass = document.getElementById('login-pass').value;
|
||||
const totpInput = document.getElementById('login-totp');
|
||||
const body = {username: user, password: pass};
|
||||
if (totpInput.style.display !== 'none' && totpInput.value.trim()) {
|
||||
const v = totpInput.value.trim();
|
||||
if (/^\d{6}$/.test(v)) body.code = v; else body.recovery = v;
|
||||
}
|
||||
hideBox('login-notice');
|
||||
причинаВыхода = null; // дальше говорит ответ на этот вход
|
||||
try {
|
||||
const r = await fetch(API + '/api/login', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({username: user, password: pass})
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
if (!r.ok) {
|
||||
showBox('login-error', await serverReason(r, 'Не удалось войти. Проверьте почту и пароль.'));
|
||||
return false;
|
||||
}
|
||||
const data = await r.json();
|
||||
if (data.totp_required) {
|
||||
totpInput.style.display = '';
|
||||
totpInput.focus();
|
||||
showBox('login-notice', 'Введите код из приложения-аутентификатора.');
|
||||
return false;
|
||||
}
|
||||
token = data.token;
|
||||
localStorage.setItem('token', token);
|
||||
if (data.refresh_token) localStorage.setItem('refresh_token', data.refresh_token);
|
||||
@@ -1274,6 +1287,12 @@ async function tryRefreshToken() {
|
||||
return false;
|
||||
}
|
||||
const data = await r.json();
|
||||
if (data.totp_required) {
|
||||
totpInput.style.display = '';
|
||||
totpInput.focus();
|
||||
showBox('login-notice', 'Введите код из приложения-аутентификатора.');
|
||||
return false;
|
||||
}
|
||||
token = data.token;
|
||||
localStorage.setItem('token', token);
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
"""P4.5b1: TOTP, recovery, login challenge, отзыв старых сессий."""
|
||||
import importlib
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def env(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
|
||||
monkeypatch.setenv("SESSION_SECRET", "test-secret")
|
||||
monkeypatch.setenv("AI_BACKEND", "claude")
|
||||
monkeypatch.chdir(ROOT)
|
||||
import auth
|
||||
import db
|
||||
import main
|
||||
import totp
|
||||
for m in (auth, db, main, totp):
|
||||
importlib.reload(m)
|
||||
db.init_db()
|
||||
db.create_user("boss@x", auth.hash_password("Passw0rd!ok"), role="admin")
|
||||
db.admin_verify_user("boss@x")
|
||||
from fastapi.testclient import TestClient
|
||||
client = TestClient(main.app)
|
||||
token = client.post("/api/login", json={"username": "boss@x",
|
||||
"password": "Passw0rd!ok"}).json()["token"]
|
||||
h = {"Authorization": "Bearer " + token}
|
||||
return auth, db, totp, client, h, token
|
||||
|
||||
|
||||
def test_totp_rfc_vector():
|
||||
import totp
|
||||
assert totp.code_at("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", 1) == "287082"
|
||||
assert totp.verify("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", "287082", at=59)
|
||||
assert not totp.verify("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", "000000", at=59)
|
||||
|
||||
|
||||
def test_enable_login_challenge_and_recovery(env):
|
||||
auth, db, totp, client, h, old = env
|
||||
s = client.post("/api/admin/2fa/setup", headers=h).json()
|
||||
code = totp.code_at(s["secret"], int(time.time() // 30))
|
||||
e = client.post("/api/admin/2fa/enable", json={"code": code}, headers=h)
|
||||
assert e.status_code == 200, e.text
|
||||
codes = e.json()["recovery_codes"]
|
||||
assert len(codes) == 8
|
||||
# включение отзывает текущую сессию
|
||||
assert client.get("/api/admin/v2/ping", headers=h).status_code == 401
|
||||
|
||||
r = client.post("/api/login", json={"username": "boss@x", "password": "Passw0rd!ok"})
|
||||
assert r.status_code == 200 and r.json().get("totp_required") is True
|
||||
assert "token" not in r.json()
|
||||
bad = client.post("/api/login", json={"username": "boss@x", "password": "Passw0rd!ok",
|
||||
"code": "000000"})
|
||||
assert bad.status_code == 401
|
||||
good = client.post("/api/login", json={"username": "boss@x", "password": "Passw0rd!ok",
|
||||
"code": totp.code_at(s["secret"], int(time.time() // 30))})
|
||||
assert good.status_code == 200 and good.json().get("token")
|
||||
recovery = client.post("/api/login", json={"username": "boss@x",
|
||||
"password": "Passw0rd!ok",
|
||||
"recovery": codes[0]})
|
||||
assert recovery.status_code == 200 and recovery.json().get("token")
|
||||
|
||||
|
||||
def test_env_admin_door_closes_when_any_admin_has_2fa(env, monkeypatch):
|
||||
auth, db, totp, client, h, token = env
|
||||
with db._conn() as c:
|
||||
c.execute("UPDATE users SET totp_enabled=1 WHERE email='boss@x'")
|
||||
monkeypatch.setenv("SMETA_USER", "envboss")
|
||||
monkeypatch.setenv("SMETA_PASS", "envpass")
|
||||
import importlib
|
||||
import auth as a2
|
||||
importlib.reload(a2)
|
||||
assert a2.authenticate("envboss", "envpass") is None
|
||||
refresh = a2._make_refresh_token("envboss", "admin")
|
||||
assert a2.refresh_access_token(refresh) is None
|
||||
@@ -0,0 +1,57 @@
|
||||
"""TOTP/RFC 6238 без внешней зависимости + recovery-коды."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
import struct
|
||||
import time
|
||||
|
||||
STEP = 30
|
||||
DIGITS = 6
|
||||
|
||||
|
||||
def new_secret() -> str:
|
||||
return base64.b32encode(secrets.token_bytes(20)).decode().rstrip("=")
|
||||
|
||||
|
||||
def _key(secret: str) -> bytes:
|
||||
return base64.b32decode(secret.upper() + "=" * ((8 - len(secret) % 8) % 8))
|
||||
|
||||
|
||||
def code_at(secret: str, counter: int) -> str:
|
||||
digest = hmac.new(_key(secret), struct.pack(">Q", counter), hashlib.sha1).digest()
|
||||
off = digest[-1] & 0x0F
|
||||
num = struct.unpack(">I", digest[off:off + 4])[0] & 0x7FFFFFFF
|
||||
return str(num % 10 ** DIGITS).zfill(DIGITS)
|
||||
|
||||
|
||||
def verify(secret: str, code: str, at: float | None = None, window: int = 1) -> bool:
|
||||
if not secret or not code or not str(code).isdigit() or len(str(code)) != DIGITS:
|
||||
return False
|
||||
counter = int((time.time() if at is None else at) // STEP)
|
||||
return any(hmac.compare_digest(code_at(secret, counter + d), str(code))
|
||||
for d in range(-window, window + 1))
|
||||
|
||||
|
||||
def provisioning_uri(secret: str, email: str, issuer: str = "smeta") -> str:
|
||||
from urllib.parse import quote
|
||||
label = quote(f"{issuer}:{email}")
|
||||
return f"otpauth://totp/{label}?secret={secret}&issuer={quote(issuer)}&digits=6&period=30"
|
||||
|
||||
|
||||
def new_recovery_codes(n: int = 8) -> list[str]:
|
||||
return [secrets.token_hex(5) for _ in range(n)]
|
||||
|
||||
|
||||
def hash_recovery(code: str) -> str:
|
||||
return hashlib.sha256(code.strip().lower().encode()).hexdigest()
|
||||
|
||||
|
||||
def verify_recovery(code: str, hashes: list[str]) -> str | None:
|
||||
h = hash_recovery(code)
|
||||
for i, x in enumerate(hashes):
|
||||
if hmac.compare_digest(h, x):
|
||||
return str(i)
|
||||
return None
|
||||
Reference in New Issue
Block a user