This repository has been archived on 2026-10-02. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
snowy-yang 96af56cc27 refactor: auth_system 全面异步化(aiosqlite),拆掉 web/services 层的 to_thread 桥接
拆掉两类垫片的最后一处:auth_system 原为同步 sqlite3 栈,web 层与 services 的
worker 只能靠 asyncio.to_thread 逐个桥接才不阻塞事件循环——每次 DB 访问都白付一次
线程池调度,且「同步调异步」的边界散落在 100+ 个调用点。B1 已把 worker 变成协程,
本批把访问层本身也迁到原生异步,两条线在此合拢。

改动(按子系统):
- auth_system:db.py 照 core/db.py 现有范式重建为原生异步访问层(aiosqlite + WAL)
  ——读路径 _q 每次独立连接、无锁、可并发;写路径 _x / write_transaction 用
  asyncio.Lock 串行化,写者不阻塞读者。users / cards / credits / ledger / logs /
  settings / mail / geo / backup 九模块随之全部 async/await;security.py 是纯计算
  (pbkdf2/normalize)不动。__init__ 去掉 _DB_LOCK 与 get_conn 导出。
- web:app / deps / billing / tasks_registry 与 routers/{admin_site,auth,music,
  register,user} 直接 await,拆掉包裹的 to_thread。deps.secret_key 改 async,
  连带 _parse_cookie 也 async(会话解析要读密钥)。
- services:_taskcore / tasks / downloads / podcast 的账本调用与查询直接 await。
  4 处 start_task 调用点(download.py)确认已 await。

设计取舍(为什么这么做,而不是直接包一层):
- 锁按**事件循环**隔离(_LOOP_LOCKS 以 id(loop) 为键):asyncio.Lock 绑定创建它的
  loop,应用主 loop 与测试各自的 loop 并存,跨 loop 复用会抛 "bound to a different
  event loop"。
- WAL 切换用**独立锁** _wal_lock 而非 _write_lock:execute() 已持写锁,再在锁内
  connect→_configure 会自锁死(asyncio.Lock 非重入)。切换 + 标记在专用锁内串行并
  二次复查,否则并发首连会同时执行 PRAGMA journal_mode=WAL 争排他锁报
  database is locked(core/db.py 同款教训,实测复现)。
- force_wal 保留:journal_mode 持久化在库文件头,库文件被删重建时新文件不继承,
  必须重设。exists() 判定须在 aiosqlite.connect **之前**(connect 会创建空文件)。
- connect() 用 DB_PATH.parent 兜底建目录,优于 DATA_DIR:生产两者相同,但测试
  monkeypatch 只换 DB_PATH 时兜底仍能命中正确目录。

留在 to_thread 上的仅剩**正当的阻塞卸载**,不是同步门面:PBKDF2 的 10 万次迭代
(登录链路每次都要跑)、smtplib 发信、备份文件的 copy2 / os.replace、secret.key
的文件 IO。原有 aria2 / downloader / zip 侧的 to_thread 未动。

不变量逐条保持(迁移只改执行模型,不改语义):
- ledger_settle 幂等:账本非 open 直接 return 0,重启后重放不重复退款;
- 终态先到先得:_mark_task_terminal 对已 done/error/canceled 的任务直接 return,
  堵住 canceled→error 的非法迁移边;
- settle 必须在任务锁**外**调用(ledger_settle 要抢 SQLite 写锁,busy 最长 15s,
  持任务锁会让全站进度/提交/取消随库停摆);
- reserve_and_open 的预扣与开账同事务,消除原两步之间的崩溃丢账窗口。

路径真源红线:DATA_DIR / DB_PATH / BACKUP_DIR / SECRET_KEY_PATH 仍是 auth_system.db
的**模块全局**(用与 core.db 相同的表达式,但**不是**它的别名)。测试只 patch
auth_system.db.*,若改成 core.db 的别名会静默把测试写到生产库。已核 data/site.db
读写前后 sha256 完全一致。
顺带清掉 get_conn:迁移后它只剩「转调 connect()」一层空壳、全仓零消费者(测试
直接开裸连接、备份用 db.connect()),保留等于留一条「拿裸连接自己写」的口子。

测试:19 个文件同步迁移——10 个文件的 web.deps.secret_key 替身改 async;
test_db_conn.py 的多线程首连用例按异步语义拆成 2 条(单 loop gather(16) 覆盖批量
并发首连、WAL 就绪后 8 线程各自 loop 建连覆盖跨 loop);test_billing_scope.py 去掉
多余的 @pytest.mark.anyio;被 await 且**正常返回**的 monkeypatch 替身一律改 async
(仅 raise 的同步替身仍可用)。

门禁:ruff 全过 / pyright 0-0-0(standard 模式含 tests 与顶层模块)/ pytest
384 项全绿(0 失败 0 error 0 skipped;383→384 因 test_db_conn 拆用例)。
data/site.db 读写前后 sha256 一致(a19f5db…6487),无 -wal/-shm 边车残留。

下一步 B3:删 core/sync_http.py、core/async_bridge.py、core/http_errors.py 及
 tests/test_async_bridge.py——三者在生产侧已零消费者(http_errors 仅 sync_http
 自用,requests 已非声明依赖)。
2026-09-28 20:13:19 +08:00

334 lines
14 KiB
Python
Raw Permalink 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.
# -*- coding: utf-8 -*-
"""认证操作端点。
端点:
- POST /api/v1/auth/logout ↔ Flask /auth/logout(顶号:递增 login_seq + 删 Cookie)
- POST /api/v1/auth/heartbeat ↔ Flask /auth/heartbeat
- POST /api/v1/auth/ann_seen ↔ Flask /auth/ann_seen
- POST /api/v1/auth/login ↔ Flask /auth/login(密码校验 + 失败锁定 + 管理员 2FA 转票据)
设计:
- 登录失败锁定与管理员 2FA 票据表**复用 web.auth_state 的模块级状态**,全进程共享同一份
计数/票据,避免「换个框架打就绕过锁定」。
- 密码校验(PBKDF2,10 万次迭代,CPU 密集)已在 auth_system.verify_login 内部经
asyncio.to_thread 卸载;其余 auth_system 调用已迁移为原生异步(aiosqlite)直接 await。
- 会话 Cookie 由 core.session 签发(沿用同一格式与密钥,存量会话继续有效),删 Cookie 亦同口径。
"""
import os
import time
from typing import Annotated
from fastapi import APIRouter, Depends, Request
from fastapi.responses import JSONResponse
import auth_system as auth
import web.deps as deps
from core import db, repo
from core import session as cs
from web import ratelimit
from web.deps import SiteUser, current_user
from web.request_utils import (
request_data as _request_data,
)
from web.response import error, success
from web.serializers import format_credits as _format_credits
from web.serializers import user_public as _user_public
router = APIRouter()
SESSION_COOKIE = cs.COOKIE_NAME
_SESSION_MAX_AGE = cs.SESSION_MAX_AGE
def _cookie_kwargs() -> dict:
secure = os.environ.get('ENABLE_SECURE_COOKIE', '').strip().lower() in ('1', 'true', 'yes')
return {'max_age': _SESSION_MAX_AGE, 'httponly': True, 'samesite': 'lax',
'path': '/', 'secure': secure}
async def _login_response(payload: dict, message: str, uid: int, seq: int) -> JSONResponse:
"""构造带会话 Cookie 的成功响应(沿用同一 Cookie 格式)。"""
resp = JSONResponse(content={'status': 200, 'success': True, 'message': message, 'data': payload})
cookie = cs.dumps(await deps.secret_key(), {
'site_uid': uid, 'site_uid_seq': seq, 'site_uid_ts': int(time.time()),
})
resp.set_cookie(SESSION_COOKIE, cookie, **_cookie_kwargs())
return resp
@router.post('/auth/logout')
async def logout(user: Annotated[SiteUser | None, Depends(current_user)]):
"""退出登录:递增 login_seq 使本账号全部已签发会话失效,并删除本机 Cookie。"""
if user is not None:
try:
await db.execute(
'UPDATE users SET login_seq = COALESCE(login_seq, 0) + 1 WHERE id = ?',
(user.id,))
except Exception:
pass
resp = JSONResponse(content={'status': 200, 'success': True, 'message': '已退出登录'})
resp.delete_cookie(SESSION_COOKIE)
return resp
@router.post('/auth/heartbeat')
async def heartbeat(user: Annotated[SiteUser | None, Depends(current_user)]):
"""会话保活:返回最新次数;超限/失效给 401(expired 语义不变)。"""
if user is None:
return error('登录已失效', 401, error_code='unauthorized')
row = await repo.get_user_by_id(user.id)
if row is None:
return error('登录已失效', 401, error_code='unauthorized')
credits = int(row.get('duration_seconds') or 0)
if row.get('role') != 'admin' and credits != -1 and credits <= 0:
return error('剩余次数已用完', 401, error_code='expired')
return success({'duration_seconds': row.get('duration_seconds'),
'duration_text': _format_credits(credits)})
@router.post('/auth/ann_seen')
async def ann_seen(user: Annotated[SiteUser | None, Depends(current_user)]):
"""标记公告已读(记录当前公告版本)。"""
if user is not None:
ann = await repo.get_announcement()
await db.execute('UPDATE users SET ann_seen = ? WHERE id = ?',
(ann.get('updated_at', ''), user.id))
return success()
async def _resolve_login_identity(username: str) -> tuple:
"""身份解析:含 @ 按归一化邮箱解析真实账号。
返回 (邮箱命中的用户或 None, 锁定计数键)。邮箱登录的锁定键用
真实用户名(命中时)或归一化邮箱(未命中时),防大小写变体绕过。
"""
if '@' not in username:
return None, username
iuser = await 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 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 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,
)
admin_email = user['email'] if 'email' in user.keys() else ''
if not admin_email:
await auth.add_log('fail', lock_name, ip,
'管理员登录', '未绑定邮箱,两步验证不可用')
return error('管理员账号未绑定邮箱,请联系管理员先完成绑定')
ticket = _admin2fa_issue(user)
await 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 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 await _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 '')
ip = ratelimit.client_ip(request)
if len(password) > 128:
# 超长密码不做 PBKDF2(CPU 放大器),直接按密码错误拒绝
return error('用户名或密码错误')
try:
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 auth.verify_login(verify_name, password)
if not user:
from web.auth_state import _login_fail_record
_login_fail_record(lock_name)
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':
return await _admin_two_factor_response(user, lock_name, ip)
return await _user_session_response(user, ip)
except Exception:
return error('登录失败,请稍后重试', 500)
# ============ 管理员两步验证 Step2 / Step3 ============
@router.post('/auth/admin_login/email')
async def admin_login_email(request: Request):
"""管理员 2FA Step2:比对绑定邮箱 → 发送 admin2fa 验证码。"""
import hmac as _hmac
from web.auth_state import (
_ADMIN2FA_LAST_SEND,
_ADMIN2FA_SEND_GAP,
_ADMIN_2FA,
_ADMIN_2FA_MAX_ATTEMPTS,
_admin2fa_mask,
_admin2fa_take,
)
data = await _request_data(request)
ip = ratelimit.client_ip(request)
ticket, v = _admin2fa_take(str(data.get('ticket') or ''))
if not v:
return error('登录会话已过期,请重新开始登录', 401, error_code='admin_2fa_expired')
email_input = auth._normalize_email(str(data.get('email') or ''))
# 第二因子比对走常时比较
if (not email_input or not v.get('email')
or not _hmac.compare_digest(email_input, v['email'])):
v['attempts'] += 1
await auth.add_log('fail', v['username'], ip, '管理员登录', '绑定邮箱不匹配')
if v['attempts'] >= _ADMIN_2FA_MAX_ATTEMPTS:
_ADMIN_2FA.pop(ticket, None)
return error('错误次数过多,请重新开始登录')
return error(f'绑定邮箱不正确,还可尝试 {_ADMIN_2FA_MAX_ATTEMPTS - v["attempts"]} 次')
last_send = _ADMIN2FA_LAST_SEND.get(v['username'], 0)
if time.time() - last_send < _ADMIN2FA_SEND_GAP:
return error('验证码发送过于频繁,请 1 分钟后再试')
try:
await auth.send_verify_code(v['email'], 'admin2fa')
_ADMIN2FA_LAST_SEND[v['username']] = time.time()
await auth.add_log('success', v['username'], ip, '管理员登录',
f'绑定邮箱验证通过,验证码已发送({_admin2fa_mask(v["email"])})')
return success(message='验证码已发送至管理员邮箱,请查收')
except (ValueError, RuntimeError) as e:
return error(str(e))
except Exception:
return error('验证码发送失败,请稍后重试', 500)
@router.post('/auth/admin_login/verify')
async def admin_login_verify(request: Request):
"""管理员 2FA Step3:验证码原子消费 → 建立管理员会话。"""
from web.auth_state import (
_ADMIN_2FA,
_ADMIN_2FA_MAX_ATTEMPTS,
_admin2fa_take,
)
data = await _request_data(request)
ip = ratelimit.client_ip(request)
ticket, v = _admin2fa_take(str(data.get('ticket') or ''))
if not v:
return error('登录会话已过期,请重新开始登录', 401, error_code='admin_2fa_expired')
code = str(data.get('code') or '').strip()
if not await auth.check_verify_code(v['email'], code, 'admin2fa'):
v['attempts'] += 1
if v['attempts'] >= _ADMIN_2FA_MAX_ATTEMPTS:
_ADMIN_2FA.pop(ticket, None)
return error('错误次数过多,请重新开始登录')
await auth.add_log('fail', v['username'], ip, '管理员登录', '验证码错误')
return error('验证码错误或已过期')
_ADMIN_2FA.pop(ticket, None) # 一次性
user = await auth.get_user_by_id(v['user_id'])
if not user or user['role'] != 'admin':
return error('登录会话已过期,请重新开始登录', 401, error_code='admin_2fa_expired')
keys = user.keys()
status = user['status'] if 'status' in keys else 1
if status == 2:
await auth.add_log('fail', v['username'], ip, '管理员登录', '封禁账号尝试登录')
return error('账号已被封禁,请联系管理员')
if status == 0:
return error('账号已被禁用,请联系管理员')
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 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 {}
await auth.add_log('success', v['username'], ip, '管理员登录', '两步验证通过')
return await _login_response({
'user': _user_public(fresh),
'duration_text': _format_credits(int(fresh.get('duration_seconds') or 0)),
'redirect': 'admin',
}, '登录成功', uid, seq)