fix(dash): license a track whose only key system is the W3C common PSSH as ClearKey

This commit is contained in:
imSp4rky
2026-11-28 14:29:36 -07:00
parent b5b34cea02
commit 5f675bd5ff
7 changed files with 222 additions and 60 deletions
+70 -5
View File
@@ -3,6 +3,7 @@
Covers the three seams of the native ClearKey flow:
- ``DASH.get_drm`` emitting a ``ClearKeyCENC`` from a clearkey ContentProtection
element (KID from own attrs or sibling mp4protection, Laurl namespace variants)
- ``DASH.get_common_clearkey`` reading a W3C common PSSH ContentProtection
- ``ClearKeyCENC.get_content_keys`` building the W3C JSON license request and
parsing the JWK Set response (dict/str/bytes, unpadded base64url)
- ``to_dict`` / ``drm_from_dict`` round-trip for the --export/import path
@@ -19,16 +20,21 @@ import pytest
# lxml.etree: XML parser used to build ContentProtection fixtures for DASH.get_drm
from lxml import etree
from pymp4.parser import Box
from pywidevine.cdm import Cdm as WidevineCdm
from unshackle.core.drm.cenc import COMMON_ID
from unshackle.core.drm.clearkey_cenc import ClearKeyCENC
from unshackle.core.manifests.dash import DASH
from unshackle.core.wire import drm_from_dict
KID = UUID("9eb4050d-e44b-4802-932e-27d75083e266")
OTHER_KID = UUID("2c2d0a35-8f2a-4b1d-9c6e-5a7b8c9d0e1f")
KEY = bytes.fromhex("ccd0064c43f7e9fcbaa9b12af3fd1f40")
LAURL = "https://license.example.test/clearkey"
CLEARKEY_URN = "urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e"
COMMON_URN = "urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b"
CENC_NS = "urn:mpeg:cenc:2013"
@@ -47,6 +53,13 @@ def protection(xml: str) -> etree._Element:
return etree.fromstring(xml.encode("utf8"))
def mp4protection(kid: str) -> etree._Element:
return protection(
f'<ContentProtection xmlns:cenc="{CENC_NS}" '
f'schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc" cenc:default_KID="{kid}"/>'
)
class StubLicence:
"""Callable license stub that records the challenge it was given."""
@@ -122,12 +135,8 @@ def test_get_drm_clearkey_laurl_variants(laurl_xml: str) -> None:
def test_get_drm_clearkey_kid_from_sibling_mp4protection() -> None:
# Canonical DASH-IF shape: default_KID on the mp4protection element only.
clearkey = protection(f'<ContentProtection schemeIdUri="{CLEARKEY_URN}" value="ClearKey1.0"/>')
mp4protection = protection(
f'<ContentProtection xmlns:cenc="{CENC_NS}" '
f'schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc" cenc:default_KID="{KID}"/>'
)
drm = DASH.get_drm([mp4protection, clearkey])
drm = DASH.get_drm([mp4protection(str(KID)), clearkey])
assert len(drm) == 1
assert isinstance(drm[0], ClearKeyCENC)
@@ -140,6 +149,62 @@ def test_get_drm_clearkey_without_any_kid_is_skipped() -> None:
assert DASH.get_drm([elem]) == []
def common_pssh(*kids: UUID, system_id: UUID = COMMON_ID, version: int = 1) -> str:
box = Box.build(
dict(type=b"pssh", version=version, flags=0, system_ID=system_id, key_IDs=list(kids), init_data=b"")
)
return base64.b64encode(box).decode("ascii")
def common_protection(pssh_b64: str, attrs: str = "") -> etree._Element:
return protection(
f'<ContentProtection xmlns:cenc="{CENC_NS}" schemeIdUri="{COMMON_URN}" {attrs}>'
f"<cenc:pssh>{pssh_b64}</cenc:pssh></ContentProtection>"
)
@pytest.mark.parametrize(
("sibling_kid", "pssh_b64"),
[
(str(KID), common_pssh(OTHER_KID)),
(str(KID), common_pssh(version=0)),
(base64.b64encode(KID.bytes).decode("ascii"), common_pssh()),
],
ids=["over-the-box-kid", "v0-box", "base64-kid"],
)
def test_common_clearkey_takes_the_sibling_default_kid(sibling_kid: str, pssh_b64: str) -> None:
clearkey = DASH.get_common_clearkey([mp4protection(sibling_kid), common_protection(pssh_b64)])
assert clearkey is not None
assert clearkey.kids == [KID]
def test_common_clearkey_without_default_kid_takes_the_box_kids() -> None:
clearkey = DASH.get_common_clearkey([common_protection(common_pssh(KID, UUID(int=0), OTHER_KID))])
assert clearkey is not None
assert clearkey.kids == [KID, OTHER_KID]
@pytest.mark.parametrize(
"pssh_b64",
[
common_pssh(version=0),
common_pssh(UUID(int=0)),
common_pssh(KID, system_id=WidevineCdm.uuid),
"not base64!",
"",
],
ids=["v0-box", "placeholder-kid", "other-system", "garbage", "empty"],
)
def test_common_clearkey_with_no_kid_is_none(pssh_b64: str) -> None:
assert DASH.get_common_clearkey([common_protection(pssh_b64)]) is None
def test_get_drm_leaves_a_common_pssh_to_the_caller() -> None:
assert DASH.get_drm([mp4protection(str(KID)), common_protection(common_pssh(KID))]) == []
@pytest.mark.parametrize(
"shape",
["dict", "str", "bytes"],
@@ -10,11 +10,15 @@ decrypt) and asserts the ClearKeyCENC drm is licensed.
from __future__ import annotations
import base64
from functools import partial
from typing import Any
from uuid import UUID
from pywidevine.pssh import PSSH
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY
from unshackle.core.drm import Widevine
from unshackle.core.drm.clearkey_cenc import ClearKeyCENC
from unshackle.core.manifests.dash import DASH
from unshackle.core.tracks.track import DownloadContext
@@ -101,3 +105,45 @@ def test_download_track_keeps_service_drm_when_manifest_has_none(tmp_path, monke
assert track.drm == service_drm
assert len(licence.calls) == 1
COMMON_MPD = MPD.replace(
MPD[MPD.index("<ContentProtection") : MPD.index("</ContentProtection>") + len("</ContentProtection>")],
f'<ContentProtection schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc" cenc:default_KID="{KID}"/>'
'<ContentProtection schemeIdUri="urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b"/>',
)
def with_init(monkeypatch: Any, init_data: bytes | None) -> None:
"""Make the period give ``init_data`` as its init segment, offline."""
segments = DASH.get_period_segments
def fake(*args: Any, **kwargs: Any) -> Any:
_, *rest = segments(*args, **kwargs)
return (init_data, *rest)
monkeypatch.setattr(DASH, "get_period_segments", staticmethod(fake))
def test_download_track_licenses_a_common_pssh_track_as_clearkey(tmp_path, monkeypatch) -> None:
track = DASH.from_text(COMMON_MPD, MANIFEST_URL).to_tracks().videos[0]
monkeypatch.setattr(track, "get_key_id", lambda *args, **kwargs: KID)
assert track.drm is None
licence = licence_only(track, tmp_path)
assert len(licence.calls) == 1
drm, _ = licence.calls[0]
assert isinstance(drm, ClearKeyCENC)
assert drm.kids == [KID]
def test_download_track_prefers_the_init_segment_pssh_over_a_common_pssh(tmp_path, monkeypatch) -> None:
track = DASH.from_text(COMMON_MPD, MANIFEST_URL).to_tracks().videos[0]
monkeypatch.setattr(track, "get_key_id", lambda *args, **kwargs: KID)
with_init(monkeypatch, base64.b64decode(PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID]).dumps()))
licence = licence_only(track, tmp_path)
assert [type(d) for d in track.drm] == [Widevine]
assert isinstance(licence.calls[0][0], Widevine)
+17
View File
@@ -7,9 +7,11 @@ from collections import Counter
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock
from uuid import UUID
import pytest
from unshackle.core.drm import ClearKeyCENC
from unshackle.core.manifests import DASH, HLS, ISM
from unshackle.core.tracks import Audio, Tracks, Video
from unshackle.core.utils.xml import load_xml
@@ -104,3 +106,18 @@ def test_dash_segments_and_drm_resolve_offline(entry: dict[str, Any]) -> None:
continue
assert segments, track
assert all(url.startswith(("http://", "https://")) for url, _ in segments), track
def test_common_pssh_manifest_gives_each_track_its_clearkey() -> None:
"""A manifest whose only key system is the W3C common PSSH gives each audio and video track its ClearKey KID."""
entry = next(e for e in INDEX if e["file"].endswith("clearkey-server-1061a743.mpd"))
tracks = parse(entry)
for track in [*tracks.videos, *tracks.audio]:
dash = track.data["dash"]
protections = dash["representation"].findall("ContentProtection") + dash["adaptation_set"].findall(
"ContentProtection"
)
assert DASH.get_drm(protections) == []
clearkey = DASH.get_common_clearkey(protections)
assert isinstance(clearkey, ClearKeyCENC)
assert clearkey.kids == [UUID("feedf00d-eede-adbe-eff0-baadf00dd00d")]