"""Over --remote, a licence that ends at this machine's own CDM stops the run at the licence step when it fails. A failed server licence moves the track to this machine's device only when the service's own cdm entry named it. """ import logging import re from types import SimpleNamespace from uuid import UUID import click import pytest from tests.core.key_resolver import key_table, resolver from tests.core.test_all_drm import playready_object from tests.core.test_licence_turns import widevine from tests.remote.key_source import MemoryKeySource, remote_session from unshackle.core.constants import DOWNLOAD_CANCELLED from unshackle.core.drm import PlayReady from unshackle.core.manifests.segment_pipeline import license_drm from unshackle.core.remote_protocol import APIErrorCode, LicensingMode, Licensor from unshackle.core.remote_service import RemoteError from unshackle.core.tracks.track import DownloadContext, Track pytestmark = pytest.mark.unit KID = UUID("161219ec3df64e0eadbb3827c0ccc46d") OTHER = UUID("75982fac2cd8412a990a59c0ef2d4bb1") DEVICE = SimpleNamespace(is_playready=False, security_level=3) CAPPED_ANSWER = { "status": "error", "error_code": "SERVER_CDM_CAPPED", "details": {"reason": "server_cdm_max_height", "max_height": 1080}, } REFUSED = "Server error [DRM_ERROR]: no licence" @pytest.fixture(autouse=True) def no_cancel(): DOWNLOAD_CANCELLED.clear() yield DOWNLOAD_CANCELLED.clear() def own_widevine(*kids, refuse=None): """A Widevine DRM whose licence with this machine's device gives the key of its first KID, or raises ``refuse``.""" drm = widevine(*(kids or (KID,))) drm.asked = [] def get_content_keys(cdm, licence, certificate): drm.asked.append(cdm) if refuse: raise refuse drm.content_keys[drm.kids[0]] = "ab" * 16 drm.get_content_keys = get_content_keys return drm def failing_server(cdm_entry, answer=None): """A server-CDM remote session whose licence route fails, or answers ``answer``; ``cdm_entry`` as dl sets it.""" svc = remote_session(DEVICE, answer or {}) svc.ctx.obj.cdm_entry = cdm_entry if answer is None: def refuse(endpoint, payload, expect=()): raise RemoteError(REFUSED, "DRM_ERROR") svc.client.post = refuse return svc def dash_track(*drms): return SimpleNamespace( id="vid", drm=list(drms), drm_preference=None, descriptor=Track.Descriptor.DASH, get_drm_for_cdm=lambda cdm: drms[-1], ) def licence_step(svc, track, drm, kid=KID, tmp_path=None, cdm=DEVICE): """Run the licence step of ``track`` as a downloader does, with the licence callback dl builds.""" callback = resolver(cdm=cdm, tag="EXAMPLE", source=svc).licence_for(track, None, key_table()) ctx = DownloadContext(save_path=tmp_path / "vid.mp4", save_dir=tmp_path / "seg", progress=lambda **kw: None) ctx.license_widevine = callback license_drm(track, drm, ctx, kid) # type: ignore[arg-type] @pytest.mark.parametrize("answer", [None, {"keys": {}}], ids=["server-error", "no-key"]) def test_a_failed_server_licence_hands_the_track_to_the_services_cdm_entry(tmp_path, caplog, answer): svc = failing_server(cdm_entry=True, answer=answer) drm = own_widevine() with caplog.at_level(logging.INFO): licence_step(svc, dash_track(drm), drm, tmp_path=tmp_path) assert (drm.asked, drm.content_keys, svc.client_licensed) == ([DEVICE], {KID: "ab" * 16}, {"vid"}) handover = [r for r in caplog.records if "your own Widevine device" in r.message] assert [r.levelname for r in handover] == ["INFO"] assert "track vid" in handover[0].message assert not [r for r in caplog.records if r.levelname in ("WARNING", "ERROR")] def test_the_services_own_cdm_failing_after_the_fallback_stops_the_run(tmp_path): svc = failing_server(cdm_entry=True) drm = own_widevine(refuse=ValueError("own CDM refused")) with pytest.raises(ValueError, match="own CDM refused"): licence_step(svc, dash_track(drm), drm, tmp_path=tmp_path) assert drm.asked == [DEVICE] assert DOWNLOAD_CANCELLED.is_set() @pytest.mark.parametrize("answer", [None, {"keys": {}}], ids=["server-error", "no-key"]) def test_without_a_services_cdm_entry_a_failed_server_licence_stops_without_the_local_cdm(tmp_path, answer): """The default cdm entry, or no entry, sets no cdm_entry: dl never falls back to that device.""" svc = failing_server(cdm_entry=False, answer=answer) drm = own_widevine() with pytest.raises(click.ClickException, match="track vid") as raised: licence_step(svc, dash_track(drm), drm, tmp_path=tmp_path) assert raised.value.error_code == APIErrorCode.DRM_ERROR # type: ignore[attr-defined] assert (drm.asked, svc.client_licensed) == ([], set()) assert DOWNLOAD_CANCELLED.is_set() def test_a_lost_remote_session_stops_without_the_services_cdm_entry(tmp_path): """The challenge relay of the fallback would use the same lost remote session.""" svc = failing_server(cdm_entry=True) def lost(endpoint, payload, expect=()): raise RemoteError("Remote session not found", APIErrorCode.SESSION_NOT_FOUND) svc.client.post = lost svc.track_call = lambda call: call("sess") drm = own_widevine() with pytest.raises(click.ClickException, match="Remote session not found") as raised: licence_step(svc, dash_track(drm), drm, tmp_path=tmp_path) assert raised.value.error_code == APIErrorCode.DRM_ERROR # type: ignore[attr-defined] assert (drm.asked, svc.client_licensed) == ([], set()) @pytest.mark.parametrize("other_system", [False, True], ids=["same-drm", "other-system-drm"]) def test_a_capped_track_whose_own_cdm_fails_stops_the_run(tmp_path, other_system): svc = failing_server(cdm_entry=True, answer=CAPPED_ANSWER) own = own_widevine(refuse=ValueError("own CDM refused")) server_drm = PlayReady.from_pssh_b64(playready_object(KID)) if other_system else own track = dash_track(server_drm, own) if other_system else dash_track(own) with pytest.raises(ValueError, match="own CDM refused"): licence_step(svc, track, server_drm, tmp_path=tmp_path) assert own.asked == [DEVICE] assert DOWNLOAD_CANCELLED.is_set() def test_a_client_device_session_whose_relayed_licence_fails_stops_the_run(tmp_path): """server_cdm: true with a service cdm entry, and the server refused its CDM at session create.""" svc = failing_server(cdm_entry=True) svc.licensing = LicensingMode(Licensor.CLIENT_DEVICE) svc.drain_server_logs = lambda: None drm = own_widevine() track = dash_track(drm) def relay(cdm, licence, certificate): drm.asked.append(cdm) svc.proxy_license(b"challenge", track, "widevine") drm.get_content_keys = relay with pytest.raises(click.ClickException, match=re.escape(REFUSED)): licence_step(svc, track, drm, tmp_path=tmp_path) assert drm.asked == [DEVICE] assert DOWNLOAD_CANCELLED.is_set() def test_a_failed_own_licence_with_only_another_kids_key_stops_a_remote_run(tmp_path): """With no track KID, a held key of another KID says nothing about the track's own key.""" drm = own_widevine(KID, OTHER, refuse=ValueError("own CDM refused")) drm.content_keys[OTHER] = "cd" * 16 with pytest.raises(ValueError, match="own CDM refused"): licence_step(MemoryKeySource(local_cdm=DEVICE, client_licensed={"vid"}), dash_track(drm), drm, None, tmp_path) assert DOWNLOAD_CANCELLED.is_set() def test_a_local_run_still_takes_another_kids_key_for_a_failed_licence(tmp_path, caplog): drm = own_widevine(KID, OTHER, refuse=ValueError("own CDM refused")) drm.content_keys[OTHER] = "cd" * 16 licence_step(None, dash_track(drm), drm, None, tmp_path) assert "Licence failed, using the 1 known key(s)" in caplog.text