refactor(vaults): move content-key provenance and the bad-key verdict into vaults

This commit is contained in:
imSp4rky
2026-11-27 10:30:45 -07:00
parent 49b3a48fbd
commit a4531a14bb
13 changed files with 417 additions and 265 deletions
+22 -33
View File
@@ -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:
+10 -20
View File
@@ -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
+1 -2
View File
@@ -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
+109 -42
View File
@@ -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(