Files
EnuivTools/backend/tests/test_admin.py
T

622 lines
24 KiB
Python

import json
import threading
from datetime import datetime, timezone
from pathlib import Path
from fastapi.testclient import TestClient
from sqlalchemy import event
from admin.identity import identity
from admin.models import SystemConfig
from admin.settings import ensure_admin_seed, load_admin_identity, refresh_interval_seconds
from euniv.client import EunivClient, JigsawRejected, ManualJigsaw
from euniv.crypto import decrypt_secret, encrypt_secret
from euniv.db import SessionLocal, engine
from euniv.models import Account
from euniv.session import COOKIE_NAME
INITIAL_PASSWORD = "242520"
CREDENTIAL = {
"ucs_token": "ucs-1",
"ucs_account_id": "acct",
"ucs_user_id": "user",
"ucs_ssoinfo": "sso",
"ucs_union_id": "union",
"yxt_token": "yxt-1",
}
def _app():
import euniv.api as api_module
return api_module
def _add_account(
employee_id: str,
password: str = "secret-pass",
credential: dict | None = CREDENTIAL,
paused: bool = False,
refreshed_at: datetime | None = None,
valid: bool | None = None,
) -> None:
with SessionLocal() as db:
db.add(
Account(
employee_id=employee_id,
password_cipher=encrypt_secret(password),
credential_cipher=encrypt_secret(json.dumps(credential)) if credential is not None else "",
refresh_paused=paused,
last_refresh_at=refreshed_at,
credential_valid=valid,
)
)
db.commit()
def _settings_body(**overrides) -> dict:
body = {
"refresh_interval_minutes": 30,
"show_manual_jigsaw": True,
"manual_preference": False,
"auto_jigsaw_attempts": 3,
"admin_username": "admin",
}
body.update(overrides)
return body
def test_admin_login_succeeds_and_wrong_password_skips_euniv() -> None:
api = _app()
calls = []
def spy(*_args, **_kwargs):
calls.append("euniv")
raise AssertionError("不应走 e 学登录")
api.login_and_store = spy
statements = []
def hear(_connection, _cursor, statement, _parameters, _context, _executemany):
statements.append(statement)
event.listen(engine, "before_cursor_execute", hear)
try:
client = TestClient(api.app)
wrong = client.post("/api/login", json={"employee_id": "admin", "password": "wrong-pass"})
assert wrong.status_code == 400
assert wrong.json()["detail"] == "登录失败"
assert calls == []
assert not any("system_config" in statement.lower() for statement in statements)
ok = client.post("/api/login", json={"employee_id": " admin ", "password": INITIAL_PASSWORD})
assert ok.status_code == 200
assert ok.json() == {"role": "admin", "username": "admin"}
assert "euniv_admin_session" in client.cookies
assert COOKIE_NAME not in client.cookies
assert client.get("/api/session").json() == {"role": "admin", "username": "admin"}
assert client.get("/api/home").status_code == 403
assert client.get("/api/exam", params={"path": "/exam/x"}).status_code == 403
assert client.get("/api/training", params={"path": "/plan/x"}).status_code == 403
assert calls == []
finally:
event.remove(engine, "before_cursor_execute", hear)
def test_admin_identity_uses_memory_until_reload() -> None:
api = _app()
calls = []
api.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: calls.append(employee_id) or {
"employee_id": employee_id
}
with SessionLocal() as db:
row = db.get(SystemConfig, 1)
assert row is not None
row.admin_username = "6650000146"
row.admin_password_cipher = encrypt_secret("other-secret")
db.commit()
client = TestClient(api.app)
user = client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"})
assert user.status_code == 200
assert user.json()["role"] == "user"
assert calls == ["6650000146"]
calls.clear()
admin = client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD})
assert admin.status_code == 200
assert admin.json() == {"role": "admin", "username": "admin"}
assert calls == []
load_admin_identity()
rejected = client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD})
assert rejected.status_code == 200
assert rejected.json()["role"] == "user"
accepted = client.post("/api/login", json={"employee_id": "6650000146", "password": "other-secret"})
assert accepted.json() == {"role": "admin", "username": "6650000146"}
def test_seed_does_not_reset_saved_admin() -> None:
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
saved = client.put(
"/api/admin/settings",
json=_settings_body(admin_username="ops", admin_password="next-secret", refresh_interval_minutes=15),
)
assert saved.status_code == 200
assert saved.json()["admin_username"] == "ops"
assert "admin_password" not in saved.json()
ensure_admin_seed()
load_admin_identity()
assert client.get("/api/admin/settings").json()["admin_username"] == "ops"
assert client.get("/api/session").json() == {"role": "admin", "username": "ops"}
old = client.post("/api/login", json={"employee_id": "ops", "password": INITIAL_PASSWORD})
assert old.status_code == 400
assert old.json()["detail"] == "登录失败"
again = client.post("/api/login", json={"employee_id": "ops", "password": "next-secret"})
assert again.json() == {"role": "admin", "username": "ops"}
with SessionLocal() as db:
row = db.get(SystemConfig, 1)
assert row is not None
assert decrypt_secret(row.admin_password_cipher) == "next-secret"
def test_login_config_changes_meaning_with_visibility() -> None:
api = _app()
seen = {}
def spy(db, employee_id, password, manual=False, auto_attempts=3):
seen["manual"] = manual
seen["attempts"] = auto_attempts
return {"employee_id": employee_id}
api.login_and_store = spy
client = TestClient(api.app)
opened = client.get("/api/login-config")
assert opened.json() == {"show_manual_checkbox": True, "manual_checkbox_checked": False}
assert set(opened.json()) == {"show_manual_checkbox", "manual_checkbox_checked"}
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
assert client.put("/api/admin/settings", json=_settings_body(manual_preference=True, auto_jigsaw_attempts=6)).status_code == 200
checked = client.get("/api/login-config").json()
assert checked == {"show_manual_checkbox": True, "manual_checkbox_checked": True}
client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": False})
assert seen == {"manual": False, "attempts": 6}
client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": True})
assert seen["manual"] is True
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
hidden = _settings_body(show_manual_jigsaw=False, manual_preference=True, auto_jigsaw_attempts=4)
assert client.put("/api/admin/settings", json=hidden).status_code == 200
assert client.get("/api/login-config").json() == {"show_manual_checkbox": False, "manual_checkbox_checked": False}
client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": True})
assert seen["manual"] is False
assert seen["attempts"] == 4
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
direct = _settings_body(show_manual_jigsaw=False, manual_preference=False, auto_jigsaw_attempts=9)
assert client.put("/api/admin/settings", json=direct).status_code == 200
client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass", "manual_jigsaw": False})
assert seen["manual"] is True
assert seen["attempts"] == 9
def test_settings_reject_interval_and_attempts_outside_range() -> None:
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
too_wide = client.put("/api/admin/settings", json=_settings_body(refresh_interval_minutes=1441))
assert too_wide.status_code == 400
assert too_wide.json()["detail"] == "定时刷新间隔须为 1 到 1440 的整数"
too_many = client.put("/api/admin/settings", json=_settings_body(auto_jigsaw_attempts=0))
assert too_many.status_code == 400
assert too_many.json()["detail"] == "自动滑动次数须为 1 到 10 的整数"
blank = client.put("/api/admin/settings", json=_settings_body(admin_username=" "))
assert blank.status_code == 400
assert blank.json()["detail"] == "请填写管理员用户名"
assert client.get("/api/admin/settings").json()["refresh_interval_minutes"] == 30
kept = client.put("/api/admin/settings", json=_settings_body(admin_password=""))
assert kept.status_code == 200
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
edges = client.put("/api/admin/settings", json=_settings_body(refresh_interval_minutes=1, auto_jigsaw_attempts=10))
assert edges.status_code == 200
assert edges.json()["refresh_interval_minutes"] == 1
assert edges.json()["auto_jigsaw_attempts"] == 10
def test_refresh_interval_comes_only_from_database(monkeypatch) -> None:
monkeypatch.setenv("EUNIV_WORKER_INTERVAL", "9")
assert refresh_interval_seconds() == 30 * 60
with SessionLocal() as db:
row = db.get(SystemConfig, 1)
assert row is not None
row.refresh_interval_minutes = 12
db.commit()
assert refresh_interval_seconds() == 12 * 60
monkeypatch.setenv("EUNIV_WORKER_INTERVAL", "1440")
assert refresh_interval_seconds() == 12 * 60
root = Path(__file__).resolve().parents[2]
example = (root / ".env.example").read_text(encoding="utf-8")
assert "EUNIV_WORKER_INTERVAL" not in example
assert "EUNIV_SECRET_KEY" in example
assert "EUNIV_DB_PATH" in example
for folder in ("euniv", "admin", "alembic"):
for path in (root / "backend" / folder).rglob("*.py"):
assert "EUNIV_WORKER_INTERVAL" not in path.read_text(encoding="utf-8")
service_text = (root / "backend" / "euniv" / "service.py").read_text(encoding="utf-8")
assert "1800" not in service_text
import euniv.service as service
seen = []
done = threading.Event()
refreshes = []
def wait(self, seconds):
seen.append(seconds)
if len(seen) >= 2:
done.set()
return "stop"
return "wake"
monkeypatch.setattr(service._RefreshGate, "wait", wait)
monkeypatch.setattr(service, "refresh_stored_credentials", lambda *args, **kwargs: refreshes.append(1))
service.start_credential_refresh()
assert done.wait(2)
assert seen == [12 * 60, 12 * 60]
assert refreshes == []
def test_saving_new_interval_restarts_wait_without_refresh(monkeypatch) -> None:
import euniv.service as service
notices = []
monkeypatch.setattr(service, "notify_refresh_interval_changed", lambda: notices.append(1))
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
same = client.put("/api/admin/settings", json=_settings_body(admin_username="admin"))
assert same.status_code == 200
assert notices == []
changed = client.put("/api/admin/settings", json=_settings_body(refresh_interval_minutes=45))
assert changed.status_code == 200
assert notices == [1]
monkeypatch.setenv("EUNIV_WORKER_INTERVAL", "1")
assert refresh_interval_seconds() == 45 * 60
class _Alive:
def __init__(self, login_name: str, password: str) -> None:
self.login_name = login_name
self.password = password
self.login_called = False
def close(self) -> None:
return None
def restore(self, _credential: dict) -> None:
return None
def credential_alive(self) -> bool:
return True
def export_credential(self) -> dict:
return dict(CREDENTIAL)
def login(self, manual: bool = False, auto_attempts: int = 3) -> dict:
self.login_called = True
raise AssertionError("不应重新登录")
def authorize(self, _profile: dict) -> None:
return None
class _Dead:
def __init__(self, login_name: str, password: str) -> None:
self.login_name = login_name
def close(self) -> None:
return None
def restore(self, _credential: dict) -> None:
return None
def credential_alive(self) -> bool:
return False
def login(self, manual: bool = False, auto_attempts: int = 3) -> dict:
raise RuntimeError("登录失败:密码错误")
def test_refresh_records_outcome_and_skips_paused_accounts() -> None:
import euniv.service as service
stamped = datetime(2026, 10, 1, 8, 0, tzinfo=timezone.utc)
_add_account("alive-user")
_add_account("failed-user")
_add_account("paused-user", paused=True, refreshed_at=stamped, valid=True)
_add_account("empty-user", credential=None, refreshed_at=stamped, valid=False)
created = []
def factory(login_name: str, password: str):
created.append(login_name)
if login_name == "failed-user":
return _Dead(login_name, password)
return _Alive(login_name, password)
service.refresh_stored_credentials(factory)
assert created == ["alive-user", "failed-user"]
with SessionLocal() as db:
alive = db.get(Account, "alive-user")
failed = db.get(Account, "failed-user")
paused = db.get(Account, "paused-user")
empty = db.get(Account, "empty-user")
assert alive is not None and failed is not None and paused is not None and empty is not None
assert alive.credential_valid is True
assert alive.last_refresh_at is not None
assert decrypt_secret(alive.password_cipher) == "secret-pass"
assert json.loads(decrypt_secret(alive.credential_cipher))["yxt_token"] == "yxt-1"
assert failed.credential_valid is False
assert failed.last_refresh_at is not None
assert decrypt_secret(failed.password_cipher) == "secret-pass"
assert json.loads(decrypt_secret(failed.credential_cipher))["yxt_token"] == "yxt-1"
assert paused.last_refresh_at == stamped.replace(tzinfo=None) or paused.last_refresh_at == stamped
assert paused.credential_valid is True
assert empty.credential_valid is False
assert decrypt_secret(empty.password_cipher) == "secret-pass"
def test_paused_account_still_updates_when_opening_home() -> None:
import euniv.service as service
_add_account("paused-user", paused=True)
class HomeClient(_Alive):
def __init__(self, login_name: str, password: str) -> None:
super().__init__(login_name, password)
self._token = "yxt-1"
def home_snapshot(self) -> dict:
self._token = "yxt-2"
return {"name": "测试用户"}
def export_credential(self) -> dict:
exported = dict(CREDENTIAL)
exported["yxt_token"] = self._token
return exported
with SessionLocal() as db:
assert service.fetch_home(db, "paused-user", HomeClient)["name"] == "测试用户"
account = db.get(Account, "paused-user")
assert account is not None
assert account.refresh_paused is True
assert json.loads(decrypt_secret(account.credential_cipher))["yxt_token"] == "yxt-2"
def test_check_skips_empty_credential_and_updates_saved_one() -> None:
import admin.users as users
stamped = datetime(2026, 10, 2, 9, 30, tzinfo=timezone.utc)
_add_account("empty-user", credential=None, refreshed_at=stamped, valid=True)
_add_account("saved-user")
calls = []
def factory(login_name: str, password: str):
calls.append(login_name)
return _Alive(login_name, password)
users.build_client = factory
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
missed = client.post("/api/admin/users/empty-user/check")
assert missed.status_code == 200
assert missed.json() == {"employee_id": "empty-user", "result": "未保存"}
assert calls == []
with SessionLocal() as db:
empty = db.get(Account, "empty-user")
assert empty is not None
assert empty.credential_valid is True
assert empty.last_refresh_at == stamped or empty.last_refresh_at == stamped.replace(tzinfo=None)
checked = client.post("/api/admin/users/saved-user/check")
assert checked.status_code == 200
assert checked.json() == {"employee_id": "saved-user", "result": "有效"}
assert calls == ["saved-user"]
listed = client.get("/api/admin/users")
assert listed.status_code == 200
body = listed.json()
assert isinstance(body, list)
saved = next(item for item in body if item["employee_id"] == "saved-user")
assert set(saved) == {
"employee_id",
"has_credential",
"refresh_paused",
"last_refresh_at",
"credential_valid",
}
assert saved["has_credential"] is True
assert saved["refresh_paused"] is False
assert saved["credential_valid"] is True
assert isinstance(saved["last_refresh_at"], str)
calls.clear()
again = client.get("/api/admin/users")
assert again.status_code == 200
assert calls == []
def test_check_all_reports_each_saved_account() -> None:
import admin.users as users
_add_account("a-user")
_add_account("b-user")
_add_account("c-user", credential=None)
calls = []
def factory(login_name: str, password: str):
calls.append(login_name)
if login_name == "b-user":
raise RuntimeError("网络失败")
return _Alive(login_name, password)
users.build_client = factory
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
response = client.post("/api/admin/users/check-all")
assert response.status_code == 200
assert response.json() == [
{"employee_id": "a-user", "result": "有效"},
{"employee_id": "b-user", "result": "检查失败", "detail": "检查失败"},
]
assert calls == ["a-user", "b-user"]
with SessionLocal() as db:
failed = db.get(Account, "b-user")
untouched = db.get(Account, "c-user")
assert failed is not None and failed.credential_valid is None
assert failed.last_refresh_at is not None
assert untouched is not None and untouched.last_refresh_at is None
def test_credentials_and_delete_user() -> None:
import admin.users as users
users.build_client = lambda *_args, **_kwargs: (_ for _ in ()).throw(AssertionError("不应请求 e 学"))
_add_account("6650000146")
_add_account("empty-user", credential=None)
api = _app()
admin = TestClient(api.app)
assert admin.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
secret = admin.get("/api/admin/users/6650000146/credentials")
assert secret.status_code == 200
assert secret.json()["password"] == "secret-pass"
assert secret.json()["ucs_token"] == "ucs-1"
assert secret.json()["yxt_token"] == "yxt-1"
assert "detail" not in secret.json()
missing = admin.get("/api/admin/users/empty-user/credentials")
assert missing.json()["detail"] == "尚未完成登录或已注销"
assert missing.json()["password"] == "secret-pass"
assert missing.json()["yxt_token"] == ""
user = TestClient(api.app)
user.cookies.set(COOKIE_NAME, encrypt_secret("6650000146"))
assert user.get("/api/session").json() == {"role": "user", "employee_id": "6650000146"}
removed = admin.delete("/api/admin/users/6650000146")
assert removed.status_code == 200
assert removed.json() == {"ok": True}
with SessionLocal() as db:
assert db.get(Account, "6650000146") is None
assert user.get("/api/session").status_code == 401
assert admin.get("/api/admin/users/6650000146/credentials").status_code == 404
def test_pause_only_changes_refresh_flag() -> None:
_add_account("6650000146", paused=False)
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
response = client.post("/api/admin/users/6650000146/refresh", json={"paused": True})
assert response.status_code == 200
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None
assert account.refresh_paused is True
assert account.credential_cipher
assert decrypt_secret(account.password_cipher) == "secret-pass"
listed = client.get("/api/admin/users").json()
row = next(item for item in listed if item["employee_id"] == "6650000146")
assert row["refresh_paused"] is True
assert row["has_credential"] is True
def test_user_cannot_call_admin_and_logout_clears_only_its_cookie() -> None:
api = _app()
api.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: {"employee_id": employee_id}
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
_add_account("6650000146")
assert client.get("/api/admin/users").status_code == 401
assert client.get("/api/admin/settings").status_code == 401
assert client.post("/api/admin/logout").status_code == 200
assert client.get("/api/session").json()["role"] == "user"
assert client.post("/api/logout").status_code == 200
assert client.get("/api/session").status_code == 401
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
assert client.post("/api/logout").status_code == 200
assert client.get("/api/session").json()["role"] == "admin"
assert client.post("/api/admin/logout").status_code == 200
assert client.get("/api/session").status_code == 401
def test_auto_attempts_count_only_rejections(monkeypatch) -> None:
monkeypatch.setattr("euniv.client.jigsaw_offset", lambda *_args: 12)
client = EunivClient.__new__(EunivClient)
loads = {"n": 0}
submits = {"n": 0}
def load():
loads["n"] += 1
return b"b", b"s", 1
def submit(_offset: int):
submits["n"] += 1
if submits["n"] == 1:
raise JigsawRejected("拼图未通过")
raise RuntimeError("登录失败:密码错误")
client._load_jigsaw = load
client.submit_jigsaw = submit
client.current_puzzle = lambda: {"y": 1}
try:
client._login_with_jigsaw(False, 5)
except RuntimeError as exc:
assert "密码错误" in str(exc)
else:
raise AssertionError("密码错误应立即停止")
assert submits["n"] == 2
assert loads["n"] == 2
submits["n"] = 0
loads["n"] = 0
def reject(_offset: int):
submits["n"] += 1
raise JigsawRejected("拼图未通过")
client.submit_jigsaw = reject
try:
client._login_with_jigsaw(False, 4)
except ManualJigsaw:
pass
else:
raise AssertionError("用完次数后应交给手动拼图")
assert submits["n"] == 4
assert loads["n"] == 5
loads["n"] = 0
try:
client._login_with_jigsaw(True, 4)
except ManualJigsaw:
pass
else:
raise AssertionError("直接手动时不应自动滑动")
assert loads["n"] == 1
def test_settings_do_not_expose_process_switches() -> None:
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
body = client.get("/api/admin/settings").json()
assert set(body) == {
"refresh_interval_minutes",
"show_manual_jigsaw",
"manual_preference",
"auto_jigsaw_attempts",
"admin_username",
}
assert identity.password_cipher()
assert decrypt_secret(identity.password_cipher()) == INITIAL_PASSWORD