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
+18
View File
@@ -52,6 +52,24 @@ class MemoryVault(Vault):
self.told.append((kid, key))
class BrokenVault(MemoryVault):
"""A memory vault whose every lookup and flag raises ``error``, and whose every push is recorded and then raises it."""
def __init__(self, error: Exception, **kwargs: Any) -> None:
super().__init__(**kwargs)
self.error = error
def get_key(self, kid: UUID | str, service: str) -> str | None:
raise self.error
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
self.pushes.append(dict(kid_keys))
raise self.error
def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None:
raise self.error
def vaults_of(*loaded: Vault, service: str = "TEST") -> Vaults:
"""A Vaults over ``loaded``, with no config."""
vaults = Vaults(service)
+1 -1
View File
@@ -173,7 +173,7 @@ def test_a_server_that_goes_down_is_skipped_for_the_rest_of_the_run(
monkeypatch.setattr(mysql_module.ConnectionFactory, "PING_AFTER", -1.0)
server.down = True
assert vaults.get_key(KID) == (None, None)
assert vaults.live() == []
assert vaults.unreachable == set(vaults.vaults)
server.down = False
assert vaults.vaults[0].get_key(KID, "EXAMPLE") == KEY
+1 -1
View File
@@ -796,7 +796,7 @@ def test_flagged_pair_warns_once_per_vault(tmp_path: Path, caplog: pytest.LogCap
vaults.vaults = [local, poisoned]
with caplog.at_level(logging.WARNING, logger="unshackle.core.vaults"):
for _ in range(3):
assert vaults.query_vault(poisoned, KID) is None
assert vaults.get_key(KID) == (None, None)
assert sum("flagged bad, skipping" in r.getMessage() for r in caplog.records) == 1
+14 -34
View File
@@ -9,6 +9,7 @@ from uuid import UUID
import pytest
import requests
from tests.core.key_resolver import BrokenVault, MemoryVault, vaults_of
from unshackle.commands.kv import copy_service_data
from unshackle.core.api import handlers
from unshackle.core.vault import RateLimited, json_body
@@ -160,56 +161,35 @@ def test_an_api_vault_still_rate_limited_fails_the_key_list_and_kv_copy_skips_it
]
class FakeVault:
no_push = False
def __init__(self, ok: bool) -> None:
self.ok = ok
def fake_server_vaults(pushes: list, vault_list: list[FakeVault]) -> Any:
class FakeVaults:
vaults = vault_list
def __len__(self) -> int:
return len(vault_list)
def clear_licensed_flags(self, content_keys: dict) -> list:
return []
def add_keys(self, key_map: dict) -> int:
pushes.append(key_map)
return sum(vault.ok for vault in vault_list)
return FakeVaults()
def test_server_does_not_push_a_pair_it_already_stored(monkeypatch: pytest.MonkeyPatch) -> None:
pushes: list = []
monkeypatch.setattr(handlers, "load_server_vaults", lambda name: fake_server_vaults(pushes, [FakeVault(True)]))
vault = MemoryVault()
monkeypatch.setattr(handlers, "load_server_vaults", lambda name: vaults_of(vault, service="SVC"))
monkeypatch.setattr(handlers, "CACHED_PAIRS", set())
handlers.cache_to_vaults({KID.hex: KEY}, "SVC")
handlers.cache_to_vaults({KID.hex: KEY}, "SVC")
assert pushes == [{KID: KEY}]
assert vault.pushes == [{KID: KEY}]
def test_server_pushes_again_after_one_vault_failed(monkeypatch: pytest.MonkeyPatch) -> None:
pushes: list = []
vault_list = [FakeVault(True), FakeVault(False)]
monkeypatch.setattr(handlers, "load_server_vaults", lambda name: fake_server_vaults(pushes, vault_list))
vault = MemoryVault()
monkeypatch.setattr(
handlers,
"load_server_vaults",
lambda name: vaults_of(vault, BrokenVault(OSError("EXAMPLE vault down")), service="SVC"),
)
monkeypatch.setattr(handlers, "CACHED_PAIRS", set())
handlers.cache_to_vaults({KID.hex: KEY}, "SVC")
handlers.cache_to_vaults({KID.hex: KEY}, "SVC")
assert len(pushes) == 2
assert len(vault.pushes) == 2
def test_one_licence_request_builds_the_server_vaults_once(monkeypatch: pytest.MonkeyPatch) -> None:
builds: list = []
pushes: list = []
down = BrokenVault(OSError("EXAMPLE vault down"))
def build(name: str) -> Any:
builds.append(name)
return fake_server_vaults(pushes, [FakeVault(False)])
return vaults_of(down, service="SVC")
monkeypatch.setattr(handlers, "load_server_vaults", build)
monkeypatch.setattr(handlers, "CACHED_PAIRS", set())
@@ -217,4 +197,4 @@ def test_one_licence_request_builds_the_server_vaults_once(monkeypatch: pytest.M
handlers.cache_to_vaults({KID.hex: KEY}, "SVC", shared=shared)
handlers.cache_to_vaults({KID.hex: KEY}, "SVC", shared=shared)
assert len(builds) == 1
assert len(pushes) == 2
assert len(down.pushes) == 2
+76
View File
@@ -0,0 +1,76 @@
"""The vault operations the server asks of Vaults: hold, store local first, flag a served pair, probe."""
from uuid import UUID
import pytest
from tests.core.key_resolver import BrokenVault, MemoryVault, vaults_of
from unshackle.core.vault import Refused, Vault
from unshackle.core.vaults import MODULES, flag_stores
KID = UUID("11111111-2222-3333-4444-555555555555")
KEY = "ab" * 16
def test_a_local_vault_with_the_kid_holds_it_and_a_remote_one_does_not_count() -> None:
assert vaults_of(MemoryVault({KID: KEY})).holds(KID)
assert not vaults_of(MemoryVault(), MemoryVault({KID: KEY}, local=False)).holds(KID)
def test_a_local_vault_that_cannot_answer_holds_the_kid_and_one_without_read_access_does_not() -> None:
assert vaults_of(BrokenVault(OSError("EXAMPLE vault file locked"))).holds(KID)
assert not vaults_of(BrokenVault(PermissionError("no read access"))).holds(KID)
def test_add_keys_stores_only_in_the_local_or_only_in_the_remote_vaults() -> None:
local, remote = MemoryVault(), MemoryVault(local=False)
vaults = vaults_of(local, remote)
assert vaults.add_keys({KID: KEY}, local=True) == 1
assert (local.added, remote.added) == ({KID: KEY}, {})
assert vaults.add_keys({KID: KEY}, local=False) == 1
assert remote.added == {KID: KEY}
def test_stored_everywhere_counts_an_unreachable_vault_and_skips_a_no_push_one() -> None:
down = MemoryVault(local=False)
vaults = vaults_of(MemoryVault(), down, MemoryVault(no_push=True))
vaults.unreachable.add(down)
stored = vaults.add_keys({KID: KEY})
assert stored == 1
assert not vaults.stored_everywhere(stored)
assert vaults.stored_everywhere(2)
def test_a_served_pair_is_flagged_in_the_local_vaults_and_its_source_only() -> None:
local = MemoryVault()
source = MemoryVault(local=False, name="source")
bystander = MemoryVault(local=False, name="other")
broken = BrokenVault(OSError("EXAMPLE vault down"))
vaults_of(broken, local, bystander, source).flag_served(KID, KEY, "source")
assert local.told == source.told == [(KID, KEY)]
assert bystander.told == []
def test_probe_passes_a_vault_that_refuses_the_query_and_raises_any_other_failure() -> None:
assert vaults_of(BrokenVault(Refused("bad kid"), name="api")).probe(KID) == "api BrokenVault"
with pytest.raises(OSError):
vaults_of(BrokenVault(OSError("EXAMPLE vault down"))).probe(KID)
def test_a_vault_type_stores_flags_only_when_it_reads_them_back() -> None:
for module in MODULES.values():
assert module.stores_flags == (module.is_bad_key is not Vault.is_bad_key), module
def test_flag_stores_names_the_configs_whose_vault_type_keeps_flags() -> None:
configs = [
{"type": "SQLite", "name": "local"},
{"type": "SQLite"},
{"type": "API", "name": "shared"},
{"type": "Unknown", "name": "x"},
]
assert flag_stores(configs) == ["local", "SQLite"]
+8 -2
View File
@@ -472,14 +472,20 @@ async def test_health_vault_probe_tolerates_api_vault_rejecting_the_probe(aiohtt
assert checks["vault:t"]["status"] == "ok", checks["vault:t"]
def test_health_warns_without_a_sqlite_vault_to_store_flags(monkeypatch) -> None:
def test_health_warns_without_a_sqlite_vault_to_store_flags(monkeypatch, tmp_path) -> None:
from unshackle.core.api.handlers import run_health_checks
monkeypatch.setattr(config, "proxy_providers", {})
monkeypatch.setattr(
config, "key_vaults", [{"type": "API", "name": "shared", "uri": "http://127.0.0.1:9", "token": "t"}]
)
assert {c["id"]: c for c in run_health_checks()}["bad_keys"]["status"] == "warn"
checks = {c["id"]: c for c in run_health_checks()}
assert (checks["bad_keys"]["status"], checks["vault:shared"]["status"]) == ("warn", "fail")
monkeypatch.setattr(config, "key_vaults", [{"type": "SQLite", "name": "local", "path": str(tmp_path / "k.db")}])
checks = {c["id"]: c for c in run_health_checks()}
assert checks["bad_keys"]["status"] == "ok" and "local" in checks["bad_keys"]["detail"]
assert checks["vault:local"]["status"] == "ok"
monkeypatch.setattr(config, "key_vaults", [])
assert {c["id"]: c for c in run_health_checks()}["bad_keys"]["status"] == "ok"
@@ -13,6 +13,7 @@ from uuid import UUID
import click
import pytest
from tests.core.key_resolver import vaults_of
from tests.remote.key_source import one_title, remote_keys
from tests.remote.sessions import session_entry
from unshackle.core.api import handlers
@@ -58,6 +59,7 @@ def test_server_vault_flag_posts_only_the_pair():
class _Vault:
local = True
name = "local"
def __init__(self):
self.flagged: list = []
@@ -78,7 +80,7 @@ def session(monkeypatch):
monkeypatch.setattr(handlers, "get_validated_session", validated)
monkeypatch.setattr(handlers, "require_authenticated", lambda s: None)
vault = _Vault()
monkeypatch.setattr(handlers, "load_server_vaults", lambda name: SimpleNamespace(vaults=[vault], service="SVC"))
monkeypatch.setattr(handlers, "load_server_vaults", lambda name: vaults_of(vault, service="SVC"))
return entry, vault
@@ -229,20 +231,6 @@ def test_the_server_reads_the_head_of_a_one_file_track_with_drm(drm, head):
)
async def test_server_tells_a_remote_vault_only_when_it_served_the_pair(monkeypatch, session):
entry, local = session
bystander, source = _Vault(), _Vault()
bystander.local = source.local = False
bystander.name, source.name = "other", "sqlite"
monkeypatch.setattr(
handlers, "load_server_vaults", lambda name: SimpleNamespace(vaults=[local, bystander, source], service="SVC")
)
await handlers.session_bad_key_handler({"kid": KID.hex, "key": "v"}, "sess")
assert local.flagged == [("SVC", KID, "v", "sqlite")]
assert source.flagged == [("SVC", KID, "v", "sqlite")]
assert bystander.flagged == []
def test_resolve_server_keys_does_not_warn_for_clear_tracks(monkeypatch):
"""A requested track the server lists in clear_tracks carries no DRM, so its
missing keys are expected and draw no warning."""
+4 -11
View File
@@ -255,19 +255,12 @@ async def test_the_server_answers_before_the_remote_vaults_take_the_keys(server,
assert server.remote.get_key(LICENSED, "EXAMPLE") == KEY
async def test_a_local_vault_that_cannot_answer_counts_as_holding_the_kid(server, monkeypatch) -> None:
real = server.local.get_key
def down(kid: Any, service: str) -> Any:
if kid == LICENSED:
raise OSError("EXAMPLE vault file locked")
return real(kid, service)
monkeypatch.setattr(server.local, "get_key", down)
await handlers.session_keys_handler({"track_id": "v2", "keys": {LICENSED.hex: KEY, LATE.hex: KEY}}, "sess")
async def test_a_client_cannot_replace_a_content_key_a_local_vault_holds(server) -> None:
server.local.add_key("EXAMPLE", LICENSED, OTHER_KEY)
await handlers.session_keys_handler({"track_id": "v2", "keys": {LICENSED.hex: KEY}}, "sess")
await settled()
assert server.local.get_key(LICENSED, "EXAMPLE") == OTHER_KEY
assert server.remote.get_key(LICENSED, "EXAMPLE") is None
assert server.remote.get_key(LATE, "EXAMPLE") == KEY
async def test_the_server_answers_empty_when_it_stores_nothing(server, caplog) -> None:
+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)