From c7a3febf882fdf05a2fc8e5ec324041f2e728c9f Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Tue, 1 Dec 2026 22:05:32 -0700 Subject: [PATCH] fix(dash): refuse an encrypted DASH track with no licensable DRM and gate FairPlay-only DASH tracks for a hook service --- docs/dev/service-architecture.md | 6 + docs/guide/drm-and-cdm.md | 7 +- .../commands/test_fairplay_selection_gate.py | 11 +- tests/core/test_dash_unlicensable_init.py | 122 ++++++++++++++++++ unshackle/commands/dl.py | 23 ++-- unshackle/core/manifests/dash.py | 19 ++- 6 files changed, 174 insertions(+), 14 deletions(-) create mode 100644 tests/core/test_dash_unlicensable_init.py diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md index cf426902..951bac25 100644 --- a/docs/dev/service-architecture.md +++ b/docs/dev/service-architecture.md @@ -502,6 +502,8 @@ such a track out of the selection: or each selected audio track is FairPlay-only, `dl` skips the title. - `--list` shows every track and checks none. An import is not checked, because its export holds the content keys. +- With the hook, `dl` still leaves out FairPlay-only DASH tracks, because the bridge works for HLS only. + The line then reads `Left out 1 FairPlay-only track: DASH has no FairPlay bridge`. A licence server that does not issue the content key refuses the challenge, and can flag the device. Test the route with a licence-only run (`--cdm-only --skip-dl`) before a service relies on it. @@ -583,6 +585,10 @@ one content key per track: the key changes of the playlist go with the tags. Thi applies to a DRM object that the download builds. Any other track stops with `None of the key systems are supported` before it downloads a segment. +A DASH track with no DRM object stops with the same error when its init segment has an encrypted +sample entry. A DASH track with no init segment stops after the download when the file has one, and +unshackle deletes the file. A service sample decrypter turns off both checks. + ### How unshackle chooses a CDM and finds keys CDM selection is config-driven: the `cdm` map resolves a service tag (and optionally the diff --git a/docs/guide/drm-and-cdm.md b/docs/guide/drm-and-cdm.md index da26f81d..c05c2006 100644 --- a/docs/guide/drm-and-cdm.md +++ b/docs/guide/drm-and-cdm.md @@ -77,7 +77,7 @@ To download a Widevine-protected title you need a `.wvd` device. For PlayReady y need a `.prd` device. You can hold both, and unshackle automatically selects the appropriate one for each track. -!!! note "HLS tracks with only a FairPlay key tag" +!!! note "Tracks with only FairPlay protection" unshackle has no FairPlay CDM and never sends a FairPlay challenge. For a FairPlay-only track it can send a PlayReady or Widevine challenge for the KIDs of the init segments to the licence server of the platform, which works only when that server issues the same @@ -87,6 +87,11 @@ appropriate one for each track. `Left out 1 FairPlay-only track: EXAMPLE has no FairPlay bridge hook`. When only FairPlay-only tracks match your quality or range options, unshackle skips the title, unless you use `--best-available`. `--list` still shows every track. + + The route works for HLS only, so a service that defines it still loses its FairPlay-only DASH tracks: + `Left out 1 FairPlay-only track: DASH has no FairPlay bridge`. + An encrypted DASH track with no DRM system that unshackle can license stops with + `None of the key systems are supported`, and unshackle keeps no output file. A licence without the content key of a key ID, or with a content key that does not decrypt the track, stops the download of that track with an error, and unshackle keeps no output file. diff --git a/tests/commands/test_fairplay_selection_gate.py b/tests/commands/test_fairplay_selection_gate.py index 23098a77..fc180fab 100644 --- a/tests/commands/test_fairplay_selection_gate.py +++ b/tests/commands/test_fairplay_selection_gate.py @@ -164,15 +164,20 @@ def test_best_available_falls_back_to_the_track_that_licenses( assert ids["video"] == ["1080"] -@pytest.mark.parametrize(("service", "expected"), [(Example, "1080"), (Bridged, "2160")], ids=["no-hook", "hook"]) +@pytest.mark.parametrize( + ("service", "reason"), + [(Example, "FAKE has no FairPlay bridge hook"), (Bridged, "DASH has no FairPlay bridge")], + ids=["no-hook", "hook"], +) def test_a_dash_adaptation_set_with_only_a_fairplay_content_protection( - monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, service: type[Example], expected: str + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, service: type[Example], reason: str ) -> None: source = service(dash=True) ids = run(monkeypatch, caplog, source) - assert ids["video"] == [expected] + assert ids["video"] == ["1080"] + assert caplog.text.count(f"Left out 1 FairPlay-only track: {reason}") == 1 assert source.session.urls == [] diff --git a/tests/core/test_dash_unlicensable_init.py b/tests/core/test_dash_unlicensable_init.py new file mode 100644 index 00000000..5625fd24 --- /dev/null +++ b/tests/core/test_dash_unlicensable_init.py @@ -0,0 +1,122 @@ +"""DASH.download_track refuses an encrypted track that no DRM it can license covers.""" + +from __future__ import annotations + +import struct +from functools import partial +from pathlib import Path +from typing import Any +from uuid import UUID + +import pytest + +from tests.core.test_dash_collapse_integration import clear_cancel as clear_cancel # noqa: F401 +from tests.core.test_dash_collapse_integration import server as server # noqa: F401 +from tests.core.test_kid_windows import box, full, moof, movie +from unshackle.core.api.errors import APIErrorCode, categorize_exception +from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY +from unshackle.core.manifests import DASH +from unshackle.core.tracks.track import DownloadContext + +KID = UUID("9eb4050d-e44b-4802-932e-27d75083e266") +TENC = full(b"tenc", b"\x00\x00\x01\x00" + KID.bytes + b"\x10" + bytes(16), version=1) +SCHEME = box(b"schm", bytes(4) + b"cbcs" + struct.pack(">I", 0x10000)) +ENCRYPTED = movie(box(b"encv", bytes(78), box(b"sinf", box(b"frma", b"avc1"), SCHEME, box(b"schi", TENC)))) +CLEAR = movie(box(b"avc1", bytes(78))) +SEGMENT = moof(1, 0, full(b"senc", bytes(4))) +FAIRPLAY = '' +MP4 = f'' +TEMPLATE = ( + '' +) +ONE_FILE = "whole.mp4" + + +def download( + srv: Any, tmp_path: Path, init: bytes, protections: str, segments: str = TEMPLATE, **kwargs: Any +) -> tuple[DownloadContext, list]: + srv.routes = {"/init.mp4": init, "/whole.mp4": init + SEGMENT + SEGMENT, "/1.m4s": SEGMENT, "/2.m4s": SEGMENT} + mpd = f""" + + http://127.0.0.1:{srv.server_address[1]}/ + + + {protections} + + {segments} + + + +""" + track = DASH.from_text(mpd, url="http://x/manifest.mpd").to_tracks(language="en").videos[0] + licences: list = [] + ctx = DownloadContext( + save_path=tmp_path / "out.mp4", + save_dir=tmp_path / "v0_segments", + progress=partial(lambda **_: None), + license_widevine=lambda drm, track_kid=None: licences.append(drm), + cdm=None, + **kwargs, + ) + DASH.download_track(track, ctx) + return ctx, licences + + +@pytest.mark.parametrize( + ("protections", "systems"), + [ + pytest.param( + FAIRPLAY + MP4, + "urn:uuid:94ce86fb-07ff-4f43-adb8-93d2fa968ca2, urn:mpeg:dash:mp4protection:2011", + id="fairplay-and-mp4protection", + ), + pytest.param(FAIRPLAY, "urn:uuid:94ce86fb-07ff-4f43-adb8-93d2fa968ca2", id="fairplay"), + pytest.param("", "no ContentProtection", id="no-content-protection"), + ], +) +@pytest.mark.parametrize("licence_only", [False, True], ids=["download", "licence-only"]) +def test_an_encrypted_init_with_no_drm_is_refused( + server: Any, tmp_path: Path, protections: str, systems: str, licence_only: bool +) -> None: + if licence_only: + DOWNLOAD_LICENCE_ONLY.set() + try: + with pytest.raises(NotImplementedError) as refused: + download(server, tmp_path, ENCRYPTED, protections) + finally: + DOWNLOAD_LICENCE_ONLY.clear() + + assert str(refused.value) == f"None of the key systems are supported: {systems}" + assert categorize_exception(refused.value).error_code is APIErrorCode.DRM_ERROR + assert not (tmp_path / "out.mp4").exists() + assert not any(path == "/1.m4s" for path, _ in server.requests) + + +def test_an_encrypted_file_with_no_init_segment_is_refused_and_removed(server: Any, tmp_path: Path) -> None: + with pytest.raises(NotImplementedError, match="^None of the key systems are supported: no ContentProtection$"): + download(server, tmp_path, ENCRYPTED, "", ONE_FILE) + + assert any(path == "/whole.mp4" for path, _ in server.requests) + assert not (tmp_path / "out.mp4").exists() + + +@pytest.mark.parametrize("segments", [TEMPLATE, ONE_FILE], ids=["init-segment", "one-file"]) +def test_a_clear_track_still_downloads(server: Any, tmp_path: Path, segments: str) -> None: + ctx, licences = download(server, tmp_path, CLEAR, "", segments) + + assert ctx.save_path.read_bytes().startswith(CLEAR) + assert licences == [] + + +def test_a_service_sample_decrypter_takes_the_encrypted_track(server: Any, tmp_path: Path) -> None: + entries: list[int] = [] + + def decrypter(entry: int) -> bytes: + entries.append(entry) + return bytes(16) + + ctx, licences = download(server, tmp_path, ENCRYPTED, "", sample_decrypter=decrypter) + + assert ctx.save_path.exists() + assert entries + assert licences == [] diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index d63db48e..1598cf49 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -2775,16 +2775,23 @@ class dl: def select_licensable(self, selection: TrackSelection, title: Title_T, service: TitleSource) -> Kept | Skip: """Select the tracks of ``title`` and load their deferred DRM. - Without a FairPlay bridge hook, a selected video or audio track with no DRM that is FairPlay-only leaves the - candidates and the selection runs again; each pass removes a track, so the loop ends. An import has the keys - of such a track in its export. A kind that loses each of its tracks skips the title. + A selected video or audio track with no DRM that is FairPlay-only leaves the candidates and the selection runs + again; each pass removes a track, so the loop ends. A FairPlay bridge hook keeps the HLS ones, as DASH has no + bridge. An import has the keys of such a track in its export. A kind that loses each of its tracks skips the + title. """ - gate = service.fairplay_bridge() is None and service.key_arrival is not KeyArrival.EXPORT + hook = service.fairplay_bridge() is not None + gate = service.key_arrival is not KeyArrival.EXPORT + reason = "DASH has no FairPlay bridge" if hook else f"{self.service} has no FairPlay bridge hook" def prepare(track: AnyTrack) -> bool: track.load_drm_if_needed(service) return ( - gate and isinstance(track, (Video, Audio)) and not track.drm and fairplay_only(track, service.session) + gate + and isinstance(track, (Video, Audio)) + and (not hook or track.descriptor is Track.Descriptor.DASH) + and not track.drm + and fairplay_only(track, service.session) ) candidates = Tracks(title.tracks) @@ -2803,14 +2810,12 @@ class dl: title.tracks.audio = [audio for audio in title.tracks.audio if not probed.get(audio.id)] if left_out := [track for track in candidates if probed.get(track.id)]: count = len(left_out) - self.log.info( - f"Left out {count} FairPlay-only track{'s' * (count != 1)}: {self.service} has no FairPlay bridge hook" - ) + self.log.info(f"Left out {count} FairPlay-only track{'s' * (count != 1)}: {reason}") if isinstance(outcome, Skip): return outcome for kind, track_type, tracks in (("video", Video, title.tracks.videos), ("audio", Audio, title.tracks.audio)): if not tracks and any(isinstance(track, track_type) for track in left_out): - return Skip(f"Each selected {kind} track is FairPlay-only: {self.service} has no FairPlay bridge hook") + return Skip(f"Each selected {kind} track is FairPlay-only: {reason}") return outcome def write_sample(self, source: Path, title: Title_T, media_info: MediaInfo) -> None: diff --git a/unshackle/core/manifests/dash.py b/unshackle/core/manifests/dash.py index c43b8b88..86113c3c 100644 --- a/unshackle/core/manifests/dash.py +++ b/unshackle/core/manifests/dash.py @@ -33,7 +33,7 @@ from unshackle.core.downloaders.requests import parse_content_range, range_answe from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine from unshackle.core.drm.cenc import COMMON_ID, PLACEHOLDER_KIDS, PLAYREADY_ID, common_pssh_kids from unshackle.core.drm.segment_decrypt import SEGMENT_DRM_T, SegmentDecrypter, can_use -from unshackle.core.drm.verify import walk +from unshackle.core.drm.verify import has_encrypted_entry, has_encrypted_sample_entry, walk from unshackle.core.manifests.segment_pipeline import ( append_segment, check_merged, @@ -42,6 +42,7 @@ from unshackle.core.manifests.segment_pipeline import ( license_drm, ) from unshackle.core.manifests.trim import trim_overlaps +from unshackle.core.remote_protocol import APIErrorCode, coded from unshackle.core.session import RnetSession, unrecorded from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore @@ -663,6 +664,9 @@ class DASH: track.drm = [clearkey] drm = track.get_drm_for_cdm(cdm) + unlicensable = not drm and not ctx.sample_decrypter + if unlicensable and init_data and has_encrypted_entry(init_data): + raise DASH.unsupported_systems(protections) license_drm(track, drm, ctx, track_kid, probe=lambda: track.get_key_id(url=segments[0][0], session=session)) if DOWNLOAD_LICENCE_ONLY.is_set(): @@ -843,8 +847,21 @@ class DASH: except Exception as e: log.warning(f"Could not trim the audio overlaps of {save_path.name}: {e}") + if unlicensable and not init_data and has_encrypted_sample_entry(save_path): + save_path.unlink() + raise DASH.unsupported_systems(protections) + complete_track(track, ctx, drm, decrypt=not decrypter) + @staticmethod + def unsupported_systems(protections: list[Element]) -> NotImplementedError: + """The error for an encrypted track with no DRM system that unshackle can license.""" + systems = ", ".join(dict.fromkeys(filter(None, (p.get("schemeIdUri") for p in protections)))) + return coded( + NotImplementedError(f"None of the key systems are supported: {systems or 'no ContentProtection'}"), + APIErrorCode.DRM_ERROR, + ) + @staticmethod def find_segment_element(name: str, adaptation_set: Element, representation: Element) -> Element | None: """Find a segment description element on the representation, or else on its adaptation set."""