mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-02 05:55:08 +00:00
feat(hls): license every content key of a FairPlay bridge playlist that rotates its key
This commit is contained in:
@@ -463,4 +463,4 @@ def test_a_lost_tag_is_bridged_with_the_first_init_segment(
|
||||
licence=lambda drm, track_kid=None: licensed.append(track_kid),
|
||||
)
|
||||
|
||||
assert licensed == [KID_A]
|
||||
assert licensed == [KID_A, KID_B]
|
||||
|
||||
@@ -17,12 +17,16 @@ import pytest
|
||||
from pywidevine.pssh import PSSH
|
||||
from requests import Session
|
||||
|
||||
from tests.core.key_resolver import key_table, resolver
|
||||
from tests.core.test_cenc import widevine_box
|
||||
from tests.core.test_kid_windows import box, encv, movie, sinf
|
||||
from tests.core.test_playready_multi_header import KEY_A, KEY_B, FakeCdm
|
||||
from unshackle.core.api.server_keys import require_track_pssh
|
||||
from unshackle.core.cdm.detect import cdm_type_stub
|
||||
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY
|
||||
from unshackle.core.drm import ClearKey, PlayReady, cenc
|
||||
from unshackle.core.drm import ClearKey, PlayReady, Widevine, cenc
|
||||
from unshackle.core.drm.cenc import drm_stub
|
||||
from unshackle.core.drm.key_resolution import ContentKeyResolver
|
||||
from unshackle.core.manifests.hls import HLS
|
||||
from unshackle.core.manifests.hls_keys import key_spans
|
||||
from unshackle.core.tracks import Video
|
||||
@@ -403,7 +407,7 @@ def test_the_key_id_of_two_keys_comes_from_the_init_after_a_method_none_lead(tmp
|
||||
manifest = m3u8.loads(text, "https://example.test/media.m3u8")
|
||||
session = InitServer(real=encrypted_init(KID))
|
||||
|
||||
assert HLS.get_bridge_kid(manifest, manifest.segments, hls_video(tmp_path, ""), session) == KID
|
||||
assert HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), session) == [KID]
|
||||
assert session.requests == ["real.mp4"]
|
||||
|
||||
|
||||
@@ -470,7 +474,7 @@ def test_a_first_encrypted_init_with_no_key_id_stops_the_reads(tmp_path: Path) -
|
||||
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 HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), session) == []
|
||||
assert session.requests == ["init.mp4"]
|
||||
|
||||
|
||||
@@ -480,7 +484,7 @@ def test_an_all_zero_key_id_from_ffprobe_reads_the_pssh(tmp_path: Path, monkeypa
|
||||
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
|
||||
assert HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), session) == [KID]
|
||||
|
||||
|
||||
def test_a_stitched_playlist_with_two_keys_is_refused(tmp_path: Path) -> None:
|
||||
@@ -491,17 +495,165 @@ def test_a_stitched_playlist_with_two_keys_is_refused(tmp_path: Path) -> None:
|
||||
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)
|
||||
def test_a_first_init_segment_that_cannot_be_read_stops_the_reads(tmp_path: Path) -> None:
|
||||
session = InitServer(init=None)
|
||||
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 HLS.get_bridge_kids(manifest, manifest.segments, hls_video(tmp_path, ""), session) == []
|
||||
assert session.requests == ["init.mp4"]
|
||||
|
||||
|
||||
ROTATION = stitched("init.mp4", "rot.mp4", keyed_from=0)
|
||||
TWO_URIS = ROTATION.replace(
|
||||
'#EXT-X-MAP:URI="rot.mp4"', f'{SKD_KEY.replace("asset", "other")}\n#EXT-X-MAP:URI="rot.mp4"'
|
||||
)
|
||||
ROTATIONS = [
|
||||
pytest.param(ROTATION, {}, [KID, OTHER_KID], ["init.mp4", "rot.mp4"], id="one-uri"),
|
||||
pytest.param(TWO_URIS, {}, [KID, OTHER_KID], ["init.mp4", "rot.mp4"], id="two-uris"),
|
||||
pytest.param(
|
||||
stitched("lead.mp4", "init.mp4", "rot.mp4", "init.mp4", "lead.mp4"),
|
||||
{},
|
||||
[KID, OTHER_KID],
|
||||
["init.mp4", "rot.mp4", "lead.mp4"],
|
||||
id="clear-lead-and-tail",
|
||||
),
|
||||
pytest.param(
|
||||
stitched("lead.mp4", "init.mp4", "rot.mp4", keyed_from=0),
|
||||
{},
|
||||
[KID, OTHER_KID],
|
||||
["lead.mp4", "init.mp4", "rot.mp4"],
|
||||
id="tag-on-the-clear-lead",
|
||||
),
|
||||
pytest.param(
|
||||
stitched("init.mp4", "rot.mp4", "zero.mp4", "tail.mp4", keyed_from=0),
|
||||
{"zero": ZERO_INIT, "tail": None},
|
||||
[KID, OTHER_KID],
|
||||
["init.mp4", "rot.mp4", "zero.mp4", "tail.mp4"],
|
||||
id="an-all-zero-and-a-failed-later-init",
|
||||
),
|
||||
pytest.param(
|
||||
ROTATION,
|
||||
{"rot": encrypted_init(UUID("00010203-0405-0607-0809-0a0b0c0d0e0f"))},
|
||||
[KID],
|
||||
["init.mp4", "rot.mp4"],
|
||||
id="a-placeholder-later-key-id",
|
||||
),
|
||||
pytest.param(ROTATION, {"rot": encrypted_init(KID)}, [KID], ["init.mp4", "rot.mp4"], id="the-same-key-id-twice"),
|
||||
pytest.param(
|
||||
stitched("init.mp4", "rot.mp4", "lead.mp4", keyed_from=0, clear_from=2),
|
||||
{},
|
||||
[KID, OTHER_KID],
|
||||
["init.mp4", "rot.mp4"],
|
||||
id="a-method-none-tail-is-not-read",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def rotation_server(**files: bytes | None) -> InitServer:
|
||||
"""An InitServer whose ``init.mp4`` names ``KID`` and whose ``rot.mp4`` names ``OTHER_KID``, unless ``files`` differ."""
|
||||
return InitServer(**{"init": encrypted_init(KID), "rot": encrypted_init(OTHER_KID), **files})
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text, files, kids, requests", ROTATIONS)
|
||||
@pytest.mark.parametrize("system", ["playready", "widevine"])
|
||||
def test_a_rotation_licenses_each_real_key_id_of_its_init_segments(
|
||||
tmp_path: Path, system: str, text: str, files: dict[str, bytes | None], kids: list[UUID], requests: list[str]
|
||||
) -> None:
|
||||
"""A licence step for each KID: the resolver skips the licence of a KID whose content key it holds."""
|
||||
session = rotation_server(**files)
|
||||
track = hls_video(tmp_path, text)
|
||||
licensed: list[UUID | None] = []
|
||||
|
||||
download(
|
||||
track,
|
||||
cdm_type_stub(system),
|
||||
lambda drm, track_kid=None: licensed.append(track_kid),
|
||||
licence_only=True,
|
||||
session=session,
|
||||
)
|
||||
|
||||
assert licensed == kids
|
||||
assert session.requests == requests
|
||||
assert track.drm is not None and len(track.drm) == 1
|
||||
drm = track.drm[0]
|
||||
if isinstance(drm, PlayReady):
|
||||
assert [drm.header_kids(header) for header in drm.distinct_headers()] == [[kid] for kid in kids]
|
||||
else:
|
||||
assert drm.pssh.key_ids == kids
|
||||
|
||||
|
||||
def test_a_playready_rotation_sends_a_challenge_for_each_key_id(tmp_path: Path) -> None:
|
||||
"""A WRMHEADER 4.0 holds one KID, so one header that names both would license the first content key only."""
|
||||
track = hls_video(tmp_path, ROTATION)
|
||||
download(
|
||||
track,
|
||||
cdm_type_stub("playready"),
|
||||
lambda drm, track_kid=None: None,
|
||||
licence_only=True,
|
||||
session=rotation_server(),
|
||||
)
|
||||
cdm = FakeCdm({KID: KEY_A, OTHER_KID: KEY_B})
|
||||
assert track.drm is not None
|
||||
|
||||
track.drm[0].get_content_keys(cdm=cdm, certificate=lambda **_: None, licence=lambda **_: "<License>x</License>")
|
||||
|
||||
assert cdm.challenged == [[KID], [OTHER_KID]]
|
||||
assert track.drm[0].content_keys == {KID: KEY_A, OTHER_KID: KEY_B}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("drm_class", [PlayReady, Widevine])
|
||||
def test_a_rotation_licenses_the_second_key_id_when_the_run_holds_the_first(
|
||||
tmp_path: Path, monkeypatch: Any, drm_class: type[PlayReady | Widevine]
|
||||
) -> None:
|
||||
track = hls_video(tmp_path, ROTATION)
|
||||
keys = resolver()
|
||||
monkeypatch.setattr(ContentKeyResolver, "LICENSE_KEY_CACHE", {KID: KEY_A})
|
||||
challenges: list[list[UUID]] = []
|
||||
|
||||
def get_content_keys(self: PlayReady | Widevine, **_: Any) -> None:
|
||||
challenges.append(list(self.kids))
|
||||
self.content_keys.update({KID: KEY_A, OTHER_KID: KEY_B})
|
||||
|
||||
monkeypatch.setattr(drm_class, "get_content_keys", get_content_keys)
|
||||
|
||||
download(
|
||||
track,
|
||||
cdm_type_stub(drm_class.__name__.lower()),
|
||||
keys.licence_for(track, None, key_table()),
|
||||
licence_only=True,
|
||||
session=rotation_server(),
|
||||
)
|
||||
|
||||
assert challenges == [[KID, OTHER_KID]]
|
||||
assert track.drm is not None and track.drm[0].content_keys == {KID: KEY_A, OTHER_KID: KEY_B}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("drm_class", [PlayReady, Widevine])
|
||||
def test_a_rotation_with_no_content_key_for_a_later_key_id_stops_before_a_segment(
|
||||
tmp_path: Path, drm_class: type[PlayReady | Widevine]
|
||||
) -> None:
|
||||
def licence(drm: Any, track_kid: UUID | None = None) -> None:
|
||||
drm.content_keys[KID] = KEY_A
|
||||
|
||||
with pytest.raises(drm_class.Exceptions.CEKNotFound, match=OTHER_KID.hex):
|
||||
download(
|
||||
hls_video(tmp_path, ROTATION), cdm_type_stub(drm_class.__name__.lower()), licence, session=rotation_server()
|
||||
)
|
||||
|
||||
|
||||
def test_the_server_names_every_key_id_of_a_rotation(tmp_path: Path, monkeypatch: Any) -> None:
|
||||
monkeypatch.setattr("unshackle.core.tracks.track.utf8_text", lambda response: ROTATION)
|
||||
track = hls_video(tmp_path, ROTATION)
|
||||
|
||||
assert track.load_drm_from_playlist(rotation_server(), bridge=True)
|
||||
|
||||
assert track.drm is not None
|
||||
assert [drm.kids for drm in track.drm] == [[KID, OTHER_KID], [KID, OTHER_KID]]
|
||||
for kid in (KID, OTHER_KID):
|
||||
require_track_pssh(track, drm_stub("playready", [kid.hex]).pssh_b64 or "", "playready")
|
||||
require_track_pssh(track, drm_stub("widevine", [KID.hex, OTHER_KID.hex]).pssh.dumps(), "widevine")
|
||||
|
||||
|
||||
@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]
|
||||
|
||||
@@ -307,16 +307,49 @@ def test_server_cdm_typeerror_inside_the_service_is_not_retried(drm_type: str, r
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def _proxy(service: Any, drm_type: str) -> Any:
|
||||
def _proxy(service: Any, drm_type: str, **relayed: Any) -> Any:
|
||||
return handlers.handle_proxy_license(
|
||||
service=service,
|
||||
title=SimpleNamespace(),
|
||||
track=SimpleNamespace(),
|
||||
challenge_b64=base64.b64encode(b"CHAL").decode(),
|
||||
drm_type=drm_type,
|
||||
**relayed,
|
||||
)
|
||||
|
||||
|
||||
WV_PSSH_B64 = wv_pssh_mod.PSSH.new(system_id=wv_pssh_mod.PSSH.SystemId.Widevine, key_ids=[KID]).dumps()
|
||||
RELAYED_PSSH = {"widevine": WV_PSSH_B64, "playready": PSSH_B64}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("drm_type", ["widevine", "playready"])
|
||||
def test_proxy_license_relayed_pssh_skips_a_service_that_does_not_declare_it(drm_type: str) -> None:
|
||||
service = ClassicService()
|
||||
_proxy(service, drm_type, pssh_b64=RELAYED_PSSH[drm_type])
|
||||
|
||||
assert set(service.calls[0]) == {"challenge", "title", "track"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("drm_type", ["widevine", "playready"])
|
||||
def test_proxy_license_drops_a_relayed_pssh_that_an_unreadable_signature_rejects(drm_type: str) -> None:
|
||||
service = ClassicService()
|
||||
method = getattr(service, f"get_{drm_type}_license")
|
||||
setattr(service, f"get_{drm_type}_license", lambda *a, **kw: method(*a, **kw))
|
||||
|
||||
assert _proxy(service, drm_type, pssh_b64=RELAYED_PSSH[drm_type]).status == 200
|
||||
assert len(service.calls) == 1
|
||||
|
||||
|
||||
def test_proxy_license_relayed_pssh_reaches_a_var_kwargs_service_as_on_the_local_path() -> None:
|
||||
widevine, playready = VarKwService(), VarKwService()
|
||||
_proxy(widevine, "widevine", pssh_b64=WV_PSSH_B64)
|
||||
_proxy(playready, "playready", pssh_b64=PSSH_B64)
|
||||
|
||||
assert widevine.calls[0]["pssh"].dumps() == WV_PSSH_B64
|
||||
assert playready.calls[0]["pssh_b64"] == PSSH_B64
|
||||
assert "pssh_b64" not in widevine.calls[0] and "pssh" not in playready.calls[0]
|
||||
|
||||
|
||||
# A PlayReady challenge is SOAP XML, and pyplayready returns it as str on the local path too.
|
||||
@pytest.mark.parametrize("drm_type, challenge", [("widevine", b"CHAL"), ("playready", "CHAL")])
|
||||
def test_proxy_license_classic_signature(drm_type: str, challenge: Any) -> None:
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""The challenge relay gives the server's licence callback the PSSH of the header the client licenses."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, cast
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.core.key_resolver import resolver
|
||||
from tests.core.test_playready_multi_header import _drm, _wrm_header
|
||||
from tests.remote.key_source import remote_session
|
||||
from tests.remote.sessions import session_entry
|
||||
from unshackle.core.api import handlers, server_keys
|
||||
from unshackle.core.drm import PlayReady
|
||||
from unshackle.core.manifests.hls import HLS
|
||||
from unshackle.core.remote_protocol import LicensingMode, Licensor
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
K1, K2 = UUID(int=0x11), UUID(int=0x22)
|
||||
|
||||
|
||||
def pr_kids(pssh_b64: str | None) -> list[UUID] | None:
|
||||
return PlayReady.from_pssh_b64(pssh_b64).kids if pssh_b64 else None
|
||||
|
||||
|
||||
class FakePlayReadyCdm:
|
||||
"""A CDM that licenses every KID of the header it makes the challenge for."""
|
||||
|
||||
def open(self) -> bytes:
|
||||
return b"s"
|
||||
|
||||
def close(self, sid: bytes) -> None:
|
||||
pass
|
||||
|
||||
def get_license_challenge(self, sid: bytes, header: Any) -> str:
|
||||
self.kids = PlayReady.header_kids(header)
|
||||
return "<Challenge/>"
|
||||
|
||||
def parse_license(self, sid: bytes, licence: str) -> None:
|
||||
pass
|
||||
|
||||
def get_keys(self, sid: bytes) -> list[Any]:
|
||||
return [SimpleNamespace(key_id=kid, key=bytes(16)) for kid in self.kids]
|
||||
|
||||
|
||||
class PsshService:
|
||||
"""EXAMPLE: licence callbacks that declare the PSSH argument of the local path."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[dict[str, Any]] = []
|
||||
|
||||
def get_playready_license(self, *, challenge: str, title: Any, track: Any, pssh_b64: str | None = None) -> str:
|
||||
self.calls.append({"challenge": challenge, "pssh_b64": pssh_b64})
|
||||
return "<License>x</License>"
|
||||
|
||||
def get_widevine_license(self, *, challenge: bytes, title: Any, track: Any, pssh: Any = None) -> bytes:
|
||||
self.calls.append({"challenge": challenge, "pssh": pssh})
|
||||
return b"LIC"
|
||||
|
||||
|
||||
def relay(
|
||||
monkeypatch: pytest.MonkeyPatch, drm: Callable[[], list[Any]], drm_system: str = "playready"
|
||||
) -> tuple[PsshService, list[Any], Any, Callable[..., Any]]:
|
||||
"""The server service, the wire PSSH list, the client track and the licence callable dl hands its DRM.
|
||||
|
||||
The client is a RemoteService whose HTTP hop calls the real server licence handler, and each track gets ``drm()``.
|
||||
"""
|
||||
service = PsshService()
|
||||
session = session_entry(
|
||||
service_tag="EXAMPLE",
|
||||
service_instance=service,
|
||||
tracks={"vid": SimpleNamespace(id="vid", drm=drm())},
|
||||
licensing=LicensingMode(Licensor.NO_DEVICE),
|
||||
)
|
||||
monkeypatch.setattr(handlers, "ensure_track_drm", lambda *a, **k: None)
|
||||
monkeypatch.setattr(server_keys, "find_title_for_track", lambda tid, s: SimpleNamespace())
|
||||
wire: list[Any] = []
|
||||
|
||||
def post(route: str, body: Any, **_: Any) -> Any:
|
||||
wire.append(body.get("pssh"))
|
||||
return json.loads(cast(bytes, handlers.license_response(body, session, "sess", None).body))
|
||||
|
||||
remote = remote_session(None, {})
|
||||
remote.client = cast(Any, SimpleNamespace(post=post))
|
||||
client_track = SimpleNamespace(id="vid", drm=drm())
|
||||
keys = resolver()
|
||||
keys.service = remote
|
||||
|
||||
def licence(**kw: Any) -> Any:
|
||||
return keys._service_licence(drm_system, title=SimpleNamespace(), track=client_track, **kw)
|
||||
|
||||
return service, wire, client_track, licence
|
||||
|
||||
|
||||
def license_all(drms: list[Any], licence: Callable[..., Any]) -> None:
|
||||
for drm in drms:
|
||||
drm.get_content_keys(FakePlayReadyCdm(), certificate=None, licence=licence)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kids, drm",
|
||||
[
|
||||
([K1], lambda: [HLS.bridge_stub("playready", [K1])]),
|
||||
([K1, K2], lambda: [HLS.bridge_stub("playready", [K1, K2])]),
|
||||
([K1, K2], lambda: [HLS.bridge_stub("playready", [K1]), HLS.bridge_stub("playready", [K2])]),
|
||||
],
|
||||
ids=["one-header", "two-headers-one-object", "two-headers-two-objects"],
|
||||
)
|
||||
def test_playready_relay_gives_each_challenge_the_pssh_of_its_header(
|
||||
monkeypatch: pytest.MonkeyPatch, kids: list[UUID], drm: Callable[[], list[Any]]
|
||||
) -> None:
|
||||
service, wire, client_track, licence = relay(monkeypatch, drm)
|
||||
|
||||
license_all(client_track.drm, licence)
|
||||
|
||||
assert [pr_kids(c["pssh_b64"]) for c in service.calls] == [[k] for k in kids]
|
||||
assert [pr_kids(p) for p in wire] == [[k] for k in kids]
|
||||
|
||||
|
||||
def test_widevine_relay_gives_the_callback_the_pssh(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
service, wire, client_track, licence = relay(monkeypatch, lambda: [HLS.bridge_stub("widevine", [K1])], "widevine")
|
||||
pssh = client_track.drm[0].pssh
|
||||
|
||||
licence(challenge=b"CHAL", pssh=pssh, session_id=b"s")
|
||||
|
||||
assert service.calls[0]["challenge"] == b"CHAL"
|
||||
assert service.calls[0]["pssh"].dumps() == pssh.dumps() == wire[0]
|
||||
|
||||
|
||||
def test_playready_relay_licenses_a_key_the_server_track_does_not_name(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
service, _, _, licence = relay(monkeypatch, lambda: [HLS.bridge_stub("playready", [K1])])
|
||||
|
||||
license_all([HLS.bridge_stub("playready", [K2])], licence)
|
||||
|
||||
assert [c["pssh_b64"] for c in service.calls] == [None]
|
||||
|
||||
|
||||
def test_playready_relay_licenses_a_header_without_a_kid(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
service, _, client_track, licence = relay(monkeypatch, lambda: [_drm(_wrm_header(K1), _wrm_header())])
|
||||
|
||||
license_all(client_track.drm, licence)
|
||||
|
||||
assert [pr_kids(c["pssh_b64"]) for c in service.calls] == [[K1], None]
|
||||
Reference in New Issue
Block a user