secretref: secret://, env:, file:, base64: references (from yavebu) for yacry and yadenes
Adds IsReference for programs that keep accepting literals, and YasevaConfig (passed as --config). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
13c1862c74
commit
43775950a4
3 files changed
+408
No files matched your search
@@ -16,6 +16,7 @@ yetano.dev/yetano/core/config
|
|||||||
yetano.dev/yetano/core/manual
|
yetano.dev/yetano/core/manual
|
||||||
yetano.dev/yetano/core/completion
|
yetano.dev/yetano/core/completion
|
||||||
yetano.dev/yetano/core/doctor
|
yetano.dev/yetano/core/doctor
|
||||||
|
yetano.dev/yetano/core/secretref
|
||||||
```
|
```
|
||||||
|
|
||||||
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
|
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
|
||||||
@@ -302,3 +303,26 @@ docs/program-conventions.md in the meta-repository):
|
|||||||
Tagged as plain semver on this repository (`v0.1.0`, ...), per the
|
Tagged as plain semver on this repository (`v0.1.0`, ...), per the
|
||||||
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
|
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
|
||||||
force-moved to a different commit.
|
force-moved to a different commit.
|
||||||
|
|
||||||
|
## core/secretref
|
||||||
|
|
||||||
|
Resolves secret references in a program's configuration, so a token or
|
||||||
|
password never has to be written into a config file in plain text:
|
||||||
|
|
||||||
|
| Form | Value from |
|
||||||
|
|---|---|
|
||||||
|
| `secret://<name>` | yaseva (`yaseva [--config <file>] get <name>`, run as a subprocess) |
|
||||||
|
| `env:<VARIABLE>` | the process environment |
|
||||||
|
| `file:<path>` | a file (`~` expanded, trailing newline trimmed) |
|
||||||
|
| `base64:<value>` | the value itself, base64 (standard or URL alphabet) -- out of plain sight, not protected |
|
||||||
|
|
||||||
|
```go
|
||||||
|
r := secretref.New("") // "yaseva" from PATH
|
||||||
|
token, err := r.ResolveString(ctx, cfg.Token)
|
||||||
|
log.Print(r.Redact(err.Error())) // resolved values become "***"
|
||||||
|
```
|
||||||
|
|
||||||
|
`Validate` accepts only these forms. A program that must keep reading
|
||||||
|
plain values it accepted before checks `IsReference` and treats anything
|
||||||
|
else as a literal. Used by yavebu (its own copy predates this package),
|
||||||
|
yacry and yadenes.
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
// Package secretref resolves secret references in Yetano program
|
||||||
|
// configurations, so a token, password or key never has to be written
|
||||||
|
// into a config file in plain text:
|
||||||
|
//
|
||||||
|
// secret://<name> resolved through yaseva (`yaseva get <name>`)
|
||||||
|
// env:<VARIABLE> read from the process environment
|
||||||
|
// file:<path> read from a local file (~ expanded, trailing newline trimmed)
|
||||||
|
// base64:<value> the value itself, base64-encoded (standard or URL alphabet,
|
||||||
|
// padding optional): kept out of plain sight, but not protected
|
||||||
|
//
|
||||||
|
// yaseva is called as a subprocess on purpose: a program never opens
|
||||||
|
// the vault itself, does not need yaseva's Go toolchain requirements,
|
||||||
|
// and works with however the operator has configured/unlocked yaseva.
|
||||||
|
//
|
||||||
|
// Validate accepts only these forms. A program that must keep reading
|
||||||
|
// plain values it accepted before (e.g. yacry's provider_config) checks
|
||||||
|
// IsReference first and treats everything else as a literal.
|
||||||
|
//
|
||||||
|
// Every resolved value is registered with the Resolver's redactor so it
|
||||||
|
// can be scrubbed from errors, logs and reports.
|
||||||
|
package secretref
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ErrInvalid is returned for a reference that is not one of the
|
||||||
|
// supported forms (including any plaintext value).
|
||||||
|
var ErrInvalid = errors.New("invalid secret reference")
|
||||||
|
|
||||||
|
// prefixes are the reference forms, in the order IsReference checks them.
|
||||||
|
var prefixes = []string{"secret://", "env:", "file:", "base64:"}
|
||||||
|
|
||||||
|
// IsReference reports whether s uses one of the reference forms
|
||||||
|
// (secret://, env:, file:, base64:), valid or not. Anything else is a
|
||||||
|
// literal value.
|
||||||
|
func IsReference(s string) bool {
|
||||||
|
for _, p := range prefixes {
|
||||||
|
if strings.HasPrefix(s, p) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate checks that ref is a supported reference form. The empty
|
||||||
|
// string is valid and means "not set".
|
||||||
|
func Validate(ref string) error {
|
||||||
|
switch {
|
||||||
|
case ref == "":
|
||||||
|
return nil
|
||||||
|
case strings.HasPrefix(ref, "secret://"):
|
||||||
|
name := strings.TrimPrefix(ref, "secret://")
|
||||||
|
if name == "" || strings.ContainsAny(name, " \t\r\n") || strings.HasPrefix(name, "-") {
|
||||||
|
return fmt.Errorf("%w: %q: empty or malformed secret name", ErrInvalid, ref)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case strings.HasPrefix(ref, "env:"):
|
||||||
|
if strings.TrimPrefix(ref, "env:") == "" {
|
||||||
|
return fmt.Errorf("%w: %q: empty variable name", ErrInvalid, ref)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case strings.HasPrefix(ref, "file:"):
|
||||||
|
if strings.TrimPrefix(ref, "file:") == "" {
|
||||||
|
return fmt.Errorf("%w: %q: empty path", ErrInvalid, ref)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
case strings.HasPrefix(ref, "base64:"):
|
||||||
|
// The value is not repeated in the error: it is the secret.
|
||||||
|
if v, err := decodeBase64(strings.TrimPrefix(ref, "base64:")); err != nil || len(v) == 0 {
|
||||||
|
return fmt.Errorf("%w: base64: value is empty or not valid base64", ErrInvalid)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("%w: plaintext secrets are not allowed; use secret://<name>, env:<VAR>, file:<path> or base64:<value>", ErrInvalid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolver resolves references. The zero value is not usable; use New.
|
||||||
|
type Resolver struct {
|
||||||
|
// YasevaBinary is the yaseva executable for secret:// references.
|
||||||
|
YasevaBinary string
|
||||||
|
// YasevaConfig, if set, is passed to yaseva as --config (default:
|
||||||
|
// yaseva's own config search, including $YASEVA_CONFIG).
|
||||||
|
YasevaConfig string
|
||||||
|
// Timeout bounds one yaseva call.
|
||||||
|
Timeout time.Duration
|
||||||
|
|
||||||
|
// Hooks for tests.
|
||||||
|
LookupEnv func(string) (string, bool)
|
||||||
|
ReadFile func(string) ([]byte, error)
|
||||||
|
Run func(ctx context.Context, bin string, args ...string) (stdout []byte, err error)
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
cache map[string][]byte
|
||||||
|
secrets [][]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// New returns a Resolver using yasevaBinary ("yaseva" if empty).
|
||||||
|
func New(yasevaBinary string) *Resolver {
|
||||||
|
if yasevaBinary == "" {
|
||||||
|
yasevaBinary = "yaseva"
|
||||||
|
}
|
||||||
|
return &Resolver{
|
||||||
|
YasevaBinary: yasevaBinary,
|
||||||
|
Timeout: 30 * time.Second,
|
||||||
|
LookupEnv: os.LookupEnv,
|
||||||
|
ReadFile: os.ReadFile,
|
||||||
|
Run: runCommand,
|
||||||
|
cache: map[string][]byte{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func runCommand(ctx context.Context, bin string, args ...string) ([]byte, error) {
|
||||||
|
cmd := exec.CommandContext(ctx, bin, args...)
|
||||||
|
var stdout, stderr bytes.Buffer
|
||||||
|
cmd.Stdout, cmd.Stderr = &stdout, &stderr
|
||||||
|
if err := cmd.Run(); err != nil {
|
||||||
|
msg := strings.TrimSpace(stderr.String())
|
||||||
|
if len(msg) > 200 {
|
||||||
|
msg = msg[:200]
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("%s: %w: %s", bin, err, msg)
|
||||||
|
}
|
||||||
|
return stdout.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveString is Resolve for callers that want a string.
|
||||||
|
func (r *Resolver) ResolveString(ctx context.Context, ref string) (string, error) {
|
||||||
|
v, err := r.Resolve(ctx, ref)
|
||||||
|
return string(v), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve returns the secret value for ref. Results are cached for the
|
||||||
|
// lifetime of the Resolver so yaseva is asked at most once per name.
|
||||||
|
func (r *Resolver) Resolve(ctx context.Context, ref string) ([]byte, error) {
|
||||||
|
if err := Validate(ref); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if ref == "" {
|
||||||
|
return nil, fmt.Errorf("%w: empty reference", ErrInvalid)
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
if v, ok := r.cache[ref]; ok {
|
||||||
|
r.mu.Unlock()
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
r.mu.Unlock()
|
||||||
|
|
||||||
|
var v []byte
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(ref, "secret://"):
|
||||||
|
cctx, cancel := context.WithTimeout(ctx, r.Timeout)
|
||||||
|
defer cancel()
|
||||||
|
args := []string{"get", strings.TrimPrefix(ref, "secret://")}
|
||||||
|
if r.YasevaConfig != "" {
|
||||||
|
args = append([]string{"--config", r.YasevaConfig}, args...)
|
||||||
|
}
|
||||||
|
out, err := r.Run(cctx, r.YasevaBinary, args...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("resolve %s: %w", ref, err)
|
||||||
|
}
|
||||||
|
v = trimNewline(out)
|
||||||
|
case strings.HasPrefix(ref, "env:"):
|
||||||
|
name := strings.TrimPrefix(ref, "env:")
|
||||||
|
s, ok := r.LookupEnv(name)
|
||||||
|
if !ok {
|
||||||
|
return nil, fmt.Errorf("resolve %s: environment variable not set", ref)
|
||||||
|
}
|
||||||
|
v = []byte(s)
|
||||||
|
case strings.HasPrefix(ref, "file:"):
|
||||||
|
p, err := ExpandHome(strings.TrimPrefix(ref, "file:"))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
b, err := r.ReadFile(p)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("resolve %s: %w", ref, err)
|
||||||
|
}
|
||||||
|
v = trimNewline(b)
|
||||||
|
case strings.HasPrefix(ref, "base64:"):
|
||||||
|
v, _ = decodeBase64(strings.TrimPrefix(ref, "base64:")) // checked by Validate
|
||||||
|
}
|
||||||
|
if len(v) == 0 {
|
||||||
|
return nil, fmt.Errorf("resolve %s: empty secret", ref)
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
r.cache[ref] = v
|
||||||
|
if len(v) >= 4 {
|
||||||
|
r.secrets = append(r.secrets, v)
|
||||||
|
}
|
||||||
|
r.mu.Unlock()
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddSecret registers a value obtained elsewhere (e.g. a Verse
|
||||||
|
// invitation token) so Redact removes it from errors and reports.
|
||||||
|
func (r *Resolver) AddSecret(v string) {
|
||||||
|
if r == nil || len(v) < 4 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
r.secrets = append(r.secrets, []byte(v))
|
||||||
|
r.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redact replaces every secret value resolved so far with "***".
|
||||||
|
// Secrets shorter than 4 bytes are not registered (they would redact
|
||||||
|
// ordinary text); such secrets are weak anyway.
|
||||||
|
func (r *Resolver) Redact(s string) string {
|
||||||
|
if r == nil {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
defer r.mu.Unlock()
|
||||||
|
for _, v := range r.secrets {
|
||||||
|
s = strings.ReplaceAll(s, string(v), "***")
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// decodeBase64 accepts the standard and the URL alphabet, with or
|
||||||
|
// without padding.
|
||||||
|
func decodeBase64(s string) ([]byte, error) {
|
||||||
|
s = strings.TrimRight(strings.TrimSpace(s), "=")
|
||||||
|
if strings.ContainsAny(s, "-_") {
|
||||||
|
return base64.RawURLEncoding.DecodeString(s)
|
||||||
|
}
|
||||||
|
return base64.RawStdEncoding.DecodeString(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
func trimNewline(b []byte) []byte {
|
||||||
|
b = bytes.TrimRight(b, "\r\n")
|
||||||
|
return bytes.Clone(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExpandHome expands a leading "~" or "~/" to the user's home directory.
|
||||||
|
func ExpandHome(p string) (string, error) {
|
||||||
|
if p == "~" || strings.HasPrefix(p, "~/") || strings.HasPrefix(p, `~\`) {
|
||||||
|
home, err := os.UserHomeDir()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(home, p[1:]), nil
|
||||||
|
}
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package secretref
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestValidate(t *testing.T) {
|
||||||
|
for _, ok := range []string{"", "secret://app/admin", "env:ADMIN_PW", "file:~/pw.txt", "base64:aHVudGVyMg==", "base64:aHVudGVyMg"} {
|
||||||
|
if err := Validate(ok); err != nil {
|
||||||
|
t.Errorf("%q: %v", ok, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bad := range []string{"hunter2", "secret://", "secret://a b", "secret://-flag", "env:", "file:", "SECRET://x", "base64:", "base64:!!", "base64:="} {
|
||||||
|
if err := Validate(bad); !errors.Is(err, ErrInvalid) {
|
||||||
|
t.Errorf("%q accepted", bad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolve(t *testing.T) {
|
||||||
|
calls := 0
|
||||||
|
r := New("yaseva-test")
|
||||||
|
r.Run = func(_ context.Context, bin string, args ...string) ([]byte, error) {
|
||||||
|
calls++
|
||||||
|
if bin != "yaseva-test" || len(args) != 2 || args[0] != "get" || args[1] != "app/admin" {
|
||||||
|
t.Fatalf("unexpected call %s %v", bin, args)
|
||||||
|
}
|
||||||
|
return []byte("s3cr3t-pass\n"), nil
|
||||||
|
}
|
||||||
|
r.LookupEnv = func(k string) (string, bool) { return "from-env", k == "PW" }
|
||||||
|
dir := t.TempDir()
|
||||||
|
f := filepath.Join(dir, "pw")
|
||||||
|
if err := os.WriteFile(f, []byte("from-file\r\n"), 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.Background()
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
v, err := r.Resolve(ctx, "secret://app/admin")
|
||||||
|
if err != nil || string(v) != "s3cr3t-pass" {
|
||||||
|
t.Fatalf("secret: %q %v", v, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if calls != 1 {
|
||||||
|
t.Fatalf("yaseva called %d times, want 1 (cached)", calls)
|
||||||
|
}
|
||||||
|
if v, err := r.Resolve(ctx, "env:PW"); err != nil || string(v) != "from-env" {
|
||||||
|
t.Fatalf("env: %q %v", v, err)
|
||||||
|
}
|
||||||
|
if _, err := r.Resolve(ctx, "env:MISSING"); err == nil {
|
||||||
|
t.Fatal("missing env accepted")
|
||||||
|
}
|
||||||
|
if v, err := r.Resolve(ctx, "file:"+f); err != nil || string(v) != "from-file" {
|
||||||
|
t.Fatalf("file: %q %v", v, err)
|
||||||
|
}
|
||||||
|
if _, err := r.Resolve(ctx, "plaintext"); err == nil {
|
||||||
|
t.Fatal("plaintext resolved")
|
||||||
|
}
|
||||||
|
|
||||||
|
msg := r.Redact("login failed with s3cr3t-pass and from-file")
|
||||||
|
if strings.Contains(msg, "s3cr3t-pass") || strings.Contains(msg, "from-file") {
|
||||||
|
t.Fatalf("not redacted: %s", msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveEmptySecret(t *testing.T) {
|
||||||
|
r := New("")
|
||||||
|
r.Run = func(context.Context, string, ...string) ([]byte, error) { return []byte("\n"), nil }
|
||||||
|
if _, err := r.Resolve(context.Background(), "secret://x"); err == nil {
|
||||||
|
t.Fatal("empty secret accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveBase64(t *testing.T) {
|
||||||
|
r := New("")
|
||||||
|
for ref, want := range map[string]string{
|
||||||
|
"base64:aHVudGVyMg==": "hunter2",
|
||||||
|
"base64:aHVudGVyMg": "hunter2",
|
||||||
|
"base64:Pz8_Pw": "????", // URL alphabet
|
||||||
|
"base64:Pz8/Pw==": "????",
|
||||||
|
} {
|
||||||
|
v, err := r.Resolve(context.Background(), ref)
|
||||||
|
if err != nil || string(v) != want {
|
||||||
|
t.Errorf("%s: %q %v, want %q", ref, v, err, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if msg := r.Redact("pw hunter2"); strings.Contains(msg, "hunter2") {
|
||||||
|
t.Fatalf("not redacted: %s", msg)
|
||||||
|
}
|
||||||
|
if err := Validate("base64:!!"); err != nil && strings.Contains(err.Error(), "!!") {
|
||||||
|
t.Fatalf("error repeats the value: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsReference(t *testing.T) {
|
||||||
|
for s, want := range map[string]bool{
|
||||||
|
"secret://x": true, "env:X": true, "file:/x": true, "base64:eA==": true,
|
||||||
|
"plain-token": false, "": false, "SECRET://x": false, "envX": false,
|
||||||
|
} {
|
||||||
|
if got := IsReference(s); got != want {
|
||||||
|
t.Errorf("IsReference(%q) = %v, want %v", s, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestYasevaConfigIsPassed(t *testing.T) {
|
||||||
|
r := New("yaseva")
|
||||||
|
r.YasevaConfig = "/etc/yaseva.yaml"
|
||||||
|
var got []string
|
||||||
|
r.Run = func(_ context.Context, bin string, args ...string) ([]byte, error) {
|
||||||
|
got = append([]string{bin}, args...)
|
||||||
|
return []byte("tok\n"), nil
|
||||||
|
}
|
||||||
|
v, err := r.ResolveString(context.Background(), "secret://dns/httpnet")
|
||||||
|
if err != nil || v != "tok" {
|
||||||
|
t.Fatalf("ResolveString = %q, %v", v, err)
|
||||||
|
}
|
||||||
|
want := []string{"yaseva", "--config", "/etc/yaseva.yaml", "get", "dns/httpnet"}
|
||||||
|
if strings.Join(got, " ") != strings.Join(want, " ") {
|
||||||
|
t.Errorf("ran %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user