From 08bacbc5a86e324d9653611e5dadd12371637100 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 16 Oct 2026 11:52:24 +0100 Subject: [PATCH] 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 --- docs/plans/002-claude-access-and-packaging.md | 56 +++ src/envbao/cli.py | 35 +- src/envbao/config.py | 46 ++- src/envbao/runner.py | 181 ++++++++++ tests/test_runner.py | 324 ++++++++++++++++++ 5 files changed, 627 insertions(+), 15 deletions(-) create mode 100644 docs/plans/002-claude-access-and-packaging.md create mode 100644 src/envbao/runner.py create mode 100644 tests/test_runner.py diff --git a/docs/plans/002-claude-access-and-packaging.md b/docs/plans/002-claude-access-and-packaging.md new file mode 100644 index 0000000..3d55df4 --- /dev/null +++ b/docs/plans/002-claude-access-and-packaging.md @@ -0,0 +1,56 @@ +# Let Claude use OpenBao credentials via `envbao exec`, plus faster startup + +## Context +Credentials now live in OpenBao (`env/shell/`). The user wants Claude Code to be able to use them. Findings: +- Going through the `envbao` binary is fine functionally, but the PyInstaller **onefile** binary re-extracts itself on every call (~1.4 s measured, also paid on every shell start via `.zshrc`). +- Letting Claude run `bao kv get` or inherit the shell env puts every secret value into the transcript. This session already shows the risk: `BAO_TOKEN` in the shell env is a **root** token, visible to any Claude command. +- Chosen model: a run-with-secrets wrapper. Claude names the groups it needs; `envbao exec` fetches only those and runs the command with them in its environment; output is redacted so values never reach the transcript. Claude gets its **own narrow token**, not the root/shell one. + +User choices: access via `envbao exec` wrapper; all nine groups allowed (gitea, github, youtrack, wiki, pkgs, elastic, photos, aws, proton — aws/proton flagged as highest-sensitivity, can be narrowed later by one policy edit); switch release to onedir for startup time. + +## Step 0 (first action once approved) +Copy this plan verbatim to the repo as `docs/plans/002-claude-access-and-packaging.md` (plan mode only allows writing the plan file; the user wants all plans kept in `docs/plans/`) and include it in the first commit. + +## 1. `envbao exec` (new subcommand) +- `envbao [--config PATH] exec -q GROUP [-q GROUP …] [--no-redact] -- CMD [ARGS…]` (also `--all` is deliberately **not** provided). +- Config: add optional `name` to `[[query]]` (default = last path segment, e.g. `shell/gitea` → `gitea`); names must be unique (validated in `config.py`). `-q` selects queries by name; unknown name → exit 78 with list of valid names. +- Reuses `resolve.run_query` / `BaoClient` / protected-variable filtering (`src/envbao/resolve.py`), same permission check (`security.check_config_dir`), fail-closed (no command run if any selected query fails). +- Execution: build `env = os.environ | secrets`; run the child with `subprocess.Popen`, inherit stdin, pipe stdout/stderr through a **redactor** that replaces every secret value (len ≥ 6) with `***`, handling matches split across chunk boundaries via a rolling buffer; forward SIGINT/SIGTERM; propagate the child's exit code (127 if not found). `--no-redact` uses `os.execvpe` (exact exec, TTY-friendly) for interactive humans. +- Audit log (`envbao.log`/syslog): groups requested, `argv[0]` only (never arguments), exit status. Never values. +- Files: `src/envbao/cli.py` (subparser), new `src/envbao/runner.py` (env build, redactor, process handling), `src/envbao/config.py` (`name`), `tests/test_runner.py`, `tests/test_cli.py`. + +## 2. Claude-specific credentials (provisioning script) +New `scripts/setup_claude_access.py` (uses the admin `BAO_TOKEN` once, like `migrate_zshrc.py`; reuse its `Bao` wrapper, `write_private`, `install_config`, `policy_text` patterns): +- Policy `envbao-claude`: read on `env/data/shell/` for each allowed group + `auth/token/lookup-self` (+ `sys/internal/ui/mounts/env`). +- Token: orphan, periodic 720h, `display-name=envbao-claude`, written to `~/.envbao/claude-token` (0600); never printed. +- `~/.envbao/claude.toml` (0600) with the nine named queries pointing at that token file; existing files backed up, never overwritten without `--force`. +- Reports whether an OpenBao audit device is enabled (`bao audit list`) and says how to enable one if not (does **not** enable it unasked). +- Optionally merges into `~/.claude/settings.json` (backup first, JSON merge, shown as a diff before writing): `env.ENVBAO_CONFIG=~/.envbao/claude.toml` (new env var honoured by `resolve_config_path`), `permissions.allow: ["Bash(envbao exec:*)"]`, `permissions.deny: ["Bash(bao:*)", "Read(~/.envbao/**)", "Read(~/.zshrc)"]`. +- Tests with the stub-`bao` approach from `tests/test_migrate_zshrc.py`. + +## 3. Startup time: PyInstaller onedir +- `envbao.spec`: switch to `COLLECT` (onedir; `exclude_binaries=True`), output `dist/envbao/`. +- `release.yml` / `test.yml`: smoke-test `dist/envbao/envbao --version`; package `envbao--.tar.gz` (directory `envbao/`), checksum those; release assets become tarballs. +- `scripts/install.sh` (new, POSIX sh): verify checksum if `SHA256SUMS` present, extract to `~/.local/lib/envbao/`, symlink `~/.local/bin/envbao` → `~/.local/lib/envbao/envbao`, clear macOS quarantine flag, print `envbao --version`. (This is where the symlink the user asked about earlier actually belongs.) +- Verify startup drops well below the current 1.4 s (target ≲0.3 s). + +## 3b. Native packages (so no folders need moving by hand) +The onedir build is a folder, so ship installable packages that place it and create the `envbao` symlink themselves: +- **macOS `.pkg`** (built on the `macos-arm64` runner with `pkgbuild --root … --identifier dev.daubney.envbao --version --install-location /usr/local/lib/envbao`, plus a `postinstall` script that symlinks `/usr/local/bin/envbao` → `/usr/local/lib/envbao/envbao` and clears the quarantine flag). Unsigned/not notarised; docs note `sudo installer -pkg … -target /` (avoids the Gatekeeper prompt) or right-click → Open. Uninstall script `scripts/packaging/uninstall-macos.sh`. +- **Debian/Ubuntu/Raspberry Pi OS `.deb`** (built with `dpkg-deb --build` from a staged tree, no extra tooling): files in `/opt/envbao/`, symlink `/usr/bin/envbao`, `DEBIAN/control` (`Package: envbao`, `Version` from the tag with `-` prerelease mapped to `~`, `Architecture: amd64|arm64`, `Depends: libc6`, maintainer, description), `postrm` removes nothing outside the package. Built on `linux-amd64` (Debian/Ubuntu x86-64) and `linux-arm64` (Ubuntu arm64 and **64-bit** Raspberry Pi OS). 32-bit Raspberry Pi OS (`armhf`) is **not** covered — would need an armv7 runner; documented as unsupported. +- glibc compatibility: Linux builds link to the build host's glibc; document the minimum (build on the oldest Debian/Ubuntu runner, ideally bookworm/22.04) in `docs/releasing.md`. +- New `scripts/packaging/` (`build_deb.sh`, `build_pkg.sh`, `postinstall`, `control.in`) with tests that stage the tree and inspect it (`dpkg-deb -c`/`--info` where available; `pkgutil --payload-files` on macOS; otherwise unit-test the generated control/postinstall text and the version mapping function). +- `release.yml` matrix produces per target: `envbao__amd64.deb`, `envbao__arm64.deb`, `envbao--macos-arm64.pkg`, plus the generic `.tar.gz` + `scripts/install.sh` for other systems; one `SHA256SUMS` covers all. +- README Install section leads with: `sudo dpkg -i envbao__.deb` / `sudo installer -pkg envbao--macos-arm64.pkg -target /`. + +## 4. Docs & hygiene +- New `docs/claude.md` (model, setup, how Claude should call it, redaction limits: a command can still exfiltrate a secret by transforming it, e.g. base64 — treat as defence in depth, not a sandbox); update `docs/security.md`, `docs/configuration.md` (`name`, `ENVBAO_CONFIG`), `docs/usage.md` (`exec`), README install section (tarball + `install.sh`), `docs/releasing.md`, CHANGELOG. +- Recommend (and print in the setup script output) removing the root `BAO_TOKEN`/`BAO_ADDR` exports from `~/.zshrc` (lines ≈2930–2931) so Claude and every child process stop inheriting a root token. Not edited automatically. +- Next release: tag `v0.2.0` after merging (tagging/pushing only when the user says so). + +## Verification +1. `uv run pytest --cov` (≥90%), ruff, mypy. Redactor tests: value split across chunks, multiple secrets, stderr, binary output, short values not redacted. +2. `envbao exec -q gitea -- sh -c 'echo $GITEA_TOKEN'` prints `***`; `-- sh -c 'test -n "$GITEA_TOKEN"'` exits 0; unknown group exits 78 with no command run; exit codes propagate. +3. Run setup script; confirm `bao token lookup` on the Claude token shows only `envbao-claude` policy and that it is denied `env/data/shell/` and `sys/policies`. +4. Build onedir locally; `time dist/envbao/envbao --version`; build the `.pkg` locally and inspect the payload (`pkgutil --payload-files`); build a `.deb` locally via `dpkg-deb` if available (else in a Debian container) and check `--info`/`-c`; install via `install.sh` into a temp prefix. Pipeline run on tag `v0.2.0` produces all assets (checked after the user approves tagging/pushing). +5. From a Claude session with the new settings, `envbao exec -q youtrack -- curl …` works and the transcript contains no secret value; `bao kv get …` is denied by permissions. diff --git a/src/envbao/cli.py b/src/envbao/cli.py index 1144fb1..cdac5a8 100644 --- a/src/envbao/cli.py +++ b/src/envbao/cli.py @@ -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) diff --git a/src/envbao/config.py b/src/envbao/config.py index fe2c9d8..b5d872c 100644 --- a/src/envbao/config.py +++ b/src/envbao/config.py @@ -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, ) diff --git a/src/envbao/runner.py b/src/envbao/runner.py new file mode 100644 index 0000000..9e8cdd0 --- /dev/null +++ b/src/envbao/runner.py @@ -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 diff --git a/tests/test_runner.py b/tests/test_runner.py new file mode 100644 index 0000000..2fdce33 --- /dev/null +++ b/tests/test_runner.py @@ -0,0 +1,324 @@ +import os +import sys +from pathlib import Path + +import pytest + +from envbao.cli import main +from envbao.config import Config, Query, ServerConfig, parse_config, resolve_config_path +from envbao.errors import EXIT_CONFIG, EXIT_UNAVAILABLE, ConfigError +from envbao.runner import MASK, Redactor, run_command, select_queries + +from .conftest import TOKEN, FakeBao, write_config + +SECRET = "sup3r-secret-value" + + +def drain(r: Redactor, chunks: list[bytes]) -> bytes: + return b"".join(r.feed(c) for c in chunks) + r.flush() + + +# ---- Redactor ------------------------------------------------------------------------- + + +def test_redacts_simple() -> None: + assert drain(Redactor([SECRET]), [f"a {SECRET} b".encode()]) == b"a *** b" + + +def test_redacts_across_chunk_boundary_every_split() -> None: + data = f"x{SECRET}y{SECRET}z".encode() + for i in range(1, len(data)): + out = drain(Redactor([SECRET]), [data[:i], data[i:]]) + assert out == b"x***y***z", i + + +def test_redacts_byte_at_a_time() -> None: + data = f"pre {SECRET} post".encode() + assert drain(Redactor([SECRET]), [bytes([b]) for b in data]) == b"pre *** post" + + +def test_never_emits_partial_secret_early() -> None: + r = Redactor([SECRET]) + emitted = r.feed(SECRET[:-3].encode()) + assert emitted == b"" # held back until we know + + +def test_json_and_url_forms() -> None: + secret = 'pa"ss/word+1' + out = drain(Redactor([secret]), [b'{"k":"pa\\"ss/word+1"} pa%22ss%2Fword%2B1 pa"ss/word+1']) + assert b"word" not in out and out.count(MASK) == 3 + + +def test_longest_match_wins() -> None: + out = drain(Redactor(["abcdef", "abcdefghij"]), [b"abcdefghij"]) + assert out == b"***" + + +def test_short_values_not_redacted() -> None: + assert drain(Redactor(["abc", "1143"]), [b"port 1143 abc"]) == b"port 1143 abc" + + +def test_no_secrets_passthrough() -> None: + r = Redactor([]) + assert r.feed(b"hello") == b"hello" and r.flush() == b"" + + +def test_binary_safe() -> None: + data = b"\xff\x00" + SECRET.encode() + b"\x80" + assert drain(Redactor([SECRET]), [data]) == b"\xff\x00***\x80" + + +# ---- run_command ---------------------------------------------------------------------- + + +def py(code: str) -> list[str]: + return [sys.executable, "-c", code] + + +def test_child_sees_secret_but_output_is_masked(capfdbinary: pytest.CaptureFixture[bytes]) -> None: + code = "import os,sys; print(os.environ['TOK']); print(os.environ['TOK'], file=sys.stderr)" + assert run_command(py(code), {"TOK": SECRET}) == 0 + out, err = capfdbinary.readouterr() + assert out == b"***\n" and err == b"***\n" + + +def test_child_can_use_secret(capfdbinary: pytest.CaptureFixture[bytes]) -> None: + code = "import os,sys; sys.exit(0 if os.environ['TOK']=='" + SECRET + "' else 3)" + assert run_command(py(code), {"TOK": SECRET}) == 0 + + +def test_exit_code_propagates() -> None: + assert run_command(py("raise SystemExit(7)"), {}) == 7 + + +def test_signal_exit_code() -> None: + assert run_command(py("import os,signal; os.kill(os.getpid(), signal.SIGTERM)"), {}) == 143 + + +def test_environment_is_inherited_and_overridden() -> None: + code = "import os,sys; sys.exit(int(os.environ['A'])+int(os.environ['B']))" + assert run_command(py(code), {"B": "2"}, environ={"A": "1", "B": "9"}) == 3 + + +def test_command_not_found(capsys: pytest.CaptureFixture[str]) -> None: + assert run_command(["/nonexistent/cmd"], {}) == 127 + assert "not found" in capsys.readouterr().err + + +def test_not_executable(tmp_path: Path) -> None: + f = tmp_path / "f" + f.write_text("x") + assert run_command([str(f)], {}) == 126 + + +def test_empty_command() -> None: + with pytest.raises(ConfigError, match="no command"): + run_command([], {}) + + +def test_no_redact_uses_execvpe(monkeypatch: pytest.MonkeyPatch) -> None: + seen: dict[str, object] = {} + + def fake(file: str, args: list[str], env: dict[str, str]) -> None: + seen.update(file=file, args=args, tok=env["TOK"]) + raise FileNotFoundError + + monkeypatch.setattr(os, "execvpe", fake) + assert run_command(["echo", "hi"], {"TOK": SECRET}, redact=False) == 127 + assert seen == {"file": "echo", "args": ["echo", "hi"], "tok": SECRET} + + +# ---- select_queries / config ---------------------------------------------------------- + + +def cfg(*queries: Query) -> Config: + return Config(ServerConfig("https://b", "t"), queries) + + +def q(name: str, path: str = "p") -> Query: + return Query("kv", {"mount": "env", "path": path}, name=name) + + +def test_select_in_order_and_dedup() -> None: + c = cfg(q("a"), q("b"), q("c")) + assert [x.name for x in select_queries(c, ["c", "a", "c"])] == ["c", "a"] + + +def test_select_unknown_lists_available() -> None: + with pytest.raises(ConfigError, match=r"unknown group 'zzz' \(available: a, b\)"): + select_queries(cfg(q("a"), q("b")), ["zzz"]) + + +def test_select_ambiguous() -> None: + with pytest.raises(ConfigError, match="ambiguous"): + select_queries(cfg(q("a"), q("a", "other")), ["a"]) + + +def test_select_requires_names() -> None: + with pytest.raises(ConfigError, match="at least one"): + select_queries(cfg(q("a")), []) + + +def test_default_and_explicit_query_names() -> None: + c = parse_config( + { + "server": {"address": "https://b", "token": "t"}, + "query": [ + {"mount": "env", "path": "shell/gitea"}, + {"mount": "env", "path": "x/y", "name": "custom"}, + {"engine": "other"}, + ], + } + ) + assert [x.name for x in c.queries] == ["gitea", "custom", "other"] + + +def test_bad_query_name() -> None: + with pytest.raises(ConfigError, match="name"): + parse_config( + { + "server": {"address": "https://b", "token": "t"}, + "query": [{"mount": "m", "path": "p", "name": "bad name!"}], + } + ) + + +def test_envbao_config_env_var(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + monkeypatch.setenv("ENVBAO_CONFIG", str(tmp_path / "claude.toml")) + assert resolve_config_path(None) == tmp_path / "claude.toml" + assert resolve_config_path(str(tmp_path / "x.toml")) == tmp_path / "x.toml" + + +# ---- CLI exec ------------------------------------------------------------------------- + + +def exec_conf(fake: FakeBao) -> str: + return f""" +[server] +address = "{fake.url}" +token = "{TOKEN}" + +[[query]] +mount = "secret" +path = "shell/gitea" +kv_version = 2 + +[[query]] +mount = "secret" +path = "shell/wiki" +kv_version = 2 + +[[query]] +mount = "secret" +path = "shell/empty" +kv_version = 2 +""" + + +@pytest.fixture +def exec_cfg(fake_bao: FakeBao, config_dir: Path) -> Path: + fake_bao.routes["/v1/secret/data/shell/gitea"] = ( + 200, + {"data": {"data": {"GITEA_TOKEN": SECRET}}}, + ) + fake_bao.routes["/v1/secret/data/shell/wiki"] = ( + 200, + {"data": {"data": {"WIKI_PASS": "another-secret-1"}}}, + ) + return write_config(config_dir, exec_conf(fake_bao)) + + +def test_exec_masks_and_exits(exec_cfg: Path, capfdbinary: pytest.CaptureFixture[bytes]) -> None: + code = "import os; print('t=' + os.environ['GITEA_TOKEN']); raise SystemExit(4)" + rc = main(["--config", str(exec_cfg), "exec", "-q", "gitea", "--", sys.executable, "-c", code]) + assert rc == 4 + assert capfdbinary.readouterr().out == b"t=***\n" + + +def test_exec_multiple_groups(exec_cfg: Path) -> None: + code = ( + "import os,sys; " + "sys.exit(0 if 'GITEA_TOKEN' in os.environ and 'WIKI_PASS' in os.environ else 9)" + ) + argv = [ + "--config", + str(exec_cfg), + "exec", + "-q", + "gitea", + "-q", + "wiki", + "--", + sys.executable, + "-c", + code, + ] + assert main(argv) == 0 + + +def test_exec_only_selected_group_is_exposed( + exec_cfg: Path, fake_bao: FakeBao, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.delenv("WIKI_PASS", raising=False) # may be set in the developer's shell + code = "import os,sys; sys.exit(0 if 'WIKI_PASS' not in os.environ else 9)" + assert ( + main(["--config", str(exec_cfg), "exec", "-q", "gitea", "--", sys.executable, "-c", code]) + == 0 + ) + assert all("wiki" not in p for p, _ in fake_bao.requests) + + +def test_exec_unknown_group_runs_nothing( + exec_cfg: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + marker = tmp_path / "ran" + code = f"open({str(marker)!r}, 'w')" + rc = main(["--config", str(exec_cfg), "exec", "-q", "nope", "--", sys.executable, "-c", code]) + assert rc == EXIT_CONFIG and not marker.exists() + assert "available: empty, gitea, wiki" in capsys.readouterr().err + + +def test_exec_failed_fetch_runs_nothing(exec_cfg: Path, tmp_path: Path) -> None: + marker = tmp_path / "ran" + code = f"open({str(marker)!r}, 'w')" + rc = main(["--config", str(exec_cfg), "exec", "-q", "empty", "--", sys.executable, "-c", code]) + assert rc == 0 or rc == EXIT_UNAVAILABLE + assert not marker.exists() + + +def test_exec_requires_group_and_command(exec_cfg: Path) -> None: + assert main(["--config", str(exec_cfg), "exec", "--", "true"]) == EXIT_CONFIG + assert main(["--config", str(exec_cfg), "exec", "-q", "gitea"]) == EXIT_CONFIG + + +def test_exec_insecure_permissions(exec_cfg: Path, fake_bao: FakeBao) -> None: + exec_cfg.chmod(0o644) + assert main(["--config", str(exec_cfg), "exec", "-q", "gitea", "--", "true"]) == EXIT_CONFIG + assert fake_bao.requests == [] + + +def test_exec_rejects_check(exec_cfg: Path) -> None: + assert ( + main(["--config", str(exec_cfg), "--check", "exec", "-q", "gitea", "--", "true"]) + == EXIT_CONFIG + ) + + +def test_audit_log_has_no_values_or_args(exec_cfg: Path) -> None: + main( + [ + "--config", + str(exec_cfg), + "exec", + "-q", + "gitea", + "--", + sys.executable, + "-c", + "pass", + "--flag-arg", + ] + ) + text = (exec_cfg.parent / "envbao.log").read_text() + assert "groups gitea" in text and "python" in text.lower() + assert SECRET not in text and "--flag-arg" not in text