refactor(vaults): give the server handlers vault operations

This commit is contained in:
imSp4rky
2026-11-27 10:51:20 -07:00
parent a4531a14bb
commit dcfd2f66ba
14 changed files with 221 additions and 130 deletions
+3 -1
View File
@@ -488,7 +488,9 @@ def serve(
regions = server_account_regions(tag) or {}
covered = list(regions.get("regions") or []) + (["global"] if regions.get("global") else [])
log.info(f"Server accounts for {tag}: {', '.join(covered)}")
if config.key_vaults and not any(v.get("type") == "SQLite" for v in config.key_vaults):
from unshackle.core.vaults import flag_stores
if config.key_vaults and not flag_stores(config.key_vaults):
log.warning(
"No SQLite key vault configured: a content key a remote client proves wrong cannot be flagged"
)
+17 -39
View File
@@ -17,7 +17,7 @@ from dataclasses import dataclass, field
from functools import partial
from http.cookiejar import CookieJar
from pathlib import Path
from typing import Any, Optional
from typing import TYPE_CHECKING, Any, Optional
from urllib.parse import urlsplit
import click
@@ -102,6 +102,9 @@ from unshackle.core.wire import (
served_url,
)
if TYPE_CHECKING:
from unshackle.core.vaults import Vaults
log = logging.getLogger("api")
@@ -2146,20 +2149,16 @@ def run_health_checks(checks: list[dict[str, Any]] | None = None) -> list[dict[s
vaults, failed = load_config_vaults(probe_service, [vault_config])
if failed:
raise next(iter(failed.values()))
vault = vaults.vaults[0]
try:
vault.get_key(HEALTH_PROBE_KID, probe_service)
except Exception as e:
if type(e).__name__ not in ("KeyIdInvalid", "ServiceTagInvalid"):
raise
return "ok", str(vault)
return "ok", vaults.probe(HEALTH_PROBE_KID)
checks.append(health_check(f"vault:{name}", f"vault {name}", vault_probe, config_secrets(vault_config)))
def bad_keys_probe() -> tuple[str, str]:
from unshackle.core.vaults import flag_stores
if not config.key_vaults:
return "ok", "no vaults configured"
local = [v.get("name") or v["type"] for v in config.key_vaults if v.get("type") == "SQLite"]
local = flag_stores(config.key_vaults)
if local:
return "ok", f"flags stored in {', '.join(local)}"
return "warn", "no SQLite vault, so a content key a client proves wrong cannot be flagged"
@@ -3713,7 +3712,7 @@ def pick_server_pssh(track: Any, candidates: list[str]) -> tuple[str, str] | Non
return None
def load_server_vaults(service_name: str) -> Any:
def load_server_vaults(service_name: str) -> "Vaults":
"""Load server vaults from config.key_vaults; a vault that fails to load is left out."""
from unshackle.core.services import Services
from unshackle.core.vaults import load_config_vaults
@@ -3739,7 +3738,7 @@ def check_vaults(
"""
try:
vaults = once({} if shared is None else shared, "vaults", lambda: load_server_vaults(service_name))
if not vaults.vaults:
if not vaults:
return None
keys: dict[str, str] = {}
sources: dict[str, str] = {}
@@ -3780,14 +3779,14 @@ def cache_to_vaults(keys: dict[str, str], service_name: str, shared: dict[str, A
if not new:
return
vaults = once({} if shared is None else shared, "vaults", lambda: load_server_vaults(service_name))
if not vaults.vaults:
if not vaults:
return
key_map = {UUID(hex=kid): key for kid, key in new.items()}
for kid in vaults.clear_licensed_flags(key_map):
log.info(f"Unflagged {kid.hex}:{key_map[kid]}, the CDM returned it")
cached = vaults.add_keys(key_map)
if cached == len([vault for vault in vaults.vaults if not vault.no_push]):
if vaults.stored_everywhere(cached):
CACHED_PAIRS.update((service_name, kid, key) for kid, key in new.items())
if cached:
log.info(f"Cached {len(key_map)} key(s) to {cached}/{len(vaults)} server vault(s)")
@@ -4525,16 +4524,7 @@ async def session_bad_key_handler(
service_name = session.service_instance.__class__.__name__
vaults = load_server_vaults(service_name)
def flag() -> None:
for vault in vaults.vaults:
if not vault.local and vault.name != source:
continue
try:
vault.flag_bad_key(vaults.service, UUID(hex=kid), served_key, source)
except Exception as e:
log.debug(f"Could not flag {kid} as bad in vault {sanitize_log(vault.name)}: {e!r}")
await asyncio.to_thread(flag)
await asyncio.to_thread(vaults.flag_served, UUID(hex=kid), served_key, source)
session.served_keys.pop(kid, None)
CACHED_PAIRS.discard((service_name, kid, served_key))
log.warning(
@@ -4572,25 +4562,14 @@ async def session_keys_handler(data: TrackKeys, session_id: str, request: web.Re
def store(named: set[str]) -> tuple[Any, dict[Any, str]]:
vaults = load_server_vaults(service.__class__.__name__)
local = [vault for vault in vaults.vaults if vault.local]
def held(vault: Any, kid: uuid.UUID) -> bool:
"""Whether ``vault`` holds a content key for ``kid``. A failed lookup counts as held, a vault with no read access as empty."""
try:
return bool(vault.get_key(kid, vaults.service))
except (PermissionError, NotImplementedError):
return False
except Exception:
return True
new: dict[Any, str] = {}
for kid_hex, key in pairs.items():
if kid_hex not in named or session.served_keys.get(kid_hex, ("",))[0].lower() == key:
continue
kid = uuid.UUID(hex=kid_hex)
if not vaults.is_flagged(kid, key) and not any(held(vault, kid) for vault in local):
if not vaults.is_flagged(kid, key) and not vaults.holds(kid):
new[kid] = key
if new and sum(vaults.push_keys(vault, new) for vault in local if not vault.no_push):
if new and vaults.add_keys(new, local=True):
log.info(
f"Session {sanitize_log(session_id[:12])} sent {len(new)} client content key(s) to the server vaults"
)
@@ -4600,9 +4579,8 @@ async def session_keys_handler(data: TrackKeys, session_id: str, request: web.Re
async with session.lock:
named = await asyncio.to_thread(named_kids)
vaults, new = await asyncio.to_thread(store, named)
remote = [vault for vault in vaults.vaults if not vault.local and not vault.no_push]
if new and remote:
asyncio.get_running_loop().run_in_executor(None, lambda: [vaults.push_keys(vault, new) for vault in remote])
if new:
asyncio.get_running_loop().run_in_executor(None, partial(vaults.add_keys, new, local=False))
except (Exception, SystemExit) as e:
log.debug(f"Session {sanitize_log(session_id[:12])} content keys not stored: {e!r}")
return web.json_response({})
+6 -1
View File
@@ -86,10 +86,15 @@ def vault_session(timeout: float) -> Session:
return session
class Refused(Exception):
"""The vault answered and refused the query, so it is up."""
class Vault(metaclass=ABCMeta):
# a vault on this machine; Vaults.get_key tries these first, before the network ones
local: bool = False
report_now: bool = False
stores_flags: bool = False
def __init__(self, name: str, no_push: bool = False) -> None:
self.name = name
@@ -148,4 +153,4 @@ class Vault(metaclass=ABCMeta):
"""Forget a flagged KID:KEY, for example when a CDM licence confirmed it."""
__all__ = ("Vault", "brief", "json_body")
__all__ = ("Refused", "Vault", "brief", "json_body")
+66 -22
View File
@@ -10,7 +10,7 @@ from uuid import UUID
from unshackle.core.config import config
from unshackle.core.utilities import get_debug_logger, import_module_by_path
from unshackle.core.vault import UNREACHABLE, RateLimited, Vault, brief, is_null_key
from unshackle.core.vault import UNREACHABLE, RateLimited, Refused, Vault, brief, is_null_key
log = logging.getLogger(__name__)
@@ -76,9 +76,9 @@ class Vaults:
and the first one with the content key wins.
"""
local = [v for v in self.vaults if v.local]
remote = [v for v in self.live() if not v.local]
remote = [v for v in self._live() if not v.local]
for vault in local:
key = self.query_vault(vault, kid)
key = self._query_vault(vault, kid)
if key:
return self.supplied(kid, key, vault)
with self.lock:
@@ -90,7 +90,7 @@ class Vaults:
return None, None
pool = ThreadPoolExecutor(len(remote))
try:
futures = {pool.submit(self.query_vault, vault, kid): vault for vault in remote}
futures = {pool.submit(self._query_vault, vault, kid): vault for vault in remote}
for future, vault in futures.items():
future.add_done_callback(partial(self.remember_candidate, kid, vault))
for future in as_completed(futures):
@@ -139,7 +139,7 @@ class Vaults:
"""True when a local vault has flagged the KID:KEY as wrong."""
return any(v.is_bad_key(kid, key) for v in self.vaults if v.local)
def query_vault(self, vault: Vault, kid: UUID | str) -> str | None:
def _query_vault(self, vault: Vault, kid: UUID | str) -> str | None:
"""Ask one vault for a content key. A failure logs a warning and returns None.
A flagged pair counts as no content key, so no vault can serve one again.
@@ -189,11 +189,11 @@ class Vaults:
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():
for vault in self._live():
if vault.local:
self.tell(vault, kid, key, name)
self._tell(vault, kid, key, name)
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:
"""A track decrypted with ``content_keys``, and a decode check passed the content key of each KID in ``checked``.
@@ -205,7 +205,7 @@ class Vaults:
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()
live = self._live()
with self.lock:
due = [
(kid, key, vault)
@@ -216,14 +216,14 @@ class Vaults:
del self.unreported[kid, key]
for kid, key, vault in due:
if vault in live:
self.tell(vault, kid, key, vault.name)
self._tell(vault, kid, key, vault.name)
def tell(self, vault: KeySource, 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)
except Exception as e:
log.debug(f"Could not flag {key} as bad in Vault '{vault.name}': {e!r}")
log.debug(f"Could not flag {key} as bad in Vault '{vault.name}': {brief(e)}")
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."""
@@ -242,7 +242,7 @@ class Vaults:
with self.lock:
self.flagged.discard((kid, key))
self.unreported.pop((kid, key), None)
for vault in self.live():
for vault in self._live():
try:
vault.unflag_bad_key(kid, key)
except Exception as e:
@@ -254,7 +254,7 @@ class Vaults:
This method pushes to all Vaults at the same time, so one unreachable Vault costs only its
own timeout and does not delay the others.
"""
vaults = [v for v in self.live() if v != excluding and not v.no_push]
vaults = [v for v in self._live() if v != excluding and not v.no_push]
if not vaults:
return 0
with ThreadPoolExecutor(len(vaults), thread_name_prefix="vault-push") as pool:
@@ -277,9 +277,10 @@ class Vaults:
dl.log_vault_query(vault.name, "add_key", kid=str(kid), success=False, error=e)
return 0
def add_keys(self, kid_keys: dict[UUID | str, str]) -> int:
def add_keys(self, kid_keys: dict[UUID | str, str], local: bool | None = None) -> int:
"""
Add multiple KID:KEYs to all Vaults. The Vaults skip duplicate Content Keys.
Add multiple KID:KEYs to all Vaults, or with ``local`` only to the local or only to the remote ones.
The Vaults skip duplicate Content Keys.
This method absorbs and ignores the PermissionError a Vault raises when it cannot make Tables.
This method also skips Vaults with no_push=True.
@@ -288,13 +289,13 @@ class Vaults:
rejects the whole batch when it contains one.
"""
kid_keys = {kid: key for kid, key in kid_keys.items() if not is_null_key(key)}
vaults = [vault for vault in self.live() if not vault.no_push]
vaults = [vault for vault in self._live() if not vault.no_push and local in (None, vault.local)]
if not vaults or not kid_keys:
return 0
with ThreadPoolExecutor(len(vaults), thread_name_prefix="vault-push") as pool:
return sum(pool.map(lambda vault: self.push_keys(vault, kid_keys), vaults))
return sum(pool.map(lambda vault: self._push_keys(vault, kid_keys), vaults))
def push_keys(self, vault: Vault, kid_keys: dict[UUID | str, str]) -> int:
def _push_keys(self, vault: Vault, kid_keys: dict[UUID | str, str]) -> int:
"""Push Content Keys to one Vault. Returns 1 if the Vault accepted them, 0 on any failure."""
try:
vault.add_keys(self.service, kid_keys)
@@ -306,13 +307,47 @@ class Vaults:
self.mark_unreachable(vault, e)
return 0
def live(self) -> list[Vault]:
def _live(self) -> list[Vault]:
"""The vaults this run still uses."""
return [vault for vault in self.vaults if vault not in self.unreachable]
def held_locally(self, kid: UUID | str, key: str) -> bool:
"""True when a local vault already holds this KID:KEY."""
return any(self.query_vault(vault, kid) == key for vault in self.vaults if vault.local)
return any(self._query_vault(vault, kid) == key for vault in self.vaults if vault.local)
def holds(self, kid: UUID | str) -> bool:
"""True when a local vault holds a content key for ``kid`` or cannot answer; a vault with no read access holds none.
A client may add a missing content key but never replace one, so a vault that cannot answer is not taken as empty.
"""
for vault in (v for v in self.vaults if v.local):
try:
if vault.get_key(kid, self.service):
return True
except (PermissionError, NotImplementedError):
continue
except Exception:
return True
return False
def stored_everywhere(self, stored: int) -> bool:
"""True when ``stored``, a count from ``add_keys``, is every vault that takes a push, unreachable ones included."""
return stored == sum(not vault.no_push for vault in self.vaults)
def flag_served(self, kid: UUID | str, key: str, source: str) -> None:
"""Flag a served KID:KEY a client proved wrong in every local vault and in ``source``, the vault that served it."""
for vault in self._live():
if vault.local or vault.name == source:
self._tell(vault, kid, key, source)
def probe(self, kid: UUID | str) -> str:
"""Ask each vault for ``kid`` and raise its failure; a vault that refuses the query answered, so it passes."""
for vault in self.vaults:
try:
vault.get_key(kid, self.service)
except Refused:
pass
return ", ".join(map(str, self.vaults))
def warn_failure(self, vault: Vault, action: str, error: Exception) -> None:
"""Warn once per vault for each distinct failure; a repeat goes to the debug log."""
@@ -338,7 +373,16 @@ class Vaults:
return True
__all__ = ("KeySource", "Vaults", "load_config_vaults")
__all__ = ("KeySource", "Vaults", "flag_stores", "load_config_vaults")
def flag_stores(configs: Iterable[dict[str, Any]]) -> list[str]:
"""The names of the vault configs whose vault type stores bad-key flags, read from the class without a load."""
return [
str(cfg.get("name") or cfg.get("type"))
for cfg in configs
if getattr(MODULES.get(str(cfg.get("type"))), "stores_flags", False)
]
def load_config_vaults(
+3 -3
View File
@@ -3,7 +3,7 @@ from uuid import UUID
from requests import HTTPError, Response
from unshackle.core.vault import RateLimited, Vault, json_body, vault_session
from unshackle.core.vault import RateLimited, Refused, Vault, json_body, vault_session
class API(Vault):
@@ -283,10 +283,10 @@ class Exceptions:
class PageInvalid(Exception):
"""Requested page does not exist."""
class ServiceTagInvalid(Exception):
class ServiceTagInvalid(Refused):
"""The Service Tag is invalid."""
class KeyIdInvalid(Exception):
class KeyIdInvalid(Refused):
"""The Key ID is invalid."""
class ContentKeyInvalid(Exception):
+1
View File
@@ -12,6 +12,7 @@ class SQLite(Vault):
"""Key Vault using a locally-accessed sqlite DB file."""
local = True
stores_flags = True
def __init__(self, name: str, path: str | Path, no_push: bool = False) -> None:
super().__init__(name, no_push)