Files
unshackle/tests/remote/unit/test_remote_plugin.py
T

284 lines
12 KiB
Python

"""A plugin DRM HLS track over --remote: the licence runs at the licence step, on the server or on the client.
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
import json
from collections.abc import Iterator
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from uuid import UUID
import click
import pytest
import requests
from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
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
from unshackle.core.remote_protocol import APIErrorCode, LicensingMode, Licensor
from unshackle.core.tracks import Video
from unshackle.core.tracks.track import DownloadContext, Track
from unshackle.core.wire import build_tracks, serialize_video_track
pytestmark = pytest.mark.unit
KID = UUID(hex="0123456789abcdef0123456789abcdef")
KEY = "5a" * 16
PLAIN = [b"EXAMPLE clear segment %d. " % i * 8 for i in range(3)]
PLAYLIST = (
"#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:5\n#EXT-X-KEY:METHOD=NONE\n"
+ "".join(f"#EXTINF:5.0,\nhttps://example.test/seg{i}.ts\n" for i in range(len(PLAIN)))
+ "#EXT-X-ENDLIST\n"
)
@pytest.fixture(autouse=True)
def cancel_flag() -> Iterator[None]:
yield
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 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 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 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)
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: 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
return payload
def rebuilt(track: Video) -> Video:
"""The track as the client rebuilds it from the track list of the server, with the playlist its snapshot holds."""
track = build_tracks({"video": [json.loads(track_list(track))]}).videos[0]
track.data["hls"] = {"playlist_text": PLAYLIST}
return track
def segments(urls: list[dict], output_dir: Path, filename: str, **_: Any) -> Iterator[dict]:
"""The ciphertext of each segment, saved as the downloader of a track saves it."""
for i, url in enumerate(urls):
path = output_dir / filename.format(i=i, ext=".ts")
path.write_bytes(xor(PLAIN[int(url["url"][-4])], bytes.fromhex(KEY)))
yield {"file_downloaded": path}
def download(track: Video, tmp_path: Path, licence: Any, downloader: Any = segments) -> bytes:
"""Download the track through the licence step; return the output file."""
track.downloader = downloader
ctx = DownloadContext(
save_path=tmp_path / "video.ts",
save_dir=tmp_path / "video_segments",
progress=lambda **_: None,
license_widevine=licence,
cdm=None,
session=requests.Session(),
)
HLS.download_track(track=track, ctx=ctx)
return ctx.save_path.read_bytes()
def test_the_batch_licence_keys_the_client_copy_and_the_client_plugin_decrypts(
server_track: Video, device: ExampleDevice, tmp_path: Path
) -> None:
posts: list[dict] = []
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, {"ticket": KID.hex})
vault = MemoryVault()
keys = resolver(vaults_of(vault))
keys.source = remote
title = one_title(track)
keys.take_server_keys(title) # type: ignore[arg-type]
keys.wait_vault_writes()
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, device: ExampleDevice, tmp_path: Path
) -> None:
posts: list[dict] = []
remote = client_of(server_of(server_track, device=device), posts)
track = rebuilt(server_track)
keys = resolver()
keys.source = remote
output = download(track, tmp_path, keys.licence_for(track, one_title(track), key_table()))
assert output == b"".join(PLAIN)
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, 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 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})), 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_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(cdm_for=lambda *_: None)
keys.source = remote
licence = keys.licence_for(track, one_title(track), key_table())
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"))
def test_a_client_without_the_plugin_refuses_the_track_with_one_line(
server_track: Video, monkeypatch: pytest.MonkeyPatch
) -> None:
payload = json.loads(track_list(server_track))
monkeypatch.setattr(plugins, "PLUGINS", {})
with pytest.raises(click.ClickException, match=r"^Unknown DRM type 'example' from the server$") as e:
build_tracks({"video": [payload]})
assert getattr(e.value, "error_code", None) == APIErrorCode.DRM_ERROR