"""The FairPlay bridge runs only for a service that defines ``get_fairplay_bridge_license``.""" from __future__ import annotations import base64 import json from pathlib import Path from types import SimpleNamespace from typing import Any from uuid import UUID import pytest from tests.core.key_resolver import resolver from tests.core.test_hls_service_drm_keys import no_ffprobe # noqa: F401 from tests.core.test_hls_service_drm_keys import ( KID, SKD_KEY, InitServer, download, hls_video, init_kid_probe, playlist, ) from tests.lang_selection import test_kind_only_selection as harness from unshackle.core.api.handlers import handle_proxy_license from unshackle.core.cdm.detect import cdm_type_stub from unshackle.core.drm.cenc import drm_stub from unshackle.core.manifests.hls import HLS from unshackle.core.title_source import TitleSource from unshackle.core.tracks.track import Track class Example(TitleSource): """EXAMPLE: licence callbacks that note each call, and no FairPlay bridge hook.""" def __init__(self) -> None: self.calls: list[tuple[str, dict[str, Any]]] = [] def authenticate(self, cookies: Any = None, credential: Any = None) -> None: pass def get_titles(self) -> Any: raise NotImplementedError def get_tracks(self, title: Any) -> Any: raise NotImplementedError def get_chapters(self, title: Any) -> Any: raise NotImplementedError def get_playready_license(self, *, challenge: Any, title: Any, track: Any, pssh_b64: str | None = None) -> str: self.calls.append(("playready", {"challenge": challenge, "pssh_b64": pssh_b64})) return "" def get_widevine_license(self, *, challenge: Any, title: Any, track: Any, pssh: Any = None) -> bytes: self.calls.append(("widevine", {"challenge": challenge, "pssh": pssh})) return b"LIC" class Bridged(Example): """EXAMPLE with the hook: its licence server issues the content keys of its FairPlay-only tracks.""" def get_fairplay_bridge_license( self, *, challenge: Any, title: Any, track: Any, drm_system: str, pssh_b64: str | None = None, pssh: Any = None ) -> str | bytes: self.calls.append(("bridge", {"challenge": challenge, "drm_system": drm_system, "pssh_b64": pssh_b64})) return "" if drm_system == "playready" else b"LIC" def test_a_fairplay_only_track_is_refused_without_the_hook(tmp_path: Path, monkeypatch: Any) -> None: track = hls_video(tmp_path, playlist(SKD_KEY)) probe = init_kid_probe(monkeypatch, KID) session = InitServer() with pytest.raises(NotImplementedError, match="None of the key systems are supported"): download(track, cdm_type_stub("playready"), session=session, fairplay_bridge=False) assert not track.drm assert not probe.called assert not session.requests @pytest.mark.parametrize( "service, drm, route", [ pytest.param(Bridged, lambda: HLS.bridge_stub("playready", [KID]), "bridge", id="bridged-stub"), pytest.param(Bridged, lambda: drm_stub("playready", [KID.hex]), "playready", id="the-stub-of-the-service"), pytest.param(Example, lambda: drm_stub("playready", [KID.hex]), "playready", id="no-hook"), ], ) def test_a_bridged_challenge_goes_to_the_hook_and_every_other_to_the_system_callback( service: type[Example], drm: Any, route: str ) -> None: keys = resolver() keys.service = service() track = SimpleNamespace(drm=[drm()]) assert keys._service_licence("playready", challenge="C", title=None, track=track, pssh_b64="P", session_id=b"s") expected = {"challenge": "C", "pssh_b64": "P", **({"drm_system": "playready"} if route == "bridge" else {})} assert keys.service.calls == [(route, expected)] def test_drm_preference_picks_the_system_of_the_stub(tmp_path: Path, monkeypatch: Any) -> None: track = hls_video(tmp_path, playlist(SKD_KEY)) track.drm_preference = "pr" init_kid_probe(monkeypatch, KID) licensed: list[str] = [] download(track, cdm_type_stub("widevine"), lambda drm, track_kid=None: licensed.append(type(drm).__name__), True) assert licensed == ["PlayReady"] assert track.drm is not None and track.drm[0].bridged def test_the_drm_of_the_service_needs_no_hook(tmp_path: Path, monkeypatch: Any) -> None: """A service that puts its own stub on a FairPlay-only track keeps its route, with no hook.""" track = hls_video(tmp_path, playlist(SKD_KEY)) track.drm = [drm_stub("playready", [KID.hex])] init_kid_probe(monkeypatch, KID) licensed: list[tuple[str, UUID | None]] = [] download( track, cdm_type_stub("widevine"), lambda drm, track_kid=None: licensed.append((type(drm).__name__, track_kid)), licence_only=True, fairplay_bridge=False, ) assert licensed == [("PlayReady", KID)] assert track.drm is not None and not track.drm[0].bridged @pytest.mark.parametrize("system", ["playready", "widevine"]) def test_the_relay_route_sends_a_bridged_challenge_to_the_hook(system: str) -> None: service = Bridged() stub = HLS.bridge_stub(system, [KID]) pssh_b64 = stub.pssh_b64 if system == "playready" else stub.pssh.dumps() reply = handle_proxy_license( service, None, SimpleNamespace(drm=[stub]), base64.b64encode(b"").decode(), system, pssh_b64=pssh_b64 ) assert json.loads(reply.body)["license"] assert [(route, call["drm_system"]) for route, call in service.calls] == [("bridge", system)] assert service.calls[0][1]["pssh_b64"] == (pssh_b64 if system == "playready" else None) @pytest.mark.parametrize("hook", [None, print], ids=["no-hook", "hook"]) def test_dl_tells_each_track_download_whether_the_service_has_the_hook( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, hook: Any ) -> None: handed: list[bool] = [] monkeypatch.setattr(harness.FakeService, "fairplay_bridge", lambda self: hook) monkeypatch.setattr(Track, "download", lambda self, *a, **k: handed.append(k["fairplay_bridge"])) def download_all(tracks: Any, workers: int, run_one: Any, **_: Any) -> None: for i, track in enumerate(tracks): run_one(track, i) harness.run(monkeypatch, caplog, {1: {}}, to_end=True, no_mux=True, download=download_all) assert handed and set(handed) == {hook is not None}