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
+5
View File
@@ -326,6 +326,11 @@ There are two ways DRM keys get resolved, chosen by the client's `server_cdm` fl
- A content key in the client's own vaults goes first, even when the server
already answered. The client proves it, and a server key waits as the next
candidate.
- When the server licence fails, or the server gives a track no content key, your
own device licenses the track only when the `cdm` entry for the service names the
loaded device (see [`remote_services`](../../reference/configuration/services.md#remote_services)).
Otherwise, or when that device also fails, the run stops at the licence step of
that track with one `DRM_ERROR` line.
!!! note "A DRM type that the client does not know"
The client rebuilds the DRM of each track from the track list of the server. When the server
+2 -1
View File
@@ -22,7 +22,8 @@ licenses the remote session.
On a server, an API key can replace the entry for a service with its own (see
[`serve`](services.md#serve)).
With only the top-level `default` entry, the server CDM licenses when the API key has it. Set
`server_cdm: true` on the server entry to keep a per-service entry for local runs only. See
`server_cdm: true` on the server entry to keep a per-service entry for local runs only. Its device
then licenses only a track that the server refuses or fails to license. See
[`remote_services`](services.md#remote_services).
```yaml
+7
View File
@@ -135,6 +135,13 @@ remote_services:
When the server refuses the server CDM for a service whose `cdm` entry loaded the device,
unshackle logs the fallback to that device as info, not as a warning.
The same device licenses a track when the server licence for that track fails, for example with a
server error or an answer with no content key for the track. unshackle logs one info line that
gives the server failure and the device. Without a `cdm` entry for the service that names the
loaded device, a failed server licence stops the run with one `DRM_ERROR` line: unshackle never
falls back to the device of the `default` entry. When the fallback device also fails, the run
stops at the licence step of that track.
The server has the last word. When it keeps the server CDM for a remote session that your
device was to license, unshackle shows a warning. This occurs with a server that does not read
your choice, and with a service option that runs the remote session on the server's device.
@@ -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()
+12 -15
View File
@@ -406,7 +406,7 @@ class ContentKeyResolver:
if track_id in batch.unanswered:
from unshackle.core.api.progress import track_log_label
self.log.warning(f"Server CDM returned no content keys for track {track_log_label(track)}")
self.log.debug("Server CDM returned no content keys for track %s", track_log_label(track))
continue
drm: Any
if entry.own_drm and track.drm:
@@ -700,7 +700,7 @@ class ContentKeyResolver:
except DownloadCancelled:
raise
except Exception as e:
if drm.content_keys and (not track_kid or track_kid in drm.content_keys):
if drm.content_keys and (track_kid in drm.content_keys if track_kid else self.source is None):
self.log.warning(
f"Licence failed, using the {len(drm.content_keys)} known key(s): {redact_secrets(str(e))}"
)
@@ -949,19 +949,6 @@ class ContentKeyResolver:
self.vaults.licensed(new_keys)
if server_cdm and not licensed_locally:
if not drm.content_keys:
if isinstance(drm, CustomDRM):
raise coded(
click.ClickException(f"The server sent no {drm.label} content key for track {track.id}"),
APIErrorCode.DRM_ERROR,
)
self.log.warning("Server CDM did not resolve any keys for this track")
return
if track_kid and track_kid not in drm.content_keys:
msg = f"No Content Key for KID {track_kid.hex} was returned by the server CDM"
if isinstance(drm, PlayReady):
raise PlayReady.Exceptions.CEKNotFound(msg)
raise Widevine.Exceptions.CEKNotFound(msg)
assert remote is not None
server_drm_type = remote.server_cdm_type
drm_name = (
@@ -969,6 +956,16 @@ class ContentKeyResolver:
if isinstance(drm, CustomDRM)
else {"widevine": "Widevine", "playready": "PlayReady"}.get(server_drm_type, drm.__class__.__name__)
)
if not drm.content_keys:
raise coded(
click.ClickException(f"The server sent no {drm_name} content key for track {track.id}"),
APIErrorCode.DRM_ERROR,
)
if track_kid and track_kid not in drm.content_keys:
msg = f"No Content Key for KID {track_kid.hex} was returned by the server CDM"
if isinstance(drm, PlayReady):
raise PlayReady.Exceptions.CEKNotFound(msg)
raise Widevine.Exceptions.CEKNotFound(msg)
log_event(
"drm_content_keys",
level="INFO",
+47 -18
View File
@@ -1671,9 +1671,9 @@ class RemoteService(TitleSource):
return batch
def license_locally(
self, track: AnyTrack, refusal: dict[str, Any], drm: Any = None, kid: UUID | None = None
self, track: AnyTrack, refusal: dict[str, Any], drm: Any = None, kid: UUID | None = None, why: str = ""
) -> None:
"""Hand a track the server CDM refused to license live to this machine's own device.
"""Hand a track the server CDM refused to license live, or failed to license (``why``), to this machine's device.
dl then licenses it through the challenge relay. An HLS track with no DRM yet passes, as its
media playlist names the DRM and the downloader honours ``drm_preference``. On the server's device
@@ -1702,12 +1702,13 @@ class RemoteService(TitleSource):
APIErrorCode.DRM_ERROR,
)
cap = refusal.get("max_height")
if cap:
why = cap_note(cap)
elif self.licensing and self.licensing.vault_first:
why = "The server vault holds no content key for this track"
else:
why = "The server CDM refused this track"
why = why or (
cap_note(cap)
if cap
else "The server vault holds no content key for this track"
if self.licensing and self.licensing.vault_first
else "The server CDM refused this track"
)
height = getattr(track, "height", None)
if (custom := custom_drm(track)) is not None:
drm_class = custom.label
@@ -1734,8 +1735,11 @@ class RemoteService(TitleSource):
label = f"the {height}p track" if height else str(track)
hint = f"; pass -q {height} to start the session on your device" if cap and height else ""
have = " and ".join(sorted(systems))
raise click.ClickException(
f"{why}, and {label} has only {have} DRM, which your local {drm_class} CDM cannot license{hint}"
raise coded(
click.ClickException(
f"{why}, and {label} has only {have} DRM, which your local {drm_class} CDM cannot license{hint}"
),
APIErrorCode.DRM_ERROR,
)
drm_class = other
track.drm_preference = drm_class.lower()
@@ -1843,7 +1847,8 @@ class RemoteService(TitleSource):
The request sends the header of ``drm`` when it is of a system the server licenses, as a playlist can name a
KID that ``track.drm`` does not hold; a plugin DRM request sends no header, as the server holds the DRM its
service built. ``kid`` is the KID the server CDM must answer; a content key for it
from a server vault stands in for the licence. A failed request logs one warning and returns no keys.
from a server vault stands in for the licence. A track with no header raises a DRM_ERROR ClickException;
a failed request or an answer without the content key goes to :meth:`after_server_failure`.
"""
if self.local_vaults_only:
self.license_locally(track, {"reason": "server_device"}, drm, kid)
@@ -1858,11 +1863,14 @@ class RemoteService(TitleSource):
if not pssh_b64:
drm_type, pssh_b64 = other_type, track_pssh(track, other_type, drm)
if not pssh_b64:
self.log.warning(f"Track {track.id} has no PSSH to send to the server CDM")
return HeldKeys()
raise coded(
click.ClickException(f"Track {track.id} has no PSSH to send to the server CDM"),
APIErrorCode.DRM_ERROR,
)
request = LicenseRequest(drm_type=drm_type, mode="server_cdm", pssh=pssh_b64)
if kid:
request["kid"] = kid.hex
licence = None
try:
with quiet():
resp = self.track_call(
@@ -1876,14 +1884,35 @@ class RemoteService(TitleSource):
self.server_cdm_type = resp.get("drm_type", server_type)
licence = held_keys(resp.get("keys", {}), set(resp.get("vault_keys", [])))
self.served_keys.update(licence.keys.items())
return licence
except DownloadCancelled:
raise
except (Exception, RemoteError) as e:
self.log.warning("server_cdm license failed: %s", e)
return HeldKeys()
self.license_locally(track, resp.get("details") or {}, drm, kid)
return None
self.log.debug("Server CDM licence failed for track %s", track.id, exc_info=True)
failure = (
f"The server CDM licence for track {track.id} failed: {redact_secrets(str(e) or type(e).__name__)}"
)
self.after_server_failure(track, failure, drm, kid, isinstance(e, RemoteError) and e.session_broke)
return None
if licence is None:
self.license_locally(track, resp.get("details") or {}, drm, kid)
return None
if not licence.keys or (kid and kid not in licence.keys):
self.after_server_failure(track, f"The server sent no content key for track {track.id}", drm, kid)
return None
return licence
def after_server_failure(
self, track: AnyTrack, failure: str, drm: Any, kid: UUID | None, session_lost: bool = False
) -> None:
"""Hand ``track`` to this machine's device after a failed server licence, else raise ``failure`` as a DRM_ERROR.
Only a device that the service's own ``cdm`` entry named takes the track, never the ``default`` entry's:
that entry is the fallback the user configured for this service. A lost remote session also takes the
challenge relay of that device, so it raises.
"""
if session_lost or not getattr(self.ctx.obj, "cdm_entry", False):
raise coded(click.ClickException(failure), APIErrorCode.DRM_ERROR)
self.license_locally(track, {}, drm, kid, failure)
def license_file(self, track: AnyTrack) -> str:
"""The content key the server licenses for the whole-file cipher of ``track``, or raise ClickException."""
+3 -2
View File
@@ -108,8 +108,9 @@ class ServerKeySource(Protocol):
"""The content keys the server licenses for ``drm`` of ``track``, or None when it hands ``track`` to this machine's CDM.
Call it only for a track ``licenses_locally`` does not name; after None, it names the track. ``kid`` is
the KID the answer must hold. A failed request returns no keys. A refusal this machine cannot take over
raises ClickException.
the KID the answer must hold. A failed request or an answer without that content key hands the track to
this machine only when the service's own ``cdm`` entry named its device. Otherwise it, a track with no
header and a refusal this machine cannot take over raise a DRM_ERROR ClickException.
"""
def license_file(self, track: AnyTrack) -> str: