Add database, aws, approle and ssh engines with credential caching
release / validate (push) Successful in 5s
test / test (push) Successful in 1m6s
release / build (, macos-arm64, macos-arm64) (push) Successful in 1m20s
release / build (amd64, linux-amd64, linux-amd64) (push) Successful in 1m7s
release / build (arm64, linux-arm64, linux-arm64) (push) Successful in 2m2s
release / release (push) Successful in 26s
release / validate (push) Successful in 5s
test / test (push) Successful in 1m6s
release / build (, macos-arm64, macos-arm64) (push) Successful in 1m20s
release / build (amd64, linux-amd64, linux-amd64) (push) Successful in 1m7s
release / build (arm64, linux-arm64, linux-arm64) (push) Successful in 2m2s
release / release (push) Successful in 26s
New OpenBao credential engines (database/PostgreSQL, aws, approle, ssh) backed by a POST-capable BaoClient. Queries can set cache = true on dynamic database and aws roles to reuse the credential until near lease expiry (file store by default, optional keychain), revoking the old lease on refresh. Adds [cache] store and --clear-cache. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
78ff2b0ddd
commit
0cde1ff7f7
20 files changed
+1708
-29
No files matched your search
@@ -20,8 +20,16 @@ class FakeBao:
|
||||
def __init__(self) -> None:
|
||||
self.routes: dict[str, tuple[int, Any]] = {}
|
||||
self.requests: list[tuple[str, dict[str, str]]] = []
|
||||
self.posts: list[tuple[str, Any]] = []
|
||||
self.url = ""
|
||||
|
||||
def route(self, path: str, data: dict[str, Any], status: int = 200) -> None:
|
||||
"""Serve ``{"data": data}`` at ``/v1/<path>`` for both GET and POST."""
|
||||
self.routes[f"/v1/{path}"] = (
|
||||
status,
|
||||
{"data": data, "lease_id": "x/1", "lease_duration": 60},
|
||||
)
|
||||
|
||||
def kv2(self, mount: str, path: str, data: dict[str, Any]) -> None:
|
||||
self.routes[f"/v1/sys/internal/ui/mounts/{mount}"] = (
|
||||
200,
|
||||
@@ -59,6 +67,23 @@ def fake_bao() -> Iterator[FakeBao]:
|
||||
status, body = state.routes.get(self.path, (404, {"errors": []}))
|
||||
self._send(status, body)
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
headers = {k.lower(): v for k, v in self.headers.items()}
|
||||
length = int(headers.get("content-length", "0"))
|
||||
payload = json.loads(self.rfile.read(length) or b"{}")
|
||||
state.requests.append((self.path, headers))
|
||||
state.posts.append((self.path, payload))
|
||||
if headers.get("x-vault-token") != TOKEN:
|
||||
self._send(403, {"errors": ["permission denied"]})
|
||||
return
|
||||
if self.path == "/v1/redirect":
|
||||
self.send_response(307)
|
||||
self.send_header("Location", "http://127.0.0.1:1/steal")
|
||||
self.end_headers()
|
||||
return
|
||||
status, body = state.routes.get(self.path, (404, {"errors": []}))
|
||||
self._send(status, body)
|
||||
|
||||
def _send(self, status: int, body: Any) -> None:
|
||||
raw = body if isinstance(body, bytes) else json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
|
||||
@@ -0,0 +1,548 @@
|
||||
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
|
||||
@@ -244,7 +244,7 @@ def test_resolve_aborts_on_auth_error(fake_bao: FakeBao, caplog: pytest.LogCaptu
|
||||
|
||||
def test_unknown_engine() -> None:
|
||||
with pytest.raises(ConfigError, match="unknown engine"):
|
||||
get_engine("approle")
|
||||
get_engine("nonexistent")
|
||||
|
||||
|
||||
def test_registry_contains_kv() -> None:
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from envbao.client import BaoClient
|
||||
from envbao.config import Config, Query, ServerConfig
|
||||
from envbao.engines import ENGINES, get_engine
|
||||
from envbao.errors import AuthError, ConfigError, NotFoundError, ServerError
|
||||
from envbao.resolve import run_query, validate_queries
|
||||
|
||||
from .conftest import TOKEN, FakeBao
|
||||
|
||||
|
||||
def client_for(fake: FakeBao, token: str = TOKEN) -> BaoClient:
|
||||
return BaoClient(ServerConfig(address=fake.url, token=token))
|
||||
|
||||
|
||||
def q(engine: str, **options: Any) -> Query:
|
||||
return Query(engine=engine, options=options, name=options.get("role", engine))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["kv", "database", "aws", "approle", "ssh"])
|
||||
def test_registry(name: str) -> None:
|
||||
assert name in ENGINES
|
||||
assert get_engine(name) is ENGINES[name]
|
||||
|
||||
|
||||
# ---- POST on the client --------------------------------------------------------------
|
||||
|
||||
|
||||
def test_post_sends_json_body_and_token(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("things", {"a": 1})
|
||||
body = client_for(fake_bao).post("things", {"x": "y"})
|
||||
assert body["data"] == {"a": 1}
|
||||
assert fake_bao.posts[-1] == ("/v1/things", {"x": "y"})
|
||||
assert fake_bao.requests[-1][1]["x-vault-token"] == TOKEN
|
||||
assert fake_bao.requests[-1][1]["content-type"] == "application/json"
|
||||
|
||||
|
||||
def test_post_without_body_sends_empty_object(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("things", {"a": 1})
|
||||
client_for(fake_bao).post("things")
|
||||
assert fake_bao.posts[-1][1] == {}
|
||||
|
||||
|
||||
def test_post_does_not_follow_redirect(fake_bao: FakeBao) -> None:
|
||||
with pytest.raises(ServerError, match="HTTP 307"):
|
||||
client_for(fake_bao).post("redirect", {})
|
||||
|
||||
|
||||
def test_post_auth_error_and_not_found(fake_bao: FakeBao) -> None:
|
||||
with pytest.raises(AuthError):
|
||||
client_for(fake_bao, token="s.wrong").post("things")
|
||||
with pytest.raises(NotFoundError):
|
||||
client_for(fake_bao).post("missing")
|
||||
|
||||
|
||||
# ---- database -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_database_dynamic(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("database/creds/ro", {"username": "v-ro-1", "password": "pw-secret"})
|
||||
query = q("database", role="ro")
|
||||
env = run_query(client_for(fake_bao), query, Config(ServerConfig("x", "t"), (query,)))
|
||||
assert env == {"username": "v-ro-1", "password": "pw-secret"}
|
||||
|
||||
|
||||
def test_database_prefix_and_lease_not_exported(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("pg/creds/ro", {"username": "u", "password": "pw-secret"})
|
||||
query = Query(
|
||||
engine="database",
|
||||
options={"role": "ro", "mount": "pg"},
|
||||
rename={"username": "PGUSER", "password": "PGPASSWORD"},
|
||||
name="pg",
|
||||
)
|
||||
env = run_query(client_for(fake_bao), query, Config(ServerConfig("x", "t"), (query,)))
|
||||
assert env == {"PGUSER": "u", "PGPASSWORD": "pw-secret"}
|
||||
|
||||
|
||||
def test_database_static(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route(
|
||||
"database/static-creds/app",
|
||||
{"username": "app", "password": "pw-secret", "last_vault_rotation": "now"},
|
||||
)
|
||||
data = get_engine("database").fetch(client_for(fake_bao), {"role": "app", "static": True})
|
||||
assert data == {"username": "app", "password": "pw-secret"}
|
||||
|
||||
|
||||
def test_database_missing_role_is_not_found(fake_bao: FakeBao) -> None:
|
||||
with pytest.raises(NotFoundError):
|
||||
get_engine("database").fetch(client_for(fake_bao), {"role": "nope"})
|
||||
|
||||
|
||||
def test_database_empty_response_fails(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("database/creds/r", {"other": "x"})
|
||||
with pytest.raises(ServerError, match="no credentials"):
|
||||
get_engine("database").fetch(client_for(fake_bao), {"role": "r"})
|
||||
|
||||
|
||||
def test_response_without_data(fake_bao: FakeBao) -> None:
|
||||
fake_bao.routes["/v1/database/creds/r"] = (200, {"data": None})
|
||||
with pytest.raises(NotFoundError):
|
||||
get_engine("database").fetch(client_for(fake_bao), {"role": "r"})
|
||||
fake_bao.routes["/v1/database/creds/r"] = (200, {"data": "str"})
|
||||
with pytest.raises(ServerError, match="shape"):
|
||||
get_engine("database").fetch(client_for(fake_bao), {"role": "r"})
|
||||
|
||||
|
||||
# ---- aws ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_aws_creds(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route(
|
||||
"aws/creds/dev", {"access_key": "AKIA1", "secret_key": "sk", "security_token": None}
|
||||
)
|
||||
data = get_engine("aws").fetch(client_for(fake_bao), {"role": "dev"})
|
||||
assert data == {"access_key": "AKIA1", "secret_key": "sk"}
|
||||
|
||||
|
||||
def test_aws_sts_with_ttl(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route(
|
||||
"aws/sts/dev?ttl=15m", {"access_key": "A", "secret_key": "S", "security_token": "T"}
|
||||
)
|
||||
data = get_engine("aws").fetch(
|
||||
client_for(fake_bao), {"role": "dev", "kind": "sts", "ttl": "15m"}
|
||||
)
|
||||
assert data["security_token"] == "T"
|
||||
|
||||
|
||||
# ---- approle --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_approle_both(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("auth/approle/role/web/role-id", {"role_id": "rid"})
|
||||
fake_bao.route(
|
||||
"auth/approle/role/web/secret-id", {"secret_id": "sid", "secret_id_accessor": "a"}
|
||||
)
|
||||
data = get_engine("approle").fetch(client_for(fake_bao), {"role": "web"})
|
||||
assert data == {"role_id": "rid", "secret_id": "sid"}
|
||||
assert fake_bao.posts[-1][0] == "/v1/auth/approle/role/web/secret-id"
|
||||
|
||||
|
||||
def test_approle_only_role_id_does_not_mint_secret_id(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("auth/ar/role/web/role-id", {"role_id": "rid"})
|
||||
data = get_engine("approle").fetch(
|
||||
client_for(fake_bao), {"role": "web", "mount": "ar", "what": "role_id"}
|
||||
)
|
||||
assert data == {"role_id": "rid"}
|
||||
assert fake_bao.posts == []
|
||||
|
||||
|
||||
def test_approle_only_secret_id(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("auth/approle/role/web/secret-id", {"secret_id": "sid"})
|
||||
data = get_engine("approle").fetch(client_for(fake_bao), {"role": "web", "what": "secret_id"})
|
||||
assert data == {"secret_id": "sid"}
|
||||
|
||||
|
||||
# ---- ssh ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_ssh_otp(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route(
|
||||
"ssh/creds/ops", {"key": "otp-value", "username": "ops", "ip": "10.0.0.5", "port": 22}
|
||||
)
|
||||
data = get_engine("ssh").fetch(client_for(fake_bao), {"role": "ops", "ip": "10.0.0.5"})
|
||||
assert data == {"key": "otp-value", "username": "ops", "ip": "10.0.0.5"}
|
||||
assert fake_bao.posts[-1][1] == {"ip": "10.0.0.5"}
|
||||
|
||||
|
||||
def test_ssh_sign(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
pub = tmp_path / "id.pub"
|
||||
pub.write_text("ssh-ed25519 AAAA test\n")
|
||||
fake_bao.route("ssh/sign/ops", {"signed_key": "cert", "serial_number": "1"})
|
||||
data = get_engine("ssh").fetch(
|
||||
client_for(fake_bao),
|
||||
{"role": "ops", "mode": "sign", "public_key_file": str(pub), "valid_principals": "ops"},
|
||||
)
|
||||
assert data == {"signed_key": "cert", "serial_number": "1"}
|
||||
assert fake_bao.posts[-1][1] == {
|
||||
"public_key": "ssh-ed25519 AAAA test",
|
||||
"valid_principals": "ops",
|
||||
}
|
||||
|
||||
|
||||
def test_ssh_sign_unreadable_key(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
with pytest.raises(ConfigError, match="cannot read"):
|
||||
get_engine("ssh").fetch(
|
||||
client_for(fake_bao),
|
||||
{"role": "ops", "mode": "sign", "public_key_file": str(tmp_path / "nope.pub")},
|
||||
)
|
||||
|
||||
|
||||
def test_ssh_sign_huge_key_rejected(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
pub = tmp_path / "big.pub"
|
||||
pub.write_text("x" * (70 * 1024))
|
||||
with pytest.raises(ConfigError, match="large"):
|
||||
get_engine("ssh").fetch(
|
||||
client_for(fake_bao),
|
||||
{"role": "ops", "mode": "sign", "public_key_file": str(pub)},
|
||||
)
|
||||
|
||||
|
||||
# ---- validation -----------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("engine", "options"),
|
||||
[
|
||||
("database", {}),
|
||||
("database", {"role": ""}),
|
||||
("database", {"role": "r", "bogus": 1}),
|
||||
("database", {"role": "r", "static": "yes"}),
|
||||
("database", {"role": "r", "mount": 5}),
|
||||
("aws", {"role": "r", "kind": "other"}),
|
||||
("aws", {"role": "r", "ttl": ""}),
|
||||
("approle", {"role": "r", "what": "everything"}),
|
||||
("ssh", {"role": "r"}),
|
||||
("ssh", {"role": "r", "ip": "1.2.3.4", "public_key_file": "k"}),
|
||||
("ssh", {"role": "r", "mode": "sign"}),
|
||||
("ssh", {"role": "r", "mode": "sign", "public_key_file": "k", "ip": "1.2.3.4"}),
|
||||
("ssh", {"role": "r", "mode": "sign", "public_key_file": "k", "valid_principals": ""}),
|
||||
("ssh", {"role": "r", "mode": "bad"}),
|
||||
],
|
||||
)
|
||||
def test_invalid_options(engine: str, options: dict[str, Any]) -> None:
|
||||
with pytest.raises(ConfigError):
|
||||
get_engine(engine).validate(options)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("engine", "options"),
|
||||
[
|
||||
("database", {"role": "r"}),
|
||||
("database", {"role": "r", "mount": "pg", "static": True}),
|
||||
("aws", {"role": "r", "kind": "sts", "ttl": "1h"}),
|
||||
("approle", {"role": "r", "what": "role_id"}),
|
||||
("ssh", {"role": "r", "ip": "1.2.3.4"}),
|
||||
("ssh", {"role": "r", "mode": "sign", "public_key_file": "k", "valid_principals": "a,b"}),
|
||||
],
|
||||
)
|
||||
def test_valid_options(engine: str, options: dict[str, Any]) -> None:
|
||||
get_engine(engine).validate(options)
|
||||
validate_queries(Config(ServerConfig("x", "t"), (Query(engine=engine, options=options),)))
|
||||
Reference in new issue
Block a user