douyinWEB/backend/tests/test_xposed_control.py
Eric ada3de5c52 Add Xposed LiveCam control console and document it in README.
Pairs Android devices over WSS for TikTok/YouTube preview and go-live from monitored Douyin sources; also spreads TikTok uploads across the Beijing day with per-channel claim cooldown.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-29 17:28:47 +08:00

157 lines
8.1 KiB
Python

import time
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app import xposed_control as control
from app.session_auth import SESSION_COOKIE, SessionAuthMiddleware, create_session_token
@pytest.fixture()
def client(temp_db):
app = FastAPI()
app.include_router(control.router)
app.add_middleware(SessionAuthMiddleware)
with TestClient(app) as client:
client.cookies.set(SESSION_COOKIE, create_session_token("test-admin"))
yield client
control._clients.clear()
def paired(client):
code = client.post("/api/xposed/pair-codes", json={"name": "Test phone"}).json()["code"]
response = client.post("/api/xposed/device/enroll", json={"code": code, "model": "test"})
assert response.status_code == 200
return code, response.json()
def queue(client, device, action, payload=None, when=0, request_id=None):
body = {"action": action, "payload": payload or {}, "not_before": when}
if request_id:
body["request_id"] = request_id
return client.post(f"/api/xposed/devices/{device['device_id']}/commands", json=body)
def test_pairing_is_one_use_and_device_credentials_are_not_exposed(client):
code, device = paired(client)
assert client.post("/api/xposed/device/enroll", json={"code": code}).status_code == 401
listing = client.get("/api/xposed/devices")
assert "token_hash" not in listing.text and device["token"] not in listing.text
client.cookies.clear()
assert client.get("/api/xposed/devices", headers={"Authorization": "Bearer " + device["token"]}).status_code == 401
with pytest.raises(Exception):
control.authenticate(device["device_id"], "wrong-token")
def test_readonly_cannot_pair_or_send_commands(client):
_, device = paired(client)
client.cookies.set(SESSION_COOKIE, create_session_token("reader", role="readonly"))
assert client.get("/api/xposed/devices").status_code == 200
assert client.post("/api/xposed/pair-codes", json={"name": "bad"}).status_code == 403
assert queue(client, device, "open_app").status_code == 403
def test_queue_deduplicates_and_never_replays_sent_ui_action(client):
_, device = paired(client)
config = {"platform": "tiktok", "source": "375743009479"}
first = queue(client, device, "apply_source", config, request_id="stable-request-id")
assert first.status_code == 200
assert queue(client, device, "apply_source", config, request_id="stable-request-id").json()["duplicate"]
command = control.next_command(device["device_id"])
assert command["config"]["source"] == "https://live.douyin.com/375743009479"
assert control.next_command(device["device_id"]) is None
control.acknowledge(device["device_id"], {"id": command["id"], "status": "succeeded", "message": "applied"})
assert control.next_command(device["device_id"]) is None
assert len(client.get(f"/api/xposed/devices/{device['device_id']}/commands").json()["commands"]) == 1
def test_expired_command_not_delivered_and_schedule_does_not_apply_early(client):
_, device = paired(client)
queue(client, device, "apply_source", {"platform": "youtube", "source": "375743009479"})
cmd = control.next_command(device["device_id"])
control.acknowledge(device["device_id"], {"id": cmd["id"], "status": "succeeded"})
queue(client, device, "start_live", when=time.time()+3600)
assert control.next_command(device["device_id"]) is None
queue(client, device, "open_app", request_id="expired-command")
with control.store() as c:
c.execute("UPDATE xposed_commands SET expires_at=? WHERE id='expired-command'", (time.time()-1,))
assert control.next_command(device["device_id"]) is None
statuses = {c["id"]: c["status"] for c in client.get(f"/api/xposed/devices/{device['device_id']}/commands").json()["commands"]}
assert statuses["expired-command"] == "expired"
def test_device_cannot_ack_another_devices_command_and_revocation_invalidates_token(client):
_, a = paired(client)
_, b = paired(client)
queue(client, a, "apply_source", {"platform": "tiktok", "source": "375743009479"}, request_id="device-a-command")
control.next_command(a["device_id"])
control.acknowledge(b["device_id"], {"id": "device-a-command", "status": "succeeded"})
assert client.get(f"/api/xposed/devices/{a['device_id']}/commands").json()["commands"][0]["status"] == "sent"
assert client.delete(f"/api/xposed/devices/{a['device_id']}").status_code == 200
with pytest.raises(Exception):
control.authenticate(a["device_id"], a["token"])
def test_source_validation_prevents_arbitrary_server_fetch_and_shell_commands(client):
_, d = paired(client)
for source in ("http://127.0.0.1/admin", "https://live.douyin.com.evil.example/123456", "file:///etc/passwd"):
assert queue(client, d, "apply_source", {"platform": "youtube", "source": source}).status_code == 422
assert queue(client, d, "shell", {"cmd": "id"}).status_code == 422
def test_websocket_dispatch_and_ack_with_device_only_credentials(client):
_, d = paired(client)
queue(client, d, "apply_source", {"platform": "youtube", "source": "375743009479"})
client.cookies.clear()
headers = {"X-Device-ID": d["device_id"], "Authorization": "Bearer " + d["token"]}
with client.websocket_connect("/api/xposed/device/ws", headers=headers) as ws:
assert ws.receive_json()["type"] == "connected"
cmd = ws.receive_json()
assert cmd["action"] == "apply_source"
ws.send_json({"type": "heartbeat", "data": {"page": "PREVIEW", "model": "test", "media": {"active": True}}})
ws.send_json({"type": "ack", "id": cmd["id"], "status": "succeeded", "message": "ok"})
assert ws.receive_json()["type"] == "ack_received"
# A following command is only sent after the acknowledgement is persisted.
client.cookies.set(SESSION_COOKIE, create_session_token("test-admin"))
queue(client, d, "open_app")
assert ws.receive_json()["action"] == "open_app"
def test_sent_timeout_is_uncertain_and_late_ack_can_reconcile(client):
_, d = paired(client)
queue(client, d, "apply_source", {"platform": "youtube", "source": "375743009479"}, request_id="timeout-command")
control.next_command(d["device_id"])
with control.store() as c:
c.execute("UPDATE xposed_commands SET sent_at=? WHERE id=?", (time.time()-181, "timeout-command"))
assert control.next_command(d["device_id"]) is None
history_url = f"/api/xposed/devices/{d['device_id']}/commands"
assert client.get(history_url).json()["commands"][0]["status"] == "uncertain"
control.acknowledge(d["device_id"], {"id": "timeout-command", "status": "succeeded"})
assert client.get(history_url).json()["commands"][0]["status"] == "succeeded"
assert control.next_command(d["device_id"]) is None
def test_source_endpoint_uses_only_device_assignment_and_keeps_site_cookie_private(client, monkeypatch):
_, d = paired(client)
queue(client, d, "apply_source", {"platform": "tiktok", "source": "375743009479"})
control.next_command(d["device_id"])
control._source_cache.clear()
calls = []
async def check_room(source, *, cookie, proxy):
calls.append((source, cookie, proxy))
return {"ok": True, "is_live": True, "stream_candidates": [{"url": "https://media.example/live.flv"}]}
monkeypatch.setattr(control.db, "get_settings_map", lambda: {"dy_cookie": "private-site-cookie", "http_proxy": "http://proxy.example:8080"})
monkeypatch.setattr(control.douyin, "check_room", check_room)
client.cookies.clear()
headers = {"X-Device-ID": d["device_id"], "Authorization": "Bearer " + d["token"]}
response = client.get("/api/xposed/device/source?source=https://evil.example", headers=headers)
assert response.status_code == 200
assert response.json()["source"] == "https://live.douyin.com/375743009479"
assert calls == [("https://live.douyin.com/375743009479", "private-site-cookie", "http://proxy.example:8080")]
assert "private-site-cookie" not in response.text and "proxy.example" not in response.text
assert client.get("/api/xposed/device/source").status_code == 401
control._source_cache.clear()