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

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

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

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

No files matched your search

View File
Whitespace-only changes.
+94
View File
@@ -0,0 +1,94 @@
"""Shared fixtures, including a tiny in-process fake OpenBao server."""
from __future__ import annotations
import json
import threading
from collections.abc import Iterator
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from typing import Any
import pytest
TOKEN = "s.test-token"
class FakeBao:
"""Records requests and serves canned responses keyed by path."""
def __init__(self) -> None:
self.routes: dict[str, tuple[int, Any]] = {}
self.requests: list[tuple[str, dict[str, str]]] = []
self.url = ""
def kv2(self, mount: str, path: str, data: dict[str, Any]) -> None:
self.routes[f"/v1/sys/internal/ui/mounts/{mount}"] = (
200,
{"data": {"options": {"version": "2"}}},
)
self.routes[f"/v1/{mount}/data/{path}"] = (200, {"data": {"data": data, "metadata": {}}})
def kv1(self, mount: str, path: str, data: dict[str, Any]) -> None:
self.routes[f"/v1/sys/internal/ui/mounts/{mount}"] = (
200,
{"data": {"options": None}},
)
self.routes[f"/v1/{mount}/{path}"] = (200, {"data": data})
@pytest.fixture
def fake_bao() -> Iterator[FakeBao]:
state = FakeBao()
class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None: # noqa: N802
headers = {k.lower(): v for k, v in self.headers.items()}
state.requests.append((self.path, headers))
if headers.get("x-vault-token") != TOKEN:
self._send(403, {"errors": ["permission denied"]})
return
if self.path == "/v1/auth/token/lookup-self":
self._send(200, {"data": {"ttl": 3600}})
return
if self.path == "/v1/redirect":
self.send_response(302)
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)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def log_message(self, *args: Any) -> None:
pass
server = HTTPServer(("127.0.0.1", 0), Handler)
state.url = f"http://127.0.0.1:{server.server_port}"
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
yield state
server.shutdown()
server.server_close()
@pytest.fixture
def config_dir(tmp_path: Path) -> Path:
d = tmp_path / ".envbao"
d.mkdir(mode=0o700)
d.chmod(0o700)
return d
def write_config(directory: Path, text: str, mode: int = 0o600) -> Path:
path = directory / "config.toml"
path.write_text(text)
path.chmod(mode)
return path
+224
View File
@@ -0,0 +1,224 @@
import os
import stat
import subprocess
import sys
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 .conftest import TOKEN, FakeBao, write_config
def conf(fake: FakeBao, token: str = TOKEN, extra: str = "") -> str:
return f"""
[server]
address = "{fake.url}"
token = "{token}"
[[query]]
mount = "secret"
path = "app"
{extra}
"""
def test_exports_variables(
fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
fake_bao.kv2("secret", "app", {"A": "1", "B": "it's"})
path = write_config(config_dir, conf(fake_bao))
assert main(["--config", str(path), "--shell", "bash"]) == EXIT_OK
out = capsys.readouterr()
assert out.out == "export A=1\nexport B='it'\"'\"'s'\n"
assert TOKEN not in out.err
def test_fish_and_auto_shell(
fake_bao: FakeBao,
config_dir: Path,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
) -> None:
fake_bao.kv2("secret", "app", {"A": "1"})
path = write_config(config_dir, conf(fake_bao))
monkeypatch.setenv("SHELL", "/usr/bin/fish")
assert main(["--config", str(path)]) == EXIT_OK
assert capsys.readouterr().out == "set -gx A '1'\n"
def test_insecure_permissions_exit_with_empty_stdout(
fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
fake_bao.kv2("secret", "app", {"A": "1"})
path = write_config(config_dir, conf(fake_bao), mode=0o644)
assert main(["--config", str(path)]) == EXIT_CONFIG
out = capsys.readouterr()
assert out.out == ""
assert "chmod 0600" in out.err
assert fake_bao.requests == [] # server never contacted
def test_insecure_directory(
fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
path = write_config(config_dir, conf(fake_bao))
config_dir.chmod(0o755)
assert main(["--config", str(path)]) == EXIT_CONFIG
assert capsys.readouterr().out == ""
def test_bad_token_exit_code(
fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
path = write_config(config_dir, conf(fake_bao, token="s.nope", extra="kv_version = 2"))
assert main(["--config", str(path)]) == EXIT_AUTH
out = capsys.readouterr()
assert out.out == ""
assert "s.nope" not in out.err
def test_unreachable_server(config_dir: Path, capsys: pytest.CaptureFixture[str]) -> None:
path = write_config(
config_dir,
'[server]\naddress = "http://127.0.0.1:1"\ntoken = "t"\ntimeout = 1\n'
'[[query]]\nmount = "s"\npath = "p"\n',
)
assert main(["--config", str(path)]) == EXIT_UNAVAILABLE
assert capsys.readouterr().out == ""
def test_missing_config(config_dir: Path, capsys: pytest.CaptureFixture[str]) -> None:
assert main(["--config", str(config_dir / "config.toml")]) == EXIT_CONFIG
assert capsys.readouterr().out == ""
def test_invalid_query_options(
fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
path = write_config(config_dir, conf(fake_bao, extra="kv_version = 9"))
assert main(["--config", str(path)]) == EXIT_CONFIG
assert "query #1" in capsys.readouterr().err
def test_fatal_query_error_prints_nothing(
fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
fake_bao.kv2("secret", "app", {"A": "1"})
path = write_config(
config_dir,
conf(fake_bao)
+ '[[query]]\nmount = "secret"\npath = "gone"\non_missing = "error"\nkv_version = 2\n',
)
assert main(["--config", str(path)]) == EXIT_UNAVAILABLE
assert capsys.readouterr().out == ""
def test_check_mode(
fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
path = write_config(config_dir, conf(fake_bao))
assert main(["--config", str(path), "--check"]) == EXIT_OK
out = capsys.readouterr()
assert out.out == ""
assert "OK" in out.err and "ttl 3600" in out.err
def test_log_file_created_private(
fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
fake_bao.kv2("secret", "app", {"A": "1"})
path = write_config(config_dir, conf(fake_bao))
assert main(["--config", str(path)]) == EXIT_OK
log = config_dir / "envbao.log"
assert stat.S_IMODE(log.stat().st_mode) == 0o600
text = log.read_text()
assert "exported 1 variable" in text and TOKEN not in text
# The log file itself must not trip the permission policy on the next run.
assert main(["--config", str(path)]) == EXIT_OK
def test_unexpected_exception_hides_details(
fake_bao: FakeBao,
config_dir: Path,
capsys: pytest.CaptureFixture[str],
monkeypatch: pytest.MonkeyPatch,
) -> None:
path = write_config(config_dir, conf(fake_bao))
def boom(*a: object, **k: object) -> None:
raise RuntimeError(f"leaks {TOKEN}")
monkeypatch.setattr("envbao.cli.resolve", boom)
assert main(["--config", str(path)]) == EXIT_FAILURE
out = capsys.readouterr()
assert out.out == "" and TOKEN not in out.err and "RuntimeError" in out.err
def test_verbose_flag(
fake_bao: FakeBao, config_dir: Path, capsys: pytest.CaptureFixture[str]
) -> None:
fake_bao.kv2("secret", "app", {"A": "1"})
path = write_config(config_dir, conf(fake_bao))
assert main(["--config", str(path), "-vv"]) == EXIT_OK
assert "KV v2" in capsys.readouterr().err
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
# ---- init -----------------------------------------------------------------------------
def test_init_creates_private_files(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
path = tmp_path / ".envbao" / "config.toml"
assert main(["--config", str(path), "--init"]) == EXIT_OK
assert stat.S_IMODE(path.parent.stat().st_mode) == 0o700
assert stat.S_IMODE(path.stat().st_mode) == 0o600
assert "[server]" in path.read_text()
def test_init_refuses_to_overwrite(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
path = tmp_path / ".envbao" / "config.toml"
init_config(path)
path.write_text("mine")
assert main(["--config", str(path), "--init"]) == EXIT_FAILURE
assert path.read_text() == "mine"
def test_init_tightens_existing_directory(tmp_path: Path) -> None:
d = tmp_path / ".envbao"
d.mkdir(mode=0o755)
init_config(d / "config.toml")
assert stat.S_IMODE(d.stat().st_mode) == 0o700
def test_template_passes_permission_policy_but_needs_token(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
path = tmp_path / ".envbao" / "config.toml"
main(["--config", str(path), "--init"])
capsys.readouterr()
assert main(["--config", str(path)]) == EXIT_CONFIG
assert "token is required" in capsys.readouterr().err
# ---- module entry point ---------------------------------------------------------------
def test_python_dash_m(tmp_path: Path) -> None:
result = subprocess.run( # noqa: S603
[sys.executable, "-m", "envbao", "--version"],
capture_output=True,
text=True,
check=True,
env={**os.environ},
)
assert __version__ in result.stdout
+272
View File
@@ -0,0 +1,272 @@
from pathlib import Path
import pytest
from envbao.client import BaoClient, validate_address
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 resolve, run_query, stringify, validate_queries
from .conftest import TOKEN, FakeBao
def server(fake: FakeBao, token: str = TOKEN, **kw: object) -> ServerConfig:
return ServerConfig(address=fake.url, token=token, **kw) # type: ignore[arg-type]
def query(**kw: object) -> Query:
opts = {"mount": "secret", "path": "app"}
opts.update(kw.pop("options", {})) # type: ignore[arg-type]
return Query(engine="kv", options=opts, **kw) # type: ignore[arg-type]
def cfg(fake: FakeBao, *queries: Query, **kw: object) -> Config:
return Config(server=server(fake), queries=queries, **kw) # type: ignore[arg-type]
# ---- address policy -------------------------------------------------------------------
@pytest.mark.parametrize("addr", ["http://127.0.0.1:8200", "http://localhost", "http://[::1]:8200"])
def test_http_loopback_allowed(addr: str) -> None:
assert validate_address(addr, allow_insecure_http=False).startswith("http://")
def test_http_remote_refused() -> None:
with pytest.raises(ConfigError, match="plain http"):
validate_address("http://bao.example.com", allow_insecure_http=False)
def test_http_remote_allowed_with_flag_warns(caplog: pytest.LogCaptureFixture) -> None:
validate_address("http://bao.example.com", allow_insecure_http=True)
assert "insecure" in caplog.text
@pytest.mark.parametrize("addr", ["ftp://x", "bao", "https://", "https://u:p@bao"])
def test_bad_addresses(addr: str) -> None:
with pytest.raises(ConfigError):
validate_address(addr, allow_insecure_http=True)
def test_bad_ca_cert(tmp_path: Path) -> None:
with pytest.raises(ConfigError, match="ca_cert"):
BaoClient(ServerConfig("https://bao", "t", ca_cert=tmp_path / "missing.pem"))
def test_https_client_builds() -> None:
BaoClient(ServerConfig("https://bao.example.com", "t"))
# ---- client ---------------------------------------------------------------------------
def test_get_sends_token_and_namespace(fake_bao: FakeBao) -> None:
client = BaoClient(server(fake_bao, namespace="team"))
client.get("auth/token/lookup-self")
_, headers = fake_bao.requests[-1]
assert headers["x-vault-token"] == TOKEN
assert headers["x-vault-namespace"] == "team"
def test_get_with_params(fake_bao: FakeBao) -> None:
fake_bao.routes["/v1/x?a=1"] = (200, {"ok": True})
assert BaoClient(server(fake_bao)).get("x", {"a": "1"}) == {"ok": True}
def test_bad_token_is_auth_error_without_leak(fake_bao: FakeBao) -> None:
with pytest.raises(AuthError) as exc:
BaoClient(server(fake_bao, token="s.wrong")).get("auth/token/lookup-self")
assert "s.wrong" not in str(exc.value)
def test_404(fake_bao: FakeBao) -> None:
with pytest.raises(NotFoundError):
BaoClient(server(fake_bao)).get("nothing")
def test_500(fake_bao: FakeBao) -> None:
fake_bao.routes["/v1/boom"] = (500, {})
with pytest.raises(ServerError, match="HTTP 500"):
BaoClient(server(fake_bao)).get("boom")
def test_unreachable() -> None:
with pytest.raises(ServerError, match="cannot reach"):
BaoClient(ServerConfig("http://127.0.0.1:1", "t", timeout=1)).get("x")
def test_invalid_json(fake_bao: FakeBao) -> None:
fake_bao.routes["/v1/bad"] = (200, b"not json")
with pytest.raises(ServerError, match="not valid JSON"):
BaoClient(server(fake_bao)).get("bad")
def test_non_object_json(fake_bao: FakeBao) -> None:
fake_bao.routes["/v1/list"] = (200, [1, 2])
with pytest.raises(ServerError, match="shape"):
BaoClient(server(fake_bao)).get("list")
def test_oversized_response(fake_bao: FakeBao, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("envbao.client._MAX_RESPONSE_BYTES", 5)
fake_bao.routes["/v1/big"] = (200, {"a": "long enough"})
with pytest.raises(ServerError, match="size limit"):
BaoClient(server(fake_bao)).get("big")
def test_redirects_not_followed(fake_bao: FakeBao) -> None:
with pytest.raises(ServerError, match="HTTP 302"):
BaoClient(server(fake_bao)).get("redirect")
# ---- kv engine ------------------------------------------------------------------------
def test_kv2_autodetect(fake_bao: FakeBao) -> None:
fake_bao.kv2("secret", "app", {"A": "1", "B": "two"})
env = run_query(BaoClient(server(fake_bao)), query(), cfg(fake_bao))
assert env == {"A": "1", "B": "two"}
def test_kv1_autodetect(fake_bao: FakeBao) -> None:
fake_bao.kv1("kv", "app", {"A": "1"})
q = query(options={"mount": "kv"})
assert run_query(BaoClient(server(fake_bao)), q, cfg(fake_bao)) == {"A": "1"}
def test_explicit_version_skips_detection(fake_bao: FakeBao) -> None:
fake_bao.routes["/v1/secret/data/app"] = (200, {"data": {"data": {"A": "1"}}})
q = query(options={"kv_version": 2})
assert run_query(BaoClient(server(fake_bao)), q, cfg(fake_bao)) == {"A": "1"}
assert all("sys/internal" not in p for p, _ in fake_bao.requests)
def test_detection_failure_message(fake_bao: FakeBao) -> None:
with pytest.raises(NotFoundError, match="kv_version"):
run_query(BaoClient(server(fake_bao)), query(on_missing="error"), cfg(fake_bao))
def test_keys_prefix_rename(fake_bao: FakeBao) -> None:
fake_bao.kv2("secret", "app", {"DB": "x", "SKIP": "y"})
q = query(keys=("DB",), prefix="APP_", rename={"DB": "DATABASE"})
assert run_query(BaoClient(server(fake_bao)), q, cfg(fake_bao)) == {"APP_DATABASE": "x"}
def test_missing_key_warn_and_error(fake_bao: FakeBao, caplog: pytest.LogCaptureFixture) -> None:
fake_bao.kv2("secret", "app", {"A": "1"})
client = BaoClient(server(fake_bao))
assert run_query(client, query(keys=("A", "Z")), cfg(fake_bao)) == {"A": "1"}
assert "'Z'" in caplog.text
with pytest.raises(NotFoundError):
run_query(client, query(keys=("Z",), on_missing="error"), cfg(fake_bao))
def test_missing_secret_warn_and_error(fake_bao: FakeBao) -> None:
fake_bao.routes["/v1/sys/internal/ui/mounts/secret"] = (
200,
{"data": {"options": {"version": "2"}}},
)
client = BaoClient(server(fake_bao))
assert run_query(client, query(), cfg(fake_bao)) == {}
with pytest.raises(NotFoundError):
run_query(client, query(on_missing="error"), cfg(fake_bao))
def test_deleted_kv2_version_is_missing(fake_bao: FakeBao) -> None:
fake_bao.routes["/v1/sys/internal/ui/mounts/secret"] = (
200,
{"data": {"options": {"version": "2"}}},
)
fake_bao.routes["/v1/secret/data/app"] = (200, {"data": {"data": None}})
assert run_query(BaoClient(server(fake_bao)), query(), cfg(fake_bao)) == {}
def test_bad_data_shape(fake_bao: FakeBao) -> None:
fake_bao.routes["/v1/secret/app"] = (200, {"data": ["x"]})
q = query(options={"kv_version": 1})
with pytest.raises(ServerError, match="shape"):
run_query(BaoClient(server(fake_bao)), q, cfg(fake_bao))
def test_invalid_and_protected_names_skipped(
fake_bao: FakeBao, caplog: pytest.LogCaptureFixture
) -> None:
fake_bao.kv2("secret", "app", {"OK": "1", "bad-name": "2", "PATH": "/evil", "LD_PRELOAD": "x"})
env = run_query(BaoClient(server(fake_bao)), query(), cfg(fake_bao))
assert env == {"OK": "1"}
assert "protected variable PATH" in caplog.text
assert "/evil" not in caplog.text
def test_protected_can_be_allowed(fake_bao: FakeBao) -> None:
fake_bao.kv2("secret", "app", {"PATH": "/opt/bin"})
c = cfg(fake_bao, allow_protected=frozenset({"PATH"}))
assert run_query(BaoClient(server(fake_bao)), query(), c) == {"PATH": "/opt/bin"}
def test_secret_values_never_logged(fake_bao: FakeBao, caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level("DEBUG")
fake_bao.kv2("secret", "app", {"A": "hunter2-super-secret"})
resolve(BaoClient(server(fake_bao)), cfg(fake_bao, query()))
assert "hunter2" not in caplog.text
assert TOKEN not in caplog.text
@pytest.mark.parametrize(
"value, expected",
[("s", "s"), (5, "5"), (1.5, "1.5"), (True, "true"), (None, "null"), ({"a": [1]}, '{"a":[1]}')],
)
def test_stringify(value: object, expected: str) -> None:
assert stringify(value) == expected
# ---- resolve --------------------------------------------------------------------------
def test_later_queries_override(fake_bao: FakeBao, caplog: pytest.LogCaptureFixture) -> None:
fake_bao.kv2("secret", "one", {"A": "1", "B": "1"})
fake_bao.kv2("secret", "two", {"A": "2"})
c = cfg(fake_bao, query(options={"path": "one"}), query(options={"path": "two"}))
assert resolve(BaoClient(c.server), c) == {"A": "2", "B": "1"}
assert "overridden" in caplog.text
def test_resolve_aborts_on_auth_error(fake_bao: FakeBao, caplog: pytest.LogCaptureFixture) -> None:
c = Config(server=server(fake_bao, token="bad"), queries=(query(options={"kv_version": 2}),))
with pytest.raises(AuthError):
resolve(BaoClient(c.server), c)
assert "failed" in caplog.text
# ---- engine registry / validation -----------------------------------------------------
def test_unknown_engine() -> None:
with pytest.raises(ConfigError, match="unknown engine"):
get_engine("approle")
def test_registry_contains_kv() -> None:
assert "kv" in ENGINES
@pytest.mark.parametrize(
"options, message",
[
({"mount": "s"}, "'path'"),
({"path": "p"}, "'mount'"),
({"mount": "/", "path": "p"}, "'mount'"),
({"mount": "s", "path": "p", "kv_version": 3}, "kv_version"),
({"mount": "s", "path": "p", "bogus": 1}, "unknown option"),
],
)
def test_kv_validation(options: dict, message: str) -> None:
c = Config(ServerConfig("https://b", "t"), (Query("kv", options),))
with pytest.raises(ConfigError, match=message):
validate_queries(c)
def test_validate_queries_ok() -> None:
c = Config(ServerConfig("https://b", "t"), (query(),))
validate_queries(c)
+126
View File
@@ -0,0 +1,126 @@
from pathlib import Path
import pytest
from envbao.config import load_config, parse_config, resolve_config_path
from envbao.errors import ConfigError, PermissionPolicyError
BASE = {"server": {"address": "https://bao:8200", "token": "t"}}
def test_minimal_config() -> None:
cfg = parse_config(BASE)
assert cfg.server.address == "https://bao:8200"
assert cfg.server.timeout == 5.0
assert cfg.queries == ()
def test_token_not_in_repr() -> None:
assert "t'" not in repr(parse_config(BASE).server).replace("token", "")
assert "token='t'" not in repr(parse_config(BASE).server)
def test_full_query() -> None:
cfg = parse_config(
{
**BASE,
"security": {"allow_protected": ["PATH"]},
"query": [
{
"mount": "secret",
"path": "a",
"keys": ["X"],
"prefix": "P_",
"rename": {"X": "Y"},
"on_missing": "error",
}
],
}
)
q = cfg.queries[0]
assert q.engine == "kv"
assert q.options == {"mount": "secret", "path": "a"}
assert q.keys == ("X",)
assert q.prefix == "P_"
assert q.rename == {"X": "Y"}
assert q.on_missing == "error"
assert cfg.allow_protected == {"PATH"}
assert "mount=secret" in q.describe()
@pytest.mark.parametrize(
"data, message",
[
({}, "missing \\[server\\]"),
({"bogus": 1, **BASE}, "unknown key"),
({"server": {"token": "t"}}, "address is required"),
({"server": {"address": "https://x"}}, "token is required"),
({"server": {"address": "x", "token": "t", "extra": 1}}, "unknown key"),
({"server": {"address": "x", "token": "t", "token_file": "f"}}, "only one"),
({"server": {"address": 5, "token": "t"}}, "must be a string"),
({"server": {"address": "x", "token": "t", "timeout": -1}}, "timeout"),
({"server": {"address": "x", "token": "t", "timeout": True}}, "timeout"),
({"server": {"address": "x", "token": "t", "allow_insecure_http": "yes"}}, "boolean"),
({"server": "nope"}, "must be a table"),
({**BASE, "query": {"a": 1}}, "\\[\\[query\\]\\]"),
({**BASE, "query": ["x"]}, "must be a table"),
({**BASE, "query": [{"keys": "A"}]}, "list of strings"),
({**BASE, "query": [{"rename": {"a": 1}}]}, "rename"),
({**BASE, "query": [{"on_missing": "ignore"}]}, "on_missing"),
({**BASE, "security": {"x": 1}}, "unknown key"),
],
)
def test_invalid_configs(data: dict, message: str) -> None:
with pytest.raises(ConfigError, match=message):
parse_config(data)
def test_token_file(tmp_path: Path) -> None:
tf = tmp_path / "tok"
tf.write_text(" s.abc\n")
tf.chmod(0o600)
cfg = parse_config({"server": {"address": "https://b", "token_file": str(tf)}})
assert cfg.server.token == "s.abc"
def test_token_file_permissions_enforced(tmp_path: Path) -> None:
tf = tmp_path / "tok"
tf.write_text("s.abc")
tf.chmod(0o644)
with pytest.raises(PermissionPolicyError):
parse_config({"server": {"address": "https://b", "token_file": str(tf)}})
def test_token_file_missing(tmp_path: Path) -> None:
with pytest.raises(PermissionPolicyError):
parse_config({"server": {"address": "https://b", "token_file": str(tmp_path / "x")}})
def test_load_config_roundtrip(tmp_path: Path) -> None:
p = tmp_path / "c.toml"
p.write_text('[server]\naddress = "https://b"\ntoken = "t"\nca_cert = "~/ca.pem"\n')
cfg = load_config(p)
assert cfg.server.ca_cert == Path("~/ca.pem").expanduser()
def test_load_missing_file(tmp_path: Path) -> None:
with pytest.raises(ConfigError, match="not found"):
load_config(tmp_path / "nope.toml")
def test_load_bad_toml(tmp_path: Path) -> None:
p = tmp_path / "c.toml"
p.write_text("[server\n")
with pytest.raises(ConfigError, match="invalid TOML"):
load_config(p)
def test_load_unreadable(tmp_path: Path) -> None:
with pytest.raises(ConfigError, match="cannot read"):
load_config(tmp_path) # a directory
def test_resolve_config_path(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
monkeypatch.setenv("HOME", str(tmp_path))
assert resolve_config_path(None) == tmp_path / ".envbao" / "config.toml"
assert resolve_config_path("~/x.toml") == tmp_path / "x.toml"
+103
View File
@@ -0,0 +1,103 @@
import shlex
import subprocess
import pytest
from envbao.errors import ConfigError
from envbao.render import detect_shell, is_protected, is_valid_name, render
@pytest.mark.parametrize("name", ["A", "_a", "FOO_BAR1", "a"])
def test_valid_names(name: str) -> None:
assert is_valid_name(name)
@pytest.mark.parametrize("name", ["", "1A", "A-B", "A B", "A=B", "A\n", "A;rm", "é"])
def test_invalid_names(name: str) -> None:
assert not is_valid_name(name)
@pytest.mark.parametrize("name", ["PATH", "LD_PRELOAD", "DYLD_INSERT_LIBRARIES", "BASH_FUNC_x%%"])
def test_protected(name: str) -> None:
assert is_protected(name)
def test_not_protected() -> None:
assert not is_protected("MY_API_KEY")
def test_posix_render() -> None:
assert render({"A": "b c", "D": "it's"}) == "export A='b c'\nexport D='it'\"'\"'s'\n"
def test_empty_render() -> None:
assert render({}) == ""
def test_fish_render() -> None:
assert render({"A": "it's \\ ok"}, "fish") == "set -gx A 'it\\'s \\\\ ok'\n"
@pytest.mark.parametrize(
"value",
[
"$(touch /tmp/pwned)",
"`id`",
"a; b",
"a\nb",
"'\"'",
"$HOME",
"\\",
"*",
"!!",
"a b\tc",
"é",
],
)
def test_roundtrip_through_real_shell(value: str) -> None:
script = render({"V": value}) + 'printf %s "$V"'
out = subprocess.run( # noqa: S603
["/bin/sh", "-c", script],
capture_output=True,
check=True,
text=True, # noqa: S607
)
assert out.stdout == value
def test_values_are_single_argument() -> None:
assert shlex.split(render({"V": "a; b"}).split("=", 1)[1]) == ["a; b"]
def test_invalid_name_raises() -> None:
with pytest.raises(ConfigError, match="invalid environment"):
render({"BAD NAME": "x"})
def test_nul_raises() -> None:
with pytest.raises(ConfigError, match="NUL"):
render({"A": "x\x00y"})
def test_unknown_shell() -> None:
with pytest.raises(ConfigError, match="unsupported"):
render({"A": "x"}, "powershell")
@pytest.mark.parametrize(
"shell, expected",
[
("/bin/zsh", "zsh"),
("/usr/bin/fish", "fish"),
("/bin/bash", "bash"),
("/bin/tcsh", "sh"),
("", "sh"),
],
)
def test_detect_shell(shell: str, expected: str) -> None:
assert detect_shell({"SHELL": shell}) == expected
def test_detect_shell_from_os_environ(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("SHELL", "/bin/zsh")
assert detect_shell() == "zsh"
+93
View File
@@ -0,0 +1,93 @@
import os
from pathlib import Path
import pytest
from envbao.errors import EXIT_CONFIG, PermissionPolicyError
from envbao.security import check_config_dir, check_path
def test_safe_directory_passes(config_dir: Path) -> None:
(config_dir / "config.toml").write_text("x")
(config_dir / "config.toml").chmod(0o600)
check_config_dir(config_dir)
def test_missing_directory(tmp_path: Path) -> None:
with pytest.raises(PermissionPolicyError, match="does not exist"):
check_config_dir(tmp_path / "nope")
@pytest.mark.parametrize("mode", [0o755, 0o770, 0o701, 0o750])
def test_directory_too_open(config_dir: Path, mode: int) -> None:
config_dir.chmod(mode)
with pytest.raises(PermissionPolicyError, match="chmod 0700"):
check_config_dir(config_dir)
@pytest.mark.parametrize("mode", [0o644, 0o640, 0o602, 0o660])
def test_file_too_open(config_dir: Path, mode: int) -> None:
f = config_dir / "config.toml"
f.write_text("x")
f.chmod(mode)
with pytest.raises(PermissionPolicyError, match="chmod 0600"):
check_config_dir(config_dir)
def test_nested_file_checked(config_dir: Path) -> None:
sub = config_dir / "sub"
sub.mkdir(mode=0o700)
bad = sub / "token"
bad.write_text("x")
bad.chmod(0o666)
with pytest.raises(PermissionPolicyError):
check_config_dir(config_dir)
def test_symlink_rejected(config_dir: Path, tmp_path: Path) -> None:
target = tmp_path / "real"
target.write_text("x")
target.chmod(0o600)
(config_dir / "link").symlink_to(target)
with pytest.raises(PermissionPolicyError, match="symbolic link"):
check_config_dir(config_dir)
def test_symlinked_directory_rejected(tmp_path: Path, config_dir: Path) -> None:
link = tmp_path / "linkdir"
link.symlink_to(config_dir)
with pytest.raises(PermissionPolicyError, match="symbolic link"):
check_config_dir(link)
def test_directory_given_as_file(tmp_path: Path) -> None:
f = tmp_path / "f"
f.write_text("x")
f.chmod(0o600)
with pytest.raises(PermissionPolicyError, match="not a directory"):
check_path(f, expect_dir=True)
def test_other_owner_rejected(config_dir: Path, monkeypatch: pytest.MonkeyPatch) -> None:
real = os.geteuid()
monkeypatch.setattr(os, "geteuid", lambda: real + 1)
with pytest.raises(PermissionPolicyError, match="not owned"):
check_path(config_dir, expect_dir=True)
def test_special_file_rejected(config_dir: Path) -> None:
fifo = config_dir / "pipe"
os.mkfifo(fifo, 0o600)
with pytest.raises(PermissionPolicyError, match="not a regular"):
check_config_dir(config_dir)
def test_violation_is_logged_critical(config_dir: Path, caplog: pytest.LogCaptureFixture) -> None:
config_dir.chmod(0o755)
with pytest.raises(PermissionPolicyError):
check_config_dir(config_dir)
assert any(r.levelname == "CRITICAL" for r in caplog.records)
def test_exit_code() -> None:
assert PermissionPolicyError.exit_code == EXIT_CONFIG
+71
View File
@@ -0,0 +1,71 @@
import importlib.util
from pathlib import Path
import pytest
_spec = importlib.util.spec_from_file_location(
"version_from_tag", Path(__file__).parent.parent / "scripts" / "version_from_tag.py"
)
assert _spec and _spec.loader
vft = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(vft)
@pytest.mark.parametrize(
"tag, version",
[
("v0.0.1", "0.0.1"),
("v1.2.3", "1.2.3"),
("v10.20.30", "10.20.30"),
("v1.0.0-rc.1", "1.0.0-rc.1"),
("v1.0.0-alpha+001", "1.0.0-alpha+001"),
("v1.0.0+20130313144700", "1.0.0+20130313144700"),
],
)
def test_valid_tags(tag: str, version: str) -> None:
assert vft.parse_tag(tag) == version
@pytest.mark.parametrize(
"tag",
[
"1.2.3",
"v1.2",
"v01.2.3",
"v1.2.3.4",
"v1.2.3-",
"v1.2.3-01",
"latest",
"",
"v1.2.3 ",
"V1.2.3",
],
)
def test_invalid_tags(tag: str) -> None:
with pytest.raises(ValueError, match="not a valid semver"):
vft.parse_tag(tag)
def test_main_writes_version(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
target = tmp_path / "_version.py"
monkeypatch.setattr(vft, "VERSION_FILE", target)
assert vft.main(["x", "v2.0.1"]) == 0
assert '__version__ = "2.0.1"' in target.read_text()
assert capsys.readouterr().out == "2.0.1\n"
def test_write_version_real(tmp_path: Path) -> None:
target = tmp_path / "v.py"
vft.write_version("3.1.4", target)
assert "Overwritten" in target.read_text() and '"3.1.4"' in target.read_text()
def test_main_rejects_bad_tag(capsys: pytest.CaptureFixture[str]) -> None:
assert vft.main(["x", "nope"]) == 1
assert "not a valid semver" in capsys.readouterr().err
def test_main_usage() -> None:
assert vft.main(["x"]) == 2