mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-02 05:55:08 +00:00
fix(hls): bridge a stitched one-key FairPlay playlist with an all-zero tenc KID
This commit is contained in:
@@ -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"<html>moov</html>", 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:
|
||||
|
||||
Reference in New Issue
Block a user