feat(drm): license MonaLisa over --remote on the server and decrypt it in core, with or without bbtsdecrypt

This commit is contained in:
imSp4rky
2026-12-02 15:23:58 -07:00
parent b1497c77a2
commit ac4425cdca
29 changed files with 1518 additions and 121 deletions
+118
View File
@@ -0,0 +1,118 @@
"""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]