Add castle secret CLI and fail-loud unresolved-secret apply gate
Writing a secret by hand meant knowing the active backend and its layout;
getting it wrong (a file write on an OpenBao fleet) left the value where the
resolver never reads it, so ${secret:NAME} silently degraded to the literal
<MISSING_SECRET:NAME> placeholder that a service then used as its credential.
- `castle secret {list|set|get|rm}` reads/writes the ACTIVE backend, so there's
no wrong store to pick. `set NAME` with no value reads a hidden prompt / stdin.
- `castle apply` (and --plan) now refuses to converge any deployment whose
${secret:...} refs don't resolve in the active backend: exits non-zero, writes
nothing, and names each deployment + secret + the `castle secret set` fix.
- New helpers in core/config.py: active_secret_backend(), active_backend_name(),
secret_refs(). Gate impl: deploy._unresolved_secrets() + ApplyResult.blocked.
- Tests: test_deploy_secret_gate.py, TestSecretRefs, test_secret.py. Docs: AGENTS.md.
This commit is contained in:
@@ -35,6 +35,14 @@ def run_apply(args: argparse.Namespace) -> int:
|
||||
|
||||
result = apply(target_name=target, plan=plan)
|
||||
|
||||
# Unresolved secrets abort the run before any change — print the error block
|
||||
# (which names each deployment, the missing ${secret:…}, and the fix) and exit
|
||||
# non-zero so a broken credential never slips through as a bogus placeholder.
|
||||
if result.blocked:
|
||||
for msg in result.messages:
|
||||
print(f" {_C['deactivate']}{msg}{_C['reset']}")
|
||||
return 1
|
||||
|
||||
# Surface any warnings the render produced (acme prerequisites, tunnel notes).
|
||||
for msg in result.messages:
|
||||
if msg.startswith("Warning"):
|
||||
|
||||
93
cli/src/castle_cli/commands/secret.py
Normal file
93
cli/src/castle_cli/commands/secret.py
Normal file
@@ -0,0 +1,93 @@
|
||||
"""castle secret — read/write secrets in the *active* backend.
|
||||
|
||||
The active backend (file or openbao) is selected by the ``secrets:`` block of
|
||||
castle.yaml (env overrides). Writing a secret by hand means knowing that choice
|
||||
and the backend's storage layout — get it wrong and the value lands somewhere the
|
||||
resolver never reads, so ``${secret:NAME}`` silently degrades to a
|
||||
``<MISSING_SECRET:NAME>`` placeholder that a service then uses as if it were the
|
||||
real credential (exactly how immich's DB password went to a file on an OpenBao
|
||||
fleet). This command routes every read/write through
|
||||
:func:`castle_core.config.active_secret_backend`, so there's no wrong store to
|
||||
pick. ``castle apply`` refuses to converge a deployment whose secrets don't
|
||||
resolve here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import getpass
|
||||
import sys
|
||||
|
||||
from castle_core.config import active_backend_name, active_secret_backend
|
||||
|
||||
|
||||
def run_secret(args: argparse.Namespace) -> int:
|
||||
sub = getattr(args, "secret_command", None)
|
||||
if not sub:
|
||||
print("Usage: castle secret {list|set|get|rm}")
|
||||
return 1
|
||||
if sub == "list":
|
||||
return _list()
|
||||
if sub == "set":
|
||||
return _set(args.name, args.value)
|
||||
if sub == "get":
|
||||
return _get(args.name)
|
||||
if sub == "rm":
|
||||
return _rm(args.name, getattr(args, "yes", False))
|
||||
return 1
|
||||
|
||||
|
||||
def _list() -> int:
|
||||
backend = active_backend_name()
|
||||
names = active_secret_backend().list_names()
|
||||
if not names:
|
||||
print(f"No secrets in the active '{backend}' backend.")
|
||||
return 0
|
||||
print(f"Secrets in the active '{backend}' backend ({len(names)}):")
|
||||
for n in names:
|
||||
print(f" {n}")
|
||||
return 0
|
||||
|
||||
|
||||
def _set(name: str, value: str | None) -> int:
|
||||
backend = active_backend_name()
|
||||
if value is None:
|
||||
# No value on the argv (keeps it out of shell history / ps). Read from a
|
||||
# hidden prompt when interactive, else from stdin (pipe-friendly).
|
||||
if sys.stdin.isatty():
|
||||
value = getpass.getpass(f"Value for {name}: ")
|
||||
else:
|
||||
value = sys.stdin.read().strip()
|
||||
if not value:
|
||||
print("Error: empty value — refusing to set.", file=sys.stderr)
|
||||
return 1
|
||||
active_secret_backend().write(name, value)
|
||||
print(f"Set '{name}' in the active '{backend}' backend.")
|
||||
return 0
|
||||
|
||||
|
||||
def _get(name: str) -> int:
|
||||
value = active_secret_backend().read(name)
|
||||
if value is None:
|
||||
print(
|
||||
f"Secret '{name}' not found in the active '{active_backend_name()}' backend.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
print(value)
|
||||
return 0
|
||||
|
||||
|
||||
def _rm(name: str, yes: bool) -> int:
|
||||
backend = active_backend_name()
|
||||
if active_secret_backend().read(name) is None:
|
||||
print(f"Secret '{name}' not found in the active '{backend}' backend.", file=sys.stderr)
|
||||
return 1
|
||||
if not yes:
|
||||
reply = input(f"Delete secret '{name}' from the '{backend}' backend? [y/N] ")
|
||||
if reply.strip().lower() not in ("y", "yes"):
|
||||
print("Aborted.")
|
||||
return 1
|
||||
active_secret_backend().delete(name)
|
||||
print(f"Deleted '{name}' from the active '{backend}' backend.")
|
||||
return 0
|
||||
@@ -212,6 +212,22 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
)
|
||||
tls_sub.add_parser("status", help="Show each TLS service's cert fingerprint + expiry")
|
||||
|
||||
# Secrets — read/write the ACTIVE backend (file or openbao), so a value never
|
||||
# gets hand-written to the wrong store (the mistake that silently shadows an
|
||||
# OpenBao fleet's secret with a stray file the vault never reads).
|
||||
sec = subparsers.add_parser("secret", help="Manage secrets in the active backend")
|
||||
sec.set_defaults(resource="secret")
|
||||
sec_sub = sec.add_subparsers(dest="secret_command")
|
||||
sec_sub.add_parser("list", help="List secret names in the active backend")
|
||||
p = sec_sub.add_parser("set", help="Set a secret (prompts if VALUE omitted)")
|
||||
p.add_argument("name", help="Secret name")
|
||||
p.add_argument("value", nargs="?", help="Value (omit to read from a hidden prompt / stdin)")
|
||||
p = sec_sub.add_parser("get", help="Read a secret's value")
|
||||
p.add_argument("name", help="Secret name")
|
||||
p = sec_sub.add_parser("rm", help="Delete a secret from the active backend")
|
||||
p.add_argument("name", help="Secret name")
|
||||
p.add_argument("-y", "--yes", action="store_true", help="Skip confirmation")
|
||||
|
||||
# Convergence — the one lifecycle verb. Renders units/Caddyfile/tunnel, then
|
||||
# reconciles the runtime to match config (activate/restart/deactivate).
|
||||
p = subparsers.add_parser(
|
||||
@@ -380,6 +396,10 @@ def main() -> int:
|
||||
from castle_cli.commands.tls import run_tls
|
||||
|
||||
return run_tls(args)
|
||||
if cmd == "secret":
|
||||
from castle_cli.commands.secret import run_secret
|
||||
|
||||
return run_secret(args)
|
||||
if cmd == "apply":
|
||||
from castle_cli.commands.apply import run_apply
|
||||
|
||||
|
||||
56
cli/tests/test_secret.py
Normal file
56
cli/tests/test_secret.py
Normal file
@@ -0,0 +1,56 @@
|
||||
"""Tests for the `castle secret` command (reads/writes the active backend)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from argparse import Namespace
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def file_secrets(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
|
||||
"""Force the active backend to a temp file store."""
|
||||
secrets = tmp_path / "secrets"
|
||||
secrets.mkdir()
|
||||
monkeypatch.setenv("CASTLE_SECRET_BACKEND", "file")
|
||||
monkeypatch.setattr("castle_core.config.SECRETS_DIR", secrets)
|
||||
return secrets
|
||||
|
||||
|
||||
def _run(**kw: object) -> int:
|
||||
from castle_cli.commands.secret import run_secret
|
||||
|
||||
return run_secret(Namespace(**kw))
|
||||
|
||||
|
||||
class TestSecretRoundtrip:
|
||||
def test_set_get_list_rm(self, file_secrets: Path, capsys: object) -> None:
|
||||
assert _run(secret_command="set", name="MY_KEY", value="s3cret") == 0
|
||||
capsys.readouterr() # type: ignore[attr-defined] # drain the "Set …" line
|
||||
|
||||
assert _run(secret_command="get", name="MY_KEY") == 0
|
||||
assert capsys.readouterr().out.strip() == "s3cret" # type: ignore[attr-defined]
|
||||
|
||||
assert _run(secret_command="list") == 0
|
||||
assert "MY_KEY" in capsys.readouterr().out # type: ignore[attr-defined]
|
||||
|
||||
assert _run(secret_command="rm", name="MY_KEY", yes=True) == 0
|
||||
# Gone → non-zero.
|
||||
assert _run(secret_command="get", name="MY_KEY") == 1
|
||||
|
||||
|
||||
class TestSecretEdges:
|
||||
def test_get_missing_is_nonzero(self, file_secrets: Path) -> None:
|
||||
assert _run(secret_command="get", name="ABSENT") == 1
|
||||
|
||||
def test_empty_value_refused(self, file_secrets: Path) -> None:
|
||||
# Explicit empty string on argv is refused (not silently stored).
|
||||
assert _run(secret_command="set", name="K", value="") == 1
|
||||
|
||||
def test_rm_missing_is_nonzero(self, file_secrets: Path) -> None:
|
||||
assert _run(secret_command="rm", name="ABSENT", yes=True) == 1
|
||||
|
||||
def test_no_subcommand_usage(self, file_secrets: Path, capsys: object) -> None:
|
||||
assert _run(secret_command=None) == 1
|
||||
assert "Usage" in capsys.readouterr().out # type: ignore[attr-defined]
|
||||
Reference in New Issue
Block a user