mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-04 06:55:09 +00:00
feat(drm)!: load DRM systems beyond the built-ins from plugins in directories.plugins
This commit is contained in:
@@ -98,7 +98,7 @@ def test_a_job_is_refused_for_a_key_with_its_own_identity(server, monkeypatch):
|
||||
({"cdm": "dev"}, "mapping of service tag"),
|
||||
({"cdm": {"default": "dev"}}, "a key has no default entry"),
|
||||
({"service_config": {"DEFAULT": {"device_id": "x"}}}, "a key has no default entry"),
|
||||
({"cdm": {"EXAMPLE": {"widevine": "dev", "tiers": "x"}}}, "device name or a widevine/playready/default"),
|
||||
({"cdm": {"EXAMPLE": {"widevine": "dev", "tiers": "x"}}}, "device name or a mapping of DRM system"),
|
||||
({"cdm": {"EXAMPLE": "missing"}}, "no CDM device named 'missing'"),
|
||||
({"service_config": {"EXAMPLE": "device_id"}}, "mapping of config key"),
|
||||
],
|
||||
|
||||
@@ -416,7 +416,7 @@ def test_proxy_license_rejects_an_unknown_drm_type() -> None:
|
||||
from unshackle.core.api.errors import APIError
|
||||
|
||||
with pytest.raises(APIError):
|
||||
_proxy(ClassicService(), "monalisa")
|
||||
_proxy(ClassicService(), "example")
|
||||
|
||||
|
||||
class _DelegatingService(Service):
|
||||
|
||||
+42
-84
@@ -1,15 +1,12 @@
|
||||
"""A MonaLisa 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 server licenses with the DRM its service built, the client decrypts it.
|
||||
|
||||
The service builds the DRM on the server with a device file there; only its KID crosses with the track list, and
|
||||
the content key comes through the licence route. The client decrypts each segment with its own tool, or with the
|
||||
built-in decrypter when it has none.
|
||||
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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import functools
|
||||
import json
|
||||
import sys
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
@@ -20,19 +17,18 @@ import click
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tests.core import bbts_sample
|
||||
from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of
|
||||
from tests.drm_plugins import FINISHED, xor
|
||||
from tests.remote.key_source import one_title, remote_session
|
||||
from tests.remote.sessions import session_entry
|
||||
from unshackle.core import binaries
|
||||
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.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.drm import MonaLisa, monalisa
|
||||
from unshackle.core.drm.bbts import decrypt_bbts, renumber_continuity
|
||||
from unshackle.core.drm import CustomDRM
|
||||
from unshackle.core.manifests.hls import HLS
|
||||
from unshackle.core.remote_protocol import LicensingMode, Licensor
|
||||
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
|
||||
@@ -47,55 +43,26 @@ PLAYLIST = (
|
||||
+ "".join(f"#EXTINF:5.0,\nhttps://example.test/seg{i}.ts\n" for i in range(len(PLAIN)))
|
||||
+ "#EXT-X-ENDLIST\n"
|
||||
)
|
||||
TOOL = """import sys
|
||||
args = dict(zip(sys.argv[1::2], sys.argv[2::2]))
|
||||
key = bytes.fromhex(args["-k"].split(":")[1])
|
||||
with open(args["-i"], "rb") as f:
|
||||
data = f.read()
|
||||
with open(args["-o"], "wb") as f:
|
||||
f.write(bytes(b ^ key[0] for b in data))
|
||||
"""
|
||||
|
||||
|
||||
def encrypt(data: bytes) -> bytes:
|
||||
return bytes(b ^ bytes.fromhex(KEY)[0] for b in data)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def tool(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:
|
||||
"""A bbtsdecrypt on this machine that XORs each byte with the first byte of the content key it gets."""
|
||||
script = tmp_path / "bbtsdecrypt.py"
|
||||
script.write_text(TOOL, encoding="utf-8")
|
||||
if sys.platform == "win32":
|
||||
path = tmp_path / "bbtsdecrypt.bat"
|
||||
path.write_text(f'@"{sys.executable}" "{script}" %*\n', encoding="utf-8")
|
||||
else:
|
||||
path = tmp_path / "bbtsdecrypt"
|
||||
path.write_text(f"#!{sys.executable}\n{TOOL}", encoding="utf-8")
|
||||
path.chmod(0o755)
|
||||
monkeypatch.setattr(monalisa, "local_tool", functools.cache(monalisa.local_tool.__wrapped__))
|
||||
find = binaries.find
|
||||
monkeypatch.setattr(binaries, "find", lambda *names, **kw: path if "bbtsdecrypt" in names else find(*names, **kw))
|
||||
yield path
|
||||
def cancel_flag() -> Iterator[None]:
|
||||
yield
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server_track(monkeypatch: pytest.MonkeyPatch) -> Video:
|
||||
"""The track the service built on the server: its MonaLisa DRM read the content key from a ticket."""
|
||||
|
||||
def extract_keys(drm: MonaLisa) -> None:
|
||||
drm._kid = KID
|
||||
drm.content_keys[KID] = KEY
|
||||
|
||||
monkeypatch.setattr(MonaLisa, "extract_keys", extract_keys)
|
||||
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
|
||||
track = Video(
|
||||
id_="vid",
|
||||
url="https://example.test/seg0.ts",
|
||||
language="en",
|
||||
descriptor=Track.Descriptor.HLS,
|
||||
codec=Video.Codec.HEVC,
|
||||
drm=[MonaLisa("EXAMPLE-TICKET", Path("server-only.mld"), segment_decrypt=False)],
|
||||
drm=[drm],
|
||||
)
|
||||
track.data["hls"] = {"playlist_text": PLAYLIST}
|
||||
return track
|
||||
@@ -119,20 +86,25 @@ def client_of(server: Any, posts: list[dict]) -> Any:
|
||||
return remote
|
||||
|
||||
|
||||
def track_list(track: Video) -> str:
|
||||
"""The track list entry of the server, which never holds the content key or the ticket."""
|
||||
payload = json.dumps(serialize_video_track(track, include_url=True))
|
||||
assert KEY not in payload and "EXAMPLE-TICKET" 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."""
|
||||
payload = json.dumps(serialize_video_track(track, include_url=True))
|
||||
assert KEY not in payload and "EXAMPLE-TICKET" not in payload and "server-only.mld" not in payload
|
||||
track = build_tracks({"video": [json.loads(payload)]}).videos[0]
|
||||
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, body: Any = None, **_: Any) -> Iterator[dict]:
|
||||
"""The ciphertext of each segment, saved as the downloader of a track saves it; ``body`` gives other bytes."""
|
||||
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(body() if body else encrypt(PLAIN[int(url["url"][-4])]))
|
||||
path.write_bytes(xor(PLAIN[int(url["url"][-4])], bytes.fromhex(KEY)))
|
||||
yield {"file_downloaded": path}
|
||||
|
||||
|
||||
@@ -151,14 +123,14 @@ def download(track: Video, tmp_path: Path, licence: Any, downloader: Any = segme
|
||||
return ctx.save_path.read_bytes()
|
||||
|
||||
|
||||
def test_the_batch_licence_keys_the_client_copy_and_the_client_tool_decrypts(
|
||||
def test_the_batch_licence_keys_the_client_copy_and_the_client_plugin_decrypts(
|
||||
server_track: Video, tmp_path: Path
|
||||
) -> None:
|
||||
posts: list[dict] = []
|
||||
remote = client_of(server_of(server_track), posts)
|
||||
track = rebuilt(server_track)
|
||||
drm = track.drm[0]
|
||||
assert isinstance(drm, MonaLisa) and (drm.kid, drm.key) == (KID, None)
|
||||
assert isinstance(drm, CustomDRM) and (drm.kid, drm.key, drm.data) == (KID, None, {})
|
||||
|
||||
vault = MemoryVault()
|
||||
keys = resolver(vaults_of(vault))
|
||||
@@ -170,6 +142,7 @@ def test_the_batch_licence_keys_the_client_copy_and_the_client_tool_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 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:
|
||||
@@ -182,7 +155,7 @@ def test_a_track_the_batch_did_not_key_asks_the_licence_route_for_it(server_trac
|
||||
output = download(track, tmp_path, keys.licence_for(track, one_title(track), key_table()))
|
||||
|
||||
assert output == b"".join(PLAIN)
|
||||
assert posts == [{"drm_type": "monalisa", "mode": "server_cdm", "track_id": "vid"}]
|
||||
assert posts == [{"drm_type": "example", "mode": "server_cdm", "track_id": "vid"}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("licensor", [Licensor.CLIENT_DEVICE, Licensor.LENT_DEVICE])
|
||||
@@ -192,7 +165,7 @@ def test_the_server_gives_no_key_outside_a_server_cdm_session(server_track: Vide
|
||||
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": "monalisa", "track_id": "vid"}, server, "sess", None
|
||||
{"mode": "server_cdm", "drm_type": "example", "track_id": "vid"}, server, "sess", None
|
||||
)
|
||||
assert not server.served_keys
|
||||
|
||||
@@ -206,32 +179,6 @@ def test_a_client_device_session_decrypts_with_the_key_of_a_client_vault(server_
|
||||
assert download(track, tmp_path, keys.licence_for(track, one_title(track), key_table())) == b"".join(PLAIN)
|
||||
|
||||
|
||||
def test_a_client_with_no_tool_decrypts_each_segment_with_the_built_in_decrypter(
|
||||
server_track: Video, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
monkeypatch.setattr(binaries, "find", lambda *_, **__: None)
|
||||
monalisa.local_tool.cache_clear()
|
||||
server_track.drm[0].content_keys[KID] = bbts_sample.KEY.hex()
|
||||
remote = client_of(server_of(server_track), [])
|
||||
track = rebuilt(server_track)
|
||||
keys = resolver()
|
||||
keys.source = remote
|
||||
|
||||
output = download(
|
||||
track,
|
||||
tmp_path,
|
||||
keys.licence_for(track, one_title(track), key_table()),
|
||||
functools.partial(segments, body=bbts_sample.bbts),
|
||||
)
|
||||
|
||||
(tmp_path / "sample.bbts").write_bytes(bbts_sample.bbts())
|
||||
decrypt_bbts(tmp_path / "sample.bbts", tmp_path / "clear.ts", bbts_sample.KEY)
|
||||
expected = tmp_path / "expected.ts"
|
||||
expected.write_bytes((tmp_path / "clear.ts").read_bytes() * len(PLAIN))
|
||||
renumber_continuity(expected)
|
||||
assert output == expected.read_bytes()
|
||||
|
||||
|
||||
def test_a_refused_licence_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)
|
||||
@@ -239,5 +186,16 @@ def test_a_refused_licence_stops_the_track_before_its_segments(server_track: Vid
|
||||
keys.source = remote
|
||||
licence = keys.licence_for(track, one_title(track), key_table())
|
||||
|
||||
with pytest.raises(click.ClickException, match="no MonaLisa content key"):
|
||||
with pytest.raises(click.ClickException, match="^The server sent no EXAMPLE content key for 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
|
||||
@@ -329,9 +329,11 @@ async def test_services_load_errors_go_to_the_admin_key_only(
|
||||
make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
from unshackle.core import services as services_module
|
||||
from unshackle.core.api import routes
|
||||
from unshackle.core.config import config
|
||||
|
||||
monkeypatch.setattr(services_module, "LOAD_ERRORS", ["BAD: failed to import - ImportError: boom"])
|
||||
monkeypatch.setattr(routes, "service_catalogue", lambda tags: {tag: {"tag": tag} for tag in tags})
|
||||
monkeypatch.setattr(config, "serve", {"api_secret": "admin", "users": {"user": {"services": ["EXAMPLE"]}}})
|
||||
client = await aiohttp_client(make_app(remote_only=True))
|
||||
user = await (await client.get("/api/services", headers={"X-Secret-Key": "user"})).json()
|
||||
|
||||
@@ -19,7 +19,7 @@ from tests.remote.key_source import install_reply, one_title, remote_keys
|
||||
from tests.remote.sessions import hold_session, session_entry
|
||||
from unshackle.core.api import handlers, server_keys
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.drm import BlowfishStripe, ClearKeyCTR
|
||||
from unshackle.core.drm import ClearKeyCTR, CustomDRM
|
||||
from unshackle.core.drm.cenc import drm_stub
|
||||
from unshackle.core.remote_protocol import LicensingMode, Licensor
|
||||
from unshackle.core.remote_service import RemoteError, RemoteService, held_keys
|
||||
@@ -212,12 +212,13 @@ async def test_batch_asks_again_when_a_cached_vault_answer_lacks_the_track_kid(m
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("drm", "head"),
|
||||
[(["drm"], b"head"), ([], None), ([BlowfishStripe(bytes(16))], None), ([KEYED_CIPHER], None)],
|
||||
ids=["with-drm", "clear", "stripe", "ctr"],
|
||||
[(["drm"], b"head"), ([], None), (["held-plugin"], None), ([KEYED_CIPHER], None)],
|
||||
ids=["with-drm", "clear", "held-plugin", "ctr"],
|
||||
)
|
||||
def test_the_server_reads_the_head_of_a_one_file_track_with_drm(drm, head):
|
||||
def test_the_server_reads_the_head_of_a_one_file_track_with_drm(example_plugins, drm, head):
|
||||
from unshackle.core.tracks import Video
|
||||
|
||||
drm = [CustomDRM("other", data={"key": "00" * 16}) if d == "held-plugin" else d for d in drm]
|
||||
fetched: list = []
|
||||
track = SimpleNamespace(
|
||||
id="v",
|
||||
@@ -435,9 +436,9 @@ async def batch_answer(monkeypatch, track, request=None, licensing=None):
|
||||
return json.loads(resp.body)
|
||||
|
||||
|
||||
async def test_a_stripe_cipher_that_holds_its_key_is_never_licensed(monkeypatch):
|
||||
"""A track whose only DRM is a stripe cipher that holds its key is named as clear and licensed by nothing."""
|
||||
cipher = BlowfishStripe(bytes(16))
|
||||
async def test_a_plugin_cipher_that_holds_its_key_is_never_licensed(monkeypatch, example_plugins):
|
||||
"""A track whose only DRM is a plugin DRM that holds its key is named as clear and licensed by nothing."""
|
||||
cipher = CustomDRM("other", data={"key": "00" * 16})
|
||||
track = SimpleNamespace(id="aud", drm=[cipher])
|
||||
|
||||
body = await batch_answer(monkeypatch, track)
|
||||
|
||||
Reference in New Issue
Block a user