diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 2e8c56504..34a72619e 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -1,3 +1,4 @@ {"id":"int-ca573b1f243d5e820077aadb21af8595","kind":"field_change","created_at":"2026-08-15T12:27:33.967613847Z","actor":"Sam Catlow","issue_id":"archie-core-1786637491053-48-fe78cd53","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Verified against current main: Route/RouteStream reject unrecognized slash commands before any LLM call (gateway.go:299-318, 449-462), /start is deterministic in both gateway and Telegram handlers, and full test matrix from acceptance criteria exists (gateway_test.go:106-133, gateway_stream_test.go:54-88, telegram_test.go:135-157). Confirmed by fresh code-tracing pass, not just prior user experience."}} {"id":"int-73ca4d209481e52e20c00c128fc6a3ca","kind":"field_change","created_at":"2026-08-15T12:41:34.047451864Z","actor":"Sam Catlow","issue_id":"archie-core-1786748942519-17-5999d55b","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}} {"id":"int-2193ae15ea3e5922294ec78dffe4958a","kind":"field_change","created_at":"2026-08-15T13:36:38.960683238Z","actor":"Sam Catlow","issue_id":"archie-core-1786637489985-8-13b9d8a8","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Documented the memory engine contract, owning manager, lifecycle/failure isolation, and third-party trust boundary in ARCHITECTURE.md; focused memory tests pass."}} +{"id":"int-b91f90f48c3115e8d29a3f60e88408e5","kind":"field_change","created_at":"2026-08-17T14:22:09.796781498Z","actor":"Sam Catlow","issue_id":"archie-core-1786748942324-9-509793a0","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Pivoted after design review: value-entry web form duplicates the Bitwarden app for bws and adds a secret-accepting web surface for no gain. The real gap was engine refresh (bws caches once per process). Replaced by fresh-resolving sops/vault/age engines (beads #409/#411/age). Remote secret-input contract kept as design doc in #505; value-entry UX deferred until a writable engine without a mobile path exists."}} diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 000000000..1fe677a78 --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,54 @@ +# Archie Core — Remote Secret Input + +The capability that lets an authenticated operator provide a secret value to a +secret engine from a remote surface. A chat channel (initially Telegram) +orchestrates the flow and transports only a one-time entry link; the raw value +is entered through a secure web form and never passes through chat, the model, +logs, or persisted state. + +## Language + +**Remote secret input**: +The end-to-end capability of delivering a secret value to a named engine +reference from a remote, mobile-first surface. It extends the secret-engine +architecture — it never bypasses an engine's own policy or resolution path. +_Avoid_: remote secret entry, secret provisioning, secret injection + +**Secret-input session**: +The tracked lifecycle of one remote secret input: initiation by an +authenticated actor, issue of an entry link, value entry, outcome, and +confirmation. Sessions are bound to the initiating actor and channel, expire, +can be cancelled, and are single-use. +_Avoid_: secret transaction, secret flow + +**SecretRef**: +The engine + key pair a value is bound to (the existing `internal/secret` +type). The entry link encodes a SecretRef so the form writes directly to the +exact required safe. _Avoid_: target, destination + +**Entry link**: +A one-time, expiring URL with an appended token that binds a SecretRef. +Opening it presents the value-entry form. It is the only thing the chat +channel transports. _Avoid_: magic link (implies authentication), secret link + +**Value-entry form**: +The secure web surface where the raw value is typed. It is the only surface +where the raw value exists besides the engine boundary; it never echoes the +value and holds no secret-derived content. + +**Writable engine**: +A secret engine that advertises a remote write/update capability for accepted +references. Engines without this capability fail clearly without weakening +resolve-only behaviour. +_Avoid_: settable engine, mutable engine + +**Redacted outcome**: +Success/failure feedback (including engine, key, and failure category) that +contains no raw value or secret-derived content. Redacted outcomes are the +only result a user receives. +_Avoid_: result, receipt + +**Confirmation**: +The initiating user's acknowledgment, in the initiating chat, that they have +completed value entry. It closes the session and surfaces the redacted +outcome. diff --git a/cmd/archied/provider_secrets.go b/cmd/archied/provider_secrets.go index e797dce5c..e061cfbc0 100644 --- a/cmd/archied/provider_secrets.go +++ b/cmd/archied/provider_secrets.go @@ -7,15 +7,24 @@ import ( "os" "strings" + "github.com/traefik/yaegi/stdlib/unrestricted" + "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/secret" + "github.com/samcharles93/archie-core/internal/secret/enginehost" "github.com/samcharles93/archie-core/internal/secret/secretextract" ) func configuredSecretRegistry(cfg *config.Config, log *slog.Logger) (*secret.Registry, error) { registry := secret.NewRegistry() if cfg.SecretEngineDir != "" { - loaded, err := registry.LoadDir(cfg.SecretEngineDir, secretextract.Symbols) + // Secret engines are operator-authored code in the same trust + // domain as the daemon config, and the shipped engines run CLIs + // (sops, vault, age). They shell out through enginehost.Run (the + // host-side helper) because yaegi's interpreted os/exec cannot + // pass an environment to child processes; unrestricted symbols + // are included for parity with skillscript interpretation. + loaded, err := registry.LoadDir(cfg.SecretEngineDir, secretextract.Symbols, enginehost.Symbols, unrestricted.Symbols) if err != nil { return nil, fmt.Errorf("load secret engines from %q: %w", cfg.SecretEngineDir, err) } diff --git a/config.example.toml b/config.example.toml index ca06d2964..49557dcb9 100644 --- a/config.example.toml +++ b/config.example.toml @@ -3,9 +3,13 @@ # # Secrets are NOT stored here: each one is a {engine, key} # reference resolved through a secrets engine at startup. -# The built-in "env" engine reads key as an environment variable name. -# Custom engines (sops, bws, vault/openbao, ...) -# are Yaegi plugins loaded from a directory -- see internal/secret. +# The built-in "env" engine reads key as an environment variable name; +# "bws" (Bitwarden Secrets Manager) is compiled in. Custom engines are +# Yaegi plugins loaded from this directory -- reference implementations +# for sops, vault/openbao and age ship in examples/secret-engines/ and +# each needs its CLI on PATH plus engine-specific env (sops: SOPS_FILE; +# vault: VAULT_ADDR, VAULT_TOKEN, optional VAULT_SECRET_PATH; +# age: AGE_FILE, AGE_IDENTITY). # secret_engine_dir = "~/.config/archie/secret-engines" # work_dir = "~/.local/share/archie/work" # default diff --git a/examples/secret-engines/age.go b/examples/secret-engines/age.go new file mode 100644 index 000000000..94f48fafd --- /dev/null +++ b/examples/secret-engines/age.go @@ -0,0 +1,74 @@ +//go:build ignore + +// age secret engine plugin for archied. +// +// Resolves a SecretRef key from an age-encrypted file of "key=value" +// lines. Requires the age CLI on PATH and the AGE_FILE (encrypted file +// path) plus AGE_IDENTITY (age private-key file) env vars. +// +// Install: copy this file into the configured secret_engine_dir (default +// ~/.config/archie/secret-engines) and restart archied. The daemon +// evaluates it with Yaegi and registers engine "age". The //go:build +// ignore tag is a comment to the interpreter, so this file loads normally; +// the Go toolchain skips it, so it may live inside the module tree. +// +// The CLI is run through enginehost.Run rather than os/exec because +// yaegi's interpreted os/exec cannot pass an environment to child +// processes; env config is read with os.Getenv, which the daemon seeds +// with the host environment. +// +// Create the encrypted file with: +// +// age -e -r secrets.txt -o secrets.age +// +// where secrets.txt holds lines like "DB_PASSWORD=..." — blank lines and +// "#" comments are skipped, the value may contain "=" (split at the first +// "="), and an empty value is treated as missing. +package main + +import ( + "errors" + "fmt" + "os" + "strings" + + "github.com/samcharles93/archie-core/internal/secret" + "github.com/samcharles93/archie-core/internal/secret/enginehost" +) + +var Engine = secret._Engine{ + WName: func() string { return "age" }, + WVersion: func() string { return "1.0.0" }, + WResolve: resolveAge, +} + +func resolveAge(key string) (string, error) { + file := os.Getenv("AGE_FILE") + identity := os.Getenv("AGE_IDENTITY") + if file == "" || identity == "" { + return "", errors.New("age engine: AGE_FILE and AGE_IDENTITY must be set") + } + out, err := enginehost.Run("age", []string{"-d", "-i", identity, file}) + if err != nil { + return "", fmt.Errorf("age engine: decrypt %s: %w", file, err) + } + for _, line := range strings.Split(out, "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + i := strings.Index(line, "=") + if i < 0 { + continue // malformed line, skip + } + if strings.TrimSpace(line[:i]) != key { + continue + } + value := strings.TrimSpace(line[i+1:]) + if value == "" { + return "", fmt.Errorf("age engine: key %q is empty in %s", key, file) + } + return value, nil + } + return "", fmt.Errorf("age engine: key %q not found in %s", key, file) +} diff --git a/examples/secret-engines/sops.go b/examples/secret-engines/sops.go new file mode 100644 index 000000000..90bcdfede --- /dev/null +++ b/examples/secret-engines/sops.go @@ -0,0 +1,58 @@ +//go:build ignore + +// sops secret engine plugin for archied. +// +// Resolves a SecretRef key to its plaintext value from a sops-encrypted +// file. Requires the sops CLI on PATH and the SOPS_FILE env var naming the +// encrypted file. Decryption keys are handled by sops itself via .sops.yaml +// or --age/--pgp configuration; no credentials are configured here. +// +// Install: copy this file into the configured secret_engine_dir (default +// ~/.config/archie/secret-engines) and restart archied. The daemon +// evaluates it with Yaegi and registers engine "sops". The //go:build +// ignore tag is a comment to the interpreter, so this file loads normally; +// the Go toolchain skips it, so it may live inside the module tree. +// +// The CLI is run through enginehost.Run rather than os/exec because +// yaegi's interpreted os/exec cannot pass an environment to child +// processes; env config is read with os.Getenv, which the daemon seeds +// with the host environment. +// +// Key names must be plain leaf names (e.g. "DB_PASSWORD"). Nested +// sops --extract JSON paths are not supported; quotes, backslashes and +// brackets in keys are rejected with a clear error. +package main + +import ( + "errors" + "fmt" + "os" + "strings" + + "github.com/samcharles93/archie-core/internal/secret" + "github.com/samcharles93/archie-core/internal/secret/enginehost" +) + +var Engine = secret._Engine{ + WName: func() string { return "sops" }, + WVersion: func() string { return "1.0.0" }, + WResolve: resolveSops, +} + +func resolveSops(key string) (string, error) { + file := os.Getenv("SOPS_FILE") + if file == "" { + return "", errors.New("sops engine: SOPS_FILE is not set") + } + if strings.ContainsAny(key, `"\[`) { + return "", fmt.Errorf("sops engine: key %q is not a valid --extract path", key) + } + value, err := enginehost.Run("sops", []string{"-d", "--extract", `["` + key + `"]`, file}) + if err != nil { + return "", fmt.Errorf("sops engine: decrypt %s: %w", file, err) + } + if value == "" { + return "", fmt.Errorf("sops engine: key %q not found in %s", key, file) + } + return value, nil +} diff --git a/examples/secret-engines/vault.go b/examples/secret-engines/vault.go new file mode 100644 index 000000000..ce1ba4995 --- /dev/null +++ b/examples/secret-engines/vault.go @@ -0,0 +1,73 @@ +//go:build ignore + +// vault secret engine plugin for archied. +// +// Resolves a SecretRef key to its plaintext value from HashiCorp Vault or +// OpenBao. Requires the vault CLI on PATH and the VAULT_ADDR + VAULT_TOKEN +// env vars, which the CLI reads natively (OpenBao's CLI accepts the same +// variables for compatibility). +// +// Install: copy this file into the configured secret_engine_dir (default +// ~/.config/archie/secret-engines) and restart archied. The daemon +// evaluates it with Yaegi and registers engine "vault". The //go:build +// ignore tag is a comment to the interpreter, so this file loads normally; +// the Go toolchain skips it, so it may live inside the module tree. +// +// The CLI is run through enginehost.Run rather than os/exec: VAULT_ADDR +// and VAULT_TOKEN must reach the child process, and yaegi's interpreted +// os/exec cannot pass an environment to children. enginehost.Run inherits +// the full host environment, so the vault CLI sees both vars. +// +// Key format: "path/field" resolves field within the KV path (e.g. +// "secret/archie/DB_PASSWORD"). A bare key resolves within the +// VAULT_SECRET_PATH prefix, which is required in that case. KV v1/v2 path +// translation is delegated to the CLI. +package main + +import ( + "errors" + "fmt" + "os" + "strings" + + "github.com/samcharles93/archie-core/internal/secret" + "github.com/samcharles93/archie-core/internal/secret/enginehost" +) + +var Engine = secret._Engine{ + WName: func() string { return "vault" }, + WVersion: func() string { return "1.0.0" }, + WResolve: resolveVault, +} + +func resolveVault(key string) (string, error) { + if os.Getenv("VAULT_ADDR") == "" || os.Getenv("VAULT_TOKEN") == "" { + return "", errors.New("vault engine: VAULT_ADDR and VAULT_TOKEN must be set") + } + path, field, err := vaultTarget(key) + if err != nil { + return "", err + } + value, err := enginehost.Run("vault", []string{"kv", "get", "-field=" + field, path}) + if err != nil { + return "", fmt.Errorf("vault engine: read %s/%s: %w", path, field, err) + } + if value == "" { + return "", fmt.Errorf("vault engine: key %q not found at %s", field, path) + } + return value, nil +} + +// vaultTarget splits a key into a KV path and field name. A key containing +// a slash names the full location ("secret/archie/DB_PASSWORD"); a bare key +// resolves within VAULT_SECRET_PATH. +func vaultTarget(key string) (path, field string, err error) { + if i := strings.LastIndex(key, "/"); i >= 0 { + return key[:i], key[i+1:], nil + } + prefix := os.Getenv("VAULT_SECRET_PATH") + if prefix == "" { + return "", "", errors.New("vault engine: key has no path and VAULT_SECRET_PATH is not set") + } + return prefix, key, nil +} diff --git a/internal/secret/engine.go b/internal/secret/engine.go index 4f75da81b..82dc04d86 100644 --- a/internal/secret/engine.go +++ b/internal/secret/engine.go @@ -118,7 +118,10 @@ func (r *Registry) Resolve(ref SecretRef) (string, error) { // extraSymbols are additional Yaegi symbol tables made available to // interpreted code. Callers should pass secretextract.Symbols so that // interpreted types can satisfy the secret.Engine interface across the -// Yaegi/Go boundary. +// Yaegi/Go boundary, and enginehost.Symbols so plugins can run CLIs with +// a real host environment (yaegi's interpreted os/exec cannot pass env +// to children). See cmd/archied/provider_secrets.go for the production +// wiring. func (r *Registry) LoadDir(dir string, extraSymbols ...map[string]map[string]reflect.Value) (int, error) { entries, err := os.ReadDir(dir) if os.IsNotExist(err) { @@ -146,7 +149,11 @@ func (r *Registry) LoadDir(dir string, extraSymbols ...map[string]map[string]ref } // Each file is package main -- must use a fresh interpreter to // avoid symbol collisions between files. - i, err := yaegiutil.New(interp.Options{}, extraSymbols...) + // The interpreter is seeded with the host environment: yaegi's + // interpreted os package keeps a private env otherwise, so + // plugins reading SOPS_FILE/VAULT_*/AGE_* via os.Getenv would + // silently see nothing. + i, err := yaegiutil.New(interp.Options{Env: os.Environ()}, extraSymbols...) if err != nil { slog.Default().Warn("skipping secret engine -- interpreter setup failed", "file", name, "err", err) continue diff --git a/internal/secret/enginehost/enginehost.go b/internal/secret/enginehost/enginehost.go new file mode 100644 index 000000000..08b70b47a --- /dev/null +++ b/internal/secret/enginehost/enginehost.go @@ -0,0 +1,54 @@ +// Package enginehost provides host-side helpers for interpreted secret +// engine plugins. +// +// Yaegi's interpreted os/exec is sandboxed: child processes cannot be +// given an environment, and env vars set or read in interpreted code do +// not reach the host or the child. Secret engines need real command +// execution with the daemon's environment (vault requires VAULT_ADDR and +// VAULT_TOKEN in the child env), so plugins shell out through Run instead +// of importing os/exec. This mirrors how the compiled-in bws engine runs +// the bws CLI, but host-side where env behaves. +package enginehost + +import ( + "context" + "fmt" + "io" + "os/exec" + "reflect" + "strings" + "time" +) + +// runTimeout bounds a CLI invocation, mirroring the compiled-in bws +// engine's bwsTimeout: a hung engine binary must not block secret +// resolution forever. +const runTimeout = 30 * time.Second + +// Run executes name with args in the host process, inheriting the full +// host environment, and returns the trimmed stdout. Stderr is discarded, +// matching the compiled-in bws engine. A non-zero exit is returned as an +// error. The engine Resolve contract carries no context, so the command +// runs with a bounded timeout rather than a caller-provided context. +func Run(name string, args []string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), runTimeout) + defer cancel() + cmd := exec.CommandContext(ctx, name, args...) + cmd.Stderr = io.Discard + out, err := cmd.Output() + if err != nil { + return "", fmt.Errorf("run %s: %w", name, err) + } + return strings.TrimSpace(string(out)), nil +} + +// Symbols is the hand-written Yaegi symbol table exposing Run to +// interpreted plugins. It is kept separate from the generated +// secretextract table because regenerating that table would not include +// this package. The key follows yaegi's convention of import path plus +// package name (see the generated secretextract file). +var Symbols = map[string]map[string]reflect.Value{ + "github.com/samcharles93/archie-core/internal/secret/enginehost/enginehost": { + "Run": reflect.ValueOf(Run), + }, +} diff --git a/internal/secret/engines_test.go b/internal/secret/engines_test.go new file mode 100644 index 000000000..f8c2e1c20 --- /dev/null +++ b/internal/secret/engines_test.go @@ -0,0 +1,339 @@ +package secret_test + +import ( + "os" + "path/filepath" + "reflect" + "testing" + + "github.com/traefik/yaegi/stdlib/unrestricted" + + "github.com/samcharles93/archie-core/internal/secret" + "github.com/samcharles93/archie-core/internal/secret/enginehost" +) + +// engineSymbols mirrors the daemon's secret-engine wiring in +// cmd/archied/provider_secrets.go: the generated secret symbols, the +// host-side enginehost helper (plugins run CLIs through it because +// yaegi's interpreted os/exec cannot pass env to children), and +// stdlib.Unrestricted for parity with the production wiring. +var engineSymbols = []map[string]map[string]reflect.Value{symbols, enginehost.Symbols, unrestricted.Symbols} + +// ── shipped engine plugin tests ───────────────────────────────────── +// +// These tests exercise the real plugin files shipped in +// examples/secret-engines/, not inline fixtures: the artifact an operator +// copies into secret_engine_dir is exactly what is tested here. Each +// engine shells out to a CLI, so a fake executable is placed on PATH and +// the engine's env vars are set, mirroring TestBWSEngineLoadsNamedSecretsOnce. + +// enginePluginDir returns the shipped plugin examples dir relative to this +// package (go test runs with cwd = the package dir). +func enginePluginDir(t *testing.T) string { + t.Helper() + dir, err := filepath.Abs(filepath.Join("..", "..", "examples", "secret-engines")) + if err != nil { + t.Fatal(err) + } + return dir +} + +// loadShippedEngines loads every engine plugin from the examples dir into a +// fresh registry and asserts the sops, vault and age engines registered. +func loadShippedEngines(t *testing.T) *secret.Registry { + t.Helper() + r := secret.NewRegistry() + n, err := r.LoadDir(enginePluginDir(t), engineSymbols...) + if err != nil { + t.Fatalf("LoadDir: %v", err) + } + if n < 3 { + t.Fatalf("LoadDir loaded %d engines, want at least 3 (sops, vault, age)", n) + } + for _, name := range []string{"sops", "vault", "age"} { + if _, ok := r.Get(name); !ok { + t.Fatalf("engine %q not registered after LoadDir", name) + } + } + return r +} + +// fakeCLI writes an executable script named name into a fresh temp dir and +// points PATH at it. +func fakeCLI(t *testing.T, name, script string) { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir) +} + +// TestEachEngineLoadsStandalone proves each shipped plugin file loads and +// registers when copied into an otherwise-empty plugin dir — the exact +// operator install path. +func TestEachEngineLoadsStandalone(t *testing.T) { + for _, name := range []string{"sops", "vault", "age"} { + t.Run(name, func(t *testing.T) { + src := filepath.Join(enginePluginDir(t), name+".go") + data, err := os.ReadFile(src) + if err != nil { + t.Fatalf("read %s: %v", src, err) + } + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, name+".go"), data, 0o644); err != nil { + t.Fatal(err) + } + r := secret.NewRegistry() + n, err := r.LoadDir(dir, engineSymbols...) + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatalf("LoadDir loaded %d engines, want 1", n) + } + if _, ok := r.Get(name); !ok { + t.Fatalf("engine %q not registered", name) + } + }) + } +} + +// ── sops ──────────────────────────────────────────────────────────── + +func TestSopsEngineResolvesViaCLI(t *testing.T) { + fakeCLI(t, "sops", `#!/bin/sh +printf '%s' 'super-secret-value' +`) + t.Setenv("SOPS_FILE", "/etc/archie/secrets.yaml") + r := loadShippedEngines(t) + e, _ := r.Get("sops") + + got, err := e.Resolve("DB_PASSWORD") + if err != nil { + t.Fatal(err) + } + if got != "super-secret-value" { + t.Fatalf("Resolve() = %q, want super-secret-value", got) + } +} + +func TestSopsEngineRequiresSOPSFile(t *testing.T) { + fakeCLI(t, "sops", `#!/bin/sh +printf '%s' 'x' +`) + r := loadShippedEngines(t) + e, _ := r.Get("sops") + + if _, err := e.Resolve("DB_PASSWORD"); err == nil { + t.Fatal("Resolve() succeeded without SOPS_FILE, want error") + } +} + +func TestSopsEngineRejectsInvalidKey(t *testing.T) { + fakeCLI(t, "sops", `#!/bin/sh +printf '%s' 'x' +`) + t.Setenv("SOPS_FILE", "/etc/archie/secrets.yaml") + r := loadShippedEngines(t) + e, _ := r.Get("sops") + + if _, err := e.Resolve(`bad"key`); err == nil { + t.Fatal("Resolve() accepted a key containing a quote, want error") + } +} + +func TestSopsEngineCLIFailure(t *testing.T) { + fakeCLI(t, "sops", `#!/bin/sh +echo 'sops: cannot open file' >&2 +exit 1 +`) + t.Setenv("SOPS_FILE", "/etc/archie/secrets.yaml") + r := loadShippedEngines(t) + e, _ := r.Get("sops") + + if _, err := e.Resolve("DB_PASSWORD"); err == nil { + t.Fatal("Resolve() succeeded with a failing CLI, want error") + } +} + +func TestSopsEngineMissingKeyErrorsOnEmptyOutput(t *testing.T) { + fakeCLI(t, "sops", `#!/bin/sh +printf '%s' '' +`) + t.Setenv("SOPS_FILE", "/etc/archie/secrets.yaml") + r := loadShippedEngines(t) + e, _ := r.Get("sops") + + if _, err := e.Resolve("NOPE"); err == nil { + t.Fatal("Resolve() succeeded with empty CLI output, want error") + } +} + +// ── vault ─────────────────────────────────────────────────────────── + +// vaultEchoCLI is a fake vault CLI that prints ":" so tests +// can assert exactly which KV path and field the engine targeted. +const vaultEchoCLI = `#!/bin/sh +field="" +path="" +for arg in "$@"; do + case "$arg" in + -field=*) field="${arg#-field=}" ;; + *) path="$arg" ;; + esac +done +printf '%s:%s' "$path" "$field" +` + +func TestVaultEngineResolvesFullPathKey(t *testing.T) { + fakeCLI(t, "vault", vaultEchoCLI) + t.Setenv("VAULT_ADDR", "https://vault.example:8200") + t.Setenv("VAULT_TOKEN", "test-token") + r := loadShippedEngines(t) + e, _ := r.Get("vault") + + got, err := e.Resolve("secret/archie/DB_PASSWORD") + if err != nil { + t.Fatal(err) + } + if got != "secret/archie:DB_PASSWORD" { + t.Fatalf("Resolve() targeted %q, want secret/archie:DB_PASSWORD", got) + } +} + +func TestVaultEngineBareKeyUsesSecretPath(t *testing.T) { + fakeCLI(t, "vault", vaultEchoCLI) + t.Setenv("VAULT_ADDR", "https://vault.example:8200") + t.Setenv("VAULT_TOKEN", "test-token") + t.Setenv("VAULT_SECRET_PATH", "secret/archie") + r := loadShippedEngines(t) + e, _ := r.Get("vault") + + got, err := e.Resolve("DB_PASSWORD") + if err != nil { + t.Fatal(err) + } + if got != "secret/archie:DB_PASSWORD" { + t.Fatalf("Resolve() targeted %q, want secret/archie:DB_PASSWORD", got) + } +} + +func TestVaultEngineBareKeyWithoutPathFails(t *testing.T) { + fakeCLI(t, "vault", `#!/bin/sh +printf '%s' 'x' +`) + t.Setenv("VAULT_ADDR", "https://vault.example:8200") + t.Setenv("VAULT_TOKEN", "test-token") + r := loadShippedEngines(t) + e, _ := r.Get("vault") + + if _, err := e.Resolve("DB_PASSWORD"); err == nil { + t.Fatal("bare key without VAULT_SECRET_PATH should fail") + } +} + +func TestVaultEngineRequiresAddrAndToken(t *testing.T) { + fakeCLI(t, "vault", `#!/bin/sh +printf '%s' 'x' +`) + r := loadShippedEngines(t) + e, _ := r.Get("vault") + + if _, err := e.Resolve("secret/archie/DB_PASSWORD"); err == nil { + t.Fatal("Resolve() succeeded without VAULT_ADDR/VAULT_TOKEN, want error") + } +} + +// ── age ───────────────────────────────────────────────────────────── + +const agePlaintext = `# archie secrets + +DB_PASSWORD=age-secret-value +API_KEY=other=with=equals +EMPTY= +# trailing comment +` + +func TestAgeEngineResolvesViaCLI(t *testing.T) { + fakeCLI(t, "age", "#!/bin/sh\nprintf '%s' '"+agePlaintext+"'\n") + t.Setenv("AGE_FILE", "/etc/archie/secrets.age") + t.Setenv("AGE_IDENTITY", "/etc/archie/age.key") + r := loadShippedEngines(t) + e, _ := r.Get("age") + + got, err := e.Resolve("DB_PASSWORD") + if err != nil { + t.Fatal(err) + } + if got != "age-secret-value" { + t.Fatalf("Resolve() = %q, want age-secret-value", got) + } +} + +func TestAgeEngineSkipsCommentsBlanksAndSplitsAtFirstEquals(t *testing.T) { + fakeCLI(t, "age", "#!/bin/sh\nprintf '%s' '"+agePlaintext+"'\n") + t.Setenv("AGE_FILE", "/etc/archie/secrets.age") + t.Setenv("AGE_IDENTITY", "/etc/archie/age.key") + r := loadShippedEngines(t) + e, _ := r.Get("age") + + got, err := e.Resolve("API_KEY") + if err != nil { + t.Fatal(err) + } + if got != "other=with=equals" { + t.Fatalf("Resolve() = %q, want other=with=equals (split at first =)", got) + } +} + +func TestAgeEngineMissingKey(t *testing.T) { + fakeCLI(t, "age", "#!/bin/sh\nprintf '%s' '"+agePlaintext+"'\n") + t.Setenv("AGE_FILE", "/etc/archie/secrets.age") + t.Setenv("AGE_IDENTITY", "/etc/archie/age.key") + r := loadShippedEngines(t) + e, _ := r.Get("age") + + if _, err := e.Resolve("NOPE"); err == nil { + t.Fatal("Resolve() succeeded for a missing key, want error") + } +} + +func TestAgeEngineEmptyValueIsError(t *testing.T) { + fakeCLI(t, "age", "#!/bin/sh\nprintf '%s' '"+agePlaintext+"'\n") + t.Setenv("AGE_FILE", "/etc/archie/secrets.age") + t.Setenv("AGE_IDENTITY", "/etc/archie/age.key") + r := loadShippedEngines(t) + e, _ := r.Get("age") + + if _, err := e.Resolve("EMPTY"); err == nil { + t.Fatal("Resolve() accepted an empty value, want error") + } +} + +func TestAgeEngineRequiresEnv(t *testing.T) { + fakeCLI(t, "age", `#!/bin/sh +printf '%s' 'x' +`) + r := loadShippedEngines(t) + e, _ := r.Get("age") + + if _, err := e.Resolve("DB_PASSWORD"); err == nil { + t.Fatal("Resolve() succeeded without AGE_FILE/AGE_IDENTITY, want error") + } +} + +func TestAgeEngineCLIFailure(t *testing.T) { + fakeCLI(t, "age", `#!/bin/sh +echo 'age: cannot decrypt' >&2 +exit 1 +`) + t.Setenv("AGE_FILE", "/etc/archie/secrets.age") + t.Setenv("AGE_IDENTITY", "/etc/archie/age.key") + r := loadShippedEngines(t) + e, _ := r.Get("age") + + if _, err := e.Resolve("DB_PASSWORD"); err == nil { + t.Fatal("Resolve() succeeded with a failing CLI, want error") + } +}