from __future__ import annotations import logging from pathlib import Path import click import pytest from click.testing import CliRunner from unshackle.commands import kv as kv_module from unshackle.core.vaults import MODULES from unshackle.vaults.SQLite import SQLite KID = "0" * 31 + "1" KEY = "a" * 32 DECRYPT_LABS_VAULT = { "type": "HTTP", "name": "labs", "host": "https://vault.example/", "api_key": "tok", "api_mode": "decrypt_labs", } 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( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: source = tmp_path / "key_store.db" SQLite("seed", source).add_key("TESTSVC", KID, KEY) dest = tmp_path / "local.db" monkeypatch.setattr(kv_module.config, "key_vaults", [{"type": "SQLite", "name": "local", "path": str(dest)}]) monkeypatch.setattr(kv_module.Services, "get_vault_tag", lambda name: "Shared" if name == "TESTSVC" else name) result = CliRunner().invoke(kv_module.kv, ["copy", "local", str(source), "-s", "TESTSVC"]) assert result.exit_code == 0, result.output check = SQLite("check", dest) assert check.get_key(KID, "Shared") == KEY assert check.get_key(KID, "TESTSVC") is None def test_kv_copy_rejects_a_name_that_is_neither_configured_nor_a_file(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(kv_module.config, "key_vaults", []) result = CliRunner().invoke(kv_module.kv, ["copy", "local", "nowhere.db"]) assert result.exit_code != 0 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), "-s", "EXAMPLE", "-v", "shared", "-v", "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: keys = tmp_path / "keys.txt" null_kid = "0" * 31 + "2" keys.write_text(f"{KID}:{KEY}\n{null_kid}:{'0' * 32}\n", encoding="utf8") dest = tmp_path / "local.db" local_vaults(monkeypatch, dest) result = CliRunner().invoke(kv_module.kv, ["add", str(keys), "-s", "TESTSVC", "-v", "local"]) assert result.exit_code == 0, result.output check = SQLite("check", dest) assert check.get_key(KID, "TESTSVC") == KEY assert check.get_key(null_kid, "TESTSVC") is None def local_vaults(monkeypatch: pytest.MonkeyPatch, *paths: Path, no_push: Path | None = None) -> None: """Configure one SQLite vault per path, plus a no_push one when given, and leave service tags as given.""" vaults = [{"type": "SQLite", "name": p.stem, "path": str(p)} for p in paths] if no_push: vaults.append({"type": "SQLite", "name": no_push.stem, "path": str(no_push), "no_push": True}) monkeypatch.setattr(kv_module.config, "key_vaults", vaults) monkeypatch.setattr(kv_module.Services, "get_vault_tag", lambda name: name) def test_kv_add_without_vault_writes_every_configured_vault_even_where_one_already_holds_the_pair( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: first, second, read_only = tmp_path / "local.db", tmp_path / "remote.db", tmp_path / "read_only.db" SQLite("seed", first).add_key("EXAMPLE", KID, KEY) SQLite("seed", read_only).add_key("OTHER", KID, KEY) local_vaults(monkeypatch, first, second, no_push=read_only) monkeypatch.setattr(kv_module.config, "key_vaults", [*kv_module.config.key_vaults, DECRYPT_LABS_VAULT]) with caplog.at_level(logging.INFO, logger="kv"): result = CliRunner().invoke(kv_module.kv, ["add", f"{KID}:{KEY}", "--service", "EXAMPLE"]) assert result.exit_code == 0, result.output assert SQLite("check", second).get_key(KID, "EXAMPLE") == KEY assert SQLite("check", read_only).get_key(KID, "EXAMPLE") is None lines = [r.getMessage() for r in caplog.records] assert not any("labs" in line for line in lines) assert "local SQLite: 0 newly added, 1 already existed (skipped)" in lines assert "remote SQLite: 1 newly added, 0 already existed (skipped)" in lines def test_kv_add_takes_a_dashed_pair_and_a_bom_key_file_into_a_vault_file( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: other_kid = "0" * 31 + "3" keys = tmp_path / "keys.txt" keys.write_text(f"{other_kid}:{KEY}\nnot a pair\n", encoding="utf-8-sig") dest = tmp_path / "file.db" dest.touch() local_vaults(monkeypatch) dashed = "00000000-0000-0000-0000-00000000000A" result = CliRunner().invoke( kv_module.kv, ["add", "-s", "EXAMPLE", "-v", str(dest), f"{dashed}:{KEY.upper()}", str(keys)] ) assert result.exit_code == 0, result.output check = SQLite("check", dest) assert check.get_key("0" * 31 + "a", "EXAMPLE") == KEY assert check.get_key(other_kid, "EXAMPLE") == KEY def test_kv_add_without_service_writes_the_generic_table(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: dest = tmp_path / "local.db" local_vaults(monkeypatch, dest) result = CliRunner().invoke(kv_module.kv, ["add", f"{KID}:{KEY}", "-v", "local"]) assert result.exit_code == 0, result.output assert SQLite("check", dest).get_key(KID, "generic") == KEY @pytest.mark.parametrize("no_push", [False, True]) def test_kv_add_without_vault_stops_when_no_configured_vault_takes_pushes( no_push: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: local_vaults(monkeypatch, no_push=tmp_path / "read_only.db" if no_push else None) result = CliRunner().invoke(kv_module.kv, ["add", f"{KID}:{KEY}", "-s", "EXAMPLE"], standalone_mode=False) assert isinstance(result.exception, click.ClickException) assert result.exception.message == "No Key Vaults without no_push are configured." @pytest.mark.parametrize("arg", [f"{KID}:{KEY[:-1]}", f"{KID}{KEY}", "missing.txt"]) def test_kv_add_rejects_an_argument_that_is_neither_a_pair_nor_a_file( arg: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: local_vaults(monkeypatch, tmp_path / "local.db") monkeypatch.chdir(tmp_path) result = CliRunner().invoke(kv_module.kv, ["add", arg, "-s", "EXAMPLE"], standalone_mode=False) assert isinstance(result.exception, click.ClickException) assert result.exception.message == f"Argument ({arg}) is not a KID:KEY or an existing file." assert not (tmp_path / "local.db").exists() def test_kv_add_names_a_key_file_that_is_not_utf8(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: keys = tmp_path / "keys.txt" keys.write_bytes(b"\xff\xfe" + f"{KID}:{KEY}".encode("utf-16-le")) local_vaults(monkeypatch, tmp_path / "local.db") result = CliRunner().invoke(kv_module.kv, ["add", str(keys), "-s", "EXAMPLE"], standalone_mode=False) assert isinstance(result.exception, click.ClickException) assert result.exception.message.startswith(f"Could not read {keys} (")