From bbe58930b5a202fdc7ade4f53c4201bf56abc09b Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Tue, 24 Nov 2026 14:44:47 -0700 Subject: [PATCH] refactor(dl): move content-key resolution into core/drm/key_resolution.py --- tests/commands/test_key_resolution_wiring.py | 60 ++ tests/core/key_resolver.py | 68 ++ tests/core/test_all_drm.py | 222 ++-- tests/core/test_drm_lock.py | 38 +- tests/core/test_import_missing_key.py | 57 +- tests/core/test_licence_turns.py | 156 ++- tests/core/test_vault_bad_keys.py | 279 ++--- .../remote/unit/test_server_cdm_max_height.py | 43 +- .../unit/test_server_cdm_vault_write.py | 162 ++- unshackle/commands/dl.py | 978 +---------------- unshackle/core/drm/key_resolution.py | 988 ++++++++++++++++++ 11 files changed, 1582 insertions(+), 1469 deletions(-) create mode 100644 tests/commands/test_key_resolution_wiring.py create mode 100644 tests/core/key_resolver.py create mode 100644 unshackle/core/drm/key_resolution.py diff --git a/tests/commands/test_key_resolution_wiring.py b/tests/commands/test_key_resolution_wiring.py new file mode 100644 index 00000000..314f3dbd --- /dev/null +++ b/tests/commands/test_key_resolution_wiring.py @@ -0,0 +1,60 @@ +"""dl builds its content-key resolution from the run's flags and installs the verified decrypt as the hook.""" + +from __future__ import annotations + +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import pytest + +from unshackle.commands.dl import dl +from unshackle.core.drm import verify + +pytestmark = pytest.mark.unit + + +def runner(written: list[tuple[Any, ...]]) -> dl: + cmd = dl.__new__(dl) + cmd.vaults = SimpleNamespace() + cmd.service = "EXAMPLE" + cmd.debug_logger = None + cmd._remote_service = SimpleNamespace() + cmd.write_export = lambda *args: written.append(args) # type: ignore[method-assign] + return cmd + + +@pytest.mark.parametrize("cdm_only, vaults_only, best_available", [(True, False, False), (False, True, True)]) +def test_the_resolver_takes_the_run_flags_and_becomes_the_decrypt_hook( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, cdm_only: bool, vaults_only: bool, best_available: bool +) -> None: + monkeypatch.setattr(verify, "DECRYPT_HOOK", None) + written: list[tuple[Any, ...]] = [] + cmd = runner(written) + service = SimpleNamespace() + + cmd.start_key_resolution( + service, + cdm_only=cdm_only, + vaults_only=vaults_only, + best_available=best_available, + export=tmp_path / "export.json", + ) + + keys = cmd.keys + assert verify.DECRYPT_HOOK == keys.decrypt_verified + assert (keys.cdm_only, keys.vaults_only, keys.best_available) == (cdm_only, vaults_only, best_available) + assert keys.source is cmd._remote_service and keys.service is service and keys.cdms is cmd + assert keys.vaults is cmd.vaults and keys.tag == "EXAMPLE" + assert keys.export is not None + keys.export("title", "track", "drm") + assert written == [(tmp_path / "export.json", "title", "track", "drm")] + + +def test_no_export_path_gives_no_export_callback(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(verify, "DECRYPT_HOOK", None) + cmd = runner([]) + + cmd.start_key_resolution(SimpleNamespace(), cdm_only=False, vaults_only=True, best_available=False, export=None) + + assert cmd.keys.export is None diff --git a/tests/core/key_resolver.py b/tests/core/key_resolver.py new file mode 100644 index 00000000..2a4d4c4e --- /dev/null +++ b/tests/core/key_resolver.py @@ -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 diff --git a/tests/core/test_all_drm.py b/tests/core/test_all_drm.py index 599daab3..e11f0e01 100644 --- a/tests/core/test_all_drm.py +++ b/tests/core/test_all_drm.py @@ -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 diff --git a/tests/core/test_drm_lock.py b/tests/core/test_drm_lock.py index 79bc6afb..9459f04e 100644 --- a/tests/core/test_drm_lock.py +++ b/tests/core/test_drm_lock.py @@ -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"} diff --git a/tests/core/test_import_missing_key.py b/tests/core/test_import_missing_key.py index 10672619..6791c424 100644 --- a/tests/core/test_import_missing_key.py +++ b/tests/core/test_import_missing_key.py @@ -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}] diff --git a/tests/core/test_licence_turns.py b/tests/core/test_licence_turns.py index d457804d..aef3bb9e 100644 --- a/tests/core/test_licence_turns.py +++ b/tests/core/test_licence_turns.py @@ -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"] == [ diff --git a/tests/core/test_vault_bad_keys.py b/tests/core/test_vault_bad_keys.py index 696a7950..a3e8ad8f 100644 --- a/tests/core/test_vault_bad_keys.py +++ b/tests/core/test_vault_bad_keys.py @@ -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: diff --git a/tests/remote/unit/test_server_cdm_max_height.py b/tests/remote/unit/test_server_cdm_max_height.py index 9664a04a..8dd3be4d 100644 --- a/tests/remote/unit/test_server_cdm_max_height.py +++ b/tests/remote/unit/test_server_cdm_max_height.py @@ -10,9 +10,9 @@ import click import pyplayready.system.pssh as pr_pssh_mod import pytest import pywidevine.pssh as wv_pssh_mod -from rich.table import Table import unshackle.core.drm as drm_mod +from tests.core.key_resolver import key_table, resolver from tests.remote.key_source import CAPPED, PR_DEVICE, one_title, remote_keys, remote_session from unshackle.commands.dl import dl from unshackle.core.api import handlers @@ -539,20 +539,17 @@ class _LocalWidevine(Widevine): raise self.Used(cdm) +def server_stub_resolver(svc, licence, cdm_for=None): + """Content-key resolution for a --cdm-only remote run, whose loaded CDM is the server stub.""" + return resolver(cdm="server stub", licence=licence, cdm_for=cdm_for, tag="EXAMPLE1", source=svc, cdm_only=True) + + def prepare(svc, licence, drm=None, track=None, cdm_for=None): - runner = dl.__new__(dl) - runner._remote_service = svc - runner.cdm = "server stub" - runner.service = "EXAMPLE1" - runner.debug_logger = None - runner.log = logging.getLogger("test-server-cdm-cap") - runner.cdm_for = cdm_for - table = Table() - table.add_column() + keys = server_stub_resolver(svc, licence, cdm_for) drm = drm or _LocalWidevine() track = track or SimpleNamespace(id="vid", drm=None, get_drm_for_cdm=lambda cdm: None) with pytest.raises(_LocalWidevine.Used) as ei: - runner.prepare_drm(drm, track, None, lambda **k: None, licence, table=table, cdm_only=True) + keys.licence_for(track, None, key_table())(drm) return ei.value.args[0] @@ -584,31 +581,15 @@ class PlayReady: self.content_keys = {} -def test_a_mid_download_handover_puts_the_keys_on_the_callers_drm(monkeypatch): +def test_a_mid_download_handover_puts_the_keys_on_the_callers_drm(): """The caller decrypts with the DRM object it passed in, so the local licence must fill that one.""" - monkeypatch.setattr(dl, "LICENSE_KEY_CACHE", {}) svc = remote_keys(local_cdm="local device") - runner = dl.__new__(dl) - runner._remote_service = svc - runner.cdm = "server stub" - runner.service = "EXAMPLE1" - runner.debug_logger = None - runner.log = logging.getLogger("test-server-cdm-cap") - runner.flush_vault_writes = lambda pending: None - table = Table() - table.add_column() + keys = server_stub_resolver(svc, lambda **k: svc.client_licensed.add("vid")) server_drm, local_drm = PlayReady(), _KeyedWidevine() track = SimpleNamespace(id="vid", drm=[server_drm, local_drm], get_drm_for_cdm=lambda cdm: local_drm) - runner.prepare_drm( - server_drm, - track, - None, - lambda **k: None, - lambda **k: svc.client_licensed.add("vid"), - table=table, - cdm_only=True, - ) + keys.licence_for(track, None, key_table())(server_drm) + keys.wait_vault_writes() assert server_drm.content_keys == {UUID(int=0xCA9): "ab" * 16} diff --git a/tests/remote/unit/test_server_cdm_vault_write.py b/tests/remote/unit/test_server_cdm_vault_write.py index 6693a680..e52ec2e2 100644 --- a/tests/remote/unit/test_server_cdm_vault_write.py +++ b/tests/remote/unit/test_server_cdm_vault_write.py @@ -1,20 +1,19 @@ """Keys the server CDM returns must land in the local vaults. -The server-CDM branch of prepare_drm reads the local vaults but used to return before +The server-CDM branch of content-key resolution reads the local vaults but used to return before the vault writes, so a remote run never kept the keys it paid for. Keys that came from a vault in the first place must not be pushed back. """ import threading -import time from types import SimpleNamespace from uuid import UUID import pytest -from rich.table import Table +from tests.core.key_resolver import key_table, resolver from tests.remote.key_source import CAPPED, PR_DEVICE, one_title, remote_keys, remote_session -from unshackle.commands.dl import dl +from unshackle.core.drm.key_resolution import ContentKeyResolver pytestmark = pytest.mark.unit @@ -62,46 +61,30 @@ class FakeWidevine: self.content_keys: dict = {} -def make_cmd(vaults): - cmd = dl.__new__(dl) - cmd.log = SimpleNamespace(warning=print, info=print, debug=print, error=print) - cmd.service = "TEST" - cmd.vaults = vaults - cmd.vault_cache_tally = None - cmd.debug_logger = None - cmd._remote_service = remote_keys() - dl.LICENSE_KEY_CACHE.clear() - dl.DRM_LOCKS.clear() - return cmd +def make_resolver(vaults, licence=None, source=None, **flags): + return resolver(vaults, licence=licence, source=source or remote_keys(), **flags) -def prepare(cmd, drm, licence, track_kid, **kwargs): - table = Table.grid() - table.add_row("") - cmd.prepare_drm( - track=SimpleNamespace(id="vid", drm=[drm]), - title=None, - drm=drm, - licence=licence, - certificate=None, - track_kid=track_kid, - table=table, - **kwargs, - ) +def prepare(keys, drm, track_kid, track=None): + track = track or SimpleNamespace(id="vid", drm=[drm]) + keys.licence_for(track, None, key_table())(drm, track_kid=track_kid) def run_prepare(vaults, kids, licence_keys, track_kid): - cmd = make_cmd(vaults) drm = FakeWidevine(kids) - - def licence(**kwargs): - drm.content_keys.update(licence_keys) - - prepare(cmd, drm, licence, track_kid) - cmd.wait_vault_writes() + keys = make_resolver(vaults, licence=lambda **kwargs: drm.content_keys.update(licence_keys)) + prepare(keys, drm, track_kid) + keys.wait_vault_writes() return drm +def batch(keys, source, title): + """Run the batch step for ``title`` with ``source``, whose keys are already on the tracks.""" + source.resolve_server_keys = lambda title: None + keys.take_server_keys(title) + keys.wait_vault_writes() + + def test_server_cdm_keys_are_cached_to_local_vaults(): vaults = FakeVaults() run_prepare(vaults, [NEW], {NEW: "k_new"}, track_kid=NEW) @@ -116,25 +99,13 @@ def test_keys_read_from_a_vault_are_not_pushed_back(): def capped_run(vaults): """A batch licence refuses the track for a local PlayReady device, then dl prepares its Widevine DRM.""" - cmd = make_cmd(vaults) svc = remote_session(PR_DEVICE, CAPPED) - cmd._remote_service = svc - drm = type("Widevine", (FakeWidevine,), {})([CACHED]) track = SimpleNamespace(id="vid", height=2160, drm=[drm], drm_preference=None) + keys = make_resolver(vaults, licence=lambda **kwargs: svc.proxy_license(b"", track, "widevine"), source=svc) svc.resolve_server_keys(one_title(track)) - table = Table.grid() - table.add_row("") - cmd.prepare_drm( - track=track, - title=None, - drm=drm, - licence=lambda **kwargs: svc.proxy_license(b"", track, "widevine"), - certificate=None, - track_kid=CACHED, - table=table, - ) + prepare(keys, drm, CACHED, track) return drm @@ -152,20 +123,14 @@ def test_a_capped_track_no_vault_holds_raises_the_refusal(): def test_batch_resolved_keys_are_cached_before_download(): """The batch licence fills track.drm before prepare_drm, so dl caches it at the call site.""" vaults = FakeVaults() - cmd = dl.__new__(dl) - cmd.log = SimpleNamespace(warning=print, info=print, debug=print, error=print) - cmd.service = "TEST" - cmd.vaults = vaults - cmd.vault_cache_tally = None - cmd.debug_logger = None - dl.LICENSE_KEY_CACHE.clear() + source = remote_keys() + keys = make_resolver(vaults, source=source) drm = FakeWidevine([NEW]) drm.content_keys = {NEW: "k_new"} title = SimpleNamespace(tracks=[SimpleNamespace(drm=[drm]), SimpleNamespace(drm=None)]) - cmd.cache_resolved_keys(remote_keys(), title) - cmd.wait_vault_writes() + batch(keys, source, title) assert vaults.added == {NEW: "k_new"} @@ -183,19 +148,18 @@ def test_server_vault_keys_are_held_back_until_verified(): from unshackle.core.remote_service import ServerVault vaults = FakeVaults() - cmd = make_cmd(vaults) - remote = cmd._remote_service + remote = remote_keys() remote.server_vault_keys = {CACHED: "k_cached"} stub = ServerVault(remote) remote.server_vault = stub drm = FakeWidevine([CACHED, NEW]) + keys = make_resolver( + vaults, licence=lambda **kwargs: drm.content_keys.update({CACHED: "k_cached", NEW: "k_new"}), source=remote + ) - def licence(**kwargs): - drm.content_keys.update({CACHED: "k_cached", NEW: "k_new"}) - - prepare(cmd, drm, licence, NEW) - cmd.wait_vault_writes() + prepare(keys, drm, NEW) + keys.wait_vault_writes() assert vaults.added == {NEW: "k_new"} assert vaults.sources == {CACHED: ("k_cached", stub)} @@ -203,30 +167,34 @@ def test_server_vault_keys_are_held_back_until_verified(): # the batch path caches at its own call site and must hold the same key back drm2 = FakeWidevine([CACHED]) drm2.content_keys = {CACHED: "k_cached"} - dl.LICENSE_KEY_CACHE.clear() - cmd.cache_resolved_keys(remote, SimpleNamespace(tracks=[SimpleNamespace(drm=[drm2])])) - cmd.wait_vault_writes() + ContentKeyResolver.LICENSE_KEY_CACHE.clear() + batch(keys, remote, SimpleNamespace(tracks=[SimpleNamespace(drm=[drm2])])) assert vaults.added == {NEW: "k_new"} def test_tracks_sharing_one_drm_licence_and_push_once(): """Two tracks on the same DRM run at the same time; the second must find the first one's keys.""" vaults = FakeVaults() - cmd = make_cmd(vaults) drm = FakeWidevine([NEW]) calls = [] def licence(**kwargs): calls.append(1) - time.sleep(0.2) drm.content_keys.update({NEW: "k_new"}) - threads = [threading.Thread(target=prepare, args=(cmd, drm, licence, NEW)) for _ in range(2)] + keys = make_resolver(vaults, licence=licence) + both_started = threading.Barrier(2) + + def track(): + both_started.wait(10) + prepare(keys, drm, NEW) + + threads = [threading.Thread(target=track) for _ in range(2)] for t in threads: t.start() for t in threads: t.join() - cmd.wait_vault_writes() + keys.wait_vault_writes() assert len(calls) == 1 assert vaults.pushes == [{NEW: "k_new"}] @@ -235,18 +203,17 @@ def test_tracks_sharing_one_drm_licence_and_push_once(): def test_cdm_only_still_reuses_keys_from_the_run_cache(): """--cdm-only skips the vaults, not LICENSE_KEY_CACHE, so a second track with the same KID does not licence twice.""" vaults = FakeVaults() - cmd = make_cmd(vaults) calls = [] + drms = [FakeWidevine([NEW]) for _ in range(2)] - for _ in range(2): - drm = FakeWidevine([NEW]) + def licence(**kwargs): + calls.append(1) + drms[len(calls) - 1].content_keys.update({NEW: "k_new"}) - def licence(**kwargs): - calls.append(1) - drm.content_keys.update({NEW: "k_new"}) - - prepare(cmd, drm, licence, NEW, cdm_only=True) - cmd.wait_vault_writes() + keys = make_resolver(vaults, licence=licence, cdm_only=True) + for drm in drms: + prepare(keys, drm, NEW) + keys.wait_vault_writes() assert len(calls) == 1 assert vaults.pushes == [{NEW: "k_new"}] @@ -257,17 +224,19 @@ def test_cdm_only_trusts_server_vault_keys(): from unshackle.core.remote_service import ServerVault vaults = FakeVaults() - cmd = make_cmd(vaults) - remote = cmd._remote_service + remote = remote_keys() remote.server_vault_keys = {CACHED: "k_cached"} remote.server_vault = ServerVault(remote) drm = FakeWidevine([CACHED]) - prepare(cmd, drm, lambda **kw: drm.content_keys.update({CACHED: "k_cached"}), CACHED, cdm_only=True) - cmd.wait_vault_writes() + keys = make_resolver( + vaults, licence=lambda **kw: drm.content_keys.update({CACHED: "k_cached"}), source=remote, cdm_only=True + ) + prepare(keys, drm, CACHED) + keys.wait_vault_writes() assert vaults.sources == {} - assert dl.LICENSE_KEY_CACHE == {CACHED: "k_cached"} + assert ContentKeyResolver.LICENSE_KEY_CACHE == {CACHED: "k_cached"} @pytest.mark.parametrize("system", ["widevine", "playready"]) @@ -277,15 +246,14 @@ def test_no_cdm_and_no_server_cdm_names_the_missing_cdm(system): from unshackle.core.drm import PlayReady, Widevine - cmd = make_cmd(FakeVaults()) - cmd._remote_service = remote_keys(server_cdm=False) - cmd.cdm = None - cmd.cdm_for = lambda system, quality=None: None + keys = resolver( + FakeVaults(), cdm=None, cdm_for=lambda system, quality=None: None, source=remote_keys(server_cdm=False) + ) drm_class = PlayReady if system == "playready" else Widevine drm = drm_class.__new__(drm_class) drm.content_keys = {} with pytest.raises(click.ClickException, match="No CDM configured for TEST"): - prepare(cmd, drm, lambda **kwargs: None, NEW) + prepare(keys, drm, NEW) NULL = UUID("0b3e2d1c4a5f46e7b8c9d0e1f2a3b4c5") @@ -296,22 +264,22 @@ def test_a_null_key_from_the_server_licence_is_dropped(): drm = run_prepare(vaults, [NEW], {NEW: "k_new", NULL: "0" * 32}, track_kid=NEW) assert drm.content_keys == {NEW: "k_new"} assert vaults.added == {NEW: "k_new"} - assert NULL not in dl.LICENSE_KEY_CACHE + assert NULL not in ContentKeyResolver.LICENSE_KEY_CACHE def test_a_null_key_from_the_batch_licence_is_dropped(monkeypatch): vaults = FakeVaults() - cmd = make_cmd(vaults) + source = remote_keys() + keys = make_resolver(vaults, source=source) drm = FakeWidevine([NEW]) title = SimpleNamespace(tracks=[SimpleNamespace(drm=[drm])]) - source = cmd._remote_service monkeypatch.setattr( source, "resolve_server_keys", lambda t: drm.content_keys.update({NEW: "k_new", NULL: "0" * 32}) ) - cmd.take_server_keys(source, title, cdm_only=False) - cmd.wait_vault_writes() + keys.take_server_keys(title) + keys.wait_vault_writes() assert drm.content_keys == {NEW: "k_new"} assert vaults.added == {NEW: "k_new"} - assert NULL not in dl.LICENSE_KEY_CACHE + assert NULL not in ContentKeyResolver.LICENSE_KEY_CACHE diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index 2177b315..849e3850 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -9,11 +9,10 @@ import shutil import subprocess import sys import time -from collections import Counter, defaultdict +from collections import Counter from collections.abc import Iterable from concurrent import futures from concurrent.futures import ThreadPoolExecutor -from contextlib import ExitStack from copy import deepcopy from datetime import date, timedelta from functools import partial @@ -23,8 +22,7 @@ from itertools import groupby from operator import attrgetter from pathlib import Path from threading import Lock -from typing import TYPE_CHECKING, Any, Callable, Collection, Optional, Sequence, TypedDict, Union, cast -from uuid import UUID +from typing import TYPE_CHECKING, Any, Callable, Collection, Optional, Sequence, TypedDict, Union import click import mediaexport @@ -37,8 +35,6 @@ from rich.progress import Progress, SpinnerColumn, TaskID, TextColumn, TimeRemai from rich.rule import Rule from rich.spinner import Spinner from rich.table import Table -from rich.text import Text -from rich.tree import Tree from unshackle.core import __version__, binaries, providers from unshackle.core.cdm import DecryptLabsRemoteCDM @@ -51,7 +47,6 @@ from unshackle.core.constants import ( DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack, - DownloadCancelled, context_settings, ) from unshackle.core.credential import Credential @@ -63,19 +58,12 @@ from unshackle.core.downloaders import ( set_speed_limit, ) from unshackle.core.drm import ( - DRM_T, - ClearKey, - ClearKeyCENC, MonaLisa, - PlayReady, - Widevine, cbcs, - drop_null_keys, - is_null_key, own_kids, - real_kids, verify, ) +from unshackle.core.drm.key_resolution import ContentKeyResolver from unshackle.core.events import events from unshackle.core.export_name import ExportNamer, move_export, plural, season_episodes, title_label from unshackle.core.manifests.snapshot import capture @@ -112,7 +100,6 @@ from unshackle.core.tracks.track import ( ) from unshackle.core.utilities import ( apply_original_language, - declared_kwargs, find_font_with_fallbacks, get_debug_logger, get_system_fonts, @@ -143,10 +130,9 @@ from unshackle.core.utils.click_types import ( from unshackle.core.utils.collections import ci_get, merge_dict from unshackle.core.utils.hdr10plus import probed_tracks from unshackle.core.utils.post_scripts import NO_POST_SCRIPTS, build_context, dispatch, season_context -from unshackle.core.utils.redact import mask_proxy, redact_secrets +from unshackle.core.utils.redact import mask_proxy from unshackle.core.utils.selector import select_multiple -from unshackle.core.utils.subprocess import ffmpeg_decodes, ffprobe -from unshackle.core.vault import Vault +from unshackle.core.utils.subprocess import ffprobe from unshackle.core.vaults import Vaults if TYPE_CHECKING: @@ -563,18 +549,6 @@ def download_tracks_in_passes( class dl: - @staticmethod - def truncate_pssh_for_display(pssh_string: str, drm_type: str) -> str: - """Truncate PSSH string for display when not in debug mode.""" - if logging.root.level == logging.DEBUG or not pssh_string: - return pssh_string - - max_width = console.width - len(drm_type) - 12 - if len(pssh_string) <= max_width: - return pssh_string - - return pssh_string[: max_width - 3] + "..." - def find_custom_font(self, font_name: str) -> Optional[Path]: """ Find font in custom fonts directory. @@ -1293,14 +1267,9 @@ class dl: def cli(ctx: click.Context, **kwargs: Any) -> dl: return dl(ctx, **kwargs) - DRM_LOCKS: dict[str, Lock] = {} - DRM_LOCKS_GUARD = Lock() - LICENCE_LOCK = Lock() - VAULT_WRITER = ThreadPoolExecutor(1, thread_name_prefix="vault-writer") EXPORT_LOCK = Lock() export_snapshots: dict[str, Optional[dict[str, Any]]] - LICENSE_KEY_CACHE: dict[UUID, str] = {} - ALL_DRM_LOCK = Lock() + keys: ContentKeyResolver _remote_service: Optional["ServerKeySource"] = None typed_params: frozenset[str] = frozenset() @@ -1517,11 +1486,9 @@ class dl: self.cdm_override = ctx.params.get("cdm_name") cdm_only = ctx.params.get("cdm_only") - self.vault_cache_tally: Optional[tuple[set[UUID], int]] = None if cdm_only: self.vaults = Vaults(self.vault_service) - verify.DECRYPT_HOOK = self.decrypt_verified self.log.info("CDM-only mode: Skipping vault loading") log_event( "vault_loading_skipped", @@ -1532,7 +1499,6 @@ class dl: else: with console.status("Loading Key Vaults...", spinner="dots"): self.vaults = Vaults(self.vault_service) - verify.DECRYPT_HOOK = self.decrypt_verified total_vaults = len(config.key_vaults) failed_vaults = [] @@ -1780,8 +1746,6 @@ class dl: DOWNLOAD_ALL_DRM.set() else: DOWNLOAD_ALL_DRM.clear() - self.all_drm_attempted: defaultdict[type, set[UUID]] = defaultdict(set) - self.all_drm_warned: set[str] = set() if no_postscript: postscript = NO_POST_SCRIPTS if continue_downloads: @@ -1983,6 +1947,13 @@ class dl: vaults_only = None else: vaults_only = not cdm_only + self.start_key_resolution( + service, + cdm_only=bool(cdm_only), + vaults_only=bool(vaults_only), + best_available=bool(best_available), + export=export_path, + ) config.decryption = resolve_decryption( config.decryption_map, config.decryption, service.__class__.__name__.upper() @@ -2597,21 +2568,7 @@ class dl: download_table.add_row(selected_tracks) def prepare_drm_for(track: AnyTrack) -> partial: - prepare = partial( - partial(self.prepare_drm, table=download_table), - track=track, - title=title, - certificate=partial(service.get_widevine_service_certificate, title=title, track=track), - licence=partial(self.service_licence, service, title=title, track=track), - clearkey_licence=partial(service.get_clearkey_license, title=title, track=track), - cdm_only=cdm_only, - vaults_only=vaults_only, - export=export_path, - service_session=service.session, - ) - if title_all_drm: - return partial(self.licence_all_drm, prepare, track, best_available, force=bool(cdm_only)) - return prepare + return self.keys.licence_for(track, title, download_table, title_all_drm) server_cdm_type = None if self._remote_service and self._remote_service.server_cdm: @@ -2662,12 +2619,11 @@ class dl: else f"set cdm.{self.service}.{system.lower()}" ) raise click.ClickException(f"--all-drm needs a {system} CDM for {self.service}: {hint}") - if is_remote_cdm(system_cdms[0]) and system not in self.all_drm_warned: - self.all_drm_warned.add(system) + if is_remote_cdm(system_cdms[0]) and system not in self.keys.all_drm_warned: + self.keys.all_drm_warned.add(system) self.log.warning(f"The {system} CDM is remote and can answer with cached content keys") - if self._remote_service: - self.take_server_keys(self._remote_service, title, bool(cdm_only)) + self.keys.take_server_keys(title) if sample and not skip_dl: whole_files = [ @@ -2763,7 +2719,7 @@ class dl: message="Download cancelled by user", context={"title": str(title)}, ) - self.wait_vault_writes() + self.keys.wait_vault_writes() if export_path: self.log_export_summary() return @@ -2799,12 +2755,12 @@ class dl: ), postscript, ) - self.wait_vault_writes() + self.keys.wait_vault_writes() if export_path: self.log_export_summary() return - self.wait_vault_writes() + self.keys.wait_vault_writes() if export_path: self.log_export_title(title) @@ -2888,7 +2844,7 @@ class dl: for track in drm_tracks: drm = track.get_drm_for_cdm(self.cdm) if drm and hasattr(drm, "decrypt"): - self.decrypt_verified(drm, track.path, prepare_drm_for(track)) + self.keys.decrypt_verified(drm, track.path, prepare_drm_for(track)) if not isinstance(drm, MonaLisa): # MonaLisa decrypts per segment; its decrypt() here is a no-op assert_fragments_decrypted(track.path) @@ -3470,7 +3426,7 @@ class dl: run_context["folder"] = str(folder) dispatch("success", "run", run_context, postscript) - self.wait_vault_writes() + self.keys.wait_vault_writes() if export_path: self.log_export_summary() if self.skipped_titles: @@ -4000,588 +3956,23 @@ class dl: line += f", {'; '.join(e.__notes__)}" return [":x: Download Failed...", f" {line}"] - def decrypt_verified( - self, - drm: DRM_T, - path: Path, - licence: Optional[Callable] = None, - track_kid: Optional[UUID] = None, - decrypt: bool = True, + def start_key_resolution( + self, service: Service, *, cdm_only: bool, vaults_only: bool, best_available: bool, export: Optional[Path] ) -> None: - """Decrypt the file, and when a vault supplied a content key, prove the output decodes. - - A poisoned vault returns the right KID with a wrong content key, and the decrypters - accept it without complaint. A content key from a vault is therefore trusted, and only - then copied to the other vaults, once FFmpeg can decode the result. Without FFmpeg - neither happens. For a fragmented MP4, ``verify.kid_windows`` reads from the ciphertext - which fragments each KID encrypts, and FFmpeg decodes windows inside each KID's - fragments, so only a KID that fails is flagged. A complete map does not judge a KID it does - not hold, so a clear file judges and copies no KID. A KID that is not in an incomplete map, - and every KID of any other file, gets a start and end check of the whole file, and a - failure there flags each of those KIDs. On failure the pair is flagged in the local - vaults, the ciphertext is restored, and the licence runs again; ``Vaults`` tells the - vault that served it. Every vault skips a flagged pair, so each pass burns at most one - vault; when the vaults run out the CDM answers, and a CDM key is not checked. A CDM - that returns the flagged key clears the flag and stores the content key again, because - then the decode check was wrong. - - With ``decrypt=False`` the downloader already decrypted the segments in place, so a - failure can only flag and raise; the next run skips the flagged pair. - - Before the decrypt, each KID the DRM names without a content key is licensed when the file - uses it, or when the file cannot be mapped, because ``prepare_drm`` licensed only for the track's KID. - """ - keys: Any = getattr(drm, "content_keys", None) - if keys is None: - if decrypt: - drm.decrypt(path) - return - - def flagged_kids() -> list[UUID]: - """The KIDs on this track whose content key another track already proved wrong.""" - return [kid for kid, key in keys.items() if (kid, key) in self.vaults.flagged] - - def drop(kid: UUID) -> str: - key = keys.pop(kid) - if self.LICENSE_KEY_CACHE.get(kid) == key: - self.LICENSE_KEY_CACHE.pop(kid) - return key - - def relicense(bad: dict[UUID, str], kids: dict[UUID, Vault]) -> None: - """Licence again for each dropped KID, then settle each dropped pair against the new key. - - prepare_drm licenses only for a KID it is told to need, so without the second call a - track that still holds other content keys would decrypt without the dropped one. A - licence can replace the DRM's dict, so ``keys`` is read from the DRM again afterwards. - A licence key equal to the dropped one proves the decode check wrong and clears its flag. - """ - nonlocal keys - if not licence: - return - licence(drm, track_kid=track_kid) - for kid in sorted(bad): - if kid != track_kid and kid not in getattr(drm, "content_keys", {}): - licence(drm, track_kid=kid) - keys = getattr(drm, "content_keys", keys) - for kid, key in bad.items(): - new = keys.get(kid) - if new is None: - continue - source = self.vaults.sources.get(kid) - if source is None: - if new == key: - self.vaults.unflag_bad_key(kid, key) - self.flush_vault_writes([partial(self.vaults.add_key, kid, key)]) - elif not self.vaults.held_locally(kid, new): - self.flush_vault_writes([partial(self.vaults.add_key, kid, new)]) - elif new == key and kid in kids and source[1] is kids[kid]: - raise ValueError(f"{key} from {kids[kid].name} was bad and no other source has the key") - - known_bad = flagged_kids() - if known_bad and licence: - relicense({kid: drop(kid) for kid in known_bad}, {}) - - unkeyed = [kid for kid in getattr(drm, "kids", None) or [] if kid not in keys] - mapped = bool(unkeyed and decrypt and licence) - kid_map = verify.kid_windows(path) if mapped else None - if mapped and licence: - for kid in unkeyed: - if kid_map is None or kid in kid_map.windows: - licence(drm, track_kid=kid) - keys = getattr(drm, "content_keys", keys) - - def vault_kids() -> dict[UUID, Vault]: - """The KIDs whose key on the track came from a vault, with that vault.""" - found = {kid: self.vaults.sources.get(kid) for kid in keys} - return {kid: src[1] for kid, src in found.items() if src and src[0] == keys[kid]} - - backup = path.with_name(path.name + ".enc") - backup.unlink(missing_ok=True) # a killed run leaves one behind; its bytes may not match - checking = bool(vault_kids() and decrypt and binaries.FFMPEG) - if checking: - try: - os.link(path, backup) - except OSError as e: - self.log.debug(f"Cannot keep the ciphertext for a decrypt retry: {e!r}") - kid_map = (kid_map if mapped else verify.kid_windows(path)) if checking else None - windows = kid_map.windows if kid_map else {} - video = kid_map.video if kid_map else None - - def window_decodes(start: float, end: float) -> bool: - return ffmpeg_decodes(path, start=start, seconds=end - start if end > start else 0.5, video=video) - - def judged_kids() -> dict[UUID, Vault]: - """The vault KIDs this file can judge. A map whose KIDs all have keys skips the KIDs it lacks.""" - kids = vault_kids() - if kid_map is not None and all(kid in keys for kid in windows): - return {kid: vault for kid, vault in kids.items() if kid in windows} - return kids - - def failed_kids(kids: dict[UUID, Vault]) -> set[UUID]: - """The vault KIDs whose content key did not decode. - - A KID in the KID map fails when one of its windows fails. The KIDs that are not in the - map share the verdict of one start and end check of the whole file, taken only when - every mapped KID passed: a wrong mapped key fails that check too and would flag them - for noise that is not theirs. The retry judges them again with the replaced key. - """ - failed = {kid for kid in kids if kid in windows and not all(window_decodes(*w) for w in windows[kid])} - absent = {kid for kid in kids if kid not in windows} - if absent and not failed and not ffmpeg_decodes(path, video=video): - failed |= absent - self.log.debug( - f"Key check on {path.name}: {len(kids) - len(absent)} KID(s) by fragment window, " - f"{len(absent)} by whole-file check, failed {sorted(k.hex for k in failed)}" - ) - return failed - - def passes_left(done: int) -> bool: - """One pass per source that can still answer: every loaded vault, the server's vaults as - one source that walks them itself over --remote, and one for the CDM.""" - remote = 1 if self._remote_service and self._remote_service.server_cdm else 0 - return done < len(self.vaults) + remote + 1 - - try: - done = 0 - while passes_left(done): - done += 1 - if decrypt: - drm.decrypt(path) - kids = judged_kids() - stale = flagged_kids() - failed: set[UUID] = set() - if not stale: - checked = bool(kids and binaries.FFMPEG and path.exists()) - failed = failed_kids(kids) if checked else set() - if not failed: - if checked: - self.flush_vault_writes( - [ - partial(self.vaults.add_key, kid, keys[kid], excluding=vault) - for kid, vault in kids.items() - ] - ) - self.vaults.report_replaced(keys) - return - bad = {kid: drop(kid) for kid in {*failed, *stale}} - for kid, key in bad.items(): - if kid not in kids: - continue - self.log.warning(f"{key} from {kids[kid].name} was bad, trying other vaults") - self.vaults.flag_bad_key(kid, key) - if not backup.exists() or not licence: - raise ValueError("The content key from the vault did not decrypt the track; run again") - path.unlink() - os.link(backup, path) - relicense(bad, kids) - raise ValueError("No vault or CDM produced a content key that decrypts the track") - finally: - backup.unlink(missing_ok=True) - - def flush_vault_writes(self, pending: list[Callable[[], Any]]) -> None: - """Hand the queued vault writes to the background writer so the track does not wait on them.""" - for write in pending: - self.VAULT_WRITER.submit(write).add_done_callback(self.report_vault_write) - pending.clear() - - def report_vault_write(self, future: futures.Future[Any]) -> None: - if exc := future.exception(): - self.log.error(f"Vault write failed: {exc!r}") - - def wait_vault_writes(self) -> None: - """Block until every queued vault write has run, then log the total once.""" - self.VAULT_WRITER.submit(lambda: None).result() - if not (self.vault_cache_tally and self.vault_cache_tally[0]): - self.vault_cache_tally = None - return - kids, successful_caches = self.vault_cache_tally - keys = len(kids) - self.vault_cache_tally = None - self.log.info(f"Cached {keys} Key{'' if keys == 1 else 's'} to {successful_caches}/{len(self.vaults)} Vaults") - - def take_server_keys(self, source: "ServerKeySource", title: Title_T, cdm_only: bool) -> None: - """Put the content keys of ``source`` on the tracks of ``title``, drop the null keys, then cache the rest.""" - source.resolve_server_keys(title) - for track in title.tracks: - for drm in track.drm or []: - drop_null_keys(drm) - if not cdm_only: - self.prefer_vault_keys(source, title) - self.cache_resolved_keys(source, title) - - def prefer_vault_keys(self, source: "ServerKeySource", title: Title_T) -> None: - """Let the client vaults answer before a content key the server batch licence returned. - - The client only learns the KIDs from the batch response, so the server has already - answered. A vault key still goes first, so ``decrypt_verified`` proves it and flags a - poisoned row; the server key waits as the next candidate. A server CDM key is trusted - like a local CDM key: it goes to the run cache and the vaults, and a retry after a - flagged vault key takes it before any vault. A server vault key is unproven, so it - waits in ``Vaults.candidates`` and gets the same check when its turn comes. Only the KIDs - the DRM names are looked up, each once, so sibling keys add no remote vault requests. - """ - looked_up: dict[UUID, tuple[Optional[str], Any]] = {} - for track in title.tracks: - for drm in getattr(track, "drm", None) or []: - content_keys = getattr(drm, "content_keys", {}) - named = set(real_kids(drm) or content_keys) - for kid, server_key in list(content_keys.items()): - if kid not in named: - continue - if kid not in looked_up: - looked_up[kid] = self.vaults.get_key(kid) - vault_key, vault = looked_up[kid] - if not vault_key or vault_key == server_key: - continue - drm.content_keys[kid] = vault_key - server_vault = source.vault_source(kid, server_key) - if server_vault is not None: - self.vaults.candidates.setdefault(kid, []).append((server_key, server_vault)) - elif kid not in self.LICENSE_KEY_CACHE: - self.LICENSE_KEY_CACHE[kid] = server_key - self.flush_vault_writes([partial(self.cache_keys_to_vaults, {kid: server_key})]) - self.log.debug( - f"{vault.name} holds a different key for {kid.hex} than the server, testing it first" - ) - - def cache_resolved_keys(self, source: "ServerKeySource", title: Title_T) -> None: - """Cache the keys a batch licence or an import put on the tracks. - - Both fill track.drm before any prepare_drm call, so this is the only point where those - keys can still reach the local vaults. A content key a local vault already holds is not pushed again. - """ - resolved = { - kid: key - for track in title.tracks - for drm in (getattr(track, "drm", None) or []) - for kid, key in getattr(drm, "content_keys", {}).items() - if kid not in self.LICENSE_KEY_CACHE - and source.vault_source(kid, key) is None - and self.vaults.sources.get(kid, (None,))[0] != key - } - keys = {kid: key for kid, key in resolved.items() if not self.vaults.held_locally(kid, key)} - if keys: - self.LICENSE_KEY_CACHE.update(keys) - self.flush_vault_writes([partial(self.cache_keys_to_vaults, keys)]) - - def cache_keys_to_vaults(self, content_keys: dict[UUID, str]) -> None: - """Store licence keys in every vault. A licence key clears a flag on its pair first: the - flag came from a decode check that was wrong, and a local vault refuses a flagged pair.""" - if not content_keys or not self.vaults: - return - self.vaults.clear_licensed_flags(content_keys) - successful_caches = self.vaults.add_keys(cast(dict[Union[UUID, str], str], content_keys)) - kids, caches = self.vault_cache_tally or (set(), successful_caches) - self.vault_cache_tally = (kids | content_keys.keys(), min(caches, successful_caches)) - - @classmethod - def drm_lock(cls, drm: DRM_T) -> Lock: - """Return the lock for one DRM's set of content keys. - - Tracks that share KIDs still take turns, so the second one finds the content keys in - LICENSE_KEY_CACHE and skips the challenge. Tracks with different KIDs query the key vaults - at the same time; their licences take turns under ``take_licence_turn``. - - Callers take the lock after get_drm_for_cdm(), which folds a track's sibling PlayReady - objects into the returned one, so the KID set is complete for that track's DRM list - before the lock is chosen. This holds because every manifest parser gives the tracks - that share a PlayReady object the same DRM list (ISM attaches one list to all tracks; - DASH and HLS build a list per track). Two tracks that share one object but list - different siblings would get different locks. - """ - kids = getattr(drm, "kids", None) or [] - key = ",".join(sorted(getattr(k, "hex", str(k)) for k in kids)) or getattr(drm, "content_id", None) - with cls.DRM_LOCKS_GUARD: - return cls.DRM_LOCKS.setdefault(key or type(drm).__name__, Lock()) - - def take_licence_turn( - self, - turn: ExitStack, - drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa], - kids: list[UUID], - track: AnyTrack, - track_kid: Optional[UUID], - cek_tree: Optional[Tree], - ) -> None: - """Hold LICENCE_LOCK until ``turn`` closes, then take the content keys of ``kids`` an earlier licence cached. - - One licence can carry the keys of a DRM with other KIDs, so licences take turns. The caller - holds its ``drm_lock`` first, so the vault lookups before this still run at the same time. - """ - turn.enter_context(self.LICENCE_LOCK) - if DOWNLOAD_CANCELLED.is_set(): - raise DownloadCancelled() - for kid in kids: - if kid not in drm.content_keys: - self.take_cached_key(drm, kid, track, track_kid, cek_tree) - - def take_cached_key( - self, - drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa], - kid: UUID, - track: AnyTrack, - track_kid: Optional[UUID], - cek_tree: Optional[Tree], - ) -> bool: - """Give the DRM the content key LICENSE_KEY_CACHE holds for ``kid``, and return whether it held one.""" - key = self.LICENSE_KEY_CACHE.get(kid) - if not key: - return False - drm.content_keys[kid] = key - if cek_tree is not None: - self.add_key_label(cek_tree, kid, key, track_kid, "from cache") - log_event( - "license_cache_hit", - level="INFO", - service=self.service, - context={"kid": kid.hex, "content_key": key, "track": str(track), "drm_type": type(drm).__name__}, + """Build the run's content-key resolution and make its verified decrypt the decrypt hook.""" + self.keys = ContentKeyResolver( + self.vaults, + self, + service, + self.service, + source=self._remote_service, + cdm_only=cdm_only, + vaults_only=vaults_only, + best_available=best_available, + export=partial(self.write_export, export) if export else None, + debug_logger=self.debug_logger, ) - return True - - def take_vault_key( - self, - drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa], - kid: UUID, - track: AnyTrack, - track_kid: Optional[UUID], - cek_tree: Optional[Tree], - ) -> bool: - """Give the DRM the content key a key vault holds for ``kid``, cache it for the run, and return whether one did.""" - key, vault = self.vaults.get_key(kid) - if not key: - return False - drm.content_keys[kid] = key - self.LICENSE_KEY_CACHE[kid] = key - if cek_tree is not None: - self.add_key_label(cek_tree, kid, key, track_kid, f"from {vault}") - if self.debug_logger: - self.debug_logger.log_vault_query( - vault_name=str(vault), - operation="get_key_success", - service=self.service, - context={ - "kid": kid.hex, - "content_key": key, - "track": str(track), - "from_cache": True, - "drm_type": type(drm).__name__, - }, - ) - return True - - @staticmethod - def with_track_kid(drm: Any, track_kid: Optional[UUID]) -> list[UUID]: - """Return the KIDs the DRM names, plus the track's own KID when the DRM leaves it out.""" - kids = list(getattr(drm, "kids", None) or []) - if track_kid and track_kid not in kids: - kids.append(track_kid) - return kids - - def take_known_keys( - self, - drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa], - kids: list[UUID], - track: AnyTrack, - track_kid: Optional[UUID], - cek_tree: Optional[Tree], - use_cache: bool = True, - use_vaults: bool = True, - stop_at_miss: bool = False, - ) -> list[UUID]: - """Give the DRM the content keys of ``kids`` the run cache or a key vault holds, and return the KIDs still missing. - - ``stop_at_miss`` returns at the first miss, so no more vaults are asked for a run that fails anyway. - """ - missing = [] - for kid in kids: - if kid in drm.content_keys: - if cek_tree is not None: - self.add_key_label(cek_tree, kid, drm.content_keys[kid], track_kid) - continue - if use_cache and self.take_cached_key(drm, kid, track, track_kid, cek_tree): - continue - if not (use_vaults and self.take_vault_key(drm, kid, track, track_kid, cek_tree)): - missing.append(kid) - if stop_at_miss: - break - return missing - - def license_drm( - self, - drm: Union[ClearKeyCENC, Widevine, PlayReady], - get_keys: Callable[[], None], - track: AnyTrack, - title: Title_T, - track_kid: Optional[UUID], - table: Table, - cdm_only: bool, - vaults_only: bool, - force: bool, - ) -> None: - """Give a Widevine, PlayReady or ClearKey DRM its content keys: run cache, then key vaults, then ``get_keys``. - - A held key for ``track_kid`` skips the licence, as the file is encrypted with that KID; - ``decrypt_verified`` licenses any other KID the file turns out to use. - ``force`` skips the run cache, so the licence runs again for each KID no vault answers. - A licence can answer a KID with a blank or null key; a vault key for that KID wins. - """ - pssh: Optional[str] = None - if isinstance(drm, ClearKeyCENC): - name = "ClearKey" - else: - name = type(drm).__name__ - pssh = drm.pssh.dumps() if isinstance(drm, Widevine) else drm.pssh_b64 or "" - if pssh is not None and self.debug_logger: - self.debug_logger.log_drm_operation( - drm_type=name, - operation="prepare_drm", - service=self.service, - context={ - "track": str(track), - "title": str(title), - "pssh": pssh, - "kids": [k.hex for k in drm.kids], - "track_kid": track_kid.hex if track_kid else None, - }, - ) - pending_vault_writes: list[Callable[[], Any]] = [] - with self.drm_lock(drm), ExitStack() as licence_turn: - label = [(f"({self.truncate_pssh_for_display(pssh, name)})", "text")] if pssh is not None else [] - cek_tree = Tree(Text.assemble((name, "cyan"), *label, overflow="fold")) - pre_existing_tree = next( - (x for x in table.columns[0].cells if isinstance(x, Tree) and x.label == cek_tree.label), None - ) - if pre_existing_tree: - cek_tree = pre_existing_tree - - def show_error(msg: str) -> None: - cek_tree.add(f"[logging.level.error]{msg}") - if not pre_existing_tree: - table.add_row(cek_tree) - self.flush_vault_writes(pending_vault_writes) - - all_kids = self.with_track_kid(drm, track_kid) - stop_at_miss = vaults_only and not cdm_only - missing = self.take_known_keys( - drm, all_kids, track, track_kid, cek_tree, not force, not cdm_only, stop_at_miss - ) - if missing and stop_at_miss: - msg = f"No Vault has a Key for {missing[0].hex} and --vaults-only was used" - log_event( - "vault_key_not_found", - level="ERROR", - service=self.service, - message=msg, - context={"kid": missing[0].hex, "track": str(track), "drm_type": type(drm).__name__}, - ) - show_error(msg) - raise drm.Exceptions.CEKNotFound(msg) - - need_license = bool(missing) and (force or not track_kid or track_kid not in drm.content_keys) - if need_license: - # force licenses again, so the turn takes no cached keys - self.take_licence_turn(licence_turn, drm, [] if force else all_kids, track, track_kid, cek_tree) - need_license = not all(kid in drm.content_keys for kid in all_kids) - - if need_license and not vaults_only: - from_vaults = drm.content_keys.copy() - log_event( - "get_license", - level="INFO", - service=self.service, - message=f"Requesting {name} license from service", - context={ - "track": str(track), - "drm_type": type(drm).__name__, - "kids_needed": [k.hex for k in all_kids if k not in drm.content_keys], - }, - ) - try: - get_keys() - except Exception as e: - if drm.content_keys and (not track_kid or track_kid in drm.content_keys): - self.log.warning( - f"Licence failed, using the {len(drm.content_keys)} known key(s): {redact_secrets(str(e))}" - ) - else: - if isinstance(e, (drm.Exceptions.EmptyLicense, drm.Exceptions.CEKNotFound)): - msg = str(e) - else: - msg = f"An exception occurred in the Service's license function: {e}" - if self.debug_logger: - self.debug_logger.log_error( - "get_license" if name == "Widevine" else f"get_license_{name.lower()}", - e, - service=self.service, - context={ - "track": str(track), - "exception_type": type(e).__name__, - "drm_type": type(drm).__name__, - }, - ) - show_error(msg) - raise - else: - log_event( - "license_keys_retrieved", - level="INFO", - service=self.service, - context={ - "track": str(track), - "drm_type": type(drm).__name__, - "keys_count": len(drm.content_keys), - "kids": [k.hex for k in drm.content_keys.keys()], - }, - ) - - for kid, key in drm.content_keys.items(): - self.add_key_label(cek_tree, kid, f"[red]{key}[/]" if is_null_key(key) else key, track_kid) - drop_null_keys(drm) - drm.content_keys.update(from_vaults) - self.LICENSE_KEY_CACHE.update(drm.content_keys) - pending_vault_writes.append( - partial( - self.cache_keys_to_vaults, - {k: v for k, v in drm.content_keys.items() if k not in from_vaults}, - ) - ) - - if track_kid and track_kid not in drm.content_keys: - msg = f"No Content Key for KID {track_kid.hex} was returned in the License" - show_error(msg) - raise drm.Exceptions.CEKNotFound(msg) - - if cek_tree.children and not pre_existing_tree: - table.add_row() - table.add_row(cek_tree) - - self.flush_vault_writes(pending_vault_writes) - - @staticmethod - def add_key_label(tree: Tree, kid: UUID, key: str, track_kid: Optional[UUID] = None, source: str = "") -> None: - """Add ``kid:key`` to a content key tree once, with ``*`` on the track's own KID and ``source`` after it.""" - if any(f"{kid.hex}:{key}" in str(x.label) for x in tree.children): - return - label = f"[text2]{kid.hex}:{key}" - if kid == track_kid: - label += "*" - if source: - label += f" {source}" - tree.add(label) - - def service_licence(self, service: Service, drm_system: Optional[str] = None, **kwargs: Any) -> Any: - """Call the service's licence function for the track's DRM system. - - Arguments go through declared_kwargs, so a service receives only the ones its own - licence function declares. - - prepare_drm passes drm_system so the choice follows the track, not the loaded CDM: - a track downloading at the same time can swap self.cdm. - """ - if drm_system is None: - drm_system = "playready" if is_playready_cdm(self.cdm) else "widevine" - fn = service.get_playready_license if drm_system == "playready" else service.get_widevine_license - return fn(**declared_kwargs(fn, kwargs)) + verify.DECRYPT_HOOK = self.keys.decrypt_verified def cdm_for(self, system: str, quality: Optional[int] = None) -> Optional[object]: """Get the CDM for one DRM system, ``widevine`` or ``playready``. @@ -4595,301 +3986,6 @@ class dl: cdm = self.get_cdm(self.service, self.profile, drm=system) return cdm - def licence_one_drm(self, prepare: Callable, drm: Union[Widevine, PlayReady], track_kid: Optional[UUID]) -> None: - """Send one challenge for the KIDs of this DRM, also when the DRM or a vault has the content keys. - - This is the ``--cdm-only`` path. The challenge goes out the first time a run sees the KIDs - for the DRM system. - - prepare_drm asks the CDM only for a KID with no content key, so the content keys the DRM - holds are removed for the call and put back after it. - """ - kids = {*drm.kids, *([track_kid] if track_kid else [])} - attempted = self.all_drm_attempted[type(drm)] - if kids <= attempted: - prepare(drm, track_kid=track_kid) - return - with self.drm_lock(drm): - held = dict(drm.content_keys) - drm.content_keys.clear() - try: - prepare(drm, track_kid=track_kid, cdm_only=True, force=True) - finally: - attempted |= kids - with self.drm_lock(drm): - for held_kid, key in held.items(): - drm.content_keys.setdefault(held_kid, key) - - def licence_all_drm( - self, - prepare: Callable, - track: AnyTrack, - tolerate: bool, - drm: DRM_T, - track_kid: Optional[UUID] = None, - force: bool = False, - ) -> None: - """License the track with each DRM system it offers, not only the one the downloader selected. - - A DRM system sends a challenge only for a KID that no vault and no earlier track gave a - content key for. With ``force``, each DRM system sends one challenge for a set of KIDs in - a run. A DRM system that fails stops the title. With ``tolerate`` it is a warning, if the - other DRM system gave the content key of the track. - """ - if not isinstance(drm, (Widevine, PlayReady)): - prepare(drm, track_kid=track_kid) - return - - other_type = PlayReady if type(drm) is Widevine else Widevine - others = [d for d in track.drm or [] if isinstance(d, (Widevine, PlayReady)) and type(d) is other_type] - if other_type is PlayReady and len(others) > 1: - playready = [d for d in others if isinstance(d, PlayReady)] - playready[0].absorb(*playready[1:]) - if not others and other_type.__name__ not in self.all_drm_warned: - self.all_drm_warned.add(other_type.__name__) - self.log.warning( - f"Track {track} has no {other_type.__name__} DRM, licensing with {type(drm).__name__} only" - ) - - targets = [drm, *others[:1]] - error: Optional[Exception] = None - with self.ALL_DRM_LOCK: - loaded_cdm = self.cdm - try: - for target in targets: - kid = track_kid if target is drm or track_kid in target.kids else None - try: - if force: - self.licence_one_drm(prepare, target, kid) - else: - prepare(target, track_kid=kid) - except Exception as e: - if not tolerate: - raise - self.log.warning(f"{type(target).__name__} licence failed for {track}: {e}") - error = error or e - - keys = {kid: key for target in targets for kid, key in target.content_keys.items()} - for target in targets: - with self.drm_lock(target): - for kid, key in keys.items(): - target.content_keys.setdefault(kid, key) - finally: - self.cdm = loaded_cdm - - track_keys = getattr(drm, "content_keys", {}) - if error and (not track_keys or (track_kid and track_kid not in track_keys)): - raise error - - def prepare_drm( - self, - drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa], - track: AnyTrack, - title: Title_T, - certificate: Callable, - licence: Callable, - clearkey_licence: Optional[Callable] = None, - track_kid: Optional[UUID] = None, - table: Optional[Table] = None, - cdm_only: bool = False, - vaults_only: bool = False, - export: Optional[Path] = None, - service_session: Optional[Any] = None, - force: bool = False, - ) -> None: - """ - Prepare the DRM by getting decryption data like KIDs, Keys, and such. - The DRM object should be ready for decryption once this function ends. - ``force`` skips the content keys of earlier tracks in this run. The CDM then licenses - again for each KID the DRM holds no content key for. - """ - if not drm: - return - assert table is not None - - remote = self._remote_service - server_cdm = bool(remote and remote.server_cdm) - licensed_locally = bool(remote and remote.licenses_locally(track)) - - if server_cdm and not licensed_locally: - assert remote is not None - with self.drm_lock(drm), ExitStack() as licence_turn: - pending_vault_writes: list[Callable[[], Any]] = [] - vault_kids = self.with_track_kid(drm, track_kid) - self.take_known_keys(drm, vault_kids, track, track_kid, None, use_vaults=not cdm_only) - - def missing_track_key() -> bool: - return not drm.content_keys or bool(track_kid and track_kid not in drm.content_keys) - - if missing_track_key(): - self.take_licence_turn(licence_turn, drm, vault_kids, track, track_kid, None) - known_keys = set(drm.content_keys) - - if missing_track_key(): - from unshackle.core.remote_service import RemoteError - - try: - licence( - drm_system="playready" if drm.__class__.__name__ == "PlayReady" else "widevine", - challenge=b"", - kid=track_kid, - ) - except click.ClickException: - raise - except (Exception, RemoteError) as e: - self.log.debug(f"Server CDM licence with an empty challenge failed: {e!r}") - drop_null_keys(drm) - - new_keys = {} - for kid, key in drm.content_keys.items(): - source = None if cdm_only else remote.vault_source(kid, key) - if source is not None: - self.vaults.sources[kid] = (key, source) - elif kid not in known_keys: - new_keys[kid] = key - if new_keys: - self.LICENSE_KEY_CACHE.update(new_keys) - pending_vault_writes.append(partial(self.cache_keys_to_vaults, new_keys)) - self.flush_vault_writes(pending_vault_writes) - - # the server can refuse the licence above its cap and hand the track to this machine - licensed_locally = bool(remote and remote.licenses_locally(track)) - if server_cdm and not licensed_locally: - if not drm.content_keys: - self.log.warning("Server CDM did not resolve any keys for this track") - return - if track_kid and track_kid not in drm.content_keys: - msg = f"No Content Key for KID {track_kid.hex} was returned by the server CDM" - if isinstance(drm, PlayReady): - raise PlayReady.Exceptions.CEKNotFound(msg) - raise Widevine.Exceptions.CEKNotFound(msg) - assert remote is not None - server_drm_type = remote.server_cdm_type - drm_name = {"widevine": "Widevine", "playready": "PlayReady"}.get(server_drm_type, drm.__class__.__name__) - log_event( - "drm_content_keys", - level="INFO", - message=f"Server CDM resolved {len(drm.content_keys)} {drm_name} content key(s)", - service=self.service, - drm_type=drm_name, - key_count=len(drm.content_keys), - keys=[{"kid": k.hex, "key": v} for k, v in drm.content_keys.items()], - remote=True, - ) - with self.drm_lock(drm): - pssh_str = "" - expected_class = "PlayReady" if server_drm_type == "playready" else "Widevine" - matching_drm = next( - (d for d in (track.drm or []) if d.__class__.__name__ == expected_class), - drm, - ) - if hasattr(matching_drm, "pssh") and matching_drm.pssh: - if hasattr(matching_drm.pssh, "dumps"): - pssh_str = self.truncate_pssh_for_display(matching_drm.pssh.dumps(), drm_name) - elif hasattr(matching_drm, "data") and matching_drm.data.get("pssh_b64"): - pssh_str = self.truncate_pssh_for_display(matching_drm.data["pssh_b64"], drm_name) - if pssh_str: - cek_tree = Tree(Text.assemble((drm_name, "cyan"), (f"({pssh_str})", "text"), overflow="fold")) - else: - cek_tree = Tree(Text.assemble((drm_name, "cyan"), overflow="fold")) - all_kids = self.with_track_kid(drm, track_kid) - for kid in all_kids: - if kid in drm.content_keys: - self.add_key_label(cek_tree, kid, drm.content_keys[kid], track_kid) - for kid, key in drm.content_keys.items(): - if kid not in all_kids: - self.add_key_label(cek_tree, kid, key) - if not any(isinstance(x, Tree) and x.label == cek_tree.label for x in table.columns[0].cells): - table.add_row(cek_tree) - if export: - self.write_export(export, title, track, drm) - return - - track_quality = None - if isinstance(track, Video) and track.height: - track_quality = track.height - elif title is not None: - track_quality = max((v.height for v in title.tracks.videos if v.height), default=None) - - track_cdm = self.cdm - if licensed_locally: - assert remote is not None - track_cdm = remote.local_cdm - local_drm = track.get_drm_for_cdm(track_cdm) - if isinstance(local_drm, (Widevine, PlayReady)) and isinstance(local_drm, PlayReady) != is_playready_cdm( - track_cdm - ): - track_cdm = self.cdm_for("playready" if isinstance(local_drm, PlayReady) else "widevine", track_quality) - if local_drm is not None and local_drm is not drm: - assert not isinstance(local_drm, ClearKey) - # a mid-download handover leaves drm on the server's DRM system, and the caller decrypts with it - self.prepare_drm( - local_drm, - track, - title, - certificate, - licence, - clearkey_licence, - track_kid, - table, - cdm_only, - vaults_only, - export, - service_session, - ) - with self.drm_lock(drm): - drm.content_keys.update(local_drm.content_keys) - return - - drm_system = "playready" if isinstance(drm, PlayReady) else "widevine" - licence = partial(licence, drm_system=drm_system) - - if not server_cdm and isinstance(drm, (Widevine, PlayReady)): - matches = is_playready_cdm if drm_system == "playready" else is_widevine_cdm - if not matches(self.cdm): - name, other = ("PlayReady", "Widevine") if drm_system == "playready" else ("Widevine", "PlayReady") - system_cdm = self.cdm_for(drm_system, track_quality) - if system_cdm and matches(system_cdm): - self.log.info(f"Switching to the {name} CDM") - self.cdm = system_cdm - track_cdm = system_cdm - elif self.cdm is None: - raise click.ClickException(f"No CDM configured for {self.service} and no default CDM") - else: - raise ValueError(f"Title needs a {name} CDM but {self.service} is configured with {other}.") - - if isinstance(drm, (Widevine, PlayReady, ClearKeyCENC)): - if isinstance(drm, ClearKeyCENC): - get_keys = partial( - drm.get_content_keys, licence=clearkey_licence or (lambda **_: None), session=service_session - ) - else: - get_keys = partial(drm.get_content_keys, cdm=track_cdm, licence=licence, certificate=certificate) - self.license_drm(drm, get_keys, track, title, track_kid, table, cdm_only, vaults_only, force) - if export: - self.write_export(export, title, track, drm) - - elif isinstance(drm, MonaLisa): - with self.drm_lock(drm): - display_id = drm.content_id or drm.pssh - pssh_display = self.truncate_pssh_for_display(display_id, "MonaLisa") - cek_tree = Tree(Text.assemble(("MonaLisa", "cyan"), (f"({pssh_display})", "text"), overflow="fold")) - pre_existing_tree = next( - (x for x in table.columns[0].cells if isinstance(x, Tree) and x.label == cek_tree.label), None - ) - if pre_existing_tree: - cek_tree = pre_existing_tree - - for kid_, key in drm.content_keys.items(): - self.add_key_label(cek_tree, kid_, key, track_kid=kid_) # every MonaLisa key is the track's own - - if cek_tree.children and not pre_existing_tree: - table.add_row() - table.add_row(cek_tree) - - if export: - self.write_export(export, title, track, drm) - @staticmethod def get_cookie_path(service: str, profile: Optional[str]) -> Optional[Path]: """Get Service Cookie File Path for Profile.""" diff --git a/unshackle/core/drm/key_resolution.py b/unshackle/core/drm/key_resolution.py new file mode 100644 index 00000000..7a2f8930 --- /dev/null +++ b/unshackle/core/drm/key_resolution.py @@ -0,0 +1,988 @@ +"""Content-key resolution: how a track's content keys are found, checked and stored.""" + +from __future__ import annotations + +import logging +import os +from collections import defaultdict +from concurrent import futures +from concurrent.futures import ThreadPoolExecutor +from contextlib import ExitStack +from functools import partial +from pathlib import Path +from threading import Lock +from typing import TYPE_CHECKING, Any, Callable, Optional, Protocol, Union, cast +from uuid import UUID + +import click +from rich.table import Table +from rich.text import Text +from rich.tree import Tree + +from unshackle.core import binaries +from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm +from unshackle.core.console import console +from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack, DownloadCancelled +from unshackle.core.drm import ( + DRM_T, + ClearKey, + ClearKeyCENC, + MonaLisa, + PlayReady, + Widevine, + drop_null_keys, + is_null_key, + real_kids, + verify, +) +from unshackle.core.service import Service +from unshackle.core.titles import Title_T +from unshackle.core.tracks import Video +from unshackle.core.utilities import declared_kwargs, log_event +from unshackle.core.utils.redact import redact_secrets +from unshackle.core.utils.subprocess import ffmpeg_decodes +from unshackle.core.vault import Vault +from unshackle.core.vaults import Vaults + +if TYPE_CHECKING: + from unshackle.core.remote_service import ServerKeySource + from unshackle.core.utilities import DebugLogger + + +def truncate_pssh_for_display(pssh_string: str, drm_type: str) -> str: + """Truncate PSSH string for display when not in debug mode.""" + if logging.root.level == logging.DEBUG or not pssh_string: + return pssh_string + + max_width = console.width - len(drm_type) - 12 + if len(pssh_string) <= max_width: + return pssh_string + + return pssh_string[: max_width - 3] + "..." + + +class CdmChooser(Protocol): + """The CDM a run licenses with, which resolution can switch, and a chooser for one DRM system.""" + + cdm: Any + + def cdm_for(self, system: str, quality: Optional[int] = None) -> Optional[object]: ... + + +class ContentKeyResolver: + """Content-key resolution for one dl run. + + The order of key sources is: the keys a server key source gave, the keys this run already + holds, the key vaults, then a licence from the CDM. The interface is ``take_server_keys``, + ``licence_for``, ``decrypt_verified`` and ``wait_vault_writes``. The locks, the key + cache and the vault writer are class-level, so every run in one process shares them. + """ + + DRM_LOCKS: dict[str, Lock] = {} + DRM_LOCKS_GUARD = Lock() + LICENCE_LOCK = Lock() + VAULT_WRITER = ThreadPoolExecutor(1, thread_name_prefix="vault-writer") + LICENSE_KEY_CACHE: dict[UUID, str] = {} + ALL_DRM_LOCK = Lock() + + def __init__( + self, + vaults: Vaults, + cdms: CdmChooser, + service: Service, + tag: str, + source: Optional[ServerKeySource] = None, + cdm_only: bool = False, + vaults_only: bool = False, + best_available: bool = False, + export: Optional[Callable[[Title_T, AnyTrack, Any], None]] = None, + debug_logger: Optional[DebugLogger] = None, + ) -> None: + self.log = logging.getLogger("download") + self.vaults = vaults + self.cdms = cdms + self.service = service + self.tag = tag + self.source = source + self.cdm_only = cdm_only + self.vaults_only = vaults_only + self.best_available = best_available + self.export = export + self.debug_logger = debug_logger + self.vault_cache_tally: Optional[tuple[set[UUID], int]] = None + self.all_drm_attempted: defaultdict[type, set[UUID]] = defaultdict(set) + self.all_drm_warned: set[str] = set() + + def licence_for(self, track: AnyTrack, title: Title_T, table: Table, all_drm: bool = False) -> partial: + """The licence callback for ``track``: call it as ``fn(drm, track_kid=None)``. + + It gives the DRM its content keys and adds the key tree to ``table``. With ``all_drm`` it + licenses each DRM system the track offers. + """ + prepare = partial(self.prepare_drm, track=track, title=title, table=table, cdm_only=self.cdm_only) + if all_drm: + return partial(self.licence_all_drm, prepare, track, self.best_available, force=self.cdm_only) + return prepare + + def decrypt_verified( + self, + drm: DRM_T, + path: Path, + licence: Optional[Callable] = None, + track_kid: Optional[UUID] = None, + decrypt: bool = True, + ) -> None: + """Decrypt the file, and when a vault supplied a content key, prove the output decodes. + + A poisoned vault returns the right KID with a wrong content key, and the decrypters + accept it without complaint. A content key from a vault is therefore trusted, and only + then copied to the other vaults, once FFmpeg can decode the result. Without FFmpeg + neither happens. For a fragmented MP4, ``verify.kid_windows`` reads from the ciphertext + which fragments each KID encrypts, and FFmpeg decodes windows inside each KID's + fragments, so only a KID that fails is flagged. A complete map does not judge a KID it does + not hold, so a clear file judges and copies no KID. A KID that is not in an incomplete map, + and every KID of any other file, gets a start and end check of the whole file, and a + failure there flags each of those KIDs. On failure the pair is flagged in the local + vaults, the ciphertext is restored, and the licence runs again; ``Vaults`` tells the + vault that served it. Every vault skips a flagged pair, so each pass burns at most one + vault; when the vaults run out the CDM answers, and a CDM key is not checked. A CDM + that returns the flagged key clears the flag and stores the content key again, because + then the decode check was wrong. + + With ``decrypt=False`` the downloader already decrypted the segments in place, so a + failure can only flag and raise; the next run skips the flagged pair. + + Before the decrypt, each KID the DRM names without a content key is licensed when the file + uses it, or when the file cannot be mapped, because ``prepare_drm`` licensed only for the track's KID. + """ + keys: Any = getattr(drm, "content_keys", None) + if keys is None: + if decrypt: + drm.decrypt(path) + return + + def flagged_kids() -> list[UUID]: + """The KIDs on this track whose content key another track already proved wrong.""" + return [kid for kid, key in keys.items() if (kid, key) in self.vaults.flagged] + + def drop(kid: UUID) -> str: + key = keys.pop(kid) + if self.LICENSE_KEY_CACHE.get(kid) == key: + self.LICENSE_KEY_CACHE.pop(kid) + return key + + def relicense(bad: dict[UUID, str], kids: dict[UUID, Vault]) -> None: + """Licence again for each dropped KID, then settle each dropped pair against the new key. + + prepare_drm licenses only for a KID it is told to need, so without the second call a + track that still holds other content keys would decrypt without the dropped one. A + licence can replace the DRM's dict, so ``keys`` is read from the DRM again afterwards. + A licence key equal to the dropped one proves the decode check wrong and clears its flag. + """ + nonlocal keys + if not licence: + return + licence(drm, track_kid=track_kid) + for kid in sorted(bad): + if kid != track_kid and kid not in getattr(drm, "content_keys", {}): + licence(drm, track_kid=kid) + keys = getattr(drm, "content_keys", keys) + for kid, key in bad.items(): + new = keys.get(kid) + if new is None: + continue + source = self.vaults.sources.get(kid) + if source is None: + if new == key: + self.vaults.unflag_bad_key(kid, key) + self.flush_vault_writes([partial(self.vaults.add_key, kid, key)]) + elif not self.vaults.held_locally(kid, new): + self.flush_vault_writes([partial(self.vaults.add_key, kid, new)]) + elif new == key and kid in kids and source[1] is kids[kid]: + raise ValueError(f"{key} from {kids[kid].name} was bad and no other source has the key") + + known_bad = flagged_kids() + if known_bad and licence: + relicense({kid: drop(kid) for kid in known_bad}, {}) + + unkeyed = [kid for kid in getattr(drm, "kids", None) or [] if kid not in keys] + mapped = bool(unkeyed and decrypt and licence) + kid_map = verify.kid_windows(path) if mapped else None + if mapped and licence: + for kid in unkeyed: + if kid_map is None or kid in kid_map.windows: + licence(drm, track_kid=kid) + keys = getattr(drm, "content_keys", keys) + + def vault_kids() -> dict[UUID, Vault]: + """The KIDs whose key on the track came from a vault, with that vault.""" + found = {kid: self.vaults.sources.get(kid) for kid in keys} + return {kid: src[1] for kid, src in found.items() if src and src[0] == keys[kid]} + + backup = path.with_name(path.name + ".enc") + backup.unlink(missing_ok=True) # a killed run leaves one behind; its bytes may not match + checking = bool(vault_kids() and decrypt and binaries.FFMPEG) + if checking: + try: + os.link(path, backup) + except OSError as e: + self.log.debug(f"Cannot keep the ciphertext for a decrypt retry: {e!r}") + kid_map = (kid_map if mapped else verify.kid_windows(path)) if checking else None + windows = kid_map.windows if kid_map else {} + video = kid_map.video if kid_map else None + + def window_decodes(start: float, end: float) -> bool: + return ffmpeg_decodes(path, start=start, seconds=end - start if end > start else 0.5, video=video) + + def judged_kids() -> dict[UUID, Vault]: + """The vault KIDs this file can judge. A map whose KIDs all have keys skips the KIDs it lacks.""" + kids = vault_kids() + if kid_map is not None and all(kid in keys for kid in windows): + return {kid: vault for kid, vault in kids.items() if kid in windows} + return kids + + def failed_kids(kids: dict[UUID, Vault]) -> set[UUID]: + """The vault KIDs whose content key did not decode. + + A KID in the KID map fails when one of its windows fails. The KIDs that are not in the + map share the verdict of one start and end check of the whole file, taken only when + every mapped KID passed: a wrong mapped key fails that check too and would flag them + for noise that is not theirs. The retry judges them again with the replaced key. + """ + failed = {kid for kid in kids if kid in windows and not all(window_decodes(*w) for w in windows[kid])} + absent = {kid for kid in kids if kid not in windows} + if absent and not failed and not ffmpeg_decodes(path, video=video): + failed |= absent + self.log.debug( + f"Key check on {path.name}: {len(kids) - len(absent)} KID(s) by fragment window, " + f"{len(absent)} by whole-file check, failed {sorted(k.hex for k in failed)}" + ) + return failed + + def passes_left(done: int) -> bool: + """One pass per source that can still answer: every loaded vault, the server's vaults as + one source that walks them itself over --remote, and one for the CDM.""" + remote = 1 if self.source and self.source.server_cdm else 0 + return done < len(self.vaults) + remote + 1 + + try: + done = 0 + while passes_left(done): + done += 1 + if decrypt: + drm.decrypt(path) + kids = judged_kids() + stale = flagged_kids() + failed: set[UUID] = set() + if not stale: + checked = bool(kids and binaries.FFMPEG and path.exists()) + failed = failed_kids(kids) if checked else set() + if not failed: + if checked: + self.flush_vault_writes( + [ + partial(self.vaults.add_key, kid, keys[kid], excluding=vault) + for kid, vault in kids.items() + ] + ) + self.vaults.report_replaced(keys) + return + bad = {kid: drop(kid) for kid in {*failed, *stale}} + for kid, key in bad.items(): + if kid not in kids: + continue + self.log.warning(f"{key} from {kids[kid].name} was bad, trying other vaults") + self.vaults.flag_bad_key(kid, key) + if not backup.exists() or not licence: + raise ValueError("The content key from the vault did not decrypt the track; run again") + path.unlink() + os.link(backup, path) + relicense(bad, kids) + raise ValueError("No vault or CDM produced a content key that decrypts the track") + finally: + backup.unlink(missing_ok=True) + + def flush_vault_writes(self, pending: list[Callable[[], Any]]) -> None: + """Hand the queued vault writes to the background writer so the track does not wait on them.""" + for write in pending: + self.VAULT_WRITER.submit(write).add_done_callback(self.report_vault_write) + pending.clear() + + def report_vault_write(self, future: futures.Future[Any]) -> None: + if exc := future.exception(): + self.log.error(f"Vault write failed: {exc!r}") + + def wait_vault_writes(self) -> None: + """Block until every queued vault write has run, then log the total once.""" + self.VAULT_WRITER.submit(lambda: None).result() + if not (self.vault_cache_tally and self.vault_cache_tally[0]): + self.vault_cache_tally = None + return + kids, successful_caches = self.vault_cache_tally + keys = len(kids) + self.vault_cache_tally = None + self.log.info(f"Cached {keys} Key{'' if keys == 1 else 's'} to {successful_caches}/{len(self.vaults)} Vaults") + + def take_server_keys(self, title: Title_T) -> None: + """Put the content keys of the server key source on the tracks of ``title``, drop the null keys, then cache the rest.""" + source = self.source + if source is None: + return + source.resolve_server_keys(title) + for track in title.tracks: + for drm in track.drm or []: + drop_null_keys(drm) + if not self.cdm_only: + self.prefer_vault_keys(source, title) + self.cache_resolved_keys(source, title) + + def prefer_vault_keys(self, source: "ServerKeySource", title: Title_T) -> None: + """Let the client vaults answer before a content key the server batch licence returned. + + The client only learns the KIDs from the batch response, so the server has already + answered. A vault key still goes first, so ``decrypt_verified`` proves it and flags a + poisoned row; the server key waits as the next candidate. A server CDM key is trusted + like a local CDM key: it goes to the run cache and the vaults, and a retry after a + flagged vault key takes it before any vault. A server vault key is unproven, so it + waits in ``Vaults.candidates`` and gets the same check when its turn comes. Only the KIDs + the DRM names are looked up, each once, so sibling keys add no remote vault requests. + """ + looked_up: dict[UUID, tuple[Optional[str], Any]] = {} + for track in title.tracks: + for drm in getattr(track, "drm", None) or []: + content_keys = getattr(drm, "content_keys", {}) + named = set(real_kids(drm) or content_keys) + for kid, server_key in list(content_keys.items()): + if kid not in named: + continue + if kid not in looked_up: + looked_up[kid] = self.vaults.get_key(kid) + vault_key, vault = looked_up[kid] + if not vault_key or vault_key == server_key: + continue + drm.content_keys[kid] = vault_key + server_vault = source.vault_source(kid, server_key) + if server_vault is not None: + self.vaults.candidates.setdefault(kid, []).append((server_key, server_vault)) + elif kid not in self.LICENSE_KEY_CACHE: + self.LICENSE_KEY_CACHE[kid] = server_key + self.flush_vault_writes([partial(self.cache_keys_to_vaults, {kid: server_key})]) + self.log.debug( + f"{vault.name} holds a different key for {kid.hex} than the server, testing it first" + ) + + def cache_resolved_keys(self, source: "ServerKeySource", title: Title_T) -> None: + """Cache the keys a batch licence or an import put on the tracks. + + Both fill track.drm before any prepare_drm call, so this is the only point where those + keys can still reach the local vaults. A content key a local vault already holds is not pushed again. + """ + resolved = { + kid: key + for track in title.tracks + for drm in (getattr(track, "drm", None) or []) + for kid, key in getattr(drm, "content_keys", {}).items() + if kid not in self.LICENSE_KEY_CACHE + and source.vault_source(kid, key) is None + and self.vaults.sources.get(kid, (None,))[0] != key + } + keys = {kid: key for kid, key in resolved.items() if not self.vaults.held_locally(kid, key)} + if keys: + self.LICENSE_KEY_CACHE.update(keys) + self.flush_vault_writes([partial(self.cache_keys_to_vaults, keys)]) + + def cache_keys_to_vaults(self, content_keys: dict[UUID, str]) -> None: + """Store licence keys in every vault. A licence key clears a flag on its pair first: the + flag came from a decode check that was wrong, and a local vault refuses a flagged pair.""" + if not content_keys or not self.vaults: + return + self.vaults.clear_licensed_flags(content_keys) + successful_caches = self.vaults.add_keys(cast(dict[Union[UUID, str], str], content_keys)) + kids, caches = self.vault_cache_tally or (set(), successful_caches) + self.vault_cache_tally = (kids | content_keys.keys(), min(caches, successful_caches)) + + @classmethod + def drm_lock(cls, drm: DRM_T) -> Lock: + """Return the lock for one DRM's set of content keys. + + Tracks that share KIDs still take turns, so the second one finds the content keys in + LICENSE_KEY_CACHE and skips the challenge. Tracks with different KIDs query the key vaults + at the same time; their licences take turns under ``take_licence_turn``. + + Callers take the lock after get_drm_for_cdm(), which folds a track's sibling PlayReady + objects into the returned one, so the KID set is complete for that track's DRM list + before the lock is chosen. This holds because every manifest parser gives the tracks + that share a PlayReady object the same DRM list (ISM attaches one list to all tracks; + DASH and HLS build a list per track). Two tracks that share one object but list + different siblings would get different locks. + """ + kids = getattr(drm, "kids", None) or [] + key = ",".join(sorted(getattr(k, "hex", str(k)) for k in kids)) or getattr(drm, "content_id", None) + with cls.DRM_LOCKS_GUARD: + return cls.DRM_LOCKS.setdefault(key or type(drm).__name__, Lock()) + + def take_licence_turn( + self, + turn: ExitStack, + drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa], + kids: list[UUID], + track: AnyTrack, + track_kid: Optional[UUID], + cek_tree: Optional[Tree], + ) -> None: + """Hold LICENCE_LOCK until ``turn`` closes, then take the content keys of ``kids`` an earlier licence cached. + + One licence can carry the keys of a DRM with other KIDs, so licences take turns. The caller + holds its ``drm_lock`` first, so the vault lookups before this still run at the same time. + """ + turn.enter_context(self.LICENCE_LOCK) + if DOWNLOAD_CANCELLED.is_set(): + raise DownloadCancelled() + for kid in kids: + if kid not in drm.content_keys: + self.take_cached_key(drm, kid, track, track_kid, cek_tree) + + def take_cached_key( + self, + drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa], + kid: UUID, + track: AnyTrack, + track_kid: Optional[UUID], + cek_tree: Optional[Tree], + ) -> bool: + """Give the DRM the content key LICENSE_KEY_CACHE holds for ``kid``, and return whether it held one.""" + key = self.LICENSE_KEY_CACHE.get(kid) + if not key: + return False + drm.content_keys[kid] = key + if cek_tree is not None: + self.add_key_label(cek_tree, kid, key, track_kid, "from cache") + log_event( + "license_cache_hit", + level="INFO", + service=self.tag, + context={"kid": kid.hex, "content_key": key, "track": str(track), "drm_type": type(drm).__name__}, + ) + return True + + def take_vault_key( + self, + drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa], + kid: UUID, + track: AnyTrack, + track_kid: Optional[UUID], + cek_tree: Optional[Tree], + ) -> bool: + """Give the DRM the content key a key vault holds for ``kid``, cache it for the run, and return whether one did.""" + key, vault = self.vaults.get_key(kid) + if not key: + return False + drm.content_keys[kid] = key + self.LICENSE_KEY_CACHE[kid] = key + if cek_tree is not None: + self.add_key_label(cek_tree, kid, key, track_kid, f"from {vault}") + if self.debug_logger: + self.debug_logger.log_vault_query( + vault_name=str(vault), + operation="get_key_success", + service=self.tag, + context={ + "kid": kid.hex, + "content_key": key, + "track": str(track), + "from_cache": True, + "drm_type": type(drm).__name__, + }, + ) + return True + + @staticmethod + def with_track_kid(drm: Any, track_kid: Optional[UUID]) -> list[UUID]: + """Return the KIDs the DRM names, plus the track's own KID when the DRM leaves it out.""" + kids = list(getattr(drm, "kids", None) or []) + if track_kid and track_kid not in kids: + kids.append(track_kid) + return kids + + def take_known_keys( + self, + drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa], + kids: list[UUID], + track: AnyTrack, + track_kid: Optional[UUID], + cek_tree: Optional[Tree], + use_cache: bool = True, + use_vaults: bool = True, + stop_at_miss: bool = False, + ) -> list[UUID]: + """Give the DRM the content keys of ``kids`` the run cache or a key vault holds, and return the KIDs still missing. + + ``stop_at_miss`` returns at the first miss, so no more vaults are asked for a run that fails anyway. + """ + missing = [] + for kid in kids: + if kid in drm.content_keys: + if cek_tree is not None: + self.add_key_label(cek_tree, kid, drm.content_keys[kid], track_kid) + continue + if use_cache and self.take_cached_key(drm, kid, track, track_kid, cek_tree): + continue + if not (use_vaults and self.take_vault_key(drm, kid, track, track_kid, cek_tree)): + missing.append(kid) + if stop_at_miss: + break + return missing + + def license_drm( + self, + drm: Union[ClearKeyCENC, Widevine, PlayReady], + get_keys: Callable[[], None], + track: AnyTrack, + title: Title_T, + track_kid: Optional[UUID], + table: Table, + cdm_only: bool, + force: bool, + ) -> None: + """Give a Widevine, PlayReady or ClearKey DRM its content keys: run cache, then key vaults, then ``get_keys``. + + A held key for ``track_kid`` skips the licence, as the file is encrypted with that KID; + ``decrypt_verified`` licenses any other KID the file turns out to use. + ``force`` skips the run cache, so the licence runs again for each KID no vault answers. + A licence can answer a KID with a blank or null key; a vault key for that KID wins. + """ + pssh: Optional[str] = None + if isinstance(drm, ClearKeyCENC): + name = "ClearKey" + else: + name = type(drm).__name__ + pssh = drm.pssh.dumps() if isinstance(drm, Widevine) else drm.pssh_b64 or "" + if pssh is not None and self.debug_logger: + self.debug_logger.log_drm_operation( + drm_type=name, + operation="prepare_drm", + service=self.tag, + context={ + "track": str(track), + "title": str(title), + "pssh": pssh, + "kids": [k.hex for k in drm.kids], + "track_kid": track_kid.hex if track_kid else None, + }, + ) + pending_vault_writes: list[Callable[[], Any]] = [] + with self.drm_lock(drm), ExitStack() as licence_turn: + label = [(f"({truncate_pssh_for_display(pssh, name)})", "text")] if pssh is not None else [] + cek_tree = Tree(Text.assemble((name, "cyan"), *label, overflow="fold")) + pre_existing_tree = next( + (x for x in table.columns[0].cells if isinstance(x, Tree) and x.label == cek_tree.label), None + ) + if pre_existing_tree: + cek_tree = pre_existing_tree + + def show_error(msg: str) -> None: + cek_tree.add(f"[logging.level.error]{msg}") + if not pre_existing_tree: + table.add_row(cek_tree) + self.flush_vault_writes(pending_vault_writes) + + all_kids = self.with_track_kid(drm, track_kid) + stop_at_miss = self.vaults_only and not cdm_only + missing = self.take_known_keys( + drm, all_kids, track, track_kid, cek_tree, not force, not cdm_only, stop_at_miss + ) + if missing and stop_at_miss: + msg = f"No Vault has a Key for {missing[0].hex} and --vaults-only was used" + log_event( + "vault_key_not_found", + level="ERROR", + service=self.tag, + message=msg, + context={"kid": missing[0].hex, "track": str(track), "drm_type": type(drm).__name__}, + ) + show_error(msg) + raise drm.Exceptions.CEKNotFound(msg) + + need_license = bool(missing) and (force or not track_kid or track_kid not in drm.content_keys) + if need_license: + # force licenses again, so the turn takes no cached keys + self.take_licence_turn(licence_turn, drm, [] if force else all_kids, track, track_kid, cek_tree) + need_license = not all(kid in drm.content_keys for kid in all_kids) + + if need_license and not self.vaults_only: + from_vaults = drm.content_keys.copy() + log_event( + "get_license", + level="INFO", + service=self.tag, + message=f"Requesting {name} license from service", + context={ + "track": str(track), + "drm_type": type(drm).__name__, + "kids_needed": [k.hex for k in all_kids if k not in drm.content_keys], + }, + ) + try: + get_keys() + except Exception as e: + if drm.content_keys and (not track_kid or track_kid in drm.content_keys): + self.log.warning( + f"Licence failed, using the {len(drm.content_keys)} known key(s): {redact_secrets(str(e))}" + ) + else: + if isinstance(e, (drm.Exceptions.EmptyLicense, drm.Exceptions.CEKNotFound)): + msg = str(e) + else: + msg = f"An exception occurred in the Service's license function: {e}" + if self.debug_logger: + self.debug_logger.log_error( + "get_license" if name == "Widevine" else f"get_license_{name.lower()}", + e, + service=self.tag, + context={ + "track": str(track), + "exception_type": type(e).__name__, + "drm_type": type(drm).__name__, + }, + ) + show_error(msg) + raise + else: + log_event( + "license_keys_retrieved", + level="INFO", + service=self.tag, + context={ + "track": str(track), + "drm_type": type(drm).__name__, + "keys_count": len(drm.content_keys), + "kids": [k.hex for k in drm.content_keys.keys()], + }, + ) + + for kid, key in drm.content_keys.items(): + self.add_key_label(cek_tree, kid, f"[red]{key}[/]" if is_null_key(key) else key, track_kid) + drop_null_keys(drm) + drm.content_keys.update(from_vaults) + self.LICENSE_KEY_CACHE.update(drm.content_keys) + pending_vault_writes.append( + partial( + self.cache_keys_to_vaults, + {k: v for k, v in drm.content_keys.items() if k not in from_vaults}, + ) + ) + + if track_kid and track_kid not in drm.content_keys: + msg = f"No Content Key for KID {track_kid.hex} was returned in the License" + show_error(msg) + raise drm.Exceptions.CEKNotFound(msg) + + if cek_tree.children and not pre_existing_tree: + table.add_row() + table.add_row(cek_tree) + + self.flush_vault_writes(pending_vault_writes) + + @staticmethod + def add_key_label(tree: Tree, kid: UUID, key: str, track_kid: Optional[UUID] = None, source: str = "") -> None: + """Add ``kid:key`` to a content key tree once, with ``*`` on the track's own KID and ``source`` after it.""" + if any(f"{kid.hex}:{key}" in str(x.label) for x in tree.children): + return + label = f"[text2]{kid.hex}:{key}" + if kid == track_kid: + label += "*" + if source: + label += f" {source}" + tree.add(label) + + def service_licence(self, drm_system: Optional[str] = None, **kwargs: Any) -> Any: + """Call the service's licence function for the track's DRM system. + + Arguments go through declared_kwargs, so a service receives only the ones its own + licence function declares. + + prepare_drm passes drm_system so the choice follows the track, not the loaded CDM: + a track downloading at the same time can swap self.cdms.cdm. + """ + if drm_system is None: + drm_system = "playready" if is_playready_cdm(self.cdms.cdm) else "widevine" + fn = self.service.get_playready_license if drm_system == "playready" else self.service.get_widevine_license + return fn(**declared_kwargs(fn, kwargs)) + + def licence_one_drm(self, prepare: Callable, drm: Union[Widevine, PlayReady], track_kid: Optional[UUID]) -> None: + """Send one challenge for the KIDs of this DRM, also when the DRM or a vault has the content keys. + + This is the ``--cdm-only`` path. The challenge goes out the first time a run sees the KIDs + for the DRM system. + + prepare_drm asks the CDM only for a KID with no content key, so the content keys the DRM + holds are removed for the call and put back after it. + """ + kids = {*drm.kids, *([track_kid] if track_kid else [])} + attempted = self.all_drm_attempted[type(drm)] + if kids <= attempted: + prepare(drm, track_kid=track_kid) + return + with self.drm_lock(drm): + held = dict(drm.content_keys) + drm.content_keys.clear() + try: + prepare(drm, track_kid=track_kid, cdm_only=True, force=True) + finally: + attempted |= kids + with self.drm_lock(drm): + for held_kid, key in held.items(): + drm.content_keys.setdefault(held_kid, key) + + def licence_all_drm( + self, + prepare: Callable, + track: AnyTrack, + tolerate: bool, + drm: DRM_T, + track_kid: Optional[UUID] = None, + force: bool = False, + ) -> None: + """License the track with each DRM system it offers, not only the one the downloader selected. + + A DRM system sends a challenge only for a KID that no vault and no earlier track gave a + content key for. With ``force``, each DRM system sends one challenge for a set of KIDs in + a run. A DRM system that fails stops the title. With ``tolerate`` it is a warning, if the + other DRM system gave the content key of the track. + """ + if not isinstance(drm, (Widevine, PlayReady)): + prepare(drm, track_kid=track_kid) + return + + other_type = PlayReady if type(drm) is Widevine else Widevine + others = [d for d in track.drm or [] if isinstance(d, (Widevine, PlayReady)) and type(d) is other_type] + if other_type is PlayReady and len(others) > 1: + playready = [d for d in others if isinstance(d, PlayReady)] + playready[0].absorb(*playready[1:]) + if not others and other_type.__name__ not in self.all_drm_warned: + self.all_drm_warned.add(other_type.__name__) + self.log.warning( + f"Track {track} has no {other_type.__name__} DRM, licensing with {type(drm).__name__} only" + ) + + targets = [drm, *others[:1]] + error: Optional[Exception] = None + with self.ALL_DRM_LOCK: + loaded_cdm = self.cdms.cdm + try: + for target in targets: + kid = track_kid if target is drm or track_kid in target.kids else None + try: + if force: + self.licence_one_drm(prepare, target, kid) + else: + prepare(target, track_kid=kid) + except Exception as e: + if not tolerate: + raise + self.log.warning(f"{type(target).__name__} licence failed for {track}: {e}") + error = error or e + + keys = {kid: key for target in targets for kid, key in target.content_keys.items()} + for target in targets: + with self.drm_lock(target): + for kid, key in keys.items(): + target.content_keys.setdefault(kid, key) + finally: + self.cdms.cdm = loaded_cdm + + track_keys = getattr(drm, "content_keys", {}) + if error and (not track_keys or (track_kid and track_kid not in track_keys)): + raise error + + def prepare_drm( + self, + drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa], + track: AnyTrack, + title: Title_T, + table: Table, + track_kid: Optional[UUID] = None, + cdm_only: bool = False, + force: bool = False, + ) -> None: + """ + Prepare the DRM by getting decryption data like KIDs, Keys, and such. + The DRM object should be ready for decryption once this function ends. + ``force`` skips the content keys of earlier tracks in this run. The CDM then licenses + again for each KID the DRM holds no content key for. + """ + if not drm: + return + licence: Callable = partial(self.service_licence, title=title, track=track) + + remote = self.source + server_cdm = bool(remote and remote.server_cdm) + licensed_locally = bool(remote and remote.licenses_locally(track)) + + if server_cdm and not licensed_locally: + assert remote is not None + with self.drm_lock(drm), ExitStack() as licence_turn: + pending_vault_writes: list[Callable[[], Any]] = [] + vault_kids = self.with_track_kid(drm, track_kid) + self.take_known_keys(drm, vault_kids, track, track_kid, None, use_vaults=not cdm_only) + + def missing_track_key() -> bool: + return not drm.content_keys or bool(track_kid and track_kid not in drm.content_keys) + + if missing_track_key(): + self.take_licence_turn(licence_turn, drm, vault_kids, track, track_kid, None) + known_keys = set(drm.content_keys) + + if missing_track_key(): + from unshackle.core.remote_service import RemoteError + + try: + licence( + drm_system="playready" if drm.__class__.__name__ == "PlayReady" else "widevine", + challenge=b"", + kid=track_kid, + ) + except click.ClickException: + raise + except (Exception, RemoteError) as e: + self.log.debug(f"Server CDM licence with an empty challenge failed: {e!r}") + drop_null_keys(drm) + + new_keys = {} + for kid, key in drm.content_keys.items(): + source = None if cdm_only else remote.vault_source(kid, key) + if source is not None: + self.vaults.sources[kid] = (key, source) + elif kid not in known_keys: + new_keys[kid] = key + if new_keys: + self.LICENSE_KEY_CACHE.update(new_keys) + pending_vault_writes.append(partial(self.cache_keys_to_vaults, new_keys)) + self.flush_vault_writes(pending_vault_writes) + + # the server can refuse the licence above its cap and hand the track to this machine + licensed_locally = bool(remote and remote.licenses_locally(track)) + if server_cdm and not licensed_locally: + if not drm.content_keys: + self.log.warning("Server CDM did not resolve any keys for this track") + return + if track_kid and track_kid not in drm.content_keys: + msg = f"No Content Key for KID {track_kid.hex} was returned by the server CDM" + if isinstance(drm, PlayReady): + raise PlayReady.Exceptions.CEKNotFound(msg) + raise Widevine.Exceptions.CEKNotFound(msg) + assert remote is not None + server_drm_type = remote.server_cdm_type + drm_name = {"widevine": "Widevine", "playready": "PlayReady"}.get(server_drm_type, drm.__class__.__name__) + log_event( + "drm_content_keys", + level="INFO", + message=f"Server CDM resolved {len(drm.content_keys)} {drm_name} content key(s)", + service=self.tag, + drm_type=drm_name, + key_count=len(drm.content_keys), + keys=[{"kid": k.hex, "key": v} for k, v in drm.content_keys.items()], + remote=True, + ) + with self.drm_lock(drm): + pssh_str = "" + expected_class = "PlayReady" if server_drm_type == "playready" else "Widevine" + matching_drm = next( + (d for d in (track.drm or []) if d.__class__.__name__ == expected_class), + drm, + ) + if hasattr(matching_drm, "pssh") and matching_drm.pssh: + if hasattr(matching_drm.pssh, "dumps"): + pssh_str = truncate_pssh_for_display(matching_drm.pssh.dumps(), drm_name) + elif hasattr(matching_drm, "data") and matching_drm.data.get("pssh_b64"): + pssh_str = truncate_pssh_for_display(matching_drm.data["pssh_b64"], drm_name) + if pssh_str: + cek_tree = Tree(Text.assemble((drm_name, "cyan"), (f"({pssh_str})", "text"), overflow="fold")) + else: + cek_tree = Tree(Text.assemble((drm_name, "cyan"), overflow="fold")) + all_kids = self.with_track_kid(drm, track_kid) + for kid in all_kids: + if kid in drm.content_keys: + self.add_key_label(cek_tree, kid, drm.content_keys[kid], track_kid) + for kid, key in drm.content_keys.items(): + if kid not in all_kids: + self.add_key_label(cek_tree, kid, key) + if not any(isinstance(x, Tree) and x.label == cek_tree.label for x in table.columns[0].cells): + table.add_row(cek_tree) + if self.export: + self.export(title, track, drm) + return + + track_quality = None + if isinstance(track, Video) and track.height: + track_quality = track.height + elif title is not None: + track_quality = max((v.height for v in title.tracks.videos if v.height), default=None) + + track_cdm = self.cdms.cdm + if licensed_locally: + assert remote is not None + track_cdm = remote.local_cdm + local_drm = track.get_drm_for_cdm(track_cdm) + if isinstance(local_drm, (Widevine, PlayReady)) and isinstance(local_drm, PlayReady) != is_playready_cdm( + track_cdm + ): + track_cdm = self.cdms.cdm_for( + "playready" if isinstance(local_drm, PlayReady) else "widevine", track_quality + ) + if local_drm is not None and local_drm is not drm: + assert not isinstance(local_drm, ClearKey) + # a mid-download handover leaves drm on the server's DRM system, and the caller decrypts with it + self.prepare_drm(local_drm, track, title, table, track_kid, cdm_only) + with self.drm_lock(drm): + drm.content_keys.update(local_drm.content_keys) + return + + drm_system = "playready" if isinstance(drm, PlayReady) else "widevine" + licence = partial(licence, drm_system=drm_system) + + if not server_cdm and isinstance(drm, (Widevine, PlayReady)): + matches = is_playready_cdm if drm_system == "playready" else is_widevine_cdm + if not matches(self.cdms.cdm): + name, other = ("PlayReady", "Widevine") if drm_system == "playready" else ("Widevine", "PlayReady") + system_cdm = self.cdms.cdm_for(drm_system, track_quality) + if system_cdm and matches(system_cdm): + self.log.info(f"Switching to the {name} CDM") + self.cdms.cdm = system_cdm + track_cdm = system_cdm + elif self.cdms.cdm is None: + raise click.ClickException(f"No CDM configured for {self.tag} and no default CDM") + else: + raise ValueError(f"Title needs a {name} CDM but {self.tag} is configured with {other}.") + + if isinstance(drm, (Widevine, PlayReady, ClearKeyCENC)): + if isinstance(drm, ClearKeyCENC): + clearkey_licence = partial(self.service.get_clearkey_license, title=title, track=track) + get_keys = partial(drm.get_content_keys, licence=clearkey_licence, session=self.service.session) + else: + certificate = partial(self.service.get_widevine_service_certificate, title=title, track=track) + get_keys = partial(drm.get_content_keys, cdm=track_cdm, licence=licence, certificate=certificate) + self.license_drm(drm, get_keys, track, title, track_kid, table, cdm_only, force) + if self.export: + self.export(title, track, drm) + + elif isinstance(drm, MonaLisa): + with self.drm_lock(drm): + display_id = drm.content_id or drm.pssh + pssh_display = truncate_pssh_for_display(display_id, "MonaLisa") + cek_tree = Tree(Text.assemble(("MonaLisa", "cyan"), (f"({pssh_display})", "text"), overflow="fold")) + pre_existing_tree = next( + (x for x in table.columns[0].cells if isinstance(x, Tree) and x.label == cek_tree.label), None + ) + if pre_existing_tree: + cek_tree = pre_existing_tree + + for kid_, key in drm.content_keys.items(): + self.add_key_label(cek_tree, kid_, key, track_kid=kid_) # every MonaLisa key is the track's own + + if cek_tree.children and not pre_existing_tree: + table.add_row() + table.add_row(cek_tree) + + if self.export: + self.export(title, track, drm)