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:
1 parent
08bacbc5a8
commit
952fa2ce63
22 files changed
+1110
-44
No files matched your search
@@ -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())
|
||||
Reference in new issue
Block a user