Initial implementation of EnvBao
test / test (push) Failing after 2s
release / validate (push) Successful in 2s
release / build (linux-amd64, linux-amd64) (push) Successful in 38s
release / build (macos-arm64, macos-arm64) (push) Successful in 45s
release / build (linux-arm64, linux-arm64) (push) Successful in 1m19s
release / release (push) Successful in 15s

Single-binary CLI that injects environment variables from an OpenBao
server into the shell via eval "$(envbao)".

- Strict permission policy for ~/.envbao (exits 78 if unsafe)
- KV v1/v2 engine with auto-detection, pluggable engine registry
- Safe quoting for bash/zsh/sh/fish, protected-variable denylist
- Audit logging (stderr, private rotating file, syslog); no secrets logged
- Gitea pipelines for tests and SemVer-tag releases
- PyInstaller spec, docs, BSD-3-Clause licence

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-15 21:20:15 +01:00
commit d5636c46c7
37 files changed
+3234

No files matched your search

+51
View File
@@ -0,0 +1,51 @@
# Configuration reference
File: `~/.envbao/config.toml`. Unknown keys and wrong types are rejected, so typos fail loudly.
## `[server]`
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `address` | string | *required* | Base URL, e.g. `https://bao.example.com:8200`. No credentials in the URL. |
| `token` | string | | OpenBao token. Exactly one of `token` / `token_file` is required. |
| `token_file` | string | | Path (`~` expanded) to a file containing the token. Must pass the same permission policy (owner only, not a symlink). |
| `namespace` | string | | Sent as `X-Vault-Namespace`. |
| `ca_cert` | string | system store | PEM CA bundle used to verify the server. |
| `timeout` | number | `5` | Per-request timeout in seconds. |
| `allow_insecure_http` | bool | `false` | Permit `http://` to a non-loopback host. Loopback (`127.0.0.1`, `::1`, `localhost`) is always allowed over HTTP. Not recommended: the token travels in clear. |
## `[security]`
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `allow_protected` | list of strings | `[]` | Protected variable names (see [security.md](security.md)) that secrets may set, e.g. `["PATH"]`. |
## `[[query]]`
One table per secret source. Queries run in order; later ones override earlier ones.
Common keys:
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `engine` | string | `"kv"` | Secret engine. Currently only `kv`. |
| `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. |
| `on_missing` | `"warn"` \| `"error"` | `"warn"` | What to do if the secret or a listed key does not exist. `error` aborts the whole run. |
### `engine = "kv"`
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `mount` | string | *required* | KV mount path, e.g. `secret`. |
| `path` | string | *required* | Secret path within the mount. |
| `kv_version` | `1` \| `2` \| `"auto"` | `"auto"` | `auto` queries `sys/internal/ui/mounts/<mount>`; set explicitly if the token cannot read that endpoint. |
Names that are not valid variable names (`[A-Za-z_][A-Za-z0-9_]*`) are skipped with a warning.
## Adding an engine
Implement `envbao.engines.Engine` (`validate` and `fetch`) in a new module under
`src/envbao/engines/`, register it in `ENGINES`, and document its options here. Filtering,
renaming, prefixing, name validation and rendering are shared.
+55
View File
@@ -0,0 +1,55 @@
# Development
## Setup
```sh
uv sync --all-groups
```
## Checks (also run by CI)
```sh
uv run ruff check . && uv run ruff format --check .
uv run mypy # strict
uv run pytest --cov # fails below 90 % coverage
```
## Layout
| Module | Responsibility |
|--------|----------------|
| `cli.py` | Argument parsing, orchestration, exit codes |
| `security.py` | Filesystem permission policy |
| `config.py` | Strict TOML parsing into dataclasses |
| `client.py` | stdlib HTTP client for the OpenBao API (TLS, no redirects) |
| `engines/` | Secret engines (`kv`); extension point for more |
| `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 |
| `errors.py` | Exceptions and exit codes |
## Testing approach
- `tests/conftest.py` provides `fake_bao`, an in-process HTTP server emulating the OpenBao endpoints
used (KV v1/v2, mount detection, `lookup-self`, redirects), so tests need no real server.
- Permission tests build real directories under `tmp_path` and `chmod` them.
- Rendering tests execute the output in `/bin/sh` to prove values round-trip unchanged.
## Building locally
```sh
uv run pyinstaller envbao.spec --clean --noconfirm
./dist/envbao --version
```
PyInstaller cannot cross-compile; build on the platform you target.
## Testing against a real OpenBao
```sh
bao server -dev -dev-root-token-id=dev &
export BAO_ADDR=http://127.0.0.1:8200 BAO_TOKEN=dev
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
```
+72
View File
@@ -0,0 +1,72 @@
# EnvBao – implementation plan
## Context
Build `envbao`, a single-binary CLI invoked from `.zshrc`/`.bashrc` (`eval "$(envbao)"`) that pulls secrets from a running OpenBao server and emits shell `export` statements. Config (server, token, queries) lives in `~/.envbao/config.toml`. Security first: strict permission checks, no secret leakage, auditable logging. Repo is currently empty apart from a stub `pyproject.toml` (Python >=3.13, uv, no deps). Remote: `ssh://git@git.daubney.dev:222/matt/EnvBao.git`. Licence BSD-3-Clause.
## Stack
- Python 3.13, `uv`, src layout (`src/envbao/`), stdlib only at runtime where possible: `tomllib`, `urllib.request`/`ssl`, `logging`, `argparse`, `shlex`. (No `hvac`/`httpx` → smaller binary, smaller attack surface.)
- Dev: `pytest`, `pytest-cov`, `ruff`, `mypy`, `pyinstaller`, `responses`-free: tests use a local `http.server` fake OpenBao.
- Build: PyInstaller `--onefile` (via `envbao.spec`), version injected from git tag.
## Layout
```
src/envbao/
__main__.py / cli.py argparse: default=emit exports; --shell {bash,zsh,fish,auto}; --config PATH; --check; --version; -v
config.py load + validate config.toml (dataclasses), token/token_file/ENVBAO_TOKEN-free by design
security.py permission checks (dir 0700, files 0600, owned by euid, no symlink escape, not group/world accessible); exit code 78 on failure
client.py minimal OpenBao HTTP client (X-Vault-Token, TLS verify on by default, timeout, CA bundle option, refuse http:// to non-loopback unless allow_insecure_http)
engines/__init__.py Engine protocol + registry (extension point for mid-term: approle, database, aws, ssh etc.)
engines/kv.py KV v1/v2 with auto-detect via sys/internal/ui/mounts/<path>; list/read, key filter, prefix, rename
render.py env-var name validation ([A-Za-z_][A-Za-z0-9_]*), shlex-quoted export/set -gx output, reject control chars/newlines
logging_setup.py stderr + rotating file log ~/.envbao/envbao.log (0600); NEVER logs token/values, only names/paths/status
tests/ unit + integration (fake OpenBao server) + permission tests (tmp_path, chmod)
docs/ usage.md, configuration.md, security.md, development.md, releasing.md
.gitea/workflows/test.yml on push/PR: ruff, mypy, pytest --cov (fail-under 90), py3.13
.gitea/workflows/release.yml on tag v*.*.*: validate semver, build linux-amd64/linux-arm64/macos-arm64, sha256sums, publish via Gitea release API
envbao.spec, LICENSE (BSD-3-Clause, © Matt Daubney), README.md, CHANGELOG.md, .gitignore, pyproject.toml (deps/groups/scripts)
```
## Config (`~/.envbao/config.toml`)
```toml
[server]
address = "https://bao.example.com:8200"
token = "s.xxxx" # or token_file = "~/.envbao/token" (also perm-checked)
namespace = "" # optional X-Vault-Namespace
ca_cert = "" # optional
timeout = 5
[[query]] # one per secret source; "engine" defaults to "kv"
engine = "kv"
mount = "secret"
path = "myapp/prod"
keys = ["DB_URL", "API_KEY"] # optional filter
prefix = "MYAPP_" # optional
rename = { DB_URL = "DATABASE_URL" } # optional
on_missing = "warn" # warn | error
```
Unknown `engine` → clear error; engine registry means new credential engines are added as modules without touching CLI/render.
## Security behaviours
1. Before reading anything: `~/.envbao` must be a real directory owned by current user with mode `0700`; every file inside `0600` and owned by user; otherwise log CRITICAL, print nothing to stdout, exit non-zero (78). Symlinks rejected.
2. Config parse errors, auth failures (403), connection/TLS errors → logged, **stdout stays empty** (so `eval` is a no-op) and a short message goes to stderr; exit code non-zero. Partial-failure policy governed by `on_missing`.
3. Output quoting via `shlex.quote`; names validated; values containing NUL rejected.
4. Token never logged or placed in argv/env; HTTP errors redacted. Optional `--check` validates config/perms/token (`auth/token/lookup-self`) without emitting values.
5. Fail-closed on TLS; plain HTTP only with explicit `allow_insecure_http=true` and loopback otherwise warned.
6. Logs: file at `0600`, events: perm violation, auth fail, each query success/fail (path only), count of vars exported.
## CI/CD (Gitea Actions)
- `test.yml`: `astral-sh/setup-uv`, `uv sync --all-groups`, ruff, mypy, pytest with coverage.
- `release.yml`: trigger `push: tags: ['v*']`; regex-check `^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$`; matrix of runners by label (`linux-amd64`, `linux-arm64`, and **`macos-arm64`** for the macOS build — labels documented in `docs/releasing.md`, as PyInstaller can't cross-compile); version written into `src/envbao/_version.py` at build from tag; artifacts `envbao-<ver>-<os>-<arch>` + `SHA256SUMS` uploaded to the Gitea release (token secret `RELEASE_TOKEN`).
## Execution steps
0. First action once approved: copy this plan verbatim into the repo as `docs/plans/001-initial-implementation.md` (plan mode currently blocks writing outside the plan file), and commit it with the scaffold.
1. `git init`, add remote, scaffold pyproject/LICENSE/.gitignore and a full **README.md** (what/why, install from release binary, quick start with `eval "$(envbao)"` for zsh/bash, example config, permission requirements, security notes, exit codes, CI/release summary, links to `docs/`, licence badge). README is kept in sync with features at the end of step 4.
2. Implement security → config → render → client → kv engine → cli (TDD, tests alongside each module).
3. Fake-OpenBao integration tests (KV v1, v2, auto-detect, 403, TLS/HTTP policy, missing keys).
4. Docs, CI workflows, PyInstaller spec; local build smoke test.
5. Initial commit (no push unless asked).
## Verification
- `uv run pytest --cov` (≥90%), `ruff check`, `mypy --strict`.
- `uv run pyinstaller envbao.spec` → run `dist/envbao --version`; `eval "$(dist/envbao --config test.toml)"` against a local `bao server -dev` (if installed) or the fake server; confirm `chmod 644 config.toml` makes it exit non-zero with empty stdout.
- Lint the workflow YAML; tag-regex unit test with valid/invalid semver strings.
+47
View File
@@ -0,0 +1,47 @@
# Releasing and CI
## Pipelines (`.gitea/workflows/`)
- **`test.yml`** - on every push and pull request: ruff, ruff format check, strict mypy, pytest with a
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.
## Cutting a release
```sh
git tag v1.0.0 && git push origin v1.0.0
```
Update `CHANGELOG.md` first.
## Runner requirements
PyInstaller cannot cross-compile, so the pipeline needs one Gitea `act_runner` per target, registered
with these labels:
| Label | Host |
|-------|------|
| `linux-amd64` | Linux x86-64 (also runs tests, validation and publishing; needs `curl`, `python3`) |
| `linux-arm64` | Linux aarch64 |
| `macos-arm64` | macOS on Apple Silicon (host-mode runner, e.g. `macos-arm64:host`) |
Runners need network access to fetch `astral-sh/setup-uv` and Python packages.
## Secrets
| Secret | Purpose |
|--------|---------|
| `RELEASE_TOKEN` | Gitea access token with `write:repository` scope, used to create the release and upload assets. |
## 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.
+43
View File
@@ -0,0 +1,43 @@
# Security model
## Threat model
`envbao` protects a long-lived OpenBao token on a single-user workstation and makes sure secrets
reach the shell without being exposed or interpreted as code. It does **not** defend against an
attacker who already runs as you or as root, nor does it protect the environment of processes once
variables are exported (any child process inherits them).
## Controls
1. **Permission policy** - before anything else, `~/.envbao` (or the `--config` parent) and every
entry beneath it must be: not a symlink, a regular file/directory, owned by the current user,
and without any group/other permission bits (effectively `0700` dirs / `0600` files). Otherwise
`envbao` logs CRITICAL, prints nothing to stdout, never contacts the server, and exits 78.
A `token_file` outside the directory is checked identically.
2. **Fail closed** - output is produced only after every query succeeded. Errors yield empty stdout.
3. **Transport** - TLS verification is always on (optional `ca_cert`). `http://` is only allowed to
loopback unless `allow_insecure_http = true`. Redirects are never followed, so the token cannot be
forwarded elsewhere. Responses are size-limited.
4. **Injection safety** - names must match `[A-Za-z_][A-Za-z0-9_]*`; values are quoted
(`shlex.quote`, or fish single-quote escaping) and NUL bytes are rejected. Tests round-trip
hostile values (`$(...)`, backticks, quotes, newlines) through a real shell.
5. **Protected variables** - secrets may not set shell/loader control variables such as `PATH`,
`IFS`, `ENV`, `BASH_ENV`, `PROMPT_COMMAND`, `LD_*`, `DYLD_*`, `PYTHONPATH`, `NODE_OPTIONS`, etc.,
unless explicitly listed in `[security] allow_protected`. Refusals are logged at ERROR.
6. **No secret leakage** - the token is excluded from `repr()`, never put on a command line or in
the environment, and never logged. Secret values are never logged. HTTP error messages carry only
status and path. Unexpected exceptions log only their type, not a traceback, unless `-vv`.
7. **Audit trail** - log file (`0600`, created atomically with that mode, rotated) plus best-effort
syslog for WARNING and above. Events: permission violations, auth failures, per-query outcome,
overrides, refused variables, count of exported variables.
## 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`.
## Reporting a vulnerability
Please report privately to the maintainer rather than opening a public issue.
+51
View File
@@ -0,0 +1,51 @@
# Usage
```
envbao [--config PATH] [--shell {auto,bash,zsh,sh,fish}] [-v|-vv] [--check | --init]
envbao --version
```
| Option | Description |
|--------|-------------|
| *(none)* | Fetch all queries and print export statements to stdout. |
| `--config PATH` | Use another config file. Its **parent directory** is the one permission-checked. |
| `--shell` | Output dialect. `auto` (default) picks from `$SHELL`; unknown shells get POSIX syntax. |
| `--check` | Validate permissions, config and token (via `auth/token/lookup-self`). Prints nothing to stdout. |
| `--init` | Create `~/.envbao` (0700) and a template `config.toml` (0600). Never overwrites. |
| `-v` / `-vv` | Show INFO / DEBUG messages on stderr. |
## Shell integration
bash / zsh:
```sh
command -v envbao >/dev/null && eval "$(envbao)"
```
fish (`~/.config/fish/config.fish`):
```fish
type -q envbao; and envbao | source
```
**Behaviour on failure:** stdout is empty and the exit code is non-zero, so `eval` does nothing and
your shell starts normally; the reason is printed to stderr and logged. If you prefer silence at
shell start-up, append `2>/dev/null` (details remain in `~/.envbao/envbao.log`).
## Output
Values are always single-quoted, so they can never be interpreted as shell syntax:
```sh
export DATABASE_URL='postgres://u:p@h/db'
export MYAPP_GREETING='it'"'"'s fine'
```
Non-string secret values (numbers, booleans, nested objects) are converted to JSON text.
Later `[[query]]` tables override earlier ones; overrides are logged.
## Logs
Records go to stderr (WARNING+ by default), the system log (WARNING+, best effort), and
`~/.envbao/envbao.log` (INFO+, mode 0600, rotated at 256 KiB, 3 backups). The log contains paths,
variable *names*, counts and outcomes only.