From f680df7eff08ce4d14cf35f77782aa1fdbaca9b1 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Tue, 1 Dec 2026 17:03:56 -0700 Subject: [PATCH] fix(hls): bridge a stitched one-key FairPlay playlist with an all-zero tenc KID --- docs/dev/service-architecture.md | 8 +- tests/core/test_hls_service_drm_keys.py | 192 +++++++++++++++++++++++- unshackle/core/drm/cenc.py | 8 +- unshackle/core/manifests/hls.py | 81 ++++++++-- 4 files changed, 267 insertions(+), 22 deletions(-) diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md index 0a12df9d..1bce61bb 100644 --- a/docs/dev/service-architecture.md +++ b/docs/dev/service-architecture.md @@ -486,8 +486,9 @@ these conditions are true: unshackle cannot license. - The configured CDM is a PlayReady or Widevine CDM. - The init segment (`EXT-X-MAP`) of the track names a key ID in its `tenc` box. When the `tenc` key ID is all - zeros, its `pssh` boxes must name exactly one key ID, and the encrypted segments must have one init - segment and the playlist one key URI. MPEG-TS media has no init segment. + zeros, the playlist must have one key URI, and each init segment under the key tag must give the same + key ID: its `tenc` key ID, or else the one key ID that its `pssh` boxes name. A clear init segment, + such as the one of a clear lead or tail, does not count. MPEG-TS media has no init segment. - The init segment does not change without an `EXT-X-DISCONTINUITY`. The download reads the key ID from the init segment, builds a DRM object for the DRM system of the @@ -498,7 +499,8 @@ licence that gives no content key stops the track before it downloads a segment. A service that must choose the DRM system itself, or one that knows the key ID, puts the DRM object on the track: -1. Read the key ID from the init segment of the track. `HLS.get_track_kid_from_init` returns it. +1. Read the key ID from the init segment of the track. `HLS.get_track_kid_from_init` returns it. It reads + the first init segment of the playlist, unless you give it the init segment of the encrypted segments. 2. Put a DRM object that names the key ID on the track: `drm_stub` from `unshackle.core.drm.cenc` with `"playready"` or `"widevine"` and the key ID. When only one of the two systems issues the content key, also set `track.drm_preference` to it. diff --git a/tests/core/test_hls_service_drm_keys.py b/tests/core/test_hls_service_drm_keys.py index 6ca99419..b414294a 100644 --- a/tests/core/test_hls_service_drm_keys.py +++ b/tests/core/test_hls_service_drm_keys.py @@ -7,6 +7,7 @@ Such a playlist carries no Widevine, PlayReady or AES-128 tag. The service puts from __future__ import annotations from pathlib import Path +from types import SimpleNamespace from typing import Any from unittest.mock import Mock from uuid import UUID @@ -14,10 +15,13 @@ from uuid import UUID import m3u8 import pytest from pywidevine.pssh import PSSH +from requests import Session +from tests.core.test_cenc import widevine_box +from tests.core.test_kid_windows import box, encv, movie, sinf from unshackle.core.cdm.detect import cdm_type_stub from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY -from unshackle.core.drm import ClearKey, PlayReady +from unshackle.core.drm import ClearKey, PlayReady, cenc from unshackle.core.drm.cenc import drm_stub from unshackle.core.manifests.hls import HLS from unshackle.core.manifests.hls_keys import key_spans @@ -36,6 +40,11 @@ WIDEVINE_KEY = ( ) +@pytest.fixture(autouse=True) +def no_ffprobe(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(cenc, "ffprobe", lambda data: {}) + + def playlist(*key_tags: str) -> str: return ( "#EXTM3U\n#EXT-X-VERSION:6\n#EXT-X-TARGETDURATION:6\n" @@ -59,13 +68,14 @@ def hls_video(tmp_path: Path, text: str) -> Video: return track -def download(track: Video, cdm: Any, licence: Any = None, licence_only: bool = False) -> None: +def download(track: Video, cdm: Any, licence: Any = None, licence_only: bool = False, session: Any = None) -> None: ctx = DownloadContext( save_path=Path(track.from_file).with_name("video.mp4"), save_dir=Path(track.from_file).with_name("video_segments"), progress=lambda **_: None, license_widevine=licence or (lambda drm, track_kid=None: pytest.fail("a licence was requested")), cdm=cdm, + session=session, ) if licence_only: DOWNLOAD_LICENCE_ONLY.set() @@ -232,12 +242,11 @@ TWO_KEYS = playlist(SKD_KEY).replace("seg0.m4s\n", f"seg0.m4s\n{SKD_KEY.replace( [ pytest.param(playlist(SKD_KEY), False, True, id="one-init-one-key"), pytest.param(two_inits("#EXT-X-DISCONTINUITY\n"), False, True, id="clear-lead"), - pytest.param(two_inits("#EXT-X-DISCONTINUITY\n", f"{SKD_KEY}\n"), False, False, id="two-inits"), pytest.param(TWO_KEYS, False, False, id="two-keys"), pytest.param(TWO_KEYS, True, False, id="sample-of-the-second-key"), ], ) -def test_the_pssh_names_the_key_id_only_of_one_init_segment_with_one_key( +def test_one_keyed_init_segment_reads_its_pssh_only_in_a_one_key_playlist( tmp_path: Path, monkeypatch: Any, text: str, skip_first: bool, pssh: bool ) -> None: """With an all-zero tenc, a decrypter gives the one content key to every segment, so a second key is garbage.""" @@ -251,6 +260,177 @@ def test_the_pssh_names_the_key_id_only_of_one_init_segment_with_one_key( assert [call.kwargs["pssh"] for call in probe.call_args_list] == [pssh] +OTHER_KID = UUID("44444444-4444-4444-4444-444444444444") +ZERO_KID = UUID(int=0) +CLEAR_INIT = movie(box(b"avc1", bytes(78))) + + +def encrypted_init(tenc: UUID, *pssh: UUID, piff: bool = False) -> bytes: + """An init segment with one Widevine pssh box for each KID of ``pssh``.""" + return movie(encv(tenc, piff), others=b"".join(widevine_box(kid) for kid in pssh)) + + +ZERO_INIT = encrypted_init(ZERO_KID, KID) + + +def stitched(*inits: str, keyed_from: int = 1) -> str: + """A playlist with one discontinuity block for each init segment, where block ``keyed_from`` holds the key tag.""" + blocks = [f'#EXT-X-MAP:URI="{name}"\n#EXTINF:6.0,\n{i}.m4s\n' for i, name in enumerate(inits)] + blocks[keyed_from] = f"{SKD_KEY}\n{blocks[keyed_from]}" + body = "#EXT-X-DISCONTINUITY\n".join(blocks) + return f"#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-TARGETDURATION:6\n{body}#EXT-X-ENDLIST\n" + + +class InitServer(Session): + """A session that serves a clear lead and a main init with an all-zero tenc by name, and the given ``files``. + + A name with no bytes gives HTTP 404 with a clear init. + """ + + def __init__(self, **files: bytes | None) -> None: + super().__init__() + self.files = {f"{name}.mp4": data for name, data in {"lead": CLEAR_INIT, "init": ZERO_INIT, **files}.items()} + self.requests: list[str] = [] + + def get(self, url: str, **_: Any) -> SimpleNamespace: # type: ignore[override] + name = url.rsplit("/", 1)[-1] + self.requests.append(name) + data = self.files.get(name) + if data is None: + return SimpleNamespace(ok=False, status_code=404, content=CLEAR_INIT) + return SimpleNamespace(ok=True, status_code=200, content=data) + + +STITCHED_ZERO = [ + pytest.param(stitched("lead.mp4", "init.mp4", "lead.mp4"), {}, ["init.mp4", "lead.mp4"], id="clear-lead-and-tail"), + pytest.param( + stitched("lead.mp4", "init.mp4", "lead.mp4", keyed_from=0), + {}, + ["lead.mp4", "init.mp4"], + id="tag-on-the-clear-lead", + ), + pytest.param( + stitched("lead.mp4", "init.mp4", "again.mp4", "init.mp4", "again.mp4"), + {"again": encrypted_init(ZERO_KID, KID, KID)}, + ["init.mp4", "again.mp4"], + id="two-encrypted-inits-of-one-kid", + ), + pytest.param( + stitched("lead.mp4", "init.mp4", "real.mp4"), + {"real": encrypted_init(KID)}, + ["init.mp4", "real.mp4"], + id="a-later-real-tenc-of-the-kid", + ), + pytest.param( + stitched("lead.mp4", "real.mp4", "lead.mp4", keyed_from=0), + {"real": encrypted_init(KID)}, + ["lead.mp4", "real.mp4"], + id="tag-on-the-clear-lead-of-a-real-tenc", + ), +] + + +@pytest.mark.parametrize("text, files, requests", STITCHED_ZERO) +def test_a_stitched_one_key_playlist_takes_the_key_id_that_every_encrypted_init_names( + tmp_path: Path, text: str, files: dict[str, bytes], requests: list[str] +) -> None: + """The tail is a keyed span with an init segment of its own, because a key tag governs until the next one.""" + session = InitServer(**files) + licensed: list[UUID | None] = [] + + download( + hls_video(tmp_path, text), + cdm_type_stub("playready"), + lambda drm, track_kid=None: licensed.append(track_kid), + licence_only=True, + session=session, + ) + + assert licensed == [KID] + assert session.requests == requests + + +@pytest.mark.parametrize( + "tail", + [ + pytest.param(encrypted_init(ZERO_KID, OTHER_KID), id="other-pssh-kid"), + pytest.param(encrypted_init(OTHER_KID, KID), id="other-tenc-kid"), + pytest.param(encrypted_init(ZERO_KID), id="no-pssh"), + pytest.param(encrypted_init(ZERO_KID, KID, OTHER_KID), id="two-kids-in-the-pssh"), + pytest.param(encrypted_init(ZERO_KID, piff=True), id="piff-tenc"), + pytest.param(None, id="failed-request"), + pytest.param(b"", id="empty-body"), + pytest.param(b"moov", id="no-init-segment"), + pytest.param(CLEAR_INIT[:-1], id="cut-init-segment"), + pytest.param(box(b"moov"), id="no-sample-table"), + pytest.param(movie(box(b"avc1", bytes(78), sinf(ZERO_KID))), id="tenc-in-a-clear-entry"), + pytest.param(movie(box(b"avc1", bytes(78), sinf(ZERO_KID, piff=True))), id="piff-tenc-in-a-clear-entry"), + pytest.param(movie(box(b"encv", bytes(78))), id="encrypted-entry-with-no-tenc"), + ], +) +def test_a_stitched_one_key_playlist_is_refused_when_an_init_can_hold_another_key_id( + tmp_path: Path, tail: bytes | None +) -> None: + session = InitServer(tail=tail) + track = hls_video(tmp_path, stitched("lead.mp4", "init.mp4", "lead.mp4", "tail.mp4")) + + with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"): + download(track, cdm_type_stub("playready"), session=session) + + assert session.requests[-1] == "tail.mp4" + + +def test_a_first_encrypted_init_with_no_key_id_stops_the_reads(tmp_path: Path) -> None: + manifest = m3u8.loads(stitched("lead.mp4", "init.mp4", "tail.mp4"), "https://example.test/media.m3u8") + session = InitServer(init=encrypted_init(ZERO_KID), tail=ZERO_INIT) + + assert HLS.get_bridge_kid(manifest, manifest.segments, hls_video(tmp_path, ""), session) is None + assert session.requests == ["init.mp4"] + + +def test_an_all_zero_key_id_from_ffprobe_reads_the_pssh(tmp_path: Path, monkeypatch: Any) -> None: + zero = {"streams": [{"tags": {"enc_key_id": "AAAAAAAAAAAAAAAAAAAAAA=="}}]} + monkeypatch.setattr(cenc, "ffprobe", lambda data: zero) + manifest = m3u8.loads(stitched("lead.mp4", "init.mp4", "lead.mp4"), "https://example.test/media.m3u8") + session = InitServer() + + assert HLS.get_bridge_kid(manifest, manifest.segments, hls_video(tmp_path, ""), session) == KID + + +def test_a_stitched_playlist_with_two_keys_is_refused(tmp_path: Path) -> None: + text = stitched("lead.mp4", "init.mp4", "lead.mp4") + text = text.replace("#EXTINF:6.0,\n2.m4s", f"{SKD_KEY.replace('asset', 'other')}\n#EXTINF:6.0,\n2.m4s") + + with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"): + download(hls_video(tmp_path, text), cdm_type_stub("playready"), session=InitServer()) + + +@pytest.mark.parametrize("init, kid", [(encrypted_init(KID), KID), (None, None)], ids=["real-kid", "failed-request"]) +def test_only_an_all_zero_first_key_id_reads_the_other_init_segments( + tmp_path: Path, init: bytes | None, kid: UUID | None +) -> None: + session = InitServer(init=init) + manifest = m3u8.loads(stitched("lead.mp4", "init.mp4", "tail.mp4"), "https://example.test/media.m3u8") + + assert HLS.get_bridge_kid(manifest, manifest.segments, hls_video(tmp_path, ""), session) == kid + assert session.requests == ["init.mp4"] + + +@pytest.mark.parametrize("text, files, requests", STITCHED_ZERO) +def test_the_server_takes_the_same_key_id_of_a_stitched_playlist( + tmp_path: Path, monkeypatch: Any, text: str, files: dict[str, bytes], requests: list[str] +) -> None: + session = InitServer(**files) + monkeypatch.setattr("unshackle.core.tracks.track.utf8_text", lambda response: text) + track = hls_video(tmp_path, text) + + assert track.load_drm_from_playlist(session, bridge=True) + + assert track.drm is not None + assert [drm.kids for drm in track.drm] == [[KID], [KID]] + assert session.requests == ["media.m3u8", *requests] + + @pytest.mark.parametrize( "text, kid, cdm", [ @@ -284,12 +464,14 @@ def test_a_track_with_no_drm_that_cannot_be_bridged_is_refused_before_the_downlo ) -> None: track = hls_video(tmp_path, text) probe = init_kid_probe(monkeypatch, kid) + session = InitServer() with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"): - download(track, cdm) + download(track, cdm, session=session) assert not track.drm assert probe.called == (kid != KID) + assert not session.requests def test_a_licence_with_no_content_key_stops_the_bridge_before_a_segment(tmp_path: Path, monkeypatch: Any) -> None: diff --git a/unshackle/core/drm/cenc.py b/unshackle/core/drm/cenc.py index 5cf6366e..13dbd485 100644 --- a/unshackle/core/drm/cenc.py +++ b/unshackle/core/drm/cenc.py @@ -20,7 +20,7 @@ from unshackle.core.config import config from unshackle.core.constants import AnyTrack from unshackle.core.drm import key_args as drm_key_args from unshackle.core.drm.decrypters import decrypt_cenc, mp4decrypt, shaka_decrypt -from unshackle.core.drm.verify import PIFF_TENC +from unshackle.core.drm.verify import PIFF_TENC, TENC, has_encrypted_entry, walk from unshackle.core.session import AnySession, utf8_text from unshackle.core.utilities import get_boxes from unshackle.core.utils import run_proxy @@ -121,6 +121,12 @@ def init_pssh_kid(init_data: bytes) -> UUID | None: return kids.pop() if len(kids) == 1 else None +def is_clear_init(init_data: bytes) -> bool: + """True when a complete init segment names no encrypted sample entry and no tenc.""" + complete = any(kind == b"stsd" for kind, _, _ in walk(init_data)) + return complete and not has_encrypted_entry(init_data) and not any(tenc in init_data for tenc in TENC) + + def hls_key_drm(key: Any, kid: UUID | None = None) -> Widevine | PlayReady | None: """The Widevine or PlayReady DRM of an EXT-X-KEY, or None for another KEYFORMAT. diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py index 0267707d..40f911ff 100644 --- a/unshackle/core/manifests/hls.py +++ b/unshackle/core/manifests/hls.py @@ -40,6 +40,7 @@ from unshackle.core.drm.cenc import ( drm_stub, hls_key_drm, init_pssh_kid, + is_clear_init, key_data, key_system, ) @@ -1449,26 +1450,40 @@ class HLS: if not map_section: return None - map_uri = urljoin(map_section.base_uri or master.base_uri or "", map_section.uri) + init_data = HLS.probe_init_section(master, session, map_section) + if init_data is None: + return None try: - if map_section.byterange: - byte_range = HLS.calculate_byte_range(map_section.byterange, 0) + kid = track.get_key_id(init_data) + if pssh and (kid is None or kid.int == 0): + return init_pssh_kid(init_data) + return kid + except Exception as e: + logging.getLogger("HLS").debug(f"Init map key-id probe failed for {map_section.uri}: {e!r}") + return None + + @staticmethod + def probe_init_section( + master: M3U8, session: Session | RnetSession, init_section: m3u8.model.InitializationSection + ) -> bytes | None: + """The bytes of an init segment (EXT-X-MAP), or None when the request for it fails.""" + try: + map_uri = urljoin(init_section.base_uri or master.base_uri or "", init_section.uri) + if init_section.byterange: + byte_range = HLS.calculate_byte_range(init_section.byterange, 0) headers = {"Range": f"bytes={byte_range}"} else: headers = {} map_res = unrecorded(session, "get", map_uri, headers=headers) if map_res.ok: - kid = track.get_key_id(map_res.content) - if pssh and (kid is None or kid.int == 0): - return init_pssh_kid(map_res.content) - return kid + return bytes(map_res.content) logging.getLogger("HLS").warning( f"Could not read the Key ID from the init segment {safe_display_url(map_uri)}: " f"HTTP {map_res.status_code}" ) - # best-effort key-id probe over network + init parse; caller falls back without it + # best-effort request; caller falls back without it except Exception as e: - logging.getLogger("HLS").debug(f"Init map key-id probe failed for {map_uri}: {e!r}") + logging.getLogger("HLS").debug(f"Init segment request failed for {init_section.uri}: {e!r}") return None @staticmethod @@ -1510,19 +1525,59 @@ class HLS: None when `only_unsupported_keys` is false of `manifest`, or when the init segment changes with no EXT-X-DISCONTINUITY: the merge splits there only on a changed EXT-X-KEY, and the tags go. - The pssh boxes count only for one init segment in a one-key playlist: an all-zero tenc takes any content key. + The pssh boxes count only in a one-key playlist, and with several init segments only as `get_stitched_kid` reads + them: an all-zero tenc takes any content key. """ keyed = [span for span in key_spans(manifest, segments) if span.init_section and span.keys] if not keyed or not HLS.only_unsupported_keys(manifest): return None - init_section = keyed[0].init_section one_key = len({key.uri for key in manifest.keys if key}) == 1 - pssh = one_key and all(span.init_section == init_section for span in keyed) if any(b.init_section != a.init_section and not b.discontinuity for a, b in pairwise(segments)): return None - kid = HLS.get_track_kid_from_init(manifest, track, session, init_section, pssh=pssh) + init_sections: list[m3u8.model.InitializationSection] = [] + for span in keyed: + if span.init_section not in init_sections: + init_sections.append(span.init_section) + if one_key and len(init_sections) > 1: + kid = HLS.get_stitched_kid(manifest, init_sections, track, session) + else: + kid = HLS.get_track_kid_from_init(manifest, track, session, init_sections[0], pssh=one_key) return None if kid in PLACEHOLDER_KIDS else kid + @staticmethod + def get_stitched_kid( + manifest: M3U8, + init_sections: list[m3u8.model.InitializationSection], + track: Track, + session: Session | RnetSession, + ) -> UUID | None: + """The tenc Key ID of the first init segment, or when that is all-zero, the one Key ID that all of them give. + + Each gives its tenc Key ID, or else that of its pssh boxes. One that is clear does not count, and one that + unshackle cannot read makes it None. + """ + found: UUID | None = None + for init_section in init_sections: + init_data = HLS.probe_init_section(manifest, session, init_section) + if not init_data: + return None + try: + if is_clear_init(init_data): + continue + kid = track.get_key_id(init_data) + if not (kid and kid.int): + kid = init_pssh_kid(init_data) + elif init_section is init_sections[0]: + return kid + except Exception as e: + logging.getLogger("HLS").debug(f"Init map key-id probe failed for {init_section.uri}: {e!r}") + return None + if kid is None or found not in (None, kid): + logging.getLogger("HLS").debug(f"{track.id}: init segment {init_section.uri} gives key ID {kid}") + return None + found = kid + return found + @staticmethod def only_unsupported_keys(manifest: M3U8) -> bool: """Whether each EXT-X-KEY of `manifest`, at least one, is sample encryption of a DRM system unshackle cannot license.