fix(remote): stop at the licence step when a licence fails, falling back only to the service's cdm entry

This commit is contained in:
imSp4rky
2026-12-04 16:31:28 -07:00
parent dd524f2cb2
commit 3bdca22bc7
10 changed files with 355 additions and 48 deletions
@@ -0,0 +1,201 @@
"""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
@@ -17,7 +17,6 @@ from tests.remote.key_source import remote_keys
from tests.remote.sessions import hold_session
from unshackle.core.api.errors import categorize_exception
from unshackle.core.remote_protocol import APIErrorCode, LicensingMode, Licensor
from unshackle.core.title_source import HeldKeys
pytestmark = pytest.mark.unit
@@ -123,7 +122,7 @@ def test_a_refused_relayed_licence_raises_a_click_exception_with_the_server_mess
assert not [r for r in caplog.records if r.levelname == "ERROR"]
def test_a_refused_server_cdm_licence_logs_one_warning(caplog):
def test_a_refused_server_cdm_licence_is_one_drm_error_line(caplog):
from unshackle.core.remote_service import RemoteError
svc = _service("widevine", {})
@@ -134,8 +133,12 @@ def test_a_refused_server_cdm_licence_logs_one_warning(caplog):
svc.client.post = refuse
track = SimpleNamespace(id="vid", drm=[_Widevine()])
assert svc.license_track(track, None) == HeldKeys()
assert [r.levelname for r in caplog.records if r.levelname in ("WARNING", "ERROR")] == ["WARNING"]
with pytest.raises(click.ClickException) as raised:
svc.license_track(track, None)
assert str(raised.value) == "The server CDM licence for track vid failed: Server error [SERVICE_ERROR]: refused"
assert raised.value.error_code == APIErrorCode.DRM_ERROR # type: ignore[attr-defined]
assert not [r for r in caplog.records if r.levelname in ("WARNING", "ERROR")]
def test_the_kid_dl_needs_goes_to_the_server():
@@ -148,7 +151,7 @@ def test_the_kid_dl_needs_goes_to_the_server():
def test_the_header_of_the_drm_dl_licenses_goes_before_the_tracks():
svc = _service("widevine", {"keys": {}})
svc = _service("widevine", {"keys": {KID.hex: "k"}})
later = _Widevine()
later.pssh = SimpleNamespace(dumps=lambda: "LATER")
@@ -157,11 +160,14 @@ def test_the_header_of_the_drm_dl_licenses_goes_before_the_tracks():
assert svc.client.posts[0]["pssh"] == "LATER"
def test_a_track_with_no_header_sends_nothing_and_gets_no_keys():
def test_a_track_with_no_header_sends_nothing_and_is_a_drm_error():
svc = _service("widevine", {})
track = SimpleNamespace(id="vid", drm=[])
assert svc.license_track(track, None) == HeldKeys()
with pytest.raises(click.ClickException, match="^Track vid has no PSSH to send to the server CDM$") as raised:
svc.license_track(track, None)
assert raised.value.error_code == APIErrorCode.DRM_ERROR # type: ignore[attr-defined]
assert svc.client.posts == []
@@ -233,9 +233,11 @@ def test_the_server_reads_the_head_of_a_one_file_track_with_drm(example_plugins,
)
def test_a_track_the_reply_lists_as_clear_draws_no_warning(caplog):
"""A requested track the server lists in clear_tracks carries no DRM, so its
missing keys are expected and draw no warning."""
def test_only_an_unanswered_track_draws_a_debug_line(caplog):
"""A requested track the server lists in clear_tracks carries no DRM, so its missing keys draw no line.
An unanswered track gets a debug line only: its own licence follows, and that one fails the run.
"""
video_track = SimpleNamespace(id="v-1", drm=None)
audio_track = SimpleNamespace(id="a-1", drm=None)
@@ -243,10 +245,12 @@ def test_a_track_the_reply_lists_as_clear_draws_no_warning(caplog):
videos = [video_track]
audio = [audio_track]
with caplog.at_level(logging.WARNING):
with caplog.at_level(logging.DEBUG):
install_reply({"keys": {}, "clear_tracks": ["a-1"]}, SimpleNamespace(tracks=Tracks([video_track, audio_track])))
assert caplog.messages == ["Server CDM returned no content keys for track simplenamespace (v-1)"]
assert [(r.levelname, r.message) for r in caplog.records if "no content keys" in r.message] == [
("DEBUG", "Server CDM returned no content keys for track simplenamespace (v-1)")
]
def test_the_batch_takes_the_key_of_a_whole_file_cipher(caplog):
@@ -0,0 +1,56 @@
"""A server-CDM licence that gives a track no content key stops the run at the licence step, before any segment."""
from types import SimpleNamespace
from uuid import UUID
import click
import pytest
from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
from tests.core.test_all_drm import widevine
from tests.remote.key_source import MemoryKeySource
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.manifests.segment_pipeline import license_drm
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks.track import DownloadContext, Track
pytestmark = pytest.mark.unit
KID = UUID("161219ec3df64e0eadbb3827c0ccc46d")
NO_KEY = "^The server sent no Widevine content key for track vid$"
@pytest.fixture(autouse=True)
def no_cancel():
DOWNLOAD_CANCELLED.clear()
yield
DOWNLOAD_CANCELLED.clear()
def keyless_track():
drm = widevine(KID)
track = SimpleNamespace(id="vid", drm=[drm], descriptor=Track.Descriptor.DASH)
callback = resolver(vaults_of(MemoryVault()), source=MemoryKeySource()).licence_for(track, None, key_table())
return track, drm, callback
@pytest.mark.parametrize("track_kid", [None, KID], ids=["no-track-kid", "track-kid"])
def test_a_server_answer_with_no_key_is_a_drm_error(track_kid):
track, drm, callback = keyless_track()
with pytest.raises(click.ClickException, match=NO_KEY) as raised:
callback(drm, track_kid=track_kid)
assert raised.value.error_code == APIErrorCode.DRM_ERROR # type: ignore[attr-defined]
def test_a_server_answer_with_no_key_cancels_the_other_tracks(tmp_path):
track, drm, callback = keyless_track()
ctx = DownloadContext(
save_path=tmp_path / "vid.mp4", save_dir=tmp_path / "seg", progress=lambda **kw: None, license_widevine=callback
)
with pytest.raises(click.ClickException, match=NO_KEY):
license_drm(track, drm, ctx, KID) # type: ignore[arg-type]
assert DOWNLOAD_CANCELLED.is_set()