refactor(vaults): move the settle rules, vault writer, stored tally and server-vault push into the key ledger

This commit is contained in:
imSp4rky
2026-12-04 14:07:04 -07:00
parent 67dea28712
commit 8c4742c0ee
8 changed files with 313 additions and 122 deletions
+29 -1
View File
@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import threading
from pathlib import Path from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
from uuid import UUID from uuid import UUID
@@ -9,7 +10,7 @@ from uuid import UUID
import click import click
import pytest import pytest
from tests.core.key_resolver import resolver, vaults_of from tests.core.key_resolver import MemoryVault, resolver, vaults_of
from tests.core.test_vault_bad_keys import BAD, GOOD, KID, FakeDRM, Remote from tests.core.test_vault_bad_keys import BAD, GOOD, KID, FakeDRM, Remote
from unshackle.core.drm import key_resolution from unshackle.core.drm import key_resolution
from unshackle.core.drm.key_resolution import ContentKeyResolver from unshackle.core.drm.key_resolution import ContentKeyResolver
@@ -111,3 +112,30 @@ def test_a_bad_vault_key_of_a_bridged_track_gives_way_to_the_licence_key_which_i
assert drm.decrypted_with == [{KID: BAD}, {KID: GOOD}] assert drm.decrypted_with == [{KID: BAD}, {KID: GOOD}]
assert path.read_bytes() == b"plain:" + GOOD.encode() assert path.read_bytes() == b"plain:" + GOOD.encode()
assert len(decodes) == 2 and vaults.vaults[0].is_bad_key(KID, BAD) assert len(decodes) == 2 and vaults.vaults[0].is_bad_key(KID, BAD)
def test_the_flag_of_a_bad_licence_key_waits_for_the_licence_write(tmp_path: Path, decodes: list[Path]) -> None:
order: list[str] = []
storing = threading.Event()
class Recording(MemoryVault):
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
assert storing.wait(10)
order.append("store")
return super().add_keys(service, kid_keys)
def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None:
order.append("flag")
vaults = vaults_of(Recording(), service="SVC")
keys = resolver(vaults, tag="SVC")
vaults.licensed({KID: BAD})
path = tmp_path / "track.mp4"
path.write_bytes(b"cipher")
with pytest.raises(click.ClickException, match="does not decrypt track vid"):
keys.decrypt_verified(BridgedDRM({KID: BAD}), path, None, KID, True, TRACK) # type: ignore[arg-type]
storing.set()
keys.wait_vault_writes()
assert order == ["store", "flag"]
+3
View File
@@ -19,6 +19,7 @@ from unshackle.core.download_archive import DownloadArchive
from unshackle.core.title_source import TitleSource from unshackle.core.title_source import TitleSource
from unshackle.core.titles import Episode, Series from unshackle.core.titles import Episode, Series
from unshackle.core.tracks import Audio, Tracks, Video from unshackle.core.tracks import Audio, Tracks, Video
from unshackle.core.vaults import Vaults
class EXAMPLE(TitleSource): class EXAMPLE(TitleSource):
@@ -75,6 +76,8 @@ class EXAMPLE(TitleSource):
class Harness(dl): class Harness(dl):
vaults = Vaults()
def __getattr__(self, name): def __getattr__(self, name):
return None return None
+2 -20
View File
@@ -416,26 +416,6 @@ def test_a_cdm_that_confirms_a_key_flagged_on_entry_clears_the_flag(
assert CONFIRMED in caplog.record_tuples assert CONFIRMED in caplog.record_tuples
def test_a_licence_key_that_replaces_a_bad_local_pair_is_stored(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""The local vault held the bad pair when the licence key arrived, so it skipped the KID; store it now."""
local = SQLite("local", tmp_path / "local.db")
local.add_key("SVC", KID, BAD)
vaults = Vaults("SVC")
vaults.vaults = [local]
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
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
def test_stale_backup_from_a_killed_run_is_not_restored(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: def test_stale_backup_from_a_killed_run_is_not_restored(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
poisoned = Remote("poisoned", tmp_path / "poisoned.db") poisoned = Remote("poisoned", tmp_path / "poisoned.db")
poisoned.add_key("SVC", KID, BAD) poisoned.add_key("SVC", KID, BAD)
@@ -901,6 +881,7 @@ def test_api_vault_reports_the_pair_upstream(monkeypatch: pytest.MonkeyPatch, ca
vaults.flag_bad_key(KID, BAD) vaults.flag_bad_key(KID, BAD)
assert not calls assert not calls
vaults.proven({KID: GOOD}, {}) vaults.proven({KID: GOOD}, {})
vaults.wait_writes()
vaults.unflag_bad_key(KID, BAD) vaults.unflag_bad_key(KID, BAD)
assert calls == [ assert calls == [
@@ -912,6 +893,7 @@ def test_api_vault_reports_the_pair_upstream(monkeypatch: pytest.MonkeyPatch, ca
vaults.supplied(KID, BAD, source) # type: ignore[arg-type] vaults.supplied(KID, BAD, source) # type: ignore[arg-type]
vaults.flag_bad_key(KID, BAD) vaults.flag_bad_key(KID, BAD)
vaults.proven({KID: GOOD}, {}) vaults.proven({KID: GOOD}, {})
vaults.wait_writes()
calls.clear() calls.clear()
flag_and_replace(SimpleNamespace(name="other", local=False, report_now=False)) flag_and_replace(SimpleNamespace(name="other", local=False, report_now=False))
+142 -2
View File
@@ -9,10 +9,14 @@ import pytest
import requests import requests
from tests.core.key_resolver import MemoryVault, vaults_of from tests.core.key_resolver import MemoryVault, vaults_of
from unshackle.vaults.SQLite import SQLite
KID = UUID(int=1) KID = UUID(int=1)
SIBLING = UUID(int=2)
NULL = UUID(int=3)
BAD = "aa" * 16 BAD = "aa" * 16
GOOD = "bb" * 16 GOOD = "bb" * 16
CONFIRMED = f"Licence returned the same content key for KID {KID.hex}, keeping it"
def server() -> SimpleNamespace: def server() -> SimpleNamespace:
@@ -37,6 +41,7 @@ def test_a_proven_vault_key_goes_to_every_other_vault() -> None:
assert vaults.get_key(KID) == (GOOD, remote) assert vaults.get_key(KID) == (GOOD, remote)
vaults.proven({KID: GOOD}, {KID: remote}) vaults.proven({KID: GOOD}, {KID: remote})
vaults.wait_writes()
assert local.added == {KID: GOOD} assert local.added == {KID: GOOD}
assert remote.added == {} assert remote.added == {}
@@ -49,6 +54,7 @@ def test_a_pair_proved_wrong_before_its_proof_is_stored_goes_nowhere() -> None:
vaults.flag_bad_key(KID, GOOD) vaults.flag_bad_key(KID, GOOD)
vaults.proven({KID: GOOD}, {KID: remote}) vaults.proven({KID: GOOD}, {KID: remote})
vaults.wait_writes()
assert local.added == {} assert local.added == {}
assert remote.added == {} assert remote.added == {}
@@ -61,24 +67,30 @@ def test_a_remote_vault_hears_of_its_bad_pair_only_once_another_key_replaces_it(
vaults.flag_bad_key(KID, BAD) vaults.flag_bad_key(KID, BAD)
vaults.proven({KID: BAD}, {}) vaults.proven({KID: BAD}, {})
vaults.wait_writes()
assert remote.told == [] assert remote.told == []
assert vaults.proved_wrong(KID, BAD) assert vaults.proved_wrong(KID, BAD)
vaults.proven({KID: GOOD}, {}) vaults.proven({KID: GOOD}, {})
vaults.proven({KID: GOOD}, {}) vaults.proven({KID: GOOD}, {})
vaults.wait_writes()
assert remote.told == [(KID, BAD)] assert remote.told == [(KID, BAD)]
def test_a_licence_clears_a_flag_of_this_run_without_a_local_vault() -> None: def test_a_licence_clears_a_flag_of_this_run_without_a_local_vault(caplog: pytest.LogCaptureFixture) -> None:
remote = MemoryVault({KID: BAD}, local=False) remote = MemoryVault({KID: BAD}, local=False)
vaults = vaults_of(remote) vaults = vaults_of(remote)
vaults.get_key(KID) vaults.get_key(KID)
vaults.flag_bad_key(KID, BAD) vaults.flag_bad_key(KID, BAD)
assert vaults.licensed({KID: BAD}) == 1 vaults.licensed({KID: BAD})
with caplog.at_level(logging.INFO, logger="download"):
vaults.wait_writes()
assert caplog.messages == ["Cached 1 Key to 1/1 Vaults"]
assert not vaults.proved_wrong(KID, BAD) assert not vaults.proved_wrong(KID, BAD)
assert remote.added == {KID: BAD} assert remote.added == {KID: BAD}
vaults.proven({KID: GOOD}, {}) vaults.proven({KID: GOOD}, {})
vaults.wait_writes()
assert remote.told == [] assert remote.told == []
@@ -147,3 +159,131 @@ def test_two_lookups_that_fail_at_once_warn_once(caplog: pytest.LogCaptureFixtur
"Failed to get key from Vault 'down': no answer", "Failed to get key from Vault 'down': no answer",
"Skipping Vault 'down' for the rest of this run", "Skipping Vault 'down' for the rest of this run",
] ]
def test_a_licence_that_returns_the_dropped_key_warns_once_unflags_it_and_stores_it_again(
caplog: pytest.LogCaptureFixture,
) -> None:
local = MemoryVault(name="local")
vaults = vaults_of(local)
vaults.flag_bad_key(KID, BAD)
with caplog.at_level(logging.WARNING, logger="download"):
vaults.relicensed({KID: BAD}, {KID: BAD}, {})
vaults.relicensed({KID: BAD}, {KID: BAD}, {})
vaults.wait_writes()
assert caplog.messages == [CONFIRMED]
assert not vaults.proved_wrong(KID, BAD)
assert local.pushes == [{KID: BAD}, {KID: BAD}]
@pytest.mark.parametrize("held", [False, True], ids=["new", "held-locally"])
def test_a_new_licence_key_for_a_dropped_pair_is_stored_unless_a_local_vault_holds_it(held: bool) -> None:
local = MemoryVault({KID: GOOD} if held else None, name="local")
vaults = vaults_of(local)
vaults.relicensed({KID: BAD, SIBLING: BAD}, {KID: GOOD}, {})
vaults.wait_writes()
assert local.pushes == ([] if held else [{KID: GOOD}])
def test_a_licence_key_that_replaces_a_bad_local_pair_is_stored(tmp_path) -> None:
"""The local vault held the bad pair when the licence key arrived, so it refused the KID; the flag frees it."""
local = SQLite("local", tmp_path / "local.db")
local.add_key("SVC", KID, BAD)
vaults = vaults_of(local, service="SVC")
assert vaults.get_key(KID) == (BAD, local)
assert local.add_keys("SVC", {KID: GOOD}) == 0
vaults.flag_bad_key(KID, BAD)
vaults.relicensed({KID: BAD}, {KID: GOOD}, {KID: local})
vaults.wait_writes()
assert local.is_bad_key(KID, BAD)
assert local.get_key(KID, "SVC") == GOOD
def test_the_same_key_again_from_its_vault_raises() -> None:
remote = MemoryVault({KID: BAD}, local=False)
vaults = vaults_of(remote)
vaults.get_key(KID)
vaults.flag_bad_key(KID, BAD)
assert vaults.get_key(KID) == (BAD, remote)
with pytest.raises(ValueError, match="from memory was bad and no other source has the key"):
vaults.relicensed({KID: BAD}, {KID: BAD}, {KID: remote})
def test_a_licence_key_is_stored_then_sent_to_the_server_vault_and_its_flag_waits_for_both() -> None:
order: list[tuple] = []
storing = threading.Event()
class Recording(MemoryVault):
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
assert storing.wait(10)
order.append(("store", dict(kid_keys)))
return super().add_keys(service, kid_keys)
def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None:
order.append(("flag", kid, key))
server_vault = SimpleNamespace(add_keys=lambda service, keys, track: order.append(("server", dict(keys), track)))
vaults = vaults_of(Recording())
vaults.licensed({KID: GOOD}, "track", server_vault) # type: ignore[arg-type]
vaults.licensed({SIBLING: GOOD}, None, server_vault) # type: ignore[arg-type]
vaults.flag_bad_key(KID, GOOD, licence=True)
vaults.proven({NULL: BAD}, {NULL: server()}) # type: ignore[dict-item]
storing.set()
vaults.wait_writes()
assert order == [
("store", {KID: GOOD}),
("server", {KID: GOOD}, "track"),
("store", {SIBLING: GOOD}),
("flag", KID, GOOD),
("store", {NULL: BAD}),
]
def test_a_vault_write_that_fails_logs_one_error_line(caplog: pytest.LogCaptureFixture) -> None:
class Failing(MemoryVault):
def is_bad_key(self, kid: UUID | str, key: str) -> bool:
raise RuntimeError("disk gone")
vaults = vaults_of(Failing())
vaults.licensed({KID: GOOD})
with caplog.at_level(logging.ERROR):
vaults.wait_writes()
assert caplog.record_tuples == [("download", logging.ERROR, "Vault write failed: RuntimeError('disk gone')")]
def test_a_proven_track_sends_one_set_to_the_server_vault_and_copies_only_its_vault_keys() -> None:
remote, local = MemoryVault({KID: GOOD}, local=False), MemoryVault(name="local")
vaults = vaults_of(local, remote)
vaults.get_key(KID)
pushed: list = []
server_vault = SimpleNamespace(add_keys=lambda service, keys, track: pushed.append((keys, track)))
content_keys = {KID: GOOD, SIBLING: BAD, NULL: "0" * 32, UUID(int=4): BAD}
vaults.proven(content_keys, {KID: remote, SIBLING: None, NULL: None}, "track", server_vault) # type: ignore[arg-type]
vaults.proven(content_keys, {KID: remote, SIBLING: None}, None, server_vault) # type: ignore[arg-type]
vaults.wait_writes()
assert local.added == {KID: GOOD}
assert remote.added == {}
assert pushed == [({KID: GOOD, SIBLING: BAD}, "track")]
def test_building_and_dropping_many_vaults_starts_no_thread() -> None:
"""The server builds a Vaults per request; the one vault writer of the process starts only on its first write."""
before = set(threading.enumerate())
for _ in range(50):
vaults_of(MemoryVault())
assert set(threading.enumerate()) - before == set()
assert all(vaults_of().WRITER is vaults_of().WRITER for _ in range(3))
@@ -23,6 +23,7 @@ from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
from unshackle.core.title_source import TitleSource from unshackle.core.title_source import TitleSource
from unshackle.core.titles import Episode, Series from unshackle.core.titles import Episode, Series
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.vaults import Vaults
class Selected(BaseException): class Selected(BaseException):
@@ -37,6 +38,8 @@ class Selected(BaseException):
class Harness(dl): class Harness(dl):
vaults = Vaults()
def __getattr__(self, name: str) -> None: def __getattr__(self, name: str) -> None:
# every optional dl attribute (tmdb ids, cdm, vaults, ...) reads as unset # every optional dl attribute (tmdb ids, cdm, vaults, ...) reads as unset
return None return None
+1 -1
View File
@@ -115,7 +115,7 @@ def titles(sid):
def push(): def push():
track = SimpleNamespace(id="example-1-login1") track = SimpleNamespace(id="example-1-login1")
return keys.VAULT_WRITER.submit(service.server_vault.add_keys, "EXAMPLE", {UUID(int=1): "ab" * 16}, track) keys.vaults.licensed({UUID(int=1): "ab" * 16}, track, service.server_vault)
calls = { calls = {
"url": service.track_url, "url": service.track_url,
+27 -83
View File
@@ -6,13 +6,11 @@ import logging
import os import os
from collections import defaultdict from collections import defaultdict
from collections.abc import Callable from collections.abc import Callable
from concurrent import futures
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack from contextlib import ExitStack
from functools import partial from functools import partial
from pathlib import Path from pathlib import Path
from threading import Lock from threading import Lock
from typing import TYPE_CHECKING, Any, Protocol, cast from typing import TYPE_CHECKING, Any, Protocol
from uuid import UUID from uuid import UUID
import click import click
@@ -89,14 +87,13 @@ class ContentKeyResolver:
The order of key sources is: the keys a server key source gave, the keys this run already 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``, 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 ``licence_for``, ``decrypt_verified`` and ``wait_vault_writes``. The locks and LICENSE_KEY_CACHE are
cache and the vault writer are class-level, so every run in one process shares them. class-level, so every run in one process shares them; the ledger in ``Vaults`` does every vault write.
""" """
DRM_LOCKS: dict[str, Lock] = {} DRM_LOCKS: dict[str, Lock] = {}
DRM_LOCKS_GUARD = Lock() DRM_LOCKS_GUARD = Lock()
LICENCE_LOCK = Lock() LICENCE_LOCK = Lock()
VAULT_WRITER = ThreadPoolExecutor(1, thread_name_prefix="vault-writer")
LICENSE_KEY_CACHE: dict[UUID, str] = {} LICENSE_KEY_CACHE: dict[UUID, str] = {}
ALL_DRM_LOCK = Lock() ALL_DRM_LOCK = Lock()
@@ -124,10 +121,14 @@ class ContentKeyResolver:
self.best_available = best_available self.best_available = best_available
self.export = export self.export = export
self.debug_logger = debug_logger self.debug_logger = debug_logger
self.vault_cache_tally: tuple[set[UUID], int] | None = None
self.all_drm_attempted: defaultdict[type, set[UUID]] = defaultdict(set) self.all_drm_attempted: defaultdict[type, set[UUID]] = defaultdict(set)
self.all_drm_warned: set[str] = set() self.all_drm_warned: set[str] = set()
@property
def server_vault(self) -> ServerVault | None:
"""The server key source's vault, which gets the proven content keys over --remote."""
return self.source.server_vault if self.source else None
def licence_for(self, track: AnyTrack, title: Title_T, table: Table, all_drm: bool = False) -> partial: 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)``. """The licence callback for ``track``: call it as ``fn(drm, track_kid=None)``.
@@ -169,9 +170,8 @@ class ContentKeyResolver:
With ``decrypt=False`` the downloader already decrypted the segments in place, so a 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. A locally licensed plugin track also loses its output. failure can only flag and raise; the next run skips the flagged pair. A locally licensed plugin track also loses its output.
After a decrypt that passes, the server key source's vault gets the proven content keys of After a decrypt that passes, the ledger gets the proven KIDs of ``track``: each licence key, and each
``track``: each licence key, and each vault key the decode check passed. A bridged track sends only vault key the decode check passed. A bridged track gives only the licence keys that the decode check decoded.
the licence keys that the decode check decoded.
Before the decrypt, each KID the DRM names without a content key is licensed when the file 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. uses it, or when the file cannot be mapped, because ``_prepare_drm`` licensed only for the track's KID.
@@ -193,12 +193,11 @@ class ContentKeyResolver:
return key return key
def relicense(bad: dict[UUID, str], kids: dict[UUID, KeySource]) -> 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. """Licence again for each dropped KID, then let the ledger 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 _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 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. 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 nonlocal keys
if not licence: if not licence:
@@ -208,20 +207,7 @@ class ContentKeyResolver:
if kid != track_kid and kid not in getattr(drm, "content_keys", {}): if kid != track_kid and kid not in getattr(drm, "content_keys", {}):
licence(drm, track_kid=kid) licence(drm, track_kid=kid)
keys = getattr(drm, "content_keys", keys) keys = getattr(drm, "content_keys", keys)
for kid, key in bad.items(): self.vaults.relicensed(bad, keys, kids)
new = keys.get(kid)
if new is None:
continue
source = self.vaults.source_of(kid, new)
if source is None:
if new == key:
if self.vaults.first(("licence", kid, key), self.vaults.warned):
self.log.warning(f"Licence returned the same content key for KID {kid.hex}, keeping it")
self.vaults.unflag_bad_key(kid, key)
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() known_bad = flagged_kids()
if known_bad and licence: if known_bad and licence:
@@ -255,17 +241,14 @@ class ContentKeyResolver:
windows = kid_map.windows if kid_map else {} windows = kid_map.windows if kid_map else {}
video = kid_map.video if kid_map else None video = kid_map.video if kid_map else None
def proven(passed: dict[UUID, KeySource], decoded: set[UUID]) -> dict[UUID | str, str]: def proven_kids(passed: dict[UUID, KeySource], decoded: set[UUID]) -> dict[UUID, KeySource | None]:
"""The licence keys and the vault keys in ``passed``, without null keys; a flagged pair never gets here. """The vault KIDs in ``passed`` with their vault, and the licence KIDs with None; a flagged pair never gets here.
A bridged DRM's licence key counts only when its KID is in ``decoded``. A bridged DRM's licence key counts only when its KID is in ``decoded``.
""" """
sourced = vault_kids() sourced = vault_kids()
return { licence_kids = (kid for kid in keys if (kid in decoded if bridged else kid not in sourced))
kid: key return {**dict.fromkeys(licence_kids), **passed}
for kid, key in keys.items()
if (kid in passed or (kid in decoded if bridged else kid not in sourced)) and not is_null_key(key)
}
def window_decodes(start: float, end: float) -> bool: 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) return ffmpeg_decodes(path, start=start, seconds=end - start if end > start else 0.5, video=video)
@@ -292,15 +275,15 @@ class ContentKeyResolver:
"""Stop a bridged or locally licensed plugin track whose licence key does not decode; flag the pair. """Stop a bridged or locally licensed plugin track whose licence key does not decode; flag the pair.
A multi-DRM licence server can issue a PlayReady or Widevine content key that is not the FairPlay one, A multi-DRM licence server can issue a PlayReady or Widevine content key that is not the FairPlay one,
and a plugin decrypter can report no error for a wrong key. The flag goes through the vault writer, after the and a plugin decrypter can report no error for a wrong key. Returns the KIDs that the check decoded.
licence's own write of the pair. Returns the KIDs that the check decoded.
""" """
if not (bridged and binaries.FFMPEG and path.exists()): if not (bridged and binaries.FFMPEG and path.exists()):
return set() return set()
sourced = vault_kids() sourced = vault_kids()
licensed = judged_kids({kid: None for kid in real_kids(drm) if kid in keys and kid not in sourced}) licensed = judged_kids({kid: None for kid in real_kids(drm) if kid in keys and kid not in sourced})
if bad := failed_kids(licensed): if bad := failed_kids(licensed):
self._flush_vault_writes([partial(self.vaults.flag_bad_key, kid, drop(kid)) for kid in bad]) for kid in bad:
self.vaults.flag_bad_key(kid, drop(kid), licence=True)
refuse(next(kid for kid in licensed if kid in bad)) refuse(next(kid for kid in licensed if kid in bad))
return set(licensed) return set(licensed)
@@ -343,10 +326,7 @@ class ContentKeyResolver:
if not failed: if not failed:
decoded = refuse_bad_licence_keys() decoded = refuse_bad_licence_keys()
passed = kids if checked else {} passed = kids if checked else {}
self._flush_vault_writes([partial(self.vaults.proven, dict(keys), passed)]) self.vaults.proven(keys, proven_kids(passed, decoded), track, self.server_vault)
server_vault = self.source.server_vault if self.source and track is not None else None
if server_vault is not None and (sent := proven(passed, decoded)):
self._flush_vault_writes([partial(server_vault.add_keys, self.tag, sent, track)])
return return
bad = {kid: drop(kid) for kid in {*failed, *stale}} bad = {kid: drop(kid) for kid in {*failed, *stale}}
retry = backup.exists() and licence retry = backup.exists() and licence
@@ -369,26 +349,9 @@ class ContentKeyResolver:
finally: finally:
backup.unlink(missing_ok=True) 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: def wait_vault_writes(self) -> None:
"""Block until every queued vault write has run, then log the total once.""" """Block until every queued vault write has run, then log the stored tally once."""
self.VAULT_WRITER.submit(lambda: None).result() self.vaults.wait_writes()
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: def take_server_keys(self, title: Title_T) -> None:
"""Put the KeyBatch of the server key source on the tracks of ``title``, drop the null keys, then cache the rest.""" """Put the KeyBatch of the server key source on the tracks of ``title``, drop the null keys, then cache the rest."""
@@ -487,7 +450,7 @@ class ContentKeyResolver:
self.vaults.offer(kid, server_key, server_vault) self.vaults.offer(kid, server_key, server_vault)
elif kid not in self.LICENSE_KEY_CACHE: elif kid not in self.LICENSE_KEY_CACHE:
self.LICENSE_KEY_CACHE[kid] = server_key self.LICENSE_KEY_CACHE[kid] = server_key
self._flush_vault_writes([partial(self._cache_keys_to_vaults, {kid: server_key})]) self.vaults.licensed({kid: server_key})
def _cache_resolved_keys(self, title: Title_T, vault_keys: set[tuple[UUID, str]]) -> None: def _cache_resolved_keys(self, title: Title_T, vault_keys: set[tuple[UUID, str]]) -> None:
"""Cache the keys a batch licence or an import put on the tracks. """Cache the keys a batch licence or an import put on the tracks.
@@ -507,16 +470,7 @@ class ContentKeyResolver:
keys = {kid: key for kid, key in resolved.items() if not self.vaults.held_locally(kid, key)} keys = {kid: key for kid, key in resolved.items() if not self.vaults.held_locally(kid, key)}
if keys: if keys:
self.LICENSE_KEY_CACHE.update(keys) self.LICENSE_KEY_CACHE.update(keys)
self._flush_vault_writes([partial(self._cache_keys_to_vaults, keys)]) self.vaults.licensed(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
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))
@classmethod @classmethod
def drm_lock(cls, drm: DRM_T) -> Lock: def drm_lock(cls, drm: DRM_T) -> Lock:
@@ -691,7 +645,6 @@ class ContentKeyResolver:
"track_kid": track_kid.hex if track_kid else None, "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: with self.drm_lock(drm), ExitStack() as licence_turn:
label = [(f"({truncate_pssh_for_display(pssh, name)})", "text")] if pssh is not None else [] 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")) cek_tree = Tree(Text.assemble((name, "cyan"), *label, overflow="fold"))
@@ -705,7 +658,6 @@ class ContentKeyResolver:
cek_tree.add(f"[logging.level.error]{msg}") cek_tree.add(f"[logging.level.error]{msg}")
if not pre_existing_tree: if not pre_existing_tree:
table.add_row(cek_tree) table.add_row(cek_tree)
self._flush_vault_writes(pending_vault_writes)
all_kids = self._with_track_kid(drm, track_kid) all_kids = self._with_track_kid(drm, track_kid)
stop_at_miss = self.vaults_only and not cdm_only stop_at_miss = self.vaults_only and not cdm_only
@@ -791,12 +743,8 @@ class ContentKeyResolver:
drm.content_keys.update(from_vaults) drm.content_keys.update(from_vaults)
self.LICENSE_KEY_CACHE.update(drm.content_keys) self.LICENSE_KEY_CACHE.update(drm.content_keys)
licensed = {k: v for k, v in drm.content_keys.items() if k not in from_vaults} licensed = {k: v for k, v in drm.content_keys.items() if k not in from_vaults}
pending_vault_writes.append(partial(self._cache_keys_to_vaults, licensed)) checked_later = getattr(drm, "bridged", False) or device_licensed(drm)
server_vault = self.source.server_vault if self.source else None self.vaults.licensed(licensed, track, None if checked_later else self.server_vault)
if server_vault is not None and not (getattr(drm, "bridged", False) or device_licensed(drm)):
pending_vault_writes.append(
partial(server_vault.add_keys, self.tag, cast(dict[UUID | str, str], licensed), track)
)
if track_kid and track_kid not in drm.content_keys: 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" msg = f"No Content Key for KID {track_kid.hex} was returned in the License"
@@ -807,8 +755,6 @@ class ContentKeyResolver:
table.add_row() table.add_row()
table.add_row(cek_tree) table.add_row(cek_tree)
self._flush_vault_writes(pending_vault_writes)
@staticmethod @staticmethod
def _add_key_label(tree: Tree, kid: UUID, key: str, track_kid: UUID | None = None, source: str = "") -> None: def _add_key_label(tree: Tree, kid: UUID, key: str, track_kid: UUID | None = None, source: str = "") -> None:
"""Add ``kid:key`` to a content key tree once, with ``*`` on the track's own KID and ``source`` after it.""" """Add ``kid:key`` to a content key tree once, with ``*`` on the track's own KID and ``source`` after it."""
@@ -966,7 +912,6 @@ class ContentKeyResolver:
if server_cdm and not licensed_locally: if server_cdm and not licensed_locally:
assert remote is not None assert remote is not None
with self.drm_lock(drm), ExitStack() as licence_turn: with self.drm_lock(drm), ExitStack() as licence_turn:
pending_vault_writes: list[Callable[[], Any]] = []
vault_kids = self._with_track_kid(drm, track_kid) 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) self._take_known_keys(drm, vault_kids, track, track_kid, None, use_vaults=not cdm_only)
@@ -1001,8 +946,7 @@ class ContentKeyResolver:
new_keys[kid] = key new_keys[kid] = key
if new_keys: if new_keys:
self.LICENSE_KEY_CACHE.update(new_keys) self.LICENSE_KEY_CACHE.update(new_keys)
pending_vault_writes.append(partial(self._cache_keys_to_vaults, new_keys)) self.vaults.licensed(new_keys)
self._flush_vault_writes(pending_vault_writes)
if server_cdm and not licensed_locally: if server_cdm and not licensed_locally:
if not drm.content_keys: if not drm.content_keys:
+106 -15
View File
@@ -1,3 +1,5 @@
from __future__ import annotations
import inspect import inspect
import logging import logging
import time import time
@@ -5,14 +7,19 @@ from collections.abc import Collection, Iterable, Iterator
from concurrent.futures import Future, ThreadPoolExecutor, as_completed from concurrent.futures import Future, ThreadPoolExecutor, as_completed
from functools import partial from functools import partial
from threading import Lock from threading import Lock
from typing import Any, Protocol, cast from typing import TYPE_CHECKING, Any, Protocol, cast
from uuid import UUID from uuid import UUID
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.utilities import get_debug_logger, import_module_by_path from unshackle.core.utilities import get_debug_logger, import_module_by_path
from unshackle.core.vault import UNREACHABLE, RateLimited, Refused, Vault, brief, is_null_key from unshackle.core.vault import UNREACHABLE, RateLimited, Refused, Vault, brief, is_null_key
if TYPE_CHECKING:
from unshackle.core.constants import AnyTrack
from unshackle.core.remote_service import ServerVault
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
download_log = logging.getLogger("download")
VAULTS = sorted( VAULTS = sorted(
(path for path in config.directories.vaults.glob("*.py") if path.stem.lower() != "__init__"), key=lambda x: x.stem (path for path in config.directories.vaults.glob("*.py") if path.stem.lower() != "__init__"), key=lambda x: x.stem
@@ -32,13 +39,16 @@ class KeySource(Protocol):
class Vaults: class Vaults:
"""The key vaults of a run, and the ledger of where each content key in use came from. """The key vaults of a run, and its key ledger: where each content key in use came from, and what follows.
A source offers a content key (``get_key``, ``offer``, ``supplied``). A decode then proves it A source gives a content key (``get_key``, ``supplied``, ``offer``). A decode proves it (``proven``) or
(``proven``) or proves it wrong (``flag_bad_key``), or a CDM licenses it (``licensed``). From these proves it wrong (``flag_bad_key``), a licence returns keys (``licensed``) or a key for a dropped pair
events the ledger decides which vault hears of a bad pair, and when. (``relicensed``). The ledger decides which vault hears of each, and writes in order on one class-level vault
writer thread; ``wait_writes`` waits for them.
""" """
WRITER = ThreadPoolExecutor(1, thread_name_prefix="vault-writer")
def __init__(self, service: str | None = None) -> None: def __init__(self, service: str | None = None) -> None:
self.service = service or "" self.service = service or ""
self.vaults: list[Vault] = [] self.vaults: list[Vault] = []
@@ -49,6 +59,7 @@ class Vaults:
self.failed: set[tuple[str, str]] = set() self.failed: set[tuple[str, str]] = set()
self.unreachable: set[Vault] = set() self.unreachable: set[Vault] = set()
self.unreported: dict[tuple[UUID | str, str], KeySource] = {} self.unreported: dict[tuple[UUID | str, str], KeySource] = {}
self.tally: tuple[set[UUID], int] | None = None
self.lock = Lock() self.lock = Lock()
def __iter__(self) -> Iterator[Vault]: def __iter__(self) -> Iterator[Vault]:
@@ -179,9 +190,15 @@ class Vaults:
) )
return key if found else None return key if found else None
def flag_bad_key(self, kid: UUID | str, key: str) -> None: def flag_bad_key(self, kid: UUID | str, key: str, licence: bool = False) -> None:
"""Flag a KID:KEY in every local vault. A failed decode is no proof, so the remote vault that """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 ``proven``, once another key replaced the pair, or at once when it sets ``report_now``.""" served it hears of it from ``proven``, once another key replaced the pair, or at once when it sets ``report_now``.
The flag of a ``licence`` content key goes through the vault writer, after the licence's own write of the pair.
"""
if licence:
self._write(partial(self.flag_bad_key, kid, key))
return
with self.lock: with self.lock:
self.flagged.add((kid, key)) self.flagged.add((kid, key))
source = self.sources.pop(kid, None) source = self.sources.pop(kid, None)
@@ -195,13 +212,26 @@ class Vaults:
if remote and remote.report_now: if remote and remote.report_now:
self._tell(remote, kid, key, name) self._tell(remote, kid, key, name)
def proven(self, content_keys: dict[UUID | str, str], checked: dict[UUID, KeySource]) -> None: def proven(
"""A track decrypted with ``content_keys``, and a decode check passed the content key of each KID in ``checked``. self,
content_keys: dict[UUID, str],
checked: dict[UUID, KeySource | None],
track: AnyTrack | None = None,
server_vault: ServerVault | None = None,
) -> None:
"""``track`` decrypted with ``content_keys`` and proved the content key of each KID in ``checked``, with its vault or None for a licence.
Each checked pair goes to the vaults other than the source ``checked`` names, unless a decode Each proven vault key goes to the other vaults, unless a decode proved it wrong since, and each remote
proved it wrong since. Each remote vault whose flagged pair ``content_keys`` replaced with vault whose flagged pair ``content_keys`` replaced with another key hears of it. With a ``track``, the
another key now hears of it. ``server_vault`` gets every proven key that is not null.
""" """
vault_keys = {kid: source for kid, source in checked.items() if source is not None}
self._write(partial(self._proven, cast(dict[UUID | str, str], dict(content_keys)), vault_keys))
if track is not None and server_vault is not None:
if sent := {kid: key for kid, key in content_keys.items() if kid in checked and not is_null_key(key)}:
self._send(sent, track, server_vault)
def _proven(self, content_keys: dict[UUID | str, str], checked: dict[UUID, KeySource]) -> None:
for proven_kid, source in checked.items(): for proven_kid, source in checked.items():
if not self.proved_wrong(proven_kid, content_keys[proven_kid]): if not self.proved_wrong(proven_kid, content_keys[proven_kid]):
self.add_key(proven_kid, content_keys[proven_kid], excluding=source) self.add_key(proven_kid, content_keys[proven_kid], excluding=source)
@@ -232,10 +262,71 @@ class Vaults:
self.unflag_bad_key(kid, content_keys[kid]) self.unflag_bad_key(kid, content_keys[kid])
return cleared return cleared
def licensed(self, content_keys: dict[UUID, str]) -> int: def licensed(
"""A CDM licensed ``content_keys``: unflag each flagged pair, then store them all. Returns the number of vaults that stored them.""" self, content_keys: dict[UUID, str], track: AnyTrack | None = None, server_vault: ServerVault | None = None
) -> None:
"""A licence returned ``content_keys``: unflag each flagged pair, then store them all; with a ``track``, the ``server_vault`` gets them too."""
content_keys = dict(content_keys)
self._write(partial(self._store, content_keys))
self._send(content_keys, track, server_vault)
def _send(self, content_keys: dict[UUID, str], track: AnyTrack | None, server_vault: ServerVault | None) -> None:
"""Queue the push of the content keys of ``track`` to the server's vaults over --remote."""
if track is not None and server_vault is not None:
self._write(partial(server_vault.add_keys, self.service, cast(dict[UUID | str, str], content_keys), track))
def _store(self, content_keys: dict[UUID, str]) -> None:
"""Clear the flags on the pairs of a licence, store its content keys in every vault and count them for ``wait_writes``."""
if not content_keys or not self.vaults:
return
self.clear_licensed_flags(content_keys) self.clear_licensed_flags(content_keys)
return self.add_keys(cast(dict[UUID | str, str], content_keys)) stored = self.add_keys(cast(dict[UUID | str, str], content_keys))
kids, least = self.tally or (set(), stored)
self.tally = (kids | content_keys.keys(), min(least, stored))
def relicensed(
self, dropped: dict[UUID, str], content_keys: dict[UUID, str], sources: dict[UUID, KeySource]
) -> None:
"""A licence ran again for the ``dropped`` pairs and gave ``content_keys``; settle each dropped pair against its new key.
The same key with no vault on record proves the decode check wrong: warn once, unflag and store it again.
A new content key that no local vault holds goes to the vaults. The same key again from its vault in ``sources`` raises ValueError.
"""
for kid, key in dropped.items():
new = content_keys.get(kid)
if new is None:
continue
source = self.source_of(kid, new)
if source is None:
if new == key:
if self.first(("licence", kid, key), self.warned):
download_log.warning(f"Licence returned the same content key for KID {kid.hex}, keeping it")
self.unflag_bad_key(kid, key)
if new == key or not self.held_locally(kid, new):
self.licensed({kid: new})
elif new == key and source is sources.get(kid):
raise ValueError(f"{key} from {sources[kid].name} was bad and no other source has the key")
def _write(self, write: Any) -> None:
"""Queue a vault write on the one writer thread, so a track does not wait on it and writes keep their order."""
self.WRITER.submit(write).add_done_callback(self._report_write)
@staticmethod
def _report_write(future: Future) -> None:
if exc := future.exception():
download_log.error(f"Vault write failed: {exc!r}")
def _take_tally(self) -> tuple[set[UUID], int] | None:
tally, self.tally = self.tally, None
return tally
def wait_writes(self) -> None:
"""Block until every queued vault write has run, then log the stored tally once."""
tally = self.WRITER.submit(self._take_tally).result()
if tally and tally[0]:
kids, stored = tally
count = len(kids)
download_log.info(f"Cached {count} Key{'' if count == 1 else 's'} to {stored}/{len(self.vaults)} Vaults")
def unflag_bad_key(self, kid: UUID | str, key: str) -> None: def unflag_bad_key(self, kid: UUID | str, key: str) -> None:
"""Remove a flag from every Vault.""" """Remove a flag from every Vault."""