Files

709 lines
24 KiB
Python

"""平台登录、会话和本机接口保护。"""
import asyncio
import inspect
import logging
import os
import subprocess
import sys
import time
from pathlib import Path
import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient
from app.features.download.jobs import DownloadJob
from app.platform.auth import login, logout, needs_captcha, purge_expired_flows, resume_saved
from app.platform.client import (
POOL_CONNECTIONS,
LoginChallenge,
NqiAuthError,
NqiClient,
NqiError,
)
from app.platform.keepalive import refresh_saved_session
from app.platform import sessions
from app.shared.state import state
@pytest.fixture(autouse=True)
def _reset_login_state():
limit = state.jobs.max_concurrent
state.client = None
state.user = None
state.expired = False
state.flows.clear()
state.jobs.jobs.clear()
yield
state.client = None
state.user = None
state.expired = False
state.flows.clear()
state.jobs.jobs.clear()
state.jobs.max_concurrent = limit
PUBLIC_KEY = (
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwjDm1HXDw8QH5ZtGMQIl2h/I8E+"
"chOQA8aQ8xCR/+aHnROaN/ZU5Vmd2Zz7g6cAacR9BSm60+iSCYtvEGJKl0WqvbPGJkc8tedjNF1QqgWqkkuE6Udgw2OkEKJCxDg6PrAniR7Cc0io9G8bW4P8JDJjSbbafvMPDDFbVVUWJxxwIDAQAB"
)
def _challenge(**extra) -> LoginChallenge:
payload = {
"execution": "exec-old",
"public_key": PUBLIC_KEY,
"captcha_png": b"png",
"page_url": "https://nqi.gmcc.net:20443/cas/login?service=1",
"username": "user",
"password": "secret",
"captcha": "abcd",
"config_ready": False,
}
payload.update(extra)
challenge = LoginChallenge(**payload)
challenge.created_at = time.monotonic()
return challenge
def _cookies(value: str) -> list[dict]:
return [{"name": "TGC", "value": value, "domain": "", "path": "/"}]
def _user(login_id: str, name: str = "甲") -> dict:
return {"loginId": login_id, "userName": name, "cityName": "江门", "orgName": ""}
def _job(directory: Path, job_id: str, **extra) -> DownloadJob:
directory.mkdir(parents=True, exist_ok=True)
return DownloadJob(
id=job_id,
directory=directory,
network="NR",
city_code="JM",
city_name="江门",
month="2026-09",
groups=["rsrp"],
concurrency=1,
grid_ids=["1"],
csv_path=directory / "out.csv",
created_at="2026-09-21T12:00:09",
**extra,
)
class _OldClient:
def __init__(self, events: list, running: DownloadJob | None = None):
self.events = events
self.running = running
async def wait_idle(self, timeout: float = 5.0) -> None:
self.events.append("wait")
if self.running is not None:
self.events.append(self.running.status)
async def aclose(self) -> None:
self.events.append("close")
def test_connection_pool_matches_keepalive_limit():
client = NqiClient()
try:
pool = client.client._transport._pool
assert POOL_CONNECTIONS >= 300
assert pool._max_connections >= 300
assert pool._max_keepalive_connections == pool._max_connections
finally:
asyncio.run(client.aclose())
def test_unused_login_form_fields_are_gone():
import app.platform.client as client_module
assert "form_action" not in LoginChallenge.__dataclass_fields__
source = inspect.getsource(client_module)
assert "_FORM_ACTION" not in source
assert "_ERROR_TEXT" not in source
def test_needs_captcha_ignores_sms_and_generic_failure():
assert needs_captcha("验证码错误")
assert needs_captcha("图形验证码已过期")
assert not needs_captcha("短信验证码错误")
assert not needs_captcha("登录未成功,请检查验证码或短信验证码")
assert not needs_captcha("密码错误")
def test_submit_login_refreshes_execution_and_captcha_flag():
asyncio.run(_submit_login_refreshes_execution_and_captcha_flag())
async def _submit_login_refreshes_execution_and_captcha_flag():
client = NqiClient()
challenge = _challenge(config_ready=True)
html = '<form><input name="execution" value="exec-new"><div id="errMsg">验证码错误</div></form>'
class Response:
status_code = 200
headers = {"content-type": "text/html"}
text = html
content = html.encode()
async def post(_url, **_kwargs):
return Response()
client.client.post = post
try:
with pytest.raises(NqiError, match="验证码错误"):
await client.submit_login(challenge, "000000")
finally:
await client.aclose()
assert challenge.execution == "exec-new"
assert challenge.config_ready is False
def test_missing_user_and_gateway_errors():
asyncio.run(_missing_user_and_gateway_errors())
async def _missing_user_and_gateway_errors():
client = NqiClient()
class JsonResponse:
def __init__(self, status_code: int, payload, url=None):
self.status_code = status_code
self._payload = payload
self.headers = {"content-type": "application/json"}
self.url = url
self.text = ""
def json(self):
if isinstance(self._payload, Exception):
raise self._payload
return self._payload
async def empty(_url, **_kwargs):
return JsonResponse(200, {})
client.client.get = empty
try:
with pytest.raises(NqiAuthError, match="失效"):
await client._cas_user_payload()
client.client.get = lambda *_args, **_kwargs: _async_return(
JsonResponse(200, {}, type("URL", (), {"path": "/cas/login"})())
)
with pytest.raises(NqiAuthError):
await client.current_user()
async def gateway(_url, **_kwargs):
response = JsonResponse(502, None)
response.headers = {"content-type": "text/html"}
response.text = "<html>bad gateway</html>"
def json_fail():
raise __import__("json").JSONDecodeError("bad", "", 0)
response.json = json_fail
return response
client.client.get = gateway
with pytest.raises(NqiError) as caught:
await client.current_user()
assert not isinstance(caught.value, NqiAuthError)
finally:
await client.aclose()
async def _async_return(value):
return value
def test_wait_idle_returns_without_waiting_out_the_timeout():
asyncio.run(_wait_idle_returns_without_waiting_out_the_timeout())
async def _wait_idle_returns_without_waiting_out_the_timeout():
client = NqiClient()
started = time.monotonic()
try:
await client.wait_idle(5)
client._inflight = 1
client._idle.clear()
async def finish() -> None:
await asyncio.sleep(0.05)
client._inflight = 0
client._idle.set()
waiter = asyncio.create_task(finish())
await client.wait_idle(5)
await waiter
finally:
await client.aclose()
assert time.monotonic() - started < 1
def test_login_captcha_failure_does_not_drop_current_session(tmp_path: Path):
asyncio.run(_login_captcha_failure_does_not_drop_current_session(tmp_path))
async def _login_captcha_failure_does_not_drop_current_session(tmp_path: Path):
events: list = []
running = _job(tmp_path / "run", "20260921120009", status="running")
old = _OldClient(events, running)
state.client = old
state.jobs.jobs[running.id] = running
challenge = _challenge(config_ready=True)
client = _FlowClient(submit_error=NqiError("验证码已过期"))
state.flows["sid"] = (client, challenge)
result = await login(
{"sessionId": "sid", "username": "user", "password": "secret", "captcha": "abcd", "smsCode": "123456"}
)
assert result["status"] == "need_captcha"
assert "验证码" in result["message"]
assert challenge.config_ready is False
assert events == []
assert running.status == "running"
assert state.client is old
assert "sid" in state.flows
def test_login_sms_error_stays_on_the_dialog():
asyncio.run(_login_sms_error_stays_on_the_dialog())
async def _login_sms_error_stays_on_the_dialog():
challenge = _challenge(config_ready=True, execution="exec-old")
class Flow:
async def submit_login(self, current, _sms):
current.execution = "exec-next"
raise NqiError("短信验证码错误")
state.flows["sid"] = (Flow(), challenge)
with pytest.raises(HTTPException) as caught:
await login(
{"sessionId": "sid", "username": "user", "password": "secret", "captcha": "abcd", "smsCode": "123456"}
)
assert caught.value.status_code == 400
assert caught.value.detail == "短信验证码错误"
assert challenge.config_ready is True
assert challenge.execution == "exec-next"
def test_login_success_resumes_only_expired_jobs(tmp_path: Path, monkeypatch):
asyncio.run(_login_success_resumes_only_expired_jobs(tmp_path, monkeypatch))
async def _login_success_resumes_only_expired_jobs(tmp_path: Path, monkeypatch):
monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json")
events: list = []
expired = _job(tmp_path / "expired", "20260921120009", status="paused", paused_by="expired")
running = _job(tmp_path / "running", "20260921120010", status="running")
old = _OldClient(events, running)
state.client = old
state.user = _user("old", "旧")
state.expired = True
state.jobs.jobs[expired.id] = expired
state.jobs.jobs[running.id] = running
seen = {}
def fill_slots() -> None:
seen["expired"] = state.expired
seen["jobs"] = {job.id: (job.status, job.paused_by) for job in state.jobs.jobs.values()}
monkeypatch.setattr("app.features.download.router.fill_slots", fill_slots)
challenge = _challenge()
client = _FlowClient(user=_user("new", "新"))
state.flows["sid"] = (client, challenge)
result = await login({"sessionId": "sid", "username": "user", "password": "secret", "captcha": "abcd"})
assert result["status"] == "ok"
assert result["user"]["loginId"] == "new"
assert state.expired is False
assert state.client is client
assert state.user["userName"] == "新"
assert challenge.password == ""
assert "sid" not in state.flows
assert events == ["wait", "paused", "close"]
assert seen["expired"] is False
assert seen["jobs"][expired.id] == ("queued", "")
assert seen["jobs"][running.id] == ("paused", "switch")
assert sessions._read()[0]["loginId"] == "new"
def test_failed_saved_login_keeps_current_client(tmp_path: Path, monkeypatch):
asyncio.run(_failed_saved_login_keeps_current_client(tmp_path, monkeypatch))
async def _failed_saved_login_keeps_current_client(tmp_path: Path, monkeypatch):
monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json")
sessions.remember(_user("down"), _cookies("down"))
events: list = []
old = _OldClient(events)
running = _job(tmp_path / "run", "20260921120009", status="running")
state.client = old
state.jobs.jobs[running.id] = running
async def current(self):
raise NqiError("平台接口没有返回数据")
monkeypatch.setattr(NqiClient, "current_user", current)
with pytest.raises(HTTPException) as caught:
await resume_saved({"loginId": "down"})
assert caught.value.status_code == 400
assert "没有返回数据" in caught.value.detail
assert events == []
assert state.client is old
assert running.status == "running"
assert sessions._read()[0]["loginId"] == "down"
def test_logout_pauses_jobs_and_keeps_saved_login(tmp_path: Path, monkeypatch):
asyncio.run(_logout_pauses_jobs_and_keeps_saved_login(tmp_path, monkeypatch))
async def _logout_pauses_jobs_and_keeps_saved_login(tmp_path: Path, monkeypatch):
monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json")
sessions.remember(_user("a"), _cookies("kept"))
events: list = []
running = _job(tmp_path / "run", "20260921120009", status="running")
waiting = _job(tmp_path / "wait", "20260921120010", status="queued")
state.client = _OldClient(events, running)
state.user = _user("a")
state.expired = True
state.jobs.jobs[running.id] = running
state.jobs.jobs[waiting.id] = waiting
result = await logout()
assert result == {"ok": True, "paused": 2}
assert events[:2] == ["wait", "paused"]
assert events[-1] == "close"
assert running.status == "paused"
assert running.paused_by == "logout"
assert waiting.paused_by == "logout"
assert state.client is None
assert state.user is None
assert state.expired is False
assert sessions._read()[0]["cookies"][0]["value"] == "kept"
assert (tmp_path / "sessions.json").is_file()
def test_saved_accounts_keep_temporary_failures(tmp_path: Path, monkeypatch):
asyncio.run(_saved_accounts_keep_temporary_failures(tmp_path, monkeypatch))
async def _saved_accounts_keep_temporary_failures(tmp_path: Path, monkeypatch):
monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json")
sessions.remember(_user("dead"), _cookies("dead"))
sessions.remember(_user("down"), _cookies("down"))
sessions.remember(_user("a"), _cookies("a"))
async def current(self):
ticket = self.ticket()
if ticket == "a":
await sessions.remember_account(_user("c", "丙"), _cookies("from-c"))
if ticket == "dead":
raise NqiAuthError("登录已失效,请重新登录")
if ticket == "down":
raise NqiError("平台接口没有返回数据")
return _user(ticket, "新")
def exported(self):
return _cookies(f"{self.ticket()}-new")
monkeypatch.setattr(NqiClient, "current_user", current)
monkeypatch.setattr(NqiClient, "export_cookies", exported)
visible = await sessions.available_accounts()
stored = {item["loginId"]: item for item in sessions._read()}
assert [item["loginId"] for item in visible] == ["a", "down"]
assert "dead" not in stored
assert stored["down"]["cookies"][0]["value"] == "down"
assert stored["a"]["cookies"][0]["value"] == "a-new"
assert stored["c"]["cookies"][0]["value"] == "from-c"
def test_saved_accounts_probe_together_and_timeout_keeps_cookie(tmp_path: Path, monkeypatch):
asyncio.run(_saved_accounts_probe_together_and_timeout_keeps_cookie(tmp_path, monkeypatch))
async def _saved_accounts_probe_together_and_timeout_keeps_cookie(tmp_path: Path, monkeypatch):
monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json")
monkeypatch.setattr(sessions, "PROBE_TIMEOUT_SECONDS", 0.05)
sessions.remember(_user("slow"), _cookies("slow"))
sessions.remember(_user("b"), _cookies("b"))
starts: list[float] = []
async def current(self):
starts.append(time.monotonic())
if self.ticket() == "slow":
await asyncio.sleep(1)
return _user(self.ticket())
monkeypatch.setattr(NqiClient, "current_user", current)
monkeypatch.setattr(NqiClient, "export_cookies", lambda self: _cookies(f"{self.ticket()}-new"))
started = time.monotonic()
visible = await sessions.available_accounts()
assert time.monotonic() - started < 0.5
assert max(starts) - min(starts) < 0.2
assert [item["loginId"] for item in visible] == ["b", "slow"]
stored = {item["loginId"]: item for item in sessions._read()}
assert stored["slow"]["cookies"][0]["value"] == "slow"
assert stored["b"]["cookies"][0]["value"] == "b-new"
def test_resume_deletes_only_auth_failures(tmp_path: Path, monkeypatch):
asyncio.run(_resume_deletes_only_auth_failures(tmp_path, monkeypatch))
async def _resume_deletes_only_auth_failures(tmp_path: Path, monkeypatch):
monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json")
sessions.remember(_user("dead"), _cookies("dead"))
sessions.remember(_user("down"), _cookies("down"))
async def current(self):
if self.ticket() == "dead":
raise NqiAuthError("登录已失效,请重新登录")
raise NqiError("平台响应超时,请稍后重试")
monkeypatch.setattr(NqiClient, "current_user", current)
with pytest.raises(NqiError, match="登录已失效"):
await sessions.resume("dead")
assert [item["loginId"] for item in sessions._read()] == ["down"]
with pytest.raises(NqiError, match="超时"):
await sessions.resume("down")
assert [item["loginId"] for item in sessions._read()] == ["down"]
def test_keepalive_auth_error_pauses_jobs(tmp_path: Path):
asyncio.run(_keepalive_auth_error_pauses_jobs(tmp_path))
async def _keepalive_auth_error_pauses_jobs(tmp_path: Path):
job = _job(tmp_path, "20260921120009", status="running", message="下载中")
state.jobs.jobs[job.id] = job
class Fake:
async def touch_session(self):
raise NqiAuthError("登录已失效,请重新登录")
def export_cookies(self):
raise AssertionError("失效后不应写回凭证")
state.client = Fake()
state.user = _user("a")
await refresh_saved_session()
assert state.expired is True
assert job.status == "paused"
assert job.paused_by == "expired"
assert "失效" in job.message
def test_keepalive_network_error_keeps_session(caplog):
asyncio.run(_keepalive_network_error_keeps_session(caplog))
async def _keepalive_network_error_keeps_session(caplog):
class Fake:
async def touch_session(self):
raise NqiError("平台响应超时,请稍后重试")
state.client = Fake()
state.user = _user("a", "原")
with caplog.at_level(logging.INFO, logger="nqi.auth"):
await refresh_saved_session()
assert state.expired is False
assert state.user["userName"] == "原"
assert "续期" in caplog.text
def test_keepalive_does_not_write_replaced_client(tmp_path: Path, monkeypatch):
asyncio.run(_keepalive_does_not_write_replaced_client(tmp_path, monkeypatch))
async def _keepalive_does_not_write_replaced_client(tmp_path: Path, monkeypatch):
monkeypatch.setattr(sessions, "STORE", tmp_path / "sessions.json")
sessions.remember(_user("new", "新"), _cookies("new"))
replacement = object()
class Old:
async def touch_session(self):
state.client = replacement
state.user = _user("new", "新")
return _user("old", "旧刷新")
def export_cookies(self):
return _cookies("old-should-not-write")
state.client = Old()
state.user = _user("old", "旧")
await refresh_saved_session()
assert state.client is replacement
assert state.user["loginId"] == "new"
assert sessions._read()[0]["cookies"][0]["value"] == "new"
def test_expired_login_flow_drops_password():
asyncio.run(_expired_login_flow_drops_password())
async def _expired_login_flow_drops_password():
logged_in = NqiClient()
fresh = NqiClient()
stale = NqiClient()
undated = NqiClient()
old = _challenge(password="plain-secret")
old.created_at = time.monotonic() - 601
current = _challenge(password="keep")
missing = _challenge(password="still")
del missing.created_at
active = _challenge(password="active")
active.created_at = time.monotonic() - 1000
state.client = logged_in
state.flows["old"] = (stale, old)
state.flows["fresh"] = (fresh, current)
state.flows["missing"] = (undated, missing)
state.flows["active"] = (logged_in, active)
try:
await purge_expired_flows()
assert "old" not in state.flows
assert old.password == ""
assert "fresh" in state.flows
assert current.password == "keep"
assert "missing" in state.flows
assert missing.password == "still"
assert "active" in state.flows
assert active.password == "active"
finally:
await logged_in.aclose()
await fresh.aclose()
await undated.aclose()
await stale.aclose()
def test_parent_watch_sees_process_exit_without_kill():
from app import main as main_module
source = inspect.getsource(main_module._parent_running) + inspect.getsource(main_module._watch_parent)
assert "os.kill(" not in source
assert "OpenProcess" in source
assert "WaitForSingleObject" in source
assert main_module._parent_running(os.getpid()) is True
proc = subprocess.Popen([sys.executable, "-c", "import sys; sys.exit(0)"])
proc.wait(timeout=15)
assert main_module._parent_running(proc.pid) is False
def test_parent_watchdog_is_off_without_env(monkeypatch):
from app import main as main_module
monkeypatch.delenv("NQI_PARENT_PID", raising=False)
assert main_module._parent_pid() is None
monkeypatch.setenv("NQI_PARENT_PID", " ")
assert main_module._parent_pid() is None
monkeypatch.setenv("NQI_PARENT_PID", "abc")
assert main_module._parent_pid() is None
def test_watchdog_exits_when_parent_is_gone(monkeypatch):
from app import main as main_module
monkeypatch.setattr(main_module, "PARENT_CHECK_SECONDS", 0.01)
monkeypatch.setattr(main_module, "_parent_running", lambda _pid: False)
def stop(code):
raise SystemExit(code)
monkeypatch.setattr(main_module.os, "_exit", stop)
async def watch() -> None:
with pytest.raises(SystemExit) as caught:
await main_module._watch_parent(123)
assert caught.value.code == 0
asyncio.run(watch())
def test_data_lock_logs_and_exits(monkeypatch, capsys):
from app import main as main_module
main_module.configure_logging()
main_module._release_data_lock()
main_module._acquire_data_lock()
held = main_module._lock_file
main_module._lock_file = None
def stop(code):
raise SystemExit(code)
monkeypatch.setattr(main_module.os, "_exit", stop)
try:
with pytest.raises(SystemExit) as caught:
main_module._acquire_data_lock()
assert caught.value.code == 1
assert "占用" in capsys.readouterr().out
finally:
main_module._lock_file = held
main_module._release_data_lock()
def test_nqi_logger_and_packaged_access_log():
import nqi_backend
from app.main import configure_logging
configure_logging()
configure_logging()
nqi = logging.getLogger("nqi")
assert nqi.level == logging.INFO
assert sum(1 for handler in nqi.handlers if getattr(handler, "_nqi_stdout", False)) == 1
assert nqi.propagate is False
source = inspect.getsource(nqi_backend.main)
assert "configure_logging()" in source
assert "access_log=False" in source
def test_token_and_host_guard(monkeypatch):
monkeypatch.delenv("NQI_PARENT_PID", raising=False)
monkeypatch.delenv("NQI_TOKEN", raising=False)
from app.main import app
with TestClient(app, base_url="http://127.0.0.1") as client:
assert client.get("/api/health").status_code == 200
open_me = client.get("/api/auth/me")
assert open_me.status_code == 401
assert open_me.json()["detail"] == "请先登录"
monkeypatch.setenv("NQI_TOKEN", "secret")
assert client.get("/api/health").status_code == 200
denied = client.get("/api/auth/me")
assert denied.status_code == 401
assert denied.json()["detail"] == "未授权"
authed = client.get("/api/auth/me", headers={"X-Nqi-Token": "secret"})
assert authed.status_code == 401
assert authed.json()["detail"] == "请先登录"
foreign = client.get("/api/health", headers={"Host": "evil.example"})
assert foreign.status_code == 400
class _FlowClient:
def __init__(self, user: dict | None = None, submit_error: Exception | None = None):
self.user = user or _user("a")
self.submit_error = submit_error
async def prepare_login(self, challenge, _username, _password, _captcha):
challenge.config_ready = True
challenge.password = _password
return "0"
async def submit_login(self, _challenge, _sms=""):
if self.submit_error:
raise self.submit_error
return self.user
def export_cookies(self):
return _cookies("fresh")
async def aclose(self):
return None
async def wait_idle(self, timeout: float = 5.0):
return None