refactor(dl): move content-key resolution into core/drm/key_resolution.py

This commit is contained in:
imSp4rky
2026-11-24 14:44:47 -07:00
parent 55138f95c2
commit bbe58930b5
11 changed files with 1582 additions and 1469 deletions
+68
View File
@@ -0,0 +1,68 @@
"""A ContentKeyResolver with stand-ins for the run it serves, for tests of content-key resolution."""
from __future__ import annotations
from types import SimpleNamespace
from typing import Any, Callable, Optional
from uuid import UUID
from rich.table import Table
from unshackle.core.cdm.detect import cdm_type_stub
from unshackle.core.drm.key_resolution import ContentKeyResolver
class NoVaults:
"""No key vault: every lookup misses and nothing is stored."""
sources: dict = {}
flagged: set = set()
def __bool__(self) -> bool:
return False
def __len__(self) -> int:
return 0
def get_key(self, kid: UUID) -> tuple[None, None]:
return None, None
def stand_in_service(licence: Optional[Callable[..., Any]] = None) -> SimpleNamespace:
"""A service whose Widevine and PlayReady licence functions both call ``licence``."""
licence = licence or (lambda **_: None)
return SimpleNamespace(
get_widevine_license=licence,
get_playready_license=licence,
get_widevine_service_certificate=lambda **_: None,
get_clearkey_license=lambda **_: None,
session=None,
)
WIDEVINE = cdm_type_stub("widevine")
def resolver(
vaults: Any = None,
cdm: Any = WIDEVINE,
licence: Optional[Callable[..., Any]] = None,
cdm_for: Optional[Callable[..., Any]] = None,
tag: str = "TEST",
**flags: Any,
) -> ContentKeyResolver:
"""A ContentKeyResolver over ``vaults`` (none by default) and a Widevine CDM, with an empty run key cache."""
ContentKeyResolver.LICENSE_KEY_CACHE.clear()
ContentKeyResolver.DRM_LOCKS.clear()
cdms = SimpleNamespace(
cdm=cdm,
cdm_for=cdm_for or (lambda system, quality=None: cdm_type_stub(system)),
)
return ContentKeyResolver(NoVaults() if vaults is None else vaults, cdms, stand_in_service(licence), tag, **flags)
def key_table() -> Table:
"""A download table that holds the selected tracks row, as dl builds it."""
table = Table.grid()
table.add_row("")
return table
+90 -132
View File
@@ -1,11 +1,9 @@
"""--all-drm: each track licenses with Widevine and with PlayReady, through one wrapper in dl."""
"""--all-drm: each track licenses with Widevine and with PlayReady, through one wrapper in content-key resolution."""
from __future__ import annotations
import base64
import logging
from collections import defaultdict
from functools import partial
from types import SimpleNamespace
from typing import Any, Optional
from uuid import UUID
@@ -15,11 +13,11 @@ import pytest
from pyplayready.system.pssh import PSSH as PR_PSSH
from pywidevine.cdm import Cdm as WidevineCdm
from pywidevine.pssh import PSSH
from rich.table import Table
from tests.core.key_resolver import NoVaults, key_table, resolver
from unshackle.commands.dl import dl
from unshackle.core.api.handlers import load_full_cdm, resolve_server_cdm, validate_download_parameters
from unshackle.core.cdm.detect import cdm_type_stub, is_widevine_cdm
from unshackle.core.cdm.detect import is_widevine_cdm
from unshackle.core.drm import PlayReady, Widevine
from unshackle.core.manifests import HLS
@@ -52,91 +50,104 @@ def playready(kid: UUID = KID) -> PlayReady:
return PlayReady(pssh=PR_PSSH(base64.b64decode(pro)), pssh_b64=pro)
class Prepare:
"""Stands in for prepare_drm: records each call and gives the content key, or fails for one DRM system."""
class Run:
"""A ContentKeyResolver whose DRM objects license with fixed content keys, for one track in an --all-drm run."""
def __init__(self, fail: Optional[type] = None) -> None:
self.fail = fail
self.calls: list[tuple[str, bool, dict[UUID, str]]] = []
def __init__(self, vault: Optional[dict[UUID, str]] = None, **flags: Any) -> None:
self.requests: list[str] = []
self.held: list[dict[UUID, str]] = []
self.vault_queries: list[UUID] = []
self.keys = resolver(Vault(self.get_key(vault or {})), tag="EXAMPLE", **flags)
def __call__(self, drm: Any, track_kid: Optional[UUID] = None, **kwargs: Any) -> None:
forced = bool(kwargs.get("force") and kwargs.get("cdm_only"))
self.calls.append((type(drm).__name__, forced, dict(drm.content_keys)))
if type(drm) is self.fail:
raise ValueError("licence refused")
drm.content_keys[KID] = KEY
def get_key(self, vault: dict[UUID, str]) -> Any:
def get_key(kid: UUID) -> tuple[Optional[str], Optional[str]]:
self.vault_queries.append(kid)
return vault.get(kid), "vault" if kid in vault else None
def forced(self) -> list[str]:
return [name for name, forced, _ in self.calls if forced]
return get_key
def drm(self, drm: Any, keys: Optional[dict[UUID, str]] = None, fail: bool = False) -> Any:
"""Give ``drm`` a licence that returns ``keys`` (KID:KEY by default), or that is refused."""
def get_content_keys(cdm: Any, certificate: Any = None, licence: Any = None) -> None:
self.requests.append(type(drm).__name__)
self.held.append(dict(drm.content_keys))
if fail:
raise ValueError("licence refused")
drm.content_keys.update({KID: KEY} if keys is None else keys)
drm.get_content_keys = get_content_keys
return drm
def run(self, drm: Any, *others: Any, track_kid: Optional[UUID] = KID) -> None:
track = SimpleNamespace(drm=[drm, *others], id="track", height=None)
self.keys.licence_for(track, None, key_table(), all_drm=True)(drm, track_kid=track_kid)
@pytest.fixture
def cmd() -> dl:
cmd = dl.__new__(dl)
cmd.log = SimpleNamespace(warning=lambda *a: None, debug=lambda *a: None)
cmd.cdm = object()
cmd.all_drm_attempted = defaultdict(set)
cmd.all_drm_warned = set()
dl.DRM_LOCKS.clear()
return cmd
class Vault(NoVaults):
"""A key vault that answers from ``get_key`` and stores nothing."""
def __init__(self, get_key: Any) -> None:
self.get_key = get_key # type: ignore[method-assign]
def test_cdm_only_licenses_each_drm_system_although_a_content_key_is_held(cmd: dl) -> None:
wv, pr = widevine(), playready()
def test_cdm_only_licenses_each_drm_system_although_a_content_key_is_held() -> None:
run = Run(cdm_only=True)
wv, pr = run.drm(widevine()), run.drm(playready())
wv.content_keys[KID] = VAULT_KEY
prepare = Prepare()
cmd.licence_all_drm(prepare, SimpleNamespace(drm=[wv, pr]), False, wv, track_kid=KID, force=True)
run.run(wv, pr)
assert prepare.forced() == ["Widevine", "PlayReady"]
assert all(held == {} for _, _, held in prepare.calls)
assert run.requests == ["Widevine", "PlayReady"]
assert run.held == [{}, {}]
assert wv.content_keys == {KID: KEY} and pr.content_keys == {KID: KEY}
def test_a_second_track_with_the_same_kids_sends_no_request(cmd: dl) -> None:
prepare = Prepare(fail=PlayReady)
def test_a_second_track_with_the_same_kids_sends_no_request() -> None:
run = Run(cdm_only=True, best_available=True)
for _ in range(2):
wv, pr = widevine(), playready()
cmd.licence_all_drm(prepare, SimpleNamespace(drm=[wv, pr]), True, wv, track_kid=KID, force=True)
run.run(run.drm(widevine()), run.drm(playready(), fail=True))
assert prepare.forced() == ["Widevine", "PlayReady"]
assert len(prepare.calls) == 4
assert run.requests == ["Widevine", "PlayReady"]
def test_a_drm_system_that_fails_stops_the_title(cmd: dl) -> None:
wv, pr = widevine(), playready()
def test_a_drm_system_that_fails_stops_the_title() -> None:
run = Run(cdm_only=True)
wv, pr = run.drm(widevine(), fail=True), run.drm(playready())
wv.content_keys[KID] = VAULT_KEY
with pytest.raises(ValueError, match="licence refused"):
cmd.licence_all_drm(Prepare(fail=Widevine), SimpleNamespace(drm=[wv, pr]), False, wv, track_kid=KID, force=True)
run.run(wv, pr)
assert wv.content_keys == {KID: VAULT_KEY}
def test_with_tolerance_the_other_drm_system_gives_the_content_key(cmd: dl) -> None:
wv, pr = widevine(), playready()
loaded = cmd.cdm
def test_with_tolerance_the_other_drm_system_gives_the_content_key() -> None:
run = Run(best_available=True)
wv, pr = run.drm(widevine(), fail=True), run.drm(playready())
loaded = run.keys.cdms.cdm
cmd.licence_all_drm(Prepare(fail=Widevine), SimpleNamespace(drm=[wv, pr]), True, wv, track_kid=KID)
run.run(wv, pr)
assert wv.content_keys == {KID: KEY}
assert cmd.cdm is loaded
assert run.keys.cdms.cdm is loaded
def test_with_tolerance_a_track_with_no_content_key_still_fails(cmd: dl) -> None:
wv = widevine()
def test_with_tolerance_a_track_with_no_content_key_still_fails() -> None:
run = Run(best_available=True)
with pytest.raises(ValueError, match="licence refused"):
cmd.licence_all_drm(Prepare(fail=Widevine), SimpleNamespace(drm=[wv]), True, wv, track_kid=KID)
run.run(run.drm(widevine(), fail=True))
def test_a_drm_type_with_no_cdm_goes_straight_through(cmd: dl) -> None:
prepare = Prepare()
def test_a_drm_type_with_no_cdm_goes_straight_through() -> None:
run = Run()
other = SimpleNamespace(content_keys={})
cmd.licence_all_drm(prepare, SimpleNamespace(drm=[other, playready()]), False, other)
run.run(other, run.drm(playready()), track_kid=None)
assert prepare.calls == [("SimpleNamespace", False, {})]
assert run.requests == []
assert other.content_keys == {}
def hls_keys(*lines: str) -> list[Any]:
@@ -162,90 +173,36 @@ def test_hls_requests_no_key_uri_for_the_other_drm_system() -> None:
assert HLS.alternate_drm(keys, widevine()) == []
def test_a_playready_track_with_two_widevine_objects_licenses(cmd: dl) -> None:
pr = playready()
prepare = Prepare()
def test_a_playready_track_with_two_widevine_objects_licenses() -> None:
run = Run(cdm_only=True)
cmd.licence_all_drm(prepare, SimpleNamespace(drm=[pr, widevine(), widevine()]), False, pr, track_kid=KID)
run.run(run.drm(playready()), run.drm(widevine()), run.drm(widevine()))
assert [name for name, _, _ in prepare.calls] == ["PlayReady", "Widevine"]
class RealPrepare:
"""A dl whose real prepare_drm runs, with the licence of each DRM object replaced by fixed content keys."""
def __init__(self, vault: Optional[dict[UUID, str]] = None) -> None:
self.requests: list[str] = []
self.vault_queries: list[UUID] = []
cmd = dl.__new__(dl)
cmd.log = SimpleNamespace(warning=lambda *a: None, debug=lambda *a: None, info=lambda *a: None)
cmd.debug_logger = None
cmd.service = "EXAMPLE"
cmd.profile = None
cmd.cdm = cdm_type_stub("widevine")
cmd.all_drm_attempted = defaultdict(set)
cmd.all_drm_warned = set()
cmd.vaults = SimpleNamespace(get_key=self.get_key(vault or {}), sources={}, flagged=set())
cmd.flush_vault_writes = lambda writes: None
cmd.cdm_for = lambda system, quality=None: cdm_type_stub(system)
dl.DRM_LOCKS.clear()
dl.LICENSE_KEY_CACHE.clear()
self.cmd = cmd
def get_key(self, vault: dict[UUID, str]) -> Any:
def get_key(kid: UUID) -> tuple[Optional[str], Optional[str]]:
self.vault_queries.append(kid)
return vault.get(kid), "vault" if kid in vault else None
return get_key
def drm(self, drm: Any, keys: dict[UUID, str]) -> Any:
def get_content_keys(cdm: Any, certificate: Any = None, licence: Any = None) -> None:
self.requests.append(type(drm).__name__)
drm.content_keys.update(keys)
drm.get_content_keys = get_content_keys
return drm
def run(self, wv: Any, pr: Any, force: bool = False) -> None:
table = Table.grid()
table.add_row("")
track = SimpleNamespace(drm=[wv, pr], id="track", height=None)
prepare = partial(
self.cmd.prepare_drm,
table=table,
track=track,
title=None,
certificate=None,
licence=lambda **kwargs: b"",
cdm_only=False,
vaults_only=False,
)
self.cmd.licence_all_drm(prepare, track, False, wv, track_kid=KID, force=force)
assert run.requests == ["PlayReady", "Widevine"]
def test_cdm_only_licenses_each_drm_system_and_does_not_read_the_vault() -> None:
real = RealPrepare(vault={KID: VAULT_KEY})
wv, pr = real.drm(widevine(), {KID: KEY}), real.drm(playready(), {KID: KEY})
run = Run(vault={KID: VAULT_KEY}, cdm_only=True)
wv, pr = run.drm(widevine()), run.drm(playready())
real.run(wv, pr, force=True)
run.run(wv, pr)
assert real.requests == ["Widevine", "PlayReady"]
assert real.vault_queries == []
assert run.requests == ["Widevine", "PlayReady"]
assert run.vault_queries == []
assert wv.content_keys == {KID: KEY} and pr.content_keys == {KID: KEY}
assert is_widevine_cdm(real.cmd.cdm)
assert is_widevine_cdm(run.keys.cdms.cdm)
real.run(real.drm(widevine(), {KID: KEY}), real.drm(playready(), {KID: KEY}), force=True)
run.run(run.drm(widevine()), run.drm(playready()))
assert real.requests == ["Widevine", "PlayReady"]
assert run.requests == ["Widevine", "PlayReady"]
def test_the_other_drm_system_can_return_a_different_set_of_kids() -> None:
real = RealPrepare()
wv = real.drm(widevine(), {KID: KEY})
pr = real.drm(playready(OTHER_KID), {OTHER_KID: OTHER_KEY})
run = Run()
wv = run.drm(widevine())
pr = run.drm(playready(OTHER_KID), {OTHER_KID: OTHER_KEY})
real.run(wv, pr)
run.run(wv, pr)
assert wv.content_keys == {KID: KEY, OTHER_KID: OTHER_KEY}
@@ -257,21 +214,21 @@ def test_the_api_refuses_all_drm_with_one_device() -> None:
def test_a_content_key_in_a_vault_stops_the_challenge_of_each_drm_system() -> None:
real = RealPrepare(vault={KID: VAULT_KEY})
wv, pr = real.drm(widevine(), {KID: KEY}), real.drm(playready(), {KID: KEY})
run = Run(vault={KID: VAULT_KEY})
wv, pr = run.drm(widevine()), run.drm(playready())
real.run(wv, pr)
run.run(wv, pr)
assert real.requests == []
assert run.requests == []
assert wv.content_keys == {KID: VAULT_KEY} and pr.content_keys == {KID: VAULT_KEY}
def test_the_other_drm_system_licenses_only_for_a_kid_with_no_content_key() -> None:
real = RealPrepare()
run = Run()
real.run(real.drm(widevine(), {KID: KEY}), real.drm(playready(), {KID: KEY}))
run.run(run.drm(widevine()), run.drm(playready()))
assert real.requests == ["Widevine"]
assert run.requests == ["Widevine"]
def test_the_init_segment_adds_the_drm_system_the_track_does_not_have(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -348,11 +305,12 @@ def test_drm_from_pssh_without_a_pssh_logs_once_and_keeps_the_drm(caplog: pytest
],
)
def test_the_first_drm_system_of_the_config_entry_loads_first(
cmd: dl, monkeypatch: pytest.MonkeyPatch, entry: dict, expected: str
monkeypatch: pytest.MonkeyPatch, entry: dict, expected: str
) -> None:
monkeypatch.setattr("unshackle.commands.dl.config.cdm", {"EXAMPLE": entry})
monkeypatch.setattr("unshackle.core.cdm.load_cdm", lambda name, **_: name)
monkeypatch.setattr("unshackle.core.config.config.cdm", {"EXAMPLE": entry})
cmd = dl.__new__(dl)
cmd.vaults = None
assert cmd.get_cdm("EXAMPLE") == expected
+19 -19
View File
@@ -1,4 +1,4 @@
"""Unit tests for dl.drm_lock, the per-key-set lock that makes tracks sharing KIDs
"""Unit tests for ContentKeyResolver.drm_lock, the per-key-set lock that makes tracks sharing KIDs
take turns so the second one reads the content keys out of the cache."""
from __future__ import annotations
@@ -9,7 +9,7 @@ from uuid import UUID
import pytest
from unshackle.commands.dl import dl
from unshackle.core.drm.key_resolution import ContentKeyResolver
pytestmark = pytest.mark.unit
@@ -31,40 +31,40 @@ class NamelessDRM:
@pytest.fixture(autouse=True)
def clean_locks() -> Any:
dl.DRM_LOCKS.clear()
ContentKeyResolver.DRM_LOCKS.clear()
yield
dl.DRM_LOCKS.clear()
ContentKeyResolver.DRM_LOCKS.clear()
def test_same_kid_set_shares_one_lock() -> None:
lock = dl.drm_lock(FakeDRM(kids=[KID_A, KID_B]))
lock = ContentKeyResolver.drm_lock(FakeDRM(kids=[KID_A, KID_B]))
assert isinstance(lock, type(Lock()))
assert dl.drm_lock(FakeDRM(kids=[KID_A, KID_B])) is lock
assert ContentKeyResolver.drm_lock(FakeDRM(kids=[KID_A, KID_B])) is lock
def test_kid_order_does_not_matter() -> None:
first = dl.drm_lock(FakeDRM(kids=[KID_A, KID_B]))
assert dl.drm_lock(FakeDRM(kids=[KID_B, KID_A])) is first
first = ContentKeyResolver.drm_lock(FakeDRM(kids=[KID_A, KID_B]))
assert ContentKeyResolver.drm_lock(FakeDRM(kids=[KID_B, KID_A])) is first
def test_different_kids_get_different_locks() -> None:
assert dl.drm_lock(FakeDRM(kids=[KID_A])) is not dl.drm_lock(FakeDRM(kids=[KID_B]))
assert len(dl.DRM_LOCKS) == 2
assert ContentKeyResolver.drm_lock(FakeDRM(kids=[KID_A])) is not ContentKeyResolver.drm_lock(FakeDRM(kids=[KID_B]))
assert len(ContentKeyResolver.DRM_LOCKS) == 2
def test_no_kids_falls_back_to_content_id() -> None:
lock = dl.drm_lock(FakeDRM(content_id="abc"))
assert dl.drm_lock(FakeDRM(content_id="abc")) is lock
assert dl.drm_lock(FakeDRM(content_id="def")) is not lock
assert set(dl.DRM_LOCKS) == {"abc", "def"}
lock = ContentKeyResolver.drm_lock(FakeDRM(content_id="EXAMPLE"))
assert ContentKeyResolver.drm_lock(FakeDRM(content_id="EXAMPLE")) is lock
assert ContentKeyResolver.drm_lock(FakeDRM(content_id="OTHER")) is not lock
assert set(ContentKeyResolver.DRM_LOCKS) == {"EXAMPLE", "OTHER"}
def test_no_kids_and_no_content_id_falls_back_to_class_name() -> None:
lock = dl.drm_lock(NamelessDRM())
assert dl.drm_lock(NamelessDRM()) is lock
assert set(dl.DRM_LOCKS) == {"NamelessDRM"}
lock = ContentKeyResolver.drm_lock(NamelessDRM())
assert ContentKeyResolver.drm_lock(NamelessDRM()) is lock
assert set(ContentKeyResolver.DRM_LOCKS) == {"NamelessDRM"}
def test_empty_content_id_still_falls_back_to_class_name() -> None:
dl.drm_lock(FakeDRM(content_id=""))
assert set(dl.DRM_LOCKS) == {"FakeDRM"}
ContentKeyResolver.drm_lock(FakeDRM(content_id=""))
assert set(ContentKeyResolver.DRM_LOCKS) == {"FakeDRM"}
+14 -43
View File
@@ -7,7 +7,6 @@ after a failed vault key asks for the licence.
from __future__ import annotations
from functools import partial
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -16,12 +15,12 @@ from uuid import UUID
import click
import pytest
from pywidevine.pssh import PSSH
from rich.table import Table
from tests.core.key_resolver import NoVaults, key_table, resolver
from tests.remote.key_source import remote_keys
from unshackle.commands import dl as dl_module
from unshackle.commands.dl import dl
from unshackle.core.drm import Widevine
from unshackle.core.drm import Widevine, key_resolution
from unshackle.core.drm.key_resolution import ContentKeyResolver
from unshackle.core.import_service import ImportService
from unshackle.core.vaults import Vaults
from unshackle.vaults.SQLite import SQLite
@@ -54,30 +53,15 @@ class FakeDRM:
out.rename(path)
class EmptyVaults:
sources: dict[UUID, Any] = {}
def get_key(self, kid: UUID) -> tuple[None, None]:
return None, None
def make_cmd(monkeypatch: pytest.MonkeyPatch, vaults: Any) -> dl:
"""A dl in server-CDM mode, the mode an import runs in, with a decoder that fails every file."""
monkeypatch.setattr(dl_module.binaries, "FFMPEG", "ffmpeg")
monkeypatch.setattr(dl_module, "ffmpeg_decodes", lambda path, start=None, seconds=3, video=None: False)
cmd = dl.__new__(dl)
cmd.log = SimpleNamespace(warning=print, info=print, debug=print, error=print)
cmd.service = "EXAMPLE"
cmd.vaults = vaults
cmd.vault_cache_tally = None
cmd._remote_service = remote_keys()
dl.LICENSE_KEY_CACHE.clear()
dl.DRM_LOCKS.clear()
return cmd
def make_resolver(monkeypatch: pytest.MonkeyPatch, vaults: Any, track: Any, calls: list[str]) -> ContentKeyResolver:
"""Content-key resolution in server-CDM mode, the mode an import runs in, with a decoder that fails every file."""
monkeypatch.setattr(key_resolution.binaries, "FFMPEG", "ffmpeg")
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", lambda path, start=None, seconds=3, video=None: False)
return resolver(vaults, licence=import_licence(track, calls), source=remote_keys(), tag="EXAMPLE")
def import_licence(track: Any, calls: list[str]) -> Any:
"""The licence dl binds for an import: service_licence calls the ImportService method."""
"""The licence function of an import: the ImportService method, which names the missing KIDs."""
def licence(**kwargs: Any) -> None:
calls.append("licence")
@@ -86,19 +70,6 @@ def import_licence(track: Any, calls: list[str]) -> Any:
return licence
def prepare_drm_for(cmd: dl, track: Any, calls: list[str]) -> Any:
table = Table.grid()
table.add_row("")
return partial(
cmd.prepare_drm,
track=track,
title=None,
licence=import_licence(track, calls),
certificate=None,
table=table,
)
def test_the_error_names_the_kids_without_a_content_key() -> None:
drm = Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=[KID, OTHER]))
drm.content_keys[OTHER] = OTHER_KEY
@@ -113,10 +84,10 @@ def test_the_error_names_the_kids_without_a_content_key() -> None:
def test_the_server_cdm_branch_lets_the_import_error_through(monkeypatch: pytest.MonkeyPatch) -> None:
drm = FakeDRM({})
track = SimpleNamespace(id="vid", drm=[drm])
cmd = make_cmd(monkeypatch, EmptyVaults())
keys = make_resolver(monkeypatch, NoVaults(), track, [])
with pytest.raises(click.ClickException, match=KID.hex):
prepare_drm_for(cmd, track, [])(drm, track_kid=None)
keys.licence_for(track, None, key_table())(drm, track_kid=None)
def test_the_retry_after_a_bad_vault_key_ends_in_the_import_error(
@@ -129,16 +100,16 @@ def test_the_retry_after_a_bad_vault_key_ends_in_the_import_error(
vaults = Vaults("SVC")
vaults.vaults = [SQLite("local", tmp_path / "local.db"), poisoned]
assert vaults.get_key(KID) == (BAD, poisoned)
cmd = make_cmd(monkeypatch, vaults)
drm = FakeDRM({KID: BAD, OTHER: OTHER_KEY})
track = SimpleNamespace(id="vid", drm=[drm])
calls: list[str] = []
keys = make_resolver(monkeypatch, vaults, track, calls)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
with pytest.raises(click.ClickException, match=KID.hex):
cmd.decrypt_verified(drm, path, prepare_drm_for(cmd, track, calls), None)
cmd.wait_vault_writes()
keys.decrypt_verified(drm, path, keys.licence_for(track, None, key_table()), None)
keys.wait_vault_writes()
assert calls == ["licence"]
assert drm.decrypted_with == [{KID: BAD, OTHER: OTHER_KEY}]
+69 -87
View File
@@ -2,9 +2,7 @@
from __future__ import annotations
import logging
import threading
import time
from types import SimpleNamespace
from typing import Any, Callable, Optional
from uuid import UUID
@@ -15,89 +13,72 @@ from pywidevine.pssh import PSSH
from rich.table import Table
from rich.tree import Tree
from tests.core.key_resolver import NoVaults, key_table, resolver
from tests.core.test_all_drm import playready
from unshackle.commands.dl import dl
from unshackle.core.cdm.detect import cdm_type_stub
from unshackle.core.constants import DOWNLOAD_CANCELLED, DownloadCancelled
from unshackle.core.drm import ClearKeyCENC, PlayReady, Widevine
from unshackle.core.drm.key_resolution import ContentKeyResolver
pytestmark = pytest.mark.unit
KID_A, KID_B, KID_C = (UUID(c * 32) for c in "abc")
KEYS = {KID_A: "aa" * 16, KID_B: "bb" * 16, KID_C: "cc" * 16}
DEADLINE = 10
class NoVaults:
sources: dict = {}
class Licences(list):
"""The thread name of each licence. A licence returns every content key of the title."""
def __bool__(self) -> bool:
return False
def get_key(self, kid: UUID) -> tuple[None, None]:
return None, None
def __init__(self) -> None:
super().__init__()
self.second_track_looked_up = threading.Event()
@pytest.fixture
def licences(monkeypatch: pytest.MonkeyPatch) -> list[str]:
"""Each licence returns every content key of the title, after a delay that lets the tracks overlap."""
calls: list[str] = []
def licences(monkeypatch: pytest.MonkeyPatch) -> Licences:
"""The first licence returns only once the other track has asked the vaults, so the tracks overlap."""
calls = Licences()
def get_content_keys(self: Widevine, **_: Any) -> None:
calls.append(threading.current_thread().name)
time.sleep(0.2)
if threading.current_thread().name == "track-0":
calls.second_track_looked_up.wait(DEADLINE)
self.content_keys = dict(KEYS)
monkeypatch.setattr(Widevine, "get_content_keys", get_content_keys)
monkeypatch.setattr(dl, "LICENSE_KEY_CACHE", {})
monkeypatch.setattr(dl, "DRM_LOCKS", {})
DOWNLOAD_CANCELLED.clear()
yield calls
DOWNLOAD_CANCELLED.clear()
@pytest.fixture
def cmd() -> dl:
cmd = dl.__new__(dl)
cmd.log = logging.getLogger(__name__)
cmd.service = "TEST"
cmd.vaults = NoVaults()
cmd.vault_cache_tally = None
cmd._remote_service = None
cmd.debug_logger = None
cmd.cdm = cdm_type_stub("widevine")
return cmd
class TrackVaults(NoVaults):
"""No key vault, but a lookup by the second track sets ``looked_up``."""
def __init__(self, looked_up: threading.Event) -> None:
self.looked_up = looked_up
def get_key(self, kid: UUID) -> tuple[None, None]:
if threading.current_thread().name == "track-1":
self.looked_up.set()
return None, None
def widevine(*kids: UUID) -> Widevine:
return Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=list(kids)))
def prepare(cmd: dl, drm: Widevine, track_kid: Optional[UUID], table: Table, **kwargs: Any) -> None:
cmd.prepare_drm(
drm,
track=SimpleNamespace(drm=[drm]),
title=None,
certificate=lambda **_: None,
licence=lambda **_: None,
table=table,
track_kid=track_kid,
**kwargs,
)
def prepare(keys: ContentKeyResolver, drm: Any, track_kid: Optional[UUID], table: Table, all_drm: bool = False) -> None:
keys.licence_for(SimpleNamespace(drm=[drm]), None, table, all_drm)(drm, track_kid=track_kid)
def new_table() -> Table:
table = Table.grid()
table.add_row("")
return table
def run_together(cmd: dl, *jobs: tuple[Widevine, UUID]) -> tuple[Table, list[BaseException]]:
table = new_table()
def run_together(keys: ContentKeyResolver, *jobs: tuple[Widevine, UUID]) -> tuple[Table, list[BaseException]]:
table = key_table()
errors: list[BaseException] = []
def run(drm: Widevine, kid: UUID) -> None:
try:
prepare(cmd, drm, kid, table)
prepare(keys, drm, kid, table)
except BaseException as e:
errors.append(e)
@@ -114,10 +95,11 @@ def tree_labels(table: Table, kid: UUID) -> list[str]:
return [str(child.label) for tree in trees for child in tree.children if kid.hex in str(child.label)]
def test_one_licence_for_two_pssh_with_different_kids(cmd: dl, licences: list[str]) -> None:
def test_one_licence_for_two_pssh_with_different_kids(licences: Licences) -> None:
keys = resolver(TrackVaults(licences.second_track_looked_up))
first, second = widevine(KID_A, KID_B), widevine(KID_C)
table, errors = run_together(cmd, (first, KID_A), (second, KID_C))
table, errors = run_together(keys, (first, KID_A), (second, KID_C))
assert not errors
assert len(licences) == 1
@@ -125,33 +107,36 @@ def test_one_licence_for_two_pssh_with_different_kids(cmd: dl, licences: list[st
assert any(label.endswith(" from cache") for kid in (KID_A, KID_C) for label in tree_labels(table, kid))
def test_a_track_waiting_for_its_turn_sends_no_licence_after_a_failure(cmd: dl, licences: list[str]) -> None:
def test_a_track_waiting_for_its_turn_sends_no_licence_after_a_failure(licences: Licences) -> None:
DOWNLOAD_CANCELLED.set()
with pytest.raises(DownloadCancelled):
prepare(cmd, widevine(KID_C), KID_C, new_table())
prepare(resolver(), widevine(KID_C), KID_C, key_table())
assert licences == []
def test_force_licenses_again_although_the_keys_are_cached(cmd: dl, licences: list[str]) -> None:
dl.LICENSE_KEY_CACHE.update(KEYS)
def test_force_licenses_again_although_the_keys_are_cached(licences: Licences) -> None:
keys = resolver(cdm_only=True)
ContentKeyResolver.LICENSE_KEY_CACHE.update(KEYS)
prepare(cmd, widevine(KID_C), KID_C, new_table(), force=True)
prepare(keys, widevine(KID_C), KID_C, key_table(), all_drm=True)
assert len(licences) == 1
def test_a_key_label_is_added_once_with_its_marker_and_source() -> None:
tree = Tree("Widevine")
def test_a_key_label_is_added_once_with_its_marker_and_source(licences: Licences) -> None:
keys = resolver()
ContentKeyResolver.LICENSE_KEY_CACHE[KID_A] = KEYS[KID_A]
table = key_table()
dl.add_key_label(tree, KID_A, KEYS[KID_A], KID_A, "from cache")
dl.add_key_label(tree, KID_A, KEYS[KID_A])
dl.add_key_label(tree, KID_B, KEYS[KID_B], KID_A)
prepare(keys, widevine(KID_A, KID_B), KID_B, table)
tree = list(table.columns[0].cells)[-1]
assert [str(child.label) for child in tree.children] == [
f"[text2]{KID_A.hex}:{KEYS[KID_A]}* from cache",
f"[text2]{KID_B.hex}:{KEYS[KID_B]}",
f"[text2]{KID_A.hex}:{KEYS[KID_A]} from cache",
f"[text2]{KID_B.hex}:{KEYS[KID_B]}*",
f"[text2]{KID_C.hex}:{KEYS[KID_C]}",
]
@@ -165,25 +150,22 @@ def test_a_key_label_is_added_once_with_its_marker_and_source() -> None:
ids=["widevine", "playready", "clearkey"],
)
def test_an_all_zero_licence_key_is_dropped(
cmd: dl, monkeypatch: pytest.MonkeyPatch, drm_class: type, build: Callable[[], Any], cdm: Optional[str]
monkeypatch: pytest.MonkeyPatch, drm_class: type, build: Callable[[], Any], cdm: Optional[str]
) -> None:
def get_content_keys(self: Any, **_: Any) -> None:
self.content_keys.update({KID_A: KEYS[KID_A], KID_C: "0" * 32})
monkeypatch.setattr(drm_class, "get_content_keys", get_content_keys)
monkeypatch.setattr(dl, "LICENSE_KEY_CACHE", {})
monkeypatch.setattr(dl, "DRM_LOCKS", {})
keys = resolver(cdm=cdm_type_stub(cdm or "widevine"))
drm = build()
if cdm:
cmd.cdm = cdm_type_stub(cdm)
prepare(cmd, drm, KID_A, new_table())
prepare(keys, drm, KID_A, key_table())
assert drm.content_keys == {KID_A: KEYS[KID_A]}
assert dl.LICENSE_KEY_CACHE == {KID_A: KEYS[KID_A]}
assert ContentKeyResolver.LICENSE_KEY_CACHE == {KID_A: KEYS[KID_A]}
def test_vaults_only_stops_at_the_first_kid_no_vault_holds(cmd: dl, licences: list[str]) -> None:
def test_vaults_only_stops_at_the_first_kid_no_vault_holds(licences: Licences) -> None:
asked: list[UUID] = []
class EmptyVaults(NoVaults):
@@ -191,10 +173,8 @@ def test_vaults_only_stops_at_the_first_kid_no_vault_holds(cmd: dl, licences: li
asked.append(kid)
return None, None
cmd.vaults = EmptyVaults()
with pytest.raises(Widevine.Exceptions.CEKNotFound, match=KID_A.hex):
prepare(cmd, widevine(KID_A, KID_B), KID_A, new_table(), vaults_only=True)
prepare(resolver(EmptyVaults(), vaults_only=True), widevine(KID_A, KID_B), KID_A, key_table())
assert asked == [KID_A]
assert licences == []
@@ -205,48 +185,50 @@ def refuse_licence(self: Widevine, **_: Any) -> None:
def test_a_refused_licence_without_the_track_key_reports_the_licence_error(
cmd: dl, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
monkeypatch.setattr(Widevine, "get_content_keys", refuse_licence)
monkeypatch.setattr(dl, "LICENSE_KEY_CACHE", {KID_B: KEYS[KID_B]})
monkeypatch.setattr(dl, "DRM_LOCKS", {})
table = new_table()
keys = resolver()
ContentKeyResolver.LICENSE_KEY_CACHE[KID_B] = KEYS[KID_B]
table = key_table()
with pytest.raises(click.ClickException, match="^Licence request failed$"):
prepare(cmd, widevine(KID_A, KID_B), KID_A, table)
prepare(keys, widevine(KID_A, KID_B), KID_A, table)
assert not [r for r in caplog.records if r.levelname == "WARNING"]
tree = list(table.columns[0].cells)[-1]
assert "Licence request failed" in str(tree.children[-1].label)
def test_a_held_track_key_needs_no_licence(cmd: dl, licences: list[str], monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(dl, "LICENSE_KEY_CACHE", {KID_A: KEYS[KID_A]})
def test_a_held_track_key_needs_no_licence(licences: Licences) -> None:
keys = resolver()
ContentKeyResolver.LICENSE_KEY_CACHE[KID_A] = KEYS[KID_A]
drm = widevine(KID_A, KID_B)
prepare(cmd, drm, KID_A, new_table())
prepare(keys, drm, KID_A, key_table())
assert licences == []
assert drm.content_keys == {KID_A: KEYS[KID_A]}
def test_force_licenses_a_held_track_key_again(cmd: dl, licences: list[str], monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(dl, "LICENSE_KEY_CACHE", {KID_A: KEYS[KID_A]})
def test_force_licenses_a_held_track_key_again(licences: Licences) -> None:
keys = resolver(cdm_only=True)
ContentKeyResolver.LICENSE_KEY_CACHE[KID_A] = KEYS[KID_A]
prepare(cmd, widevine(KID_A, KID_B), KID_A, new_table(), force=True)
prepare(keys, widevine(KID_A, KID_B), KID_A, key_table(), all_drm=True)
assert len(licences) == 1
def test_a_refused_licence_keeps_the_known_keys_when_the_track_kid_is_unknown(
cmd: dl, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
monkeypatch.setattr(Widevine, "get_content_keys", refuse_licence)
monkeypatch.setattr(dl, "LICENSE_KEY_CACHE", {KID_A: KEYS[KID_A]})
monkeypatch.setattr(dl, "DRM_LOCKS", {})
keys = resolver()
ContentKeyResolver.LICENSE_KEY_CACHE[KID_A] = KEYS[KID_A]
drm = widevine(KID_A, KID_B)
prepare(cmd, drm, None, new_table())
prepare(keys, drm, None, key_table())
assert drm.content_keys == {KID_A: KEYS[KID_A]}
assert [r.getMessage() for r in caplog.records if r.levelname == "WARNING"] == [
+160 -119
View File
@@ -8,9 +8,9 @@ from uuid import UUID
import pytest
from tests.remote.key_source import remote_keys
from unshackle.commands import dl as dl_module
from unshackle.commands.dl import dl
from tests.core.key_resolver import NoVaults, key_table, resolver
from unshackle.core.drm import key_resolution
from unshackle.core.drm.key_resolution import ContentKeyResolver
from unshackle.core.vault import RateLimited, vault_session
from unshackle.core.vaults import Vaults
from unshackle.vaults.API import API, Exceptions
@@ -81,20 +81,35 @@ class FakeDRM:
out.rename(path)
def make_cmd(monkeypatch: pytest.MonkeyPatch, vaults: Vaults) -> dl:
monkeypatch.setattr(dl_module.binaries, "FFMPEG", "ffmpeg")
def make_resolver(monkeypatch: pytest.MonkeyPatch, vaults: Vaults) -> ContentKeyResolver:
monkeypatch.setattr(key_resolution.binaries, "FFMPEG", "ffmpeg")
monkeypatch.setattr(
dl_module,
key_resolution,
"ffmpeg_decodes",
lambda path, start=None, seconds=3, video=None: path.read_bytes() == b"plain:" + GOOD.encode(),
)
cmd = dl.__new__(dl)
cmd.log = SimpleNamespace(warning=print, info=print, debug=print)
cmd.vaults = vaults
cmd.vault_cache_tally = None
dl.LICENSE_KEY_CACHE.clear()
dl.LICENSE_KEY_CACHE[KID] = BAD
return cmd
keys = resolver(vaults, tag="SVC")
ContentKeyResolver.LICENSE_KEY_CACHE[KID] = BAD
return keys
class BatchDRM(SimpleNamespace):
"""A DRM that a batch licence fills with ``batch``."""
SERVER = SimpleNamespace(
resolve_server_keys=lambda title: [d.content_keys.update(d.batch) for t in title.tracks for d in t.drm],
vault_source=lambda kid, key: None,
)
def batch_title(*batches: dict[UUID, str], kids: Optional[list[UUID]] = None) -> SimpleNamespace:
"""A title with one track per batch, whose DRM names ``kids`` (every KID of its batch by default)."""
return SimpleNamespace(
tracks=[
SimpleNamespace(drm=[BatchDRM(kids=kids or list(keys), content_keys={}, batch=keys)]) for keys in batches
]
)
def test_decrypt_verified_flags_and_retries(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -104,7 +119,7 @@ def test_decrypt_verified_flags_and_retries(tmp_path: Path, monkeypatch: pytest.
vaults = Vaults("SVC")
vaults.vaults = [local, poisoned]
assert vaults.get_key(KID) == (BAD, poisoned)
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
@@ -119,21 +134,21 @@ def test_decrypt_verified_flags_and_retries(tmp_path: Path, monkeypatch: pytest.
vaults.vaults.append(other)
drm.content_keys[KID] = vaults.get_key(KID)[0]
cmd.decrypt_verified(drm, path, licence, KID)
cmd.wait_vault_writes()
keys.decrypt_verified(drm, path, licence, KID)
keys.wait_vault_writes()
assert path.read_bytes() == b"plain:" + GOOD.encode()
assert drm.decrypted_with == [{KID: BAD}, {KID: GOOD}]
assert local.is_bad_key(KID, BAD)
assert local.get_key(KID, "SVC") == GOOD # the key that proved itself on the retry is kept locally
assert KID not in dl.LICENSE_KEY_CACHE
assert KID not in ContentKeyResolver.LICENSE_KEY_CACHE
assert not (tmp_path / "video.mp4.enc").exists()
# a sibling track that still carries the poisoned key is checked too and takes the cached good key
sibling = tmp_path / "audio.mp4"
sibling.write_bytes(b"cipher")
drm2 = FakeDRM({KID: BAD})
cmd.decrypt_verified(drm2, sibling, lambda drm, track_kid: drm.content_keys.update({KID: GOOD}), KID)
keys.decrypt_verified(drm2, sibling, lambda drm, track_kid: drm.content_keys.update({KID: GOOD}), KID)
assert sibling.read_bytes() == b"plain:" + GOOD.encode()
@@ -143,7 +158,7 @@ def test_no_local_vault_raises_instead_of_reusing_the_poison(tmp_path: Path, mon
vaults = Vaults("SVC")
vaults.vaults = [poisoned]
assert vaults.get_key(KID) == (BAD, poisoned)
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
drm = FakeDRM({KID: BAD})
@@ -153,7 +168,7 @@ def test_no_local_vault_raises_instead_of_reusing_the_poison(tmp_path: Path, mon
drm.content_keys[KID] = key
with pytest.raises(ValueError, match="no other source"):
cmd.decrypt_verified(drm, path, licence, KID)
keys.decrypt_verified(drm, path, licence, KID)
assert path.read_bytes() == b"cipher" # ciphertext restored, nothing written with the poison
assert not (tmp_path / "video.mp4.enc").exists()
@@ -165,11 +180,11 @@ def test_segment_decrypted_track_flags_and_raises(tmp_path: Path, monkeypatch: p
vaults = Vaults("SVC")
vaults.vaults = [local, poisoned]
vaults.get_key(KID)
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
path = tmp_path / "video.mp4"
path.write_bytes(b"plain:" + BAD.encode())
with pytest.raises(ValueError, match="run again"):
cmd.decrypt_verified(FakeDRM({KID: BAD}), path, lambda *a, **k: None, KID, decrypt=False)
keys.decrypt_verified(FakeDRM({KID: BAD}), path, lambda *a, **k: None, KID, decrypt=False)
assert local.is_bad_key(KID, BAD)
@@ -197,7 +212,7 @@ def test_every_poisoned_vault_is_burned_then_the_cdm_answers(tmp_path: Path, mon
vault.add_key("SVC", KID, f"{i + 1:02x}" * 16)
vaults = Vaults("SVC")
vaults.vaults = [local, *poisoned]
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
drm = FakeDRM({KID: vaults.get_key(KID)[0]})
@@ -211,7 +226,7 @@ def test_every_poisoned_vault_is_burned_then_the_cdm_answers(tmp_path: Path, mon
key = GOOD
drm.content_keys[KID] = key
cmd.decrypt_verified(drm, path, licence, KID)
keys.decrypt_verified(drm, path, licence, KID)
assert path.read_bytes() == b"plain:" + GOOD.encode()
assert cdm_calls == 1
assert len(drm.decrypted_with) == 4 # three vault keys burned, then the CDM key
@@ -280,8 +295,8 @@ def test_cdm_returning_the_flagged_key_clears_the_flag(
poisoned.add_key("SVC", KID, BAD)
vaults = Vaults("SVC")
vaults.vaults = [local, poisoned]
cmd = make_cmd(monkeypatch, vaults)
monkeypatch.setattr(dl_module, "ffmpeg_decodes", lambda path, start=None, seconds=3, video=None: False)
keys = make_resolver(monkeypatch, vaults)
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", lambda path, start=None, seconds=3, video=None: False)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
drm = FakeDRM({KID: vaults.get_key(KID)[0]})
@@ -293,7 +308,7 @@ def test_cdm_returning_the_flagged_key_clears_the_flag(
else:
drm.content_keys[KID] = BAD # the CDM answers with the same key
cmd.decrypt_verified(drm, path, licence, KID)
keys.decrypt_verified(drm, path, licence, KID)
assert path.read_bytes() == b"plain:" + BAD.encode()
assert not local.is_bad_key(KID, BAD)
@@ -305,7 +320,7 @@ def test_a_replacement_key_in_a_new_dict_is_checked_and_stored(tmp_path: Path, m
vaults = Vaults("SVC")
vaults.vaults = [local, poisoned]
assert vaults.get_key(KID) == (BAD, poisoned)
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
drm = FakeDRM({KID: BAD})
@@ -316,8 +331,8 @@ def test_a_replacement_key_in_a_new_dict_is_checked_and_stored(tmp_path: Path, m
vaults.vaults.append(other)
drm.content_keys = {KID: vaults.get_key(KID)[0]}
cmd.decrypt_verified(drm, path, licence, KID)
cmd.wait_vault_writes()
keys.decrypt_verified(drm, path, licence, KID)
keys.wait_vault_writes()
assert path.read_bytes() == b"plain:" + GOOD.encode()
assert local.get_key(KID, "SVC") == GOOD
@@ -330,7 +345,7 @@ def test_a_cdm_that_confirms_a_key_flagged_on_entry_clears_the_flag(
local = SQLite("local", tmp_path / "local.db")
vaults = Vaults("SVC")
vaults.vaults = [local]
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
vaults.flag_bad_key(KID, BAD)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
@@ -342,8 +357,8 @@ def test_a_cdm_that_confirms_a_key_flagged_on_entry_clears_the_flag(
else:
drm.content_keys[KID] = BAD
cmd.decrypt_verified(drm, path, licence, KID)
cmd.wait_vault_writes()
keys.decrypt_verified(drm, path, licence, KID)
keys.wait_vault_writes()
assert path.read_bytes() == b"plain:" + BAD.encode()
assert not local.is_bad_key(KID, BAD)
assert local.get_key(KID, "SVC") == BAD
@@ -357,14 +372,14 @@ def test_a_licence_key_that_replaces_a_bad_local_pair_is_stored(
local.add_key("SVC", KID, BAD)
vaults = Vaults("SVC")
vaults.vaults = [local]
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
drm = FakeDRM({KID: vaults.get_key(KID)[0]})
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
assert local.add_keys("SVC", {KID: GOOD}) == 0
cmd.decrypt_verified(drm, path, lambda drm, track_kid: drm.content_keys.update({KID: GOOD}), KID)
cmd.wait_vault_writes()
keys.decrypt_verified(drm, path, lambda drm, track_kid: drm.content_keys.update({KID: GOOD}), KID)
keys.wait_vault_writes()
assert local.is_bad_key(KID, BAD)
assert local.get_key(KID, "SVC") == GOOD
@@ -375,7 +390,7 @@ def test_stale_backup_from_a_killed_run_is_not_restored(tmp_path: Path, monkeypa
vaults = Vaults("SVC")
vaults.vaults = [poisoned]
vaults.get_key(KID)
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
(tmp_path / "video.mp4.enc").write_bytes(b"stale")
@@ -384,7 +399,7 @@ def test_stale_backup_from_a_killed_run_is_not_restored(tmp_path: Path, monkeypa
drm.content_keys[KID] = vaults.get_key(KID)[0]
with pytest.raises(ValueError, match="no other source"):
cmd.decrypt_verified(FakeDRM({KID: BAD}), path, licence, KID)
keys.decrypt_verified(FakeDRM({KID: BAD}), path, licence, KID)
assert path.read_bytes() == b"cipher"
@@ -396,19 +411,19 @@ def test_stale_backup_from_a_killed_run_is_not_restored(tmp_path: Path, monkeypa
def test_an_unkeyed_kid_the_file_uses_is_licensed_before_the_decrypt(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, windows: Optional[dict], licensed: list[UUID]
) -> None:
cmd = make_cmd(monkeypatch, Vaults("SVC"))
keys = make_resolver(monkeypatch, Vaults("SVC"))
drm = FakeDRM({KID: GOOD})
drm.kids = [KID, SIBLING]
monkeypatch.setattr(
dl_module.verify,
key_resolution.verify,
"kid_windows",
lambda path: None if windows is None else dl_module.verify.KidMap(windows, True),
lambda path: None if windows is None else key_resolution.verify.KidMap(windows, True),
)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
licences: list[UUID] = []
cmd.decrypt_verified(drm, path, lambda drm, track_kid: licences.append(track_kid), KID)
keys.decrypt_verified(drm, path, lambda drm, track_kid: licences.append(track_kid), KID)
assert licences == licensed
assert drm.decrypted_with == [{KID: GOOD}]
@@ -416,11 +431,11 @@ def test_an_unkeyed_kid_the_file_uses_is_licensed_before_the_decrypt(
def test_drm_without_content_keys_still_decrypts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""HLS AES-128 ClearKey has no KID:KEY map; the hook must pass it straight through."""
cmd = make_cmd(monkeypatch, Vaults("SVC"))
keys = make_resolver(monkeypatch, Vaults("SVC"))
path = tmp_path / "video.ts"
path.write_bytes(b"cipher")
calls: list[Path] = []
cmd.decrypt_verified(SimpleNamespace(decrypt=calls.append), path)
keys.decrypt_verified(SimpleNamespace(decrypt=calls.append), path)
assert calls == [path]
@@ -451,38 +466,61 @@ def test_a_licence_key_clears_a_flag_from_an_earlier_run(tmp_path: Path, monkeyp
local.flag_bad_key("SVC", KID, GOOD, "poisoned")
vaults = Vaults("SVC")
vaults.vaults = [local]
cmd = make_cmd(monkeypatch, vaults)
cmd.vault_cache_tally = None
cmd.cache_keys_to_vaults({KID: GOOD})
keys = resolver(vaults, source=SERVER)
keys.take_server_keys(batch_title({KID: GOOD}))
keys.wait_vault_writes()
assert not local.is_bad_key(KID, GOOD)
assert local.get_key(KID, "SVC") == GOOD
def test_a_licence_with_no_new_keys_sends_no_vault_write(monkeypatch: pytest.MonkeyPatch) -> None:
"""A PSSH KID the licence never answers forces a licence on every run; the vaults must not get an empty push."""
vault = SimpleNamespace(no_push=False, add_keys=lambda *_: pytest.fail("empty push reached a vault"))
vaults = Vaults("SVC")
vaults.vaults = [vault] # type: ignore[list-item]
cmd = make_cmd(monkeypatch, vaults)
cmd.cache_keys_to_vaults({})
assert cmd.vault_cache_tally is None
from unshackle.core.drm import ClearKeyCENC
pushes: list[dict] = []
class PushVaults(NoVaults):
def __bool__(self) -> bool:
return True
def clear_licensed_flags(self, content_keys: dict) -> None:
pass
def add_keys(self, kid_keys: dict) -> int:
pushes.append(kid_keys)
return 1
monkeypatch.setattr(ClearKeyCENC, "get_content_keys", lambda self, **_: None)
keys = resolver(PushVaults())
drm = ClearKeyCENC(kids=[KID])
keys.licence_for(SimpleNamespace(drm=[drm]), None, key_table())(drm, track_kid=None)
keys.wait_vault_writes()
assert pushes == []
def test_the_cached_key_count_is_unique_and_skipped_without_vaults(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
tmp_path: Path, caplog: pytest.LogCaptureFixture
) -> None:
"""Two tracks licensed in parallel can return the same key; --cdm-only loads no vaults at all."""
other = UUID(int=9)
vaults = Vaults("SVC")
vaults.vaults = [SQLite("local", tmp_path / "local.db")]
cmd = make_cmd(monkeypatch, vaults)
cmd.cache_keys_to_vaults({KID: GOOD})
cmd.cache_keys_to_vaults({KID: GOOD, other: GOOD})
assert cmd.vault_cache_tally == ({KID, other}, 1)
keys = resolver(vaults, source=SERVER)
keys.take_server_keys(batch_title({KID: GOOD}))
ContentKeyResolver.LICENSE_KEY_CACHE.clear()
keys.take_server_keys(batch_title({KID: GOOD, other: GOOD}))
with caplog.at_level(logging.INFO, logger="download"):
keys.wait_vault_writes()
assert [r.getMessage() for r in caplog.records if r.name == "download"] == ["Cached 2 Keys to 1/1 Vaults"]
cmd = make_cmd(monkeypatch, Vaults("SVC"))
cmd.cache_keys_to_vaults({KID: GOOD})
assert cmd.vault_cache_tally is None
caplog.clear()
keys = resolver(Vaults("SVC"), source=SERVER)
keys.take_server_keys(batch_title({KID: GOOD}))
with caplog.at_level(logging.INFO, logger="download"):
keys.wait_vault_writes()
assert not [r for r in caplog.records if r.name == "download"]
def test_bulk_add_refuses_a_flagged_pair_in_any_case_or_kid_form(tmp_path: Path) -> None:
@@ -504,16 +542,16 @@ def test_only_the_kid_whose_window_fails_is_flagged(tmp_path: Path, monkeypatch:
other.add_key("SVC", KID, GOOD)
vaults = Vaults("SVC")
vaults.vaults = [local, poisoned]
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
drm = FakeDRM({lead: vaults.get_key(lead)[0], KID: vaults.get_key(KID)[0]})
right = {lead: BAD, KID: GOOD}
monkeypatch.setattr(
dl_module.verify,
key_resolution.verify,
"kid_windows",
lambda path: dl_module.verify.KidMap({lead: [(0.0, 2.0)], KID: [(120.0, 122.0)]}, True),
lambda path: key_resolution.verify.KidMap({lead: [(0.0, 2.0)], KID: [(120.0, 122.0)]}, True),
)
monkeypatch.setattr(
dl_module,
key_resolution,
"ffmpeg_decodes",
lambda path, start=None, seconds=3, video=None: (
drm.decrypted_with[-1][lead if start == 0.0 else KID] == right[lead if start == 0.0 else KID]
@@ -526,8 +564,8 @@ def test_only_the_kid_whose_window_fails_is_flagged(tmp_path: Path, monkeypatch:
vaults.vaults.append(other)
drm.content_keys[KID] = vaults.get_key(KID)[0]
cmd.decrypt_verified(drm, path, licence, KID)
cmd.wait_vault_writes()
keys.decrypt_verified(drm, path, licence, KID)
keys.wait_vault_writes()
assert drm.content_keys == right
assert local.is_bad_key(KID, BAD)
assert not local.is_bad_key(lead, BAD)
@@ -545,7 +583,7 @@ def test_a_kid_absent_from_the_map_is_judged_by_the_fallback(tmp_path: Path, mon
other.add_key("SVC", KID, GOOD)
vaults = Vaults("SVC")
vaults.vaults = [local, poisoned]
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
drm = FakeDRM({lead: vaults.get_key(lead)[0], KID: vaults.get_key(KID)[0]})
calls: list[tuple] = []
@@ -554,11 +592,11 @@ def test_a_kid_absent_from_the_map_is_judged_by_the_fallback(tmp_path: Path, mon
return drm.decrypted_with[-1][lead if start is not None else KID] == GOOD
monkeypatch.setattr(
dl_module.verify,
key_resolution.verify,
"kid_windows",
lambda path: dl_module.verify.KidMap({lead: [(4.0, 6.0)], UUID(int=0): [(8.0, 10.0)]}, True),
lambda path: key_resolution.verify.KidMap({lead: [(4.0, 6.0)], UUID(int=0): [(8.0, 10.0)]}, True),
)
monkeypatch.setattr(dl_module, "ffmpeg_decodes", decodes)
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", decodes)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
@@ -566,8 +604,8 @@ def test_a_kid_absent_from_the_map_is_judged_by_the_fallback(tmp_path: Path, mon
vaults.vaults.append(other)
drm.content_keys[KID] = vaults.get_key(KID)[0]
cmd.decrypt_verified(drm, path, licence, KID)
cmd.wait_vault_writes()
keys.decrypt_verified(drm, path, licence, KID)
keys.wait_vault_writes()
assert drm.content_keys == {lead: GOOD, KID: GOOD}
assert local.is_bad_key(KID, BAD)
assert not local.is_bad_key(lead, GOOD)
@@ -589,13 +627,13 @@ def test_a_wrong_mapped_key_does_not_flag_a_kid_the_file_does_not_carry(
other.add_key("SVC", KID, GOOD)
vaults = Vaults("SVC")
vaults.vaults = [local, poisoned]
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
drm = FakeDRM({audio: vaults.get_key(audio)[0], KID: vaults.get_key(KID)[0]})
monkeypatch.setattr(
dl_module.verify, "kid_windows", lambda path: dl_module.verify.KidMap({KID: [(4.0, 6.0)]}, True)
key_resolution.verify, "kid_windows", lambda path: key_resolution.verify.KidMap({KID: [(4.0, 6.0)]}, True)
)
monkeypatch.setattr(
dl_module,
key_resolution,
"ffmpeg_decodes",
lambda path, start=None, seconds=3, video=None: drm.decrypted_with[-1][KID] == GOOD,
)
@@ -606,8 +644,8 @@ def test_a_wrong_mapped_key_does_not_flag_a_kid_the_file_does_not_carry(
vaults.vaults.append(other)
drm.content_keys[KID] = vaults.get_key(KID)[0]
cmd.decrypt_verified(drm, path, licence, KID)
cmd.wait_vault_writes()
keys.decrypt_verified(drm, path, licence, KID)
keys.wait_vault_writes()
assert drm.content_keys == {audio: GOOD, KID: GOOD}
assert local.is_bad_key(KID, BAD)
assert not local.is_bad_key(audio, GOOD)
@@ -623,18 +661,18 @@ def test_a_kid_the_file_does_not_carry_is_not_judged_by_it(tmp_path: Path, monke
remote.add_key("SVC", audio, GOOD)
vaults = Vaults("SVC")
vaults.vaults = [local, remote]
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
drm = FakeDRM({audio: vaults.get_key(audio)[0], KID: GOOD})
monkeypatch.setattr(
dl_module.verify, "kid_windows", lambda path: dl_module.verify.KidMap({KID: [(4.0, 6.0)]}, True)
key_resolution.verify, "kid_windows", lambda path: key_resolution.verify.KidMap({KID: [(4.0, 6.0)]}, True)
)
monkeypatch.setattr(dl_module, "ffmpeg_decodes", lambda path, start=None, seconds=3, video=None: False)
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", lambda path, start=None, seconds=3, video=None: False)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
licences: list[UUID] = []
cmd.decrypt_verified(drm, path, lambda drm, track_kid: licences.append(track_kid), KID)
cmd.wait_vault_writes()
keys.decrypt_verified(drm, path, lambda drm, track_kid: licences.append(track_kid), KID)
keys.wait_vault_writes()
assert drm.content_keys == {audio: GOOD, KID: GOOD}
assert not licences
assert not local.is_bad_key(audio, GOOD)
@@ -655,9 +693,9 @@ def test_a_remote_vault_is_told_only_when_another_key_replaces_its_pair(
remote.add_key("SVC", KID, served)
vaults = Vaults("SVC")
vaults.vaults = [SQLite("local", tmp_path / "local.db"), remote]
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
if not decodes:
monkeypatch.setattr(dl_module, "ffmpeg_decodes", lambda path, start=None, seconds=3, video=None: False)
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", lambda path, start=None, seconds=3, video=None: False)
drm = FakeDRM({KID: vaults.get_key(KID)[0]})
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
@@ -666,7 +704,7 @@ def test_a_remote_vault_is_told_only_when_another_key_replaces_its_pair(
assert not remote.is_bad_key(KID, served)
drm.content_keys[KID] = GOOD
cmd.decrypt_verified(drm, path, licence, KID)
keys.decrypt_verified(drm, path, licence, KID)
assert drm.content_keys == {KID: GOOD}
assert remote.is_bad_key(KID, served) is told
@@ -683,7 +721,7 @@ def test_the_server_vault_is_told_at_once(tmp_path: Path, monkeypatch: pytest.Mo
vaults = Vaults("SVC")
vaults.vaults = [SQLite("local", tmp_path / "local.db")]
vaults.sources[KID] = (BAD, server)
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
drm = FakeDRM({KID: BAD})
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
@@ -692,7 +730,7 @@ def test_the_server_vault_is_told_at_once(tmp_path: Path, monkeypatch: pytest.Mo
assert reports == [(KID, BAD)]
drm.content_keys[KID] = GOOD
cmd.decrypt_verified(drm, path, licence, KID)
keys.decrypt_verified(drm, path, licence, KID)
assert drm.content_keys == {KID: GOOD}
@@ -705,7 +743,7 @@ def test_only_checked_kids_are_copied_to_other_vaults(tmp_path: Path, monkeypatc
remote.add_key("SVC", KID, GOOD)
vaults = Vaults("SVC")
vaults.vaults = [local, remote]
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
drm = FakeDRM({lead: vaults.get_key(lead)[0], KID: vaults.get_key(KID)[0]})
starts: list = []
@@ -714,14 +752,14 @@ def test_only_checked_kids_are_copied_to_other_vaults(tmp_path: Path, monkeypatc
return True
monkeypatch.setattr(
dl_module.verify, "kid_windows", lambda path: dl_module.verify.KidMap({lead: [(4.0, 6.0)]}, True)
key_resolution.verify, "kid_windows", lambda path: key_resolution.verify.KidMap({lead: [(4.0, 6.0)]}, True)
)
monkeypatch.setattr(dl_module, "ffmpeg_decodes", decodes)
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", decodes)
path = tmp_path / "video.mp4"
path.write_bytes(b"cipher")
cmd.decrypt_verified(drm, path, None, KID)
cmd.wait_vault_writes()
keys.decrypt_verified(drm, path, None, KID)
keys.wait_vault_writes()
assert None not in starts
assert local.get_key(lead, "SVC") == GOOD
assert local.get_key(KID, "SVC") is None
@@ -733,7 +771,7 @@ def test_a_clear_file_judges_and_copies_no_vault_key(tmp_path: Path, monkeypatch
remote.add_key("SVC", KID, BAD)
vaults = Vaults("SVC")
vaults.vaults = [local, remote]
cmd = make_cmd(monkeypatch, vaults)
keys = make_resolver(monkeypatch, vaults)
drm = FakeDRM({KID: vaults.get_key(KID)[0]})
checks: list = []
@@ -741,13 +779,13 @@ def test_a_clear_file_judges_and_copies_no_vault_key(tmp_path: Path, monkeypatch
checks.append(start)
return True
monkeypatch.setattr(dl_module.verify, "kid_windows", lambda path: dl_module.verify.KidMap({}, False))
monkeypatch.setattr(dl_module, "ffmpeg_decodes", decodes)
monkeypatch.setattr(key_resolution.verify, "kid_windows", lambda path: key_resolution.verify.KidMap({}, False))
monkeypatch.setattr(key_resolution, "ffmpeg_decodes", decodes)
path = tmp_path / "audio.mp4"
path.write_bytes(b"clear")
cmd.decrypt_verified(drm, path, None, KID)
cmd.wait_vault_writes()
keys.decrypt_verified(drm, path, None, KID)
keys.wait_vault_writes()
assert checks == []
assert local.get_key(KID, "SVC") is None
assert not local.is_bad_key(KID, BAD)
@@ -783,8 +821,8 @@ def test_a_sibling_verdict_during_the_decrypt_still_triggers_the_retry(
vaults = Vaults("SVC")
vaults.vaults = [local]
vaults.sources[KID] = (BAD, local)
cmd = make_cmd(monkeypatch, vaults)
dl.LICENSE_KEY_CACHE[KID] = GOOD # the sibling's retry already licensed the good key
keys = make_resolver(monkeypatch, vaults)
ContentKeyResolver.LICENSE_KEY_CACHE[KID] = GOOD # the sibling's retry already licensed the good key
path = tmp_path / "audio.mp4"
path.write_bytes(b"cipher")
@@ -799,10 +837,10 @@ def test_a_sibling_verdict_during_the_decrypt_still_triggers_the_retry(
licences: list = []
def licence(drm: FakeDRM, track_kid: UUID) -> None:
licences.append(dl.LICENSE_KEY_CACHE.get(KID))
drm.content_keys[KID] = dl.LICENSE_KEY_CACHE[KID]
licences.append(ContentKeyResolver.LICENSE_KEY_CACHE.get(KID))
drm.content_keys[KID] = ContentKeyResolver.LICENSE_KEY_CACHE[KID]
cmd.decrypt_verified(drm, path, licence, KID)
keys.decrypt_verified(drm, path, licence, KID)
assert path.read_bytes() == b"plain:" + GOOD.encode()
assert drm.decrypted_with == [{KID: BAD}, {KID: GOOD}]
@@ -860,31 +898,34 @@ def test_api_vault_reports_the_pair_upstream(monkeypatch: pytest.MonkeyPatch, ca
def test_prefer_vault_keys_queries_each_named_kid_once() -> None:
asked: list[UUID] = []
cmd = dl.__new__(dl)
cmd.vaults = SimpleNamespace(get_key=lambda kid: asked.append(kid) or (None, None))
video, audio = (SimpleNamespace(kids=[KID], content_keys={KID: GOOD, SIBLING: BAD}) for _ in range(2))
cmd.prefer_vault_keys(
remote_keys(), SimpleNamespace(tracks=[SimpleNamespace(drm=[video]), SimpleNamespace(drm=[audio])])
)
class AskedVaults(NoVaults):
def get_key(self, kid: UUID) -> tuple[None, None]:
asked.append(kid)
return None, None
def held_locally(self, kid: UUID, key: str) -> bool:
return False
keys = resolver(AskedVaults(), source=SERVER)
keys.take_server_keys(batch_title({KID: GOOD, SIBLING: BAD}, {KID: GOOD, SIBLING: BAD}, kids=[KID]))
assert asked == [KID]
def test_cache_resolved_keys_skips_a_key_a_local_vault_holds(tmp_path: Path) -> None:
def test_cache_resolved_keys_skips_a_key_a_local_vault_holds(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
local = SQLite("local", tmp_path / "local.db")
local.add_key("SVC", SIBLING, BAD)
cmd = dl.__new__(dl)
cmd.vaults = Vaults("SVC")
cmd.vaults.vaults = [local]
pushed: list[dict] = []
cmd.flush_vault_writes = lambda writes: pushed.extend(w.args[0] for w in writes)
dl.LICENSE_KEY_CACHE.clear()
drm = SimpleNamespace(kids=[KID], content_keys={KID: GOOD, SIBLING: BAD})
vaults = Vaults("SVC")
vaults.vaults = [local]
keys = resolver(vaults, source=SERVER)
cmd.cache_resolved_keys(remote_keys(), SimpleNamespace(tracks=[SimpleNamespace(drm=[drm])]))
keys.take_server_keys(batch_title({KID: GOOD, SIBLING: BAD}, kids=[KID]))
with caplog.at_level(logging.INFO, logger="download"):
keys.wait_vault_writes()
assert pushed == [{KID: GOOD}]
assert local.get_key(KID, "SVC") == GOOD
assert [r.getMessage() for r in caplog.records if r.name == "download"] == ["Cached 1 Key to 1/1 Vaults"]
def test_api_vault_does_not_shrink_the_batch_on_429(monkeypatch: pytest.MonkeyPatch) -> None: