Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6e3d9049f | ||
|
|
0cde1ff7f7 | ||
|
|
78ff2b0ddd | ||
|
|
5af3aa524c | ||
|
|
952fa2ce63 | ||
|
|
08bacbc5a8 | ||
|
|
877b1ed99e | ||
|
|
926c0f0470 | ||
|
|
19a5373796 | ||
|
|
83cfa74416 |
No files matched your search
@@ -0,0 +1,47 @@
|
||||
name: build-check
|
||||
# Linux build in Debian 12 + glibc guard, without publishing a release.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: ["ci/**"]
|
||||
|
||||
jobs:
|
||||
build-check:
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
include:
|
||||
# PyInstaller cannot cross-compile: each target builds on a matching runner.
|
||||
# Building inside Debian 12 (glibc 2.36) keeps the binaries runnable on bookworm and newer.
|
||||
- { runner: linux-amd64, target: linux-amd64, deb_arch: amd64 }
|
||||
- { runner: linux-arm64, target: linux-arm64, deb_arch: arm64 }
|
||||
runs-on: ${{ matrix.runner }}
|
||||
container:
|
||||
image: node:20-bookworm
|
||||
env:
|
||||
VERSION: 0.0.0-check
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
python-version: "3.13"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-groups --frozen
|
||||
- name: Test
|
||||
run: uv run pytest -q --cov
|
||||
- name: Build one-dir application
|
||||
run: uv run pyinstaller envbao.spec --clean --noconfirm
|
||||
- name: Smoke test
|
||||
run: ./dist/envbao/envbao --version
|
||||
- name: Check glibc requirement is Debian 12 compatible (<= 2.36)
|
||||
run: |
|
||||
max="$(objdump -T dist/envbao/envbao dist/envbao/_internal/*.so* 2>/dev/null | grep -o 'GLIBC_[0-9.]*' | sed 's/GLIBC_//' | sort -Vu | tail -1)"
|
||||
echo "max glibc symbol: ${max}"
|
||||
test "$(printf '%s\n2.36\n' "${max}" | sort -V | tail -1)" = "2.36"
|
||||
- name: Package
|
||||
run: |
|
||||
mkdir -p out
|
||||
tar -C dist -czf "out/envbao-${VERSION}-${{ matrix.target }}.tar.gz" envbao
|
||||
python3 scripts/packaging/build_deb.py "${VERSION}" "${{ matrix.deb_arch }}" dist out
|
||||
ls -l out
|
||||
|
||||
@@ -18,17 +18,21 @@ jobs:
|
||||
version="$(python3 scripts/version_from_tag.py "${GITHUB_REF_NAME}")"
|
||||
echo "version=${version}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
build:
|
||||
build-linux:
|
||||
needs: validate
|
||||
strategy:
|
||||
fail-fast: true
|
||||
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 }
|
||||
# Building inside Debian 12 (glibc 2.36) keeps the binaries runnable on bookworm and newer.
|
||||
- { runner: linux-amd64, target: linux-amd64, deb_arch: amd64 }
|
||||
- { runner: linux-arm64, target: linux-arm64, deb_arch: arm64 }
|
||||
runs-on: ${{ matrix.runner }}
|
||||
container:
|
||||
image: node:20-bookworm
|
||||
env:
|
||||
VERSION: ${{ needs.validate.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: astral-sh/setup-uv@v5
|
||||
@@ -40,19 +44,59 @@ 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: Check glibc requirement is Debian 12 compatible (<= 2.36)
|
||||
run: |
|
||||
test "$(./dist/envbao --version)" = "envbao ${{ needs.validate.outputs.version }}"
|
||||
mv dist/envbao "dist/envbao-${{ needs.validate.outputs.version }}-${{ matrix.target }}"
|
||||
max="$(objdump -T dist/envbao/envbao dist/envbao/_internal/*.so* 2>/dev/null | grep -o 'GLIBC_[0-9.]*' | sed 's/GLIBC_//' | sort -Vu | tail -1)"
|
||||
echo "max glibc symbol: ${max}"
|
||||
test "$(printf '%s\n2.36\n' "${max}" | sort -V | tail -1)" = "2.36"
|
||||
- name: Package
|
||||
run: |
|
||||
mkdir -p out
|
||||
tar -C dist -czf "out/envbao-${VERSION}-${{ matrix.target }}.tar.gz" envbao
|
||||
python3 scripts/packaging/build_deb.py "${VERSION}" "${{ matrix.deb_arch }}" dist out
|
||||
ls -l out
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: envbao-${{ matrix.target }}
|
||||
path: dist/envbao-*
|
||||
path: out/*
|
||||
|
||||
build-macos:
|
||||
needs: validate
|
||||
runs-on: macos-arm64
|
||||
env:
|
||||
VERSION: ${{ needs.validate.outputs.version }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: astral-sh/setup-uv@v5
|
||||
with:
|
||||
python-version: "3.13"
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-groups --frozen
|
||||
- name: Test
|
||||
run: uv run pytest -q --cov
|
||||
- name: Stamp version from tag
|
||||
run: python3 scripts/version_from_tag.py "${GITHUB_REF_NAME}"
|
||||
- name: Build one-dir application
|
||||
run: uv run pyinstaller envbao.spec --clean --noconfirm
|
||||
- name: Smoke test
|
||||
run: test "$(./dist/envbao/envbao --version)" = "envbao ${VERSION}"
|
||||
- name: Package
|
||||
run: |
|
||||
mkdir -p out
|
||||
tar -C dist -czf "out/envbao-${VERSION}-macos-arm64.tar.gz" envbao
|
||||
sh scripts/packaging/build_pkg.sh "${VERSION}" dist out
|
||||
ls -l out
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: envbao-macos-arm64
|
||||
path: out/*
|
||||
|
||||
release:
|
||||
needs: [validate, build]
|
||||
needs: [validate, build-linux, build-macos]
|
||||
runs-on: linux-amd64
|
||||
steps:
|
||||
- uses: actions/download-artifact@v3
|
||||
@@ -61,8 +105,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 }}
|
||||
@@ -80,3 +124,18 @@ jobs:
|
||||
curl -fsS -X POST "$API/releases/$id/assets?name=$(basename "$f")" \
|
||||
-H "Authorization: token $TOKEN" -F "attachment=@$f" >/dev/null
|
||||
done
|
||||
|
||||
# Ask the playbooks repo to roll the new release out to every node.
|
||||
deploy:
|
||||
needs: release
|
||||
runs-on: linux-amd64
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- name: Trigger playbooks deploy (envbao)
|
||||
env:
|
||||
TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||
SERVER: ${{ github.server_url }}
|
||||
run: |
|
||||
curl -fsS -X POST "$SERVER/api/v1/repos/matt/playbooks/actions/workflows/deploy.yml/dispatches" \
|
||||
-H "Authorization: token $TOKEN" -H 'Content-Type: application/json' \
|
||||
-d '{"ref":"main","inputs":{"playbook":"envbao","limit":"","check_only":"false","allow_reboot":"false"}}'
|
||||
@@ -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,35 @@ All notable changes are documented here. This project follows [Semantic Versioni
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.3.0] - 2026-11-09
|
||||
|
||||
### Added
|
||||
- Credential engines `database` (PostgreSQL etc.), `aws`, `approle` and `ssh`.
|
||||
- `BaoClient.post` for engines that generate credentials on write.
|
||||
- `cache = true` on `database` (dynamic) and `aws` queries: reuse the credential until near lease
|
||||
expiry (`0600` file by default, or the keychain), revoke the old lease on refresh; `[cache] store`
|
||||
and `envbao --clear-cache`.
|
||||
|
||||
## [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).
|
||||
@@ -1,3 +1,5 @@
|
||||
<p align="center"><img src="assets/logo.svg" alt="EnvBao logo: a steamed bun with a terminal prompt face" width="128"></p>
|
||||
|
||||
# EnvBao
|
||||
|
||||
[](LICENSE)
|
||||
@@ -18,24 +20,38 @@ safely quoted `export` statements for your shell to evaluate.
|
||||
you only; all failures print *nothing* to stdout, so a failed run can never half-configure
|
||||
your shell. See [docs/security.md](docs/security.md).
|
||||
- **Config-driven queries** - choose exactly which secrets, keys, prefixes and renames you want.
|
||||
- **KV v1 and v2** with automatic version detection. Other credential engines are planned and
|
||||
slot into an engine registry.
|
||||
- **KV v1 and v2** with automatic version detection.
|
||||
- **Dynamic credentials** from the OpenBao `database` (e.g. PostgreSQL), `aws`, `approle` and `ssh`
|
||||
engines; see `docs/configuration.md`. `cache = true` reuses a credential until near expiry, so
|
||||
it is safe in a startup `eval`.
|
||||
- **Audited** - issues are logged to stderr, `~/.envbao/envbao.log` (mode 0600) and the system
|
||||
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 +67,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 +118,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,13 @@
|
||||
# Logo assets
|
||||
|
||||
The EnvBao mascot: a steamed bun (包, as in OpenBao) with a `>_` terminal prompt for a face.
|
||||
|
||||
| File | Use |
|
||||
|------|-----|
|
||||
| `logo.svg` | Primary, for light backgrounds |
|
||||
| `logo-dark.svg` | For dark backgrounds |
|
||||
| `logo-mono.svg` | Single colour, follows `currentColor` (stamps, print, one-colour contexts) |
|
||||
| `logo-512.png` | Raster, transparent background |
|
||||
| `favicon.ico`, `favicon-{16,32,48}.png` | Favicons |
|
||||
|
||||
The PNGs are rendered from `logo.svg` with headless Chrome (ImageMagick's built-in SVG renderer drops strokes).
|
||||
|
After Width: | Height: | Size: 624 B |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.9 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 23 KiB |
@@ -0,0 +1,11 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-label="EnvBao: a steamed bun with a terminal prompt face">
|
||||
<title>EnvBao</title>
|
||||
<path d="M26 128C26 80 66 48 100 48C134 48 174 80 174 128C174 156 142 168 100 168C58 168 26 156 26 128Z" fill="#d9b27a" stroke="#e8ebf2" stroke-width="6" stroke-linejoin="round"/>
|
||||
<path d="M100 48C92 66 86 82 80 100M100 48C100 68 100 84 100 102M100 48C108 66 114 82 120 100" fill="none" stroke="#e8ebf2" stroke-width="5" stroke-linecap="round"/>
|
||||
<path d="M44 150C60 160 80 163 100 163" fill="none" stroke="#b78e55" stroke-width="5" stroke-linecap="round" opacity=".7"/>
|
||||
<ellipse cx="46" cy="140" rx="10" ry="6" fill="#f09a80" opacity=".7"/>
|
||||
<ellipse cx="154" cy="140" rx="10" ry="6" fill="#f09a80" opacity=".7"/>
|
||||
<g fill="none" stroke="#e8ebf2" stroke-width="7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M62 112L80 124L62 136"/><path d="M104 138H132"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 959 B |
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-label="EnvBao: a steamed bun with a terminal prompt face">
|
||||
<title>EnvBao</title>
|
||||
<path d="M26 128C26 80 66 48 100 48C134 48 174 80 174 128C174 156 142 168 100 168C58 168 26 156 26 128Z" fill="none" stroke="currentColor" stroke-width="6" stroke-linejoin="round"/>
|
||||
<path d="M100 48C92 66 86 82 80 100M100 48C100 68 100 84 100 102M100 48C108 66 114 82 120 100" fill="none" stroke="currentColor" stroke-width="5" stroke-linecap="round"/>
|
||||
<g fill="none" stroke="currentColor" stroke-width="7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M62 112L80 124L62 136"/><path d="M104 138H132"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 698 B |
@@ -0,0 +1,11 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" role="img" aria-label="EnvBao: a steamed bun with a terminal prompt face">
|
||||
<title>EnvBao</title>
|
||||
<path d="M26 128C26 80 66 48 100 48C134 48 174 80 174 128C174 156 142 168 100 168C58 168 26 156 26 128Z" fill="#f1d8a6" stroke="#1b2130" stroke-width="6" stroke-linejoin="round"/>
|
||||
<path d="M100 48C92 66 86 82 80 100M100 48C100 68 100 84 100 102M100 48C108 66 114 82 120 100" fill="none" stroke="#1b2130" stroke-width="5" stroke-linecap="round"/>
|
||||
<path d="M44 150C60 160 80 163 100 163" fill="none" stroke="#d9b47a" stroke-width="5" stroke-linecap="round" opacity=".7"/>
|
||||
<ellipse cx="46" cy="140" rx="10" ry="6" fill="#e8826a" opacity=".7"/>
|
||||
<ellipse cx="154" cy="140" rx="10" ry="6" fill="#e8826a" opacity=".7"/>
|
||||
<g fill="none" stroke="#1b2130" stroke-width="7" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M62 112L80 124L62 136"/><path d="M104 138H132"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 959 B |
@@ -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. |
|
||||
@@ -44,6 +46,66 @@ Common keys:
|
||||
|
||||
Names that are not valid variable names (`[A-Za-z_][A-Za-z0-9_]*`) are skipped with a warning.
|
||||
|
||||
## Credential engines
|
||||
|
||||
Besides `kv`, queries can use `engine = "database" | "aws" | "approle" | "ssh"`. They go through the
|
||||
same `[server]` and are filtered/renamed/prefixed like KV data. Only credential fields are exported;
|
||||
lease metadata is dropped. Variable names are the returned field names, so use `rename` (or `prefix`)
|
||||
to get the names your tools expect.
|
||||
|
||||
```toml
|
||||
[[query]] # PostgreSQL via the OpenBao database engine
|
||||
engine = "database"
|
||||
role = "readonly" # required; mount defaults to "database"
|
||||
# static = true # read static-creds/<role> instead of creating a user
|
||||
name = "pg"
|
||||
rename = { username = "PGUSER", password = "PGPASSWORD" }
|
||||
|
||||
[[query]]
|
||||
engine = "aws" # role required; mount "aws"; kind = "creds" | "sts"; ttl = "15m"
|
||||
role = "deploy"
|
||||
rename = { access_key = "AWS_ACCESS_KEY_ID", secret_key = "AWS_SECRET_ACCESS_KEY", security_token = "AWS_SESSION_TOKEN" }
|
||||
|
||||
[[query]]
|
||||
engine = "approle" # role required; mount "approle"; what = "both" | "role_id" | "secret_id"
|
||||
role = "web"
|
||||
|
||||
[[query]]
|
||||
engine = "ssh" # otp (default): needs ip; sign: needs public_key_file
|
||||
role = "ops"
|
||||
ip = "10.0.0.5"
|
||||
```
|
||||
|
||||
### Caching dynamic credentials (`cache = true`)
|
||||
|
||||
Dynamic credentials are created on every fetch (a new database user or IAM user each time), which
|
||||
would make `eval "$(envbao)"` in a shell startup file mint one per shell. Add `cache = true` to a
|
||||
`database` (non-`static`) or `aws` query to reuse the credential until shortly before its lease
|
||||
expires:
|
||||
|
||||
```toml
|
||||
[cache]
|
||||
store = "file" # default. "keychain" (fail if unavailable) or "auto" (keychain, else file)
|
||||
|
||||
[[query]]
|
||||
engine = "database"
|
||||
role = "readonly"
|
||||
cache = true
|
||||
```
|
||||
|
||||
* The credential is reused while more than `max(60s, 10% of the lease)` remains. After that a new one
|
||||
is fetched and the old lease is revoked (best effort; it expires on its own if the token may not
|
||||
call `sys/leases/revoke`).
|
||||
* Storage (`[cache] store`): `file` (default) keeps a `0600` file in `~/.envbao/cache/`; `keychain` uses
|
||||
the macOS Keychain (`security`) or Linux secret service (`secret-tool`) and fails if unavailable;
|
||||
`auto` tries the keychain and falls back to the file. Secrets are never put on a command line.
|
||||
* The key covers server address, namespace, engine and options; it ignores the token, so rotating
|
||||
the token keeps the cache valid.
|
||||
* `cache = true` is rejected for `kv`, `approle`, `ssh` (one-time passwords and certificates have no
|
||||
reusable lease) and `database` with `static = true`.
|
||||
* Without `cache = true`, prefer `envbao exec -q pg -- command` for dynamic engines.
|
||||
* `envbao --clear-cache` revokes and deletes the cached credentials.
|
||||
|
||||
## Adding an engine
|
||||
|
||||
Implement `envbao.engines.Engine` (`validate` and `fetch`) in a new module under
|
||||
|
||||
@@ -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.
|
||||
@@ -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 /`.
|
||||
@@ -31,12 +31,23 @@ 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)).
|
||||
9. **Credential cache (opt-in)** - with `cache = true`, a dynamic credential is stored at rest until
|
||||
near lease expiry: in a `0600` file under `~/.envbao/cache/` (covered by control 1) by default, or in the OS
|
||||
keychain with `[cache] store = "keychain"` / `"auto"`. Cache entries are short-lived by construction, are revoked on refresh and by
|
||||
`envbao --clear-cache`, and are never logged or passed on a command line. Nothing is written
|
||||
unless a query opts in.
|
||||
|
||||
## 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:
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
@@ -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"
|
||||
@@ -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())
|
||||
@@ -0,0 +1,389 @@
|
||||
"""Reuse of dynamically generated credentials until shortly before they expire.
|
||||
|
||||
OpenBao cannot return the same dynamic credential twice, so a query with ``cache = true``
|
||||
stores the credential locally together with its lease and only asks the server for a new
|
||||
one when less than a safety margin of the lease remains (the old lease is then revoked).
|
||||
|
||||
Storage prefers the operating system keychain and falls back to a ``0600`` file inside the
|
||||
EnvBao configuration directory, which the permission policy already covers. Secrets are
|
||||
never passed on a command line: keychain writes use stdin and values are base64-encoded so
|
||||
they survive the tools' own quoting rules.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import contextlib
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import subprocess # noqa: S404
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable, Iterator
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Protocol
|
||||
|
||||
from envbao.client import BaoClient
|
||||
from envbao.config import Config, Query
|
||||
from envbao.engines import CacheableEngine, get_engine
|
||||
from envbao.errors import ConfigError, EnvBaoError, ServerError
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
SERVICE = "envbao"
|
||||
CACHE_DIR_NAME = "cache"
|
||||
MIN_MARGIN = 60.0
|
||||
MARGIN_FRACTION = 0.10
|
||||
_SUBPROCESS_TIMEOUT = 10.0
|
||||
_MACOS_NOT_FOUND = 44
|
||||
|
||||
|
||||
class CacheUnavailable(EnvBaoError):
|
||||
"""The selected cache store cannot be used (for example no keychain)."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CacheEntry:
|
||||
"""A cached credential and the lease it belongs to."""
|
||||
|
||||
values: dict[str, Any]
|
||||
lease_id: str
|
||||
fetched_at: float
|
||||
duration: int
|
||||
|
||||
def remaining(self, now: float) -> float:
|
||||
return self.fetched_at + self.duration - now
|
||||
|
||||
def is_fresh(self, now: float) -> bool:
|
||||
"""True if the credential can still be used without refreshing."""
|
||||
if self.fetched_at > now: # clock went backwards: do not trust the entry
|
||||
return False
|
||||
margin = max(MIN_MARGIN, MARGIN_FRACTION * self.duration)
|
||||
return self.remaining(now) > margin
|
||||
|
||||
def dumps(self) -> str:
|
||||
return json.dumps(asdict(self), separators=(",", ":"))
|
||||
|
||||
@classmethod
|
||||
def loads(cls, text: str) -> CacheEntry | None:
|
||||
"""Parse an entry; anything malformed is treated as a cache miss."""
|
||||
try:
|
||||
raw = json.loads(text)
|
||||
entry = cls(
|
||||
values=dict(raw["values"]),
|
||||
lease_id=str(raw["lease_id"]),
|
||||
fetched_at=float(raw["fetched_at"]),
|
||||
duration=int(raw["duration"]),
|
||||
)
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return None
|
||||
return entry if entry.values and entry.duration > 0 else None
|
||||
|
||||
|
||||
class CacheStore(Protocol):
|
||||
"""Where cached entries are kept."""
|
||||
|
||||
def get(self, key: str) -> CacheEntry | None: ...
|
||||
|
||||
def put(self, key: str, entry: CacheEntry) -> None: ...
|
||||
|
||||
def delete(self, key: str) -> None: ...
|
||||
|
||||
|
||||
# ---- file store -----------------------------------------------------------------------
|
||||
|
||||
|
||||
class FileStore:
|
||||
"""One ``0600`` JSON file per entry in ``<config dir>/cache`` (directory ``0700``)."""
|
||||
|
||||
def __init__(self, directory: Path) -> None:
|
||||
self._dir = directory
|
||||
|
||||
def _ensure_dir(self) -> None:
|
||||
self._dir.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
os.chmod(self._dir, 0o700)
|
||||
|
||||
def _path(self, key: str) -> Path:
|
||||
return self._dir / f"{key}.json"
|
||||
|
||||
def get(self, key: str) -> CacheEntry | None:
|
||||
path = self._path(key)
|
||||
try:
|
||||
if path.is_symlink():
|
||||
raise CacheUnavailable(f"{path} is a symbolic link; refusing to follow it")
|
||||
return CacheEntry.loads(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except (OSError, UnicodeDecodeError):
|
||||
return None
|
||||
|
||||
def put(self, key: str, entry: CacheEntry) -> None:
|
||||
self._ensure_dir()
|
||||
target = self._path(key)
|
||||
tmp = self._dir / f".{key}.{os.getpid()}.tmp"
|
||||
try:
|
||||
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
||||
fh.write(entry.dumps())
|
||||
os.replace(tmp, target)
|
||||
except OSError as exc:
|
||||
with contextlib.suppress(OSError):
|
||||
tmp.unlink()
|
||||
raise CacheUnavailable(f"cannot write cache file: {exc.strerror}") from None
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
with contextlib.suppress(FileNotFoundError, OSError):
|
||||
self._path(key).unlink()
|
||||
|
||||
|
||||
# ---- keychain store -------------------------------------------------------------------
|
||||
|
||||
|
||||
def _run(argv: list[str], stdin: str | None = None) -> subprocess.CompletedProcess[str]:
|
||||
try:
|
||||
return subprocess.run( # noqa: S603
|
||||
argv,
|
||||
input=stdin,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=_SUBPROCESS_TIMEOUT,
|
||||
check=False,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as exc:
|
||||
raise CacheUnavailable(f"{Path(argv[0]).name} failed: {type(exc).__name__}") from None
|
||||
|
||||
|
||||
def _encode(entry: CacheEntry) -> str:
|
||||
return base64.b64encode(entry.dumps().encode()).decode()
|
||||
|
||||
|
||||
def _decode(text: str) -> CacheEntry | None:
|
||||
try:
|
||||
return CacheEntry.loads(base64.b64decode(text.strip(), validate=True).decode())
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
return None
|
||||
|
||||
|
||||
class KeychainStore:
|
||||
"""macOS Keychain (``security``) or the freedesktop secret service (``secret-tool``)."""
|
||||
|
||||
def __init__(self, platform: str | None = None) -> None:
|
||||
platform = platform or sys.platform
|
||||
if platform == "darwin":
|
||||
self._tool = shutil.which("security")
|
||||
self._mac = True
|
||||
elif platform.startswith("linux"):
|
||||
self._tool = shutil.which("secret-tool")
|
||||
self._mac = False
|
||||
else:
|
||||
self._tool = None
|
||||
self._mac = False
|
||||
if not self._tool:
|
||||
raise CacheUnavailable("no keychain tool available on this system")
|
||||
|
||||
# -- macOS
|
||||
def _mac_get(self, key: str) -> CacheEntry | None:
|
||||
assert self._tool # noqa: S101
|
||||
result = _run([self._tool, "find-generic-password", "-s", SERVICE, "-a", key, "-w"])
|
||||
if result.returncode == _MACOS_NOT_FOUND:
|
||||
return None
|
||||
if result.returncode != 0:
|
||||
raise CacheUnavailable("keychain lookup failed")
|
||||
return _decode(result.stdout)
|
||||
|
||||
def _mac_put(self, key: str, entry: CacheEntry) -> None:
|
||||
assert self._tool # noqa: S101
|
||||
# ``security -i`` reads commands from stdin, keeping the secret out of ``ps``.
|
||||
command = f"add-generic-password -U -s {SERVICE} -a {key} -w {_encode(entry)}\n"
|
||||
result = _run([self._tool, "-i"], stdin=command)
|
||||
if result.returncode != 0:
|
||||
raise CacheUnavailable("keychain write failed")
|
||||
|
||||
def _mac_delete(self, key: str) -> None:
|
||||
assert self._tool # noqa: S101
|
||||
_run([self._tool, "delete-generic-password", "-s", SERVICE, "-a", key])
|
||||
|
||||
# -- Linux
|
||||
def _linux_get(self, key: str) -> CacheEntry | None:
|
||||
assert self._tool # noqa: S101
|
||||
result = _run([self._tool, "lookup", "service", SERVICE, "account", key])
|
||||
if result.returncode != 0:
|
||||
if result.returncode == 1 and not result.stderr.strip():
|
||||
return None
|
||||
raise CacheUnavailable("secret service lookup failed")
|
||||
return _decode(result.stdout)
|
||||
|
||||
def _linux_put(self, key: str, entry: CacheEntry) -> None:
|
||||
assert self._tool # noqa: S101
|
||||
argv = [self._tool, "store", f"--label={SERVICE}", "service", SERVICE, "account", key]
|
||||
if _run(argv, stdin=_encode(entry)).returncode != 0:
|
||||
raise CacheUnavailable("secret service write failed")
|
||||
|
||||
def _linux_delete(self, key: str) -> None:
|
||||
assert self._tool # noqa: S101
|
||||
_run([self._tool, "clear", "service", SERVICE, "account", key])
|
||||
|
||||
def get(self, key: str) -> CacheEntry | None:
|
||||
return self._mac_get(key) if self._mac else self._linux_get(key)
|
||||
|
||||
def put(self, key: str, entry: CacheEntry) -> None:
|
||||
if self._mac:
|
||||
self._mac_put(key, entry)
|
||||
else:
|
||||
self._linux_put(key, entry)
|
||||
# Some tool versions report success without storing; verify so we can fall back.
|
||||
if self.get(key) != entry:
|
||||
raise CacheUnavailable("keychain did not retain the entry")
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
if self._mac:
|
||||
self._mac_delete(key)
|
||||
else:
|
||||
self._linux_delete(key)
|
||||
|
||||
|
||||
class AutoStore:
|
||||
"""Keychain first; if it is unusable fall back to files (warning once)."""
|
||||
|
||||
def __init__(self, primary: CacheStore, fallback: CacheStore) -> None:
|
||||
self._primary = primary
|
||||
self._fallback = fallback
|
||||
self._warned = False
|
||||
|
||||
def _degrade(self, exc: CacheUnavailable) -> None:
|
||||
if not self._warned:
|
||||
log.warning("keychain unavailable (%s); caching credentials in a file instead", exc)
|
||||
self._warned = True
|
||||
|
||||
def get(self, key: str) -> CacheEntry | None:
|
||||
try:
|
||||
entry = self._primary.get(key)
|
||||
except CacheUnavailable as exc:
|
||||
self._degrade(exc)
|
||||
entry = None
|
||||
return entry or self._fallback.get(key)
|
||||
|
||||
def put(self, key: str, entry: CacheEntry) -> None:
|
||||
try:
|
||||
self._primary.put(key, entry)
|
||||
except CacheUnavailable as exc:
|
||||
self._degrade(exc)
|
||||
self._fallback.put(key, entry)
|
||||
else:
|
||||
self._fallback.delete(key)
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
with contextlib.suppress(CacheUnavailable):
|
||||
self._primary.delete(key)
|
||||
self._fallback.delete(key)
|
||||
|
||||
|
||||
def make_store(kind: str, config_dir: Path) -> CacheStore:
|
||||
"""Build the store selected by ``[cache] store``."""
|
||||
files = FileStore(config_dir / CACHE_DIR_NAME)
|
||||
if kind == "file":
|
||||
return files
|
||||
if kind == "keychain":
|
||||
return KeychainStore() # raises CacheUnavailable: fail closed
|
||||
try:
|
||||
return AutoStore(KeychainStore(), files)
|
||||
except CacheUnavailable as exc:
|
||||
log.warning("keychain unavailable (%s); caching credentials in a file instead", exc)
|
||||
return files
|
||||
|
||||
|
||||
# ---- cache ----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def cache_key(config: Config, query: Query) -> str:
|
||||
"""Stable key for a query on a given server. The token is deliberately not part of it."""
|
||||
material = json.dumps(
|
||||
[config.server.address, config.server.namespace, query.engine, dict(query.options)],
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
default=str,
|
||||
)
|
||||
return hashlib.sha256(material.encode()).hexdigest()[:40]
|
||||
|
||||
|
||||
class CredentialCache:
|
||||
"""Serve cached credentials, refreshing them (and revoking the old lease) when due."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
store: CacheStore,
|
||||
lock_path: Path,
|
||||
now: Callable[[], float] = time.time,
|
||||
) -> None:
|
||||
self._store = store
|
||||
self._lock_path = lock_path
|
||||
self._now = now
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _locked(self) -> Iterator[None]:
|
||||
"""Serialise refreshes across processes so parallel shells mint one credential."""
|
||||
self._lock_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
os.chmod(self._lock_path.parent, 0o700)
|
||||
fd = os.open(self._lock_path, os.O_WRONLY | os.O_CREAT, 0o600)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX)
|
||||
yield
|
||||
finally:
|
||||
os.close(fd) # closing releases the lock
|
||||
|
||||
def get_or_fetch(self, client: BaoClient, query: Query, config: Config) -> dict[str, Any]:
|
||||
"""Return the query's credential values, reusing a still-valid cached one."""
|
||||
engine = get_engine(query.engine)
|
||||
if not isinstance(engine, CacheableEngine) or not engine.cacheable(query.options):
|
||||
raise ConfigError(f"{query.describe()} does not support cache = true")
|
||||
key = cache_key(config, query)
|
||||
|
||||
with self._locked():
|
||||
entry = self._store.get(key)
|
||||
now = self._now()
|
||||
if entry is not None and entry.is_fresh(now):
|
||||
log.info(
|
||||
"%s: using cached credential (%ds left)", query.describe(), entry.remaining(now)
|
||||
)
|
||||
return dict(entry.values)
|
||||
|
||||
values, lease = engine.fetch_leased(client, query.options)
|
||||
if lease is None:
|
||||
log.warning("%s: no lease in response; not caching", query.describe())
|
||||
self._revoke(client, entry)
|
||||
return values
|
||||
self._store.put(
|
||||
key, CacheEntry(dict(values), lease.lease_id, self._now(), lease.duration)
|
||||
)
|
||||
self._revoke(client, entry)
|
||||
return values
|
||||
|
||||
def clear(self, client: BaoClient, config: Config) -> int:
|
||||
"""Revoke and delete the cached credentials of all ``cache = true`` queries."""
|
||||
cleared = 0
|
||||
with self._locked():
|
||||
for query in config.queries:
|
||||
if not query.cache:
|
||||
continue
|
||||
key = cache_key(config, query)
|
||||
entry = self._store.get(key)
|
||||
if entry is None:
|
||||
continue
|
||||
self._revoke(client, entry)
|
||||
self._store.delete(key)
|
||||
cleared += 1
|
||||
return cleared
|
||||
|
||||
@staticmethod
|
||||
def _revoke(client: BaoClient, entry: CacheEntry | None) -> None:
|
||||
if entry is None:
|
||||
return
|
||||
try:
|
||||
client.post("sys/leases/revoke", {"lease_id": entry.lease_id})
|
||||
except ServerError as exc:
|
||||
log.debug("could not revoke old lease: %s", exc)
|
||||
@@ -14,14 +14,16 @@ import sys
|
||||
from collections.abc import Sequence
|
||||
from pathlib import Path
|
||||
|
||||
from envbao import __version__
|
||||
from envbao.cache import CACHE_DIR_NAME, CredentialCache, make_store
|
||||
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 +48,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(
|
||||
@@ -73,8 +86,36 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
action="store_true",
|
||||
help="create ~/.envbao with safe permissions and a template config.toml",
|
||||
)
|
||||
mode.add_argument(
|
||||
"--clear-cache",
|
||||
action="store_true",
|
||||
help="revoke and delete cached dynamic credentials, then exit",
|
||||
)
|
||||
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
|
||||
|
||||
|
||||
@@ -97,10 +138,17 @@ def _check(config: Config, client: BaoClient) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _build_cache(config: Config, config_dir: Path) -> CredentialCache:
|
||||
store = make_store(config.cache_store, config_dir)
|
||||
return CredentialCache(store, config_dir / CACHE_DIR_NAME / ".lock")
|
||||
|
||||
|
||||
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 or args.clear_cache):
|
||||
raise ConfigError("--check/--init/--clear-cache cannot be combined with exec")
|
||||
if args.init:
|
||||
try:
|
||||
init_config(path)
|
||||
@@ -122,7 +170,24 @@ def run(args: argparse.Namespace) -> int:
|
||||
_check(config, client)
|
||||
return EXIT_OK
|
||||
|
||||
env = resolve(client, config)
|
||||
cache = _build_cache(config, path.parent) if any(q.cache for q in config.queries) else None
|
||||
if args.clear_cache:
|
||||
count = _build_cache(config, path.parent).clear(client, config)
|
||||
sys.stderr.write(f"envbao: cleared {count} cached credential(s)\n")
|
||||
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, cache)
|
||||
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, cache)
|
||||
shell = detect_shell() if args.shell == "auto" else args.shell
|
||||
output = render(env, shell)
|
||||
log.info("exported %d variable(s) for %s", len(env), shell)
|
||||
|
||||
@@ -66,7 +66,7 @@ def validate_address(address: str, *, allow_insecure_http: bool) -> str:
|
||||
|
||||
|
||||
class BaoClient:
|
||||
"""Authenticated read-only access to the OpenBao HTTP API."""
|
||||
"""Authenticated access (GET and POST) to the OpenBao HTTP API."""
|
||||
|
||||
def __init__(self, server: ServerConfig) -> None:
|
||||
self._base = validate_address(
|
||||
@@ -94,18 +94,42 @@ class BaoClient:
|
||||
NotFoundError: HTTP 404.
|
||||
ServerError: any other failure (network, TLS, 5xx, malformed response).
|
||||
"""
|
||||
return self._request("GET", path, params=params)
|
||||
|
||||
def post(self, path: str, body: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""POST a JSON ``body`` to ``/v1/<path>`` and return the decoded JSON object.
|
||||
|
||||
Used by engines that generate credentials on write (e.g. AppRole secret-ids, SSH).
|
||||
Raises the same exceptions as :meth:`get`.
|
||||
"""
|
||||
return self._request("POST", path, body=body if body is not None else {})
|
||||
|
||||
def _request(
|
||||
self,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
params: dict[str, str] | None = None,
|
||||
body: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
url = f"{self._base}{_API_PREFIX}{path.lstrip('/')}"
|
||||
if params:
|
||||
url += "?" + urlencode(params)
|
||||
headers = {"X-Vault-Token": self._token, "Accept": "application/json"}
|
||||
if self._namespace:
|
||||
headers["X-Vault-Namespace"] = self._namespace
|
||||
request = urllib.request.Request(url, headers=headers, method="GET") # noqa: S310
|
||||
data: bytes | None = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
request = urllib.request.Request( # noqa: S310
|
||||
url, data=data, headers=headers, method=method
|
||||
)
|
||||
|
||||
shown = f"/{_API_PREFIX.strip('/')}/{path.lstrip('/')}"
|
||||
try:
|
||||
with self._opener.open(request, timeout=self._timeout) as response:
|
||||
body = response.read(_MAX_RESPONSE_BYTES + 1)
|
||||
raw = response.read(_MAX_RESPONSE_BYTES + 1)
|
||||
except urllib.error.HTTPError as exc:
|
||||
exc.close()
|
||||
if exc.code in (401, 403):
|
||||
@@ -117,10 +141,12 @@ class BaoClient:
|
||||
reason = getattr(exc, "reason", exc)
|
||||
raise ServerError(f"cannot reach {self._base}: {reason}") from None
|
||||
|
||||
if len(body) > _MAX_RESPONSE_BYTES:
|
||||
if len(raw) > _MAX_RESPONSE_BYTES:
|
||||
raise ServerError(f"response for {shown} exceeds size limit")
|
||||
if not raw.strip(): # e.g. HTTP 204 from sys/leases/revoke
|
||||
return {}
|
||||
try:
|
||||
decoded = json.loads(body)
|
||||
decoded = json.loads(raw)
|
||||
except ValueError:
|
||||
raise ServerError(f"response for {shown} is not valid JSON") from None
|
||||
if not isinstance(decoded, dict):
|
||||
|
||||
@@ -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,13 @@ _SERVER_KEYS = {
|
||||
"timeout",
|
||||
"allow_insecure_http",
|
||||
}
|
||||
_SECURITY_KEYS = {"allow_protected"}
|
||||
_TOP_KEYS = {"server", "security", "query"}
|
||||
_QUERY_COMMON_KEYS = {"engine", "keys", "prefix", "rename", "on_missing"}
|
||||
_SECURITY_KEYS = {"allow_protected", "exec_only"}
|
||||
_CACHE_KEYS = {"store"}
|
||||
CACHE_STORES = ("auto", "keychain", "file")
|
||||
_TOP_KEYS = {"server", "security", "query", "cache"}
|
||||
_QUERY_COMMON_KEYS = {"engine", "name", "keys", "prefix", "rename", "on_missing", "cache"}
|
||||
_NAME_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\Z")
|
||||
CONFIG_ENV_VAR = "ENVBAO_CONFIG"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -64,6 +70,8 @@ class Query:
|
||||
prefix: str = ""
|
||||
rename: Mapping[str, str] = field(default_factory=dict)
|
||||
on_missing: str = "warn"
|
||||
name: str = ""
|
||||
cache: bool = False
|
||||
|
||||
def describe(self) -> str:
|
||||
"""Short, secret-free description of this query for logs."""
|
||||
@@ -78,12 +86,15 @@ class Config:
|
||||
server: ServerConfig
|
||||
queries: tuple[Query, ...]
|
||||
allow_protected: frozenset[str] = frozenset()
|
||||
exec_only: bool = False
|
||||
cache_store: str = "file"
|
||||
|
||||
|
||||
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 +174,45 @@ 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``).
|
||||
|
||||
engine = _get_str(raw, "engine", name) or "kv"
|
||||
keys = _get_str_list(raw, "keys", name)
|
||||
prefix = _get_str(raw, "prefix", name) or ""
|
||||
Engines addressed by ``role`` rather than ``path`` fall back to the role name.
|
||||
"""
|
||||
for key in ("path", "role"):
|
||||
value = options.get(key)
|
||||
if isinstance(value, str) and value.strip("/"):
|
||||
return value.strip("/").rsplit("/", 1)[-1]
|
||||
return engine
|
||||
|
||||
|
||||
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)}")
|
||||
|
||||
cache = raw.get("cache", False)
|
||||
if not isinstance(cache, bool):
|
||||
raise ConfigError(f"{name_label}.cache must be a boolean")
|
||||
|
||||
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 +220,8 @@ def _parse_query(raw: Any, index: int) -> Query:
|
||||
prefix=prefix,
|
||||
rename=dict(rename),
|
||||
on_missing=on_missing,
|
||||
name=name,
|
||||
cache=cache,
|
||||
)
|
||||
|
||||
|
||||
@@ -209,7 +241,23 @@ 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")
|
||||
|
||||
cache_table = _require_table(data.get("cache", {}), "cache")
|
||||
_reject_unknown(cache_table, _CACHE_KEYS, "[cache]")
|
||||
cache_store = _get_str(cache_table, "store", "cache") or "file"
|
||||
if cache_store not in CACHE_STORES:
|
||||
raise ConfigError(f"cache.store must be one of {', '.join(CACHE_STORES)}")
|
||||
|
||||
return Config(
|
||||
server=server,
|
||||
queries=queries,
|
||||
allow_protected=frozenset(allow_protected),
|
||||
exec_only=exec_only,
|
||||
cache_store=cache_store,
|
||||
)
|
||||
|
||||
|
||||
def load_config(path: Path) -> Config:
|
||||
|
||||
@@ -9,10 +9,11 @@ implements :class:`Engine` and an entry in :data:`ENGINES`.
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, Protocol
|
||||
from typing import Any, Protocol, runtime_checkable
|
||||
|
||||
from envbao.client import BaoClient
|
||||
from envbao.engines import kv
|
||||
from envbao.engines import approle, aws, database, kv, ssh
|
||||
from envbao.engines._common import Lease
|
||||
from envbao.errors import ConfigError
|
||||
|
||||
|
||||
@@ -30,7 +31,28 @@ class Engine(Protocol):
|
||||
"""
|
||||
|
||||
|
||||
ENGINES: dict[str, Engine] = {"kv": kv.KvEngine()}
|
||||
@runtime_checkable
|
||||
class CacheableEngine(Engine, Protocol):
|
||||
"""Engines that mint a leased credential per fetch and so support ``cache = true``."""
|
||||
|
||||
def cacheable(self, options: Mapping[str, Any]) -> bool:
|
||||
"""Whether a query with these options may be cached."""
|
||||
|
||||
def fetch_leased(
|
||||
self, client: BaoClient, options: Mapping[str, Any]
|
||||
) -> tuple[dict[str, Any], Lease | None]:
|
||||
"""Like :meth:`Engine.fetch`, also returning the credential's lease."""
|
||||
|
||||
|
||||
__all__ = ["ENGINES", "CacheableEngine", "Engine", "Lease", "get_engine"]
|
||||
|
||||
ENGINES: dict[str, Engine] = {
|
||||
"kv": kv.KvEngine(),
|
||||
"database": database.DatabaseEngine(),
|
||||
"aws": aws.AwsEngine(),
|
||||
"approle": approle.ApproleEngine(),
|
||||
"ssh": ssh.SshEngine(),
|
||||
}
|
||||
|
||||
|
||||
def get_engine(name: str) -> Engine:
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Helpers shared by the credential-generating engines (database, aws, approle, ssh)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Collection, Mapping
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from envbao.errors import ConfigError, NotFoundError, ServerError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Lease:
|
||||
"""Server-side lease attached to a dynamically generated credential."""
|
||||
|
||||
lease_id: str
|
||||
duration: int # seconds
|
||||
|
||||
|
||||
def lease_of(body: Mapping[str, Any]) -> Lease | None:
|
||||
"""Extract the lease from an API response, or ``None`` if it has no usable one."""
|
||||
lease_id = body.get("lease_id")
|
||||
duration = body.get("lease_duration")
|
||||
if (
|
||||
isinstance(lease_id, str)
|
||||
and lease_id
|
||||
and isinstance(duration, int)
|
||||
and not isinstance(duration, bool)
|
||||
and duration > 0
|
||||
):
|
||||
return Lease(lease_id, duration)
|
||||
return None
|
||||
|
||||
|
||||
def check_options(engine: str, options: Mapping[str, Any], allowed: Collection[str]) -> None:
|
||||
"""Reject option names the engine does not know."""
|
||||
unknown = sorted(set(options) - set(allowed))
|
||||
if unknown:
|
||||
raise ConfigError(f"unknown option(s) for {engine} engine: {', '.join(unknown)}")
|
||||
|
||||
|
||||
def get_str(
|
||||
engine: str, options: Mapping[str, Any], key: str, *, default: str | None = None
|
||||
) -> str:
|
||||
"""Return a non-empty string option (stripped of surrounding slashes) or ``default``."""
|
||||
value = options.get(key, default)
|
||||
if not isinstance(value, str) or not value.strip("/"):
|
||||
raise ConfigError(f"{engine} query requires a non-empty string '{key}'")
|
||||
return value.strip("/")
|
||||
|
||||
|
||||
def get_choice(
|
||||
engine: str, options: Mapping[str, Any], key: str, choices: tuple[str, ...], default: str
|
||||
) -> str:
|
||||
"""Return an option constrained to ``choices``."""
|
||||
value = options.get(key, default)
|
||||
if value not in choices:
|
||||
raise ConfigError(f"{engine} option '{key}' must be one of: {', '.join(choices)}")
|
||||
return str(value)
|
||||
|
||||
|
||||
def get_bool(engine: str, options: Mapping[str, Any], key: str, default: bool = False) -> bool:
|
||||
value = options.get(key, default)
|
||||
if not isinstance(value, bool):
|
||||
raise ConfigError(f"{engine} option '{key}' must be true or false")
|
||||
return value
|
||||
|
||||
|
||||
def response_data(body: Mapping[str, Any], where: str) -> dict[str, Any]:
|
||||
"""Return the ``data`` object of an API response, failing closed if absent."""
|
||||
data = body.get("data")
|
||||
if data is None:
|
||||
raise NotFoundError(f"no data at {where}")
|
||||
if not isinstance(data, dict):
|
||||
raise ServerError(f"unexpected data shape at {where}")
|
||||
return data
|
||||
|
||||
|
||||
def pick(data: Mapping[str, Any], names: Collection[str], where: str) -> dict[str, Any]:
|
||||
"""Keep only ``names`` from ``data``.
|
||||
|
||||
Lease metadata and other bookkeeping fields are dropped so they never become environment
|
||||
variables. Fails if none of the expected fields are present.
|
||||
"""
|
||||
picked = {k: data[k] for k in names if data.get(k) not in (None, "")}
|
||||
if not picked:
|
||||
raise ServerError(f"response from {where} contained no credentials")
|
||||
return picked
|
||||
@@ -0,0 +1,41 @@
|
||||
"""AppRole auth method: fetch a role-id and/or generate a fresh secret-id."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from envbao.client import BaoClient
|
||||
from envbao.engines import _common as c
|
||||
|
||||
_OPTIONS = {"mount", "role", "what"}
|
||||
_WHAT = ("both", "role_id", "secret_id")
|
||||
|
||||
|
||||
class ApproleEngine:
|
||||
"""Reads AppRole login material for a role.
|
||||
|
||||
Options: ``role`` (required), ``mount`` (default ``"approle"``), ``what`` (``"both"``,
|
||||
``"role_id"`` or ``"secret_id"``, default ``"both"``). Each fetch of a secret-id creates
|
||||
a new one.
|
||||
"""
|
||||
|
||||
def validate(self, options: Mapping[str, Any]) -> None:
|
||||
c.check_options("approle", options, _OPTIONS)
|
||||
c.get_str("approle", options, "role")
|
||||
c.get_str("approle", options, "mount", default="approle")
|
||||
c.get_choice("approle", options, "what", _WHAT, "both")
|
||||
|
||||
def fetch(self, client: BaoClient, options: Mapping[str, Any]) -> dict[str, Any]:
|
||||
mount = c.get_str("approle", options, "mount", default="approle")
|
||||
role = c.get_str("approle", options, "role")
|
||||
what = c.get_choice("approle", options, "what", _WHAT, "both")
|
||||
base = f"auth/{mount}/role/{role}"
|
||||
out: dict[str, Any] = {}
|
||||
if what in ("both", "role_id"):
|
||||
where = f"{base}/role-id"
|
||||
out.update(c.pick(c.response_data(client.get(where), where), ("role_id",), where))
|
||||
if what in ("both", "secret_id"):
|
||||
where = f"{base}/secret-id"
|
||||
out.update(c.pick(c.response_data(client.post(where), where), ("secret_id",), where))
|
||||
return out
|
||||
@@ -0,0 +1,48 @@
|
||||
"""AWS secrets engine (dynamic IAM users or STS credentials)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from envbao.client import BaoClient
|
||||
from envbao.engines import _common as c
|
||||
from envbao.errors import ConfigError
|
||||
|
||||
_OPTIONS = {"mount", "role", "kind", "ttl"}
|
||||
_FIELDS = ("access_key", "secret_key", "security_token")
|
||||
|
||||
|
||||
class AwsEngine:
|
||||
"""Reads AWS credentials for a role.
|
||||
|
||||
Options: ``role`` (required), ``mount`` (default ``"aws"``), ``kind`` (``"creds"`` or
|
||||
``"sts"``, default ``"creds"``), ``ttl`` (optional duration string such as ``"15m"``).
|
||||
Returns ``access_key``, ``secret_key`` and, for STS, ``security_token``.
|
||||
"""
|
||||
|
||||
def validate(self, options: Mapping[str, Any]) -> None:
|
||||
c.check_options("aws", options, _OPTIONS)
|
||||
c.get_str("aws", options, "role")
|
||||
c.get_str("aws", options, "mount", default="aws")
|
||||
c.get_choice("aws", options, "kind", ("creds", "sts"), "creds")
|
||||
ttl = options.get("ttl")
|
||||
if ttl is not None and (not isinstance(ttl, str) or not ttl):
|
||||
raise ConfigError("aws option 'ttl' must be a non-empty string such as \"15m\"")
|
||||
|
||||
def cacheable(self, options: Mapping[str, Any]) -> bool:
|
||||
return True
|
||||
|
||||
def fetch(self, client: BaoClient, options: Mapping[str, Any]) -> dict[str, Any]:
|
||||
return self.fetch_leased(client, options)[0]
|
||||
|
||||
def fetch_leased(
|
||||
self, client: BaoClient, options: Mapping[str, Any]
|
||||
) -> tuple[dict[str, Any], c.Lease | None]:
|
||||
mount = c.get_str("aws", options, "mount", default="aws")
|
||||
role = c.get_str("aws", options, "role")
|
||||
kind = c.get_choice("aws", options, "kind", ("creds", "sts"), "creds")
|
||||
ttl = options.get("ttl")
|
||||
where = f"{mount}/{kind}/{role}"
|
||||
body = client.get(where, {"ttl": ttl} if ttl else None)
|
||||
return c.pick(c.response_data(body, where), _FIELDS, where), c.lease_of(body)
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Database secrets engine (PostgreSQL, MySQL, ... whatever the mount is configured for)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from envbao.client import BaoClient
|
||||
from envbao.engines import _common as c
|
||||
|
||||
_OPTIONS = {"mount", "role", "static"}
|
||||
_FIELDS = ("username", "password")
|
||||
|
||||
|
||||
class DatabaseEngine:
|
||||
"""Reads database credentials for a role.
|
||||
|
||||
Options: ``role`` (required), ``mount`` (default ``"database"``), ``static`` (default
|
||||
``false``; read ``static-creds/<role>`` instead of generating dynamic credentials).
|
||||
Returns ``username`` and ``password``. Dynamic roles create a new database user per fetch.
|
||||
"""
|
||||
|
||||
def validate(self, options: Mapping[str, Any]) -> None:
|
||||
c.check_options("database", options, _OPTIONS)
|
||||
c.get_str("database", options, "role")
|
||||
c.get_str("database", options, "mount", default="database")
|
||||
c.get_bool("database", options, "static")
|
||||
|
||||
def cacheable(self, options: Mapping[str, Any]) -> bool:
|
||||
"""Only dynamic roles mint a new credential per fetch."""
|
||||
return not c.get_bool("database", options, "static")
|
||||
|
||||
def fetch(self, client: BaoClient, options: Mapping[str, Any]) -> dict[str, Any]:
|
||||
return self.fetch_leased(client, options)[0]
|
||||
|
||||
def fetch_leased(
|
||||
self, client: BaoClient, options: Mapping[str, Any]
|
||||
) -> tuple[dict[str, Any], c.Lease | None]:
|
||||
mount = c.get_str("database", options, "mount", default="database")
|
||||
role = c.get_str("database", options, "role")
|
||||
kind = "static-creds" if c.get_bool("database", options, "static") else "creds"
|
||||
where = f"{mount}/{kind}/{role}"
|
||||
body = client.get(where)
|
||||
return c.pick(c.response_data(body, where), _FIELDS, where), c.lease_of(body)
|
||||
@@ -0,0 +1,69 @@
|
||||
"""SSH secrets engine: one-time passwords or signed client certificates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from envbao.client import BaoClient
|
||||
from envbao.engines import _common as c
|
||||
from envbao.errors import ConfigError
|
||||
|
||||
_OPTIONS = {"mount", "role", "mode", "ip", "public_key_file", "valid_principals"}
|
||||
_MAX_KEY_BYTES = 64 * 1024
|
||||
|
||||
|
||||
class SshEngine:
|
||||
"""Generates SSH credentials for a role.
|
||||
|
||||
Options: ``role`` (required), ``mount`` (default ``"ssh"``), ``mode`` (``"otp"`` or
|
||||
``"sign"``, default ``"otp"``).
|
||||
|
||||
* ``otp``: requires ``ip``; returns ``key`` (the one-time password), ``username``, ``ip``.
|
||||
* ``sign``: requires ``public_key_file``; optional ``valid_principals``; returns
|
||||
``signed_key`` and ``serial_number``.
|
||||
"""
|
||||
|
||||
def validate(self, options: Mapping[str, Any]) -> None:
|
||||
c.check_options("ssh", options, _OPTIONS)
|
||||
c.get_str("ssh", options, "role")
|
||||
c.get_str("ssh", options, "mount", default="ssh")
|
||||
mode = c.get_choice("ssh", options, "mode", ("otp", "sign"), "otp")
|
||||
if mode == "otp":
|
||||
c.get_str("ssh", options, "ip")
|
||||
extra = {"public_key_file", "valid_principals"} & set(options)
|
||||
else:
|
||||
c.get_str("ssh", options, "public_key_file")
|
||||
extra = {"ip"} & set(options)
|
||||
if extra:
|
||||
raise ConfigError(f"ssh mode '{mode}' does not accept: {', '.join(sorted(extra))}")
|
||||
principals = options.get("valid_principals")
|
||||
if principals is not None and (not isinstance(principals, str) or not principals):
|
||||
raise ConfigError("ssh option 'valid_principals' must be a comma-separated string")
|
||||
|
||||
def fetch(self, client: BaoClient, options: Mapping[str, Any]) -> dict[str, Any]:
|
||||
mount = c.get_str("ssh", options, "mount", default="ssh")
|
||||
role = c.get_str("ssh", options, "role")
|
||||
mode = c.get_choice("ssh", options, "mode", ("otp", "sign"), "otp")
|
||||
if mode == "otp":
|
||||
where = f"{mount}/creds/{role}"
|
||||
body = client.post(where, {"ip": options["ip"]})
|
||||
return c.pick(c.response_data(body, where), ("key", "username", "ip"), where)
|
||||
|
||||
where = f"{mount}/sign/{role}"
|
||||
request: dict[str, Any] = {"public_key": _read_public_key(str(options["public_key_file"]))}
|
||||
if options.get("valid_principals"):
|
||||
request["valid_principals"] = options["valid_principals"]
|
||||
body = client.post(where, request)
|
||||
return c.pick(c.response_data(body, where), ("signed_key", "serial_number"), where)
|
||||
|
||||
|
||||
def _read_public_key(name: str) -> str:
|
||||
path = Path(name).expanduser()
|
||||
try:
|
||||
if path.stat().st_size > _MAX_KEY_BYTES:
|
||||
raise ConfigError(f"public key file {path} is unreasonably large")
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
except (OSError, UnicodeDecodeError) as exc:
|
||||
raise ConfigError(f"cannot read public key file {path}: {exc}") from None
|
||||
@@ -6,9 +6,10 @@ import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from envbao.cache import CredentialCache
|
||||
from envbao.client import BaoClient
|
||||
from envbao.config import Config, Query
|
||||
from envbao.engines import get_engine
|
||||
from envbao.engines import CacheableEngine, get_engine
|
||||
from envbao.errors import ConfigError, EnvBaoError, NotFoundError
|
||||
from envbao.render import is_protected, is_valid_name
|
||||
|
||||
@@ -26,7 +27,12 @@ def validate_queries(config: Config) -> None:
|
||||
"""Validate engine-specific options of every query without contacting the server."""
|
||||
for index, query in enumerate(config.queries, start=1):
|
||||
try:
|
||||
get_engine(query.engine).validate(query.options)
|
||||
engine = get_engine(query.engine)
|
||||
engine.validate(query.options)
|
||||
if query.cache and not (
|
||||
isinstance(engine, CacheableEngine) and engine.cacheable(query.options)
|
||||
):
|
||||
raise ConfigError(f"cache = true is not supported for {query.describe()}")
|
||||
except ConfigError as exc:
|
||||
raise ConfigError(f"query #{index}: {exc}") from None
|
||||
|
||||
@@ -42,7 +48,12 @@ def _select(raw: dict[str, Any], query: Query) -> dict[str, Any]:
|
||||
return {k: raw[k] for k in query.keys if k in raw}
|
||||
|
||||
|
||||
def run_query(client: BaoClient, query: Query, config: Config) -> dict[str, str]:
|
||||
def run_query(
|
||||
client: BaoClient,
|
||||
query: Query,
|
||||
config: Config,
|
||||
cache: CredentialCache | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Execute one query and return ``{ENV_NAME: value}``.
|
||||
|
||||
Names that are not valid variable names, or that are protected shell/loader variables
|
||||
@@ -50,7 +61,10 @@ def run_query(client: BaoClient, query: Query, config: Config) -> dict[str, str]
|
||||
"""
|
||||
engine = get_engine(query.engine)
|
||||
try:
|
||||
raw = engine.fetch(client, query.options)
|
||||
if query.cache and cache is not None:
|
||||
raw = cache.get_or_fetch(client, query, config)
|
||||
else:
|
||||
raw = engine.fetch(client, query.options)
|
||||
except NotFoundError as exc:
|
||||
if query.on_missing == "error":
|
||||
raise
|
||||
@@ -77,7 +91,9 @@ def run_query(client: BaoClient, query: Query, config: Config) -> dict[str, str]
|
||||
return result
|
||||
|
||||
|
||||
def resolve(client: BaoClient, config: Config) -> dict[str, str]:
|
||||
def resolve(
|
||||
client: BaoClient, config: Config, cache: CredentialCache | None = None
|
||||
) -> dict[str, str]:
|
||||
"""Run all queries in order (later queries override earlier ones).
|
||||
|
||||
All-or-nothing: any non-recoverable error aborts and nothing is returned.
|
||||
@@ -88,7 +104,7 @@ def resolve(client: BaoClient, config: Config) -> dict[str, str]:
|
||||
env: dict[str, str] = {}
|
||||
for query in config.queries:
|
||||
try:
|
||||
values = run_query(client, query, config)
|
||||
values = run_query(client, query, config, cache)
|
||||
except EnvBaoError as exc:
|
||||
log.error("query %s failed: %s", query.describe(), exc)
|
||||
raise
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"""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.cache import CredentialCache
|
||||
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],
|
||||
cache: CredentialCache | None = None,
|
||||
) -> 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, cache)
|
||||
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
|
||||
@@ -20,8 +20,16 @@ class FakeBao:
|
||||
def __init__(self) -> None:
|
||||
self.routes: dict[str, tuple[int, Any]] = {}
|
||||
self.requests: list[tuple[str, dict[str, str]]] = []
|
||||
self.posts: list[tuple[str, Any]] = []
|
||||
self.url = ""
|
||||
|
||||
def route(self, path: str, data: dict[str, Any], status: int = 200) -> None:
|
||||
"""Serve ``{"data": data}`` at ``/v1/<path>`` for both GET and POST."""
|
||||
self.routes[f"/v1/{path}"] = (
|
||||
status,
|
||||
{"data": data, "lease_id": "x/1", "lease_duration": 60},
|
||||
)
|
||||
|
||||
def kv2(self, mount: str, path: str, data: dict[str, Any]) -> None:
|
||||
self.routes[f"/v1/sys/internal/ui/mounts/{mount}"] = (
|
||||
200,
|
||||
@@ -59,6 +67,23 @@ def fake_bao() -> Iterator[FakeBao]:
|
||||
status, body = state.routes.get(self.path, (404, {"errors": []}))
|
||||
self._send(status, body)
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
headers = {k.lower(): v for k, v in self.headers.items()}
|
||||
length = int(headers.get("content-length", "0"))
|
||||
payload = json.loads(self.rfile.read(length) or b"{}")
|
||||
state.requests.append((self.path, headers))
|
||||
state.posts.append((self.path, payload))
|
||||
if headers.get("x-vault-token") != TOKEN:
|
||||
self._send(403, {"errors": ["permission denied"]})
|
||||
return
|
||||
if self.path == "/v1/redirect":
|
||||
self.send_response(307)
|
||||
self.send_header("Location", "http://127.0.0.1:1/steal")
|
||||
self.end_headers()
|
||||
return
|
||||
status, body = state.routes.get(self.path, (404, {"errors": []}))
|
||||
self._send(status, body)
|
||||
|
||||
def _send(self, status: int, body: Any) -> None:
|
||||
raw = body if isinstance(body, bytes) else json.dumps(body).encode()
|
||||
self.send_response(status)
|
||||
|
||||
@@ -0,0 +1,548 @@
|
||||
import stat
|
||||
import subprocess
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from envbao import cache as cache_mod
|
||||
from envbao.cache import (
|
||||
AutoStore,
|
||||
CacheEntry,
|
||||
CacheUnavailable,
|
||||
CredentialCache,
|
||||
FileStore,
|
||||
KeychainStore,
|
||||
cache_key,
|
||||
make_store,
|
||||
)
|
||||
from envbao.cli import main
|
||||
from envbao.client import BaoClient
|
||||
from envbao.config import Config, Query, ServerConfig, parse_config
|
||||
from envbao.errors import ConfigError
|
||||
from envbao.resolve import validate_queries
|
||||
|
||||
from .conftest import TOKEN, FakeBao, write_config
|
||||
|
||||
CREDS = "/v1/database/creds/ro"
|
||||
REVOKE = "/v1/sys/leases/revoke"
|
||||
|
||||
|
||||
class Clock:
|
||||
def __init__(self, t: float = 1000.0) -> None:
|
||||
self.t = t
|
||||
|
||||
def __call__(self) -> float:
|
||||
return self.t
|
||||
|
||||
|
||||
class MemStore:
|
||||
def __init__(self) -> None:
|
||||
self.data: dict[str, CacheEntry] = {}
|
||||
|
||||
def get(self, key: str) -> CacheEntry | None:
|
||||
return self.data.get(key)
|
||||
|
||||
def put(self, key: str, entry: CacheEntry) -> None:
|
||||
self.data[key] = entry
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
self.data.pop(key, None)
|
||||
|
||||
|
||||
def serve_creds(
|
||||
fake: FakeBao, duration: int | None = 3600, lease: str = "database/creds/ro/l1"
|
||||
) -> None:
|
||||
body: dict[str, Any] = {"data": {"username": "u", "password": "pw-secret"}}
|
||||
if duration is not None:
|
||||
body.update(lease_id=lease, lease_duration=duration)
|
||||
fake.routes[CREDS] = (200, body)
|
||||
|
||||
|
||||
def creds_gets(fake: FakeBao) -> int:
|
||||
return sum(1 for path, _ in fake.requests if path == CREDS)
|
||||
|
||||
|
||||
def setup(fake: FakeBao, tmp_path: Path, **query_kw: Any) -> tuple[BaoClient, Config, Query, Any]:
|
||||
query = Query(engine="database", options={"role": "ro"}, name="ro", cache=True, **query_kw)
|
||||
config = Config(ServerConfig(fake.url, TOKEN), (query,))
|
||||
clock = Clock()
|
||||
cache = CredentialCache(MemStore(), tmp_path / "cache" / ".lock", now=clock)
|
||||
return BaoClient(config.server), config, query, (cache, clock)
|
||||
|
||||
|
||||
# ---- CredentialCache ------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_reuses_fresh_credential(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
serve_creds(fake_bao)
|
||||
client, config, query, (cache, clock) = setup(fake_bao, tmp_path)
|
||||
first = cache.get_or_fetch(client, query, config)
|
||||
clock.t += 100
|
||||
assert cache.get_or_fetch(client, query, config) == first
|
||||
assert creds_gets(fake_bao) == 1
|
||||
assert fake_bao.posts == []
|
||||
|
||||
|
||||
def test_refreshes_inside_margin_and_revokes_old_lease(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
serve_creds(fake_bao, duration=3600) # margin = 360s
|
||||
fake_bao.routes[REVOKE] = (204, b"")
|
||||
client, config, query, (cache, clock) = setup(fake_bao, tmp_path)
|
||||
cache.get_or_fetch(client, query, config)
|
||||
clock.t += 3300 # 300s left < 360s margin
|
||||
serve_creds(fake_bao, lease="database/creds/ro/l2")
|
||||
cache.get_or_fetch(client, query, config)
|
||||
assert creds_gets(fake_bao) == 2
|
||||
assert fake_bao.posts == [("/v1/sys/leases/revoke", {"lease_id": "database/creds/ro/l1"})]
|
||||
|
||||
|
||||
def test_minimum_margin_applies_to_short_leases(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
serve_creds(fake_bao, duration=100) # 10% = 10s, floor is 60s
|
||||
client, config, query, (cache, clock) = setup(fake_bao, tmp_path)
|
||||
cache.get_or_fetch(client, query, config)
|
||||
clock.t += 50 # 50s left < 60s
|
||||
cache.get_or_fetch(client, query, config)
|
||||
assert creds_gets(fake_bao) == 2
|
||||
|
||||
|
||||
def test_refreshes_when_expired(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
serve_creds(fake_bao)
|
||||
client, config, query, (cache, clock) = setup(fake_bao, tmp_path)
|
||||
cache.get_or_fetch(client, query, config)
|
||||
clock.t += 10_000
|
||||
cache.get_or_fetch(client, query, config)
|
||||
assert creds_gets(fake_bao) == 2
|
||||
|
||||
|
||||
def test_clock_going_backwards_distrusts_entry(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
serve_creds(fake_bao)
|
||||
client, config, query, (cache, clock) = setup(fake_bao, tmp_path)
|
||||
cache.get_or_fetch(client, query, config)
|
||||
clock.t -= 500
|
||||
cache.get_or_fetch(client, query, config)
|
||||
assert creds_gets(fake_bao) == 2
|
||||
|
||||
|
||||
def test_response_without_lease_is_not_cached(
|
||||
fake_bao: FakeBao, tmp_path: Path, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
serve_creds(fake_bao, duration=None)
|
||||
client, config, query, (cache, _) = setup(fake_bao, tmp_path)
|
||||
cache.get_or_fetch(client, query, config)
|
||||
cache.get_or_fetch(client, query, config)
|
||||
assert creds_gets(fake_bao) == 2
|
||||
assert "not caching" in caplog.text
|
||||
|
||||
|
||||
def test_revoke_failure_is_tolerated(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
serve_creds(fake_bao) # no revoke route -> 404
|
||||
client, config, query, (cache, clock) = setup(fake_bao, tmp_path)
|
||||
cache.get_or_fetch(client, query, config)
|
||||
clock.t += 10_000
|
||||
assert cache.get_or_fetch(client, query, config)["password"] == "pw-secret"
|
||||
|
||||
|
||||
def test_stale_entry_with_no_new_lease_is_revoked(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
serve_creds(fake_bao)
|
||||
fake_bao.routes[REVOKE] = (204, b"")
|
||||
client, config, query, (cache, clock) = setup(fake_bao, tmp_path)
|
||||
cache.get_or_fetch(client, query, config)
|
||||
clock.t += 10_000
|
||||
serve_creds(fake_bao, duration=None)
|
||||
cache.get_or_fetch(client, query, config)
|
||||
assert len(fake_bao.posts) == 1
|
||||
|
||||
|
||||
def test_non_cacheable_engine_rejected(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
client, config, _, (cache, _) = setup(fake_bao, tmp_path)
|
||||
for query in (
|
||||
Query(engine="kv", options={"mount": "s", "path": "p"}, cache=True),
|
||||
Query(engine="database", options={"role": "r", "static": True}, cache=True),
|
||||
):
|
||||
with pytest.raises(ConfigError, match="does not support"):
|
||||
cache.get_or_fetch(client, query, config)
|
||||
|
||||
|
||||
def test_cache_key_depends_on_target_not_token() -> None:
|
||||
q1 = Query(engine="database", options={"role": "a"})
|
||||
q2 = Query(engine="database", options={"role": "b"})
|
||||
a = Config(ServerConfig("https://bao:8200", "t1"), (q1,))
|
||||
same_other_token = Config(ServerConfig("https://bao:8200", "t2"), (q1,))
|
||||
other_server = Config(ServerConfig("https://other:8200", "t1"), (q1,))
|
||||
other_ns = Config(ServerConfig("https://bao:8200", "t1", namespace="n"), (q1,))
|
||||
assert cache_key(a, q1) == cache_key(same_other_token, q1)
|
||||
assert (
|
||||
len(
|
||||
{
|
||||
cache_key(a, q1),
|
||||
cache_key(a, q2),
|
||||
cache_key(other_server, q1),
|
||||
cache_key(other_ns, q1),
|
||||
}
|
||||
)
|
||||
== 4
|
||||
)
|
||||
|
||||
|
||||
def test_concurrent_refresh_mints_once(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
serve_creds(fake_bao)
|
||||
client, config, query, (cache, _) = setup(fake_bao, tmp_path)
|
||||
results: list[dict[str, Any]] = []
|
||||
threads = [
|
||||
threading.Thread(target=lambda: results.append(cache.get_or_fetch(client, query, config)))
|
||||
for _ in range(6)
|
||||
]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
assert len(results) == 6
|
||||
assert creds_gets(fake_bao) == 1
|
||||
|
||||
|
||||
def test_clear_revokes_and_deletes(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
serve_creds(fake_bao)
|
||||
fake_bao.routes[REVOKE] = (204, b"")
|
||||
client, config, query, (cache, _) = setup(fake_bao, tmp_path)
|
||||
cache.get_or_fetch(client, query, config)
|
||||
assert cache.clear(client, config) == 1
|
||||
assert fake_bao.posts[-1][1] == {"lease_id": "database/creds/ro/l1"}
|
||||
assert cache.clear(client, config) == 0
|
||||
plain = Config(config.server, (Query(engine="database", options={"role": "ro"}),))
|
||||
assert cache.clear(client, plain) == 0
|
||||
|
||||
|
||||
# ---- CacheEntry -----------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"text",
|
||||
[
|
||||
"not json",
|
||||
"[]",
|
||||
'{"values": {}, "lease_id": "x", "fetched_at": 1, "duration": 5}',
|
||||
'{"values": {"a": "b"}, "lease_id": "x", "fetched_at": "bad", "duration": 5}',
|
||||
'{"values": {"a": "b"}, "lease_id": "x", "fetched_at": 1, "duration": 0}',
|
||||
],
|
||||
)
|
||||
def test_malformed_entries_are_misses(text: str) -> None:
|
||||
assert CacheEntry.loads(text) is None
|
||||
|
||||
|
||||
def test_entry_roundtrip() -> None:
|
||||
entry = CacheEntry({"a": "b"}, "lease", 5.0, 60)
|
||||
assert CacheEntry.loads(entry.dumps()) == entry
|
||||
|
||||
|
||||
# ---- FileStore ------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_file_store_modes_and_roundtrip(tmp_path: Path) -> None:
|
||||
store = FileStore(tmp_path / "cache")
|
||||
entry = CacheEntry({"password": "pw"}, "l", 1.0, 60)
|
||||
store.put("k", entry)
|
||||
assert store.get("k") == entry
|
||||
assert stat.S_IMODE((tmp_path / "cache").stat().st_mode) == 0o700
|
||||
assert stat.S_IMODE((tmp_path / "cache" / "k.json").stat().st_mode) == 0o600
|
||||
assert list((tmp_path / "cache").glob(".*.tmp")) == []
|
||||
store.delete("k")
|
||||
assert store.get("k") is None
|
||||
store.delete("k") # idempotent
|
||||
|
||||
|
||||
def test_file_store_corrupt_file_is_miss(tmp_path: Path) -> None:
|
||||
store = FileStore(tmp_path)
|
||||
(tmp_path / "k.json").write_text("garbage")
|
||||
assert store.get("k") is None
|
||||
|
||||
|
||||
def test_file_store_refuses_symlink(tmp_path: Path) -> None:
|
||||
target = tmp_path / "elsewhere.json"
|
||||
target.write_text(CacheEntry({"a": "b"}, "l", 1.0, 60).dumps())
|
||||
(tmp_path / "k.json").symlink_to(target)
|
||||
with pytest.raises(CacheUnavailable, match="symbolic link"):
|
||||
FileStore(tmp_path).get("k")
|
||||
|
||||
|
||||
def test_file_store_write_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def boom(*_: Any) -> None:
|
||||
raise OSError(28, "No space left")
|
||||
|
||||
monkeypatch.setattr(cache_mod.os, "replace", boom)
|
||||
with pytest.raises(CacheUnavailable, match="cannot write"):
|
||||
FileStore(tmp_path / "c").put("k", CacheEntry({"a": "b"}, "l", 1.0, 60))
|
||||
assert list((tmp_path / "c").glob(".*.tmp")) == []
|
||||
|
||||
|
||||
# ---- KeychainStore --------------------------------------------------------------------
|
||||
|
||||
|
||||
class FakeTools:
|
||||
"""Emulates `security` (macOS) and `secret-tool` (Linux) closely enough for the store."""
|
||||
|
||||
def __init__(self, mac: bool, *, fail: str | None = None, lossy: bool = False) -> None:
|
||||
self.mac = mac
|
||||
self.fail = fail
|
||||
self.lossy = lossy
|
||||
self.items: dict[str, str] = {}
|
||||
self.calls: list[tuple[list[str], str | None]] = []
|
||||
|
||||
def __call__(
|
||||
self, argv: list[str], stdin: str | None = None
|
||||
) -> subprocess.CompletedProcess[str]:
|
||||
self.calls.append((argv, stdin))
|
||||
if self.fail:
|
||||
raise CacheUnavailable(self.fail)
|
||||
|
||||
def done(rc: int = 0, out: str = "", err: str = "") -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.CompletedProcess(argv, rc, out, err)
|
||||
|
||||
if self.mac:
|
||||
if argv[1] == "-i":
|
||||
assert stdin is not None
|
||||
parts = stdin.split()
|
||||
if not self.lossy:
|
||||
self.items[parts[parts.index("-a") + 1]] = parts[parts.index("-w") + 1]
|
||||
return done()
|
||||
key = argv[argv.index("-a") + 1]
|
||||
if argv[1] == "find-generic-password":
|
||||
return done(0, self.items[key] + "\n") if key in self.items else done(44)
|
||||
self.items.pop(key, None)
|
||||
return done()
|
||||
key = argv[-1]
|
||||
if argv[1] == "store":
|
||||
if not self.lossy:
|
||||
assert stdin is not None
|
||||
self.items[key] = stdin
|
||||
return done()
|
||||
if argv[1] == "lookup":
|
||||
return done(0, self.items[key]) if key in self.items else done(1)
|
||||
self.items.pop(key, None)
|
||||
return done()
|
||||
|
||||
|
||||
def keychain(monkeypatch: pytest.MonkeyPatch, platform: str, tools: FakeTools) -> KeychainStore:
|
||||
monkeypatch.setattr(cache_mod.shutil, "which", lambda name: f"/usr/bin/{name}")
|
||||
monkeypatch.setattr(cache_mod, "_run", tools)
|
||||
return KeychainStore(platform)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("platform", "mac"), [("darwin", True), ("linux", False)])
|
||||
def test_keychain_roundtrip_keeps_secret_out_of_argv(
|
||||
monkeypatch: pytest.MonkeyPatch, platform: str, mac: bool
|
||||
) -> None:
|
||||
tools = FakeTools(mac)
|
||||
store = keychain(monkeypatch, platform, tools)
|
||||
entry = CacheEntry({"password": "pw-secret"}, "l", 1.0, 60)
|
||||
assert store.get("k") is None
|
||||
store.put("k", entry)
|
||||
assert store.get("k") == entry
|
||||
encoded = cache_mod._encode(entry)
|
||||
for argv, _ in tools.calls:
|
||||
assert not any(encoded in a or "pw-secret" in a for a in argv)
|
||||
assert any(stdin and encoded in stdin for _, stdin in tools.calls)
|
||||
store.delete("k")
|
||||
assert store.get("k") is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("platform", "mac"), [("darwin", True), ("linux", False)])
|
||||
def test_keychain_detects_silent_write_loss(
|
||||
monkeypatch: pytest.MonkeyPatch, platform: str, mac: bool
|
||||
) -> None:
|
||||
store = keychain(monkeypatch, platform, FakeTools(mac, lossy=True))
|
||||
with pytest.raises(CacheUnavailable, match="did not retain"):
|
||||
store.put("k", CacheEntry({"a": "b"}, "l", 1.0, 60))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("platform", "result"),
|
||||
[("darwin", 51), ("linux", 2)],
|
||||
)
|
||||
def test_keychain_tool_errors_map_to_unavailable(
|
||||
monkeypatch: pytest.MonkeyPatch, platform: str, result: int
|
||||
) -> None:
|
||||
store = keychain(monkeypatch, platform, FakeTools(platform == "darwin"))
|
||||
monkeypatch.setattr(
|
||||
cache_mod,
|
||||
"_run",
|
||||
lambda argv, stdin=None: subprocess.CompletedProcess(argv, result, "", "boom"),
|
||||
)
|
||||
with pytest.raises(CacheUnavailable):
|
||||
store.get("k")
|
||||
with pytest.raises(CacheUnavailable):
|
||||
store.put("k", CacheEntry({"a": "b"}, "l", 1.0, 60))
|
||||
|
||||
|
||||
def test_keychain_unavailable_when_tool_missing(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(cache_mod.shutil, "which", lambda name: None)
|
||||
for platform in ("darwin", "linux", "win32"):
|
||||
with pytest.raises(CacheUnavailable):
|
||||
KeychainStore(platform)
|
||||
|
||||
|
||||
def test_run_wraps_subprocess_errors() -> None:
|
||||
with pytest.raises(CacheUnavailable):
|
||||
cache_mod._run(["/nonexistent/definitely-not-here"])
|
||||
result = cache_mod._run(["/bin/cat"], stdin="hello")
|
||||
assert result.stdout == "hello"
|
||||
|
||||
|
||||
# ---- AutoStore / make_store -----------------------------------------------------------
|
||||
|
||||
|
||||
class BrokenStore(MemStore):
|
||||
def get(self, key: str) -> CacheEntry | None:
|
||||
raise CacheUnavailable("locked")
|
||||
|
||||
def put(self, key: str, entry: CacheEntry) -> None:
|
||||
raise CacheUnavailable("locked")
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
raise CacheUnavailable("locked")
|
||||
|
||||
|
||||
def test_auto_store_falls_back_and_warns_once(caplog: pytest.LogCaptureFixture) -> None:
|
||||
fallback = MemStore()
|
||||
store = AutoStore(BrokenStore(), fallback)
|
||||
entry = CacheEntry({"a": "b"}, "l", 1.0, 60)
|
||||
store.put("k", entry)
|
||||
assert store.get("k") == entry
|
||||
store.delete("k")
|
||||
assert store.get("k") is None
|
||||
assert caplog.text.count("keychain unavailable") == 1
|
||||
|
||||
|
||||
def test_auto_store_prefers_primary_and_clears_fallback() -> None:
|
||||
primary, fallback = MemStore(), MemStore()
|
||||
entry = CacheEntry({"a": "b"}, "l", 1.0, 60)
|
||||
fallback.put("k", entry)
|
||||
store = AutoStore(primary, fallback)
|
||||
store.put("k", entry)
|
||||
assert primary.get("k") == entry
|
||||
assert fallback.get("k") is None
|
||||
|
||||
|
||||
def test_make_store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(cache_mod.shutil, "which", lambda name: None)
|
||||
assert isinstance(make_store("file", tmp_path), FileStore)
|
||||
assert isinstance(make_store("auto", tmp_path), FileStore) # no keychain -> files
|
||||
with pytest.raises(CacheUnavailable):
|
||||
make_store("keychain", tmp_path)
|
||||
monkeypatch.setattr(cache_mod.shutil, "which", lambda name: f"/usr/bin/{name}")
|
||||
assert isinstance(make_store("auto", tmp_path), AutoStore)
|
||||
|
||||
|
||||
# ---- config ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def toml_config(
|
||||
extra: str = "", query: str = 'engine = "database"\nrole = "ro"\ncache = true'
|
||||
) -> dict[str, Any]:
|
||||
import tomllib
|
||||
|
||||
return tomllib.loads(
|
||||
f'[server]\naddress = "http://127.0.0.1:1"\ntoken = "t"\n{extra}\n[[query]]\n{query}\n'
|
||||
)
|
||||
|
||||
|
||||
def test_config_parses_cache_settings() -> None:
|
||||
cfg = parse_config(toml_config('[cache]\nstore = "file"'))
|
||||
assert cfg.queries[0].cache is True
|
||||
assert cfg.cache_store == "file"
|
||||
assert "cache" not in cfg.queries[0].options
|
||||
assert (
|
||||
parse_config(toml_config(query='engine = "kv"\nmount="s"\npath="p"')).cache_store == "file"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("extra", "query"),
|
||||
[
|
||||
('[cache]\nstore = "cloud"', 'engine = "database"\nrole = "r"'),
|
||||
("[cache]\nbogus = 1", 'engine = "database"\nrole = "r"'),
|
||||
("", 'engine = "database"\nrole = "r"\ncache = "yes"'),
|
||||
],
|
||||
)
|
||||
def test_config_rejects_bad_cache_settings(extra: str, query: str) -> None:
|
||||
with pytest.raises(ConfigError):
|
||||
parse_config(toml_config(extra, query))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
'engine = "kv"\nmount = "s"\npath = "p"\ncache = true',
|
||||
'engine = "ssh"\nrole = "r"\nip = "1.2.3.4"\ncache = true',
|
||||
'engine = "approle"\nrole = "r"\ncache = true',
|
||||
'engine = "database"\nrole = "r"\nstatic = true\ncache = true',
|
||||
],
|
||||
)
|
||||
def test_cache_rejected_for_uncacheable_queries(query: str) -> None:
|
||||
with pytest.raises(ConfigError, match="cache = true is not supported"):
|
||||
validate_queries(parse_config(toml_config(query=query)))
|
||||
|
||||
|
||||
def test_cache_accepted_for_dynamic_engines() -> None:
|
||||
validate_queries(parse_config(toml_config()))
|
||||
validate_queries(parse_config(toml_config(query='engine = "aws"\nrole = "r"\ncache = true')))
|
||||
|
||||
|
||||
# ---- CLI end to end -------------------------------------------------------------------
|
||||
|
||||
|
||||
def cli_config(config_dir: Path, fake: FakeBao) -> Path:
|
||||
return write_config(
|
||||
config_dir,
|
||||
f'[server]\naddress = "{fake.url}"\ntoken = "{TOKEN}"\n'
|
||||
'[cache]\nstore = "file"\n'
|
||||
'[[query]]\nengine = "database"\nrole = "ro"\nname = "pg"\ncache = true\n'
|
||||
'rename = { username = "PGUSER", password = "PGPASSWORD" }\n',
|
||||
)
|
||||
|
||||
|
||||
def test_cli_reuses_cached_credential(
|
||||
fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
serve_creds(fake_bao)
|
||||
path = cli_config(config_dir, fake_bao)
|
||||
outputs = []
|
||||
for _ in range(3):
|
||||
assert main(["--config", str(path), "--shell", "sh"]) == 0
|
||||
outputs.append(capsys.readouterr().out)
|
||||
assert creds_gets(fake_bao) == 1
|
||||
assert outputs[0] == outputs[1] == outputs[2]
|
||||
assert "PGPASSWORD=pw-secret" in outputs[0]
|
||||
cached = list((config_dir / "cache").glob("*.json"))
|
||||
assert len(cached) == 1
|
||||
assert stat.S_IMODE(cached[0].stat().st_mode) == 0o600
|
||||
|
||||
|
||||
def test_cli_exec_uses_cache(fake_bao: FakeBao, config_dir: Path) -> None:
|
||||
serve_creds(fake_bao)
|
||||
path = cli_config(config_dir, fake_bao)
|
||||
for _ in range(2):
|
||||
code = main(["--config", str(path), "exec", "-q", "pg", "--", "/usr/bin/true"])
|
||||
assert code == 0
|
||||
assert creds_gets(fake_bao) == 1
|
||||
|
||||
|
||||
def test_cli_clear_cache(
|
||||
fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
serve_creds(fake_bao)
|
||||
fake_bao.routes[REVOKE] = (204, b"")
|
||||
path = cli_config(config_dir, fake_bao)
|
||||
main(["--config", str(path), "--shell", "sh"])
|
||||
capsys.readouterr()
|
||||
assert main(["--config", str(path), "--clear-cache"]) == 0
|
||||
assert "cleared 1" in capsys.readouterr().err
|
||||
assert list((config_dir / "cache").glob("*.json")) == []
|
||||
assert fake_bao.posts[-1][0] == "/v1/sys/leases/revoke"
|
||||
main(["--config", str(path), "--shell", "sh"])
|
||||
assert creds_gets(fake_bao) == 2
|
||||
|
||||
|
||||
def test_cli_clear_cache_incompatible_with_exec(fake_bao: FakeBao, config_dir: Path) -> None:
|
||||
path = cli_config(config_dir, fake_bao)
|
||||
assert main(["--config", str(path), "--clear-cache", "exec", "-q", "pg", "--", "true"]) != 0
|
||||
@@ -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
|
||||
@@ -244,7 +244,7 @@ def test_resolve_aborts_on_auth_error(fake_bao: FakeBao, caplog: pytest.LogCaptu
|
||||
|
||||
def test_unknown_engine() -> None:
|
||||
with pytest.raises(ConfigError, match="unknown engine"):
|
||||
get_engine("approle")
|
||||
get_engine("nonexistent")
|
||||
|
||||
|
||||
def test_registry_contains_kv() -> None:
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from envbao.client import BaoClient
|
||||
from envbao.config import Config, Query, ServerConfig
|
||||
from envbao.engines import ENGINES, get_engine
|
||||
from envbao.errors import AuthError, ConfigError, NotFoundError, ServerError
|
||||
from envbao.resolve import run_query, validate_queries
|
||||
|
||||
from .conftest import TOKEN, FakeBao
|
||||
|
||||
|
||||
def client_for(fake: FakeBao, token: str = TOKEN) -> BaoClient:
|
||||
return BaoClient(ServerConfig(address=fake.url, token=token))
|
||||
|
||||
|
||||
def q(engine: str, **options: Any) -> Query:
|
||||
return Query(engine=engine, options=options, name=options.get("role", engine))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["kv", "database", "aws", "approle", "ssh"])
|
||||
def test_registry(name: str) -> None:
|
||||
assert name in ENGINES
|
||||
assert get_engine(name) is ENGINES[name]
|
||||
|
||||
|
||||
# ---- POST on the client --------------------------------------------------------------
|
||||
|
||||
|
||||
def test_post_sends_json_body_and_token(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("things", {"a": 1})
|
||||
body = client_for(fake_bao).post("things", {"x": "y"})
|
||||
assert body["data"] == {"a": 1}
|
||||
assert fake_bao.posts[-1] == ("/v1/things", {"x": "y"})
|
||||
assert fake_bao.requests[-1][1]["x-vault-token"] == TOKEN
|
||||
assert fake_bao.requests[-1][1]["content-type"] == "application/json"
|
||||
|
||||
|
||||
def test_post_without_body_sends_empty_object(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("things", {"a": 1})
|
||||
client_for(fake_bao).post("things")
|
||||
assert fake_bao.posts[-1][1] == {}
|
||||
|
||||
|
||||
def test_post_does_not_follow_redirect(fake_bao: FakeBao) -> None:
|
||||
with pytest.raises(ServerError, match="HTTP 307"):
|
||||
client_for(fake_bao).post("redirect", {})
|
||||
|
||||
|
||||
def test_post_auth_error_and_not_found(fake_bao: FakeBao) -> None:
|
||||
with pytest.raises(AuthError):
|
||||
client_for(fake_bao, token="s.wrong").post("things")
|
||||
with pytest.raises(NotFoundError):
|
||||
client_for(fake_bao).post("missing")
|
||||
|
||||
|
||||
# ---- database -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_database_dynamic(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("database/creds/ro", {"username": "v-ro-1", "password": "pw-secret"})
|
||||
query = q("database", role="ro")
|
||||
env = run_query(client_for(fake_bao), query, Config(ServerConfig("x", "t"), (query,)))
|
||||
assert env == {"username": "v-ro-1", "password": "pw-secret"}
|
||||
|
||||
|
||||
def test_database_prefix_and_lease_not_exported(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("pg/creds/ro", {"username": "u", "password": "pw-secret"})
|
||||
query = Query(
|
||||
engine="database",
|
||||
options={"role": "ro", "mount": "pg"},
|
||||
rename={"username": "PGUSER", "password": "PGPASSWORD"},
|
||||
name="pg",
|
||||
)
|
||||
env = run_query(client_for(fake_bao), query, Config(ServerConfig("x", "t"), (query,)))
|
||||
assert env == {"PGUSER": "u", "PGPASSWORD": "pw-secret"}
|
||||
|
||||
|
||||
def test_database_static(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route(
|
||||
"database/static-creds/app",
|
||||
{"username": "app", "password": "pw-secret", "last_vault_rotation": "now"},
|
||||
)
|
||||
data = get_engine("database").fetch(client_for(fake_bao), {"role": "app", "static": True})
|
||||
assert data == {"username": "app", "password": "pw-secret"}
|
||||
|
||||
|
||||
def test_database_missing_role_is_not_found(fake_bao: FakeBao) -> None:
|
||||
with pytest.raises(NotFoundError):
|
||||
get_engine("database").fetch(client_for(fake_bao), {"role": "nope"})
|
||||
|
||||
|
||||
def test_database_empty_response_fails(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("database/creds/r", {"other": "x"})
|
||||
with pytest.raises(ServerError, match="no credentials"):
|
||||
get_engine("database").fetch(client_for(fake_bao), {"role": "r"})
|
||||
|
||||
|
||||
def test_response_without_data(fake_bao: FakeBao) -> None:
|
||||
fake_bao.routes["/v1/database/creds/r"] = (200, {"data": None})
|
||||
with pytest.raises(NotFoundError):
|
||||
get_engine("database").fetch(client_for(fake_bao), {"role": "r"})
|
||||
fake_bao.routes["/v1/database/creds/r"] = (200, {"data": "str"})
|
||||
with pytest.raises(ServerError, match="shape"):
|
||||
get_engine("database").fetch(client_for(fake_bao), {"role": "r"})
|
||||
|
||||
|
||||
# ---- aws ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_aws_creds(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route(
|
||||
"aws/creds/dev", {"access_key": "AKIA1", "secret_key": "sk", "security_token": None}
|
||||
)
|
||||
data = get_engine("aws").fetch(client_for(fake_bao), {"role": "dev"})
|
||||
assert data == {"access_key": "AKIA1", "secret_key": "sk"}
|
||||
|
||||
|
||||
def test_aws_sts_with_ttl(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route(
|
||||
"aws/sts/dev?ttl=15m", {"access_key": "A", "secret_key": "S", "security_token": "T"}
|
||||
)
|
||||
data = get_engine("aws").fetch(
|
||||
client_for(fake_bao), {"role": "dev", "kind": "sts", "ttl": "15m"}
|
||||
)
|
||||
assert data["security_token"] == "T"
|
||||
|
||||
|
||||
# ---- approle --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_approle_both(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("auth/approle/role/web/role-id", {"role_id": "rid"})
|
||||
fake_bao.route(
|
||||
"auth/approle/role/web/secret-id", {"secret_id": "sid", "secret_id_accessor": "a"}
|
||||
)
|
||||
data = get_engine("approle").fetch(client_for(fake_bao), {"role": "web"})
|
||||
assert data == {"role_id": "rid", "secret_id": "sid"}
|
||||
assert fake_bao.posts[-1][0] == "/v1/auth/approle/role/web/secret-id"
|
||||
|
||||
|
||||
def test_approle_only_role_id_does_not_mint_secret_id(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("auth/ar/role/web/role-id", {"role_id": "rid"})
|
||||
data = get_engine("approle").fetch(
|
||||
client_for(fake_bao), {"role": "web", "mount": "ar", "what": "role_id"}
|
||||
)
|
||||
assert data == {"role_id": "rid"}
|
||||
assert fake_bao.posts == []
|
||||
|
||||
|
||||
def test_approle_only_secret_id(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route("auth/approle/role/web/secret-id", {"secret_id": "sid"})
|
||||
data = get_engine("approle").fetch(client_for(fake_bao), {"role": "web", "what": "secret_id"})
|
||||
assert data == {"secret_id": "sid"}
|
||||
|
||||
|
||||
# ---- ssh ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_ssh_otp(fake_bao: FakeBao) -> None:
|
||||
fake_bao.route(
|
||||
"ssh/creds/ops", {"key": "otp-value", "username": "ops", "ip": "10.0.0.5", "port": 22}
|
||||
)
|
||||
data = get_engine("ssh").fetch(client_for(fake_bao), {"role": "ops", "ip": "10.0.0.5"})
|
||||
assert data == {"key": "otp-value", "username": "ops", "ip": "10.0.0.5"}
|
||||
assert fake_bao.posts[-1][1] == {"ip": "10.0.0.5"}
|
||||
|
||||
|
||||
def test_ssh_sign(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
pub = tmp_path / "id.pub"
|
||||
pub.write_text("ssh-ed25519 AAAA test\n")
|
||||
fake_bao.route("ssh/sign/ops", {"signed_key": "cert", "serial_number": "1"})
|
||||
data = get_engine("ssh").fetch(
|
||||
client_for(fake_bao),
|
||||
{"role": "ops", "mode": "sign", "public_key_file": str(pub), "valid_principals": "ops"},
|
||||
)
|
||||
assert data == {"signed_key": "cert", "serial_number": "1"}
|
||||
assert fake_bao.posts[-1][1] == {
|
||||
"public_key": "ssh-ed25519 AAAA test",
|
||||
"valid_principals": "ops",
|
||||
}
|
||||
|
||||
|
||||
def test_ssh_sign_unreadable_key(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
with pytest.raises(ConfigError, match="cannot read"):
|
||||
get_engine("ssh").fetch(
|
||||
client_for(fake_bao),
|
||||
{"role": "ops", "mode": "sign", "public_key_file": str(tmp_path / "nope.pub")},
|
||||
)
|
||||
|
||||
|
||||
def test_ssh_sign_huge_key_rejected(fake_bao: FakeBao, tmp_path: Path) -> None:
|
||||
pub = tmp_path / "big.pub"
|
||||
pub.write_text("x" * (70 * 1024))
|
||||
with pytest.raises(ConfigError, match="large"):
|
||||
get_engine("ssh").fetch(
|
||||
client_for(fake_bao),
|
||||
{"role": "ops", "mode": "sign", "public_key_file": str(pub)},
|
||||
)
|
||||
|
||||
|
||||
# ---- validation -----------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("engine", "options"),
|
||||
[
|
||||
("database", {}),
|
||||
("database", {"role": ""}),
|
||||
("database", {"role": "r", "bogus": 1}),
|
||||
("database", {"role": "r", "static": "yes"}),
|
||||
("database", {"role": "r", "mount": 5}),
|
||||
("aws", {"role": "r", "kind": "other"}),
|
||||
("aws", {"role": "r", "ttl": ""}),
|
||||
("approle", {"role": "r", "what": "everything"}),
|
||||
("ssh", {"role": "r"}),
|
||||
("ssh", {"role": "r", "ip": "1.2.3.4", "public_key_file": "k"}),
|
||||
("ssh", {"role": "r", "mode": "sign"}),
|
||||
("ssh", {"role": "r", "mode": "sign", "public_key_file": "k", "ip": "1.2.3.4"}),
|
||||
("ssh", {"role": "r", "mode": "sign", "public_key_file": "k", "valid_principals": ""}),
|
||||
("ssh", {"role": "r", "mode": "bad"}),
|
||||
],
|
||||
)
|
||||
def test_invalid_options(engine: str, options: dict[str, Any]) -> None:
|
||||
with pytest.raises(ConfigError):
|
||||
get_engine(engine).validate(options)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("engine", "options"),
|
||||
[
|
||||
("database", {"role": "r"}),
|
||||
("database", {"role": "r", "mount": "pg", "static": True}),
|
||||
("aws", {"role": "r", "kind": "sts", "ttl": "1h"}),
|
||||
("approle", {"role": "r", "what": "role_id"}),
|
||||
("ssh", {"role": "r", "ip": "1.2.3.4"}),
|
||||
("ssh", {"role": "r", "mode": "sign", "public_key_file": "k", "valid_principals": "a,b"}),
|
||||
],
|
||||
)
|
||||
def test_valid_options(engine: str, options: dict[str, Any]) -> None:
|
||||
get_engine(engine).validate(options)
|
||||
validate_queries(Config(ServerConfig("x", "t"), (Query(engine=engine, options=options),)))
|
||||
@@ -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
|
||||