mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-02 05:55:08 +00:00
178 lines
6.9 KiB
Python
178 lines
6.9 KiB
Python
"""The FairPlay bridge over ``--remote``: the real client against the real server routes, over loopback HTTP."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
|
|
import pytest
|
|
from click import ClickException
|
|
from langcodes import Language
|
|
|
|
from tests.core.key_resolver import resolver
|
|
from tests.core.test_hls_service_drm_keys import KID, OTHER_KID, ROTATION, InitServer, download, encrypted_init
|
|
from tests.remote.sessions import session_entry
|
|
from tests.remote.unit.test_relay_per_header_pssh import license_all, pr_kids
|
|
from tests.remote.unit.test_remote_loopback import StubService, make_client, server # noqa: F401
|
|
from unshackle.core.api import handlers, server_keys
|
|
from unshackle.core.api.key_policy import KeyPolicy
|
|
from unshackle.core.cdm.detect import cdm_type_stub
|
|
from unshackle.core.drm import PlayReady, cenc
|
|
from unshackle.core.tracks import Tracks, Video
|
|
from unshackle.core.tracks.track import Track
|
|
|
|
pytestmark = pytest.mark.unit
|
|
|
|
URL = "https://cdn.example/media.m3u8"
|
|
|
|
|
|
class Origin(InitServer):
|
|
"""The CDN of EXAMPLE: the FairPlay-only rotation playlist and its init segments."""
|
|
|
|
def __init__(self) -> None:
|
|
super().__init__(init=encrypted_init(KID), rot=encrypted_init(OTHER_KID))
|
|
|
|
def get(self, url: str, **kwargs: Any) -> SimpleNamespace: # type: ignore[override]
|
|
if url.endswith(".m3u8"):
|
|
return SimpleNamespace(ok=True, status_code=200, text=ROTATION)
|
|
return super().get(url, **kwargs)
|
|
|
|
|
|
def serve(origin: type[Origin]) -> Any:
|
|
"""A ``get_tracks`` that gives one FairPlay-only HLS video from ``origin``."""
|
|
|
|
def get_tracks(self: StubService, title: Any) -> Tracks:
|
|
self.session = origin()
|
|
video = Video(
|
|
url=URL, language=Language.get("en"), descriptor=Track.Descriptor.HLS, codec=Video.Codec.HEVC, id_="vid"
|
|
)
|
|
return Tracks([video])
|
|
|
|
return get_tracks
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def no_ffprobe(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setattr(cenc, "ffprobe", lambda data: {})
|
|
|
|
|
|
@pytest.fixture
|
|
def served(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]:
|
|
"""The server's EXAMPLE serves one FairPlay-only HLS video; each call of its hook lands in the list."""
|
|
calls: list[dict[str, Any]] = []
|
|
|
|
monkeypatch.setattr(StubService, "get_tracks", serve(Origin))
|
|
return calls
|
|
|
|
|
|
def bridge(remote: Any, tmp_path: Path) -> Video:
|
|
"""Download the first video of the first title in a licence-only run, as dl does, and return it."""
|
|
title = remote.get_titles()[0]
|
|
track = remote.get_tracks(title).videos[0]
|
|
track.from_file = tmp_path / "media.m3u8"
|
|
track.from_file.write_text(ROTATION, encoding="utf-8")
|
|
bridged = remote.fairplay_bridge() is not None
|
|
download(track, cdm_type_stub("playready"), lambda drm, track_kid=None: None, True, Origin(), bridged)
|
|
keys = resolver()
|
|
keys.service = remote
|
|
assert track.drm is not None
|
|
license_all(track.drm, lambda **kw: keys._service_licence("playready", title=title, track=track, **kw))
|
|
return track
|
|
|
|
|
|
def test_a_served_hook_licenses_each_key_id_of_a_rotation_through_the_relay(
|
|
server: SimpleNamespace, # noqa: F811
|
|
served: list[dict[str, Any]],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
tmp_path: Path,
|
|
) -> None:
|
|
def hook(self: StubService, *, challenge: str, title: Any, track: Any, drm_system: str, pssh_b64: str) -> str:
|
|
served.append({"drm_system": drm_system, "kids": pr_kids(pssh_b64)})
|
|
return "<License/>"
|
|
|
|
monkeypatch.setattr(StubService, "get_fairplay_bridge_license", hook, raising=False)
|
|
remote = make_client(server.url)
|
|
try:
|
|
remote.authenticate()
|
|
track = bridge(remote, tmp_path)
|
|
finally:
|
|
remote.close()
|
|
|
|
assert remote.fairplay_bridge() == remote.relay_fairplay_bridge
|
|
assert served == [{"drm_system": "playready", "kids": [KID]}, {"drm_system": "playready", "kids": [OTHER_KID]}]
|
|
assert isinstance(track.drm[0], PlayReady) and track.drm[0].content_keys.keys() == {KID, OTHER_KID}
|
|
|
|
|
|
def test_a_served_service_without_the_hook_gets_no_bridge(
|
|
server: SimpleNamespace, # noqa: F811
|
|
served: list[dict[str, Any]],
|
|
tmp_path: Path,
|
|
) -> None:
|
|
remote = make_client(server.url)
|
|
try:
|
|
remote.authenticate()
|
|
with pytest.raises(NotImplementedError, match="None of the key systems are supported"):
|
|
bridge(remote, tmp_path)
|
|
assert remote.fairplay_bridge() is None
|
|
finally:
|
|
remote.close()
|
|
|
|
assert not served
|
|
|
|
|
|
def test_the_server_refuses_a_bridged_challenge_it_cannot_read_the_key_ids_of(
|
|
server: SimpleNamespace, # noqa: F811
|
|
served: list[dict[str, Any]],
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
tmp_path: Path,
|
|
) -> None:
|
|
"""The client's stub must not reach get_playready_license when the server's own stub build failed."""
|
|
|
|
class Unreachable(Origin):
|
|
def get(self, url: str, **kwargs: Any) -> SimpleNamespace: # type: ignore[override]
|
|
if url.endswith(".m3u8"):
|
|
return super().get(url, **kwargs)
|
|
raise ConnectionError("EXAMPLE init segment unreachable")
|
|
|
|
def licence(self: StubService, **kwargs: Any) -> str:
|
|
served.append(kwargs)
|
|
return "<License/>"
|
|
|
|
monkeypatch.setattr(StubService, "get_tracks", serve(Unreachable))
|
|
monkeypatch.setattr(StubService, "get_fairplay_bridge_license", licence, raising=False)
|
|
monkeypatch.setattr(StubService, "get_playready_license", licence, raising=False)
|
|
remote = make_client(server.url)
|
|
try:
|
|
remote.authenticate()
|
|
with pytest.raises(ClickException, match="DRM_ERROR.*read no key ID of track .* for the FairPlay bridge"):
|
|
bridge(remote, tmp_path)
|
|
finally:
|
|
remote.close()
|
|
|
|
assert not served
|
|
|
|
|
|
@pytest.mark.parametrize("hook", [None, print], ids=["no-hook", "hook"])
|
|
def test_the_server_builds_stubs_only_for_a_service_with_the_hook(monkeypatch: pytest.MonkeyPatch, hook: Any) -> None:
|
|
"""The batch keys route and the licence route ask the service before ``ensure_track_drm`` may bridge."""
|
|
track = SimpleNamespace(id="vid", drm=None, data={})
|
|
session = session_entry(service_instance=SimpleNamespace(fairplay_bridge=lambda: hook), tracks={"vid": track})
|
|
asked: list[bool] = []
|
|
|
|
def ensure(track: Any, session: Any = None, init_data: Any = None, bridge: bool = False) -> None:
|
|
asked.append(bridge)
|
|
|
|
monkeypatch.setattr(server_keys, "ensure_track_drm", ensure)
|
|
monkeypatch.setattr(handlers, "ensure_track_drm", ensure)
|
|
monkeypatch.setattr(server_keys, "fetch_init_segment", lambda *a: None)
|
|
|
|
server_keys.resolve_batch(session, ["vid"], "playready", KeyPolicy())
|
|
with contextlib.suppress(Exception):
|
|
handlers.license_response(
|
|
{"track_id": "vid", "challenge": "Qw==", "drm_type": "playready", "pssh": "cHNzaA=="}, session, "s", None
|
|
)
|
|
|
|
assert asked == [hook is not None] * 2
|