refactor(vaults): pick kv vault behaviour from class flags and keep the api batch size

This commit is contained in:
imSp4rky
2026-11-27 12:10:07 -07:00
parent 84751b1f9e
commit cfe6685dfc
14 changed files with 212 additions and 26 deletions
+13
View File
@@ -7,6 +7,7 @@ from types import SimpleNamespace
from typing import Any
from uuid import UUID
import requests
from rich.table import Table
from unshackle.core.cdm.detect import cdm_type_stub
@@ -14,6 +15,18 @@ from unshackle.core.drm.key_resolution import ContentKeyResolver
from unshackle.core.vault import Vault
from unshackle.core.vaults import Vaults
PARKED_PAGE = b"<!DOCTYPE html><html><body>This domain may be for sale.</body></html>"
def fake_response(
status: int = 200, body: bytes = PARKED_PAGE, content_type: str = "text/html; charset=utf-8"
) -> requests.Response:
r = requests.Response()
r.status_code = status
r.headers["Content-Type"] = content_type
r._content = body
return r
class MemoryVault(Vault):
"""A key vault in memory that records each lookup in ``asked``, each push in ``pushes`` and ``added``, and each flag in ``told``."""
+42
View File
@@ -2,18 +2,23 @@
from __future__ import annotations
import contextlib
import logging
from collections.abc import Iterator
from pathlib import Path
from uuid import UUID
import pytest
import requests
from tests.core.key_resolver import fake_response
from unshackle.commands.kv import add_keys_with_progress
from unshackle.core.vault import Vault
from unshackle.vaults.API import API
from unshackle.vaults.SQLite import SQLite
LOG = logging.getLogger("kv-test")
JSON = "application/json"
def make_keys(n: int) -> dict[str, str]:
@@ -64,3 +69,40 @@ def test_network_vault_probes_then_batches() -> None:
vault = RecordingVault()
assert add_keys_with_progress(vault, "SVC", make_keys(1201), LOG) == 1201
assert vault.batches == [1, 500, 500, 200]
def test_a_vault_that_refuses_batches_gets_one_key_per_call() -> None:
vault = RecordingVault()
vault.batch_insert = False
assert add_keys_with_progress(vault, "SVC", make_keys(3), LOG) == 3
assert vault.batches == [1, 1, 1]
def test_an_api_vault_keeps_the_batch_size_its_server_accepted(monkeypatch: pytest.MonkeyPatch) -> None:
vault = API("api", "https://api.example/", "tok")
posts: list[int] = []
def capped(*args: object, json: dict, **kw: object) -> requests.Response:
size = len(json["content_keys"])
posts.append(size)
return fake_response(413 if size > 300 else 200, f'{{"code": 0, "added": {size}}}'.encode(), JSON)
monkeypatch.setattr(vault.session, "post", capped)
assert add_keys_with_progress(vault, "SVC", make_keys(1001), LOG) == 1001
assert posts == [1, 500, 400, 300, 200, 300, 200]
@pytest.mark.parametrize("statuses", [[400] * 5 + [200, 400], [503, 200]], ids=["call-fails", "server-error"])
def test_an_api_vault_keeps_its_batch_size_when_size_was_not_the_cause(
statuses: list[int], monkeypatch: pytest.MonkeyPatch
) -> None:
vault = API("api", "https://api.example/", "tok")
replies = iter(statuses)
def answer(*args: object, json: dict, **kw: object) -> requests.Response:
return fake_response(next(replies), f'{{"code": 0, "added": {len(json["content_keys"])}}}'.encode(), JSON)
monkeypatch.setattr(vault.session, "post", answer)
with contextlib.suppress(requests.HTTPError):
vault.add_keys("SVC", make_keys(3))
assert vault.batch_size == 500
+16
View File
@@ -6,6 +6,7 @@ import click
import pytest
import requests
from tests.core.key_resolver import fake_response
from unshackle.commands.kv import copy_service_data
from unshackle.core.utilities import close_debug_logger, init_debug_logger
from unshackle.core.vault import brief
@@ -178,6 +179,21 @@ def test_a_broken_sqlite_file_warns_once_and_is_still_used(
assert queried == [KID, SIBLING]
def test_kv_copy_skips_a_service_whose_content_key_an_api_vault_refuses(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
source = SQLite("source", tmp_path / "source.db")
source.add_key("EXAMPLE", KID, "bb" * 16)
vault = API("api", "https://api.example/", "tok")
reply = fake_response(200, b'{"code": 5, "message": "bad content key"}', "application/json")
monkeypatch.setattr(vault.session, "post", lambda *a, **kw: reply)
with caplog.at_level(logging.WARNING, logger="kv"):
assert copy_service_data(vault, source, "EXAMPLE", logging.getLogger("kv")) == 0
assert [r.getMessage() for r in caplog.records] == [
"EXAMPLE: Could not write to api API (bad content key (5)), skipped"
]
def test_kv_copy_names_the_vault_it_cannot_write_to_without_its_password(tmp_path: Path) -> None:
class Down(SQLite):
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
+13 -14
View File
@@ -9,7 +9,7 @@ from uuid import UUID
import pytest
import requests
from tests.core.key_resolver import BrokenVault, MemoryVault, vaults_of
from tests.core.key_resolver import PARKED_PAGE, BrokenVault, MemoryVault, fake_response, vaults_of
from unshackle.commands.kv import copy_service_data
from unshackle.core.api import handlers
from unshackle.core.vault import RateLimited, json_body
@@ -23,19 +23,6 @@ KID2 = UUID("66666666-7777-8888-9999-000000000000")
KEY = "a" * 32
PARKED_PAGE = b"<!DOCTYPE html><html><body>This domain may be for sale.</body></html>"
def fake_response(
status: int = 200, body: bytes = PARKED_PAGE, content_type: str = "text/html; charset=utf-8"
) -> requests.Response:
r = requests.Response()
r.status_code = status
r.headers["Content-Type"] = content_type
r._content = body
return r
def parked_host(calls: list, status: int = 200, body: bytes = PARKED_PAGE) -> Callable[..., requests.Response]:
def parked(*args: object, **kw: object) -> requests.Response:
calls.append(1)
@@ -183,6 +170,17 @@ def query_vault() -> HTTP:
id="decrypt_labs-get_key",
),
pytest.param(API("api", "https://api.example/", "tok"), lambda v: v.add_key("SVC", KID, KEY), id="api-add_key"),
pytest.param(
API("api", "https://api.example/", "tok"), lambda v: list(v.get_services()), id="api-get_services"
),
pytest.param(
API("api", "https://api.example/", "tok"),
lambda v: v.flag_bad_key("SVC", KID, KEY, "api"),
id="api-flag_bad_key",
),
pytest.param(
API("api", "https://api.example/", "tok"), lambda v: v.unflag_bad_key(KID, KEY), id="api-unflag_bad_key"
),
],
)
def test_a_vault_still_rate_limited_after_the_retries_raises(
@@ -190,6 +188,7 @@ def test_a_vault_still_rate_limited_after_the_retries_raises(
) -> None:
monkeypatch.setattr(vault.session, "get", rate_limited)
monkeypatch.setattr(vault.session, "post", rate_limited)
monkeypatch.setattr(vault.session, "delete", rate_limited)
with pytest.raises(RateLimited):
call(vault)
+5
View File
@@ -66,6 +66,11 @@ def test_a_vault_type_stores_flags_only_when_it_reads_them_back() -> None:
assert module.stores_flags == (module.is_bad_key is not Vault.is_bad_key), module
def test_a_vault_type_has_tables_only_when_it_can_make_them() -> None:
for module in MODULES.values():
assert module.has_tables == (module.create_table is not Vault.create_table), module
def test_flag_stores_names_the_configs_whose_vault_type_keeps_flags() -> None:
configs = [
{"type": "SQLite", "name": "local"},