Initial implementation of EnvBao
test / test (push) Failing after 2s
release / validate (push) Successful in 2s
release / build (linux-amd64, linux-amd64) (push) Successful in 38s
release / build (macos-arm64, macos-arm64) (push) Successful in 45s
release / build (linux-arm64, linux-arm64) (push) Successful in 1m19s
release / release (push) Successful in 15s
test / test (push) Failing after 2s
release / validate (push) Successful in 2s
release / build (linux-amd64, linux-amd64) (push) Successful in 38s
release / build (macos-arm64, macos-arm64) (push) Successful in 45s
release / build (linux-arm64, linux-arm64) (push) Successful in 1m19s
release / release (push) Successful in 15s
Single-binary CLI that injects environment variables from an OpenBao server into the shell via eval "$(envbao)". - Strict permission policy for ~/.envbao (exits 78 if unsafe) - KV v1/v2 engine with auto-detection, pluggable engine registry - Safe quoting for bash/zsh/sh/fish, protected-variable denylist - Audit logging (stderr, private rotating file, syslog); no secrets logged - Gitea pipelines for tests and SemVer-tag releases - PyInstaller spec, docs, BSD-3-Clause licence Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
d5636c46c7
37 files changed
+3234
No files matched your search
@@ -0,0 +1,5 @@
|
||||
"""EnvBao: inject environment variables from an OpenBao server into your shell."""
|
||||
|
||||
from envbao._version import __version__
|
||||
|
||||
__all__ = ["__version__"]
|
||||
@@ -0,0 +1,6 @@
|
||||
import sys
|
||||
|
||||
from envbao.cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Package version. Overwritten from the git tag by the release pipeline."""
|
||||
|
||||
__version__ = "0.0.0.dev0"
|
||||
@@ -0,0 +1,147 @@
|
||||
"""Command line interface.
|
||||
|
||||
Normal use is ``eval "$(envbao)"`` from a shell start-up file. In that mode **stdout
|
||||
carries only shell statements** and is empty on any failure; diagnostics go to stderr and
|
||||
the log. The process exit status tells scripts what went wrong (see ``envbao.errors``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
from envbao import __version__
|
||||
from envbao.client import BaoClient
|
||||
from envbao.config import Config, load_config, resolve_config_path
|
||||
from envbao.errors import EXIT_FAILURE, EXIT_OK, EnvBaoError, PermissionPolicyError
|
||||
from envbao.logging_setup import add_file_logging, setup_stderr_logging
|
||||
from envbao.render import SHELLS, detect_shell, render
|
||||
from envbao.resolve import resolve, validate_queries
|
||||
from envbao.security import check_config_dir
|
||||
|
||||
log = logging.getLogger("envbao")
|
||||
|
||||
CONFIG_TEMPLATE = """\
|
||||
# EnvBao configuration. This file and its directory must be accessible by you only.
|
||||
[server]
|
||||
address = "https://bao.example.com:8200"
|
||||
token = "" # or: token_file = "~/.envbao/token" (mode 0600)
|
||||
# namespace = ""
|
||||
# ca_cert = "/path/to/ca.pem"
|
||||
# timeout = 5
|
||||
|
||||
# One [[query]] table per secret. Later queries override earlier ones.
|
||||
[[query]]
|
||||
engine = "kv"
|
||||
mount = "secret"
|
||||
path = "myapp/prod"
|
||||
# keys = ["DB_URL"]
|
||||
# prefix = "MYAPP_"
|
||||
# rename = { DB_URL = "DATABASE_URL" }
|
||||
# on_missing = "warn" # or "error"
|
||||
"""
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
"""Create the argument parser."""
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="envbao",
|
||||
description="Print shell export statements for secrets stored in OpenBao. "
|
||||
'Use as: eval "$(envbao)"',
|
||||
)
|
||||
parser.add_argument(
|
||||
"--config", metavar="PATH", help="config file (default: ~/.envbao/config.toml)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--shell",
|
||||
choices=("auto", *SHELLS),
|
||||
default="auto",
|
||||
help="output syntax (default: detect from $SHELL)",
|
||||
)
|
||||
mode = parser.add_mutually_exclusive_group()
|
||||
mode.add_argument(
|
||||
"--check",
|
||||
action="store_true",
|
||||
help="verify permissions, config and token, then exit without printing variables",
|
||||
)
|
||||
mode.add_argument(
|
||||
"--init",
|
||||
action="store_true",
|
||||
help="create ~/.envbao with safe permissions and a template config.toml",
|
||||
)
|
||||
parser.add_argument("-v", "--verbose", action="count", default=0, help="log more to stderr")
|
||||
parser.add_argument("--version", action="version", version=f"envbao {__version__}")
|
||||
return parser
|
||||
|
||||
|
||||
def init_config(path: Path) -> None:
|
||||
"""Create the config directory (0700) and a template config (0600) at ``path``."""
|
||||
directory = path.parent
|
||||
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
os.chmod(directory, 0o700)
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||
fh.write(CONFIG_TEMPLATE)
|
||||
|
||||
|
||||
def _check(config: Config, client: BaoClient) -> None:
|
||||
info = client.get("auth/token/lookup-self").get("data", {})
|
||||
ttl = info.get("ttl")
|
||||
sys.stderr.write(
|
||||
f"envbao: OK - permissions safe, {len(config.queries)} query(ies) valid, "
|
||||
f"token accepted{f' (ttl {ttl}s)' if ttl is not None else ''}\n"
|
||||
)
|
||||
|
||||
|
||||
def run(args: argparse.Namespace) -> int:
|
||||
"""Execute the requested action and return the exit status."""
|
||||
path = resolve_config_path(args.config)
|
||||
|
||||
if args.init:
|
||||
try:
|
||||
init_config(path)
|
||||
except FileExistsError:
|
||||
sys.stderr.write(f"envbao: {path} already exists; not overwriting\n")
|
||||
return EXIT_FAILURE
|
||||
sys.stderr.write(f"envbao: created {path}; edit it to add your server and token\n")
|
||||
return EXIT_OK
|
||||
|
||||
# Permissions first: nothing in the directory is read or logged to until it is safe.
|
||||
check_config_dir(path.parent)
|
||||
add_file_logging(path.parent)
|
||||
|
||||
config = load_config(path)
|
||||
validate_queries(config)
|
||||
client = BaoClient(config.server)
|
||||
|
||||
if args.check:
|
||||
_check(config, client)
|
||||
return EXIT_OK
|
||||
|
||||
env = resolve(client, config)
|
||||
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)
|
||||
sys.stdout.write(output)
|
||||
return EXIT_OK
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
"""Program entry point; returns the process exit status."""
|
||||
args = build_parser().parse_args(argv)
|
||||
setup_stderr_logging(args.verbose)
|
||||
try:
|
||||
return run(args)
|
||||
except PermissionPolicyError as exc:
|
||||
return exc.exit_code # already logged at CRITICAL by the security check
|
||||
except EnvBaoError as exc:
|
||||
log.error("%s", exc)
|
||||
return exc.exit_code
|
||||
except Exception as exc: # last resort: never dump a traceback that could hold secrets
|
||||
log.critical("unexpected %s", type(exc).__name__)
|
||||
log.debug("details", exc_info=True)
|
||||
return EXIT_FAILURE
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Minimal OpenBao HTTP client built on the standard library.
|
||||
|
||||
Security properties:
|
||||
|
||||
* TLS certificate and hostname verification are always on (optionally against a custom CA).
|
||||
* ``http://`` is only accepted for loopback addresses unless ``allow_insecure_http`` is set.
|
||||
* Redirects are never followed, so the token cannot be forwarded to another host.
|
||||
* Error messages contain the HTTP status and request path only, never the token or bodies.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import logging
|
||||
import ssl
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode, urlsplit
|
||||
|
||||
from envbao.config import ServerConfig
|
||||
from envbao.errors import AuthError, ConfigError, NotFoundError, ServerError
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_API_PREFIX = "/v1/"
|
||||
_MAX_RESPONSE_BYTES = 8 * 1024 * 1024
|
||||
|
||||
|
||||
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
||||
return None
|
||||
|
||||
|
||||
def _is_loopback(host: str) -> bool:
|
||||
if host == "localhost":
|
||||
return True
|
||||
try:
|
||||
return ipaddress.ip_address(host).is_loopback
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def validate_address(address: str, *, allow_insecure_http: bool) -> str:
|
||||
"""Return the normalised base URL, enforcing the transport-security policy.
|
||||
|
||||
Raises:
|
||||
ConfigError: for unsupported schemes or plain HTTP to a non-loopback host.
|
||||
"""
|
||||
parts = urlsplit(address)
|
||||
if parts.scheme not in ("http", "https") or not parts.hostname:
|
||||
raise ConfigError("server.address must be an http(s) URL such as https://bao:8200")
|
||||
if parts.username or parts.password:
|
||||
raise ConfigError("server.address must not contain credentials")
|
||||
if parts.scheme == "http" and not _is_loopback(parts.hostname):
|
||||
if not allow_insecure_http:
|
||||
raise ConfigError(
|
||||
"refusing plain http:// to a non-loopback host; use https or set "
|
||||
"server.allow_insecure_http = true"
|
||||
)
|
||||
log.warning(
|
||||
"using insecure http:// transport to %s; the token is sent in clear", parts.netloc
|
||||
)
|
||||
return f"{parts.scheme}://{parts.netloc}"
|
||||
|
||||
|
||||
class BaoClient:
|
||||
"""Authenticated read-only access to the OpenBao HTTP API."""
|
||||
|
||||
def __init__(self, server: ServerConfig) -> None:
|
||||
self._base = validate_address(
|
||||
server.address, allow_insecure_http=server.allow_insecure_http
|
||||
)
|
||||
self._token = server.token
|
||||
self._namespace = server.namespace
|
||||
self._timeout = server.timeout
|
||||
handlers: list[urllib.request.BaseHandler] = [_NoRedirect()]
|
||||
if self._base.startswith("https://"):
|
||||
try:
|
||||
ctx = ssl.create_default_context(
|
||||
cafile=str(server.ca_cert) if server.ca_cert else None
|
||||
)
|
||||
except (OSError, ssl.SSLError) as exc:
|
||||
raise ConfigError(f"cannot load server.ca_cert: {exc}") from None
|
||||
handlers.append(urllib.request.HTTPSHandler(context=ctx))
|
||||
self._opener = urllib.request.build_opener(*handlers)
|
||||
|
||||
def get(self, path: str, params: dict[str, str] | None = None) -> dict[str, Any]:
|
||||
"""GET ``/v1/<path>`` and return the decoded JSON object.
|
||||
|
||||
Raises:
|
||||
AuthError: HTTP 401/403.
|
||||
NotFoundError: HTTP 404.
|
||||
ServerError: any other failure (network, TLS, 5xx, malformed response).
|
||||
"""
|
||||
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
|
||||
|
||||
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)
|
||||
except urllib.error.HTTPError as exc:
|
||||
exc.close()
|
||||
if exc.code in (401, 403):
|
||||
raise AuthError(f"access denied (HTTP {exc.code}) for {shown}") from None
|
||||
if exc.code == 404:
|
||||
raise NotFoundError(f"not found: {shown}") from None
|
||||
raise ServerError(f"server returned HTTP {exc.code} for {shown}") from None
|
||||
except (urllib.error.URLError, OSError, TimeoutError) as exc:
|
||||
reason = getattr(exc, "reason", exc)
|
||||
raise ServerError(f"cannot reach {self._base}: {reason}") from None
|
||||
|
||||
if len(body) > _MAX_RESPONSE_BYTES:
|
||||
raise ServerError(f"response for {shown} exceeds size limit")
|
||||
try:
|
||||
decoded = json.loads(body)
|
||||
except ValueError:
|
||||
raise ServerError(f"response for {shown} is not valid JSON") from None
|
||||
if not isinstance(decoded, dict):
|
||||
raise ServerError(f"unexpected response shape for {shown}")
|
||||
return decoded
|
||||
@@ -0,0 +1,232 @@
|
||||
"""Loading and validation of ``config.toml``.
|
||||
|
||||
The parser is deliberately strict: unknown keys and wrongly typed values are rejected so
|
||||
that typos (for example in a security-relevant option) never silently fall back to a
|
||||
default.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import tomllib
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from envbao.errors import ConfigError
|
||||
from envbao.security import check_path
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_DIR = Path("~/.envbao")
|
||||
CONFIG_NAME = "config.toml"
|
||||
DEFAULT_TIMEOUT = 5.0
|
||||
ON_MISSING_CHOICES = ("warn", "error")
|
||||
|
||||
_SERVER_KEYS = {
|
||||
"address",
|
||||
"token",
|
||||
"token_file",
|
||||
"namespace",
|
||||
"ca_cert",
|
||||
"timeout",
|
||||
"allow_insecure_http",
|
||||
}
|
||||
_SECURITY_KEYS = {"allow_protected"}
|
||||
_TOP_KEYS = {"server", "security", "query"}
|
||||
_QUERY_COMMON_KEYS = {"engine", "keys", "prefix", "rename", "on_missing"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ServerConfig:
|
||||
"""Connection settings for the OpenBao server."""
|
||||
|
||||
address: str
|
||||
token: str = field(repr=False) # never show the token in reprs/tracebacks
|
||||
namespace: str | None = None
|
||||
ca_cert: Path | None = None
|
||||
timeout: float = DEFAULT_TIMEOUT
|
||||
allow_insecure_http: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Query:
|
||||
"""One secret source and how its keys map to environment variables.
|
||||
|
||||
``options`` holds the engine-specific settings (e.g. ``mount``/``path`` for ``kv``);
|
||||
they are validated by the engine itself.
|
||||
"""
|
||||
|
||||
engine: str
|
||||
options: Mapping[str, Any]
|
||||
keys: tuple[str, ...] | None = None
|
||||
prefix: str = ""
|
||||
rename: Mapping[str, str] = field(default_factory=dict)
|
||||
on_missing: str = "warn"
|
||||
|
||||
def describe(self) -> str:
|
||||
"""Short, secret-free description of this query for logs."""
|
||||
opts = " ".join(f"{k}={v}" for k, v in self.options.items())
|
||||
return f"{self.engine}({opts})"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Config:
|
||||
"""Fully validated configuration."""
|
||||
|
||||
server: ServerConfig
|
||||
queries: tuple[Query, ...]
|
||||
allow_protected: frozenset[str] = frozenset()
|
||||
|
||||
|
||||
def resolve_config_path(explicit: str | None) -> Path:
|
||||
"""Return the config file path: ``explicit`` if given, else ``~/.envbao/config.toml``."""
|
||||
if explicit:
|
||||
return Path(explicit).expanduser()
|
||||
return DEFAULT_DIR.expanduser() / CONFIG_NAME
|
||||
|
||||
|
||||
def _require_table(value: Any, name: str) -> Mapping[str, Any]:
|
||||
if not isinstance(value, dict):
|
||||
raise ConfigError(f"[{name}] must be a table")
|
||||
return value
|
||||
|
||||
|
||||
def _reject_unknown(table: Mapping[str, Any], allowed: set[str], name: str) -> None:
|
||||
unknown = sorted(set(table) - allowed)
|
||||
if unknown:
|
||||
raise ConfigError(f"unknown key(s) in {name}: {', '.join(unknown)}")
|
||||
|
||||
|
||||
def _get_str(table: Mapping[str, Any], key: str, name: str) -> str | None:
|
||||
value = table.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, str):
|
||||
raise ConfigError(f"{name}.{key} must be a string")
|
||||
return value
|
||||
|
||||
|
||||
def _get_str_list(table: Mapping[str, Any], key: str, name: str) -> list[str] | None:
|
||||
value = table.get(key)
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, list) or not all(isinstance(v, str) for v in value):
|
||||
raise ConfigError(f"{name}.{key} must be a list of strings")
|
||||
return list(value)
|
||||
|
||||
|
||||
def _read_token_file(path_str: str) -> str:
|
||||
path = Path(path_str).expanduser()
|
||||
# The token file may live outside ~/.envbao, so it is checked on its own as well.
|
||||
check_path(path, expect_dir=False)
|
||||
try:
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
except (OSError, UnicodeDecodeError) as exc:
|
||||
raise ConfigError(f"cannot read token_file {path}: {exc}") from None
|
||||
|
||||
|
||||
def _parse_server(raw: Mapping[str, Any]) -> ServerConfig:
|
||||
table = _require_table(raw, "server")
|
||||
_reject_unknown(table, _SERVER_KEYS, "[server]")
|
||||
|
||||
address = _get_str(table, "address", "server")
|
||||
if not address:
|
||||
raise ConfigError("server.address is required")
|
||||
|
||||
token = _get_str(table, "token", "server")
|
||||
token_file = _get_str(table, "token_file", "server")
|
||||
if token and token_file:
|
||||
raise ConfigError("set only one of server.token and server.token_file")
|
||||
if token_file:
|
||||
token = _read_token_file(token_file)
|
||||
if not token:
|
||||
raise ConfigError("a token is required: set server.token or server.token_file")
|
||||
|
||||
timeout = table.get("timeout", DEFAULT_TIMEOUT)
|
||||
if isinstance(timeout, bool) or not isinstance(timeout, int | float) or timeout <= 0:
|
||||
raise ConfigError("server.timeout must be a positive number")
|
||||
|
||||
allow_http = table.get("allow_insecure_http", False)
|
||||
if not isinstance(allow_http, bool):
|
||||
raise ConfigError("server.allow_insecure_http must be a boolean")
|
||||
|
||||
ca_cert = _get_str(table, "ca_cert", "server")
|
||||
return ServerConfig(
|
||||
address=address,
|
||||
token=token,
|
||||
namespace=_get_str(table, "namespace", "server") or None,
|
||||
ca_cert=Path(ca_cert).expanduser() if ca_cert else None,
|
||||
timeout=float(timeout),
|
||||
allow_insecure_http=allow_http,
|
||||
)
|
||||
|
||||
|
||||
def _parse_query(raw: Any, index: int) -> Query:
|
||||
name = f"query #{index + 1}"
|
||||
if not isinstance(raw, dict):
|
||||
raise ConfigError(f"{name} must be a table")
|
||||
|
||||
engine = _get_str(raw, "engine", name) or "kv"
|
||||
keys = _get_str_list(raw, "keys", name)
|
||||
prefix = _get_str(raw, "prefix", name) or ""
|
||||
|
||||
rename = raw.get("rename", {})
|
||||
if not isinstance(rename, dict) or not all(
|
||||
isinstance(k, str) and isinstance(v, str) for k, v in rename.items()
|
||||
):
|
||||
raise ConfigError(f"{name}.rename must be a table of string to string")
|
||||
|
||||
on_missing = _get_str(raw, "on_missing", name) or "warn"
|
||||
if on_missing not in ON_MISSING_CHOICES:
|
||||
raise ConfigError(f"{name}.on_missing must be one of {', '.join(ON_MISSING_CHOICES)}")
|
||||
|
||||
options = {k: v for k, v in raw.items() if k not in _QUERY_COMMON_KEYS}
|
||||
return Query(
|
||||
engine=engine,
|
||||
options=options,
|
||||
keys=tuple(keys) if keys is not None else None,
|
||||
prefix=prefix,
|
||||
rename=dict(rename),
|
||||
on_missing=on_missing,
|
||||
)
|
||||
|
||||
|
||||
def parse_config(data: Mapping[str, Any]) -> Config:
|
||||
"""Validate parsed TOML ``data`` and build a :class:`Config`."""
|
||||
_reject_unknown(data, _TOP_KEYS, "config file")
|
||||
if "server" not in data:
|
||||
raise ConfigError("missing [server] table")
|
||||
server = _parse_server(data["server"])
|
||||
|
||||
queries_raw = data.get("query", [])
|
||||
if not isinstance(queries_raw, list):
|
||||
raise ConfigError("queries must be declared with [[query]] tables")
|
||||
queries = tuple(_parse_query(q, i) for i, q in enumerate(queries_raw))
|
||||
|
||||
security = _require_table(data.get("security", {}), "security")
|
||||
_reject_unknown(security, _SECURITY_KEYS, "[security]")
|
||||
allow_protected = _get_str_list(security, "allow_protected", "security") or []
|
||||
|
||||
return Config(server=server, queries=queries, allow_protected=frozenset(allow_protected))
|
||||
|
||||
|
||||
def load_config(path: Path) -> Config:
|
||||
"""Read and validate the config file at ``path``.
|
||||
|
||||
The caller is responsible for having checked file permissions first.
|
||||
|
||||
Raises:
|
||||
ConfigError: if the file is missing, unparsable or invalid.
|
||||
"""
|
||||
try:
|
||||
with path.open("rb") as fh:
|
||||
data = tomllib.load(fh)
|
||||
except FileNotFoundError:
|
||||
raise ConfigError(f"config file not found: {path}") from None
|
||||
except tomllib.TOMLDecodeError as exc:
|
||||
raise ConfigError(f"invalid TOML in {path}: {exc}") from None
|
||||
except OSError as exc:
|
||||
raise ConfigError(f"cannot read {path}: {exc.strerror}") from None
|
||||
return parse_config(data)
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Secret engines.
|
||||
|
||||
An engine turns the engine-specific options of a ``[[query]]`` into a flat mapping of
|
||||
names to values. Filtering (``keys``), ``prefix`` and ``rename`` are applied centrally in
|
||||
:mod:`envbao.resolve`, so adding a new credential engine only requires a new module that
|
||||
implements :class:`Engine` and an entry in :data:`ENGINES`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Protocol
|
||||
|
||||
from envbao.client import BaoClient
|
||||
from envbao.engines import kv
|
||||
from envbao.errors import ConfigError
|
||||
|
||||
|
||||
class Engine(Protocol):
|
||||
"""Interface every secret engine implements."""
|
||||
|
||||
def validate(self, options: Mapping[str, Any]) -> None:
|
||||
"""Raise :class:`~envbao.errors.ConfigError` if ``options`` are invalid."""
|
||||
|
||||
def fetch(self, client: BaoClient, options: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""Return the raw name -> value mapping.
|
||||
|
||||
Raises:
|
||||
NotFoundError: if the secret does not exist.
|
||||
"""
|
||||
|
||||
|
||||
ENGINES: dict[str, Engine] = {"kv": kv.KvEngine()}
|
||||
|
||||
|
||||
def get_engine(name: str) -> Engine:
|
||||
"""Look up an engine by name, raising :class:`ConfigError` if unknown."""
|
||||
try:
|
||||
return ENGINES[name]
|
||||
except KeyError:
|
||||
known = ", ".join(sorted(ENGINES))
|
||||
raise ConfigError(f"unknown engine {name!r} (available: {known})") from None
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Key/Value secrets engine (versions 1 and 2) with automatic version detection."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from envbao.client import BaoClient
|
||||
from envbao.errors import ConfigError, EnvBaoError, NotFoundError, ServerError
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_OPTIONS = {"mount", "path", "kv_version"}
|
||||
|
||||
|
||||
class KvEngine:
|
||||
"""Reads one secret from a KV v1 or v2 mount.
|
||||
|
||||
Options: ``mount`` (required), ``path`` (required), ``kv_version`` (``1``, ``2`` or
|
||||
``"auto"``, default ``"auto"``).
|
||||
"""
|
||||
|
||||
def validate(self, options: Mapping[str, Any]) -> None:
|
||||
unknown = sorted(set(options) - _OPTIONS)
|
||||
if unknown:
|
||||
raise ConfigError(f"unknown option(s) for kv engine: {', '.join(unknown)}")
|
||||
for key in ("mount", "path"):
|
||||
value = options.get(key)
|
||||
if not isinstance(value, str) or not value.strip("/"):
|
||||
raise ConfigError(f"kv query requires a non-empty string '{key}'")
|
||||
version = options.get("kv_version", "auto")
|
||||
if version not in (1, 2, "auto"):
|
||||
raise ConfigError('kv_version must be 1, 2 or "auto"')
|
||||
|
||||
def fetch(self, client: BaoClient, options: Mapping[str, Any]) -> dict[str, Any]:
|
||||
mount = str(options["mount"]).strip("/")
|
||||
path = str(options["path"]).strip("/")
|
||||
version = options.get("kv_version", "auto")
|
||||
if version == "auto":
|
||||
version = detect_version(client, mount)
|
||||
|
||||
if version == 2:
|
||||
body = client.get(f"{mount}/data/{path}")
|
||||
data = body.get("data", {}).get("data")
|
||||
else:
|
||||
body = client.get(f"{mount}/{path}")
|
||||
data = body.get("data")
|
||||
|
||||
if data is None: # e.g. a soft-deleted KV v2 version
|
||||
raise NotFoundError(f"no data at {mount}/{path}")
|
||||
if not isinstance(data, dict):
|
||||
raise ServerError(f"unexpected data shape at {mount}/{path}")
|
||||
return data
|
||||
|
||||
|
||||
def detect_version(client: BaoClient, mount: str) -> int:
|
||||
"""Return the KV version (1 or 2) of ``mount`` via ``sys/internal/ui/mounts``."""
|
||||
try:
|
||||
body = client.get(f"sys/internal/ui/mounts/{mount}")
|
||||
except EnvBaoError as exc:
|
||||
raise type(exc)(
|
||||
f"could not detect KV version of mount '{mount}' ({exc}); "
|
||||
"set kv_version = 1 or 2 on the query to skip detection"
|
||||
) from None
|
||||
options = body.get("data", {}).get("options") or {}
|
||||
version = str(options.get("version", "1")) or "1"
|
||||
log.debug("mount %s detected as KV v%s", mount, version)
|
||||
return 2 if version == "2" else 1
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Exception hierarchy and process exit codes.
|
||||
|
||||
Every error EnvBao raises deliberately derives from :class:`EnvBaoError` and carries the
|
||||
exit code the CLI should terminate with. Messages must never contain secrets (tokens or
|
||||
secret values).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
EXIT_OK = 0
|
||||
EXIT_FAILURE = 1
|
||||
EXIT_USAGE = 2 # argparse default
|
||||
EXIT_UNAVAILABLE = 69 # server unreachable / unexpected server response (EX_UNAVAILABLE)
|
||||
EXIT_AUTH = 77 # token rejected (EX_NOPERM)
|
||||
EXIT_CONFIG = 78 # bad config or unsafe file permissions (EX_CONFIG)
|
||||
|
||||
|
||||
class EnvBaoError(Exception):
|
||||
"""Base class for all expected EnvBao failures."""
|
||||
|
||||
exit_code = EXIT_FAILURE
|
||||
|
||||
|
||||
class ConfigError(EnvBaoError):
|
||||
"""The configuration file is missing, malformed or invalid."""
|
||||
|
||||
exit_code = EXIT_CONFIG
|
||||
|
||||
|
||||
class PermissionPolicyError(EnvBaoError):
|
||||
"""A file or directory under the EnvBao config directory has unsafe permissions."""
|
||||
|
||||
exit_code = EXIT_CONFIG
|
||||
|
||||
|
||||
class ServerError(EnvBaoError):
|
||||
"""The OpenBao server could not be reached or returned an unexpected response."""
|
||||
|
||||
exit_code = EXIT_UNAVAILABLE
|
||||
|
||||
|
||||
class AuthError(ServerError):
|
||||
"""The OpenBao server rejected the token (HTTP 401/403)."""
|
||||
|
||||
exit_code = EXIT_AUTH
|
||||
|
||||
|
||||
class NotFoundError(ServerError):
|
||||
"""The requested path does not exist (HTTP 404)."""
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Logging configuration.
|
||||
|
||||
Logs never contain tokens or secret values; only paths, variable names and outcomes.
|
||||
Records go to stderr (so stdout stays clean for ``eval``), to ``<config dir>/envbao.log``
|
||||
(mode 0600, rotated) once the directory has passed the permission check, and best-effort
|
||||
to the system log for auditing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
LOG_NAME = "envbao.log"
|
||||
_FORMAT = "%(asctime)s %(levelname)s envbao[%(process)d]: %(message)s"
|
||||
_SYSLOG_FORMAT = "envbao[%(process)d]: %(levelname)s %(message)s"
|
||||
_SYSLOG_SOCKETS = ("/dev/log", "/var/run/syslog")
|
||||
|
||||
|
||||
class _PrivateRotatingFileHandler(logging.handlers.RotatingFileHandler):
|
||||
"""Rotating handler that always creates files with mode 0600."""
|
||||
|
||||
def _open(self): # type: ignore[no-untyped-def]
|
||||
fd = os.open(self.baseFilename, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
||||
return os.fdopen(fd, self.mode, encoding=self.encoding)
|
||||
|
||||
|
||||
def setup_stderr_logging(verbosity: int = 0) -> None:
|
||||
"""Configure the root ``envbao`` logger with a stderr handler (and best-effort syslog)."""
|
||||
logger = logging.getLogger("envbao")
|
||||
logger.handlers.clear()
|
||||
logger.propagate = False
|
||||
logger.setLevel(logging.DEBUG)
|
||||
|
||||
stderr = logging.StreamHandler(sys.stderr)
|
||||
stderr.setLevel(
|
||||
logging.DEBUG if verbosity >= 2 else logging.INFO if verbosity else logging.WARNING
|
||||
)
|
||||
stderr.setFormatter(logging.Formatter("envbao: %(levelname)s: %(message)s"))
|
||||
logger.addHandler(stderr)
|
||||
|
||||
for sock in _SYSLOG_SOCKETS:
|
||||
if os.path.exists(sock):
|
||||
try:
|
||||
syslog = logging.handlers.SysLogHandler(address=sock)
|
||||
except OSError:
|
||||
continue
|
||||
syslog.setLevel(logging.WARNING)
|
||||
syslog.setFormatter(logging.Formatter(_SYSLOG_FORMAT))
|
||||
logger.addHandler(syslog)
|
||||
break
|
||||
|
||||
|
||||
def add_file_logging(directory: Path) -> None:
|
||||
"""Also log INFO and above to ``directory/envbao.log``. Call only after the permission check."""
|
||||
try:
|
||||
handler = _PrivateRotatingFileHandler(
|
||||
directory / LOG_NAME, maxBytes=256 * 1024, backupCount=3, encoding="utf-8"
|
||||
)
|
||||
except OSError as exc:
|
||||
logging.getLogger("envbao").warning("cannot open log file: %s", exc.strerror)
|
||||
return
|
||||
handler.setLevel(logging.INFO)
|
||||
handler.setFormatter(logging.Formatter(_FORMAT))
|
||||
logging.getLogger("envbao").addHandler(handler)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Rendering of environment variables as shell statements.
|
||||
|
||||
Variable names are validated against a strict pattern and values are always quoted, so
|
||||
that a secret value can never be interpreted as shell syntax by ``eval``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shlex
|
||||
from collections.abc import Mapping
|
||||
|
||||
from envbao.errors import ConfigError
|
||||
|
||||
SHELLS = ("bash", "zsh", "sh", "fish")
|
||||
_NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")
|
||||
|
||||
#: Variables that change how the shell or dynamic loader behaves. A compromised or
|
||||
#: misconfigured secret store must not be able to set these, so they are refused unless
|
||||
#: listed in ``[security] allow_protected``.
|
||||
PROTECTED = frozenset(
|
||||
{
|
||||
"PATH", "IFS", "SHELL", "HOME", "USER", "LOGNAME", "ENV", "BASH_ENV", "CDPATH",
|
||||
"PROMPT_COMMAND", "PS1", "PS2", "PS4", "SHELLOPTS", "BASHOPTS", "FPATH", "ZDOTDIR",
|
||||
"LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT", "PYTHONPATH", "PYTHONSTARTUP",
|
||||
"PERL5OPT", "NODE_OPTIONS", "RUBYOPT",
|
||||
}
|
||||
) # fmt: skip
|
||||
_PROTECTED_PREFIXES = ("DYLD_", "BASH_FUNC_", "LD_")
|
||||
|
||||
|
||||
def is_valid_name(name: str) -> bool:
|
||||
"""Return True if ``name`` is a legal POSIX environment variable name."""
|
||||
return bool(_NAME_RE.match(name))
|
||||
|
||||
|
||||
def is_protected(name: str) -> bool:
|
||||
"""Return True if ``name`` is a shell/loader control variable."""
|
||||
return name in PROTECTED or name.startswith(_PROTECTED_PREFIXES)
|
||||
|
||||
|
||||
def detect_shell(environ: Mapping[str, str] | None = None) -> str:
|
||||
"""Guess the output dialect from ``$SHELL``; defaults to ``sh`` syntax."""
|
||||
shell = os.path.basename((environ or os.environ).get("SHELL", ""))
|
||||
return shell if shell in SHELLS else "sh"
|
||||
|
||||
|
||||
def _fish_quote(value: str) -> str:
|
||||
return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"
|
||||
|
||||
|
||||
def render(env: Mapping[str, str], shell: str = "sh") -> str:
|
||||
"""Return one export statement per variable, newline separated.
|
||||
|
||||
Raises:
|
||||
ConfigError: for an invalid name, a value containing NUL, or an unknown shell.
|
||||
"""
|
||||
if shell not in SHELLS:
|
||||
raise ConfigError(f"unsupported shell {shell!r}")
|
||||
lines: list[str] = []
|
||||
for name, value in env.items():
|
||||
if not is_valid_name(name):
|
||||
raise ConfigError(f"invalid environment variable name {name!r}")
|
||||
if "\x00" in value:
|
||||
raise ConfigError(f"value for {name} contains a NUL byte")
|
||||
if shell == "fish":
|
||||
lines.append(f"set -gx {name} {_fish_quote(value)}")
|
||||
else:
|
||||
lines.append(f"export {name}={shlex.quote(value)}")
|
||||
return "\n".join(lines) + ("\n" if lines else "")
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Run the configured queries and build the final environment mapping."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from envbao.client import BaoClient
|
||||
from envbao.config import Config, Query
|
||||
from envbao.engines import get_engine
|
||||
from envbao.errors import ConfigError, EnvBaoError, NotFoundError
|
||||
from envbao.render import is_protected, is_valid_name
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def stringify(value: Any) -> str:
|
||||
"""Convert a secret value to the string placed in the environment."""
|
||||
if isinstance(value, str):
|
||||
return value
|
||||
return json.dumps(value, separators=(",", ":"))
|
||||
|
||||
|
||||
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)
|
||||
except ConfigError as exc:
|
||||
raise ConfigError(f"query #{index}: {exc}") from None
|
||||
|
||||
|
||||
def _select(raw: dict[str, Any], query: Query) -> dict[str, Any]:
|
||||
if query.keys is None:
|
||||
return raw
|
||||
missing = [k for k in query.keys if k not in raw]
|
||||
for key in missing:
|
||||
log.warning("key %r not present in %s", key, query.describe())
|
||||
if missing and query.on_missing == "error":
|
||||
raise NotFoundError(f"required key(s) missing from {query.describe()}")
|
||||
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]:
|
||||
"""Execute one query and return ``{ENV_NAME: value}``.
|
||||
|
||||
Names that are not valid variable names, or that are protected shell/loader variables
|
||||
(unless allowed in ``[security] allow_protected``), are skipped and logged.
|
||||
"""
|
||||
engine = get_engine(query.engine)
|
||||
try:
|
||||
raw = engine.fetch(client, query.options)
|
||||
except NotFoundError as exc:
|
||||
if query.on_missing == "error":
|
||||
raise
|
||||
log.warning("%s: %s", query.describe(), exc)
|
||||
return {}
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for key, value in _select(raw, query).items():
|
||||
name = query.rename.get(key, key)
|
||||
name = f"{query.prefix}{name}"
|
||||
if not is_valid_name(name):
|
||||
log.warning("skipping %r from %s: not a valid variable name", name, query.describe())
|
||||
continue
|
||||
if is_protected(name) and name not in config.allow_protected:
|
||||
log.error(
|
||||
"refusing to set protected variable %s from %s "
|
||||
"(add it to [security] allow_protected to permit)",
|
||||
name,
|
||||
query.describe(),
|
||||
)
|
||||
continue
|
||||
result[name] = stringify(value)
|
||||
log.info("%s: %d variable(s)", query.describe(), len(result))
|
||||
return result
|
||||
|
||||
|
||||
def resolve(client: BaoClient, config: Config) -> 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.
|
||||
|
||||
Raises:
|
||||
EnvBaoError: on the first fatal failure.
|
||||
"""
|
||||
env: dict[str, str] = {}
|
||||
for query in config.queries:
|
||||
try:
|
||||
values = run_query(client, query, config)
|
||||
except EnvBaoError as exc:
|
||||
log.error("query %s failed: %s", query.describe(), exc)
|
||||
raise
|
||||
for name in values:
|
||||
if name in env:
|
||||
log.warning("%s overridden by %s", name, query.describe())
|
||||
env.update(values)
|
||||
return env
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Filesystem permission policy for the EnvBao configuration directory.
|
||||
|
||||
The directory holds an API token, so EnvBao refuses to run unless everything in it is
|
||||
readable and writable by the current user only. Symlinks are rejected outright to avoid
|
||||
being tricked into reading (or trusting the permissions of) a file elsewhere.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import stat
|
||||
from pathlib import Path
|
||||
|
||||
from envbao.errors import PermissionPolicyError
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
_GROUP_OTHER_BITS = stat.S_IRWXG | stat.S_IRWXO
|
||||
|
||||
|
||||
def _check(path: Path, *, expect_dir: bool) -> None:
|
||||
"""Verify ``path`` is a non-symlink owned by the current user with no group/other access.
|
||||
|
||||
Raises:
|
||||
PermissionPolicyError: if any check fails.
|
||||
"""
|
||||
try:
|
||||
st = os.lstat(path)
|
||||
except FileNotFoundError:
|
||||
raise PermissionPolicyError(f"{path} does not exist") from None
|
||||
except OSError as exc:
|
||||
raise PermissionPolicyError(f"cannot stat {path}: {exc.strerror}") from None
|
||||
|
||||
if stat.S_ISLNK(st.st_mode):
|
||||
raise PermissionPolicyError(f"{path} is a symbolic link; refusing to follow it")
|
||||
if expect_dir and not stat.S_ISDIR(st.st_mode):
|
||||
raise PermissionPolicyError(f"{path} is not a directory")
|
||||
if not expect_dir and not (stat.S_ISREG(st.st_mode) or stat.S_ISDIR(st.st_mode)):
|
||||
raise PermissionPolicyError(f"{path} is not a regular file or directory")
|
||||
if st.st_uid != os.geteuid():
|
||||
raise PermissionPolicyError(f"{path} is not owned by the current user")
|
||||
|
||||
mode = stat.S_IMODE(st.st_mode)
|
||||
if mode & _GROUP_OTHER_BITS:
|
||||
want = "0700" if stat.S_ISDIR(st.st_mode) else "0600"
|
||||
raise PermissionPolicyError(
|
||||
f"{path} has mode {mode:04o}; it must be accessible by the owner only "
|
||||
f"(fix with: chmod {want} '{path}')"
|
||||
)
|
||||
|
||||
|
||||
def check_path(path: Path, *, expect_dir: bool) -> None:
|
||||
"""Check a single path against the policy, logging any violation at CRITICAL.
|
||||
|
||||
Raises:
|
||||
PermissionPolicyError: if any check fails.
|
||||
"""
|
||||
try:
|
||||
_check(path, expect_dir=expect_dir)
|
||||
except PermissionPolicyError as exc:
|
||||
log.critical("permission policy violation: %s", exc)
|
||||
raise
|
||||
|
||||
|
||||
def check_config_dir(directory: Path) -> None:
|
||||
"""Check ``directory`` and everything beneath it against the permission policy.
|
||||
|
||||
Raises:
|
||||
PermissionPolicyError: on the first violation found. The violation is also logged
|
||||
at CRITICAL level for auditing.
|
||||
"""
|
||||
try:
|
||||
_check(directory, expect_dir=True)
|
||||
for root, dirs, files in os.walk(directory, followlinks=False):
|
||||
for name in (*dirs, *files):
|
||||
_check(Path(root) / name, expect_dir=False)
|
||||
except PermissionPolicyError as exc:
|
||||
log.critical("permission policy violation: %s", exc)
|
||||
raise
|
||||
Reference in new issue
Block a user