import stat import subprocess import threading from pathlib import Path from typing import Any import pytest from envbao import cache as cache_mod from envbao.cache import ( AutoStore, CacheEntry, CacheUnavailable, CredentialCache, FileStore, KeychainStore, cache_key, make_store, ) from envbao.cli import main from envbao.client import BaoClient from envbao.config import Config, Query, ServerConfig, parse_config from envbao.errors import ConfigError from envbao.resolve import validate_queries from .conftest import TOKEN, FakeBao, write_config CREDS = "/v1/database/creds/ro" REVOKE = "/v1/sys/leases/revoke" class Clock: def __init__(self, t: float = 1000.0) -> None: self.t = t def __call__(self) -> float: return self.t class MemStore: def __init__(self) -> None: self.data: dict[str, CacheEntry] = {} def get(self, key: str) -> CacheEntry | None: return self.data.get(key) def put(self, key: str, entry: CacheEntry) -> None: self.data[key] = entry def delete(self, key: str) -> None: self.data.pop(key, None) def serve_creds( fake: FakeBao, duration: int | None = 3600, lease: str = "database/creds/ro/l1" ) -> None: body: dict[str, Any] = {"data": {"username": "u", "password": "pw-secret"}} if duration is not None: body.update(lease_id=lease, lease_duration=duration) fake.routes[CREDS] = (200, body) def creds_gets(fake: FakeBao) -> int: return sum(1 for path, _ in fake.requests if path == CREDS) def setup(fake: FakeBao, tmp_path: Path, **query_kw: Any) -> tuple[BaoClient, Config, Query, Any]: query = Query(engine="database", options={"role": "ro"}, name="ro", cache=True, **query_kw) config = Config(ServerConfig(fake.url, TOKEN), (query,)) clock = Clock() cache = CredentialCache(MemStore(), tmp_path / "cache" / ".lock", now=clock) return BaoClient(config.server), config, query, (cache, clock) # ---- CredentialCache ------------------------------------------------------------------ def test_reuses_fresh_credential(fake_bao: FakeBao, tmp_path: Path) -> None: serve_creds(fake_bao) client, config, query, (cache, clock) = setup(fake_bao, tmp_path) first = cache.get_or_fetch(client, query, config) clock.t += 100 assert cache.get_or_fetch(client, query, config) == first assert creds_gets(fake_bao) == 1 assert fake_bao.posts == [] def test_refreshes_inside_margin_and_revokes_old_lease(fake_bao: FakeBao, tmp_path: Path) -> None: serve_creds(fake_bao, duration=3600) # margin = 360s fake_bao.routes[REVOKE] = (204, b"") client, config, query, (cache, clock) = setup(fake_bao, tmp_path) cache.get_or_fetch(client, query, config) clock.t += 3300 # 300s left < 360s margin serve_creds(fake_bao, lease="database/creds/ro/l2") cache.get_or_fetch(client, query, config) assert creds_gets(fake_bao) == 2 assert fake_bao.posts == [("/v1/sys/leases/revoke", {"lease_id": "database/creds/ro/l1"})] def test_minimum_margin_applies_to_short_leases(fake_bao: FakeBao, tmp_path: Path) -> None: serve_creds(fake_bao, duration=100) # 10% = 10s, floor is 60s client, config, query, (cache, clock) = setup(fake_bao, tmp_path) cache.get_or_fetch(client, query, config) clock.t += 50 # 50s left < 60s cache.get_or_fetch(client, query, config) assert creds_gets(fake_bao) == 2 def test_refreshes_when_expired(fake_bao: FakeBao, tmp_path: Path) -> None: serve_creds(fake_bao) client, config, query, (cache, clock) = setup(fake_bao, tmp_path) cache.get_or_fetch(client, query, config) clock.t += 10_000 cache.get_or_fetch(client, query, config) assert creds_gets(fake_bao) == 2 def test_clock_going_backwards_distrusts_entry(fake_bao: FakeBao, tmp_path: Path) -> None: serve_creds(fake_bao) client, config, query, (cache, clock) = setup(fake_bao, tmp_path) cache.get_or_fetch(client, query, config) clock.t -= 500 cache.get_or_fetch(client, query, config) assert creds_gets(fake_bao) == 2 def test_response_without_lease_is_not_cached( fake_bao: FakeBao, tmp_path: Path, caplog: pytest.LogCaptureFixture ) -> None: serve_creds(fake_bao, duration=None) client, config, query, (cache, _) = setup(fake_bao, tmp_path) cache.get_or_fetch(client, query, config) cache.get_or_fetch(client, query, config) assert creds_gets(fake_bao) == 2 assert "not caching" in caplog.text def test_revoke_failure_is_tolerated(fake_bao: FakeBao, tmp_path: Path) -> None: serve_creds(fake_bao) # no revoke route -> 404 client, config, query, (cache, clock) = setup(fake_bao, tmp_path) cache.get_or_fetch(client, query, config) clock.t += 10_000 assert cache.get_or_fetch(client, query, config)["password"] == "pw-secret" def test_stale_entry_with_no_new_lease_is_revoked(fake_bao: FakeBao, tmp_path: Path) -> None: serve_creds(fake_bao) fake_bao.routes[REVOKE] = (204, b"") client, config, query, (cache, clock) = setup(fake_bao, tmp_path) cache.get_or_fetch(client, query, config) clock.t += 10_000 serve_creds(fake_bao, duration=None) cache.get_or_fetch(client, query, config) assert len(fake_bao.posts) == 1 def test_non_cacheable_engine_rejected(fake_bao: FakeBao, tmp_path: Path) -> None: client, config, _, (cache, _) = setup(fake_bao, tmp_path) for query in ( Query(engine="kv", options={"mount": "s", "path": "p"}, cache=True), Query(engine="database", options={"role": "r", "static": True}, cache=True), ): with pytest.raises(ConfigError, match="does not support"): cache.get_or_fetch(client, query, config) def test_cache_key_depends_on_target_not_token() -> None: q1 = Query(engine="database", options={"role": "a"}) q2 = Query(engine="database", options={"role": "b"}) a = Config(ServerConfig("https://bao:8200", "t1"), (q1,)) same_other_token = Config(ServerConfig("https://bao:8200", "t2"), (q1,)) other_server = Config(ServerConfig("https://other:8200", "t1"), (q1,)) other_ns = Config(ServerConfig("https://bao:8200", "t1", namespace="n"), (q1,)) assert cache_key(a, q1) == cache_key(same_other_token, q1) assert ( len( { cache_key(a, q1), cache_key(a, q2), cache_key(other_server, q1), cache_key(other_ns, q1), } ) == 4 ) def test_concurrent_refresh_mints_once(fake_bao: FakeBao, tmp_path: Path) -> None: serve_creds(fake_bao) client, config, query, (cache, _) = setup(fake_bao, tmp_path) results: list[dict[str, Any]] = [] threads = [ threading.Thread(target=lambda: results.append(cache.get_or_fetch(client, query, config))) for _ in range(6) ] for t in threads: t.start() for t in threads: t.join() assert len(results) == 6 assert creds_gets(fake_bao) == 1 def test_clear_revokes_and_deletes(fake_bao: FakeBao, tmp_path: Path) -> None: serve_creds(fake_bao) fake_bao.routes[REVOKE] = (204, b"") client, config, query, (cache, _) = setup(fake_bao, tmp_path) cache.get_or_fetch(client, query, config) assert cache.clear(client, config) == 1 assert fake_bao.posts[-1][1] == {"lease_id": "database/creds/ro/l1"} assert cache.clear(client, config) == 0 plain = Config(config.server, (Query(engine="database", options={"role": "ro"}),)) assert cache.clear(client, plain) == 0 # ---- CacheEntry ----------------------------------------------------------------------- @pytest.mark.parametrize( "text", [ "not json", "[]", '{"values": {}, "lease_id": "x", "fetched_at": 1, "duration": 5}', '{"values": {"a": "b"}, "lease_id": "x", "fetched_at": "bad", "duration": 5}', '{"values": {"a": "b"}, "lease_id": "x", "fetched_at": 1, "duration": 0}', ], ) def test_malformed_entries_are_misses(text: str) -> None: assert CacheEntry.loads(text) is None def test_entry_roundtrip() -> None: entry = CacheEntry({"a": "b"}, "lease", 5.0, 60) assert CacheEntry.loads(entry.dumps()) == entry # ---- FileStore ------------------------------------------------------------------------ def test_file_store_modes_and_roundtrip(tmp_path: Path) -> None: store = FileStore(tmp_path / "cache") entry = CacheEntry({"password": "pw"}, "l", 1.0, 60) store.put("k", entry) assert store.get("k") == entry assert stat.S_IMODE((tmp_path / "cache").stat().st_mode) == 0o700 assert stat.S_IMODE((tmp_path / "cache" / "k.json").stat().st_mode) == 0o600 assert list((tmp_path / "cache").glob(".*.tmp")) == [] store.delete("k") assert store.get("k") is None store.delete("k") # idempotent def test_file_store_corrupt_file_is_miss(tmp_path: Path) -> None: store = FileStore(tmp_path) (tmp_path / "k.json").write_text("garbage") assert store.get("k") is None def test_file_store_refuses_symlink(tmp_path: Path) -> None: target = tmp_path / "elsewhere.json" target.write_text(CacheEntry({"a": "b"}, "l", 1.0, 60).dumps()) (tmp_path / "k.json").symlink_to(target) with pytest.raises(CacheUnavailable, match="symbolic link"): FileStore(tmp_path).get("k") def test_file_store_write_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: def boom(*_: Any) -> None: raise OSError(28, "No space left") monkeypatch.setattr(cache_mod.os, "replace", boom) with pytest.raises(CacheUnavailable, match="cannot write"): FileStore(tmp_path / "c").put("k", CacheEntry({"a": "b"}, "l", 1.0, 60)) assert list((tmp_path / "c").glob(".*.tmp")) == [] # ---- KeychainStore -------------------------------------------------------------------- class FakeTools: """Emulates `security` (macOS) and `secret-tool` (Linux) closely enough for the store.""" def __init__(self, mac: bool, *, fail: str | None = None, lossy: bool = False) -> None: self.mac = mac self.fail = fail self.lossy = lossy self.items: dict[str, str] = {} self.calls: list[tuple[list[str], str | None]] = [] def __call__( self, argv: list[str], stdin: str | None = None ) -> subprocess.CompletedProcess[str]: self.calls.append((argv, stdin)) if self.fail: raise CacheUnavailable(self.fail) def done(rc: int = 0, out: str = "", err: str = "") -> subprocess.CompletedProcess[str]: return subprocess.CompletedProcess(argv, rc, out, err) if self.mac: if argv[1] == "-i": assert stdin is not None parts = stdin.split() if not self.lossy: self.items[parts[parts.index("-a") + 1]] = parts[parts.index("-w") + 1] return done() key = argv[argv.index("-a") + 1] if argv[1] == "find-generic-password": return done(0, self.items[key] + "\n") if key in self.items else done(44) self.items.pop(key, None) return done() key = argv[-1] if argv[1] == "store": if not self.lossy: assert stdin is not None self.items[key] = stdin return done() if argv[1] == "lookup": return done(0, self.items[key]) if key in self.items else done(1) self.items.pop(key, None) return done() def keychain(monkeypatch: pytest.MonkeyPatch, platform: str, tools: FakeTools) -> KeychainStore: monkeypatch.setattr(cache_mod.shutil, "which", lambda name: f"/usr/bin/{name}") monkeypatch.setattr(cache_mod, "_run", tools) return KeychainStore(platform) @pytest.mark.parametrize(("platform", "mac"), [("darwin", True), ("linux", False)]) def test_keychain_roundtrip_keeps_secret_out_of_argv( monkeypatch: pytest.MonkeyPatch, platform: str, mac: bool ) -> None: tools = FakeTools(mac) store = keychain(monkeypatch, platform, tools) entry = CacheEntry({"password": "pw-secret"}, "l", 1.0, 60) assert store.get("k") is None store.put("k", entry) assert store.get("k") == entry encoded = cache_mod._encode(entry) for argv, _ in tools.calls: assert not any(encoded in a or "pw-secret" in a for a in argv) assert any(stdin and encoded in stdin for _, stdin in tools.calls) store.delete("k") assert store.get("k") is None @pytest.mark.parametrize(("platform", "mac"), [("darwin", True), ("linux", False)]) def test_keychain_detects_silent_write_loss( monkeypatch: pytest.MonkeyPatch, platform: str, mac: bool ) -> None: store = keychain(monkeypatch, platform, FakeTools(mac, lossy=True)) with pytest.raises(CacheUnavailable, match="did not retain"): store.put("k", CacheEntry({"a": "b"}, "l", 1.0, 60)) @pytest.mark.parametrize( ("platform", "result"), [("darwin", 51), ("linux", 2)], ) def test_keychain_tool_errors_map_to_unavailable( monkeypatch: pytest.MonkeyPatch, platform: str, result: int ) -> None: store = keychain(monkeypatch, platform, FakeTools(platform == "darwin")) monkeypatch.setattr( cache_mod, "_run", lambda argv, stdin=None: subprocess.CompletedProcess(argv, result, "", "boom"), ) with pytest.raises(CacheUnavailable): store.get("k") with pytest.raises(CacheUnavailable): store.put("k", CacheEntry({"a": "b"}, "l", 1.0, 60)) def test_keychain_unavailable_when_tool_missing(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(cache_mod.shutil, "which", lambda name: None) for platform in ("darwin", "linux", "win32"): with pytest.raises(CacheUnavailable): KeychainStore(platform) def test_run_wraps_subprocess_errors() -> None: with pytest.raises(CacheUnavailable): cache_mod._run(["/nonexistent/definitely-not-here"]) result = cache_mod._run(["/bin/cat"], stdin="hello") assert result.stdout == "hello" # ---- AutoStore / make_store ----------------------------------------------------------- class BrokenStore(MemStore): def get(self, key: str) -> CacheEntry | None: raise CacheUnavailable("locked") def put(self, key: str, entry: CacheEntry) -> None: raise CacheUnavailable("locked") def delete(self, key: str) -> None: raise CacheUnavailable("locked") def test_auto_store_falls_back_and_warns_once(caplog: pytest.LogCaptureFixture) -> None: fallback = MemStore() store = AutoStore(BrokenStore(), fallback) entry = CacheEntry({"a": "b"}, "l", 1.0, 60) store.put("k", entry) assert store.get("k") == entry store.delete("k") assert store.get("k") is None assert caplog.text.count("keychain unavailable") == 1 def test_auto_store_prefers_primary_and_clears_fallback() -> None: primary, fallback = MemStore(), MemStore() entry = CacheEntry({"a": "b"}, "l", 1.0, 60) fallback.put("k", entry) store = AutoStore(primary, fallback) store.put("k", entry) assert primary.get("k") == entry assert fallback.get("k") is None def test_make_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(cache_mod.shutil, "which", lambda name: None) assert isinstance(make_store("file", tmp_path), FileStore) assert isinstance(make_store("auto", tmp_path), FileStore) # no keychain -> files with pytest.raises(CacheUnavailable): make_store("keychain", tmp_path) monkeypatch.setattr(cache_mod.shutil, "which", lambda name: f"/usr/bin/{name}") assert isinstance(make_store("auto", tmp_path), AutoStore) # ---- config --------------------------------------------------------------------------- def toml_config( extra: str = "", query: str = 'engine = "database"\nrole = "ro"\ncache = true' ) -> dict[str, Any]: import tomllib return tomllib.loads( f'[server]\naddress = "http://127.0.0.1:1"\ntoken = "t"\n{extra}\n[[query]]\n{query}\n' ) def test_config_parses_cache_settings() -> None: cfg = parse_config(toml_config('[cache]\nstore = "file"')) assert cfg.queries[0].cache is True assert cfg.cache_store == "file" assert "cache" not in cfg.queries[0].options assert ( parse_config(toml_config(query='engine = "kv"\nmount="s"\npath="p"')).cache_store == "file" ) @pytest.mark.parametrize( ("extra", "query"), [ ('[cache]\nstore = "cloud"', 'engine = "database"\nrole = "r"'), ("[cache]\nbogus = 1", 'engine = "database"\nrole = "r"'), ("", 'engine = "database"\nrole = "r"\ncache = "yes"'), ], ) def test_config_rejects_bad_cache_settings(extra: str, query: str) -> None: with pytest.raises(ConfigError): parse_config(toml_config(extra, query)) @pytest.mark.parametrize( "query", [ 'engine = "kv"\nmount = "s"\npath = "p"\ncache = true', 'engine = "ssh"\nrole = "r"\nip = "1.2.3.4"\ncache = true', 'engine = "approle"\nrole = "r"\ncache = true', 'engine = "database"\nrole = "r"\nstatic = true\ncache = true', ], ) def test_cache_rejected_for_uncacheable_queries(query: str) -> None: with pytest.raises(ConfigError, match="cache = true is not supported"): validate_queries(parse_config(toml_config(query=query))) def test_cache_accepted_for_dynamic_engines() -> None: validate_queries(parse_config(toml_config())) validate_queries(parse_config(toml_config(query='engine = "aws"\nrole = "r"\ncache = true'))) # ---- CLI end to end ------------------------------------------------------------------- def cli_config(config_dir: Path, fake: FakeBao) -> Path: return write_config( config_dir, f'[server]\naddress = "{fake.url}"\ntoken = "{TOKEN}"\n' '[cache]\nstore = "file"\n' '[[query]]\nengine = "database"\nrole = "ro"\nname = "pg"\ncache = true\n' 'rename = { username = "PGUSER", password = "PGPASSWORD" }\n', ) def test_cli_reuses_cached_credential( fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str] ) -> None: serve_creds(fake_bao) path = cli_config(config_dir, fake_bao) outputs = [] for _ in range(3): assert main(["--config", str(path), "--shell", "sh"]) == 0 outputs.append(capsys.readouterr().out) assert creds_gets(fake_bao) == 1 assert outputs[0] == outputs[1] == outputs[2] assert "PGPASSWORD=pw-secret" in outputs[0] cached = list((config_dir / "cache").glob("*.json")) assert len(cached) == 1 assert stat.S_IMODE(cached[0].stat().st_mode) == 0o600 def test_cli_exec_uses_cache(fake_bao: FakeBao, config_dir: Path) -> None: serve_creds(fake_bao) path = cli_config(config_dir, fake_bao) for _ in range(2): code = main(["--config", str(path), "exec", "-q", "pg", "--", "/usr/bin/true"]) assert code == 0 assert creds_gets(fake_bao) == 1 def test_cli_clear_cache( fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str] ) -> None: serve_creds(fake_bao) fake_bao.routes[REVOKE] = (204, b"") path = cli_config(config_dir, fake_bao) main(["--config", str(path), "--shell", "sh"]) capsys.readouterr() assert main(["--config", str(path), "--clear-cache"]) == 0 assert "cleared 1" in capsys.readouterr().err assert list((config_dir / "cache").glob("*.json")) == [] assert fake_bao.posts[-1][0] == "/v1/sys/leases/revoke" main(["--config", str(path), "--shell", "sh"]) assert creds_gets(fake_bao) == 2 def test_cli_clear_cache_incompatible_with_exec(fake_bao: FakeBao, config_dir: Path) -> None: path = cli_config(config_dir, fake_bao) assert main(["--config", str(path), "--clear-cache", "exec", "-q", "pg", "--", "true"]) != 0