"""Vaults as the ledger of content keys: where each key in use came from, and who hears that it is bad.""" import logging import threading from types import SimpleNamespace from uuid import UUID 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: """A source outside the loaded vaults, as the server's vaults are over --remote.""" return SimpleNamespace(name="server_cdm", local=False, report_now=True) def test_an_offered_key_comes_after_the_local_vaults_and_is_its_sources() -> None: local, source = MemoryVault(), server() vaults = vaults_of(local) vaults.offer(KID, BAD, source) # type: ignore[arg-type] assert vaults.get_key(KID) == (BAD, source) assert local.asked == [KID] assert vaults.source_of(KID, BAD) is source assert vaults.source_of(KID, GOOD) is None def test_a_proven_vault_key_goes_to_every_other_vault() -> None: remote, local = MemoryVault({KID: GOOD}, local=False), MemoryVault(name="local") vaults = vaults_of(local, remote) assert vaults.get_key(KID) == (GOOD, remote) vaults.proven({KID: GOOD}, {KID: remote}) vaults.wait_writes() assert local.added == {KID: GOOD} assert remote.added == {} def test_a_pair_proved_wrong_before_its_proof_is_stored_goes_nowhere() -> None: remote, local = MemoryVault({KID: GOOD}, local=False), MemoryVault(name="local") vaults = vaults_of(local, remote) vaults.get_key(KID) vaults.flag_bad_key(KID, GOOD) vaults.proven({KID: GOOD}, {KID: remote}) vaults.wait_writes() assert local.added == {} assert remote.added == {} def test_a_remote_vault_hears_of_its_bad_pair_only_once_another_key_replaces_it() -> None: remote = MemoryVault({KID: BAD}, local=False) vaults = vaults_of(remote) vaults.get_key(KID) 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(caplog: pytest.LogCaptureFixture) -> None: remote = MemoryVault({KID: BAD}, local=False) vaults = vaults_of(remote) vaults.get_key(KID) vaults.flag_bad_key(KID, BAD) 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 == [] def test_one_source_offered_twice_at_once_is_held_once() -> None: """Thread A has checked an offer and not yet stored it when thread B offers the same pair.""" a_storing, b_moved, release = threading.Event(), threading.Event(), threading.Event() vaults = vaults_of() source = server() class HeldList(list): def append(self, item: object) -> None: if threading.current_thread().name == "a": a_storing.set() release.wait(10) else: b_moved.set() super().append(item) class Lock: """The ledger lock, which tells the test when thread B waits for it.""" def __init__(self) -> None: self.lock = threading.Lock() def __enter__(self) -> None: if threading.current_thread().name == "b": b_moved.set() self.lock.acquire() def __exit__(self, *exc: object) -> None: self.lock.release() vaults.candidates[KID] = HeldList() vaults.lock = Lock() # type: ignore[assignment] a = threading.Thread(target=vaults.offer, args=(KID, BAD, source), name="a") b = threading.Thread(target=vaults.offer, args=(KID, BAD, source), name="b") a.start() assert a_storing.wait(10) b.start() assert b_moved.wait(10) release.set() a.join(10) b.join(10) assert vaults.candidates[KID] == [(BAD, source)] def test_two_lookups_that_fail_at_once_warn_once(caplog: pytest.LogCaptureFixture) -> None: both_asking = threading.Barrier(2, timeout=10) class Down(MemoryVault): def get_key(self, kid: UUID | str, service: str) -> str | None: both_asking.wait() raise requests.ConnectTimeout("no answer") vaults = vaults_of(Down(local=False, name="down")) with caplog.at_level(logging.WARNING, logger="unshackle.core.vaults"): threads = [threading.Thread(target=vaults.get_key, args=(KID,)) for _ in range(2)] for thread in threads: thread.start() for thread in threads: thread.join(10) messages = [record.getMessage() for record in caplog.records] assert messages == [ "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))