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
+5 -1
View File
@@ -254,7 +254,7 @@ key_vaults:
The backend talks to endpoints under `uri` (for example `GET {uri}/{service}/{kid}` to look up a single key). It interprets a numeric `code` field in each JSON response to detect errors such as an invalid token, rate limiting, or an invalid service tag. The backend talks to endpoints under `uri` (for example `GET {uri}/{service}/{kid}` to look up a single key). It interprets a numeric `code` field in each JSON response to detect errors such as an invalid token, rate limiting, or an invalid service tag.
!!! warning "This is unshackle's own protocol, not a generic vault client" !!! warning "This is unshackle's own protocol, not a generic vault client"
The `API` backend expects unshackle's specific HTTP request and response shape. An API or HTTP key-vault endpoint built for a different project or service will generally *not* be compatible. You cannot point this at an arbitrary third-party vault API and expect it to work. To bridge another service, put an adapter in front of it that speaks this format, or use the `HTTP` backend if one of its wire protocols matches. When pushing many keys at once it batches requests and automatically shrinks the batch size if the server rejects an over-large request. The `API` backend expects unshackle's specific HTTP request and response shape. An API or HTTP key-vault endpoint built for a different project or service will generally *not* be compatible. You cannot point this at an arbitrary third-party vault API and expect it to work. To bridge another service, put an adapter in front of it that speaks this format, or use the `HTTP` backend if one of its wire protocols matches. When pushing many keys at once it batches requests and automatically shrinks the batch size if the server rejects an over-large request. After a push that succeeds at a smaller size, later pushes to that vault start at that size.
!!! tip "DecryptLabs shortcut" !!! tip "DecryptLabs shortcut"
An `API` vault whose `name` contains `decrypt_labs` will have its `token` filled in automatically from a global `decrypt_labs_api_key` in your config if you leave `token` unset. This lets you keep the API key in one place. An `API` vault whose `name` contains `decrypt_labs` will have its `token` filled in automatically from a global `decrypt_labs_api_key` in your config if you leave `token` unset. This lets you keep the API key in one place.
@@ -284,6 +284,8 @@ $ unshackle kv add keys.txt EXAMPLE local shared
The service argument (`EXAMPLE` above) is normalized to its canonical tag automatically. Keys that already exist in a vault are reported as skipped. The service argument (`EXAMPLE` above) is normalized to its canonical tag automatically. Keys that already exist in a vault are reported as skipped.
If a vault answers and refuses the content keys, `kv add` shows one warning and continues with the next vault. If a vault is unreachable or still rate limited, `kv add` stops with an error.
### `kv search`: find a content key by KID ### `kv search`: find a content key by KID
Search your vaults for a KID and print any matching content key. Search your vaults for a KID and print any matching content key.
@@ -333,6 +335,8 @@ $ unshackle kv copy local ~/Downloads/key_store.db -s EXAMPLE
With `--service`, `kv copy` reads the table named by the service's vault tag and the table named by its plain tag. It writes both into the vault-tag table, which is the table a download reads. Without `--service`, each table keeps its name. With `--service`, `kv copy` reads the table named by the service's vault tag and the table named by its plain tag. It writes both into the vault-tag table, which is the table a download reads. Without `--service`, each table keeps its name.
If the destination vault answers and refuses the content keys of a service, `kv copy` shows one warning and continues with the next service. If the destination vault is unreachable or still rate limited, `kv copy` stops with an error.
A pair the destination vault has flagged in `bad_keys` is left behind, so a copy does not undo a flag. `bad_keys` is never treated as a service, so its rows are never copied into a service table. A pair the destination vault has flagged in `bad_keys` is left behind, so a copy does not undo a flag. `bad_keys` is never treated as a service, so its rows are never copied into a service table.
### `kv sync`: mirror vaults both ways ### `kv sync`: mirror vaults both ways
+58
View File
@@ -1,15 +1,32 @@
from __future__ import annotations from __future__ import annotations
import logging
from pathlib import Path from pathlib import Path
import pytest import pytest
from click.testing import CliRunner from click.testing import CliRunner
from unshackle.commands import kv as kv_module from unshackle.commands import kv as kv_module
from unshackle.core.vaults import MODULES
from unshackle.vaults.SQLite import SQLite from unshackle.vaults.SQLite import SQLite
KID = "0" * 31 + "1" KID = "0" * 31 + "1"
KEY = "a" * 32 KEY = "a" * 32
QUERY_VAULT = {"type": "HTTP", "name": "shared", "host": "https://vault.example/", "password": "tok", "username": "u"}
def refuse_example(monkeypatch: pytest.MonkeyPatch) -> list[dict]:
"""Make a query-mode HTTP vault refuse every push for the EXAMPLE service and accept the rest."""
pushed: list[dict] = []
def answer(self: object, params: dict) -> dict:
if params["service"] == "example":
return {"status_code": 403, "message": "service not allowed"}
pushed.append(params)
return {"status_code": 200, "inserted": True}
monkeypatch.setattr(MODULES["HTTP"], "_query", answer)
return pushed
def test_kv_copy_moves_a_plain_tag_table_from_a_file_into_the_vault_tag_table( def test_kv_copy_moves_a_plain_tag_table_from_a_file_into_the_vault_tag_table(
@@ -38,6 +55,47 @@ def test_kv_copy_rejects_a_name_that_is_neither_configured_nor_a_file(monkeypatc
assert "not defined in the config" in result.output assert "not defined in the config" in result.output
def test_kv_copy_warns_and_skips_a_service_the_vault_refuses_and_copies_the_next(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
source = tmp_path / "key_store.db"
for service in ("EXAMPLE", "OTHER"):
SQLite("seed", source).add_key(service, KID, KEY)
monkeypatch.setattr(kv_module.config, "key_vaults", [QUERY_VAULT])
pushed = refuse_example(monkeypatch)
with caplog.at_level(logging.WARNING, logger="kv"):
result = CliRunner().invoke(kv_module.kv, ["copy", "shared", str(source)])
assert result.exit_code == 0, result.output
assert [p["service"] for p in pushed] == ["other"]
assert [r.getMessage() for r in caplog.records] == [
"EXAMPLE: Could not write to shared HTTP (API returned an error: 403 - service not allowed), skipped"
]
def test_kv_add_warns_and_skips_a_vault_that_refuses_and_adds_to_the_next(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
keys = tmp_path / "keys.txt"
keys.write_text(f"{KID}:{KEY}\n", encoding="utf8")
dest = tmp_path / "local.db"
monkeypatch.setattr(
kv_module.config, "key_vaults", [QUERY_VAULT, {"type": "SQLite", "name": "local", "path": str(dest)}]
)
monkeypatch.setattr(kv_module.Services, "get_vault_tag", lambda name: name)
refuse_example(monkeypatch)
with caplog.at_level(logging.WARNING, logger="kv"):
result = CliRunner().invoke(kv_module.kv, ["add", str(keys), "EXAMPLE", "shared", "local"])
assert result.exit_code == 0, result.output
assert SQLite("check", dest).get_key(KID, "EXAMPLE") == KEY
assert [r.getMessage() for r in caplog.records] == [
"Could not write to shared HTTP (API returned an error: 403 - service not allowed), skipped"
]
def test_kv_add_skips_a_null_key_line_and_adds_the_rest(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: def test_kv_add_skips_a_null_key_line_and_adds_the_rest(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
keys = tmp_path / "keys.txt" keys = tmp_path / "keys.txt"
null_kid = "0" * 31 + "2" null_kid = "0" * 31 + "2"
+13
View File
@@ -7,6 +7,7 @@ from types import SimpleNamespace
from typing import Any from typing import Any
from uuid import UUID from uuid import UUID
import requests
from rich.table import Table from rich.table import Table
from unshackle.core.cdm.detect import cdm_type_stub 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.vault import Vault
from unshackle.core.vaults import Vaults 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): 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``.""" """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 from __future__ import annotations
import contextlib
import logging import logging
from collections.abc import Iterator from collections.abc import Iterator
from pathlib import Path from pathlib import Path
from uuid import UUID from uuid import UUID
import pytest import pytest
import requests
from tests.core.key_resolver import fake_response
from unshackle.commands.kv import add_keys_with_progress from unshackle.commands.kv import add_keys_with_progress
from unshackle.core.vault import Vault from unshackle.core.vault import Vault
from unshackle.vaults.API import API
from unshackle.vaults.SQLite import SQLite from unshackle.vaults.SQLite import SQLite
LOG = logging.getLogger("kv-test") LOG = logging.getLogger("kv-test")
JSON = "application/json"
def make_keys(n: int) -> dict[str, str]: def make_keys(n: int) -> dict[str, str]:
@@ -64,3 +69,40 @@ def test_network_vault_probes_then_batches() -> None:
vault = RecordingVault() vault = RecordingVault()
assert add_keys_with_progress(vault, "SVC", make_keys(1201), LOG) == 1201 assert add_keys_with_progress(vault, "SVC", make_keys(1201), LOG) == 1201
assert vault.batches == [1, 500, 500, 200] 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 pytest
import requests import requests
from tests.core.key_resolver import fake_response
from unshackle.commands.kv import copy_service_data from unshackle.commands.kv import copy_service_data
from unshackle.core.utilities import close_debug_logger, init_debug_logger from unshackle.core.utilities import close_debug_logger, init_debug_logger
from unshackle.core.vault import brief 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] 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: def test_kv_copy_names_the_vault_it_cannot_write_to_without_its_password(tmp_path: Path) -> None:
class Down(SQLite): class Down(SQLite):
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int: 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 pytest
import requests 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.commands.kv import copy_service_data
from unshackle.core.api import handlers from unshackle.core.api import handlers
from unshackle.core.vault import RateLimited, json_body from unshackle.core.vault import RateLimited, json_body
@@ -23,19 +23,6 @@ KID2 = UUID("66666666-7777-8888-9999-000000000000")
KEY = "a" * 32 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_host(calls: list, status: int = 200, body: bytes = PARKED_PAGE) -> Callable[..., requests.Response]:
def parked(*args: object, **kw: object) -> requests.Response: def parked(*args: object, **kw: object) -> requests.Response:
calls.append(1) calls.append(1)
@@ -183,6 +170,17 @@ def query_vault() -> HTTP:
id="decrypt_labs-get_key", 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: 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( 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: ) -> None:
monkeypatch.setattr(vault.session, "get", rate_limited) monkeypatch.setattr(vault.session, "get", rate_limited)
monkeypatch.setattr(vault.session, "post", rate_limited) monkeypatch.setattr(vault.session, "post", rate_limited)
monkeypatch.setattr(vault.session, "delete", rate_limited)
with pytest.raises(RateLimited): with pytest.raises(RateLimited):
call(vault) 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 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: def test_flag_stores_names_the_configs_whose_vault_type_keeps_flags() -> None:
configs = [ configs = [
{"type": "SQLite", "name": "local"}, {"type": "SQLite", "name": "local"},
+18 -6
View File
@@ -7,6 +7,7 @@ from typing import cast
from uuid import UUID from uuid import UUID
import click import click
from requests import RequestException
from rich.console import RenderableType from rich.console import RenderableType
from rich.padding import Padding from rich.padding import Padding
from rich.progress import ( from rich.progress import (
@@ -24,7 +25,7 @@ from unshackle.core.config import config
from unshackle.core.console import GradientPulseBarColumn, console from unshackle.core.console import GradientPulseBarColumn, console
from unshackle.core.constants import context_settings from unshackle.core.constants import context_settings
from unshackle.core.services import Services from unshackle.core.services import Services
from unshackle.core.vault import Vault, brief, is_null_key from unshackle.core.vault import Refused, Vault, brief, is_null_key
from unshackle.core.vaults import Vaults, load_config_vaults from unshackle.core.vaults import Vaults, load_config_vaults
@@ -57,6 +58,11 @@ def without_null_keys(pairs: Iterable[tuple[str, str]], log: logging.Logger) ->
return kid_keys return kid_keys
def is_refusal(error: Exception) -> bool:
"""True when the vault answered and refused the write, not when it is unreachable or misconfigured."""
return isinstance(error, Refused) or (isinstance(error, ValueError) and not isinstance(error, RequestException))
def process_service_keys(from_vault: Vault, service: str, log: logging.Logger) -> dict[str, str]: def process_service_keys(from_vault: Vault, service: str, log: logging.Logger) -> dict[str, str]:
"""Get and validate keys from a vault for a specific service.""" """Get and validate keys from a vault for a specific service."""
return without_null_keys(from_vault.get_keys(service), log) return without_null_keys(from_vault.get_keys(service), log)
@@ -71,12 +77,12 @@ class _PaddedProgress(Progress):
def add_keys_with_progress(vault: Vault, service: str, kid_keys: dict[str, str], log: logging.Logger) -> int: def add_keys_with_progress(vault: Vault, service: str, kid_keys: dict[str, str], log: logging.Logger) -> int:
"""Add content keys to a vault. Network vaults write in batches behind a progress bar.""" """Add content keys to a vault. Network vaults write in batches behind a progress bar."""
if type(vault).__name__ in ("MySQL", "SQLite"): if vault.bulk_writes:
return vault.add_keys(service, cast(dict[UUID | str, str], kid_keys)) return vault.add_keys(service, cast(dict[UUID | str, str], kid_keys))
def chunk(i: int) -> int: def chunk(i: int) -> int:
# Probe with one key so a server that rejects batches costs one row, not 500. # Probe with one key so a server that rejects batches costs one row, not 500.
return 500 if i and getattr(vault, "batch_insert", True) else 1 return 500 if i and vault.batch_insert else 1
kids = list(kid_keys) kids = list(kid_keys)
added = 0 added = 0
@@ -130,7 +136,10 @@ def copy_service_data(
log.warning(f"{service}: No permission to create table in {to_vault}, skipped") log.warning(f"{service}: No permission to create table in {to_vault}, skipped")
return 0 return 0
except Exception as e: except Exception as e:
raise click.ClickException(f"Could not write to {to_vault} ({brief(e)})") from None if not is_refusal(e):
raise click.ClickException(f"Could not write to {to_vault} ({brief(e)})") from None
log.warning(f"{service}: Could not write to {to_vault} ({brief(e)}), skipped")
return 0
existed = total_count - added existed = total_count - added
@@ -318,7 +327,10 @@ def add(file: Path, service: str, vaults: list[str]) -> None:
try: try:
added_count = add_keys_with_progress(vault, service, kid_keys, log) added_count = add_keys_with_progress(vault, service, kid_keys, log)
except Exception as e: except Exception as e:
raise click.ClickException(f"Could not write to {vault} ({brief(e)})") from None if not is_refusal(e):
raise click.ClickException(f"Could not write to {vault} ({brief(e)})") from None
log.warning(f"Could not write to {vault} ({brief(e)}), skipped")
continue
existed_count = total_count - added_count existed_count = total_count - added_count
log.info(f"{vault}: {added_count} newly added, {existed_count} already existed (skipped)") log.info(f"{vault}: {added_count} newly added, {existed_count} already existed (skipped)")
@@ -430,7 +442,7 @@ def prepare(vaults: list[str]) -> None:
vaults_ = load_vaults(vaults) vaults_ = load_vaults(vaults)
for vault in vaults_: for vault in vaults_:
if hasattr(vault, "resolve_table") and hasattr(vault, "create_table"): if vault.has_tables:
for service_tag in dict.fromkeys(Services.get_vault_tag(tag) for tag in Services.get_tags()): for service_tag in dict.fromkeys(Services.get_vault_tag(tag) for tag in Services.get_tags()):
existing = vault.resolve_table(service_tag) existing = vault.resolve_table(service_tag)
if existing: if existing:
+18
View File
@@ -91,10 +91,20 @@ class Refused(Exception):
class Vault(metaclass=ABCMeta): class Vault(metaclass=ABCMeta):
"""A key vault of KID:KEY pairs.
Its class flags tell kv what it can do: bulk_writes (add_keys takes a whole service in one call),
batch_insert (add_keys takes more than one content key; HTTP clears it when the server refuses
batches) and has_tables (one table per service, with resolve_table and create_table).
"""
# a vault on this machine; Vaults.get_key tries these first, before the network ones # a vault on this machine; Vaults.get_key tries these first, before the network ones
local: bool = False local: bool = False
report_now: bool = False report_now: bool = False
stores_flags: bool = False stores_flags: bool = False
bulk_writes: bool = False
batch_insert: bool = True
has_tables: bool = False
def __init__(self, name: str, no_push: bool = False) -> None: def __init__(self, name: str, no_push: bool = False) -> None:
self.name = name self.name = name
@@ -152,5 +162,13 @@ class Vault(metaclass=ABCMeta):
def unflag_bad_key(self, kid: UUID | str, key: str) -> None: def unflag_bad_key(self, kid: UUID | str, key: str) -> None:
"""Forget a flagged KID:KEY, for example when a CDM licence confirmed it.""" """Forget a flagged KID:KEY, for example when a CDM licence confirmed it."""
def resolve_table(self, name: str) -> str | None:
"""The stored name of the table of a service, or None. Only a vault with has_tables has tables."""
return None
def create_table(self, name: str) -> None:
"""Make the table of a service. Only a vault with has_tables has tables."""
raise NotImplementedError
__all__ = ("Refused", "Vault", "brief", "json_body") __all__ = ("Refused", "Vault", "brief", "json_body")
+1 -1
View File
@@ -246,7 +246,7 @@ class Vaults:
try: try:
vault.unflag_bad_key(kid, key) vault.unflag_bad_key(kid, key)
except Exception as e: except Exception as e:
log.debug(f"Could not unflag {key} in Vault '{vault.name}': {e!r}") log.debug(f"Could not unflag {key} in Vault '{vault.name}': {brief(e)}")
def add_key(self, kid: UUID | str, key: str, excluding: KeySource | None = None) -> int: def add_key(self, kid: UUID | str, key: str, excluding: KeySource | None = None) -> int:
"""Add a KID:KEY to all Vaults, optionally with an exclusion. """Add a KID:KEY to all Vaults, optionally with an exclusion.
+18 -3
View File
@@ -21,6 +21,7 @@ class API(Vault):
super().__init__(name, no_push) super().__init__(name, no_push)
self.uri = uri.rstrip("/") self.uri = uri.rstrip("/")
self.timeout = timeout self.timeout = timeout
self.batch_size = 500
self.session = vault_session(timeout) self.session = vault_session(timeout)
self.session.headers.update({"Authorization": f"Bearer {token}"}) self.session.headers.update({"Authorization": f"Bearer {token}"})
@@ -142,14 +143,20 @@ class API(Vault):
return added or updated return added or updated
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int: def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
"""Post the keys in batches. A failed batch is sent again 100 content keys smaller, down to 1.
When a call shrank its batch because the server found it too large (400, 413, 414) and then
stored every batch, later calls start at that size, so a server with a lower cap costs its
failed posts once per vault, not once per call.
"""
normalized_keys = {str(kid).replace("-", ""): key for kid, key in kid_keys.items()} normalized_keys = {str(kid).replace("-", ""): key for kid, key in kid_keys.items()}
kid_list = list(normalized_keys.keys()) kid_list = list(normalized_keys.keys())
if not kid_list: if not kid_list:
return 0 return 0
# Try batches starting at 500, stepping down by 100 on failure, fallback to 1 batch_size = self.batch_size
batch_size = 500 too_large = False
total_added = 0 total_added = 0
i = 0 i = 0
@@ -172,6 +179,7 @@ class API(Vault):
batch_size -= 100 batch_size -= 100
else: else:
batch_size = 1 batch_size = 1
too_large = True
continue continue
if response.status_code == 429: if response.status_code == 429:
@@ -207,6 +215,9 @@ class API(Vault):
total_added += added + updated total_added += added + updated
i += batch_size i += batch_size
if too_large and batch_size > 1:
self.batch_size = batch_size
return total_added return total_added
def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None: def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None:
@@ -241,6 +252,8 @@ class API(Vault):
def _check(response: Response, ignore: frozenset[int] = frozenset()) -> None: def _check(response: Response, ignore: frozenset[int] = frozenset()) -> None:
if response.status_code in (404, 405, 501): if response.status_code in (404, 405, 501):
return return
if response.status_code == 429:
raise Exceptions.TooManyRequests()
response.raise_for_status() response.raise_for_status()
data = json_body(response) data = json_body(response)
code = int(data.get("code", 0)) code = int(data.get("code", 0))
@@ -253,6 +266,8 @@ class API(Vault):
response = self.session.post( response = self.session.post(
url=self.uri, headers={"Accept": "application/json"}, timeout=self.timeout, allow_redirects=False url=self.uri, headers={"Accept": "application/json"}, timeout=self.timeout, allow_redirects=False
) )
if response.status_code == 429:
raise Exceptions.TooManyRequests()
response.raise_for_status() response.raise_for_status()
data = json_body(response) data = json_body(response)
@@ -291,5 +306,5 @@ class Exceptions:
class KeyIdInvalid(Refused): class KeyIdInvalid(Refused):
"""The Key ID is invalid.""" """The Key ID is invalid."""
class ContentKeyInvalid(Exception): class ContentKeyInvalid(Refused):
"""The Content Key is invalid.""" """The Content Key is invalid."""
-1
View File
@@ -54,7 +54,6 @@ class HTTP(Vault):
self.username = username self.username = username
self.api_mode = api_mode.lower() self.api_mode = api_mode.lower()
self.batch_insert = True
self.current_title: str | None = None self.current_title: str | None = None
self.session = vault_session(timeout) self.session = vault_session(timeout)
self.api_session_id = None self.api_session_id = None
+3
View File
@@ -17,6 +17,9 @@ from unshackle.core.vault import Vault, is_null_key
class MySQL(Vault): class MySQL(Vault):
"""Key Vault using a remotely-accessed mysql database connection.""" """Key Vault using a remotely-accessed mysql database connection."""
bulk_writes = True
has_tables = True
def __init__( def __init__(
self, name: str, host: str, database: str, username: str, no_push: bool = False, **kwargs: Any self, name: str, host: str, database: str, username: str, no_push: bool = False, **kwargs: Any
) -> None: ) -> None:
+2
View File
@@ -13,6 +13,8 @@ class SQLite(Vault):
local = True local = True
stores_flags = True stores_flags = True
bulk_writes = True
has_tables = True
def __init__(self, name: str, path: str | Path, no_push: bool = False) -> None: def __init__(self, name: str, path: str | Path, no_push: bool = False) -> None:
super().__init__(name, no_push) super().__init__(name, no_push)