mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 19:35:06 +00:00
refactor(vaults): give the server handlers vault operations
This commit is contained in:
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"]
|
||||
@@ -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."""
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in New Issue
Block a user