Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5af3aa524c | ||
|
|
952fa2ce63 | ||
|
|
08bacbc5a8 | ||
|
|
877b1ed99e | ||
|
|
926c0f0470 | ||
|
|
19a5373796 | ||
|
|
83cfa74416 |
No files matched your search
@@ -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 }}
|
||||
|
||||
@@ -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
|
||||
@@ -4,7 +4,26 @@ All notable changes are documented here. This project follows [Semantic Versioni
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.2.0] - 2026-10-16
|
||||
|
||||
### 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.
|
||||
|
||||
## [0.1.0]
|
||||
|
||||
### Added
|
||||
- `scripts/migrate_zshrc.py`: one-off migration of zshrc exports into OpenBao KV (`env/shell/<group>`),
|
||||
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).
|
||||
@@ -24,18 +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-<version>-linux-amd64`, `-linux-arm64`, `-macos-arm64`), verify it against `SHA256SUMS`,
|
||||
then:
|
||||
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
|
||||
chmod +x envbao-*; mv envbao-* ~/.local/bin/envbao
|
||||
```
|
||||
| Platform | Asset | Install |
|
||||
|----------|-------|---------|
|
||||
| macOS (Apple Silicon) | `envbao-<version>-macos-arm64.pkg` | `sudo installer -pkg envbao-<version>-macos-arm64.pkg -target /` |
|
||||
| Debian / Ubuntu (x86-64) | `envbao_<version>_amd64.deb` | `sudo dpkg -i envbao_<version>_amd64.deb` |
|
||||
| Debian / Ubuntu / Raspberry Pi OS (64-bit ARM) | `envbao_<version>_arm64.deb` | `sudo dpkg -i envbao_<version>_arm64.deb` |
|
||||
| Any other / no root | `envbao-<version>-<target>.tar.gz` | `scripts/install.sh envbao-<version>-<target>.tar.gz` |
|
||||
|
||||
Or run from source: `uv sync && uv run envbao --help`.
|
||||
* 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.
|
||||
|
||||
Check with `envbao --version`. Or run from source: `uv sync && uv run envbao --help`.
|
||||
|
||||
## Quick start
|
||||
|
||||
@@ -51,6 +63,23 @@ Add to `~/.zshrc` or `~/.bashrc`:
|
||||
command -v envbao >/dev/null && eval "$(envbao)"
|
||||
```
|
||||
|
||||
> **Caveat: `PATH` must already include `envbao` where this line runs.** The guard
|
||||
> `command -v envbao` is evaluated at that point in the file. If `~/.local/bin` (or wherever you
|
||||
> installed the binary) is only added to `PATH` *later* in your `.zshrc` / `.bashrc` (a common
|
||||
> case with Oh My Zsh, nvm or pyenv snippets), the guard fails and the line is **silently
|
||||
> skipped**: no variables are loaded, yet running `eval "$(envbao)"` by hand later works.
|
||||
>
|
||||
> Either put the line *after* your last `PATH` change, or avoid the dependency by using the
|
||||
> full path:
|
||||
>
|
||||
> ```sh
|
||||
> [ -x "$HOME/.local/bin/envbao" ] && eval "$("$HOME/.local/bin/envbao")"
|
||||
> ```
|
||||
>
|
||||
> To debug, open a new shell and run `command -v envbao`; if it prints nothing, `PATH` is the
|
||||
> problem. Remember that a failing `envbao` also prints nothing to stdout by design, so check
|
||||
> stderr and `~/.envbao/envbao.log` for the reason.
|
||||
|
||||
### Example `~/.envbao/config.toml`
|
||||
|
||||
```toml
|
||||
@@ -85,6 +114,8 @@ 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)
|
||||
- [Plans](docs/plans/)
|
||||
|
||||
@@ -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/<group>` 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.
|
||||
@@ -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. |
|
||||
|
||||
+12
-1
@@ -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.
|
||||
@@ -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 `<mount>/shell/<group>` (`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.
|
||||
@@ -0,0 +1,56 @@
|
||||
# Let Claude use OpenBao credentials via `envbao exec`, plus faster startup
|
||||
|
||||
## Context
|
||||
Credentials now live in OpenBao (`env/shell/<group>`). 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/<g>` 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-<ver>-<target>.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 <ver> --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_<ver>_amd64.deb`, `envbao_<ver>_arm64.deb`, `envbao-<ver>-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_<ver>_<arch>.deb` / `sudo installer -pkg envbao-<ver>-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/<unlisted>` 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.
|
||||
+12
-8
@@ -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-<ver>-<target>.tar.gz` everywhere, plus `envbao_<ver>_<arch>.deb` (linux, built in pure
|
||||
Python by `scripts/packaging/build_deb.py`) or `envbao-<ver>-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 /`.
|
||||
+7
-1
@@ -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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
+11
-4
@@ -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",
|
||||
)
|
||||
+1
-1
@@ -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
|
||||
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
#!/bin/sh
|
||||
# Install EnvBao from a release tarball (for systems without a .deb/.pkg).
|
||||
#
|
||||
# Usage: scripts/install.sh envbao-<version>-<target>.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
|
||||
@@ -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 ``<mount>/shell/<group>`` 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, "<redacted>")
|
||||
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/<group> 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())
|
||||
@@ -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 <mattcdaubney@gmail.com>"
|
||||
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"!<arch>\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))
|
||||
Executable
+28
@@ -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"
|
||||
Executable
+7
@@ -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."
|
||||
@@ -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
|
||||
``<mount>/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 ``<mount>/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())
|
||||
+51
-3
@@ -14,14 +14,15 @@ import sys
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
from envbao import __version__
|
||||
from envbao.client import BaoClient
|
||||
from envbao.config import Config, load_config, resolve_config_path
|
||||
from envbao.errors import EXIT_FAILURE, EXIT_OK, EnvBaoError, PermissionPolicyError
|
||||
from envbao.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
|
||||
|
||||
log = logging.getLogger("envbao")
|
||||
|
||||
@@ -46,6 +47,17 @@ path = "myapp/prod"
|
||||
"""
|
||||
|
||||
|
||||
class _VersionAction(argparse.Action):
|
||||
"""``--version`` that resolves the version lazily (git is never run otherwise)."""
|
||||
|
||||
def __init__(self, option_strings: Sequence[str], dest: str, **kwargs: object) -> None:
|
||||
super().__init__(option_strings, dest, nargs=0, help="show version and exit")
|
||||
|
||||
def __call__(self, parser: argparse.ArgumentParser, *args: object, **kwargs: object) -> None:
|
||||
sys.stdout.write(f"envbao {get_version()}\n")
|
||||
parser.exit()
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
"""Create the argument parser."""
|
||||
parser = argparse.ArgumentParser(
|
||||
@@ -74,7 +86,30 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
help="create ~/.envbao with safe permissions and a template config.toml",
|
||||
)
|
||||
parser.add_argument("-v", "--verbose", action="count", default=0, help="log more to stderr")
|
||||
parser.add_argument("--version", action="version", version=f"envbao {__version__}")
|
||||
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
|
||||
|
||||
|
||||
@@ -101,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)
|
||||
@@ -122,6 +159,17 @@ 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)
|
||||
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)
|
||||
|
||||
+44
-16
@@ -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
|
||||
@@ -33,9 +35,11 @@ _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", "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."""
|
||||
@@ -78,12 +83,14 @@ class Config:
|
||||
server: ServerConfig
|
||||
queries: tuple[Query, ...]
|
||||
allow_protected: frozenset[str] = frozenset()
|
||||
exec_only: bool = False
|
||||
|
||||
|
||||
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 +170,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 +208,7 @@ def _parse_query(raw: Any, index: int) -> Query:
|
||||
prefix=prefix,
|
||||
rename=dict(rename),
|
||||
on_missing=on_missing,
|
||||
name=name,
|
||||
)
|
||||
|
||||
|
||||
@@ -209,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:
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Version reporting.
|
||||
|
||||
Release binaries carry the version stamped into ``_version.py`` from the git tag. When
|
||||
running from a source checkout (stamp is the placeholder) the version is derived from
|
||||
``git describe`` so a development build never masquerades as a release, e.g.
|
||||
``0.1.0.dev3+g19a5373`` (3 commits after ``v0.1.0``), with ``.dirty`` appended if the
|
||||
working tree has uncommitted changes.
|
||||
|
||||
git is only consulted lazily (``--version``), never during normal shell start-up.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shutil
|
||||
import subprocess # noqa: S404
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from envbao._version import __version__ as STAMPED
|
||||
|
||||
PLACEHOLDER = "0.0.0.dev0"
|
||||
_DESCRIBE_RE = re.compile(r"^v(?P<tag>.+?)-(?P<n>\d+)-g(?P<sha>[0-9a-f]+)(?P<dirty>-dirty)?$")
|
||||
|
||||
|
||||
def format_describe(described: str) -> str | None:
|
||||
"""Convert ``git describe --long --dirty`` output to a PEP 440 style version.
|
||||
|
||||
``v0.1.0-0-gabc1234`` -> ``0.1.0``;
|
||||
``v0.1.0-3-gabc1234-dirty`` -> ``0.1.0.dev3+gabc1234.dirty``.
|
||||
Returns None if the text is not from a ``v*`` tag.
|
||||
"""
|
||||
match = _DESCRIBE_RE.match(described.strip())
|
||||
if not match:
|
||||
return None
|
||||
tag, count, sha, dirty = match["tag"], int(match["n"]), match["sha"], bool(match["dirty"])
|
||||
if count == 0 and not dirty:
|
||||
return tag
|
||||
local = f"g{sha}.dirty" if dirty else f"g{sha}"
|
||||
return f"{tag}.dev{count}+{local}"
|
||||
|
||||
|
||||
def _git_version(root: Path) -> str | None:
|
||||
git = shutil.which("git")
|
||||
if not git or not (root / ".git").exists():
|
||||
return None
|
||||
try:
|
||||
proc = subprocess.run( # noqa: S603
|
||||
[git, "describe", "--tags", "--long", "--dirty", "--match", "v[0-9]*"],
|
||||
cwd=root,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return None
|
||||
return format_describe(proc.stdout) if proc.returncode == 0 else None
|
||||
|
||||
|
||||
def get_version() -> str:
|
||||
"""Return the stamped release version, or a git-derived one for source checkouts."""
|
||||
if STAMPED != PLACEHOLDER or getattr(sys, "frozen", False):
|
||||
return STAMPED
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
return _git_version(root) or STAMPED
|
||||
+3
-3
@@ -6,9 +6,9 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from envbao import __version__
|
||||
from envbao.cli import init_config, main
|
||||
from envbao.errors import EXIT_AUTH, EXIT_CONFIG, EXIT_FAILURE, EXIT_OK, EXIT_UNAVAILABLE
|
||||
from envbao.version import get_version
|
||||
|
||||
from .conftest import TOKEN, FakeBao, write_config
|
||||
|
||||
@@ -171,7 +171,7 @@ def test_version(capsys: pytest.CaptureFixture[str]) -> None:
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
main(["--version"])
|
||||
assert exc.value.code == 0
|
||||
assert __version__ in capsys.readouterr().out
|
||||
assert get_version() in capsys.readouterr().out
|
||||
|
||||
|
||||
# ---- init -----------------------------------------------------------------------------
|
||||
@@ -221,4 +221,4 @@ def test_python_dash_m(tmp_path: Path) -> None:
|
||||
check=True,
|
||||
env={**os.environ},
|
||||
)
|
||||
assert __version__ in result.stdout
|
||||
assert get_version() in result.stdout
|
||||
@@ -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 <redacted> 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)
|
||||
@@ -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"!<arch>\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
|
||||
@@ -0,0 +1,347 @@
|
||||
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
|
||||
|
||||
|
||||
# ---- 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"}}
|
||||
)
|
||||
@@ -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
|
||||
@@ -0,0 +1,87 @@
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from envbao import version
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"described, expected",
|
||||
[
|
||||
("v0.1.0-0-g19a5373", "0.1.0"),
|
||||
("v0.1.0-3-g19a5373", "0.1.0.dev3+g19a5373"),
|
||||
("v1.2.3-rc.1-0-gabc1234", "1.2.3-rc.1"),
|
||||
("v0.1.0-0-g19a5373-dirty", "0.1.0.dev0+g19a5373.dirty"),
|
||||
("v0.1.0-3-g19a5373-dirty\n", "0.1.0.dev3+g19a5373.dirty"),
|
||||
("19a5373", None),
|
||||
("", None),
|
||||
("release-1-g123", None),
|
||||
],
|
||||
)
|
||||
def test_format_describe(described: str, expected: str | None) -> None:
|
||||
assert version.format_describe(described) == expected
|
||||
|
||||
|
||||
def test_stamped_release_version_wins(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(version, "STAMPED", "2.0.0")
|
||||
monkeypatch.setattr(version, "_git_version", lambda root: pytest.fail("git must not run"))
|
||||
assert version.get_version() == "2.0.0"
|
||||
|
||||
|
||||
def test_frozen_never_uses_git(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(version.sys, "frozen", True, raising=False)
|
||||
monkeypatch.setattr(version, "_git_version", lambda root: pytest.fail("git must not run"))
|
||||
assert version.get_version() == version.STAMPED
|
||||
|
||||
|
||||
def test_source_checkout_uses_git(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(version, "STAMPED", version.PLACEHOLDER)
|
||||
monkeypatch.setattr(version, "_git_version", lambda root: "0.1.0.dev3+gabc")
|
||||
assert version.get_version() == "0.1.0.dev3+gabc"
|
||||
|
||||
|
||||
def test_falls_back_to_placeholder(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(version, "STAMPED", version.PLACEHOLDER)
|
||||
monkeypatch.setattr(version, "_git_version", lambda root: None)
|
||||
assert version.get_version() == version.PLACEHOLDER
|
||||
|
||||
|
||||
def test_git_version_no_repo(tmp_path: Path) -> None:
|
||||
assert version._git_version(tmp_path) is None # noqa: SLF001
|
||||
|
||||
|
||||
def test_git_version_real_repo(tmp_path: Path) -> None:
|
||||
def git(*a: str) -> None:
|
||||
subprocess.run( # noqa: S603
|
||||
["git", "-c", "user.name=t", "-c", "user.email=t@t", *a], # noqa: S607
|
||||
cwd=tmp_path, check=True, capture_output=True,
|
||||
) # fmt: skip
|
||||
|
||||
git("init", "-q")
|
||||
(tmp_path / "f").write_text("1")
|
||||
git("add", "f")
|
||||
git("commit", "-qm", "one")
|
||||
git("tag", "v1.0.0")
|
||||
assert version._git_version(tmp_path) == "1.0.0" # noqa: SLF001
|
||||
(tmp_path / "f").write_text("2")
|
||||
git("commit", "-qam", "two")
|
||||
assert version._git_version(tmp_path).startswith("1.0.0.dev1+g") # type: ignore[union-attr] # noqa: SLF001
|
||||
(tmp_path / "f").write_text("3")
|
||||
assert version._git_version(tmp_path).endswith(".dirty") # type: ignore[union-attr] # noqa: SLF001
|
||||
|
||||
|
||||
def test_git_missing(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
(tmp_path / ".git").mkdir()
|
||||
monkeypatch.setattr(version.shutil, "which", lambda name: None)
|
||||
assert version._git_version(tmp_path) is None # noqa: SLF001
|
||||
|
||||
|
||||
def test_git_failure(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
(tmp_path / ".git").mkdir()
|
||||
|
||||
def boom(*a: object, **k: object) -> None:
|
||||
raise OSError
|
||||
|
||||
monkeypatch.setattr(version.subprocess, "run", boom)
|
||||
assert version._git_version(tmp_path) is None # noqa: SLF001
|
||||
Reference in new issue
Block a user