diff --git a/tests/core/key_resolver.py b/tests/core/key_resolver.py index 23d85891..91b3a29b 100644 --- a/tests/core/key_resolver.py +++ b/tests/core/key_resolver.py @@ -2,7 +2,7 @@ from __future__ import annotations -from collections.abc import Callable +from collections.abc import Callable, Iterator from types import SimpleNamespace from typing import Any from uuid import UUID @@ -11,22 +11,52 @@ from rich.table import Table from unshackle.core.cdm.detect import cdm_type_stub from unshackle.core.drm.key_resolution import ContentKeyResolver +from unshackle.core.vault import Vault +from unshackle.core.vaults import Vaults -class NoVaults: - """No key vault: every lookup misses and nothing is stored.""" +class MemoryVault(Vault): + """A key vault in memory that records each lookup in ``asked``, each push in ``pushes`` and ``added``, and each flag in ``told``.""" - sources: dict = {} - flagged: set = set() + def __init__( + self, keys: dict[UUID, str] | None = None, local: bool = True, name: str = "memory", no_push: bool = False + ) -> None: + super().__init__(name, no_push) + self.local = local + self.keys: dict[UUID | str, str] = dict(keys or {}) + self.asked: list[UUID | str] = [] + self.pushes: list[dict[UUID | str, str]] = [] + self.added: dict[UUID | str, str] = {} + self.told: list[tuple[UUID | str, str]] = [] - def __bool__(self) -> bool: - return False + def get_key(self, kid: UUID | str, service: str) -> str | None: + self.asked.append(kid) + return self.keys.get(kid) - def __len__(self) -> int: - return 0 + def get_keys(self, service: str) -> Iterator[tuple[str, str]]: + return iter((str(kid), key) for kid, key in self.keys.items()) - def get_key(self, kid: UUID) -> tuple[None, None]: - return None, None + def add_key(self, service: str, kid: UUID | str, key: str) -> bool: + return bool(self.add_keys(service, {kid: key})) + + def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int: + self.pushes.append(dict(kid_keys)) + self.added.update(kid_keys) + self.keys.update(kid_keys) + return len(kid_keys) + + def get_services(self) -> Iterator[str]: + return iter(()) + + def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None: + self.told.append((kid, key)) + + +def vaults_of(*loaded: Vault, service: str = "TEST") -> Vaults: + """A Vaults over ``loaded``, with no config.""" + vaults = Vaults(service) + vaults.vaults = list(loaded) + return vaults def stand_in_service() -> SimpleNamespace: @@ -50,14 +80,14 @@ def resolver( tag: str = "TEST", **flags: Any, ) -> ContentKeyResolver: - """A ContentKeyResolver over ``vaults`` (none by default) and a Widevine CDM, with an empty run key cache.""" + """A ContentKeyResolver over ``vaults`` (no vault 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(), tag, **flags) + return ContentKeyResolver(vaults_of() if vaults is None else vaults, cdms, stand_in_service(), tag, **flags) def key_table() -> Table: diff --git a/tests/core/test_all_drm.py b/tests/core/test_all_drm.py index 1fa505f5..4d2be3e3 100644 --- a/tests/core/test_all_drm.py +++ b/tests/core/test_all_drm.py @@ -15,7 +15,7 @@ from pywidevine.cdm import Cdm as WidevineCdm from pywidevine.pssh import PSSH from tests.admission import refusal -from tests.core.key_resolver import NoVaults, key_table, resolver +from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of from unshackle.commands.dl import dl from unshackle.core.api.handlers import load_full_cdm, resolve_server_cdm from unshackle.core.cdm.detect import is_widevine_cdm @@ -57,15 +57,9 @@ class Run: def __init__(self, vault: dict[UUID, str] | None = 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 get_key(self, vault: dict[UUID, str]) -> Any: - def get_key(kid: UUID) -> tuple[str | None, str | None]: - self.vault_queries.append(kid) - return vault.get(kid), "vault" if kid in vault else None - - return get_key + self.vault = MemoryVault(vault, no_push=True) + self.vault_queries = self.vault.asked + self.keys = resolver(vaults_of(self.vault), tag="EXAMPLE", **flags) def drm(self, drm: Any, keys: dict[UUID, str] | None = None, fail: bool = False) -> Any: """Give ``drm`` a licence that returns ``keys`` (KID:KEY by default), or that is refused.""" @@ -85,13 +79,6 @@ class Run: self.keys.licence_for(track, None, key_table(), all_drm=True)(drm, track_kid=track_kid) -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() -> None: run = Run(cdm_only=True) wv, pr = run.drm(widevine()), run.drm(playready()) diff --git a/tests/core/test_http_cdm.py b/tests/core/test_http_cdm.py index 222e2201..ef2f1894 100644 --- a/tests/core/test_http_cdm.py +++ b/tests/core/test_http_cdm.py @@ -10,6 +10,7 @@ import pytest from pywidevine.cdm import Cdm as WidevineCdm from pywidevine.pssh import PSSH +from tests.core.key_resolver import MemoryVault, vaults_of from unshackle.core.cdm.custom_remote_cdm import CustomRemoteCDM, CustomRemoteCDMExceptions from unshackle.core.cdm.decrypt_labs_remote_cdm import DecryptLabsRemoteCDM, DecryptLabsRemoteCDMExceptions from unshackle.core.cdm.http_cdm import HttpCdm, HttpCdmExceptions @@ -22,21 +23,6 @@ KID_B = UUID("ffeeddccbbaa99887766554433221100") KEY_A, KEY_B, KEY_X = "01" * 16, "02" * 16, "0f" * 16 -class FakeVaults: - def __init__(self, keys: dict[UUID, str]) -> None: - self.keys = dict(keys) - self.added: dict[Any, str] = {} - - def __len__(self) -> int: - return 1 - - def get_key(self, kid: UUID) -> tuple[str | None, None]: - return self.keys.get(kid), None - - def add_keys(self, keys: dict[Any, str]) -> None: - self.added.update(keys) - - class StubCdm(HttpCdm): """An adapter whose API answers from fixed lists and records what it was asked.""" @@ -85,16 +71,16 @@ def licensed(cdm: StubCdm, *kids: UUID) -> dict[UUID, str]: def test_vaults_holding_every_kid_skip_the_api() -> None: - cdm = StubCdm(vaults=FakeVaults({KID_A: KEY_A, KID_B: KEY_B})) + cdm = StubCdm(vaults=vaults_of(MemoryVault({KID_A: KEY_A, KID_B: KEY_B}))) assert licensed(cdm, KID_A, KID_B) == {KID_A: KEY_A, KID_B: KEY_B} assert cdm.challenges == 0 def test_a_vault_key_wins_over_the_licence_and_licence_keys_go_to_the_vaults() -> None: - vaults = FakeVaults({KID_A: KEY_A}) - cdm = StubCdm(licence=[key(KID_A, KEY_X), key(KID_B, KEY_B), key(KID_B, KEY_X)], vaults=vaults) + vault = MemoryVault({KID_A: KEY_A}) + cdm = StubCdm(licence=[key(KID_A, KEY_X), key(KID_B, KEY_B), key(KID_B, KEY_X)], vaults=vaults_of(vault)) assert licensed(cdm, KID_A, KID_B) == {KID_A: KEY_A, KID_B: KEY_B} - assert vaults.added == {KID_A: KEY_A, KID_B: KEY_B} + assert vault.added == {KID_A: KEY_A, KID_B: KEY_B} def test_cached_keys_covering_every_kid_need_no_licence() -> None: diff --git a/tests/core/test_import_missing_key.py b/tests/core/test_import_missing_key.py index b925fcdf..256597c8 100644 --- a/tests/core/test_import_missing_key.py +++ b/tests/core/test_import_missing_key.py @@ -16,7 +16,7 @@ import click import pytest from pywidevine.pssh import PSSH -from tests.core.key_resolver import NoVaults, key_table, resolver +from tests.core.key_resolver import key_table, resolver, vaults_of from unshackle.commands.dl import dl from unshackle.core.drm import Widevine, key_resolution from unshackle.core.drm.key_resolution import ContentKeyResolver @@ -85,7 +85,7 @@ 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]) - keys = make_resolver(monkeypatch, NoVaults(), track, []) + keys = make_resolver(monkeypatch, vaults_of(), track, []) with pytest.raises(click.ClickException, match=KID.hex): keys.licence_for(track, None, key_table())(drm, track_kid=None) diff --git a/tests/core/test_licence_turns.py b/tests/core/test_licence_turns.py index e4736127..c2e04bec 100644 --- a/tests/core/test_licence_turns.py +++ b/tests/core/test_licence_turns.py @@ -14,7 +14,7 @@ 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.key_resolver import MemoryVault, key_table, resolver, vaults_of from tests.core.test_all_drm import playready from unshackle.core.cdm.detect import cdm_type_stub from unshackle.core.constants import DOWNLOAD_CANCELLED, DownloadCancelled @@ -53,16 +53,17 @@ def licences(monkeypatch: pytest.MonkeyPatch) -> Licences: DOWNLOAD_CANCELLED.clear() -class TrackVaults(NoVaults): - """No key vault, but a lookup by the second track sets ``looked_up``.""" +class TrackVault(MemoryVault): + """An empty key vault; a lookup by the second track sets ``looked_up``.""" def __init__(self, looked_up: threading.Event) -> None: + super().__init__() self.looked_up = looked_up - def get_key(self, kid: UUID) -> tuple[None, None]: + def get_key(self, kid: UUID | str, service: str) -> str | None: if threading.current_thread().name == "track-1": self.looked_up.set() - return None, None + return super().get_key(kid, service) def widevine(*kids: UUID) -> Widevine: @@ -97,7 +98,7 @@ def tree_labels(table: Table, kid: UUID) -> list[str]: def test_one_licence_for_two_pssh_with_different_kids(licences: Licences) -> None: - keys = resolver(TrackVaults(licences.second_track_looked_up)) + keys = resolver(vaults_of(TrackVault(licences.second_track_looked_up))) first, second = widevine(KID_A, KID_B), widevine(KID_C) table, errors = run_together(keys, (first, KID_A), (second, KID_C)) @@ -167,17 +168,12 @@ def test_an_all_zero_licence_key_is_dropped( def test_vaults_only_stops_at_the_first_kid_no_vault_holds(licences: Licences) -> None: - asked: list[UUID] = [] - - class EmptyVaults(NoVaults): - def get_key(self, kid: UUID) -> tuple[None, None]: - asked.append(kid) - return None, None + empty = MemoryVault() with pytest.raises(Widevine.Exceptions.CEKNotFound, match=KID_A.hex): - prepare(resolver(EmptyVaults(), vaults_only=True), widevine(KID_A, KID_B), KID_A, key_table()) + prepare(resolver(vaults_of(empty), vaults_only=True), widevine(KID_A, KID_B), KID_A, key_table()) - assert asked == [KID_A] + assert empty.asked == [KID_A] assert licences == [] diff --git a/tests/core/test_vault_bad_keys.py b/tests/core/test_vault_bad_keys.py index 7a3718a5..90aa992a 100644 --- a/tests/core/test_vault_bad_keys.py +++ b/tests/core/test_vault_bad_keys.py @@ -1,13 +1,12 @@ import logging import threading -import time from pathlib import Path from types import SimpleNamespace from uuid import UUID import pytest -from tests.core.key_resolver import NoVaults, key_table, resolver +from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of from unshackle.core.drm import key_resolution from unshackle.core.drm.key_resolution import ContentKeyResolver from unshackle.core.vault import RateLimited, vault_session @@ -37,7 +36,7 @@ def test_flagged_pair_is_skipped_and_named(tmp_path: Path) -> None: vaults.vaults = [local, poisoned] assert vaults.get_key(KID) == (BAD, poisoned) - assert vaults.sources[KID] == (BAD, poisoned) + assert vaults.source_of(KID, BAD) is poisoned local.add_key("SVC", KID, BAD) # the cross-vault copy that happened before verification vaults.flag_bad_key(KID, BAD) @@ -273,13 +272,20 @@ def test_retry_takes_the_next_parallel_answer_without_a_new_request(tmp_path: Pa fast, slow = Fast("fast", BAD), Slow("slow", GOOD) vaults = Vaults("SVC") vaults.vaults = [local, fast, slow] + landed = threading.Event() + offer = vaults.offer + + def offered(kid: UUID | str, key: str, source: object) -> None: + offer(kid, key, source) # type: ignore[arg-type] + if source is slow: + landed.set() + + vaults.offer = offered # type: ignore[method-assign] assert vaults.get_key(KID) == (BAD, fast) vaults.flag_bad_key(KID, BAD) - release.set() # the slow answer lands in candidates after the first call returned - deadline = time.monotonic() + 5 - while len(vaults.candidates.get(KID, [])) < 2 and time.monotonic() < deadline: - time.sleep(0.01) + release.set() + assert landed.wait(5) assert vaults.get_key(KID) == (GOOD, slow) assert fast.calls == 1 and slow.calls == 1 @@ -308,8 +314,10 @@ def test_cdm_returning_the_flagged_key_clears_the_flag( drm.content_keys[KID] = BAD # the CDM answers with the same key 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 def test_a_replacement_key_in_a_new_dict_is_checked_and_stored(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: @@ -476,27 +484,15 @@ def test_a_licence_with_no_new_keys_sends_no_vault_write(monkeypatch: pytest.Mon """A PSSH KID the licence never answers forces a licence on every run; the vaults must not get an empty push.""" 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 - + vault = MemoryVault() monkeypatch.setattr(ClearKeyCENC, "get_content_keys", lambda self, **_: None) - keys = resolver(PushVaults()) + keys = resolver(vaults_of(vault)) drm = ClearKeyCENC(kids=[KID]) keys.licence_for(SimpleNamespace(drm=[drm]), None, key_table())(drm, track_kid=None) keys.wait_vault_writes() - assert pushes == [] + assert vault.pushes == [] def test_the_cached_key_count_is_unique_and_skipped_without_vaults( @@ -704,6 +700,7 @@ def test_a_remote_vault_is_told_only_when_another_key_replaces_its_pair( drm.content_keys[KID] = GOOD keys.decrypt_verified(drm, path, licence, KID) + keys.wait_vault_writes() assert drm.content_keys == {KID: GOOD} assert remote.is_bad_key(KID, served) is told @@ -719,7 +716,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) + vaults.supplied(KID, BAD, server) # type: ignore[arg-type] keys = make_resolver(monkeypatch, vaults) drm = FakeDRM({KID: BAD}) path = tmp_path / "video.mp4" @@ -819,7 +816,7 @@ def test_a_sibling_verdict_during_the_decrypt_still_triggers_the_retry( local = SQLite("local", tmp_path / "local.db") vaults = Vaults("SVC") vaults.vaults = [local] - vaults.sources[KID] = (BAD, local) + vaults.supplied(KID, BAD, local) keys = make_resolver(monkeypatch, vaults) ContentKeyResolver.LICENSE_KEY_CACHE[KID] = GOOD # the sibling's retry already licensed the good key @@ -855,10 +852,10 @@ def test_api_vault_reports_the_pair_upstream(monkeypatch: pytest.MonkeyPatch, ca vaults = Vaults("SVC") vaults.vaults = [api] - vaults.sources[KID] = (BAD, api) + vaults.supplied(KID, BAD, api) vaults.flag_bad_key(KID, BAD) assert not calls - vaults.report_replaced({KID: GOOD}) + vaults.proven({KID: GOOD}, {}) vaults.unflag_bad_key(KID, BAD) assert calls == [ @@ -867,9 +864,9 @@ def test_api_vault_reports_the_pair_upstream(monkeypatch: pytest.MonkeyPatch, ca ] def flag_and_replace(source: object) -> None: - vaults.sources[KID] = (BAD, source) + vaults.supplied(KID, BAD, source) # type: ignore[arg-type] vaults.flag_bad_key(KID, BAD) - vaults.report_replaced({KID: GOOD}) + vaults.proven({KID: GOOD}, {}) calls.clear() flag_and_replace(SimpleNamespace(name="other", local=False, report_now=False)) @@ -896,20 +893,11 @@ 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] = [] - - 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) + remote = MemoryVault(local=False) + keys = resolver(vaults_of(remote), source=SERVER) keys.take_server_keys(batch_title({KID: GOOD, SIBLING: BAD}, {KID: GOOD, SIBLING: BAD}, kids=[KID])) - assert asked == [KID] + assert remote.asked == [KID] def test_cache_resolved_keys_skips_a_key_a_local_vault_holds(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: diff --git a/tests/core/test_vault_ledger.py b/tests/core/test_vault_ledger.py new file mode 100644 index 00000000..bee66063 --- /dev/null +++ b/tests/core/test_vault_ledger.py @@ -0,0 +1,149 @@ +"""Vaults as the ledger of content keys: where each key in use came from, and who hears that it is bad.""" + +import logging +import threading +from types import SimpleNamespace +from uuid import UUID + +import pytest +import requests + +from tests.core.key_resolver import MemoryVault, vaults_of + +KID = UUID(int=1) +BAD = "aa" * 16 +GOOD = "bb" * 16 + + +def server() -> SimpleNamespace: + """A source outside the loaded vaults, as the server's vaults are over --remote.""" + return SimpleNamespace(name="server_cdm", local=False, report_now=True) + + +def test_an_offered_key_comes_after_the_local_vaults_and_is_its_sources() -> None: + local, source = MemoryVault(), server() + vaults = vaults_of(local) + vaults.offer(KID, BAD, source) # type: ignore[arg-type] + + assert vaults.get_key(KID) == (BAD, source) + assert local.asked == [KID] + assert vaults.source_of(KID, BAD) is source + assert vaults.source_of(KID, GOOD) is None + + +def test_a_proven_vault_key_goes_to_every_other_vault() -> None: + remote, local = MemoryVault({KID: GOOD}, local=False), MemoryVault(name="local") + vaults = vaults_of(local, remote) + assert vaults.get_key(KID) == (GOOD, remote) + + vaults.proven({KID: GOOD}, {KID: remote}) + + assert local.added == {KID: GOOD} + assert remote.added == {} + + +def test_a_pair_proved_wrong_before_its_proof_is_stored_goes_nowhere() -> None: + remote, local = MemoryVault({KID: GOOD}, local=False), MemoryVault(name="local") + vaults = vaults_of(local, remote) + vaults.get_key(KID) + + vaults.flag_bad_key(KID, GOOD) + vaults.proven({KID: GOOD}, {KID: remote}) + + assert local.added == {} + assert remote.added == {} + + +def test_a_remote_vault_hears_of_its_bad_pair_only_once_another_key_replaces_it() -> None: + remote = MemoryVault({KID: BAD}, local=False) + vaults = vaults_of(remote) + vaults.get_key(KID) + + vaults.flag_bad_key(KID, BAD) + vaults.proven({KID: BAD}, {}) + assert remote.told == [] + assert vaults.proved_wrong(KID, BAD) + + vaults.proven({KID: GOOD}, {}) + vaults.proven({KID: GOOD}, {}) + assert remote.told == [(KID, BAD)] + + +def test_a_licence_clears_a_flag_of_this_run_without_a_local_vault() -> None: + remote = MemoryVault({KID: BAD}, local=False) + vaults = vaults_of(remote) + vaults.get_key(KID) + vaults.flag_bad_key(KID, BAD) + + assert vaults.licensed({KID: BAD}) == 1 + assert not vaults.proved_wrong(KID, BAD) + assert remote.added == {KID: BAD} + vaults.proven({KID: GOOD}, {}) + assert remote.told == [] + + +def test_one_source_offered_twice_at_once_is_held_once() -> None: + """Thread A has checked an offer and not yet stored it when thread B offers the same pair.""" + a_storing, b_moved, release = threading.Event(), threading.Event(), threading.Event() + vaults = vaults_of() + source = server() + + class HeldList(list): + def append(self, item: object) -> None: + if threading.current_thread().name == "a": + a_storing.set() + release.wait(10) + else: + b_moved.set() + super().append(item) + + class Lock: + """The ledger lock, which tells the test when thread B waits for it.""" + + def __init__(self) -> None: + self.lock = threading.Lock() + + def __enter__(self) -> None: + if threading.current_thread().name == "b": + b_moved.set() + self.lock.acquire() + + def __exit__(self, *exc: object) -> None: + self.lock.release() + + vaults.candidates[KID] = HeldList() + vaults.lock = Lock() # type: ignore[assignment] + a = threading.Thread(target=vaults.offer, args=(KID, BAD, source), name="a") + b = threading.Thread(target=vaults.offer, args=(KID, BAD, source), name="b") + a.start() + assert a_storing.wait(10) + b.start() + assert b_moved.wait(10) + release.set() + a.join(10) + b.join(10) + + assert vaults.candidates[KID] == [(BAD, source)] + + +def test_two_lookups_that_fail_at_once_warn_once(caplog: pytest.LogCaptureFixture) -> None: + both_asking = threading.Barrier(2, timeout=10) + + class Down(MemoryVault): + def get_key(self, kid: UUID | str, service: str) -> str | None: + both_asking.wait() + raise requests.ConnectTimeout("no answer") + + vaults = vaults_of(Down(local=False, name="down")) + with caplog.at_level(logging.WARNING, logger="unshackle.core.vaults"): + threads = [threading.Thread(target=vaults.get_key, args=(KID,)) for _ in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(10) + + messages = [record.getMessage() for record in caplog.records] + assert messages == [ + "Failed to get key from Vault 'down': no answer", + "Skipping Vault 'down' for the rest of this run", + ] diff --git a/tests/remote/unit/test_server_cdm_vault_write.py b/tests/remote/unit/test_server_cdm_vault_write.py index 436d87d7..a0551493 100644 --- a/tests/remote/unit/test_server_cdm_vault_write.py +++ b/tests/remote/unit/test_server_cdm_vault_write.py @@ -11,7 +11,7 @@ from uuid import UUID import pytest -from tests.core.key_resolver import key_table, resolver +from tests.core.key_resolver import MemoryVault, key_table, resolver, vaults_of from tests.remote.key_source import CAPPED, PR_DEVICE, MemoryKeySource, one_title, remote_keys, remote_session from unshackle.core.drm.key_resolution import ContentKeyResolver @@ -21,46 +21,17 @@ NEW = UUID("161219ec3df64e0eadbb3827c0ccc46d") CACHED = UUID("75982fac2cd8412a990a59c0ef2d4bb1") -class FakeVaults: - def __init__(self, held=None, vault_used=None): - self.held = held or {} - self.vault_used = vault_used - self.added: dict = {} - self.pushes: list = [] - self.replicated: list = [] - self.sources: dict = {} - - def __len__(self): - return 1 - - def held_locally(self, kid, key): - return False - - def get_key(self, kid): - return self.held.get(kid), self.vault_used - - def is_flagged(self, kid, key): - return False - - def clear_licensed_flags(self, content_keys): - return [] - - def add_keys(self, kid_keys): - self.added.update(kid_keys) - self.pushes.append(dict(kid_keys)) - return 1 - - def add_key(self, kid, key, excluding=None): - self.replicated.append((kid, key, excluding)) - return 1 - - class FakeWidevine: def __init__(self, kids): self.kids = list(kids) self.content_keys: dict = {} +def memory_vaults(held=None): + """A Vaults over one local MemoryVault that holds ``held``.""" + return vaults_of(MemoryVault(held)) + + def make_resolver(vaults, source=None, **flags): return resolver(vaults, source=source or MemoryKeySource(), **flags) @@ -86,15 +57,15 @@ def batch(keys, source, title): def test_server_cdm_keys_are_cached_to_local_vaults(): - vaults = FakeVaults() + vaults = memory_vaults() run_prepare(vaults, [NEW], {NEW: "k_new"}, track_kid=NEW) - assert vaults.added == {NEW: "k_new"} + assert vaults.vaults[0].added == {NEW: "k_new"} def test_keys_read_from_a_vault_are_not_pushed_back(): - vaults = FakeVaults({CACHED: "k_cached"}) + vaults = memory_vaults({CACHED: "k_cached"}) run_prepare(vaults, [CACHED, NEW], {NEW: "k_new"}, track_kid=NEW) - assert vaults.added == {NEW: "k_new"} + assert vaults.vaults[0].added == {NEW: "k_new"} def capped_run(vaults): @@ -120,25 +91,25 @@ def test_a_drm_the_track_does_not_hold_gets_the_server_keys(): manifest_drm.pssh, later_drm.pssh = SimpleNamespace(dumps=lambda: "OLD"), SimpleNamespace(dumps=lambda: "LATER") track = SimpleNamespace(id="vid", drm=[manifest_drm]) - prepare(make_resolver(FakeVaults(), svc), later_drm, NEW, track) + prepare(make_resolver(memory_vaults(), svc), later_drm, NEW, track) assert later_drm.content_keys == {NEW: "k_new"} def test_a_capped_track_takes_a_local_vault_key_before_the_refusal(): - assert capped_run(FakeVaults({CACHED: "k_cached"})).content_keys == {CACHED: "k_cached"} + assert capped_run(memory_vaults({CACHED: "k_cached"})).content_keys == {CACHED: "k_cached"} def test_a_capped_track_no_vault_holds_raises_the_refusal(): import click with pytest.raises(click.ClickException, match="only Widevine DRM, which your local PlayReady CDM cannot license"): - capped_run(FakeVaults()) + capped_run(memory_vaults()) 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() + vaults = memory_vaults() source = MemoryKeySource() keys = make_resolver(vaults, source) @@ -148,20 +119,19 @@ def test_batch_resolved_keys_are_cached_before_download(): batch(keys, source, title) - assert vaults.added == {NEW: "k_new"} + assert vaults.vaults[0].added == {NEW: "k_new"} def test_vault_hits_wait_for_the_decrypt_before_replicating(): """A vault hit reaches the other vaults only after decrypt_verified proves it, never from prepare_drm.""" - vaults = FakeVaults({CACHED: "k_cached"}, vault_used="vault-a") + vaults = memory_vaults({CACHED: "k_cached"}) run_prepare(vaults, [CACHED], {}, track_kid=CACHED) - assert vaults.replicated == [] - assert vaults.added == {} + assert vaults.vaults[0].added == {} def test_server_vault_keys_are_held_back_until_verified(): """A key the server took from its vault is sourced like a local vault hit and not pushed yet.""" - vaults = FakeVaults() + vaults = memory_vaults() remote = MemoryKeySource({CACHED: "k_cached", NEW: "k_new"}) remote.server_vault_keys = {CACHED: "k_cached"} stub = object() @@ -173,20 +143,20 @@ def test_server_vault_keys_are_held_back_until_verified(): prepare(keys, drm, NEW) keys.wait_vault_writes() - assert vaults.added == {NEW: "k_new"} - assert vaults.sources == {CACHED: ("k_cached", stub)} + assert vaults.vaults[0].added == {NEW: "k_new"} + assert vaults.source_of(CACHED, "k_cached") is stub # 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"} ContentKeyResolver.LICENSE_KEY_CACHE.clear() batch(keys, remote, SimpleNamespace(tracks=[SimpleNamespace(drm=[drm2])])) - assert vaults.added == {NEW: "k_new"} + assert vaults.vaults[0].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() + vaults = memory_vaults() drm = FakeWidevine([NEW]) source = MemoryKeySource({NEW: "k_new"}) keys = make_resolver(vaults, source) @@ -204,12 +174,12 @@ def test_tracks_sharing_one_drm_licence_and_push_once(): keys.wait_vault_writes() assert len(source.asked) == 1 - assert vaults.pushes == [{NEW: "k_new"}] + assert vaults.vaults[0].pushes == [{NEW: "k_new"}] 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() + vaults = memory_vaults() source = MemoryKeySource({NEW: "k_new"}) keys = make_resolver(vaults, source, cdm_only=True) for drm in [FakeWidevine([NEW]) for _ in range(2)]: @@ -217,12 +187,12 @@ def test_cdm_only_still_reuses_keys_from_the_run_cache(): keys.wait_vault_writes() assert len(source.asked) == 1 - assert vaults.pushes == [{NEW: "k_new"}] + assert vaults.vaults[0].pushes == [{NEW: "k_new"}] def test_a_forced_licence_trusts_server_vault_keys(): """A forced licence (cdm_only=True, as --all-drm passes) does not name the server vault as a source, so no decode check.""" - vaults = FakeVaults() + vaults = memory_vaults() remote = MemoryKeySource({CACHED: "k_cached"}) remote.server_vault_keys = {CACHED: "k_cached"} remote.server_vault = object() @@ -232,7 +202,7 @@ def test_a_forced_licence_trusts_server_vault_keys(): prepare(keys, drm, CACHED) keys.wait_vault_writes() - assert vaults.sources == {} + assert vaults.source_of(CACHED, "k_cached") is None assert ContentKeyResolver.LICENSE_KEY_CACHE == {CACHED: "k_cached"} @@ -244,7 +214,7 @@ def test_no_cdm_and_no_server_cdm_names_the_missing_cdm(system): from unshackle.core.drm import PlayReady, Widevine keys = resolver( - FakeVaults(), cdm=None, cdm_for=lambda system, quality=None: None, source=remote_keys(server_cdm=False) + memory_vaults(), 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) @@ -257,15 +227,15 @@ NULL = UUID("0b3e2d1c4a5f46e7b8c9d0e1f2a3b4c5") def test_a_null_key_from_the_server_licence_is_dropped(): - vaults = FakeVaults() + vaults = memory_vaults() 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 vaults.vaults[0].added == {NEW: "k_new"} assert NULL not in ContentKeyResolver.LICENSE_KEY_CACHE def test_a_null_key_from_the_batch_licence_is_dropped(monkeypatch): - vaults = FakeVaults() + vaults = memory_vaults() source = MemoryKeySource() keys = make_resolver(vaults, source) drm = FakeWidevine([NEW]) @@ -278,5 +248,5 @@ def test_a_null_key_from_the_batch_licence_is_dropped(monkeypatch): keys.wait_vault_writes() assert drm.content_keys == {NEW: "k_new"} - assert vaults.added == {NEW: "k_new"} + assert vaults.vaults[0].added == {NEW: "k_new"} assert NULL not in ContentKeyResolver.LICENSE_KEY_CACHE diff --git a/tests/remote/unit/test_server_vault_push.py b/tests/remote/unit/test_server_vault_push.py index f793c575..2cbe930c 100644 --- a/tests/remote/unit/test_server_vault_push.py +++ b/tests/remote/unit/test_server_vault_push.py @@ -139,7 +139,8 @@ def decrypt( server_vault=SimpleNamespace(add_keys=lambda service, keys, track: pushed.append((keys, track))), ) keys = resolver(vaults, tag="EXAMPLE", source=source) - vaults.flagged.update((flagged or {}).items()) + for kid, key in (flagged or {}).items(): + vaults.flag_bad_key(kid, key) path = tmp_path / "video.mp4" path.write_bytes(b"cipher") content_keys = {LICENSED: KEY, VAULTED: OTHER_KEY, NULL: "0" * 32, **(flagged or {})} diff --git a/unshackle/core/drm/key_resolution.py b/unshackle/core/drm/key_resolution.py index a815ae8a..d0be09a2 100644 --- a/unshackle/core/drm/key_resolution.py +++ b/unshackle/core/drm/key_resolution.py @@ -43,8 +43,7 @@ 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 +from unshackle.core.vaults import KeySource, Vaults if TYPE_CHECKING: from unshackle.core.title_source import ServerKeySource @@ -169,7 +168,7 @@ class ContentKeyResolver: 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] + return [kid for kid, key in keys.items() if self.vaults.proved_wrong(kid, key)] def drop(kid: UUID) -> str: key = keys.pop(kid) @@ -177,7 +176,7 @@ class ContentKeyResolver: self.LICENSE_KEY_CACHE.pop(kid) return key - def relicense(bad: dict[UUID, str], kids: dict[UUID, Vault]) -> None: + def relicense(bad: dict[UUID, str], kids: dict[UUID, KeySource]) -> 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 @@ -197,14 +196,13 @@ class ContentKeyResolver: new = keys.get(kid) if new is None: continue - source = self.vaults.sources.get(kid) + source = self.vaults.source_of(kid, new) 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]: + if new == key or not self.vaults.held_locally(kid, new): + self._flush_vault_writes([partial(self._cache_keys_to_vaults, {kid: new})]) + elif new == key and source is kids.get(kid): raise ValueError(f"{key} from {kids[kid].name} was bad and no other source has the key") known_bad = flagged_kids() @@ -220,10 +218,10 @@ class ContentKeyResolver: licence(drm, track_kid=kid) keys = getattr(drm, "content_keys", keys) - def vault_kids() -> dict[UUID, Vault]: + def vault_kids() -> dict[UUID, KeySource]: """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]} + found = {kid: self.vaults.source_of(kid, key) for kid, key in keys.items()} + return {kid: source for kid, source in found.items() if source is not None} backup = path.with_name(path.name + ".enc") backup.unlink(missing_ok=True) # a killed run leaves one behind; its bytes may not match @@ -237,7 +235,7 @@ class ContentKeyResolver: windows = kid_map.windows if kid_map else {} video = kid_map.video if kid_map else None - def proven(passed: dict[UUID, Vault]) -> dict[UUID | str, str]: + def proven(passed: dict[UUID, KeySource]) -> dict[UUID | str, str]: """The licence keys and the vault keys in ``passed``, without null keys; a flagged pair never gets here.""" sourced = vault_kids() return { @@ -247,14 +245,14 @@ class ContentKeyResolver: 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]: + def judged_kids() -> dict[UUID, KeySource]: """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]: + def failed_kids(kids: dict[UUID, KeySource]) -> 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 @@ -291,19 +289,11 @@ class ContentKeyResolver: 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) + passed = kids if checked else {} + self._flush_vault_writes([partial(self.vaults.proven, dict(keys), passed)]) server_vault = self.source.server_vault if self.source and track is not None else None if server_vault is not None: - self._flush_vault_writes( - [partial(server_vault.add_keys, self.tag, proven(kids if checked else {}), track)] - ) + self._flush_vault_writes([partial(server_vault.add_keys, self.tag, proven(passed), track)]) return bad = {kid: drop(kid) for kid in {*failed, *stale}} for kid, key in bad.items(): @@ -361,8 +351,8 @@ class ContentKeyResolver: 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 + flagged vault key takes it before any vault. A server vault key is unproven, so + ``Vaults`` holds it as an offer and it 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[str | None, Any]] = {} @@ -381,7 +371,7 @@ class ContentKeyResolver: 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)) + self.vaults.offer(kid, 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})]) @@ -399,7 +389,7 @@ class ContentKeyResolver: 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 + and self.vaults.source_of(kid, key) is None } keys = {kid: key for kid, key in resolved.items() if not self.vaults.held_locally(kid, key)} if keys: @@ -411,8 +401,7 @@ class ContentKeyResolver: 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[UUID | str, str], content_keys)) + successful_caches = self.vaults.licensed(content_keys) kids, caches = self.vault_cache_tally or (set(), successful_caches) self.vault_cache_tally = (kids | content_keys.keys(), min(caches, successful_caches)) @@ -872,7 +861,7 @@ class ContentKeyResolver: 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) + self.vaults.supplied(kid, key, source) elif kid not in known_keys: new_keys[kid] = key if new_keys: diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index 3ad4f91b..b2a0e491 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -98,7 +98,6 @@ from unshackle.core.utils import run_proxy from unshackle.core.utils.collections import ci_get from unshackle.core.utils.redact import redact_path, redact_text, safe_display_url from unshackle.core.utils.service_params import service_options -from unshackle.core.vault import Vault from unshackle.core.wire import apply_title_fields, build_title, build_tracks if TYPE_CHECKING: @@ -789,29 +788,23 @@ def cache_key_filter(service_tag: str, profile: str | None) -> Callable[[str], b return relevant -class ServerVault(Vault): - """The server's vaults as one source for the client, which reports bad pairs to it and pushes proven ones. +class ServerVault: + """The server's vaults as one content-key source for the client, which reports bad pairs to it and pushes proven ones. - ``decrypt_verified`` needs a Vault to hold in ``Vaults.sources`` so a server-supplied - content key gets the same decode check as a local vault key. The client never learns - which server vault answered and cannot read it. A bad verdict goes to the server at once, - so its next licence skips the pair. ``add_keys`` pushes the proven keys the server did not serve. + A content key the server's vaults supplied gets the same decode check as a local vault key, with this + source on record in ``Vaults``. The client never learns which server vault answered and cannot read + it. A bad verdict goes to the server at once, so its next licence skips the pair. """ + name = "server_cdm" + local = False report_now = True def __init__(self, service: RemoteService) -> None: - super().__init__("server_cdm", no_push=True) self.service = service - def get_key(self, kid: UUID | str, service: str) -> str | None: - return None - - def get_keys(self, service: str) -> Iterator[tuple[str, str]]: - return iter(()) - - def add_key(self, service: str, kid: UUID | str, key: str) -> bool: - return False + def __str__(self) -> str: + return f"{self.name} {type(self).__name__}" def add_keys(self, service: str, kid_keys: dict[UUID | str, str], track: AnyTrack | None = None) -> int: """Post the pairs of ``track`` the server neither served nor accepted; always 0, as it does not say what it stored. @@ -832,9 +825,6 @@ class ServerVault(Vault): remote.served_keys.update((UUID(hex=kid), key) for kid, key in keys.items()) return 0 - def get_services(self) -> Iterator[str]: - return iter(()) - def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None: self.service.report_bad_key(UUID(str(kid)), key) @@ -1667,7 +1657,7 @@ class RemoteService(TitleSource): """True when the server handed ``track`` to this machine's own CDM to license.""" return str(track.id) in self.client_licensed - def vault_source(self, kid: UUID, key: str) -> Vault | None: + def vault_source(self, kid: UUID, key: str) -> ServerVault | None: """The server vault when it served ``key`` for ``kid``, else None.""" return self.server_vault if self.server_vault_keys.get(kid) == key else None diff --git a/unshackle/core/title_source.py b/unshackle/core/title_source.py index 10043ccf..1d30ae5a 100644 --- a/unshackle/core/title_source.py +++ b/unshackle/core/title_source.py @@ -25,7 +25,6 @@ from unshackle.core.utilities import declared_kwargs if TYPE_CHECKING: from unshackle.core.drm.cbcs import SampleDecrypter from unshackle.core.remote_service import ServerVault - from unshackle.core.vault import Vault class KeyArrival(Enum): @@ -86,7 +85,7 @@ class ServerKeySource(Protocol): def license_file(self, track: AnyTrack) -> str: """The content key the server licenses for the whole-file cipher of ``track``; a refusal raises.""" - def vault_source(self, kid: UUID, key: str) -> Vault | None: + def vault_source(self, kid: UUID, key: str) -> ServerVault | None: """The server vault when it served ``key`` for ``kid``, else None. That content key must pass a decrypt check.""" @property diff --git a/unshackle/core/vaults.py b/unshackle/core/vaults.py index 86ccddce..d2d6ba85 100644 --- a/unshackle/core/vaults.py +++ b/unshackle/core/vaults.py @@ -4,7 +4,8 @@ import time from collections.abc import Collection, Iterable, Iterator from concurrent.futures import Future, ThreadPoolExecutor, as_completed from functools import partial -from typing import Any +from threading import Lock +from typing import Any, Protocol, cast from uuid import UUID from unshackle.core.config import config @@ -20,19 +21,35 @@ VAULTS = sorted( MODULES = {path.stem: getattr(import_module_by_path(path), path.stem) for path in VAULTS} +class KeySource(Protocol): + """Where a content key came from: a loaded vault, or the server's vaults over --remote.""" + + name: str + local: bool + report_now: bool + + def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None: ... + + class Vaults: - """Keeps hold of Key Vaults with convenience functions, e.g. searching all vaults.""" + """The key vaults of a run, and the ledger of where each content key in use came from. + + A source offers a content key (``get_key``, ``offer``, ``supplied``). A decode then proves it + (``proven``) or proves it wrong (``flag_bad_key``), or a CDM licenses it (``licensed``). From these + events the ledger decides which vault hears of a bad pair, and when. + """ def __init__(self, service: str | None = None) -> None: self.service = service or "" self.vaults: list[Vault] = [] - self.sources: dict[UUID | str, tuple[str, Vault]] = {} + self.sources: dict[UUID | str, tuple[str, KeySource]] = {} self.flagged: set[tuple[UUID | str, str]] = set() - self.candidates: dict[UUID | str, list[tuple[str, Vault]]] = {} + self.candidates: dict[UUID | str, list[tuple[str, KeySource]]] = {} self.warned: set[tuple[str, UUID | str, str]] = set() self.failed: set[tuple[str, str]] = set() self.unreachable: set[Vault] = set() - self.unreported: dict[tuple[UUID | str, str], Vault] = {} + self.unreported: dict[tuple[UUID | str, str], KeySource] = {} + self.lock = Lock() def __iter__(self) -> Iterator[Vault]: return iter(self.vaults) @@ -50,7 +67,7 @@ class Vaults: kwargs["timeout"] = config.vault_timeout self.vaults.append(module(**kwargs)) - def get_key(self, kid: UUID | str) -> tuple[str | None, Vault | None]: + def get_key(self, kid: UUID | str) -> tuple[str | None, KeySource | None]: """Get Key from the first Vault it can by KID (Key ID) and Service. Local vaults go first, one at a time: a hit there costs nothing and skips the network. @@ -63,12 +80,12 @@ class Vaults: for vault in local: key = self.query_vault(vault, kid) if key: - self.sources[kid] = (key, vault) - return key, vault - for key, vault in self.candidates.get(kid, []): + return self.supplied(kid, key, vault) + with self.lock: + candidates = list(self.candidates.get(kid, [])) + for key, source in candidates: if not self.is_flagged(kid, key): - self.sources[kid] = (key, vault) - return key, vault + return self.supplied(kid, key, source) if not remote: return None, None pool = ThreadPoolExecutor(len(remote)) @@ -79,8 +96,7 @@ class Vaults: for future in as_completed(futures): key = future.result() if key: - self.sources[kid] = (key, futures[future]) - return key, futures[future] + return self.supplied(kid, key, futures[future]) return None, None finally: # a slow vault must not hold up a content key another vault already returned; the @@ -92,8 +108,32 @@ class Vaults: if future.cancelled() or future.exception(): return key = future.result() - if key and (key, vault) not in self.candidates.setdefault(kid, []): - self.candidates[kid].append((key, vault)) + if key: + self.offer(kid, key, vault) + + def offer(self, kid: UUID | str, key: str, source: KeySource) -> None: + """Keep a content key ``source`` offered for ``kid``; ``get_key`` gives it after the local vaults miss.""" + with self.lock: + offered = self.candidates.setdefault(kid, []) + if (key, source) not in offered: + offered.append((key, source)) + + def supplied(self, kid: UUID | str, key: str, source: KeySource) -> tuple[str, KeySource]: + """Record that the content key in use for ``kid`` came from ``source``, which a failed decode then tells.""" + with self.lock: + self.sources[kid] = (key, source) + return key, source + + def source_of(self, kid: UUID | str, key: str) -> KeySource | None: + """The source that supplied ``key`` for ``kid``, or None when no vault or server vault did.""" + with self.lock: + source = self.sources.get(kid) + return source[1] if source and source[0] == key else None + + def proved_wrong(self, kid: UUID | str, key: str) -> bool: + """True when a decode in this run proved the pair wrong and no licence has confirmed it since.""" + with self.lock: + return (kid, key) in self.flagged def is_flagged(self, kid: UUID | str, key: str) -> bool: """True when a local vault has flagged the KID:KEY as wrong.""" @@ -126,8 +166,7 @@ class Vaults: found = not is_null_key(key) if found and key and self.is_flagged(kid, key): found = False - if (vault.name, kid, key) not in self.warned: - self.warned.add((vault.name, kid, key)) + if self.first((vault.name, kid, key), self.warned): log.warning(f"{key} from {vault.name} is flagged bad, skipping") if dl: dl.log_vault_query( @@ -142,29 +181,44 @@ class Vaults: def flag_bad_key(self, kid: UUID | str, key: str) -> None: """Flag a KID:KEY in every local vault. A failed decode is no proof, so the remote vault that - served it hears of it from ``report_replaced``, or at once when it sets ``report_now``.""" - self.flagged.add((kid, key)) - source = self.sources.pop(kid, None) + served it hears of it from ``proven``, once another key replaced the pair, or at once when it sets ``report_now``.""" + with self.lock: + self.flagged.add((kid, key)) + source = self.sources.pop(kid, None) + remote = source[1] if source and not source[1].local else None + if remote and not remote.report_now: + self.unreported[kid, key] = remote name = source[1].name if source else "unknown" for vault in self.live(): if vault.local: self.tell(vault, kid, key, name) - if source and not source[1].local: - if source[1].report_now: - self.tell(source[1], kid, key, name) - else: - self.unreported[kid, key] = source[1] + if remote and remote.report_now: + self.tell(remote, kid, key, name) - def report_replaced(self, content_keys: dict[UUID | str, str]) -> None: - """Tell each remote vault about its flagged pair once ``content_keys`` holds another key for the KID.""" + def proven(self, content_keys: dict[UUID | str, str], checked: dict[UUID, KeySource]) -> None: + """A track decrypted with ``content_keys``, and a decode check passed the content key of each KID in ``checked``. + + Each checked pair goes to the vaults other than the source ``checked`` names, unless a decode + proved it wrong since. Each remote vault whose flagged pair ``content_keys`` replaced with + another key now hears of it. + """ + for proven_kid, source in checked.items(): + if not self.proved_wrong(proven_kid, content_keys[proven_kid]): + self.add_key(proven_kid, content_keys[proven_kid], excluding=source) live = self.live() - for (kid, key), vault in list(self.unreported.items()): - if content_keys.get(kid) not in (None, key): + with self.lock: + due = [ + (kid, key, vault) + for (kid, key), vault in self.unreported.items() + if content_keys.get(kid) not in (None, key) + ] + for kid, key, _ in due: del self.unreported[kid, key] - if vault in live: - self.tell(vault, kid, key, vault.name) + for kid, key, vault in due: + if vault in live: + self.tell(vault, kid, key, vault.name) - def tell(self, vault: Vault, kid: UUID | str, key: str, source: str) -> None: + def tell(self, vault: KeySource, kid: UUID | str, key: str, source: str) -> None: """Flag one pair in one vault; a failure is only a debug line.""" try: vault.flag_bad_key(self.service, kid, key, source) @@ -173,21 +227,28 @@ class Vaults: def clear_licensed_flags(self, content_keys: dict[UUID, str]) -> list[UUID]: """Unflag each pair a licence returned, since the decode check was wrong. Returns their KIDs.""" - cleared = [kid for kid, key in content_keys.items() if self.is_flagged(kid, key)] + cleared = [kid for kid, key in content_keys.items() if self.proved_wrong(kid, key) or self.is_flagged(kid, key)] for kid in cleared: self.unflag_bad_key(kid, content_keys[kid]) return cleared + def licensed(self, content_keys: dict[UUID, str]) -> int: + """A CDM licensed ``content_keys``: unflag each flagged pair, then store them all. Returns the number of vaults that stored them.""" + self.clear_licensed_flags(content_keys) + return self.add_keys(cast(dict[UUID | str, str], content_keys)) + def unflag_bad_key(self, kid: UUID | str, key: str) -> None: """Remove a flag from every Vault.""" - self.flagged.discard((kid, key)) + with self.lock: + self.flagged.discard((kid, key)) + self.unreported.pop((kid, key), None) for vault in self.live(): try: vault.unflag_bad_key(kid, key) except Exception as e: log.debug(f"Could not unflag {key} in Vault '{vault.name}': {e!r}") - def add_key(self, kid: UUID | str, key: str, excluding: Vault | None = None) -> int: + def add_key(self, kid: UUID | str, key: str, excluding: KeySource | None = None) -> int: """Add a KID:KEY to all Vaults, optionally with an exclusion. This method pushes to all Vaults at the same time, so one unreachable Vault costs only its @@ -257,21 +318,27 @@ class Vaults: """Warn once per vault for each distinct failure; a repeat goes to the debug log.""" text = brief(error) message = f"Failed to {action} Vault '{vault.name}': {text}" - if (vault.name, text) in self.failed: - log.debug(message) - else: - self.failed.add((vault.name, text)) + if self.first((vault.name, text), self.failed): log.warning(message) + else: + log.debug(message) def mark_unreachable(self, vault: Vault, error: Exception) -> None: """Skip a vault that is down or still rate limited for the rest of the run, so it costs one timeout, not one per KID.""" - if isinstance(error, (RateLimited, *UNREACHABLE)) and vault not in self.unreachable: - self.unreachable.add(vault) + if isinstance(error, (RateLimited, *UNREACHABLE)) and self.first(vault, self.unreachable): log.warning(f"Skipping Vault '{vault.name}' for the rest of this run") + def first(self, item: Any, seen: set) -> bool: + """Add ``item`` to ``seen``; True only for the thread that added it first.""" + with self.lock: + if item in seen: + return False + seen.add(item) + return True -__all__ = ("Vaults", "load_config_vaults") + +__all__ = ("KeySource", "Vaults", "load_config_vaults") def load_config_vaults(