refactor(drm): move track drm discovery into core and merge the drifted pssh and hls playlist readers

This commit is contained in:
imSp4rky
2026-11-26 13:40:06 -07:00
parent 136e9fc84d
commit 3c90346ae4
18 changed files with 260 additions and 206 deletions
+44
View File
@@ -184,6 +184,50 @@ def test_load_drm_from_playlist_takes_the_init_kid_when_the_tag_and_pssh_have_no
assert [drm.kids for drm in track.drm] == [[TRACK_KID]]
def kid_pssh(kid: UUID) -> str:
return str(PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[kid]).dumps())
def test_load_drm_from_playlist_reads_the_session_keys_and_skips_a_bad_key() -> None:
bad = KEY_LINE.format(pssh="AAAA")
session = KEY_LINE.format(pssh=kid_pssh(TRACK_KID)).replace("#EXT-X-KEY", "#EXT-X-SESSION-KEY")
track = playlist_track(f"#EXTM3U\n{session}\n{bad}\n#EXTINF:6.0,\na.m4s\n#EXT-X-ENDLIST\n")
assert track.load_drm_from_playlist() is True
assert track.drm is not None
assert [drm.kids for drm in track.drm] == [[TRACK_KID]]
assert track.needs_drm_loading is False
def test_load_drm_from_playlist_keeps_every_key_once() -> None:
line = KEY_LINE.format(pssh=kid_pssh(TRACK_KID))
other = KEY_LINE.format(pssh=kid_pssh(OTHER_KID))
iso = f'#EXT-X-KEY:METHOD=ISO-23001-7,URI="data:text/plain;base64,{base64.b64encode(OTHER_KID.bytes).decode()}"'
session = line.replace("#EXT-X-KEY", "#EXT-X-SESSION-KEY")
track = playlist_track(
f"#EXTM3U\n{session}\n{line}\n#EXTINF:6.0,\na.m4s\n{other}\n#EXTINF:6.0,\nb.m4s\n{iso}\n#EXTINF:6.0,\nc.m4s\n"
)
assert track.load_drm_from_playlist() is True
assert track.drm is not None
assert [drm.kids for drm in track.drm] == [[TRACK_KID], [OTHER_KID], [OTHER_KID]]
def test_load_drm_from_playlist_raises_when_every_key_fails() -> None:
track = playlist_track(f"#EXTM3U\n{KEY_LINE.format(pssh='AAAA')}\n#EXTINF:6.0,\na.m4s\n#EXT-X-ENDLIST\n")
with pytest.raises(ValueError, match="Failed to load DRM from playlist"):
track.load_drm_from_playlist()
def test_load_drm_from_playlist_uses_the_given_session_when_the_track_has_none() -> None:
track = playlist_track(f"#EXTM3U\n{KEY_LINE.format(pssh=kid_pssh(TRACK_KID))}\n#EXTINF:6.0,\na.m4s\n")
given, track.session = track.session, None
assert track.load_drm_from_playlist(given) is True
assert track.drm is not None
def test_from_track_reads_the_playlist_pssh_and_the_init_kid() -> None:
pssh_b64 = base64.b64encode(playready_box(OTHER_KID)).decode()
line = (
@@ -14,9 +14,9 @@ import pytest
from pywidevine.pssh import PSSH as WvPSSH
from tests.core.test_hls_kid_from_init import NO_KID_PSSH
from unshackle.core.api import handlers
from unshackle.core.drm import Widevine
from unshackle.core.tracks import Track
from unshackle.core.drm.discovery import ensure_track_drm, track_pssh
from unshackle.core.tracks import Track, Video
pytestmark = pytest.mark.unit
@@ -40,32 +40,45 @@ def _media_playlist(pssh: str | None = None) -> str:
)
def hls_track() -> Video:
track = Video.__new__(Video)
track.id = "vid"
track.url = "https://cdn.example.invalid/media.m3u8"
track.descriptor = Track.Descriptor.HLS
track.data = {}
track.drm = None
track.session = None
return track
def test_hls_descriptor_alone_reaches_the_media_playlist_keys():
session = SimpleNamespace(get=lambda url: SimpleNamespace(text=_media_playlist()))
track = SimpleNamespace(
id="vid", url="https://cdn.example.invalid/media.m3u8", descriptor=Track.Descriptor.HLS, data={}, drm=None
)
track = hls_track()
handlers.ensure_track_drm(track, session)
ensure_track_drm(track, session)
assert track.drm and isinstance(track.drm[0], Widevine), "media playlist DRM not read"
assert track.drm[0].kids == [KID]
assert base64.b64decode(handlers.extract_pssh_from_track(track, "widevine"))
assert base64.b64decode(track_pssh(track, "widevine"))
def test_key_without_a_kid_takes_it_from_the_init_segment():
"""A PSSH that holds a content id and no Key ID is DRM, and the server must not call the track clear."""
response = SimpleNamespace(text=_media_playlist(NO_KID_PSSH), ok=True, content=b"init")
session = SimpleNamespace(get=lambda url, headers=None: response)
track = SimpleNamespace(
id="vid",
url="https://cdn.example.invalid/media.m3u8",
descriptor=Track.Descriptor.HLS,
data={},
drm=None,
get_key_id=lambda init: KID,
)
track = hls_track()
track.get_key_id = lambda init: KID # type: ignore[method-assign]
handlers.ensure_track_drm(track, session)
ensure_track_drm(track, session)
assert track.drm and track.drm[0].kids == [KID]
def test_a_playlist_whose_keys_all_fail_leaves_the_track_without_drm():
"""The server logs and goes on where dl raises."""
session = SimpleNamespace(get=lambda url: SimpleNamespace(text=_media_playlist("AAAA")))
track = hls_track()
ensure_track_drm(track, session)
assert not track.drm
+21 -8
View File
@@ -1,4 +1,4 @@
"""extract_pssh_from_track must answer for the requested DRM system only.
"""track_pssh must answer for the requested DRM system only.
A loose match made the batch candidate loop a no-op: the first candidate always won, so the
loop licensed a PlayReady-only track as Widevine by accident. A Widevine device can still
@@ -12,13 +12,14 @@ import pytest
from tests.remote.sessions import session_entry
from unshackle.core.api import handlers
from unshackle.core.drm.discovery import track_pssh
pytestmark = pytest.mark.unit
class _WV:
def __init__(self, b64):
self._pssh = SimpleNamespace(dumps=lambda: b64)
self.pssh = SimpleNamespace(dumps=lambda: b64)
_WV.__name__ = "Widevine"
@@ -26,7 +27,7 @@ _WV.__name__ = "Widevine"
class _PR:
def __init__(self, b64):
self.data = {"pssh_b64": b64}
self.pssh_b64 = b64
_PR.__name__ = "PlayReady"
@@ -34,13 +35,25 @@ _PR.__name__ = "PlayReady"
def test_extractor_is_type_strict():
track = SimpleNamespace(drm=[_PR("pr")])
assert handlers.extract_pssh_from_track(track, "playready") == "pr"
assert handlers.extract_pssh_from_track(track, "widevine") is None
assert track_pssh(track, "playready") == "pr"
assert track_pssh(track, "widevine") is None
track = SimpleNamespace(drm=[_WV("wv"), _PR("pr")])
assert handlers.extract_pssh_from_track(track, "widevine") == "wv"
assert handlers.extract_pssh_from_track(track, "playready") == "pr"
assert handlers.extract_pssh_from_track(SimpleNamespace(drm=None), "widevine") is None
assert track_pssh(track, "widevine") == "wv"
assert track_pssh(track, "playready") == "pr"
assert track_pssh(SimpleNamespace(drm=None), "widevine") is None
def test_a_playready_header_without_a_pssh_is_skipped():
track = SimpleNamespace(drm=[_PR(None), _PR("pr")])
assert track_pssh(track, "playready") == "pr"
assert track_pssh(SimpleNamespace(drm=[_PR(None)]), "playready") is None
def test_the_given_drm_goes_before_the_track_drm():
track = SimpleNamespace(drm=[_WV("track")])
assert track_pssh(track, "widevine", _WV("given")) == "given"
assert track_pssh(track, "widevine", _PR("pr")) == "track"
async def _run_batch(monkeypatch, tracks, cdm_type, calls):
@@ -20,7 +20,7 @@ KID = UUID("161219ec3df64e0eadbb3827c0ccc46d")
class _PlayReady:
def __init__(self):
self.data = {"pssh_b64": "PR"}
self.pssh_b64 = "PR"
self.content_keys: dict = {}
@@ -138,7 +138,7 @@ async def test_no_pssh_tells_the_client_why(env, monkeypatch):
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "playready")
monkeypatch.setattr(handlers, "drm_preference_name", lambda track: None)
monkeypatch.setattr(handlers, "fetch_init_segment", lambda track, sess: None)
monkeypatch.setattr(handlers, "extract_pssh_from_track", lambda track, drm: None)
monkeypatch.setattr(handlers, "track_pssh", lambda track, drm: None)
await handlers.session_license_handler(
{"mode": "server_cdm", "track_ids": ["vid"], "drm_type": "playready"}, "sess", None
@@ -1,7 +1,7 @@
"""The server CDM must license every WRM header a track carries, not only the first.
A track can hold one `PlayReady` object per header: `ISM` shares a Protection list, `HLS`
emits one per `EXT-X-KEY`. `extract_pssh_from_track` returns the first PSSH only, so the
emits one per `EXT-X-KEY`. `track_pssh` returns the first PSSH only, so the
server folds in the siblings. Without that it returns fewer content keys than a local CDM.
"""
@@ -103,7 +103,7 @@ async def test_server_does_not_flag_a_pair_its_cdm_licensed(session):
class _WV:
def __init__(self, b64, kids):
self._pssh = SimpleNamespace(dumps=lambda: b64)
self.pssh = SimpleNamespace(dumps=lambda: b64)
self.kids = kids
@@ -354,7 +354,7 @@ CAP_DETAILS = {"reason": "server_cdm_max_height", "max_height": 1080}
class _PSSHDrm:
def __init__(self, b64, kids):
self._pssh = SimpleNamespace(dumps=lambda: b64)
self.pssh = SimpleNamespace(dumps=lambda: b64)
self.kids = kids
@@ -147,7 +147,7 @@ async def test_batch_shares_full_bundle_per_pssh(monkeypatch):
monkeypatch.setattr(handlers, "detect_cdm_type_for_service", lambda tag, cfg: "playready")
monkeypatch.setattr(handlers, "resolve_device_name", lambda *a, **k: "dev")
monkeypatch.setattr(handlers, "drm_preference_name", lambda track: None)
monkeypatch.setattr(handlers, "extract_pssh_from_track", lambda track, drm: track_pssh[track.id])
monkeypatch.setattr(handlers, "track_pssh", lambda track, drm: track_pssh[track.id])
monkeypatch.setattr(handlers, "handle_single_server_cdm", fake_single)
monkeypatch.setattr(handlers.config, "serve", {"users": {}}, raising=False)
@@ -57,7 +57,7 @@ class _FakePlayReady:
self.content_keys = {KID: "key_pr"}
# extract_pssh_from_track matches on class name, so name the fakes after the DRM classes
# track_pssh matches on class name, so name the fakes after the DRM classes
_FakePlayReady.__name__ = "PlayReady"
_FakeWidevine.__name__ = "Widevine"
+1 -1
View File
@@ -246,7 +246,7 @@ def test_server_login_strips_nested_and_unlisted_secrets():
def test_track_own_pssh_passes_without_kids(monkeypatch):
from unshackle.core.api import handlers
monkeypatch.setattr(handlers, "extract_pssh_from_track", lambda track, drm_type: "OWN")
monkeypatch.setattr(handlers, "track_pssh", lambda track, drm_type: "OWN")
monkeypatch.setattr(handlers, "pssh_kids", lambda pssh, drm_type: set())
handlers.require_track_pssh(SimpleNamespace(id="t", drm=[]), "OWN", "widevine")
with pytest.raises(APIError):