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,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
|
||||
@@ -322,3 +322,26 @@ def test_audit_log_has_no_values_or_args(exec_cfg: Path) -> None:
|
||||
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
|
||||
Reference in new issue
Block a user