diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f39b65..dc9ff79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ All notable changes are documented here. This project follows [Semantic Versioni ## [Unreleased] +## [0.3.0] - 2026-11-09 + +### Added +- Credential engines `database` (PostgreSQL etc.), `aws`, `approle` and `ssh`. +- `BaoClient.post` for engines that generate credentials on write. +- `cache = true` on `database` (dynamic) and `aws` queries: reuse the credential until near lease + expiry (`0600` file by default, or the keychain), revoke the old lease on refresh; `[cache] store` + and `envbao --clear-cache`. + ## [0.2.0] - 2026-10-16 ### Added (exec and packaging) diff --git a/README.md b/README.md index 3b7ad7c..191604f 100644 --- a/README.md +++ b/README.md @@ -20,8 +20,10 @@ safely quoted `export` statements for your shell to evaluate. you only; all failures print *nothing* to stdout, so a failed run can never half-configure your shell. See [docs/security.md](docs/security.md). - **Config-driven queries** - choose exactly which secrets, keys, prefixes and renames you want. -- **KV v1 and v2** with automatic version detection. Other credential engines are planned and - slot into an engine registry. +- **KV v1 and v2** with automatic version detection. +- **Dynamic credentials** from the OpenBao `database` (e.g. PostgreSQL), `aws`, `approle` and `ssh` + engines; see `docs/configuration.md`. `cache = true` reuses a credential until near expiry, so + it is safe in a startup `eval`. - **Audited** - issues are logged to stderr, `~/.envbao/envbao.log` (mode 0600) and the system log. Tokens and secret values are never logged. - **Single binary**, no runtime dependencies (built with PyInstaller). diff --git a/docs/configuration.md b/docs/configuration.md index e20f0ce..01c7888 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -46,6 +46,66 @@ Common keys: Names that are not valid variable names (`[A-Za-z_][A-Za-z0-9_]*`) are skipped with a warning. +## Credential engines + +Besides `kv`, queries can use `engine = "database" | "aws" | "approle" | "ssh"`. They go through the +same `[server]` and are filtered/renamed/prefixed like KV data. Only credential fields are exported; +lease metadata is dropped. Variable names are the returned field names, so use `rename` (or `prefix`) +to get the names your tools expect. + +```toml +[[query]] # PostgreSQL via the OpenBao database engine +engine = "database" +role = "readonly" # required; mount defaults to "database" +# static = true # read static-creds/ instead of creating a user +name = "pg" +rename = { username = "PGUSER", password = "PGPASSWORD" } + +[[query]] +engine = "aws" # role required; mount "aws"; kind = "creds" | "sts"; ttl = "15m" +role = "deploy" +rename = { access_key = "AWS_ACCESS_KEY_ID", secret_key = "AWS_SECRET_ACCESS_KEY", security_token = "AWS_SESSION_TOKEN" } + +[[query]] +engine = "approle" # role required; mount "approle"; what = "both" | "role_id" | "secret_id" +role = "web" + +[[query]] +engine = "ssh" # otp (default): needs ip; sign: needs public_key_file +role = "ops" +ip = "10.0.0.5" +``` + +### Caching dynamic credentials (`cache = true`) + +Dynamic credentials are created on every fetch (a new database user or IAM user each time), which +would make `eval "$(envbao)"` in a shell startup file mint one per shell. Add `cache = true` to a +`database` (non-`static`) or `aws` query to reuse the credential until shortly before its lease +expires: + +```toml +[cache] +store = "file" # default. "keychain" (fail if unavailable) or "auto" (keychain, else file) + +[[query]] +engine = "database" +role = "readonly" +cache = true +``` + +* The credential is reused while more than `max(60s, 10% of the lease)` remains. After that a new one + is fetched and the old lease is revoked (best effort; it expires on its own if the token may not + call `sys/leases/revoke`). +* Storage (`[cache] store`): `file` (default) keeps a `0600` file in `~/.envbao/cache/`; `keychain` uses + the macOS Keychain (`security`) or Linux secret service (`secret-tool`) and fails if unavailable; + `auto` tries the keychain and falls back to the file. Secrets are never put on a command line. +* The key covers server address, namespace, engine and options; it ignores the token, so rotating + the token keeps the cache valid. +* `cache = true` is rejected for `kv`, `approle`, `ssh` (one-time passwords and certificates have no + reusable lease) and `database` with `static = true`. +* Without `cache = true`, prefer `envbao exec -q pg -- command` for dynamic engines. +* `envbao --clear-cache` revokes and deletes the cached credentials. + ## Adding an engine Implement `envbao.engines.Engine` (`validate` and `fetch`) in a new module under diff --git a/docs/security.md b/docs/security.md index 75a1b99..41e8c93 100644 --- a/docs/security.md +++ b/docs/security.md @@ -35,6 +35,11 @@ variables are exported (any child process inherits them). their values (raw, JSON, URL-encoded) in its output; with `[security] exec_only = true` plain export mode and `--no-redact` are refused. Masking is defence in depth, not a sandbox (see [claude-access.md](claude-access.md)). +9. **Credential cache (opt-in)** - with `cache = true`, a dynamic credential is stored at rest until + near lease expiry: in a `0600` file under `~/.envbao/cache/` (covered by control 1) by default, or in the OS + keychain with `[cache] store = "keychain"` / `"auto"`. Cache entries are short-lived by construction, are revoked on refresh and by + `envbao --clear-cache`, and are never logged or passed on a command line. Nothing is written + unless a query opts in. ## Recommendations diff --git a/src/envbao/cache.py b/src/envbao/cache.py new file mode 100644 index 0000000..600def5 --- /dev/null +++ b/src/envbao/cache.py @@ -0,0 +1,389 @@ +"""Reuse of dynamically generated credentials until shortly before they expire. + +OpenBao cannot return the same dynamic credential twice, so a query with ``cache = true`` +stores the credential locally together with its lease and only asks the server for a new +one when less than a safety margin of the lease remains (the old lease is then revoked). + +Storage prefers the operating system keychain and falls back to a ``0600`` file inside the +EnvBao configuration directory, which the permission policy already covers. Secrets are +never passed on a command line: keychain writes use stdin and values are base64-encoded so +they survive the tools' own quoting rules. +""" + +from __future__ import annotations + +import base64 +import contextlib +import fcntl +import hashlib +import json +import logging +import os +import shutil +import subprocess # noqa: S404 +import sys +import time +from collections.abc import Callable, Iterator +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any, Protocol + +from envbao.client import BaoClient +from envbao.config import Config, Query +from envbao.engines import CacheableEngine, get_engine +from envbao.errors import ConfigError, EnvBaoError, ServerError + +log = logging.getLogger(__name__) + +SERVICE = "envbao" +CACHE_DIR_NAME = "cache" +MIN_MARGIN = 60.0 +MARGIN_FRACTION = 0.10 +_SUBPROCESS_TIMEOUT = 10.0 +_MACOS_NOT_FOUND = 44 + + +class CacheUnavailable(EnvBaoError): + """The selected cache store cannot be used (for example no keychain).""" + + +@dataclass(frozen=True) +class CacheEntry: + """A cached credential and the lease it belongs to.""" + + values: dict[str, Any] + lease_id: str + fetched_at: float + duration: int + + def remaining(self, now: float) -> float: + return self.fetched_at + self.duration - now + + def is_fresh(self, now: float) -> bool: + """True if the credential can still be used without refreshing.""" + if self.fetched_at > now: # clock went backwards: do not trust the entry + return False + margin = max(MIN_MARGIN, MARGIN_FRACTION * self.duration) + return self.remaining(now) > margin + + def dumps(self) -> str: + return json.dumps(asdict(self), separators=(",", ":")) + + @classmethod + def loads(cls, text: str) -> CacheEntry | None: + """Parse an entry; anything malformed is treated as a cache miss.""" + try: + raw = json.loads(text) + entry = cls( + values=dict(raw["values"]), + lease_id=str(raw["lease_id"]), + fetched_at=float(raw["fetched_at"]), + duration=int(raw["duration"]), + ) + except (ValueError, KeyError, TypeError): + return None + return entry if entry.values and entry.duration > 0 else None + + +class CacheStore(Protocol): + """Where cached entries are kept.""" + + def get(self, key: str) -> CacheEntry | None: ... + + def put(self, key: str, entry: CacheEntry) -> None: ... + + def delete(self, key: str) -> None: ... + + +# ---- file store ----------------------------------------------------------------------- + + +class FileStore: + """One ``0600`` JSON file per entry in ``/cache`` (directory ``0700``).""" + + def __init__(self, directory: Path) -> None: + self._dir = directory + + def _ensure_dir(self) -> None: + self._dir.mkdir(mode=0o700, parents=True, exist_ok=True) + os.chmod(self._dir, 0o700) + + def _path(self, key: str) -> Path: + return self._dir / f"{key}.json" + + def get(self, key: str) -> CacheEntry | None: + path = self._path(key) + try: + if path.is_symlink(): + raise CacheUnavailable(f"{path} is a symbolic link; refusing to follow it") + return CacheEntry.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError: + return None + except (OSError, UnicodeDecodeError): + return None + + def put(self, key: str, entry: CacheEntry) -> None: + self._ensure_dir() + target = self._path(key) + tmp = self._dir / f".{key}.{os.getpid()}.tmp" + try: + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(entry.dumps()) + os.replace(tmp, target) + except OSError as exc: + with contextlib.suppress(OSError): + tmp.unlink() + raise CacheUnavailable(f"cannot write cache file: {exc.strerror}") from None + + def delete(self, key: str) -> None: + with contextlib.suppress(FileNotFoundError, OSError): + self._path(key).unlink() + + +# ---- keychain store ------------------------------------------------------------------- + + +def _run(argv: list[str], stdin: str | None = None) -> subprocess.CompletedProcess[str]: + try: + return subprocess.run( # noqa: S603 + argv, + input=stdin, + capture_output=True, + text=True, + timeout=_SUBPROCESS_TIMEOUT, + check=False, + ) + except (OSError, subprocess.SubprocessError) as exc: + raise CacheUnavailable(f"{Path(argv[0]).name} failed: {type(exc).__name__}") from None + + +def _encode(entry: CacheEntry) -> str: + return base64.b64encode(entry.dumps().encode()).decode() + + +def _decode(text: str) -> CacheEntry | None: + try: + return CacheEntry.loads(base64.b64decode(text.strip(), validate=True).decode()) + except (ValueError, UnicodeDecodeError): + return None + + +class KeychainStore: + """macOS Keychain (``security``) or the freedesktop secret service (``secret-tool``).""" + + def __init__(self, platform: str | None = None) -> None: + platform = platform or sys.platform + if platform == "darwin": + self._tool = shutil.which("security") + self._mac = True + elif platform.startswith("linux"): + self._tool = shutil.which("secret-tool") + self._mac = False + else: + self._tool = None + self._mac = False + if not self._tool: + raise CacheUnavailable("no keychain tool available on this system") + + # -- macOS + def _mac_get(self, key: str) -> CacheEntry | None: + assert self._tool # noqa: S101 + result = _run([self._tool, "find-generic-password", "-s", SERVICE, "-a", key, "-w"]) + if result.returncode == _MACOS_NOT_FOUND: + return None + if result.returncode != 0: + raise CacheUnavailable("keychain lookup failed") + return _decode(result.stdout) + + def _mac_put(self, key: str, entry: CacheEntry) -> None: + assert self._tool # noqa: S101 + # ``security -i`` reads commands from stdin, keeping the secret out of ``ps``. + command = f"add-generic-password -U -s {SERVICE} -a {key} -w {_encode(entry)}\n" + result = _run([self._tool, "-i"], stdin=command) + if result.returncode != 0: + raise CacheUnavailable("keychain write failed") + + def _mac_delete(self, key: str) -> None: + assert self._tool # noqa: S101 + _run([self._tool, "delete-generic-password", "-s", SERVICE, "-a", key]) + + # -- Linux + def _linux_get(self, key: str) -> CacheEntry | None: + assert self._tool # noqa: S101 + result = _run([self._tool, "lookup", "service", SERVICE, "account", key]) + if result.returncode != 0: + if result.returncode == 1 and not result.stderr.strip(): + return None + raise CacheUnavailable("secret service lookup failed") + return _decode(result.stdout) + + def _linux_put(self, key: str, entry: CacheEntry) -> None: + assert self._tool # noqa: S101 + argv = [self._tool, "store", f"--label={SERVICE}", "service", SERVICE, "account", key] + if _run(argv, stdin=_encode(entry)).returncode != 0: + raise CacheUnavailable("secret service write failed") + + def _linux_delete(self, key: str) -> None: + assert self._tool # noqa: S101 + _run([self._tool, "clear", "service", SERVICE, "account", key]) + + def get(self, key: str) -> CacheEntry | None: + return self._mac_get(key) if self._mac else self._linux_get(key) + + def put(self, key: str, entry: CacheEntry) -> None: + if self._mac: + self._mac_put(key, entry) + else: + self._linux_put(key, entry) + # Some tool versions report success without storing; verify so we can fall back. + if self.get(key) != entry: + raise CacheUnavailable("keychain did not retain the entry") + + def delete(self, key: str) -> None: + if self._mac: + self._mac_delete(key) + else: + self._linux_delete(key) + + +class AutoStore: + """Keychain first; if it is unusable fall back to files (warning once).""" + + def __init__(self, primary: CacheStore, fallback: CacheStore) -> None: + self._primary = primary + self._fallback = fallback + self._warned = False + + def _degrade(self, exc: CacheUnavailable) -> None: + if not self._warned: + log.warning("keychain unavailable (%s); caching credentials in a file instead", exc) + self._warned = True + + def get(self, key: str) -> CacheEntry | None: + try: + entry = self._primary.get(key) + except CacheUnavailable as exc: + self._degrade(exc) + entry = None + return entry or self._fallback.get(key) + + def put(self, key: str, entry: CacheEntry) -> None: + try: + self._primary.put(key, entry) + except CacheUnavailable as exc: + self._degrade(exc) + self._fallback.put(key, entry) + else: + self._fallback.delete(key) + + def delete(self, key: str) -> None: + with contextlib.suppress(CacheUnavailable): + self._primary.delete(key) + self._fallback.delete(key) + + +def make_store(kind: str, config_dir: Path) -> CacheStore: + """Build the store selected by ``[cache] store``.""" + files = FileStore(config_dir / CACHE_DIR_NAME) + if kind == "file": + return files + if kind == "keychain": + return KeychainStore() # raises CacheUnavailable: fail closed + try: + return AutoStore(KeychainStore(), files) + except CacheUnavailable as exc: + log.warning("keychain unavailable (%s); caching credentials in a file instead", exc) + return files + + +# ---- cache ---------------------------------------------------------------------------- + + +def cache_key(config: Config, query: Query) -> str: + """Stable key for a query on a given server. The token is deliberately not part of it.""" + material = json.dumps( + [config.server.address, config.server.namespace, query.engine, dict(query.options)], + sort_keys=True, + separators=(",", ":"), + default=str, + ) + return hashlib.sha256(material.encode()).hexdigest()[:40] + + +class CredentialCache: + """Serve cached credentials, refreshing them (and revoking the old lease) when due.""" + + def __init__( + self, + store: CacheStore, + lock_path: Path, + now: Callable[[], float] = time.time, + ) -> None: + self._store = store + self._lock_path = lock_path + self._now = now + + @contextlib.contextmanager + def _locked(self) -> Iterator[None]: + """Serialise refreshes across processes so parallel shells mint one credential.""" + self._lock_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + os.chmod(self._lock_path.parent, 0o700) + fd = os.open(self._lock_path, os.O_WRONLY | os.O_CREAT, 0o600) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + yield + finally: + os.close(fd) # closing releases the lock + + def get_or_fetch(self, client: BaoClient, query: Query, config: Config) -> dict[str, Any]: + """Return the query's credential values, reusing a still-valid cached one.""" + engine = get_engine(query.engine) + if not isinstance(engine, CacheableEngine) or not engine.cacheable(query.options): + raise ConfigError(f"{query.describe()} does not support cache = true") + key = cache_key(config, query) + + with self._locked(): + entry = self._store.get(key) + now = self._now() + if entry is not None and entry.is_fresh(now): + log.info( + "%s: using cached credential (%ds left)", query.describe(), entry.remaining(now) + ) + return dict(entry.values) + + values, lease = engine.fetch_leased(client, query.options) + if lease is None: + log.warning("%s: no lease in response; not caching", query.describe()) + self._revoke(client, entry) + return values + self._store.put( + key, CacheEntry(dict(values), lease.lease_id, self._now(), lease.duration) + ) + self._revoke(client, entry) + return values + + def clear(self, client: BaoClient, config: Config) -> int: + """Revoke and delete the cached credentials of all ``cache = true`` queries.""" + cleared = 0 + with self._locked(): + for query in config.queries: + if not query.cache: + continue + key = cache_key(config, query) + entry = self._store.get(key) + if entry is None: + continue + self._revoke(client, entry) + self._store.delete(key) + cleared += 1 + return cleared + + @staticmethod + def _revoke(client: BaoClient, entry: CacheEntry | None) -> None: + if entry is None: + return + try: + client.post("sys/leases/revoke", {"lease_id": entry.lease_id}) + except ServerError as exc: + log.debug("could not revoke old lease: %s", exc) diff --git a/src/envbao/cli.py b/src/envbao/cli.py index 7313abb..8753687 100644 --- a/src/envbao/cli.py +++ b/src/envbao/cli.py @@ -14,6 +14,7 @@ import sys from collections.abc import Sequence from pathlib import Path +from envbao.cache import CACHE_DIR_NAME, CredentialCache, make_store from envbao.client import BaoClient from envbao.config import Config, load_config, resolve_config_path from envbao.errors import EXIT_FAILURE, EXIT_OK, ConfigError, EnvBaoError, PermissionPolicyError @@ -85,6 +86,11 @@ def build_parser() -> argparse.ArgumentParser: action="store_true", help="create ~/.envbao with safe permissions and a template config.toml", ) + mode.add_argument( + "--clear-cache", + action="store_true", + help="revoke and delete cached dynamic credentials, then exit", + ) parser.add_argument("-v", "--verbose", action="count", default=0, help="log more to stderr") parser.add_argument("--version", action=_VersionAction) @@ -132,12 +138,17 @@ def _check(config: Config, client: BaoClient) -> None: ) +def _build_cache(config: Config, config_dir: Path) -> CredentialCache: + store = make_store(config.cache_store, config_dir) + return CredentialCache(store, config_dir / CACHE_DIR_NAME / ".lock") + + def run(args: argparse.Namespace) -> int: """Execute the requested action and return the exit status.""" path = resolve_config_path(args.config) - if args.command == "exec" and (args.check or args.init): - raise ConfigError("--check/--init cannot be combined with exec") + if args.command == "exec" and (args.check or args.init or args.clear_cache): + raise ConfigError("--check/--init/--clear-cache cannot be combined with exec") if args.init: try: init_config(path) @@ -159,6 +170,12 @@ def run(args: argparse.Namespace) -> int: _check(config, client) return EXIT_OK + cache = _build_cache(config, path.parent) if any(q.cache for q in config.queries) else None + if args.clear_cache: + count = _build_cache(config, path.parent).clear(client, config) + sys.stderr.write(f"envbao: cleared {count} cached credential(s)\n") + return EXIT_OK + if config.exec_only and args.command != "exec" and not args.check: raise ConfigError("this configuration only permits 'envbao exec' (security.exec_only)") if args.command == "exec": @@ -166,11 +183,11 @@ def run(args: argparse.Namespace) -> int: raise ConfigError("--no-redact is not permitted (security.exec_only)") argv = args.argv[1:] if args.argv[:1] == ["--"] else args.argv queries = select_queries(config, args.query) - secrets = fetch_secrets(client, config, queries) + secrets = fetch_secrets(client, config, queries, cache) log.info("exec: groups %s", ", ".join(q.name for q in queries)) return run_command(argv, secrets, redact=not args.no_redact) - env = resolve(client, config) + env = resolve(client, config, cache) shell = detect_shell() if args.shell == "auto" else args.shell output = render(env, shell) log.info("exported %d variable(s) for %s", len(env), shell) diff --git a/src/envbao/client.py b/src/envbao/client.py index 320084b..797f252 100644 --- a/src/envbao/client.py +++ b/src/envbao/client.py @@ -66,7 +66,7 @@ def validate_address(address: str, *, allow_insecure_http: bool) -> str: class BaoClient: - """Authenticated read-only access to the OpenBao HTTP API.""" + """Authenticated access (GET and POST) to the OpenBao HTTP API.""" def __init__(self, server: ServerConfig) -> None: self._base = validate_address( @@ -94,18 +94,42 @@ class BaoClient: NotFoundError: HTTP 404. ServerError: any other failure (network, TLS, 5xx, malformed response). """ + return self._request("GET", path, params=params) + + def post(self, path: str, body: dict[str, Any] | None = None) -> dict[str, Any]: + """POST a JSON ``body`` to ``/v1/`` and return the decoded JSON object. + + Used by engines that generate credentials on write (e.g. AppRole secret-ids, SSH). + Raises the same exceptions as :meth:`get`. + """ + return self._request("POST", path, body=body if body is not None else {}) + + def _request( + self, + method: str, + path: str, + *, + params: dict[str, str] | None = None, + body: dict[str, Any] | None = None, + ) -> dict[str, Any]: url = f"{self._base}{_API_PREFIX}{path.lstrip('/')}" if params: url += "?" + urlencode(params) headers = {"X-Vault-Token": self._token, "Accept": "application/json"} if self._namespace: headers["X-Vault-Namespace"] = self._namespace - request = urllib.request.Request(url, headers=headers, method="GET") # noqa: S310 + data: bytes | None = None + if body is not None: + data = json.dumps(body).encode() + headers["Content-Type"] = "application/json" + request = urllib.request.Request( # noqa: S310 + url, data=data, headers=headers, method=method + ) shown = f"/{_API_PREFIX.strip('/')}/{path.lstrip('/')}" try: with self._opener.open(request, timeout=self._timeout) as response: - body = response.read(_MAX_RESPONSE_BYTES + 1) + raw = response.read(_MAX_RESPONSE_BYTES + 1) except urllib.error.HTTPError as exc: exc.close() if exc.code in (401, 403): @@ -117,10 +141,12 @@ class BaoClient: reason = getattr(exc, "reason", exc) raise ServerError(f"cannot reach {self._base}: {reason}") from None - if len(body) > _MAX_RESPONSE_BYTES: + if len(raw) > _MAX_RESPONSE_BYTES: raise ServerError(f"response for {shown} exceeds size limit") + if not raw.strip(): # e.g. HTTP 204 from sys/leases/revoke + return {} try: - decoded = json.loads(body) + decoded = json.loads(raw) except ValueError: raise ServerError(f"response for {shown} is not valid JSON") from None if not isinstance(decoded, dict): diff --git a/src/envbao/config.py b/src/envbao/config.py index 6b26805..5ae94e7 100644 --- a/src/envbao/config.py +++ b/src/envbao/config.py @@ -36,8 +36,10 @@ _SERVER_KEYS = { "allow_insecure_http", } _SECURITY_KEYS = {"allow_protected", "exec_only"} -_TOP_KEYS = {"server", "security", "query"} -_QUERY_COMMON_KEYS = {"engine", "name", "keys", "prefix", "rename", "on_missing"} +_CACHE_KEYS = {"store"} +CACHE_STORES = ("auto", "keychain", "file") +_TOP_KEYS = {"server", "security", "query", "cache"} +_QUERY_COMMON_KEYS = {"engine", "name", "keys", "prefix", "rename", "on_missing", "cache"} _NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\Z") CONFIG_ENV_VAR = "ENVBAO_CONFIG" @@ -69,6 +71,7 @@ class Query: rename: Mapping[str, str] = field(default_factory=dict) on_missing: str = "warn" name: str = "" + cache: bool = False def describe(self) -> str: """Short, secret-free description of this query for logs.""" @@ -84,6 +87,7 @@ class Config: queries: tuple[Query, ...] allow_protected: frozenset[str] = frozenset() exec_only: bool = False + cache_store: str = "file" def resolve_config_path(explicit: str | None) -> Path: @@ -171,10 +175,14 @@ def _parse_server(raw: Mapping[str, Any]) -> ServerConfig: def _default_name(engine: str, options: Mapping[str, Any]) -> str: - """Name used by ``envbao exec -q``: last path segment (e.g. ``shell/gitea`` -> ``gitea``).""" - path = options.get("path") - if isinstance(path, str) and path.strip("/"): - return path.strip("/").rsplit("/", 1)[-1] + """Name used by ``envbao exec -q``: last path segment (e.g. ``shell/gitea`` -> ``gitea``). + + Engines addressed by ``role`` rather than ``path`` fall back to the role name. + """ + for key in ("path", "role"): + value = options.get(key) + if isinstance(value, str) and value.strip("/"): + return value.strip("/").rsplit("/", 1)[-1] return engine @@ -197,6 +205,10 @@ def _parse_query(raw: Any, index: int) -> Query: if on_missing not in ON_MISSING_CHOICES: raise ConfigError(f"{name_label}.on_missing must be one of {', '.join(ON_MISSING_CHOICES)}") + cache = raw.get("cache", False) + if not isinstance(cache, bool): + raise ConfigError(f"{name_label}.cache must be a boolean") + options = {k: v for k, v in raw.items() if k not in _QUERY_COMMON_KEYS} name = _get_str(raw, "name", name_label) or _default_name(engine, options) if not _NAME_RE.match(name): @@ -209,6 +221,7 @@ def _parse_query(raw: Any, index: int) -> Query: rename=dict(rename), on_missing=on_missing, name=name, + cache=cache, ) @@ -232,11 +245,18 @@ def parse_config(data: Mapping[str, Any]) -> Config: if not isinstance(exec_only, bool): raise ConfigError("security.exec_only must be a boolean") + cache_table = _require_table(data.get("cache", {}), "cache") + _reject_unknown(cache_table, _CACHE_KEYS, "[cache]") + cache_store = _get_str(cache_table, "store", "cache") or "file" + if cache_store not in CACHE_STORES: + raise ConfigError(f"cache.store must be one of {', '.join(CACHE_STORES)}") + return Config( server=server, queries=queries, allow_protected=frozenset(allow_protected), exec_only=exec_only, + cache_store=cache_store, ) diff --git a/src/envbao/engines/__init__.py b/src/envbao/engines/__init__.py index 8e6ab00..783b3e6 100644 --- a/src/envbao/engines/__init__.py +++ b/src/envbao/engines/__init__.py @@ -9,10 +9,11 @@ implements :class:`Engine` and an entry in :data:`ENGINES`. from __future__ import annotations from collections.abc import Mapping -from typing import Any, Protocol +from typing import Any, Protocol, runtime_checkable from envbao.client import BaoClient -from envbao.engines import kv +from envbao.engines import approle, aws, database, kv, ssh +from envbao.engines._common import Lease from envbao.errors import ConfigError @@ -30,7 +31,28 @@ class Engine(Protocol): """ -ENGINES: dict[str, Engine] = {"kv": kv.KvEngine()} +@runtime_checkable +class CacheableEngine(Engine, Protocol): + """Engines that mint a leased credential per fetch and so support ``cache = true``.""" + + def cacheable(self, options: Mapping[str, Any]) -> bool: + """Whether a query with these options may be cached.""" + + def fetch_leased( + self, client: BaoClient, options: Mapping[str, Any] + ) -> tuple[dict[str, Any], Lease | None]: + """Like :meth:`Engine.fetch`, also returning the credential's lease.""" + + +__all__ = ["ENGINES", "CacheableEngine", "Engine", "Lease", "get_engine"] + +ENGINES: dict[str, Engine] = { + "kv": kv.KvEngine(), + "database": database.DatabaseEngine(), + "aws": aws.AwsEngine(), + "approle": approle.ApproleEngine(), + "ssh": ssh.SshEngine(), +} def get_engine(name: str) -> Engine: diff --git a/src/envbao/engines/_common.py b/src/envbao/engines/_common.py new file mode 100644 index 0000000..c2f4ad2 --- /dev/null +++ b/src/envbao/engines/_common.py @@ -0,0 +1,88 @@ +"""Helpers shared by the credential-generating engines (database, aws, approle, ssh).""" + +from __future__ import annotations + +from collections.abc import Collection, Mapping +from dataclasses import dataclass +from typing import Any + +from envbao.errors import ConfigError, NotFoundError, ServerError + + +@dataclass(frozen=True) +class Lease: + """Server-side lease attached to a dynamically generated credential.""" + + lease_id: str + duration: int # seconds + + +def lease_of(body: Mapping[str, Any]) -> Lease | None: + """Extract the lease from an API response, or ``None`` if it has no usable one.""" + lease_id = body.get("lease_id") + duration = body.get("lease_duration") + if ( + isinstance(lease_id, str) + and lease_id + and isinstance(duration, int) + and not isinstance(duration, bool) + and duration > 0 + ): + return Lease(lease_id, duration) + return None + + +def check_options(engine: str, options: Mapping[str, Any], allowed: Collection[str]) -> None: + """Reject option names the engine does not know.""" + unknown = sorted(set(options) - set(allowed)) + if unknown: + raise ConfigError(f"unknown option(s) for {engine} engine: {', '.join(unknown)}") + + +def get_str( + engine: str, options: Mapping[str, Any], key: str, *, default: str | None = None +) -> str: + """Return a non-empty string option (stripped of surrounding slashes) or ``default``.""" + value = options.get(key, default) + if not isinstance(value, str) or not value.strip("/"): + raise ConfigError(f"{engine} query requires a non-empty string '{key}'") + return value.strip("/") + + +def get_choice( + engine: str, options: Mapping[str, Any], key: str, choices: tuple[str, ...], default: str +) -> str: + """Return an option constrained to ``choices``.""" + value = options.get(key, default) + if value not in choices: + raise ConfigError(f"{engine} option '{key}' must be one of: {', '.join(choices)}") + return str(value) + + +def get_bool(engine: str, options: Mapping[str, Any], key: str, default: bool = False) -> bool: + value = options.get(key, default) + if not isinstance(value, bool): + raise ConfigError(f"{engine} option '{key}' must be true or false") + return value + + +def response_data(body: Mapping[str, Any], where: str) -> dict[str, Any]: + """Return the ``data`` object of an API response, failing closed if absent.""" + data = body.get("data") + if data is None: + raise NotFoundError(f"no data at {where}") + if not isinstance(data, dict): + raise ServerError(f"unexpected data shape at {where}") + return data + + +def pick(data: Mapping[str, Any], names: Collection[str], where: str) -> dict[str, Any]: + """Keep only ``names`` from ``data``. + + Lease metadata and other bookkeeping fields are dropped so they never become environment + variables. Fails if none of the expected fields are present. + """ + picked = {k: data[k] for k in names if data.get(k) not in (None, "")} + if not picked: + raise ServerError(f"response from {where} contained no credentials") + return picked diff --git a/src/envbao/engines/approle.py b/src/envbao/engines/approle.py new file mode 100644 index 0000000..2b17111 --- /dev/null +++ b/src/envbao/engines/approle.py @@ -0,0 +1,41 @@ +"""AppRole auth method: fetch a role-id and/or generate a fresh secret-id.""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from envbao.client import BaoClient +from envbao.engines import _common as c + +_OPTIONS = {"mount", "role", "what"} +_WHAT = ("both", "role_id", "secret_id") + + +class ApproleEngine: + """Reads AppRole login material for a role. + + Options: ``role`` (required), ``mount`` (default ``"approle"``), ``what`` (``"both"``, + ``"role_id"`` or ``"secret_id"``, default ``"both"``). Each fetch of a secret-id creates + a new one. + """ + + def validate(self, options: Mapping[str, Any]) -> None: + c.check_options("approle", options, _OPTIONS) + c.get_str("approle", options, "role") + c.get_str("approle", options, "mount", default="approle") + c.get_choice("approle", options, "what", _WHAT, "both") + + def fetch(self, client: BaoClient, options: Mapping[str, Any]) -> dict[str, Any]: + mount = c.get_str("approle", options, "mount", default="approle") + role = c.get_str("approle", options, "role") + what = c.get_choice("approle", options, "what", _WHAT, "both") + base = f"auth/{mount}/role/{role}" + out: dict[str, Any] = {} + if what in ("both", "role_id"): + where = f"{base}/role-id" + out.update(c.pick(c.response_data(client.get(where), where), ("role_id",), where)) + if what in ("both", "secret_id"): + where = f"{base}/secret-id" + out.update(c.pick(c.response_data(client.post(where), where), ("secret_id",), where)) + return out diff --git a/src/envbao/engines/aws.py b/src/envbao/engines/aws.py new file mode 100644 index 0000000..250dafd --- /dev/null +++ b/src/envbao/engines/aws.py @@ -0,0 +1,48 @@ +"""AWS secrets engine (dynamic IAM users or STS credentials).""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from envbao.client import BaoClient +from envbao.engines import _common as c +from envbao.errors import ConfigError + +_OPTIONS = {"mount", "role", "kind", "ttl"} +_FIELDS = ("access_key", "secret_key", "security_token") + + +class AwsEngine: + """Reads AWS credentials for a role. + + Options: ``role`` (required), ``mount`` (default ``"aws"``), ``kind`` (``"creds"`` or + ``"sts"``, default ``"creds"``), ``ttl`` (optional duration string such as ``"15m"``). + Returns ``access_key``, ``secret_key`` and, for STS, ``security_token``. + """ + + def validate(self, options: Mapping[str, Any]) -> None: + c.check_options("aws", options, _OPTIONS) + c.get_str("aws", options, "role") + c.get_str("aws", options, "mount", default="aws") + c.get_choice("aws", options, "kind", ("creds", "sts"), "creds") + ttl = options.get("ttl") + if ttl is not None and (not isinstance(ttl, str) or not ttl): + raise ConfigError("aws option 'ttl' must be a non-empty string such as \"15m\"") + + def cacheable(self, options: Mapping[str, Any]) -> bool: + return True + + def fetch(self, client: BaoClient, options: Mapping[str, Any]) -> dict[str, Any]: + return self.fetch_leased(client, options)[0] + + def fetch_leased( + self, client: BaoClient, options: Mapping[str, Any] + ) -> tuple[dict[str, Any], c.Lease | None]: + mount = c.get_str("aws", options, "mount", default="aws") + role = c.get_str("aws", options, "role") + kind = c.get_choice("aws", options, "kind", ("creds", "sts"), "creds") + ttl = options.get("ttl") + where = f"{mount}/{kind}/{role}" + body = client.get(where, {"ttl": ttl} if ttl else None) + return c.pick(c.response_data(body, where), _FIELDS, where), c.lease_of(body) diff --git a/src/envbao/engines/database.py b/src/envbao/engines/database.py new file mode 100644 index 0000000..48d9889 --- /dev/null +++ b/src/envbao/engines/database.py @@ -0,0 +1,44 @@ +"""Database secrets engine (PostgreSQL, MySQL, ... whatever the mount is configured for).""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from envbao.client import BaoClient +from envbao.engines import _common as c + +_OPTIONS = {"mount", "role", "static"} +_FIELDS = ("username", "password") + + +class DatabaseEngine: + """Reads database credentials for a role. + + Options: ``role`` (required), ``mount`` (default ``"database"``), ``static`` (default + ``false``; read ``static-creds/`` instead of generating dynamic credentials). + Returns ``username`` and ``password``. Dynamic roles create a new database user per fetch. + """ + + def validate(self, options: Mapping[str, Any]) -> None: + c.check_options("database", options, _OPTIONS) + c.get_str("database", options, "role") + c.get_str("database", options, "mount", default="database") + c.get_bool("database", options, "static") + + def cacheable(self, options: Mapping[str, Any]) -> bool: + """Only dynamic roles mint a new credential per fetch.""" + return not c.get_bool("database", options, "static") + + def fetch(self, client: BaoClient, options: Mapping[str, Any]) -> dict[str, Any]: + return self.fetch_leased(client, options)[0] + + def fetch_leased( + self, client: BaoClient, options: Mapping[str, Any] + ) -> tuple[dict[str, Any], c.Lease | None]: + mount = c.get_str("database", options, "mount", default="database") + role = c.get_str("database", options, "role") + kind = "static-creds" if c.get_bool("database", options, "static") else "creds" + where = f"{mount}/{kind}/{role}" + body = client.get(where) + return c.pick(c.response_data(body, where), _FIELDS, where), c.lease_of(body) diff --git a/src/envbao/engines/ssh.py b/src/envbao/engines/ssh.py new file mode 100644 index 0000000..421341f --- /dev/null +++ b/src/envbao/engines/ssh.py @@ -0,0 +1,69 @@ +"""SSH secrets engine: one-time passwords or signed client certificates.""" + +from __future__ import annotations + +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from envbao.client import BaoClient +from envbao.engines import _common as c +from envbao.errors import ConfigError + +_OPTIONS = {"mount", "role", "mode", "ip", "public_key_file", "valid_principals"} +_MAX_KEY_BYTES = 64 * 1024 + + +class SshEngine: + """Generates SSH credentials for a role. + + Options: ``role`` (required), ``mount`` (default ``"ssh"``), ``mode`` (``"otp"`` or + ``"sign"``, default ``"otp"``). + + * ``otp``: requires ``ip``; returns ``key`` (the one-time password), ``username``, ``ip``. + * ``sign``: requires ``public_key_file``; optional ``valid_principals``; returns + ``signed_key`` and ``serial_number``. + """ + + def validate(self, options: Mapping[str, Any]) -> None: + c.check_options("ssh", options, _OPTIONS) + c.get_str("ssh", options, "role") + c.get_str("ssh", options, "mount", default="ssh") + mode = c.get_choice("ssh", options, "mode", ("otp", "sign"), "otp") + if mode == "otp": + c.get_str("ssh", options, "ip") + extra = {"public_key_file", "valid_principals"} & set(options) + else: + c.get_str("ssh", options, "public_key_file") + extra = {"ip"} & set(options) + if extra: + raise ConfigError(f"ssh mode '{mode}' does not accept: {', '.join(sorted(extra))}") + principals = options.get("valid_principals") + if principals is not None and (not isinstance(principals, str) or not principals): + raise ConfigError("ssh option 'valid_principals' must be a comma-separated string") + + def fetch(self, client: BaoClient, options: Mapping[str, Any]) -> dict[str, Any]: + mount = c.get_str("ssh", options, "mount", default="ssh") + role = c.get_str("ssh", options, "role") + mode = c.get_choice("ssh", options, "mode", ("otp", "sign"), "otp") + if mode == "otp": + where = f"{mount}/creds/{role}" + body = client.post(where, {"ip": options["ip"]}) + return c.pick(c.response_data(body, where), ("key", "username", "ip"), where) + + where = f"{mount}/sign/{role}" + request: dict[str, Any] = {"public_key": _read_public_key(str(options["public_key_file"]))} + if options.get("valid_principals"): + request["valid_principals"] = options["valid_principals"] + body = client.post(where, request) + return c.pick(c.response_data(body, where), ("signed_key", "serial_number"), where) + + +def _read_public_key(name: str) -> str: + path = Path(name).expanduser() + try: + if path.stat().st_size > _MAX_KEY_BYTES: + raise ConfigError(f"public key file {path} is unreasonably large") + return path.read_text(encoding="utf-8").strip() + except (OSError, UnicodeDecodeError) as exc: + raise ConfigError(f"cannot read public key file {path}: {exc}") from None diff --git a/src/envbao/resolve.py b/src/envbao/resolve.py index f222c9e..e425cfc 100644 --- a/src/envbao/resolve.py +++ b/src/envbao/resolve.py @@ -6,9 +6,10 @@ import json import logging from typing import Any +from envbao.cache import CredentialCache from envbao.client import BaoClient from envbao.config import Config, Query -from envbao.engines import get_engine +from envbao.engines import CacheableEngine, get_engine from envbao.errors import ConfigError, EnvBaoError, NotFoundError from envbao.render import is_protected, is_valid_name @@ -26,7 +27,12 @@ def validate_queries(config: Config) -> None: """Validate engine-specific options of every query without contacting the server.""" for index, query in enumerate(config.queries, start=1): try: - get_engine(query.engine).validate(query.options) + engine = get_engine(query.engine) + engine.validate(query.options) + if query.cache and not ( + isinstance(engine, CacheableEngine) and engine.cacheable(query.options) + ): + raise ConfigError(f"cache = true is not supported for {query.describe()}") except ConfigError as exc: raise ConfigError(f"query #{index}: {exc}") from None @@ -42,7 +48,12 @@ def _select(raw: dict[str, Any], query: Query) -> dict[str, Any]: return {k: raw[k] for k in query.keys if k in raw} -def run_query(client: BaoClient, query: Query, config: Config) -> dict[str, str]: +def run_query( + client: BaoClient, + query: Query, + config: Config, + cache: CredentialCache | None = None, +) -> dict[str, str]: """Execute one query and return ``{ENV_NAME: value}``. Names that are not valid variable names, or that are protected shell/loader variables @@ -50,7 +61,10 @@ def run_query(client: BaoClient, query: Query, config: Config) -> dict[str, str] """ engine = get_engine(query.engine) try: - raw = engine.fetch(client, query.options) + if query.cache and cache is not None: + raw = cache.get_or_fetch(client, query, config) + else: + raw = engine.fetch(client, query.options) except NotFoundError as exc: if query.on_missing == "error": raise @@ -77,7 +91,9 @@ def run_query(client: BaoClient, query: Query, config: Config) -> dict[str, str] return result -def resolve(client: BaoClient, config: Config) -> dict[str, str]: +def resolve( + client: BaoClient, config: Config, cache: CredentialCache | None = None +) -> dict[str, str]: """Run all queries in order (later queries override earlier ones). All-or-nothing: any non-recoverable error aborts and nothing is returned. @@ -88,7 +104,7 @@ def resolve(client: BaoClient, config: Config) -> dict[str, str]: env: dict[str, str] = {} for query in config.queries: try: - values = run_query(client, query, config) + values = run_query(client, query, config, cache) except EnvBaoError as exc: log.error("query %s failed: %s", query.describe(), exc) raise diff --git a/src/envbao/runner.py b/src/envbao/runner.py index 9e8cdd0..c3b4ae0 100644 --- a/src/envbao/runner.py +++ b/src/envbao/runner.py @@ -23,6 +23,7 @@ from types import FrameType from typing import Any, BinaryIO from urllib.parse import quote +from envbao.cache import CredentialCache from envbao.client import BaoClient from envbao.config import Config, Query from envbao.errors import ConfigError, NotFoundError @@ -59,11 +60,16 @@ def select_queries(config: Config, names: Sequence[str]) -> list[Query]: return selected -def fetch_secrets(client: BaoClient, config: Config, queries: Iterable[Query]) -> dict[str, str]: +def fetch_secrets( + client: BaoClient, + config: Config, + queries: Iterable[Query], + cache: CredentialCache | None = None, +) -> dict[str, str]: """Fetch the given queries. Fails closed: a missing/empty group is an error.""" env: dict[str, str] = {} for query in queries: - values = run_query(client, query, config) + values = run_query(client, query, config, cache) if not values: raise NotFoundError(f"group {query.name!r} produced no variables") env.update(values) diff --git a/tests/conftest.py b/tests/conftest.py index 6a89734..763db45 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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/`` 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) diff --git a/tests/test_cache.py b/tests/test_cache.py new file mode 100644 index 0000000..4972d8c --- /dev/null +++ b/tests/test_cache.py @@ -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 diff --git a/tests/test_client_and_kv.py b/tests/test_client_and_kv.py index b35d59b..416d823 100644 --- a/tests/test_client_and_kv.py +++ b/tests/test_client_and_kv.py @@ -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: diff --git a/tests/test_engines.py b/tests/test_engines.py new file mode 100644 index 0000000..79d1d67 --- /dev/null +++ b/tests/test_engines.py @@ -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),)))