Archived
## uv 环境管理 - pyproject.toml 声明 dependencies + [dependency-groups].dev,uv.lock 精确锁定 - 删除 requirements.txt / requirements-fastapi.txt / requirements-dev.txt - .python-version = 3.12;Dockerfile 改用 uv sync --frozen(可复现构建) - 新增 jinja2(首页渲染) ## 删除 Flask 技术债 - 从 main.py 用 ast 精确剥离 56 个 Flask 节点(路由/中间件/错误处理/启动), 框架无关的服务层落为 services/runtime.py(MusicAPIService、下载/打包 worker、 任务监控、缓存清扫),零 Flask 依赖 - 删除 main.py(4527 行)与 auth_routes.py(1050 行) - auth_system.py 移除会话/请求上下文层(login_session/current_user/login_required/ admin_required/_client_ip 等),保留数据与业务层 - 新增 core/net.py(IP 解析)、web/auth_state.py(登录锁定/2FA 票据/发码限流) - FastAPI 侧改直接依赖 services.runtime,不再 import main - web/app.py 去掉 Flask fallback;入口默认根路径模式(API_PREFIX 可选) ## 删除 requests 技术债 - 新增 core/sync_http.py:requests 风格的同步门面(底层 aiohttp 连接池, 流式读取经有界队列背压),含 Session/headers/(connect,read) 元组超时兼容 - core/utils、auth_system、podcast_api、music_downloader、services 全部切换 - 实测真实下载 5.2MB 音频完整成功 ## 质量门禁归零 - ruff:0 错误(B904 全部修复,不再忽略) - pyright:0 错误(类型收窄修复) - pytest:140/140(含 golden 契约回归、root 模式 66 项路径覆盖) - 真实 uvicorn 启动:/health、/、/static、受保护端鉴权全部正确 新增 tests/golden/responses.json:删除 Flask 前捕获的 32 例响应快照, FastAPI 逐字段复现——删除巨石后行为回归仍有硬证据。
112 lines
4.1 KiB
Python
112 lines
4.1 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""登录/会话端点测试(沙箱库,不触碰生产 data/site.db)。
|
|
|
|
覆盖:密码错误、正常用户登录签发可用 Cookie、管理员转 2FA 票据、
|
|
退出登录递增 login_seq、heartbeat 次数校验。
|
|
"""
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
|
|
import auth_system as auth
|
|
import core.db as db
|
|
|
|
SECRET = 'auth-test-secret'
|
|
USER_PW = 'UserPass123'
|
|
ADMIN_PW = 'AdminPass123'
|
|
|
|
|
|
@pytest.fixture()
|
|
def app_env(tmp_path, monkeypatch):
|
|
"""沙箱站点库 + 独立密钥,隔离生产数据。"""
|
|
db_path = tmp_path / 'site.db'
|
|
monkeypatch.setattr(auth, 'DATA_DIR', tmp_path)
|
|
monkeypatch.setattr(auth, 'DB_PATH', db_path)
|
|
monkeypatch.setattr(auth, 'BACKUP_DIR', tmp_path / 'backups')
|
|
monkeypatch.setattr(auth, '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) VALUES (?,?,?,?,?,1,0,?)',
|
|
('normaluser', auth._hash_new(USER_PW), '', 'user', 97, 1730000000))
|
|
conn.execute('INSERT INTO users (username, password_hash, salt, role, duration_seconds, '
|
|
'status, login_seq, created_at, email) VALUES (?,?,?,?,?,1,0,?,?)',
|
|
('bossuser', auth._hash_new(ADMIN_PW), '', 'admin', -1, 1730000000,
|
|
'boss@example.com'))
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
monkeypatch.setattr('web.deps.secret_key', lambda: SECRET)
|
|
|
|
# 清空登录失败锁定/2FA 的模块级内存态,避免测试间串扰
|
|
import web.auth_state as auth_routes
|
|
auth_routes._LOGIN_FAILS.clear()
|
|
auth_routes._LOGIN_FAIL_LOGGED.clear()
|
|
auth_routes._ADMIN_2FA.clear()
|
|
|
|
from web.app import create_app
|
|
return TestClient(create_app())
|
|
|
|
|
|
def test_wrong_password(app_env):
|
|
r = app_env.post('/auth/login', json={'username': 'normaluser', 'password': 'nope'})
|
|
assert r.status_code == 400
|
|
assert r.json()['success'] is False
|
|
assert 'session' not in r.cookies
|
|
|
|
|
|
def test_user_login_issues_working_cookie(app_env):
|
|
r = app_env.post('/auth/login', json={'username': 'normaluser', 'password': USER_PW})
|
|
assert r.status_code == 200
|
|
body = r.json()
|
|
assert body['success'] is True
|
|
assert body['data']['redirect'] == 'user'
|
|
assert 'session' in r.cookies
|
|
|
|
# 用签发的 Cookie 访问受保护端点,应放行
|
|
r2 = app_env.post('/auth/heartbeat', json={})
|
|
assert r2.status_code == 200
|
|
assert r2.json()['data']['duration_text'] == '97 次'
|
|
|
|
|
|
def test_admin_login_returns_2fa_ticket(app_env):
|
|
r = app_env.post('/auth/login', json={'username': 'bossuser', 'password': ADMIN_PW})
|
|
assert r.status_code == 200
|
|
data = r.json()['data']
|
|
assert data['admin_2fa'] is True
|
|
assert data['ticket']
|
|
assert 'session' not in r.cookies # 管理员不在此建立会话
|
|
|
|
|
|
def test_logout_bumps_login_seq_and_clears(app_env):
|
|
app_env.post('/auth/login', json={'username': 'normaluser', 'password': USER_PW})
|
|
conn = auth.get_conn()
|
|
seq_before = conn.execute(
|
|
"SELECT login_seq FROM users WHERE username='normaluser'").fetchone()[0]
|
|
conn.close()
|
|
r = app_env.post('/auth/logout', json={})
|
|
assert r.status_code == 200
|
|
conn = auth.get_conn()
|
|
seq_after = conn.execute(
|
|
"SELECT login_seq FROM users WHERE username='normaluser'").fetchone()[0]
|
|
conn.close()
|
|
assert seq_after == seq_before + 1
|
|
# 旧 Cookie 失效
|
|
r2 = app_env.post('/auth/heartbeat', json={})
|
|
assert r2.status_code == 401
|
|
|
|
|
|
def test_heartbeat_expired_credits(app_env):
|
|
conn = auth.get_conn()
|
|
conn.execute("UPDATE users SET duration_seconds=0 WHERE username='normaluser'")
|
|
conn.commit()
|
|
conn.close()
|
|
r = app_env.post('/auth/login', json={'username': 'normaluser', 'password': USER_PW})
|
|
assert r.status_code == 200
|
|
r2 = app_env.post('/auth/heartbeat', json={})
|
|
assert r2.status_code == 401
|
|
assert r2.json().get('error_code') == 'expired'
|