mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-04 06:55:09 +00:00
261 lines
9.8 KiB
Python
261 lines
9.8 KiB
Python
"""The remote session names the client's DRM plugins: the server refuses a title the client cannot decrypt before it
|
|
lists the tracks, and a stand-in of the client's plugin device carries the device facts the client sent.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
|
|
import click
|
|
import pytest
|
|
|
|
from tests.drm_plugins import ExampleDevice
|
|
from tests.remote.key_source import remote_session
|
|
from tests.remote.sessions import launch_session, stub_service_build
|
|
from unshackle.core.api import handlers, key_policy
|
|
from unshackle.core.api import session_store as store_mod
|
|
from unshackle.core.api.errors import APIError
|
|
from unshackle.core.cdm.detect import cdm_system
|
|
from unshackle.core.drm import CustomDRM
|
|
from unshackle.core.remote_protocol import APIErrorCode, Licensor
|
|
from unshackle.core.tracks import Tracks, Video
|
|
from unshackle.core.tracks.track import Track
|
|
|
|
pytestmark = [pytest.mark.unit, pytest.mark.usefixtures("example_plugins")]
|
|
|
|
DEVICE_FACTS = {"device_name": "EXAMPLE_DEVICE"}
|
|
WIDEVINE_CDM = SimpleNamespace(is_playready=False)
|
|
|
|
|
|
class _SentCreate(Exception):
|
|
pass
|
|
|
|
|
|
def sent_create(cdm_for: Any, local_cdm: Any = WIDEVINE_CDM) -> dict:
|
|
"""The session create body that a client whose ``cdm_for`` gives its plugin devices sends."""
|
|
|
|
def post(path: str, data: dict) -> dict:
|
|
raise _SentCreate(data)
|
|
|
|
svc = remote_session(local_cdm, {})
|
|
svc.ctx.obj.cdm_for = cdm_for
|
|
svc.ctx.obj.cdm_entry = False
|
|
svc.licensing = None
|
|
svc._server_cdm_request = None
|
|
svc.service_tag = "EXAMPLE"
|
|
svc.title_id = "t1"
|
|
svc._server_accounts = {"global": True}
|
|
svc._service_params = {}
|
|
svc._client_config = None
|
|
svc.ctx.parent = SimpleNamespace(params={"no_proxy": True})
|
|
svc.client = SimpleNamespace(post=post)
|
|
with pytest.raises(_SentCreate) as exc:
|
|
svc.authenticate()
|
|
return exc.value.args[0]
|
|
|
|
|
|
def test_the_create_body_lists_each_plugin_with_its_version_and_device_facts(tmp_path: Path) -> None:
|
|
path = tmp_path / "EXAMPLE_DEVICE.exd"
|
|
path.write_bytes(b"\x5a")
|
|
device = ExampleDevice(path)
|
|
|
|
data = sent_create(lambda system, quality=None: device if system == "example" else None)
|
|
|
|
assert data["plugins"] == {"example": {"version": "1.0", "device": DEVICE_FACTS}, "other": {"version": ""}}
|
|
assert str(tmp_path) not in json.dumps(data["plugins"])
|
|
|
|
|
|
def test_a_client_with_no_local_device_sends_no_device_facts() -> None:
|
|
data = sent_create(lambda system, quality=None: pytest.fail("a device was loaded"), local_cdm=None)
|
|
|
|
assert data["plugins"] == {"example": {"version": "1.0"}, "other": {"version": ""}}
|
|
|
|
|
|
def test_a_plugin_device_that_does_not_load_sends_no_facts(caplog: pytest.LogCaptureFixture) -> None:
|
|
def broken(system: str, quality: int | None = None) -> Any:
|
|
raise ValueError("EXAMPLE device file is damaged")
|
|
|
|
data = sent_create(broken)
|
|
|
|
assert data["plugins"] == {"example": {"version": "1.0"}, "other": {"version": ""}}
|
|
assert "EXAMPLE device file is damaged" in caplog.text
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"plugins",
|
|
[
|
|
["example"],
|
|
{"example": "1.0"},
|
|
{"example": {"version": 1}},
|
|
{"example": {"device": ["v5"]}},
|
|
{"example": {"device": {"name": {"nested": True}}}},
|
|
{"example": {"device": {"name": ["v5"]}}},
|
|
{"example": {"device": {"blob": "x" * 20000}}},
|
|
],
|
|
)
|
|
def test_a_malformed_plugin_list_is_refused(plugins: Any) -> None:
|
|
with pytest.raises(APIError) as e:
|
|
handlers.client_plugins(plugins)
|
|
assert e.value.error_code == APIErrorCode.INVALID_INPUT
|
|
|
|
|
|
def test_an_old_client_sends_no_plugin_list() -> None:
|
|
assert handlers.client_plugins(None) is None
|
|
assert handlers.client_plugins({"example": {"version": "1.0"}}) == {"example": {"version": "1.0"}}
|
|
assert handlers.client_plugins({"example": {"device": {"name": None}}}) == {"example": {"device": {"name": None}}}
|
|
|
|
|
|
def plugin_tracks() -> Tracks:
|
|
track = Video(
|
|
id_="vid",
|
|
url="https://example.test/seg0.ts",
|
|
language="en",
|
|
descriptor=Track.Descriptor.HLS,
|
|
codec=Video.Codec.HEVC,
|
|
height=2160,
|
|
drm=[CustomDRM("example", data={"ticket": "00" * 16})],
|
|
)
|
|
return Tracks([track])
|
|
|
|
|
|
def tracks_reply(client_plugins: Any) -> tuple[Any, Any]:
|
|
"""The answer of the tracks route for a title with an EXAMPLE plugin track (its body or its APIError), and the session."""
|
|
|
|
class StubService:
|
|
session = SimpleNamespace(headers={}, cookies=[])
|
|
|
|
def fairplay_bridge(self) -> None:
|
|
return None
|
|
|
|
def get_tracks(self, title: Any) -> Tracks:
|
|
return plugin_tracks()
|
|
|
|
def get_chapters(self, title: Any) -> list:
|
|
return []
|
|
|
|
def decrypts_samples(self, track: Any) -> bool:
|
|
return False
|
|
|
|
async def run() -> tuple[Any, Any]:
|
|
store = store_mod.get_session_store()
|
|
entry = await store.create(
|
|
service_tag="EXAMPLE",
|
|
service_instance=StubService(),
|
|
session_id="plugins",
|
|
client_plugins=client_plugins,
|
|
)
|
|
entry.title_map = {"t1": "EXAMPLE title"}
|
|
try:
|
|
resp = await handlers.session_tracks_handler({"title_id": "t1"}, "plugins")
|
|
answer: Any = json.loads(resp.text)
|
|
except APIError as e:
|
|
answer = e
|
|
finally:
|
|
await store.delete("plugins")
|
|
return answer, entry
|
|
|
|
return asyncio.run(run())
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("client_plugins", "message"),
|
|
[
|
|
(None, "This title needs the DRM plugin 'example', and your unshackle sends no plugin list"),
|
|
({"other": {"version": ""}}, "This title needs the DRM plugin 'example', which your unshackle does not have"),
|
|
],
|
|
)
|
|
def test_a_client_that_cannot_decrypt_the_title_is_refused_before_the_track_list(
|
|
client_plugins: Any, message: str
|
|
) -> None:
|
|
refusal, entry = tracks_reply(client_plugins)
|
|
|
|
assert isinstance(refusal, APIError)
|
|
assert (refusal.error_code, refusal.message) == (APIErrorCode.DRM_ERROR, message)
|
|
assert entry.tracks == {}
|
|
|
|
|
|
def test_a_client_with_the_plugin_gets_the_track_list() -> None:
|
|
body, entry = tracks_reply({"example": {"version": "1.0"}})
|
|
|
|
assert [track["id"] for track in body["video"]] == ["vid"]
|
|
assert list(entry.tracks) == ["vid"]
|
|
|
|
|
|
def test_the_create_route_keeps_the_client_plugin_list(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
|
class Service:
|
|
_input_bridge = None
|
|
log = None
|
|
cache = None
|
|
|
|
def authenticate(self, cookies: Any, credential: Any) -> None:
|
|
pass
|
|
|
|
monkeypatch.setattr(handlers.config.directories, "cache", tmp_path)
|
|
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: Service)
|
|
stub_service_build(monkeypatch, Service)
|
|
listed = {"example": {"version": "1.0", "device": DEVICE_FACTS}}
|
|
|
|
async def run() -> Any:
|
|
resp = await handlers.session_create_handler({"service": "EXAMPLE", "title_id": "t", "plugins": listed})
|
|
session_id = json.loads(resp.body)["session_id"]
|
|
entry = store_mod.get_session_store().peek(session_id)
|
|
await store_mod.get_session_store().delete(session_id)
|
|
return entry
|
|
|
|
assert asyncio.run(run()).client_plugins == listed
|
|
|
|
|
|
def launched_cdm_for(monkeypatch: pytest.MonkeyPatch, licensor: Licensor, client_plugins: Any) -> Any:
|
|
"""The ``cdm_for`` that the service of a remote session gets on the server."""
|
|
seen: dict[str, Any] = {}
|
|
monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {})
|
|
monkeypatch.setattr(handlers, "load_full_cdm", lambda service, profile, cdm_type, cfg: f"server {cdm_type}")
|
|
monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace())
|
|
|
|
def instantiate(parent_ctx: click.Context, *rest: Any) -> Any:
|
|
seen["cdm_for"] = parent_ctx.obj.cdm_for
|
|
return SimpleNamespace()
|
|
|
|
monkeypatch.setattr(handlers, "instantiate_service", instantiate)
|
|
launch_session("EXAMPLE", "t", {"cdm_type": "widevine"}, licensor=licensor, client_plugins=client_plugins)
|
|
return seen["cdm_for"]
|
|
|
|
|
|
def test_a_client_device_session_gives_the_service_a_stand_in_with_the_client_device_facts(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
sent = {"example": {"version": "1.0", "device": {**DEVICE_FACTS, "path": "/client/EXAMPLE_DEVICE.exd"}}}
|
|
cdm_for = launched_cdm_for(monkeypatch, Licensor.CLIENT_DEVICE, sent)
|
|
|
|
stub = cdm_for("example")
|
|
assert cdm_system(stub) == "example"
|
|
assert stub.device_name == "EXAMPLE_DEVICE"
|
|
assert not hasattr(stub, "path")
|
|
assert cdm_for("other") is None
|
|
assert cdm_for("unknown") is None
|
|
assert cdm_system(cdm_for("widevine")) == "widevine"
|
|
assert cdm_for("playready") is None
|
|
|
|
|
|
def test_a_fact_the_client_did_not_send_is_none_on_the_stand_in(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
cdm_for = launched_cdm_for(monkeypatch, Licensor.CLIENT_DEVICE, {"example": {"version": "1.0", "device": {}}})
|
|
assert cdm_for("example").device_name is None
|
|
|
|
|
|
def test_a_client_device_session_with_no_device_facts_gives_no_plugin_device(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
cdm_for = launched_cdm_for(monkeypatch, Licensor.CLIENT_DEVICE, {"example": {"version": "1.0"}})
|
|
assert cdm_for("example") is None
|
|
|
|
|
|
def test_a_server_cdm_session_keeps_the_server_device(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
sent = {"example": {"version": "1.0", "device": DEVICE_FACTS}}
|
|
cdm_for = launched_cdm_for(monkeypatch, Licensor.SERVER_CDM, sent)
|
|
assert cdm_for("example") == "server example"
|