From 83cfa7441686b80b00136432360cf1dd129ac9ba Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 16 Oct 2026 10:30:50 +0100 Subject: [PATCH] Add one-off zshrc to OpenBao migration helper Parses literal exports from ~/.zshrc (never sourced), writes them to env/shell/ via the bao CLI with stdin transport, verifies by SHA-256 digest, then creates a read-only policy/token and generates the EnvBao config. Values are never printed, logged or placed in argv. Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 2 + README.md | 1 + docs/migration.md | 44 ++++ scripts/migrate_zshrc.py | 450 ++++++++++++++++++++++++++++++++++++ tests/test_migrate_zshrc.py | 337 +++++++++++++++++++++++++++ 5 files changed, 834 insertions(+) create mode 100644 docs/migration.md create mode 100644 scripts/migrate_zshrc.py create mode 100644 tests/test_migrate_zshrc.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0902224..fec6199 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ All notable changes are documented here. This project follows [Semantic Versioni ## [Unreleased] ### Added +- `scripts/migrate_zshrc.py`: one-off migration of zshrc exports into OpenBao KV (`env/shell/`), + with digest verification and generation of the EnvBao config and a read-only token. - Initial implementation: config loading, strict permission policy, KV v1/v2 engine with auto-detection, safe shell rendering (bash/zsh/sh/fish), `--check` and `--init`, audit logging. - Gitea pipelines for tests and tag-driven releases (linux-amd64, linux-arm64, macos-arm64). diff --git a/README.md b/README.md index 1b1ac83..78a6da5 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ Full reference: [docs/configuration.md](docs/configuration.md). - [Usage](docs/usage.md) - [Configuration reference](docs/configuration.md) - [Security model](docs/security.md) +- [Migrating from ~/.zshrc](docs/migration.md) - [Development](docs/development.md) - [Releasing and CI](docs/releasing.md) - [Plans](docs/plans/) diff --git a/docs/migration.md b/docs/migration.md new file mode 100644 index 0000000..7c5f120 --- /dev/null +++ b/docs/migration.md @@ -0,0 +1,44 @@ +# Migrating secrets from `~/.zshrc` into OpenBao + +`scripts/migrate_zshrc.py` is a one-off helper (stdlib only, not part of the binary). It needs the +`bao` CLI and `BAO_ADDR` / `BAO_TOKEN` in the environment with enough rights to write the target +KV mount and to create a policy and token (e.g. a root or admin token). + +## What it does + +1. **Parses** `~/.zshrc` as text (never sourced). Only column-0 `export NAME=value` lines with + literal values are considered; values needing shell expansion (`$HOME`, `$(...)`, backticks) + are skipped and reported by name. +2. **Groups** variables by name prefix into `/shell/` (`AWS_*` → `aws`, + `PROTON_BRIDGE_*` → `proton`, `GITHUB_*`, `GITEA_*`, `ELASTIC_*`, `PHOTOS_*`, `PKGS_*`, `WIKI_*`, + `YOUTRACK_*`). Toolchain variables (`PATH`, `ZSH`, `LDFLAGS`, `CPPFLAGS`, `NVM_DIR`) and + `BAO_TOKEN` / `BAO_ADDR` are never migrated. Unrecognised names are listed; map them with + `--group NAME=group`. +3. **Writes** each group with `bao kv put` (JSON on stdin, so values never appear in `ps`), + refusing to overwrite an existing secret unless `--force`, then **reads it back and compares + SHA-256 digests**. +4. Creates the read-only policy `envbao-shell`, mints an orphan periodic token (720h) for it, + and writes `~/.envbao/token` and `~/.envbao/config.toml` (0600, directory 0700; any previous + config is saved as `config.toml.bak`), then runs `envbao --check`. + +Values are never printed or logged; `bao` error output is scrubbed of known secrets. + +## Usage + +```sh +uv run python scripts/migrate_zshrc.py # dry run: names and line numbers only +uv run python scripts/migrate_zshrc.py --apply # write, verify, generate EnvBao config +``` + +Options: `--zshrc PATH`, `--mount NAME` (default `env`; must already exist as a KV engine), +`--force`, `--group NAME=group`, `--config-dir DIR`, `--no-check`. + +## Afterwards + +1. Remove the listed line numbers from `~/.zshrc` and add + `command -v envbao >/dev/null && eval "$(envbao)"`. +2. Open a new shell and confirm the variables are present. +3. **Rotate the credentials.** They lived in plaintext, in shell history/backups, and (if you used an + AI assistant on that file) possibly in its transcripts. +4. The generated token period is 720h: renew it (`bao token renew`) or re-run the helper with + `--force` to issue a new one before it lapses. diff --git a/scripts/migrate_zshrc.py b/scripts/migrate_zshrc.py new file mode 100644 index 0000000..39c62ce --- /dev/null +++ b/scripts/migrate_zshrc.py @@ -0,0 +1,450 @@ +"""One-off migration of ``export NAME=value`` secrets from ~/.zshrc into OpenBao. + +Run without arguments for a dry run that lists variable *names* and line numbers only. +With ``--apply`` it will, per service group: + +1. write the variables to ``/shell/`` via the ``bao`` CLI (JSON on stdin), +2. read them back and compare SHA-256 digests, + +and, once everything verified, create a read-only policy and token for EnvBao and write +``~/.envbao/config.toml`` plus ``~/.envbao/token`` (modes 0600; directory 0700). + +``~/.zshrc`` is parsed as text and never sourced. Secret values are never printed, +logged or passed on a command line; they only travel over stdin/stdout pipes. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import shutil +import subprocess # noqa: S404 +import sys +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path + +DEFAULT_MOUNT = "env" +SECRET_PREFIX = "shell" # noqa: S105 - a path, not a credential +POLICY_NAME = "envbao-shell" +TOKEN_PERIOD = "720h" # noqa: S105 - a duration + +#: Shell/toolchain configuration that belongs in the shell startup file, not in OpenBao. +EXCLUDED = frozenset( + { + "PATH", "ZSH", "ZSH_THEME", "LDFLAGS", "CPPFLAGS", "NVM_DIR", "BAO_TOKEN", "BAO_ADDR", + } +) # fmt: skip + +#: Longest prefixes first: ``PROTON_BRIDGE_`` must win over any shorter match. +GROUP_PREFIXES: tuple[tuple[str, str], ...] = ( + ("PROTON_BRIDGE_", "proton"), + ("YOUTRACK_", "youtrack"), + ("ELASTIC_", "elastic"), + ("PHOTOS_", "photos"), + ("GITHUB_", "github"), + ("GITEA_", "gitea"), + ("PKGS_", "pkgs"), + ("WIKI_", "wiki"), + ("AWS_", "aws"), +) + +_EXPORT_RE = re.compile(r"^export[ \t]+([A-Za-z_][A-Za-z0-9_]*)=(.*)$") +_GROUP_RE = re.compile(r"^[a-z][a-z0-9_-]*$") + + +class MigrationError(Exception): + """A fatal, user-presentable problem. Messages never contain secret values.""" + + +@dataclass(frozen=True) +class Entry: + """A literal assignment found in the shell file.""" + + name: str + value: str = "" + lines: tuple[int, ...] = () + + def __repr__(self) -> str: # keep values out of tracebacks and logs + return f"Entry(name={self.name!r}, lines={self.lines})" + + +@dataclass(frozen=True) +class ParseResult: + """Outcome of scanning a shell file.""" + + entries: dict[str, Entry] + skipped_dynamic: dict[str, int] # name -> line (value needs shell expansion) + + +# --------------------------------------------------------------------------------------- +# Parsing +# --------------------------------------------------------------------------------------- + + +def _parse_value(raw: str) -> str | None: + """Return the literal value of the right-hand side, or None if it is not a plain literal.""" + raw = raw.strip() + if raw[:1] == "'": + end = raw.find("'", 1) + if end == -1: + return None + rest = raw[end + 1 :].strip() + return raw[1:end] if not rest or rest.startswith("#") else None + if raw[:1] == '"': + out: list[str] = [] + i = 1 + while i < len(raw): + ch = raw[i] + if ch == "\\" and i + 1 < len(raw) and raw[i + 1] in '"\\$`': + out.append(raw[i + 1]) + i += 2 + continue + if ch in "$`": + return None + if ch == '"': + rest = raw[i + 1 :].strip() + return "".join(out) if not rest or rest.startswith("#") else None + out.append(ch) + i += 1 + return None + # bare word: ends at whitespace; anything needing expansion/quoting is not a literal + match = re.match(r"^(\S*)(?:\s+#.*|\s*)$", raw) + if not match: + return None + word = match.group(1) + if re.search(r"[$`\\'\"(){}*?;&|<>~]", word): + return None + return word + + +def parse_zshrc(text: str) -> ParseResult: + """Extract top-level literal ``export NAME=value`` assignments from ``text``. + + Later assignments override earlier ones; all line numbers are retained so the + caller can report every line that may be deleted. + """ + entries: dict[str, Entry] = {} + dynamic: dict[str, int] = {} + for lineno, line in enumerate(text.splitlines(), start=1): + match = _EXPORT_RE.match(line) + if not match: + continue + name, raw = match.groups() + value = _parse_value(raw) + if value is None: + dynamic[name] = lineno + continue + previous = entries.get(name) + lines = (*previous.lines, lineno) if previous else (lineno,) + entries[name] = Entry(name, value, lines) + dynamic.pop(name, None) + return ParseResult(entries, dynamic) + + +def classify( + entries: Mapping[str, Entry], extra: Mapping[str, str] | None = None +) -> tuple[dict[str, dict[str, Entry]], list[str]]: + """Group entries by service. Returns ``(groups, unmapped_names)``.""" + extra = extra or {} + groups: dict[str, dict[str, Entry]] = {} + unmapped: list[str] = [] + for name, entry in entries.items(): + if name in EXCLUDED: + continue + group = extra.get(name) or next((g for p, g in GROUP_PREFIXES if name.startswith(p)), None) + if group is None: + unmapped.append(name) + continue + groups.setdefault(group, {})[name] = entry + return dict(sorted(groups.items())), sorted(unmapped) + + +# --------------------------------------------------------------------------------------- +# bao CLI wrapper +# --------------------------------------------------------------------------------------- + + +def scrub(text: str, secrets: Sequence[str]) -> str: + """Remove every known secret string from ``text`` before it is shown.""" + for secret in sorted((s for s in secrets if len(s) >= 4), key=len, reverse=True): + text = text.replace(secret, "") + return text + + +class Bao: + """Thin wrapper over the ``bao`` CLI that keeps secrets out of argv and output.""" + + def __init__(self, secrets: Sequence[str], executable: str = "bao") -> None: + self._secrets = list(secrets) + self._exe = executable + + def add_secret(self, value: str) -> None: + self._secrets.append(value) + + def run( + self, *args: str, stdin: str | None = None, check: bool = True + ) -> subprocess.CompletedProcess[str]: + proc = subprocess.run( # noqa: S603 + [self._exe, *args], + input=stdin, + capture_output=True, + text=True, + check=False, + ) + if check and proc.returncode != 0: + detail = scrub(proc.stderr.strip(), self._secrets) + raise MigrationError(f"`bao {' '.join(args[:2])}` failed: {detail or proc.returncode}") + return proc + + +def detect_kv_version(bao: Bao, mount: str) -> int: + """Return the KV engine version (1 or 2) of ``mount``.""" + out = bao.run("read", "-format=json", f"sys/internal/ui/mounts/{mount}").stdout + try: + options = json.loads(out).get("data", {}).get("options") or {} + except ValueError: + raise MigrationError(f"could not parse mount info for '{mount}'") from None + return 2 if str(options.get("version", "1")) == "2" else 1 + + +def read_secret(bao: Bao, mount: str, path: str, version: int) -> dict[str, str] | None: + """Return the stored key/value map, or None if the secret does not exist.""" + proc = bao.run("kv", "get", f"-mount={mount}", "-format=json", path, check=False) + if proc.returncode != 0: + if "No value found" in proc.stderr: + return None + raise MigrationError(f"`bao kv get` failed: {scrub(proc.stderr.strip(), [])}") + data = json.loads(proc.stdout).get("data", {}) + inner = data.get("data") if version == 2 else data + return {k: str(v) for k, v in (inner or {}).items()} + + +def digest(value: str) -> str: + """SHA-256 hex digest of ``value`` (used to compare without showing values).""" + return hashlib.sha256(value.encode()).hexdigest() + + +# --------------------------------------------------------------------------------------- +# Config generation +# --------------------------------------------------------------------------------------- + + +def render_config(address: str, mount: str, groups: Sequence[str], kv_version: int) -> str: + """Return the EnvBao ``config.toml`` text for the migrated groups.""" + lines = [ + "# Generated by scripts/migrate_zshrc.py. Keep this directory owner-only (0700).", + "[server]", + f"address = {json.dumps(address)}", + 'token_file = "~/.envbao/token"', + ] + for group in groups: + lines += [ + "", + "[[query]]", + 'engine = "kv"', + f"mount = {json.dumps(mount)}", + f"path = {json.dumps(f'{SECRET_PREFIX}/{group}')}", + f"kv_version = {kv_version}", + 'on_missing = "warn"', + ] + return "\n".join(lines) + "\n" + + +def policy_text(mount: str, kv_version: int) -> str: + """HCL for the read-only EnvBao policy.""" + data_path = ( + f"{mount}/data/{SECRET_PREFIX}/*" if kv_version == 2 else f"{mount}/{SECRET_PREFIX}/*" + ) + return ( + f'path "{data_path}" {{\n capabilities = ["read"]\n}}\n' + f'path "sys/internal/ui/mounts/{mount}" {{\n capabilities = ["read"]\n}}\n' + 'path "auth/token/lookup-self" {\n capabilities = ["read"]\n}\n' + ) + + +def write_private(path: Path, content: str) -> None: + """Write ``content`` to ``path`` with mode 0600, replacing any existing file.""" + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(content) + os.chmod(path, 0o600) + + +def install_config(config_dir: Path, config_text: str, token: str | None) -> None: + """Create ``config_dir`` (0700), back up any existing config, write config and token.""" + config_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + os.chmod(config_dir, 0o700) + config_path = config_dir / "config.toml" + if config_path.exists(): + backup = config_dir / "config.toml.bak" + shutil.copyfile(config_path, backup) + os.chmod(backup, 0o600) + write_private(config_path, config_text) + if token is not None: + write_private(config_dir / "token", token) + + +# --------------------------------------------------------------------------------------- +# Orchestration +# --------------------------------------------------------------------------------------- + + +def report( + groups: Mapping[str, Mapping[str, Entry]], + unmapped: Sequence[str], + parsed: ParseResult, + out: object, +) -> None: + """Print group -> names/lines (never values).""" + emit = out.write # type: ignore[attr-defined] + for group, members in groups.items(): + emit(f"{SECRET_PREFIX}/{group}\n") + for name, entry in members.items(): + emit(f" {name} (line {', '.join(map(str, entry.lines))})\n") + if unmapped: + emit(f"unmapped (not migrated; use --group NAME=group): {', '.join(unmapped)}\n") + if parsed.skipped_dynamic: + names = ", ".join(f"{n} (line {ln})" for n, ln in sorted(parsed.skipped_dynamic.items())) + emit(f"skipped, value needs shell expansion: {names}\n") + + +def migrate_group( + bao: Bao, mount: str, version: int, group: str, members: Mapping[str, Entry], *, force: bool +) -> None: + """Write one group and verify it by digest. Raises MigrationError on any problem.""" + path = f"{SECRET_PREFIX}/{group}" + if read_secret(bao, mount, path, version) is not None and not force: + raise MigrationError(f"{mount}/{path} already exists; use --force to overwrite") + payload = json.dumps({name: e.value for name, e in members.items()}) + bao.run("kv", "put", f"-mount={mount}", path, "-", stdin=payload) + + stored = read_secret(bao, mount, path, version) or {} + bad = [n for n, e in members.items() if digest(stored.get(n, "")) != digest(e.value)] + if bad: + raise MigrationError(f"verification FAILED for {mount}/{path}: {', '.join(bad)}") + + +def parse_args(argv: Sequence[str] | None) -> argparse.Namespace: + p = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + p.add_argument("--zshrc", type=Path, default=Path("~/.zshrc")) + p.add_argument("--mount", default=DEFAULT_MOUNT, help="KV mount name (default: env)") + p.add_argument("--apply", action="store_true", help="write to OpenBao and create EnvBao config") + p.add_argument("--force", action="store_true", help="overwrite existing shell/ secrets") + p.add_argument("--group", action="append", default=[], metavar="NAME=group") + p.add_argument("--config-dir", type=Path, default=Path("~/.envbao")) + p.add_argument("--no-check", action="store_true", help="skip running `envbao --check`") + return p.parse_args(argv) + + +def _run_check(config_dir: Path) -> bool: + exe = shutil.which("envbao") + cmd = [exe] if exe else [sys.executable, "-m", "envbao"] + env = dict(os.environ) + if not exe: + env["PYTHONPATH"] = str(Path(__file__).resolve().parent.parent / "src") + proc = subprocess.run( # noqa: S603 + [*cmd, "--config", str(config_dir / "config.toml"), "--check"], + capture_output=True, + text=True, + env=env, + check=False, + ) + sys.stderr.write(proc.stderr) + return proc.returncode == 0 + + +def main(argv: Sequence[str] | None = None, environ: Mapping[str, str] | None = None) -> int: + args = parse_args(argv) + environ = os.environ if environ is None else environ + extra: dict[str, str] = {} + for item in args.group: + name, sep, group = item.partition("=") + if not sep or not _GROUP_RE.match(group): + sys.stderr.write(f"error: bad --group {name!r}; expected NAME=group\n") + return 2 + extra[name] = group + + try: + text = args.zshrc.expanduser().read_text(encoding="utf-8", errors="replace") + except OSError as exc: + sys.stderr.write(f"error: cannot read {args.zshrc}: {exc.strerror}\n") + return 1 + parsed = parse_zshrc(text) + groups, unmapped = classify(parsed.entries, extra) + report(groups, unmapped, parsed, sys.stdout) + + if not args.apply: + sys.stdout.write("\nDry run only. Re-run with --apply to write to OpenBao.\n") + return 0 + if not groups: + sys.stderr.write("error: nothing to migrate\n") + return 1 + + address = environ.get("BAO_ADDR", "").rstrip("/") + if not address or not environ.get("BAO_TOKEN"): + sys.stderr.write("error: BAO_ADDR and BAO_TOKEN must be set in the environment\n") + return 1 + secrets = [e.value for g in groups.values() for e in g.values()] + [environ["BAO_TOKEN"]] + bao = Bao(secrets) + + try: + version = detect_kv_version(bao, args.mount) + sys.stdout.write(f"\nmount '{args.mount}' is KV v{version}\n") + for group, members in groups.items(): + migrate_group(bao, args.mount, version, group, members, force=args.force) + sys.stdout.write( + f" OK {args.mount}/{SECRET_PREFIX}/{group} ({len(members)} keys verified)\n" + ) + except MigrationError as exc: + sys.stderr.write(f"error: {exc}\n") + return 1 + + config_dir = args.config_dir.expanduser() + config_text = render_config(address, args.mount, list(groups), version) + token: str | None = None + problem: str | None = None + try: + bao.run("policy", "write", POLICY_NAME, "-", stdin=policy_text(args.mount, version)) + token = bao.run( + "token", "create", f"-policy={POLICY_NAME}", "-orphan", f"-period={TOKEN_PERIOD}", + "-display-name=envbao", "-field=token", + ).stdout.strip() # fmt: skip + bao.add_secret(token) + except MigrationError as exc: + problem = str(exc) + + install_config(config_dir, config_text, token) + sys.stdout.write( + f"wrote {config_dir / 'config.toml'}" + + (f" and {config_dir / 'token'}\n" if token else "\n") + ) + + if problem or not token: + sys.stderr.write( + f"error: secrets were migrated, but the EnvBao token could not be created: {problem}\n" + f" Create a token with policy '{POLICY_NAME}' and save it (mode 0600) to " + f"{config_dir / 'token'}.\n" + ) + return 1 + if not args.no_check and not _run_check(config_dir): + sys.stderr.write("error: `envbao --check` failed\n") + return 1 + + lines = sorted({ln for g in groups.values() for e in g.values() for ln in e.lines}) + sys.stdout.write( + "\nDone. After verifying, remove these lines from your zshrc: " + + ", ".join(map(str, lines)) + + '\nand add: command -v envbao >/dev/null && eval "$(envbao)"\n' + "The old values were exposed in plaintext: rotate them in their services.\n" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_migrate_zshrc.py b/tests/test_migrate_zshrc.py new file mode 100644 index 0000000..ad261ab --- /dev/null +++ b/tests/test_migrate_zshrc.py @@ -0,0 +1,337 @@ +import importlib.util +import json +import os +import stat +import sys +from pathlib import Path + +import pytest + +from envbao.config import load_config + +_spec = importlib.util.spec_from_file_location( + "migrate_zshrc", Path(__file__).parent.parent / "scripts" / "migrate_zshrc.py" +) +assert _spec and _spec.loader +mz = importlib.util.module_from_spec(_spec) +sys.modules["migrate_zshrc"] = mz +_spec.loader.exec_module(mz) + +SECRET_A = "tok-AAAA-secret-value" +SECRET_B = "pa$$word-BBBB" # literal in single quotes below + +ZSHRC = f"""\ +export PATH=$HOME/bin:$PATH +export ZSH="$HOME/.oh-my-zsh" +export AWS_ACCESS_KEY_ID=ffaeb8e5-aaaa +export AWS_SECRET_ACCESS_KEY={SECRET_A} +export GITEA_TOKEN='{SECRET_B}' +export WIKI_USER="old" + export NOT_TOP_LEVEL=x +export WIKI_USER="matt" # trailing comment +export PROTON_BRIDGE_PASS="U_3u-Q" +export PROTON_BRIDGE_HOST="127.0.0.1" +export DYNAMIC=$(cat /etc/hostname) +export BAO_TOKEN="s.admin-token" +export BAO_ADDR=https://vault.example/ +export MYSTERY_VAR=abc +export QUOTED="has \\"escaped\\" quote" +export BROKEN="no end +""" + + +def parsed() -> "mz.ParseResult": + return mz.parse_zshrc(ZSHRC) + + +# ---- parsing -------------------------------------------------------------------------- + + +def test_parse_literals() -> None: + e = parsed().entries + assert e["AWS_SECRET_ACCESS_KEY"].value == SECRET_A + assert e["GITEA_TOKEN"].value == SECRET_B + assert e["WIKI_USER"].value == "matt" + assert e["WIKI_USER"].lines == (6, 8) + assert e["QUOTED"].value == 'has "escaped" quote' + + +def test_parse_ignores_indented_and_non_literals() -> None: + p = parsed() + assert "NOT_TOP_LEVEL" not in p.entries + assert "PATH" not in p.entries and "PATH" in p.skipped_dynamic + assert "DYNAMIC" in p.skipped_dynamic + assert "BROKEN" in p.skipped_dynamic + + +def test_later_literal_clears_dynamic() -> None: + p = mz.parse_zshrc("export A=$X\nexport A=lit\n") + assert p.entries["A"].value == "lit" and "A" not in p.skipped_dynamic + + +@pytest.mark.parametrize( + "raw, expected", + [ + ("abc", "abc"), + ("abc # c", "abc"), + ("'a b'", "a b"), + ('"a b"', "a b"), + ("'x' y", None), + ("'unterminated", None), + ("a=b==", "a=b=="), + ("a$b", None), + ("~/x", None), + ('"\\$HOME"', "$HOME"), + ("", ""), + ], +) +def test_parse_value(raw: str, expected: str | None) -> None: + assert mz._parse_value(raw) == expected # noqa: SLF001 + + +def test_entry_repr_hides_value() -> None: + assert SECRET_A not in repr(parsed().entries["AWS_SECRET_ACCESS_KEY"]) + + +# ---- classification ------------------------------------------------------------------- + + +def test_classify() -> None: + groups, unmapped = mz.classify(parsed().entries) + assert list(groups) == ["aws", "gitea", "proton", "wiki"] + assert set(groups["proton"]) == {"PROTON_BRIDGE_PASS", "PROTON_BRIDGE_HOST"} + assert "BAO_TOKEN" not in str(groups) and "BAO_ADDR" not in str(groups) + assert unmapped == ["MYSTERY_VAR", "QUOTED"] + + +def test_classify_extra_mapping() -> None: + groups, unmapped = mz.classify(parsed().entries, {"MYSTERY_VAR": "misc"}) + assert "misc" in groups and "MYSTERY_VAR" not in unmapped + + +# ---- scrub / helpers ------------------------------------------------------------------ + + +def test_scrub() -> None: + assert mz.scrub("bad abcdef here", ["abcdef", "ab"]) == "bad here" + + +def test_render_config_is_valid_for_envbao(tmp_path: Path) -> None: + text = mz.render_config("https://vault.example", "env", ["aws", "wiki"], 2) + tok = tmp_path / "token" + tok.write_text("t") + tok.chmod(0o600) + cfg = load_config_from_text(tmp_path, text.replace("~/.envbao/token", str(tok))) + assert [q.options["path"] for q in cfg.queries] == ["shell/aws", "shell/wiki"] + assert all(q.options["mount"] == "env" and q.options["kv_version"] == 2 for q in cfg.queries) + assert cfg.server.address == "https://vault.example" + + +def load_config_from_text(directory: Path, text: str): # type: ignore[no-untyped-def] + p = directory / "c.toml" + p.write_text(text) + return load_config(p) + + +def test_policy_text_v1_v2() -> None: + assert 'path "env/data/shell/*"' in mz.policy_text("env", 2) + assert 'path "env/shell/*"' in mz.policy_text("env", 1) + assert "lookup-self" in mz.policy_text("env", 2) + + +def test_install_config_permissions_and_backup(tmp_path: Path) -> None: + d = tmp_path / ".envbao" + d.mkdir(mode=0o755) + (d / "config.toml").write_text("old") + mz.install_config(d, "new", "s.tok") + assert stat.S_IMODE(d.stat().st_mode) == 0o700 + for name in ("config.toml", "config.toml.bak", "token"): + assert stat.S_IMODE((d / name).stat().st_mode) == 0o600 + assert (d / "config.toml.bak").read_text() == "old" + assert (d / "token").read_text() == "s.tok" + + +def test_install_config_without_token(tmp_path: Path) -> None: + mz.install_config(tmp_path / "x", "cfg", None) + assert not (tmp_path / "x" / "token").exists() + + +# ---- end to end with a stub `bao` ----------------------------------------------------- + +STUB = """#!{python} +import json, os, sys +state = os.environ["STUB_DIR"] +args = sys.argv[1:] +stdin = "" if sys.stdin.isatty() else sys.stdin.read() +with open(os.path.join(state, "calls.log"), "a") as fh: + fh.write(json.dumps({{"args": args, "stdin": stdin}}) + "\\n") +ver = os.environ.get("STUB_KV_VERSION", "2") +if args[0] == "read": + print(json.dumps({{"data": {{"options": {{"version": ver}}}}}})) +elif args[:2] == ["kv", "get"]: + f = os.path.join(state, args[-1].replace("/", "_") + ".json") + if not os.path.exists(f): + sys.stderr.write("No value found at " + args[-1]); sys.exit(2) + data = json.load(open(f)) + if os.environ.get("STUB_CORRUPT"): + data[sorted(data)[0]] = "tampered" + print(json.dumps({{"data": {{"data": data}} if ver == "2" else data}})) +elif args[:2] == ["kv", "put"]: + with open(os.path.join(state, args[-2].replace("/", "_") + ".json"), "w") as fh: + fh.write(stdin) +elif args[:2] == ["policy", "write"]: + open(os.path.join(state, "policy.hcl"), "w").write(stdin) +elif args[:2] == ["token", "create"]: + if os.environ.get("STUB_DENY_TOKEN"): + sys.stderr.write("permission denied"); sys.exit(2) + print("s.new-envbao-token") +else: + sys.exit(9) +""" + + +@pytest.fixture +def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> dict[str, Path]: + bin_dir = tmp_path / "bin" + bin_dir.mkdir() + stub = bin_dir / "bao" + stub.write_text(STUB.format(python=sys.executable)) + stub.chmod(0o755) + state = tmp_path / "state" + state.mkdir() + rc = tmp_path / "zshrc" + rc.write_text(ZSHRC) + monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}") + monkeypatch.setenv("STUB_DIR", str(state)) + monkeypatch.setenv("BAO_ADDR", "https://vault.example/") + monkeypatch.setenv("BAO_TOKEN", "s.admin-token") + return {"state": state, "rc": rc, "cfg": tmp_path / ".envbao"} + + +def run(env: dict[str, Path], *extra: str) -> int: + return mz.main( + ["--zshrc", str(env["rc"]), "--config-dir", str(env["cfg"]), "--no-check", *extra] + ) + + +def calls(env: dict[str, Path]) -> list[dict]: + log = env["state"] / "calls.log" + return [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else [] + + +def test_dry_run_prints_names_not_values( + env: dict[str, Path], capsys: pytest.CaptureFixture[str] +) -> None: + assert run(env) == 0 + out = capsys.readouterr() + text = out.out + out.err + assert "AWS_SECRET_ACCESS_KEY (line 4)" in text + assert "Dry run" in text and "needs shell expansion" in text + for secret in (SECRET_A, SECRET_B, "U_3u-Q", "s.admin-token"): + assert secret not in text + assert calls(env) == [] and not env["cfg"].exists() + + +def test_apply_end_to_end(env: dict[str, Path], capsys: pytest.CaptureFixture[str]) -> None: + assert run(env, "--apply") == 0 + out = capsys.readouterr() + text = out.out + out.err + for secret in (SECRET_A, SECRET_B, "U_3u-Q", "s.admin-token", "s.new-envbao-token"): + assert secret not in text + + stored = json.loads((env["state"] / "shell_aws.json").read_text()) + assert stored == {"AWS_ACCESS_KEY_ID": "ffaeb8e5-aaaa", "AWS_SECRET_ACCESS_KEY": SECRET_A} + + # no secret value ever appears in any argv + argv = " ".join(" ".join(c["args"]) for c in calls(env)) + assert SECRET_A not in argv and SECRET_B not in argv and "s.admin" not in argv + + cfg_dir = env["cfg"] + assert stat.S_IMODE((cfg_dir / "token").stat().st_mode) == 0o600 + assert (cfg_dir / "token").read_text() == "s.new-envbao-token" + assert "token = " not in (cfg_dir / "config.toml").read_text() + assert "env/data/shell/*" in (env["state"] / "policy.hcl").read_text() + assert "remove these lines" in text and "rotate" in text + + +def test_generated_config_loads(env: dict[str, Path]) -> None: + assert run(env, "--apply") == 0 + home = env["cfg"].parent + os.environ["HOME"] = str(home) # token_file uses ~ + cfg = load_config(env["cfg"] / "config.toml") + assert cfg.server.token == "s.new-envbao-token" + assert cfg.server.address == "https://vault.example" + assert {q.options["path"] for q in cfg.queries} == { + "shell/aws", "shell/gitea", "shell/proton", "shell/wiki", + } # fmt: skip + + +def test_kv_v1(env: dict[str, Path], monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("STUB_KV_VERSION", "1") + assert run(env, "--apply") == 0 + assert "kv_version = 1" in (env["cfg"] / "config.toml").read_text() + assert 'path "env/shell/*"' in (env["state"] / "policy.hcl").read_text() + + +def test_refuses_to_overwrite_then_force( + env: dict[str, Path], capsys: pytest.CaptureFixture[str] +) -> None: + assert run(env, "--apply") == 0 + capsys.readouterr() + assert run(env, "--apply") == 1 + assert "already exists" in capsys.readouterr().err + assert run(env, "--apply", "--force") == 0 + + +def test_verification_failure( + env: dict[str, Path], monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setenv("STUB_CORRUPT", "1") + assert run(env, "--apply", "--force") == 1 + err = capsys.readouterr().err + assert "verification FAILED" in err and "tampered" not in err + assert not env["cfg"].exists() # no config written when verification fails + + +def test_token_creation_denied( + env: dict[str, Path], monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setenv("STUB_DENY_TOKEN", "1") + assert run(env, "--apply") == 1 + err = capsys.readouterr().err + assert "could not be created" in err and "migrated" in err + assert (env["cfg"] / "config.toml").exists() and not (env["cfg"] / "token").exists() + + +def test_requires_bao_env(env: dict[str, Path], monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("BAO_TOKEN") + assert run(env, "--apply") == 1 + + +def test_bad_group_option(env: dict[str, Path]) -> None: + assert run(env, "--group", "NOEQUALS") == 2 + assert run(env, "--group", "X=Bad Group") == 2 + + +def test_group_option_migrates_unmapped(env: dict[str, Path]) -> None: + assert run(env, "--apply", "--group", "MYSTERY_VAR=misc") == 0 + assert json.loads((env["state"] / "shell_misc.json").read_text()) == {"MYSTERY_VAR": "abc"} + + +def test_missing_zshrc(tmp_path: Path) -> None: + assert mz.main(["--zshrc", str(tmp_path / "nope")]) == 1 + + +def test_nothing_to_migrate(tmp_path: Path, env: dict[str, Path]) -> None: + empty = tmp_path / "empty" + empty.write_text("export PATH=/x\n") + assert mz.main(["--zshrc", str(empty), "--apply"]) == 1 + + +def test_bao_error_is_scrubbed() -> None: + bao = mz.Bao(["supersecretvalue"], executable=sys.executable) + with pytest.raises(mz.MigrationError) as exc: + bao.run( + "-c", "import sys; sys.stderr.write('oops ' + 'supersecret' + 'value'); sys.exit(1)" + ) + assert "supersecretvalue" not in str(exc.value) and "redacted" in str(exc.value)