mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-06 07:55:10 +00:00
309 lines
13 KiB
Python
309 lines
13 KiB
Python
"""The real remote client against the real server routes, over HTTP on a loopback port."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import logging
|
|
from collections.abc import Callable, Iterator
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
from threading import Semaphore, Thread
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
|
|
import click
|
|
import pytest
|
|
import requests
|
|
from aiohttp import web
|
|
from langcodes import Language
|
|
|
|
from tests.remote.sessions import stub_service_build
|
|
from tests.remote.unit.test_tunnel import wait_until
|
|
from unshackle.core import remote_channel, remote_service
|
|
from unshackle.core.api import handlers, routes, session_store
|
|
from unshackle.core.api.handlers import api_key_authentication
|
|
from unshackle.core.api.routes import cors_middleware, no_5xx_middleware, setup_routes
|
|
from unshackle.core.config import config
|
|
from unshackle.core.remote_service import RemoteService
|
|
from unshackle.core.session import RnetSession, record_requests
|
|
from unshackle.core.title_source import TitleSource
|
|
from unshackle.core.titles.movie import Movie, Movies
|
|
from unshackle.core.tracks import Audio, Chapters, Tracks
|
|
from unshackle.core.tracks.track import Track
|
|
from unshackle.core.utilities import close_debug_logger, init_debug_logger
|
|
|
|
pytestmark = pytest.mark.unit
|
|
|
|
KEY = "loopback-key"
|
|
OTHER_KEY = "other-key"
|
|
CODE = "1234"
|
|
|
|
|
|
class StubService:
|
|
"""The server side of the remote session: a login that asks for a code, three titles, one audio track each.
|
|
|
|
A test puts extra service work in ``hooks``: "titles" runs inside get_titles, on the service thread.
|
|
"""
|
|
|
|
LICENSE_FIRST = False
|
|
logins = 0
|
|
hooks: dict[str, Callable[[StubService], None]] = {}
|
|
|
|
def __init__(self, beats: Semaphore) -> None:
|
|
self.beats = beats
|
|
self.log = logging.getLogger("stub-server")
|
|
self.session = requests.Session()
|
|
self.cache = None
|
|
self._input_bridge: Any = None
|
|
StubService.logins += 1
|
|
self.login = StubService.logins
|
|
if hook := self.hooks.get("init"):
|
|
hook(self)
|
|
|
|
def authenticate(self, cookies: Any, credential: Any) -> None:
|
|
if self._input_bridge.request_input("Enter the EXAMPLE code") != CODE:
|
|
raise ValueError("wrong code")
|
|
self.log.info(f"Logged in to EXAMPLE, login {self.login}")
|
|
|
|
def get_titles(self) -> Movies:
|
|
if hook := self.hooks.get("titles"):
|
|
hook(self)
|
|
return Movies(
|
|
[Movie(id_=f"example-{n}", service=StubService, name=f"Example {n}", year=2024) for n in (1, 2, 3)]
|
|
)
|
|
|
|
def get_tracks(self, title: Movie) -> Tracks:
|
|
"""Answer after the route sent its first heartbeat, so every tracks call outlasts one interval."""
|
|
assert self.beats.acquire(timeout=10), "the tracks route sent no heartbeat"
|
|
if title.id == "example-3":
|
|
raise ValueError("No tracks for OTHER region")
|
|
audio = Audio(
|
|
url=f"https://cdn.example/{title.id}.m4a",
|
|
language=Language.get("en"),
|
|
descriptor=Track.Descriptor.URL,
|
|
codec=Audio.Codec.AAC,
|
|
bitrate=128_000,
|
|
channels=2,
|
|
id_=f"{title.id}-login{self.login}",
|
|
)
|
|
return Tracks([audio])
|
|
|
|
def get_chapters(self, title: Movie) -> Chapters:
|
|
return Chapters()
|
|
|
|
def decrypts_samples(self, track: Any) -> bool:
|
|
return False
|
|
|
|
def get_widevine_license(self, *, challenge: bytes, title: Movie, track: Any, **_: Any) -> bytes:
|
|
"""Make one call on the client's CDM, as a service with a CDM-based licence step does."""
|
|
return json.dumps(self._input_bridge.request_cdm({"op": "close", "session": "EXAMPLE"})).encode()
|
|
|
|
fairplay_bridge = TitleSource.fairplay_bridge
|
|
|
|
|
|
@pytest.fixture
|
|
def server(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> Iterator[SimpleNamespace]:
|
|
"""The real route table and API key middleware on a loopback port, with the stub as the only service.
|
|
|
|
A test parametrized with ``server=False`` gets a gateway in front of it that answers the channel upgrade with 502.
|
|
"""
|
|
refuse = not getattr(request, "param", True)
|
|
beats = Semaphore(0)
|
|
seen: list[tuple[str, str, int]] = []
|
|
bodies: list[tuple[str, bytes]] = []
|
|
|
|
class CountedHeartbeat(web.StreamResponse):
|
|
"""Count the first heartbeat of each tracks request; aiohttp calls prepare again when the handler returns."""
|
|
|
|
async def prepare(self, request: web.BaseRequest) -> Any:
|
|
first = not self.prepared
|
|
writer = await super().prepare(request)
|
|
if first and request.path.endswith("/tracks"):
|
|
beats.release()
|
|
return writer
|
|
|
|
@web.middleware
|
|
async def record(request: web.Request, handler: Any) -> web.StreamResponse:
|
|
if refuse and request.path.endswith("/channel"):
|
|
seen.append((request.method, request.path, 502))
|
|
return web.Response(status=502, text="Bad gateway")
|
|
try:
|
|
response = await handler(request)
|
|
except web.HTTPException as e:
|
|
seen.append((request.method, request.path, e.status))
|
|
raise
|
|
seen.append((request.method, request.path, response.status))
|
|
if isinstance(response, web.Response) and response.body is not None:
|
|
bodies.append((request.path, bytes(response.body))) # type: ignore[arg-type]
|
|
return response
|
|
|
|
StubService.logins = 0
|
|
monkeypatch.setattr(StubService, "hooks", {})
|
|
monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 0.02)
|
|
monkeypatch.setattr(routes.web, "StreamResponse", CountedHeartbeat)
|
|
monkeypatch.setattr(remote_channel, "AUTH_POLL_INTERVAL", 0.01)
|
|
monkeypatch.setattr(remote_service, "REOPEN_WAIT", 5.0)
|
|
monkeypatch.setattr(session_store, "session_store", None)
|
|
monkeypatch.setattr(config, "serve", {"session_ttl": 1.5})
|
|
monkeypatch.setattr(config, "credentials", {})
|
|
monkeypatch.setattr(config.directories, "cache", tmp_path / "cache")
|
|
monkeypatch.setattr(config.directories, "cookies", tmp_path / "cookies")
|
|
monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service)
|
|
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
|
|
monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
|
|
monkeypatch.setattr(handlers.Services, "load", lambda service: StubService)
|
|
stub_service_build(monkeypatch, lambda: StubService(beats))
|
|
|
|
app = web.Application(middlewares=[record, cors_middleware, no_5xx_middleware, api_key_authentication])
|
|
app["config"] = {"users": [KEY, OTHER_KEY]}
|
|
setup_routes(app, remote_only=True)
|
|
|
|
async def close_store(_: web.Application) -> None:
|
|
await session_store.get_session_store().close()
|
|
|
|
app.on_cleanup.append(close_store)
|
|
loop = asyncio.new_event_loop()
|
|
runner = web.AppRunner(app)
|
|
loop.run_until_complete(runner.setup())
|
|
site = web.TCPSite(runner, "127.0.0.1", 0)
|
|
loop.run_until_complete(site.start())
|
|
thread = Thread(target=loop.run_forever, daemon=True)
|
|
thread.start()
|
|
host, port = runner.addresses[0][:2]
|
|
try:
|
|
yield SimpleNamespace(url=f"http://{host}:{port}", loop=loop, seen=seen, bodies=bodies)
|
|
finally:
|
|
asyncio.run_coroutine_threadsafe(runner.cleanup(), loop).result(10)
|
|
loop.call_soon_threadsafe(loop.stop)
|
|
thread.join(10)
|
|
loop.close()
|
|
|
|
|
|
def make_client(url: str, cdm: Any = None) -> RemoteService:
|
|
"""A client whose first candidate header is not the one the server reads, so it must move to the second."""
|
|
obj = SimpleNamespace(cdm=cdm, cdm_entry=False, proxy_providers=[])
|
|
parent = click.Context(click.Command("dl"), obj=obj)
|
|
parent.params = {"no_proxy": True}
|
|
ctx = click.Context(click.Command("EXAMPLE"), parent=parent, obj=obj)
|
|
service = RemoteService(ctx, "EXAMPLE", "example-1", url, KEY, {"_auth_headers": ["X-Api-Key", "X-Secret-Key"]})
|
|
service._input_bridge = SimpleNamespace(request_input=lambda prompt, qr=None: CODE)
|
|
return service
|
|
|
|
|
|
def forget(server: SimpleNamespace, session_id: str) -> None:
|
|
"""Drop the session on the server, as a restart does."""
|
|
store = session_store.get_session_store()
|
|
asyncio.run_coroutine_threadsafe(store.delete(session_id), server.loop).result(10)
|
|
|
|
|
|
def on_loop(server: SimpleNamespace, coroutine: Any) -> Any:
|
|
return asyncio.run_coroutine_threadsafe(coroutine, server.loop).result(10)
|
|
|
|
|
|
def count(server: SimpleNamespace, method: str, route: str, session_id: str | None = None) -> int:
|
|
"""The requests the server saw for one route; without a session id, for any session."""
|
|
if session_id is None:
|
|
prefix, _, suffix = route.partition("{session_id}")
|
|
return len(
|
|
[
|
|
s
|
|
for s in server.seen
|
|
if s[0] == method
|
|
and s[1].startswith(prefix)
|
|
and s[1].endswith(suffix)
|
|
and "/" not in s[1][len(prefix) : len(s[1]) - len(suffix) or None]
|
|
]
|
|
)
|
|
return len([s for s in server.seen if s[:2] == (method, route.format(session_id=session_id))])
|
|
|
|
|
|
def example_messages(caplog: pytest.LogCaptureFixture) -> list[str]:
|
|
"""What the client logged as the service's own lines, which the server relayed."""
|
|
return [r.getMessage() for r in caplog.records if r.name == "EXAMPLE"]
|
|
|
|
|
|
class Origin(BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
|
|
def log_message(self, *_: Any) -> None:
|
|
pass
|
|
|
|
def do_GET(self) -> None:
|
|
self.send_response(200)
|
|
self.send_header("Content-Length", "2")
|
|
self.end_headers()
|
|
self.wfile.write(b"{}")
|
|
|
|
|
|
def test_server_request_records_never_reach_the_remote_client(
|
|
server: SimpleNamespace,
|
|
caplog: pytest.LogCaptureFixture,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
tmp_path: Path,
|
|
) -> None:
|
|
"""The http_request entries of the service's requests stay in the server's JSONL, out of the session log."""
|
|
caplog.set_level(logging.DEBUG)
|
|
origin = ThreadingHTTPServer(("127.0.0.1", 0), Origin)
|
|
origin.daemon_threads = True
|
|
Thread(target=origin.serve_forever, daemon=True).start()
|
|
base = f"127.0.0.1:{origin.server_address[1]}"
|
|
monkeypatch.setattr(config, "debug_requests", True)
|
|
debug_log = tmp_path / "server.jsonl"
|
|
init_debug_logger(log_path=debug_log, enabled=True)
|
|
|
|
def fetch(step: str) -> None:
|
|
plain = requests.Session()
|
|
record_requests(plain)
|
|
plain.get(f"http://{base}/v1/{step}?access_token=EXAMPLE")
|
|
RnetSession().get(f"http://{base}/v1/{step}-rnet?access_token=EXAMPLE")
|
|
|
|
def init(stub: StubService) -> None:
|
|
fetch("init")
|
|
logging.getLogger("StubService").info("EXAMPLE init done")
|
|
|
|
def titles(stub: StubService) -> None:
|
|
fetch("titles")
|
|
stub.log.info("EXAMPLE titles fetched")
|
|
|
|
StubService.hooks.update(init=init, titles=titles)
|
|
service = make_client(server.url)
|
|
try:
|
|
service.authenticate()
|
|
assert len(service.get_titles()) == 3
|
|
assert wait_until(lambda: {"EXAMPLE init done", "EXAMPLE titles fetched"} <= set(example_messages(caplog)), 10)
|
|
(entry,) = session_store.get_session_store()._sessions.values()
|
|
buffered = [r["message"] for r in entry.log_buffer.since(0)]
|
|
finally:
|
|
service.close()
|
|
origin.shutdown()
|
|
origin.server_close()
|
|
close_debug_logger()
|
|
|
|
assert {"EXAMPLE init done", "EXAMPLE titles fetched"} <= set(buffered)
|
|
sent = [*buffered, *example_messages(caplog), *(body.decode("utf-8", "replace") for _, body in server.bodies)]
|
|
for text in sent:
|
|
assert "http_request" not in text and base not in text and "/v1/" not in text
|
|
records = [json.loads(line) for line in debug_log.read_text(encoding="utf-8").splitlines()]
|
|
entries = [e for e in records if e.get("operation") == "http_request"]
|
|
assert {"/v1/init", "/v1/init-rnet", "/v1/titles", "/v1/titles-rnet"} <= {e["request"]["path"] for e in entries}
|
|
server_host = server.url.split("://")[1].rstrip("/")
|
|
assert all("body" not in e["response"] for e in entries)
|
|
own = [e for e in entries if e["request"]["host"] == server_host and e["request"]["path"].endswith("/titles")]
|
|
assert own and all((tmp_path / "server" / e["response"]["body_file"]).is_file() for e in own)
|
|
|
|
|
|
@pytest.mark.parametrize("forced", [True, False])
|
|
def test_the_client_reports_the_license_first_of_the_served_service(
|
|
server: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, forced: bool
|
|
) -> None:
|
|
monkeypatch.setattr(StubService, "LICENSE_FIRST", forced)
|
|
remote = make_client(server.url)
|
|
try:
|
|
remote.authenticate()
|
|
remote.get_tracks(remote.get_titles()[0])
|
|
finally:
|
|
remote.close()
|
|
|
|
assert remote.LICENSE_FIRST is forced
|