feat(drm): license a plugin DRM at the licence step and over --remote with the client's plugin device

This commit is contained in:
imSp4rky
2026-12-03 15:51:42 -07:00
parent f1f91a7d5c
commit 0536056ed6
24 changed files with 803 additions and 136 deletions
+109 -27
View File
@@ -1,7 +1,9 @@
"""A plugin DRM HLS track over --remote: the server licenses with the DRM its service built, the client decrypts it.
"""A plugin DRM HLS track over --remote: the licence runs at the licence step, on the server or on the client.
The service builds the DRM on the server; only its KIDs, label and display id cross with the track list, and the
content key comes through the licence route. The client decrypts each segment with its own copy of the plugin.
The service records only the plugin data (a ticket) on the DRM; its KIDs, label, display id and the data the plugin
lets a peer carry cross with the track list. The server licenses with its own plugin device under the Licensing mode
and the Licence cap, as for a CDM track; a client-device session, --cdm-only and a refused track license with the
client's own plugin device. The client decrypts each segment with its own copy of the plugin.
"""
from __future__ import annotations
@@ -18,13 +20,14 @@ import pytest
import requests
from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
from tests.drm_plugins import FINISHED, xor
from tests.drm_plugins import FINISHED, ExampleDevice, xor
from tests.remote.key_source import one_title, remote_session
from tests.remote.sessions import session_entry
from unshackle.core import plugins
from unshackle.core.api import handlers, server_keys
from unshackle.core.api.errors import APIError
from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.cdm.detect import cdm_type_stub
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import CustomDRM
from unshackle.core.manifests.hls import HLS
@@ -51,45 +54,67 @@ def cancel_flag() -> Iterator[None]:
DOWNLOAD_CANCELLED.clear()
@pytest.fixture
def device(tmp_path: Path) -> ExampleDevice:
"""An EXAMPLE device whose licence gives KEY."""
path = tmp_path / "EXAMPLE_DEVICE.exd"
path.write_bytes(bytes.fromhex(KEY))
return ExampleDevice(path)
@pytest.fixture
def server_track(example_plugins: None) -> Video:
"""The track the service built on the server: its plugin DRM holds the content key and a server-only ticket."""
drm = CustomDRM("example", kids=[KID], display_id="EXAMPLE-1", data={"ticket": "EXAMPLE-TICKET"})
drm.content_keys[KID] = KEY
"""The track the service built on the server: its plugin DRM holds the ticket and no content key."""
drm = CustomDRM("example", display_id="EXAMPLE-1", data={"ticket": KID.hex})
track = Video(
id_="vid",
url="https://example.test/seg0.ts",
language="en",
descriptor=Track.Descriptor.HLS,
codec=Video.Codec.HEVC,
height=2160,
drm=[drm],
)
track.data["hls"] = {"playlist_text": PLAYLIST}
return track
def server_of(track: Video, licensor: Licensor = Licensor.SERVER_CDM) -> Any:
"""A remote session on the server that holds the track."""
service = SimpleNamespace(fairplay_bridge=lambda: None, session=None)
return session_entry(service_instance=service, tracks={"vid": track}, licensing=LicensingMode(licensor))
def devices(device: Any) -> Any:
"""A cdm_for that gives ``device`` for its plugin system and a stub of any other system."""
return lambda system, quality=None: device if system == "example" else cdm_type_stub(system)
def client_of(server: Any, posts: list[dict]) -> Any:
def server_of(track: Video, licensing: LicensingMode | Licensor = Licensor.SERVER_CDM, device: Any = None) -> Any:
"""A remote session on the server that holds the track, whose service gets ``device`` for the plugin."""
obj = SimpleNamespace(cdm_for=devices(device) if device else None)
service = SimpleNamespace(fairplay_bridge=lambda: None, session=None, ctx=SimpleNamespace(obj=obj))
mode = licensing if isinstance(licensing, LicensingMode) else LicensingMode(licensing)
return session_entry(service_instance=service, tracks={"vid": track}, licensing=mode)
def client_of(server: Any, posts: list[dict], device: Any = None) -> Any:
"""A client of the server session whose licence requests run the licence route of the server."""
remote = remote_session(None, {})
remote.licensing = server.licensing
remote.ctx.obj.cdm_for = devices(device) if device else None
def post(endpoint: str, payload: dict, expect: Any = ()) -> dict:
posts.append(payload)
return json.loads(handlers.license_response(payload, server, "sess", None).text)
try:
return json.loads(handlers.license_response(payload, server, "sess", None).text)
except APIError as e:
if e.error_code not in expect:
raise
return {"error_code": e.error_code, "details": e.details}
remote.client = SimpleNamespace(post=post)
return remote
def track_list(track: Video) -> str:
"""The track list entry of the server, which never holds the content key or the ticket."""
"""The track list entry of the server: the ticket crosses as licence data, the content key never does."""
payload = json.dumps(serialize_video_track(track, include_url=True))
assert KEY not in payload and "EXAMPLE-TICKET" not in payload
assert KEY not in payload
return payload
@@ -124,13 +149,14 @@ def download(track: Video, tmp_path: Path, licence: Any, downloader: Any = segme
def test_the_batch_licence_keys_the_client_copy_and_the_client_plugin_decrypts(
server_track: Video, tmp_path: Path
server_track: Video, device: ExampleDevice, tmp_path: Path
) -> None:
posts: list[dict] = []
remote = client_of(server_of(server_track), posts)
server = server_of(server_track, device=device)
remote = client_of(server, posts)
track = rebuilt(server_track)
drm = track.drm[0]
assert isinstance(drm, CustomDRM) and (drm.kid, drm.key, drm.data) == (KID, None, {})
assert isinstance(drm, CustomDRM) and (drm.kid, drm.key, drm.data) == (KID, None, {"ticket": KID.hex})
vault = MemoryVault()
keys = resolver(vaults_of(vault))
@@ -142,12 +168,15 @@ def test_the_batch_licence_keys_the_client_copy_and_the_client_plugin_decrypts(
assert download(track, tmp_path, keys.licence_for(track, title, key_table())) == b"".join(PLAIN)
assert [post.get("track_ids") for post in posts] == [["vid"]]
assert vault.added == {KID: KEY}
assert server.served_keys == {KID.hex: (KEY, "cdm")}
assert FINISHED == [tmp_path / "video.ts"]
def test_a_track_the_batch_did_not_key_asks_the_licence_route_for_it(server_track: Video, tmp_path: Path) -> None:
def test_a_track_the_batch_did_not_key_asks_the_licence_route_for_it(
server_track: Video, device: ExampleDevice, tmp_path: Path
) -> None:
posts: list[dict] = []
remote = client_of(server_of(server_track), posts)
remote = client_of(server_of(server_track, device=device), posts)
track = rebuilt(server_track)
keys = resolver()
keys.source = remote
@@ -158,35 +187,88 @@ def test_a_track_the_batch_did_not_key_asks_the_licence_route_for_it(server_trac
assert posts == [{"drm_type": "example", "mode": "server_cdm", "track_id": "vid"}]
def test_the_licence_cap_refuses_a_plugin_track_above_it(server_track: Video, device: ExampleDevice) -> None:
"""A content key the service already holds, as one that licensed while it listed the tracks, stays behind the cap."""
server_track.drm[0].license(device)
server = server_of(server_track, LicensingMode(Licensor.SERVER_CDM, max_height=1080), device)
batch = server_keys.resolve_batch(server, ["vid"], "widevine", KeyPolicy())
assert batch.keys == {} and batch.capped_tracks["vid"]["max_height"] == 1080
with pytest.raises(APIError) as e:
handlers.license_response(
{"mode": "server_cdm", "drm_type": "example", "track_id": "vid"}, server, "sess", None
)
assert e.value.error_code is APIErrorCode.SERVER_CDM_CAPPED
assert not server.served_keys
def test_a_track_above_the_cap_licenses_with_the_client_plugin_device(
server_track: Video, device: ExampleDevice, tmp_path: Path
) -> None:
posts: list[dict] = []
server = server_of(server_track, LicensingMode(Licensor.SERVER_CDM, max_height=1080), device)
remote = client_of(server, posts, device)
track = rebuilt(server_track)
keys = resolver(cdm_for=devices(device))
keys.source = remote
title = one_title(track)
keys.take_server_keys(title) # type: ignore[arg-type]
assert download(track, tmp_path, keys.licence_for(track, title, key_table())) == b"".join(PLAIN)
assert remote.licenses_locally(track) and not server.served_keys
def test_cdm_only_licenses_a_plugin_track_with_the_client_plugin_device(
server_track: Video, device: ExampleDevice, tmp_path: Path
) -> None:
posts: list[dict] = []
server = server_of(server_track, Licensor.CLIENT_DEVICE)
remote = client_of(server, posts, device)
track = rebuilt(server_track)
vault = MemoryVault({KID: "00" * 16})
keys = resolver(vaults_of(vault), cdm_for=devices(device), cdm_only=True)
keys.source = remote
title = one_title(track)
keys.take_server_keys(title) # type: ignore[arg-type]
assert download(track, tmp_path, keys.licence_for(track, title, key_table())) == b"".join(PLAIN)
assert posts == [] and vault.asked == []
@pytest.mark.parametrize("licensor", [Licensor.CLIENT_DEVICE, Licensor.LENT_DEVICE])
def test_the_server_gives_no_key_outside_a_server_cdm_session(server_track: Video, licensor: Licensor) -> None:
server = server_of(server_track, licensor)
def test_the_server_gives_no_key_outside_a_server_cdm_session(
server_track: Video, device: ExampleDevice, licensor: Licensor
) -> None:
server = server_of(server_track, licensor, device)
assert server_keys.resolve_batch(server, ["vid"], "widevine", KeyPolicy()).keys == {}
with pytest.raises(APIError, match="not enabled"):
handlers.license_response(
{"mode": "server_cdm", "drm_type": "example", "track_id": "vid"}, server, "sess", None
)
assert not server.served_keys
assert not server.served_keys and not server_track.drm[0].content_keys
def test_a_client_device_session_decrypts_with_the_key_of_a_client_vault(server_track: Video, tmp_path: Path) -> None:
remote = client_of(server_of(server_track, Licensor.CLIENT_DEVICE), [])
track = rebuilt(server_track)
keys = resolver(vaults_of(MemoryVault({KID: KEY})))
keys = resolver(vaults_of(MemoryVault({KID: KEY})), cdm_for=lambda *_: pytest.fail("a device was loaded"))
keys.source = remote
assert download(track, tmp_path, keys.licence_for(track, one_title(track), key_table())) == b"".join(PLAIN)
def test_a_refused_licence_stops_the_track_before_its_segments(server_track: Video, tmp_path: Path) -> None:
def test_a_client_without_a_plugin_device_stops_the_track_before_its_segments(
server_track: Video, tmp_path: Path
) -> None:
remote = client_of(server_of(server_track, Licensor.CLIENT_DEVICE), [])
track = rebuilt(server_track)
keys = resolver()
keys = resolver(cdm_for=lambda *_: None)
keys.source = remote
licence = keys.licence_for(track, one_title(track), key_table())
with pytest.raises(click.ClickException, match="^The server sent no EXAMPLE content key for track vid$"):
with pytest.raises(click.ClickException, match="^No EXAMPLE device to license track vid$"):
download(track, tmp_path, licence, lambda **_: pytest.fail("a segment was requested"))
@@ -169,6 +169,7 @@ def test_session_transport_keys_are_the_create_body():
"best_available",
"generate_dv",
"dl_params",
"plugins",
}
@@ -737,7 +737,7 @@ def _sent_create_data(parent_params: dict, service_params: dict) -> dict:
def test_open_session_posts_what_session_request_builds() -> None:
parent = {"profile": "work", "lang": ["en"], "range_": [Video.Range.DV], "quality": [1080]}
data = _sent_create_data(parent, {"lang": 3})
sent = {k: v for k, v in data.items() if k not in ("service", "title_id", "client", "session_id")}
sent = {k: v for k, v in data.items() if k not in ("service", "title_id", "client", "session_id", "plugins")}
assert sent == session_request({"no_proxy": True, **parent}, {"lang": 3})
assert sent["dl_params"]["lang"] == ["en"]
+1 -1
View File
@@ -326,7 +326,7 @@ async def test_every_response_carries_a_generic_server_header(make_app, aiohttp_
async def test_services_load_errors_go_to_the_admin_key_only(
make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch
make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch, example_service: None
) -> None:
from unshackle.core import services as services_module
from unshackle.core.api import routes
+260
View File
@@ -0,0 +1,260 @@
"""The remote session names the client's DRM plugins: the server refuses a title the client cannot decrypt before it
lists the tracks, and a stand-in of the client's plugin device carries the device facts the client sent.
"""
from __future__ import annotations
import asyncio
import json
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import click
import pytest
from tests.drm_plugins import ExampleDevice
from tests.remote.key_source import remote_session
from tests.remote.sessions import launch_session, stub_service_build
from unshackle.core.api import handlers, key_policy
from unshackle.core.api import session_store as store_mod
from unshackle.core.api.errors import APIError
from unshackle.core.cdm.detect import cdm_system
from unshackle.core.drm import CustomDRM
from unshackle.core.remote_protocol import APIErrorCode, Licensor
from unshackle.core.tracks import Tracks, Video
from unshackle.core.tracks.track import Track
pytestmark = [pytest.mark.unit, pytest.mark.usefixtures("example_plugins")]
DEVICE_FACTS = {"device_name": "EXAMPLE_DEVICE"}
WIDEVINE_CDM = SimpleNamespace(is_playready=False)
class _SentCreate(Exception):
pass
def sent_create(cdm_for: Any, local_cdm: Any = WIDEVINE_CDM) -> dict:
"""The session create body that a client whose ``cdm_for`` gives its plugin devices sends."""
def post(path: str, data: dict) -> dict:
raise _SentCreate(data)
svc = remote_session(local_cdm, {})
svc.ctx.obj.cdm_for = cdm_for
svc.ctx.obj.cdm_entry = False
svc.licensing = None
svc._server_cdm_request = None
svc.service_tag = "EXAMPLE"
svc.title_id = "t1"
svc._server_accounts = {"global": True}
svc._service_params = {}
svc._client_config = None
svc.ctx.parent = SimpleNamespace(params={"no_proxy": True})
svc.client = SimpleNamespace(post=post)
with pytest.raises(_SentCreate) as exc:
svc.authenticate()
return exc.value.args[0]
def test_the_create_body_lists_each_plugin_with_its_version_and_device_facts(tmp_path: Path) -> None:
path = tmp_path / "EXAMPLE_DEVICE.exd"
path.write_bytes(b"\x5a")
device = ExampleDevice(path)
data = sent_create(lambda system, quality=None: device if system == "example" else None)
assert data["plugins"] == {"example": {"version": "1.0", "device": DEVICE_FACTS}, "other": {"version": ""}}
assert str(tmp_path) not in json.dumps(data["plugins"])
def test_a_client_with_no_local_device_sends_no_device_facts() -> None:
data = sent_create(lambda system, quality=None: pytest.fail("a device was loaded"), local_cdm=None)
assert data["plugins"] == {"example": {"version": "1.0"}, "other": {"version": ""}}
def test_a_plugin_device_that_does_not_load_sends_no_facts(caplog: pytest.LogCaptureFixture) -> None:
def broken(system: str, quality: int | None = None) -> Any:
raise ValueError("EXAMPLE device file is damaged")
data = sent_create(broken)
assert data["plugins"] == {"example": {"version": "1.0"}, "other": {"version": ""}}
assert "EXAMPLE device file is damaged" in caplog.text
@pytest.mark.parametrize(
"plugins",
[
["example"],
{"example": "1.0"},
{"example": {"version": 1}},
{"example": {"device": ["v5"]}},
{"example": {"device": {"name": {"nested": True}}}},
{"example": {"device": {"name": ["v5"]}}},
{"example": {"device": {"blob": "x" * 20000}}},
],
)
def test_a_malformed_plugin_list_is_refused(plugins: Any) -> None:
with pytest.raises(APIError) as e:
handlers.client_plugins(plugins)
assert e.value.error_code == APIErrorCode.INVALID_INPUT
def test_an_old_client_sends_no_plugin_list() -> None:
assert handlers.client_plugins(None) is None
assert handlers.client_plugins({"example": {"version": "1.0"}}) == {"example": {"version": "1.0"}}
assert handlers.client_plugins({"example": {"device": {"name": None}}}) == {"example": {"device": {"name": None}}}
def plugin_tracks() -> Tracks:
track = Video(
id_="vid",
url="https://example.test/seg0.ts",
language="en",
descriptor=Track.Descriptor.HLS,
codec=Video.Codec.HEVC,
height=2160,
drm=[CustomDRM("example", data={"ticket": "00" * 16})],
)
return Tracks([track])
def tracks_reply(client_plugins: Any) -> tuple[Any, Any]:
"""The answer of the tracks route for a title with an EXAMPLE plugin track (its body or its APIError), and the session."""
class StubService:
session = SimpleNamespace(headers={}, cookies=[])
def fairplay_bridge(self) -> None:
return None
def get_tracks(self, title: Any) -> Tracks:
return plugin_tracks()
def get_chapters(self, title: Any) -> list:
return []
def decrypts_samples(self, track: Any) -> bool:
return False
async def run() -> tuple[Any, Any]:
store = store_mod.get_session_store()
entry = await store.create(
service_tag="EXAMPLE",
service_instance=StubService(),
session_id="plugins",
client_plugins=client_plugins,
)
entry.title_map = {"t1": "EXAMPLE title"}
try:
resp = await handlers.session_tracks_handler({"title_id": "t1"}, "plugins")
answer: Any = json.loads(resp.text)
except APIError as e:
answer = e
finally:
await store.delete("plugins")
return answer, entry
return asyncio.run(run())
@pytest.mark.parametrize(
("client_plugins", "message"),
[
(None, "This title needs the DRM plugin 'example', and your unshackle sends no plugin list"),
({"other": {"version": ""}}, "This title needs the DRM plugin 'example', which your unshackle does not have"),
],
)
def test_a_client_that_cannot_decrypt_the_title_is_refused_before_the_track_list(
client_plugins: Any, message: str
) -> None:
refusal, entry = tracks_reply(client_plugins)
assert isinstance(refusal, APIError)
assert (refusal.error_code, refusal.message) == (APIErrorCode.DRM_ERROR, message)
assert entry.tracks == {}
def test_a_client_with_the_plugin_gets_the_track_list() -> None:
body, entry = tracks_reply({"example": {"version": "1.0"}})
assert [track["id"] for track in body["video"]] == ["vid"]
assert list(entry.tracks) == ["vid"]
def test_the_create_route_keeps_the_client_plugin_list(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
class Service:
_input_bridge = None
log = None
cache = None
def authenticate(self, cookies: Any, credential: Any) -> None:
pass
monkeypatch.setattr(handlers.config.directories, "cache", tmp_path)
monkeypatch.setattr(handlers, "validate_service", lambda service, request=None: service)
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
monkeypatch.setattr(handlers, "server_account_for", lambda *args: False)
monkeypatch.setattr(handlers.Services, "load", lambda service: Service)
stub_service_build(monkeypatch, Service)
listed = {"example": {"version": "1.0", "device": DEVICE_FACTS}}
async def run() -> Any:
resp = await handlers.session_create_handler({"service": "EXAMPLE", "title_id": "t", "plugins": listed})
session_id = json.loads(resp.body)["session_id"]
entry = store_mod.get_session_store().peek(session_id)
await store_mod.get_session_store().delete(session_id)
return entry
assert asyncio.run(run()).client_plugins == listed
def launched_cdm_for(monkeypatch: pytest.MonkeyPatch, licensor: Licensor, client_plugins: Any) -> Any:
"""The ``cdm_for`` that the service of a remote session gets on the server."""
seen: dict[str, Any] = {}
monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda service, profile, cdm_type, cfg: f"server {cdm_type}")
monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace())
def instantiate(parent_ctx: click.Context, *rest: Any) -> Any:
seen["cdm_for"] = parent_ctx.obj.cdm_for
return SimpleNamespace()
monkeypatch.setattr(handlers, "instantiate_service", instantiate)
launch_session("EXAMPLE", "t", {"cdm_type": "widevine"}, licensor=licensor, client_plugins=client_plugins)
return seen["cdm_for"]
def test_a_client_device_session_gives_the_service_a_stand_in_with_the_client_device_facts(
monkeypatch: pytest.MonkeyPatch,
) -> None:
sent = {"example": {"version": "1.0", "device": {**DEVICE_FACTS, "path": "/client/EXAMPLE_DEVICE.exd"}}}
cdm_for = launched_cdm_for(monkeypatch, Licensor.CLIENT_DEVICE, sent)
stub = cdm_for("example")
assert cdm_system(stub) == "example"
assert stub.device_name == "EXAMPLE_DEVICE"
assert not hasattr(stub, "path")
assert cdm_for("other") is None
assert cdm_for("unknown") is None
assert cdm_system(cdm_for("widevine")) == "widevine"
assert cdm_for("playready") is None
def test_a_fact_the_client_did_not_send_is_none_on_the_stand_in(monkeypatch: pytest.MonkeyPatch) -> None:
cdm_for = launched_cdm_for(monkeypatch, Licensor.CLIENT_DEVICE, {"example": {"version": "1.0", "device": {}}})
assert cdm_for("example").device_name is None
def test_a_client_device_session_with_no_device_facts_gives_no_plugin_device(monkeypatch: pytest.MonkeyPatch) -> None:
cdm_for = launched_cdm_for(monkeypatch, Licensor.CLIENT_DEVICE, {"example": {"version": "1.0"}})
assert cdm_for("example") is None
def test_a_server_cdm_session_keeps_the_server_device(monkeypatch: pytest.MonkeyPatch) -> None:
sent = {"example": {"version": "1.0", "device": DEVICE_FACTS}}
cdm_for = launched_cdm_for(monkeypatch, Licensor.SERVER_CDM, sent)
assert cdm_for("example") == "server example"