mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-05 07:25:08 +00:00
refactor(vaults): move the settle rules, vault writer, stored tally and server-vault push into the key ledger
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from uuid import UUID
|
||||
@@ -9,7 +10,7 @@ from uuid import UUID
|
||||
import click
|
||||
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 unshackle.core.drm import key_resolution
|
||||
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 path.read_bytes() == b"plain:" + GOOD.encode()
|
||||
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"]
|
||||
|
||||
@@ -19,6 +19,7 @@ from unshackle.core.download_archive import DownloadArchive
|
||||
from unshackle.core.title_source import TitleSource
|
||||
from unshackle.core.titles import Episode, Series
|
||||
from unshackle.core.tracks import Audio, Tracks, Video
|
||||
from unshackle.core.vaults import Vaults
|
||||
|
||||
|
||||
class EXAMPLE(TitleSource):
|
||||
@@ -75,6 +76,8 @@ class EXAMPLE(TitleSource):
|
||||
|
||||
|
||||
class Harness(dl):
|
||||
vaults = Vaults()
|
||||
|
||||
def __getattr__(self, name):
|
||||
return None
|
||||
|
||||
|
||||
@@ -416,26 +416,6 @@ def test_a_cdm_that_confirms_a_key_flagged_on_entry_clears_the_flag(
|
||||
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:
|
||||
poisoned = Remote("poisoned", tmp_path / "poisoned.db")
|
||||
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)
|
||||
assert not calls
|
||||
vaults.proven({KID: GOOD}, {})
|
||||
vaults.wait_writes()
|
||||
vaults.unflag_bad_key(KID, BAD)
|
||||
|
||||
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.flag_bad_key(KID, BAD)
|
||||
vaults.proven({KID: GOOD}, {})
|
||||
vaults.wait_writes()
|
||||
|
||||
calls.clear()
|
||||
flag_and_replace(SimpleNamespace(name="other", local=False, report_now=False))
|
||||
|
||||
@@ -9,10 +9,14 @@ import pytest
|
||||
import requests
|
||||
|
||||
from tests.core.key_resolver import MemoryVault, vaults_of
|
||||
from unshackle.vaults.SQLite import SQLite
|
||||
|
||||
KID = UUID(int=1)
|
||||
SIBLING = UUID(int=2)
|
||||
NULL = UUID(int=3)
|
||||
BAD = "aa" * 16
|
||||
GOOD = "bb" * 16
|
||||
CONFIRMED = f"Licence returned the same content key for KID {KID.hex}, keeping it"
|
||||
|
||||
|
||||
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)
|
||||
|
||||
vaults.proven({KID: GOOD}, {KID: remote})
|
||||
vaults.wait_writes()
|
||||
|
||||
assert local.added == {KID: GOOD}
|
||||
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.proven({KID: GOOD}, {KID: remote})
|
||||
vaults.wait_writes()
|
||||
|
||||
assert local.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.proven({KID: BAD}, {})
|
||||
vaults.wait_writes()
|
||||
assert remote.told == []
|
||||
assert vaults.proved_wrong(KID, BAD)
|
||||
|
||||
vaults.proven({KID: GOOD}, {})
|
||||
vaults.proven({KID: GOOD}, {})
|
||||
vaults.wait_writes()
|
||||
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)
|
||||
vaults = vaults_of(remote)
|
||||
vaults.get_key(KID)
|
||||
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 remote.added == {KID: BAD}
|
||||
vaults.proven({KID: GOOD}, {})
|
||||
vaults.wait_writes()
|
||||
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",
|
||||
"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))
|
||||
|
||||
Reference in New Issue
Block a user