4 Commits
Author SHA1 Message Date
terminarandClaude Opus 5.5 43775950a4 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>
2026-10-12 12:17:04 +02:00
terminarandClaude Opus 5.5 13c1862c74 completion, doctor: the shared standard commands
core/completion prints bash, zsh, fish or PowerShell completion scripts
from a static command tree ("<program> completion <shell>"); core/doctor
is one report shape (resolved paths incl. the standard core/paths ones,
named checks), printed as a table or --json, exit 0/1/2. Together with
core/manual they implement the Yetano program standard
(docs/program-conventions.md in the meta-repo).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:30:45 +02:00
terminarandClaude Opus 5.5 e757fdd025 manual: the shared "<program> manual" command (ADR-0012)
FromFS turns embedded README.md + docs/**/*.md into topics (README is
"readme", titles from the first heading); Run serves "manual",
"manual <topic>" and "manual --json [topic]" -- the JSON shape yet
reads for an installed program's manual (yet manual --package, TUI,
yet-gui), same as "yet manual --json".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 16:22:03 +02:00
terminarandClaude Opus 5.5 e8bf23a064 paths: skip the user search tier when there is no home directory
ConfigSearchDirs/DataSearchDirs/ExecutableSearchDirs (and therefore
core/config's Resolve/ResolveAll/LoadMerged) failed outright with
ErrNoHomeDirectory when HOME/USERPROFILE was unset, so a service
started without HOME could no longer find its working-directory or
/etc/<app> config -- a regression against the hand-rolled lookups
being migrated onto core, which just skipped the user location.
Missing-home now only drops the user tier from the search lists; the
canonical <Category>Dir() methods still report ErrNoHomeDirectory.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-22 22:24:51 +02:00
15 changed files with 1359 additions and 15 deletions

No files matched your search

+70
View File
@@ -13,6 +13,10 @@ configuration resolution**: `core/paths` and `core/config`.
yetano.dev/yetano/core
yetano.dev/yetano/core/paths
yetano.dev/yetano/core/config
yetano.dev/yetano/core/manual
yetano.dev/yetano/core/completion
yetano.dev/yetano/core/doctor
yetano.dev/yetano/core/secretref
```
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
@@ -59,6 +63,13 @@ write location) and, for Config/Data/executables,
search, highest priority first). These are not always the same
location -- see "Windows" below.
Without a home directory (`HOME`/`USERPROFILE` unset, and no override
for the user tier), the search lists simply omit the user tier and still
report the system tier -- a system service started without `HOME` keeps
finding `/etc/<app>`. The canonical `<Category>Dir()` methods still
return `paths.ErrNoHomeDirectory` in that case; a write location is never
silently swapped for a different tier.
### Environment variable priority
Every canonical category is resolved through the same chain, highest
@@ -237,6 +248,42 @@ ecosystem-wide, shared settings (`repositories.yaml`, `trust.yaml`,
layered into, any one application's own configuration. An application
opts in explicitly with `config.WithYetanoDefaults(true)`.
## core/manual: the "<program> manual" command
Every Yetano program serves its own documentation (ADR-0012), embedded
in the binary. `core/manual` is that command in one shared shape:
```go
// at the module root (go:embed can't reach parent directories):
//go:embed README.md docs
var docsFS embed.FS
var Manual = manual.MustFromFS("yasl", docsFS)
// in the CLI dispatch:
case "manual", "doc":
if err := yasl.Manual.Run(args[1:], os.Stdout); err != nil { ... exit non-zero ... }
```
`FromFS` makes `README.md` the topic `readme` and every `docs/**/*.md`
a topic (slug = path below `docs/` without `.md`, title = first `#`
heading). `Run` serves `manual`, `manual <topic>` and `manual --json
[topic]`; the JSON form (`[{slug,title,path}]` / `{slug,title,path,
markdown}`) is what yet reads to show an installed program's manual
(`yet manual --package`, its TUI and yet-gui).
## core/completion and core/doctor
The other two standard commands of every Yetano program (see
docs/program-conventions.md in the meta-repository):
- `completion.Run(program, tree, args, w)` prints a bash, zsh, fish or
PowerShell completion script generated from a static `completion.Tree`
of the program's commands.
- `doctor.Report` collects the locations the program resolves
(`AddPaths(app)` adds the standard `core/paths` ones) and named checks;
`Run(args, stdout, stderr)` prints a table or `--json` and returns the
exit code (0 all good, 1 a check failed, 2 usage).
## Security
- Environment expansion is variable substitution only -- never shell
@@ -256,3 +303,26 @@ opts in explicitly with `config.WithYetanoDefaults(true)`.
Tagged as plain semver on this repository (`v0.1.0`, ...), per the
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
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.
+165
View File
@@ -0,0 +1,165 @@
// Package completion is the shared "<program> completion <shell>" command
// of the Yetano program standard (see docs/program-conventions.md in the
// yetano meta-repository): it prints a shell completion script for bash,
// zsh, fish or PowerShell, generated from a static command tree.
//
// The scripts are deliberately simple, word-based completion of command
// and subcommand names (not flag-aware): they join the words typed so far
// into a prefix and look up what may follow it.
//
// var tree = completion.Tree{
// "serve": nil,
// "config": completion.Leaf("create", "validate", "path"),
// "manual": nil,
// "doctor": nil,
// "completion": completion.Leaf(completion.Shells...),
// "version": nil,
// }
// case "completion":
// err := completion.Run("yasl", tree, args[1:], os.Stdout)
package completion
import (
"errors"
"fmt"
"io"
"regexp"
"sort"
"strings"
)
// Tree is one level of a program's commands: a name maps to its
// subcommands, or to nil for a command without any.
type Tree map[string]Tree
// Leaf is a level of commands that have no subcommands themselves.
func Leaf(names ...string) Tree {
t := make(Tree, len(names))
for _, n := range names {
t[n] = nil
}
return t
}
// Shells are the supported shells, in the order help texts list them.
var Shells = []string{"bash", "zsh", "fish", "powershell"}
// ErrUsage is returned by Run for a missing or unknown shell.
var ErrUsage = errors.New("usage: completion <bash|zsh|fish|powershell>")
var safeWord = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:+-]*$`)
// entry is a prefix (words typed so far, space-joined) and what may follow.
type entry struct {
prefix string
words []string
}
func flatten(tree Tree) ([]entry, error) {
var out []entry
var walk func(prefix string, t Tree) error
walk = func(prefix string, t Tree) error {
names := make([]string, 0, len(t))
for n := range t {
if !safeWord.MatchString(n) {
return fmt.Errorf("completion: command name %q is not a plain word", n)
}
names = append(names, n)
}
sort.Strings(names)
out = append(out, entry{prefix, names})
for _, n := range names {
if sub := t[n]; len(sub) > 0 {
p := n
if prefix != "" {
p = prefix + " " + n
}
if err := walk(p, sub); err != nil {
return err
}
}
}
return nil
}
return out, walk("", tree)
}
// Script returns the completion script for shell.
func Script(program, shell string, tree Tree) (string, error) {
if !safeWord.MatchString(program) {
return "", fmt.Errorf("completion: program name %q is not a plain word", program)
}
entries, err := flatten(tree)
if err != nil {
return "", err
}
fn := "_" + strings.NewReplacer("-", "_", ".", "_", ":", "_", "+", "_").Replace(program) + "_complete"
var b strings.Builder
switch shell {
case "bash":
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# source <(%s completion bash)\n", program, program)
fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn)
for _, e := range entries {
fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\")); return ;;\n", e.prefix, strings.Join(e.words, " "))
}
fmt.Fprintf(&b, " *) COMPREPLY=() ;;\n esac\n}\ncomplete -F %s %s\n", fn, program)
case "zsh":
fmt.Fprintf(&b, "#compdef %s\n# %s zsh completion. Install with:\n# source <(%s completion zsh)\n", program, program, program)
fmt.Fprintf(&b, "%s() {\n local prefix=\"${words[2,CURRENT-1]}\"\n local -a completions\n case \"$prefix\" in\n", fn)
for _, e := range entries {
fmt.Fprintf(&b, " %q) completions=(%s) ;;\n", e.prefix, strings.Join(e.words, " "))
}
fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n}\n")
fmt.Fprintf(&b, "if (( $+functions[compdef] )); then\n compdef %s %s\nelse\n echo '%s: zsh completion needs \"autoload -U compinit && compinit\" run first (e.g. in ~/.zshrc)' >&2\nfi\n", fn, program, program)
case "fish":
fmt.Fprintf(&b, "# %s fish completion. Install with:\n# %s completion fish | source\n", program, program)
fmt.Fprintf(&b, "function %s\n set -l tokens (commandline -opc)\n set -l prefix (string join ' ' -- $tokens[2..-1])\n switch \"$prefix\"\n", fn)
for _, e := range entries {
if e.prefix == "" {
b.WriteString(" case ''\n")
} else {
fmt.Fprintf(&b, " case %q\n", e.prefix)
}
quoted := make([]string, len(e.words))
for i, w := range e.words {
quoted[i] = fmt.Sprintf("%q", w)
}
fmt.Fprintf(&b, " printf '%%s\\n' %s\n", strings.Join(quoted, " "))
}
fmt.Fprintf(&b, " end\nend\ncomplete -c %s -f -a '(%s)'\n", program, fn)
case "powershell":
fmt.Fprintf(&b, "# %s PowerShell completion. Install with:\n# %s completion powershell | Out-String | Invoke-Expression\n", program, program)
fmt.Fprintf(&b, "Register-ArgumentCompleter -Native -CommandName '%s', '%s.exe' -ScriptBlock {\n", program, program)
b.WriteString(" param($wordToComplete, $commandAst, $cursorPosition)\n")
b.WriteString(" $words = @($commandAst.CommandElements | Select-Object -Skip 1 | ForEach-Object { $_.ToString() })\n")
b.WriteString(" if ($wordToComplete -ne '' -and $words.Count -gt 0) { $words = @($words | Select-Object -First ($words.Count - 1)) }\n")
b.WriteString(" $prefix = $words -join ' '\n $candidates = switch ($prefix) {\n")
for _, e := range entries {
quoted := make([]string, len(e.words))
for i, w := range e.words {
quoted[i] = "'" + w + "'"
}
fmt.Fprintf(&b, " '%s' { @(%s) }\n", e.prefix, strings.Join(quoted, ", "))
}
b.WriteString(" default { @() }\n }\n")
b.WriteString(" $candidates | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n")
b.WriteString(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n}\n")
default:
return "", fmt.Errorf("%w (unknown shell %q)", ErrUsage, shell)
}
return b.String(), nil
}
// Run serves "<program> completion <shell>" -- args are the arguments
// after "completion" -- writing the script to w.
func Run(program string, tree Tree, args []string, w io.Writer) error {
if len(args) != 1 {
return ErrUsage
}
script, err := Script(program, args[0], tree)
if err != nil {
return err
}
_, err = io.WriteString(w, script)
return err
}
+50
View File
@@ -0,0 +1,50 @@
package completion
import (
"errors"
"os/exec"
"strings"
"testing"
)
var tree = Tree{
"serve": nil,
"config": Leaf("create", "validate"),
"completion": Leaf(Shells...),
}
func TestScripts(t *testing.T) {
for _, shell := range Shells {
s, err := Script("my-tool", shell, tree)
if err != nil {
t.Fatal(err)
}
for _, want := range []string{"config", "create", "validate", "powershell"} {
if !strings.Contains(s, want) {
t.Errorf("%s script lacks %q", shell, want)
}
}
}
if _, err := Script("tool", "tcsh", tree); !errors.Is(err, ErrUsage) {
t.Errorf("unknown shell: %v", err)
}
if _, err := Script("tool", "bash", Tree{"a b": nil}); err == nil {
t.Error("a name with a space must be refused")
}
var b strings.Builder
if err := Run("tool", tree, nil, &b); !errors.Is(err, ErrUsage) {
t.Errorf("no shell: %v", err)
}
}
// TestBashCompletes runs the generated bash function, when bash is there.
func TestBashCompletes(t *testing.T) {
if _, err := exec.LookPath("bash"); err != nil {
t.Skip("no bash")
}
s, _ := Script("tool", "bash", tree)
out, err := exec.Command("bash", "-c", s+"\nCOMP_WORDS=(tool config v); COMP_CWORD=2; _tool_complete; echo \"${COMPREPLY[@]}\"").CombinedOutput()
if err != nil || strings.TrimSpace(string(out)) != "validate" {
t.Fatalf("bash completion: %v %q", err, out)
}
}
+42
View File
@@ -0,0 +1,42 @@
package config
import (
"path/filepath"
"testing"
"yetano.dev/yetano/core/paths"
)
// A process without HOME (e.g. a system service) still finds its
// working-directory and system config; only the user tier is skipped.
func TestResolveWithoutHome(t *testing.T) {
root := t.TempDir()
workdir := filepath.Join(root, "work")
newResolver := func() *Resolver {
return mustResolver(t, yetApp(),
WithEnvironment(map[string]string{}),
WithWorkdirPath(workdir),
WithPathsOptions(paths.WithPlatform("linux"), paths.WithRoot(root)))
}
if _, found, err := newResolver().Resolve(); err != nil || found {
t.Fatalf("Resolve() on empty tree = found=%v err=%v, want found=false err=nil", found, err)
}
system := filepath.Join(root, "etc", "yet", "yet.yaml")
writeFile(t, system, "system: true\n")
layer, found, err := newResolver().Resolve()
if err != nil || !found {
t.Fatalf("Resolve() = found=%v err=%v, want the system file", found, err)
}
if layer.Path != system {
t.Errorf("Resolve() path = %q, want %q", layer.Path, system)
}
cwd := filepath.Join(workdir, "yet.yaml")
writeFile(t, cwd, "cwd: true\n")
layer, found, err = newResolver().Resolve()
if err != nil || !found || layer.Path != cwd {
t.Fatalf("Resolve() = %q found=%v err=%v, want %q", layer.Path, found, err, cwd)
}
}
+198
View File
@@ -0,0 +1,198 @@
// Package doctor is the shared "<program> doctor [--json]" command of the
// Yetano program standard (see docs/program-conventions.md in the yetano
// meta-repository): one report shape -- the locations the program
// resolves, and named checks -- printed as a table or as JSON, with one
// exit-code rule.
//
// r := doctor.Report{Program: "yasl"}
// r.AddPaths(app) // core/paths locations
// r.Check("config file valid", err == nil, note) // program-specific
// os.Exit(r.Run(args, os.Stdout, os.Stderr))
//
// A doctor only observes: it never creates a directory or file (a
// writability check may create and remove a probe file in a directory
// that already exists, and must say so in its note).
package doctor
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"text/tabwriter"
"yetano.dev/yetano/core"
"yetano.dev/yetano/core/paths"
)
// Path is one location the program resolves. Exists is only observed.
type Path struct {
Name string `json:"name"`
Path string `json:"path,omitempty"`
Target string `json:"target,omitempty"` // symlink-resolved Path, when it differs
Exists bool `json:"exists"`
Error string `json:"error,omitempty"`
}
// Check is one named check.
type Check struct {
Name string `json:"name"`
OK bool `json:"ok"`
Note string `json:"note,omitempty"`
}
// Report is "<program> doctor --json"'s output.
type Report struct {
Program string `json:"program,omitempty"`
Scope string `json:"scope,omitempty"` // "user" or "system"
Paths []Path `json:"paths"`
Checks []Check `json:"checks"`
}
// Exit codes of Run.
const (
ExitOK = 0 // every check passed
ExitProblems = 1 // at least one check failed
ExitUsage = 2 // bad arguments
)
// AddPath records a location, observing whether it exists.
func (r *Report) AddPath(name, path string, err error) {
p := Path{Name: name, Path: path}
if err != nil {
p.Error = err.Error()
} else if path != "" {
if _, statErr := os.Stat(path); statErr == nil {
p.Exists = true
}
if target, lerr := filepath.EvalSymlinks(path); lerr == nil && target != path {
p.Target = target
}
}
r.Paths = append(r.Paths, p)
}
// AddPaths records the standard core/paths locations of app (config, data,
// state, cache, log; runtime only where the platform has one) and sets
// Scope.
func (r *Report) AddPaths(app core.Application) {
r.Scope = "user"
if app.Scope == core.SystemScope {
r.Scope = "system"
}
res, err := paths.For(app)
if err != nil {
r.AddPath("paths", "", err)
return
}
for _, c := range []struct {
name string
fn func() (string, error)
}{
{"config dir", res.ConfigDir},
{"data dir", res.DataDir},
{"state dir", res.StateDir},
{"cache dir", res.CacheDir},
{"log dir", res.LogDir},
} {
p, err := c.fn()
r.AddPath(c.name, p, err)
}
if p, err := res.RuntimeDir(); err == nil && p != "" {
r.AddPath("runtime dir", p, nil)
}
}
// Check records a named check.
func (r *Report) Check(name string, ok bool, note string) {
r.Checks = append(r.Checks, Check{Name: name, OK: ok, Note: note})
}
// Problems counts failed checks.
func (r Report) Problems() int {
n := 0
for _, c := range r.Checks {
if !c.OK {
n++
}
}
return n
}
// Write prints the report: JSON, or a paths table and a checks table.
func (r Report) Write(w io.Writer, asJSON bool) error {
if asJSON {
if r.Paths == nil {
r.Paths = []Path{}
}
if r.Checks == nil {
r.Checks = []Check{}
}
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(r)
}
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
if len(r.Paths) > 0 {
fmt.Fprintf(tw, "PATH\tLOCATION\tEXISTS\n")
for _, p := range r.Paths {
loc := p.Path
if p.Error != "" {
loc = "error: " + p.Error
} else if p.Target != "" {
loc += " -> " + p.Target
}
fmt.Fprintf(tw, "%s\t%s\t%s\n", p.Name, loc, yesNo(p.Exists))
}
fmt.Fprintln(tw)
}
fmt.Fprintf(tw, "CHECK\tOK\tNOTE\n")
for _, c := range r.Checks {
fmt.Fprintf(tw, "%s\t%s\t%s\n", c.Name, yesNo(c.OK), c.Note)
}
return tw.Flush()
}
func yesNo(b bool) string {
if b {
return "yes"
}
return "no"
}
// Run serves "<program> doctor [--json]" -- args are the arguments after
// "doctor" -- and returns the exit code: ExitOK, ExitProblems (also
// reported on stderr), or ExitUsage.
func (r Report) Run(args []string, stdout, stderr io.Writer) int {
asJSON := false
for _, a := range args {
switch a {
case "--json", "-json":
asJSON = true
case "-h", "--help", "-help":
fmt.Fprintf(stdout, "usage: %s doctor [--json]\n", nameOr(r.Program))
return ExitOK
default:
fmt.Fprintf(stderr, "usage: %s doctor [--json] (unknown argument %q)\n", nameOr(r.Program), a)
return ExitUsage
}
}
if err := r.Write(stdout, asJSON); err != nil {
fmt.Fprintln(stderr, err)
return ExitProblems
}
if n := r.Problems(); n > 0 {
fmt.Fprintf(stderr, "%s doctor: %d problem(s) found\n", nameOr(r.Program), n)
return ExitProblems
}
return ExitOK
}
func nameOr(s string) string {
if strings.TrimSpace(s) == "" {
return "program"
}
return s
}
+51
View File
@@ -0,0 +1,51 @@
package doctor
import (
"encoding/json"
"errors"
"path/filepath"
"strings"
"testing"
"yetano.dev/yetano/core"
)
func TestRun(t *testing.T) {
dir := t.TempDir()
r := Report{Program: "tool"}
r.AddPath("data dir", dir, nil)
r.AddPath("missing", filepath.Join(dir, "nope"), nil)
r.AddPath("broken", "", errors.New("no home"))
r.Check("config valid", true, "")
var out, errOut strings.Builder
if code := r.Run([]string{"--json"}, &out, &errOut); code != ExitOK {
t.Fatalf("exit %d: %s", code, errOut.String())
}
var got Report
if err := json.Unmarshal([]byte(out.String()), &got); err != nil || len(got.Paths) != 3 || !got.Paths[0].Exists || got.Paths[1].Exists || got.Paths[2].Error != "no home" {
t.Fatalf("json: %v %+v", err, got)
}
r.Check("listener port free", false, "port 514 in use")
out.Reset()
if code := r.Run(nil, &out, &errOut); code != ExitProblems || !strings.Contains(out.String(), "port 514 in use") || !strings.Contains(errOut.String(), "1 problem") {
t.Fatalf("problems: %d %q %q", code, out.String(), errOut.String())
}
if code := r.Run([]string{"--bogus"}, &out, &errOut); code != ExitUsage {
t.Fatalf("usage: %d", code)
}
}
func TestAddPaths(t *testing.T) {
var r Report
r.AddPaths(core.Application{Name: "doctor-test", Kind: core.CLI})
if r.Scope != "user" || len(r.Paths) < 5 || r.Paths[0].Name != "config dir" {
t.Fatalf("paths: %+v", r)
}
for _, p := range r.Paths {
if p.Error == "" && p.Path == "" {
t.Errorf("%s: no path", p.Name)
}
}
}
+183
View File
@@ -0,0 +1,183 @@
// Package manual gives a Yetano program its embedded, self-served manual:
// the "<program> manual" command of ADR-0012, in one shared shape.
//
// A program embeds its documentation -- usually README.md and docs/*.md,
// with a //go:embed in a Go file at the module root, since go:embed cannot
// reach parent directories -- and hands it to FromFS; Run then serves
//
// <program> manual topic list
// <program> manual <topic> one topic's Markdown
// <program> manual --json [{"slug", "title", "path"}, ...]
// <program> manual --json <topic> {"slug", "title", "path", "markdown"}
//
// The --json form is what yet reads to show an installed program's manual
// in "yet manual --package", its TUI and yet-gui (yet's own "yet manual
// --json" uses the same shape). path is the page's source path in the
// repository, so relative links between pages resolve against it.
package manual
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"path"
"regexp"
"sort"
"strings"
)
// Topic is one manual page.
type Topic struct {
Slug string `json:"slug"`
Title string `json:"title"`
Path string `json:"path"`
}
// Manual is a program's embedded manual.
type Manual struct {
// Name is the program name, used in the plain-text listing.
Name string
FS fs.FS
Topics []Topic
}
var heading = regexp.MustCompile(`(?m)^#\s+(.+?)\s*#*\s*$`)
// FromFS builds a Manual from fsys: README.md first (slug "readme"), then
// every *.md under docs/ (recursively, by path; slug: the path below docs/
// without ".md", e.g. "configuration" or "adr/0001-x"). A page's title is
// its first "# " heading, else its slug. Other files are ignored.
func FromFS(name string, fsys fs.FS) (Manual, error) {
m := Manual{Name: name, FS: fsys}
if data, err := fs.ReadFile(fsys, "README.md"); err == nil {
m.Topics = append(m.Topics, Topic{Slug: "readme", Title: titleOf(data, "Overview"), Path: "README.md"})
}
var docs []Topic
err := fs.WalkDir(fsys, "docs", func(p string, d fs.DirEntry, err error) error {
if err != nil {
if errors.Is(err, fs.ErrNotExist) && p == "docs" {
return fs.SkipDir
}
return err
}
if d.IsDir() || !strings.EqualFold(path.Ext(p), ".md") {
return nil
}
data, err := fs.ReadFile(fsys, p)
if err != nil {
return err
}
slug := strings.TrimSuffix(strings.TrimPrefix(p, "docs/"), path.Ext(p))
docs = append(docs, Topic{Slug: slug, Title: titleOf(data, slug), Path: p})
return nil
})
if err != nil {
return Manual{}, err
}
sort.Slice(docs, func(i, j int) bool { return docs[i].Path < docs[j].Path })
m.Topics = append(m.Topics, docs...)
if len(m.Topics) == 0 {
return Manual{}, errors.New("manual: no README.md and no docs/*.md in the embedded files")
}
return m, nil
}
// MustFromFS is FromFS for a package-level variable; it panics on error
// (a missing embed is a build mistake).
func MustFromFS(name string, fsys fs.FS) Manual {
m, err := FromFS(name, fsys)
if err != nil {
panic(err)
}
return m
}
func titleOf(data []byte, fallback string) string {
if m := heading.FindSubmatch(data); m != nil {
return string(m[1])
}
return fallback
}
// Lookup returns the topic with slug.
func (m Manual) Lookup(slug string) (Topic, bool) {
for _, t := range m.Topics {
if t.Slug == slug {
return t, true
}
}
return Topic{}, false
}
// Markdown returns a topic's source.
func (m Manual) Markdown(t Topic) (string, error) {
data, err := fs.ReadFile(m.FS, t.Path)
return string(data), err
}
// ErrUsage is returned by Run for bad arguments; the caller should print
// it and exit with its usage exit code.
var ErrUsage = errors.New("usage: manual [--json] [topic]")
// Run serves "<program> manual [--json] [topic]" -- args are the
// arguments after "manual" -- writing to w. An unknown topic is an error
// (the caller exits non-zero).
func (m Manual) Run(args []string, w io.Writer) error {
asJSON := false
var rest []string
for _, a := range args {
switch a {
case "--json", "-json":
asJSON = true
case "-h", "--help", "-help":
fmt.Fprintf(w, "usage: %s manual [--json] [topic]\n", m.Name)
return nil
default:
if strings.HasPrefix(a, "-") {
return fmt.Errorf("%w (unknown flag %q)", ErrUsage, a)
}
rest = append(rest, a)
}
}
if len(rest) > 1 {
return ErrUsage
}
if len(rest) == 0 {
if asJSON {
return writeJSON(w, m.Topics)
}
fmt.Fprintf(w, "%s manual topics:\n", m.Name)
for _, t := range m.Topics {
fmt.Fprintf(w, " %-28s %s\n", t.Slug, t.Title)
}
fmt.Fprintf(w, "\nrun \"%s manual <topic>\" to read one\n", m.Name)
return nil
}
t, ok := m.Lookup(rest[0])
if !ok {
return fmt.Errorf("unknown manual topic %q (run \"%s manual\" for the list)", rest[0], m.Name)
}
md, err := m.Markdown(t)
if err != nil {
return err
}
if asJSON {
return writeJSON(w, struct {
Topic
Markdown string `json:"markdown"`
}{t, md})
}
_, err = io.WriteString(w, md)
if err == nil && !strings.HasSuffix(md, "\n") {
_, err = io.WriteString(w, "\n")
}
return err
}
func writeJSON(w io.Writer, v any) error {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(v)
}
+87
View File
@@ -0,0 +1,87 @@
package manual
import (
"encoding/json"
"errors"
"strings"
"testing"
"testing/fstest"
)
func testFS() fstest.MapFS {
return fstest.MapFS{
"README.md": {Data: []byte("# Tool\n\nIntro.\n")},
"docs/configuration.md": {Data: []byte("# Configuration\n\nKeys.")},
"docs/adr/0001-decision.md": {Data: []byte("no heading here")},
"docs/image.png": {Data: []byte("x")},
}
}
func TestFromFSAndJSON(t *testing.T) {
m, err := FromFS("tool", testFS())
if err != nil {
t.Fatal(err)
}
want := []Topic{
{Slug: "readme", Title: "Tool", Path: "README.md"},
{Slug: "adr/0001-decision", Title: "adr/0001-decision", Path: "docs/adr/0001-decision.md"},
{Slug: "configuration", Title: "Configuration", Path: "docs/configuration.md"},
}
if len(m.Topics) != len(want) {
t.Fatalf("topics = %+v", m.Topics)
}
for i := range want {
if m.Topics[i] != want[i] {
t.Errorf("topic %d = %+v, want %+v", i, m.Topics[i], want[i])
}
}
var b strings.Builder
if err := m.Run([]string{"--json"}, &b); err != nil {
t.Fatal(err)
}
var list []Topic
if err := json.Unmarshal([]byte(b.String()), &list); err != nil || len(list) != 3 {
t.Fatalf("list json: %v %s", err, b.String())
}
b.Reset()
if err := m.Run([]string{"--json", "configuration"}, &b); err != nil {
t.Fatal(err)
}
var page struct {
Topic
Markdown string `json:"markdown"`
}
if err := json.Unmarshal([]byte(b.String()), &page); err != nil || page.Markdown != "# Configuration\n\nKeys." || page.Path != "docs/configuration.md" {
t.Fatalf("page json: %v %+v", err, page)
}
b.Reset()
if err := m.Run([]string{"readme"}, &b); err != nil || b.String() != "# Tool\n\nIntro.\n" {
t.Fatalf("plain page: %v %q", err, b.String())
}
b.Reset()
if err := m.Run(nil, &b); err != nil || !strings.Contains(b.String(), "configuration") {
t.Fatalf("plain list: %v %q", err, b.String())
}
}
func TestRunErrors(t *testing.T) {
m := MustFromFS("tool", testFS())
var b strings.Builder
if err := m.Run([]string{"nope"}, &b); err == nil {
t.Error("unknown topic should fail")
}
if err := m.Run([]string{"--bogus"}, &b); !errors.Is(err, ErrUsage) {
t.Errorf("unknown flag: %v", err)
}
if err := m.Run([]string{"a", "b"}, &b); !errors.Is(err, ErrUsage) {
t.Errorf("two topics: %v", err)
}
if _, err := FromFS("empty", fstestEmpty()); err == nil {
t.Error("an empty manual should be an error")
}
}
func fstestEmpty() fstest.MapFS { return fstest.MapFS{"x.txt": {Data: []byte("x")}} }
+5 -2
View File
@@ -160,16 +160,19 @@ func (r *Resolver) darwinDesktopLayers(kind PathKind, base func(core.Scope, stri
if v, ok := r.overrideValue(kind); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
var user []layer
home, err := r.homeDir()
if err != nil {
if err := skipMissingHome(err); err != nil {
return nil, err
}
user := []layer{{
if err == nil {
user = []layer{{
path: r.applyRoot(unixJoin(base(core.UserScope, home), r.app.Name)),
source: MacOSNative,
priority: PriorityUser,
canonical: true,
}}
}
system := []layer{{
path: r.applyRoot(unixJoin(base(core.SystemScope, ""), r.app.Name)),
source: SystemDirectory,
+21 -1
View File
@@ -1,6 +1,10 @@
package paths
import "yetano.dev/yetano/core"
import (
"errors"
"yetano.dev/yetano/core"
)
// layer is one directory in a search/priority hierarchy (see
// AGENTS.md-style docs in paths.go: "canonical path vs. search paths").
@@ -40,6 +44,22 @@ func composeSearch(user, system []layer, scope core.Scope) []layer {
return out
}
// skipMissingHome filters a user-tier lookup error for the search-dir
// builders (Config/Data/Executable): a missing home directory only means
// there is no user tier to search -- the working-directory and system
// tiers are still meaningful (e.g. a system service started without
// HOME whose config lives in /etc/<app>), so ErrNoHomeDirectory is
// dropped here and the caller simply omits its user layer(s). Any other
// error is returned unchanged. The canonical <Category>Dir() methods are
// unaffected and still report ErrNoHomeDirectory: a write location is
// never silently swapped for a different tier.
func skipMissingHome(err error) error {
if errors.Is(err, ErrNoHomeDirectory) {
return nil
}
return err
}
// envSuffix maps each category to the "_HOME" suffix used to build its
// YETANO_*/<PREFIX>_* environment variable names (e.g. ConfigPath ->
// "YETANO_CONFIG_HOME" / "YET_CONFIG_HOME").
+72
View File
@@ -0,0 +1,72 @@
package paths
import (
"testing"
"yetano.dev/yetano/core"
)
// Without a home directory, the search-dir builders drop only the user
// tier; the system tier stays searchable, while the canonical *Dir()
// methods keep reporting ErrNoHomeDirectory.
func TestSearchDirsWithoutHome(t *testing.T) {
cases := []struct {
name string
platform string
app core.Application
search func(*Resolver) ([]SearchResult, error)
want []string
}{
{"linux config", "linux", yetApp(), (*Resolver).ConfigSearchDirs, []string{"/etc/yet"}},
{"freebsd config", "freebsd", yetApp(), (*Resolver).ConfigSearchDirs, []string{"/usr/local/etc/yet"}},
{"linux data", "linux", yetApp(), (*Resolver).DataSearchDirs, []string{"/usr/local/share/yet", "/usr/share/yet"}},
{"linux bin", "linux", yetApp(), (*Resolver).ExecutableSearchDirs, []string{"/usr/local/bin"}},
{"darwin desktop config", "darwin", core.Application{Name: "Yet", Kind: core.Desktop}, (*Resolver).ConfigSearchDirs, []string{"/Library/Application Support/Yet"}},
{"windows config", "windows", yetApp(), (*Resolver).ConfigSearchDirs, []string{`C:\ProgramData\yet`}},
{"windows data", "windows", yetApp(), (*Resolver).DataSearchDirs, []string{`C:\ProgramData\yet`}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
r := mustResolver(t, tc.app, WithPlatform(tc.platform), WithEnvironment(map[string]string{}))
dirs, err := tc.search(r)
if err != nil {
t.Fatalf("search dirs: %v", err)
}
var got []string
for _, d := range dirs {
got = append(got, d.Path)
}
if len(got) != len(tc.want) {
t.Fatalf("search dirs = %v, want %v", got, tc.want)
}
for i := range got {
if got[i] != tc.want[i] {
t.Fatalf("search dirs = %v, want %v", got, tc.want)
}
}
if _, err := r.ConfigDir(); err != ErrNoHomeDirectory {
t.Errorf("ConfigDir() error = %v, want ErrNoHomeDirectory", err)
}
})
}
}
// A partially available Windows user tier (APPDATA set, LOCALAPPDATA and
// USERPROFILE unset) keeps the layers it can resolve.
func TestWindowsConfigSearchPartialUserTier(t *testing.T) {
r := mustResolver(t, yetApp(), WithPlatform("windows"),
WithEnvironment(map[string]string{"APPDATA": `C:\Users\t\AppData\Roaming`}))
dirs, err := r.ConfigSearchDirs()
if err != nil {
t.Fatalf("ConfigSearchDirs: %v", err)
}
want := []string{`C:\Users\t\AppData\Roaming\yet`, `C:\ProgramData\yet`}
if len(dirs) != len(want) {
t.Fatalf("ConfigSearchDirs = %v, want %v", dirs, want)
}
for i, d := range dirs {
if d.Path != want[i] {
t.Fatalf("ConfigSearchDirs[%d] = %q, want %q", i, d.Path, want[i])
}
}
}
+15 -6
View File
@@ -186,16 +186,19 @@ func (r *Resolver) configLayersUnix() ([]layer, error) {
if v, ok := r.overrideValue(ConfigPath); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
var user []layer
userVal, err := r.xdgBase("XDG_CONFIG_HOME", ".config")
if err != nil {
if err := skipMissingHome(err); err != nil {
return nil, err
}
user := []layer{{
if err == nil {
user = []layer{{
path: r.applyRoot(unixJoin(userVal.path, r.app.Name)),
source: userVal.source,
priority: PriorityUser,
canonical: true,
}}
}
system := make([]layer, len(r.flavor().systemConfigDirs))
for i, dir := range r.flavor().systemConfigDirs {
system[i] = layer{
@@ -212,16 +215,19 @@ func (r *Resolver) dataLayersUnix() ([]layer, error) {
if v, ok := r.overrideValue(DataPath); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
var user []layer
userVal, err := r.xdgBase("XDG_DATA_HOME", ".local", "share")
if err != nil {
if err := skipMissingHome(err); err != nil {
return nil, err
}
user := []layer{{
if err == nil {
user = []layer{{
path: r.applyRoot(unixJoin(userVal.path, r.app.Name)),
source: userVal.source,
priority: PriorityUser,
canonical: true,
}}
}
dirs, source := r.xdgDataDirs()
system := make([]layer, len(dirs))
for i, dir := range dirs {
@@ -239,16 +245,19 @@ func (r *Resolver) executableLayersUnix() ([]layer, error) {
if v, ok := r.overrideValue(BinPath); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
var user []layer
home, err := r.homeDir()
if err != nil {
if err := skipMissingHome(err); err != nil {
return nil, err
}
user := []layer{{
if err == nil {
user = []layer{{
path: r.applyRoot(unixJoin(home, ".local", "bin")),
source: PlatformDefault,
priority: PriorityUser,
canonical: true,
}}
}
system := []layer{{
path: r.applyRoot(r.flavor().systemBinDir),
source: SystemDirectory,
+16 -6
View File
@@ -128,9 +128,10 @@ func (r *Resolver) configLayersWindows() ([]layer, error) {
var user []layer
if r.app.Kind != core.Desktop {
local, err := r.windowsBase("LOCALAPPDATA")
if err != nil {
if err := skipMissingHome(err); err != nil {
return nil, err
}
if err == nil {
user = append(user, layer{
path: r.applyRoot(windowsJoin(local.path, r.app.Name)),
source: local.source,
@@ -138,16 +139,19 @@ func (r *Resolver) configLayersWindows() ([]layer, error) {
canonical: false,
})
}
}
roaming, err := r.windowsBase("APPDATA")
if err != nil {
if err := skipMissingHome(err); err != nil {
return nil, err
}
if err == nil {
user = append(user, layer{
path: r.applyRoot(windowsJoin(roaming.path, r.app.Name)),
source: roaming.source,
priority: PriorityUser,
canonical: true,
})
}
system, err := r.windowsSystemLayer(r.app.Name)
if err != nil {
return nil, err
@@ -161,16 +165,19 @@ func (r *Resolver) dataLayersWindows() ([]layer, error) {
if v, ok := r.overrideValue(DataPath); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
var user []layer
local, err := r.windowsBase("LOCALAPPDATA")
if err != nil {
if err := skipMissingHome(err); err != nil {
return nil, err
}
user := []layer{{
if err == nil {
user = []layer{{
path: r.applyRoot(windowsJoin(local.path, r.app.Name)),
source: local.source,
priority: PriorityUserLocal,
canonical: true,
}}
}
system, err := r.windowsSystemLayer(r.app.Name)
if err != nil {
return nil, err
@@ -182,16 +189,19 @@ func (r *Resolver) executableLayersWindows() ([]layer, error) {
if v, ok := r.overrideValue(BinPath); ok {
return []layer{{path: r.applyRoot(v.path), source: v.source, priority: PriorityUser, canonical: true}}, nil
}
var user []layer
local, err := r.windowsBase("LOCALAPPDATA")
if err != nil {
if err := skipMissingHome(err); err != nil {
return nil, err
}
user := []layer{{
if err == nil {
user = []layer{{
path: r.applyRoot(windowsJoin(local.path, "Yetano", "bin")),
source: local.source,
priority: PriorityUserLocal,
canonical: true,
}}
}
system, err := r.windowsSystemLayer("Yetano", "bin")
if err != nil {
return nil, err
+257
View File
@@ -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
}
+127
View File
@@ -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)
}
}