Files
EnuivTools/backend/tests/test_encrypt.py
T

90 lines
3.1 KiB
Python

import inspect
import httpx
from euniv import autostudy as autostudy_mod
from euniv import client as client_mod
from euniv.encrypt import (
encrypt_path_from_js,
encrypt_payload,
fetch_encryption,
note_play_html,
parse_encrypt_response,
reset_encrypt_config,
)
def test_encrypt_payload_wraps_progress_json_as_string() -> None:
body = '{"knowledgeId":"abc","end":false}'
assert encrypt_payload(body) == b'{"body":"{\\"knowledgeId\\":\\"abc\\",\\"end\\":false}"}'
def test_parse_encrypt_response_accepts_wcf_shapes() -> None:
digest = "a" * 32
as_object = httpx.Response(200, json={"Status": "OK", "Data": digest})
assert parse_encrypt_response(as_object) == digest
as_string = httpx.Response(200, json='{"Status":"OK","Data":"%s"}' % digest)
assert parse_encrypt_response(as_string) == digest
quoted = httpx.Response(200, text="{'Status':'OK','Data':'%s'}" % digest)
assert parse_encrypt_response(quoted) == digest
wrapped = httpx.Response(200, json={"d": '{"Status":"OK","Data":"%s"}' % digest})
assert parse_encrypt_response(wrapped) == digest
live = httpx.Response(
200,
text='"{\'Status\':\'OK\',\'Data\':\'%s\'}"' % digest,
headers={"content-type": "application/json; charset=utf-8"},
)
assert parse_encrypt_response(live) == digest
def test_note_play_html_and_js_path() -> None:
reset_encrypt_config()
html = (
'<script src="https://staticbdc1.yunxuetang.cn/SystemFiles/Js/'
'kng_studytrack_rw.js?v=10.11.45"></script>'
)
note_play_html(html, "https://euniv.zte.com.cn")
js = (
'jQuery.ajax({type:"POST",contentType:"text/json",'
'url:"/kng/services/KngComService.svc/GetEncryptRequest",data:arr})'
)
assert encrypt_path_from_js(js) == "/kng/services/KngComService.svc/GetEncryptRequest"
def test_fetch_encryption_posts_player_body() -> None:
reset_encrypt_config()
seen: dict[str, bytes] = {}
def handler(request: httpx.Request) -> httpx.Response:
if "kng_studytrack_rw.js" in str(request.url):
return httpx.Response(
200,
text='url:"/kng/services/KngComService.svc/GetEncryptRequest"',
)
seen["content_type"] = request.headers["content-type"].encode()
seen["body"] = request.content
return httpx.Response(200, json={"Status": "OK", "Data": "b" * 32})
with httpx.Client(transport=httpx.MockTransport(handler)) as client:
digest = fetch_encryption(
client,
'{"knowledgeId":"k1"}',
origin="https://euniv.zte.com.cn",
user_agent="UA",
)
assert digest == "b" * 32
assert seen["content_type"] == b"text/json"
assert seen["body"] == b'{"body":"{\\"knowledgeId\\":\\"k1\\"}"}'
def test_client_has_no_hardcoded_study_md5_key() -> None:
for module in (client_mod, autostudy_mod):
source = inspect.getsource(module)
assert "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696" not in source
assert "STUDY_MD5_KEY" not in source
assert "study_encryption" not in source