feat(drm)!: load DRM systems beyond the built-ins from plugins in directories.plugins

This commit is contained in:
imSp4rky
2026-12-03 15:51:42 -07:00
parent f8a248a29e
commit e9adc50594
65 changed files with 1651 additions and 2526 deletions
+254
View File
@@ -0,0 +1,254 @@
"""The DRM plugin seam: the registry and loader, the facts core reads, the CDM catalogue and the wire and export forms."""
from __future__ import annotations
import logging
import zipfile
from pathlib import Path
from types import SimpleNamespace
from uuid import UUID
import click
import pytest
from tests.drm_plugins import EXAMPLE, ExampleDevice
from unshackle.commands.dl import cdm_summary
from unshackle.core import plugins
from unshackle.core.cdm import loader
from unshackle.core.cdm.choice import choose_cdm, drm_system
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub
from unshackle.core.drm import ClearKeyCTR, CustomDRM, held_key, own_cipher
from unshackle.core.plugins import DrmPlugin, load_folder
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks import Video
from unshackle.core.wire import drm_from_dict, export_system
pytestmark = pytest.mark.unit
KID = UUID(hex="11111111111111111111111111111111")
SOURCE = """from unshackle.core.plugins import DrmPlugin
from .{module} import decrypt
PLUGIN = DrmPlugin(id="{id}", label="EXAMPLE", licensing="held", media="own", mode="track", decrypt=decrypt)
"""
HELPER = "def decrypt(drm, src, dst):\n dst.write_bytes(src.read_bytes())\n"
def plugin_folder(folder: Path, name: str, plugin_id: str = "example") -> Path:
"""A folder plugin ``name`` that imports a helper module of its own package."""
path = folder / name
path.mkdir(parents=True)
(path / "__init__.py").write_text(SOURCE.format(module="helper", id=plugin_id), encoding="utf-8")
(path / "helper.py").write_text(HELPER, encoding="utf-8")
return path
def plugin_zip(folder: Path, name: str, plugin_id: str = "example") -> Path:
"""The zip form: the package folder ``name`` inside ``name``.zip, as the plugins zip script builds it."""
path = folder / f"{name}.zip"
with zipfile.ZipFile(path, "w") as z:
z.writestr(f"{name}/__init__.py", SOURCE.format(module="helper", id=plugin_id))
z.writestr(f"{name}/helper.py", HELPER)
return path
@pytest.mark.parametrize("make", [plugin_folder, plugin_zip], ids=["folder", "zip"])
def test_the_registry_loads_a_plugin_and_its_own_modules(tmp_path: Path, make) -> None:
make(tmp_path, "example_pkg")
found = load_folder(tmp_path)
assert list(found) == ["example"] and found["example"].label == "EXAMPLE"
src, dst = tmp_path / "in.bin", tmp_path / "out.bin"
src.write_bytes(b"EXAMPLE")
found["example"].decrypt(None, src, dst) # type: ignore[arg-type]
assert dst.read_bytes() == b"EXAMPLE"
def test_a_plugin_that_fails_to_load_gives_one_warning_naming_the_file(tmp_path: Path, caplog) -> None:
(tmp_path / "broken.zip").write_bytes(b"not a zip")
(tmp_path / "noplugin").mkdir()
(tmp_path / "noplugin" / "__init__.py").write_text("", encoding="utf-8")
plugin_folder(tmp_path, "good")
with caplog.at_level(logging.WARNING):
found = load_folder(tmp_path)
assert list(found) == ["example"]
assert [m.split(":")[0] for m in caplog.messages] == [
"DRM plugin broken.zip failed to load",
"DRM plugin noplugin failed to load",
]
def test_a_plugin_that_exits_at_import_gives_one_warning(tmp_path: Path, caplog) -> None:
(tmp_path / "exits").mkdir()
(tmp_path / "exits" / "__init__.py").write_text("raise SystemExit(1)", encoding="utf-8")
with caplog.at_level(logging.WARNING):
assert load_folder(tmp_path) == {}
assert caplog.messages == ["DRM plugin exits failed to load: SystemExit(1)"]
def test_a_plugin_that_reads_the_registry_while_it_loads_does_not_deadlock(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
path = plugin_folder(tmp_path, "example_pkg")
(path / "helper.py").write_text(
HELPER + "from unshackle.core import plugins\nSEEN = plugins.get('example')\n", encoding="utf-8"
)
monkeypatch.setattr(plugins, "PLUGINS", None)
from unshackle.core.config import config
monkeypatch.setattr(config.directories, "plugins", tmp_path)
assert plugins.get("example") is not None
def test_a_second_plugin_with_the_same_id_is_skipped(tmp_path: Path, caplog) -> None:
plugin_folder(tmp_path, "first")
plugin_zip(tmp_path, "second")
with caplog.at_level(logging.WARNING):
found = load_folder(tmp_path)
assert list(found) == ["example"]
assert caplog.messages == ["DRM plugin second.zip repeats the id 'example', skipped"]
def test_a_missing_plugin_folder_loads_nothing(tmp_path: Path) -> None:
assert load_folder(tmp_path / "absent") == {}
@pytest.mark.parametrize(
"facts",
[{"id": "widevine"}, {"id": "Bad-Id"}, {"licensing": "remote"}, {"mode": "file"}, {"device_suffix": ".exd"}],
)
def test_a_plugin_with_a_bad_fact_is_refused(facts: dict) -> None:
base = dict(id="example", label="EXAMPLE", licensing="held", media="own", mode="track")
with pytest.raises(ValueError):
DrmPlugin(**{**base, **facts}, decrypt=lambda *a: None) # type: ignore[arg-type]
def test_a_drm_of_a_plugin_that_is_not_loaded_stops_the_track() -> None:
with pytest.raises(click.ClickException, match=r"^No DRM plugin 'example' is installed$") as e:
CustomDRM("example")
assert e.value.error_code is APIErrorCode.DRM_ERROR # type: ignore[attr-defined]
def test_core_reads_the_facts_of_a_plugin(example_plugins: None) -> None:
local, held = CustomDRM("example"), CustomDRM("other")
ctr = ClearKeyCTR(None, bytes(16), b"OggS")
assert (own_cipher(local), own_cipher(held), own_cipher(ctr)) == (True, True, True)
assert (held_key(local), held_key(held), held_key(ctr)) == (False, True, False)
def test_a_failed_plugin_decrypt_keeps_the_ciphertext(example_plugins: None, tmp_path: Path) -> None:
drm = CustomDRM("other")
path = tmp_path / "track.ts"
path.write_bytes(b"cipher")
with pytest.raises(ValueError, match="No OTHER key"):
drm.decrypt(path)
assert path.read_bytes() == b"cipher" and sorted(p.name for p in tmp_path.iterdir()) == ["track.ts"]
def test_a_plugin_device_is_an_entry_of_the_cdm_catalogue(example_plugins: None, tmp_path: Path) -> None:
app_config = SimpleNamespace(remote_cdm=[], directories=SimpleNamespace(wvds=tmp_path, prds=tmp_path / "prds"))
(tmp_path / "EXAMPLE_DEVICE.exd").write_bytes(b"device")
device = loader.find_device("EXAMPLE_DEVICE", app_config)
assert device is not None and (device.system, device.source) == ("example", tmp_path / "EXAMPLE_DEVICE.exd")
assert loader.find_device("OTHER_DEVICE", app_config) is None
cdm = loader.load_local_cdm("EXAMPLE_DEVICE", device.system, tmp_path / "EXAMPLE_DEVICE.exd")
assert isinstance(cdm, ExampleDevice) and cdm_system(cdm) == "example"
def test_the_load_log_names_a_plugin_cdm_by_its_label_and_device_name(example_plugins: None, tmp_path: Path) -> None:
cdm = ExampleDevice(tmp_path / "EXAMPLE_DEVICE.exd")
assert cdm_summary(cdm) == {"drm_type": "EXAMPLE", "remote": False, "device": "EXAMPLE_DEVICE"}
del cdm.device_name
assert cdm_summary(cdm)["device"] == "EXAMPLE"
cdm.security_level = "v5"
assert cdm_summary(cdm)["security_level"] == "v5"
def test_a_stub_of_a_plugin_system_is_that_system(example_plugins: None) -> None:
assert cdm_system(cdm_type_stub("example")) == "example"
assert cdm_system(cdm_type_stub("None")) == "widevine"
def test_a_client_with_a_plugin_cdm_is_a_stand_in_of_its_system(example_plugins: None) -> None:
from unshackle.core.api.handlers import client_device_cdm
cdm = client_device_cdm({"cdm_type": "example", "cdm_relay": True}, input_bridge=SimpleNamespace())
assert cdm_system(cdm) == "example"
def test_a_plugin_device_licenses_a_plugin_drm(example_plugins: None, tmp_path: Path) -> None:
device = tmp_path / "EXAMPLE_DEVICE.exd"
device.write_bytes(bytes(range(16)))
drm = CustomDRM("example", data={"ticket": KID.hex})
drm.license(ExampleDevice(device))
assert (drm.kids, drm.content_keys) == ([KID], {KID: bytes(range(16)).hex()})
with pytest.raises(click.ClickException, match=r"^The OTHER plugin has no licence$"):
CustomDRM("other").license(ExampleDevice(device))
def test_the_cdm_choice_names_a_plugin_device_for_its_system(example_plugins: None) -> None:
cdm = {"EXAMPLE": {"widevine": "EXAMPLE_WVD", "example": "EXAMPLE_DEVICE"}}
assert drm_system("EXAMPLE") == "example" and drm_system("unknown") is None
assert choose_cdm(cdm, "EXAMPLE", drm="example", view="licence").device == "EXAMPLE_DEVICE"
assert choose_cdm(cdm, "EXAMPLE", drm="widevine", view="licence").device == "EXAMPLE_WVD"
def test_a_track_gives_a_plugin_cdm_the_drm_of_its_plugin(example_plugins: None) -> None:
other, example = CustomDRM("other"), CustomDRM("example")
track = Video(url="https://example.test/v.m3u8", language="en", drm=[other, example])
assert track.get_drm_for_cdm(ExampleDevice(Path("EXAMPLE_DEVICE.exd"))) is example
assert track.get_drm_for_cdm(None) is other
def test_the_export_form_of_a_plugin_drm_round_trips_without_its_keys(example_plugins: None) -> None:
drm = CustomDRM("other", kids=[KID], display_id="EXAMPLE-1", data={"key": "aa" * 16, "ticket": "server only"})
drm.content_keys[KID] = "bb" * 16
form = drm.to_dict()
assert form == {
"system": "other",
"kids": [KID.hex],
"label": "OTHER",
"display_id": "EXAMPLE-1",
"data": {"key": "aa" * 16},
}
rebuilt = drm_from_dict(form)
assert isinstance(rebuilt, CustomDRM)
assert (rebuilt.plugin is drm.plugin, rebuilt.kids, rebuilt.data, rebuilt.content_keys) == (
True,
[KID],
{"key": "aa" * 16},
{},
)
def test_an_export_of_a_plugin_that_is_not_loaded_stops_the_track() -> None:
with pytest.raises(click.ClickException, match=r"^Unknown DRM system 'example' in the export$"):
export_system("example")
def test_the_registry_loads_the_plugin_folder_once(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
plugin_folder(tmp_path, "example_pkg")
monkeypatch.setattr(plugins, "PLUGINS", None)
from unshackle.core.config import config
monkeypatch.setattr(config.directories, "plugins", tmp_path)
assert plugins.get("example") is not None and plugins.get("example") is plugins.plugins()["example"]
assert plugins.get(EXAMPLE) is None