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:
@@ -637,7 +637,7 @@ current `title` and `track`:
|
||||
| `get_playready_license` | PlayReady | The license response. Defaults to delegating to `get_widevine_license`. |
|
||||
| `get_clearkey_license` | DASH `org.w3.clearkey` | The JWK Set (dict/JSON/bytes), or `None` to let the framework POST the challenge to the manifest's Laurl. |
|
||||
|
||||
A license callback can also declare optional keyword arguments. `get_widevine_license` can ask for `pssh` and `session_id`. `get_playready_license` can ask for `pssh_b64` and `session_id`. `session_id` is the open CDM session. A callback gets only the arguments that its signature declares.
|
||||
A license callback can also declare optional keyword arguments. `get_widevine_license` can ask for `pssh` and `session_id`. `get_playready_license` can ask for `pssh_b64` and `session_id`. `session_id` is the open CDM session. A callback gets only the arguments that its signature declares. When a `--remote` client licenses with its own CDM, the callback on the server gets `pssh` or `pssh_b64` for the header the client licenses, but no `session_id`.
|
||||
|
||||
```python
|
||||
def get_widevine_license(self, *, challenge: bytes, title, track):
|
||||
|
||||
@@ -1246,7 +1246,7 @@ A slow answer arrives as a [slow response](#slow-responses).
|
||||
| --- | --- |
|
||||
| `track_id` / `track_ids` | Single track, or a batch of tracks. |
|
||||
| `challenge` | Base64 CDM challenge (proxy mode). |
|
||||
| `pssh` | Base64 PSSH (server-CDM mode). |
|
||||
| `pssh` | Base64 PSSH. Server-CDM mode licenses this PSSH. Proxy mode gives it to the service licence callback as `pssh` (Widevine) or `pssh_b64` (PlayReady), the PSSH of the header the challenge is for. A proxy-mode PSSH that names a KID the track does not carry goes to no callback. |
|
||||
| `drm_type` | `widevine` (default) or `playready`. In server-CDM mode the server's `cdm` mapping for the service decides the DRM system and the response `drm_type` names the system that licensed. A mapping with a device for each system takes the system of the device the remote session loaded. With no mapping, the client's value decides when the track carries that system; else a system the track carries decides, PlayReady first. The tracks response `server_cdm_type` names the system the same order gives for the title's tracks. A track whose DRM is a whole-file cipher takes `clearkeyctr` with no `pssh`: the service on the server licenses it. |
|
||||
| `mode` | `proxy` (default) or `server_cdm`. |
|
||||
| `clear_tracks` (response) | Requested track ids that carry no DRM, so they have no keys. Absent when every requested track is encrypted. |
|
||||
|
||||
@@ -499,6 +499,14 @@ CDM with `drm_stub`, and sends the challenge to the licence callback of the serv
|
||||
the server reads the same key ID at the licence step, so it accepts the DRM object of the client. A
|
||||
licence that gives no content key stops the track before it downloads a segment.
|
||||
|
||||
unshackle reads one key ID from each init segment. So it licenses a playlist that changes its content key
|
||||
correctly only when each content key has its own init segment with a real `tenc` key ID, after an
|
||||
`EXT-X-DISCONTINUITY`. When the first key ID is real, the download also reads the `tenc` key ID of
|
||||
each other init segment of the encrypted segments, and licenses each real key ID in its own licence step. A
|
||||
PlayReady DRM object then has one header for each key ID, because the header of `drm_stub` holds
|
||||
one key ID. A key ID that gets no content key stops the track before it downloads a segment. An
|
||||
init segment that gives no real key ID does not count.
|
||||
|
||||
A service that must choose the DRM system itself, or one that knows the key ID, puts the DRM object
|
||||
on the track:
|
||||
|
||||
|
||||
@@ -80,7 +80,9 @@ appropriate one for each track.
|
||||
!!! note "HLS tracks with only a FairPlay key tag"
|
||||
unshackle has no FairPlay CDM. When each `EXT-X-KEY` of an fMP4 playlist is sample encryption
|
||||
for a DRM system that unshackle cannot license, such as FairPlay, unshackle reads the key ID from
|
||||
the init segment and asks for the licence with your PlayReady or Widevine device. This works
|
||||
the init segment and asks for the licence with your PlayReady or Widevine device. unshackle reads one
|
||||
key ID from each init segment. So it licenses a playlist that changes its content key correctly only
|
||||
when each content key has its own init segment with a real key ID, after an `EXT-X-DISCONTINUITY`. This works
|
||||
only when the licence server of the platform also issues that content key for that DRM system. MPEG-TS SAMPLE-AES stops with an error.
|
||||
Each key ID must name one content key: a playlist that encrypts two blocks with two content keys under
|
||||
one key ID gives wrong frames. A clear part under `METHOD=NONE` must have its own init segment, or the
|
||||
|
||||
@@ -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]
|
||||
@@ -97,7 +97,7 @@ from unshackle.core.tunnel import (
|
||||
is_public_ip,
|
||||
tunnel_proxy,
|
||||
)
|
||||
from unshackle.core.utilities import declared_kwargs
|
||||
from unshackle.core.utilities import call_licence, declared_kwargs
|
||||
from unshackle.core.utils.click_types import SEASON_RANGE, ContextData
|
||||
from unshackle.core.utils.hdr10plus import probed_tracks
|
||||
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text
|
||||
@@ -3561,8 +3561,13 @@ def handle_proxy_license(
|
||||
challenge_b64: str | None,
|
||||
drm_type: str,
|
||||
certificate: bool = False,
|
||||
pssh_b64: str | None = None,
|
||||
) -> web.Response:
|
||||
"""Forward a client CDM challenge to the service license endpoint, or to its certificate hook with ``certificate``."""
|
||||
"""Forward a client CDM challenge to the service license endpoint, or to its certificate hook with ``certificate``.
|
||||
|
||||
``pssh_b64`` is the PSSH of the header the challenge is for. It goes to the service as on the local path:
|
||||
``pssh`` (a Widevine PSSH) or ``pssh_b64`` (PlayReady), and ``call_licence`` drops it for a service that refuses it.
|
||||
"""
|
||||
import base64
|
||||
|
||||
if not challenge_b64:
|
||||
@@ -3589,18 +3594,21 @@ def handle_proxy_license(
|
||||
{"challenge": challenge_bytes, "title": title, "track": track},
|
||||
)
|
||||
)
|
||||
elif drm_type == "widevine":
|
||||
license_blob = service.get_widevine_license(
|
||||
**declared_kwargs(
|
||||
service.get_widevine_license, {"challenge": challenge_bytes, "title": title, "track": track}
|
||||
)
|
||||
)
|
||||
else:
|
||||
challenge_str = challenge_bytes.decode("utf-8", errors="replace")
|
||||
license_blob = service.get_playready_license(
|
||||
**declared_kwargs(
|
||||
service.get_playready_license, {"challenge": challenge_str, "title": title, "track": track}
|
||||
)
|
||||
challenge: bytes | str
|
||||
relayed: dict[str, Any]
|
||||
if drm_type == "widevine":
|
||||
from pywidevine.pssh import PSSH
|
||||
|
||||
licence, challenge = service.get_widevine_license, challenge_bytes
|
||||
relayed = {"pssh": PSSH(pssh_b64)} if pssh_b64 else {}
|
||||
else:
|
||||
licence, challenge = service.get_playready_license, challenge_bytes.decode("utf-8", errors="replace")
|
||||
relayed = {"pssh_b64": pssh_b64} if pssh_b64 else {}
|
||||
license_blob = call_licence(
|
||||
lambda **kw: licence(**declared_kwargs(licence, {"title": title, "track": track, **kw})),
|
||||
challenge,
|
||||
**relayed,
|
||||
)
|
||||
except APIError:
|
||||
raise
|
||||
@@ -3846,16 +3854,22 @@ def license_response(data: LicenseRequest, session: Any, session_id: str, reques
|
||||
return web.json_response(LicenseReply(keys=keys, vault_keys=list(key_sources), drm_type=server_drm_type))
|
||||
|
||||
if pssh_b64:
|
||||
try:
|
||||
server_keys.require_track_pssh(track, pssh_b64, drm_type)
|
||||
if drm_type == "playready":
|
||||
track.pr_pssh = pssh_b64
|
||||
except APIError as e:
|
||||
log.debug(f"Relaying track {track_log_label(track)} without the client PSSH: {e.message}")
|
||||
pssh_b64 = None
|
||||
|
||||
certificate = data.get("is_certificate") is True
|
||||
if licensing.server_device and not certificate:
|
||||
denied = server_keys.live_licence_refusal(session, track)
|
||||
if denied:
|
||||
raise denied
|
||||
return handle_proxy_license(service, title, track, challenge_b64, drm_type, certificate=certificate)
|
||||
return handle_proxy_license(
|
||||
service, title, track, challenge_b64, drm_type, certificate=certificate, pssh_b64=pssh_b64
|
||||
)
|
||||
|
||||
except APIError:
|
||||
raise
|
||||
|
||||
@@ -711,15 +711,19 @@ class HLS:
|
||||
|
||||
# Get session DRM as fallback but prefer media playlist keys for accurate KID matching
|
||||
session_drm = track.get_drm_for_cdm(cdm) if track.drm else None
|
||||
bridge_drm = bridge_kid = None
|
||||
bridge_drm = None
|
||||
bridge_kids: list[UUID] = []
|
||||
if session_drm is None and (system := cdm_system(cdm)):
|
||||
bridge_kid = HLS.get_bridge_kid(master, wanted_segments, track, session)
|
||||
bridge_drm = drm_stub(system, [bridge_kid.hex]) if bridge_kid else None
|
||||
if bridge_drm and bridge_kid:
|
||||
bridge_kids = HLS.get_bridge_kids(master, wanted_segments, track, session)
|
||||
bridge_drm = HLS.bridge_stub(system, bridge_kids) if bridge_kids else None
|
||||
if bridge_drm:
|
||||
HLS.drop_unsupported_keys(master)
|
||||
session_drm = bridge_drm
|
||||
track.drm = [bridge_drm]
|
||||
log.debug(f"{track.id}: licensing key ID {bridge_kid.hex} of its init segment as {bridge_drm.NAME}")
|
||||
log.debug(
|
||||
f"{track.id}: licensing key IDs {', '.join(kid.hex for kid in bridge_kids)} "
|
||||
f"of its init segments as {bridge_drm.NAME}"
|
||||
)
|
||||
elif isinstance(session_drm, (Widevine, PlayReady)) and HLS.drop_unsupported_keys(master):
|
||||
log.debug(f"{track.id}: its key tags name key systems unshackle cannot license, using the DRM of the track")
|
||||
|
||||
@@ -766,8 +770,9 @@ class HLS:
|
||||
initial_drm_licensed = True
|
||||
|
||||
if not initial_drm_licensed:
|
||||
for kid in bridge_kids or (None,):
|
||||
license_drm(
|
||||
track, session_drm, ctx, bridge_kid, probe=lambda: HLS.get_track_kid_from_init(master, track, session)
|
||||
track, session_drm, ctx, kid, probe=lambda: HLS.get_track_kid_from_init(master, track, session)
|
||||
)
|
||||
|
||||
if DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
@@ -783,8 +788,11 @@ class HLS:
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
return
|
||||
|
||||
if bridge_drm and bridge_kid and not bridge_drm.content_keys:
|
||||
raise bridge_drm.Exceptions.CEKNotFound(f"No content key for KID {bridge_kid.hex} of track {track.id}")
|
||||
if bridge_drm:
|
||||
content_keys = bridge_drm.content_keys
|
||||
missing = [k for k in bridge_kids[1:] if k not in content_keys] if content_keys else bridge_kids[:1]
|
||||
if missing:
|
||||
raise bridge_drm.Exceptions.CEKNotFound(f"No content key for KID {missing[0].hex} of track {track.id}")
|
||||
|
||||
# Downloaded segment files are named by post-filter index; map that back to the wanted
|
||||
# segment so the IV uses the absolute media sequence number, not the download index.
|
||||
@@ -1518,65 +1526,91 @@ class HLS:
|
||||
raise NotImplementedError(f"None of the key systems are supported: {', '.join(unsupported_systems)}")
|
||||
|
||||
@staticmethod
|
||||
def get_bridge_kid(
|
||||
def get_bridge_kids(
|
||||
manifest: M3U8, segments: list[Any], track: Track, session: Session | RnetSession
|
||||
) -> UUID | None:
|
||||
"""The real Key ID of the init segment of the first `segments` entry with an EXT-X-KEY unshackle cannot license.
|
||||
) -> list[UUID]:
|
||||
"""The real Key IDs of the init segments of the `segments` entries with an EXT-X-KEY unshackle cannot license.
|
||||
|
||||
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 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.
|
||||
A real first Key ID adds each other real tenc Key ID once, in playlist order. Empty 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. The pssh boxes count only in a one-key playlist, as `get_stitched_kids` reads them:
|
||||
an all-zero tenc takes any content key.
|
||||
"""
|
||||
keyed = [span for span in key_spans(manifest, segments) if span.init_section and HLS.encrypts(span.keys)]
|
||||
if not keyed or not HLS.only_unsupported_keys(manifest):
|
||||
return None
|
||||
return []
|
||||
one_key = len({key.uri for key in manifest.keys if key and key.method != "NONE"}) == 1
|
||||
if any(b.init_section != a.init_section and not b.discontinuity for a, b in pairwise(segments)):
|
||||
return None
|
||||
return []
|
||||
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)
|
||||
kids = HLS.get_stitched_kids(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
|
||||
if kid is None or kid in PLACEHOLDER_KIDS:
|
||||
return []
|
||||
kids = [kid, *HLS.get_later_kids(manifest, init_sections[1:], track, session)]
|
||||
return [] if not kids or kids[0] in PLACEHOLDER_KIDS else list(dict.fromkeys(kids))
|
||||
|
||||
@staticmethod
|
||||
def get_stitched_kid(
|
||||
def get_stitched_kids(
|
||||
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.
|
||||
) -> list[UUID]:
|
||||
"""The real tenc Key ID of the first encrypted init segment and `get_later_kids` of the rest, else one Key ID of all.
|
||||
|
||||
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.
|
||||
For the one Key ID, 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 empty.
|
||||
"""
|
||||
found: UUID | None = None
|
||||
for init_section in init_sections:
|
||||
for i, init_section in enumerate(init_sections):
|
||||
init_data = HLS.probe_init_section(manifest, session, init_section)
|
||||
if not init_data:
|
||||
return None
|
||||
return []
|
||||
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
|
||||
elif found is None:
|
||||
return [kid, *HLS.get_later_kids(manifest, init_sections[i + 1 :], track, session)]
|
||||
except Exception as e:
|
||||
logging.getLogger("HLS").debug(f"Init map key-id probe failed for {init_section.uri}: {e!r}")
|
||||
return None
|
||||
return []
|
||||
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
|
||||
return []
|
||||
found = kid
|
||||
return found
|
||||
return [found] if found else []
|
||||
|
||||
@staticmethod
|
||||
def get_later_kids(
|
||||
manifest: M3U8,
|
||||
init_sections: list[m3u8.model.InitializationSection],
|
||||
track: Track,
|
||||
session: Session | RnetSession,
|
||||
) -> list[UUID]:
|
||||
"""The real tenc Key IDs of the init segments of a playlist that changes its key, without one that gives none."""
|
||||
kids = (HLS.get_track_kid_from_init(manifest, track, session, init_section) for init_section in init_sections)
|
||||
return [kid for kid in kids if kid and kid not in PLACEHOLDER_KIDS]
|
||||
|
||||
@staticmethod
|
||||
def bridge_stub(system: str, kids: list[UUID]) -> Widevine | PlayReady:
|
||||
"""The `drm_stub` of `system` for `kids`: one Widevine header that names each, or a PlayReady header for each.
|
||||
|
||||
A PlayReady stub header holds one KID, so one that named several would license only the first content key.
|
||||
"""
|
||||
if system != "playready":
|
||||
return drm_stub(system, [kid.hex for kid in kids])
|
||||
drm, *others = (cast(PlayReady, drm_stub(system, [kid.hex])) for kid in kids)
|
||||
drm.absorb(*others)
|
||||
return drm
|
||||
|
||||
@staticmethod
|
||||
def only_unsupported_keys(manifest: M3U8) -> bool:
|
||||
|
||||
@@ -103,6 +103,8 @@ from unshackle.core.utils.service_params import service_options
|
||||
from unshackle.core.wire import apply_tracks_reply, build_chapters, build_music, build_title
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pywidevine.pssh import PSSH
|
||||
|
||||
from unshackle.core.remote_channel import Channel
|
||||
from unshackle.core.remote_lifetime import RemoteSessionLifetime
|
||||
|
||||
@@ -1731,11 +1733,15 @@ class RemoteService(TitleSource):
|
||||
with malformed_answer("chapters"):
|
||||
return build_chapters(raw)
|
||||
|
||||
def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
|
||||
return self.proxy_license(challenge, track, "widevine")
|
||||
def get_widevine_license(
|
||||
self, *, challenge: bytes, title: Title_T, track: AnyTrack, pssh: PSSH | None = None
|
||||
) -> bytes | str | None:
|
||||
return self.proxy_license(challenge, track, "widevine", pssh.dumps() if pssh else None)
|
||||
|
||||
def get_playready_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
|
||||
return self.proxy_license(challenge, track, "playready")
|
||||
def get_playready_license(
|
||||
self, *, challenge: bytes, title: Title_T, track: AnyTrack, pssh_b64: str | None = None
|
||||
) -> bytes | str | None:
|
||||
return self.proxy_license(challenge, track, "playready", pssh_b64)
|
||||
|
||||
def get_widevine_service_certificate(
|
||||
self,
|
||||
@@ -1859,12 +1865,17 @@ class RemoteService(TitleSource):
|
||||
raise click.ClickException(f"The server sent no URL for track {track.id}")
|
||||
return str(url)
|
||||
|
||||
def proxy_license(self, challenge: bytes | str, track: AnyTrack, drm_type: str) -> bytes:
|
||||
"""Relay a licence challenge to the server. A failed relay raises ClickException, so dl's licence fallbacks see it."""
|
||||
def proxy_license(
|
||||
self, challenge: bytes | str, track: AnyTrack, drm_type: str, pssh_b64: str | None = None
|
||||
) -> bytes:
|
||||
"""Relay a licence challenge and the PSSH of its header, by default the track's first, to the server.
|
||||
|
||||
A failed relay raises ClickException, so dl's licence fallbacks see it.
|
||||
"""
|
||||
if isinstance(challenge, str):
|
||||
challenge = challenge.encode("utf-8")
|
||||
|
||||
pssh_b64 = track_pssh(track, drm_type)
|
||||
pssh_b64 = pssh_b64 or track_pssh(track, drm_type)
|
||||
|
||||
payload = LicenseRequest(challenge=base64.b64encode(challenge).decode("ascii"), drm_type=drm_type)
|
||||
if pssh_b64:
|
||||
|
||||
@@ -29,7 +29,7 @@ from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY,
|
||||
from unshackle.core.downloaders.requests import requests
|
||||
from unshackle.core.drm import DRM_T, PlayReady, Widevine
|
||||
from unshackle.core.drm.cbcs import SampleDecrypter
|
||||
from unshackle.core.drm.cenc import cenc_key, drm_stub, init_kid
|
||||
from unshackle.core.drm.cenc import cenc_key, init_kid
|
||||
from unshackle.core.drm.verify import (
|
||||
children,
|
||||
find_child_box,
|
||||
@@ -998,7 +998,7 @@ class Track:
|
||||
"""Load the Widevine and PlayReady DRM of the EXT-X-KEY and EXT-X-SESSION-KEY tags of this track's playlist.
|
||||
|
||||
It skips a tag that gives no DRM, and raises ValueError when the fetch fails or when every such tag fails.
|
||||
With ``bridge`` it builds both stubs for the key ID that ``HLS.get_bridge_kid`` finds when no tag gives a DRM.
|
||||
With ``bridge`` it builds both stubs for the key IDs that ``HLS.get_bridge_kids`` finds when no tag gives a DRM.
|
||||
"""
|
||||
if self.drm:
|
||||
self.needs_drm_loading = False
|
||||
@@ -1032,8 +1032,8 @@ class Track:
|
||||
segments = [
|
||||
s for s in playlist.segments if not (callable(self.OnSegmentFilter) and self.OnSegmentFilter(s))
|
||||
]
|
||||
if kid := HLS.get_bridge_kid(playlist, segments, self, session):
|
||||
drm_list = [drm_stub(system, [kid.hex]) for system in SYSTEMS]
|
||||
if kids := HLS.get_bridge_kids(playlist, segments, self, session):
|
||||
drm_list = [HLS.bridge_stub(system, kids) for system in SYSTEMS]
|
||||
if drm_list:
|
||||
self.drm = drm_list
|
||||
self.needs_drm_loading = False
|
||||
|
||||
Reference in New Issue
Block a user