"""``launch_served``: the one build of a served service, with the rules its purpose picks.""" from __future__ import annotations from types import SimpleNamespace from typing import Any import click import pytest from tests.remote.sessions import session_launch from unshackle.core.api import handlers, key_policy from unshackle.core.api.errors import APIError from unshackle.core.api.input_bridge import NoUserBridge from unshackle.core.api.stats import stats from unshackle.core.remote_protocol import APIErrorCode, Licensor pytestmark = pytest.mark.unit @click.command() @click.option("--server-side", is_flag=True, default=False) def server_side_cli(server_side: bool) -> None: ... class ServerSideModule: SERVER_DEVICE_OPTIONS = ("server_side",) cli = server_side_cli class Built: def __init__(self) -> None: self.logins: list[tuple[Any, Any]] = [] def authenticate(self, cookies: Any, credential: Any) -> None: self.logins.append((cookies, credential)) @pytest.fixture def seen(monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> dict[str, Any]: """Stub everything around the launch and record what it asked for.""" record: dict[str, Any] = {"cdm_types": []} monkeypatch.setattr(handlers.config.directories, "cache", tmp_path) monkeypatch.setattr(stats, "mode", "full") monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {}) monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *a: (None, [])) monkeypatch.setattr(handlers, "resolve_server_account", lambda *a: None) monkeypatch.setattr( handlers, "load_full_cdm", lambda service, profile, cdm_type, cfg: record["cdm_types"].append(cdm_type) ) monkeypatch.setattr(handlers.Services, "load", lambda tag: ServerSideModule) monkeypatch.setattr(handlers, "server_account_cookies", lambda *a: "account-jar") monkeypatch.setattr("unshackle.core.login.get_cookie_jar", lambda *a: "server-jar") monkeypatch.setattr("unshackle.core.login.get_credentials", lambda *a: "server-credential") def instantiate(parent_ctx: click.Context, module: Any, title: str, *rest: Any) -> Built: record["keys"] = rest[1] if rest else None return Built() monkeypatch.setattr(handlers, "instantiate_service", instantiate) return record PURPOSES = { "list": lambda: handlers.LIST, "search": lambda: handlers.SEARCH, "session": lambda: session_launch(), "server-cdm session": lambda: session_launch(Licensor.SERVER_CDM), } @pytest.mark.parametrize( ("purpose", "server_side", "asked"), [ ("list", False, "widevine"), ("list", True, None), ("search", False, "widevine"), ("search", True, None), ("session", True, "widevine"), ("server-cdm session", False, None), ], ) def test_the_purpose_picks_the_cdm_rule(seen: dict, purpose: str, server_side: bool, asked: str | None) -> None: data = {"cdm_type": "widevine", "service_params": {"server_side": server_side}} handlers.launch_served(PURPOSES[purpose](), data, "EXAMPLE", "t", None) assert seen["cdm_types"] == [asked] def test_a_server_cdm_session_follows_the_client_only_on_a_dual_entry(seen: dict, monkeypatch) -> None: monkeypatch.setattr(handlers.config, "cdm", {"EXAMPLE": {"widevine": "wv", "playready": "pr"}}, raising=False) for server_side in (False, True): data = {"cdm_type": "widevine", "service_params": {"server_side": server_side}} handlers.launch_served(session_launch(Licensor.SERVER_CDM), data, "EXAMPLE", "t", None) assert seen["cdm_types"] == ["widevine", None] @pytest.mark.parametrize( ("purpose", "mode", "login"), [ ("list", "full", ("server-jar", "server-credential")), ("list", "remote_only", (None, None)), ("search", "full", ("server-jar", "server-credential")), ("session", "full", (None, None)), ], ) def test_the_purpose_picks_the_login_material( seen: dict, monkeypatch: pytest.MonkeyPatch, purpose: str, mode: str, login: tuple ) -> None: monkeypatch.setattr(stats, "mode", mode) launched = handlers.launch_served(PURPOSES[purpose](), {}, "EXAMPLE", "t", None) assert (launched.cookies, launched.credential) == login @pytest.mark.parametrize("purpose", ["list", "search"]) def test_a_server_account_takes_its_own_files_and_cache(seen: dict, monkeypatch, purpose: str) -> None: monkeypatch.setattr(handlers, "resolve_server_account", lambda *a: "acct") launched = handlers.launch_served(PURPOSES[purpose](), {}, "EXAMPLE", "t", None) assert (launched.cookies, launched.service.cache.service_tag) == ("account-jar", "_accounts/EXAMPLE/acct") def test_a_session_on_a_server_account_takes_its_own_files_and_cache(seen: dict) -> None: purpose = session_launch(server_account=True) launched = handlers.launch_served(purpose, {"cookies": "client"}, "EXAMPLE", "t", "work") assert (launched.cookies, launched.service.cache.service_tag) == ("account-jar", "_accounts/EXAMPLE/work") def test_a_session_runs_on_its_own_cache_and_bridge_and_logs_in_later(seen: dict) -> None: purpose = session_launch() launched = handlers.launch_served(purpose, {}, "EXAMPLE", "t", None) assert launched.service.cache.service_tag == purpose.cache_dir assert launched.service._input_bridge is purpose.input_bridge assert launched.service.logins == [] assert launched.licensing == purpose.licensing assert seen["keys"] == handlers.SESSION_TRANSPORT_KEYS @pytest.mark.parametrize(("purpose", "keys"), [("list", handlers.LIST_HANDLER_TRANSPORT_KEYS), ("search", None)]) def test_a_list_or_search_logs_in_with_no_user(seen: dict, purpose: str, keys: set | None) -> None: launched = handlers.launch_served(PURPOSES[purpose](), {}, "EXAMPLE", "t", None) assert isinstance(launched.service._input_bridge, NoUserBridge) assert launched.service.logins == [("server-jar", "server-credential")] assert seen["keys"] == keys def test_an_anonymous_search_skips_the_login(seen: dict, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(ServerSideModule, "ANONYMOUS_SEARCH", True, raising=False) launched = handlers.launch_served(handlers.SEARCH, {}, "EXAMPLE", "q", None) assert (launched.cookies, launched.service.logins) == (None, []) def test_only_a_search_maps_a_failed_build_to_a_service_error(seen: dict, monkeypatch: pytest.MonkeyPatch) -> None: def broken(*a: Any) -> Any: raise RuntimeError("boom") monkeypatch.setattr(handlers, "instantiate_service", broken) with pytest.raises(APIError) as exc: handlers.launch_served(handlers.SEARCH, {}, "EXAMPLE", "q", None) assert exc.value.error_code is APIErrorCode.SERVICE_ERROR with pytest.raises(RuntimeError): handlers.launch_served(handlers.LIST, {}, "EXAMPLE", "t", None) def test_a_lent_device_turns_the_session_licensing_lent(seen: dict, monkeypatch: pytest.MonkeyPatch) -> None: lent = Built() lent.ctx = SimpleNamespace(obj=SimpleNamespace(cdm=SimpleNamespace(lent=True))) # type: ignore[attr-defined] monkeypatch.setattr(handlers, "instantiate_service", lambda *a: lent) launched = handlers.launch_served(session_launch(Licensor.CLIENT_DEVICE), {}, "EXAMPLE", "t", None) assert launched.licensing is not None and launched.licensing.licensor is Licensor.LENT_DEVICE @pytest.mark.parametrize(("licensor", "routed"), [(Licensor.NO_DEVICE, True), (Licensor.CLIENT_DEVICE, False)]) def test_a_session_keeps_identity_keys_apart_unless_the_identity_is_the_clients( seen: dict, monkeypatch: pytest.MonkeyPatch, licensor: Licensor, routed: bool ) -> None: monkeypatch.setattr(Built, "IDENTITY_CACHE", ("keys/",), raising=False) launched = handlers.launch_served(session_launch(licensor), {}, "EXAMPLE", "t", None) assert (launched.service.cache.route is not None) is routed