Add Claude access setup, onedir build and native packages

- scripts/setup_claude_access.py: narrow envbao-claude policy/token and an
  exec_only claude.toml; optional merge of Claude Code settings
- [security] exec_only refuses plain export mode and --no-redact
- PyInstaller onedir build (~0.06s start-up vs ~1.4s onefile)
- macOS .pkg, Debian/Ubuntu/Raspberry Pi OS .deb (pure-Python builder),
  tarball + scripts/install.sh; release pipeline updated
- docs: claude-access, install matrix, releasing, usage, security

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Sonnet 5.5 committed 2026-10-16 11:57:47 +01:00
1 parent 08bacbc5a8
commit 952fa2ce63
22 files changed
+1110 -44

No files matched your search

+45
View File
@@ -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
+228
View File
@@ -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))
+28
View File
@@ -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"
+7
View File
@@ -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."
+210
View File
@@ -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())