feat(hls): license a FairPlay-only SAMPLE-AES playlist through a PlayReady or Widevine CDM

This commit is contained in:
imSp4rky
2026-11-30 19:36:01 -07:00
parent c41d8ec3cf
commit b826eccb86
9 changed files with 449 additions and 98 deletions
+45
View File
@@ -18,6 +18,7 @@ from tests.core.test_kid_windows import box, encv
from unshackle.core import binaries
from unshackle.core.drm import PlayReady, Widevine, cenc
from unshackle.core.drm.verify import PIFF_TENC
from unshackle.core.manifests import HLS
from unshackle.core.tracks import Video
from unshackle.core.utils import subprocess as subprocess_utils
@@ -76,6 +77,38 @@ def test_init_kid_is_none_without_a_real_kid() -> None:
assert cenc.init_kid(init(encv(UUID(int=0)))) is None
def common_box(kid: UUID) -> bytes:
body = {"type": b"pssh", "version": 1, "flags": 0, "system_ID": cenc.COMMON_ID, "key_IDs": [kid], "init_data": b""}
return Box.build(body)
def widevine_box(*kids: UUID) -> bytes:
return PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=list(kids)).dump()
@pytest.mark.parametrize(
"boxes, kid",
[
pytest.param([playready_box(TRACK_KID)], TRACK_KID, id="one-system"),
pytest.param([widevine_box(TRACK_KID), playready_box(TRACK_KID)], TRACK_KID, id="both-systems-agree"),
pytest.param([widevine_box(TRACK_KID, OTHER_KID)], None, id="several-kids"),
pytest.param([widevine_box(OTHER_KID), playready_box(TRACK_KID)], None, id="systems-disagree"),
pytest.param([widevine_box(TRACK_KID), widevine_box(OTHER_KID)], None, id="two-boxes-of-one-system"),
pytest.param([widevine_box(TRACK_KID), common_box(OTHER_KID)], None, id="common-box-disagrees"),
pytest.param([common_box(TRACK_KID)], TRACK_KID, id="common-box"),
pytest.param([PSSH(no_kid_pssh()).dump(), playready_box(TRACK_KID)], TRACK_KID, id="one-box-without-a-kid"),
pytest.param([widevine_box(UUID(int=0))], None, id="placeholder"),
pytest.param([], None, id="no-pssh"),
],
)
def test_init_pssh_kid_is_the_one_real_kid_the_pssh_boxes_name(boxes: list[bytes], kid: UUID | None) -> None:
assert cenc.init_pssh_kid(init(*boxes, encv(UUID(int=0)))) == kid
def test_init_pssh_kid_needs_a_tenc() -> None:
assert cenc.init_pssh_kid(init(widevine_box(TRACK_KID))) is None
def test_widevine_from_init_data_takes_the_piff_kid_when_the_pssh_names_none() -> None:
pssh = PSSH(no_kid_pssh()).dump()
drm = Widevine.from_init_data(init(pssh, encv(TRACK_KID, piff=True)))
@@ -249,3 +282,15 @@ def test_from_track_reads_the_playlist_pssh_and_the_init_kid() -> None:
assert drm.kids == [OTHER_KID, TRACK_KID]
with pytest.raises(Widevine.Exceptions.PSSHNotFound):
Widevine.from_track(track, track.session)
def test_the_hls_probe_reads_the_pssh_kid_only_when_asked() -> None:
manifest = cenc.m3u8.loads('#EXTM3U\n#EXT-X-MAP:URI="init.mp4"\n#EXTINF:6.0,\nseg0.m4s\n#EXT-X-ENDLIST\n')
content = init(playready_box(TRACK_KID), encv(UUID(int=0)))
session: Any = SimpleNamespace(get=lambda url, headers=None: SimpleNamespace(ok=True, content=content))
track = playlist_track("")
track.get_key_id = lambda data: cenc.init_kid(data) # type: ignore[method-assign]
assert HLS.get_track_kid_from_init(manifest, track, session) is None
assert HLS.get_track_kid_from_init(manifest, track, session, pssh=True) == TRACK_KID
+210 -76
View File
@@ -1,13 +1,14 @@
"""A service can license a playlist whose key tags name key systems unshackle cannot license itself.
"""A playlist whose key tags name key systems unshackle cannot license is licensed with another DRM of the track.
Such a playlist carries no Widevine, PlayReady or AES-128 tag. The service puts its own DRM on the track, and
``HLS.download_track`` then reads the playlist as one with no key tag.
Such a playlist carries no Widevine, PlayReady or AES-128 tag. The service puts its own DRM on the track, or
``HLS.download_track`` builds one for the CDM, and the download then reads the playlist as one with no key tag.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from unittest.mock import Mock
from uuid import UUID
import m3u8
@@ -16,7 +17,7 @@ from pywidevine.pssh import PSSH
from unshackle.core.cdm.detect import cdm_type_stub
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY
from unshackle.core.drm import ClearKey
from unshackle.core.drm import ClearKey, PlayReady
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.manifests.hls import HLS
from unshackle.core.tracks import Video
@@ -43,6 +44,43 @@ def playlist(*key_tags: str) -> str:
)
def hls_video(tmp_path: Path, text: str) -> Video:
playlist_file = tmp_path / "media.m3u8"
playlist_file.write_text(text, encoding="utf-8")
track = Video(
url="https://example.test/media.m3u8",
language="en",
descriptor=Track.Descriptor.HLS,
codec=Video.Codec.HEVC,
)
track.from_file = playlist_file
track.downloader = lambda **kwargs: pytest.fail("a segment was requested")
return track
def download(track: Video, cdm: Any, licence: Any = None, licence_only: bool = False) -> 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,
)
if licence_only:
DOWNLOAD_LICENCE_ONLY.set()
try:
HLS.download_track(track=track, ctx=ctx)
finally:
DOWNLOAD_LICENCE_ONLY.clear()
def init_kid_probe(monkeypatch: Any, kid: UUID | None) -> Mock:
"""The KID normally comes from the init segment; these tests are offline."""
probe = Mock(return_value=kid)
monkeypatch.setattr(HLS, "get_track_kid_from_init", probe)
return probe
def test_key_tags_no_licence_route_can_use_are_dropped() -> None:
manifest = m3u8.loads(playlist(SKD_KEY))
@@ -85,91 +123,187 @@ def test_a_playlist_with_no_key_tag_is_left_alone() -> None:
def test_the_drm_of_the_service_licenses_the_track(tmp_path: Path, monkeypatch: Any) -> None:
playlist_file = tmp_path / "media.m3u8"
playlist_file.write_text(playlist(SKD_KEY), encoding="utf-8")
track = Video(
url="https://example.test/media.m3u8",
language="en",
descriptor=Track.Descriptor.HLS,
codec=Video.Codec.HEVC,
)
track.from_file = playlist_file
drm = drm_stub("playready", [KID.hex])
track.drm = [drm]
# the KID normally comes from the init segment; this test is offline
monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: KID))
track = hls_video(tmp_path, playlist(SKD_KEY))
track.drm = [drm_stub("playready", [KID.hex])]
init_kid_probe(monkeypatch, KID)
licensed: list[tuple[str, UUID | None]] = []
ctx = DownloadContext(
save_path=tmp_path / "video.mp4",
save_dir=tmp_path / "video_segments",
progress=lambda **_: None,
license_widevine=lambda drm, track_kid=None: licensed.append((type(drm).__name__, track_kid)),
cdm=None,
)
DOWNLOAD_LICENCE_ONLY.set()
try:
HLS.download_track(track=track, ctx=ctx)
finally:
DOWNLOAD_LICENCE_ONLY.clear()
download(
track,
None,
lambda drm, track_kid=None: licensed.append((type(drm).__name__, track_kid)),
licence_only=True,
)
assert licensed == [("PlayReady", KID)]
def test_a_track_without_drm_still_refuses_the_key_tag(tmp_path: Path, monkeypatch: Any) -> None:
playlist_file = tmp_path / "media.m3u8"
playlist_file.write_text(playlist(SKD_KEY), encoding="utf-8")
track = Video(
url="https://example.test/media.m3u8",
language="en",
descriptor=Track.Descriptor.HLS,
codec=Video.Codec.HEVC,
)
track.from_file = playlist_file
monkeypatch.setattr(HLS, "get_track_kid_from_init", staticmethod(lambda *args, **kwargs: None))
ctx = DownloadContext(
save_path=tmp_path / "video.mp4",
save_dir=tmp_path / "video_segments",
progress=lambda **_: None,
license_widevine=lambda drm, track_kid=None: None,
cdm=None,
)
@pytest.mark.parametrize("method", ["SAMPLE-AES", "SAMPLE-AES-CTR"])
@pytest.mark.parametrize("system, drm_class", [("playready", "PlayReady"), ("widevine", "Widevine")])
def test_a_track_with_no_drm_licenses_through_the_cdm(
tmp_path: Path, monkeypatch: Any, caplog: pytest.LogCaptureFixture, system: str, drm_class: str, method: str
) -> None:
track = hls_video(tmp_path, playlist(SKD_KEY.replace("SAMPLE-AES", method)))
probe = init_kid_probe(monkeypatch, KID)
licensed: list[tuple[str, list[UUID], UUID | None]] = []
DOWNLOAD_LICENCE_ONLY.set()
try:
with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"):
HLS.download_track(track=track, ctx=ctx)
finally:
DOWNLOAD_LICENCE_ONLY.clear()
with caplog.at_level("DEBUG", logger="HLS"):
download(
track,
cdm_type_stub(system),
lambda drm, track_kid=None: licensed.append((type(drm).__name__, drm.kids, track_kid)),
licence_only=True,
)
assert licensed == [(drm_class, [KID], KID)]
assert [type(drm).__name__ for drm in track.drm] == [drm_class]
assert probe.call_count == 1
lines = [record.getMessage() for record in caplog.records if KID.hex in record.getMessage()]
assert len(lines) == 1 and track.id in lines[0] and drm_class in lines[0]
def two_inits(between: str, lead_key: str = "") -> str:
"""A playlist with a lead under ``ad.mp4``, then the segments of ``init.mp4`` with the FairPlay key tag."""
return playlist(SKD_KEY).replace(
'#EXT-X-MAP:URI="init.mp4",BYTERANGE="994@0"\n',
f'#EXT-X-MAP:URI="ad.mp4"\n{lead_key}#EXTINF:6.0,\nad.m4s\n{between}#EXT-X-MAP:URI="init.mp4"\n',
)
@pytest.mark.parametrize(
"drm",
"text, skip_lead",
[
pytest.param(None, id="no-drm"),
pytest.param(ClearKey(key=bytes(16)), id="aes-128-session-key"),
pytest.param(two_inits("#EXT-X-DISCONTINUITY\n", f"{SKD_KEY}\n"), True, id="filtered-encrypted-lead"),
pytest.param(two_inits("#EXT-X-DISCONTINUITY\n"), False, id="clear-lead"),
],
)
def test_a_track_whose_drm_cannot_stand_in_is_refused_before_the_download(tmp_path: Path, drm: Any) -> None:
"""The refusal comes before a segment is requested: a ClearKey would otherwise write the ciphertext as the output."""
playlist_file = tmp_path / "media.m3u8"
playlist_file.write_text(playlist(SKD_KEY), encoding="utf-8")
track = Video(
url="https://example.test/media.m3u8",
language="en",
descriptor=Track.Descriptor.HLS,
codec=Video.Codec.HEVC,
)
track.from_file = playlist_file
track.drm = [drm] if drm else None
track.downloader = lambda **kwargs: pytest.fail("a segment was requested")
ctx = DownloadContext(
save_path=tmp_path / "video.mp4",
save_dir=tmp_path / "video_segments",
progress=lambda **_: None,
license_widevine=lambda drm, track_kid=None: pytest.fail("a licence was requested"),
cdm=cdm_type_stub("playready"),
def test_the_key_id_comes_from_the_init_segment_of_the_encrypted_segments(
tmp_path: Path, monkeypatch: Any, text: str, skip_lead: bool
) -> None:
track = hls_video(tmp_path, text)
if skip_lead:
track.OnSegmentFilter = lambda segment: segment.uri.startswith("ad")
licensed: list[UUID | None] = []
init_kid_probe(monkeypatch, None).side_effect = lambda master, track, session, init_section=None, pssh=False: {
"init.mp4": KID
}.get(init_section.uri)
download(
track,
cdm_type_stub("playready"),
lambda drm, track_kid=None: licensed.append(track_kid),
licence_only=True,
)
assert licensed == [KID]
def filter_first_segment(track: Video) -> None:
track.OnSegmentFilter = lambda segment: segment.uri == "seg0.m4s"
@pytest.mark.parametrize(
"cdm", [pytest.param(cdm_type_stub("playready"), id="bridge"), pytest.param(None, id="refused")]
)
def test_a_key_tag_on_a_skipped_segment_stays_in_force(tmp_path: Path, monkeypatch: Any, cdm: Any) -> None:
"""python-m3u8 puts a key tag on the next segment only, and ``--sample`` can skip that segment."""
track = hls_video(tmp_path, playlist(SKD_KEY))
filter_first_segment(track)
init_kid_probe(monkeypatch, KID)
licensed: list[UUID | None] = []
def run() -> None:
download(track, cdm, lambda drm, track_kid=None: licensed.append(track_kid), licence_only=True)
if cdm:
run()
assert licensed == [KID]
else:
with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"):
run()
TWO_KEYS = playlist(SKD_KEY).replace("seg0.m4s\n", f"seg0.m4s\n{SKD_KEY.replace('asset', 'other')}\n")
@pytest.mark.parametrize(
"text, skip_first, pssh",
[
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(
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."""
track = hls_video(tmp_path, text)
if skip_first:
filter_first_segment(track)
probe = init_kid_probe(monkeypatch, KID)
download(track, cdm_type_stub("playready"), lambda drm, track_kid=None: None, licence_only=True)
assert [call.kwargs["pssh"] for call in probe.call_args_list] == [pssh]
@pytest.mark.parametrize(
"text, kid, cdm",
[
pytest.param(playlist(SKD_KEY), KID, None, id="no-cdm"),
pytest.param(playlist(SKD_KEY), KID, object(), id="cdm-of-neither-system"),
pytest.param(
playlist(SKD_KEY).replace('#EXT-X-MAP:URI="init.mp4",BYTERANGE="994@0"\n', ""),
KID,
cdm_type_stub("playready"),
id="no-init-segment",
),
pytest.param(playlist(SKD_KEY), None, cdm_type_stub("playready"), id="no-key-id"),
pytest.param(playlist(SKD_KEY), UUID(int=0), cdm_type_stub("playready"), id="all-zero-key-id"),
pytest.param(
playlist(SKD_KEY),
UUID("00010203-0405-0607-0809-0a0b0c0d0e0f"),
cdm_type_stub("playready"),
id="placeholder-key-id",
),
pytest.param(two_inits("", f"{SKD_KEY}\n"), KID, cdm_type_stub("playready"), id="init-changes-in-place"),
pytest.param(
playlist(SKD_KEY, '#EXT-X-KEY:METHOD=AES-256,URI="skd://keys.example/asset",KEYFORMAT="other"'),
KID,
cdm_type_stub("playready"),
id="not-sample-encryption",
),
],
)
def test_a_track_with_no_drm_that_cannot_be_bridged_is_refused_before_the_download(
tmp_path: Path, monkeypatch: Any, text: str, kid: UUID | None, cdm: Any
) -> None:
track = hls_video(tmp_path, text)
probe = init_kid_probe(monkeypatch, kid)
with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"):
HLS.download_track(track=track, ctx=ctx)
download(track, cdm)
assert not track.drm
assert probe.called == (kid != KID)
def test_a_licence_with_no_content_key_stops_the_bridge_before_a_segment(tmp_path: Path, monkeypatch: Any) -> None:
track = hls_video(tmp_path, playlist(SKD_KEY))
init_kid_probe(monkeypatch, KID)
with pytest.raises(PlayReady.Exceptions.CEKNotFound, match=KID.hex):
download(track, cdm_type_stub("playready"), lambda drm, track_kid=None: None)
def test_a_track_whose_drm_cannot_stand_in_is_refused_before_the_download(tmp_path: Path, monkeypatch: Any) -> None:
"""The refusal comes before a segment is requested: a ClearKey would otherwise write the ciphertext as the output."""
track = hls_video(tmp_path, playlist(SKD_KEY))
track.drm = [ClearKey(key=bytes(16))]
init_kid_probe(monkeypatch, KID)
with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"):
download(track, cdm_type_stub("playready"))