201 lines
6.8 KiB
Python
201 lines
6.8 KiB
Python
import json
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
|
|
from euniv.client import (
|
|
QR_PASSWORD_MARK,
|
|
EunivClient,
|
|
QrWaiting,
|
|
encrypt_field,
|
|
is_qr_password,
|
|
make_qr_payload,
|
|
parse_uac,
|
|
qr_data_uri,
|
|
set_cookie,
|
|
)
|
|
from euniv.crypto import decrypt_secret
|
|
from euniv.db import SessionLocal
|
|
from euniv.models import Account
|
|
|
|
|
|
def test_parse_uac_nested_and_flat() -> None:
|
|
top, inner, data, message = parse_uac(
|
|
{
|
|
"code": {"code": "0000", "msg": "操作成功"},
|
|
"bo": {"code": "4002", "msg": "二维码状态轮询失败"},
|
|
"other": None,
|
|
}
|
|
)
|
|
assert top == "0000"
|
|
assert inner == "4002"
|
|
assert data is None
|
|
assert "二维码" in message
|
|
|
|
top, inner, data, message = parse_uac(
|
|
{
|
|
"code": {"code": "0000", "msg": "操作成功"},
|
|
"bo": {"code": "0000", "msg": "成功"},
|
|
"other": {"data": {"callbackUrl": "https://example.test/sso?code=1"}},
|
|
}
|
|
)
|
|
assert top == inner == "0000"
|
|
assert data == {"callbackUrl": "https://example.test/sso?code=1"}
|
|
|
|
top, inner, data, message = parse_uac(
|
|
{
|
|
"code": "0000",
|
|
"reason": {"zh_CN": "成功"},
|
|
"data": {"accountId": "6650000146", "token": "abc"},
|
|
}
|
|
)
|
|
assert top == inner == "0000"
|
|
assert data["token"] == "abc"
|
|
assert message == "成功"
|
|
|
|
|
|
def test_qr_payload_and_rsa_cipher_shape() -> None:
|
|
text = make_qr_payload()
|
|
prefix, key, value = text.split(":")
|
|
assert prefix == "TwoDIMAuth"
|
|
assert len(key) == 32
|
|
assert len(value) == 32
|
|
assert int(key, 16) >= 0
|
|
cipher = encrypt_field("6650000146")
|
|
assert len(cipher) == 344
|
|
assert is_qr_password(QR_PASSWORD_MARK)
|
|
assert not is_qr_password("secret-pass")
|
|
uri = qr_data_uri(text)
|
|
assert uri.startswith("data:image/png;base64,")
|
|
|
|
|
|
def test_qr_password_cannot_use_password_login() -> None:
|
|
client = EunivClient("6650000146", QR_PASSWORD_MARK)
|
|
try:
|
|
with pytest.raises(RuntimeError, match="扫码登录已失效"):
|
|
client.login()
|
|
finally:
|
|
client.close()
|
|
|
|
|
|
def test_qr_login_stores_scan_mark(monkeypatch) -> None:
|
|
import euniv.api as api_module
|
|
import euniv.service as service_module
|
|
|
|
service_module._pending.clear()
|
|
service_module._pending_qr.clear()
|
|
|
|
class QrClient:
|
|
def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None:
|
|
self.login_name = login_name
|
|
self.password = password
|
|
self.proxy = proxy
|
|
self._profile: dict = {}
|
|
self._token = "yxt-qr"
|
|
self._polls = 0
|
|
|
|
def close(self) -> None:
|
|
return None
|
|
|
|
def start_qr(self) -> tuple[str, str]:
|
|
return "TwoDIMAuth:aa:bb", "data:image/png;base64,QQ=="
|
|
|
|
def poll_qr(self) -> dict:
|
|
self._polls += 1
|
|
if self._polls == 1:
|
|
raise QrWaiting()
|
|
return {
|
|
"accountId": "6650000146",
|
|
"userId": "6650000146",
|
|
"token": "ucs-qr",
|
|
"unionId": "un-1",
|
|
}
|
|
|
|
def authorize(self, profile: dict) -> None:
|
|
self._profile = dict(profile)
|
|
|
|
def export_credential(self) -> dict:
|
|
return {
|
|
"ucs_token": self._profile["token"],
|
|
"ucs_account_id": self._profile["accountId"],
|
|
"ucs_user_id": self._profile["userId"],
|
|
"ucs_ssoinfo": "",
|
|
"ucs_union_id": self._profile.get("unionId") or "",
|
|
"yxt_token": self._token,
|
|
}
|
|
|
|
monkeypatch.setattr(api_module, "start_qr_login", lambda: service_module.start_qr_login(QrClient))
|
|
monkeypatch.setattr(api_module, "poll_qr_login", service_module.poll_qr_login)
|
|
monkeypatch.setattr(service_module, "_request_course_sync", lambda employee_id: None)
|
|
|
|
client = TestClient(api_module.app)
|
|
started = client.post("/api/login/qr")
|
|
assert started.status_code == 200
|
|
body = started.json()
|
|
assert body["qr_image"].startswith("data:image/png;base64,")
|
|
attempt_id = body["attempt_id"]
|
|
|
|
waiting = client.post("/api/login/qr/poll", json={"attempt_id": attempt_id})
|
|
assert waiting.status_code == 200
|
|
assert waiting.json() == {"status": "waiting"}
|
|
|
|
done = client.post("/api/login/qr/poll", json={"attempt_id": attempt_id})
|
|
assert done.status_code == 200
|
|
assert done.json() == {"role": "user", "employee_id": "6650000146"}
|
|
|
|
with SessionLocal() as db:
|
|
account = db.get(Account, "6650000146")
|
|
assert account is not None
|
|
assert decrypt_secret(account.password_cipher) == QR_PASSWORD_MARK
|
|
stored = json.loads(decrypt_secret(account.credential_cipher))
|
|
assert stored["ucs_token"] == "ucs-qr"
|
|
assert stored["yxt_token"] == "yxt-qr"
|
|
assert "secret" not in decrypt_secret(account.password_cipher)
|
|
|
|
|
|
def test_async_study_hook_can_be_awaited() -> None:
|
|
import asyncio
|
|
import inspect
|
|
|
|
import httpx
|
|
|
|
from euniv.autostudy import StudySession
|
|
|
|
seen: dict[str, str | None] = {}
|
|
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
seen["host"] = request.url.host
|
|
seen["token"] = request.headers.get("token")
|
|
return httpx.Response(200, text="ok")
|
|
|
|
async def main() -> None:
|
|
async with StudySession("secret-token", []) as session:
|
|
hook = session._client._event_hooks["request"][0]
|
|
assert inspect.iscoroutinefunction(hook)
|
|
async with httpx.AsyncClient(
|
|
transport=httpx.MockTransport(handler),
|
|
event_hooks={"request": [hook]},
|
|
) as client:
|
|
other = await client.get("https://example.com/x", headers={"token": "secret-token"})
|
|
assert other.status_code == 200
|
|
assert seen["token"] is None
|
|
kept = await client.get("https://euniv.zte.com.cn/kng/view/video/x.html", headers={"token": "secret-token"})
|
|
assert kept.status_code == 200
|
|
assert seen["token"] == "secret-token"
|
|
|
|
asyncio.run(main())
|
|
|
|
|
|
def test_secure_cookie_is_written_through_the_jar() -> None:
|
|
client = EunivClient("6650000146", "secret-pass")
|
|
try:
|
|
set_cookie(client.client.cookies, "PORTALSSOCookie", "token", domain="zte.com.cn", path="/", secure=True)
|
|
client.restore({"yxt_token": "learning-token", "ucs_token": "ucs", "ucs_account_id": "6650000146"})
|
|
portal = [item for item in client.client.cookies.jar if item.name == "PORTALSSOCookie"]
|
|
learning = [item for item in client.client.cookies.jar if item.name == "ELEARNING_00024"]
|
|
assert portal and portal[0].secure is True
|
|
assert len(learning) == 2
|
|
assert all(item.secure for item in learning)
|
|
finally:
|
|
client.close()
|