From 952fa2ce63e3a4d995c732b08a9f986d21715786 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 16 Oct 2026 11:57:47 +0100 Subject: [PATCH] Add Claude access setup, onedir build and native packages - scripts/setup_claude_access.py: narrow envbao-claude policy/token and an exec_only claude.toml; optional merge of Claude Code settings - [security] exec_only refuses plain export mode and --no-redact - PyInstaller onedir build (~0.06s start-up vs ~1.4s onefile) - macOS .pkg, Debian/Ubuntu/Raspberry Pi OS .deb (pure-Python builder), tarball + scripts/install.sh; release pipeline updated - docs: claude-access, install matrix, releasing, usage, security Co-Authored-By: Claude Sonnet 5.5 --- .gitea/workflows/release.yml | 30 ++-- .gitea/workflows/test.yml | 3 +- CHANGELOG.md | 9 ++ README.md | 34 ++-- docs/claude-access.md | 72 +++++++++ docs/configuration.md | 4 +- docs/development.md | 13 +- docs/releasing.md | 20 ++- docs/security.md | 8 +- docs/usage.md | 13 ++ envbao.spec | 15 +- pyproject.toml | 2 +- scripts/install.sh | 45 ++++++ scripts/packaging/build_deb.py | 228 +++++++++++++++++++++++++++ scripts/packaging/build_pkg.sh | 28 ++++ scripts/packaging/uninstall-macos.sh | 7 + scripts/setup_claude_access.py | 210 ++++++++++++++++++++++++ src/envbao/cli.py | 4 + src/envbao/config.py | 14 +- tests/test_packaging.py | 213 +++++++++++++++++++++++++ tests/test_runner.py | 23 +++ tests/test_setup_claude_access.py | 159 +++++++++++++++++++ 22 files changed, 1110 insertions(+), 44 deletions(-) create mode 100644 docs/claude-access.md create mode 100755 scripts/install.sh create mode 100644 scripts/packaging/build_deb.py create mode 100755 scripts/packaging/build_pkg.sh create mode 100755 scripts/packaging/uninstall-macos.sh create mode 100644 scripts/setup_claude_access.py create mode 100644 tests/test_packaging.py create mode 100644 tests/test_setup_claude_access.py diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index d1039c9..3a52a0e 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -25,10 +25,12 @@ jobs: matrix: include: # PyInstaller cannot cross-compile: each target builds on a matching runner. - - { runner: linux-amd64, target: linux-amd64 } - - { runner: linux-arm64, target: linux-arm64 } - - { runner: macos-arm64, target: macos-arm64 } + - { runner: linux-amd64, target: linux-amd64, deb_arch: amd64 } + - { runner: linux-arm64, target: linux-arm64, deb_arch: arm64 } + - { runner: macos-arm64, target: macos-arm64, deb_arch: "" } runs-on: ${{ matrix.runner }} + env: + VERSION: ${{ needs.validate.outputs.version }} steps: - uses: actions/checkout@v4 - uses: astral-sh/setup-uv@v5 @@ -40,16 +42,24 @@ jobs: run: uv run pytest -q --cov - name: Stamp version from tag run: python3 scripts/version_from_tag.py "${GITHUB_REF_NAME}" - - name: Build single-file binary + - name: Build one-dir application run: uv run pyinstaller envbao.spec --clean --noconfirm - - name: Smoke test and name artifact + - name: Smoke test + run: test "$(./dist/envbao/envbao --version)" = "envbao ${VERSION}" + - name: Package run: | - test "$(./dist/envbao --version)" = "envbao ${{ needs.validate.outputs.version }}" - mv dist/envbao "dist/envbao-${{ needs.validate.outputs.version }}-${{ matrix.target }}" + mkdir -p out + tar -C dist -czf "out/envbao-${VERSION}-${{ matrix.target }}.tar.gz" envbao + if [ -n "${{ matrix.deb_arch }}" ]; then + python3 scripts/packaging/build_deb.py "${VERSION}" "${{ matrix.deb_arch }}" dist out + else + sh scripts/packaging/build_pkg.sh "${VERSION}" dist out + fi + ls -l out - uses: actions/upload-artifact@v3 with: name: envbao-${{ matrix.target }} - path: dist/envbao-* + path: out/* release: needs: [validate, build] @@ -61,8 +71,8 @@ jobs: - name: Checksums run: | mkdir release - cp artifacts/*/envbao-* release/ - (cd release && sha256sum envbao-* > SHA256SUMS) + cp artifacts/*/* release/ + (cd release && sha256sum * > SHA256SUMS) - name: Publish Gitea release env: TOKEN: ${{ secrets.RELEASE_TOKEN }} diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml index eb727ba..4edd88e 100644 --- a/.gitea/workflows/test.yml +++ b/.gitea/workflows/test.yml @@ -27,4 +27,5 @@ jobs: - name: Build smoke test run: | uv run pyinstaller envbao.spec --clean --noconfirm - ./dist/envbao --version + ./dist/envbao/envbao --version + python3 scripts/packaging/build_deb.py 0.0.0 amd64 dist out diff --git a/CHANGELOG.md b/CHANGELOG.md index ff37ba8..74d0825 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,16 @@ All notable changes are documented here. This project follows [Semantic Versioni ## [Unreleased] +### Added (exec and packaging) +- `envbao exec -q GROUP -- COMMAND`: run a command with chosen secret groups, output redacted; + `name` on queries, `ENVBAO_CONFIG`, `[security] exec_only`. +- `scripts/setup_claude_access.py`: narrow policy/token and restricted config for Claude Code + (`docs/claude-access.md`). +- Native packages: macOS `.pkg`, Debian/Ubuntu/Raspberry Pi OS `.deb` (amd64, arm64) and a generic + tarball with `scripts/install.sh`. + ### Changed +- Release builds are now one-directory apps (about 0.06 s start-up instead of ~1.4 s). - `--version` from a source checkout now reports a git-derived version such as `0.1.0.dev3+g19a5373` instead of `0.0.0.dev0`. Release binaries are unchanged. diff --git a/README.md b/README.md index 867623e..6f714b9 100644 --- a/README.md +++ b/README.md @@ -24,27 +24,30 @@ safely quoted `export` statements for your shell to evaluate. log. Tokens and secret values are never logged. - **Single binary**, no runtime dependencies (built with PyInstaller). - bash, zsh, sh and fish output. +- `envbao exec`: run a command with chosen secret groups, output redacted (see [docs/claude-access.md](docs/claude-access.md)). ## Install -Download the binary for your platform from the project's releases page -(`envbao--linux-amd64`, `-linux-arm64`, `-macos-arm64`) along with `SHA256SUMS`. -EnvBao is a single self-contained file: there is no installer and nothing to symlink. Verify -it, then copy it onto your `PATH` (`~/.local/bin` shown): +Download the package for your platform from the project's releases page, together with +`SHA256SUMS`, and verify it (`shasum -a 256 -c SHA256SUMS --ignore-missing`, or `sha256sum -c` +on Linux). The packages install the application and create the `envbao` command for you: -```sh -shasum -a 256 -c SHA256SUMS --ignore-missing # Linux: sha256sum -c SHA256SUMS --ignore-missing -# macOS, only if downloaded through a browser (clears the quarantine flag): -xattr -d com.apple.quarantine envbao-*-macos-arm64 -install -m 755 envbao-- ~/.local/bin/envbao -envbao --version -``` +| Platform | Asset | Install | +|----------|-------|---------| +| macOS (Apple Silicon) | `envbao--macos-arm64.pkg` | `sudo installer -pkg envbao--macos-arm64.pkg -target /` | +| Debian / Ubuntu (x86-64) | `envbao__amd64.deb` | `sudo dpkg -i envbao__amd64.deb` | +| Debian / Ubuntu / Raspberry Pi OS (64-bit ARM) | `envbao__arm64.deb` | `sudo dpkg -i envbao__arm64.deb` | +| Any other / no root | `envbao--.tar.gz` | `scripts/install.sh envbao--.tar.gz` | -`install` copies the file and sets its mode in one step. Make sure `~/.local/bin` is on your -`PATH`. To track a local build instead of copying, symlink it: -`ln -s "$PWD/dist/envbao" ~/.local/bin/envbao`. +* The `.pkg` is unsigned: using `installer` on the command line avoids the Gatekeeper prompt. + Uninstall with `scripts/packaging/uninstall-macos.sh`. +* The `.deb` installs to `/opt/envbao` with `/usr/bin/envbao`; remove with `sudo apt remove envbao`. + 32-bit Raspberry Pi OS (armhf) is not supported. +* `scripts/install.sh` verifies the checksum, unpacks to `~/.local/lib/envbao` and links + `~/.local/bin/envbao`. Make sure `~/.local/bin` is on your `PATH`. +* Linux packages need glibc 2.31 or newer. -Or run from source: `uv sync && uv run envbao --help`. +Check with `envbao --version`. Or run from source: `uv sync && uv run envbao --help`. ## Quick start @@ -111,6 +114,7 @@ Full reference: [docs/configuration.md](docs/configuration.md). - [Usage](docs/usage.md) - [Configuration reference](docs/configuration.md) - [Security model](docs/security.md) +- [Using EnvBao from Claude Code](docs/claude-access.md) - [Migrating from ~/.zshrc](docs/migration.md) - [Development](docs/development.md) - [Releasing and CI](docs/releasing.md) diff --git a/docs/claude-access.md b/docs/claude-access.md new file mode 100644 index 0000000..1eac885 --- /dev/null +++ b/docs/claude-access.md @@ -0,0 +1,72 @@ +# Using EnvBao credentials from Claude Code + +Goal: let Claude Code *use* your credentials (call an API, push to a repo, query a service) +without the secret values ever entering the conversation transcript, and without handing it +your admin token. + +## How it works + +``` +Claude ──▶ envbao exec -q gitea -- curl -H "Authorization: token $GITEA_TOKEN" … + │ 1. reads ~/.envbao/claude.toml ($ENVBAO_CONFIG) + │ 2. fetches ONLY group "gitea" with Claude's own narrow token + │ 3. runs the command with GITEA_TOKEN in its environment + └─ 4. replaces secret values in stdout/stderr with *** +``` + +* **Narrow token.** `scripts/setup_claude_access.py` creates the policy `envbao-claude` (read on + `env/shell/` only) and an orphan, periodic token named `envbao-claude`. Revoke it at any + time without touching your own token. +* **`exec_only`.** The generated `claude.toml` sets `[security] exec_only = true`: plain + `envbao` (which prints `export` lines for everything) and `--no-redact` are refused. +* **Redaction.** Secret values (6+ characters; raw, JSON-escaped and URL-encoded forms) are masked + in the command's output, including across read boundaries. +* **Permissions.** Optional Claude Code rules deny `bao`, and reading `~/.envbao/**` and + `~/.zshrc`, so the only route to a secret is `envbao exec`. +* **Audit.** Every `exec` is logged (groups and the program name, never arguments or values) in + `~/.envbao/envbao.log`, and OpenBao's own audit device attributes reads to the + `envbao-claude` token. + +## Setup (once) + +With an admin `BAO_ADDR`/`BAO_TOKEN` in your shell: + +```sh +uv run python scripts/setup_claude_access.py # policy, token, ~/.envbao/claude.toml +uv run python scripts/setup_claude_access.py --settings # also update ~/.claude/settings.json +``` + +Options: `--groups gitea,youtrack` (default: every group under `shell/`), `--mount`, `--force`. +`--settings` sets `ENVBAO_CONFIG` for Claude's sessions and merges these permission rules (a +`.bak` copy of the file is kept): + +```json +{ + "permissions": { + "allow": ["Bash(envbao exec:*)"], + "deny": ["Bash(bao:*)", "Read(~/.envbao/**)", "Read(~/.zshrc)"] + } +} +``` + +Then **remove the root `BAO_TOKEN`/`BAO_ADDR` exports from `~/.zshrc`**: every process started from +your shell, including Claude's tools, inherits them. + +## Using it + +```sh +envbao exec -q youtrack -- curl -s -H "Authorization: Bearer $YOUTRACK_TOKEN" "https://$YOUTRACK_URL/api/users/me" +envbao exec -q gitea -q github -- ./deploy.sh +``` + +Note that `$VAR` inside the command line is expanded by the *calling* shell, before envbao runs. To +have the child expand it, quote it: `envbao exec -q gitea -- sh -c 'curl -H "Authorization: token $GITEA_TOKEN" …'`. +Group names are the last path segment (`shell/gitea` → `gitea`) unless a query sets `name`. + +## Limits + +Redaction is defence in depth, not a sandbox. A command that deliberately transforms a secret +(base64, hashing, splitting it across lines) or sends it to a remote service defeats the filter. +Only grant Claude groups you are comfortable with it using; to narrow later, edit the +`envbao-claude` policy and `claude.toml` (re-run the setup script with `--groups … --force`). +`aws` and `proton` (cloud keys and your mail bridge password) are the most sensitive groups. diff --git a/docs/configuration.md b/docs/configuration.md index 20624da..e20f0ce 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,6 +1,6 @@ # Configuration reference -File: `~/.envbao/config.toml`. Unknown keys and wrong types are rejected, so typos fail loudly. +File: `~/.envbao/config.toml`, or the path in `--config` / the `ENVBAO_CONFIG` environment variable (the flag wins). Unknown keys and wrong types are rejected, so typos fail loudly. ## `[server]` @@ -19,6 +19,7 @@ File: `~/.envbao/config.toml`. Unknown keys and wrong types are rejected, so typ | Key | Type | Default | Description | |-----|------|---------|-------------| | `allow_protected` | list of strings | `[]` | Protected variable names (see [security.md](security.md)) that secrets may set, e.g. `["PATH"]`. | +| `exec_only` | bool | `false` | Refuse plain `envbao` (which prints every value) and `exec --no-redact`; only redacted `envbao exec` and `--check` work. Used by the Claude profile. | ## `[[query]]` @@ -29,6 +30,7 @@ Common keys: | Key | Type | Default | Description | |-----|------|---------|-------------| | `engine` | string | `"kv"` | Secret engine. Currently only `kv`. | +| `name` | string | last `path` segment | Group name for `envbao exec -q NAME` (letters, digits, `.` `_` `-`). | | `keys` | list of strings | all | Only export these keys from the secret. | | `rename` | table | `{}` | Map secret key → variable name. Applied before `prefix`. | | `prefix` | string | `""` | Prepended to every variable name. | diff --git a/docs/development.md b/docs/development.md index 0fdb42a..80dc3cc 100644 --- a/docs/development.md +++ b/docs/development.md @@ -26,6 +26,8 @@ uv run pytest --cov # fails below 90 % coverage | `resolve.py` | Runs queries, applies keys/rename/prefix, filters unsafe names | | `render.py` | Name validation, quoting, shell dialects | | `logging_setup.py` | stderr, private rotating file, syslog | +| `runner.py` | `exec`: secret selection, output redaction, process handling | +| `version.py` | Release/stamped version, git-derived version for checkouts | | `errors.py` | Exceptions and exit codes | ## Testing approach @@ -39,7 +41,7 @@ uv run pytest --cov # fails below 90 % coverage ```sh uv run pyinstaller envbao.spec --clean --noconfirm -./dist/envbao --version +./dist/envbao/envbao --version ``` PyInstaller cannot cross-compile; build on the platform you target. @@ -53,3 +55,12 @@ bao kv put -mount=secret myapp/prod DB_URL=postgres://x API_KEY=abc envbao --init # then set address/token, add a [[query]] for secret/myapp/prod envbao --check && envbao ``` + +## Packaging locally + +```sh +python3 scripts/packaging/build_deb.py 0.2.0 arm64 dist out # .deb (pure Python, any OS) +sh scripts/packaging/build_pkg.sh 0.2.0 dist out # macOS .pkg (needs pkgbuild) +``` + +The binary inside is for the OS you built on, so only ship packages built on the matching runner. diff --git a/docs/releasing.md b/docs/releasing.md index 2f0b611..c999232 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -6,10 +6,13 @@ 90 % coverage gate, and a PyInstaller build smoke test. - **`release.yml`** - on a pushed tag `vMAJOR.MINOR.PATCH[-prerelease][+build]` ([SemVer 2.0.0](https://semver.org)): 1. `validate` rejects tags that are not valid SemVer (`scripts/version_from_tag.py`). - 2. `build` runs tests then builds `envbao` with PyInstaller on each runner, stamping the version - from the tag into the binary and checking `envbao --version` matches. - 3. `release` writes `SHA256SUMS` and creates a Gitea release (marked *prerelease* if the tag has a - `-suffix`) with all binaries attached. + 2. `build` runs tests then builds the one-directory `envbao` app with PyInstaller on each runner, + stamping the version from the tag and checking `envbao --version` matches. It then packages it: + `envbao--.tar.gz` everywhere, plus `envbao__.deb` (linux, built in pure + Python by `scripts/packaging/build_deb.py`) or `envbao--macos-arm64.pkg` (macOS, via + `pkgbuild` in `scripts/packaging/build_pkg.sh`). + 3. `release` writes one `SHA256SUMS` and creates a Gitea release (marked *prerelease* if the tag + has a `-suffix`) with all packages attached. ## Cutting a release @@ -41,7 +44,8 @@ Runners need network access to fetch `astral-sh/setup-uv` and Python packages. ## Notes - `actions/upload-artifact@v3` / `download-artifact@v3` are used because Gitea does not yet support v4. -- Linux binaries link against the glibc of the build host; build on the oldest distro you want to - support. -- macOS binaries are unsigned; first run may need `xattr -d com.apple.quarantine envbao` if downloaded - through a browser. +- Linux builds link against the glibc of the build host, and the `.deb` declares `libc6 (>= 2.31)`: + keep the Linux runners on Debian 11 / Ubuntu 20.04 or newer, ideally the oldest you want to + support. Pre-release tags map to Debian `~` versions (`1.0.0-rc.1` → `1.0.0~rc.1`). +- Raspberry Pi OS 64-bit is covered by the arm64 `.deb`; 32-bit (armhf) would need an armv7 runner. +- The macOS `.pkg` is unsigned and not notarised; install with `sudo installer -pkg … -target /`. diff --git a/docs/security.md b/docs/security.md index d08f1b7..75a1b99 100644 --- a/docs/security.md +++ b/docs/security.md @@ -31,12 +31,18 @@ variables are exported (any child process inherits them). syslog for WARNING and above. Events: permission violations, auth failures, per-query outcome, overrides, refused variables, count of exported variables. +8. **`exec` mode** - `envbao exec` injects only the requested groups into one child process and masks + their values (raw, JSON, URL-encoded) in its output; with `[security] exec_only = true` plain + export mode and `--no-redact` are refused. Masking is defence in depth, not a sandbox (see + [claude-access.md](claude-access.md)). + ## Recommendations - Use a token with a narrow read-only policy and a TTL; renew it periodically. - Prefer `token_file` if you want to rotate the token without editing the config. - Keep `~/.envbao` out of backups/sync tools that change permissions. -- Verify release binaries against `SHA256SUMS`. +- Verify release packages against `SHA256SUMS`. +- Do not keep a root/admin `BAO_TOKEN` exported in your shell profile. ## Reporting a vulnerability diff --git a/docs/usage.md b/docs/usage.md index 2947d86..778885c 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -2,6 +2,7 @@ ``` envbao [--config PATH] [--shell {auto,bash,zsh,sh,fish}] [-v|-vv] [--check | --init] +envbao [options] exec -q GROUP [-q GROUP ...] [--no-redact] -- COMMAND [ARGS ...] envbao --version ``` @@ -14,6 +15,18 @@ envbao --version | `--init` | Create `~/.envbao` (0700) and a template `config.toml` (0600). Never overwrites. | | `-v` / `-vv` | Show INFO / DEBUG messages on stderr. | +## `exec`: run a command with secrets + +```sh +envbao exec -q gitea -q youtrack -- ./script.sh +``` + +Fetches only the named groups (see `name` in the configuration reference), runs `COMMAND` with +them as environment variables, and returns the command's exit status. Its stdout/stderr are filtered +so secret values appear as `***`; `--no-redact` replaces the process with the command instead (not +available when `exec_only` is set). Nothing runs if any selected group cannot be fetched. See +[claude-access.md](claude-access.md). + ## Shell integration bash / zsh: diff --git a/envbao.spec b/envbao.spec index 6983bd1..9f4f8e0 100644 --- a/envbao.spec +++ b/envbao.spec @@ -1,5 +1,6 @@ # -*- mode: python ; coding: utf-8 -*- -# PyInstaller spec: builds a single self-contained executable at dist/envbao. +# PyInstaller spec: builds a one-directory application at dist/envbao/ (run dist/envbao/envbao). +# One-dir starts much faster than one-file because nothing is unpacked on every run. # Usage: uv run pyinstaller envbao.spec --clean --noconfirm a = Analysis( ["src/envbao/__main__.py"], @@ -14,13 +15,19 @@ pyz = PYZ(a.pure) exe = EXE( pyz, a.scripts, - a.binaries, - a.datas, [], + exclude_binaries=True, name="envbao", debug=False, strip=False, upx=False, console=True, - runtime_tmpdir=None, +) +coll = COLLECT( + exe, + a.binaries, + a.datas, + strip=False, + upx=False, + name="envbao", ) diff --git a/pyproject.toml b/pyproject.toml index 24587d3..70c2ddd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,7 +51,7 @@ src = ["src", "tests"] select = ["E", "F", "I", "B", "UP", "S", "SIM"] [tool.ruff.lint.per-file-ignores] -"tests/*" = ["S101", "S105", "S106"] +"tests/*" = ["S101", "S105", "S106", "S603", "S607"] [tool.mypy] strict = true diff --git a/scripts/install.sh b/scripts/install.sh new file mode 100755 index 0000000..e3638c0 --- /dev/null +++ b/scripts/install.sh @@ -0,0 +1,45 @@ +#!/bin/sh +# Install EnvBao from a release tarball (for systems without a .deb/.pkg). +# +# Usage: scripts/install.sh envbao--.tar.gz [PREFIX] +# +# Extracts to PREFIX/lib/envbao and links PREFIX/bin/envbao to it (default PREFIX: ~/.local). +# If a SHA256SUMS file sits next to the tarball, the checksum is verified first. +set -eu + +[ $# -ge 1 ] && [ $# -le 2 ] || { sed -n '2,7p' "$0" >&2; exit 2; } +tarball=$1 +prefix=${2:-$HOME/.local} +[ -f "$tarball" ] || { echo "error: $tarball not found" >&2; exit 1; } + +sums="$(dirname "$tarball")/SHA256SUMS" +if [ -f "$sums" ]; then + name=$(basename "$tarball") + expected=$(awk -v n="$name" '$2 == n || $2 == "*" n { print $1 }' "$sums") + [ -n "$expected" ] || { echo "error: $name is not listed in $sums" >&2; exit 1; } + if command -v sha256sum >/dev/null 2>&1; then + actual=$(sha256sum "$tarball" | awk '{ print $1 }') + else + actual=$(shasum -a 256 "$tarball" | awk '{ print $1 }') + fi + [ "$expected" = "$actual" ] || { echo "error: checksum mismatch for $name" >&2; exit 1; } + echo "checksum OK" +else + echo "warning: no SHA256SUMS next to the tarball; skipping verification" >&2 +fi + +lib="$prefix/lib" +mkdir -p "$lib" "$prefix/bin" +rm -rf "$lib/envbao" +tar -xzf "$tarball" -C "$lib" +[ -x "$lib/envbao/envbao" ] || { echo "error: tarball did not contain envbao/envbao" >&2; exit 1; } +ln -sf "$lib/envbao/envbao" "$prefix/bin/envbao" +# Downloaded via a browser on macOS? Clear the quarantine flag (harmless elsewhere). +xattr -dr com.apple.quarantine "$lib/envbao" 2>/dev/null || true + +echo "installed: $prefix/bin/envbao -> $lib/envbao/envbao" +"$prefix/bin/envbao" --version +case ":$PATH:" in + *":$prefix/bin:"*) ;; + *) echo "note: $prefix/bin is not on your PATH" >&2 ;; +esac diff --git a/scripts/packaging/build_deb.py b/scripts/packaging/build_deb.py new file mode 100644 index 0000000..54fe17f --- /dev/null +++ b/scripts/packaging/build_deb.py @@ -0,0 +1,228 @@ +"""Build a ``.deb`` from the PyInstaller one-dir output, in pure Python. + +No dpkg tooling is required, so this works on any runner (and on macOS). Layout: + +* ``/opt/envbao/`` the one-dir application +* ``/usr/bin/envbao`` symlink to ``/opt/envbao/envbao`` +* ``/usr/share/doc/envbao/copyright`` + +Usage: ``python scripts/packaging/build_deb.py VERSION ARCH DIST_DIR OUT_DIR`` +(``VERSION`` is a bare SemVer such as ``1.2.3`` or ``1.2.3-rc.1``; ``ARCH`` is ``amd64`` +or ``arm64``). +""" + +from __future__ import annotations + +import gzip +import hashlib +import io +import os +import re +import sys +import tarfile +import time +from pathlib import Path + +ARCHES = ("amd64", "arm64") +INSTALL_DIR = "opt/envbao" +MAINTAINER = "Matt Daubney " +HOMEPAGE = "https://git.daubney.dev/matt/EnvBao" +_SEMVER = re.compile(r"^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$") + + +def deb_version(version: str) -> str: + """Map SemVer to a Debian version: ``1.2.3-rc.1+b`` -> ``1.2.3~rc.1``. + + ``~`` sorts a pre-release *before* the final release, as SemVer requires. Build + metadata is dropped. + """ + if not _SEMVER.match(version): + raise ValueError(f"not a SemVer version: {version!r}") + core, _, rest = version.partition("-") + if "+" in version and not rest: + core = core.split("+", 1)[0] + pre = rest.split("+", 1)[0] + return f"{core}~{pre}" if pre else core + + +def control_text(version: str, arch: str, installed_kib: int) -> str: + """Contents of ``DEBIAN/control``.""" + if arch not in ARCHES: + raise ValueError(f"unsupported architecture {arch!r}") + return ( + "Package: envbao\n" + f"Version: {deb_version(version)}\n" + "Section: utils\n" + "Priority: optional\n" + f"Architecture: {arch}\n" + "Depends: libc6 (>= 2.31)\n" + f"Installed-Size: {installed_kib}\n" + f"Maintainer: {MAINTAINER}\n" + f"Homepage: {HOMEPAGE}\n" + "Description: Inject OpenBao secrets into your shell\n" + " EnvBao reads queries from ~/.envbao/config.toml and prints shell export\n" + " statements for secrets stored in an OpenBao server, or runs a command with\n" + " selected secrets in its environment (envbao exec). It refuses to run unless\n" + " its configuration is readable by the owner only.\n" + ) + + +def _ar_member(name: str, data: bytes, mtime: int) -> bytes: + header = f"{name:<16}{mtime:<12}{0:<6}{0:<6}{'100644':<8}{len(data):<10}`\n".encode() + assert len(header) == 60 # noqa: S101 + return header + data + (b"\n" if len(data) % 2 else b"") + + +def _tar_gz(entries: list[tuple[tarfile.TarInfo, bytes | None]]) -> bytes: + raw = io.BytesIO() + with tarfile.open(fileobj=raw, mode="w", format=tarfile.GNU_FORMAT) as tar: + for info, data in entries: + tar.addfile(info, io.BytesIO(data) if data is not None else None) + out = io.BytesIO() + with gzip.GzipFile(fileobj=out, mode="wb", mtime=0) as gz: + gz.write(raw.getvalue()) + return out.getvalue() + + +def _info( + name: str, mtime: int, *, mode: int, kind: bytes, size: int = 0, link: str = "" +) -> tarfile.TarInfo: + info = tarfile.TarInfo(name) + info.mode, info.mtime, info.type, info.size = mode, mtime, kind, size + info.uid = info.gid = 0 + info.uname = info.gname = "root" + info.linkname = link + return info + + +def build(version: str, arch: str, dist_dir: Path, out_dir: Path) -> Path: + """Create the package and return its path.""" + app = dist_dir / "envbao" + if not (app / "envbao").is_file(): + raise FileNotFoundError(f"{app / 'envbao'} not found; run PyInstaller first") + mtime = int(os.environ.get("SOURCE_DATE_EPOCH", time.time())) + + data: list[tuple[tarfile.TarInfo, bytes | None]] = [] + md5s: list[str] = [] + size_bytes = 0 + seen_dirs: set[str] = set() + + def add_dir(path: str) -> None: + parts = path.strip("/").split("/") + for i in range(1, len(parts) + 1): + d = "/".join(parts[:i]) + if d not in seen_dirs: + seen_dirs.add(d) + data.append((_info(f"./{d}/", mtime, mode=0o755, kind=tarfile.DIRTYPE), None)) + + add_dir(INSTALL_DIR) + for root, dirs, files in os.walk(app): + dirs.sort() + rel_root = Path(root).relative_to(app) + add_dir(f"{INSTALL_DIR}/{rel_root}" if str(rel_root) != "." else INSTALL_DIR) + for name in sorted(files): + src = Path(root) / name + rel = f"{INSTALL_DIR}/{(rel_root / name).as_posix()}".replace("/./", "/") + if src.is_symlink(): + data.append( + ( + _info( + f"./{rel}", + mtime, + mode=0o777, + kind=tarfile.SYMTYPE, + link=os.readlink(src), + ), + None, + ) + ) + continue + content = src.read_bytes() + executable = os.access(src, os.X_OK) + data.append( + ( + _info( + f"./{rel}", + mtime, + mode=0o755 if executable else 0o644, + kind=tarfile.REGTYPE, + size=len(content), + ), + content, + ) + ) + md5s.append(f"{hashlib.md5(content, usedforsecurity=False).hexdigest()} {rel}") + size_bytes += len(content) + + add_dir("usr/bin") + data.append( + ( + _info( + "./usr/bin/envbao", + mtime, + mode=0o777, + kind=tarfile.SYMTYPE, + link="/opt/envbao/envbao", + ), + None, + ) + ) + add_dir("usr/share/doc/envbao") + licence = (Path(__file__).resolve().parents[2] / "LICENSE").read_bytes() + data.append( + ( + _info( + "./usr/share/doc/envbao/copyright", + mtime, + mode=0o644, + kind=tarfile.REGTYPE, + size=len(licence), + ), + licence, + ) + ) + md5s.append( + f"{hashlib.md5(licence, usedforsecurity=False).hexdigest()} usr/share/doc/envbao/copyright" + ) + + control = control_text(version, arch, (size_bytes + 1023) // 1024).encode() + md5_file = ("\n".join(md5s) + "\n").encode() + control_tar = _tar_gz( + [ + (_info("./", mtime, mode=0o755, kind=tarfile.DIRTYPE), None), + ( + _info("./control", mtime, mode=0o644, kind=tarfile.REGTYPE, size=len(control)), + control, + ), + ( + _info("./md5sums", mtime, mode=0o644, kind=tarfile.REGTYPE, size=len(md5_file)), + md5_file, + ), + ] + ) + out_dir.mkdir(parents=True, exist_ok=True) + target = out_dir / f"envbao_{deb_version(version)}_{arch}.deb" + target.write_bytes( + b"!\n" + + _ar_member("debian-binary", b"2.0\n", mtime) + + _ar_member("control.tar.gz", control_tar, mtime) + + _ar_member("data.tar.gz", _tar_gz(data), mtime) + ) + return target + + +def main(argv: list[str]) -> int: + if len(argv) != 5: + sys.stderr.write(__doc__ or "") + return 2 + try: + path = build(argv[1], argv[2], Path(argv[3]), Path(argv[4])) + except (ValueError, FileNotFoundError) as exc: + sys.stderr.write(f"error: {exc}\n") + return 1 + sys.stdout.write(f"{path}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/scripts/packaging/build_pkg.sh b/scripts/packaging/build_pkg.sh new file mode 100755 index 0000000..f4a42ad --- /dev/null +++ b/scripts/packaging/build_pkg.sh @@ -0,0 +1,28 @@ +#!/bin/sh +# Build a macOS installer package from the PyInstaller one-dir output. +# +# Usage: scripts/packaging/build_pkg.sh VERSION DIST_DIR OUT_DIR +# e.g. scripts/packaging/build_pkg.sh 1.2.3 dist out +# +# Installs the application to /usr/local/lib/envbao and a symlink /usr/local/bin/envbao. +# The package is unsigned; install it with: sudo installer -pkg FILE -target / +set -eu + +[ $# -eq 3 ] || { sed -n '2,8p' "$0" >&2; exit 2; } +version=$1 dist=$2 out=$3 +[ -x "$dist/envbao/envbao" ] || { echo "error: $dist/envbao/envbao not found" >&2; exit 1; } +command -v pkgbuild >/dev/null || { echo "error: pkgbuild (macOS) is required" >&2; exit 1; } + +stage=$(mktemp -d) +trap 'rm -rf "$stage"' EXIT +mkdir -p "$stage/usr/local/lib" "$stage/usr/local/bin" "$out" +cp -R "$dist/envbao" "$stage/usr/local/lib/envbao" +ln -s ../lib/envbao/envbao "$stage/usr/local/bin/envbao" + +pkg="$out/envbao-$version-macos-arm64.pkg" +pkgbuild --root "$stage" \ + --identifier dev.daubney.envbao \ + --version "$version" \ + --install-location / \ + "$pkg" >/dev/null +echo "$pkg" diff --git a/scripts/packaging/uninstall-macos.sh b/scripts/packaging/uninstall-macos.sh new file mode 100755 index 0000000..32f3423 --- /dev/null +++ b/scripts/packaging/uninstall-macos.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Remove EnvBao installed from the macOS .pkg. Leaves ~/.envbao (your config) untouched. +set -eu +sudo rm -f /usr/local/bin/envbao +sudo rm -rf /usr/local/lib/envbao +sudo pkgutil --forget dev.daubney.envbao >/dev/null 2>&1 || true +echo "EnvBao removed. Your configuration in ~/.envbao was left in place." diff --git a/scripts/setup_claude_access.py b/scripts/setup_claude_access.py new file mode 100644 index 0000000..c734bbb --- /dev/null +++ b/scripts/setup_claude_access.py @@ -0,0 +1,210 @@ +"""Give Claude Code narrow, auditable access to OpenBao secrets via ``envbao exec``. + +Run once with an admin ``BAO_ADDR``/``BAO_TOKEN`` in the environment. It: + +1. creates the read-only policy ``envbao-claude`` for the chosen groups under + ``/shell/``, +2. mints a dedicated orphan, periodic token for it (``~/.envbao/claude-token``, 0600), +3. writes ``~/.envbao/claude.toml`` (0600) with ``exec_only = true`` so that plain + ``envbao`` (which would print every value) is refused and ``--no-redact`` is disabled, +4. with ``--settings``, merges ``ENVBAO_CONFIG`` and permission rules into + ``~/.claude/settings.json`` (backed up first). + +Tokens and secret values are never printed or passed on a command line. +""" + +from __future__ import annotations + +import argparse +import copy +import json +import os +import shutil +import sys +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +from migrate_zshrc import ( # type: ignore[import-not-found] + DEFAULT_MOUNT, + SECRET_PREFIX, + Bao, + MigrationError, + detect_kv_version, + write_private, +) + +POLICY_NAME = "envbao-claude" +TOKEN_PERIOD = "720h" # noqa: S105 - a duration +CLAUDE_CONFIG = "claude.toml" +CLAUDE_TOKEN = "claude-token" # noqa: S105 - a file name + +ALLOW = ["Bash(envbao exec:*)"] +DENY = ["Bash(bao:*)", "Read(~/.envbao/**)", "Read(~/.zshrc)"] + + +def policy_text(mount: str, version: int, groups: Sequence[str]) -> str: + """HCL granting read on exactly ``groups`` plus what EnvBao needs to use the token.""" + blocks = [] + for group in groups: + path = ( + f"{mount}/data/{SECRET_PREFIX}/{group}" + if version == 2 + else f"{mount}/{SECRET_PREFIX}/{group}" + ) + blocks.append(f'path "{path}" {{\n capabilities = ["read"]\n}}\n') + blocks.append(f'path "sys/internal/ui/mounts/{mount}" {{\n capabilities = ["read"]\n}}\n') + blocks.append('path "auth/token/lookup-self" {\n capabilities = ["read"]\n}\n') + return "".join(blocks) + + +def render_config(address: str, mount: str, groups: Sequence[str], version: int) -> str: + """The ``claude.toml`` text: named queries, token file, exec-only.""" + lines = [ + "# Generated by scripts/setup_claude_access.py - Claude's restricted EnvBao profile.", + "[server]", + f"address = {json.dumps(address)}", + f'token_file = "~/.envbao/{CLAUDE_TOKEN}"', + "", + "[security]", + "exec_only = true", + ] + for group in groups: + lines += [ + "", + "[[query]]", + f"name = {json.dumps(group)}", + 'engine = "kv"', + f"mount = {json.dumps(mount)}", + f"path = {json.dumps(f'{SECRET_PREFIX}/{group}')}", + f"kv_version = {version}", + 'on_missing = "error"', + ] + return "\n".join(lines) + "\n" + + +def merge_settings(existing: Mapping[str, Any], config_path: str) -> dict[str, Any]: + """Return ``existing`` with the EnvBao env var and permission rules added (idempotent).""" + merged = copy.deepcopy(dict(existing)) + merged.setdefault("env", {})["ENVBAO_CONFIG"] = config_path + perms = merged.setdefault("permissions", {}) + for key, rules in (("allow", ALLOW), ("deny", DENY)): + current = perms.setdefault(key, []) + current.extend(r for r in rules if r not in current) + return merged + + +def apply_settings(path: Path, config_path: str) -> list[str]: + """Merge into the settings file (creating a 0600 backup) and describe what changed.""" + existing: dict[str, Any] = {} + if path.exists(): + existing = json.loads(path.read_text(encoding="utf-8")) + backup = path.with_name(path.name + ".bak") + shutil.copyfile(path, backup) + os.chmod(backup, 0o600) + merged = merge_settings(existing, config_path) + changes = [f"env.ENVBAO_CONFIG = {config_path}"] + for key in ("allow", "deny"): + added = [ + r + for r in merged["permissions"][key] + if r not in existing.get("permissions", {}).get(key, []) + ] + changes += [f"permissions.{key} += {r}" for r in added] + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(merged, indent=2) + "\n", encoding="utf-8") + return changes + + +def list_groups(bao: Bao, mount: str) -> list[str]: + """Group names currently stored under ``/shell/``.""" + out = bao.run("kv", "list", f"-mount={mount}", "-format=json", SECRET_PREFIX).stdout + return sorted(g for g in json.loads(out) if not g.endswith("/")) + + +def parse_args(argv: Sequence[str] | None) -> argparse.Namespace: + p = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + p.add_argument("--mount", default=DEFAULT_MOUNT) + p.add_argument("--groups", help="comma separated; default: every group under shell/") + p.add_argument("--config-dir", type=Path, default=Path("~/.envbao")) + p.add_argument( + "--settings", + nargs="?", + const="~/.claude/settings.json", + metavar="PATH", + help="also merge Claude Code settings (default ~/.claude/settings.json)", + ) + p.add_argument("--force", action="store_true", help="replace an existing claude.toml/token") + return p.parse_args(argv) + + +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 + 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 + config_dir = args.config_dir.expanduser() + config_path, token_path = config_dir / CLAUDE_CONFIG, config_dir / CLAUDE_TOKEN + if (config_path.exists() or token_path.exists()) and not args.force: + sys.stderr.write(f"error: {config_path} or {token_path} exists; use --force to replace\n") + return 1 + + bao = Bao([environ["BAO_TOKEN"]]) + try: + version = detect_kv_version(bao, args.mount) + groups = ( + [g.strip() for g in args.groups.split(",")] + if args.groups + else list_groups(bao, args.mount) + ) + if not groups: + raise MigrationError(f"no groups found under {args.mount}/{SECRET_PREFIX}/") + bao.run("policy", "write", POLICY_NAME, "-", stdin=policy_text(args.mount, version, groups)) + token = bao.run( + "token", "create", f"-policy={POLICY_NAME}", "-orphan", f"-period={TOKEN_PERIOD}", + "-display-name=envbao-claude", "-field=token", + ).stdout.strip() # fmt: skip + bao.add_secret(token) + audit = bao.run("audit", "list", check=False) + except MigrationError as exc: + sys.stderr.write(f"error: {exc}\n") + return 1 + + config_dir.mkdir(mode=0o700, parents=True, exist_ok=True) + os.chmod(config_dir, 0o700) + for path in (config_path, token_path): + if path.exists(): + backup = path.with_name(path.name + ".bak") + shutil.copyfile(path, backup) + os.chmod(backup, 0o600) + write_private(token_path, token) + write_private(config_path, render_config(address, args.mount, groups, version)) + sys.stdout.write(f"policy {POLICY_NAME}: read on {', '.join(groups)}\n") + sys.stdout.write(f"wrote {config_path} and {token_path}\n") + + if args.settings: + settings_path = Path(args.settings).expanduser() + for change in apply_settings(settings_path, str(config_path)): + sys.stdout.write(f" settings: {change}\n") + sys.stdout.write(f"updated {settings_path} (backup: {settings_path.name}.bak)\n") + else: + sys.stdout.write("Claude settings not changed; re-run with --settings to add them.\n") + + if audit.returncode != 0 or "No audit" in audit.stderr or not audit.stdout.strip(): + sys.stdout.write( + "warning: no OpenBao audit device is enabled, so Claude's reads are not logged.\n" + " Enable one: bao audit enable file file_path=/var/log/openbao/audit.log\n" + ) + sys.stdout.write( + "Recommended: remove the root BAO_TOKEN/BAO_ADDR exports from ~/.zshrc so that Claude\n" + "and every child process stop inheriting them. Use: envbao exec -q GROUP -- COMMAND\n" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/envbao/cli.py b/src/envbao/cli.py index cdac5a8..7313abb 100644 --- a/src/envbao/cli.py +++ b/src/envbao/cli.py @@ -159,7 +159,11 @@ def run(args: argparse.Namespace) -> int: _check(config, client) return EXIT_OK + if config.exec_only and args.command != "exec" and not args.check: + raise ConfigError("this configuration only permits 'envbao exec' (security.exec_only)") if args.command == "exec": + if config.exec_only and args.no_redact: + raise ConfigError("--no-redact is not permitted (security.exec_only)") argv = args.argv[1:] if args.argv[:1] == ["--"] else args.argv queries = select_queries(config, args.query) secrets = fetch_secrets(client, config, queries) diff --git a/src/envbao/config.py b/src/envbao/config.py index b5d872c..6b26805 100644 --- a/src/envbao/config.py +++ b/src/envbao/config.py @@ -35,7 +35,7 @@ _SERVER_KEYS = { "timeout", "allow_insecure_http", } -_SECURITY_KEYS = {"allow_protected"} +_SECURITY_KEYS = {"allow_protected", "exec_only"} _TOP_KEYS = {"server", "security", "query"} _QUERY_COMMON_KEYS = {"engine", "name", "keys", "prefix", "rename", "on_missing"} _NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\Z") @@ -83,6 +83,7 @@ class Config: server: ServerConfig queries: tuple[Query, ...] allow_protected: frozenset[str] = frozenset() + exec_only: bool = False def resolve_config_path(explicit: str | None) -> Path: @@ -227,7 +228,16 @@ def parse_config(data: Mapping[str, Any]) -> Config: _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)) + exec_only = security.get("exec_only", False) + if not isinstance(exec_only, bool): + raise ConfigError("security.exec_only must be a boolean") + + return Config( + server=server, + queries=queries, + allow_protected=frozenset(allow_protected), + exec_only=exec_only, + ) def load_config(path: Path) -> Config: diff --git a/tests/test_packaging.py b/tests/test_packaging.py new file mode 100644 index 0000000..fcb091f --- /dev/null +++ b/tests/test_packaging.py @@ -0,0 +1,213 @@ +import gzip +import importlib.util +import io +import shutil +import subprocess +import sys +import tarfile +from pathlib import Path + +import pytest + +ROOT = Path(__file__).parent.parent +_spec = importlib.util.spec_from_file_location( + "build_deb", ROOT / "scripts" / "packaging" / "build_deb.py" +) +assert _spec and _spec.loader +bd = importlib.util.module_from_spec(_spec) +sys.modules["build_deb"] = bd +_spec.loader.exec_module(bd) + + +@pytest.mark.parametrize( + "semver, deb", + [ + ("1.2.3", "1.2.3"), + ("0.2.0-rc.1", "0.2.0~rc.1"), + ("1.0.0-alpha+001", "1.0.0~alpha"), + ("1.0.0+20130313", "1.0.0"), + ], +) +def test_deb_version(semver: str, deb: str) -> None: + assert bd.deb_version(semver) == deb + + +@pytest.mark.parametrize("bad", ["1.2", "v1.2.3", "", "1.2.3-"]) +def test_deb_version_rejects(bad: str) -> None: + with pytest.raises(ValueError): + bd.deb_version(bad) + + +def test_control_text() -> None: + text = bd.control_text("1.2.3", "arm64", 42) + assert "Package: envbao\nVersion: 1.2.3\n" in text + assert "Architecture: arm64\n" in text and "Installed-Size: 42\n" in text + assert text.endswith("\n") and "Depends: libc6" in text + with pytest.raises(ValueError): + bd.control_text("1.2.3", "armhf", 1) + + +@pytest.fixture +def fake_dist(tmp_path: Path) -> Path: + app = tmp_path / "dist" / "envbao" + (app / "_internal" / "lib").mkdir(parents=True) + (app / "envbao").write_bytes(b"\x7fELFfake") + (app / "envbao").chmod(0o755) + (app / "_internal" / "lib" / "data.bin").write_bytes(b"x" * 2048) + (app / "_internal" / "link").symlink_to("lib/data.bin") + return tmp_path / "dist" + + +def read_ar(path: Path) -> dict[str, bytes]: + raw = path.read_bytes() + assert raw.startswith(b"!\n") + members, pos = {}, 8 + while pos < len(raw): + name = raw[pos : pos + 16].decode().strip() + size = int(raw[pos + 48 : pos + 58]) + assert raw[pos + 58 : pos + 60] == b"`\n" + members[name] = raw[pos + 60 : pos + 60 + size] + pos += 60 + size + size % 2 + return members + + +def test_build_deb_structure(fake_dist: Path, tmp_path: Path) -> None: + out = bd.build("0.2.0-rc.1", "amd64", fake_dist, tmp_path / "out") + assert out.name == "envbao_0.2.0~rc.1_amd64.deb" + members = read_ar(out) + assert list(members) == ["debian-binary", "control.tar.gz", "data.tar.gz"] + assert members["debian-binary"] == b"2.0\n" + + control = tarfile.open(fileobj=io.BytesIO(members["control.tar.gz"])) # noqa: SIM115 + assert b"Version: 0.2.0~rc.1" in control.extractfile("./control").read() # type: ignore[union-attr] + md5s = control.extractfile("./md5sums").read().decode() # type: ignore[union-attr] + assert "opt/envbao/envbao" in md5s and "usr/share/doc/envbao/copyright" in md5s + + data = tarfile.open(fileobj=io.BytesIO(members["data.tar.gz"])) # noqa: SIM115 + by_name = {m.name: m for m in data.getmembers()} + assert ( + by_name["./usr/bin/envbao"].issym() + and by_name["./usr/bin/envbao"].linkname == "/opt/envbao/envbao" + ) + assert by_name["./opt/envbao/envbao"].mode == 0o755 + assert by_name["./opt/envbao/_internal/lib/data.bin"].mode == 0o644 + assert by_name["./opt/envbao/_internal/link"].issym() + assert all(m.uid == 0 and m.gid == 0 and m.uname == "root" for m in by_name.values()) + for d in ("./opt", "./opt/envbao", "./usr", "./usr/bin"): + assert by_name[d].isdir() + assert gzip.decompress(members["data.tar.gz"]) # valid gzip + + +def test_build_deb_missing_dist(tmp_path: Path) -> None: + with pytest.raises(FileNotFoundError): + bd.build("1.0.0", "amd64", tmp_path, tmp_path / "o") + + +def test_main_errors(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + assert bd.main(["x"]) == 2 + assert bd.main(["x", "bad", "amd64", str(tmp_path), str(tmp_path)]) == 1 + assert "error" in capsys.readouterr().err + + +def test_main_success(fake_dist: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + assert bd.main(["x", "1.0.0", "arm64", str(fake_dist), str(tmp_path / "o")]) == 0 + assert capsys.readouterr().out.strip().endswith("envbao_1.0.0_arm64.deb") + + +@pytest.mark.skipif(not shutil.which("dpkg-deb"), reason="dpkg-deb not installed") +def test_dpkg_accepts_package(fake_dist: Path, tmp_path: Path) -> None: + out = bd.build("1.0.0", "amd64", fake_dist, tmp_path / "o") + info = subprocess.run(["dpkg-deb", "-I", str(out)], capture_output=True, text=True, check=True) + assert "Package: envbao" in info.stdout + + +@pytest.mark.skipif(not shutil.which("pkgbuild"), reason="pkgbuild (macOS) not available") +def test_macos_pkg(fake_dist: Path, tmp_path: Path) -> None: + script = ROOT / "scripts" / "packaging" / "build_pkg.sh" + proc = subprocess.run( + ["/bin/sh", str(script), "1.2.3", str(fake_dist), str(tmp_path / "o")], + capture_output=True, text=True, check=True, + ) # fmt: skip + pkg = Path(proc.stdout.strip()) + assert pkg.name == "envbao-1.2.3-macos-arm64.pkg" and pkg.exists() + files = subprocess.run( + ["pkgutil", "--payload-files", str(pkg)], + capture_output=True, + text=True, + check=True, + ).stdout + assert "./usr/local/lib/envbao/envbao" in files and "./usr/local/bin/envbao" in files + + +def test_pkg_script_usage_errors(tmp_path: Path) -> None: + script = ROOT / "scripts" / "packaging" / "build_pkg.sh" + assert ( + subprocess.run(["/bin/sh", str(script)], capture_output=True, check=False).returncode == 2 + ) + bad = subprocess.run( + ["/bin/sh", str(script), "1.0.0", str(tmp_path), str(tmp_path / "o")], + capture_output=True, text=True, check=False, + ) # fmt: skip + assert bad.returncode == 1 and "not found" in bad.stderr + + +# ---- scripts/install.sh --------------------------------------------------------------- + + +def make_tarball(tmp_path: Path) -> Path: + app = tmp_path / "src" / "envbao" + app.mkdir(parents=True) + exe = app / "envbao" + exe.write_text("#!/bin/sh\necho envbao 9.9.9\n") + exe.chmod(0o755) + tarball = tmp_path / "envbao-9.9.9-linux-amd64.tar.gz" + with tarfile.open(tarball, "w:gz") as tar: + tar.add(app, arcname="envbao") + return tarball + + +def install(tarball: Path, prefix: Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + ["/bin/sh", str(ROOT / "scripts" / "install.sh"), str(tarball), str(prefix)], + capture_output=True, + text=True, + check=False, + ) + + +def sha(path: Path) -> str: + import hashlib + + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def test_install_script_with_checksum(tmp_path: Path) -> None: + tarball = make_tarball(tmp_path) + (tmp_path / "SHA256SUMS").write_text(f"{sha(tarball)} {tarball.name}\n") + prefix = tmp_path / "prefix" + proc = install(tarball, prefix) + assert proc.returncode == 0, proc.stderr + assert "checksum OK" in proc.stdout and "envbao 9.9.9" in proc.stdout + assert (prefix / "bin" / "envbao").is_symlink() + assert (prefix / "lib" / "envbao" / "envbao").exists() + assert install(tarball, prefix).returncode == 0 # re-install over the top + + +def test_install_script_rejects_bad_checksum(tmp_path: Path) -> None: + tarball = make_tarball(tmp_path) + (tmp_path / "SHA256SUMS").write_text(f"{'0' * 64} {tarball.name}\n") + proc = install(tarball, tmp_path / "prefix") + assert proc.returncode == 1 and "mismatch" in proc.stderr + assert not (tmp_path / "prefix" / "bin" / "envbao").exists() + + +def test_install_script_unlisted_and_missing(tmp_path: Path) -> None: + tarball = make_tarball(tmp_path) + (tmp_path / "SHA256SUMS").write_text(f"{sha(tarball)} other.tar.gz\n") + assert "not listed" in install(tarball, tmp_path / "p").stderr + assert install(tmp_path / "nope.tar.gz", tmp_path / "p").returncode == 1 + + +def test_install_script_without_sums_warns(tmp_path: Path) -> None: + proc = install(make_tarball(tmp_path), tmp_path / "prefix") + assert proc.returncode == 0 and "skipping verification" in proc.stderr diff --git a/tests/test_runner.py b/tests/test_runner.py index 2fdce33..de57502 100644 --- a/tests/test_runner.py +++ b/tests/test_runner.py @@ -322,3 +322,26 @@ def test_audit_log_has_no_values_or_args(exec_cfg: Path) -> None: 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 + + +# ---- security.exec_only --------------------------------------------------------------- + + +def test_exec_only_blocks_plain_export_and_no_redact( + exec_cfg: Path, capsys: pytest.CaptureFixture[str] +) -> None: + exec_cfg.write_text(exec_cfg.read_text() + "\n[security]\nexec_only = true\n") + assert main(["--config", str(exec_cfg)]) == EXIT_CONFIG + assert "only permits" in capsys.readouterr().err + argv = ["--config", str(exec_cfg), "exec", "-q", "gitea", "--no-redact", "--", "true"] + assert main(argv) == EXIT_CONFIG + assert main(["--config", str(exec_cfg), "--check"]) == 0 + ok = ["--config", str(exec_cfg), "exec", "-q", "gitea", "--", sys.executable, "-c", "pass"] + assert main(ok) == 0 + + +def test_exec_only_must_be_bool() -> None: + with pytest.raises(ConfigError, match="exec_only"): + parse_config( + {"server": {"address": "https://b", "token": "t"}, "security": {"exec_only": "yes"}} + ) diff --git a/tests/test_setup_claude_access.py b/tests/test_setup_claude_access.py new file mode 100644 index 0000000..a886565 --- /dev/null +++ b/tests/test_setup_claude_access.py @@ -0,0 +1,159 @@ +import importlib.util +import json +import os +import stat +import sys +from pathlib import Path + +import pytest + +from envbao.config import load_config + +SCRIPTS = Path(__file__).parent.parent / "scripts" +sys.path.insert(0, str(SCRIPTS)) # the script imports its sibling migrate_zshrc +_spec = importlib.util.spec_from_file_location( + "setup_claude_access", SCRIPTS / "setup_claude_access.py" +) +assert _spec and _spec.loader +sca = importlib.util.module_from_spec(_spec) +sys.modules["setup_claude_access"] = sca +_spec.loader.exec_module(sca) + +STUB = """#!{python} +import json, os, sys +state = os.environ["STUB_DIR"] +args = sys.argv[1:] +stdin = "" if sys.stdin.isatty() else sys.stdin.read() +open(os.path.join(state, "calls.log"), "a").write(json.dumps({{"args": args}}) + "\\n") +if args[0] == "read": + print(json.dumps({{"data": {{"options": {{"version": "2"}}}}}})) +elif args[:2] == ["kv", "list"]: + print(json.dumps(["aws", "gitea", "wiki/"])) +elif args[:2] == ["policy", "write"]: + open(os.path.join(state, "policy.hcl"), "w").write(stdin) +elif args[:2] == ["token", "create"]: + print("s.claude-token-123") +elif args[:2] == ["audit", "list"]: + if os.environ.get("STUB_AUDIT"): + print("file/ file file_path=/x") + else: + sys.stderr.write("No audit devices are enabled."); sys.exit(2) +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() + 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-root") + monkeypatch.setenv("HOME", str(tmp_path)) + return {"state": state, "cfg": tmp_path / ".envbao", "home": tmp_path} + + +def run(env: dict[str, Path], *extra: str) -> int: + return sca.main(["--config-dir", str(env["cfg"]), *extra]) + + +def test_policy_text() -> None: + hcl = sca.policy_text("env", 2, ["aws", "gitea"]) + assert 'path "env/data/shell/aws"' in hcl and 'path "env/data/shell/gitea"' in hcl + assert "shell/*" not in hcl and "lookup-self" in hcl + assert 'path "env/shell/aws"' in sca.policy_text("env", 1, ["aws"]) + + +def test_merge_settings_idempotent_and_preserving() -> None: + existing = {"model": "x", "permissions": {"allow": ["Bash(ls:*)"], "deny": ["Bash(bao:*)"]}} + once = sca.merge_settings(existing, "/c/claude.toml") + twice = sca.merge_settings(once, "/c/claude.toml") + assert once == twice + assert once["model"] == "x" and "Bash(ls:*)" in once["permissions"]["allow"] + assert once["permissions"]["deny"].count("Bash(bao:*)") == 1 + assert once["env"]["ENVBAO_CONFIG"] == "/c/claude.toml" + assert "Bash(envbao exec:*)" in once["permissions"]["allow"] + assert existing["permissions"]["allow"] == ["Bash(ls:*)"] # input not mutated + + +def test_end_to_end(env: dict[str, Path], capsys: pytest.CaptureFixture[str]) -> None: + assert run(env) == 0 + out = capsys.readouterr() + text = out.out + out.err + assert "s.claude-token-123" not in text and "s.admin-root" not in text + assert "no OpenBao audit device" in text and "Recommended" in text + assert "wiki/" not in (env["state"] / "policy.hcl").read_text() # sub-folders skipped + + cfg_dir = env["cfg"] + assert stat.S_IMODE(cfg_dir.stat().st_mode) == 0o700 + for name in ("claude.toml", "claude-token"): + assert stat.S_IMODE((cfg_dir / name).stat().st_mode) == 0o600 + assert (cfg_dir / "claude-token").read_text() == "s.claude-token-123" + + cfg = load_config(cfg_dir / "claude.toml") + assert cfg.exec_only and cfg.server.token == "s.claude-token-123" + assert [q.name for q in cfg.queries] == ["aws", "gitea"] + assert all(q.on_missing == "error" for q in cfg.queries) + + argv = " ".join(a for line in (env["state"] / "calls.log").read_text().splitlines() + for a in json.loads(line)["args"]) # fmt: skip + assert "s.admin-root" not in argv and "s.claude-token" not in argv + assert "-orphan" in argv and "-display-name=envbao-claude" in argv + + +def test_audit_device_present_no_warning( + env: dict[str, Path], monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + monkeypatch.setenv("STUB_AUDIT", "1") + assert run(env) == 0 + assert "no OpenBao audit device" not in capsys.readouterr().out + + +def test_explicit_groups(env: dict[str, Path]) -> None: + assert run(env, "--groups", "gitea") == 0 + assert [q.name for q in load_config(env["cfg"] / "claude.toml").queries] == ["gitea"] + + +def test_refuses_to_replace_without_force(env: dict[str, Path], capsys) -> None: # type: ignore[no-untyped-def] + assert run(env) == 0 + assert run(env) == 1 + assert "--force" in capsys.readouterr().err + assert run(env, "--force") == 0 + assert (env["cfg"] / "claude.toml.bak").exists() + + +def test_settings_merge(env: dict[str, Path]) -> None: + settings = env["home"] / ".claude" / "settings.json" + settings.parent.mkdir() + settings.write_text(json.dumps({"model": "m"})) + assert run(env, "--settings") == 0 + data = json.loads(settings.read_text()) + assert data["model"] == "m" and data["env"]["ENVBAO_CONFIG"].endswith("claude.toml") + assert "Read(~/.envbao/**)" in data["permissions"]["deny"] + assert json.loads((settings.parent / "settings.json.bak").read_text()) == {"model": "m"} + + +def test_settings_created_when_missing(env: dict[str, Path]) -> None: + settings = env["home"] / "s" / "settings.json" + assert run(env, "--settings", str(settings)) == 0 + assert "permissions" in json.loads(settings.read_text()) + + +def test_requires_bao_env(env: dict[str, Path], monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("BAO_TOKEN") + assert run(env) == 1 + + +def test_no_groups(env: dict[str, Path], monkeypatch: pytest.MonkeyPatch, capsys) -> None: # type: ignore[no-untyped-def] + monkeypatch.setattr(sca, "list_groups", lambda bao, mount: []) + (env["cfg"] / "claude.toml").unlink(missing_ok=True) + (env["cfg"] / "claude-token").unlink(missing_ok=True) + assert run(env) == 1 + assert "no groups found" in capsys.readouterr().err