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
+16 -1
View File
@@ -11,7 +11,7 @@ from typing import Any
import pytest
from unshackle.core import binaries, console, process_exit
from unshackle.core import binaries, console, plugins, process_exit
from unshackle.core import session as http_session
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY, RunCancel
@@ -108,6 +108,21 @@ def no_dl_run_state(monkeypatch: pytest.MonkeyPatch) -> None:
DOWNLOAD_LICENCE_ONLY.clear()
@pytest.fixture(autouse=True)
def no_drm_plugins(monkeypatch: pytest.MonkeyPatch) -> None:
"""Start with an empty DRM plugin registry, whatever the local plugin folder holds."""
monkeypatch.setattr(plugins, "PLUGINS", {})
@pytest.fixture
def example_plugins(monkeypatch: pytest.MonkeyPatch) -> None:
"""Load the EXAMPLE and OTHER test DRM plugins (tests/drm_plugins.py) as the only plugins."""
from tests.drm_plugins import EXAMPLE, FINISHED, OTHER
FINISHED.clear()
monkeypatch.setattr(plugins, "PLUGINS", {EXAMPLE.id: EXAMPLE, OTHER.id: OTHER})
@pytest.fixture(autouse=True)
def no_speed_limit(monkeypatch: pytest.MonkeyPatch) -> None:
"""Start with no speed limit, so a limit that an earlier test locked cannot block a later one."""
-187
View File
@@ -1,187 +0,0 @@
"""A synthetic BBTS file and its cipher, built from scratch so the tests need no real media.
The cipher here is a slow, plain reading of the format; the decrypter under test never builds its own input.
"""
from __future__ import annotations
import hashlib
import re
from Cryptodome.Cipher import AES
KEY = bytes.fromhex("00112233445566778899aabbccddeeff")
IVS = (bytes.fromhex("0123456789abcdef0123456789abcdef"), bytes.fromhex("fedcba9876543210fedcba9876543210"))
HEVC, H264, AAC = 0x24, 0x1B, 0x0F
SC3, SC4 = b"\x00\x00\x01", b"\x00\x00\x00\x01"
# SHA-256 of what the bbtsdecrypt binary wrote for bbts(video_type), so CI needs no binary.
GOLDEN = {
HEVC: "b2d70cf98ca9b08b94363c627266da9c31ed07f08acf2ac3d2645ca9cff0366a",
H264: "0f2bb9586781768f086d9a6d05ec09466453ee9e53557fa6ad6d09598be2e8b3",
}
def noise(seed: str, size: int) -> bytes:
"""Deterministic bytes with no zero byte."""
out = b"".join(hashlib.sha256(f"{seed}{i}".encode()).digest() for i in range(size // 32 + 1))[:size]
return out.replace(b"\x00", b"\x5a")
def crc32_mpeg(data: bytes) -> int:
crc = 0xFFFFFFFF
for byte in data:
crc ^= byte << 24
for _ in range(8):
crc = ((crc << 1) ^ 0x104C11DB7) if crc & 0x80000000 else crc << 1
return crc & 0xFFFFFFFF
def encrypt(payload: bytes, iv: bytes) -> bytes:
"""Encrypt a NAL payload: all but its last 2 bytes, block by block, then escape the result for the byte stream."""
ecb = AES.new(KEY, AES.MODE_ECB)
counter = int.from_bytes(iv[:12] + bytes(4), "big")
body, out = payload[:-2], bytearray()
for n, at in enumerate(range(0, len(body), 16)):
counter += 1
block = counter.to_bytes(16, "big")
if n % 10 == 0 or len(body) - at <= 16:
block = ecb.encrypt(block)
out += bytes(a ^ b for a, b in zip(body[at : at + 16], block, strict=False))
return re.sub(b"\x00\x00(?=[\x00-\x03])", b"\x00\x00\x03", bytes(out) + payload[-2:])
def section(table_id: int, body: bytes) -> bytes:
"""A long-form PSI section with its CRC."""
data = bytes([table_id]) + (0xB000 | (len(body) + 9)).to_bytes(2, "big") + b"\x00\x01\xc1\x00\x00" + body
return data + crc32_mpeg(data).to_bytes(4, "big")
def psi_packet(pid: int, data: bytes) -> bytes:
payload = b"\x00" + data
return bytes([0x47, 0x40 | pid >> 8, pid & 0xFF, 0x10]) + payload + b"\xff" * (184 - len(payload))
def sdt(iv: bytes, name_format: str) -> bytes:
"""An SDT whose service name is ``name_format`` with the IV in it."""
name = name_format.format(iv=iv.hex()).encode()
descriptor = bytes([0x48, 3 + 7 + len(name), 0x01, 7]) + b"EXAMPLE" + bytes([len(name)]) + name
service = b"\x00\x01\xfc" + (0x8000 | len(descriptor)).to_bytes(2, "big") + descriptor
return psi_packet(0x11, section(0x42, b"\x00\x01\xff" + service))
def pmt(video_type: int) -> bytes:
"""A PMT with the video stream, an AAC stream and an H.264 stream on another PID."""
streams = bytes([video_type, 0xE1, 0x00, 0xF0, 0x00, AAC, 0xE1, 0x01, 0xF0, 0x00, H264, 0xE1, 0x02, 0xF0, 0x00])
return psi_packet(0x1000, section(0x02, b"\xe1\x00\xf0\x00" + streams))
PAT = psi_packet(0, section(0x00, b"\x00\x01\xf0\x00"))
def packets(pid: int, pes: bytes, counter: list[int], last: int) -> list[bytes]:
"""Cut a PES packet into TS packets, the last of which carries ``last`` bytes after adaptation-field stuffing."""
sizes = [184] * ((len(pes) - last) // 184) + [last]
assert sum(sizes) == len(pes), "the PES does not end on the asked size"
out, at = [], 0
for size in sizes:
chunk, at = pes[at : at + size], at + size
start = 0x40 if at == size else 0
head = bytes([0x47, start | pid >> 8, pid & 0xFF, (0x10 if size == 184 else 0x30) | counter[0] % 16])
counter[0] += 1
stuffing = 183 - size
field = b"" if size == 184 else bytes([stuffing]) + (b"\x00" + b"\xff" * (stuffing - 1) if stuffing else b"")
out.append(head + field + chunk)
return out
def pes(stream_id: int, es: bytes) -> bytes:
return SC3 + bytes([stream_id]) + b"\x00\x00\x80\x80\x05\x21\x00\x01\x00\x01" + es
def with_zero_runs(seed: str, size: int) -> bytes:
"""Bytes whose zero runs make the cipher hold emulation-prevention bytes."""
data = bytearray(noise(seed, size))
for at in range(20, size - 8, 37):
data[at : at + 5] = bytes(5)
return bytes(data)
def nal_units(seed: str, iv: bytes, h264: bool) -> bytes:
"""An access unit: a delimiter, a SEI and an RPU with the 4 bytes the cipher appends, slices, and a short NAL."""
aud, sei, slice_ = (b"\x09", b"\x06", b"\x65") if h264 else (b"\x46\x01", b"\x4e\x01", b"\x02\x01")
rpu = b"\x19" + noise(seed + "r", 40)
rpu += crc32_mpeg(rpu[1:]).to_bytes(4, "big") + b"\x80"
units = [
SC4 + aud + encrypt(b"\x50" + noise(seed + "a", 4), iv),
SC3 + sei + encrypt(b"\x05\x04\xaa\xbb\xcc\xdd\xff\x01\x02\x11\x22\x80" + noise(seed + "s", 4), iv),
SC3 + slice_ + encrypt(with_zero_runs(seed + "l", 300) + b"\x00", iv),
SC4 + slice_ + encrypt(noise(seed + "m", 2), iv),
SC3 + slice_ + encrypt(noise(seed + "n", 161), iv),
]
if not h264:
units.insert(2, SC3 + b"\x7c\x01" + encrypt(rpu + noise(seed + "p", 4), iv))
return b"".join(units)
def timestamp(ticks: int) -> bytes:
"""A PES PTS field of ``ticks`` at 90 kHz."""
return bytes(
[
0x21 | ticks >> 29 & 0x0E,
ticks >> 22 & 0xFF,
ticks >> 14 & 0xFE | 1,
ticks >> 7 & 0xFF,
ticks << 1 & 0xFE | 1,
]
)
def bbts_segments(es: bytes, iv: bytes, frames: int, fps: int) -> list[bytes]:
"""BBTS segments of ``frames`` pictures each, from an Annex B HEVC stream with a delimiter before each picture.
Each segment opens with its tables, and each picture is one video PES packet with only a PTS.
"""
pictures: list[list[bytes]] = []
for nal in es.split(SC3)[1:]:
if nal[0] >> 1 & 0x3F == 35:
pictures.append([])
pictures[-1].append(nal.rstrip(b"\x00"))
hevc_pmt = psi_packet(0x1000, section(0x02, b"\xe1\x00\xf0\x00" + bytes([HEVC, 0xE1, 0x00, 0xF0, 0x00])))
segments, counter = [], [0]
for first in range(0, len(pictures), frames):
out = [PAT, hevc_pmt, sdt(iv, "a0|mdcm|s1:9:10|e1|v{iv}|f1|gv|q")]
for n, picture in enumerate(pictures[first : first + frames], first):
es_out = b"".join(SC4 + nal[:2] + (encrypt(nal[2:], iv) if len(nal) > 4 else nal[2:]) for nal in picture)
packet = SC3 + b"\xe0\x00\x00\x80\x80\x05" + timestamp(90000 * (n + 1) // fps) + es_out
out += packets(0x100, packet, counter, len(packet) % 184 or 184)
segments.append(b"".join(out))
return segments
def bbts(
video_type: int = HEVC, pmt_first: bool = False, name_format: str = "a0|mdcm|s1:9:10|e1|v{iv}|f1|gv|q"
) -> bytes:
"""Two segments with their own IV, each with SDT, PMT, two video PES packets and an audio PES packet between them.
``pmt_first`` puts the PMT before the SDT; ``name_format`` is the service name that holds the IV.
The first video PES ends in a packet of 6 bytes, so the bytes the decrypter drops empty that packet; the second
ends in a packet whose adaptation field is only its length byte.
"""
counters: list[list[int]] = [[0], [0]]
out = []
for n, iv in enumerate(IVS):
tables = (
[PAT, pmt(video_type), sdt(iv, name_format)] if pmt_first else [PAT, sdt(iv, name_format), pmt(video_type)]
)
out += tables
for k, last in ((0, 6), (1, 183)):
es = nal_units(f"v{n}{k}", iv, video_type == H264)
head = b"\x01" if video_type == H264 else b"\x02\x01"
filler = (last - len(pes(0xE0, es)) - 3 - len(head)) % 184 + 184
es += SC3 + head + noise(f"f{n}{k}", filler)
out += packets(0x100, pes(0xE0, es), counters[0], last)
if k == 0:
audio = pes(0xC0, noise(f"a{n}", 400))
out += packets(0x101, audio, counters[1], len(audio) % 184)
return b"".join(out)
-108
View File
@@ -1,108 +0,0 @@
"""The built-in BBTS decrypter against output of the bbtsdecrypt binary, on a synthetic file built in the test."""
import hashlib
import subprocess
from pathlib import Path
import pytest
from tests.core import bbts_sample
from unshackle.core import binaries
from unshackle.core.drm.bbts import decrypt_bbts, renumber_continuity
from unshackle.core.utils.hdr10plus import ts_packets, ts_pid
pytestmark = pytest.mark.unit
def packets_of(data: bytes, pid: int) -> list[bytes]:
"""The TS packets of one PID, or of every PID for -1."""
return [packet for packet in ts_packets(data) if pid in (-1, ts_pid(packet))]
@pytest.fixture(params=[bbts_sample.HEVC, bbts_sample.H264], ids=["hevc", "h264"])
def sample(request: pytest.FixtureRequest, tmp_path: Path) -> tuple[int, Path]:
path = tmp_path / "segment.bbts"
path.write_bytes(bbts_sample.bbts(request.param))
return request.param, path
def test_the_clear_file_is_the_one_bbtsdecrypt_wrote(sample: tuple[int, Path], tmp_path: Path) -> None:
video_type, src = sample
decrypt_bbts(src, tmp_path / "clear.ts", bbts_sample.KEY)
assert hashlib.sha256((tmp_path / "clear.ts").read_bytes()).hexdigest() == bbts_sample.GOLDEN[video_type]
def test_only_the_video_pid_changes(sample: tuple[int, Path], tmp_path: Path) -> None:
_, src = sample
decrypt_bbts(src, tmp_path / "clear.ts", bbts_sample.KEY)
before, after = src.read_bytes(), (tmp_path / "clear.ts").read_bytes()
assert len(after) == len(before)
for pid in (0x0000, 0x0011, 0x1000, 0x0101):
assert packets_of(after, pid) == packets_of(before, pid)
assert packets_of(after, 0x0100) != packets_of(before, 0x0100)
def test_the_binary_writes_the_same_file(sample: tuple[int, Path], tmp_path: Path) -> None:
if not (tool := binaries.find("bbtsdecrypt")):
pytest.skip("no bbtsdecrypt binary on this machine")
_, src = sample
decrypt_bbts(src, tmp_path / "builtin.ts", bbts_sample.KEY)
subprocess.run(
[tool, "-i", src, "-o", tmp_path / "tool.ts", "-k", f"{'0' * 32}:{bbts_sample.KEY.hex()}"],
capture_output=True,
check=True,
)
assert (tmp_path / "builtin.ts").read_bytes() == (tmp_path / "tool.ts").read_bytes()
@pytest.mark.parametrize("video_type", [bbts_sample.HEVC, bbts_sample.H264], ids=["hevc", "h264"])
@pytest.mark.parametrize(
"layout",
[{"pmt_first": True}, {"name_format": "mdcm|a|b|{iv}|c"}],
ids=["pmt-before-sdt", "iv-in-fourth-field"],
)
def test_other_table_layouts_give_the_same_video(video_type: int, layout: dict, tmp_path: Path) -> None:
(tmp_path / "usual.bbts").write_bytes(bbts_sample.bbts(video_type))
(tmp_path / "other.bbts").write_bytes(bbts_sample.bbts(video_type, **layout))
for name in ("usual", "other"):
decrypt_bbts(tmp_path / f"{name}.bbts", tmp_path / f"{name}.ts", bbts_sample.KEY)
usual, other = ((tmp_path / f"{name}.ts").read_bytes() for name in ("usual", "other"))
assert hashlib.sha256(usual).hexdigest() == bbts_sample.GOLDEN[video_type]
assert packets_of(other, 0x0100) == packets_of(usual, 0x0100)
def test_a_file_with_no_iv_is_copied(tmp_path: Path) -> None:
data = b"".join(packet for packet in packets_of(bbts_sample.bbts(), -1) if packet[1:3] != b"\x40\x11")
(tmp_path / "in.ts").write_bytes(data)
decrypt_bbts(tmp_path / "in.ts", tmp_path / "out.ts", bbts_sample.KEY)
assert (tmp_path / "out.ts").read_bytes() == data
def test_a_key_of_another_length_is_refused(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="16-byte key"):
decrypt_bbts(tmp_path / "in.ts", tmp_path / "out.ts", b"short")
def test_the_counter_steps_only_on_a_packet_with_payload(tmp_path: Path) -> None:
def packet(pid: int, cc: int, payload: bool = True) -> bytes:
body = b"\x00" * 184 if payload else bytes([183, 0]) + b"\xff" * 182
return bytes([0x47, pid >> 8, pid & 0xFF, (0x10 if payload else 0x20) | cc]) + body
path = tmp_path / "clear.ts"
sent = [
(0x100, 5, True),
(0x100, 6, False),
(0x1FFF, 3, True),
(0x100, 7, True),
(0x100, 7, True),
(0x100, 8, True),
]
path.write_bytes(b"".join(packet(*p) for p in sent))
renumber_continuity(path)
assert [p[3] & 0x0F for p in packets_of(path.read_bytes(), -1)] == [5, 5, 3, 6, 6, 7]
-144
View File
@@ -1,144 +0,0 @@
"""Tests for the Blowfish CBC stripe cipher (``unshackle.core.drm.blowfish_stripe``)."""
from __future__ import annotations
import os
from collections.abc import Iterator
from functools import partial
from pathlib import Path
from typing import Any
import pytest
import requests
from Cryptodome.Cipher import Blowfish
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import BlowfishStripe
from unshackle.core.tracks import Audio, Track
from unshackle.core.tracks import track as track_module
from unshackle.core.wire import build_tracks, reconstruct_drm, serialize_audio_track, serialize_drm
KEY = bytes.fromhex("00112233445566778899aabbccddeeff")
CHUNK = BlowfishStripe.CHUNK
def stripe_encrypt(data: bytes, key: bytes = KEY) -> bytes:
"""Reference encryption: every third full chunk, each with a fresh CBC run."""
out = bytearray(data)
for offset in range(0, len(data), CHUNK * 3):
chunk = data[offset : offset + CHUNK]
if len(chunk) == CHUNK:
out[offset : offset + CHUNK] = Blowfish.new(key, Blowfish.MODE_CBC, iv=BlowfishStripe.IV).encrypt(chunk)
return bytes(out)
def test_decrypt_round_trip(tmp_path: Path) -> None:
plain = os.urandom(CHUNK * 10 + 123)
path = tmp_path / "track.flac"
path.write_bytes(stripe_encrypt(plain))
assert path.read_bytes() != plain
BlowfishStripe(KEY).decrypt(path)
assert path.read_bytes() == plain
assert list(tmp_path.iterdir()) == [path]
def refuse_replace(monkeypatch: pytest.MonkeyPatch) -> None:
def refuse(self: Path, target: Path) -> None:
raise PermissionError(target)
monkeypatch.setattr(Path, "replace", refuse)
def fail_chunk(monkeypatch: pytest.MonkeyPatch) -> None:
def fail(self: BlowfishStripe, chunk: bytes) -> bytes:
raise ValueError("bad chunk")
monkeypatch.setattr(BlowfishStripe, "decrypt_chunk", fail)
@pytest.mark.parametrize(
("break_step", "raises"),
[pytest.param(fail_chunk, ValueError, id="decrypt"), pytest.param(refuse_replace, PermissionError, id="replace")],
)
def test_a_failed_decrypt_keeps_the_input(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, break_step: Any, raises: type[BaseException]
) -> None:
path = tmp_path / "track.flac"
path.write_bytes(stripe_encrypt(os.urandom(CHUNK * 4)))
original = path.read_bytes()
break_step(monkeypatch)
with pytest.raises(raises):
BlowfishStripe(KEY).decrypt(path)
assert path.read_bytes() == original
assert list(tmp_path.iterdir()) == [path]
def test_short_trailing_chunk_untouched(tmp_path: Path) -> None:
# the last stripe starts at CHUNK * 3 and holds only 100 bytes, so it stays clear
plain = os.urandom(CHUNK * 3 + 100)
encrypted = stripe_encrypt(plain)
assert encrypted[CHUNK * 3 :] == plain[CHUNK * 3 :]
path = tmp_path / "track.mp3"
path.write_bytes(encrypted)
BlowfishStripe(KEY).decrypt(path)
assert path.read_bytes() == plain
def test_serialize_round_trip_keeps_key() -> None:
serialized = serialize_drm([BlowfishStripe(KEY)])
assert serialized == [{"type": "blowfishstripe", "key": KEY.hex()}]
rebuilt = reconstruct_drm(serialized)
assert len(rebuilt) == 1
assert isinstance(rebuilt[0], BlowfishStripe)
assert rebuilt[0].key == KEY
def test_remote_tracks_keep_the_stripe_drm() -> None:
track = Audio(
id_="a1", url="https://example.test/a1", language="en", codec=Audio.Codec.FLAC, drm=[BlowfishStripe(KEY)]
)
rebuilt = build_tracks({"audio": [serialize_audio_track(track, include_url=True)]})
assert isinstance(rebuilt.audio[0].drm[0], BlowfishStripe)
assert rebuilt.audio[0].drm[0].key == KEY
def test_url_download_decrypts_once_without_a_kid_probe(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config.directories, "temp", tmp_path)
monkeypatch.setattr(Track, "get_key_id", lambda *a, **k: pytest.fail("a stripe-cipher file has no KID to probe"))
monkeypatch.setattr(
track_module, "assert_fragments_decrypted", lambda path: pytest.fail("a stripe-cipher file has no fragments")
)
plain = os.urandom(CHUNK * 7 + 5)
def downloader(**kwargs: Any) -> Iterator[dict[str, Any]]:
(Path(kwargs["output_dir"]) / kwargs["filename"]).write_bytes(stripe_encrypt(plain))
yield {"file_downloaded": Path(kwargs["output_dir"]) / kwargs["filename"]}
track = Audio(
id_="a1",
url="https://example.test/a1.flac",
language="en",
codec=Audio.Codec.FLAC,
drm=[BlowfishStripe(KEY)],
downloader=downloader,
)
try:
track.download(
session=requests.Session(), prepare_drm=partial(lambda *a, **kw: None), progress=partial(lambda **kw: None)
)
finally:
DOWNLOAD_CANCELLED.clear()
assert track.path is not None and track.path.read_bytes() == plain
assert track.drm is None
+107
View File
@@ -0,0 +1,107 @@
"""A track of a locally licensed plugin DRM whose content key does not decode stops after the merge."""
from __future__ import annotations
import dataclasses
import threading
from collections.abc import Iterator
from http.server import ThreadingHTTPServer
from pathlib import Path
from uuid import UUID
import click
import pytest
from tests.core.key_resolver import MemoryVault, resolver, vaults_of
from tests.core.test_rolling_merge_hls_ism import _Handler, base, make_ctx
from tests.drm_plugins import EXAMPLE, xor
from unshackle.core import binaries, plugins
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import CustomDRM, key_resolution, verify
from unshackle.core.manifests import HLS
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks import Audio, Video
KID = UUID(hex="11111111111111111111111111111111")
KEY, WRONG = "a5" * 16, "5a" * 16
PLAIN = [b"EXAMPLE clear segment %d. " % i * 8 for i in range(3)]
@pytest.fixture
def server(monkeypatch: pytest.MonkeyPatch, example_plugins: None) -> Iterator[ThreadingHTTPServer]:
"""An HLS playlist of EXAMPLE segments; ffmpeg "decodes" a file only when it is the plaintext."""
monkeypatch.setattr(binaries, "FFMPEG", Path("ffmpeg"))
monkeypatch.setattr(verify, "kid_windows", lambda path: None)
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", lambda path, **kw: path.read_bytes() == b"".join(PLAIN))
srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
lines = ["#EXTM3U", "#EXT-X-VERSION:3", "#EXT-X-TARGETDURATION:2"]
srv.routes = {} # type: ignore[attr-defined]
for i, segment in enumerate(PLAIN):
srv.routes[f"/{i}.ts"] = xor(segment, bytes.fromhex(KEY)) # type: ignore[attr-defined]
lines += ["#EXTINF:2.0,", f"{i}.ts"]
srv.routes["/v.m3u8"] = "\n".join([*lines, "#EXT-X-ENDLIST"]).encode() # type: ignore[attr-defined]
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.shutdown()
thread.join(timeout=5)
DOWNLOAD_CANCELLED.clear()
def download(
server: ThreadingHTTPServer,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
key: str,
memory: MemoryVault,
vault: bool,
kind: type[Video] | type[Audio] = Video,
) -> Video | Audio:
"""Download the track with the hook of dl; with ``vault``, ``memory`` is the key's source."""
keys = resolver(vaults_of(memory, MemoryVault(name="other")))
monkeypatch.setattr(verify, "DECRYPT_HOOK", keys.decrypt_verified)
drm = CustomDRM("example", kids=[KID])
drm.content_keys[KID] = key
if vault:
keys.vaults.supplied(KID, key, memory)
track = kind(url=f"{base(server)}v.m3u8", language="en", descriptor=kind.Descriptor.HLS)
track.drm = [drm]
ctx = make_ctx(tmp_path, "plugin.ts")
ctx.license_widevine = lambda *a, **kw: None
try:
HLS.download_track(track, ctx)
finally:
keys.wait_vault_writes()
return track
@pytest.mark.parametrize("vault", [False, True], ids=["licence", "vault"])
def test_a_wrong_plugin_key_stops_the_track_and_leaves_no_output(server, tmp_path, monkeypatch, vault: bool) -> None:
memory = MemoryVault({KID: WRONG} if vault else {})
with pytest.raises(
click.ClickException, match=f"^The EXAMPLE content key of KID {KID.hex} does not decrypt track "
) as e:
download(server, tmp_path, monkeypatch, WRONG, memory, vault)
assert getattr(e.value, "error_code", None) == APIErrorCode.DRM_ERROR
assert not (tmp_path / "plugin.ts").exists()
assert memory.told == [(KID, WRONG)] and not memory.added
def test_the_right_plugin_key_keeps_a_track_that_decodes(server, tmp_path, monkeypatch) -> None:
track = download(server, tmp_path, monkeypatch, KEY, MemoryVault(), vault=False)
assert track.path.read_bytes() == b"".join(PLAIN)
def test_a_track_the_plugin_finish_leaves_unjudged_judges_and_copies_no_vault_key(
server, tmp_path, monkeypatch
) -> None:
monkeypatch.setattr(
plugins, "PLUGINS", {"example": dataclasses.replace(EXAMPLE, finish=lambda drm, path, track: False)}
)
memory = MemoryVault({KID: WRONG})
download(server, tmp_path, monkeypatch, WRONG, memory, vault=True, kind=Audio)
assert (tmp_path / "plugin.ts").exists() and not memory.told
+25
View File
@@ -0,0 +1,25 @@
"""A held-key plugin DRM in an export: the import rebuilds it with the key the plugin lets an export carry."""
from __future__ import annotations
import json
from pathlib import Path
from tests.core.test_export import make_title, make_writer, written
from tests.core.test_import_track_keys import import_service
from unshackle.core.drm import CustomDRM
KEY = "00112233445566778899aabbccddeeff"
def test_an_imported_held_key_plugin_track_keeps_its_key(example_plugins: None, tmp_path: Path) -> None:
title = make_title()
writer = make_writer(tmp_path)
writer.record(title, title.tracks.videos[0], CustomDRM("other", data={"key": KEY, "secret": "server only"}))
export = written(writer)
entry = json.loads(export.read_text(encoding="utf8"))["titles"][0]
assert entry["x-unshackle"]["drm"] == [{"system": "other", "kids": [], "label": "OTHER", "data": {"key": KEY}}]
assert entry.get("drm", []) == [] and "server only" not in json.dumps(entry)
(drm,) = import_service(export).rebuild_drm({"id": "v1", "type": "Video"}, "movie-1") or []
assert isinstance(drm, CustomDRM) and (drm.plugin_id, drm.data) == ("other", {"key": KEY})
+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
+5 -3
View File
@@ -15,7 +15,7 @@ from unshackle.core import binaries
from unshackle.core import service as service_mod
from unshackle.core.api.errors import categorize_exception
from unshackle.core.api.input_bridge import InputBridge, NoUserBridge
from unshackle.core.drm import ClearKeyCENC, MonaLisa, PlayReady, Widevine, decrypters
from unshackle.core.drm import ClearKeyCENC, CustomDRM, PlayReady, Widevine, decrypters
from unshackle.core.import_service import ImportService, manifest_fetch_error
from unshackle.core.proxies.gluetun import Gluetun
from unshackle.core.proxies.nordvpn import NordVPN
@@ -108,14 +108,16 @@ def test_an_import_key_the_export_lacks_is_a_drm_error() -> None:
PlayReady.Exceptions.KIDNotFound,
PlayReady.Exceptions.DeviceRevoked,
ClearKeyCENC.Exceptions.KIDNotFound,
MonaLisa.Exceptions.TicketNotFound,
MonaLisa.Exceptions.KeyExtractionFailed,
],
)
def test_a_drm_exception_class_is_a_drm_error(error: type[Exception]) -> None:
assert categorize_exception(error("PSSH was not found in track data.")).error_code == APIErrorCode.DRM_ERROR
def test_a_drm_plugin_that_is_not_installed_is_a_drm_error() -> None:
assert code_of(lambda: CustomDRM("example")) == APIErrorCode.DRM_ERROR
def test_a_missing_decrypter_is_a_drm_error(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(binaries, "Mp4decrypt", None)
monkeypatch.setattr(binaries, "ShakaPackager", None)
+69
View File
@@ -0,0 +1,69 @@
"""An import stops on a DRM system it does not know, and never turns it into a Widevine stub."""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any
import click
import pytest
from tests.core.test_import_bridged import export_bridged
from tests.core.test_import_track_keys import import_service, keys_by_track, write_export
from unshackle.core.remote_protocol import APIErrorCode
def rewrite(export: Path, change: Any) -> None:
doc = json.loads(export.read_text(encoding="utf8"))
change(doc["titles"][0])
export.write_text(json.dumps(doc), encoding="utf8")
def own_system(entry: dict[str, Any]) -> None:
for d in entry["x-unshackle"]["drm"]:
d["system"] = "FutureDRM"
def shared_system(entry: dict[str, Any]) -> None:
del entry["x-unshackle"]["drm"]
entry["drm"] = [*entry["drm"], {"system": "futuredrm"}]
@pytest.mark.parametrize("row_kids", [True, False], ids=["row-kids", "stub-fallback"])
@pytest.mark.parametrize(
("change", "system"), [(own_system, "FutureDRM"), (shared_system, "futuredrm")], ids=["own", "shared"]
)
def test_an_unknown_export_system_stops_the_track(tmp_path: Path, row_kids: bool, change: Any, system: str) -> None:
export, video_id = export_bridged(tmp_path, row_kids=row_kids)
rewrite(export, change)
svc = import_service(export)
with pytest.raises(click.ClickException, match=rf"^Unknown DRM system '{system}' in the export$") as e:
svc.rebuild_drm({"id": video_id, "type": "Video"}, "movie-1")
assert e.value.error_code is APIErrorCode.DRM_ERROR # type: ignore[attr-defined]
@pytest.mark.parametrize(
("change", "system"), [(own_system, "FutureDRM"), (shared_system, "futuredrm")], ids=["own", "shared"]
)
def test_an_unknown_export_system_stops_a_reparsed_dash_title(tmp_path: Path, change: Any, system: str) -> None:
export = write_export(tmp_path)
rewrite(export, change)
svc = import_service(export)
with pytest.raises(click.ClickException, match=rf"^Unknown DRM system '{system}' in the export$"):
keys_by_track(svc)
def test_a_shared_hls_aes_entry_still_imports(tmp_path: Path) -> None:
export, video_id = export_bridged(tmp_path)
def hls_aes(entry: dict[str, Any]) -> None:
entry["drm"] = [*entry["drm"], {"system": "aes-128"}]
del entry["x-unshackle"]["drm"]
rewrite(export, hls_aes)
assert import_service(export).rebuild_drm({"id": video_id, "type": "Video"}, "movie-1")
-119
View File
@@ -1,119 +0,0 @@
"""A MonaLisa track whose content key does not decode stops after the merge, through ``HLS.download_track``.
The segments are a real HEVC clip in the synthetic BBTS format, and the built-in decrypter decrypts them.
"""
from __future__ import annotations
import subprocess
import threading
from collections.abc import Iterator
from http.server import ThreadingHTTPServer
from pathlib import Path
from uuid import UUID
import click
import pytest
from tests.core import bbts_sample
from tests.core.key_resolver import MemoryVault, resolver, vaults_of
from tests.core.test_rolling_merge_hls_ism import _Handler, base, make_ctx
from unshackle.core import binaries
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import MonaLisa, monalisa, verify
from unshackle.core.manifests import HLS
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks import Audio, Video
from unshackle.core.tracks.track import DownloadContext
from unshackle.core.utils.subprocess import ffmpeg_decodes
pytestmark = pytest.mark.skipif(binaries.FFMPEG is None, reason="requires ffmpeg")
KID = UUID(hex="11111111111111111111111111111111")
WRONG = "5a" * 16
FPS = 25
@pytest.fixture(scope="module")
def segments(tmp_path_factory: pytest.TempPathFactory) -> list[bytes]:
"""Three 2 s BBTS segments of a 640x360 HEVC clip, encrypted with bbts_sample.KEY and a fixed IV."""
clip = tmp_path_factory.mktemp("bbts") / "clip.hevc"
x265 = "keyint=50:min-keyint=50:scenecut=0:bframes=0:aud=1:info=0:repeat-headers=1:log-level=none"
source = f"testsrc2=size=640x360:rate={FPS}:duration=6"
subprocess.run(
[str(binaries.FFMPEG), "-nostdin", "-v", "error", "-f", "lavfi", "-i", source, "-c:v", "libx265"]
+ ["-preset", "ultrafast", "-pix_fmt", "yuv420p", "-x265-params", x265, "-f", "hevc", str(clip)],
check=True,
)
return bbts_sample.bbts_segments(clip.read_bytes(), bbts_sample.IVS[0], 2 * FPS, FPS)
@pytest.fixture
def server(segments: list[bytes]) -> Iterator[ThreadingHTTPServer]:
srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
lines = ["#EXTM3U", "#EXT-X-VERSION:3", "#EXT-X-TARGETDURATION:2"]
srv.routes = {} # type: ignore[attr-defined]
for i, segment in enumerate(segments):
srv.routes[f"/{i}.ts"] = segment # type: ignore[attr-defined]
lines += ["#EXTINF:2.0,", f"{i}.ts"]
srv.routes["/v.m3u8"] = "\n".join([*lines, "#EXT-X-ENDLIST"]).encode() # type: ignore[attr-defined]
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
yield srv
srv.shutdown()
thread.join(timeout=5)
DOWNLOAD_CANCELLED.clear()
def download(
server: ThreadingHTTPServer,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
key: str,
memory: MemoryVault,
vault: bool,
kind: type[Video] | type[Audio] = Video,
) -> tuple[Video | Audio, DownloadContext]:
"""Download the track with the built-in decrypter and the hook of dl; with ``vault``, ``memory`` is the key's source."""
monkeypatch.setattr(monalisa, "local_tool", lambda: None)
keys = resolver(vaults_of(memory, MemoryVault(name="other")))
monkeypatch.setattr(verify, "DECRYPT_HOOK", keys.decrypt_verified)
drm = MonaLisa(kid=KID)
drm.content_keys[KID] = key
if vault:
keys.vaults.supplied(KID, key, memory)
track = kind(url=f"{base(server)}v.m3u8", language="en", descriptor=kind.Descriptor.HLS)
track.drm = [drm]
ctx = make_ctx(tmp_path, "monalisa.ts")
ctx.license_widevine = lambda *a, **kw: None
try:
HLS.download_track(track, ctx)
finally:
keys.wait_vault_writes()
return track, ctx
@pytest.mark.parametrize("vault", [False, True], ids=["licence", "vault"])
def test_a_wrong_monalisa_key_stops_the_track_and_leaves_no_output(server, tmp_path, monkeypatch, vault: bool) -> None:
memory = MemoryVault({KID: WRONG} if vault else {})
refused = f"^The MonaLisa content key of KID {KID.hex} does not decrypt track "
with pytest.raises(click.ClickException, match=refused) as e:
download(server, tmp_path, monkeypatch, WRONG, memory, vault)
assert getattr(e.value, "error_code", None) == APIErrorCode.DRM_ERROR
assert not (tmp_path / "monalisa.ts").exists()
assert memory.told == [(KID, WRONG)] and not memory.added
def test_the_right_monalisa_key_keeps_a_track_that_decodes(server, tmp_path, monkeypatch) -> None:
track, ctx = download(server, tmp_path, monkeypatch, bbts_sample.KEY.hex(), MemoryVault(), vault=False)
assert track.path == ctx.save_path and ffmpeg_decodes(ctx.save_path)
def test_an_audio_track_judges_and_copies_no_vault_key(server, tmp_path, monkeypatch) -> None:
"""BBTS leaves audio clear, so a decode of an audio track proves no key."""
memory = MemoryVault({KID: WRONG})
download(server, tmp_path, monkeypatch, WRONG, memory, vault=True, kind=Audio)
assert (tmp_path / "monalisa.ts").exists() and not memory.told
-265
View File
@@ -1,265 +0,0 @@
"""MonaLisa's decrypt step: the external tool, or the built-in decrypter when this machine has none."""
import functools
import hashlib
import subprocess
from pathlib import Path
from uuid import UUID
import pytest
from tests.core import bbts_sample
from unshackle.core.drm import monalisa
from unshackle.core.drm.monalisa import MonaLisa, bbtsdecrypt_command
from unshackle.core.utils import subprocess as tool_runner
pytestmark = pytest.mark.unit
@pytest.fixture
def track(tmp_path: Path) -> Path:
path = tmp_path / "track.mp4"
path.write_bytes(b"cipher")
return path
@pytest.fixture
def make_drm(monkeypatch: pytest.MonkeyPatch):
"""Build a MonaLisa with a known key; extract_keys needs a real device file, so it is skipped."""
monkeypatch.setattr(MonaLisa, "extract_keys", lambda self: None)
def build(tool: Path, **kwargs) -> MonaLisa:
drm = MonaLisa("ticket", Path("unused.mld"), tool, **kwargs)
drm._kid = UUID(int=1)
drm.content_keys[drm._kid] = "00" * 16
return drm
return build
@pytest.fixture
def tool(tmp_path: Path) -> Path:
path = tmp_path / "decrypt-tool"
path.write_bytes(b"")
return path
def fake_tool(monkeypatch: pytest.MonkeyPatch, output: bytes, returncode: int = 0, stderr: bytes = b"") -> None:
"""Replace the tool run with one that writes `output` to the `-o` path."""
def run(cmd, **kwargs):
Path(cmd[cmd.index("-o") + 1]).write_bytes(output)
return subprocess.CompletedProcess(cmd, returncode, b"", stderr)
monkeypatch.setattr(tool_runner.subprocess, "run", run)
def test_a_missing_tool_raises_and_keeps_the_file(make_drm, track: Path, tmp_path: Path) -> None:
with pytest.raises(RuntimeError, match="tool"):
make_drm(tmp_path / "absent").decrypt(track)
assert track.read_bytes() == b"cipher"
@pytest.mark.parametrize(
("output", "returncode", "stderr"),
[(b"partial", 1, b"bad key"), (b"", 0, b"")],
ids=["non-zero exit", "empty output"],
)
def test_a_failed_run_keeps_the_ciphertext(
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch, output: bytes, returncode: int, stderr: bytes
) -> None:
fake_tool(monkeypatch, output, returncode, stderr)
with pytest.raises(RuntimeError, match=f"failed: {stderr.decode()}"):
make_drm(tool).decrypt(track)
assert track.read_bytes() == b"cipher"
assert not track.with_name("track_decrypted.mp4").exists()
def test_a_timeout_keeps_the_ciphertext_and_hides_the_key(
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
def hang(cmd, **kwargs):
raise subprocess.TimeoutExpired(cmd, kwargs.get("timeout"))
monkeypatch.setattr(tool_runner.subprocess, "run", hang)
drm = make_drm(tool)
with pytest.raises(RuntimeError, match="timed out after 60s") as raised:
drm.decrypt_segment(track)
assert drm.key_pair not in str(raised.value)
assert raised.value.__suppress_context__
assert track.read_bytes() == b"cipher"
def test_a_good_run_replaces_the_file_and_drops_the_temp_output(
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
fake_tool(monkeypatch, b"plain")
make_drm(tool).decrypt(track)
assert track.read_bytes() == b"plain"
assert not track.with_name("track_decrypted.mp4").exists()
@pytest.mark.parametrize("build", ["constructor", "from_ticket"])
def test_a_service_command_builder_replaces_the_default_command(
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch, build: str
) -> None:
commands = []
def run(cmd, **kwargs):
commands.append((cmd, kwargs["timeout"]))
Path(cmd[-1]).write_bytes(b"plain")
return subprocess.CompletedProcess(cmd, 0, b"", b"")
def command(tool_path, src, dst, kid, key):
return [tool_path, f"{kid}/{key}", src, dst]
monkeypatch.setattr(tool_runner.subprocess, "run", run)
if build == "constructor":
drm = make_drm(tool, command_builder=command, segment_decrypt=False)
else:
drm = MonaLisa.from_ticket("ticket", Path("unused.mld"), tool, command, False)
drm._kid = UUID(int=1)
drm.content_keys[drm._kid] = "00" * 16
assert not drm.supports_segment_decrypt
drm.decrypt(track)
output = track.with_name("track_decrypted.mp4")
assert commands == [([str(tool), f"{drm.kid.hex}/{drm.key}", str(track), str(output)], None)]
assert track.read_bytes() == b"plain"
@pytest.mark.parametrize("segment_decrypt", [True, False])
def test_every_in_place_file_is_decrypted(
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch, segment_decrypt: bool
) -> None:
fake_tool(monkeypatch, b"plain")
drm = make_drm(tool, segment_decrypt=segment_decrypt)
other = track.with_name("other.mp4")
other.write_bytes(b"cipher")
drm.decrypt(track)
drm.decrypt(other)
assert (track.read_bytes(), other.read_bytes()) == (b"plain", b"plain")
assert not drm.track_decrypted
def test_a_track_that_the_service_decrypted_is_not_decrypted_again(
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
fake_tool(monkeypatch, b"plain")
drm = make_drm(tool, segment_decrypt=False)
out = track.with_name("out.mp4")
drm.decrypt(track, out)
fake_tool(monkeypatch, b"twice")
drm.decrypt(out)
assert drm.track_decrypted and out.read_bytes() == b"plain"
def test_a_segment_tool_decrypts_every_file_it_gets_an_output_path_for(
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
fake_tool(monkeypatch, b"plain")
drm = make_drm(tool)
outputs = [track.with_name(f"{i}.mp4") for i in range(2)]
for output in outputs:
drm.decrypt(track, output)
assert [output.read_bytes() for output in outputs] == [b"plain", b"plain"]
def local_tools(monkeypatch: pytest.MonkeyPatch, bbtsdecrypt: Path | None, shaka: Path | None) -> None:
"""Make `bbtsdecrypt` and `shaka` the binaries that this machine has."""
monkeypatch.setattr(monalisa, "local_tool", functools.cache(monalisa.local_tool.__wrapped__))
monkeypatch.setattr(
monalisa.binaries, "find", lambda *names, **kwargs: bbtsdecrypt if "bbtsdecrypt" in names else None
)
monkeypatch.setattr(monalisa.binaries, "ShakaPackager", shaka, raising=False)
def test_a_drm_without_a_tool_runs_the_bbtsdecrypt_of_this_machine_per_segment(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, track: Path
) -> None:
tool = tmp_path / "bbtsdecrypt"
tool.write_bytes(b"")
local_tools(monkeypatch, tool, None)
commands = []
def run(cmd, **kwargs):
commands.append(cmd)
Path(cmd[cmd.index("-o") + 1]).write_bytes(b"plain")
return subprocess.CompletedProcess(cmd, 0, b"", b"")
monkeypatch.setattr(tool_runner.subprocess, "run", run)
drm = MonaLisa(kid=UUID(int=1))
drm.content_keys[UUID(int=1)] = "ab" * 16
assert drm.supports_segment_decrypt
drm.decrypt(track)
output = track.with_name("track_decrypted.mp4")
assert commands == [[str(arg) for arg in bbtsdecrypt_command(tool, track, output, UUID(int=1).hex, "ab" * 16)]]
assert track.read_bytes() == b"plain"
def built_in_drm(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> MonaLisa:
"""A MonaLisa on a machine with no bbtsdecrypt but a shaka-packager built with BBTS, keyed for the synthetic file."""
shaka = tmp_path / "packager"
shaka.write_bytes(b"..bbts_decryptor.cc..")
local_tools(monkeypatch, None, shaka)
drm = MonaLisa(kid=UUID(int=1))
drm.content_keys[UUID(int=1)] = bbts_sample.KEY.hex()
return drm
def test_with_no_tool_the_built_in_decrypter_decrypts_each_segment(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
drm = built_in_drm(monkeypatch, tmp_path)
segment = tmp_path / "0.ts"
segment.write_bytes(bbts_sample.bbts())
assert drm.tool is None and drm.supports_segment_decrypt
drm.decrypt_segment(segment)
assert hashlib.sha256(segment.read_bytes()).hexdigest() == bbts_sample.GOLDEN[bbts_sample.HEVC]
assert [path.name for path in tmp_path.iterdir() if path.suffix == ".ts"] == ["0.ts"]
def test_with_no_tool_a_whole_track_drm_decrypts_the_merged_file_built_in(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
drm = built_in_drm(monkeypatch, tmp_path)
drm._segment_decrypt = False
merged = tmp_path / "merged.ts"
merged.write_bytes(bbts_sample.bbts())
assert not drm.supports_segment_decrypt
drm.decrypt(merged)
assert hashlib.sha256(merged.read_bytes()).hexdigest() == bbts_sample.GOLDEN[bbts_sample.HEVC]
def test_a_failed_built_in_run_keeps_the_ciphertext(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, track: Path
) -> None:
def fail(src: Path, dst: Path, key: bytes) -> None:
dst.write_bytes(b"partial")
raise OSError("disk full")
drm = built_in_drm(monkeypatch, tmp_path)
monkeypatch.setattr(monalisa, "decrypt_bbts", fail)
with pytest.raises(OSError, match="disk full"):
drm.decrypt(track)
assert track.read_bytes() == b"cipher"
assert not track.with_name("track_decrypted.mp4").exists()
def test_a_copy_with_only_a_kid_holds_no_key_until_one_arrives() -> None:
drm = MonaLisa(kid=UUID(int=1).hex)
assert (drm.kid, drm.kids, drm.key, drm.content_keys) == (UUID(int=1), [UUID(int=1)], None, {})
drm.content_keys[UUID(int=1)] = "ab" * 16
assert drm.key_pair == f"{UUID(int=1).hex}:{'ab' * 16}"
def test_no_ticket_and_no_kid_is_refused() -> None:
with pytest.raises(MonaLisa.Exceptions.TicketNotFound):
MonaLisa()
-118
View File
@@ -1,118 +0,0 @@
"""A MonaLisa licence runs one CDM at a time per process, and a MonaLisa track survives an export and an import."""
from __future__ import annotations
import hashlib
import json
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any
from uuid import UUID
import pytest
from tests.core import bbts_sample
from tests.core.test_export import make_title, make_writer, written
from tests.core.test_import_track_keys import import_service
from tests.core.test_monalisa_decrypt import local_tools
from unshackle.core.drm import monalisa
from unshackle.core.drm.monalisa import MonaLisa
KID = UUID(int=1)
KEY = bbts_sample.KEY.hex()
def test_concurrent_licences_open_one_cdm_at_a_time(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
open_sessions = 0
peak = 0
guard = threading.Lock()
class OneSessionCDM:
def __init__(self, device_path: Path) -> None:
pass
def open(self) -> int:
nonlocal open_sessions, peak
with guard:
open_sessions += 1
peak = max(peak, open_sessions)
time.sleep(0.05)
return 1
def extract_keys(self, ticket: str) -> dict[str, str]:
return {"kid": KID.hex, "key": KEY}
def close(self, session_id: int) -> None:
nonlocal open_sessions
with guard:
open_sessions -= 1
monkeypatch.setattr(monalisa, "MonaLisaCDM", OneSessionCDM)
start = threading.Barrier(4)
def licence(_: int) -> MonaLisa:
start.wait()
return MonaLisa("EXAMPLE-TICKET", tmp_path / "device.mld")
with ThreadPoolExecutor(4) as pool:
drms = list(pool.map(licence, range(4)))
assert peak == 1
assert [drm.key_pair for drm in drms] == [f"{KID.hex}:{KEY}"] * 4
def test_a_failed_licence_raises_one_error_and_frees_the_lock(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
class TrappingCDM:
def __init__(self, device_path: Path) -> None:
pass
def open(self) -> int:
return 1
def extract_keys(self, ticket: str) -> dict[str, str]:
raise RuntimeError("wasm trap")
def close(self, session_id: int) -> None:
pass
monkeypatch.setattr(monalisa, "MonaLisaCDM", TrappingCDM)
with pytest.raises(MonaLisa.Exceptions.KeyExtractionFailed, match="^Failed to extract keys: wasm trap$"):
MonaLisa("EXAMPLE-TICKET", tmp_path / "device.mld")
assert not monalisa.CDM_LOCK.locked()
def export_monalisa(tmp_path: Path) -> Path:
"""Export a title whose video carries a licensed MonaLisa DRM with a service tool and whole-track mode."""
title = make_title()
drm = MonaLisa(kid=KID, tool_path=tmp_path / "service-tool", command_builder=lambda *a: [], segment_decrypt=False)
drm.content_keys[KID] = KEY
writer = make_writer(tmp_path)
writer.record(title, title.tracks.videos[0], drm)
return written(writer)
def test_the_export_holds_the_kid_and_no_tool_or_callable(tmp_path: Path) -> None:
entry = json.loads(export_monalisa(tmp_path).read_text(encoding="utf8"))["titles"][0]
assert entry["x-unshackle"]["drm"] == [{"system": "MonaLisa", "kids": [KID.hex]}]
assert entry.get("drm", []) == []
assert "service-tool" not in json.dumps(entry)
def test_an_imported_monalisa_track_decrypts_with_the_exported_key(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
export = export_monalisa(tmp_path)
local_tools(monkeypatch, None, None)
drm: Any = import_service(export).rebuild_drm({"id": "v1", "type": "Video"}, "movie-1")[0] # type: ignore[index]
segment = tmp_path / "0.ts"
segment.write_bytes(bbts_sample.bbts())
assert isinstance(drm, MonaLisa)
assert (drm.key_pair, drm.tool, drm.supports_segment_decrypt) == (f"{KID.hex}:{KEY}", None, True)
drm.decrypt_segment(segment)
assert hashlib.sha256(segment.read_bytes()).hexdigest() == bbts_sample.GOLDEN[bbts_sample.HEVC]
+38
View File
@@ -0,0 +1,38 @@
"""Core names no plugin DRM: a plugin brings its own names, and its docs live in its own README."""
from __future__ import annotations
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
NAMES = re.compile("|".join(["mona" + "lisa", "bb" + "ts", "blow" + "fish", "stripe " + "cipher", r"\.ml" + "d"]), re.I)
PLACES = ["unshackle", "tests", "docs", "mkdocs.yml", "README.md", "pyproject.toml"]
SKIP = {"plugins", "_repos", "__pycache__"}
def files() -> list[Path]:
found = []
for place in PLACES:
path = ROOT / place
if path.is_file():
found.append(path)
elif path.is_dir():
found += [
p
for p in path.rglob("*")
if p.is_file()
and not SKIP & set(p.relative_to(path).parts)
and p.suffix in {".py", ".md", ".yml", ".yaml", ".toml", ".json", ".txt"}
]
return found
def test_core_tests_and_docs_name_no_plugin_drm() -> None:
hits = [
f"{path.relative_to(ROOT)}:{n}"
for path in files()
for n, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), 1)
if NAMES.search(line)
]
assert hits == []
+212
View File
@@ -0,0 +1,212 @@
"""A DRM plugin's own device files and its default device: found from a folder or a zip, after the operator's files."""
from __future__ import annotations
import dataclasses
import zipfile
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
from tests.drm_plugins import EXAMPLE, OTHER, ExampleDevice
from tests.remote.sessions import launch_session
from unshackle.commands.dl import dl
from unshackle.core import plugins
from unshackle.core.api import handlers, key_policy
from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.cdm import loader
from unshackle.core.config import config
from unshackle.core.plugins import load_folder
from unshackle.core.remote_protocol import Licensor
pytestmark = pytest.mark.unit
SOURCE = """from importlib import resources
from unshackle.core.plugins import DrmPlugin
PLUGIN = DrmPlugin(
id="example",
label="EXAMPLE",
licensing="local",
media="own",
mode="segment",
decrypt=lambda drm, src, dst: None,
device_suffix=".exd",
load_device=lambda path: path.read_bytes(),
devices=lambda: resources.files(__name__) / "devices",
default_device="EXAMPLE_DEFAULT",
)
"""
def bundled_folder(folder: Path) -> None:
path = folder / "bundled_pkg"
(path / "devices").mkdir(parents=True)
(path / "__init__.py").write_text(SOURCE, encoding="utf-8")
(path / "devices" / "EXAMPLE_DEFAULT.exd").write_bytes(b"bundled")
def bundled_zip(folder: Path) -> None:
with zipfile.ZipFile(folder / "bundled_pkg.zip", "w") as z:
z.writestr("bundled_pkg/__init__.py", SOURCE)
z.writestr("bundled_pkg/devices/EXAMPLE_DEFAULT.exd", b"bundled")
def folders(tmp_path: Path) -> SimpleNamespace:
return SimpleNamespace(remote_cdm=[], directories=SimpleNamespace(wvds=tmp_path / "wvds", prds=tmp_path / "prds"))
@pytest.mark.parametrize("make", [bundled_folder, bundled_zip], ids=["folder", "zip"])
def test_a_plugin_loads_its_bundled_device_from_a_folder_or_a_zip(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, make: Any
) -> None:
make(tmp_path)
monkeypatch.setattr(plugins, "PLUGINS", load_folder(tmp_path))
device = loader.find_device("EXAMPLE_DEFAULT", folders(tmp_path))
assert device is not None and device.system == "example"
assert loader.load_local_cdm("EXAMPLE_DEFAULT", device.system, device.source) == b"bundled"
assert loader.find_device("EXAMPLE_OTHER", folders(tmp_path)) is None
assert loader.default_device("example") == "EXAMPLE_DEFAULT"
def test_an_operator_device_file_comes_before_the_bundled_one(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
bundled_folder(tmp_path)
monkeypatch.setattr(plugins, "PLUGINS", load_folder(tmp_path))
app_config = folders(tmp_path)
app_config.directories.prds.mkdir()
(app_config.directories.prds / "EXAMPLE_DEFAULT.exd").write_bytes(b"operator")
device = loader.find_device("EXAMPLE_DEFAULT", app_config)
assert device is not None and device.source == app_config.directories.prds / "EXAMPLE_DEFAULT.exd"
def test_devices_need_a_device_suffix() -> None:
with pytest.raises(ValueError, match="has devices but no device_suffix"):
dataclasses.replace(OTHER, default_device="EXAMPLE_DEFAULT")
@pytest.fixture
def bundled(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
"""EXAMPLE with its own devices EXAMPLE_DEFAULT (its default) and EXAMPLE_V3, and no operator device files."""
devices = tmp_path / "bundled"
devices.mkdir()
for name in ("EXAMPLE_DEFAULT", "EXAMPLE_V3"):
(devices / f"{name}.exd").write_bytes(name.encode())
example = dataclasses.replace(EXAMPLE, devices=lambda: devices, default_device="EXAMPLE_DEFAULT")
monkeypatch.setattr(plugins, "PLUGINS", {"example": example})
monkeypatch.setattr(config, "remote_cdm", [], raising=False)
monkeypatch.setattr(config, "cdm", {}, raising=False)
monkeypatch.setattr(config.directories, "wvds", tmp_path / "wvds")
monkeypatch.setattr(config.directories, "prds", tmp_path / "prds")
return tmp_path
def local_device(cdm: dict) -> str:
"""The name of the device ``dl`` gives the EXAMPLE service for the EXAMPLE plugin system."""
config.cdm = cdm
cmd = dl.__new__(dl)
cmd.vaults, cmd.service, cmd.profile, cmd.log = None, "EXAMPLE", None, SimpleNamespace(debug=lambda msg: None)
device = cmd.cdm_for("example")
assert isinstance(device, ExampleDevice)
return device.path.read_bytes().decode()
def server_device(cdm: dict) -> str:
"""The name of the device the server loads for the EXAMPLE plugin system."""
config.cdm = cdm
device = handlers.load_full_cdm("EXAMPLE", None, "example")
assert isinstance(device, ExampleDevice)
return device.path.read_bytes().decode()
@pytest.mark.parametrize("device", [local_device, server_device], ids=["local", "server"])
@pytest.mark.parametrize(
("cdm", "name"),
[
({}, "EXAMPLE_DEFAULT"),
({"default": "wv_other"}, "EXAMPLE_DEFAULT"),
({"EXAMPLE": {"widevine": "wv_other"}}, "EXAMPLE_DEFAULT"),
({"EXAMPLE": {"example": "EXAMPLE_V3"}}, "EXAMPLE_V3"),
({"EXAMPLE": "EXAMPLE_V3"}, "EXAMPLE_V3"),
],
ids=["no entry", "default entry of another system", "entry of another system", "plugin key", "device name"],
)
def test_a_service_gets_the_plugin_default_unless_its_entry_names_a_plugin_device(
monkeypatch: pytest.MonkeyPatch, bundled: Path, device: Any, cdm: dict, name: str
) -> None:
monkeypatch.setattr(loader, "find_device", wrap_unknown(loader.find_device))
load = loader.load_local_cdm
monkeypatch.setattr(
loader,
"load_local_cdm",
lambda n, s, p: SimpleNamespace(is_playready=False) if n[:3] == "wv_" else load(n, s, p),
)
assert device(cdm) == name
def wrap_unknown(find: Any) -> Any:
"""A ``wv_`` name is a Widevine device that the test never loads."""
return lambda name, app_config=None: (
loader.Device("widevine", Path(name)) if name.startswith("wv_") else find(name, app_config)
)
def test_an_operator_file_named_like_the_default_replaces_it(monkeypatch: pytest.MonkeyPatch, bundled: Path) -> None:
(bundled / "wvds").mkdir()
(bundled / "wvds" / "EXAMPLE_DEFAULT.exd").write_bytes(b"operator")
assert local_device({}) == "operator"
def test_an_api_key_cdm_entry_can_name_a_plugin_device(bundled: Path) -> None:
assert key_policy._identity_error("k", {"cdm": {"EXAMPLE": {"example": "EXAMPLE_V3"}}}, config) is None
assert "no example device named 'wv_other'" in str(
key_policy._identity_error("k", {"cdm": {"EXAMPLE": {"example": "wv_other"}}}, config)
)
@pytest.mark.parametrize(
("licensor", "grant", "served"),
[
(Licensor.SERVER_CDM, False, True),
(Licensor.NO_DEVICE, True, False),
(Licensor.CLIENT_DEVICE, True, False),
(None, True, True),
(None, False, False),
],
ids=["server cdm session", "vault session", "client device session", "list with grant", "list without grant"],
)
def test_a_served_service_gets_a_device_by_system_only_where_the_server_licenses(
monkeypatch: pytest.MonkeyPatch, licensor: Licensor | None, grant: bool, served: bool
) -> None:
seen: dict = {}
loads: list = []
def instantiate(parent_ctx: Any, *a: Any) -> Any:
seen["ctx"] = parent_ctx
return SimpleNamespace(authenticate=lambda cookies, credential: None)
monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {})
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *a: (None, []))
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: loads.append(a[:3]))
monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace())
monkeypatch.setattr(handlers, "instantiate_service", instantiate)
monkeypatch.setattr(handlers, "request_policy", lambda request: KeyPolicy({"server_cdm": grant}))
if licensor is None:
handlers.launch_served(handlers.LIST, {}, "EXAMPLE", "t", None)
else:
launch_session("EXAMPLE", "t", {}, licensor=licensor)
cdm_for = seen["ctx"].obj.cdm_for
assert (cdm_for is not None) == served
if cdm_for:
cdm_for("example")
assert loads[-1] == ("EXAMPLE", None, "example")
+20 -47
View File
@@ -11,6 +11,7 @@ The last test runs Track.download for each descriptor and counts the TRACK_DOWNL
from __future__ import annotations
import dataclasses
import threading
from concurrent.futures import Future
from functools import partial
@@ -28,11 +29,11 @@ from pywidevine.pssh import PSSH
from tests.core.key_resolver import MemoryVault, resolver, vaults_of
from tests.core.test_hls_kid_from_init import KEY_LINE, no_kid_pssh
from tests.core.test_ism_init import piff_fragment
from unshackle.core import constants
from tests.drm_plugins import EXAMPLE, FINISHED
from unshackle.core import constants, plugins
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.downloaders import requests as requests_downloader
from unshackle.core.drm import ClearKeyCENC, MonaLisa, Widevine
from unshackle.core.drm import ClearKeyCENC, CustomDRM, Widevine
from unshackle.core.drm import cenc as cenc_module
from unshackle.core.drm import key_resolution, verify
from unshackle.core.events import events
@@ -344,14 +345,9 @@ def test_dash_segment_decrypt_writes_decrypted_init_and_only_checks(server, tmp_
assert [decrypt for _, decrypt in decrypted] == [False]
@pytest.mark.parametrize("site", ["session-drm", "monalisa"])
def test_hls_licence_failure_cancels_the_other_tracks(server, tmp_path, monkeypatch, site):
if site == "monalisa":
# extract_keys needs a real device file
monkeypatch.setattr(MonaLisa, "extract_keys", lambda self: None)
drm = MonaLisa("ticket", Path("unused.mld"))
else:
drm = widevine()
@pytest.mark.parametrize("site", ["session-drm", "plugin"])
def test_hls_licence_failure_cancels_the_other_tracks(server, tmp_path, example_plugins, site):
drm = CustomDRM("example") if site == "plugin" else widevine()
track = hls_track(server, False)
track.drm = [drm]
licensed: list[object] = []
@@ -369,15 +365,14 @@ def test_hls_licence_failure_cancels_the_other_tracks(server, tmp_path, monkeypa
assert ctx.statuses[-2:] == ["LICENSING", "[red]FAILED"]
@pytest.mark.parametrize("mode", ["segments", "core-whole", "service-whole", "service-whole-keeps-cipher"])
@pytest.mark.parametrize("mode", ["segment", "track"])
@pytest.mark.parametrize("playlist", ["plain", "discontinuity", "init", "method-none"])
@pytest.mark.parametrize("hooked", [False, True])
def test_hls_monalisa_decrypts_every_segment_once(server, tmp_path, monkeypatch, mode, playlist, hooked):
"""A segment tool runs per segment, a whole-track tool on each merged block or in the service's downloader.
def test_hls_plugin_decrypts_every_segment_once(server, tmp_path, monkeypatch, example_plugins, mode, playlist, hooked):
"""A segment plugin decrypts each segment, then finishes the merged file; a track plugin decrypts each merged block.
With the hook of dl installed, the content key resolver runs the whole-track decrypt.
"""
monkeypatch.setattr(MonaLisa, "extract_keys", lambda self: None)
monkeypatch.setattr(
HLS,
"merge_segments",
@@ -387,11 +382,11 @@ def test_hls_monalisa_decrypts_every_segment_once(server, tmp_path, monkeypatch,
)
runs: list[bytes] = []
def run_tool(self, path, output_path=None, *, timeout=None):
runs.append(path.read_bytes())
(output_path or path).write_bytes(path.read_bytes().swapcase())
def run_tool(drm, src, dst):
runs.append(src.read_bytes())
dst.write_bytes(src.read_bytes().swapcase())
monkeypatch.setattr(MonaLisa, "_execute_decrypt", run_tool)
monkeypatch.setattr(plugins, "PLUGINS", {"example": dataclasses.replace(EXAMPLE, mode=mode, decrypt=run_tool)})
hook = resolver(vaults_of(MemoryVault())).decrypt_verified if hooked else None
monkeypatch.setattr(verify, "DECRYPT_HOOK", hook)
@@ -411,40 +406,18 @@ def test_hls_monalisa_decrypts_every_segment_once(server, tmp_path, monkeypatch,
lines += ["#EXTINF:4.0,", f"part{i}.m4s"]
server.routes["/v.m3u8"] = "\n".join([*lines, "#EXT-X-ENDLIST"]).encode()
track = Video(url=f"{base(server)}v.m3u8", language="en", codec=Video.Codec.HEVC, descriptor=Video.Descriptor.HLS)
drm = MonaLisa("ticket", Path("unused.mld"), segment_decrypt=mode == "segments")
drm._kid = KID
drm = CustomDRM("example", kids=[KID])
drm.content_keys[KID] = "00" * 16
track.drm = [drm]
if mode.startswith("service"):
def download(**kwargs):
segments = []
for status in requests_downloader(**kwargs):
if status.get("file_downloaded"):
segments.append(status["file_downloaded"])
yield status
folder = segments[0].parent
merged = folder.parent / "segments_encrypted.ts"
merged.write_bytes(b"".join(s.read_bytes() for s in sorted(segments)))
out = folder.parent / "out.mp4"
drm.decrypt(merged, out)
for segment in segments:
segment.unlink()
out.rename(folder / "000.mp4")
if mode == "service-whole":
merged.unlink()
track.downloader = download
ctx = make_ctx(tmp_path, "monalisa.mp4")
ctx = make_ctx(tmp_path, "plugin.mp4")
ctx.license_widevine = lambda *a, **kw: None
HLS.download_track(track, ctx)
init = b"INIT" if playlist == "init" and not mode.startswith("service") else b""
init = b"INIT" if playlist == "init" else b""
plain = b"".join(parts).swapcase()
assert ctx.save_path.read_bytes() == (init.swapcase() if mode == "core-whole" else init) + plain
expected = {"segments": len(parts), "core-whole": 2 if playlist == "discontinuity" else 1}
assert len(runs) == expected.get(mode, 1)
assert ctx.save_path.read_bytes() == (init.swapcase() if mode == "track" else init) + plain
assert len(runs) == (len(parts) if mode == "segment" else 2 if playlist == "discontinuity" else 1)
assert len(FINISHED) == (mode == "segment")
def test_hls_aes128_keeps_post_merge(server, tmp_path, monkeypatch):
+16 -14
View File
@@ -15,7 +15,7 @@ import pytest
from tests.core.test_all_drm import playready, widevine
from unshackle.core import temp
from unshackle.core.constants import DOWNLOAD_CANCELLED
from unshackle.core.drm import ClearKey, ClearKeyCENC, ClearKeyCTR, MonaLisa, verify
from unshackle.core.drm import ClearKey, ClearKeyCENC, ClearKeyCTR, CustomDRM, verify
from unshackle.core.events import events
from unshackle.core.manifests import segment_pipeline
from unshackle.core.manifests.segment_pipeline import (
@@ -222,13 +222,14 @@ def test_a_short_rolling_merge_raises_and_removes_the_output(tmp_path):
check_merged(merger, 0, SimpleNamespace(id="EXAMPLE"), ctx, "EXAMPLE") # type: ignore[arg-type]
WV, PR, CKC, ML, AES, CTR = "Widevine", "PlayReady", "ClearKeyCENC", "MonaLisa", "ClearKey", "ClearKeyCTR"
WV, PR, CKC, AES, CTR = "Widevine", "PlayReady", "ClearKeyCENC", "ClearKey", "ClearKeyCTR"
LOCAL, HELD = "example", "other"
PSSH_KID = UUID(hex="22222222222222222222222222222222")
PROBED_KID = UUID(hex="33333333333333333333333333333333")
URL, DASH_, HLS_, ISM_ = (Track.Descriptor.URL, Track.Descriptor.DASH, Track.Descriptor.HLS, Track.Descriptor.ISM)
def make_drm(system: str, monkeypatch: pytest.MonkeyPatch) -> Any:
def make_drm(system: str) -> Any:
"""One DRM of each system; every one that names a KID names PSSH_KID."""
if system == WV:
return widevine(PSSH_KID)
@@ -236,9 +237,8 @@ def make_drm(system: str, monkeypatch: pytest.MonkeyPatch) -> Any:
return playready(PSSH_KID)
if system == CKC:
return ClearKeyCENC(kids=[PSSH_KID])
if system == ML:
monkeypatch.setattr(MonaLisa, "extract_keys", lambda self: None)
return MonaLisa("EXAMPLE", Path("unused.mld"))
if system in (LOCAL, HELD):
return CustomDRM(system, data={"key": bytes(16).hex()})
if system == CTR:
return ClearKeyCTR(None, bytes(16), b"OggS")
return ClearKey(key=bytes(16))
@@ -249,14 +249,16 @@ def licence_calls(tmp_path: Path) -> tuple[DownloadContext, list[tuple[Any, Any]
return make_ctx(tmp_path, license_widevine=lambda drm, track_kid: calls.append((drm, track_kid))), calls
LICENSED = {URL: {WV, PR, CKC, CTR}, DASH_: {WV, PR, CKC}, HLS_: {WV, PR, ML}, ISM_: {WV, PR}}
LICENSED = {URL: {WV, PR, CKC, CTR}, DASH_: {WV, PR, CKC}, HLS_: {WV, PR, LOCAL}, ISM_: {WV, PR}}
@pytest.mark.parametrize("descriptor", list(LICENSED), ids=lambda d: d.name)
@pytest.mark.parametrize("system", [WV, PR, CKC, ML, AES, CTR])
def test_the_licence_step_licenses_the_systems_each_manifest_kind_licensed(tmp_path, monkeypatch, descriptor, system):
@pytest.mark.parametrize("system", [WV, PR, CKC, LOCAL, HELD, AES, CTR])
def test_the_licence_step_licenses_the_systems_each_manifest_kind_licensed(
tmp_path, example_plugins, descriptor, system
):
ctx, calls = licence_calls(tmp_path)
drm = make_drm(system, monkeypatch)
drm = make_drm(system)
license_drm(SimpleNamespace(descriptor=descriptor, id="EXAMPLE"), drm, ctx) # type: ignore[arg-type]
@@ -281,7 +283,7 @@ def test_the_licence_step_skips_a_track_with_no_drm(tmp_path):
(HLS_, WV, KID, "no probe", KID),
(HLS_, PR, None, "no probe", PSSH_KID),
(HLS_, WV, None, None, PSSH_KID),
(HLS_, ML, KID, PROBED_KID, None),
(HLS_, LOCAL, KID, PROBED_KID, None),
(ISM_, PR, None, "no probe", PSSH_KID),
],
ids=[
@@ -292,11 +294,11 @@ def test_the_licence_step_skips_a_track_with_no_drm(tmp_path):
"hls-init-kid",
"hls-drm-kid",
"hls-probe-misses",
"monalisa-no-kid",
"plugin-own-media-no-kid",
"ism-drm-kid",
],
)
def test_the_licence_step_finds_the_track_kid(tmp_path, monkeypatch, descriptor, system, kid, probed, expected):
def test_the_licence_step_finds_the_track_kid(tmp_path, example_plugins, descriptor, system, kid, probed, expected):
ctx, calls = licence_calls(tmp_path)
probes: list[bool] = []
@@ -305,7 +307,7 @@ def test_the_licence_step_finds_the_track_kid(tmp_path, monkeypatch, descriptor,
return probed
track = SimpleNamespace(descriptor=descriptor, id="EXAMPLE")
license_drm(track, make_drm(system, monkeypatch), ctx, kid, None if probed == "no probe" else probe) # type: ignore[arg-type]
license_drm(track, make_drm(system), ctx, kid, None if probed == "no probe" else probe) # type: ignore[arg-type]
assert [c[1] for c in calls] == [expected]
assert not (kid and probes), "a KID the caller holds needs no probe"
+7 -3
View File
@@ -17,7 +17,7 @@ from tests.remote.key_source import MemoryKeySource, remote_keys
from unshackle.commands import dl as dl_module
from unshackle.core.config import config
from unshackle.core.credential import Credential
from unshackle.core.drm import BlowfishStripe, ClearKeyCTR, PlayReady, Widevine
from unshackle.core.drm import ClearKeyCTR, CustomDRM, PlayReady, Widevine
from unshackle.core.drm.cenc import drm_stub
from unshackle.core.import_service import ImportService
from unshackle.core.service import Service
@@ -262,7 +262,7 @@ def ctr() -> ClearKeyCTR:
[
({"v": [ctr()], "a": [ctr()]}, "widevine", "Using keys from the server; no local CDM required"),
(
{"v": [BlowfishStripe(key=bytes(8))], "a": [ctr()]},
{"v": ["held-plugin"], "a": [ctr()]},
"playready",
"Using keys from the server; no local CDM required",
),
@@ -273,16 +273,20 @@ def ctr() -> ClearKeyCTR:
"Using server CDM (Widevine); no local CDM required",
),
({"v": [drm_stub("playready", KIDS)]}, "playready", "Using server CDM (PlayReady); no local CDM required"),
({"a": [ctr()]}, "example", "Using server CDM (EXAMPLE); no local CDM required"),
],
ids=["whole-file", "whole-file-playready-server", "video-drm-not-loaded", "mixed", "playready"],
ids=["whole-file", "whole-file-playready-server", "video-drm-not-loaded", "mixed", "playready", "plugin"],
)
def test_dl_names_the_server_cdm_only_for_a_title_that_needs_one(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
example_plugins: None,
drm: dict[str, Any],
server_cdm_type: str,
line: str,
) -> None:
held = CustomDRM("other", data={"key": bytes(8).hex()})
drm = {kind: [held if d == "held-plugin" else d for d in drms] for kind, drms in drm.items()}
lines: list[str] = []
monkeypatch.setattr(logging.getLogger("test_kind_only"), "info", lambda msg, *a, **k: lines.append(msg))
monkeypatch.setattr(dl_module.login, "save_cookies", lambda *a: None)
+80 -11
View File
@@ -20,8 +20,9 @@ from pywidevine.pssh import PSSH as WidevinePSSH
from tests.core.test_zero_kid_fallback import _playready_pssh
from unshackle.core import wire
from unshackle.core.config import config
from unshackle.core.drm import BlowfishStripe, ClearKeyCENC, ClearKeyCTR, PlayReady, Widevine
from unshackle.core.drm import ClearKeyCENC, ClearKeyCTR, CustomDRM, PlayReady, Widevine
from unshackle.core.import_service import ImportService
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.titles import Episode, Movie, Song
from unshackle.core.titles.music import SONG_FIELDS
from unshackle.core.tracks import Audio, Chapter, Subtitle, Tracks, Video
@@ -59,7 +60,7 @@ pytestmark = pytest.mark.unit
VIDEO_KID = UUID("00112233-4455-6677-8899-aabbccddeeff")
AUDIO_KID = UUID("ffeeddcc-bbaa-9988-7766-554433221100")
VIDEO_KEY = "0123456789abcdef0123456789abcdef"
BLOWFISH_KEY = bytes(range(16))
HELD_KEY = bytes(range(16))
CTR_CIPHER = ClearKeyCTR(None, bytes(range(16, 32)), b"OggS", skip=7, key=bytes(range(16)))
@@ -246,8 +247,8 @@ def drm_fields(drm: Any) -> dict[str, Any]:
out["pssh"] = drm.pssh_b64
if isinstance(drm, ClearKeyCENC):
out["laurl"] = drm.laurl
if isinstance(drm, BlowfishStripe):
out["key"] = drm.key.hex()
if isinstance(drm, CustomDRM):
out.update(plugin=drm.plugin_id, label=drm.label, display_id=drm.display_id, data=drm.data)
return out
@@ -1065,20 +1066,29 @@ def every_drm() -> list:
return [
widevine(VIDEO_KID, keys=True),
playready(VIDEO_KID, AUDIO_KID),
BlowfishStripe(BLOWFISH_KEY),
CustomDRM("other", data={"key": HELD_KEY.hex(), "secret": "server only"}),
local_plugin_drm(),
CTR_CIPHER,
clearkey(),
]
def test_rest_drm_of_each_system() -> None:
def local_plugin_drm() -> CustomDRM:
"""A plugin DRM that a device licensed: its content key and its ticket never leave the machine."""
drm = CustomDRM("example", kids=[VIDEO_KID], display_id="EXAMPLE-1", data={"ticket": "server only"})
drm.content_keys[VIDEO_KID] = VIDEO_KEY
return drm
def test_rest_drm_of_each_system(example_plugins: None) -> None:
drm = every_drm()
assert serialize_drm(drm) == [
*REST_VIDEO["drm"],
{"type": "blowfishstripe", "key": "000102030405060708090a0b0c0d0e0f"},
{"type": "other", "kids": [], "label": "OTHER", "data": {"key": HELD_KEY.hex()}},
{"type": "example", "kids": [VIDEO_KID.hex], "label": "EXAMPLE", "display_id": "EXAMPLE-1"},
{
"type": "clearkeyctr",
"key": BLOWFISH_KEY.hex(),
"key": HELD_KEY.hex(),
"iv": bytes(range(16, 32)).hex(),
"magic": "4f676753",
"skip": 7,
@@ -1105,13 +1115,22 @@ def test_export_drm_of_each_system() -> None:
}
def test_reconstruct_rest_drm() -> None:
def test_reconstruct_rest_drm(example_plugins: None) -> None:
drm = every_drm()
rebuilt = reconstruct_drm(json_copy(serialize_drm(drm)))
custom = {"class": "CustomDRM", "kids": [], "content_keys": {}, "display_id": None}
assert [drm_fields(d) for d in rebuilt] == [
WIDEVINE_FIELDS,
PLAYREADY_FIELDS,
{"class": "BlowfishStripe", "kids": [], "content_keys": {}, "key": "000102030405060708090a0b0c0d0e0f"},
{**custom, "plugin": "other", "label": "OTHER", "data": {"key": HELD_KEY.hex()}},
{
**custom,
"plugin": "example",
"label": "EXAMPLE",
"kids": [VIDEO_KID.hex],
"display_id": "EXAMPLE-1",
"data": {},
},
{"class": "ClearKeyCTR", "kids": [], "content_keys": {}},
]
@@ -1153,7 +1172,6 @@ def test_export_drm_decode_takes_the_stored_keys() -> None:
"data, message",
[
({"system": "Widevine"}, "Cannot reconstruct DRM without a stored PSSH."),
({"system": "Nope", "pssh_b64": "x"}, "Unsupported DRM system for reconstruction: 'Nope'"),
],
)
def test_export_drm_decode_refuses(data: dict[str, Any], message: str) -> None:
@@ -1161,6 +1179,57 @@ def test_export_drm_decode_refuses(data: dict[str, Any], message: str) -> None:
drm_from_dict(data)
class FutureDRM:
def __init__(self) -> None:
self.kids = [VIDEO_KID]
self.content_keys = {VIDEO_KID: VIDEO_KEY}
def test_rest_drm_of_an_unknown_class_has_no_content_keys() -> None:
assert serialize_drm([FutureDRM()]) == [{"type": "futuredrm", "kids": [str(VIDEO_KID)]}]
@pytest.mark.parametrize("drm", [widevine(VIDEO_KID), playready(VIDEO_KID), clearkey()], ids=lambda d: type(d).__name__)
def test_rest_drm_keeps_the_content_keys_of_the_classes_that_carry_them(drm: Any) -> None:
drm.content_keys[VIDEO_KID] = VIDEO_KEY
(info,) = serialize_drm([drm])
assert info["content_keys"] == {str(VIDEO_KID): VIDEO_KEY}
def test_reconstruct_rest_drm_leaves_hls_clearkey_to_the_manifest() -> None:
assert reconstruct_drm([{"type": "clearkey"}]) == []
@pytest.mark.parametrize(
"entry", [{"type": "futuredrm", "kids": [str(VIDEO_KID)]}, {"type": "futuredrm", "pssh": "AAAA"}]
)
def test_reconstruct_rest_drm_refuses_an_unknown_type(entry: dict[str, Any]) -> None:
with pytest.raises(click.ClickException, match=r"^Unknown DRM type 'futuredrm' from the server$") as e:
reconstruct_drm([entry])
assert e.value.error_code is APIErrorCode.DRM_ERROR # type: ignore[attr-defined]
@pytest.mark.parametrize("kids", [[1], ["not hex"]], ids=["number", "text"])
def test_reconstruct_rest_drm_refuses_a_bad_plugin_kid_with_one_line(example_plugins: None, kids: list) -> None:
with pytest.raises(click.ClickException, match=r"^Bad example DRM entry from the server: ") as e:
reconstruct_drm([{"type": "example", "kids": kids}])
assert e.value.error_code is APIErrorCode.DRM_ERROR # type: ignore[attr-defined]
def test_a_track_with_an_unknown_drm_type_stops_the_title() -> None:
with pytest.raises(click.ClickException, match="futuredrm"):
build_tracks({"video": [{**REST_VIDEO, "drm": [{"type": "futuredrm", "kids": [str(VIDEO_KID)]}]}]})
@pytest.mark.parametrize(
"data", [{"system": "FutureDRM", "kids": [VIDEO_KID.hex]}, {"system": "FutureDRM", "pssh_b64": "x"}]
)
def test_export_drm_decode_refuses_an_unknown_system(data: dict[str, Any]) -> None:
with pytest.raises(click.ClickException, match=r"^Unknown DRM system 'FutureDRM' in the export$") as e:
drm_from_dict(data)
assert e.value.error_code is APIErrorCode.DRM_ERROR # type: ignore[attr-defined]
def test_rest_attachment_by_url() -> None:
attachment = Attachment(
url="https://img.example/poster.jpg", name="Poster", mime_type="image/jpeg", description="Cover"
+75
View File
@@ -0,0 +1,75 @@
"""Test DRM plugins: EXAMPLE licenses locally and decrypts per segment, OTHER holds its key and decrypts a whole file.
Both use a repeating XOR of the content key, so a test can build ciphertext with ``xor``.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
from uuid import UUID
from unshackle.core.drm.custom import CustomDRM
from unshackle.core.plugins import DrmPlugin
FINISHED: list[Path] = []
def xor(data: bytes, key: bytes) -> bytes:
return bytes(b ^ key[i % len(key)] for i, b in enumerate(data))
def drm_key(drm: CustomDRM) -> bytes:
key = drm.key or drm.data.get("key")
if not key:
raise ValueError(f"No {drm.label} key")
return bytes.fromhex(key)
def decrypt(drm: CustomDRM, src: Path, dst: Path) -> None:
dst.write_bytes(xor(src.read_bytes(), drm_key(drm)))
def licence(drm: CustomDRM, cdm: ExampleDevice) -> None:
"""The EXAMPLE device turns the ticket into one KID and its key."""
kid = UUID(hex=drm.data["ticket"])
drm.kids = [kid]
drm.content_keys[kid] = cdm.path.read_bytes().hex()
def finish(drm: CustomDRM, path: Path, track: Any) -> bool:
FINISHED.append(path)
return True
class ExampleDevice:
"""A plugin CDM: the plugin id as its system, the device file it was built from and its name."""
drm_system = "example"
def __init__(self, path: Path) -> None:
self.path = path
self.device_name = path.stem
EXAMPLE = DrmPlugin(
id="example",
label="EXAMPLE",
licensing="local",
media="own",
mode="segment",
decrypt=decrypt,
finish=finish,
licence=licence,
device_suffix=".exd",
load_device=ExampleDevice,
)
OTHER = DrmPlugin(
id="other",
label="OTHER",
licensing="held",
media="own",
mode="track",
decrypt=decrypt,
wire_data=("key",),
)
+1 -1
View File
@@ -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):
@@ -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
+2
View File
@@ -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)