diff --git a/tests/test_login_flow.py b/tests/test_login_flow.py new file mode 100644 index 0000000..a3cbe2d --- /dev/null +++ b/tests/test_login_flow.py @@ -0,0 +1,157 @@ +# -*- coding: utf-8 -*- +"""login 端点失败路径契约(超长密码 / 邮箱登录 / 锁定 / 封禁禁用 / 2FA 前置 / 异常映射)。 + +test_auth_routes.py 覆盖成功主路径;本文件钉住 login 的各拒绝分支, +作为 login 拆解的等价性验证器。 +""" +import pytest +from fastapi.testclient import TestClient + +import auth_system as auth +import core.db as db + +SECRET = 'login-flow-test-secret' +USER_PW = 'UserPass123' +ADMIN_PW = 'AdminPass123' + + +@pytest.fixture() +def env(tmp_path, monkeypatch): + db_path = tmp_path / 'site.db' + monkeypatch.setattr(auth.db, 'DATA_DIR', tmp_path) + monkeypatch.setattr(auth.db, 'DB_PATH', db_path) + monkeypatch.setattr(auth.db, 'BACKUP_DIR', tmp_path / 'backups') + monkeypatch.setattr(auth.db, 'SECRET_KEY_PATH', tmp_path / 'secret.key') + monkeypatch.setattr(db, 'DATA_DIR', tmp_path) + monkeypatch.setattr(db, 'DB_PATH', db_path) + auth.init_db() + + conn = auth.get_conn() + conn.execute('INSERT INTO users (username, password_hash, salt, role, duration_seconds, ' + 'status, login_seq, created_at, email) VALUES (?,?,?,?,?,1,0,?,?)', + ('mailuser', auth._hash_new(USER_PW), '', 'user', 97, 1730000000, + 'mail@example.com')) + conn.execute('INSERT INTO users (username, password_hash, salt, role, duration_seconds, ' + 'status, login_seq, created_at) VALUES (?,?,?,?,?,1,0,?)', + ('bossuser', auth._hash_new(ADMIN_PW), '', 'admin', -1, 1730000000)) + conn.commit() + conn.close() + + monkeypatch.setattr('web.deps.secret_key', lambda: SECRET) + + import web.auth_state as auth_state + auth_state._LOGIN_FAILS.clear() + auth_state._LOGIN_FAIL_LOGGED.clear() + auth_state._ADMIN_2FA.clear() + + from web.app import create_app + return TestClient(create_app()) + + +def _logs(conn, action: str) -> list[tuple[str, str]]: + rows = conn.execute('SELECT type, detail FROM logs WHERE action = ?', (action,)).fetchall() + return [(r['type'], r['detail']) for r in rows] + + +def test_overlong_password_rejected_without_pbkdf2(env, monkeypatch): + """超长密码(>128):不碰 PBKDF2,直接按密码错误拒绝。""" + def _boom(*a, **k): + raise AssertionError('verify_login must not be called') + + monkeypatch.setattr(auth, 'verify_login', _boom) + r = env.post('/auth/login', json={'username': 'mailuser', 'password': 'x' * 129}) + assert r.status_code == 400 + assert r.json()['message'] == '用户名或密码错误' + + +def test_email_login_resolves_account(env): + """邮箱登录:按归一化邮箱解析真实账号(大小写不敏感)。""" + r = env.post('/auth/login', json={'username': 'MAIL@Example.com', 'password': USER_PW}) + assert r.status_code == 200 + assert r.json()['success'] is True + assert 'session' in r.cookies + + +def test_unknown_email_locks_by_normalized_email(env): + """邮箱登录失败锁定:键用归一化邮箱(不含大小写变体绕过)。""" + for _ in range(5): + r = env.post('/auth/login', json={'username': 'Ghost@Example.com', 'password': 'nope'}) + assert r.json()['message'] == '用户名或密码错误' + r = env.post('/auth/login', json={'username': 'ghost@example.com', 'password': USER_PW}) + assert '尝试过于频繁' in r.json()['message'] + + import web.auth_state as auth_state + assert 'ghost@example.com' in auth_state._LOGIN_FAILS + + +def test_locked_log_written_once(env): + """锁定周期内重复被封尝试只落一条 fail 日志。""" + for _ in range(5): + env.post('/auth/login', json={'username': 'mailuser', 'password': 'nope'}) + for _ in range(3): + env.post('/auth/login', json={'username': 'mailuser', 'password': USER_PW}) + conn = auth.get_conn() + locked_logs = [d for t, d in _logs(conn, '登录') if d == '失败次数过多,临时锁定'] + conn.close() + assert len(locked_logs) == 1 + + +def test_banned_account_message(env, monkeypatch): + """封禁账号(status=2):文案带原因 + 失败日志。""" + conn = auth.get_conn() + conn.execute("UPDATE users SET status=2, ban_reason='刷单' WHERE username='mailuser'") + conn.commit() + conn.close() + + r = env.post('/auth/login', json={'username': 'mailuser', 'password': USER_PW}) + assert r.json()['message'] == '账号已被封禁:刷单,请联系管理员' + conn = auth.get_conn() + assert ('fail', '封禁账号尝试登录: 刷单') in _logs(conn, '登录') + conn.close() + + +def test_disabled_account_message(env): + """禁用账号(status=0):固定文案,无原因拼接。""" + conn = auth.get_conn() + conn.execute("UPDATE users SET status=0 WHERE username='mailuser'") + conn.commit() + conn.close() + + r = env.post('/auth/login', json={'username': 'mailuser', 'password': USER_PW}) + assert r.json()['message'] == '账号已被禁用,请联系管理员' + + +def test_admin_without_email_blocked_fail_closed(env): + """管理员未绑定邮箱:fail-closed,不签发票据。""" + r = env.post('/auth/login', json={'username': 'bossuser', 'password': ADMIN_PW}) + assert r.json()['message'] == '管理员账号未绑定邮箱,请联系管理员先完成绑定' + assert 'session' not in r.cookies + conn = auth.get_conn() + assert ('fail', '未绑定邮箱,两步验证不可用') in _logs(conn, '管理员登录') + conn.close() + + +def test_geo_ban_bumps_seq_again(env, monkeypatch): + """异地多省封禁:login_seq 再递增一次(已签发中的会话全部顶下线)。""" + def _banned(user, ip): + return True, {'province': 'X'} + + monkeypatch.setattr(auth, 'record_login_location', _banned) + r = env.post('/auth/login', json={'username': 'mailuser', 'password': USER_PW}) + assert r.json()['message'] == '检测到账号在多个省份异常登录,已自动封禁,请联系管理员' + + conn = auth.get_conn() + seq = conn.execute("SELECT login_seq FROM users WHERE username='mailuser'").fetchone()[0] + conn.close() + assert seq == 2 # 会话递增 + 封禁再递增 + + +def test_unexpected_error_is_500(env, monkeypatch): + """非预期异常:泛化文案 + HTTP 500。""" + def _boom(*a, **k): + raise RuntimeError('db busy') + + monkeypatch.setattr(auth, 'verify_login', _boom) + r = env.post('/auth/login', json={'username': 'mailuser', 'password': USER_PW}) + assert r.status_code == 500 + assert r.json()['message'] == '登录失败,请稍后重试' diff --git a/web/routers/auth.py b/web/routers/auth.py index 839cd5a..f5c3397 100644 --- a/web/routers/auth.py +++ b/web/routers/auth.py @@ -101,18 +101,99 @@ async def ann_seen(user: Annotated[SiteUser | None, Depends(current_user)]): return success() -@router.post('/auth/login') -async def login(request: Request): - """登录:密码校验(含邮箱登录)、失败锁定、管理员两步验证转票据。""" +async def _resolve_login_identity(username: str) -> tuple: + """身份解析:含 @ 按归一化邮箱解析真实账号。 + + 返回 (邮箱命中的用户或 None, 锁定计数键)。邮箱登录的锁定键用 + 真实用户名(命中时)或归一化邮箱(未命中时),防大小写变体绕过。 + """ + if '@' not in username: + return None, username + iuser = await asyncio.to_thread(auth.get_user_by_email, username) + lock_name = iuser['username'] if iuser else (auth._normalize_email(username) or username) + return iuser, lock_name + + +async def _allow_login_attempt(lock_name: str, ip: str) -> bool: + """失败锁定闸:允许尝试返回 True;锁定时落一条一次性审计日志并返回 False。""" + from web.auth_state import ( + _login_fail_check, + _login_fail_locked_log_once, + ) + + if _login_fail_check(lock_name): + return True + if _login_fail_locked_log_once(lock_name): + await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip, + '登录', '失败次数过多,临时锁定') + return False + + +async def _check_account_status(user, lock_name: str, ip: str): + """账号状态闸:封禁(原因落日志)/禁用;通过返回 None。""" + keys = user.keys() + status = user['status'] if 'status' in keys else 1 + if status == 2: + reason = user['ban_reason'] if 'ban_reason' in keys else '' + await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip, + '登录', f'封禁账号尝试登录: {reason}') + return error('账号已被封禁' + (f':{reason}' if reason else '') + ',请联系管理员') + if status == 0: + return error('账号已被禁用,请联系管理员') + return None + + +async def _admin_two_factor_response(user, lock_name: str, ip: str) -> JSONResponse: + """管理员登录一律转两步验证通道(密码正确才签发票据;未绑定邮箱 fail-closed)。""" from web.auth_state import ( _admin2fa_issue, _admin2fa_mask, - _login_fail_check, - _login_fail_clear, - _login_fail_locked_log_once, - _login_fail_record, ) + admin_email = user['email'] if 'email' in user.keys() else '' + if not admin_email: + await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip, + '管理员登录', '未绑定邮箱,两步验证不可用') + return error('管理员账号未绑定邮箱,请联系管理员先完成绑定') + ticket = _admin2fa_issue(user) + await asyncio.to_thread(auth.add_log, 'success', lock_name, ip, + '管理员登录', '密码验证通过,待邮箱验证') + return success({'ticket': ticket, 'email_masked': _admin2fa_mask(admin_email), + 'username': user['username'], 'admin_2fa': True}, + '密码验证通过,请完成邮箱验证') + + +async def _user_session_response(user, ip: str) -> JSONResponse: + """普通用户建会话:login_seq 原子递增顶号 → 异地多省封禁闸 → 签发 Cookie。""" + uid = int(user['id']) + now = int(time.time()) + await db.execute( + 'UPDATE users SET last_active = ?, last_login = ?, ' + 'login_seq = COALESCE(login_seq, 0) + 1 WHERE id = ?', (now, now, uid)) + seq_row = await repo.get_user_by_id(uid) + seq = int((seq_row or {}).get('login_seq') or 1) + + banned, _info = await asyncio.to_thread(auth.record_login_location, user, ip) + if banned: + await db.execute( + 'UPDATE users SET login_seq = COALESCE(login_seq, 0) + 1 WHERE id = ?', (uid,)) + return error('检测到账号在多个省份异常登录,已自动封禁,请联系管理员') + + fresh = await repo.get_user_by_id(uid) or {} + return _login_response({ + 'user': _user_public(fresh), + 'duration_text': _format_credits(int(fresh.get('duration_seconds') or 0)), + 'redirect': 'admin' if fresh.get('role') == 'admin' else 'user', + }, '登录成功', uid, seq) + + +@router.post('/auth/login') +async def login(request: Request): + """登录:密码校验(含邮箱登录)、失败锁定、管理员两步验证转票据。 + + 分支顺序:超长密码直拒 → 身份解析 → 失败锁定 → 密码校验 → + 状态闸(封禁/禁用)→ 管理员转 2FA → 普通用户建会话(含异地封禁)。 + """ data = await _request_data(request) username = str(data.get('username') or '').strip() password = str(data.get('password') or '') @@ -123,73 +204,27 @@ async def login(request: Request): return error('用户名或密码错误') try: - # 邮箱登录:含 @ 按归一化邮箱解析真实账号;锁定 key 用真实用户名 - if '@' in username: - iuser = await asyncio.to_thread(auth.get_user_by_email, username) - lock_name = iuser['username'] if iuser else (auth._normalize_email(username) or username) - else: - iuser = None - lock_name = username - - if not _login_fail_check(lock_name): - if _login_fail_locked_log_once(lock_name): - await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip, - '登录', '失败次数过多,临时锁定') + iuser, lock_name = await _resolve_login_identity(username) + if not await _allow_login_attempt(lock_name, ip): return error('尝试过于频繁,该账号已临时锁定,请 10 分钟后再试') verify_name = iuser['username'] if iuser is not None else username user = await asyncio.to_thread(auth.verify_login, verify_name, password) if not user: + from web.auth_state import _login_fail_record _login_fail_record(lock_name) return error('用户名或密码错误') - keys = user.keys() - status = user['status'] if 'status' in keys else 1 - if status == 2: - reason = user['ban_reason'] if 'ban_reason' in keys else '' - await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip, - '登录', f'封禁账号尝试登录: {reason}') - return error('账号已被封禁' + (f':{reason}' if reason else '') + ',请联系管理员') - if status == 0: - return error('账号已被禁用,请联系管理员') + status_err = await _check_account_status(user, lock_name, ip) + if status_err is not None: + return status_err + from web.auth_state import _login_fail_clear _login_fail_clear(lock_name) if user['role'] == 'admin': - # 管理员一律转两步验证通道(密码正确才签发票据;未绑定邮箱 fail-closed) - admin_email = user['email'] if 'email' in keys else '' - if not admin_email: - await asyncio.to_thread(auth.add_log, 'fail', lock_name, ip, - '管理员登录', '未绑定邮箱,两步验证不可用') - return error('管理员账号未绑定邮箱,请联系管理员先完成绑定') - ticket = _admin2fa_issue(user) - await asyncio.to_thread(auth.add_log, 'success', lock_name, ip, - '管理员登录', '密码验证通过,待邮箱验证') - return success({'ticket': ticket, 'email_masked': _admin2fa_mask(admin_email), - 'username': user['username'], 'admin_2fa': True}, - '密码验证通过,请完成邮箱验证') - - # 普通用户:建立会话(原子递增 login_seq 顶号) - uid = int(user['id']) - now = int(time.time()) - await db.execute( - 'UPDATE users SET last_active = ?, last_login = ?, ' - 'login_seq = COALESCE(login_seq, 0) + 1 WHERE id = ?', (now, now, uid)) - seq_row = await repo.get_user_by_id(uid) - seq = int((seq_row or {}).get('login_seq') or 1) - - banned, _info = await asyncio.to_thread(auth.record_login_location, user, ip) - if banned: - await db.execute( - 'UPDATE users SET login_seq = COALESCE(login_seq, 0) + 1 WHERE id = ?', (uid,)) - return error('检测到账号在多个省份异常登录,已自动封禁,请联系管理员') - - fresh = await repo.get_user_by_id(uid) or {} - return _login_response({ - 'user': _user_public(fresh), - 'duration_text': _format_credits(int(fresh.get('duration_seconds') or 0)), - 'redirect': 'admin' if fresh.get('role') == 'admin' else 'user', - }, '登录成功', uid, seq) + return await _admin_two_factor_response(user, lock_name, ip) + return await _user_session_response(user, ip) except Exception: return error('登录失败,请稍后重试', 500)