Add 'envbao exec' to run commands with selected secret groups

Fetches only the named groups, injects them into the child environment and
filters secret values (raw, JSON, URL-encoded) from stdout/stderr. Queries
gain an optional 'name'; ENVBAO_CONFIG selects an alternative config.
Includes plan 002.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-16 11:52:24 +01:00
1 parent 877b1ed99e
commit 08bacbc5a8
5 files changed
+627 -15

No files matched your search

+34 -1
View File
@@ -16,10 +16,11 @@ from pathlib import Path
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.errors import EXIT_FAILURE, EXIT_OK, ConfigError, 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.runner import fetch_secrets, run_command, select_queries
from envbao.security import check_config_dir
from envbao.version import get_version
@@ -86,6 +87,29 @@ def build_parser() -> argparse.ArgumentParser:
)
parser.add_argument("-v", "--verbose", action="count", default=0, help="log more to stderr")
parser.add_argument("--version", action=_VersionAction)
sub = parser.add_subparsers(dest="command", metavar="{exec}")
run_p = sub.add_parser(
"exec",
help="run a command with selected secret groups in its environment",
description="Fetch the named groups and run COMMAND with them as environment variables. "
"Output is filtered so secret values are shown as ***.",
usage="envbao [options] exec -q GROUP [-q GROUP ...] [--no-redact] -- COMMAND [ARGS ...]",
)
run_p.add_argument(
"-q",
"--query",
action="append",
default=[],
metavar="GROUP",
help="group name (repeatable)",
)
run_p.add_argument(
"--no-redact",
action="store_true",
help="replace this process with COMMAND (no output filtering; for interactive use)",
)
run_p.add_argument("argv", nargs=argparse.REMAINDER, metavar="-- COMMAND [ARGS ...]")
return parser
@@ -112,6 +136,8 @@ 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.init:
try:
init_config(path)
@@ -133,6 +159,13 @@ def run(args: argparse.Namespace) -> int:
_check(config, client)
return EXIT_OK
if args.command == "exec":
argv = args.argv[1:] if args.argv[:1] == ["--"] else args.argv
queries = select_queries(config, args.query)
secrets = fetch_secrets(client, config, queries)
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)
shell = detect_shell() if args.shell == "auto" else args.shell
output = render(env, shell)
+32 -14
View File
@@ -8,6 +8,8 @@ default.
from __future__ import annotations
import logging
import os
import re
import tomllib
from collections.abc import Mapping
from dataclasses import dataclass, field
@@ -35,7 +37,9 @@ _SERVER_KEYS = {
}
_SECURITY_KEYS = {"allow_protected"}
_TOP_KEYS = {"server", "security", "query"}
_QUERY_COMMON_KEYS = {"engine", "keys", "prefix", "rename", "on_missing"}
_QUERY_COMMON_KEYS = {"engine", "name", "keys", "prefix", "rename", "on_missing"}
_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\Z")
CONFIG_ENV_VAR = "ENVBAO_CONFIG"
@dataclass(frozen=True)
@@ -64,6 +68,7 @@ class Query:
prefix: str = ""
rename: Mapping[str, str] = field(default_factory=dict)
on_missing: str = "warn"
name: str = ""
def describe(self) -> str:
"""Short, secret-free description of this query for logs."""
@@ -81,9 +86,10 @@ class Config:
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 the config path: ``explicit``, ``$ENVBAO_CONFIG`` or ``~/.envbao/config.toml``."""
chosen = explicit or os.environ.get(CONFIG_ENV_VAR)
if chosen:
return Path(chosen).expanduser()
return DEFAULT_DIR.expanduser() / CONFIG_NAME
@@ -163,26 +169,37 @@ def _parse_server(raw: Mapping[str, Any]) -> ServerConfig:
)
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")
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]
return engine
engine = _get_str(raw, "engine", name) or "kv"
keys = _get_str_list(raw, "keys", name)
prefix = _get_str(raw, "prefix", name) or ""
def _parse_query(raw: Any, index: int) -> Query:
name_label = f"query #{index + 1}"
if not isinstance(raw, dict):
raise ConfigError(f"{name_label} must be a table")
engine = _get_str(raw, "engine", name_label) or "kv"
keys = _get_str_list(raw, "keys", name_label)
prefix = _get_str(raw, "prefix", name_label) 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")
raise ConfigError(f"{name_label}.rename must be a table of string to string")
on_missing = _get_str(raw, "on_missing", name) or "warn"
on_missing = _get_str(raw, "on_missing", name_label) or "warn"
if on_missing not in ON_MISSING_CHOICES:
raise ConfigError(f"{name}.on_missing must be one of {', '.join(ON_MISSING_CHOICES)}")
raise ConfigError(f"{name_label}.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}
name = _get_str(raw, "name", name_label) or _default_name(engine, options)
if not _NAME_RE.match(name):
raise ConfigError(f"{name_label}.name {name!r} may only contain letters, digits, . _ -")
return Query(
engine=engine,
options=options,
@@ -190,6 +207,7 @@ def _parse_query(raw: Any, index: int) -> Query:
prefix=prefix,
rename=dict(rename),
on_missing=on_missing,
name=name,
)
+181
View File
@@ -0,0 +1,181 @@
"""Run a command with secrets injected into its environment (``envbao exec``).
The command receives the selected secrets as environment variables. By default its
stdout/stderr are filtered so that the secret values (raw, JSON-escaped and URL-encoded
forms) are replaced with ``***`` before they reach the caller - for example an AI tool's
transcript. This is defence in depth, not a sandbox: a command can still transform a
secret (base64, hashing, splitting) into a form the filter does not recognise.
"""
from __future__ import annotations
import contextlib
import json
import logging
import os
import re
import signal
import subprocess # noqa: S404
import sys
import threading
from collections.abc import Iterable, Mapping, Sequence
from types import FrameType
from typing import Any, BinaryIO
from urllib.parse import quote
from envbao.client import BaoClient
from envbao.config import Config, Query
from envbao.errors import ConfigError, NotFoundError
from envbao.resolve import run_query
log = logging.getLogger("envbao")
MASK = b"***"
MIN_SECRET_LEN = 6
EXIT_NOT_EXECUTABLE = 126
EXIT_NOT_FOUND = 127
_CHUNK = 65536
def select_queries(config: Config, names: Sequence[str]) -> list[Query]:
"""Return the queries called ``names`` (in the order given).
Raises:
ConfigError: for an unknown or ambiguous name, or an empty selection.
"""
if not names:
raise ConfigError("select at least one group with -q/--query")
selected: list[Query] = []
available = sorted({q.name for q in config.queries})
for name in dict.fromkeys(names):
matches = [q for q in config.queries if q.name == name]
if not matches:
raise ConfigError(
f"unknown group {name!r} (available: {', '.join(available) or 'none'})"
)
if len(matches) > 1:
raise ConfigError(f"group name {name!r} is ambiguous; set a unique 'name' on the query")
selected.append(matches[0])
return selected
def fetch_secrets(client: BaoClient, config: Config, queries: Iterable[Query]) -> 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)
if not values:
raise NotFoundError(f"group {query.name!r} produced no variables")
env.update(values)
return env
def _variants(value: str) -> set[bytes]:
forms = {value, json.dumps(value)[1:-1], quote(value, safe=""), quote(value)}
return {f.encode() for f in forms if f}
class Redactor:
"""Streaming replacement of secret values, safe across chunk boundaries."""
def __init__(self, secrets: Iterable[str]) -> None:
needles: set[bytes] = set()
for secret in secrets:
if len(secret) >= MIN_SECRET_LEN:
needles |= _variants(secret)
ordered = sorted(needles, key=len, reverse=True)
self._pattern = re.compile(b"|".join(re.escape(n) for n in ordered)) if ordered else None
self._hold = max((len(n) for n in ordered), default=1) - 1
self._tail = b""
def feed(self, data: bytes) -> bytes:
"""Consume ``data``; return the bytes that are safe to emit now."""
if self._pattern is None:
return data
buf = self._pattern.sub(MASK, self._tail + data)
cut = max(len(buf) - self._hold, 0)
self._tail = buf[cut:]
return buf[:cut]
def flush(self) -> bytes:
"""Return whatever is still held back (call at end of stream)."""
if self._pattern is None:
return b""
out = self._pattern.sub(MASK, self._tail)
self._tail = b""
return out
def _pump(src: BinaryIO, dst: BinaryIO, redactor: Redactor) -> None:
fd = src.fileno()
while chunk := os.read(fd, _CHUNK):
out = redactor.feed(chunk)
if out:
dst.write(out)
dst.flush()
tail = redactor.flush()
if tail:
dst.write(tail)
dst.flush()
def run_command(
argv: Sequence[str],
secrets: Mapping[str, str],
*,
redact: bool = True,
environ: Mapping[str, str] | None = None,
) -> int:
"""Run ``argv`` with ``secrets`` added to its environment and return its exit status."""
if not argv:
raise ConfigError("no command given; usage: envbao exec -q GROUP -- COMMAND [ARGS...]")
env = {**(os.environ if environ is None else environ), **secrets}
log.info("exec: %d variable(s) for command %s", len(secrets), os.path.basename(argv[0]))
if not redact:
for handler in log.handlers: # exec discards buffered output
with contextlib.suppress(OSError, ValueError):
handler.flush()
try:
os.execvpe(argv[0], list(argv), env) # noqa: S606 - replaces this process
except FileNotFoundError:
return EXIT_NOT_FOUND
except PermissionError:
return EXIT_NOT_EXECUTABLE
try:
proc = subprocess.Popen( # noqa: S603
list(argv), env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
except FileNotFoundError:
sys.stderr.write(f"envbao: command not found: {argv[0]}\n")
return EXIT_NOT_FOUND
except PermissionError:
sys.stderr.write(f"envbao: permission denied: {argv[0]}\n")
return EXIT_NOT_EXECUTABLE
def forward(signum: int, _frame: FrameType | None) -> None:
if proc.poll() is None:
proc.send_signal(signum)
old: dict[int, Any] = {s: signal.signal(s, forward) for s in (signal.SIGINT, signal.SIGTERM)}
try:
assert proc.stdout is not None and proc.stderr is not None # noqa: S101
values = list(secrets.values())
threads = [
threading.Thread(
target=_pump, args=(proc.stdout, sys.stdout.buffer, Redactor(values)), daemon=True
),
threading.Thread(
target=_pump, args=(proc.stderr, sys.stderr.buffer, Redactor(values)), daemon=True
),
]
for t in threads:
t.start()
code = proc.wait()
for t in threads:
t.join()
finally:
for sig, handler in old.items():
signal.signal(sig, handler)
return 128 - code if code < 0 else code