Author SHA1 Message Date
terminarandClaude Opus 5.5 c8a219a84b solutions: exit 3 is "interrupted", "not found" moves to 7
The family convention (docs/program-conventions.md) gives 3 to a
command stopped by SIGINT/SIGTERM (owner decision 2026-12-01 to unify).
A cancelled context now exits 3; yetano-solutions also stops on SIGTERM.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 13:21:10 +01:00
terminarandClaude Opus 5.5 4fb9bf9a5a solutions: the guide is its own program, not part of yet
Default program name in messages is yetano-solutions; comments no
longer describe mounting the commands into yet (owner decision
2026-12-01, docs/knowledge-solutions ADR-0006 in the meta-repo).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:20:25 +01:00
terminarandClaude Opus 5.5 2481a0dd27 solutions: Solutions Guide engine (catalog, rules, wizard state, native config, knowledge index, CLI)
New nested module yetano.dev/yetano/core/solutions: loads the catalog
in assets/solutions on top of the Big Picture, evaluates questions and
conditions, resolves packages/modules/capabilities, generates native
configuration from typed fragments with per-value origins, and builds
architecture graph, plan, lock file and handbook. Knowledge index with
yetano: references, search and lint (incl. manual sections). CLI with
yet's conventions (solution, task, knowledge, open), standalone as
yetano-solutions. No execution, no network.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 08:42:58 +01:00
terminarandClaude Opus 5.5 586e76889c gui/window (Windows): give the keyboard focus to WebView2
The host window never moved the focus into the WebView2 control, so a
page got no keys after the start or after Alt-Tab until it was
clicked. Move it on WM_SETFOCUS and once the control exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:34:08 +01:00
terminarandClaude Opus 5.5 5dd4a86b68 TODO: core/gui resident app with a prewarmed WebView (proposal from yamc)
Startup measurements on macOS and what was tried without effect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 21:15:35 +01:00
terminarandClaude Opus 5.5 975340b5f7 fix(configcmd): config create --output - prints the template to stdout
It wrote a file named "-" in the working directory instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:33:03 +01:00
terminarandClaude Opus 5.5 5d141c7cef gui/window: native open and save file dialogs
ShowFileDialog (UI thread) and ChooseFile (any goroutine, waits) show a
native dialog for the window -- NSOpenPanel/NSSavePanel as a sheet on
macOS, GetOpenFileNameW/GetSaveFileNameW on Windows -- with a title, a
start folder, a suggested name and allowed extensions. It only returns
the chosen path; one dialog at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:41:23 +01:00
terminarandClaude Opus 5.5 e1495430c5 trust: the signing half of publisher signatures
Moved from yet's internal/trust without changing behavior or file
formats: KeyPair, GenerateKey, SaveKeyPair, LoadPrivateKey,
ParsePrivateKey, LoadPublicKey, MarshalPublicKey, SignEd25519,
VerifyEd25519, ExportPEM, ImportPEM, and the package signature as
SignDigest. New: Sign and VerifyMessage, a detached minisign signature
over any bytes and its check (returns the trusted comment; another key
with a colliding ID fails), and KeyFromRef, a key pair from a
core/secretref reference with error messages that never carry the
secret. A golden vector (testdata/sign-vector.*) pins the output, and
VerifySignature is tested against what SignDigest makes.

For yabar's evidence signing (ADR-0037 there, owner decision Q-5
option A); yet keeps registry signing and its auto-sign key store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 22:08:12 +01:00
terminarandClaude Opus 5.5 9395fadbf7 fix(configcmd): redact secret fields inside list values
"config show" prints a list as one value, and redaction only looked at
the leaf's own key, so the password of every entry of a list (yamocir's
bootstrap.admins) was printed in clear. The same rule now applies inside
lists and maps of a leaf: a field is secret by its default name or by a
Spec.SecretKeys key without the list index ("admins.password").
References (env:, file:, secret://) stay visible as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:47:44 +01:00
terminarandClaude Opus 5.5 8513b6db4c feat(configcmd): Spec.SecretKeys redacts a program's own secret options
"config show" redacted only keys whose last segment is secrets, secret,
token or password. A program's own secrets (database.url,
oidc.client_secret, smtp.url, ...) were printed, so programs disabled
show. Spec.SecretKeys names them as dotted keys (a key covers everything
below it); Effective carries them to Values and Show. First consumer:
yaemp and yaemp-mcp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 17:32:16 +01:00
terminarandClaude Opus 5.5 31dbc347e8 gui/window: keep the window frame across starts, take the first click
- Options.FrameFile: the window's position, size and maximized state in
  a small JSON file, read at New (a frame on no connected screen is
  ignored, the window opens centered), written shortly after every move
  or resize and at Destroy. macOS: NSWindow frame (the normal frame
  under a zoomed one), checked against NSScreen visible frames; Windows:
  Get/SetWindowPlacement, checked with MonitorFromRect.
- macOS: the web view is a WKWebView subclass that accepts the first
  mouse click, so a page in an inactive window reacts to it instead of
  the click only activating the window (yanks' start dialog).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:19:45 +01:00
terminarandClaude Opus 5.5 c16b871db5 TODO: core/gui should accept the first mouse click on macOS
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:28:30 +01:00
terminarandClaude Opus 5.5 35f8b7d18a trust: the verifying half of publisher signatures (own module)
Moved from yet/internal/trust, behavior and file formats unchanged, so
yacota (images) checks against the same trust-policy.json and
known-keys.json as yet (packages): the signature payload and its check
(Verify over fetched referrers), known keys with TOFU pinning
(Reconcile; refusals are ErrRefused), the trust policy (Evaluate,
AllowsCapability), Curated, Pinned and Home (yet's data directory).
Signing, key storage and the registry side stay in yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 16:27:35 +01:00
terminarandClaude Opus 5.5 764b6f36ea backup: archives with a checksummed manifest, rotation, safe restore
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 20:41:16 +01:00
86 changed files with 14445 additions and 21 deletions

No files matched your search

+40 -5
View File
@@ -17,7 +17,9 @@ Two **separate, nested modules** keep this module at its single
dependency: the native WebView GUI host `yetano.dev/yetano/core/gui`
(tags `gui/vX.Y.Z`, cgo, see [gui/README.md](gui/README.md)) and the
shared terminal-UI kernel `yetano.dev/yetano/core/tui` (tags
`tui/vX.Y.Z`, Charm lipgloss v2, see [tui/README.md](tui/README.md)).
`tui/vX.Y.Z`, Charm lipgloss v2, see [tui/README.md](tui/README.md)), and
the publisher-signature check `yetano.dev/yetano/core/trust` (tags
`trust/vX.Y.Z`, minisign, see [trust/README.md](trust/README.md)).
```text
yetano.dev/yetano/core
@@ -30,6 +32,7 @@ yetano.dev/yetano/core/configcmd
yetano.dev/yetano/core/configfamily
yetano.dev/yetano/core/version
yetano.dev/yetano/core/secretref
yetano.dev/yetano/core/backup
yetano.dev/yetano/core/cobracmd (separate module)
yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z)
@@ -38,6 +41,7 @@ yetano.dev/yetano/core/gui/document
yetano.dev/yetano/core/gui/bridge
yetano.dev/yetano/core/gui/window
yetano.dev/yetano/core/tui (own module, tags tui/vX.Y.Z)
yetano.dev/yetano/core/trust (own module, tags trust/vX.Y.Z)
```
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
@@ -370,8 +374,11 @@ report options the program ignores. Taken over from
`config show [--json] [--show-secrets]` prints the configuration with
the file every value comes from (`Effective.Show`; secrets -- keys
`secrets`, `secret`, `token`, `password` -- are redacted unless
`--show-secrets`, references like `env:X` stay visible), and
`secrets`, `secret`, `token`, `password`, plus the program's own
`Spec.SecretKeys` such as `database.url` (a key covers everything below
it) -- are redacted unless `--show-secrets`, references like `env:X`
stay visible; inside a list the same rule applies to every entry's
fields, a Spec key naming them without the index: `admins.password`), and
`configcmd.Doctor(report, spec, explicit)` is the config part of a
`doctor` command (paths, layers, "config file found", unknown options).
@@ -459,8 +466,9 @@ one-line form for log lines and web UI footers.
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. The nested `gui` and `tui` modules
have their own prefixed tags (`gui/v0.1.0`, `tui/v0.1.0`, ...); a change
force-moved to a different commit. The nested `gui`, `tui` and `trust`
modules have their own prefixed tags (`gui/v0.1.0`, `tui/v0.1.0`,
`trust/v0.1.0`, ...); a change
there needs no main-module tag and vice versa.
## core/secretref
@@ -486,6 +494,33 @@ plain values it accepted before checks `IsReference` and treats anything
else as a literal. Used by yavebu,
yacry and yadenes.
## core/backup: "<program> backup"
The archive behind `<program> backup create|list|verify|restore` (see
docs/program-conventions.md in the meta-repository). The program
chooses the content; `core/backup` writes, lists, rotates, verifies and
unpacks:
```go
w, err := backup.Create(dir, "yanks-registry", version.Version)
w.AddFile("registry.db", snapshot) // a consistent copy, not the live file
w.AddDir("state", dataDir, skipBlobs) // regular files below a directory
w.AddFile("config/yanks-registry.yaml", cfgPath)
a, err := w.Close() // atomic: complete or nothing
removed, err := backup.Prune(dir, "yanks-registry", backup.DefaultKeep, nil)
m, err := backup.Verify(path) // every file against MANIFEST.json
m, err := backup.Extract(path, newDir) // verified first; only below newDir
```
`<program>-<UTC time>.tar.gz`, a gzip tar with `MANIFEST.json` last
(schema, program, version, time, each file's name, size, mode and
SHA-256). Archives and their directory are owner-only (0600/0700).
`Extract` never writes over anything and never outside its destination
(`..`, absolute names and links are rejected before a byte is written).
`Prune` keeps `Keep{Last, Daily, Weekly, Monthly}` (default 3/7/4/6); an
empty `Keep` removes nothing.
## core/gui (separate module)
`yetano.dev/yetano/core/gui` is the native WebView host for desktop
+31
View File
@@ -36,6 +36,8 @@ speculatively.
whose fields are alternatives (SecretRef `env`/`file`/`value`);
`completion.Files` completes paths for programs without subcommands
(yamc) -- 2026-10-31.
- [x] `backup` (v0.11.0): archive format, rotation, verify, safe
extract for the optional `<program> backup` command -- 2026-11-05.
- [x] `doctor.Check` with optional `area` and `hint` (JSON and table,
omitted when empty), `Report.Add` -- 2026-11-01, for v0.10.0.
- [x] macOS CLI/Service system-scope `RuntimeDir` is `/var/run/<app>`
@@ -45,7 +47,36 @@ speculatively.
`yetano.dev/yetano/core/gui` (`gui/v0.1.0`). The prototype uses it.
- [ ] Move yet-gui off its copy in `yet/gui/internal` onto `core/gui`
(steps in [gui/README.md](gui/README.md)).
- [x] `core/gui` (macOS): the web view accepts the first mouse click in
an inactive window (`YTWebView`, `acceptsFirstMouse:` YES;
`gui/v0.2.0`, 2026-11-15) -- before, the first click only activated
the window, so a dialog shown at start looked dead (yanks).
- [x] `core/gui`: `window.Options.FrameFile` keeps the window's position,
size and maximized state across starts (macOS and Windows;
`gui/v0.2.0`, 2026-11-15).
- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md.
- [ ] `core/gui`: resident app with a prewarmed WebView, for a start
under 300 ms (proposal from yamc, 2026-11-29, for its H-STARTUP;
see yamc `docs/spec/gui-comparison.md`). Measured on macOS (Apple
Silicon, warm): NSApp setup ~65 ms, WKWebView init ~45 ms, window
~25 ms, then ~190 ms until the web content process asks for the
first resource and ~150 ms for WebKit's first paint -- ~550 ms to
the first frame, ~340 ms of it WebKit's own, which only advances
while the main run loop runs. Tried without effect (yamc,
2026-11-29): `loadRequest` right after the WKWebView exists
(before the window is built, also before `finishLaunching`),
spinning the run loop after it, building the app's state in
parallel -- the first request still comes ~200 ms after the main
thread is free. So a fresh process stays at ~500 ms or more.
Proposal: keep the process alive after its last window (macOS: a
normal Dock app; Windows: a background process), hold one hidden
WebView with the page loaded in reserve, and let a new start hand
its arguments to the running instance (single instance, e.g. a
socket in the runtime dir), which shows the reserve window and
prepares the next. Needs several windows per process, a
reserve-window API, and the same on WebView2. The first start
stays at ~550 ms. Only worth it once a program needs it (yamc's
Gio-vs-WebView choice is still open).
- [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer,
ListState, text helpers) as the nested module
`yetano.dev/yetano/core/tui` (`tui/v0.1.0`).
+525
View File
@@ -0,0 +1,525 @@
// Package backup is the archive format and handling behind the optional
// "<program> backup create|list|verify|restore" commands of the Yetano
// program standard (docs/program-conventions.md in the yetano
// meta-repository). The program decides what goes in (a consistent
// database copy, its config, state files -- never what can be fetched
// again); this package writes, lists, rotates, checks and unpacks.
//
// w, err := backup.Create(dir, "yanks-registry", version.Version)
// w.AddFile("registry.db", snapshotPath)
// w.AddFile("config/yanks-registry.yaml", cfgPath)
// a, err := w.Close() // atomic: complete or nothing
// removed, err := backup.Prune(dir, "yanks-registry", backup.DefaultKeep, time.Now())
//
// An archive is a gzip-compressed tar named
// "<program>-<UTC time>.tar.gz": the files, then MANIFEST.json (program,
// version, time, and every file's name, size, mode and SHA-256).
// Archives and their directory are only readable by the owner -- they
// hold password hashes and keys as often as not. Extract verifies an
// archive completely before it writes anything, and only ever writes
// below its destination.
package backup
import (
"archive/tar"
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
)
// Schema is the manifest version this package writes and reads.
const Schema = 1
// ManifestName is the archive's last entry.
const ManifestName = "MANIFEST.json"
// timeLayout is the UTC time in archive names; it sorts as text.
const timeLayout = "20060102T150405Z"
// Manifest describes an archive.
type Manifest struct {
Schema int `json:"schema"`
Program string `json:"program"`
Version string `json:"version,omitempty"`
CreatedAt time.Time `json:"created_at"`
Files []File `json:"files"`
}
// File is one archived file. Name is slash-separated and relative.
type File struct {
Name string `json:"name"`
Size int64 `json:"size"`
Mode uint32 `json:"mode"`
SHA256 string `json:"sha256"`
}
// Archive is a backup file in a directory.
type Archive struct {
Path string `json:"path"`
Program string `json:"program"`
CreatedAt time.Time `json:"created_at"`
Size int64 `json:"size"`
}
// ErrInvalid: the archive is damaged, incomplete or not a backup.
var ErrInvalid = errors.New("backup: invalid archive")
func invalid(format string, args ...any) error {
return fmt.Errorf("%w: %s", ErrInvalid, fmt.Sprintf(format, args...))
}
var (
programRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
suffixRE = regexp.MustCompile(`^-[0-9]+$`)
)
// Writer builds an archive in a temporary file next to its final name.
type Writer struct {
dir, program string
m Manifest
f *os.File
gz *gzip.Writer
tw *tar.Writer
names map[string]bool
err error
}
// Create starts an archive of program in dir (created owner-only when
// missing).
func Create(dir, program, version string) (*Writer, error) {
if !programRE.MatchString(program) {
return nil, fmt.Errorf("backup: invalid program name %q", program)
}
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, fmt.Errorf("backup: %w", err)
}
f, err := os.CreateTemp(dir, "."+program+"-*.partial")
if err != nil {
return nil, fmt.Errorf("backup: %w", err)
}
if err := f.Chmod(0o600); err != nil {
f.Close()
os.Remove(f.Name())
return nil, fmt.Errorf("backup: %w", err)
}
gz := gzip.NewWriter(f)
return &Writer{dir: dir, program: program, f: f, gz: gz, tw: tar.NewWriter(gz), names: map[string]bool{},
m: Manifest{Schema: Schema, Program: program, Version: version, CreatedAt: time.Now().UTC().Truncate(time.Second), Files: []File{}}}, nil
}
// validName: relative, slash-separated, clean, inside the archive.
func validName(name string) bool {
return name != "" && name != "." && name != ManifestName && !strings.HasPrefix(name, "/") &&
!strings.Contains(name, `\`) && path.Clean(name) == name && name != ".." && !strings.HasPrefix(name, "../")
}
func (w *Writer) add(name string, mode fs.FileMode, size int64, mtime time.Time, r io.Reader) error {
if w.err != nil {
return w.err
}
if !validName(name) {
return fmt.Errorf("backup: invalid name %q", name)
}
if w.names[name] {
return fmt.Errorf("backup: %s added twice", name)
}
w.names[name] = true
perm := uint32(mode.Perm())
h := &tar.Header{Name: name, Mode: int64(perm), Size: size, ModTime: mtime, Typeflag: tar.TypeReg, Format: tar.FormatPAX}
if err := w.tw.WriteHeader(h); err != nil {
w.err = fmt.Errorf("backup: %s: %w", name, err)
return w.err
}
sum := sha256.New()
n, err := io.Copy(w.tw, io.TeeReader(r, sum))
if err == nil && n != size {
err = fmt.Errorf("changed while it was read (%d of %d bytes)", n, size)
}
if err != nil {
w.err = fmt.Errorf("backup: %s: %w", name, err)
return w.err
}
w.m.Files = append(w.m.Files, File{Name: name, Size: size, Mode: perm, SHA256: hex.EncodeToString(sum.Sum(nil))})
return nil
}
// AddFile archives the regular file src as name.
func (w *Writer) AddFile(name, src string) error {
f, err := os.Open(src)
if err != nil {
return fmt.Errorf("backup: %w", err)
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return fmt.Errorf("backup: %w", err)
}
if !fi.Mode().IsRegular() {
return fmt.Errorf("backup: %s is not a regular file", src)
}
return w.add(name, fi.Mode(), fi.Size(), fi.ModTime(), f)
}
// AddBytes archives data as name.
func (w *Writer) AddBytes(name string, data []byte, mode fs.FileMode) error {
return w.add(name, mode, int64(len(data)), w.m.CreatedAt, strings.NewReader(string(data)))
}
// AddDir archives the regular files below src as prefix/<relative
// path>, in a stable order. skip (may be nil) leaves out a file or, for
// a directory, everything below it; rel is slash-separated. Symbolic
// links and other special files are left out.
func (w *Writer) AddDir(prefix, src string, skip func(rel string, d fs.DirEntry) bool) error {
return filepath.WalkDir(src, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return fmt.Errorf("backup: %w", err)
}
rel, err := filepath.Rel(src, p)
if err != nil {
return err
}
if rel == "." {
return nil
}
rel = filepath.ToSlash(rel)
if skip != nil && skip(rel, d) {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if !d.Type().IsRegular() {
return nil
}
return w.AddFile(path.Join(prefix, rel), p)
})
}
// Close finishes the archive: the manifest, then an atomic rename to
// "<program>-<time>.tar.gz". After an error the archive is removed.
func (w *Writer) Close() (Archive, error) {
if w.err != nil {
w.Abort()
return Archive{}, w.err
}
b, err := json.MarshalIndent(w.m, "", " ")
if err == nil {
err = w.tw.WriteHeader(&tar.Header{Name: ManifestName, Mode: 0o600, Size: int64(len(b)), ModTime: w.m.CreatedAt,
Typeflag: tar.TypeReg, Format: tar.FormatPAX})
}
if err == nil {
_, err = w.tw.Write(b)
}
if err == nil {
err = w.tw.Close()
}
if err == nil {
err = w.gz.Close()
}
if err == nil {
err = w.f.Sync()
}
if cerr := w.f.Close(); err == nil {
err = cerr
}
if err != nil {
os.Remove(w.f.Name())
return Archive{}, fmt.Errorf("backup: %w", err)
}
final, err := freeName(w.dir, w.program, w.m.CreatedAt)
if err == nil {
err = os.Rename(w.f.Name(), final)
}
if err != nil {
os.Remove(w.f.Name())
return Archive{}, fmt.Errorf("backup: %w", err)
}
fi, err := os.Stat(final)
if err != nil {
return Archive{}, fmt.Errorf("backup: %w", err)
}
return Archive{Path: final, Program: w.program, CreatedAt: w.m.CreatedAt, Size: fi.Size()}, nil
}
// Abort drops an unfinished archive.
func (w *Writer) Abort() {
w.f.Close()
os.Remove(w.f.Name())
}
func freeName(dir, program string, t time.Time) (string, error) {
base := program + "-" + t.UTC().Format(timeLayout)
for i := 1; i < 100; i++ {
name := base + ".tar.gz"
if i > 1 {
name = fmt.Sprintf("%s-%d.tar.gz", base, i)
}
p := filepath.Join(dir, name)
if _, err := os.Lstat(p); errors.Is(err, os.ErrNotExist) {
return p, nil
}
}
return "", fmt.Errorf("no free archive name for %s", base)
}
// parseName reads the time and the sequence number (1, or n of "-n")
// from an archive's file name.
func parseName(name, program string) (time.Time, int, bool) {
rest, ok := strings.CutPrefix(name, program+"-")
if !ok {
return time.Time{}, 0, false
}
rest, ok = strings.CutSuffix(rest, ".tar.gz")
if !ok || len(rest) < len(timeLayout) {
return time.Time{}, 0, false
}
stamp, suffix := rest[:len(timeLayout)], rest[len(timeLayout):]
seq := 1
if suffix != "" {
if !suffixRE.MatchString(suffix) {
return time.Time{}, 0, false
}
fmt.Sscanf(suffix[1:], "%d", &seq)
}
t, err := time.Parse(timeLayout, stamp)
return t, seq, err == nil
}
// List returns program's archives in dir, newest first. A missing dir
// is no archive.
func List(dir, program string) ([]Archive, error) {
entries, err := os.ReadDir(dir)
if errors.Is(err, os.ErrNotExist) {
return []Archive{}, nil
}
if err != nil {
return nil, fmt.Errorf("backup: %w", err)
}
out := []Archive{}
seq := map[string]int{}
for _, e := range entries {
t, n, ok := parseName(e.Name(), program)
if !ok || !e.Type().IsRegular() {
continue
}
fi, err := e.Info()
if err != nil {
continue
}
p := filepath.Join(dir, e.Name())
seq[p] = n
out = append(out, Archive{Path: p, Program: program, CreatedAt: t, Size: fi.Size()})
}
sort.SliceStable(out, func(i, j int) bool {
if !out[i].CreatedAt.Equal(out[j].CreatedAt) {
return out[i].CreatedAt.After(out[j].CreatedAt)
}
return seq[out[i].Path] > seq[out[j].Path]
})
return out, nil
}
// Keep says which archives Prune keeps: the Last newest, and the newest
// of each of the last Daily days, Weekly ISO weeks and Monthly months
// that have one (local time).
type Keep struct {
Last int `json:"last" yaml:"last"`
Daily int `json:"daily" yaml:"daily"`
Weekly int `json:"weekly" yaml:"weekly"`
Monthly int `json:"monthly" yaml:"monthly"`
}
// DefaultKeep: the 3 newest, a week of days, a month of weeks, half a
// year of months.
var DefaultKeep = Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}
// Prune removes program's archives in dir that keep does not hold and
// returns them. A Keep of all zeros removes nothing (a misconfiguration
// must not delete every backup).
func Prune(dir, program string, keep Keep, loc *time.Location) ([]Archive, error) {
if keep == (Keep{}) {
return []Archive{}, nil
}
if loc == nil {
loc = time.Local
}
all, err := List(dir, program)
if err != nil {
return nil, err
}
kept := map[string]bool{}
for i := 0; i < keep.Last && i < len(all); i++ {
kept[all[i].Path] = true
}
bucket := func(n int, key func(time.Time) string) {
seen := map[string]bool{}
for _, a := range all { // newest first: the first of a bucket is its newest
k := key(a.CreatedAt.In(loc))
if seen[k] {
continue
}
if len(seen) == n {
return
}
seen[k] = true
kept[a.Path] = true
}
}
bucket(keep.Daily, func(t time.Time) string { return t.Format("2006-01-02") })
bucket(keep.Weekly, func(t time.Time) string { y, w := t.ISOWeek(); return fmt.Sprintf("%d-%02d", y, w) })
bucket(keep.Monthly, func(t time.Time) string { return t.Format("2006-01") })
removed := []Archive{}
for _, a := range all {
if kept[a.Path] {
continue
}
if err := os.Remove(a.Path); err != nil {
return removed, fmt.Errorf("backup: %w", err)
}
removed = append(removed, a)
}
return removed, nil
}
// walk reads an archive, calling fn for every file entry with its
// content; it returns the manifest after checking that it lists exactly
// the files read, with their sizes and checksums.
func walk(archive string, fn func(h *tar.Header, r io.Reader) error) (Manifest, error) {
var m Manifest
f, err := os.Open(archive)
if err != nil {
return m, fmt.Errorf("backup: %w", err)
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
return m, invalid("%s: %v", filepath.Base(archive), err)
}
tr := tar.NewReader(gz)
got := map[string]File{}
haveManifest := false
for {
h, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return m, invalid("%s: %v", filepath.Base(archive), err)
}
if haveManifest {
return m, invalid("an entry after the manifest: %q", h.Name)
}
if h.Name == ManifestName {
b, err := io.ReadAll(io.LimitReader(tr, 64<<20))
if err != nil {
return m, invalid("manifest: %v", err)
}
if err := json.Unmarshal(b, &m); err != nil {
return m, invalid("manifest: %v", err)
}
haveManifest = true
continue
}
if h.Typeflag != tar.TypeReg || !validName(h.Name) {
return m, invalid("unexpected entry %q", h.Name)
}
if _, dup := got[h.Name]; dup {
return m, invalid("%q twice", h.Name)
}
sum := sha256.New()
r := io.TeeReader(tr, sum)
if fn != nil {
if err := fn(h, r); err != nil {
return m, err
}
}
if _, err := io.Copy(io.Discard, r); err != nil { // what fn did not read
return m, invalid("%s: %v", h.Name, err)
}
got[h.Name] = File{Name: h.Name, Size: h.Size, SHA256: hex.EncodeToString(sum.Sum(nil))}
}
if !haveManifest {
return m, invalid("no manifest: the archive is incomplete")
}
if m.Schema != Schema {
return m, invalid("manifest schema %d, this program reads %d", m.Schema, Schema)
}
if len(m.Files) != len(got) {
return m, invalid("the manifest lists %d files, the archive holds %d", len(m.Files), len(got))
}
for _, mf := range m.Files {
g, ok := got[mf.Name]
if !ok {
return m, invalid("%s is missing", mf.Name)
}
if g.Size != mf.Size || g.SHA256 != mf.SHA256 {
return m, invalid("%s does not match its checksum", mf.Name)
}
}
return m, nil
}
// Verify reads an archive completely and checks every file against the
// manifest.
func Verify(archive string) (Manifest, error) {
return walk(archive, nil)
}
// Extract verifies the archive, then unpacks it into dest, which must
// not exist yet (its parent must): nothing is ever written over, and
// nothing outside dest. On an error dest is removed again.
func Extract(archive, dest string) (Manifest, error) {
if _, err := Verify(archive); err != nil {
return Manifest{}, err
}
if _, err := os.Lstat(dest); err == nil {
return Manifest{}, fmt.Errorf("backup: %s exists; extract into a new directory", dest)
}
if err := os.Mkdir(dest, 0o700); err != nil {
return Manifest{}, fmt.Errorf("backup: %w", err)
}
m, err := walk(archive, func(h *tar.Header, r io.Reader) error {
target := filepath.Join(dest, filepath.FromSlash(h.Name))
if rel, err := filepath.Rel(dest, target); err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return invalid("%q leaves the destination", h.Name)
}
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
return fmt.Errorf("backup: %w", err)
}
f, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, fs.FileMode(h.Mode).Perm()|0o200)
if err != nil {
return fmt.Errorf("backup: %w", err)
}
_, err = io.Copy(f, r)
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Chmod(target, fs.FileMode(h.Mode).Perm())
}
if err == nil {
err = os.Chtimes(target, h.ModTime, h.ModTime)
}
if err != nil {
return fmt.Errorf("backup: %s: %w", h.Name, err)
}
return nil
})
if err != nil {
os.RemoveAll(dest)
return Manifest{}, err
}
return m, nil
}
+241
View File
@@ -0,0 +1,241 @@
package backup
import (
"archive/tar"
"compress/gzip"
"errors"
"io/fs"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
)
func write(t *testing.T, p, content string, mode fs.FileMode) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(content), mode); err != nil {
t.Fatal(err)
}
}
func makeArchive(t *testing.T, dir string) Archive {
t.Helper()
src := t.TempDir()
write(t, filepath.Join(src, "db"), "database", 0o600)
write(t, filepath.Join(src, "state", "users.json"), `{"u":1}`, 0o600)
write(t, filepath.Join(src, "state", "repos", "a", "tags", "latest"), "sha256:x", 0o644)
write(t, filepath.Join(src, "state", "blobs", "big"), "blob", 0o644)
w, err := Create(dir, "prog", "1.2.3")
if err != nil {
t.Fatal(err)
}
if err := w.AddFile("db/registry.db", filepath.Join(src, "db")); err != nil {
t.Fatal(err)
}
if err := w.AddDir("state", filepath.Join(src, "state"), func(rel string, d fs.DirEntry) bool { return rel == "blobs" }); err != nil {
t.Fatal(err)
}
if err := w.AddBytes("config/prog.yaml", []byte("listen: x\n"), 0o640); err != nil {
t.Fatal(err)
}
if err := w.AddFile("db/registry.db", filepath.Join(src, "db")); err == nil {
t.Error("the same name added twice")
}
w.err = nil // the duplicate is the test's own doing
a, err := w.Close()
if err != nil {
t.Fatal(err)
}
return a
}
func TestRoundTrip(t *testing.T) {
dir := filepath.Join(t.TempDir(), "backups")
a := makeArchive(t, dir)
if !strings.HasPrefix(filepath.Base(a.Path), "prog-") || !strings.HasSuffix(a.Path, ".tar.gz") {
t.Errorf("archive name %s", a.Path)
}
if runtime.GOOS != "windows" {
for p, want := range map[string]fs.FileMode{dir: 0o700, a.Path: 0o600} {
if fi, _ := os.Stat(p); fi.Mode().Perm() != want {
t.Errorf("%s mode %v, want %v", p, fi.Mode().Perm(), want)
}
}
}
if left, _ := filepath.Glob(filepath.Join(dir, ".*partial")); len(left) != 0 {
t.Errorf("temporary files left: %v", left)
}
m, err := Verify(a.Path)
if err != nil {
t.Fatal(err)
}
var names []string
for _, f := range m.Files {
names = append(names, f.Name)
}
if m.Program != "prog" || m.Version != "1.2.3" ||
strings.Join(names, ",") != "db/registry.db,state/repos/a/tags/latest,state/users.json,config/prog.yaml" {
t.Errorf("manifest = %+v", m)
}
dest := filepath.Join(t.TempDir(), "restore")
if _, err := Extract(a.Path, dest); err != nil {
t.Fatal(err)
}
b, _ := os.ReadFile(filepath.Join(dest, "state", "users.json"))
if string(b) != `{"u":1}` {
t.Errorf("users.json = %q", b)
}
if _, err := os.Stat(filepath.Join(dest, "state", "blobs")); !errors.Is(err, os.ErrNotExist) {
t.Error("a skipped directory was archived")
}
if runtime.GOOS != "windows" {
if fi, _ := os.Stat(filepath.Join(dest, "config", "prog.yaml")); fi.Mode().Perm() != 0o640 {
t.Errorf("restored mode %v", fi.Mode().Perm())
}
}
if _, err := Extract(a.Path, dest); err == nil {
t.Error("extracted over an existing directory")
}
}
func TestDamagedArchives(t *testing.T) {
dir := t.TempDir()
a := makeArchive(t, dir)
raw, _ := os.ReadFile(a.Path)
// Cut off: no manifest, or not even a complete gzip stream.
cut := filepath.Join(dir, "cut.tar.gz")
write(t, cut, string(raw[:len(raw)/2]), 0o600)
if _, err := Verify(cut); !errors.Is(err, ErrInvalid) {
t.Errorf("truncated archive: %v", err)
}
// A file whose content does not match the manifest.
tampered := filepath.Join(dir, "tampered.tar.gz")
writeTar(t, tampered, []entry{{"db/registry.db", "other!!!"}, {ManifestName, manifestFor(t, a.Path)}})
if _, err := Verify(tampered); !errors.Is(err, ErrInvalid) {
t.Errorf("tampered archive: %v", err)
}
// Names that leave the destination are refused before anything is
// written.
for _, name := range []string{"../evil", "/etc/evil", "a/../../evil", `a\..\evil`} {
evil := filepath.Join(dir, "evil.tar.gz")
writeTar(t, evil, []entry{{name, "x"}, {ManifestName, `{"schema":1,"program":"prog","files":[]}`}})
dest := filepath.Join(t.TempDir(), "d")
if _, err := Extract(evil, dest); !errors.Is(err, ErrInvalid) {
t.Errorf("%q: %v", name, err)
}
if _, err := os.Stat(dest); !errors.Is(err, os.ErrNotExist) {
t.Errorf("%q: destination created", name)
}
}
}
type entry struct{ name, content string }
func writeTar(t *testing.T, p string, entries []entry) {
t.Helper()
f, err := os.Create(p)
if err != nil {
t.Fatal(err)
}
gz := gzip.NewWriter(f)
tw := tar.NewWriter(gz)
for _, e := range entries {
tw.WriteHeader(&tar.Header{Name: e.name, Mode: 0o600, Size: int64(len(e.content)), Typeflag: tar.TypeReg})
tw.Write([]byte(e.content))
}
tw.Close()
gz.Close()
f.Close()
}
// manifestFor is a manifest that lists only db/registry.db as in a.
func manifestFor(t *testing.T, archive string) string {
m, err := Verify(archive)
if err != nil {
t.Fatal(err)
}
return `{"schema":1,"program":"prog","files":[{"name":"db/registry.db","size":8,"mode":384,"sha256":"` + m.Files[0].SHA256 + `"}]}`
}
func TestListAndPrune(t *testing.T) {
dir := t.TempDir()
loc := time.UTC
start := time.Date(2026, 1, 1, 3, 0, 0, 0, loc)
// One archive a day for 200 days, two on the last day.
for d := 0; d < 200; d++ {
ts := start.AddDate(0, 0, d)
write(t, filepath.Join(dir, "prog-"+ts.Format(timeLayout)+".tar.gz"), "x", 0o600)
}
last := start.AddDate(0, 0, 199)
write(t, filepath.Join(dir, "prog-"+last.Format(timeLayout)+"-2.tar.gz"), "x", 0o600)
write(t, filepath.Join(dir, "other-"+last.Format(timeLayout)+".tar.gz"), "x", 0o600)
write(t, filepath.Join(dir, "prog-notatime.tar.gz"), "x", 0o600)
all, err := List(dir, "prog")
if err != nil {
t.Fatal(err)
}
if len(all) != 201 || !strings.HasSuffix(all[0].Path, "-2.tar.gz") {
t.Fatalf("list = %d, first %s", len(all), all[0].Path)
}
if none, _ := List(filepath.Join(dir, "missing"), "prog"); len(none) != 0 {
t.Error("a missing directory lists archives")
}
if removed, _ := Prune(dir, "prog", Keep{}, loc); len(removed) != 0 {
t.Error("an empty Keep removed archives")
}
removed, err := Prune(dir, "prog", Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}, loc)
if err != nil {
t.Fatal(err)
}
kept, _ := List(dir, "prog")
if len(kept)+len(removed) != 201 {
t.Fatalf("kept %d + removed %d", len(kept), len(removed))
}
// 3 newest (2 of them on the last day) + 6 more days; weekly and
// monthly add the older ones: at most 3+7+4+6, at least 7+6.
if len(kept) < 13 || len(kept) > 20 {
t.Errorf("kept %d archives", len(kept))
}
months := map[string]bool{}
for _, a := range kept {
months[a.CreatedAt.Format("2006-01")] = true
}
if len(months) != 6 {
t.Errorf("months kept: %v", months)
}
if _, err := os.Stat(filepath.Join(dir, "other-"+last.Format(timeLayout)+".tar.gz")); err != nil {
t.Error("another program's archive was removed")
}
// Pruning again changes nothing.
if again, _ := Prune(dir, "prog", Keep{Last: 3, Daily: 7, Weekly: 4, Monthly: 6}, loc); len(again) != 0 {
t.Errorf("second prune removed %d", len(again))
}
}
func TestCreateRejectsBadInput(t *testing.T) {
if _, err := Create(t.TempDir(), "../x", ""); err == nil {
t.Error("program name with a path")
}
w, err := Create(t.TempDir(), "prog", "")
if err != nil {
t.Fatal(err)
}
defer w.Abort()
for _, n := range []string{"", "/abs", "../up", "a/./b", ManifestName} {
if err := w.AddBytes(n, nil, 0o600); err == nil {
t.Errorf("name %q accepted", n)
}
}
}
+15 -3
View File
@@ -2,7 +2,7 @@
// Yetano program standard (docs/program-conventions.md and ADR-0012 in
// the yetano meta-repository):
//
// <program> config create [--minimal|--full] [--force] [--output <file>]
// <program> config create [--minimal|--full] [--force] [--output <file>|-]
// <program> config validate
// <program> config upgrade [--write]
// <program> config path
@@ -116,6 +116,14 @@ type Spec struct {
// options (see Missing). Optional.
Schema any
// SecretKeys are the program's own secret options, as dotted keys
// ("database.url", "oidc.client_secret"): "config show" redacts them
// like the keys it always treats as secret (a last segment secrets,
// secret, token or password). A key also covers everything below it.
// Fields of list entries are named without the index
// ("admins.password" for every entry of the list admins).
SecretKeys []string
// Options are passed through to core/config; tests use them to
// inject a platform, environment, root and working directory.
Options []coreconfig.Option
@@ -193,7 +201,7 @@ func usage(s Spec, w io.Writer) {
}
fmt.Fprintf(w, `usage: %[1]s config <subcommand> [--config <file>]
create [--minimal|--full] [--force] [--output <file>]
create [--minimal|--full] [--force] [--output <file>|-]
write a commented starter configuration (minimal by default)
validate check the configuration file the program would use
upgrade [--write]
@@ -334,7 +342,7 @@ func (s Spec) create(explicit string, args []string, stdout, stderr io.Writer) i
minimal := fs.Bool("minimal", false, "write the minimal starter configuration (default)")
full := fs.Bool("full", false, "write the fully commented reference configuration")
force := fs.Bool("force", false, "overwrite the file if it already exists")
output := fs.String("output", "", "file to write (default: --config, else the file the program would use, else "+s.filename()+" in the user config directory -- the system one as root)")
output := fs.String("output", "", "file to write, - for stdout (default: --config, else the file the program would use, else "+s.filename()+" in the user config directory -- the system one as root)")
if code := parse(fs, args); code >= 0 {
return code
}
@@ -348,6 +356,10 @@ func (s Spec) create(explicit string, args []string, stdout, stderr io.Writer) i
}
path := *output
if path == "-" { // the template on stdout, nothing written
io.WriteString(stdout, content)
return ExitOK
}
if path == "" {
var err error
if path, err = s.defaultCreatePath(explicit); err != nil {
+21
View File
@@ -190,6 +190,27 @@ func TestCreateExplicitAndOutput(t *testing.T) {
}
}
// --output - prints the template and writes no file (not one named "-").
func TestCreateOutputStdout(t *testing.T) {
root := t.TempDir()
s := testSpec(root)
work := filepath.Join(root, "work")
if err := os.MkdirAll(work, 0o755); err != nil {
t.Fatal(err)
}
t.Chdir(work)
code, out, errOut := run(t, s, "", "create", "--full", "--output", "-")
if code != ExitOK || out != fullTemplate || errOut != "" {
t.Fatalf("create --output -: exit %d, stdout %q, stderr %q", code, out, errOut)
}
if _, err := os.Stat(filepath.Join(work, "-")); !errors.Is(err, os.ErrNotExist) {
t.Errorf("create --output - wrote a file named \"-\": %v", err)
}
if code, out, _ := run(t, s, "", "create", "--output=-"); code != ExitOK || out != minimalTemplate {
t.Errorf("create --output=-: exit %d, stdout %q", code, out)
}
}
func TestValidate(t *testing.T) {
root := t.TempDir()
s := testSpec(root)
+4
View File
@@ -73,6 +73,9 @@ type Effective struct {
// Loader is the Layered loader's own value for this configuration
// (e.g. its richer layer list), for its Unknown hook; nil otherwise.
Loader any
// SecretKeys are redacted by Values and Show in addition to the
// default secret names (Spec.SecretKeys).
SecretKeys []string
}
// Used returns the layers that contributed, highest priority first.
@@ -233,6 +236,7 @@ func (s Spec) show(explicit string, args []string, stdout, stderr io.Writer) int
return ExitProblem
}
used := s.usedFunc()
e.SecretKeys = s.SecretKeys
if err := e.Show(stdout, used, *asJSON, *secrets); err != nil {
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
return ExitProblem
+87
View File
@@ -174,6 +174,43 @@ func TestValuesRedaction(t *testing.T) {
}
}
// TestValuesProgramSecrets: Spec.SecretKeys (on Effective) redacts a
// program's own secret options and everything below one; other keys and
// a key that only shares a prefix stay.
func TestValuesProgramSecrets(t *testing.T) {
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
"database": map[string]any{"url": "postgres://app:pw@db/x", "owner_url": "file:/run/o", "urls": "kept"},
"smtp": map[string]any{"url": "smtps://u:pw@mail", "from": "a@b"},
"vault": map[string]any{"inner": map[string]any{"key": "deep"}},
}})
e := &Effective{Name: "p", Merged: merged, Origins: origins, SecretKeys: []string{"database.url", "database.owner_url", "smtp.url", "vault"}}
got := map[string]any{}
for _, v := range e.Values(nil, false) {
got[v.Key] = v.Value
}
want := map[string]any{
"database.url": "<redacted>", "database.owner_url": "file:/run/o", "database.urls": "kept",
"smtp.url": "<redacted>", "smtp.from": "a@b", "vault.inner.key": "<redacted>",
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Values = %v, want %v", got, want)
}
for _, v := range e.Values(nil, true) {
if v.Key == "smtp.url" && v.Value != "smtps://u:pw@mail" {
t.Errorf("show-secrets: %v", v.Value)
}
}
// Through "config show": the Spec's keys reach the output.
root := t.TempDir()
s := testSpec(root)
s.SecretKeys = []string{"log-level"}
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"), minimalTemplate+"log-level: debug\n")
if code, out, errOut := run(t, s, "", "show"); code != ExitOK || strings.Contains(out, `"debug"`) || !strings.Contains(out, `log-level: "<redacted>"`) {
t.Errorf("show: exit %d\n%s%s", code, out, errOut)
}
}
type inlineBase struct {
Enabled bool `yaml:"enabled"`
}
@@ -211,3 +248,53 @@ func statExistsForTest(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// TestValuesRedactionInLists: a list leaf is printed as one value, so
// the secret fields of its entries are redacted inside it -- by default
// name and by a Spec key without the index -- and the rest stays.
func TestValuesRedactionInLists(t *testing.T) {
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
"admins": []any{
map[string]any{"username": "admin", "password": "changeme"},
map[string]any{"username": "ops", "password": "env:OPS_PW", "tags": []any{"a"}},
},
"ids": []any{map[string]any{"name": "gc", "nested": map[string]any{"token": "t0k"}, "url": "pg://u:pw@h"}},
"plain": []any{"x", "y"},
}})
e := &Effective{Name: "p", Merged: merged, Origins: origins, SecretKeys: []string{"ids.url"}}
got := map[string]any{}
for _, v := range e.Values(nil, false) {
got[v.Key] = v.Value
}
want := map[string]any{
"admins": []any{
map[string]any{"username": "admin", "password": "<redacted>"},
map[string]any{"username": "ops", "password": "env:OPS_PW", "tags": []any{"a"}},
},
"ids": []any{map[string]any{"name": "gc", "nested": map[string]any{"token": "<redacted>"}, "url": "<redacted>"}},
"plain": []any{"x", "y"},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Values = %v\nwant %v", got, want)
}
if merged["admins"].([]any)[0].(map[string]any)["password"] != "changeme" {
t.Error("the merged configuration was changed")
}
for _, v := range e.Values(nil, true) {
if v.Key == "admins" && !strings.Contains(renderValue(v.Value), "changeme") {
t.Errorf("show-secrets: %v", v.Value)
}
}
// Through "config show" from a file, YAML and JSON.
root := t.TempDir()
s := testSpec(root)
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"),
minimalTemplate+"users:\n - name: a\n password: hunter2\n")
for _, args := range [][]string{{"show"}, {"show", "--json"}} {
code, out, errOut := run(t, s, "", args...)
if code != ExitOK || strings.Contains(out, "hunter2") || !strings.Contains(out, "<redacted>") || !strings.Contains(out, `"name"`) {
t.Errorf("%v: exit %d\n%s%s", args, code, out, errOut)
}
}
}
+50 -4
View File
@@ -28,9 +28,12 @@ const DefaultOrigin = "default"
// Values returns every leaf of e, sorted by key, with its origin.
// used reports whether the program reads a key (nil: every key); a
// default it does not read is left out. Secret values (keys secrets,
// secret, token, password) are replaced by "<redacted>" unless
// secret, token, password, and e.SecretKeys) are replaced by "<redacted>" unless
// showSecrets; a reference that only says where a secret is (env:,
// file:, secret://) is shown.
// file:, secret://) is shown. A leaf that is a list is printed as one
// value, so the same rule is applied inside it: a field of a list entry
// is secret by its name or by its key without the index ("admins.password"
// for the field password of every entry of the list admins).
func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value {
var out []Value
walkLeaves("", e.Merged, func(key string, v any) {
@@ -42,8 +45,12 @@ func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value {
if !u && source == DefaultOrigin {
return
}
if !showSecrets && isSecretKey(key) {
v = redact(v)
if !showSecrets {
if e.isSecret(key) {
v = redact(v)
} else {
v = e.redactWithin(key, v)
}
}
out = append(out, Value{Key: key, Value: v, Source: source, Used: u})
})
@@ -117,6 +124,45 @@ var secretKeys = map[string]bool{"secrets": true, "secret": true, "token": true,
func isSecretKey(key string) bool { return secretKeys[key[strings.LastIndex(key, ".")+1:]] }
// isSecret: a default secret name, or one of e.SecretKeys or a key below
// one.
func (e *Effective) isSecret(key string) bool {
if isSecretKey(key) {
return true
}
for _, k := range e.SecretKeys {
if key == k || strings.HasPrefix(key, k+".") {
return true
}
}
return false
}
// redactWithin redacts the secret fields of the maps inside a list (or
// a map) leaf at key, by the same rule as isSecret. A list entry adds no
// segment to the key. v is copied, never changed.
func (e *Effective) redactWithin(key string, v any) any {
switch x := v.(type) {
case []any:
out := make([]any, len(x))
for i, el := range x {
out[i] = e.redactWithin(key, el)
}
return out
case map[string]any:
out := make(map[string]any, len(x))
for k, el := range x {
if sub := key + "." + k; e.isSecret(sub) {
out[k] = redact(el)
} else {
out[k] = e.redactWithin(sub, el)
}
}
return out
}
return v
}
// redact replaces secret values, keeping references that only say where
// the secret is.
func redact(v any) any {
+9 -1
View File
@@ -38,7 +38,7 @@ the main module's `vX.Y.Z` tags do not version this one. Never move a tag.
| `gui/assets` | `NewResolver(sources...)` over `NewFSSource` (embed.FS), `NewDirSource` (os.Root), `NewZipFileSource`/`NewZipBytesSource`; first source that has a file wins, a read error does not fall through. `ValidatePath` (checked, never cleaned), `Join`, `DetectMIME`. |
| `gui/document` | `Prepare(ctx, res, entry, html, Options{Link})`: rewrites `assets:` / relative references in HTML and CSS (`img`, `srcset`, `script`, `link`, `style`, CSS `url()`/`@import`). Link mode -> `/assets/...` URLs, validated against the resolver; inline mode -> typed `data:` URLs (entry <= 1.5 MiB). |
| `gui/bridge` | `NewRouter(res)`, `Router.Handle("POST /rpc/x", h)`, `Router.SetDocument`, `Router.ServeNative` (for the window's resource handler), `Router.HTML` (Go-rendered fragments through `document`). `NewSession(router, Options)` speaks protocol v1 with the page (`hello`/`ready`, `req`/`res`, `chunk`/`end` streams, `abort`, generations). `InitScript(PageConfig)` is the page side (`bridge.js`). |
| `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`. |
| `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource, FrameFile})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`, `ShowFileDialog` (UI thread) / `ChooseFile` (any goroutine, waits): a native open or save dialog (`FileDialog{Save, Title, Directory, Name, Extensions}`; macOS NSOpenPanel/NSSavePanel as a sheet, Windows GetOpenFileNameW/GetSaveFileNameW), "" when cancelled -- it only returns a path, nothing is read or written. |
## Wiring
@@ -70,6 +70,14 @@ w.Destroy() // then: native window, on the UI thread
The WebView2 user-data folder (`DataPath`) belongs under the program's
`core/paths` cache or data directory (`%LOCALAPPDATA%`, never roaming).
`FrameFile` (since `gui/v0.2.0`) keeps the window's position, size and
maximized state across starts: a small JSON file the program places in
its `core/paths` state directory. It is read at `New` -- a frame that is
on no connected screen any more is ignored and the window opens
centered -- and written shortly after every move or resize and at
`Destroy`. The coordinates are the platform's own (macOS: points from
the bottom left; Windows: `WINDOWPLACEMENT`'s normal position).
## Invariants
- **No listener, no ports, no localhost.** After a transport change,
+3 -1
View File
@@ -2,7 +2,8 @@
#define YETANO_WINDOW_DARWIN_H
#include <stdint.h>
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme);
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme,
int hasFrame, int fx, int fy, int fw, int fh, int zoomed);
void yt_add_script(void *h, const char *js);
void yt_navigate(void *h, const char *url);
void yt_eval(void *h, const char *js);
@@ -17,5 +18,6 @@ void yt_snapshot(void *h, const char *path);
void yt_set_appearance(void *h, int mode);
void yt_accent_color(char *buf, int n);
void yt_set_app_icon(const void *png, int n);
void yt_file_dialog(void *h, int save, const char *title, const char *dir, const char *name, const char *types);
#endif
+89 -3
View File
@@ -9,6 +9,7 @@
// marshalled with dispatch_async onto the main queue.
#import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h>
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
#include "darwin.h"
// Implemented in Go (window_darwin.go).
@@ -18,6 +19,18 @@ extern void ytGoSchemeStop(uintptr_t h, long id);
extern void ytGoDispatch(uintptr_t fn);
extern void ytGoClosed(uintptr_t h);
extern void ytGoSnapshotDone(uintptr_t h, const char *err);
extern void ytGoFrame(uintptr_t h, int x, int y, int w, int hgt, int zoomed);
extern void ytGoFileDone(uintptr_t h, const char *path);
// YTWebView takes the first mouse click in an inactive window: without
// it the click only activates the window, so a page (a dialog shown at
// start) looks dead until clicked twice.
@interface YTWebView : WKWebView
@end
@implementation YTWebView
- (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
@end
@interface YTHost : NSObject <WKScriptMessageHandler, WKURLSchemeHandler, NSWindowDelegate>
@property (assign) uintptr_t goHandle;
@@ -26,6 +39,7 @@ extern void ytGoSnapshotDone(uintptr_t h, const char *err);
@property (strong) NSMutableDictionary<NSNumber *, id<WKURLSchemeTask>> *tasks;
@property (assign) long nextTask;
@property (assign) BOOL closed;
@property (assign) NSRect normalFrame; // the last frame while not zoomed
@end
@implementation YTHost
@@ -67,7 +81,21 @@ extern void ytGoSnapshotDone(uintptr_t h, const char *err);
ytGoSchemeStop(self.goHandle, key.longValue);
}
// The frame is reported after every move and resize; while zoomed, the
// normal frame underneath is kept, so un-zooming returns to it.
- (void)reportFrame {
if (self.closed || !self.window) return;
BOOL zoomed = self.window.isZoomed;
if (!zoomed) self.normalFrame = self.window.frame;
NSRect f = self.normalFrame;
if (f.size.width <= 0) return;
ytGoFrame(self.goHandle, (int)f.origin.x, (int)f.origin.y, (int)f.size.width, (int)f.size.height, zoomed ? 1 : 0);
}
- (void)windowDidMove:(NSNotification *)n { [self reportFrame]; }
- (void)windowDidResize:(NSNotification *)n { [self reportFrame]; }
- (void)windowWillClose:(NSNotification *)n {
[self reportFrame];
if (self.closed) return;
ytGoClosed(self.goHandle);
yt_stop();
@@ -102,7 +130,19 @@ static void ensureApp(void) {
[NSApp finishLaunching];
}
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme) {
// onScreen: at least a 120 x 60 point piece of the frame (with its title
// bar) is on a connected screen -- a frame saved on a display that is
// gone is not restored off screen.
static BOOL onScreen(NSRect f) {
for (NSScreen *s in [NSScreen screens]) {
NSRect i = NSIntersectionRect(f, s.visibleFrame);
if (i.size.width >= 120 && i.size.height >= 60) return YES;
}
return NO;
}
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme,
int hasFrame, int fx, int fy, int fw, int fh, int zoomed) {
@autoreleasepool {
ensureApp();
YTHost *host = [YTHost new];
@@ -115,7 +155,7 @@ void *yt_create(uintptr_t goHandle, const char *title, int width, int height, in
if (debug) [cfg.preferences setValue:@YES forKey:@"developerExtrasEnabled"];
NSRect frame = NSMakeRect(0, 0, width, height);
host.webview = [[WKWebView alloc] initWithFrame:frame configuration:cfg];
host.webview = [[YTWebView alloc] initWithFrame:frame configuration:cfg];
if (@available(macOS 13.3, *)) { if (debug) host.webview.inspectable = YES; }
host.window = [[NSWindow alloc] initWithContentRect:frame
@@ -126,9 +166,17 @@ void *yt_create(uintptr_t goHandle, const char *title, int width, int height, in
host.window.releasedWhenClosed = NO;
host.window.title = str(title);
host.window.contentView = host.webview;
NSRect saved = NSMakeRect(fx, fy, fw, fh);
BOOL restore = hasFrame && onScreen(saved);
if (restore) {
[host.window setFrame:saved display:NO];
} else {
[host.window center];
}
host.normalFrame = host.window.frame;
host.window.delegate = host;
[host.window center];
[host.window makeKeyAndOrderFront:nil];
if (restore && zoomed && !host.window.isZoomed) [host.window zoom:nil];
[NSApp activateIgnoringOtherApps:YES];
return (__bridge_retained void *)host;
}
@@ -171,6 +219,7 @@ void yt_stop(void) {
void yt_destroy(void *h) {
YTHost *host = (__bridge_transfer YTHost *)h; // balances __bridge_retained
[host reportFrame]; // a window ended by Terminate, not closed by the user
host.closed = YES;
for (NSNumber *k in host.tasks.allKeys) {
// Remaining tasks are failed so WebKit does not wait forever.
@@ -280,3 +329,40 @@ void yt_set_app_icon(const void *png, int n) {
if (img) NSApp.applicationIconImage = img;
}
}
// --- file dialogs ------------------------------------------------------------
// yt_file_dialog shows an open (save = 0) or save panel as a sheet on the
// window. dir: the folder to start in, name: a save panel's suggested file
// name, types: allowed file extensions, comma-separated ("" = any). The
// chosen path, or NULL when cancelled, goes to ytGoFileDone.
void yt_file_dialog(void *h, int save, const char *title, const char *dir, const char *name, const char *types) {
YTHost *host = (__bridge YTHost *)h;
uintptr_t gh = host.goHandle;
NSSavePanel *panel;
if (save) {
panel = [NSSavePanel savePanel];
if (name && name[0]) panel.nameFieldStringValue = str(name);
} else {
NSOpenPanel *open = [NSOpenPanel openPanel];
open.canChooseFiles = YES;
open.canChooseDirectories = NO;
open.allowsMultipleSelection = NO;
open.resolvesAliases = YES;
panel = open;
}
if (title && title[0]) { panel.title = str(title); panel.message = str(title); }
if (dir && dir[0]) panel.directoryURL = [NSURL fileURLWithPath:str(dir) isDirectory:YES];
if (types && types[0]) {
NSMutableArray<UTType *> *uts = [NSMutableArray array];
for (NSString *ext in [str(types) componentsSeparatedByString:@","]) {
UTType *t = [UTType typeWithFilenameExtension:ext];
if (t) [uts addObject:t];
}
if (uts.count) panel.allowedContentTypes = uts;
}
[panel beginSheetModalForWindow:host.window completionHandler:^(NSModalResponse r) {
if (r != NSModalResponseOK || !panel.URL) { ytGoFileDone(gh, NULL); return; }
ytGoFileDone(gh, panel.URL.path.fileSystemRepresentation);
}];
}
+115
View File
@@ -0,0 +1,115 @@
//go:build windows
package window
import (
"fmt"
"strings"
"unsafe"
"golang.org/x/sys/windows"
)
var (
comdlg32 = windows.NewLazySystemDLL("comdlg32.dll")
pGetOpenFile = comdlg32.NewProc("GetOpenFileNameW")
pGetSaveFile = comdlg32.NewProc("GetSaveFileNameW")
pCommDlgExtErr = comdlg32.NewProc("CommDlgExtendedError")
errNoFileDialog = fmt.Errorf("window: file dialog failed")
)
// openFileName is OPENFILENAMEW (commdlg.h).
type openFileName struct {
lStructSize uint32
hwndOwner uintptr
hInstance uintptr
lpstrFilter *uint16
lpstrCustomFilter *uint16
nMaxCustFilter uint32
nFilterIndex uint32
lpstrFile *uint16
nMaxFile uint32
lpstrFileTitle *uint16
nMaxFileTitle uint32
lpstrInitialDir *uint16
lpstrTitle *uint16
flags uint32
nFileOffset uint16
nFileExtension uint16
lpstrDefExt *uint16
lCustData uintptr
lpfnHook uintptr
lpTemplateName *uint16
pvReserved uintptr
dwReserved uint32
flagsEx uint32
}
const (
ofnOverwritePrompt = 0x00000002
ofnNoChangeDir = 0x00000008
ofnPathMustExist = 0x00000800
ofnFileMustExist = 0x00001000
ofnExplorer = 0x00080000
)
// fileFilter is the dialog's filter list: the allowed extensions, then
// all files; pairs of display text and pattern, each NUL-terminated,
// the list ending with an extra NUL.
func fileFilter(exts []string) []uint16 {
var b strings.Builder
if len(exts) > 0 {
pats := make([]string, len(exts))
for i, e := range exts {
pats[i] = "*." + strings.TrimPrefix(e, ".")
}
p := strings.Join(pats, ";")
b.WriteString(p + " (" + p + ")\x00" + p + "\x00")
}
b.WriteString("All files (*.*)\x00*.*\x00\x00")
return windows.StringToUTF16(b.String())
}
// FileDialog shows the common open or save dialog, modal to the window
// (it runs its own message loop on the UI thread); done runs right after.
func (b *winBackend) FileDialog(d FileDialog, done func(string, error)) {
buf := make([]uint16, 32768)
if d.Save && d.Name != "" {
copy(buf[:len(buf)-1], windows.StringToUTF16(d.Name))
}
filter := fileFilter(d.Extensions)
ofn := openFileName{
hwndOwner: b.hwnd,
lpstrFilter: &filter[0],
nFilterIndex: 1,
lpstrFile: &buf[0],
nMaxFile: uint32(len(buf)),
flags: ofnExplorer | ofnNoChangeDir | ofnPathMustExist,
}
ofn.lStructSize = uint32(unsafe.Sizeof(ofn))
if d.Title != "" {
ofn.lpstrTitle, _ = windows.UTF16PtrFromString(d.Title)
}
if d.Directory != "" {
ofn.lpstrInitialDir, _ = windows.UTF16PtrFromString(d.Directory)
}
proc := pGetOpenFile
if d.Save {
proc = pGetSaveFile
ofn.flags |= ofnOverwritePrompt
if len(d.Extensions) > 0 {
ofn.lpstrDefExt, _ = windows.UTF16PtrFromString(strings.TrimPrefix(d.Extensions[0], "."))
}
} else {
ofn.flags |= ofnFileMustExist
}
if r, _, _ := proc.Call(uintptr(unsafe.Pointer(&ofn))); r == 0 {
if code, _, _ := pCommDlgExtErr.Call(); code != 0 {
done("", fmt.Errorf("%w: CommDlgExtendedError 0x%x", errNoFileDialog, code))
return
}
done("", nil) // cancelled
return
}
done(windows.UTF16ToString(buf), nil)
}
+22
View File
@@ -0,0 +1,22 @@
//go:build windows
package window
import "testing"
func TestFileFilter(t *testing.T) {
raw := fileFilter([]string{"pdf", ".txt"})
s := string(utf16Runes(raw))
want := "*.pdf;*.txt (*.pdf;*.txt)\x00*.pdf;*.txt\x00All files (*.*)\x00*.*\x00\x00\x00"
if s != want {
t.Errorf("filter = %q, want %q", s, want)
}
}
func utf16Runes(u []uint16) []rune {
r := make([]rune, len(u))
for i, c := range u {
r[i] = rune(c)
}
return r
}
+116
View File
@@ -0,0 +1,116 @@
package window
import (
"encoding/json"
"os"
"path/filepath"
"sync"
"time"
)
// Frame is a window's position and size in the platform's own screen
// coordinates (macOS: points, origin bottom left; Windows: pixels of the
// virtual screen, origin top left). It is only ever read back on the
// platform that wrote it. Maximized (macOS: zoomed) keeps the normal
// frame underneath, so un-maximizing returns to it.
type Frame struct {
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
Maximized bool `json:"maximized,omitempty"`
}
// minFrame is the smallest frame restored; anything smaller is a broken
// file, not a window someone made.
const minFrame = 200
func (f Frame) usable() bool { return f.Width >= minFrame && f.Height >= minFrame }
// loadFrame reads a frame file written by frameSaver. A missing,
// unreadable or implausible file is no frame: the window opens with its
// default size, centered.
func loadFrame(path string) (Frame, bool) {
if path == "" {
return Frame{}, false
}
data, err := os.ReadFile(path)
if err != nil {
return Frame{}, false
}
var f Frame
if json.Unmarshal(data, &f) != nil || !f.usable() {
return Frame{}, false
}
return f, true
}
// frameSaver writes the window's frame to its file, a moment after the
// last move or resize (a drag reports many), and once more at Destroy.
type frameSaver struct {
path string
mu sync.Mutex
last Frame
dirty bool
timer *time.Timer
}
const frameSaveDelay = 400 * time.Millisecond
func (s *frameSaver) changed(f Frame) {
if s == nil || !f.usable() {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if f == s.last && !s.dirty {
return
}
s.last, s.dirty = f, true
if s.timer == nil {
s.timer = time.AfterFunc(frameSaveDelay, s.flush)
} else {
s.timer.Reset(frameSaveDelay)
}
}
// flush writes a pending frame (temp file + rename, so a crash never
// leaves half a file). Errors are not fatal: the next start just opens
// with the default frame.
func (s *frameSaver) flush() {
if s == nil {
return
}
s.mu.Lock()
if s.timer != nil {
s.timer.Stop()
}
f, dirty := s.last, s.dirty
s.dirty = false
s.mu.Unlock()
if !dirty {
return
}
data, err := json.Marshal(f)
if err != nil {
return
}
if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil {
debugf("window: frame file: %v", err)
return
}
tmp := s.path + ".tmp"
if err := os.WriteFile(tmp, append(data, '\n'), 0o644); err != nil {
debugf("window: frame file: %v", err)
return
}
if err := os.Rename(tmp, s.path); err != nil {
debugf("window: frame file: %v", err)
}
}
func debugf(format string, args ...any) {
if Debugf != nil {
Debugf(format, args...)
}
}
+40
View File
@@ -0,0 +1,40 @@
package window
import (
"os"
"path/filepath"
"testing"
)
func TestFrameFileRoundTrip(t *testing.T) {
path := filepath.Join(t.TempDir(), "state", "window.json")
if _, ok := loadFrame(path); ok {
t.Fatal("a missing file is a frame")
}
s := &frameSaver{path: path}
s.changed(Frame{X: 10, Y: 20, Width: 300, Height: 200})
s.changed(Frame{X: 40, Y: 50, Width: 1200, Height: 800, Maximized: true}) // the last one wins
s.flush()
f, ok := loadFrame(path)
if !ok || f != (Frame{X: 40, Y: 50, Width: 1200, Height: 800, Maximized: true}) {
t.Fatalf("loaded %+v, %v", f, ok)
}
if _, err := os.Stat(path + ".tmp"); !os.IsNotExist(err) {
t.Errorf("temp file left behind: %v", err)
}
// Too small or broken: no frame, the window opens with its default.
for _, data := range []string{`{"x":0,"y":0,"width":50,"height":40}`, `not json`, ``} {
if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
t.Fatal(err)
}
if f, ok := loadFrame(path); ok {
t.Errorf("%q loaded as %+v", data, f)
}
}
s.changed(Frame{Width: 10, Height: 10}) // ignored
s.flush()
if data, _ := os.ReadFile(path); string(data) != "" {
t.Errorf("an unusable frame was written: %q", data)
}
}
+79 -1
View File
@@ -53,6 +53,16 @@ type Options struct {
DataPath string // WebView2 user data folder (Windows)
OnMessage func(msg string)
Resource ResourceHandler // nil: no native resource handler
// FrameFile, if set, keeps the window's position and size across
// starts: read at New (a frame that is no longer on any screen is
// ignored), written a moment after every move or resize and at
// Destroy. A small JSON file (Frame); the program picks the path,
// e.g. in its state directory.
FrameFile string
// Set by New for the backend.
restore *Frame // the frame to open with, nil: default, centered
onFrame func(Frame) // the backend reports a moved or resized window
}
type backend interface {
@@ -67,6 +77,7 @@ type backend interface {
// Window is a guarded native WebView window.
type Window struct {
frames *frameSaver
mu sync.Mutex
b backend
alive bool
@@ -92,11 +103,20 @@ func New(opt Options) (*Window, error) {
if opt.Width == 0 {
opt.Width, opt.Height = 1100, 820
}
var frames *frameSaver
if opt.FrameFile != "" {
frames = &frameSaver{path: opt.FrameFile}
if f, ok := loadFrame(opt.FrameFile); ok {
opt.restore = &f
frames.last = f
}
opt.onFrame = frames.changed
}
b, name, base, err := newBackend(opt)
if err != nil {
return nil, err
}
return &Window{b: b, alive: true, name: name, base: base}, nil
return &Window{b: b, alive: true, name: name, base: base, frames: frames}, nil
}
// Backend names the native backend.
@@ -156,6 +176,7 @@ func (w *Window) Destroy() {
w.alive = false
w.mu.Unlock()
w.b.Destroy()
w.frames.flush()
}
// snapshotter is implemented by backends that can render the page to PNG.
@@ -198,6 +219,63 @@ func SetAppIcon(png []byte) { setAppIcon(png) }
// unknown. Safe to call before a window exists.
func AccentColor() string { return accentColor() }
// FileDialog describes a native open or save dialog.
type FileDialog struct {
Save bool // a save dialog; otherwise open one existing file
Title string // the prompt; "" for the system's
Directory string // the folder to start in; "" for the system's choice
Name string // save: the suggested file name
Extensions []string // allowed extensions without the dot ("pdf"); empty: any file
}
// ErrDialogOpen: a file dialog of this window is already open.
var ErrDialogOpen = errors.New("window: a file dialog is already open")
// fileDialoger is implemented by backends with native file dialogs.
type fileDialoger interface {
FileDialog(d FileDialog, done func(path string, err error))
}
// ShowFileDialog shows a native open or save dialog for the window (UI
// thread; one at a time). done runs on the UI thread with the chosen
// path, or "" and a nil error when the user cancelled. A save dialog
// has asked about replacing an existing file already; nothing is read
// or written here -- that is the program's choice.
func (w *Window) ShowFileDialog(d FileDialog, done func(path string, err error)) {
f, ok := w.b.(fileDialoger)
if !ok {
done("", errors.New("window: file dialogs not supported by "+w.name))
return
}
f.FileDialog(d, done)
}
// ChooseFile shows a file dialog from any goroutine and waits for the
// user: the chosen path, or "" and nil when cancelled. ctx ending (the
// request was dropped) stops the wait, not the dialog.
func (w *Window) ChooseFile(ctx context.Context, d FileDialog) (string, error) {
type result struct {
path string
err error
}
ch := make(chan result, 1)
w.mu.Lock()
alive := w.alive
w.mu.Unlock()
if !alive {
return "", errors.New("window: destroyed")
}
w.Dispatch(func() {
w.ShowFileDialog(d, func(p string, err error) { ch <- result{p, err} })
})
select {
case r := <-ch:
return r.path, r.err
case <-ctx.Done():
return "", ctx.Err()
}
}
// DroppedDispatches counts Dispatch calls that arrived after Destroy.
func (w *Window) DroppedDispatches() int {
w.mu.Lock()
+67 -2
View File
@@ -4,7 +4,7 @@ package window
/*
#cgo CFLAGS: -x objective-c -fobjc-arc
#cgo LDFLAGS: -framework Cocoa -framework WebKit
#cgo LDFLAGS: -framework Cocoa -framework WebKit -framework UniformTypeIdentifiers
#include <stdlib.h>
#include "darwin.h"
*/
@@ -16,6 +16,7 @@ import (
"net/http"
"runtime"
"runtime/cgo"
"strings"
"sync"
"unsafe"
)
@@ -35,6 +36,7 @@ type darwinBackend struct {
mu sync.RWMutex // guards h against Destroy while a goroutine calls into ObjC
snapDone func(error)
fileDone func(path string, err error)
}
// with runs f with the live host pointer, or not at all after Destroy.
@@ -63,7 +65,16 @@ func newBackend(opt Options) (backend, string, string, error) {
if opt.Debug {
debug = 1
}
b.h = C.yt_create(C.uintptr_t(b.handle), title, C.int(opt.Width), C.int(opt.Height), C.int(debug), scheme)
var has, zoomed C.int
var f Frame
if opt.restore != nil {
has, f = 1, *opt.restore
if f.Maximized {
zoomed = 1
}
}
b.h = C.yt_create(C.uintptr_t(b.handle), title, C.int(opt.Width), C.int(opt.Height), C.int(debug), scheme,
has, C.int(f.X), C.int(f.Y), C.int(f.Width), C.int(f.Height), zoomed)
if b.h == nil {
b.handle.Delete()
return nil, "", "", errUnavailable("WKWebView could not be created")
@@ -122,6 +133,14 @@ func ytGoDispatch(fn C.uintptr_t) {
f()
}
//export ytGoFrame
func ytGoFrame(h C.uintptr_t, x, y, w, hgt, zoomed C.int) {
b := cgo.Handle(h).Value().(*darwinBackend)
if b.opt.onFrame != nil {
b.opt.onFrame(Frame{X: int(x), Y: int(y), Width: int(w), Height: int(hgt), Maximized: zoomed != 0})
}
}
//export ytGoMessage
func ytGoMessage(h C.uintptr_t, msg *C.char) {
b := cgo.Handle(h).Value().(*darwinBackend)
@@ -281,3 +300,49 @@ func (t *darwinTask) Close(err error) {
}
t.b.with(func(h unsafe.Pointer) { C.yt_task_finish(h, C.long(t.id), ce) })
}
// FileDialog shows a native open or save panel as a sheet on the window;
// done runs on the UI thread.
func (b *darwinBackend) FileDialog(d FileDialog, done func(string, error)) {
b.mu.Lock()
if b.fileDone != nil {
b.mu.Unlock()
done("", ErrDialogOpen)
return
}
b.fileDone = done
b.mu.Unlock()
save := 0
if d.Save {
save = 1
}
title, dir, name, types := cstr(d.Title), cstr(d.Directory), cstr(d.Name), cstr(strings.Join(d.Extensions, ","))
defer func() {
for _, c := range []*C.char{title, dir, name, types} {
C.free(unsafe.Pointer(c))
}
}()
if !b.with(func(h unsafe.Pointer) { C.yt_file_dialog(h, C.int(save), title, dir, name, types) }) {
b.mu.Lock()
b.fileDone = nil
b.mu.Unlock()
done("", errUnavailable("file dialog: the window is gone"))
}
}
//export ytGoFileDone
func ytGoFileDone(h C.uintptr_t, path *C.char) {
b := cgo.Handle(h).Value().(*darwinBackend)
b.mu.Lock()
done := b.fileDone
b.fileDone = nil
b.mu.Unlock()
if done == nil {
return
}
if path == nil {
done("", nil)
return
}
done(C.GoString(path), nil)
}
+71 -1
View File
@@ -56,6 +56,9 @@ var (
pDwmSetAttribute = dwmapi.NewProc("DwmSetWindowAttribute")
pSetWindowPos = user32.NewProc("SetWindowPos")
pGetDpiForSystem = user32.NewProc("GetDpiForSystem")
pGetPlacement = user32.NewProc("GetWindowPlacement")
pSetPlacement = user32.NewProc("SetWindowPlacement")
pMonitorFromRect = user32.NewProc("MonitorFromRect")
)
func setAppIcon([]byte) {} // the icon comes from the .exe resources (RT_GROUP_ICON "APP")
@@ -64,6 +67,7 @@ const (
wmDestroy = 0x0002
wmMove = 0x0003
wmSize = 0x0005
wmSetFocus = 0x0007
wmClose = 0x0010
wmQuit = 0x0012
wmMoving = 0x0216
@@ -168,7 +172,9 @@ func newBackend(opt Options) (backend, string, string, error) {
windowsMu.Lock()
byHWND[hwnd] = b
windowsMu.Unlock()
pShowWindow.Call(hwnd, swShow)
if f := opt.restore; f == nil || !restorePlacement(hwnd, *f) {
pShowWindow.Call(hwnd, swShow)
}
pUpdateWindow.Call(hwnd)
pSetFocus.Call(hwnd)
@@ -188,6 +194,7 @@ func newBackend(opt Options) (backend, string, string, error) {
return nil, "", "", errors.New("window: WebView2 could not be created (is the Microsoft Edge WebView2 Runtime installed?)")
}
c.Resize()
c.Focus() // the window got WM_SETFOCUS before the control existed
if s, err := c.GetSettings(); err == nil {
_ = s.PutAreDevToolsEnabled(opt.Debug)
_ = s.PutAreDefaultContextMenusEnabled(opt.Debug)
@@ -209,14 +216,25 @@ func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
if b.chromium != nil {
b.chromium.Resize()
}
b.reportFrame()
case wmMove, wmMoving:
if b.chromium != nil {
_ = b.chromium.NotifyParentWindowPositionChanged()
}
b.reportFrame()
case wmSetFocus:
// The keyboard focus belongs in the WebView2 control (its own
// child window): without this a page gets no keys after the
// start or after Alt-Tab until it is clicked.
if b.chromium != nil {
b.chromium.Focus()
}
return 0
case wmApp:
b.runQueue()
return 0
case wmClose:
b.reportFrame()
pDestroyWindow.Call(hwnd)
return 0
case wmDestroy:
@@ -233,6 +251,57 @@ func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
return r
}
// windowPlacement is WINDOWPLACEMENT. rcNormalPosition is the restored
// (not maximized) frame in workspace coordinates; Get and Set use the
// same ones, so a saved frame comes back where it was.
type windowPlacement struct {
length uint32
flags uint32
showCmd uint32
ptMinPosition [2]int32
ptMaxPosition [2]int32
rcNormalPosition [4]int32 // left, top, right, bottom
}
const (
swShowNormal = 1
swShowMinimized = 2
swShowMaximized = 3
wpfRestoreToMaximize = 0x0002
)
// reportFrame hands the window's normal frame and maximized state to
// Options.FrameFile's saver.
func (b *winBackend) reportFrame() {
if b.opt.onFrame == nil {
return
}
var wp windowPlacement
wp.length = uint32(unsafe.Sizeof(wp))
if r, _, _ := pGetPlacement.Call(b.hwnd, uintptr(unsafe.Pointer(&wp))); r == 0 {
return
}
rc := wp.rcNormalPosition
maximized := wp.showCmd == swShowMaximized || (wp.showCmd == swShowMinimized && wp.flags&wpfRestoreToMaximize != 0)
b.opt.onFrame(Frame{X: int(rc[0]), Y: int(rc[1]), Width: int(rc[2] - rc[0]), Height: int(rc[3] - rc[1]), Maximized: maximized})
}
// restorePlacement shows the window with a saved frame, when that frame
// is still on a monitor (MONITOR_DEFAULTTONULL); false: show it as new.
func restorePlacement(hwnd uintptr, f Frame) bool {
rc := [4]int32{int32(f.X), int32(f.Y), int32(f.X + f.Width), int32(f.Y + f.Height)}
if m, _, _ := pMonitorFromRect.Call(uintptr(unsafe.Pointer(&rc)), 0); m == 0 {
return false
}
wp := windowPlacement{showCmd: swShowNormal, rcNormalPosition: rc}
if f.Maximized {
wp.showCmd = swShowMaximized
}
wp.length = uint32(unsafe.Sizeof(wp))
r, _, _ := pSetPlacement.Call(hwnd, uintptr(unsafe.Pointer(&wp)))
return r != 0
}
func (b *winBackend) runQueue() {
b.mu.Lock()
q := b.queue
@@ -277,6 +346,7 @@ func (b *winBackend) Destroy() {
b.destroying = true
b.mu.Unlock()
if ok, _, _ := pIsWindow.Call(b.hwnd); ok != 0 {
b.reportFrame() // a window ended by Terminate, not closed by the user
pDestroyWindow.Call(b.hwnd)
}
windowsMu.Lock()
+36
View File
@@ -0,0 +1,36 @@
# yetano.dev/yetano/core/solutions
The engine of the **Yetano Solutions Guide** (Yetano Knowledge &
Solutions): from what a user wants to achieve, through questions, rules
and existing knowledge, to native, checked configuration. Design and
requirements: `docs/knowledge-solutions/` in the meta-repo; the catalog
it reads: `assets/solutions/`.
```text
module yetano.dev/yetano/core/solutions tags: solutions/v0.1.0, ... go 1.25
```
A nested module of the core repository (like `core/gui`, `core/tui`):
standard library, `gopkg.in/yaml.v3` and `yetano.dev/yetano/core`
(`secretref`, `paths`). No cgo; builds for js/wasm.
| Package | What |
|---|---|
| `catalog` | manifest model, strict loader, Big Picture view, validation, condition language, JSON Schemas |
| `ref` | `yetano:<kind>/<path>[#section][@version]` references, heading slugs |
| `engine` | `Evaluate` (questions, rules, packages, capabilities, providers, modules, configuration with origins, graph, steps, checks), `Generate`/`Write` (lock, plan, handbook, hand-edit protection), presets |
| `knowledge` | index over catalog, Big Picture and manuals; `Resolve`, `Read`, `Search`, backlinks, `Lint`, coverage |
| `store` | instances, sessions, presets, favorites, recent as files |
| `cli` | `solution`, `task`, `knowledge`, `open` with yet's conventions (`cli.Run`) |
| `cmd/yetano-solutions` | the same commands standalone (catalog CI, development) |
The engine is pure: it never runs a command and never opens a network
connection (tested); only the CLI's `doctor` resolves DNS and probes
local ports.
```sh
go test ./...
go run ./cmd/yetano-solutions --catalog ../../assets/solutions solution setup mail-server
```
Tags carry the `solutions/` prefix; never move a tag.
+219
View File
@@ -0,0 +1,219 @@
package catalog
import (
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"gopkg.in/yaml.v3"
)
// BigPicture is the read-only view of assets/bigpicture/verse that the
// guide builds on (ADR-0002). Validation of these files belongs to bpgen;
// here they are decoded leniently and only the fields the guide uses are
// kept.
type BigPicture struct {
Dir string `json:"-"`
Title string `json:"title"`
WebPath string `json:"webPath"` // "map/"
Topics map[string]*BPTopic `json:"topics"`
Stories map[string]*BPStory `json:"stories"`
Products map[string]*BPProduct `json:"products"`
Connections []BPConnection `json:"connections"`
Interfaces map[string]BPInterface `json:"interfaces"`
Files []FileHash `json:"-"`
}
// BPTopic is a Big Picture topic.
type BPTopic struct {
ID string `yaml:"id" json:"id"`
Title string `yaml:"title" json:"title"`
Summary string `yaml:"summary" json:"summary"`
EntryStory string `yaml:"entryStory" json:"entryStory,omitempty"`
}
// BPStory is a Big Picture goal (user story).
type BPStory struct {
ID string `yaml:"id" json:"id"`
Title string `yaml:"title" json:"title"`
Intent string `yaml:"intent" json:"intent"`
Outcome string `yaml:"outcome" json:"outcome"`
Explanation string `yaml:"explanation" json:"explanation,omitempty"`
PrimaryTopic string `yaml:"primaryTopic" json:"primaryTopic"`
RelatedTopics []string `yaml:"relatedTopics" json:"relatedTopics,omitempty"`
Roles []struct {
ID string `yaml:"id" json:"id"`
Product string `yaml:"product" json:"product"`
Contribution string `yaml:"contribution" json:"contribution"`
Participation string `yaml:"participation" json:"participation"`
} `yaml:"roles" json:"roles"`
Next []struct {
Story string `yaml:"story" json:"story"`
Reason string `yaml:"reason" json:"reason"`
} `yaml:"next" json:"next,omitempty"`
}
// BPProduct is a Big Picture program.
type BPProduct struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name" json:"name"`
Summary string `yaml:"summary" json:"summary"`
PrimaryTopic string `yaml:"primaryTopic" json:"primaryTopic"`
Tasks []string `yaml:"tasks" json:"tasks,omitempty"`
Links []struct {
Title string `yaml:"title" json:"title"`
Href string `yaml:"href" json:"href"`
} `yaml:"links" json:"links,omitempty"`
}
// BPConnection is a technical relation between programs/interfaces.
type BPConnection struct {
ID string `yaml:"id" json:"id"`
From string `yaml:"from" json:"from"`
To string `yaml:"to" json:"to"`
Type string `yaml:"type" json:"type"`
Label string `yaml:"label" json:"label"`
Scope string `yaml:"scope" json:"scope"`
Review string `yaml:"review" json:"review"`
Stories []string `yaml:"stories" json:"stories,omitempty"`
}
// BPInterface is a shared interface (OCI registry, ...).
type BPInterface struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name" json:"name"`
Summary string `yaml:"summary" json:"summary"`
}
// LoadBigPicture reads dir/manifest.yaml and the files it names.
func LoadBigPicture(dir string) (*BigPicture, error) {
bp := &BigPicture{
Dir: dir, WebPath: "map/",
Topics: map[string]*BPTopic{}, Stories: map[string]*BPStory{},
Products: map[string]*BPProduct{}, Interfaces: map[string]BPInterface{},
}
var manifest struct {
Title string `yaml:"title"`
Content struct {
Topics string `yaml:"topics"`
Products string `yaml:"products"`
Stories string `yaml:"stories"`
Connections string `yaml:"connections"`
} `yaml:"content"`
}
if err := bp.read("manifest.yaml", &manifest); err != nil {
return nil, err
}
bp.Title = manifest.Title
var topics struct {
Topics []*BPTopic `yaml:"topics"`
}
if err := bp.read(manifest.Content.Topics, &topics); err != nil {
return nil, err
}
for _, t := range topics.Topics {
bp.Topics[t.ID] = t
}
if err := bp.readDir(manifest.Content.Products, func(name string) error {
var p BPProduct
if err := bp.read(name, &p); err != nil {
return err
}
bp.Products[p.ID] = &p
return nil
}); err != nil {
return nil, err
}
if err := bp.readDir(manifest.Content.Stories, func(name string) error {
var s BPStory
if err := bp.read(name, &s); err != nil {
return err
}
bp.Stories[s.ID] = &s
return nil
}); err != nil {
return nil, err
}
var conns struct {
Interfaces []BPInterface `yaml:"interfaces"`
Connections []BPConnection `yaml:"connections"`
}
if manifest.Content.Connections != "" {
if err := bp.read(manifest.Content.Connections, &conns); err != nil {
return nil, err
}
}
for _, i := range conns.Interfaces {
bp.Interfaces[i.ID] = i
}
bp.Connections = conns.Connections
sort.Slice(bp.Files, func(i, j int) bool { return bp.Files[i].Path < bp.Files[j].Path })
return bp, nil
}
func (bp *BigPicture) read(name string, v any) error {
if name == "" {
return fmt.Errorf("big picture: manifest names no file")
}
b, err := os.ReadFile(filepath.Join(bp.Dir, name))
if err != nil {
return fmt.Errorf("big picture: %w", err)
}
if len(b) > MaxFileSize {
return fmt.Errorf("big picture: %s too large", name)
}
bp.Files = append(bp.Files, FileHash{Path: "bigpicture:" + filepath.ToSlash(name), Hash: sha(b)})
if err := yaml.Unmarshal(b, v); err != nil {
return fmt.Errorf("big picture: %s: %w", name, err)
}
return nil
}
func (bp *BigPicture) readDir(sub string, fn func(string) error) error {
ents, err := os.ReadDir(filepath.Join(bp.Dir, sub))
if err != nil {
return fmt.Errorf("big picture: %w", err)
}
for _, e := range ents {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".yaml") {
continue
}
if err := fn(filepath.Join(sub, e.Name())); err != nil {
return err
}
}
return nil
}
// Has reports whether a Big Picture element ID exists.
func (bp *BigPicture) Has(id string) bool {
if bp == nil {
return false
}
if _, ok := bp.Topics[id]; ok {
return true
}
if _, ok := bp.Stories[id]; ok {
return true
}
if _, ok := bp.Products[id]; ok {
return true
}
_, ok := bp.Interfaces[id]
return ok
}
// Fragment is the map URL fragment for an element (story.x -> story=x).
func (bp *BigPicture) Fragment(id string) string {
kind, slug, ok := strings.Cut(id, ".")
if !ok {
return ""
}
switch kind {
case "topic", "story", "product", "interface":
return kind + "=" + slug
}
return ""
}
+61
View File
@@ -0,0 +1,61 @@
package catalog
import "testing"
func TestCond(t *testing.T) {
env := Env{Answers: map[string]any{"a": "x", "n": 3, "l": []any{"p", "q"}, "b": true, "e": ""}, Mode: LevelGuided}
cases := []struct {
c Cond
want bool
}{
{Cond{}, true},
{Cond{"a": "x"}, true},
{Cond{"a": "y"}, false},
{Cond{"a": []any{"y", "x"}}, true},
{Cond{"l": "q"}, true},
{Cond{"l": "z"}, false},
{Cond{"a": map[string]any{"not": "x"}}, false},
{Cond{"n": map[string]any{"gte": 3, "lt": 4}}, true},
{Cond{"l": map[string]any{"count_gte": 2}}, true},
{Cond{"e": map[string]any{"set": false}}, true},
{Cond{"missing": map[string]any{"set": true}}, false},
{Cond{"b": true}, true},
{Cond{"b": "true"}, true},
{Cond{"any": []any{map[string]any{"a": "y"}, map[string]any{"n": 3}}}, true},
{Cond{"all": []any{map[string]any{"a": "x"}, map[string]any{"n": 4}}}, false},
{Cond{"not": map[string]any{"a": "x"}}, false},
{Cond{"$mode": "guided"}, true},
}
for i, c := range cases {
got, err := c.c.Eval(env)
if err != nil || got != c.want {
t.Errorf("%d %v: got %v %v", i, c.c, got, err)
}
}
if _, err := (Cond{"a": map[string]any{"regex": "x"}}).Eval(env); err == nil {
t.Error("unknown operator accepted")
}
deep := Cond{"a": "x"}
for i := 0; i < MaxCondDepth+2; i++ {
deep = Cond{"not": map[string]any(deep)}
}
if _, err := deep.Eval(env); err == nil {
t.Error("unbounded nesting accepted")
}
if r := (Cond{"any": []any{map[string]any{"x": 1}}, "y": 2, "$mode": "q"}).Refs(); len(r) != 2 || r[0] != "x" || r[1] != "y" {
t.Errorf("refs %v", r)
}
}
func TestSafeRelPath(t *testing.T) {
for _, ok := range []string{"a/b.yaml", "yamase/yamase.yaml"} {
if !SafeRelPath(ok) {
t.Errorf("%s rejected", ok)
}
}
for _, bad := range []string{"", "/etc/passwd", "../x", "a/../../x", "a/./b", "a//b", ".hidden/x", `a\b`, "c:/x"} {
if SafeRelPath(bad) {
t.Errorf("%q accepted", bad)
}
}
}
+323
View File
@@ -0,0 +1,323 @@
package catalog
import (
"fmt"
"sort"
"strconv"
"strings"
)
// Cond is a condition over wizard answers (ADR-0003). It is plain data:
//
// {q: v} answer equals v (a multiselect answer: contains v)
// {q: [a, b]} answer is one of a, b (multiselect: contains one)
// {q: {in: [..]}} same as a list
// {q: {not: v}} answer is not v (not one of a list)
// {q: {set: true|false}} answer is (not) given and non-empty
// {q: {gt|gte|lt|lte: n}} numeric comparison
// {q: {count_gte|count_lte: n}} number of list items
// {all: [c, ..]} {any: [c, ..]} {not: c}
// {$mode: guided} wizard mode; {$platform: linux}
//
// Several keys in one map must all hold. An empty condition is true.
type Cond map[string]any
// Env is what a condition is evaluated against.
type Env struct {
Answers map[string]any
Mode Level
Platform string
}
// MaxCondDepth bounds nesting (RULE-08).
const MaxCondDepth = 16
// Eval evaluates c. Errors are malformed conditions (the linter reports
// them before a catalog is used).
func (c Cond) Eval(env Env) (bool, error) { return evalMap(map[string]any(c), env, 0) }
// Holds is Eval for callers that validated the catalog: a malformed
// condition counts as false.
func (c Cond) Holds(env Env) bool {
ok, err := c.Eval(env)
return err == nil && ok
}
func evalMap(m map[string]any, env Env, depth int) (bool, error) {
if depth > MaxCondDepth {
return false, fmt.Errorf("condition nested deeper than %d", MaxCondDepth)
}
keys := sortedKeys(m)
for _, k := range keys {
v := m[k]
var ok bool
var err error
switch k {
case "all", "any":
list, isList := v.([]any)
if !isList {
return false, fmt.Errorf("%s: want a list of conditions", k)
}
ok = k == "all"
for _, item := range list {
sub, isMap := asMap(item)
if !isMap {
return false, fmt.Errorf("%s: want a list of conditions", k)
}
r, err := evalMap(sub, env, depth+1)
if err != nil {
return false, err
}
if k == "all" && !r {
ok = false
break
}
if k == "any" && r {
ok = true
break
}
}
case "not":
sub, isMap := asMap(v)
if !isMap {
return false, fmt.Errorf("not: want a condition")
}
r, err := evalMap(sub, env, depth+1)
if err != nil {
return false, err
}
ok = !r
case "$mode":
ok, err = match(string(env.Mode), v)
case "$platform":
ok, err = match(env.Platform, v)
default:
ok, err = match(env.Answers[k], v)
}
if err != nil {
return false, fmt.Errorf("%s: %w", k, err)
}
if !ok {
return false, nil
}
}
return true, nil
}
// match compares one answer with a condition value.
func match(answer any, want any) (bool, error) {
if ops, ok := asMap(want); ok {
for _, op := range sortedKeys(ops) {
arg := ops[op]
var r bool
switch op {
case "in":
r = matchAny(answer, arg)
case "not":
r = !matchAny(answer, arg)
case "set":
b, isBool := arg.(bool)
if !isBool {
return false, fmt.Errorf("set: want true or false")
}
r = IsSet(answer) == b
case "gt", "gte", "lt", "lte":
a, aok := toFloat(answer)
n, nok := toFloat(arg)
if !nok {
return false, fmt.Errorf("%s: want a number", op)
}
if !aok {
r = false
break
}
switch op {
case "gt":
r = a > n
case "gte":
r = a >= n
case "lt":
r = a < n
case "lte":
r = a <= n
}
case "count_gte", "count_lte":
n, nok := toFloat(arg)
if !nok {
return false, fmt.Errorf("%s: want a number", op)
}
cnt := float64(len(asList(answer)))
if op == "count_gte" {
r = cnt >= n
} else {
r = cnt <= n
}
default:
return false, fmt.Errorf("unknown operator %q", op)
}
if !r {
return false, nil
}
}
return true, nil
}
return matchAny(answer, want), nil
}
// matchAny: want is a scalar or a list of scalars; answer a scalar or list.
func matchAny(answer any, want any) bool {
wants := asList(want)
if want != nil && len(wants) == 0 {
if _, isList := want.([]any); !isList {
wants = []any{want}
}
}
answers := asList(answer)
if _, isList := answer.([]any); !isList {
if _, isStrList := answer.([]string); !isStrList {
answers = []any{answer}
}
}
for _, a := range answers {
for _, w := range wants {
if Equal(a, w) {
return true
}
}
}
return false
}
// Equal compares two scalar answer values loosely: numbers by value,
// everything else by its string form ("true" == true).
func Equal(a, b any) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
if fa, ok := toFloat(a); ok {
if fb, ok := toFloat(b); ok {
return fa == fb
}
}
return Scalar(a) == Scalar(b)
}
// Scalar renders a scalar answer as text.
func Scalar(v any) string {
switch x := v.(type) {
case nil:
return ""
case string:
return x
case bool:
return strconv.FormatBool(x)
case int:
return strconv.Itoa(x)
case int64:
return strconv.FormatInt(x, 10)
case float64:
return strconv.FormatFloat(x, 'f', -1, 64)
}
return fmt.Sprint(v)
}
// IsSet reports whether an answer is present and not empty.
func IsSet(v any) bool {
switch x := v.(type) {
case nil:
return false
case string:
return strings.TrimSpace(x) != ""
case []any:
return len(x) > 0
case []string:
return len(x) > 0
case map[string]any:
return len(x) > 0
}
return true
}
func toFloat(v any) (float64, bool) {
switch x := v.(type) {
case int:
return float64(x), true
case int64:
return float64(x), true
case float64:
return x, true
case uint64:
return float64(x), true
}
return 0, false
}
func asList(v any) []any {
switch x := v.(type) {
case []any:
return x
case []string:
out := make([]any, len(x))
for i, s := range x {
out[i] = s
}
return out
}
return nil
}
func asMap(v any) (map[string]any, bool) {
switch x := v.(type) {
case map[string]any:
return x, true
case Cond:
return map[string]any(x), true
}
return nil, false
}
func sortedKeys(m map[string]any) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// Refs returns the question IDs a condition reads (for the linter).
func (c Cond) Refs() []string {
seen := map[string]bool{}
var walk func(m map[string]any, depth int)
walk = func(m map[string]any, depth int) {
if depth > MaxCondDepth {
return
}
for k, v := range m {
switch k {
case "all", "any":
if list, ok := v.([]any); ok {
for _, item := range list {
if sub, ok := asMap(item); ok {
walk(sub, depth+1)
}
}
}
case "not":
if sub, ok := asMap(v); ok {
walk(sub, depth+1)
}
case "$mode", "$platform":
default:
seen[k] = true
}
}
}
walk(map[string]any(c), 0)
out := make([]string, 0, len(seen))
for k := range seen {
out = append(out, k)
}
sort.Strings(out)
return out
}
+503
View File
@@ -0,0 +1,503 @@
package catalog
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"sort"
"strings"
"gopkg.in/yaml.v3"
)
// Limits protect against hostile catalogs (SEC-03).
const (
MaxFileSize = 4 << 20
MaxFiles = 10000
MaxQuestions = 500
MaxRules = 1000
)
// Entity fields shared by all loaded manifests.
type Entity struct {
Kind string `json:"kind"`
Meta Meta `json:"metadata"`
File string `json:"file"` // relative to the catalog root (or "bigpicture:...")
Line int `json:"line"`
Hash string `json:"hash"` // sha256 of the document's source
}
// Package is a loaded Package manifest.
type Package struct {
Entity
Spec PackageSpec `json:"spec"`
}
// Module returns the module with that ID.
func (p *Package) Module(id string) *Module {
for i := range p.Spec.Modules {
if p.Spec.Modules[i].ID == id {
return &p.Spec.Modules[i]
}
}
return nil
}
// Profile is a loaded Profile manifest.
type Profile struct {
Entity
Spec ProfileSpec `json:"spec"`
}
// Key is "<package>/<id>".
func (p *Profile) Key() string { return p.Meta.Package + "/" + p.Meta.ID }
// Solution is a loaded Solution or Task manifest.
type Solution struct {
Entity
Spec SolutionSpec `json:"spec"`
}
// IsTask reports whether this is a Task.
func (s *Solution) IsTask() bool { return s.Kind == KindTask }
// Question returns the question with that ID and its index.
func (s *Solution) Question(id string) (*Question, int) {
for i := range s.Spec.Questions {
if s.Spec.Questions[i].ID == id {
return &s.Spec.Questions[i], i
}
}
return nil, -1
}
// Example is a loaded Example manifest.
type Example struct {
Entity
Spec ExampleSpec `json:"spec"`
}
// Key is "<solution>/<id>".
func (e *Example) Key() string { return e.Spec.Solution + "/" + e.Meta.ID }
// KnowledgeSource is a loaded KnowledgeSource manifest.
type KnowledgeSource struct {
Entity
Spec KnowledgeSourceSpec `json:"spec"`
}
// Catalog is everything loaded from one catalog root.
type Catalog struct {
Root string `json:"-"`
Meta Meta `json:"metadata"`
Spec CatalogSpec `json:"spec"`
Capabilities map[string]*Capability `json:"capabilities"`
Packages map[string]*Package `json:"packages"`
Profiles map[string]*Profile `json:"profiles"`
Solutions map[string]*Solution `json:"solutions"`
Tasks map[string]*Solution `json:"tasks"`
Examples map[string]*Example `json:"examples"`
Sources map[string]*KnowledgeSource `json:"sources"`
BigPicture *BigPicture `json:"bigpicture"`
// Files are all source files with their hashes, sorted (for locks).
Files []FileHash `json:"files"`
// Issues found while loading (fatal ones make Load fail).
Issues []Issue `json:"-"`
capFile map[string]string
}
// FileHash is one source file and its sha256.
type FileHash struct {
Path string `json:"path"`
Hash string `json:"sha256"`
}
// Issue is a problem in a catalog (load, validation or lint).
type Issue struct {
Severity string `json:"severity"` // error | warning
File string `json:"file,omitempty"`
Line int `json:"line,omitempty"`
ID string `json:"id,omitempty"`
Code string `json:"code"`
Message string `json:"message"`
}
func (i Issue) String() string {
loc := i.File
if i.Line > 0 {
loc = fmt.Sprintf("%s:%d", i.File, i.Line)
}
if loc != "" {
loc += ": "
}
id := ""
if i.ID != "" {
id = i.ID + ": "
}
return fmt.Sprintf("%s%s%s (%s)", loc, id, i.Message, i.Code)
}
// ErrInvalid wraps load errors.
var ErrInvalid = errors.New("invalid catalog")
// Load reads a catalog root directory (the one with catalog.yaml).
func Load(root string) (*Catalog, error) {
return LoadFS(os.DirFS(root), root)
}
// LoadFS reads a catalog from fsys (root is only used for messages and
// to find the Big Picture relative to it, when fsys is a directory).
func LoadFS(fsys fs.FS, root string) (*Catalog, error) {
c := &Catalog{
Root: root,
Capabilities: map[string]*Capability{},
Packages: map[string]*Package{},
Profiles: map[string]*Profile{},
Solutions: map[string]*Solution{},
Tasks: map[string]*Solution{},
Examples: map[string]*Example{},
Sources: map[string]*KnowledgeSource{},
capFile: map[string]string{},
}
var files []string
err := fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
name := d.Name()
if d.IsDir() {
if p != "." && (strings.HasPrefix(name, ".") || name == "schema" || name == "testdata" || name == "golden") {
return fs.SkipDir
}
return nil
}
if strings.HasSuffix(name, ".yaml") || strings.HasSuffix(name, ".yml") {
files = append(files, p)
if len(files) > MaxFiles {
return fmt.Errorf("more than %d files", MaxFiles)
}
}
return nil
})
if err != nil {
return nil, fmt.Errorf("%w: %v", ErrInvalid, err)
}
sort.Strings(files)
sawRoot := false
for _, f := range files {
b, err := readLimited(fsys, f)
if err != nil {
c.add("error", f, 0, "", "read", err.Error())
continue
}
c.Files = append(c.Files, FileHash{Path: f, Hash: sha(b)})
if c.loadFile(f, b) {
sawRoot = true
}
}
if !sawRoot {
c.add("error", "catalog.yaml", 0, "", "no-root", "no Catalog manifest (catalog.yaml) found")
}
if c.Spec.BigPicture != "" {
bpDir := c.Spec.BigPicture
if !filepath.IsAbs(bpDir) {
bpDir = filepath.Join(root, bpDir)
}
bp, err := LoadBigPicture(bpDir)
if err != nil {
c.add("error", "catalog.yaml", 0, "", "bigpicture", err.Error())
} else {
c.BigPicture = bp
c.Files = append(c.Files, bp.Files...)
}
}
sort.Slice(c.Files, func(i, j int) bool { return c.Files[i].Path < c.Files[j].Path })
if errs := c.Errors(); len(errs) > 0 {
return c, fmt.Errorf("%w: %d error(s), first: %s", ErrInvalid, len(errs), errs[0])
}
return c, nil
}
func readLimited(fsys fs.FS, p string) ([]byte, error) {
f, err := fsys.Open(p)
if err != nil {
return nil, err
}
defer f.Close()
b, err := io.ReadAll(io.LimitReader(f, MaxFileSize+1))
if err != nil {
return nil, err
}
if len(b) > MaxFileSize {
return nil, fmt.Errorf("larger than %d bytes", MaxFileSize)
}
return b, nil
}
func sha(b []byte) string {
h := sha256.Sum256(b)
return hex.EncodeToString(h[:])
}
func (c *Catalog) add(sev, file string, line int, id, code, msg string) {
c.Issues = append(c.Issues, Issue{Severity: sev, File: file, Line: line, ID: id, Code: code, Message: msg})
}
// Errors returns the issues with severity error.
func (c *Catalog) Errors() []Issue {
var out []Issue
for _, i := range c.Issues {
if i.Severity == "error" {
out = append(out, i)
}
}
return out
}
// loadFile decodes all documents of one file; reports whether it held the root.
func (c *Catalog) loadFile(file string, b []byte) bool {
dec := yaml.NewDecoder(bytes.NewReader(b))
root := false
for {
var doc yaml.Node
err := dec.Decode(&doc)
if errors.Is(err, io.EOF) {
break
}
if err != nil {
c.add("error", file, 0, "", "yaml", err.Error())
return root
}
if len(doc.Content) == 0 {
continue
}
raw, _ := yaml.Marshal(&doc)
var h Header
if err := strictDecode(raw, &h); err != nil {
c.add("error", file, doc.Line, "", "header", err.Error())
continue
}
line := doc.Content[0].Line
if h.APIVersion != APIVersion {
c.add("error", file, line, h.Metadata.ID, "api-version", fmt.Sprintf("apiVersion %q, want %q", h.APIVersion, APIVersion))
continue
}
ent := Entity{Kind: h.Kind, Meta: h.Metadata, File: file, Line: line, Hash: sha(raw)}
specRaw, _ := yaml.Marshal(&h.Spec)
if h.Spec.Kind == 0 {
specRaw = []byte("{}")
}
if err := c.addEntity(ent, specRaw); err != nil {
c.add("error", file, line, h.Metadata.ID, "spec", err.Error())
continue
}
if h.Kind == KindCatalog {
root = true
}
}
return root
}
func strictDecode(b []byte, v any) error {
d := yaml.NewDecoder(bytes.NewReader(b))
d.KnownFields(true)
if err := d.Decode(v); err != nil && !errors.Is(err, io.EOF) {
return err
}
return nil
}
func (c *Catalog) addEntity(e Entity, spec []byte) error {
dup := func(kind, id, other string) error {
return fmt.Errorf("duplicate %s %q (also in %s)", kind, id, other)
}
switch e.Kind {
case KindCatalog:
if c.Meta.ID != "" {
return fmt.Errorf("more than one Catalog manifest")
}
if err := strictDecode(spec, &c.Spec); err != nil {
return err
}
c.Meta = e.Meta
case KindCapabilities:
var s CapabilitiesSpec
if err := strictDecode(spec, &s); err != nil {
return err
}
for i := range s.Capabilities {
cp := s.Capabilities[i]
if other, ok := c.capFile[cp.ID]; ok {
return dup("capability", cp.ID, other)
}
c.Capabilities[cp.ID] = &cp
c.capFile[cp.ID] = e.File
}
case KindPackage:
p := &Package{Entity: e}
if err := strictDecode(spec, &p.Spec); err != nil {
return err
}
if o, ok := c.Packages[e.Meta.ID]; ok {
return dup("package", e.Meta.ID, o.File)
}
c.Packages[e.Meta.ID] = p
case KindProfile:
p := &Profile{Entity: e}
if err := strictDecode(spec, &p.Spec); err != nil {
return err
}
if e.Meta.Package == "" {
return fmt.Errorf("profile %q: metadata.package is required", e.Meta.ID)
}
if o, ok := c.Profiles[p.Key()]; ok {
return dup("profile", p.Key(), o.File)
}
c.Profiles[p.Key()] = p
case KindSolution, KindTask:
s := &Solution{Entity: e}
if err := strictDecode(spec, &s.Spec); err != nil {
return err
}
if len(s.Spec.Questions) > MaxQuestions || len(s.Spec.Rules) > MaxRules {
return fmt.Errorf("more than %d questions or %d rules", MaxQuestions, MaxRules)
}
m := c.Solutions
if e.Kind == KindTask {
m = c.Tasks
}
if o, ok := m[e.Meta.ID]; ok {
return dup(strings.ToLower(e.Kind), e.Meta.ID, o.File)
}
m[e.Meta.ID] = s
case KindExample:
x := &Example{Entity: e}
if err := strictDecode(spec, &x.Spec); err != nil {
return err
}
if x.Spec.Solution == "" {
// default: the solution directory the example lives in
x.Spec.Solution = solutionDirOf(e.File)
}
if o, ok := c.Examples[x.Key()]; ok {
return dup("example", x.Key(), o.File)
}
c.Examples[x.Key()] = x
case KindKnowledgeSource:
k := &KnowledgeSource{Entity: e}
if err := strictDecode(spec, &k.Spec); err != nil {
return err
}
if o, ok := c.Sources[e.Meta.ID]; ok {
return dup("knowledge source", e.Meta.ID, o.File)
}
c.Sources[e.Meta.ID] = k
default:
return fmt.Errorf("unknown kind %q", e.Kind)
}
return nil
}
// solutionDirOf: solutions/<category>/<id>/examples/x.yaml -> <id>.
func solutionDirOf(file string) string {
dir := path.Dir(path.Dir(file))
return path.Base(dir)
}
// SortedIDs returns the keys of a map in order.
func SortedIDs[V any](m map[string]V) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}
// Lookup finds a solution or task by ID (solutions first).
func (c *Catalog) Lookup(id string) *Solution {
if s, ok := c.Solutions[id]; ok {
return s
}
if s, ok := c.Tasks[id]; ok {
return s
}
for _, m := range []map[string]*Solution{c.Solutions, c.Tasks} {
for _, s := range m {
for _, a := range s.Meta.Aliases {
if a == id {
return s
}
}
}
}
return nil
}
// ProvidersOf lists package modules providing a capability, best first.
func (c *Catalog) ProvidersOf(capID string) []ModuleRef {
var out []ModuleRef
for _, pid := range SortedIDs(c.Packages) {
p := c.Packages[pid]
for _, m := range p.Spec.Modules {
for _, pr := range m.Provides {
if pr == capID {
out = append(out, ModuleRef{Package: pid, Module: m.ID, Priority: m.Priority, Support: m.Support})
}
}
}
}
sort.SliceStable(out, func(i, j int) bool { return out[i].Priority > out[j].Priority })
return out
}
// ModuleRef points at one module of one package.
type ModuleRef struct {
Package string `json:"package"`
Module string `json:"module"`
Priority int `json:"priority,omitempty"`
Support Support `json:"support,omitempty"`
}
func (m ModuleRef) String() string { return m.Package + "/" + m.Module }
// ProfileChain returns the profile and its ancestors, base first; it
// fails on unknown profiles and cycles (PROF-03).
func (c *Catalog) ProfileChain(pkg, id string) ([]*Profile, error) {
var chain []*Profile
seen := map[string]bool{}
for cur := id; cur != ""; {
key := pkg + "/" + cur
if seen[key] {
return nil, fmt.Errorf("profile %s: inheritance cycle", key)
}
seen[key] = true
p, ok := c.Profiles[key]
if !ok {
return nil, fmt.Errorf("unknown profile %s", key)
}
chain = append(chain, p)
cur = p.Spec.Extends
}
for i, j := 0, len(chain)-1; i < j; i, j = i+1, j-1 {
chain[i], chain[j] = chain[j], chain[i]
}
return chain, nil
}
// Hash is a digest over all catalog files (catalog version for locks).
func (c *Catalog) Hash() string {
h := sha256.New()
for _, f := range c.Files {
fmt.Fprintf(h, "%s %s\n", f.Path, f.Hash)
}
return hex.EncodeToString(h.Sum(nil))
}
+509
View File
@@ -0,0 +1,509 @@
// Package catalog is the data model of Yetano Knowledge & Solutions: the
// manifests under assets/solutions (Capability, Package, Profile,
// Solution, Task, Example, KnowledgeSource) and the read-only view of the
// Big Picture sources (topics, goals, programs) they build on.
//
// Everything here is data. Nothing in a catalog is ever executed: there
// are no template functions, no commands run by the engine and no network
// access (see docs/knowledge-solutions/SECURITY.md in the meta-repo).
package catalog
import "gopkg.in/yaml.v3"
// APIVersion is the only manifest version this package reads.
const APIVersion = "yetano.dev/v1"
// Manifest kinds.
const (
KindCatalog = "Catalog"
KindCapabilities = "Capabilities"
KindPackage = "Package"
KindProfile = "Profile"
KindSolution = "Solution"
KindTask = "Task"
KindExample = "Example"
KindPreset = "Preset"
KindInstance = "SolutionInstance"
KindSession = "WizardSession"
KindKnowledgeSource = "KnowledgeSource"
)
// Support says how far an option, module or solution is backed by the
// real programs (RULE-03). Only Supported, Experimental, Untested and
// Discouraged can be selected; the others are shown with their reason.
type Support string
const (
Supported Support = "supported"
Experimental Support = "experimental"
Untested Support = "untested"
Discouraged Support = "discouraged"
NeedsPrereq Support = "needs-prerequisites"
NotImplemented Support = "not-implemented"
NotSupported Support = "not-supported"
Impossible Support = "impossible"
Insecure Support = "insecure"
)
// Selectable reports whether an option with this support level may be chosen.
func (s Support) Selectable() bool {
switch s {
case "", Supported, Experimental, Untested, Discouraged, NeedsPrereq:
return true
}
return false
}
// Valid reports whether s is a known support level ("" means supported).
func (s Support) Valid() bool {
switch s {
case "", Supported, Experimental, Untested, Discouraged, NeedsPrereq,
NotImplemented, NotSupported, Impossible, Insecure:
return true
}
return false
}
// Text is a translatable string set: the English base plus translations.
type Translations map[string]map[string]string // lang -> field -> text
// Meta is the common metadata block.
type Meta struct {
ID string `yaml:"id" json:"id"`
Name string `yaml:"name,omitempty" json:"name,omitempty"` // presets/instances
Package string `yaml:"package,omitempty" json:"package,omitempty"`
Version string `yaml:"version,omitempty" json:"version,omitempty"`
Title string `yaml:"title,omitempty" json:"title,omitempty"`
Summary string `yaml:"summary,omitempty" json:"summary,omitempty"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Category string `yaml:"category,omitempty" json:"category,omitempty"`
Tags []string `yaml:"tags,omitempty" json:"tags,omitempty"`
Synonyms []string `yaml:"synonyms,omitempty" json:"synonyms,omitempty"`
Difficulty string `yaml:"difficulty,omitempty" json:"difficulty,omitempty"`
Status Support `yaml:"status,omitempty" json:"status,omitempty"`
Audience []string `yaml:"audience,omitempty" json:"audience,omitempty"`
Featured bool `yaml:"featured,omitempty" json:"featured,omitempty"`
Origin string `yaml:"origin,omitempty" json:"origin,omitempty"` // official | local | org | community | ai
Aliases []string `yaml:"aliases,omitempty" json:"aliases,omitempty"`
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
}
// Header is the envelope every manifest file has.
type Header struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Metadata Meta `yaml:"metadata"`
Spec yaml.Node `yaml:"spec"`
}
// ---- Catalog root -------------------------------------------------------
// CatalogSpec is catalog.yaml: where the other sources are.
type CatalogSpec struct {
// BigPicture is the directory with the Big Picture manifest.yaml,
// relative to catalog.yaml.
BigPicture string `yaml:"bigpicture"`
// SourcesRoot is where repositories named in knowledge sources are
// checked out, relative to catalog.yaml (optional; manuals are then
// only referenced, not indexed).
SourcesRoot string `yaml:"sourcesRoot,omitempty"`
// WebBase resolves web references (https://yetano.app/).
WebBase string `yaml:"webBase"`
// Categories maps Big Picture topics to guide categories (order = display order).
Categories []Category `yaml:"categories"`
// Locales the catalog is (partly) translated into; English is the base.
Locales []string `yaml:"locales,omitempty"`
}
// Category is a guide category, normally one Big Picture topic.
type Category struct {
ID string `yaml:"id" json:"id"`
Topic string `yaml:"topic,omitempty" json:"topic,omitempty"`
Title string `yaml:"title,omitempty" json:"title,omitempty"`
Summary string `yaml:"summary,omitempty" json:"summary,omitempty"`
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
}
// ---- Capabilities ---------------------------------------------------------
// Capability is an abstract ability (mail.smtp.server); see CAPABILITIES.md.
type Capability struct {
ID string `yaml:"id" json:"id"`
Title string `yaml:"title" json:"title"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Requires []string `yaml:"requires,omitempty" json:"requires,omitempty"`
Conflicts []string `yaml:"conflicts,omitempty" json:"conflicts,omitempty"`
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
// Providers outside Yetano (an existing LDAP, PostgreSQL, ...).
External []ExternalProvider `yaml:"external,omitempty" json:"external,omitempty"`
}
// ExternalProvider is a provider that is not a Yetano package.
type ExternalProvider struct {
ID string `yaml:"id" json:"id"`
Title string `yaml:"title" json:"title"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Support Support `yaml:"support,omitempty" json:"support,omitempty"`
}
// CapabilitiesSpec is a capabilities file.
type CapabilitiesSpec struct {
Capabilities []Capability `yaml:"capabilities"`
}
// ---- Packages -------------------------------------------------------------
// PackageSpec describes a Yetano package for the guide. Its human summary
// comes from the Big Picture program (BigPicture), never copied here.
type PackageSpec struct {
BigPicture string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"` // product.<name>
Registry string `yaml:"registry,omitempty" json:"registry,omitempty"` // yetano.app/yetano/<pkg>
Microsite string `yaml:"microsite,omitempty" json:"microsite,omitempty"` // path below webBase
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
Modules []Module `yaml:"modules" json:"modules"`
// Sources back every claim about what the package can do (ANA-02).
Sources []string `yaml:"sources" json:"sources"`
}
// Module is one functional part of a package (a yamase-* program, ...).
type Module struct {
ID string `yaml:"id" json:"id"`
Title string `yaml:"title" json:"title"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Program string `yaml:"program,omitempty" json:"program,omitempty"` // binary name
Kind string `yaml:"kind,omitempty" json:"kind,omitempty"` // daemon | cli | plugin | library
Provides []string `yaml:"provides,omitempty" json:"provides,omitempty"`
Requires []string `yaml:"requires,omitempty" json:"requires,omitempty"` // capabilities
Support Support `yaml:"support,omitempty" json:"support,omitempty"`
// Priority orders providers of the same capability (higher first).
Priority int `yaml:"priority,omitempty" json:"priority,omitempty"`
// Manual is the knowledge source with this module's manual, if any.
Manual string `yaml:"manual,omitempty" json:"manual,omitempty"`
Doctor []string `yaml:"doctor,omitempty" json:"doctor,omitempty"` // commands that check it
Sources []string `yaml:"sources,omitempty" json:"sources,omitempty"`
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
}
// ---- Profiles -------------------------------------------------------------
// ProfileSpec is a recommended way to run one package.
type ProfileSpec struct {
Extends string `yaml:"extends,omitempty" json:"extends,omitempty"`
Modules map[string]string `yaml:"modules,omitempty" json:"modules,omitempty"` // module -> enabled|disabled
Parameters []string `yaml:"parameters,omitempty" json:"parameters,omitempty"`
Config []Fragment `yaml:"config,omitempty" json:"config,omitempty"`
Recommendations []Recommendation `yaml:"recommendations,omitempty" json:"recommendations,omitempty"`
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
References []string `yaml:"references,omitempty" json:"references,omitempty"`
}
// Recommendation names something worth adding, with the reason.
type Recommendation struct {
Package string `yaml:"package,omitempty" json:"package,omitempty"`
Capability string `yaml:"capability,omitempty" json:"capability,omitempty"`
Reason string `yaml:"reason" json:"reason"`
}
// Fragment is a typed YAML piece for one generated file (ADR-0005).
type Fragment struct {
ID string `yaml:"id,omitempty" json:"id,omitempty"`
File string `yaml:"file" json:"file"`
// Module: the fragment only applies while this module of the file's
// package is enabled (a disabled program gets no configuration).
Module string `yaml:"module,omitempty" json:"module,omitempty"`
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
Set yaml.Node `yaml:"set" json:"-"`
}
// ---- Solutions and tasks ----------------------------------------------------
// SolutionSpec is a complete use case. Tasks use the same structure.
type SolutionSpec struct {
BigPicture string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"`
Kind string `yaml:"kind,omitempty" json:"kind,omitempty"` // tasks: read-only|generate|diagnostic|planning|mutating|deployment|maintenance
Goals []string `yaml:"goals,omitempty" json:"goals,omitempty"`
Scenarios []string `yaml:"scenarios,omitempty" json:"scenarios,omitempty"`
NotFor []string `yaml:"notFor,omitempty" json:"notFor,omitempty"`
AppliesTo *AppliesTo `yaml:"appliesTo,omitempty" json:"appliesTo,omitempty"`
Capabilities CapSets `yaml:"capabilities,omitempty" json:"capabilities"`
Packages []PackageUse `yaml:"packages,omitempty" json:"packages"`
Questions []Question `yaml:"questions,omitempty" json:"questions"`
Rules []Rule `yaml:"rules,omitempty" json:"rules,omitempty"`
Config []Fragment `yaml:"configuration,omitempty" json:"-"`
Steps []Step `yaml:"steps,omitempty" json:"steps,omitempty"`
Requirements []Check `yaml:"requirements,omitempty" json:"requirements,omitempty"`
Architecture Architecture `yaml:"architecture,omitempty" json:"architecture"`
References References `yaml:"references,omitempty" json:"references"`
Related []string `yaml:"related,omitempty" json:"related,omitempty"`
Operations []string `yaml:"operations,omitempty" json:"operations,omitempty"`
Lifecycle Lifecycle `yaml:"lifecycle,omitempty" json:"lifecycle"`
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
Sources []string `yaml:"sources,omitempty" json:"sources,omitempty"`
}
// AppliesTo limits a task to solutions/capabilities (applicableWhen).
type AppliesTo struct {
Solutions []string `yaml:"solutions,omitempty" json:"solutions,omitempty"`
Capabilities []string `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`
}
// CapSets are the capabilities a solution needs.
type CapSets struct {
Required []string `yaml:"required,omitempty" json:"required,omitempty"`
Recommended []string `yaml:"recommended,omitempty" json:"recommended,omitempty"`
Optional []string `yaml:"optional,omitempty" json:"optional,omitempty"`
}
// PackageUse puts a package into a solution, optionally under a condition.
type PackageUse struct {
ID string `yaml:"id" json:"id"`
Profile string `yaml:"profile,omitempty" json:"profile,omitempty"`
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
Role string `yaml:"role,omitempty" json:"role,omitempty"` // core | optional
Recommended bool `yaml:"recommended,omitempty" json:"recommended,omitempty"`
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
}
// Level orders the wizard modes.
type Level string
const (
LevelQuick Level = "quick"
LevelGuided Level = "guided"
LevelAdvanced Level = "advanced"
)
// Rank is the order of the modes (quick < guided < advanced).
func (l Level) Rank() int {
switch l {
case LevelGuided:
return 1
case LevelAdvanced:
return 2
}
return 0
}
// Question is one wizard question.
type Question struct {
ID string `yaml:"id" json:"id"`
Type string `yaml:"type" json:"type"`
Item string `yaml:"item,omitempty" json:"item,omitempty"` // list element type
Group string `yaml:"group,omitempty" json:"group,omitempty"`
Level Level `yaml:"level,omitempty" json:"level,omitempty"`
Title string `yaml:"title" json:"title"`
Help string `yaml:"help,omitempty" json:"help,omitempty"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Decide string `yaml:"decide,omitempty" json:"decide,omitempty"` // "Help me decide" text
Placeholder string `yaml:"placeholder,omitempty" json:"placeholder,omitempty"`
Examples []string `yaml:"examples,omitempty" json:"examples,omitempty"`
Default any `yaml:"default,omitempty" json:"default,omitempty"`
DefaultWhen []CondValue `yaml:"defaultWhen,omitempty" json:"defaultWhen,omitempty"`
Recommended any `yaml:"recommended,omitempty" json:"recommended,omitempty"`
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
Required bool `yaml:"required,omitempty" json:"required,omitempty"`
RequiredWhen Cond `yaml:"requiredWhen,omitempty" json:"requiredWhen,omitempty"`
VisibleWhen Cond `yaml:"visibleWhen,omitempty" json:"visibleWhen,omitempty"`
InstanceSpecific bool `yaml:"instanceSpecific,omitempty" json:"instanceSpecific,omitempty"`
Options []Option `yaml:"options,omitempty" json:"options,omitempty"`
Validation Validation `yaml:"validation,omitempty" json:"validation"`
ValidateWhen []CondCheck `yaml:"validateWhen,omitempty" json:"validateWhen,omitempty"`
References []string `yaml:"references,omitempty" json:"references,omitempty"`
Warnings []CondText `yaml:"warnings,omitempty" json:"warnings,omitempty"`
Platforms []string `yaml:"platforms,omitempty" json:"platforms,omitempty"`
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
}
// Option is one choice of a select/multiselect question.
type Option struct {
ID string `yaml:"id" json:"id"`
Title string `yaml:"title" json:"title"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Recommended bool `yaml:"recommended,omitempty" json:"recommended,omitempty"`
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
Support Support `yaml:"support,omitempty" json:"support,omitempty"`
SupportNote string `yaml:"supportNote,omitempty" json:"supportNote,omitempty"`
EnabledWhen Cond `yaml:"enabledWhen,omitempty" json:"enabledWhen,omitempty"`
Effects Effects `yaml:",inline" json:"effects"`
References []string `yaml:"references,omitempty" json:"references,omitempty"`
Translations Translations `yaml:"translations,omitempty" json:"translations,omitempty"`
}
// Effects are what a rule or a chosen option does (RULE-01).
type Effects struct {
Requires *Targets `yaml:"requires,omitempty" json:"requires,omitempty"`
Excludes *Targets `yaml:"excludes,omitempty" json:"excludes,omitempty"`
Conflicts *Targets `yaml:"conflicts,omitempty" json:"conflicts,omitempty"`
Implies *Targets `yaml:"implies,omitempty" json:"implies,omitempty"`
Recommends *Targets `yaml:"recommends,omitempty" json:"recommends,omitempty"`
Discourages *Targets `yaml:"discourages,omitempty" json:"discourages,omitempty"`
Provides []string `yaml:"provides,omitempty" json:"provides,omitempty"` // capabilities provided outside Yetano
}
// Targets lists packages, capabilities, modules and option answers.
type Targets struct {
Packages []string `yaml:"packages,omitempty" json:"packages,omitempty"`
Capabilities []string `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`
Modules []string `yaml:"modules,omitempty" json:"modules,omitempty"` // pkg/module
Answers map[string]any `yaml:"answers,omitempty" json:"answers,omitempty"` // question -> option
}
// Rule is a declarative rule of a solution or task.
type Rule struct {
ID string `yaml:"id" json:"id"`
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
Effects Effects `yaml:",inline" json:"effects"`
Severity string `yaml:"severity,omitempty" json:"severity,omitempty"` // for warnings: info|warning|error
Message string `yaml:"message,omitempty" json:"message,omitempty"`
Reason string `yaml:"reason,omitempty" json:"reason,omitempty"`
Source string `yaml:"source,omitempty" json:"source,omitempty"`
}
// Validation constrains an answer.
type Validation struct {
Min *float64 `yaml:"min,omitempty" json:"min,omitempty"`
Max *float64 `yaml:"max,omitempty" json:"max,omitempty"`
MinItems int `yaml:"minItems,omitempty" json:"minItems,omitempty"`
MaxItems int `yaml:"maxItems,omitempty" json:"maxItems,omitempty"`
MinLength int `yaml:"minLength,omitempty" json:"minLength,omitempty"`
MaxLength int `yaml:"maxLength,omitempty" json:"maxLength,omitempty"`
Pattern string `yaml:"pattern,omitempty" json:"pattern,omitempty"`
Message string `yaml:"message,omitempty" json:"message,omitempty"`
}
// CondValue is a conditional default.
type CondValue struct {
When Cond `yaml:"when" json:"when"`
Value any `yaml:"value" json:"value"`
}
// CondText is a conditional message.
type CondText struct {
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
Severity string `yaml:"severity,omitempty" json:"severity,omitempty"`
Text string `yaml:"text" json:"text"`
}
// CondCheck is a conditional validation (validateWhen).
type CondCheck struct {
When Cond `yaml:"when" json:"when"`
Validation Validation `yaml:"validation" json:"validation"`
}
// Step is a setup step that is not configuration (yamase-ctl directory
// domain add ...). The engine only lists steps; it never runs them.
type Step struct {
ID string `yaml:"id" json:"id"`
Title string `yaml:"title" json:"title"`
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
Package string `yaml:"package,omitempty" json:"package,omitempty"`
Module string `yaml:"module,omitempty" json:"module,omitempty"`
ForEach string `yaml:"forEach,omitempty" json:"forEach,omitempty"` // list parameter; ${item}
Run string `yaml:"run,omitempty" json:"run,omitempty"`
Note string `yaml:"note,omitempty" json:"note,omitempty"`
Phase string `yaml:"phase,omitempty" json:"phase,omitempty"` // install | configure | data | dns | start | verify
Mutating bool `yaml:"mutating,omitempty" json:"mutating,omitempty"`
Reversible *bool `yaml:"reversible,omitempty" json:"reversible,omitempty"`
References []string `yaml:"references,omitempty" json:"references,omitempty"`
}
// Check is a requirement or doctor check (DR-01).
type Check struct {
ID string `yaml:"id" json:"id"`
Title string `yaml:"title" json:"title"`
Kind string `yaml:"kind" json:"kind"` // os | arch | port | dns | tls | program | command | manual
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
Severity string `yaml:"severity,omitempty" json:"severity,omitempty"` // error | warning | info
Local bool `yaml:"local,omitempty" json:"local,omitempty"` // needs the target system
Params map[string]string `yaml:"params,omitempty" json:"params,omitempty"`
Run string `yaml:"run,omitempty" json:"run,omitempty"` // command the operator can run
Hint string `yaml:"hint,omitempty" json:"hint,omitempty"`
References []string `yaml:"references,omitempty" json:"references,omitempty"`
}
// Architecture adds solution-specific nodes and edges to the resolved graph.
type Architecture struct {
Nodes []ArchNode `yaml:"nodes,omitempty" json:"nodes,omitempty"`
Edges []ArchEdge `yaml:"edges,omitempty" json:"edges,omitempty"`
}
// ArchNode is an extra node (clients, external services, storage, ...).
type ArchNode struct {
ID string `yaml:"id" json:"id"`
Type string `yaml:"type" json:"type"` // client | external | storage | network | identity | target
Title string `yaml:"title" json:"title"`
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
}
// ArchEdge connects two nodes; IDs are node IDs, "pkg:<id>", "mod:<pkg>/<id>" or "cap:<id>".
type ArchEdge struct {
From string `yaml:"from" json:"from"`
To string `yaml:"to" json:"to"`
Type string `yaml:"type" json:"type"`
Label string `yaml:"label,omitempty" json:"label,omitempty"`
When Cond `yaml:"when,omitempty" json:"when,omitempty"`
}
// References are typed yetano: references.
type References struct {
Manuals []string `yaml:"manuals,omitempty" json:"manuals,omitempty"`
Microsites []string `yaml:"microsites,omitempty" json:"microsites,omitempty"`
BigPicture []string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"`
Other []string `yaml:"other,omitempty" json:"other,omitempty"`
}
// All returns every reference in a stable order.
func (r References) All() []string {
var out []string
out = append(out, r.Manuals...)
out = append(out, r.Microsites...)
out = append(out, r.BigPicture...)
out = append(out, r.Other...)
return out
}
// Lifecycle says which lifecycle operations a solution supports.
type Lifecycle struct {
Configure bool `yaml:"configure,omitempty" json:"configure"`
Validate bool `yaml:"validate,omitempty" json:"validate"`
Plan bool `yaml:"plan,omitempty" json:"plan"`
Deploy string `yaml:"deploy,omitempty" json:"deploy,omitempty"` // no | optional | yes
Doctor bool `yaml:"doctor,omitempty" json:"doctor"`
Update string `yaml:"update,omitempty" json:"update,omitempty"`
}
// ---- Examples, presets, instances ------------------------------------------
// ExampleSpec is a curated answer set for a solution (EX-01). Examples
// are generated by the engine like any session, so they cannot drift.
type ExampleSpec struct {
Solution string `yaml:"solution" json:"solution"`
Mode Level `yaml:"mode,omitempty" json:"mode,omitempty"`
Scenario string `yaml:"scenario,omitempty" json:"scenario,omitempty"`
Parameters map[string]any `yaml:"parameters" json:"parameters"`
Tested bool `yaml:"tested,omitempty" json:"tested"`
}
// ---- Knowledge sources --------------------------------------------------------
// KnowledgeSourceSpec points at existing documentation (KNOW-04/06): the
// documents stay where they are; sections are extracted from headings.
type KnowledgeSourceSpec struct {
Package string `yaml:"package" json:"package"`
Type string `yaml:"type" json:"type"` // manual
Format string `yaml:"format" json:"format"` // markdown
Repository string `yaml:"repository" json:"repository"`
Root string `yaml:"root,omitempty" json:"root,omitempty"` // dir with README.md and docs/
Program string `yaml:"program,omitempty" json:"program,omitempty"`
Layout string `yaml:"layout,omitempty" json:"layout,omitempty"` // core-manual (README + docs/**) | docs-tree
Web string `yaml:"web,omitempty" json:"web,omitempty"` // URL base for topics, {slug} placeholder
Exclude []string `yaml:"exclude,omitempty" json:"exclude,omitempty"`
Topics []SourceTopic `yaml:"topics,omitempty" json:"topics,omitempty"`
}
// SourceTopic attaches capabilities/modules to one manual topic.
type SourceTopic struct {
Slug string `yaml:"slug" json:"slug"`
Capabilities []string `yaml:"capabilities,omitempty" json:"capabilities,omitempty"`
Modules []string `yaml:"modules,omitempty" json:"modules,omitempty"`
}
+116
View File
@@ -0,0 +1,116 @@
package catalog
import (
"reflect"
"strings"
"gopkg.in/yaml.v3"
)
// SchemaKinds maps a schema file name to the manifest it describes.
var SchemaKinds = map[string]struct {
Kind string
Spec any
}{
"catalog": {KindCatalog, CatalogSpec{}},
"capabilities": {KindCapabilities, CapabilitiesSpec{}},
"package": {KindPackage, PackageSpec{}},
"profile": {KindProfile, ProfileSpec{}},
"solution": {KindSolution, SolutionSpec{}},
"example": {KindExample, ExampleSpec{}},
"knowledge-source": {KindKnowledgeSource, KnowledgeSourceSpec{}},
}
// JSONSchema returns the JSON Schema (draft 2020-12) of a manifest kind,
// derived from the Go types the loader decodes with KnownFields -- so the
// editor's check and the loader cannot disagree (CAT-05). Several
// documents per file ("---") are not expressible in JSON Schema; the
// schema describes one document. Solution and Task share a schema.
func JSONSchema(name string) map[string]any {
k := SchemaKinds[name]
kinds := []any{k.Kind}
if k.Kind == KindSolution {
kinds = append(kinds, KindTask)
}
return map[string]any{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://yetano.app/schema/solutions/" + name + ".schema.json",
"title": "Yetano " + k.Kind + " manifest",
"type": "object",
"additionalProperties": false,
"required": []any{"apiVersion", "kind", "metadata"},
"properties": map[string]any{
"apiVersion": map[string]any{"const": APIVersion},
"kind": map[string]any{"enum": kinds},
"metadata": schemaOf(reflect.TypeOf(Meta{}), 0),
"spec": schemaOf(reflect.TypeOf(k.Spec), 0),
},
}
}
var (
nodeType = reflect.TypeOf(yaml.Node{})
condType = reflect.TypeOf(Cond{})
)
func schemaOf(t reflect.Type, depth int) map[string]any {
if depth > 12 {
return map[string]any{}
}
if t.Kind() == reflect.Pointer {
t = t.Elem()
}
switch {
case t == nodeType:
return map[string]any{"description": "native configuration (any YAML)"}
case t == condType:
return map[string]any{"type": "object", "description": "condition over earlier answers (ADR-0003)"}
case t == reflect.TypeOf(Support("")):
return map[string]any{"enum": []any{"supported", "experimental", "untested", "discouraged", "needs-prerequisites", "not-implemented", "not-supported", "impossible", "insecure"}}
case t == reflect.TypeOf(Level("")):
return map[string]any{"enum": []any{"quick", "guided", "advanced"}}
}
switch t.Kind() {
case reflect.String:
return map[string]any{"type": "string"}
case reflect.Bool:
return map[string]any{"type": "boolean"}
case reflect.Int, reflect.Int64:
return map[string]any{"type": "integer"}
case reflect.Float64:
return map[string]any{"type": "number"}
case reflect.Slice:
return map[string]any{"type": "array", "items": schemaOf(t.Elem(), depth+1)}
case reflect.Map:
return map[string]any{"type": "object", "additionalProperties": schemaOf(t.Elem(), depth+1)}
case reflect.Interface:
return map[string]any{}
case reflect.Struct:
props := map[string]any{}
addFields(t, props, depth)
return map[string]any{"type": "object", "additionalProperties": false, "properties": props}
}
return map[string]any{}
}
func addFields(t reflect.Type, props map[string]any, depth int) {
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if !f.IsExported() {
continue
}
tag := f.Tag.Get("yaml")
name, opts, _ := strings.Cut(tag, ",")
if name == "-" {
continue
}
if strings.Contains(opts, "inline") {
addFields(f.Type, props, depth)
continue
}
if name == "" {
name = strings.ToLower(f.Name)
}
props[name] = schemaOf(f.Type, depth+1)
}
}
+548
View File
@@ -0,0 +1,548 @@
package catalog
import (
"fmt"
"path"
"regexp"
"strings"
)
// QuestionTypes are the built-in question types (WIZ-03).
var QuestionTypes = map[string]bool{
"boolean": true, "select": true, "multiselect": true,
"string": true, "text": true, "integer": true, "decimal": true,
"date": true, "duration": true, "hostname": true, "domain": true,
"email": true, "ip": true, "cidr": true, "port": true, "url": true,
"path": true, "dir": true, "list": true, "keyvalue": true,
"package": true, "profile": true, "capability": true, "provider": true,
"target": true, "secret": true,
}
// ListItemTypes may be used as list items.
var ListItemTypes = map[string]bool{
"string": true, "hostname": true, "domain": true, "email": true, "ip": true,
"cidr": true, "port": true, "url": true, "path": true, "integer": true,
}
var idRE = regexp.MustCompile(`^[a-z0-9][a-z0-9.-]*[a-z0-9]$|^[a-z0-9]$`)
var questionIDRE = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9_]*$`)
// SafeRelPath reports whether p is a clean relative slash path without
// "..", usable as an output file name (SEC-03).
func SafeRelPath(p string) bool {
if p == "" || strings.HasPrefix(p, "/") || strings.Contains(p, "\\") || strings.Contains(p, ":") {
return false
}
if path.Clean(p) != p {
return false
}
for _, part := range strings.Split(p, "/") {
if part == ".." || part == "." || part == "" || strings.HasPrefix(part, ".") {
return false
}
}
return true
}
// Validate checks the catalog's internal consistency and returns all
// issues (load issues included). Reference targets outside the catalog
// (manual sections, microsites) are checked by knowledge.Lint.
func (c *Catalog) Validate() []Issue {
v := &validator{c: c, issues: append([]Issue(nil), c.Issues...)}
v.root()
for _, id := range SortedIDs(c.Capabilities) {
v.capability(c.Capabilities[id])
}
for _, id := range SortedIDs(c.Packages) {
v.pkg(c.Packages[id])
}
for _, id := range SortedIDs(c.Profiles) {
v.profile(c.Profiles[id])
}
for _, id := range SortedIDs(c.Solutions) {
v.solution(c.Solutions[id])
}
for _, id := range SortedIDs(c.Tasks) {
v.solution(c.Tasks[id])
}
for _, id := range SortedIDs(c.Examples) {
v.example(c.Examples[id])
}
for _, id := range SortedIDs(c.Sources) {
v.source(c.Sources[id])
}
return v.issues
}
type validator struct {
c *Catalog
issues []Issue
}
func (v *validator) errf(e *Entity, id, code, f string, a ...any) {
i := Issue{Severity: "error", ID: id, Code: code, Message: fmt.Sprintf(f, a...)}
if e != nil {
i.File, i.Line = e.File, e.Line
}
v.issues = append(v.issues, i)
}
func (v *validator) warnf(e *Entity, id, code, f string, a ...any) {
i := Issue{Severity: "warning", ID: id, Code: code, Message: fmt.Sprintf(f, a...)}
if e != nil {
i.File, i.Line = e.File, e.Line
}
v.issues = append(v.issues, i)
}
func (v *validator) root() {
c := v.c
if c.Spec.WebBase == "" {
v.errf(nil, "catalog", "web-base", "catalog.yaml: spec.webBase is required")
}
seen := map[string]bool{}
for _, cat := range c.Spec.Categories {
if seen[cat.ID] {
v.errf(nil, cat.ID, "duplicate", "duplicate category %q", cat.ID)
}
seen[cat.ID] = true
if cat.Topic != "" && c.BigPicture != nil {
if _, ok := c.BigPicture.Topics[cat.Topic]; !ok {
v.errf(nil, cat.ID, "bigpicture-ref", "category %q: unknown Big Picture topic %q", cat.ID, cat.Topic)
}
}
if cat.Topic == "" && cat.Title == "" {
v.errf(nil, cat.ID, "category", "category %q needs a topic or a title", cat.ID)
}
}
}
func (v *validator) capability(cp *Capability) {
e := &Entity{File: v.c.capFile[cp.ID]}
if !idRE.MatchString(cp.ID) || strings.Contains(cp.ID, "@") {
v.errf(e, cp.ID, "id", "capability ID %q: lower case, dot separated, no '@' (ADR-0003)", cp.ID)
}
if cp.Title == "" {
v.errf(e, cp.ID, "required", "capability %q: title is required", cp.ID)
}
for _, r := range append(append([]string{}, cp.Requires...), cp.Conflicts...) {
if _, ok := v.c.Capabilities[r]; !ok {
v.errf(e, cp.ID, "capability-ref", "capability %q names unknown capability %q", cp.ID, r)
}
}
for _, x := range cp.External {
if !x.Support.Valid() {
v.errf(e, cp.ID, "support", "external provider %q: unknown support %q", x.ID, x.Support)
}
}
}
func (v *validator) caps(e *Entity, id string, list []string) {
for _, cp := range list {
if _, ok := v.c.Capabilities[cp]; !ok {
v.errf(e, id, "capability-ref", "unknown capability %q", cp)
}
}
}
func (v *validator) pkg(p *Package) {
e := &p.Entity
if !idRE.MatchString(p.Meta.ID) {
v.errf(e, p.Meta.ID, "id", "package ID %q is not valid", p.Meta.ID)
}
if p.Spec.BigPicture != "" && v.c.BigPicture != nil {
if _, ok := v.c.BigPicture.Products[p.Spec.BigPicture]; !ok {
v.errf(e, p.Meta.ID, "bigpicture-ref", "unknown Big Picture program %q", p.Spec.BigPicture)
}
}
if p.Spec.BigPicture == "" && p.Meta.Summary == "" {
v.errf(e, p.Meta.ID, "required", "package needs spec.bigpicture or metadata.summary")
}
if len(p.Spec.Sources) == 0 {
v.errf(e, p.Meta.ID, "sources", "package claims need sources (ANA-02)")
}
seen := map[string]bool{}
for _, m := range p.Spec.Modules {
if seen[m.ID] {
v.errf(e, p.Meta.ID, "duplicate", "duplicate module %q", m.ID)
}
seen[m.ID] = true
if !m.Support.Valid() {
v.errf(e, p.Meta.ID, "support", "module %q: unknown support %q", m.ID, m.Support)
}
v.caps(e, p.Meta.ID+"/"+m.ID, m.Provides)
v.caps(e, p.Meta.ID+"/"+m.ID, m.Requires)
if m.Manual != "" {
if _, ok := v.c.Sources[m.Manual]; !ok {
v.errf(e, p.Meta.ID+"/"+m.ID, "source-ref", "unknown knowledge source %q", m.Manual)
}
}
}
}
func (v *validator) profile(p *Profile) {
e := &p.Entity
pkg, ok := v.c.Packages[p.Meta.Package]
if !ok {
v.errf(e, p.Key(), "package-ref", "profile of unknown package %q", p.Meta.Package)
return
}
if _, err := v.c.ProfileChain(p.Meta.Package, p.Meta.ID); err != nil {
v.errf(e, p.Key(), "extends", "%v", err)
}
for m, state := range p.Spec.Modules {
if pkg.Module(m) == nil {
v.errf(e, p.Key(), "module-ref", "unknown module %q", m)
}
if state != "enabled" && state != "disabled" {
v.errf(e, p.Key(), "module-state", "module %q: want enabled or disabled, got %q", m, state)
}
}
for _, f := range p.Spec.Config {
v.fragment(e, p.Key(), f, nil, 0)
}
for _, r := range p.Spec.Recommendations {
if r.Package != "" {
if _, ok := v.c.Packages[r.Package]; !ok {
v.errf(e, p.Key(), "package-ref", "recommendation names unknown package %q", r.Package)
}
}
if r.Capability != "" {
v.caps(e, p.Key(), []string{r.Capability})
}
if r.Reason == "" {
v.errf(e, p.Key(), "reason", "a recommendation needs a reason (EX-03)")
}
}
}
func (v *validator) fragment(e *Entity, id string, f Fragment, s *Solution, upto int) {
if !SafeRelPath(f.File) {
v.errf(e, id, "path", "fragment file %q: want a clean relative path", f.File)
}
if f.Set.Kind == 0 {
v.errf(e, id, "fragment", "fragment for %q has no set", f.File)
}
if s != nil {
v.cond(e, id, "fragment "+f.File, f.When, s, upto)
} else if len(f.When) > 0 {
v.errf(e, id, "fragment", "profile fragments cannot have conditions")
}
}
// cond checks a condition: well-formed and only naming questions before
// index upto (ADR-0003).
func (v *validator) cond(e *Entity, id, where string, c Cond, s *Solution, upto int) {
if len(c) == 0 {
return
}
if _, err := c.Eval(Env{Answers: map[string]any{}}); err != nil {
v.errf(e, id, "condition", "%s: %v", where, err)
}
for _, ref := range c.Refs() {
_, idx := s.Question(ref)
if idx < 0 {
v.errf(e, id, "condition", "%s: unknown question %q", where, ref)
} else if idx >= upto {
v.errf(e, id, "condition-order", "%s: names question %q, which is not asked before it", where, ref)
}
}
}
func (v *validator) targets(e *Entity, id string, t *Targets, s *Solution) {
if t == nil {
return
}
for _, p := range t.Packages {
if _, ok := v.c.Packages[p]; !ok {
v.errf(e, id, "package-ref", "unknown package %q", p)
}
}
v.caps(e, id, t.Capabilities)
for _, m := range t.Modules {
pkg, mod, _ := strings.Cut(m, "/")
p, ok := v.c.Packages[pkg]
if !ok || p.Module(mod) == nil {
v.errf(e, id, "module-ref", "unknown module %q (want package/module)", m)
}
}
for q, val := range t.Answers {
qq, _ := s.Question(q)
if qq == nil {
v.errf(e, id, "question-ref", "unknown question %q", q)
continue
}
v.optionValue(e, id, qq, val)
}
}
func (v *validator) optionValue(e *Entity, id string, q *Question, val any) {
if q.Type != "select" && q.Type != "multiselect" {
return
}
vals := asList(val)
if _, isList := val.([]any); !isList {
vals = []any{val}
}
for _, x := range vals {
found := false
for _, o := range q.Options {
if Equal(o.ID, x) {
found = true
if !o.Support.Selectable() {
v.errf(e, id, "default-unselectable", "question %q: value %q is %s and cannot be selected", q.ID, Scalar(x), o.Support)
}
}
}
if !found {
v.errf(e, id, "option-ref", "question %q has no option %q", q.ID, Scalar(x))
}
}
}
func (v *validator) solution(s *Solution) {
e := &s.Entity
id := s.Meta.ID
if !idRE.MatchString(id) {
v.errf(e, id, "id", "ID %q is not valid", id)
}
if s.Meta.Version == "" {
v.errf(e, id, "version", "metadata.version is required (LOCK)")
}
if !s.Meta.Status.Valid() {
v.errf(e, id, "support", "unknown status %q", s.Meta.Status)
}
if s.Spec.BigPicture != "" && v.c.BigPicture != nil {
if _, ok := v.c.BigPicture.Stories[s.Spec.BigPicture]; !ok {
v.errf(e, id, "bigpicture-ref", "unknown Big Picture goal %q", s.Spec.BigPicture)
}
}
if s.Meta.Title == "" && s.Spec.BigPicture == "" {
v.errf(e, id, "required", "title or spec.bigpicture is required")
}
if s.Kind == KindSolution && s.Meta.Category != "" {
found := false
for _, cat := range v.c.Spec.Categories {
found = found || cat.ID == s.Meta.Category
}
if !found {
v.errf(e, id, "category", "unknown category %q", s.Meta.Category)
}
}
if s.Kind == KindTask {
switch s.Spec.Kind {
case "read-only", "generate", "diagnostic", "planning", "mutating", "deployment", "maintenance":
default:
v.errf(e, id, "task-kind", "spec.kind %q: want read-only, generate, diagnostic, planning, mutating, deployment or maintenance", s.Spec.Kind)
}
if s.Spec.AppliesTo != nil {
for _, sid := range s.Spec.AppliesTo.Solutions {
if _, ok := v.c.Solutions[sid]; !ok {
v.errf(e, id, "solution-ref", "appliesTo: unknown solution %q", sid)
}
}
v.caps(e, id, s.Spec.AppliesTo.Capabilities)
}
}
v.caps(e, id, s.Spec.Capabilities.Required)
v.caps(e, id, s.Spec.Capabilities.Recommended)
v.caps(e, id, s.Spec.Capabilities.Optional)
nq := len(s.Spec.Questions)
for _, pu := range s.Spec.Packages {
if _, ok := v.c.Packages[pu.ID]; !ok {
v.errf(e, id, "package-ref", "unknown package %q", pu.ID)
continue
}
if pu.Profile != "" {
if _, ok := v.c.Profiles[pu.ID+"/"+pu.Profile]; !ok {
v.errf(e, id, "profile-ref", "unknown profile %s/%s", pu.ID, pu.Profile)
}
}
v.cond(e, id, "package "+pu.ID, pu.When, s, nq)
}
seenQ := map[string]bool{}
for i := range s.Spec.Questions {
q := &s.Spec.Questions[i]
qid := id + "." + q.ID
if !questionIDRE.MatchString(q.ID) {
v.errf(e, qid, "id", "question ID %q: letters, digits and _ only", q.ID)
}
if seenQ[q.ID] {
v.errf(e, qid, "duplicate", "duplicate question %q", q.ID)
}
seenQ[q.ID] = true
if !QuestionTypes[q.Type] {
v.errf(e, qid, "type", "unknown question type %q", q.Type)
}
if q.Type == "list" && !ListItemTypes[q.Item] {
v.errf(e, qid, "type", "list needs item: one of the scalar types, got %q", q.Item)
}
if q.Title == "" {
v.errf(e, qid, "required", "question needs a title")
}
switch q.Level {
case "", LevelQuick, LevelGuided, LevelAdvanced:
default:
v.errf(e, qid, "level", "unknown level %q", q.Level)
}
if (q.Type == "select" || q.Type == "multiselect") && len(q.Options) == 0 {
v.errf(e, qid, "options", "%s question without options", q.Type)
}
if q.Type == "secret" && q.Default != nil {
v.errf(e, qid, "secret-default", "a secret question cannot have a default (SEC-01)")
}
seenO := map[string]bool{}
anySelectable := false
for _, o := range q.Options {
if seenO[o.ID] {
v.errf(e, qid, "duplicate", "duplicate option %q", o.ID)
}
seenO[o.ID] = true
if !o.Support.Valid() {
v.errf(e, qid, "support", "option %q: unknown support %q", o.ID, o.Support)
}
if o.Support.Selectable() {
anySelectable = true
} else if o.SupportNote == "" {
v.errf(e, qid, "support-note", "option %q is %s: supportNote must say why", o.ID, o.Support)
}
if o.Recommended && o.Reason == "" {
v.errf(e, qid, "reason", "recommended option %q needs a reason (EX-03)", o.ID)
}
v.cond(e, qid, "option "+o.ID+" enabledWhen", o.EnabledWhen, s, i)
v.effects(e, qid+"/"+o.ID, o.Effects, s)
}
if len(q.Options) > 0 && !anySelectable {
v.errf(e, qid, "unsatisfiable", "no option of %q can be selected", q.ID)
}
if q.Default != nil {
v.optionValue(e, qid, q, q.Default)
}
for _, d := range q.DefaultWhen {
v.cond(e, qid, "defaultWhen", d.When, s, i)
v.optionValue(e, qid, q, d.Value)
}
v.cond(e, qid, "visibleWhen", q.VisibleWhen, s, i)
v.cond(e, qid, "requiredWhen", q.RequiredWhen, s, i)
for _, w := range q.ValidateWhen {
v.cond(e, qid, "validateWhen", w.When, s, i)
}
for _, w := range q.Warnings {
v.cond(e, qid, "warning", w.When, s, i+1)
}
if q.Validation.Pattern != "" {
if _, err := regexp.Compile(q.Validation.Pattern); err != nil {
v.errf(e, qid, "pattern", "validation pattern: %v", err)
}
}
}
seenR := map[string]bool{}
for _, r := range s.Spec.Rules {
rid := id + "#" + r.ID
if r.ID == "" || seenR[r.ID] {
v.errf(e, rid, "rule-id", "every rule needs a unique id")
}
seenR[r.ID] = true
v.cond(e, rid, "rule when", r.When, s, nq)
v.effects(e, rid, r.Effects, s)
switch r.Severity {
case "", "info", "warning", "error":
default:
v.errf(e, rid, "severity", "unknown severity %q", r.Severity)
}
}
for i, f := range s.Spec.Config {
fid := f.ID
if fid == "" {
fid = fmt.Sprint(i)
}
v.fragment(e, id+"#config:"+fid, f, s, nq)
if pkg, _, ok := strings.Cut(f.File, "/"); !ok || v.c.Packages[pkg] == nil {
v.errf(e, id, "fragment-file", "fragment file %q must start with a package directory", f.File)
}
}
for _, st := range s.Spec.Steps {
v.cond(e, id+"#step:"+st.ID, "step", st.When, s, nq)
if st.ForEach == "$modules" && st.Package == "" {
v.errf(e, id+"#step:"+st.ID, "step", "forEach: $modules needs a package")
} else if st.ForEach != "" && st.ForEach != "$modules" {
if q, _ := s.Question(st.ForEach); q == nil {
v.errf(e, id+"#step:"+st.ID, "question-ref", "forEach names unknown question %q", st.ForEach)
}
}
if st.Package != "" && v.c.Packages[st.Package] == nil {
v.errf(e, id+"#step:"+st.ID, "package-ref", "unknown package %q", st.Package)
}
}
for _, ck := range s.Spec.Requirements {
v.cond(e, id+"#check:"+ck.ID, "requirement", ck.When, s, nq)
}
for _, n := range s.Spec.Architecture.Nodes {
v.cond(e, id+"#node:"+n.ID, "node", n.When, s, nq)
}
for _, ed := range s.Spec.Architecture.Edges {
v.cond(e, id+"#edge", "edge", ed.When, s, nq)
}
for _, r := range s.Spec.Related {
if v.c.Lookup(r) == nil {
v.errf(e, id, "related", "related: unknown solution or task %q", r)
}
}
}
func (v *validator) effects(e *Entity, id string, fx Effects, s *Solution) {
for _, t := range []*Targets{fx.Requires, fx.Excludes, fx.Conflicts, fx.Implies, fx.Recommends, fx.Discourages} {
v.targets(e, id, t, s)
}
v.caps(e, id, fx.Provides)
}
func (v *validator) example(x *Example) {
e := &x.Entity
s, ok := v.c.Solutions[x.Spec.Solution]
if !ok {
s, ok = v.c.Tasks[x.Spec.Solution]
}
if !ok {
v.errf(e, x.Key(), "solution-ref", "example of unknown solution %q", x.Spec.Solution)
return
}
for k, val := range x.Spec.Parameters {
q, _ := s.Question(k)
if q == nil {
v.errf(e, x.Key(), "question-ref", "unknown parameter %q", k)
continue
}
v.optionValue(e, x.Key(), q, val)
}
if x.Meta.Title == "" {
v.errf(e, x.Key(), "required", "an example needs a title")
}
}
func (v *validator) source(k *KnowledgeSource) {
e := &k.Entity
if _, ok := v.c.Packages[k.Spec.Package]; !ok {
v.errf(e, k.Meta.ID, "package-ref", "unknown package %q", k.Spec.Package)
}
if k.Spec.Type != "manual" {
v.errf(e, k.Meta.ID, "type", "type %q: only manual is supported", k.Spec.Type)
}
if k.Spec.Format != "markdown" {
v.errf(e, k.Meta.ID, "format", "format %q: only markdown is supported", k.Spec.Format)
}
switch k.Spec.Layout {
case "", "core-manual", "docs-tree":
default:
v.errf(e, k.Meta.ID, "layout", "layout %q: want core-manual or docs-tree", k.Spec.Layout)
}
if k.Spec.Root != "" && !SafeRelPath(k.Spec.Root) {
v.errf(e, k.Meta.ID, "path", "root %q: want a clean relative path", k.Spec.Root)
}
if !SafeRelPath(k.Spec.Repository) {
v.errf(e, k.Meta.ID, "path", "repository %q: want a plain name", k.Spec.Repository)
}
for _, t := range k.Spec.Topics {
v.caps(e, k.Meta.ID+"/"+t.Slug, t.Capabilities)
}
}
+327
View File
@@ -0,0 +1,327 @@
// Package cli implements the guide's commands -- solution, task,
// knowledge and open -- with yet's conventions (stdlib flag, --json on
// every command, data on stdout, messages on stderr, stable exit codes).
// The guide's own program calls Run from main; yet does not embed it.
package cli
import (
"bufio"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
"yetano.dev/yetano/core/solutions/engine"
"yetano.dev/yetano/core/solutions/knowledge"
"yetano.dev/yetano/core/solutions/store"
)
// Exit codes, the same as yet's (yet/internal/cliutil). 0-3 are the
// family-wide ones (docs/program-conventions.md in the meta-repo); 3 is
// "interrupted" there, so "not found" is 7 (owner decision 2026-12-01,
// it was 3 up to solutions/v0.1.0).
const (
ExitOK = 0
ExitError = 1
ExitUsage = 2
ExitInterrupted = 3 // stopped by SIGINT/SIGTERM (the context was cancelled)
ExitConflict = 4
ExitNotFound = 7
)
// Env is what the embedding program provides.
type Env struct {
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
// Interactive: stdin and stdout are a terminal. Without it no command
// ever waits for input (CLI-03).
Interactive bool
// Program is the command name in messages.
Program string
// Catalogs are default catalog directories (an installed knowledge
// bundle); --catalog and $YETANO_SOLUTIONS_CATALOG come first.
Catalogs []string
// StoreDir keeps instances, sessions, presets (from core/paths).
StoreDir string
// Version is stamped into lock files.
Version string
// Getenv defaults to os.Getenv.
Getenv func(string) string
}
type app struct {
env Env
ctx context.Context
catDir string
locale string
cat *catalog.Catalog
ix *knowledge.Index
eng *engine.Engine
store store.Store
jsonOut bool
}
// exitErr carries an exit code.
type exitErr struct {
code int
err error
}
func (e exitErr) Error() string { return e.err.Error() }
func fail(code int, f string, a ...any) error { return exitErr{code, fmt.Errorf(f, a...)} }
// Run runs one command; args start with the command name.
func Run(ctx context.Context, args []string, env Env) int {
if env.Getenv == nil {
env.Getenv = os.Getenv
}
if env.Program == "" {
env.Program = "yetano-solutions"
}
if env.Stdin == nil {
env.Stdin = os.Stdin
}
a := &app{env: env, ctx: ctx, store: store.Store{Dir: env.StoreDir}}
if env.Version != "" {
engine.GeneratorVersion = env.Version
}
err := a.dispatch(args)
if err == nil {
return ExitOK
}
if errors.Is(err, flag.ErrHelp) {
return ExitOK
}
code := ExitError
var ee exitErr
if errors.As(err, &ee) {
code = ee.code
}
switch {
case ctx.Err() != nil:
// whatever failed, it failed because we were told to stop
code = ExitInterrupted
case errors.Is(err, engine.ErrNotFound), errors.Is(err, store.ErrNotFound):
code = ExitNotFound
case errors.Is(err, engine.ErrModified):
code = ExitConflict
case errors.Is(err, engine.ErrIncomplete):
code = ExitUsage
}
if a.jsonOut {
enc := json.NewEncoder(env.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(map[string]any{"error": err.Error(), "code": code})
} else if err.Error() != "" {
fmt.Fprintf(env.Stderr, "error: %v\n", err)
}
return code
}
func (a *app) dispatch(args []string) error {
// global flags before the command (--catalog dir solution list) move
// behind it, where every subcommand's flag set parses them
var lead []string
for len(args) > 0 && strings.HasPrefix(args[0], "-") && args[0] != "-h" && args[0] != "--help" {
lead = append(lead, args[0])
name := strings.TrimLeft(args[0], "-")
args = args[1:]
if (name == "catalog" || name == "locale") && len(args) > 0 {
lead = append(lead, args[0])
args = args[1:]
}
}
if len(lead) > 0 && len(args) > 0 {
args = append(append([]string{}, args...), lead...)
}
if len(args) == 0 {
return a.usage("")
}
cmd, rest := args[0], args[1:]
switch cmd {
case "solution", "solutions":
return a.solution(rest)
case "task", "tasks":
return a.task(rest)
case "knowledge":
return a.knowledge(rest)
case "open":
return a.open(rest)
case "help", "-h", "--help":
return a.usage("")
}
return a.usage(cmd)
}
// Usage is the help text.
const Usage = `Solutions Guide -- describe what you want to achieve, get native configuration:
solution list|search|show|setup|generate|validate|plan|doctor
solution config show|explain, architecture, handbook, package
solution instance list|show|export|import|delete
solution preset list|save|show|export|import|delete
solution catalog validate|test|coverage
task list|search|show|run
knowledge search|show|status|backlinks|coverage
open <yetano:reference>
Common flags: --catalog DIR, --locale de, --json.
`
func (a *app) usage(unknown string) error {
if unknown != "" {
fmt.Fprintf(a.env.Stderr, "unknown command %q\n\n", unknown)
}
fmt.Fprint(a.env.Stderr, Usage)
if unknown != "" {
return exitErr{ExitUsage, errors.New("")}
}
return nil
}
// flags makes a flag set with the common flags.
func (a *app) flags(name string) *flag.FlagSet {
fs := flag.NewFlagSet(a.env.Program+" "+name, flag.ContinueOnError)
fs.SetOutput(a.env.Stderr)
fs.StringVar(&a.catDir, "catalog", "", "catalog directory (default: $YETANO_SOLUTIONS_CATALOG, then the installed bundle)")
fs.StringVar(&a.locale, "locale", "", "language of texts (en, de); default from $LANG")
fs.BoolVar(&a.jsonOut, "json", false, "machine-readable output")
return fs
}
func (a *app) parse(fs *flag.FlagSet, args []string) error {
// allow flags after positional arguments (yet does the same)
var flags, pos []string
for i := 0; i < len(args); i++ {
s := args[i]
if s == "--" {
pos = append(pos, args[i+1:]...)
break
}
if strings.HasPrefix(s, "-") && len(s) > 1 {
flags = append(flags, s)
name := strings.TrimLeft(s, "-")
if !strings.Contains(name, "=") {
if f := fs.Lookup(name); f != nil {
if bf, ok := f.Value.(interface{ IsBoolFlag() bool }); !ok || !bf.IsBoolFlag() {
if i+1 < len(args) {
flags = append(flags, args[i+1])
i++
}
}
}
}
continue
}
pos = append(pos, s)
}
if err := fs.Parse(flags); err != nil {
if errors.Is(err, flag.ErrHelp) {
return err
}
return exitErr{ExitUsage, err}
}
return fs.Parse(append([]string{"--"}, pos...))
}
// load finds and loads the catalog and the index.
func (a *app) load() error {
if a.cat != nil {
return nil
}
if a.locale == "" {
lang := a.env.Getenv("LANG")
if strings.HasPrefix(lang, "de") {
a.locale = "de"
} else {
a.locale = "en"
}
}
candidates := []string{a.catDir, a.env.Getenv("YETANO_SOLUTIONS_CATALOG")}
candidates = append(candidates, a.env.Catalogs...)
dir := ""
for _, c := range candidates {
if c == "" {
continue
}
if _, err := os.Stat(filepath.Join(c, "catalog.yaml")); err == nil {
dir = c
break
}
if c == a.catDir {
return fail(ExitUsage, "--catalog %s: no catalog.yaml there", c)
}
}
if dir == "" {
return fail(ExitNotFound, "no solutions catalog found: pass --catalog <dir> or set YETANO_SOLUTIONS_CATALOG (the meta-repo's assets/solutions)")
}
c, err := catalog.Load(dir)
if err != nil {
return err
}
a.cat = c
a.ix = knowledge.Build(c)
a.eng = engine.New(c)
return nil
}
func (a *app) out() io.Writer { return a.env.Stdout }
func (a *app) printJSON(v any) error {
enc := json.NewEncoder(a.env.Stdout)
enc.SetIndent("", " ")
return enc.Encode(v)
}
func (a *app) say(f string, args ...any) { fmt.Fprintf(a.env.Stdout, f, args...) }
func (a *app) note(f string, args ...any) { fmt.Fprintf(a.env.Stderr, f, args...) }
// tr localizes a meta field.
func (a *app) tr(t catalog.Translations, field, base string) string {
return engine.Tr(t, a.locale, field, base)
}
func (a *app) readLine(r *bufio.Reader) (string, error) {
s, err := r.ReadString('\n')
if err != nil && (s == "" || !errors.Is(err, io.EOF)) {
return "", err
}
return strings.TrimSpace(s), nil
}
func sortedKeys[V any](m map[string]V) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
sort.Strings(out)
return out
}
func wrap(s string, width int, indent string) string {
words := strings.Fields(s)
var b strings.Builder
line := 0
for _, w := range words {
if line > 0 && line+len(w)+1 > width {
b.WriteString("\n" + indent)
line = 0
} else if line > 0 {
b.WriteByte(' ')
line++
}
b.WriteString(w)
line += len(w)
}
return b.String()
}
+168
View File
@@ -0,0 +1,168 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
type result struct {
code int
stdout, stderr string
}
func run(t *testing.T, store string, args ...string) result {
t.Helper()
var out, errb bytes.Buffer
code := Run(context.Background(), args, Env{
Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errb,
Program: "yetano-solutions", StoreDir: store, Catalogs: []string{"../engine/testdata/cat"},
Getenv: func(string) string { return "" },
})
return result{code, out.String(), errb.String()}
}
// Scenario D: CI use without a terminal (ACC-D, CLI-03).
func TestNonInteractive(t *testing.T) {
store := t.TempDir()
out := filepath.Join(t.TempDir(), "gen")
// missing answers: exit 2, never a prompt
r := run(t, store, "solution", "setup", "app-run", "--json")
if r.code != ExitUsage || !strings.Contains(r.stdout, `"missing"`) || !strings.Contains(r.stdout, "hosts") {
t.Fatalf("missing: %d %s %s", r.code, r.stdout, r.stderr)
}
// invalid value: exit 2
if r := run(t, store, "solution", "setup", "app-run", "--set", "hosts=bad_host!"); r.code != ExitUsage {
t.Errorf("invalid value: %d %s", r.code, r.stderr)
}
// unknown question: exit 2
if r := run(t, store, "solution", "setup", "app-run", "--set", "nope=1"); r.code != ExitUsage {
t.Errorf("unknown question: %d", r.code)
}
// unknown solution: exit 3
if r := run(t, store, "solution", "show", "nope"); r.code != ExitNotFound {
t.Errorf("unknown solution: %d", r.code)
}
// complete: files written, instance saved
r = run(t, store, "solution", "setup", "app-run", "--set", "hosts=a.example.org", "--name", "prod", "--save", "--output", out)
if r.code != 0 {
t.Fatalf("setup: %d %s", r.code, r.stderr)
}
for _, f := range []string{"solution.yaml", "solution.lock.yaml", "config/app/app.yaml", "deployment-plan.yaml", "handbook/index.md", "architecture/graph.json"} {
if _, err := os.Stat(filepath.Join(out, f)); err != nil {
t.Errorf("missing %s", f)
}
}
// regenerate from the manifest: same files, exit 0
if r := run(t, store, "solution", "generate", "--file", filepath.Join(out, "solution.yaml"), "--output", out, "--locked"); r.code != 0 {
t.Fatalf("regenerate: %d %s", r.code, r.stderr)
}
// a hand edit: exit 4 (conflict)
os.WriteFile(filepath.Join(out, "config/app/app.yaml"), []byte("# mine\n"), 0o644)
if r := run(t, store, "solution", "generate", "--file", filepath.Join(out, "solution.yaml"), "--output", out); r.code != ExitConflict {
t.Errorf("hand edit: %d %s", r.code, r.stderr)
}
// stored instance works by name
if r := run(t, store, "solution", "validate", "prod"); r.code != 0 {
t.Errorf("validate prod: %d %s %s", r.code, r.stdout, r.stderr)
}
r = run(t, store, "solution", "instance", "list", "--json")
var rows []map[string]string
if err := json.Unmarshal([]byte(r.stdout), &rows); err != nil || len(rows) != 1 || rows[0]["status"] != "Configured" {
t.Errorf("instance list: %s %v", r.stdout, err)
}
// preset from it; a new instance needs only the instance-specific answer
if r := run(t, store, "solution", "preset", "save", "mine", "--from", "prod"); r.code != 0 {
t.Fatalf("preset: %d %s", r.code, r.stderr)
}
if r := run(t, store, "solution", "setup", "app-run", "--preset", "mine", "--set", "hosts=b.example.org", "--json"); r.code != 0 {
t.Errorf("setup with preset: %d %s", r.code, r.stderr)
}
// explain
r = run(t, store, "solution", "config", "explain", "prod", "app/app.yaml", "limits.max")
if r.code != 0 || !strings.Contains(r.stdout, "profile:app/base") {
t.Errorf("explain: %d %s %s", r.code, r.stdout, r.stderr)
}
}
func TestStateJSONIsTheAPI(t *testing.T) {
store := t.TempDir()
f := filepath.Join(t.TempDir(), "s.yaml")
os.WriteFile(f, []byte("apiVersion: yetano.dev/v1\nkind: WizardSession\nmetadata: {name: x}\nspec:\n solution: {id: app-run}\n mode: guided\n parameters: {hosts: [a.example.org], identity: central}\n"), 0o644)
r := run(t, store, "solution", "state", "--file", f)
var st map[string]any
if err := json.Unmarshal([]byte(r.stdout), &st); err != nil {
t.Fatalf("%v: %s %s", err, r.stdout, r.stderr)
}
if st["complete"] != false || st["next"] != "realm" {
t.Errorf("state: complete=%v next=%v", st["complete"], st["next"])
}
}
func TestSearchOpenKnowledge(t *testing.T) {
store := t.TempDir()
if r := run(t, store, "solution", "search", "run", "app"); r.code != 0 || !strings.Contains(r.stdout, "yetano:solution/app-run") {
t.Errorf("search: %d %s", r.code, r.stdout)
}
if r := run(t, store, "open", "yetano:solution/app-run"); r.code != 0 {
t.Errorf("open: %d %s", r.code, r.stderr)
}
if r := run(t, store, "open", "yetano:solution/missing"); r.code != ExitNotFound {
t.Errorf("open missing: %d", r.code)
}
if r := run(t, store, "open", "not a ref"); r.code != ExitUsage {
t.Errorf("open bad: %d", r.code)
}
if r := run(t, store, "solution", "catalog", "validate"); r.code != 0 {
t.Errorf("catalog validate: %d %s %s", r.code, r.stdout, r.stderr)
}
if r := run(t, store, "nonsense"); r.code != ExitUsage {
t.Errorf("unknown command: %d", r.code)
}
}
func TestInteractiveWizard(t *testing.T) {
store := t.TempDir()
out := filepath.Join(t.TempDir(), "gen")
var o, e bytes.Buffer
// size: Enter (default small), hosts: a.example.org, then actions: 6 export, 8 quit
in := strings.NewReader("\na.example.org\n6\n8\n")
code := Run(context.Background(), []string{"solution", "setup", "app-run", "--output", out}, Env{
Stdin: in, Stdout: &o, Stderr: &e, Interactive: true, Program: "yetano-solutions", StoreDir: store,
Catalogs: []string{"../engine/testdata/cat"}, Getenv: func(string) string { return "" },
})
if code != 0 {
t.Fatalf("%d\n%s\n%s", code, o.String(), e.String())
}
for _, want := range []string{"[1/2] How big?", "(recommended)", "YOUR SOLUTION", "Actions:"} {
if !strings.Contains(o.String(), want) {
t.Errorf("output lacks %q:\n%s", want, o.String())
}
}
if _, err := os.Stat(filepath.Join(out, "config/app/app.yaml")); err != nil {
t.Error("export did not write the configuration")
}
}
// Ctrl-C: a cancelled context is exit 3, the family-wide "interrupted"
// (docs/program-conventions.md); "not found" moved to 7 for it.
func TestInterrupted(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
var out, errb bytes.Buffer
code := Run(ctx, []string{"solution", "show", "nope"}, Env{
Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errb,
Program: "yetano-solutions", StoreDir: t.TempDir(), Catalogs: []string{"../engine/testdata/cat"},
Getenv: func(string) string { return "" },
})
if code != ExitInterrupted || ExitInterrupted != 3 || ExitNotFound != 7 {
t.Fatalf("cancelled: exit %d (%s)", code, errb.String())
}
if r := run(t, t.TempDir(), "solution", "show", "nope"); r.code != 7 {
t.Fatalf("not found: exit %d", r.code)
}
}
+194
View File
@@ -0,0 +1,194 @@
package cli
import (
"context"
"errors"
"fmt"
"net"
"os"
"runtime"
"strings"
"syscall"
"time"
"yetano.dev/yetano/core/solutions/engine"
)
// doctor runs a state's requirement checks on this machine (DR-01/03).
// Only kinds it can really check get PASS/WARNING/ERROR; everything else
// stays NOT_CHECKED with the command to run -- never a fake PASS.
func (a *app) doctor(args []string) error {
fs := a.flags("solution doctor")
f := a.instFlags(fs)
offline := fs.Bool("offline", false, "skip checks that need the network (DNS)")
if err := a.parse(fs, args); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(a.ctx, 30*time.Second)
defer cancel()
worst := 0
for i := range st.Checks {
c := &st.Checks[i]
if c.Status == engine.CheckNotApplicable {
continue
}
runCheck(ctx, c, *offline)
if c.Status == engine.CheckError || c.Status == engine.CheckBlocked {
worst = 1
}
}
if a.jsonOut {
if err := a.printJSON(map[string]any{"solution": st.Solution.ID, "instance": st.Instance, "checks": st.Checks}); err != nil {
return err
}
} else {
for _, c := range st.Checks {
a.say("%-14s %s\n", c.Status, c.Title)
if c.Note != "" {
a.say("%-14s %s\n", "", wrap(c.Note, 62, strings.Repeat(" ", 15)))
}
if c.Status == engine.CheckNotChecked && c.Run != "" {
a.say("%-14s run: %s\n", "", c.Run)
}
if (c.Status == engine.CheckWarning || c.Status == engine.CheckError) && c.Hint != "" {
a.say("%-14s hint: %s\n", "", wrap(c.Hint, 60, strings.Repeat(" ", 21)))
}
}
}
if worst > 0 {
return exitErr{ExitError, errors.New("")}
}
return nil
}
func sevStatus(sev string) string {
switch sev {
case "warning":
return engine.CheckWarning
case "info":
return engine.CheckInfo
}
return engine.CheckError
}
func runCheck(ctx context.Context, c *engine.CheckResult, offline bool) {
p := c.Params
switch c.Kind {
case "os":
want := strings.Split(p["want"], ",")
for _, w := range want {
if w == runtime.GOOS {
c.Status, c.Note = engine.CheckPass, runtime.GOOS
return
}
}
c.Status, c.Note = sevStatus(c.Severity), runtime.GOOS+" is not supported"
case "port":
var busy, denied []string
for _, port := range strings.Split(p["port"], ",") {
l, err := net.Listen("tcp", ":"+strings.TrimSpace(port))
if err == nil {
l.Close()
continue
}
if errors.Is(err, syscall.EACCES) || errors.Is(err, os.ErrPermission) {
denied = append(denied, port)
} else {
busy = append(busy, port)
}
}
switch {
case len(busy) > 0:
c.Status, c.Note = sevStatus(c.Severity), "in use: "+strings.Join(busy, ", ")
case len(denied) > 0:
c.Status, c.Note = engine.CheckNotChecked, "no permission to test port(s) "+strings.Join(denied, ", ")+" as this user"
default:
c.Status = engine.CheckPass
}
case "file":
var missing []string
for _, f := range strings.Split(p["paths"], ",") {
if _, err := os.Stat(strings.TrimSpace(f)); err != nil {
missing = append(missing, f)
}
}
if len(missing) > 0 {
c.Status, c.Note = sevStatus(c.Severity), "missing: "+strings.Join(missing, ", ")
} else {
c.Status = engine.CheckPass
}
case "dns":
if offline {
c.Status, c.Note = engine.CheckNotChecked, "offline"
return
}
dnsCheck(ctx, c)
case "manual":
c.Status = engine.CheckInfo
c.Note = "check this yourself"
default:
c.Status = engine.CheckNotChecked
}
}
func dnsCheck(ctx context.Context, c *engine.CheckResult) {
p := c.Params
r := net.DefaultResolver
var problems []string
names := strings.Split(p["names"], ",")
for _, name := range names {
name = p["prefix"] + strings.TrimSpace(name)
if name == "" {
continue
}
qctx, cancel := context.WithTimeout(ctx, 5*time.Second)
switch strings.ToUpper(p["type"]) {
case "MX":
mx, err := r.LookupMX(qctx, name)
if err != nil || len(mx) == 0 {
problems = append(problems, name+": no MX record")
break
}
if want := strings.TrimSuffix(p["want"], "."); want != "" {
ok := false
for _, m := range mx {
ok = ok || strings.EqualFold(strings.TrimSuffix(m.Host, "."), want)
}
if !ok {
problems = append(problems, fmt.Sprintf("%s: MX does not point to %s", name, want))
}
}
case "A":
if ips, err := r.LookupIPAddr(qctx, name); err != nil || len(ips) == 0 {
problems = append(problems, name+": does not resolve")
}
case "TXT":
txt, err := r.LookupTXT(qctx, name)
found := false
for _, t := range txt {
found = found || strings.Contains(t, p["contains"])
}
if err != nil || !found {
problems = append(problems, fmt.Sprintf("%s: no TXT record with %q", name, p["contains"]))
}
default:
c.Status = engine.CheckNotChecked
cancel()
return
}
cancel()
}
if ctx.Err() != nil {
c.Status, c.Note = engine.CheckNotChecked, "timed out"
return
}
if len(problems) > 0 {
c.Status, c.Note = sevStatus(c.Severity), strings.Join(problems, "; ")
return
}
c.Status = engine.CheckPass
}
+623
View File
@@ -0,0 +1,623 @@
package cli
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
"yetano.dev/yetano/core/solutions/engine"
"yetano.dev/yetano/core/solutions/knowledge"
"yetano.dev/yetano/core/solutions/ref"
)
// ---- search --------------------------------------------------------------------
func (a *app) searchCmd(args []string, kinds []string) error {
fs := a.flags("search")
all := fs.Bool("all", false, "search everything (manuals, packages, Big Picture, ...)")
limit := fs.Int("limit", 8, "hits per group")
if err := a.parse(fs, args); err != nil {
return err
}
if fs.NArg() == 0 {
return fail(ExitUsage, "usage: search <words>")
}
if err := a.load(); err != nil {
return err
}
if *all {
kinds = nil
}
groups := a.ix.Search(strings.Join(fs.Args(), " "), knowledge.SearchOptions{Kinds: kinds, Limit: *limit, Locale: a.locale})
if a.jsonOut {
if groups == nil {
groups = []knowledge.Group{}
}
return a.printJSON(groups)
}
if len(groups) == 0 {
a.note("nothing found\n")
return exitErr{ExitNotFound, errors.New("")}
}
for _, g := range groups {
a.say("%s\n", g.Title)
for _, h := range g.Hits {
a.say(" %-44s %s\n", trunc(h.Title, 44), h.Ref)
}
a.say("\n")
}
return nil
}
func trunc(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n-1]) + "…"
}
// ---- instances --------------------------------------------------------------------
func (a *app) instance(args []string) error {
if len(args) == 0 {
args = []string{"list"}
}
fs := a.flags("solution instance " + args[0])
if err := a.parse(fs, args[1:]); err != nil {
return err
}
switch args[0] {
case "list", "ls":
inst, err := a.store.Instances()
if err != nil {
return err
}
sess, err := a.store.Sessions()
if err != nil {
return err
}
type row struct {
Name string `json:"name"`
Kind string `json:"kind"`
Solution string `json:"solution"`
Status string `json:"status"`
Updated string `json:"updated"`
}
var rows []row
for _, list := range [][]string{inst, sess} {
for _, n := range list {
in, err := a.store.LoadInstance(n)
if err != nil {
continue
}
status := "Draft"
if in.Kind == catalog.KindInstance {
status = "Configured"
if a.load() == nil {
if st, err := a.evaluate(in, nil); err == nil && !st.Complete {
status = "Invalid"
}
}
}
rows = append(rows, row{n, in.Kind, in.Spec.Solution.ID, status, in.Metadata.Updated})
}
}
if a.jsonOut {
if rows == nil {
rows = []row{}
}
return a.printJSON(rows)
}
if len(rows) == 0 {
a.note("no saved solutions (save one with: %s solution setup <id> --save)\n", a.env.Program)
}
for _, r := range rows {
a.say("%-24s %-14s %-11s %s\n", r.Name, r.Solution, r.Status, r.Updated)
}
return nil
case "show", "export":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance %s <name>", a.env.Program, args[0])
}
in, err := a.store.LoadInstance(fs.Arg(0))
if err != nil {
return err
}
if a.jsonOut {
return a.printJSON(in)
}
b, err := engine.Marshal(in)
if err != nil {
return err
}
a.say("%s", b)
return nil
case "import":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance import <file>", a.env.Program)
}
f, err := os.Open(fs.Arg(0))
if err != nil {
return fail(ExitNotFound, "%v", err)
}
defer f.Close()
in, err := engine.ReadInstance(f)
if err != nil {
return fail(ExitUsage, "%v", err)
}
if err := a.load(); err != nil {
return err
}
if _, err := a.evaluate(in, nil); err != nil {
return err
}
if err := a.store.SaveInstance(in); err != nil {
return err
}
a.note("imported %s\n", in.Metadata.Name)
return nil
case "delete", "rm":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance delete <name>", a.env.Program)
}
return a.store.DeleteInstance(fs.Arg(0))
case "duplicate", "cp":
if fs.NArg() != 2 {
return fail(ExitUsage, "usage: %s solution instance duplicate <name> <new-name>", a.env.Program)
}
in, err := a.store.LoadInstance(fs.Arg(0))
if err != nil {
return err
}
in.Metadata.Name, in.Metadata.Created = fs.Arg(1), ""
return a.store.SaveInstance(in)
case "favorite":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution instance favorite <name>", a.env.Program)
}
in, err := a.store.LoadInstance(fs.Arg(0))
if err != nil {
return err
}
in.Metadata.Favorite = !in.Metadata.Favorite
return a.store.SaveInstance(in)
}
return a.usage("solution instance " + args[0])
}
// ---- presets ------------------------------------------------------------------------
func (a *app) preset(args []string) error {
if len(args) == 0 {
args = []string{"list"}
}
fs := a.flags("solution preset " + args[0])
from := fs.String("from", "", "save: the instance to take the answers from")
file := fs.String("file", "", "save: a solution.yaml to take the answers from")
if err := a.parse(fs, args[1:]); err != nil {
return err
}
switch args[0] {
case "list", "ls":
names, err := a.store.Presets()
if err != nil {
return err
}
if a.jsonOut {
if names == nil {
names = []string{}
}
return a.printJSON(names)
}
for _, n := range names {
p, err := a.store.LoadPreset(n)
if err != nil {
continue
}
a.say("%-24s %-14s %d answer(s)\n", n, p.Spec.Solution, len(p.Spec.Parameters))
}
return nil
case "save":
if fs.NArg() != 1 || (*from == "" && *file == "") {
return fail(ExitUsage, "usage: %s solution preset save <name> --from <instance> | --file <solution.yaml>", a.env.Program)
}
if err := a.load(); err != nil {
return err
}
var in *engine.Instance
var err error
if *file != "" {
in, err = a.instanceFrom(*file, fs)
} else {
in, err = a.store.LoadInstance(*from)
}
if err != nil {
return err
}
s := a.cat.Lookup(in.Spec.Solution.ID)
if s == nil {
return fmt.Errorf("%w: solution %s", engine.ErrNotFound, in.Spec.Solution.ID)
}
p := engine.PresetFrom(fs.Arg(0), in, s)
if err := a.store.SavePreset(p); err != nil {
return err
}
a.note("saved preset %s (%d answers; instance-specific and secret answers are left out)\n", p.Metadata.Name, len(p.Spec.Parameters))
return nil
case "show", "export":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution preset show <name>", a.env.Program)
}
p, err := a.store.LoadPreset(fs.Arg(0))
if err != nil {
return err
}
if a.jsonOut {
return a.printJSON(p)
}
b, _ := engine.Marshal(p)
a.say("%s", b)
return nil
case "import":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution preset import <file>", a.env.Program)
}
f, err := os.Open(fs.Arg(0))
if err != nil {
return fail(ExitNotFound, "%v", err)
}
defer f.Close()
p, err := engine.ReadPreset(f)
if err != nil {
return fail(ExitUsage, "%v", err)
}
return a.store.SavePreset(p)
case "delete", "rm":
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution preset delete <name>", a.env.Program)
}
return a.store.DeletePreset(fs.Arg(0))
}
return a.usage("solution preset " + args[0])
}
// ---- catalog --------------------------------------------------------------------------
func (a *app) catalogCmd(args []string) error {
if len(args) == 0 {
return fail(ExitUsage, "usage: %s solution catalog validate|test|coverage", a.env.Program)
}
fs := a.flags("solution catalog " + args[0])
update := fs.Bool("update", false, "test: rewrite the golden files")
if err := a.parse(fs, args[1:]); err != nil {
return err
}
if err := a.load(); err != nil {
var ee exitErr
if a.cat != nil && !errors.As(err, &ee) {
// print every load issue, not just the first
for _, i := range a.cat.Issues {
a.note("%s\n", i)
}
}
return err
}
switch args[0] {
case "validate", "lint":
issues := knowledge.Lint(a.ix)
errs := 0
for _, i := range issues {
if i.Severity == "error" {
errs++
}
}
if a.jsonOut {
if issues == nil {
issues = []catalog.Issue{}
}
_ = a.printJSON(issues)
} else {
for _, i := range issues {
a.say("%-7s %s\n", strings.ToUpper(i.Severity), i)
}
a.note("%d solution(s), %d task(s), %d package(s), %d capabilities, %d manual topics: %d error(s), %d warning(s)\n",
len(a.cat.Solutions), len(a.cat.Tasks), len(a.cat.Packages), len(a.cat.Capabilities), len(a.ix.Topics), errs, len(issues)-errs)
}
if errs > 0 {
return exitErr{ExitError, errors.New("")}
}
return nil
case "test":
return a.catalogTest(*update)
case "schema":
dir := filepath.Join(a.cat.Root, "schema")
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
for _, name := range sortedKeys(catalog.SchemaKinds) {
b, err := json.MarshalIndent(catalog.JSONSchema(name), "", " ")
if err != nil {
return err
}
if err := os.WriteFile(filepath.Join(dir, name+".schema.json"), append(b, '\n'), 0o644); err != nil {
return err
}
}
a.note("wrote %d schemas to %s\n", len(catalog.SchemaKinds), dir)
return nil
case "coverage":
cov := knowledge.ComputeCoverage(a.ix)
if a.jsonOut {
return a.printJSON(cov)
}
a.say("Yetano Knowledge Coverage (%d packages in the catalog)\n\n", cov.Packages)
for _, m := range cov.Metrics {
a.say(" %-38s %5.1f%% (%d/%d)\n", m.Name, m.Pct, m.Have, m.Total)
}
if len(cov.ProgramsWithout) > 0 {
a.say("\nBig Picture programs not in the catalog yet: %s\n", strings.Join(cov.ProgramsWithout, ", "))
}
return nil
}
return a.usage("solution catalog " + args[0])
}
// catalogTest evaluates every example, generates its output and compares
// it with the golden files next to the solution (EX-02, QS-08). An example
// that stops being complete or changes output fails (ACC-J).
func (a *app) catalogTest(update bool) error {
failed := 0
for _, key := range catalog.SortedIDs(a.cat.Examples) {
x := a.cat.Examples[key]
s := a.cat.Lookup(x.Spec.Solution)
in := engine.NewInstance(x.Meta.ID, s, x.Spec.Mode)
in.Kind = catalog.KindInstance
for k, v := range x.Spec.Parameters {
in.Spec.Parameters[k] = v
}
in.Spec.Locale = "en"
st, err := a.eng.Evaluate(in, nil)
if err != nil {
return err
}
out, err := a.eng.Generate(st, in, nil, false)
if err != nil {
a.say("FAIL %s: %v\n", key, err)
failed++
continue
}
dir := filepath.Join(a.cat.Root, filepath.FromSlash(path.Dir(path.Dir(x.File))), "testdata", x.Meta.ID)
if update {
if err := os.RemoveAll(dir); err != nil {
return err
}
for _, f := range out.Files {
if f.Kind == "lock" {
continue // hashes of the whole catalog: not stable across unrelated edits
}
p := filepath.Join(dir, filepath.FromSlash(f.Path))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
if err := os.WriteFile(p, f.Content, 0o644); err != nil {
return err
}
}
a.say("UPDATED %s (%d files)\n", key, len(out.Files)-1)
continue
}
var diffs []string
want := map[string]bool{}
for _, f := range out.Files {
if f.Kind == "lock" {
continue
}
want[f.Path] = true
b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(f.Path)))
if err != nil {
diffs = append(diffs, f.Path+" (no golden file)")
} else if !bytes.Equal(b, f.Content) {
diffs = append(diffs, f.Path+" ("+firstDiff(b, f.Content)+")")
}
}
_ = filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
if err == nil && !d.IsDir() {
rel, _ := filepath.Rel(dir, p)
if !want[filepath.ToSlash(rel)] {
diffs = append(diffs, filepath.ToSlash(rel)+" (no longer generated)")
}
}
return nil
})
sort.Strings(diffs)
if len(diffs) > 0 {
a.say("FAIL %s\n", key)
for _, d := range diffs {
a.say(" %s\n", d)
}
failed++
continue
}
a.say("ok %s\n", key)
}
if failed > 0 {
a.note("%d example(s) failed; after an intended change: make golden (catalog test --update) and review the diff\n", failed)
return exitErr{ExitError, errors.New("")}
}
return nil
}
func firstDiff(a, b []byte) string {
la, lb := strings.Split(string(a), "\n"), strings.Split(string(b), "\n")
for i := 0; i < len(la) || i < len(lb); i++ {
var x, y string
if i < len(la) {
x = la[i]
}
if i < len(lb) {
y = lb[i]
}
if x != y {
return fmt.Sprintf("line %d: golden %q, now %q", i+1, trunc(x, 50), trunc(y, 50))
}
}
return "differs"
}
// ---- knowledge, open ------------------------------------------------------------------
func (a *app) knowledge(args []string) error {
if len(args) == 0 {
return fail(ExitUsage, "usage: %s knowledge search|show|status|backlinks|coverage|validate", a.env.Program)
}
switch args[0] {
case "search":
return a.searchCmd(args[1:], nil)
case "show":
return a.open(args[1:])
case "validate", "lint":
return a.catalogCmd(append([]string{"validate"}, args[1:]...))
case "coverage":
return a.catalogCmd(append([]string{"coverage"}, args[1:]...))
case "status", "index":
fs := a.flags("knowledge " + args[0])
if err := a.parse(fs, args[1:]); err != nil {
return err
}
if err := a.load(); err != nil {
return err
}
kinds := map[string]int{}
for _, e := range a.ix.Entries {
kinds[e.Kind]++
}
st := map[string]any{"catalog": a.cat.Root, "id": a.cat.Meta.ID, "version": a.cat.Meta.Version, "hash": a.cat.Hash(),
"entries": len(a.ix.Entries), "byKind": kinds, "manualTopics": len(a.ix.Topics), "sourcesNotAvailable": a.ix.Missing}
if args[0] == "index" {
st["index"] = a.ix.Entries
}
if a.jsonOut {
return a.printJSON(st)
}
a.say("catalog %s %s (%s)\nentries %d\n", a.cat.Meta.ID, a.cat.Meta.Version, a.cat.Root, len(a.ix.Entries))
for _, k := range sortedKeys(kinds) {
a.say(" %-12s %d\n", k, kinds[k])
}
if len(a.ix.Missing) > 0 {
a.say("not available locally: %s\n", strings.Join(a.ix.Missing, ", "))
}
return nil
case "backlinks":
fs := a.flags("knowledge backlinks")
if err := a.parse(fs, args[1:]); err != nil {
return err
}
if err := a.load(); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s knowledge backlinks <yetano:ref>", a.env.Program)
}
bl := a.ix.BacklinksOf(fs.Arg(0))
if a.jsonOut {
if bl == nil {
bl = []string{}
}
return a.printJSON(bl)
}
for _, b := range bl {
a.say("%s\n", b)
}
return nil
}
return a.usage("knowledge " + args[0])
}
// open shows a reference in the terminal (REF-04): manual text, a
// solution's details, or where it lives.
func (a *app) open(args []string) error {
fs := a.flags("open")
if err := a.parse(fs, args); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s open <yetano:reference>", a.env.Program)
}
if err := a.load(); err != nil {
return err
}
r := fs.Arg(0)
if !strings.HasPrefix(r, "yetano:") {
r = "yetano:" + r
}
res, err := a.ix.Resolve(r)
if err != nil {
return fail(ExitUsage, "%v", err)
}
if !res.Exists {
return fmt.Errorf("%w: %s", engine.ErrNotFound, r)
}
if !res.SectionExists {
return fmt.Errorf("%w: %s has no such section", engine.ErrNotFound, r)
}
if a.jsonOut {
return a.printJSON(res)
}
p, _ := ref.Parse(r)
switch p.Kind {
case ref.Solution:
return a.show([]string{p.Path[0]}, false)
case ref.Task:
return a.show([]string{p.Path[0]}, true)
case ref.Package:
return a.packageCmd([]string{p.Path[0]})
case ref.Manual:
if _, md, err := a.ix.Read(r); err == nil {
a.say("%s", md)
return nil
}
case ref.Example:
if x := a.cat.Examples[p.Path[0]+"/"+p.Path[1]]; x != nil {
b, _ := engine.Marshal(x.Spec)
a.say("# %s\n%s", x.Meta.Title, b)
return nil
}
case ref.Profile:
if pr := a.cat.Profiles[p.Path[0]+"/"+p.Path[1]]; pr != nil {
b, _ := engine.Marshal(pr.Spec)
a.say("# %s\n%s", firstNonEmpty(pr.Meta.Title, pr.Meta.ID), b)
return nil
}
case ref.Capability:
a.say("%s -- %s\n", res.Title, res.Summary)
for _, pr := range a.cat.ProvidersOf(p.Path[0]) {
a.say(" provided by %s\n", pr)
}
for _, b := range a.ix.BacklinksOf(r) {
a.say(" used by %s\n", b)
}
return nil
}
a.say("%s\n", res.Title)
if res.Summary != "" {
a.say("%s\n", wrap(res.Summary, 76, ""))
}
if res.Web != "" {
a.say("web: %s\n", res.Web)
}
if res.CLI != "" {
a.say("cli: %s\n", res.CLI)
}
if res.Note != "" {
a.say("note: %s\n", res.Note)
}
return nil
}
+494
View File
@@ -0,0 +1,494 @@
package cli
import (
"bufio"
"errors"
"fmt"
"os"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
"yetano.dev/yetano/core/solutions/engine"
"yetano.dev/yetano/core/solutions/ref"
"yetano.dev/yetano/core/solutions/store"
)
func (a *app) setup(args []string, task bool) error {
cmd := "solution setup"
if task {
cmd = "task run"
}
fs := a.flags(cmd)
quick := fs.Bool("quick", false, "quick setup: only what is needed, recommended defaults")
guided := fs.Bool("guided", false, "guided setup: the relevant choices, with explanations")
advanced := fs.Bool("advanced", false, "advanced setup: every option")
presetName := fs.String("preset", "", "take answers from a saved preset")
example := fs.String("example", "", "start from an example of the solution")
answers := fs.String("answers", "", "start from the answers in a solution.yaml")
name := fs.String("name", "", "name of the instance (default: the solution ID)")
output := fs.String("output", "", "generate the files into this directory when complete")
save := fs.Bool("save", false, "save the instance (incomplete: as a draft session)")
nonInteractive := fs.Bool("non-interactive", false, "never ask; fail listing what is missing (the default without a terminal)")
platform := fs.String("platform", "", "target platform (linux, freebsd, darwin, windows)")
force := fs.Bool("force", false, "with --output: overwrite files changed by hand")
var sets multi
fs.Var(&sets, "set", "answer as question=value (repeatable; lists comma-separated)")
if err := a.parse(fs, args); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s %s <id> [--quick|--guided|--advanced] [--set q=v]...", a.env.Program, cmd)
}
if err := a.load(); err != nil {
return err
}
s, err := a.lookup(fs.Arg(0), task)
if err != nil {
return err
}
mode := catalog.LevelQuick
switch {
case *advanced:
mode = catalog.LevelAdvanced
case *guided:
mode = catalog.LevelGuided
}
nm := firstNonEmpty(*name, s.Meta.ID)
if err := store.ValidName(nm); err != nil {
return fail(ExitUsage, "%v", err)
}
in := engine.NewInstance(nm, s, mode)
in.Spec.Locale = a.locale
in.Spec.Platform = *platform
if *example != "" {
x := a.cat.Examples[s.Meta.ID+"/"+*example]
if x == nil {
return fmt.Errorf("%w: example %s of %s", engine.ErrNotFound, *example, s.Meta.ID)
}
for k, v := range x.Spec.Parameters {
in.Spec.Parameters[k] = v
}
if !*quick && !*guided && !*advanced && x.Spec.Mode != "" {
in.Spec.Mode = x.Spec.Mode
}
}
if *answers != "" {
f, err := os.Open(*answers)
if err != nil {
return fail(ExitNotFound, "%v", err)
}
from, err := engine.ReadInstance(f)
f.Close()
if err != nil {
return fail(ExitUsage, "%s: %v", *answers, err)
}
for k, v := range from.Spec.Parameters {
in.Spec.Parameters[k] = v
}
in.Spec.Overrides = from.Spec.Overrides
}
for _, kv := range sets {
k, v, ok := strings.Cut(kv, "=")
if !ok {
return fail(ExitUsage, "--set %q: want question=value", kv)
}
if q, _ := s.Question(k); q == nil {
return fail(ExitUsage, "--set %s: %s has no question %q", kv, s.Meta.ID, k)
}
in.Spec.Parameters[k] = v
}
var preset *engine.Preset
if *presetName != "" {
preset, err = a.presetFor(in, *presetName)
if err != nil {
return err
}
in.Spec.Preset = preset.Metadata.Name
if preset.Spec.Mode != "" && !*quick && !*guided && !*advanced {
in.Spec.Mode = preset.Spec.Mode
}
}
kind := ref.Solution
if task {
kind = ref.Task
}
_ = a.store.Touch(ref.For(kind, s.Meta.ID), nm)
if a.env.Interactive && !*nonInteractive && !a.jsonOut {
return a.wizard(in, preset, *output, *force)
}
st, err := a.evaluate(in, preset)
if err != nil {
return err
}
if !st.Complete {
if *save {
in.Kind = catalog.KindSession
if err := a.store.SaveInstance(in); err != nil {
return err
}
a.note("saved draft %s\n", nm)
}
if a.jsonOut {
_ = a.printJSON(map[string]any{"complete": false, "missing": st.Progress.Missing, "messages": st.Messages, "state": st})
return exitErr{ExitUsage, errors.New("")}
}
for _, m := range st.Progress.Missing {
q := findQ(st, m)
a.note("missing: %s (%s) -- --set %s=...\n", m, q.Title, m)
}
for _, q := range st.Questions {
for _, e := range q.Errors {
a.note("invalid: %s: %s\n", q.ID, e)
}
}
a.printMessages(st)
return fmt.Errorf("%w (%s)", engine.ErrIncomplete, strings.Join(st.Progress.Missing, ", "))
}
if *save {
in.Kind = catalog.KindInstance
if err := a.store.SaveInstance(in); err != nil {
return err
}
a.note("saved instance %s\n", nm)
}
if *output != "" {
return a.writeOut(in, st, *output, *force, false, false)
}
if a.jsonOut {
return a.printJSON(st)
}
a.summary(st)
b, _ := engine.Marshal(in)
a.note("\nAnswers (save with --save, or as solution.yaml for '%s solution generate --file'):\n", a.env.Program)
a.say("%s", b)
return nil
}
func findQ(st *engine.State, id string) engine.QuestionState {
for _, q := range st.Questions {
if q.ID == id {
return q
}
}
return engine.QuestionState{ID: id}
}
// summary prints "YOUR SOLUTION" (CLI-02).
func (a *app) summary(st *engine.State) {
w := a.env.Stdout
line := strings.Repeat("-", 60)
fmt.Fprintf(w, "%s\nYOUR SOLUTION: %s\n\n", line, st.Solution.Title)
fmt.Fprintf(w, "Packages:\n")
for _, p := range st.Packages {
if p.Selected {
var mods []string
for _, m := range p.Modules {
if m.Enabled && m.Program != "" {
mods = append(mods, m.Program)
}
}
fmt.Fprintf(w, " + %-10s %s\n", p.ID, strings.Join(mods, " "))
}
}
for _, p := range st.Packages {
if !p.Selected {
fmt.Fprintf(w, " ? %-10s recommended: %s\n", p.ID, strings.Join(p.Reasons, "; "))
}
}
fmt.Fprintf(w, "\nCapabilities:\n")
for _, c := range st.Capabilities {
switch c.Status {
case engine.StRequired, engine.StSelected, engine.StExternal:
fmt.Fprintf(w, " + %s\n", c.Title)
case engine.StRecommended:
fmt.Fprintf(w, " ? %s (recommended)\n", c.Title)
case engine.StMissing, engine.StConflicting:
fmt.Fprintf(w, " ! %s (%s)\n", c.Title, c.Status)
}
}
fmt.Fprintf(w, "\nConfiguration: %d file(s)", len(st.Files))
if st.Complete {
fmt.Fprintf(w, ", complete\n")
} else {
fmt.Fprintf(w, ", INCOMPLETE: %s\n", strings.Join(st.Progress.Missing, ", "))
}
if len(st.Messages) > 0 {
fmt.Fprintf(w, "\nNotes:\n")
for _, m := range st.Messages {
fmt.Fprintf(w, " %-7s %s\n", strings.ToUpper(m.Severity), wrap(m.Text, 66, " "))
}
}
nc := 0
for _, c := range st.Checks {
if c.Status == engine.CheckNotChecked {
nc++
}
}
if nc > 0 {
fmt.Fprintf(w, "\nEnvironment: %d check(s) not run yet -- '%s solution doctor' runs them on the target.\n", nc, a.env.Program)
}
fmt.Fprintf(w, "%s\n", line)
}
// wizard is the interactive CLI wizard (CLI-02). All decisions come from
// the engine: this only asks what the state says, in its order.
func (a *app) wizard(in *engine.Instance, preset *engine.Preset, output string, force bool) error {
r := bufio.NewReader(a.env.Stdin)
w := a.env.Stdout
done := map[string]bool{}
var history []string
st, err := a.evaluate(in, preset)
if err != nil {
return err
}
fmt.Fprintf(w, "Yetano Solutions Guide\n%s\n%s (%s setup)\n\n", strings.Repeat("-", 40), st.Solution.Title, st.Mode)
fmt.Fprintf(w, "Enter keeps the value in [brackets]. ? explains, m manual, a architecture, b back, q save and quit.\n\n")
for {
st, err = a.evaluate(in, preset)
if err != nil {
return err
}
var q *engine.QuestionState
for i := range st.Questions {
x := &st.Questions[i]
if x.Visible && x.Asked && !done[x.ID] {
q = x
break
}
}
if q == nil {
break
}
step, total := 0, 0
for _, x := range st.Questions {
if x.Visible && x.Asked {
total++
if done[x.ID] || x.ID == q.ID {
step++
}
}
}
fmt.Fprintf(w, "[%d/%d] %s\n", step, total, q.Title)
if q.Help != "" {
fmt.Fprintf(w, " %s\n", wrap(q.Help, 70, " "))
}
for i, o := range q.Options {
mark := " "
if !o.Enabled {
mark = "x"
}
rec := ""
if o.Recommended {
rec = " (recommended)"
}
fmt.Fprintf(w, " %s %d. %s%s\n", mark, i+1, o.Title, rec)
if !o.Enabled && o.Disabled != "" {
fmt.Fprintf(w, " not available: %s\n", wrap(o.Disabled, 62, " "))
}
}
def := ""
if q.Value != nil {
def = displayValue(q, q.Value)
}
prompt := "> "
if def != "" {
prompt = fmt.Sprintf("[%s] > ", def)
}
fmt.Fprint(w, prompt)
line, err := a.readLine(r)
if err != nil {
fmt.Fprintln(w)
return a.saveDraft(in, "input ended")
}
switch line {
case "?":
a.explain(q)
continue
case "m":
a.showManual(q, st)
continue
case "a":
fmt.Fprintf(w, "\n%s\n", engine.GraphText(st.Graph))
continue
case "b":
if len(history) > 0 {
last := history[len(history)-1]
history = history[:len(history)-1]
delete(done, last)
}
continue
case "q":
return a.saveDraft(in, "")
case "":
if q.Value == nil && q.Required {
fmt.Fprintf(w, " an answer is needed\n")
continue
}
if q.Value != nil {
in.Spec.Parameters[q.ID] = q.Value
}
default:
in.Spec.Parameters[q.ID] = line
}
st2, err := a.evaluate(in, preset)
if err != nil {
return err
}
if q2 := findQ(st2, q.ID); len(q2.Errors) > 0 {
fmt.Fprintf(w, " %s\n", strings.Join(q2.Errors, "; "))
delete(in.Spec.Parameters, q.ID)
continue
}
for _, s := range st2.Stale {
if s.Question == q.ID {
fmt.Fprintf(w, " %s\n", s.Reason)
delete(in.Spec.Parameters, q.ID)
goto next
}
}
done[q.ID] = true
history = append(history, q.ID)
fmt.Fprintln(w)
next:
}
a.summary(st)
for {
fmt.Fprintf(w, "\nActions:\n 1. Show configuration\n 2. Show architecture\n 3. Show plan\n 4. Read related manual\n 5. Save solution\n 6. Export configuration (generate files)\n 7. Change an answer\n 8. Quit\n> ")
line, err := a.readLine(r)
if err != nil {
return nil
}
switch line {
case "1":
for _, f := range st.Files {
fmt.Fprintf(w, "--- %s\n%s\n", f.Path, f.Content)
}
case "2":
fmt.Fprintf(w, "%s", engine.GraphText(st.Graph))
case "3":
for i, s := range st.Steps {
fmt.Fprintf(w, "%3d. [%s] %s\n", i+1, s.Phase, s.Title)
if s.Run != "" {
fmt.Fprintf(w, " $ %s\n", s.Run)
}
}
case "4":
for _, rf := range st.References {
if res, err := a.ix.Resolve(rf); err == nil {
fmt.Fprintf(w, " %s\n", refLine(res))
}
}
case "5":
in.Kind = catalog.KindInstance
if !st.Complete {
in.Kind = catalog.KindSession
}
if err := a.store.SaveInstance(in); err != nil {
return err
}
fmt.Fprintf(w, "saved %s (%s)\n", in.Metadata.Name, in.Kind)
case "6":
dir := output
if dir == "" {
fmt.Fprintf(w, "directory [./%s] > ", in.Metadata.Name)
d, _ := a.readLine(r)
dir = firstNonEmpty(d, "./"+in.Metadata.Name)
}
if err := a.writeOut(in, st, dir, force, false, false); err != nil {
fmt.Fprintf(w, "error: %v\n", err)
}
case "7":
fmt.Fprintf(w, "question id > ")
id, _ := a.readLine(r)
if _, ok := in.Spec.Parameters[id]; ok || findQ(st, id).Title != "" {
delete(in.Spec.Parameters, id)
return a.wizard(in, preset, output, force)
}
fmt.Fprintf(w, "no such question\n")
case "8", "q", "":
return nil
}
}
}
func (a *app) saveDraft(in *engine.Instance, why string) error {
in.Kind = catalog.KindSession
if err := a.store.SaveInstance(in); err != nil {
return err
}
a.note("saved the draft as %s; continue with '%s solution setup %s --answers <(%s solution instance export %s)'\n",
in.Metadata.Name, a.env.Program, in.Spec.Solution.ID, a.env.Program, in.Metadata.Name)
if why != "" {
return fail(ExitUsage, "%s", why)
}
return nil
}
func displayValue(q *engine.QuestionState, v any) string {
if l, ok := v.([]any); ok {
var parts []string
for _, x := range l {
parts = append(parts, catalog.Scalar(x))
}
return strings.Join(parts, ", ")
}
s := catalog.Scalar(v)
for i, o := range q.Options {
if o.ID == s {
return fmt.Sprintf("%d", i+1)
}
}
return s
}
// explain is "Help me decide" (HELP-01/02).
func (a *app) explain(q *engine.QuestionState) {
w := a.env.Stdout
if q.Decide != "" {
fmt.Fprintf(w, "\n %s\n", wrap(q.Decide, 72, " "))
}
if q.Description != "" {
fmt.Fprintf(w, "\n %s\n", wrap(q.Description, 72, " "))
}
for _, o := range q.Options {
line := o.Title
if o.Description != "" {
line += ": " + o.Description
}
if o.Recommended && o.Reason != "" {
line += " Recommended: " + o.Reason
}
if !o.Enabled {
line += " Not available: " + o.Disabled
}
fmt.Fprintf(w, " - %s\n", wrap(line, 70, " "))
}
if q.Recommended != nil && q.Reason != "" {
fmt.Fprintf(w, " Recommended: %v -- %s\n", q.Recommended, q.Reason)
}
fmt.Fprintln(w)
}
func (a *app) showManual(q *engine.QuestionState, st *engine.State) {
w := a.env.Stdout
refs := append([]string{}, q.References...)
for _, o := range q.Options {
refs = append(refs, o.References...)
}
refs = append(refs, st.References...)
for _, r := range refs {
if !strings.HasPrefix(r, "yetano:manual/") {
continue
}
title, md, ok := a.ix.Excerpt(r, 30)
res, _ := a.ix.Resolve(r)
if !ok {
fmt.Fprintf(w, "\n %s\n\n", refLine(res))
return
}
fmt.Fprintf(w, "\n=== %s\n%s\n=== full text: %s\n\n", title, md, firstNonEmpty(res.CLI, res.File))
return
}
fmt.Fprintf(w, " no manual reference for this question\n")
}
+727
View File
@@ -0,0 +1,727 @@
package cli
import (
"bufio"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
"yetano.dev/yetano/core/solutions/engine"
"yetano.dev/yetano/core/solutions/knowledge"
"yetano.dev/yetano/core/solutions/ref"
"yetano.dev/yetano/core/solutions/store"
)
// multi is a repeatable flag.
type multi []string
func (m *multi) String() string { return strings.Join(*m, ",") }
func (m *multi) Set(s string) error { *m = append(*m, s); return nil }
func (a *app) solution(args []string) error {
if len(args) == 0 {
return a.usage("")
}
sub, rest := args[0], args[1:]
switch sub {
case "list", "ls":
return a.list(rest, false)
case "search":
return a.searchCmd(rest, []string{ref.Solution, ref.Task, ref.Example})
case "show":
return a.show(rest, false)
case "setup", "new":
return a.setup(rest, false)
case "state", "evaluate":
return a.stateCmd(rest)
case "generate":
return a.generate(rest)
case "validate":
return a.validate(rest)
case "plan":
return a.plan(rest)
case "doctor":
return a.doctor(rest)
case "config":
return a.config(rest)
case "architecture", "arch":
return a.architecture(rest)
case "handbook":
return a.handbook(rest)
case "package":
return a.packageCmd(rest)
case "instance", "instances":
return a.instance(rest)
case "preset", "presets":
return a.preset(rest)
case "catalog":
return a.catalogCmd(rest)
}
return a.usage("solution " + sub)
}
func (a *app) task(args []string) error {
if len(args) == 0 {
return a.usage("")
}
sub, rest := args[0], args[1:]
switch sub {
case "list", "ls":
return a.list(rest, true)
case "search":
return a.searchCmd(rest, []string{ref.Task})
case "show":
return a.show(rest, true)
case "run", "setup":
return a.setup(rest, true)
}
return a.usage("task " + sub)
}
// ---- list, show ------------------------------------------------------------
type listItem struct {
ID string `json:"id"`
Kind string `json:"kind"`
Title string `json:"title"`
Summary string `json:"summary"`
Category string `json:"category,omitempty"`
Status catalog.Support `json:"status"`
Featured bool `json:"featured,omitempty"`
TaskKind string `json:"taskKind,omitempty"`
}
func (a *app) items(tasks bool) []listItem {
m := a.cat.Solutions
if tasks {
m = a.cat.Tasks
}
var out []listItem
for _, id := range catalog.SortedIDs(m) {
s := m[id]
e := a.ix.Entry(ref.For(map[bool]string{false: ref.Solution, true: ref.Task}[tasks], id))
title, summary := s.Meta.Title, s.Meta.Summary
if e != nil {
title, summary = e.Title, e.Summary
}
st := s.Meta.Status
if st == "" {
st = catalog.Supported
}
out = append(out, listItem{ID: id, Kind: strings.ToLower(s.Kind), Title: a.tr(s.Meta.Translations, "title", title),
Summary: a.tr(s.Meta.Translations, "summary", summary), Category: s.Meta.Category, Status: st, Featured: s.Meta.Featured, TaskKind: s.Spec.Kind})
}
return out
}
func (a *app) list(args []string, tasks bool) error {
fs := a.flags("list")
category := fs.String("category", "", "only this category")
if err := a.parse(fs, args); err != nil {
return err
}
if err := a.load(); err != nil {
return err
}
items := a.items(tasks)
if *category != "" {
var f []listItem
for _, it := range items {
if it.Category == *category {
f = append(f, it)
}
}
items = f
}
if a.jsonOut {
if items == nil {
items = []listItem{}
}
return a.printJSON(items)
}
for _, it := range items {
mark := ""
if it.Status != catalog.Supported {
mark = " [" + string(it.Status) + "]"
}
a.say("%-22s %s%s\n%-22s %s\n", it.ID, it.Title, mark, "", wrap(it.Summary, 70, strings.Repeat(" ", 23)))
}
if len(items) == 0 {
a.note("nothing found\n")
}
return nil
}
func (a *app) lookup(id string, tasks bool) (*catalog.Solution, error) {
s := a.cat.Lookup(id)
if s == nil {
var hint string
if groups := a.ix.Search(id, knowledge.SearchOptions{Kinds: []string{ref.Solution, ref.Task}, Limit: 3}); len(groups) > 0 {
hint = " -- did you mean " + strings.TrimPrefix(strings.TrimPrefix(groups[0].Hits[0].Ref, "yetano:solution/"), "yetano:task/") + "?"
}
return nil, fmt.Errorf("%w: %s%s", engine.ErrNotFound, id, hint)
}
return s, nil
}
type showOut struct {
listItem
Goals []string `json:"goals,omitempty"`
Scenarios []string `json:"scenarios,omitempty"`
NotFor []string `json:"notFor,omitempty"`
Outcome string `json:"outcome,omitempty"`
Packages []string `json:"packages"`
Capabilities catalog.CapSets `json:"capabilities"`
Platforms []string `json:"platforms,omitempty"`
Questions int `json:"questions"`
Quick []string `json:"quickQuestions"`
Examples []map[string]string `json:"examples"`
References []knowledge.Resolution `json:"references"`
Related []string `json:"related,omitempty"`
Backlinks []string `json:"backlinks,omitempty"`
Version string `json:"version"`
}
func (a *app) show(args []string, tasks bool) error {
fs := a.flags("show")
if err := a.parse(fs, args); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s %s show <id>", a.env.Program, map[bool]string{false: "solution", true: "task"}[tasks])
}
if err := a.load(); err != nil {
return err
}
s, err := a.lookup(fs.Arg(0), tasks)
if err != nil {
return err
}
var item listItem
for _, it := range a.items(s.IsTask()) {
if it.ID == s.Meta.ID {
item = it
}
}
o := showOut{listItem: item, Goals: s.Spec.Goals, Scenarios: s.Spec.Scenarios, NotFor: s.Spec.NotFor,
Capabilities: s.Spec.Capabilities, Platforms: s.Spec.Platforms, Questions: len(s.Spec.Questions), Related: s.Spec.Related,
Version: s.Meta.Version, Examples: []map[string]string{}}
if bp := a.cat.BigPicture; bp != nil {
if g, ok := bp.Stories[s.Spec.BigPicture]; ok {
o.Outcome = g.Outcome
}
}
seen := map[string]bool{}
for _, p := range s.Spec.Packages {
if !seen[p.ID] {
seen[p.ID] = true
o.Packages = append(o.Packages, p.ID)
}
}
for _, q := range s.Spec.Questions {
if q.Level == "" || q.Level == catalog.LevelQuick {
o.Quick = append(o.Quick, q.ID)
}
}
for _, k := range catalog.SortedIDs(a.cat.Examples) {
x := a.cat.Examples[k]
if x.Spec.Solution == s.Meta.ID {
o.Examples = append(o.Examples, map[string]string{"id": x.Meta.ID, "title": a.tr(x.Meta.Translations, "title", x.Meta.Title), "summary": x.Meta.Summary})
}
}
for _, r := range s.Spec.References.All() {
if res, err := a.ix.Resolve(r); err == nil {
o.References = append(o.References, res)
}
}
kind := ref.Solution
if s.IsTask() {
kind = ref.Task
}
o.Backlinks = a.ix.BacklinksOf(ref.For(kind, s.Meta.ID))
if a.jsonOut {
return a.printJSON(o)
}
a.say("%s (%s %s, %s)\n\n", o.Title, o.ID, o.Version, o.Status)
a.say("%s\n", wrap(o.Summary, 76, ""))
if o.Outcome != "" {
a.say("\nResult: %s\n", wrap(o.Outcome, 76, " "))
}
section := func(title string, list []string) {
if len(list) > 0 {
a.say("\n%s\n", title)
for _, l := range list {
a.say(" - %s\n", wrap(l, 72, " "))
}
}
}
section("Goals", o.Goals)
section("Good for", o.Scenarios)
section("Not for", o.NotFor)
a.say("\nPackages: %s\n", strings.Join(o.Packages, ", "))
a.say("Needs: %s\n", strings.Join(o.Capabilities.Required, ", "))
if len(o.Platforms) > 0 {
a.say("Platforms: %s\n", strings.Join(o.Platforms, ", "))
}
a.say("Questions: %d (quick setup asks %d)\n", o.Questions, len(o.Quick))
if len(o.Examples) > 0 {
a.say("\nExamples\n")
for _, x := range o.Examples {
a.say(" %-16s %s\n", x["id"], x["title"])
}
}
if len(o.References) > 0 {
a.say("\nRead more\n")
for _, r := range o.References {
a.say(" %s\n", refLine(r))
}
}
cmd := "solution setup"
if s.IsTask() {
cmd = "task run"
}
a.say("\nStart: %s %s %s [--quick|--guided|--advanced] [--example <id>]\n", a.env.Program, cmd, o.ID)
return nil
}
func refLine(r knowledge.Resolution) string {
where := r.Web
if r.CLI != "" && (where == "" || r.Kind == ref.Manual) {
where = r.CLI
}
title := r.Title
if title == "" {
title = r.Ref
}
if !r.Exists {
title += " (missing)"
}
return fmt.Sprintf("%-40s %s", title, where)
}
// ---- instances from files or the store ----------------------------------------
// instanceFrom reads --file, or a stored instance named by the first argument.
func (a *app) instanceFrom(file string, fs *flag.FlagSet) (*engine.Instance, error) {
if file != "" {
var f *os.File
var err error
if file == "-" {
b := bufio.NewReader(a.env.Stdin)
in, err := engine.ReadInstance(b)
if err != nil {
return nil, fail(ExitUsage, "stdin: %v", err)
}
return in, nil
}
f, err = os.Open(file)
if err != nil {
return nil, fail(ExitNotFound, "%v", err)
}
defer f.Close()
in, err := engine.ReadInstance(f)
if err != nil {
return nil, fail(ExitUsage, "%s: %v", file, err)
}
return in, nil
}
if fs.NArg() < 1 {
return nil, fail(ExitUsage, "name a saved instance or pass --file <solution.yaml>")
}
return a.store.LoadInstance(fs.Arg(0))
}
func (a *app) presetFor(in *engine.Instance, name string) (*engine.Preset, error) {
if name == "" {
name = in.Spec.Preset
}
if name == "" {
return nil, nil
}
if strings.HasSuffix(name, ".yaml") || strings.Contains(name, string(filepath.Separator)) {
f, err := os.Open(name)
if err != nil {
return nil, err
}
defer f.Close()
return engine.ReadPreset(f)
}
return a.store.LoadPreset(name)
}
func (a *app) evaluate(in *engine.Instance, preset *engine.Preset) (*engine.State, error) {
if in.Spec.Locale == "" {
in.Spec.Locale = a.locale
}
return a.eng.Evaluate(in, preset)
}
// common flags of the commands that take an instance
type instFlags struct {
file *string
preset *string
}
func (a *app) instFlags(fs *flag.FlagSet) instFlags {
return instFlags{
file: fs.String("file", "", "solution.yaml (SolutionInstance or WizardSession); - for stdin"),
preset: fs.String("preset", "", "preset name or file (default: the instance's)"),
}
}
func (a *app) stateOf(fs *flag.FlagSet, f instFlags) (*engine.Instance, *engine.State, error) {
if err := a.load(); err != nil {
return nil, nil, err
}
in, err := a.instanceFrom(*f.file, fs)
if err != nil {
return nil, nil, err
}
p, err := a.presetFor(in, *f.preset)
if err != nil {
return nil, nil, err
}
st, err := a.evaluate(in, p)
return in, st, err
}
// stateCmd prints the full engine state: the shared client API as JSON
// (API-01); GUI and web clients render exactly this.
func (a *app) stateCmd(args []string) error {
fs := a.flags("solution state")
f := a.instFlags(fs)
if err := a.parse(fs, args); err != nil {
return err
}
a.jsonOut = true
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
return a.printJSON(st)
}
// ---- generate, validate, plan -------------------------------------------------
func (a *app) generate(args []string) error {
fs := a.flags("solution generate")
f := a.instFlags(fs)
output := fs.String("output", "", "output directory (required)")
force := fs.Bool("force", false, "overwrite files changed by hand")
locked := fs.Bool("locked", false, "fail if the catalog changed the meaning since the last generation (solution.lock.yaml)")
dry := fs.Bool("dry-run", false, "list the files, write nothing")
if err := a.parse(fs, args); err != nil {
return err
}
if *output == "" && !*dry {
return fail(ExitUsage, "--output <dir> is required")
}
in, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
return a.writeOut(in, st, *output, *force, *locked, *dry)
}
func (a *app) writeOut(in *engine.Instance, st *engine.State, dir string, force, locked, dry bool) error {
out, err := a.eng.Generate(st, in, a.ix, false)
if err != nil {
return err
}
if dir != "" && !dry {
if prev, err := engine.ReadLock(dir); err == nil && prev != nil {
if drift := engine.LockDrift(prev, out.Lock); len(drift) > 0 {
if locked {
return fail(ExitConflict, "the catalog changed since the last generation: %s (run without --locked to accept)", strings.Join(drift, "; "))
}
a.note("note: since the last generation: %s\n", strings.Join(drift, "; "))
}
}
if err := engine.Write(dir, out, force); err != nil {
return err
}
}
if a.jsonOut {
return a.printJSON(map[string]any{"output": dir, "dryRun": dry, "files": out.Files, "complete": st.Complete, "messages": st.Messages})
}
verb := "wrote"
if dry {
verb = "would write"
}
a.note("%s %d files to %s\n", verb, len(out.Files), dir)
for _, f := range out.Files {
a.say(" %s\n", f.Path)
}
a.printMessages(st)
return nil
}
func (a *app) printMessages(st *engine.State) {
for _, m := range st.Messages {
a.note("%-7s %s\n", strings.ToUpper(m.Severity), wrap(m.Text, 70, " "))
}
}
// validate: is the instance complete and valid; with --native also run
// the programs' own validators on a generated directory.
func (a *app) validate(args []string) error {
fs := a.flags("solution validate")
f := a.instFlags(fs)
if err := a.parse(fs, args); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
type qerr struct {
Question string `json:"question"`
Errors []string `json:"errors"`
}
var qerrs []qerr
for _, q := range st.Questions {
if len(q.Errors) > 0 {
qerrs = append(qerrs, qerr{q.ID, q.Errors})
}
}
if a.jsonOut {
if err := a.printJSON(map[string]any{"complete": st.Complete, "missing": st.Progress.Missing, "errors": qerrs, "stale": st.Stale, "messages": st.Messages}); err != nil {
return err
}
} else {
for _, q := range qerrs {
a.say("ERROR %s: %s\n", q.Question, strings.Join(q.Errors, "; "))
}
for _, m := range st.Progress.Missing {
a.say("MISSING %s\n", m)
}
for _, s := range st.Stale {
a.say("STALE %s=%v: %s\n", s.Question, s.Value, s.Reason)
}
a.printMessages(st)
if st.Complete {
a.say("valid: %s is complete\n", st.Solution.ID)
}
}
if !st.Complete {
return exitErr{ExitError, errors.New("")}
}
return nil
}
func (a *app) plan(args []string) error {
fs := a.flags("solution plan")
f := a.instFlags(fs)
if err := a.parse(fs, args); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
p := engine.PlanOf(st)
if a.jsonOut {
return a.printJSON(p)
}
a.say("Plan for %s (%s) -- nothing is executed by the guide.\n", firstNonEmpty(st.Instance, st.Solution.ID), p.Spec.Solution)
phase := ""
for i, s := range p.Spec.Steps {
if s.Phase != phase {
phase = s.Phase
a.say("\n%s\n", strings.ToUpper(phase))
}
mark := " "
if s.Mutating {
mark = "*"
}
a.say("%3d.%s %s\n", i+1, mark, s.Title)
if s.Run != "" {
a.say(" $ %s\n", s.Run)
}
}
a.say("\n* changes the system\n")
if !st.Complete {
a.printMessages(st)
return fail(ExitUsage, "the solution is incomplete: %s", strings.Join(st.Progress.Missing, ", "))
}
return nil
}
func firstNonEmpty(a ...string) string {
for _, s := range a {
if s != "" {
return s
}
}
return ""
}
// ---- config, architecture, handbook ------------------------------------------
func (a *app) config(args []string) error {
if len(args) == 0 {
return fail(ExitUsage, "usage: %s solution config show|explain ...", a.env.Program)
}
switch args[0] {
case "show":
fs := a.flags("solution config show")
f := a.instFlags(fs)
fs.Bool("effective", true, "show the effective, merged configuration (the default)")
origins := fs.Bool("origins", false, "show where each value comes from")
if err := a.parse(fs, args[1:]); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
if a.jsonOut {
return a.printJSON(st.Files)
}
for _, file := range st.Files {
a.say("--- %s\n%s\n", file.Path, file.Content)
if *origins {
for _, k := range sortedKeys(file.Origins) {
o := file.Origins[k]
a.say(" %-40s %s %s\n", k, o.Source, strings.Join(o.Params, ","))
}
a.say("\n")
}
}
return nil
case "explain":
fs := a.flags("solution config explain")
f := a.instFlags(fs)
if err := a.parse(fs, args[1:]); err != nil {
return err
}
// [instance] <file> <path>
pos := fs.Args()
var file, path string
switch {
case *f.file != "" && len(pos) == 2:
file, path = pos[0], pos[1]
case *f.file == "" && len(pos) == 3:
file, path = pos[1], pos[2]
default:
return fail(ExitUsage, "usage: %s solution config explain <instance>|--file f <file> <path> (e.g. yamase/yamase.yaml tls.cert-file)", a.env.Program)
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
ex := engine.Explain(st, file, path)
if a.jsonOut {
return a.printJSON(ex)
}
if !ex.Found {
return fail(ExitNotFound, "%s: %s is not set by the guide (the program's built-in default applies)", ex.File, path)
}
a.say("%s %s\n set by %s (%s layer)\n", ex.File, path, ex.Origin.Source, ex.Origin.Layer)
for _, p := range sortedKeys(ex.Answers) {
a.say(" uses answer %s = %v (%s)\n", p, ex.Answers[p], ex.Origins[p])
}
return nil
}
return a.usage("solution config " + args[0])
}
func (a *app) architecture(args []string) error {
fs := a.flags("solution architecture")
f := a.instFlags(fs)
if err := a.parse(fs, args); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
if a.jsonOut {
return a.printJSON(st.Graph)
}
a.say("%s", engine.GraphText(st.Graph))
return nil
}
func (a *app) handbook(args []string) error {
fs := a.flags("solution handbook")
f := a.instFlags(fs)
output := fs.String("output", "", "directory to write the handbook to (default: print index)")
if err := a.parse(fs, args); err != nil {
return err
}
_, st, err := a.stateOf(fs, f)
if err != nil {
return err
}
pages := a.eng.Handbook(st, a.ix)
if *output == "" {
for _, p := range pages {
a.say("%s\n", p.Content)
}
return nil
}
for _, p := range pages {
path := filepath.Join(*output, filepath.FromSlash(strings.TrimPrefix(p.Path, "handbook/")))
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
if err := os.WriteFile(path, p.Content, 0o644); err != nil {
return err
}
}
a.note("wrote %d pages to %s\n", len(pages), *output)
return nil
}
func (a *app) packageCmd(args []string) error {
fs := a.flags("solution package")
if err := a.parse(fs, args); err != nil {
return err
}
if err := a.load(); err != nil {
return err
}
if fs.NArg() != 1 {
return fail(ExitUsage, "usage: %s solution package <id>", a.env.Program)
}
p := a.cat.Packages[fs.Arg(0)]
if p == nil {
return fmt.Errorf("%w: package %s", engine.ErrNotFound, fs.Arg(0))
}
r := ref.For(ref.Package, p.Meta.ID)
back := a.ix.BacklinksOf(r)
if a.jsonOut {
return a.printJSON(map[string]any{"package": p, "summary": a.eng.PackageSummary(p.Meta.ID), "usedBy": back})
}
a.say("%s -- %s\n\n", p.Meta.ID, wrap(a.eng.PackageSummary(p.Meta.ID), 70, " "))
for _, m := range p.Spec.Modules {
sup := ""
if m.Support != "" && m.Support != catalog.Supported {
sup = " [" + string(m.Support) + "]"
}
a.say(" %-14s %s%s\n", m.ID, m.Title, sup)
if len(m.Provides) > 0 {
a.say(" %-14s provides %s\n", "", strings.Join(m.Provides, ", "))
}
}
if len(back) > 0 {
a.say("\nWhat would you like to do with %s?\n", p.Meta.ID)
for _, b := range back {
if strings.HasPrefix(b, "yetano:solution/") || strings.HasPrefix(b, "yetano:task/") {
res, _ := a.ix.Resolve(b)
a.say(" %-30s %s\n", res.Title, res.CLI)
}
}
}
if res, err := a.ix.Resolve(ref.For(ref.Microsite, p.Meta.ID)); err == nil && res.Web != "" {
a.say("\nMicrosite: %s\n", res.Web)
}
return nil
}
var _ = store.ErrNotFound
+55
View File
@@ -0,0 +1,55 @@
// Command yetano-solutions runs the Solutions Guide commands (CI of the
// catalog, development). The guide is deliberately not part of yet, which
// stays a general tool; the full program with TUI and GUI moves to its
// own repository (docs/knowledge-solutions ADR-0006).
//
// yetano-solutions solution list --catalog assets/solutions
package main
import (
"context"
"os"
"os/signal"
"syscall"
"yetano.dev/yetano/core"
"yetano.dev/yetano/core/paths"
"yetano.dev/yetano/core/solutions/cli"
)
var version = "dev"
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
// instances, sessions and presets are user data: core/paths' data
// directory (nothing is created until something is saved)
storeDir := os.Getenv("YETANO_SOLUTIONS_HOME")
if storeDir == "" {
if r, err := paths.For(core.Application{Name: "yetano-solutions", Kind: core.CLI}); err == nil {
if d, err := r.DataDir(); err == nil {
storeDir = d
}
}
}
os.Exit(cli.Run(ctx, os.Args[1:], cli.Env{
Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr,
Interactive: isTerminal(os.Stdin) && isTerminal(os.Stdout),
Program: "yetano-solutions",
StoreDir: storeDir,
Version: version,
}))
}
// isTerminal: a character device that is not the null device (/dev/null
// is a character device too, and must never start an interactive wizard).
func isTerminal(f *os.File) bool {
st, err := f.Stat()
if err != nil || st.Mode()&os.ModeCharDevice == 0 {
return false
}
if null, err := os.Stat(os.DevNull); err == nil && os.SameFile(st, null) {
return false
}
return true
}
+53
View File
@@ -0,0 +1,53 @@
package engine
import (
"os"
"path/filepath"
"testing"
"yetano.dev/yetano/core/solutions/catalog"
)
// The meta-repo's catalog, when this module is checked out inside it.
func assetsCatalog(t *testing.T) *catalog.Catalog {
t.Helper()
dir, _ := filepath.Abs("../../../assets/solutions")
if _, err := os.Stat(filepath.Join(dir, "catalog.yaml")); err != nil {
t.Skip("assets/solutions not present (module outside the meta-repo)")
}
c, err := catalog.Load(dir)
if err != nil {
for _, i := range c.Issues {
t.Log(i)
}
t.Fatal(err)
}
return c
}
func TestAssetsCatalog(t *testing.T) {
c := assetsCatalog(t)
for _, i := range c.Validate() {
if i.Severity == "error" {
t.Error(i)
} else {
t.Log(i)
}
}
e := New(c)
for _, key := range catalog.SortedIDs(c.Examples) {
x := c.Examples[key]
in := NewInstance(x.Meta.ID, c.Lookup(x.Spec.Solution), x.Spec.Mode)
in.Spec.Parameters = x.Spec.Parameters
st, err := e.Evaluate(in, nil)
if err != nil {
t.Fatalf("%s: %v", key, err)
}
if !st.Complete {
t.Errorf("%s: not complete: %s", key, incompleteText(st))
}
for _, m := range st.Messages {
t.Logf("%s: %s %s", key, m.Severity, m.Text)
}
}
}
+398
View File
@@ -0,0 +1,398 @@
package engine
import (
"bytes"
"fmt"
"regexp"
"sort"
"strconv"
"strings"
"gopkg.in/yaml.v3"
"yetano.dev/yetano/core/solutions/catalog"
)
// placeholder: ${name}, ${name[0]}, ${name.count}, ${name.join}; $${ is a literal "${".
var placeholderRE = regexp.MustCompile(`\$\$\{|\$\{((?:instance|solution)\.[a-z]+|[A-Za-z_][A-Za-z0-9_]*)(?:\[(\d+)\]|\.(count|join))?\}`)
type genFile struct {
path string
pkg string
root *yaml.Node // mapping
origins map[string]Origin
}
func (ev *evaluation) vars() map[string]any {
v := map[string]any{}
for k, a := range ev.answers {
v[k] = a
}
v["instance.name"] = ev.in.Metadata.Name
v["solution.id"] = ev.s.Meta.ID
v["solution.version"] = ev.s.Meta.Version
return v
}
func (ev *evaluation) config() {
files := map[string]*genFile{}
var order []string
get := func(path string) *genFile {
f, ok := files[path]
if !ok {
pkg, _, _ := strings.Cut(path, "/")
f = &genFile{path: path, pkg: pkg, root: &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}, origins: map[string]Origin{}}
files[path] = f
order = append(order, path)
}
return f
}
vars := ev.vars()
applyFrag := func(fr catalog.Fragment, origin Origin) {
pkg, _, _ := strings.Cut(fr.File, "/")
if !ev.pkgSelected(pkg) {
return
}
if fr.Module != "" {
mp, mm := pkg, fr.Module
if a, b, ok := strings.Cut(fr.Module, "/"); ok {
mp, mm = a, b
}
if !ev.moduleEnabled(mp, mm) {
return
}
}
node := deepCopy(&fr.Set)
params := map[string]bool{}
if err := interpolate(node, vars, params); err != nil {
ev.msg("error", "config", fmt.Sprintf("%s: %v", origin.Source, err), origin.Source)
return
}
for p := range params {
origin.Params = append(origin.Params, p)
}
sort.Strings(origin.Params)
if node.Kind != yaml.MappingNode {
ev.msg("error", "config", fmt.Sprintf("%s: fragment for %s is not a map", origin.Source, fr.File), origin.Source)
return
}
f := get(fr.File)
mergeMap(f.root, node, "", origin, f.origins)
}
// layer 2: profiles (base first), in package order
ids := append([]string{}, ev.pkgSeen...)
sort.Strings(ids)
for _, id := range ids {
p := ev.pkgs[id]
if !p.Selected || p.Profile == "" {
continue
}
chain, err := ev.e.Cat.ProfileChain(id, p.Profile)
if err != nil {
continue
}
for _, prof := range chain {
for _, fr := range prof.Spec.Config {
applyFrag(fr, Origin{Layer: "profile", Source: "profile:" + prof.Key()})
}
}
}
// layer 3: the solution's fragments
for i, fr := range ev.s.Spec.Config {
if len(fr.When) > 0 && !fr.When.Holds(ev.env) {
continue
}
id := fr.ID
if id == "" {
id = strconv.Itoa(i)
}
applyFrag(fr, Origin{Layer: "solution", Source: "solution:" + ev.s.Meta.ID + "#" + id})
}
// layer 6: explicit overrides
for _, o := range ev.in.Spec.Overrides {
if !catalog.SafeRelPath(o.File) || o.Path == "" {
ev.msg("error", "override", fmt.Sprintf("override %s %s: bad file or path", o.File, o.Path), "override")
continue
}
f, ok := files[o.File]
if !ok {
ev.msg("warning", "override", fmt.Sprintf("override for %s: the solution generates no such file", o.File), "override")
continue
}
var val yaml.Node
if err := val.Encode(o.Value); err != nil {
ev.msg("error", "override", err.Error(), "override")
continue
}
setPath(f.root, strings.Split(o.Path, "."), &val)
f.origins[o.Path] = Origin{Layer: "override", Source: "override"}
ev.msg("info", "override", fmt.Sprintf("%s: %s is set directly, not through a question", o.File, o.Path), "override")
}
sort.Strings(order)
for _, path := range order {
f := files[path]
body, err := render(f.root, ev.s, path)
if err != nil {
ev.msg("error", "config", err.Error(), path)
continue
}
ev.st.Files = append(ev.st.Files, FilePreview{Path: "config/" + path, Package: f.pkg, Content: body, Origins: f.origins})
}
}
func render(root *yaml.Node, s *catalog.Solution, path string) (string, error) {
doc := &yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{root}}
doc.HeadComment = fmt.Sprintf("Generated by the Yetano Solutions Guide from %s %s.\n"+
"This is a native configuration file: edit it like any other. See\n"+
"solution.lock.yaml before regenerating over hand edits.", s.Meta.ID, s.Meta.Version)
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf)
enc.SetIndent(2)
if err := enc.Encode(doc); err != nil {
return "", fmt.Errorf("%s: %v", path, err)
}
enc.Close()
return buf.String(), nil
}
func deepCopy(n *yaml.Node) *yaml.Node {
if n == nil {
return nil
}
c := *n
if c.Kind == yaml.MappingNode || c.Kind == yaml.SequenceNode {
c.Style = 0 // generated files use block style, whatever the catalog wrote
}
c.Line, c.Column = 0, 0
c.Content = make([]*yaml.Node, len(n.Content))
for i, ch := range n.Content {
c.Content[i] = deepCopy(ch)
}
if n.Kind == yaml.DocumentNode && len(c.Content) == 1 {
return c.Content[0]
}
return &c
}
// interpolate replaces placeholders in scalars (ADR-0005).
func interpolate(n *yaml.Node, vars map[string]any, used map[string]bool) error {
switch n.Kind {
case yaml.MappingNode:
for i := 1; i < len(n.Content); i += 2 {
if err := interpolate(n.Content[i], vars, used); err != nil {
return err
}
}
case yaml.SequenceNode:
for _, ch := range n.Content {
if err := interpolate(ch, vars, used); err != nil {
return err
}
}
case yaml.ScalarNode:
if !strings.Contains(n.Value, "${") {
return nil
}
whole := placeholderRE.FindStringSubmatchIndex(n.Value)
if whole != nil && whole[0] == 0 && whole[1] == len(n.Value) && n.Value != "$${" {
v, err := lookup(n.Value, vars, used)
if err != nil {
return err
}
var repl yaml.Node
if err := repl.Encode(v); err != nil {
return err
}
repl.Style = 0
*n = repl
return nil
}
var firstErr error
out := placeholderRE.ReplaceAllStringFunc(n.Value, func(m string) string {
if m == "$${" {
return "${"
}
v, err := lookup(m, vars, used)
if err != nil && firstErr == nil {
firstErr = err
}
return text(v)
})
if firstErr != nil {
return firstErr
}
n.Value = out
n.Tag = "!!str"
n.Style = 0
}
return nil
}
func lookup(ph string, vars map[string]any, used map[string]bool) (any, error) {
m := placeholderRE.FindStringSubmatch(ph)
name := m[1]
v, ok := vars[name]
if !ok {
return nil, fmt.Errorf("placeholder ${%s}: no answer for %q", name, name)
}
used[name] = true
switch {
case m[2] != "":
i, _ := strconv.Atoi(m[2])
l := listOf(v)
if i >= len(l) {
return nil, fmt.Errorf("placeholder %s: %q has only %d item(s)", ph, name, len(l))
}
return l[i], nil
case m[3] == "count":
return len(listOf(v)), nil
case m[3] == "join":
var parts []string
for _, x := range listOf(v) {
parts = append(parts, catalog.Scalar(x))
}
return strings.Join(parts, ","), nil
}
return v, nil
}
func text(v any) string {
if l, ok := v.([]any); ok {
var parts []string
for _, x := range l {
parts = append(parts, catalog.Scalar(x))
}
return strings.Join(parts, ",")
}
return catalog.Scalar(v)
}
// mergeMap merges src into dst like core/config: maps key by key, lists
// and scalars replace, null removes. Origins are recorded per path.
func mergeMap(dst, src *yaml.Node, prefix string, origin Origin, origins map[string]Origin) {
for i := 0; i+1 < len(src.Content); i += 2 {
k, v := src.Content[i], src.Content[i+1]
path := k.Value
if prefix != "" {
path = prefix + "." + k.Value
}
idx := -1
for j := 0; j+1 < len(dst.Content); j += 2 {
if dst.Content[j].Value == k.Value {
idx = j
break
}
}
if v.Kind == yaml.ScalarNode && v.Tag == "!!null" {
if idx >= 0 {
dst.Content = append(dst.Content[:idx], dst.Content[idx+2:]...)
}
for p := range origins {
if p == path || strings.HasPrefix(p, path+".") {
delete(origins, p)
}
}
continue
}
if idx >= 0 && v.Kind == yaml.MappingNode && dst.Content[idx+1].Kind == yaml.MappingNode {
mergeMap(dst.Content[idx+1], v, path, origin, origins)
continue
}
for p := range origins {
if strings.HasPrefix(p, path+".") {
delete(origins, p)
}
}
if idx >= 0 {
dst.Content[idx+1] = v
} else {
dst.Content = append(dst.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k.Value}, v)
}
recordLeaves(v, path, origin, origins)
}
}
func recordLeaves(v *yaml.Node, path string, origin Origin, origins map[string]Origin) {
if v.Kind == yaml.MappingNode {
for i := 0; i+1 < len(v.Content); i += 2 {
recordLeaves(v.Content[i+1], path+"."+v.Content[i].Value, origin, origins)
}
return
}
origins[path] = origin
}
func setPath(root *yaml.Node, keys []string, val *yaml.Node) {
cur := root
for i, k := range keys {
idx := -1
for j := 0; j+1 < len(cur.Content); j += 2 {
if cur.Content[j].Value == k {
idx = j
}
}
if i == len(keys)-1 {
if idx >= 0 {
cur.Content[idx+1] = val
} else {
cur.Content = append(cur.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k}, val)
}
return
}
if idx < 0 || cur.Content[idx+1].Kind != yaml.MappingNode {
m := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
if idx >= 0 {
cur.Content[idx+1] = m
} else {
cur.Content = append(cur.Content, &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!str", Value: k}, m)
}
cur = m
} else {
cur = cur.Content[idx+1]
}
}
}
// Explanation answers "where does this value come from?" (PROF-05).
type Explanation struct {
File string `json:"file"`
Path string `json:"path"`
Found bool `json:"found"`
Origin Origin `json:"origin"`
Answers map[string]any `json:"answers,omitempty"` // the answers it used, with their origin
Origins map[string]string `json:"answerOrigins,omitempty"`
}
// Explain finds the origin of a value in a generated file. file may omit
// the "config/" prefix; path is dot separated.
func Explain(st *State, file, path string) Explanation {
file = strings.TrimPrefix(file, "config/")
ex := Explanation{File: "config/" + file, Path: path}
for _, f := range st.Files {
if f.Path != "config/"+file {
continue
}
p := path
for p != "" {
if o, ok := f.Origins[p]; ok {
ex.Found, ex.Origin = true, o
break
}
i := strings.LastIndex(p, ".")
if i < 0 {
break
}
p = p[:i]
}
}
if ex.Found && len(ex.Origin.Params) > 0 {
ex.Answers, ex.Origins = map[string]any{}, map[string]string{}
for _, p := range ex.Origin.Params {
if a, ok := st.Answers[p]; ok {
ex.Answers[p] = a.Value
ex.Origins[p] = a.Origin
}
}
}
return ex
}
+408
View File
@@ -0,0 +1,408 @@
package engine
import (
"encoding/json"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"yetano.dev/yetano/core/solutions/catalog"
)
func testCat(t *testing.T) *catalog.Catalog {
t.Helper()
c, err := catalog.Load("testdata/cat")
if err != nil {
for _, i := range c.Issues {
t.Log(i)
}
t.Fatal(err)
}
for _, i := range c.Validate() {
if i.Severity == "error" {
t.Fatal(i)
}
}
return c
}
func eval(t *testing.T, e *Engine, mode catalog.Level, params map[string]any, p *Preset) *State {
t.Helper()
in := NewInstance("t1", e.Cat.Solutions["app-run"], mode)
for k, v := range params {
in.Spec.Parameters[k] = v
}
st, err := e.Evaluate(in, p)
if err != nil {
t.Fatal(err)
}
return st
}
func pkg(st *State, id string) *PackageState {
for i := range st.Packages {
if st.Packages[i].ID == id {
return &st.Packages[i]
}
}
return nil
}
func capOf(st *State, id string) *CapState {
for i := range st.Capabilities {
if st.Capabilities[i].ID == id {
return &st.Capabilities[i]
}
}
return nil
}
func file(st *State, path string) string {
for _, f := range st.Files {
if f.Path == path {
return f.Content
}
}
return ""
}
func question(st *State, id string) QuestionState { return findQuestion(st, id) }
func findQuestion(st *State, id string) QuestionState {
for _, q := range st.Questions {
if q.ID == id {
return q
}
}
return QuestionState{}
}
func hasMsg(st *State, sub string) bool {
for _, m := range st.Messages {
if strings.Contains(m.Text, sub) {
return true
}
}
return false
}
func TestQuickDefaultPath(t *testing.T) {
e := New(testCat(t))
st := eval(t, e, catalog.LevelQuick, nil, nil)
if st.Complete || len(st.Progress.Missing) != 1 || st.Progress.Missing[0] != "hosts" {
t.Fatalf("want only hosts missing, got %v", st.Progress.Missing)
}
if st.Next != "hosts" {
t.Errorf("next = %q", st.Next)
}
// quick asks size and hosts only; guided questions take their defaults
var asked []string
for _, q := range st.Questions {
if q.Asked {
asked = append(asked, q.ID)
}
}
if strings.Join(asked, ",") != "size,hosts" {
t.Errorf("asked %v", asked)
}
st = eval(t, e, catalog.LevelQuick, map[string]any{"hosts": "a.example.org, b.example.org"}, nil)
if !st.Complete {
t.Fatalf("incomplete: %v %v", st.Progress.Missing, st.Messages)
}
if p := pkg(st, "app"); p == nil || !p.Selected || p.Profile != "base" {
t.Fatalf("app: %+v", p)
}
if c := capOf(st, "auth.users"); c == nil || c.Provider != "app/users" {
t.Errorf("auth.users provider: %+v", c)
}
if c := capOf(st, "backup.files"); c == nil || c.Status != StRecommended {
t.Errorf("backup.files should be recommended: %+v", c)
}
if c := capOf(st, "feature.x"); c != nil && c.Status != StExcluded {
t.Errorf("feature.x should be excluded or absent: %+v", c)
}
cfg := file(st, "config/app/app.yaml")
for _, want := range []string{"hosts:\n - a.example.org\n - b.example.org", "owner: admin@a.example.org", "listen: :8080", "first: a.example.org", "n: 2", "max: 10"} {
if !strings.Contains(cfg, want) {
t.Errorf("config lacks %q:\n%s", want, cfg)
}
}
if file(st, "config/bak/bak.yaml") != "" || file(st, "config/idp/idp.yaml") != "" {
t.Error("files for packages that are not selected")
}
if len(st.Steps) != 3 { // 2 hosts + 1 program (server; extra is disabled)
t.Errorf("steps: %+v", st.Steps)
}
}
// Scenario B: local -> central identity and back (ACC-B, RULE-06).
func TestIdentitySwitch(t *testing.T) {
e := New(testCat(t))
base := map[string]any{"hosts": []any{"a.example.org"}}
st := eval(t, e, catalog.LevelGuided, base, nil)
if pkg(st, "idp") != nil {
t.Fatal("idp without central identity")
}
central := map[string]any{"hosts": []any{"a.example.org"}, "identity": "central"}
st = eval(t, e, catalog.LevelGuided, central, nil)
if !question(st, "realm").Visible || st.Complete {
t.Fatal("realm must appear and be required")
}
central["realm"] = "corp"
st = eval(t, e, catalog.LevelGuided, central, nil)
if !st.Complete {
t.Fatalf("incomplete: %v %v", st.Progress.Missing, st.Messages)
}
if p := pkg(st, "idp"); p == nil || !p.Selected {
t.Fatal("idp must be selected")
}
if c := capOf(st, "auth.sso"); c == nil || c.Provider != "idp/sso" {
t.Fatalf("auth.sso must come from idp, not the unimplemented module: %+v", c)
}
if !strings.Contains(file(st, "config/app/app.yaml"), "realm: corp") || file(st, "config/idp/idp.yaml") == "" {
t.Error("central identity config missing")
}
edge := false
for _, ed := range st.Graph.Edges {
edge = edge || (ed.From == "pkg:app" && ed.To == "pkg:idp" && ed.Type == "authenticatesVia")
}
if !edge {
t.Error("confirmed Big Picture connection app -> idp missing from the graph")
}
// back to local: realm is stale, not in the config, idp gone
central["identity"] = "local"
st = eval(t, e, catalog.LevelGuided, central, nil)
if pkg(st, "idp") != nil || strings.Contains(file(st, "config/app/app.yaml"), "realm") {
t.Error("central leftovers after switching back")
}
if len(st.Stale) != 1 || st.Stale[0].Question != "realm" {
t.Errorf("stale: %+v", st.Stale)
}
}
func TestNotImplementedOptionIsVisibleButNotSelectable(t *testing.T) {
e := New(testCat(t))
st := eval(t, e, catalog.LevelGuided, map[string]any{"hosts": []any{"a.example.org"}, "identity": "ghost"}, nil)
q := question(st, "identity")
var ghost OptionState
for _, o := range q.Options {
if o.ID == "ghost" {
ghost = o
}
}
if ghost.Enabled || ghost.Disabled != "not built" {
t.Errorf("ghost option: %+v", ghost)
}
if len(st.Stale) != 1 || q.Value != "local" {
t.Errorf("the unselectable answer must be stale and the default used: %+v %v", st.Stale, q.Value)
}
}
func TestModeSwitchKeepsAnswers(t *testing.T) {
e := New(testCat(t))
params := map[string]any{"hosts": []any{"a.example.org"}, "port": 9090}
adv := eval(t, e, catalog.LevelAdvanced, params, nil)
quick := eval(t, e, catalog.LevelQuick, params, nil)
if file(adv, "config/app/app.yaml") != file(quick, "config/app/app.yaml") {
t.Error("the mode must not change the result")
}
if !strings.Contains(file(quick, "config/app/app.yaml"), ":9090") {
t.Error("an advanced answer is lost in quick mode")
}
if question(quick, "port").Asked {
t.Error("quick mode asks an advanced question")
}
}
func TestValidationAndSecrets(t *testing.T) {
e := New(testCat(t))
st := eval(t, e, catalog.LevelAdvanced, map[string]any{"hosts": []any{"not a host"}, "token": "hunter2"}, nil)
if len(question(st, "hosts").Errors) == 0 {
t.Error("an invalid host name is accepted")
}
if len(question(st, "token").Errors) == 0 {
t.Error("a plain secret is accepted")
}
st = eval(t, e, catalog.LevelAdvanced, map[string]any{"hosts": []any{"a.example.org"}, "token": "secret://app/token"}, nil)
if !st.Complete || !strings.Contains(file(st, "config/app/app.yaml"), "token: secret://app/token") {
t.Errorf("secret reference not taken: %v", st.Messages)
}
for _, p := range e.Handbook(st, nil) {
if strings.Contains(string(p.Content), "secret://app/token") && strings.HasSuffix(p.Path, "index.md") {
t.Error("the handbook's decision table shows a secret reference")
}
}
}
// Scenario G: a preset answers everything but the instance-specific questions.
func TestPreset(t *testing.T) {
e := New(testCat(t))
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelGuided)
in.Spec.Parameters = map[string]any{"hosts": []any{"a.example.org"}, "size": "big", "backup": "mine", "token": "secret://x"}
p := PresetFrom("mine", in, e.Cat.Solutions["app-run"])
if _, ok := p.Spec.Parameters["hosts"]; ok {
t.Error("an instance-specific answer in the preset")
}
if _, ok := p.Spec.Parameters["token"]; ok {
t.Error("a secret in the preset")
}
st := eval(t, e, catalog.LevelQuick, map[string]any{"hosts": []any{"new.example.org"}}, p)
if !st.Complete || pkg(st, "app").Profile != "big" || st.Answers["size"].Origin != "preset:mine" {
t.Fatalf("preset not applied: %+v %v", st.Answers["size"], st.Messages)
}
if question(st, "size").Asked {
t.Error("a question the preset answered is asked again")
}
if !question(st, "hosts").Asked {
t.Error("the instance-specific question must be asked")
}
if !hasMsg(st, "Big needs more memory") {
t.Error("rule message missing")
}
if !strings.Contains(file(st, "config/app/extra.yaml"), "on: true") || !strings.Contains(file(st, "config/app/app.yaml"), "max: 100") {
t.Error("profile inheritance (big extends base) not applied")
}
if c := capOf(st, "backup.files"); c == nil || c.Status != StExternal {
t.Errorf("backup by own tool must be external: %+v", c)
}
}
func TestExplainAndOverride(t *testing.T) {
e := New(testCat(t))
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
in.Spec.Overrides = []Override{{File: "app/app.yaml", Path: "limits.min", Value: 5}}
st, err := e.Evaluate(in, nil)
if err != nil {
t.Fatal(err)
}
ex := Explain(st, "app/app.yaml", "owner")
if !ex.Found || ex.Origin.Source != "solution:app-run#main" || ex.Origins["owner"] != "default" {
t.Errorf("explain owner: %+v", ex)
}
if ex := Explain(st, "config/app/app.yaml", "limits.max"); ex.Origin.Source != "profile:app/base" {
t.Errorf("explain limits.max: %+v", ex)
}
if ex := Explain(st, "app/app.yaml", "limits.min"); ex.Origin.Layer != "override" {
t.Errorf("explain override: %+v", ex)
}
if !strings.Contains(file(st, "config/app/app.yaml"), "min: 5") {
t.Error("override not applied")
}
}
func TestDeterministicAndJSON(t *testing.T) {
e := New(testCat(t))
p := map[string]any{"hosts": []any{"a.example.org", "b.example.org"}, "identity": "central", "realm": "r"}
a, _ := json.Marshal(eval(t, e, catalog.LevelGuided, p, nil))
for i := 0; i < 5; i++ {
b, _ := json.Marshal(eval(t, e, catalog.LevelGuided, p, nil))
if string(a) != string(b) {
t.Fatal("evaluation is not deterministic")
}
}
}
func TestGenerateWriteAndProtect(t *testing.T) {
e := New(testCat(t))
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
st, _ := e.Evaluate(in, nil)
out, err := e.Generate(st, in, nil, false)
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
if err := Write(dir, out, false); err != nil {
t.Fatal(err)
}
// regenerating unchanged is fine
if err := Write(dir, out, false); err != nil {
t.Fatal(err)
}
// a hand edit blocks regeneration (CONF-06)
cfg := filepath.Join(dir, "config", "app", "app.yaml")
if err := os.WriteFile(cfg, []byte("# mine\n"), 0o644); err != nil {
t.Fatal(err)
}
if err := Write(dir, out, false); !errors.Is(err, ErrModified) {
t.Fatalf("hand edit overwritten: %v", err)
}
if err := Write(dir, out, true); err != nil {
t.Fatal(err)
}
// an incomplete state does not generate
in2 := NewInstance("t2", e.Cat.Solutions["app-run"], catalog.LevelQuick)
st2, _ := e.Evaluate(in2, nil)
if _, err := e.Generate(st2, in2, nil, false); !errors.Is(err, ErrIncomplete) {
t.Errorf("incomplete generated: %v", err)
}
}
func TestLockDrift(t *testing.T) {
e := New(testCat(t))
in := NewInstance("t1", e.Cat.Solutions["app-run"], catalog.LevelQuick)
in.Spec.Parameters["hosts"] = []any{"a.example.org"}
st, _ := e.Evaluate(in, nil)
out, _ := e.Generate(st, in, nil, false)
out2, _ := e.Generate(st, in, nil, false)
if d := LockDrift(out.Lock, out2.Lock); len(d) != 0 {
t.Errorf("drift without change: %v", d)
}
changed := *out.Lock
changed.Spec.Profiles = append([]Pinned{}, out.Lock.Spec.Profiles...)
changed.Spec.Profiles[0].Hash = "x"
if d := LockDrift(&changed, out2.Lock); len(d) != 1 || !strings.Contains(d[0], "profile app/base changed") {
t.Errorf("profile change not detected: %v", d)
}
}
func TestStepsChecksGraph(t *testing.T) {
e := New(testCat(t))
st := eval(t, e, catalog.LevelQuick, map[string]any{"hosts": []any{"a.example.org"}, "size": "big"}, nil)
if st.Steps[0].Phase != "install" || len(st.Steps) != 3 {
t.Errorf("steps: %+v", st.Steps)
}
if st.Steps[0].Run != "yet install app-server" || st.Steps[1].Run != "yet install app-extra" {
t.Errorf("module steps: %+v", st.Steps)
}
for _, c := range st.Checks {
switch c.ID {
case "port":
if c.Status != CheckNotChecked || c.Params["port"] != "8080" {
t.Errorf("port check: %+v", c)
}
case "bigonly":
if c.Status != CheckNotChecked {
t.Errorf("bigonly: %+v", c)
}
}
}
found := false
for _, n := range st.Graph.Nodes {
found = found || n.Title == "Users of a.example.org"
}
if !found {
t.Error("node title not interpolated")
}
if !strings.Contains(GraphText(st.Graph), "app-extra") {
t.Error(GraphText(st.Graph))
}
}
func TestConditionOrderIsEnforced(t *testing.T) {
c := testCat(t)
s := c.Solutions["app-run"]
q, _ := s.Question("size")
q.VisibleWhen = catalog.Cond{"hosts": map[string]any{"set": true}}
defer func() { q.VisibleWhen = nil }()
found := false
for _, i := range c.Validate() {
found = found || i.Code == "condition-order"
}
if !found {
t.Error("a condition on a later question is not reported")
}
}
+998
View File
@@ -0,0 +1,998 @@
package engine
import (
"errors"
"fmt"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
)
// GeneratorVersion is stamped into lock files; the program embedding the
// engine may set it to its own version.
var GeneratorVersion = "dev"
// ErrNotFound is returned for unknown solutions, tasks, examples.
var ErrNotFound = errors.New("not found")
// Engine evaluates instances against one catalog. It is safe for
// concurrent use: Evaluate does not modify the catalog.
type Engine struct {
Cat *catalog.Catalog
}
// New returns an engine for a validated catalog.
func New(c *catalog.Catalog) *Engine { return &Engine{Cat: c} }
type evaluation struct {
e *Engine
s *catalog.Solution
in *Instance
preset *Preset
st *State
answers map[string]any
env catalog.Env
reqPkg, recPkg, discPkg, conflPkg map[string][]string
reqCap, recCap, discCap, exclCap, implCap map[string][]string
extCap map[string]string
exclMod, reqMod map[string][]string
pkgs map[string]*PackageState
mods map[string]map[string]*ModuleState // pkg -> module -> state
caps map[string]*CapState
pkgSeen []string
}
// Evaluate computes the full State of an instance (and an optional preset).
func (e *Engine) Evaluate(in *Instance, preset *Preset) (*State, error) {
s := e.Cat.Lookup(in.Spec.Solution.ID)
if s == nil {
return nil, fmt.Errorf("%w: solution or task %q", ErrNotFound, in.Spec.Solution.ID)
}
mode := in.Spec.Mode
if mode == "" {
mode = catalog.LevelQuick
}
loc := in.Spec.Locale
if loc == "" {
loc = "en"
}
st := &State{
Solution: SolutionInfo{
ID: s.Meta.ID, Kind: s.Kind, TaskKind: s.Spec.Kind, Version: s.Meta.Version,
Title: e.title(s, loc), Summary: e.summary(s, loc), Status: statusOf(s.Meta.Status),
Category: s.Meta.Category, BigPicture: s.Spec.BigPicture,
},
Instance: in.Metadata.Name, Mode: mode, Locale: loc, Platform: in.Spec.Platform,
Answers: map[string]Answer{},
Messages: []Message{}, Rules: []AppliedRule{}, Packages: []PackageState{},
Capabilities: []CapState{}, Files: []FilePreview{}, Steps: []PlannedStep{},
Checks: []CheckResult{}, References: []string{},
}
ev := &evaluation{
e: e, s: s, in: in, preset: preset, st: st, answers: map[string]any{},
reqPkg: map[string][]string{}, recPkg: map[string][]string{}, discPkg: map[string][]string{}, conflPkg: map[string][]string{},
reqCap: map[string][]string{}, recCap: map[string][]string{}, discCap: map[string][]string{},
exclCap: map[string][]string{}, implCap: map[string][]string{}, extCap: map[string]string{},
exclMod: map[string][]string{}, reqMod: map[string][]string{},
pkgs: map[string]*PackageState{}, mods: map[string]map[string]*ModuleState{}, caps: map[string]*CapState{},
}
ev.env = catalog.Env{Answers: ev.answers, Mode: mode, Platform: in.Spec.Platform}
if in.Spec.Solution.Version != "" && in.Spec.Solution.Version != s.Meta.Version {
ev.msg("warning", "version", fmt.Sprintf("these answers were made for %s %s; the catalog now has %s. Review the answers (LOCK-02).", s.Meta.ID, in.Spec.Solution.Version, s.Meta.Version), "")
}
if preset != nil && preset.Spec.Solution != "" && preset.Spec.Solution != s.Meta.ID {
ev.msg("warning", "preset", fmt.Sprintf("preset %q is for %s, not %s; only matching answers are used", preset.Metadata.Name, preset.Spec.Solution, s.Meta.ID), "")
}
for k := range in.Spec.Parameters {
if q, _ := s.Question(k); q == nil {
ev.msg("warning", "unknown-parameter", fmt.Sprintf("parameter %q is not a question of %s and is ignored", k, s.Meta.ID), "")
}
}
ev.questions()
ev.effects()
ev.packages()
ev.capabilities()
ev.finishModules()
ev.config()
ev.steps()
ev.checks()
ev.graph()
ev.finish()
return st, nil
}
func statusOf(s catalog.Support) catalog.Support {
if s == "" {
return catalog.Supported
}
return s
}
// ---- text ----------------------------------------------------------------
// Tr returns the translation of field in loc, or base.
func Tr(t catalog.Translations, loc, field, base string) string {
if loc != "" && loc != "en" {
if m, ok := t[loc]; ok {
if v, ok := m[field]; ok && v != "" {
return v
}
}
}
return base
}
func (e *Engine) title(s *catalog.Solution, loc string) string {
base := s.Meta.Title
if base == "" && e.Cat.BigPicture != nil {
if g, ok := e.Cat.BigPicture.Stories[s.Spec.BigPicture]; ok {
base = g.Title
}
}
return Tr(s.Meta.Translations, loc, "title", base)
}
func (e *Engine) summary(s *catalog.Solution, loc string) string {
base := s.Meta.Summary
if base == "" && e.Cat.BigPicture != nil {
if g, ok := e.Cat.BigPicture.Stories[s.Spec.BigPicture]; ok {
base = g.Intent
}
}
return Tr(s.Meta.Translations, loc, "summary", base)
}
// PackageTitle and PackageSummary come from the Big Picture (ADR-0002).
func (e *Engine) PackageSummary(id string) string {
p := e.Cat.Packages[id]
if p == nil {
return ""
}
if p.Meta.Summary != "" {
return p.Meta.Summary
}
if e.Cat.BigPicture != nil {
if bp, ok := e.Cat.BigPicture.Products[p.Spec.BigPicture]; ok {
return bp.Summary
}
}
return ""
}
func (ev *evaluation) msg(sev, code, text, source string) {
ev.st.Messages = append(ev.st.Messages, Message{Severity: sev, Code: code, Text: text, Source: source})
}
func add(m map[string][]string, k, reason string) {
for _, r := range m[k] {
if r == reason {
return
}
}
m[k] = append(m[k], reason)
}
// ---- questions -------------------------------------------------------------
func platformOK(list []string, p string) bool {
if len(list) == 0 || p == "" {
return true
}
for _, x := range list {
if x == p {
return true
}
}
return false
}
func (ev *evaluation) stale(q string, v any, reason string) {
ev.st.Stale = append(ev.st.Stale, StaleAnswer{Question: q, Value: v, Reason: reason})
}
func (ev *evaluation) questions() {
s, st, loc := ev.s, ev.st, ev.st.Locale
mode := st.Mode
askedIdx := 0
for i := range s.Spec.Questions {
q := &s.Spec.Questions[i]
qs := QuestionState{
ID: q.ID, Type: q.Type, Item: q.Item, Group: q.Group, Level: levelOf(q.Level),
Title: Tr(q.Translations, loc, "title", q.Title),
Help: Tr(q.Translations, loc, "help", q.Help),
Description: Tr(q.Translations, loc, "description", q.Description),
Decide: Tr(q.Translations, loc, "decide", q.Decide),
Placeholder: Tr(q.Translations, loc, "placeholder", q.Placeholder),
Examples: q.Examples, InstanceSpecific: q.InstanceSpecific,
Recommended: q.Recommended, Reason: Tr(q.Translations, loc, "reason", q.Reason),
References: q.References,
}
explicit, hasExplicit := ev.in.Spec.Parameters[q.ID]
qs.Visible = q.VisibleWhen.Holds(ev.env) && platformOK(q.Platforms, ev.in.Spec.Platform)
if !qs.Visible {
if hasExplicit {
ev.stale(q.ID, explicit, "the question does not apply to the current answers")
}
st.Questions = append(st.Questions, qs)
continue
}
qs.Required = q.Required || (len(q.RequiredWhen) > 0 && q.RequiredWhen.Holds(ev.env))
// options and their availability
enabled := map[string]bool{}
for _, o := range q.Options {
os := OptionState{
ID: o.ID, Title: Tr(o.Translations, loc, "title", o.Title),
Description: Tr(o.Translations, loc, "description", o.Description),
Recommended: o.Recommended, Reason: Tr(o.Translations, loc, "reason", o.Reason),
Support: statusOf(o.Support), SupportNote: Tr(o.Translations, loc, "supportNote", o.SupportNote),
References: o.References,
}
os.Enabled = o.Support.Selectable()
if !os.Enabled {
os.Disabled = os.SupportNote
} else if len(o.EnabledWhen) > 0 && !o.EnabledWhen.Holds(ev.env) {
os.Enabled = false
os.Disabled = "not available with the answers given before"
}
enabled[o.ID] = os.Enabled
for _, t := range []*catalog.Targets{o.Effects.Requires, o.Effects.Implies} {
if t != nil {
for _, p := range t.Packages {
os.Adds = append(os.Adds, "package:"+p)
}
for _, c := range t.Capabilities {
os.Adds = append(os.Adds, "capability:"+c)
}
}
}
qs.Options = append(qs.Options, os)
}
checkOpts := func(v any) string {
if q.Type != "select" && q.Type != "multiselect" {
return ""
}
for _, x := range listOf(v) {
if !enabled[catalog.Scalar(x)] {
for _, o := range qs.Options {
if o.ID == catalog.Scalar(x) {
return fmt.Sprintf("option %q is not available: %s", o.ID, o.Disabled)
}
}
}
}
return ""
}
// default (defaultWhen first match wins)
def := q.Default
for _, dw := range q.DefaultWhen {
if dw.When.Holds(ev.env) {
def = dw.Value
break
}
}
if ds, ok := def.(string); ok && strings.Contains(ds, "${") {
// a default built from earlier answers (postmaster@${domains[0]})
if x, err := expand(ds, ev.vars()); err == nil {
def = strings.Trim(x, "'")
} else {
def = nil
}
}
if def != nil {
if n, err := Normalize(q, def); err == nil {
def = n
if bad := checkOpts(def); bad != "" {
def = ev.fallbackOption(q, enabled)
}
} else {
ev.msg("error", "default", fmt.Sprintf("question %s: default %v is invalid: %v", q.ID, def, err), "catalog")
def = nil
}
}
qs.Default = def
var val any
origin := ""
if hasExplicit {
n, err := Normalize(q, explicit)
switch {
case err != nil:
qs.Errors = append(qs.Errors, err.Error())
case checkOpts(n) != "":
ev.stale(q.ID, explicit, checkOpts(n))
default:
val, origin = n, "instance"
}
}
if origin == "" && ev.preset != nil && !q.InstanceSpecific && q.Type != "secret" &&
(ev.preset.Spec.Solution == "" || ev.preset.Spec.Solution == ev.s.Meta.ID) {
if pv, ok := ev.preset.Spec.Parameters[q.ID]; ok {
if n, err := Normalize(q, pv); err == nil && checkOpts(n) == "" {
val, origin = n, "preset:"+ev.preset.Metadata.Name
} else {
ev.msg("warning", "preset", fmt.Sprintf("preset value for %s is not valid any more and is ignored", q.ID), "preset:"+ev.preset.Metadata.Name)
}
}
}
if origin == "" && len(qs.Errors) == 0 && def != nil {
val, origin = def, "default"
}
if val != nil && len(qs.Errors) == 0 {
for _, vw := range q.ValidateWhen {
if vw.When.Holds(ev.env) {
var err error
if l, isList := val.([]any); isList {
err = checkCount(vw.Validation, len(l))
} else {
err = checkValue(vw.Validation, val)
}
if err != nil {
qs.Errors = append(qs.Errors, err.Error())
}
}
}
}
levelAsked := qs.Level.Rank() <= mode.Rank()
missing := qs.Required && (!catalog.IsSet(val) || len(qs.Errors) > 0)
qs.Asked = (levelAsked && !strings.HasPrefix(origin, "preset:")) || missing || len(qs.Errors) > 0
if qs.Asked && q.InstanceSpecific {
qs.Asked = true
}
if val != nil && len(qs.Errors) == 0 {
ev.answers[q.ID] = val
st.Answers[q.ID] = Answer{Value: val, Origin: origin}
qs.Value, qs.Origin = val, origin
}
for j := range qs.Options {
for _, x := range listOf(qs.Value) {
if catalog.Scalar(x) == qs.Options[j].ID {
qs.Options[j].Selected = true
if sup := qs.Options[j].Support; sup == catalog.Experimental || sup == catalog.Untested || sup == catalog.Discouraged || sup == catalog.NeedsPrereq {
ev.msg("warning", "support-"+string(sup), fmt.Sprintf("%s: %q is %s. %s", qs.Title, qs.Options[j].Title, sup, qs.Options[j].SupportNote), "question:"+q.ID)
}
}
}
}
for _, w := range q.Warnings {
if w.When.Holds(ev.env) {
sev := w.Severity
if sev == "" {
sev = "warning"
}
m := Message{Severity: sev, Code: "question", Text: Tr(q.Translations, loc, "warning", w.Text), Source: "question:" + q.ID}
qs.Warnings = append(qs.Warnings, m)
st.Messages = append(st.Messages, m)
}
}
if missing {
st.Progress.Missing = append(st.Progress.Missing, q.ID)
}
if qs.Asked {
st.Progress.Asked++
askedIdx++
if origin == "instance" {
st.Progress.Answered++
} else if st.Next == "" {
st.Next = q.ID
st.Progress.Step = askedIdx
}
}
st.Questions = append(st.Questions, qs)
}
if st.Next == "" {
st.Progress.Step = askedIdx
}
// what needs attention first: a missing or invalid answer
idx := 0
for _, q := range st.Questions {
if q.Visible && q.Asked {
idx++
if len(q.Errors) > 0 || (q.Required && !catalog.IsSet(q.Value)) {
st.Next, st.Progress.Step = q.ID, idx
break
}
}
}
}
func levelOf(l catalog.Level) catalog.Level {
if l == "" {
return catalog.LevelQuick
}
return l
}
// fallbackOption: the recommended enabled option, else the first enabled.
func (ev *evaluation) fallbackOption(q *catalog.Question, enabled map[string]bool) any {
for _, o := range q.Options {
if o.Recommended && enabled[o.ID] {
return o.ID
}
}
for _, o := range q.Options {
if enabled[o.ID] {
return o.ID
}
}
return nil
}
// ---- effects of options and rules ----------------------------------------
func (ev *evaluation) effects() {
for i := range ev.s.Spec.Questions {
q := &ev.s.Spec.Questions[i]
v, ok := ev.answers[q.ID]
if !ok {
continue
}
for _, o := range q.Options {
for _, x := range listOf(v) {
if catalog.Scalar(x) == o.ID {
ev.apply("option "+q.ID+"="+o.ID, "option", o.Effects, o.Reason)
}
}
}
}
for _, r := range ev.s.Spec.Rules {
if !r.When.Holds(ev.env) {
continue
}
ev.apply("rule "+r.ID, "rule", r.Effects, r.Reason)
if r.Message != "" {
sev := r.Severity
if sev == "" {
sev = "warning"
}
ev.msg(sev, "rule", r.Message, "rule:"+r.ID)
}
}
}
func (ev *evaluation) apply(source, kind string, fx catalog.Effects, reason string) {
var parts []string
put := func(t *catalog.Targets, pk, cp map[string][]string, verb string) {
if t == nil {
return
}
for _, p := range t.Packages {
if pk != nil {
add(pk, p, source)
}
parts = append(parts, verb+" package "+p)
}
for _, c := range t.Capabilities {
if cp != nil {
add(cp, c, source)
}
parts = append(parts, verb+" "+c)
}
for _, m := range t.Modules {
if verb == "excludes" {
add(ev.exclMod, m, source)
} else if verb == "requires" || verb == "implies" {
add(ev.reqMod, m, source)
}
parts = append(parts, verb+" module "+m)
}
for q, want := range t.Answers {
parts = append(parts, fmt.Sprintf("%s %s=%v", verb, q, want))
if verb == "excludes" || verb == "conflicts" {
if have, ok := ev.answers[q]; ok && matchesAnswer(have, want) {
ev.msg("error", "conflict", fmt.Sprintf("%s=%v cannot be combined with this choice (%s)", q, catalog.Scalar(want), source), source)
}
}
if verb == "requires" {
if have, ok := ev.answers[q]; !ok || !matchesAnswer(have, want) {
ev.msg("error", "requires-answer", fmt.Sprintf("%s requires %s=%v", source, q, catalog.Scalar(want)), source)
}
}
}
}
put(fx.Requires, ev.reqPkg, ev.reqCap, "requires")
put(fx.Implies, ev.reqPkg, ev.implCap, "implies")
put(fx.Excludes, nil, ev.exclCap, "excludes")
put(fx.Conflicts, ev.conflPkg, ev.exclCap, "conflicts")
put(fx.Recommends, ev.recPkg, ev.recCap, "recommends")
put(fx.Discourages, ev.discPkg, ev.discCap, "discourages")
for _, c := range fx.Provides {
ev.extCap[c] = source
parts = append(parts, "provides "+c+" (external)")
}
if len(parts) == 0 && kind == "option" {
return
}
sort.Strings(parts)
ev.st.Rules = append(ev.st.Rules, AppliedRule{ID: source, Source: kind, Effect: strings.Join(parts, "; "), Reason: reason})
}
func matchesAnswer(have, want any) bool {
for _, h := range listOf(have) {
for _, w := range listOf(want) {
if catalog.Equal(h, w) {
return true
}
}
}
return false
}
// ---- packages, capabilities, modules ---------------------------------------
func (ev *evaluation) pkg(id, status, reason string) *PackageState {
p, ok := ev.pkgs[id]
if !ok {
cp := ev.e.Cat.Packages[id]
title := id
_ = cp
p = &PackageState{ID: id, Title: title, Summary: ev.e.PackageSummary(id), Status: status, Reasons: []string{}}
ev.pkgs[id] = p
ev.pkgSeen = append(ev.pkgSeen, id)
}
if rank(status) > rank(p.Status) {
p.Status = status
}
if status == StRequired || status == StSelected || status == StOptional {
p.Selected = true
}
for _, r := range p.Reasons {
if r == reason {
return p
}
}
if reason != "" {
p.Reasons = append(p.Reasons, reason)
}
return p
}
func rank(s string) int {
switch s {
case StRequired:
return 4
case StSelected:
return 3
case StOptional:
return 2
case StRecommended:
return 1
}
return 0
}
func (ev *evaluation) packages() {
for _, pu := range ev.s.Spec.Packages {
holds := len(pu.When) == 0 || pu.When.Holds(ev.env)
if pu.Recommended {
// a recommendation never selects a package
if holds {
ev.pkg(pu.ID, StRecommended, firstNonEmpty(pu.Reason, "recommended for this solution"))
}
continue
}
if !holds {
continue
}
status := StRequired
if pu.Role == "optional" {
status = StOptional
}
p := ev.pkg(pu.ID, status, firstNonEmpty(pu.Reason, "part of this solution"))
if pu.Profile != "" {
p.Profile = pu.Profile
}
}
for _, id := range catalog.SortedIDs(ev.reqPkg) {
for _, r := range ev.reqPkg[id] {
ev.pkg(id, StRequired, r)
}
}
for _, id := range catalog.SortedIDs(ev.recPkg) {
for _, r := range ev.recPkg[id] {
ev.pkg(id, StRecommended, r)
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Package: id, Reason: r, Source: r})
}
}
// modules from profiles
for _, id := range ev.pkgSeen {
p := ev.pkgs[id]
if !p.Selected {
continue
}
ev.mods[id] = map[string]*ModuleState{}
cp := ev.e.Cat.Packages[id]
for _, m := range cp.Spec.Modules {
ev.mods[id][m.ID] = &ModuleState{ID: m.ID, Title: m.Title, Program: m.Program, Kind: m.Kind, Support: statusOf(m.Support)}
}
if p.Profile == "" {
// no profile: every selectable module of the package is used
for _, m := range cp.Spec.Modules {
if m.Support.Selectable() {
ms := ev.mods[id][m.ID]
ms.Enabled = true
ms.Reason = "package " + id
}
}
continue
}
chain, err := ev.e.Cat.ProfileChain(id, p.Profile)
if err != nil {
ev.msg("error", "profile", err.Error(), "package:"+id)
continue
}
for _, prof := range chain {
for mid, state := range prof.Spec.Modules {
if ms := ev.mods[id][mid]; ms != nil {
ms.Enabled = state == "enabled"
ms.Reason = "profile " + prof.Key()
}
}
for _, r := range prof.Spec.Recommendations {
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Package: r.Package, Capability: r.Capability, Reason: r.Reason, Source: "profile:" + prof.Key()})
if r.Package != "" {
ev.pkg(r.Package, StRecommended, r.Reason)
}
}
}
}
for _, m := range catalog.SortedIDs(ev.reqMod) {
pkg, mod, _ := strings.Cut(m, "/")
ev.pkg(pkg, StRequired, ev.reqMod[m][0])
ev.ensureMods(pkg)
if ms := ev.mods[pkg][mod]; ms != nil {
ms.Enabled = true
ms.Reason = ev.reqMod[m][0]
}
}
for _, m := range catalog.SortedIDs(ev.exclMod) {
pkg, mod, _ := strings.Cut(m, "/")
if ms := ev.mods[pkg][mod]; ms != nil {
if _, needed := ev.reqMod[m]; needed {
ev.msg("error", "module-conflict", fmt.Sprintf("module %s is both required and excluded (%s)", m, ev.exclMod[m][0]), ev.exclMod[m][0])
continue
}
ms.Enabled = false
ms.Reason = "excluded by " + ev.exclMod[m][0]
}
}
}
func (ev *evaluation) ensureMods(pkg string) {
if ev.mods[pkg] != nil {
return
}
ev.mods[pkg] = map[string]*ModuleState{}
cp := ev.e.Cat.Packages[pkg]
if cp == nil {
return
}
profile := ""
if p := ev.pkgs[pkg]; p != nil {
profile = p.Profile
}
for _, m := range cp.Spec.Modules {
ms := &ModuleState{ID: m.ID, Title: m.Title, Program: m.Program, Kind: m.Kind, Support: statusOf(m.Support)}
if profile == "" && m.Support.Selectable() {
ms.Enabled, ms.Reason = true, "package "+pkg
}
ev.mods[pkg][m.ID] = ms
}
}
func firstNonEmpty(a ...string) string {
for _, s := range a {
if s != "" {
return s
}
}
return ""
}
func (ev *evaluation) capTitle(id string) string {
if c, ok := ev.e.Cat.Capabilities[id]; ok {
return Tr(c.Translations, ev.st.Locale, "title", c.Title)
}
return id
}
func (ev *evaluation) capState(id string) *CapState {
c, ok := ev.caps[id]
if !ok {
c = &CapState{ID: id, Title: ev.capTitle(id), Reasons: []string{}}
ev.caps[id] = c
}
return c
}
func (ev *evaluation) capabilities() {
type need struct{ id, reason string }
var queue []need
for _, c := range ev.s.Spec.Capabilities.Required {
queue = append(queue, need{c, "required by the solution"})
}
for _, m := range []map[string][]string{ev.reqCap, ev.implCap} {
for _, c := range catalog.SortedIDs(m) {
queue = append(queue, need{c, m[c][0]})
}
}
// requirements of modules the profiles enabled
for _, pid := range ev.pkgSeen {
cp := ev.e.Cat.Packages[pid]
for _, m := range cp.Spec.Modules {
if ms := ev.mods[pid][m.ID]; ms != nil && ms.Enabled {
for _, r := range m.Requires {
queue = append(queue, need{r, "needed by " + pid + "/" + m.ID})
}
}
}
}
done := map[string]bool{}
for steps := 0; len(queue) > 0 && steps < 10000; steps++ {
n := queue[0]
queue = queue[1:]
cs := ev.capState(n.id)
add2(&cs.Reasons, n.reason)
if done[n.id] {
continue
}
done[n.id] = true
cs.Status = StRequired
if src, ok := ev.exclCap[n.id]; ok {
cs.Status = StConflicting
ev.msg("error", "capability-conflict", fmt.Sprintf("%s is needed (%s) but excluded (%s)", n.id, n.reason, src[0]), src[0])
continue
}
if src, ok := ev.extCap[n.id]; ok {
cs.Status = StExternal
cs.Provider = "external:" + src
continue
}
var chosen *catalog.ModuleRef
var alts []string
providers := ev.e.Cat.ProvidersOf(n.id)
// a module that already provides it wins, then a selected package
pick := func(f func(catalog.ModuleRef) bool) {
for i := range providers {
if chosen == nil && providers[i].Support.Selectable() && f(providers[i]) {
chosen = &providers[i]
}
}
}
pick(func(r catalog.ModuleRef) bool {
ms := ev.mods[r.Package][r.Module]
return ms != nil && ms.Enabled
})
pick(func(r catalog.ModuleRef) bool { return ev.pkgs[r.Package] != nil && ev.pkgs[r.Package].Selected })
pick(func(r catalog.ModuleRef) bool { return true })
for _, pr := range providers {
if chosen == nil || pr != *chosen {
alts = append(alts, pr.String())
}
}
if c, ok := ev.e.Cat.Capabilities[n.id]; ok {
for _, x := range c.External {
alts = append(alts, "external:"+x.ID)
}
for _, r := range c.Requires {
queue = append(queue, need{r, "needed by " + n.id})
}
}
cs.Alternatives = alts
if chosen == nil {
cs.Status = StMissing
ev.msg("error", "capability-missing", fmt.Sprintf("no available provider for %s (%s)", n.id, n.reason), "")
continue
}
cs.Provider = chosen.String()
p := ev.pkg(chosen.Package, StRequired, "provides "+n.id)
_ = p
ev.ensureMods(chosen.Package)
ms := ev.mods[chosen.Package][chosen.Module]
if !ms.Enabled {
if src, excluded := ev.exclMod[chosen.String()]; excluded {
cs.Status = StConflicting
ev.msg("error", "module-conflict", fmt.Sprintf("%s needs module %s, which is excluded (%s)", n.id, chosen, src[0]), src[0])
continue
}
ms.Enabled = true
ms.Reason = "provides " + n.id
}
cm := ev.e.Cat.Packages[chosen.Package].Module(chosen.Module)
for _, r := range cm.Requires {
queue = append(queue, need{r, "needed by " + chosen.String()})
}
}
// capabilities provided as a side effect, recommended, optional, excluded
for _, pid := range ev.pkgSeen {
for _, m := range ev.e.Cat.Packages[pid].Spec.Modules {
if ms := ev.mods[pid][m.ID]; ms != nil && ms.Enabled {
for _, c := range m.Provides {
if !ev.requiresMet(c) {
continue // e.g. AI analysis without an AI server
}
cs := ev.capState(c)
if cs.Status == "" {
cs.Status = StSelected
cs.Provider = pid + "/" + m.ID
add2(&cs.Reasons, "provided by "+pid+"/"+m.ID)
}
}
}
}
}
// capabilities the user's answers say exist outside Yetano
for _, c := range catalog.SortedIDs(ev.extCap) {
cs := ev.capState(c)
if cs.Status == "" {
cs.Status = StExternal
cs.Provider = "external:" + ev.extCap[c]
add2(&cs.Reasons, "provided outside Yetano ("+ev.extCap[c]+")")
}
}
soft := func(list []string, m map[string][]string, status, why string) {
ids := append([]string{}, list...)
ids = append(ids, catalog.SortedIDs(m)...)
for _, c := range ids {
cs := ev.capState(c)
if cs.Status != "" {
continue
}
cs.Status = status
r := why
if rs, ok := m[c]; ok {
r = rs[0]
}
add2(&cs.Reasons, r)
for _, pr := range ev.e.Cat.ProvidersOf(c) {
cs.Alternatives = append(cs.Alternatives, pr.String())
}
if status == StRecommended {
ev.st.Recommended = append(ev.st.Recommended, Recommendation{Capability: c, Reason: r, Source: r})
}
}
}
soft(ev.s.Spec.Capabilities.Recommended, ev.recCap, StRecommended, "recommended by the solution")
soft(ev.s.Spec.Capabilities.Optional, nil, StOptional, "optional for this solution")
for _, c := range catalog.SortedIDs(ev.exclCap) {
cs := ev.capState(c)
// required and excluded was reported above; a capability an enabled
// module merely could provide is just not used
if cs.Status == "" || cs.Status == StSelected {
cs.Status = StExcluded
cs.Provider = ""
add2(&cs.Reasons, "excluded by "+ev.exclCap[c][0])
}
}
// capability-level conflicts between provided capabilities
for _, id := range catalog.SortedIDs(ev.caps) {
cs := ev.caps[id]
if c, ok := ev.e.Cat.Capabilities[id]; ok && provided(cs.Status) {
for _, other := range c.Conflicts {
if o, ok := ev.caps[other]; ok && provided(o.Status) && id < other {
ev.msg("error", "capability-conflict", fmt.Sprintf("%s and %s cannot be combined", id, other), "capability:"+id)
}
}
}
}
for _, c := range catalog.SortedIDs(ev.discCap) {
if cs, ok := ev.caps[c]; ok && provided(cs.Status) {
ev.msg("warning", "discouraged", fmt.Sprintf("%s is possible but not recommended here (%s)", c, ev.discCap[c][0]), ev.discCap[c][0])
}
}
}
// requiresMet: every capability c requires is required/provided already.
func (ev *evaluation) requiresMet(c string) bool {
cp, ok := ev.e.Cat.Capabilities[c]
if !ok {
return true
}
for _, r := range cp.Requires {
if cs, ok := ev.caps[r]; !ok || !provided(cs.Status) {
if _, ext := ev.extCap[r]; !ext {
return false
}
}
}
return true
}
func provided(s string) bool {
return s == StRequired || s == StSelected || s == StExternal
}
func add2(list *[]string, s string) {
for _, x := range *list {
if x == s {
return
}
}
*list = append(*list, s)
}
func (ev *evaluation) finishModules() {
for _, id := range catalog.SortedIDs(ev.conflPkg) {
if p, ok := ev.pkgs[id]; ok && p.Selected {
ev.msg("error", "package-conflict", fmt.Sprintf("package %s cannot be used with this choice (%s)", id, ev.conflPkg[id][0]), ev.conflPkg[id][0])
}
}
for _, id := range catalog.SortedIDs(ev.discPkg) {
if p, ok := ev.pkgs[id]; ok && p.Selected {
ev.msg("warning", "discouraged", fmt.Sprintf("package %s is possible but not recommended here (%s)", id, ev.discPkg[id][0]), ev.discPkg[id][0])
}
}
ids := append([]string{}, ev.pkgSeen...)
sort.Strings(ids)
for _, id := range ids {
p := ev.pkgs[id]
if p.Selected {
cp := ev.e.Cat.Packages[id]
for _, m := range cp.Spec.Modules {
ms := ev.mods[id][m.ID]
if ms == nil {
continue
}
if ms.Enabled && (m.Support == catalog.Experimental || m.Support == catalog.Untested) {
ev.msg("warning", "support-"+string(m.Support), fmt.Sprintf("module %s/%s is %s", id, m.ID, m.Support), "package:"+id)
}
p.Modules = append(p.Modules, *ms)
}
}
ev.st.Packages = append(ev.st.Packages, *p)
}
for _, id := range catalog.SortedIDs(ev.caps) {
ev.st.Capabilities = append(ev.st.Capabilities, *ev.caps[id])
}
}
// moduleEnabled reports whether pkg/module is enabled in this evaluation.
func (ev *evaluation) moduleEnabled(pkg, mod string) bool {
ms := ev.mods[pkg][mod]
return ms != nil && ms.Enabled
}
func (ev *evaluation) pkgSelected(id string) bool {
p, ok := ev.pkgs[id]
return ok && p.Selected
}
func (ev *evaluation) finish() {
st := ev.st
refs := append([]string{}, ev.s.Spec.References.All()...)
for _, q := range st.Questions {
if q.Visible {
refs = append(refs, q.References...)
}
}
seen := map[string]bool{}
for _, r := range refs {
if !seen[r] {
seen[r] = true
st.References = append(st.References, r)
}
}
st.Related = ev.s.Spec.Related
sort.SliceStable(st.Messages, func(i, j int) bool { return sevRank(st.Messages[i].Severity) > sevRank(st.Messages[j].Severity) })
errs := 0
for _, m := range st.Messages {
if m.Severity == "error" {
errs++
}
}
st.Complete = len(st.Progress.Missing) == 0 && errs == 0
}
func sevRank(s string) int {
switch s {
case "error":
return 2
case "warning":
return 1
}
return 0
}
+266
View File
@@ -0,0 +1,266 @@
package engine
import (
"fmt"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
)
// Graph is the resolved architecture of a state (BP-03/BP-04). Node IDs:
// "pkg:<id>", "mod:<pkg>/<module>", "cap:<id>", "ext:<id>" and the
// solution's own node IDs ("n:<id>").
type Graph struct {
Nodes []GraphNode `json:"nodes"`
Edges []GraphEdge `json:"edges"`
}
// GraphNode is one node with its state (required, selected, ...).
type GraphNode struct {
ID string `json:"id"`
Type string `json:"type"` // package | module | capability | external | client | storage | network | identity | target | solution
Title string `json:"title"`
Status string `json:"status"`
Parent string `json:"parent,omitempty"` // module -> package
Ref string `json:"ref,omitempty"` // yetano: reference to open
}
// GraphEdge is a typed relation (requires, provides, connectsTo, ...).
type GraphEdge struct {
From string `json:"from"`
To string `json:"to"`
Type string `json:"type"`
Label string `json:"label,omitempty"`
Status string `json:"status,omitempty"`
}
func (ev *evaluation) graph() {
g := Graph{Nodes: []GraphNode{}, Edges: []GraphEdge{}}
have := map[string]bool{}
node := func(n GraphNode) {
if !have[n.ID] {
have[n.ID] = true
g.Nodes = append(g.Nodes, n)
}
}
edge := func(e GraphEdge) { g.Edges = append(g.Edges, e) }
solID := "sol:" + ev.s.Meta.ID
node(GraphNode{ID: solID, Type: "solution", Title: ev.st.Solution.Title, Status: StSelected, Ref: "yetano:solution/" + ev.s.Meta.ID})
for _, p := range ev.st.Packages {
status := p.Status
switch {
case !p.Selected:
status = StRecommended
case status == StOptional:
status = StSelected // an optional package the answers chose
}
pid := "pkg:" + p.ID
node(GraphNode{ID: pid, Type: "package", Title: p.ID, Status: status, Ref: "yetano:package/" + p.ID})
if p.Selected {
edge(GraphEdge{From: solID, To: pid, Type: "requires", Status: status})
} else {
edge(GraphEdge{From: solID, To: pid, Type: "optional", Label: "recommended", Status: StRecommended})
}
for _, m := range p.Modules {
st := StDisabled
if m.Enabled {
st = StSelected
}
if !m.Support.Selectable() {
st = StUnsupported
}
if !m.Enabled {
continue // disabled modules stay out of the picture; the package detail lists them
}
mid := "mod:" + p.ID + "/" + m.ID
node(GraphNode{ID: mid, Type: "module", Title: firstNonEmpty(m.Program, m.ID), Status: st, Parent: pid, Ref: "yetano:module/" + p.ID + "/" + m.ID})
}
}
for _, c := range ev.st.Capabilities {
cid := "cap:" + c.ID
node(GraphNode{ID: cid, Type: "capability", Title: c.Title, Status: c.Status, Ref: "yetano:capability/" + c.ID})
switch {
case strings.HasPrefix(c.Provider, "external:"):
xid := "ext:" + c.ID
node(GraphNode{ID: xid, Type: "external", Title: "existing " + c.Title, Status: StExternal})
edge(GraphEdge{From: xid, To: cid, Type: "provides", Status: StExternal})
case c.Provider != "":
pkg, _, _ := strings.Cut(c.Provider, "/")
from := "mod:" + c.Provider
if !have[from] {
from = "pkg:" + pkg
}
edge(GraphEdge{From: from, To: cid, Type: "provides", Status: c.Status})
}
if c.Status == StRecommended || c.Status == StOptional || c.Status == StMissing {
for _, alt := range c.Alternatives {
if strings.HasPrefix(alt, "external:") {
continue
}
pkg, _, _ := strings.Cut(alt, "/")
if !have["pkg:"+pkg] {
node(GraphNode{ID: "pkg:" + pkg, Type: "package", Title: pkg, Status: StAlternative, Ref: "yetano:package/" + pkg})
}
edge(GraphEdge{From: "pkg:" + pkg, To: cid, Type: "alternativeTo", Status: StAlternative})
}
}
if c.Status == StRequired || c.Status == StMissing || c.Status == StConflicting {
edge(GraphEdge{From: solID, To: cid, Type: "requires", Status: c.Status})
}
}
// not implemented options of visible questions: shown as unsupported alternatives
for _, q := range ev.st.Questions {
if !q.Visible {
continue
}
for _, o := range q.Options {
if o.Support.Selectable() {
continue
}
for _, a := range o.Adds {
if p, ok := strings.CutPrefix(a, "package:"); ok && !have["pkg:"+p] {
node(GraphNode{ID: "pkg:" + p, Type: "package", Title: p, Status: StUnsupported, Ref: "yetano:package/" + p})
}
}
}
}
// solution-specific nodes and edges
for _, n := range ev.s.Spec.Architecture.Nodes {
if len(n.When) > 0 && !n.When.Holds(ev.env) {
continue
}
st := StSelected
if n.Type == "external" || n.Type == "client" {
st = StExternal
}
title, err := expand(n.Title, ev.vars())
if err != nil {
title = n.Title
}
node(GraphNode{ID: "n:" + n.ID, Type: n.Type, Title: strings.Trim(title, "'"), Status: st})
}
resolve := func(id string) string {
if strings.Contains(id, ":") {
return id
}
return "n:" + id
}
for _, e := range ev.s.Spec.Architecture.Edges {
if len(e.When) > 0 && !e.When.Holds(ev.env) {
continue
}
from, to := resolve(e.From), resolve(e.To)
if !have[from] || !have[to] || !inUse(g, from) || !inUse(g, to) {
continue // an end that is not part of this resolution
}
edge(GraphEdge{From: from, To: to, Type: e.Type, Label: e.Label})
}
// confirmed Big Picture connections between selected packages
if bp := ev.e.Cat.BigPicture; bp != nil {
byProduct := map[string]string{}
for _, p := range ev.st.Packages {
if cp := ev.e.Cat.Packages[p.ID]; cp != nil && p.Selected {
byProduct[cp.Spec.BigPicture] = "pkg:" + p.ID
}
}
for _, c := range bp.Connections {
f, okf := byProduct[c.From]
t, okt := byProduct[c.To]
if okf && okt && c.Review == "confirmed" {
edge(GraphEdge{From: f, To: t, Type: c.Type, Label: c.Label})
}
}
}
sort.SliceStable(g.Edges, func(i, j int) bool {
a, b := g.Edges[i], g.Edges[j]
return fmt.Sprint(a.From, a.To, a.Type) < fmt.Sprint(b.From, b.To, b.Type)
})
ev.st.Graph = g
}
// inUse: the node is part of the solution (not only an alternative).
func inUse(g Graph, id string) bool {
for _, n := range g.Nodes {
if n.ID == id {
switch n.Status {
case StRequired, StSelected, StExternal:
return true
}
return false
}
}
return false
}
// GraphText renders a graph as indented text for the CLI (BP-06).
func GraphText(g Graph) string {
var b strings.Builder
byID := map[string]GraphNode{}
for _, n := range g.Nodes {
byID[n.ID] = n
}
mark := func(status string) string {
switch status {
case StRequired, StSelected:
return "+"
case StRecommended, StOptional, StAlternative:
return "?"
case StExternal:
return "~"
case StMissing, StConflicting, StUnsupported:
return "!"
}
return " "
}
for _, n := range g.Nodes {
if n.Type != "package" {
continue
}
fmt.Fprintf(&b, "%s %s [%s]\n", mark(n.Status), n.Title, n.Status)
for _, m := range g.Nodes {
if m.Parent == n.ID {
fmt.Fprintf(&b, " %s %s\n", mark(m.Status), m.Title)
for _, e := range g.Edges {
if e.From == m.ID && e.Type == "provides" {
fmt.Fprintf(&b, " provides %s\n", byID[e.To].Title)
}
}
}
}
}
var other []string
for _, n := range g.Nodes {
switch n.Type {
case "external", "client", "storage", "network", "identity", "target":
other = append(other, fmt.Sprintf("%s %s (%s)", mark(n.Status), n.Title, n.Type))
}
}
if len(other) > 0 {
b.WriteString("around it:\n")
for _, o := range other {
fmt.Fprintf(&b, " %s\n", o)
}
}
var rel []string
for _, e := range g.Edges {
f, t := byID[e.From], byID[e.To]
if e.Type == "provides" || e.Type == "requires" || e.Type == "optional" || f.Type == "solution" {
continue
}
label := e.Type
if e.Label != "" {
label += " (" + e.Label + ")"
}
rel = append(rel, fmt.Sprintf(" %s --%s--> %s", f.Title, label, t.Title))
}
if len(rel) > 0 {
b.WriteString("connections:\n")
b.WriteString(strings.Join(rel, "\n"))
b.WriteString("\n")
}
b.WriteString("legend: + used ? recommended/optional ~ external ! missing/unsupported\n")
return b.String()
}
var _ = catalog.Supported
+278
View File
@@ -0,0 +1,278 @@
package engine
import (
"fmt"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
)
// HandbookPage is one Markdown page of a solution handbook (HB-01).
type HandbookPage struct {
Path string
Content []byte
}
// Handbook composes the handbook of a state from the solution, the
// decisions, the generated files and existing manual text (via mr). It
// covers only what was chosen (HB-02) and never prints secret values
// (HB-04): secret answers are references and are shown as such.
func (e *Engine) Handbook(st *State, mr ManualReader) []HandbookPage {
s := e.Cat.Lookup(st.Solution.ID)
link := func(ref string) string {
if mr != nil {
if l := mr.Link(ref); l != "" {
return l
}
}
return "`" + ref + "`"
}
excerpt := func(b *strings.Builder, ref string) {
if mr == nil {
fmt.Fprintf(b, "- %s\n", link(ref))
return
}
title, md, ok := mr.Excerpt(ref, 40)
if !ok {
fmt.Fprintf(b, "- %s\n", link(ref))
return
}
fmt.Fprintf(b, "> From the manual: **%s** (%s)\n>\n", title, link(ref))
for _, line := range strings.Split(strings.TrimRight(md, "\n"), "\n") {
fmt.Fprintf(b, "> %s\n", line)
}
b.WriteString("\n")
}
var pages []HandbookPage
page := func(name, title string, body func(b *strings.Builder)) {
var b strings.Builder
fmt.Fprintf(&b, "# %s\n\n", title)
body(&b)
pages = append(pages, HandbookPage{Path: "handbook/" + name, Content: []byte(b.String())})
}
selected := []PackageState{}
for _, p := range st.Packages {
if p.Selected {
selected = append(selected, p)
}
}
hasCap := func(prefix string) bool {
for _, c := range st.Capabilities {
if strings.HasPrefix(c.ID, prefix) && provided(c.Status) {
return true
}
}
return false
}
secretQ := map[string]bool{}
for _, q := range s.Spec.Questions {
if q.Type == "secret" {
secretQ[q.ID] = true
}
}
page("index.md", "Handbook: "+firstNonEmpty(st.Instance, st.Solution.Title), func(b *strings.Builder) {
fmt.Fprintf(b, "%s\n\n", st.Solution.Summary)
fmt.Fprintf(b, "Solution `%s` %s, status **%s**.\n\n", st.Solution.ID, st.Solution.Version, st.Solution.Status)
b.WriteString("1. [Your architecture](architecture.md)\n2. [Installation and configuration](installation.md)\n3. [Configuration reference](configuration.md)\n4. [Security](security.md)\n5. [Operations and maintenance](operations.md)\n")
if hasCap("backup.") {
b.WriteString("6. [Backup and restore](backup-restore.md)\n7. [Troubleshooting](troubleshooting.md)\n")
} else {
b.WriteString("6. [Troubleshooting](troubleshooting.md)\n")
}
b.WriteString("\n## Your decisions\n\n| Question | Answer | From |\n|---|---|---|\n")
for _, q := range st.Questions {
if !q.Visible || q.Value == nil {
continue
}
val := answerText(q)
if secretQ[q.ID] {
val = "(secret reference)"
}
fmt.Fprintf(b, "| %s | %s | %s |\n", q.Title, val, q.Origin)
}
if len(st.Messages) > 0 {
b.WriteString("\n## Notes and warnings\n\n")
for _, m := range st.Messages {
fmt.Fprintf(b, "- **%s**: %s\n", m.Severity, m.Text)
}
}
})
page("architecture.md", "Your architecture", func(b *strings.Builder) {
b.WriteString("```text\n")
b.WriteString(GraphText(st.Graph))
b.WriteString("```\n\n## Packages\n\n")
for _, p := range selected {
fmt.Fprintf(b, "### %s\n\n%s\n\n", p.ID, p.Summary)
if p.Profile != "" {
fmt.Fprintf(b, "Profile: `%s`. ", p.Profile)
}
fmt.Fprintf(b, "Why: %s.\n\n", strings.Join(p.Reasons, "; "))
var on []string
for _, m := range p.Modules {
if m.Enabled {
on = append(on, fmt.Sprintf("`%s`", firstNonEmpty(m.Program, m.ID)))
}
}
if len(on) > 0 {
fmt.Fprintf(b, "Programs used: %s.\n\n", strings.Join(on, ", "))
}
}
b.WriteString("## Capabilities\n\n| Capability | Status | Provided by |\n|---|---|---|\n")
for _, c := range st.Capabilities {
if c.Status == StExcluded {
continue
}
fmt.Fprintf(b, "| %s | %s | %s |\n", c.Title, c.Status, firstNonEmpty(c.Provider, "–"))
}
if st.Solution.BigPicture != "" {
fmt.Fprintf(b, "\nIn the Big Picture: %s\n", link("yetano:bigpicture/"+st.Solution.BigPicture))
}
})
page("installation.md", "Installation and configuration", func(b *strings.Builder) {
b.WriteString("The guide has not changed any system. These are the steps, in order;\n" +
"`deployment-plan.yaml` has the same list in machine-readable form.\n\n")
phase := ""
n := 0
for _, sp := range st.Steps {
if sp.Phase != phase {
phase = sp.Phase
fmt.Fprintf(b, "## %s\n\n", strings.ToUpper(phase[:1])+phase[1:])
}
n++
fmt.Fprintf(b, "%d. %s\n", n, sp.Title)
if sp.Run != "" {
fmt.Fprintf(b, "\n ```sh\n %s\n ```\n", sp.Run)
}
if sp.Note != "" {
fmt.Fprintf(b, "\n %s\n", sp.Note)
}
if sp.Reversible != nil && !*sp.Reversible {
b.WriteString("\n **Cannot be undone automatically.**\n")
}
b.WriteString("\n")
}
})
page("configuration.md", "Configuration reference", func(b *strings.Builder) {
for _, f := range st.Files {
fmt.Fprintf(b, "## `%s`\n\n```yaml\n%s```\n\n", f.Path, f.Content)
keys := make([]string, 0, len(f.Origins))
for k := range f.Origins {
keys = append(keys, k)
}
sort.Strings(keys)
b.WriteString("| Setting | Comes from | Uses answers |\n|---|---|---|\n")
for _, k := range keys {
o := f.Origins[k]
fmt.Fprintf(b, "| `%s` | %s | %s |\n", k, o.Source, strings.Join(o.Params, ", "))
}
b.WriteString("\n")
}
for _, p := range selected {
if cp := e.Cat.Packages[p.ID]; cp != nil {
for _, m := range cp.Spec.Modules {
if ms := findModule(p, m.ID); ms != nil && ms.Enabled && m.Manual != "" {
fmt.Fprintf(b, "- Full option list of %s: %s\n", firstNonEmpty(m.Program, m.ID), link("yetano:manual/"+m.Manual+"/configuration"))
}
}
}
}
})
page("security.md", "Security", func(b *strings.Builder) {
b.WriteString("Secrets are never written into these files: secret answers are\nreferences (`secret://…` resolved by yaseva, `env:`, `file:`).\n\n")
for _, c := range st.Checks {
if c.Status == CheckNotApplicable {
continue
}
if c.Kind == "tls" || c.Kind == "dns" || strings.Contains(c.ID, "tls") || strings.Contains(c.ID, "relay") {
fmt.Fprintf(b, "- **%s** (%s): %s", c.Title, c.Severity, c.Hint)
if c.Run != "" {
fmt.Fprintf(b, " Check: `%s`", c.Run)
}
b.WriteString("\n")
}
}
for _, r := range s.Spec.References.Manuals {
if strings.Contains(r, "dkim") || strings.Contains(r, "tls") || strings.Contains(r, "security") {
b.WriteString("\n")
excerpt(b, r)
}
}
})
page("operations.md", "Operations and maintenance", func(b *strings.Builder) {
for _, op := range s.Spec.Operations {
fmt.Fprintf(b, "- %s\n", op)
}
b.WriteString("\n## Health checks\n\n")
for _, p := range selected {
if cp := e.Cat.Packages[p.ID]; cp != nil {
for _, m := range cp.Spec.Modules {
if ms := findModule(p, m.ID); ms != nil && ms.Enabled {
for _, d := range m.Doctor {
fmt.Fprintf(b, "- `%s`\n", d)
}
}
}
}
}
if len(st.Related) > 0 {
b.WriteString("\n## Related tasks and solutions\n\n")
for _, r := range st.Related {
kind := "solution"
if e.Cat.Tasks[r] != nil {
kind = "task"
}
fmt.Fprintf(b, "- `yet %s show %s`\n", kind, r)
}
}
})
if hasCap("backup.") {
page("backup-restore.md", "Backup and restore", func(b *strings.Builder) {
for _, c := range st.Capabilities {
if strings.HasPrefix(c.ID, "backup.") && provided(c.Status) {
fmt.Fprintf(b, "- %s: %s\n", c.Title, c.Provider)
}
}
})
}
page("troubleshooting.md", "Troubleshooting", func(b *strings.Builder) {
b.WriteString("Run the health checks from [operations](operations.md) first: they name\nthe failing area and give a hint.\n\n## Manuals\n\n")
refs := append([]string{}, st.References...)
for _, r := range refs {
if strings.HasPrefix(r, "yetano:manual/") {
fmt.Fprintf(b, "- %s\n", link(r))
}
}
})
return pages
}
func findModule(p PackageState, id string) *ModuleState {
for i := range p.Modules {
if p.Modules[i].ID == id {
return &p.Modules[i]
}
}
return nil
}
func answerText(q QuestionState) string {
if l, ok := q.Value.([]any); ok {
var parts []string
for _, x := range l {
parts = append(parts, optTitle(q, catalog.Scalar(x)))
}
return strings.Join(parts, ", ")
}
return optTitle(q, catalog.Scalar(q.Value))
}
func optTitle(q QuestionState, v string) string {
for _, o := range q.Options {
if o.ID == v {
return o.Title
}
}
return v
}
+190
View File
@@ -0,0 +1,190 @@
// Package engine is the Solutions Engine: it evaluates a solution's
// questions and rules against a user's answers, resolves packages,
// modules, capabilities and providers, generates native configuration
// with the origin of every value, and builds the architecture graph,
// the plan, the lock file and the handbook.
//
// The engine is pure: it reads a loaded catalog and values, and returns
// values. It never touches the network, never runs a command and writes
// files only in Write, into the directory it is given.
package engine
import (
"bytes"
"errors"
"fmt"
"io"
"sort"
"gopkg.in/yaml.v3"
"yetano.dev/yetano/core/solutions/catalog"
)
// Instance is a user's answers for one solution: a draft wizard session
// (kind WizardSession) or a saved solution instance (SolutionInstance).
// It never contains plain-text secrets (secret answers are references).
type Instance struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Kind string `yaml:"kind" json:"kind"`
Metadata InstanceMeta `yaml:"metadata" json:"metadata"`
Spec InstanceSpec `yaml:"spec" json:"spec"`
}
// InstanceMeta names an instance.
type InstanceMeta struct {
Name string `yaml:"name" json:"name"`
Description string `yaml:"description,omitempty" json:"description,omitempty"`
Created string `yaml:"created,omitempty" json:"created,omitempty"`
Updated string `yaml:"updated,omitempty" json:"updated,omitempty"`
Favorite bool `yaml:"favorite,omitempty" json:"favorite,omitempty"`
Archived bool `yaml:"archived,omitempty" json:"archived,omitempty"`
}
// InstanceSpec holds the decisions.
type InstanceSpec struct {
Solution SolutionPin `yaml:"solution" json:"solution"`
Mode catalog.Level `yaml:"mode,omitempty" json:"mode,omitempty"`
Preset string `yaml:"preset,omitempty" json:"preset,omitempty"`
Locale string `yaml:"locale,omitempty" json:"locale,omitempty"`
Platform string `yaml:"platform,omitempty" json:"platform,omitempty"`
Target string `yaml:"target,omitempty" json:"target,omitempty"`
Parameters map[string]any `yaml:"parameters" json:"parameters"`
Overrides []Override `yaml:"overrides,omitempty" json:"overrides,omitempty"`
// Cursor is the question a wizard session was at (sessions only).
Cursor string `yaml:"cursor,omitempty" json:"cursor,omitempty"`
}
// SolutionPin names the solution and the version the answers were made for.
type SolutionPin struct {
ID string `yaml:"id" json:"id"`
Version string `yaml:"version,omitempty" json:"version,omitempty"`
}
// Override sets one value in a generated file directly (layer 6 of
// ARCHITECTURE.md): path is dot-separated map keys.
type Override struct {
File string `yaml:"file" json:"file"`
Path string `yaml:"path" json:"path"`
Value any `yaml:"value" json:"value"`
}
// Preset is a reusable set of answers (PRE-01). Instance-specific and
// secret questions are never taken from a preset.
type Preset struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Kind string `yaml:"kind" json:"kind"`
Metadata InstanceMeta `yaml:"metadata" json:"metadata"`
Spec PresetSpec `yaml:"spec" json:"spec"`
}
// PresetSpec holds a preset's answers.
type PresetSpec struct {
Solution string `yaml:"solution,omitempty" json:"solution,omitempty"`
Version string `yaml:"version,omitempty" json:"version,omitempty"`
Mode catalog.Level `yaml:"mode,omitempty" json:"mode,omitempty"`
Parameters map[string]any `yaml:"parameters" json:"parameters"`
}
// NewInstance starts a session for a solution.
func NewInstance(name string, s *catalog.Solution, mode catalog.Level) *Instance {
if mode == "" {
mode = catalog.LevelQuick
}
return &Instance{
APIVersion: catalog.APIVersion, Kind: catalog.KindSession,
Metadata: InstanceMeta{Name: name},
Spec: InstanceSpec{
Solution: SolutionPin{ID: s.Meta.ID, Version: s.Meta.Version},
Mode: mode,
Parameters: map[string]any{},
},
}
}
// MaxInstanceSize bounds instance and preset files.
const MaxInstanceSize = 1 << 20
// ReadInstance decodes an instance or session (strict).
func ReadInstance(r io.Reader) (*Instance, error) {
var in Instance
if err := strict(r, &in); err != nil {
return nil, err
}
if in.APIVersion != catalog.APIVersion {
return nil, fmt.Errorf("apiVersion %q, want %q", in.APIVersion, catalog.APIVersion)
}
if in.Kind != catalog.KindInstance && in.Kind != catalog.KindSession {
return nil, fmt.Errorf("kind %q, want %s or %s", in.Kind, catalog.KindInstance, catalog.KindSession)
}
if in.Spec.Parameters == nil {
in.Spec.Parameters = map[string]any{}
}
return &in, nil
}
// ReadPreset decodes a preset (strict).
func ReadPreset(r io.Reader) (*Preset, error) {
var p Preset
if err := strict(r, &p); err != nil {
return nil, err
}
if p.APIVersion != catalog.APIVersion || p.Kind != catalog.KindPreset {
return nil, fmt.Errorf("not a %s %s", catalog.APIVersion, catalog.KindPreset)
}
if p.Spec.Parameters == nil {
p.Spec.Parameters = map[string]any{}
}
return &p, nil
}
func strict(r io.Reader, v any) error {
b, err := io.ReadAll(io.LimitReader(r, MaxInstanceSize+1))
if err != nil {
return err
}
if len(b) > MaxInstanceSize {
return fmt.Errorf("larger than %d bytes", MaxInstanceSize)
}
d := yaml.NewDecoder(bytes.NewReader(b))
d.KnownFields(true)
if err := d.Decode(v); err != nil && !errors.Is(err, io.EOF) {
return err
}
return nil
}
// Marshal renders any of the user files as YAML with sorted parameters.
func Marshal(v any) ([]byte, error) {
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf)
enc.SetIndent(2)
if err := enc.Encode(v); err != nil {
return nil, err
}
enc.Close()
return buf.Bytes(), nil
}
// PresetFrom derives a preset from an instance: all answers except
// instance-specific and secret ones (PRE-02, PRE-04).
func PresetFrom(name string, in *Instance, s *catalog.Solution) *Preset {
p := &Preset{
APIVersion: catalog.APIVersion, Kind: catalog.KindPreset,
Metadata: InstanceMeta{Name: name},
Spec: PresetSpec{Solution: s.Meta.ID, Version: s.Meta.Version, Mode: in.Spec.Mode, Parameters: map[string]any{}},
}
keys := make([]string, 0, len(in.Spec.Parameters))
for k := range in.Spec.Parameters {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
q, _ := s.Question(k)
if q == nil || q.InstanceSpecific || q.Type == "secret" {
continue
}
p.Spec.Parameters[k] = in.Spec.Parameters[k]
}
return p
}
+379
View File
@@ -0,0 +1,379 @@
package engine
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
)
// Lock pins what a generation was made from (LOCK-01). It has no
// timestamps, so the same inputs give the same file.
type Lock struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Kind string `yaml:"kind" json:"kind"`
Spec LockSpec `yaml:"spec" json:"spec"`
}
// LockSpec is the content of a lock.
type LockSpec struct {
Generator string `yaml:"generator" json:"generator"`
Catalog Pinned `yaml:"catalog" json:"catalog"`
Solution Pinned `yaml:"solution" json:"solution"`
Profiles []Pinned `yaml:"profiles,omitempty" json:"profiles,omitempty"`
Packages []Pinned `yaml:"packages,omitempty" json:"packages,omitempty"`
Capability string `yaml:"capabilities" json:"capabilities"` // hash of the capability files
BigPicture string `yaml:"bigpicture,omitempty" json:"bigpicture,omitempty"`
Answers string `yaml:"answers" json:"answers"`
Files []FileHash `yaml:"files" json:"files"`
}
// Pinned is an entity with version and content hash.
type Pinned struct {
ID string `yaml:"id" json:"id"`
Version string `yaml:"version,omitempty" json:"version,omitempty"`
Hash string `yaml:"sha256" json:"sha256"`
}
// FileHash is a generated file and its hash.
type FileHash = catalog.FileHash
// OutFile is one file of a generated solution directory.
type OutFile struct {
Path string `json:"path"`
Kind string `json:"kind"` // instance | lock | config | architecture | handbook | plan | readme
Content []byte `json:"-"`
}
// Output is everything Generate produces.
type Output struct {
Files []OutFile `json:"files"`
Lock *Lock `json:"lock"`
}
// ManualReader gives the handbook existing manual text (implemented by
// package knowledge). It may be nil: the handbook then links instead.
type ManualReader interface {
// Excerpt returns the title and Markdown of a manual reference
// (yetano:manual/...#section), shortened to at most maxLines lines.
Excerpt(ref string, maxLines int) (title, markdown string, ok bool)
// Link returns a human link for a reference (web URL or CLI command).
Link(ref string) string
}
// Generate renders all output files of a complete state. It refuses an
// incomplete state unless allowIncomplete is set.
func (e *Engine) Generate(st *State, in *Instance, mr ManualReader, allowIncomplete bool) (*Output, error) {
if !st.Complete && !allowIncomplete {
return nil, fmt.Errorf("%w: %s", ErrIncomplete, incompleteText(st))
}
s := e.Cat.Lookup(st.Solution.ID)
out := &Output{}
addf := func(path, kind string, b []byte) {
out.Files = append(out.Files, OutFile{Path: path, Kind: kind, Content: b})
}
inst := *in
inst.Kind = catalog.KindInstance
inst.Spec.Solution.Version = s.Meta.Version
inst.Spec.Cursor = ""
b, err := Marshal(&inst)
if err != nil {
return nil, err
}
addf("solution.yaml", "instance", b)
for _, f := range st.Files {
addf(f.Path, "config", []byte(f.Content))
}
gj, _ := json.MarshalIndent(st.Graph, "", " ")
addf("architecture/graph.json", "architecture", append(gj, '\n'))
addf("architecture/graph.txt", "architecture", []byte(GraphText(st.Graph)))
pb, err := Marshal(PlanOf(st))
if err != nil {
return nil, err
}
addf("deployment-plan.yaml", "plan", pb)
for _, h := range e.Handbook(st, mr) {
addf(h.Path, "handbook", h.Content)
}
addf("README.md", "readme", []byte(readme(st)))
sort.Slice(out.Files, func(i, j int) bool { return out.Files[i].Path < out.Files[j].Path })
for _, f := range out.Files {
if !catalog.SafeRelPath(f.Path) {
return nil, fmt.Errorf("refusing unsafe output path %q", f.Path)
}
}
out.Lock = e.lock(st, s, in, out.Files)
lb, err := Marshal(out.Lock)
if err != nil {
return nil, err
}
out.Files = append(out.Files, OutFile{Path: "solution.lock.yaml", Kind: "lock", Content: lb})
return out, nil
}
// ErrIncomplete: required answers are missing or errors remain.
var ErrIncomplete = errors.New("the solution is not complete")
func incompleteText(st *State) string {
var parts []string
if len(st.Progress.Missing) > 0 {
parts = append(parts, "missing: "+strings.Join(st.Progress.Missing, ", "))
}
for _, m := range st.Messages {
if m.Severity == "error" {
parts = append(parts, m.Text)
}
}
for _, q := range st.Questions {
for _, e := range q.Errors {
parts = append(parts, q.ID+": "+e)
}
}
return strings.Join(parts, "; ")
}
func hashBytes(b []byte) string {
h := sha256.Sum256(b)
return hex.EncodeToString(h[:])
}
func (e *Engine) lock(st *State, s *catalog.Solution, in *Instance, files []OutFile) *Lock {
c := e.Cat
l := &Lock{APIVersion: catalog.APIVersion, Kind: "SolutionLock"}
l.Spec.Generator = GeneratorVersion
l.Spec.Catalog = Pinned{ID: c.Meta.ID, Version: c.Meta.Version, Hash: c.Hash()}
l.Spec.Solution = Pinned{ID: s.Meta.ID, Version: s.Meta.Version, Hash: s.Hash}
for _, p := range st.Packages {
if !p.Selected {
continue
}
if cp := c.Packages[p.ID]; cp != nil {
l.Spec.Packages = append(l.Spec.Packages, Pinned{ID: p.ID, Hash: cp.Hash})
}
if p.Profile != "" {
chain, _ := c.ProfileChain(p.ID, p.Profile)
for _, pr := range chain {
l.Spec.Profiles = append(l.Spec.Profiles, Pinned{ID: pr.Key(), Hash: pr.Hash})
}
}
}
var capFiles, bpFiles []string
for _, f := range c.Files {
if strings.HasPrefix(f.Path, "bigpicture:") {
bpFiles = append(bpFiles, f.Path+" "+f.Hash)
} else if strings.HasPrefix(f.Path, "capabilities") {
capFiles = append(capFiles, f.Path+" "+f.Hash)
}
}
l.Spec.Capability = hashBytes([]byte(strings.Join(capFiles, "\n")))
if len(bpFiles) > 0 {
l.Spec.BigPicture = hashBytes([]byte(strings.Join(bpFiles, "\n")))
}
ab, _ := json.Marshal(in.Spec.Parameters) // map keys are sorted by encoding/json
ob, _ := json.Marshal(in.Spec.Overrides)
l.Spec.Answers = hashBytes(append(append(ab, '\n'), ob...))
for _, f := range files {
l.Spec.Files = append(l.Spec.Files, FileHash{Path: f.Path, Hash: hashBytes(f.Content)})
}
return l
}
// LockDrift lists what changed meaning between a previous lock and now
// (LOCK-02/03): a changed solution, profile or package definition.
func LockDrift(prev, cur *Lock) []string {
var out []string
if prev.Spec.Solution.Hash != cur.Spec.Solution.Hash {
out = append(out, fmt.Sprintf("solution %s changed (%s -> %s)", cur.Spec.Solution.ID, prev.Spec.Solution.Version, cur.Spec.Solution.Version))
}
cmp := func(kind string, a, b []Pinned) {
m := map[string]string{}
for _, p := range a {
m[p.ID] = p.Hash
}
for _, p := range b {
if h, ok := m[p.ID]; !ok {
out = append(out, fmt.Sprintf("%s %s is new", kind, p.ID))
} else if h != p.Hash {
out = append(out, fmt.Sprintf("%s %s changed", kind, p.ID))
}
delete(m, p.ID)
}
for id := range m {
out = append(out, fmt.Sprintf("%s %s is no longer used", kind, id))
}
}
cmp("profile", prev.Spec.Profiles, cur.Spec.Profiles)
cmp("package", prev.Spec.Packages, cur.Spec.Packages)
if prev.Spec.Capability != cur.Spec.Capability {
out = append(out, "the capability catalog changed")
}
sort.Strings(out)
return out
}
// ReadLock reads dir/solution.lock.yaml; a missing file is (nil, nil).
func ReadLock(dir string) (*Lock, error) {
f, err := os.Open(filepath.Join(dir, "solution.lock.yaml"))
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
defer f.Close()
var l Lock
if err := strict(f, &l); err != nil {
return nil, fmt.Errorf("solution.lock.yaml: %w", err)
}
return &l, nil
}
// ErrModified: a file in the output directory was changed by hand.
var ErrModified = errors.New("output directory has changes that would be overwritten")
// Write writes out into dir (CONF-05, CONF-06). Without force it refuses
// to overwrite a file that differs from what the previous lock recorded
// (a hand edit) or a file the previous generation did not write. Files of
// the previous generation that are no longer produced are removed only
// when they are unchanged.
func Write(dir string, out *Output, force bool) error {
prev, err := ReadLock(dir)
if err != nil && !force {
return err
}
known := map[string]string{}
if prev != nil {
for _, f := range prev.Spec.Files {
known[f.Path] = f.Hash
}
known["solution.lock.yaml"] = "*"
}
var conflicts []string
for _, f := range out.Files {
p := filepath.Join(dir, filepath.FromSlash(f.Path))
cur, err := os.ReadFile(p)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return err
}
h, isKnown := known[f.Path]
switch {
case h == "*":
case !isKnown && hashBytes(cur) != hashBytes(f.Content):
conflicts = append(conflicts, f.Path+" (not written by the guide)")
case isKnown && hashBytes(cur) != h:
conflicts = append(conflicts, f.Path+" (changed by hand)")
}
}
if len(conflicts) > 0 && !force {
return fmt.Errorf("%w: %s; use --force to overwrite", ErrModified, strings.Join(conflicts, ", "))
}
for _, f := range out.Files {
p := filepath.Join(dir, filepath.FromSlash(f.Path))
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
return err
}
tmp := p + ".tmp"
if err := os.WriteFile(tmp, f.Content, 0o644); err != nil {
return err
}
if err := os.Rename(tmp, p); err != nil {
return err
}
}
// stale files of the previous generation
now := map[string]bool{}
for _, f := range out.Files {
now[f.Path] = true
}
if prev != nil {
for _, f := range prev.Spec.Files {
if now[f.Path] || !catalog.SafeRelPath(f.Path) {
continue
}
p := filepath.Join(dir, filepath.FromSlash(f.Path))
if cur, err := os.ReadFile(p); err == nil && hashBytes(cur) == f.Hash {
os.Remove(p)
}
}
}
return nil
}
// Plan is the deployment plan: what an operator (or a later apply) does,
// in order. It is never executed by the engine (LIFE-01).
type Plan struct {
APIVersion string `yaml:"apiVersion" json:"apiVersion"`
Kind string `yaml:"kind" json:"kind"`
Spec PlanSpec `yaml:"spec" json:"spec"`
}
// PlanSpec lists files, steps and checks.
type PlanSpec struct {
Solution string `yaml:"solution" json:"solution"`
Instance string `yaml:"instance" json:"instance"`
Target string `yaml:"target" json:"target"`
Apply string `yaml:"apply" json:"apply"`
Packages []string `yaml:"packages" json:"packages"`
Files []string `yaml:"files" json:"files"`
Steps []PlannedStep `yaml:"steps" json:"steps"`
Checks []PlanCheck `yaml:"checks" json:"checks"`
}
// PlanCheck is a check to run after applying.
type PlanCheck struct {
ID string `yaml:"id" json:"id"`
Title string `yaml:"title" json:"title"`
Run string `yaml:"run,omitempty" json:"run,omitempty"`
}
// PlanOf builds the plan of a state.
func PlanOf(st *State) *Plan {
p := &Plan{APIVersion: catalog.APIVersion, Kind: "DeploymentPlan"}
p.Spec.Solution = st.Solution.ID + " " + st.Solution.Version
p.Spec.Instance = st.Instance
p.Spec.Target = firstNonEmpty(st.Platform, "local")
p.Spec.Apply = "manual: the guide does not apply plans yet; run the steps yourself (LIFE-01)"
for _, pk := range st.Packages {
if pk.Selected {
p.Spec.Packages = append(p.Spec.Packages, pk.ID)
}
}
for _, f := range st.Files {
p.Spec.Files = append(p.Spec.Files, f.Path)
}
p.Spec.Steps = st.Steps
if p.Spec.Steps == nil {
p.Spec.Steps = []PlannedStep{}
}
for _, c := range st.Checks {
if c.Status != CheckNotApplicable {
p.Spec.Checks = append(p.Spec.Checks, PlanCheck{ID: c.ID, Title: c.Title, Run: c.Run})
}
}
return p
}
func readme(st *State) string {
var b strings.Builder
fmt.Fprintf(&b, "# %s\n\n", firstNonEmpty(st.Instance, st.Solution.Title))
fmt.Fprintf(&b, "Solution: %s (`%s` %s), generated by the Yetano Solutions Guide.\n\n", st.Solution.Title, st.Solution.ID, st.Solution.Version)
b.WriteString("| Path | Content |\n|---|---|\n")
b.WriteString("| `solution.yaml` | your answers (SolutionInstance); regenerate with `yet solution generate --file solution.yaml --output .` |\n")
b.WriteString("| `solution.lock.yaml` | what this was generated from (catalog, profiles, file hashes) |\n")
b.WriteString("| `config/` | native configuration files, one directory per package |\n")
b.WriteString("| `deployment-plan.yaml` | the steps to install, configure and check it (not executed by the guide) |\n")
b.WriteString("| `architecture/` | the resolved architecture (`graph.json`, `graph.txt`) |\n")
b.WriteString("| `handbook/` | your handbook: start with `handbook/index.md` |\n\n")
b.WriteString("Nothing here has been installed or changed on any system.\n")
return b.String()
}
+138
View File
@@ -0,0 +1,138 @@
package engine
import (
"fmt"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
)
// phases in plan order.
var phaseOrder = map[string]int{"install": 0, "configure": 1, "data": 2, "dns": 3, "start": 4, "verify": 5}
func (ev *evaluation) steps() {
vars := ev.vars()
for _, s := range ev.s.Spec.Steps {
if len(s.When) > 0 && !s.When.Holds(ev.env) {
continue
}
if s.Package != "" && !ev.pkgSelected(s.Package) {
continue
}
if s.Package != "" && s.Module != "" && s.ForEach != "$modules" && !ev.moduleEnabled(s.Package, s.Module) {
continue
}
items := []any{nil}
switch {
case s.ForEach == "$modules":
// every enabled module of the step's package that is a program
items = nil
if cp := ev.e.Cat.Packages[s.Package]; cp != nil {
for _, m := range cp.Spec.Modules {
if m.Program != "" && ev.moduleEnabled(s.Package, m.ID) && (s.Module == "" || m.Kind == s.Module) {
items = append(items, m.Program)
}
}
}
case s.ForEach != "":
items = listOf(ev.answers[s.ForEach])
}
for i, it := range items {
v := vars
if s.ForEach != "" {
v = map[string]any{}
for k, x := range vars {
v[k] = x
}
v["item"] = it
}
run, err := expand(s.Run, v)
if err != nil {
ev.msg("error", "step", fmt.Sprintf("step %s: %v", s.ID, err), "step:"+s.ID)
continue
}
title, _ := expand(s.Title, v)
note, _ := expand(s.Note, v)
id := s.ID
if s.ForEach != "" {
id = fmt.Sprintf("%s-%d", s.ID, i+1)
}
phase := s.Phase
if phase == "" {
phase = "configure"
}
ev.st.Steps = append(ev.st.Steps, PlannedStep{
ID: id, Title: title, Phase: phase, Package: s.Package, Module: s.Module,
Run: run, Note: note, Mutating: s.Mutating, Reversible: s.Reversible, References: s.References,
})
}
}
sort.SliceStable(ev.st.Steps, func(i, j int) bool {
return phaseOrder[ev.st.Steps[i].Phase] < phaseOrder[ev.st.Steps[j].Phase]
})
}
// expand fills placeholders into a text (steps, notes). Values are
// inserted as text; steps are shown to the operator, never run.
func expand(s string, vars map[string]any) (string, error) {
if !strings.Contains(s, "${") {
return s, nil
}
var firstErr error
used := map[string]bool{}
out := placeholderRE.ReplaceAllStringFunc(s, func(m string) string {
if m == "$${" {
return "${"
}
if strings.HasPrefix(m, "${item") {
if it, ok := vars["item"]; ok {
return catalog.Scalar(it)
}
}
v, err := lookup(m, vars, used)
if err != nil && firstErr == nil {
firstErr = err
}
return shellWord(text(v))
})
return out, firstErr
}
// shellWord quotes a value for display in a command line if needed.
func shellWord(s string) string {
if s == "" {
return "''"
}
for _, r := range s {
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("@%+=:,./_-", r)) {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
}
return s
}
func (ev *evaluation) checks() {
vars := ev.vars()
for _, c := range ev.s.Spec.Requirements {
r := CheckResult{ID: c.ID, Title: c.Title, Kind: c.Kind, Severity: firstNonEmpty(c.Severity, "error"),
Local: c.Local, Hint: c.Hint, References: c.References, Params: map[string]string{}}
if len(c.When) > 0 && !c.When.Holds(ev.env) {
r.Status = CheckNotApplicable
ev.st.Checks = append(ev.st.Checks, r)
continue
}
for k, v := range c.Params {
x, err := expand(v, vars)
if err != nil {
x = v
}
r.Params[k] = strings.Trim(x, "'")
}
r.Run, _ = expand(c.Run, vars)
// The engine itself never inspects a system: every check starts
// as NOT_CHECKED; a doctor runner fills in results (DR-03).
r.Status = CheckNotChecked
ev.st.Checks = append(ev.st.Checks, r)
}
}
+33
View File
@@ -0,0 +1,33 @@
package engine
import (
"os/exec"
"strings"
"testing"
)
// SEC-02: the catalog, the engine and the knowledge index never run a
// program or open a network connection; the CLI may (doctor checks).
// core/secretref links os/exec for resolving secret:// through yaseva;
// the engine only uses its Validate, so os/exec is checked on the
// packages' own imports, network packages on all dependencies.
func TestNoExecOrNetwork(t *testing.T) {
for _, pkg := range []string{"../catalog", "../engine", "../knowledge", "../ref"} {
own, err := exec.Command("go", "list", "-f", "{{join .Imports \" \"}}", pkg).Output()
if err != nil {
t.Skip("go list not available")
}
for _, dep := range strings.Fields(string(own)) {
if dep == "os/exec" || dep == "syscall" || dep == "plugin" || dep == "unsafe" {
t.Errorf("%s imports %s", pkg, dep)
}
}
all, _ := exec.Command("go", "list", "-deps", "-f", "{{.ImportPath}}", pkg).Output()
for _, dep := range strings.Fields(string(all)) {
switch dep {
case "net/http", "net/rpc", "net/smtp", "crypto/tls":
t.Errorf("%s depends on %s", pkg, dep)
}
}
}
}
+236
View File
@@ -0,0 +1,236 @@
package engine
import "yetano.dev/yetano/core/solutions/catalog"
// State is the complete result of evaluating an instance: everything a
// client shows. Clients never compute visibility, options or resolution
// themselves (API-02); they render a State.
type State struct {
Solution SolutionInfo `json:"solution"`
Instance string `json:"instance"`
Mode catalog.Level `json:"mode"`
Locale string `json:"locale"`
Platform string `json:"platform,omitempty"`
Questions []QuestionState `json:"questions"`
Next string `json:"next,omitempty"`
Progress Progress `json:"progress"`
Complete bool `json:"complete"`
Answers map[string]Answer `json:"answers"`
Stale []StaleAnswer `json:"stale,omitempty"`
Packages []PackageState `json:"packages"`
Capabilities []CapState `json:"capabilities"`
Rules []AppliedRule `json:"rules"`
Messages []Message `json:"messages"`
Recommended []Recommendation `json:"recommendations,omitempty"`
Files []FilePreview `json:"files"`
Steps []PlannedStep `json:"steps"`
Checks []CheckResult `json:"checks"`
Graph Graph `json:"graph"`
References []string `json:"references"`
Related []string `json:"related,omitempty"`
}
// SolutionInfo identifies the evaluated solution or task.
type SolutionInfo struct {
ID string `json:"id"`
Kind string `json:"kind"`
TaskKind string `json:"taskKind,omitempty"`
Version string `json:"version"`
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
Status catalog.Support `json:"status"`
Category string `json:"category,omitempty"`
BigPicture string `json:"bigpicture,omitempty"`
}
// QuestionState is one question as the client shows it.
type QuestionState struct {
ID string `json:"id"`
Type string `json:"type"`
Item string `json:"item,omitempty"`
Group string `json:"group,omitempty"`
Level catalog.Level `json:"level"`
Title string `json:"title"`
Help string `json:"help,omitempty"`
Description string `json:"description,omitempty"`
Decide string `json:"decide,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
Examples []string `json:"examples,omitempty"`
Visible bool `json:"visible"`
Asked bool `json:"asked"` // shown in the current mode
Required bool `json:"required"`
InstanceSpecific bool `json:"instanceSpecific,omitempty"`
Value any `json:"value,omitempty"`
Origin string `json:"origin,omitempty"` // default | preset | instance | ""
Default any `json:"default,omitempty"`
Recommended any `json:"recommended,omitempty"`
Reason string `json:"reason,omitempty"`
Options []OptionState `json:"options,omitempty"`
Errors []string `json:"errors,omitempty"`
Warnings []Message `json:"warnings,omitempty"`
References []string `json:"references,omitempty"`
}
// OptionState is one option with whether and why it can be chosen.
type OptionState struct {
ID string `json:"id"`
Title string `json:"title"`
Description string `json:"description,omitempty"`
Recommended bool `json:"recommended,omitempty"`
Reason string `json:"reason,omitempty"`
Support catalog.Support `json:"support"`
SupportNote string `json:"supportNote,omitempty"`
Enabled bool `json:"enabled"`
Disabled string `json:"disabledReason,omitempty"`
Selected bool `json:"selected"`
Adds []string `json:"adds,omitempty"` // packages/capabilities it brings in
References []string `json:"references,omitempty"`
}
// Progress counts asked questions.
type Progress struct {
Asked int `json:"asked"`
Answered int `json:"answered"`
Missing []string `json:"missing,omitempty"`
Step int `json:"step"` // 1-based index of Next among asked questions
}
// Answer is an effective answer and where it came from.
type Answer struct {
Value any `json:"value"`
Origin string `json:"origin"`
}
// StaleAnswer is an explicit answer that no longer counts (RULE-06).
type StaleAnswer struct {
Question string `json:"question"`
Value any `json:"value"`
Reason string `json:"reason"`
}
// Status values of packages, modules and capabilities in a state and a graph (BP-04).
const (
StRequired = "required"
StSelected = "selected"
StRecommended = "recommended"
StOptional = "optional"
StExternal = "external"
StAlternative = "alternative"
StDisabled = "disabled"
StUnsupported = "unsupported"
StMissing = "missing"
StConflicting = "conflicting"
StExcluded = "excluded"
)
// PackageState is a package in the resolved solution.
type PackageState struct {
ID string `json:"id"`
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
Status string `json:"status"`
Profile string `json:"profile,omitempty"`
Reasons []string `json:"reasons"`
Modules []ModuleState `json:"modules,omitempty"`
Selected bool `json:"selected"`
}
// ModuleState is a module of a selected package.
type ModuleState struct {
ID string `json:"id"`
Title string `json:"title"`
Program string `json:"program,omitempty"`
Kind string `json:"kind,omitempty"`
Enabled bool `json:"enabled"`
Support catalog.Support `json:"support,omitempty"`
Reason string `json:"reason,omitempty"`
}
// CapState is a capability in the resolved solution.
type CapState struct {
ID string `json:"id"`
Title string `json:"title"`
Status string `json:"status"`
Provider string `json:"provider,omitempty"` // pkg/module or external:<id>
Alternatives []string `json:"alternatives,omitempty"`
Reasons []string `json:"reasons"`
}
// AppliedRule records a rule (or an option's effects) that fired.
type AppliedRule struct {
ID string `json:"id"`
Source string `json:"source"` // rule | option | package | capability
Effect string `json:"effect"`
Reason string `json:"reason,omitempty"`
}
// Message is a warning, error or note.
type Message struct {
Severity string `json:"severity"` // info | warning | error
Code string `json:"code"`
Text string `json:"text"`
Source string `json:"source,omitempty"`
}
// Recommendation suggests an extension.
type Recommendation struct {
Package string `json:"package,omitempty"`
Capability string `json:"capability,omitempty"`
Reason string `json:"reason"`
Source string `json:"source,omitempty"`
}
// FilePreview is one generated file.
type FilePreview struct {
Path string `json:"path"`
Package string `json:"package"`
Content string `json:"content"`
Origins map[string]Origin `json:"origins"`
}
// Origin says where a configuration value came from (PROF-05).
type Origin struct {
Layer string `json:"layer"` // profile | solution | override
Source string `json:"source"` // profile:yamase/mailbox, solution:mail-server#tls, override
Params []string `json:"params,omitempty"`
}
// PlannedStep is a setup step (never executed by the engine).
type PlannedStep struct {
ID string `json:"id"`
Title string `json:"title"`
Phase string `json:"phase"`
Package string `json:"package,omitempty"`
Module string `json:"module,omitempty"`
Run string `json:"run,omitempty"`
Note string `json:"note,omitempty"`
Mutating bool `json:"mutating"`
Reversible *bool `json:"reversible,omitempty"`
References []string `json:"references,omitempty"`
}
// Check status values (DR-03).
const (
CheckPass = "PASS"
CheckInfo = "INFO"
CheckWarning = "WARNING"
CheckError = "ERROR"
CheckBlocked = "BLOCKED"
CheckNotApplicable = "NOT_APPLICABLE"
CheckNotChecked = "NOT_CHECKED"
)
// CheckResult is a requirement/doctor check and its result.
type CheckResult struct {
ID string `json:"id"`
Title string `json:"title"`
Kind string `json:"kind"`
Severity string `json:"severity"`
Local bool `json:"local"`
Params map[string]string `json:"params,omitempty"`
Run string `json:"run,omitempty"`
Hint string `json:"hint,omitempty"`
Status string `json:"status"`
Note string `json:"note,omitempty"`
References []string `json:"references,omitempty"`
}
+3
View File
@@ -0,0 +1,3 @@
interfaces: []
connections:
- {id: connection.app-idp, from: product.app, to: product.idp, type: authenticatesVia, label: signs in through, scope: general, review: confirmed}
+2
View File
@@ -0,0 +1,2 @@
title: Test Big Picture
content: {topics: topics.yaml, products: products, stories: stories, connections: connections.yaml}
+3
View File
@@ -0,0 +1,3 @@
id: product.app
name: app
summary: The test application.
+3
View File
@@ -0,0 +1,3 @@
id: product.idp
name: idp
summary: An identity provider.
+5
View File
@@ -0,0 +1,5 @@
id: story.run-app
title: Run the app
intent: I want to run the app.
outcome: The app runs.
primaryTopic: topic.t
+2
View File
@@ -0,0 +1,2 @@
topics:
- {id: topic.t, title: Testing, summary: Test topic}
+18
View File
@@ -0,0 +1,18 @@
apiVersion: yetano.dev/v1
kind: Catalog
metadata: {id: test, version: 1.0.0}
spec:
bigpicture: ../bp
webBase: https://example.test/
categories: [{id: t, topic: topic.t}]
---
apiVersion: yetano.dev/v1
kind: Capabilities
metadata: {id: caps}
spec:
capabilities:
- {id: app.serve, title: Serve the app, requires: [auth.users]}
- {id: auth.users, title: Users}
- {id: auth.sso, title: Single sign-on}
- {id: backup.files, title: Backups, external: [{id: tool, title: Your tool}]}
- {id: feature.x, title: Feature X}
+48
View File
@@ -0,0 +1,48 @@
apiVersion: yetano.dev/v1
kind: Package
metadata: {id: app}
spec:
bigpicture: product.app
sources: [test]
modules:
- {id: server, title: Server, program: app-server, kind: daemon, provides: [app.serve]}
- {id: users, title: Local users, kind: library, provides: [auth.users], priority: 10}
- {id: extra, title: Extra, program: app-extra, kind: daemon, provides: [feature.x]}
- {id: ghost, title: Not built, support: not-implemented, provides: [auth.sso]}
---
apiVersion: yetano.dev/v1
kind: Package
metadata: {id: idp}
spec:
bigpicture: product.idp
sources: [test]
modules:
- {id: sso, title: SSO, program: idp, kind: daemon, provides: [auth.sso, auth.users], priority: 1}
---
apiVersion: yetano.dev/v1
kind: Package
metadata: {id: bak, summary: Backups}
spec:
sources: [test]
modules:
- {id: b, title: Backup, program: bak, provides: [backup.files], support: experimental}
---
apiVersion: yetano.dev/v1
kind: Profile
metadata: {id: base, package: app}
spec:
modules: {server: enabled, users: enabled, extra: disabled}
config:
- file: app/app.yaml
set: {log: info, listen: ":8080", limits: {max: 10, min: 1}}
---
apiVersion: yetano.dev/v1
kind: Profile
metadata: {id: big, package: app}
spec:
extends: base
modules: {extra: enabled}
config:
- file: app/app.yaml
set: {limits: {max: 100}}
- {file: app/extra.yaml, module: extra, set: {on: true}}
+60
View File
@@ -0,0 +1,60 @@
apiVersion: yetano.dev/v1
kind: Solution
metadata: {id: app-run, version: 1.0.0, category: t, status: supported}
spec:
bigpicture: story.run-app
capabilities: {required: [app.serve], recommended: [backup.files]}
packages:
- {id: app, profile: base, role: core, when: {size: small}}
- {id: app, profile: big, role: core, when: {size: big}}
questions:
- id: size
type: select
title: How big?
default: small
options:
- {id: small, title: Small, recommended: true, reason: fits most}
- {id: big, title: Big}
- {id: hosts, type: list, item: hostname, title: Host names, required: true, instanceSpecific: true, validation: {minItems: 1}}
- id: identity
type: select
title: Users?
level: guided
default: local
options:
- {id: local, title: Local}
- {id: central, title: Central IdP, requires: {packages: [idp], capabilities: [auth.sso]}}
- {id: ghost, title: Ghost, support: not-implemented, supportNote: not built}
- {id: realm, type: string, title: Realm, visibleWhen: {identity: central}, required: true}
- {id: token, type: secret, level: advanced, title: Token}
- {id: owner, type: email, level: guided, title: Owner, default: "admin@${hosts[0]}"}
- id: backup
type: select
title: Backup
level: guided
default: none
options:
- {id: none, title: None}
- {id: mine, title: My tool, provides: [backup.files]}
- {id: bak, title: bak, requires: {packages: [bak]}}
- {id: port, type: port, level: advanced, title: Port, default: 8080}
rules:
- {id: big-warn, when: {size: big}, message: Big needs more memory., severity: warning}
- {id: no-x-small, when: {size: small}, excludes: {capabilities: [feature.x]}}
configuration:
- id: main
file: app/app.yaml
set: {hosts: "${hosts}", owner: "${owner}", listen: ":${port}", first: "${hosts[0]}", n: "${hosts.count}"}
- {id: sso, file: app/app.yaml, when: {identity: central}, set: {sso: {realm: "${realm}"}}}
- {id: tok, file: app/app.yaml, when: {token: {set: true}}, set: {token: "${token}"}}
- {id: idp, file: idp/idp.yaml, set: {realm: "${realm}"}, when: {identity: central}}
- {id: never, file: bak/bak.yaml, set: {x: 1}}
steps:
- {id: add, title: "Add ${item}", forEach: hosts, run: "app add ${item}", phase: data, mutating: true}
- {id: inst, title: "Install ${item}", package: app, forEach: $modules, run: "yet install ${item}", phase: install}
requirements:
- {id: port, title: Port free, kind: port, params: {port: "${port}"}, local: true}
- {id: bigonly, title: Memory, kind: manual, when: {size: big}}
architecture:
nodes: [{id: users, type: client, title: "Users of ${hosts[0]}"}]
edges: [{from: users, to: "mod:app/server", type: connectsTo}]
+306
View File
@@ -0,0 +1,306 @@
package engine
import (
"fmt"
"net"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"yetano.dev/yetano/core/secretref"
"yetano.dev/yetano/core/solutions/catalog"
)
// MaxAnswerLen bounds a single text answer (SEC-03).
const MaxAnswerLen = 64 << 10
var (
hostnameRE = regexp.MustCompile(`^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$`)
emailRE = regexp.MustCompile(`^[^@\s]+@[^@\s]+$`)
dateRE = regexp.MustCompile(`^\d{4}-\d{2}-\d{2}$`)
)
// TypeValidator checks and normalizes one scalar answer of a type. New
// question types are added with RegisterType (WIZ-04).
type TypeValidator func(v any) (any, error)
var extraTypes = map[string]TypeValidator{}
// RegisterType adds a question type. It must be called before catalogs
// using the type are validated; built-in types cannot be replaced.
func RegisterType(name string, fn TypeValidator) error {
if catalog.QuestionTypes[name] {
return fmt.Errorf("type %q is built in", name)
}
extraTypes[name] = fn
catalog.QuestionTypes[name] = true
return nil
}
// Normalize converts an answer given as text (CLI --set, interactive
// input) or as decoded YAML/JSON into the canonical value for the
// question and validates it. It does not check option enablement.
func Normalize(q *catalog.Question, v any) (any, error) {
switch q.Type {
case "multiselect", "list":
items := listOf(v)
out := make([]any, 0, len(items))
seen := map[string]bool{}
for _, it := range items {
var n any
var err error
if q.Type == "multiselect" {
n, err = optionValue(q, it)
} else {
n, err = scalar(q.Item, it)
}
if err != nil {
return nil, err
}
k := catalog.Scalar(n)
if seen[k] {
continue
}
seen[k] = true
out = append(out, n)
}
if err := checkCount(q.Validation, len(out)); err != nil {
return nil, err
}
return out, nil
case "select":
return optionValue(q, v)
case "keyvalue":
m, ok := v.(map[string]any)
if !ok {
s, isStr := v.(string)
if !isStr {
return nil, fmt.Errorf("want key=value pairs")
}
m = map[string]any{}
for _, part := range splitList(s) {
k, val, ok := strings.Cut(part, "=")
if !ok || strings.TrimSpace(k) == "" {
return nil, fmt.Errorf("%q: want key=value", part)
}
m[strings.TrimSpace(k)] = strings.TrimSpace(val)
}
}
return m, nil
}
n, err := scalar(q.Type, v)
if err != nil {
return nil, err
}
return n, checkValue(q.Validation, n)
}
func optionValue(q *catalog.Question, v any) (any, error) {
s := strings.TrimSpace(catalog.Scalar(v))
for _, o := range q.Options {
if o.ID == s {
return o.ID, nil
}
}
// a number picks the n-th option (interactive CLI)
if n, err := strconv.Atoi(s); err == nil && n >= 1 && n <= len(q.Options) {
return q.Options[n-1].ID, nil
}
ids := make([]string, len(q.Options))
for i, o := range q.Options {
ids[i] = o.ID
}
return nil, fmt.Errorf("%q is not one of %s", s, strings.Join(ids, ", "))
}
func listOf(v any) []any {
switch x := v.(type) {
case []any:
return x
case []string:
out := make([]any, len(x))
for i, s := range x {
out[i] = s
}
return out
case string:
var out []any
for _, p := range splitList(x) {
out = append(out, p)
}
return out
case nil:
return nil
}
return []any{v}
}
func splitList(s string) []string {
var out []string
for _, p := range strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == '\n' || r == ' ' || r == ';' }) {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
// scalar validates one value of a scalar type.
func scalar(typ string, v any) (any, error) {
if fn, ok := extraTypes[typ]; ok {
return fn(v)
}
if b, ok := v.(bool); ok && typ == "boolean" {
return b, nil
}
s := strings.TrimSpace(catalog.Scalar(v))
if len(s) > MaxAnswerLen || !utf8.ValidString(s) {
return nil, fmt.Errorf("value too long or not UTF-8")
}
switch typ {
case "boolean":
switch strings.ToLower(s) {
case "true", "yes", "y", "on", "1", "ja", "j":
return true, nil
case "false", "no", "n", "off", "0", "nein":
return false, nil
}
return nil, fmt.Errorf("%q: want yes or no", s)
case "integer":
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return nil, fmt.Errorf("%q: want a whole number", s)
}
return int(n), nil
case "decimal":
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return nil, fmt.Errorf("%q: want a number", s)
}
return f, nil
case "port":
n, err := strconv.Atoi(s)
if err != nil || n < 1 || n > 65535 {
return nil, fmt.Errorf("%q: want a port 1-65535", s)
}
return n, nil
case "hostname", "domain":
s = strings.ToLower(strings.TrimSuffix(s, "."))
if !hostnameRE.MatchString(s) || len(s) > 253 {
return nil, fmt.Errorf("%q: not a valid %s", s, typ)
}
if typ == "domain" && !strings.Contains(s, ".") {
return nil, fmt.Errorf("%q: a domain needs a dot (example.org)", s)
}
return s, nil
case "email":
if !emailRE.MatchString(s) {
return nil, fmt.Errorf("%q: not an e-mail address", s)
}
return s, nil
case "ip":
if net.ParseIP(s) == nil {
return nil, fmt.Errorf("%q: not an IP address", s)
}
return s, nil
case "cidr":
if _, _, err := net.ParseCIDR(s); err != nil {
if net.ParseIP(s) == nil {
return nil, fmt.Errorf("%q: not a network (CIDR) or address", s)
}
}
return s, nil
case "url":
u, err := url.Parse(s)
if err != nil || u.Scheme == "" || u.Host == "" {
return nil, fmt.Errorf("%q: not a URL", s)
}
return s, nil
case "duration":
if _, err := time.ParseDuration(s); err != nil {
return nil, fmt.Errorf("%q: want a duration like 30s, 5m, 4h", s)
}
return s, nil
case "date":
if !dateRE.MatchString(s) {
return nil, fmt.Errorf("%q: want YYYY-MM-DD", s)
}
if _, err := time.Parse("2006-01-02", s); err != nil {
return nil, fmt.Errorf("%q: not a date", s)
}
return s, nil
case "path", "dir":
if s == "" || strings.ContainsRune(s, 0) {
return nil, fmt.Errorf("want a path")
}
return s, nil
case "secret":
// SEC-01/WIZ-07: only references, never the secret itself.
if err := secretref.Validate(s); err != nil || s == "" {
return nil, fmt.Errorf("give a reference (secret://name, env:VAR, file:path), never the secret itself")
}
return s, nil
case "string", "text", "package", "profile", "capability", "provider", "target":
return s, nil
}
return nil, fmt.Errorf("unknown type %q", typ)
}
func checkValue(val catalog.Validation, v any) error {
msg := func(err string) error {
if val.Message != "" {
return fmt.Errorf("%s", val.Message)
}
return fmt.Errorf("%s", err)
}
if f, ok := v.(float64); ok {
return checkRange(val, f, msg)
}
if n, ok := v.(int); ok {
return checkRange(val, float64(n), msg)
}
if s, ok := v.(string); ok {
if val.MinLength > 0 && len(s) < val.MinLength {
return msg(fmt.Sprintf("at least %d characters", val.MinLength))
}
if val.MaxLength > 0 && len(s) > val.MaxLength {
return msg(fmt.Sprintf("at most %d characters", val.MaxLength))
}
if val.Pattern != "" {
re, err := regexp.Compile(val.Pattern)
if err != nil {
return fmt.Errorf("bad pattern in catalog: %v", err)
}
if !re.MatchString(s) {
return msg(fmt.Sprintf("%q does not match %s", s, val.Pattern))
}
}
}
return nil
}
func checkRange(val catalog.Validation, f float64, msg func(string) error) error {
if val.Min != nil && f < *val.Min {
return msg(fmt.Sprintf("at least %v", *val.Min))
}
if val.Max != nil && f > *val.Max {
return msg(fmt.Sprintf("at most %v", *val.Max))
}
return nil
}
func checkCount(val catalog.Validation, n int) error {
if val.MinItems > 0 && n < val.MinItems {
if val.Message != "" {
return fmt.Errorf("%s", val.Message)
}
return fmt.Errorf("at least %d item(s)", val.MinItems)
}
if val.MaxItems > 0 && n > val.MaxItems {
return fmt.Errorf("at most %d item(s)", val.MaxItems)
}
return nil
}
+28
View File
@@ -0,0 +1,28 @@
package engine
import (
"os"
"testing"
)
func TestZZDump(t *testing.T) {
if os.Getenv("DUMP") == "" {
t.Skip()
}
c := assetsCatalog(t)
e := New(c)
x := c.Examples[os.Getenv("DUMP")]
in := NewInstance(x.Meta.ID, c.Lookup(x.Spec.Solution), x.Spec.Mode)
in.Spec.Parameters = x.Spec.Parameters
st, _ := e.Evaluate(in, nil)
for _, f := range st.Files {
t.Logf("=== %s\n%s", f.Path, f.Content)
}
for _, s := range st.Steps {
t.Logf("step %s [%s] %s", s.Phase, s.Run, s.Title)
}
for _, p := range st.Packages {
t.Logf("pkg %s %s %v", p.ID, p.Status, p.Reasons)
}
t.Log(GraphText(st.Graph))
}
+7
View File
@@ -0,0 +1,7 @@
module yetano.dev/yetano/core/solutions
go 1.25.0
require gopkg.in/yaml.v3 v3.0.1
require yetano.dev/yetano/core v0.12.2
+6
View File
@@ -0,0 +1,6 @@
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
yetano.dev/yetano/core v0.12.2 h1:y8xkA1XjNTGiO9/JJRal5/IruoaqcE8aKJUYG8wVF6Q=
yetano.dev/yetano/core v0.12.2/go.mod h1:T2TdFvZiHbYVgcRmRXk9NC82AYL8krGVxxtLyedWuJE=
+34
View File
@@ -0,0 +1,34 @@
package knowledge
import (
"os"
"path/filepath"
"testing"
"yetano.dev/yetano/core/solutions/catalog"
)
func assetsIndex(t *testing.T) *Index {
t.Helper()
dir, _ := filepath.Abs("../../../assets/solutions")
if _, err := os.Stat(filepath.Join(dir, "catalog.yaml")); err != nil {
t.Skip("assets/solutions not present")
}
c, err := catalog.Load(dir)
if err != nil {
t.Fatal(err)
}
return Build(c)
}
func TestAssetsLint(t *testing.T) {
ix := assetsIndex(t)
for _, i := range Lint(ix) {
if i.Severity == "error" {
t.Error(i)
} else {
t.Log(i)
}
}
t.Logf("%d entries, %d manual topics, missing sources: %v", len(ix.Entries), len(ix.Topics), ix.Missing)
}
+439
View File
@@ -0,0 +1,439 @@
// Package knowledge is the Knowledge Engine: one local index over the
// catalog, the Big Picture and the existing manuals, with reference
// resolution per client, backlinks, search, lint and coverage. The index
// is derived data: it is rebuilt from the sources and never edited.
package knowledge
import (
"bufio"
"bytes"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
"yetano.dev/yetano/core/solutions/ref"
)
// Entry is one searchable, linkable thing.
type Entry struct {
Ref string `json:"ref"`
Kind string `json:"kind"`
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
Package string `json:"package,omitempty"`
Category string `json:"category,omitempty"`
Tags []string `json:"tags,omitempty"`
Synonyms []string `json:"synonyms,omitempty"`
Capabilities []string `json:"capabilities,omitempty"`
Status string `json:"status,omitempty"`
File string `json:"file,omitempty"` // local file (manuals)
Line int `json:"line,omitempty"`
Body string `json:"-"` // searchable text
Translations catalog.Translations `json:"-"`
}
// Section is a heading of a manual topic.
type Section struct {
ID string `json:"id"`
Title string `json:"title"`
Level int `json:"level"`
Start int `json:"start"` // first line (1-based)
End int `json:"end"` // last line
}
// Topic is one manual document.
type Topic struct {
Source string `json:"source"`
Slug string `json:"slug"`
Title string `json:"title"`
File string `json:"file"`
Sections []Section `json:"sections"`
lines []string
}
// Index is the knowledge index of one catalog.
type Index struct {
Cat *catalog.Catalog
Entries []*Entry
byRef map[string]*Entry
Topics map[string]*Topic // "<source>/<slug>"
Backlinks map[string][]string // target ref -> refs that point to it
// Missing lists knowledge sources whose files are not checked out.
Missing []string
}
// Build indexes the catalog, the Big Picture and the manuals that are
// available locally under the catalog's sourcesRoot.
func Build(c *catalog.Catalog) *Index {
ix := &Index{Cat: c, byRef: map[string]*Entry{}, Topics: map[string]*Topic{}, Backlinks: map[string][]string{}}
ix.catalogEntries()
ix.bigPictureEntries()
ix.manuals()
ix.links()
sort.Slice(ix.Entries, func(i, j int) bool { return ix.Entries[i].Ref < ix.Entries[j].Ref })
return ix
}
func (ix *Index) add(e *Entry) {
if _, dup := ix.byRef[e.Ref]; dup {
return
}
ix.byRef[e.Ref] = e
ix.Entries = append(ix.Entries, e)
}
// Entry returns the entry for a reference target (no section/version).
func (ix *Index) Entry(r string) *Entry { return ix.byRef[r] }
func (ix *Index) catalogEntries() {
c := ix.Cat
for _, id := range catalog.SortedIDs(c.Solutions) {
ix.add(solutionEntry(c, c.Solutions[id], ref.Solution))
}
for _, id := range catalog.SortedIDs(c.Tasks) {
ix.add(solutionEntry(c, c.Tasks[id], ref.Task))
}
for _, id := range catalog.SortedIDs(c.Packages) {
p := c.Packages[id]
e := &Entry{Ref: ref.For(ref.Package, id), Kind: ref.Package, Title: id, Package: id, Summary: p.Meta.Summary}
if bp := c.BigPicture; bp != nil {
if pr, ok := bp.Products[p.Spec.BigPicture]; ok {
e.Summary = firstNonEmpty(e.Summary, pr.Summary)
e.Body = strings.Join(pr.Tasks, "\n")
}
}
for _, m := range p.Spec.Modules {
e.Capabilities = append(e.Capabilities, m.Provides...)
e.Body += "\n" + m.Title + " " + m.Program
ix.add(&Entry{Ref: ref.For(ref.Module, id, m.ID), Kind: ref.Module, Title: firstNonEmpty(m.Program, m.ID) + ": " + m.Title,
Summary: m.Description, Package: id, Capabilities: m.Provides, Status: string(m.Support)})
}
if p.Spec.Microsite != "" {
ix.add(&Entry{Ref: ref.For(ref.Microsite, id), Kind: ref.Microsite, Title: id + " microsite", Package: id, Summary: e.Summary})
}
ix.add(e)
}
for _, id := range catalog.SortedIDs(c.Capabilities) {
cp := c.Capabilities[id]
ix.add(&Entry{Ref: ref.For(ref.Capability, id), Kind: ref.Capability, Title: cp.Title, Summary: cp.Description, Capabilities: []string{id}, Translations: cp.Translations})
}
for _, id := range catalog.SortedIDs(c.Profiles) {
p := c.Profiles[id]
ix.add(&Entry{Ref: ref.For(ref.Profile, p.Meta.Package, p.Meta.ID), Kind: ref.Profile, Title: firstNonEmpty(p.Meta.Title, p.Meta.ID),
Summary: p.Meta.Description, Package: p.Meta.Package})
}
for _, id := range catalog.SortedIDs(c.Examples) {
x := c.Examples[id]
ix.add(&Entry{Ref: ref.For(ref.Example, x.Spec.Solution, x.Meta.ID), Kind: ref.Example, Title: x.Meta.Title, Summary: x.Meta.Summary,
Translations: x.Meta.Translations, Body: x.Spec.Scenario})
}
}
func solutionEntry(c *catalog.Catalog, s *catalog.Solution, kind string) *Entry {
e := &Entry{Ref: ref.For(kind, s.Meta.ID), Kind: kind, Title: s.Meta.Title, Summary: s.Meta.Summary, Category: s.Meta.Category,
Tags: s.Meta.Tags, Synonyms: s.Meta.Synonyms, Status: string(s.Meta.Status), Translations: s.Meta.Translations}
if bp := c.BigPicture; bp != nil {
if g, ok := bp.Stories[s.Spec.BigPicture]; ok {
e.Title = firstNonEmpty(e.Title, g.Title)
e.Summary = firstNonEmpty(e.Summary, g.Intent)
e.Body = g.Intent + "\n" + g.Outcome
}
}
e.Body += "\n" + strings.Join(s.Spec.Goals, "\n") + "\n" + strings.Join(s.Spec.Scenarios, "\n")
for _, q := range s.Spec.Questions {
e.Body += "\n" + q.Title
for _, o := range q.Options {
e.Body += "\n" + o.Title
}
}
e.Capabilities = append(append([]string{}, s.Spec.Capabilities.Required...), s.Spec.Capabilities.Recommended...)
for _, p := range s.Spec.Packages {
e.Body += "\n" + p.ID
}
return e
}
func (ix *Index) bigPictureEntries() {
bp := ix.Cat.BigPicture
if bp == nil {
return
}
for _, id := range catalog.SortedIDs(bp.Topics) {
t := bp.Topics[id]
ix.add(&Entry{Ref: ref.For(ref.BigPicture, id), Kind: ref.BigPicture, Title: t.Title, Summary: t.Summary})
}
for _, id := range catalog.SortedIDs(bp.Stories) {
s := bp.Stories[id]
ix.add(&Entry{Ref: ref.For(ref.BigPicture, id), Kind: ref.BigPicture, Title: s.Title, Summary: s.Intent, Body: s.Outcome + "\n" + s.Explanation})
}
for _, id := range catalog.SortedIDs(bp.Products) {
p := bp.Products[id]
ix.add(&Entry{Ref: ref.For(ref.BigPicture, id), Kind: ref.BigPicture, Title: p.Name + " (Big Picture)", Summary: p.Summary})
}
}
// ---- manuals ---------------------------------------------------------------
// SourceDir is where a knowledge source's files are, or "" if unknown.
func (ix *Index) SourceDir(k *catalog.KnowledgeSource) string {
if ix.Cat.Spec.SourcesRoot == "" || ix.Cat.Root == "" {
return ""
}
root := ix.Cat.Spec.SourcesRoot
if !filepath.IsAbs(root) {
root = filepath.Join(ix.Cat.Root, root)
}
return filepath.Join(root, filepath.FromSlash(k.Spec.Repository), filepath.FromSlash(k.Spec.Root))
}
// MaxManualSize bounds one manual file.
const MaxManualSize = 2 << 20
func (ix *Index) manuals() {
for _, id := range catalog.SortedIDs(ix.Cat.Sources) {
k := ix.Cat.Sources[id]
dir := ix.SourceDir(k)
if dir == "" {
ix.Missing = append(ix.Missing, id)
continue
}
if _, err := os.Stat(filepath.Join(dir, "README.md")); err != nil {
ix.Missing = append(ix.Missing, id)
continue
}
files := []string{"README.md"}
docs := filepath.Join(dir, "docs")
_ = filepath.WalkDir(docs, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
rel, _ := filepath.Rel(dir, p)
rel = filepath.ToSlash(rel)
for _, ex := range k.Spec.Exclude {
if rel == ex || strings.HasPrefix(rel, ex+"/") {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
}
if d.IsDir() && strings.HasPrefix(d.Name(), ".") {
return fs.SkipDir
}
if !d.IsDir() && strings.HasSuffix(p, ".md") {
files = append(files, rel)
}
return nil
})
sort.Strings(files)
for _, f := range files {
b, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(f)))
if err != nil || len(b) > MaxManualSize {
continue
}
t := parseTopic(id, TopicSlug(f), filepath.Join(dir, filepath.FromSlash(f)), b)
ix.Topics[id+"/"+t.Slug] = t
caps := []string{}
for _, st := range k.Spec.Topics {
if st.Slug == t.Slug {
caps = st.Capabilities
}
}
r := ref.For(ref.Manual, id, t.Slug)
ix.add(&Entry{Ref: r, Kind: ref.Manual, Title: t.Title, Summary: firstLine(t), Package: k.Spec.Package,
Capabilities: caps, File: t.File, Body: strings.Join(t.lines, "\n")})
for _, s := range t.Sections[1:] {
ix.add(&Entry{Ref: r + "#" + s.ID, Kind: "section", Title: t.Title + " › " + s.Title, Package: k.Spec.Package,
File: t.File, Line: s.Start, Body: strings.Join(t.lines[s.Start-1:s.End], "\n")})
}
}
}
}
// TopicSlug follows core/manual: README.md -> readme, docs/x.md -> x,
// docs/x/README.md -> x.
func TopicSlug(rel string) string {
if rel == "README.md" {
return "readme"
}
s := strings.TrimSuffix(strings.TrimPrefix(rel, "docs/"), ".md")
s = strings.TrimSuffix(s, "/README")
return strings.ReplaceAll(s, "/", ".")
}
func parseTopic(source, slug, file string, b []byte) *Topic {
t := &Topic{Source: source, Slug: slug, File: file}
sc := bufio.NewScanner(bytes.NewReader(b))
sc.Buffer(make([]byte, 64<<10), MaxManualSize)
fence := false
seen := map[string]int{}
for sc.Scan() {
line := sc.Text()
t.lines = append(t.lines, line)
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") {
fence = !fence
continue
}
if fence || !strings.HasPrefix(line, "#") {
continue
}
level := len(line) - len(strings.TrimLeft(line, "#"))
title := strings.TrimSpace(line[level:])
if level > 6 || title == "" {
continue
}
id := ref.Slug(title)
if n := seen[id]; n > 0 {
id = fmt.Sprintf("%s-%d", id, n)
}
seen[ref.Slug(title)]++
if len(t.Sections) > 0 {
t.Sections[len(t.Sections)-1].End = len(t.lines) - 1
}
t.Sections = append(t.Sections, Section{ID: id, Title: title, Level: level, Start: len(t.lines)})
if t.Title == "" && level == 1 {
t.Title = title
}
}
if len(t.Sections) == 0 {
t.Sections = []Section{{ID: "", Title: slug, Level: 1, Start: 1}}
}
t.Sections[len(t.Sections)-1].End = len(t.lines)
if t.Title == "" {
t.Title = slug
}
return t
}
func firstLine(t *Topic) string {
for _, l := range t.lines {
l = strings.TrimSpace(l)
if l != "" && !strings.HasPrefix(l, "#") && !strings.HasPrefix(l, "```") && !strings.HasPrefix(l, "|") && !strings.HasPrefix(l, "<") {
if len(l) > 200 {
l = l[:200] + "…"
}
return l
}
}
return ""
}
func firstNonEmpty(a ...string) string {
for _, s := range a {
if s != "" {
return s
}
}
return ""
}
// links collects every reference the catalog makes, for backlinks (REL-01/02).
func (ix *Index) links() {
c := ix.Cat
link := func(from string, to string) {
r, err := ref.Parse(to)
if err != nil {
return
}
t := r.Target()
for _, x := range ix.Backlinks[t] {
if x == from {
return
}
}
ix.Backlinks[t] = append(ix.Backlinks[t], from)
}
for _, m := range []map[string]*catalog.Solution{c.Solutions, c.Tasks} {
for _, id := range catalog.SortedIDs(m) {
s := m[id]
kind := ref.Solution
if s.IsTask() {
kind = ref.Task
}
from := ref.For(kind, id)
for _, r := range RefsOf(s) {
link(from, r)
}
for _, p := range s.Spec.Packages {
link(from, ref.For(ref.Package, p.ID))
}
for _, cp := range append(append([]string{}, s.Spec.Capabilities.Required...), s.Spec.Capabilities.Recommended...) {
link(from, ref.For(ref.Capability, cp))
}
if s.Spec.BigPicture != "" {
link(from, ref.For(ref.BigPicture, s.Spec.BigPicture))
}
for _, r := range s.Spec.Related {
k := ref.Solution
if c.Tasks[r] != nil {
k = ref.Task
}
link(from, ref.For(k, r))
}
}
}
for _, id := range catalog.SortedIDs(c.Packages) {
p := c.Packages[id]
from := ref.For(ref.Package, id)
for _, m := range p.Spec.Modules {
for _, cp := range m.Provides {
link(ref.For(ref.Module, id, m.ID), ref.For(ref.Capability, cp))
link(from, ref.For(ref.Capability, cp))
}
}
if p.Spec.BigPicture != "" {
link(from, ref.For(ref.BigPicture, p.Spec.BigPicture))
}
}
for _, id := range catalog.SortedIDs(c.Profiles) {
p := c.Profiles[id]
for _, r := range p.Spec.References {
link(ref.For(ref.Profile, p.Meta.Package, p.Meta.ID), r)
}
link(ref.For(ref.Profile, p.Meta.Package, p.Meta.ID), ref.For(ref.Package, p.Meta.Package))
}
for _, id := range catalog.SortedIDs(c.Examples) {
x := c.Examples[id]
k := ref.Solution
if c.Tasks[x.Spec.Solution] != nil {
k = ref.Task
}
link(ref.For(ref.Example, x.Spec.Solution, x.Meta.ID), ref.For(k, x.Spec.Solution))
}
for k := range ix.Backlinks {
sort.Strings(ix.Backlinks[k])
}
}
// RefsOf lists every yetano: reference a solution or task contains.
func RefsOf(s *catalog.Solution) []string {
var out []string
out = append(out, s.Spec.References.All()...)
for _, q := range s.Spec.Questions {
out = append(out, q.References...)
for _, o := range q.Options {
out = append(out, o.References...)
}
}
for _, st := range s.Spec.Steps {
out = append(out, st.References...)
}
for _, c := range s.Spec.Requirements {
out = append(out, c.References...)
}
return out
}
// Backlinks of a reference (its target), sorted.
func (ix *Index) BacklinksOf(r string) []string {
p, err := ref.Parse(r)
if err != nil {
return nil
}
return ix.Backlinks[p.Target()]
}
+214
View File
@@ -0,0 +1,214 @@
package knowledge
import (
"fmt"
"sort"
"strings"
"yetano.dev/yetano/core/solutions/catalog"
"yetano.dev/yetano/core/solutions/ref"
)
// Lint checks what catalog.Validate cannot: every yetano: reference
// resolves (manual topics and sections included), and catalog-wide
// advice (QS-03). It returns catalog.Validate's issues plus its own.
func Lint(ix *Index) []catalog.Issue {
c := ix.Cat
issues := c.Validate()
check := func(e *catalog.Entity, owner, r string) {
res, err := ix.Resolve(r)
switch {
case err != nil:
issues = append(issues, catalog.Issue{Severity: "error", File: e.File, Line: e.Line, ID: owner, Code: "reference", Message: err.Error()})
case !res.Exists:
issues = append(issues, catalog.Issue{Severity: "error", File: e.File, Line: e.Line, ID: owner, Code: "reference", Message: fmt.Sprintf("%s does not resolve", r)})
case !res.SectionExists:
issues = append(issues, catalog.Issue{Severity: "error", File: e.File, Line: e.Line, ID: owner, Code: "reference-section", Message: fmt.Sprintf("%s: the manual has no such section (renamed heading?)", r)})
}
}
for _, m := range []map[string]*catalog.Solution{c.Solutions, c.Tasks} {
for _, id := range catalog.SortedIDs(m) {
s := m[id]
for _, r := range RefsOf(s) {
check(&s.Entity, id, r)
}
if s.Kind == catalog.KindSolution && len(c.Examples) > 0 {
has := false
for _, x := range c.Examples {
has = has || x.Spec.Solution == id
}
if !has {
issues = append(issues, catalog.Issue{Severity: "warning", File: s.File, ID: id, Code: "no-example", Message: "a solution should have at least one example (EX-01)"})
}
}
for _, q := range s.Spec.Questions {
if q.Type == "select" && q.Decide == "" && q.Level != catalog.LevelAdvanced && len(q.Options) > 2 {
issues = append(issues, catalog.Issue{Severity: "warning", File: s.File, ID: id + "." + q.ID, Code: "no-decide", Message: "a choice between several options should explain it (decide, HELP-01)"})
}
}
}
}
for _, id := range catalog.SortedIDs(c.Profiles) {
p := c.Profiles[id]
for _, r := range p.Spec.References {
check(&p.Entity, id, r)
}
}
for _, id := range ix.Missing {
issues = append(issues, catalog.Issue{Severity: "warning", ID: id, Code: "source-missing", Message: "documents not checked out under sourcesRoot; its references are not checked"})
}
return issues
}
// Coverage is the knowledge coverage report (COV-01), computed from data.
type Coverage struct {
Packages int `json:"packages"`
Metrics []Metric `json:"metrics"`
GoalsWithout []string `json:"goalsWithoutSolution"`
ProgramsWithout []string `json:"bigPictureProgramsWithoutPackage"`
ByPackage map[string]PackageCoverage `json:"byPackage"`
}
// Metric is one percentage.
type Metric struct {
Name string `json:"name"`
Have int `json:"have"`
Total int `json:"total"`
Pct float64 `json:"percent"`
}
// PackageCoverage is what exists for one package.
type PackageCoverage struct {
Manual bool `json:"manual"`
Microsite bool `json:"microsite"`
Provides int `json:"capabilities"`
Profiles int `json:"profiles"`
Solutions int `json:"solutions"`
Tasks int `json:"tasks"`
}
// ComputeCoverage builds the report.
func ComputeCoverage(ix *Index) Coverage {
c := ix.Cat
cov := Coverage{ByPackage: map[string]PackageCoverage{}}
for _, id := range catalog.SortedIDs(c.Packages) {
p := c.Packages[id]
pc := PackageCoverage{Microsite: p.Spec.Microsite != ""}
for _, m := range p.Spec.Modules {
pc.Provides += len(m.Provides)
}
for _, k := range c.Sources {
pc.Manual = pc.Manual || k.Spec.Package == id
}
for _, pr := range c.Profiles {
if pr.Meta.Package == id {
pc.Profiles++
}
}
for _, s := range c.Solutions {
for _, pu := range s.Spec.Packages {
if pu.ID == id {
pc.Solutions++
break
}
}
}
for _, s := range c.Tasks {
for _, pu := range s.Spec.Packages {
if pu.ID == id {
pc.Tasks++
break
}
}
}
cov.ByPackage[id] = pc
}
cov.Packages = len(c.Packages)
count := func(name string, f func(PackageCoverage) bool) {
m := Metric{Name: name, Total: len(cov.ByPackage)}
for _, pc := range cov.ByPackage {
if f(pc) {
m.Have++
}
}
cov.Metrics = append(cov.Metrics, pct(m))
}
count("Packages with a manual source", func(p PackageCoverage) bool { return p.Manual })
count("Packages with a microsite", func(p PackageCoverage) bool { return p.Microsite })
count("Packages with capabilities", func(p PackageCoverage) bool { return p.Provides > 0 })
count("Packages with profiles", func(p PackageCoverage) bool { return p.Profiles > 0 })
count("Packages used by a solution", func(p PackageCoverage) bool { return p.Solutions > 0 })
count("Packages with a task", func(p PackageCoverage) bool { return p.Tasks > 0 })
// references
refs, ok := 0, 0
for _, m := range []map[string]*catalog.Solution{c.Solutions, c.Tasks} {
for _, s := range m {
for _, r := range RefsOf(s) {
refs++
if res, err := ix.Resolve(r); err == nil && res.Exists && res.SectionExists {
ok++
}
}
}
}
cov.Metrics = append(cov.Metrics, pct(Metric{Name: "Valid references", Have: ok, Total: refs}))
tested := 0
for _, x := range c.Examples {
if x.Spec.Tested {
tested++
}
}
cov.Metrics = append(cov.Metrics, pct(Metric{Name: "Examples marked tested", Have: tested, Total: len(c.Examples)}))
// translations of solution titles
tr, total := 0, 0
for _, loc := range c.Spec.Locales {
if loc == "en" {
continue
}
for _, m := range []map[string]*catalog.Solution{c.Solutions, c.Tasks} {
for _, s := range m {
total++
if s.Meta.Translations[loc]["title"] != "" {
tr++
}
}
}
}
cov.Metrics = append(cov.Metrics, pct(Metric{Name: "Solution titles translated", Have: tr, Total: total}))
if bp := c.BigPicture; bp != nil {
used := map[string]bool{}
for _, s := range c.Solutions {
used[s.Spec.BigPicture] = true
}
goals := 0
for _, id := range catalog.SortedIDs(bp.Stories) {
if used[id] {
goals++
} else {
cov.GoalsWithout = append(cov.GoalsWithout, id)
}
}
cov.Metrics = append(cov.Metrics, pct(Metric{Name: "Big Picture goals with a solution", Have: goals, Total: len(bp.Stories)}))
pk := map[string]bool{}
for _, p := range c.Packages {
pk[p.Spec.BigPicture] = true
}
for _, id := range catalog.SortedIDs(bp.Products) {
if !pk[id] {
cov.ProgramsWithout = append(cov.ProgramsWithout, strings.TrimPrefix(id, "product."))
}
}
cov.Metrics = append(cov.Metrics, pct(Metric{Name: "Big Picture programs in the catalog", Have: len(bp.Products) - len(cov.ProgramsWithout), Total: len(bp.Products)}))
}
sort.SliceStable(cov.Metrics, func(i, j int) bool { return false })
return cov
}
func pct(m Metric) Metric {
if m.Total > 0 {
m.Pct = float64(int(float64(m.Have)*1000/float64(m.Total)+0.5)) / 10
}
return m
}
var _ = ref.Solution
+193
View File
@@ -0,0 +1,193 @@
package knowledge
import (
"fmt"
"net/url"
"strings"
"yetano.dev/yetano/core/solutions/ref"
)
// Resolution says what a reference points at and how each client opens
// it (REF-02). Exists is false for targets the index does not know.
type Resolution struct {
Ref string `json:"ref"`
Kind string `json:"kind"`
Title string `json:"title,omitempty"`
Summary string `json:"summary,omitempty"`
Exists bool `json:"exists"`
// SectionExists is false when the ref names a section that is not there.
SectionExists bool `json:"sectionExists"`
Web string `json:"web,omitempty"` // URL on yetano.app (only for pages that exist)
CLI string `json:"cli,omitempty"` // command that shows it in a terminal
File string `json:"file,omitempty"` // local Markdown file (manuals)
Line int `json:"line,omitempty"`
View string `json:"view"` // how a UI shows it: wizard | reader | graph | package | code | list
Note string `json:"note,omitempty"`
}
// Resolve resolves a reference against the index.
func (ix *Index) Resolve(s string) (Resolution, error) {
r, err := ref.Parse(s)
if err != nil {
return Resolution{}, err
}
res := Resolution{Ref: s, Kind: r.Kind, SectionExists: r.Section == ""}
web := strings.TrimRight(ix.Cat.Spec.WebBase, "/") + "/"
if e := ix.byRef[r.Target()]; e != nil {
res.Exists, res.Title, res.Summary = true, e.Title, e.Summary
}
switch r.Kind {
case ref.Solution, ref.Task:
res.View = "wizard"
cmd := "solution"
if r.Kind == ref.Task {
cmd = "task"
}
res.CLI = fmt.Sprintf("yet %s show %s", cmd, r.Path[0])
case ref.Package:
res.View = "package"
res.CLI = "yet solution package " + r.Path[0]
if p := ix.Cat.Packages[r.Path[0]]; p != nil && p.Spec.Microsite != "" {
res.Web = web + p.Spec.Microsite
}
case ref.Module:
res.View = "package"
res.CLI = "yet solution package " + r.Path[0]
case ref.Microsite:
res.View = "package"
if p := ix.Cat.Packages[r.Path[0]]; p != nil && p.Spec.Microsite != "" {
res.Web = web + p.Spec.Microsite
res.Exists = true
}
case ref.Capability:
res.View = "list"
res.CLI = "yet knowledge show " + s
case ref.Profile, ref.Example:
res.View = "code"
res.CLI = "yet knowledge show " + s
case ref.BigPicture:
res.View = "graph"
if bp := ix.Cat.BigPicture; bp != nil && bp.Has(r.Path[0]) {
res.Exists = true
res.Web = web + bp.WebPath + "#" + bp.Fragment(r.Path[0])
}
case ref.Manual:
res.View = "reader"
source := r.Path[0]
slug := strings.Join(r.Path[1:], ".")
k := ix.Cat.Sources[source]
if k == nil {
res.Note = "unknown knowledge source " + source
break
}
realSlug := strings.ReplaceAll(slug, ".", "/")
if k.Spec.Program != "" {
res.CLI = fmt.Sprintf("%s manual %s", k.Spec.Program, realSlug)
} else {
res.CLI = "yet knowledge show " + s
}
if k.Spec.Web != "" {
res.Web = k.Spec.Web
}
t := ix.Topics[source+"/"+slug]
if t == nil {
if ix.missing(source) {
res.Note = "the documents of " + source + " are not available locally; the reference is not checked"
res.Exists = true // cannot tell; do not report as broken
}
break
}
res.Exists, res.Title, res.File = true, t.Title, t.File
if r.Section != "" {
for _, sec := range t.Sections {
if sec.ID == r.Section {
res.SectionExists, res.Title, res.Line = true, t.Title+" › "+sec.Title, sec.Start
}
}
}
}
if res.Web != "" {
if _, err := url.Parse(res.Web); err != nil {
res.Web = ""
}
}
return res, nil
}
func (ix *Index) missing(source string) bool {
for _, m := range ix.Missing {
if m == source {
return true
}
}
return false
}
// Read returns the Markdown of a manual reference: the whole topic, or
// just the section (with its subsections).
func (ix *Index) Read(s string) (title, markdown string, err error) {
r, err := ref.Parse(s)
if err != nil {
return "", "", err
}
if r.Kind != ref.Manual {
return "", "", fmt.Errorf("%s is not a manual reference", s)
}
t := ix.Topics[r.Path[0]+"/"+strings.Join(r.Path[1:], ".")]
if t == nil {
return "", "", fmt.Errorf("manual %s is not available locally", s)
}
if r.Section == "" {
return t.Title, strings.Join(t.lines, "\n") + "\n", nil
}
for i, sec := range t.Sections {
if sec.ID != r.Section {
continue
}
end := len(t.lines)
for _, next := range t.Sections[i+1:] {
if next.Level <= sec.Level {
end = next.Start - 1
break
}
}
return sec.Title, strings.Join(t.lines[sec.Start-1:end], "\n") + "\n", nil
}
return "", "", fmt.Errorf("%s: no section %q", s, r.Section)
}
// Excerpt implements engine.ManualReader.
func (ix *Index) Excerpt(s string, maxLines int) (string, string, bool) {
title, md, err := ix.Read(s)
if err != nil {
return "", "", false
}
lines := strings.Split(strings.TrimRight(md, "\n"), "\n")
if len(lines) > 0 && strings.HasPrefix(lines[0], "#") {
lines = lines[1:]
}
for len(lines) > 0 && strings.TrimSpace(lines[0]) == "" {
lines = lines[1:]
}
if len(lines) > maxLines {
lines = append(lines[:maxLines], "…")
}
return title, strings.Join(lines, "\n"), true
}
// Link implements engine.ManualReader: a web URL, else the CLI command.
func (ix *Index) Link(s string) string {
res, err := ix.Resolve(s)
if err != nil {
return "`" + s + "`"
}
label := firstNonEmpty(res.Title, s)
switch {
case res.Web != "" && res.Kind != ref.Manual:
return fmt.Sprintf("[%s](%s)", label, res.Web)
case res.CLI != "":
return fmt.Sprintf("%s (`%s`)", label, res.CLI)
}
return "`" + s + "`"
}
+180
View File
@@ -0,0 +1,180 @@
package knowledge
import (
"sort"
"strings"
"unicode"
"yetano.dev/yetano/core/solutions/ref"
)
// Hit is one search result.
type Hit struct {
Ref string `json:"ref"`
Kind string `json:"kind"`
Title string `json:"title"`
Summary string `json:"summary,omitempty"`
Score float64 `json:"score"`
Status string `json:"status,omitempty"`
}
// Group collects the hits of one kind (SEARCH-01).
type Group struct {
Kind string `json:"kind"`
Title string `json:"title"`
Hits []Hit `json:"hits"`
}
// SearchOptions narrow a search.
type SearchOptions struct {
Kinds []string // only these kinds (solution, task, package, manual, ...)
Limit int // per group; 0 = 10
Locale string
Package string
}
// Group order: use cases first (SEARCH-04).
var groupOrder = []struct{ kind, title string }{
{ref.Solution, "Solutions"}, {ref.Task, "Tasks"}, {ref.Example, "Examples"},
{ref.Package, "Packages"}, {ref.Module, "Modules"}, {ref.Capability, "Capabilities"},
{ref.Manual, "Manuals"}, {"section", "Manual sections"}, {ref.Microsite, "Microsites"},
{ref.BigPicture, "Big Picture"}, {ref.Profile, "Profiles"},
}
var stop = map[string]bool{"i": true, "a": true, "an": true, "the": true, "to": true, "want": true, "my": true, "own": true,
"with": true, "for": true, "of": true, "and": true, "run": false, "ich": true, "will": true, "einen": true, "ein": true, "mit": true, "möchte": true}
// Tokens splits text into lower-case search words.
func Tokens(s string) []string {
f := strings.FieldsFunc(strings.ToLower(s), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) && r != '.' })
var out []string
for _, w := range f {
w = strings.Trim(w, ".")
if w != "" && !stop[w] {
out = append(out, w)
}
}
return out
}
// Search runs a deterministic full-text search over the index: titles,
// IDs, tags and synonyms weigh most, then summaries, then body text.
// No embeddings and no network (SEARCH-05).
func (ix *Index) Search(q string, opt SearchOptions) []Group {
words := Tokens(q)
if len(words) == 0 {
return nil
}
limit := opt.Limit
if limit <= 0 {
limit = 10
}
allowed := map[string]bool{}
for _, k := range opt.Kinds {
allowed[k] = true
}
byKind := map[string][]Hit{}
for _, e := range ix.Entries {
if len(allowed) > 0 && !allowed[e.Kind] {
continue
}
if opt.Package != "" && e.Package != opt.Package {
continue
}
title := e.Title
summary := e.Summary
if opt.Locale != "" && e.Translations != nil {
if m, ok := e.Translations[opt.Locale]; ok {
title = firstNonEmpty(m["title"], title)
summary = firstNonEmpty(m["summary"], summary)
}
}
fields := []struct {
text string
weight float64
}{
{title + " " + e.Title, 6}, {e.Ref, 4}, {strings.Join(e.Tags, " ") + " " + strings.Join(e.Synonyms, " "), 5},
{strings.Join(e.Capabilities, " ") + " " + e.Package, 3}, {summary + " " + e.Summary, 2}, {e.Body, 0.5},
}
score := 0.0
matched := 0
phrase := strings.ToLower(strings.Join(words, " "))
for _, w := range words {
best := 0.0
for _, f := range fields {
lt := strings.ToLower(f.text)
if strings.Contains(lt, w) {
s := f.weight
if hasWord(lt, w) {
s *= 1.5
}
if s > best {
best = s
}
}
}
if best > 0 {
matched++
}
score += best
}
if matched == 0 {
continue
}
score *= float64(matched) / float64(len(words))
if strings.Contains(strings.ToLower(title+" "+strings.Join(e.Synonyms, " ")), phrase) && len(words) > 1 {
score += 5
}
switch e.Kind {
case ref.Solution, ref.Task:
score *= 1.5
case "section":
score *= 0.6
}
byKind[e.Kind] = append(byKind[e.Kind], Hit{Ref: e.Ref, Kind: e.Kind, Title: title, Summary: summary, Score: round(score), Status: e.Status})
}
var out []Group
for _, g := range groupOrder {
hits := byKind[g.kind]
if len(hits) == 0 {
continue
}
sort.SliceStable(hits, func(i, j int) bool {
if hits[i].Score != hits[j].Score {
return hits[i].Score > hits[j].Score
}
return hits[i].Ref < hits[j].Ref
})
if len(hits) > limit {
hits = hits[:limit]
}
out = append(out, Group{Kind: g.kind, Title: g.title, Hits: hits})
}
// groups with the best hit first, but solutions and tasks keep the lead
sort.SliceStable(out, func(i, j int) bool {
pi, pj := lead(out[i].Kind), lead(out[j].Kind)
if pi != pj {
return pi > pj
}
return out[i].Hits[0].Score > out[j].Hits[0].Score
})
return out
}
func lead(kind string) int {
if kind == ref.Solution || kind == ref.Task {
return 1
}
return 0
}
func hasWord(text, w string) bool {
for _, t := range Tokens(text) {
if t == w {
return true
}
}
return false
}
func round(f float64) float64 { return float64(int(f*100+0.5)) / 100 }
+155
View File
@@ -0,0 +1,155 @@
// Package ref parses and formats yetano: references (ADR-0004):
//
// yetano:<kind>/<path>[#<section>][@<version>]
//
// It only knows the syntax; resolving a reference against a catalog and
// rendering it for a client lives in package knowledge.
package ref
import (
"errors"
"fmt"
"regexp"
"strings"
)
// Kinds of references.
const (
Package = "package"
Module = "module"
Manual = "manual"
Microsite = "microsite"
Solution = "solution"
Task = "task"
Profile = "profile"
Capability = "capability"
Example = "example"
BigPicture = "bigpicture"
)
// Kinds lists the valid kinds and how many path segments each takes.
var Kinds = map[string]int{
Package: 1, Module: 2, Manual: -2, Microsite: 1, Solution: 1, Task: 1,
Profile: 2, Capability: 1, Example: 2, BigPicture: 1,
}
// Ref is a parsed reference.
type Ref struct {
Kind string `json:"kind"`
Path []string `json:"path"`
Section string `json:"section,omitempty"`
Version string `json:"version,omitempty"`
}
// ErrSyntax is returned for malformed references.
var ErrSyntax = errors.New("invalid yetano reference")
var segRE = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
// MaxLen bounds a reference (SEC-03).
const MaxLen = 512
// Parse parses s.
func Parse(s string) (Ref, error) {
if len(s) > MaxLen {
return Ref{}, fmt.Errorf("%w: longer than %d bytes", ErrSyntax, MaxLen)
}
rest, ok := strings.CutPrefix(s, "yetano:")
if !ok {
return Ref{}, fmt.Errorf("%w %q: must start with yetano:", ErrSyntax, s)
}
var r Ref
if i := strings.LastIndex(rest, "@"); i >= 0 {
r.Version, rest = rest[i+1:], rest[:i]
if r.Version == "" {
return Ref{}, fmt.Errorf("%w %q: empty version", ErrSyntax, s)
}
}
if i := strings.Index(rest, "#"); i >= 0 {
r.Section, rest = rest[i+1:], rest[:i]
if !segRE.MatchString(r.Section) {
return Ref{}, fmt.Errorf("%w %q: bad section", ErrSyntax, s)
}
}
parts := strings.Split(rest, "/")
r.Kind = parts[0]
r.Path = parts[1:]
want, ok := Kinds[r.Kind]
if !ok {
return Ref{}, fmt.Errorf("%w %q: unknown kind %q", ErrSyntax, s, r.Kind)
}
switch {
case want > 0 && len(r.Path) != want:
return Ref{}, fmt.Errorf("%w %q: %s takes %d path segment(s)", ErrSyntax, s, r.Kind, want)
case want < 0 && (len(r.Path) < 2):
return Ref{}, fmt.Errorf("%w %q: %s takes <package>/<topic>", ErrSyntax, s, r.Kind)
}
for _, p := range r.Path {
if !segRE.MatchString(p) {
return Ref{}, fmt.Errorf("%w %q: bad path segment %q", ErrSyntax, s, p)
}
}
return r, nil
}
// MustParse is Parse for constants in tests.
func MustParse(s string) Ref {
r, err := Parse(s)
if err != nil {
panic(err)
}
return r
}
// String formats r.
func (r Ref) String() string {
var b strings.Builder
b.WriteString("yetano:")
b.WriteString(r.Kind)
for _, p := range r.Path {
b.WriteByte('/')
b.WriteString(p)
}
if r.Section != "" {
b.WriteByte('#')
b.WriteString(r.Section)
}
if r.Version != "" {
b.WriteByte('@')
b.WriteString(r.Version)
}
return b.String()
}
// Target is the reference without section and version (what Backlinks index).
func (r Ref) Target() string {
r.Section, r.Version = "", ""
return r.String()
}
// For builds a reference.
func For(kind string, path ...string) string {
return Ref{Kind: kind, Path: path}.String()
}
var translit = strings.NewReplacer("ä", "ae", "ö", "oe", "ü", "ue", "ß", "ss", "é", "e", "è", "e", "à", "a", "ç", "c")
// Slug turns a heading into a section ID: lower case ASCII letters and
// digits; every run of anything else becomes one "-", trimmed.
func Slug(heading string) string {
var b strings.Builder
dash := false
heading = translit.Replace(strings.ToLower(heading))
for _, r := range heading {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
b.WriteRune(r)
dash = false
continue
}
if !dash && b.Len() > 0 {
b.WriteByte('-')
dash = true
}
}
return strings.TrimRight(b.String(), "-")
}
+38
View File
@@ -0,0 +1,38 @@
package ref
import "testing"
func TestParse(t *testing.T) {
for _, s := range []string{
"yetano:package/yamase", "yetano:module/yamase/smtpd", "yetano:manual/yamase/mail-domain#dkim",
"yetano:manual/yamase-ctl/backup", "yetano:solution/mail-server@1.0.0", "yetano:task/mail.add-domain",
"yetano:capability/mail.smtp.inbound", "yetano:bigpicture/story.mail-groupware", "yetano:example/mail-server/personal",
} {
r, err := Parse(s)
if err != nil {
t.Errorf("%s: %v", s, err)
continue
}
if r.String() != s {
t.Errorf("round trip %s -> %s", s, r.String())
}
}
for _, bad := range []string{"package/yamase", "yetano:", "yetano:nope/x", "yetano:package", "yetano:package/a/b",
"yetano:module/x", "yetano:package/../x", "yetano:manual/x", "yetano:package/x#", "yetano:package/x@"} {
if _, err := Parse(bad); err == nil {
t.Errorf("%q accepted", bad)
}
}
}
func TestSlug(t *testing.T) {
for in, want := range map[string]string{
"Schritt 2: Schlüssel erzeugen": "schritt-2-schluessel-erzeugen",
"4. Trusted relays, SRS bounces and ereject": "4-trusted-relays-srs-bounces-and-ereject",
" Hello World! ": "hello-world",
} {
if got := Slug(in); got != want {
t.Errorf("%q: %q, want %q", in, got, want)
}
}
}
+261
View File
@@ -0,0 +1,261 @@
// Package store keeps a user's solution instances, wizard sessions,
// presets, favorites and recently used items as plain files in one
// directory (the embedding program's data directory, from core/paths):
//
// <dir>/instances/<name>.yaml SolutionInstance
// <dir>/sessions/<name>.yaml WizardSession (drafts)
// <dir>/presets/<name>.yaml Preset
// <dir>/state.json favorites and recent
//
// Nothing is created until something is saved (core rule: no silent
// filesystem mutation).
package store
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"yetano.dev/yetano/core/solutions/engine"
)
// Store is a directory.
type Store struct{ Dir string }
// ErrNotFound for unknown names.
var ErrNotFound = errors.New("not found")
var nameRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$`)
// ValidName reports whether name can be a file name in the store.
func ValidName(name string) error {
if !nameRE.MatchString(name) || strings.Contains(name, "..") {
return fmt.Errorf("name %q: letters, digits, '.', '_' and '-', at most 80", name)
}
return nil
}
func (s Store) path(kind, name string) (string, error) {
if err := ValidName(name); err != nil {
return "", err
}
return filepath.Join(s.Dir, kind, name+".yaml"), nil
}
func (s Store) write(kind, name string, v any) error {
p, err := s.path(kind, name)
if err != nil {
return err
}
b, err := engine.Marshal(v)
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
return err
}
tmp := p + ".tmp"
if err := os.WriteFile(tmp, b, 0o600); err != nil {
return err
}
return os.Rename(tmp, p)
}
func (s Store) list(kind string) ([]string, error) {
ents, err := os.ReadDir(filepath.Join(s.Dir, kind))
if errors.Is(err, os.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var out []string
for _, e := range ents {
if n, ok := strings.CutSuffix(e.Name(), ".yaml"); ok && !e.IsDir() {
out = append(out, n)
}
}
sort.Strings(out)
return out, nil
}
func (s Store) remove(kind, name string) error {
p, err := s.path(kind, name)
if err != nil {
return err
}
if err := os.Remove(p); errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("%w: %s %s", ErrNotFound, strings.TrimSuffix(kind, "s"), name)
} else {
return err
}
}
// SaveInstance stores an instance (kind SolutionInstance) or a session
// (kind WizardSession) under its metadata name.
func (s Store) SaveInstance(in *engine.Instance) error {
now := time.Now().UTC().Format(time.RFC3339)
if in.Metadata.Created == "" {
in.Metadata.Created = now
}
in.Metadata.Updated = now
kind := "instances"
if in.Kind == "WizardSession" {
kind = "sessions"
}
return s.write(kind, in.Metadata.Name, in)
}
// LoadInstance reads an instance, else a session, by name.
func (s Store) LoadInstance(name string) (*engine.Instance, error) {
for _, kind := range []string{"instances", "sessions"} {
p, err := s.path(kind, name)
if err != nil {
return nil, err
}
f, err := os.Open(p)
if errors.Is(err, os.ErrNotExist) {
continue
}
if err != nil {
return nil, err
}
defer f.Close()
in, err := engine.ReadInstance(f)
if err != nil {
return nil, fmt.Errorf("%s: %w", p, err)
}
return in, nil
}
return nil, fmt.Errorf("%w: instance %s", ErrNotFound, name)
}
// Instances lists saved instances; Sessions lists drafts.
func (s Store) Instances() ([]string, error) { return s.list("instances") }
// Sessions lists drafts.
func (s Store) Sessions() ([]string, error) { return s.list("sessions") }
// DeleteInstance removes an instance (or session).
func (s Store) DeleteInstance(name string) error {
if err := s.remove("instances", name); err == nil || !errors.Is(err, ErrNotFound) {
return err
}
return s.remove("sessions", name)
}
// DeleteSession removes a draft only.
func (s Store) DeleteSession(name string) error { return s.remove("sessions", name) }
// SavePreset stores a preset.
func (s Store) SavePreset(p *engine.Preset) error { return s.write("presets", p.Metadata.Name, p) }
// LoadPreset reads a preset.
func (s Store) LoadPreset(name string) (*engine.Preset, error) {
p, err := s.path("presets", name)
if err != nil {
return nil, err
}
f, err := os.Open(p)
if errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("%w: preset %s", ErrNotFound, name)
}
if err != nil {
return nil, err
}
defer f.Close()
return engine.ReadPreset(f)
}
// Presets lists presets.
func (s Store) Presets() ([]string, error) { return s.list("presets") }
// DeletePreset removes a preset.
func (s Store) DeletePreset(name string) error { return s.remove("presets", name) }
// State holds favorites and recently used references (QA-01).
type State struct {
Favorites []string `json:"favorites"`
Recent []Recent `json:"recent"`
}
// Recent is one recently used item.
type Recent struct {
Ref string `json:"ref"`
Name string `json:"name,omitempty"` // instance, if any
At string `json:"at"`
}
// MaxRecent bounds the recent list.
const MaxRecent = 30
// LoadState reads state.json (empty when missing).
func (s Store) LoadState() (State, error) {
var st State
b, err := os.ReadFile(filepath.Join(s.Dir, "state.json"))
if errors.Is(err, os.ErrNotExist) {
return st, nil
}
if err != nil {
return st, err
}
err = json.Unmarshal(b, &st)
return st, err
}
func (s Store) saveState(st State) error {
b, _ := json.MarshalIndent(st, "", " ")
if err := os.MkdirAll(s.Dir, 0o700); err != nil {
return err
}
tmp := filepath.Join(s.Dir, "state.json.tmp")
if err := os.WriteFile(tmp, b, 0o600); err != nil {
return err
}
return os.Rename(tmp, filepath.Join(s.Dir, "state.json"))
}
// Touch records a use of ref (most recent first, no duplicates).
func (s Store) Touch(ref, name string) error {
st, err := s.LoadState()
if err != nil {
return err
}
out := []Recent{{Ref: ref, Name: name, At: time.Now().UTC().Format(time.RFC3339)}}
for _, r := range st.Recent {
if r.Ref != ref || r.Name != name {
out = append(out, r)
}
}
if len(out) > MaxRecent {
out = out[:MaxRecent]
}
st.Recent = out
return s.saveState(st)
}
// SetFavorite adds or removes a favorite.
func (s Store) SetFavorite(ref string, on bool) error {
st, err := s.LoadState()
if err != nil {
return err
}
var out []string
for _, f := range st.Favorites {
if f != ref {
out = append(out, f)
}
}
if on {
out = append(out, ref)
}
sort.Strings(out)
st.Favorites = out
return s.saveState(st)
}
+42
View File
@@ -0,0 +1,42 @@
package store
import (
"errors"
"testing"
"yetano.dev/yetano/core/solutions/engine"
)
func TestStore(t *testing.T) {
s := Store{Dir: t.TempDir()}
if names, err := s.Instances(); err != nil || len(names) != 0 {
t.Fatal("empty store")
}
in := &engine.Instance{APIVersion: "yetano.dev/v1", Kind: "SolutionInstance", Metadata: engine.InstanceMeta{Name: "a"},
Spec: engine.InstanceSpec{Solution: engine.SolutionPin{ID: "x"}, Parameters: map[string]any{"k": "v"}}}
if err := s.SaveInstance(in); err != nil {
t.Fatal(err)
}
got, err := s.LoadInstance("a")
if err != nil || got.Spec.Parameters["k"] != "v" || got.Metadata.Created == "" {
t.Fatalf("%v %+v", err, got)
}
if _, err := s.LoadInstance("../a"); err == nil {
t.Error("path traversal accepted")
}
if _, err := s.LoadInstance("nope"); !errors.Is(err, ErrNotFound) {
t.Error(err)
}
if err := s.Touch("yetano:solution/x", "a"); err != nil {
t.Fatal(err)
}
s.Touch("yetano:solution/y", "")
s.Touch("yetano:solution/x", "a")
st, _ := s.LoadState()
if len(st.Recent) != 2 || st.Recent[0].Ref != "yetano:solution/x" {
t.Errorf("recent: %+v", st.Recent)
}
if err := s.DeleteInstance("a"); err != nil {
t.Fatal(err)
}
}
+77
View File
@@ -0,0 +1,77 @@
# yetano.dev/yetano/core/trust
The family's minisign (Ed25519) signatures: verifying, shared by every
program that pulls signed content -- yet (packages) and yacota (images)
check against the same files, so a host makes one trust decision -- and
signing, shared by every program that signs: yet (packages,
attestations) and yabar (evidence records, ADR-0037 there).
```text
module yetano.dev/yetano/core/trust tags: trust/v0.1.0, trust/v0.2.0, ... go 1.25
```
A nested module of the core repository, like `core/tui`, so the main core
module stays free of minisign. Depends on `aead.dev/minisign` (MIT) and
core (`core/paths`, for `Home`; `core/secretref`, for `KeyFromRef`).
Moved from `yet/internal/trust` without changing behavior or file
formats: the verifying half on 2026-11-12 (trust/v0.1.0), the signing
half on 2026-11-27 (trust/v0.2.0). Pushing signatures to a registry and
where auto-sign keeps its keys stay in yet.
## What it is
- **Signatures:** minisign (Ed25519) over the resolved OCI manifest
digest, as the JSON payload (`Signature`, media and artifact type
`application/vnd.yetano.signature.v1+json`) of an OCI 1.1 referrer
on that digest. `Verify(subjectDigest, payloads)` checks fetched
referrers (the caller fetches them with its own registry client);
valid signatures whose key IDs collide are made invalid.
- **Known keys** (`known-keys.json`, TOFU like SSH's known_hosts):
`Reconcile` pins a repository's first valid signer and refuses later
content signed only by other keys (an error that `errors.Is`
`ErrRefused`). A key is compared as the key (`SameKey`), never by its
ID alone.
- **Trust policy** (`trust-policy.json`, edited with `yet trust
policy`): rules per namespace pattern naming allowed keys,
`require_signatures`; `Evaluate`, `AllowsCapability`, `Curated`.
- **Where:** `Home(scope)` is yet's data directory (core/paths' DataDir
for "yet"), `DefaultPolicyPath(home)`, `DefaultKnownKeysPath(home)`.
- **Keys:** `KeyPair`, `GenerateKey`, `SaveKeyPair(path, kp, password)`
(private key owner-only, `<path>.pub` beside it; the minisign CLI's
formats, scrypt-encrypted with a password), `LoadPrivateKey`,
`ParsePrivateKey`, `LoadPublicKey`, `MarshalPublicKey`, and
`KeyFromRef(ctx, resolver, keyRef, passwordRef)` for a key held as a
secret reference (`secret://...` in yaseva, `env:`, `file:`).
- **Signing:** `SignDigest(kp, digest)` makes the package signature
`VerifySignature` checks; `Sign(kp, message, trustedComment,
untrustedComment)` makes a detached `.minisig` over any bytes, and
`VerifyMessage(pub, message, sig)` checks it and returns the trusted
comment (`minisign -Vm` checks it too); `SignEd25519`/`VerifyEd25519`
are plain Ed25519 for DSSE envelopes; `ExportPEM`/`ImportPEM` for
cosign and openssl.
- **Vector:** `testdata/sign-vector.*` -- a published test key, a
message and its signature; every version must produce and accept it.
## Use
```go
home, _ := trust.Home(core.UserScope)
verified := trust.Verify(manifestDigest, payloads) // fetched referrers
if err := trust.Reconcile(trust.DefaultKnownKeysPath(home), "registry/repo", verified); err != nil {
return err // errors.Is(err, trust.ErrRefused): the pinned key changed
}
policy, _ := trust.LoadPolicy(trust.DefaultPolicyPath(home))
if d := policy.Evaluate(name, kind, verified); !d.Trusted { ... }
```
Signing:
```go
kp, err := trust.KeyFromRef(ctx, secretref.New(""), "secret://yabar/evidence/minisign", "")
sig, err := trust.Sign(kp, recordBytes, "yabar evidence <test_id> <repository_id>", "")
comment, err := trust.VerifyMessage(pub, recordBytes, sig)
```
`Warn` (a variable) reports warnings that are not errors, on standard
error by default.
+13
View File
@@ -0,0 +1,13 @@
module yetano.dev/yetano/core/trust
go 1.26.0
require (
aead.dev/minisign v0.3.0
yetano.dev/yetano/core v0.11.0
)
require (
golang.org/x/crypto v0.58.0 // indirect
golang.org/x/sys v0.49.0 // indirect
)
+12
View File
@@ -0,0 +1,12 @@
aead.dev/minisign v0.3.0 h1:8Xafzy5PEVZqYDNP60yJHARlW1eOQtsKNp/Ph2c0vRA=
aead.dev/minisign v0.3.0/go.mod h1:NLvG3Uoq3skkRMDuc3YHpWUTMTrSExqm+Ij73W13F6Y=
golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
yetano.dev/yetano/core v0.11.0 h1:0i16HJ1lc26OUBSudepZORs+SjtmLT6bmXvEfazsaQg=
yetano.dev/yetano/core v0.11.0/go.mod h1:T2TdFvZiHbYVgcRmRXk9NC82AYL8krGVxxtLyedWuJE=
+37
View File
@@ -0,0 +1,37 @@
package trust
import (
"yetano.dev/yetano/core"
"yetano.dev/yetano/core/paths"
)
// Home is the directory of a host's trust state: yet's data directory
// (core/paths' DataDir for "yet" in scope), which holds
// trust-policy.json (DefaultPolicyPath) and known-keys.json
// (DefaultKnownKeysPath). Every program that checks signatures reads
// these, so a host has one trust policy and one set of pinned keys,
// whichever program pulled first.
func Home(scope core.Scope) (string, error) {
r, err := paths.New(core.Application{Name: "yet", Kind: core.CLI, Scope: scope})
if err != nil {
return "", err
}
return r.DataDir()
}
// Curated reports whether a rule of p covers the namespace of name (any
// type): only its allowed keys satisfy such a namespace (Evaluate).
func (p Policy) Curated(name string) bool {
for _, rule := range p.Rules {
if matchesNamespace(rule.Namespace, name) {
return true
}
}
return false
}
// Pinned reports whether keys accept a key for repoKey: its content has
// been seen signed (Reconcile), or a key was added for it.
func (keys KnownKeys) Pinned(repoKey string) bool {
return len(keys[repoKey]) > 0
}
+191
View File
@@ -0,0 +1,191 @@
package trust
// The signing half of publisher signatures, moved from yet's
// internal/trust (2026-11-27, YABAR-036a) without changing behavior or
// file formats: key pairs in minisign's own file formats, the package
// signature over an OCI digest (SignDigest), detached signatures over
// any bytes (Sign, VerifyMessage), plain Ed25519 for DSSE envelopes,
// and PEM for cosign and openssl. Where keys are kept for auto-signing
// and pushing signatures to a registry stay in yet.
import (
"bytes"
"crypto"
"crypto/ed25519"
"crypto/sha512"
"fmt"
"os"
"path/filepath"
"aead.dev/minisign"
)
// KeyPair is a minisign key pair. The private key never leaves the host's
// filesystem; only the public key is shared with other hosts (as a plain
// ".pub" file) and embedded in signatures.
type KeyPair struct {
Public minisign.PublicKey
Private minisign.PrivateKey
}
// GenerateKey creates a new minisign key pair.
func GenerateKey() (KeyPair, error) {
pub, priv, err := minisign.GenerateKey(nil)
if err != nil {
return KeyPair{}, err
}
return KeyPair{Public: pub, Private: priv}, nil
}
// SaveKeyPair writes kp's private key to path (owner-only permissions) and
// its public key to path+".pub" (world-readable: it is meant to be shared).
// This mirrors the real minisign CLI's `-p file.pub -s file` convention, so
// `trust policy allow` only ever needs the ".pub" file, never the private
// key -- a relying party registering a publisher's trust never needs (and
// should never be handed) their private key.
//
// If password is non-empty, the private key is scrypt-encrypted exactly as
// `minisign -G` with a passphrase would; if empty, it is written
// unencrypted, matching the minisign CLI's own behavior when a blank
// passphrase is given. Either way the file is only ever readable by its
// owner; a password additionally protects it if the file itself leaks.
func SaveKeyPair(path string, kp KeyPair, password string) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
var privData []byte
var err error
if password != "" {
privData, err = minisign.EncryptKey(password, kp.Private)
} else {
privData, err = kp.Private.MarshalText()
}
if err != nil {
return fmt.Errorf("encode private key: %w", err)
}
if err := writeOwnerOnly(path, privData); err != nil {
return err
}
pubData, err := MarshalPublicKey(kp.Public)
if err != nil {
return fmt.Errorf("encode public key: %w", err)
}
return writeFile(path+".pub", pubData, 0o644)
}
// LoadPrivateKey reads a key pair previously written by SaveKeyPair,
// decrypting it with password if it is encrypted (password is ignored, and
// may be empty, for an unencrypted key).
func LoadPrivateKey(path, password string) (KeyPair, error) {
data, err := os.ReadFile(path)
if err != nil {
return KeyPair{}, err
}
return ParsePrivateKey(data, password)
}
// ParsePrivateKey parses a minisign private key file's contents, the
// same bytes LoadPrivateKey reads from disk, so a key can also come from
// somewhere other than a file (a yaseva secret, see KeyStore).
func ParsePrivateKey(data []byte, password string) (KeyPair, error) {
var err error
var priv minisign.PrivateKey
if minisign.IsEncrypted(data) {
priv, err = minisign.DecryptKey(password, data)
if err != nil {
return KeyPair{}, fmt.Errorf("decrypt private key (wrong password?): %w", err)
}
} else if err := priv.UnmarshalText(data); err != nil {
return KeyPair{}, fmt.Errorf("parse private key: %w", err)
}
pub, ok := priv.Public().(minisign.PublicKey)
if !ok {
return KeyPair{}, fmt.Errorf("derive public key: unexpected type %T", priv.Public())
}
return KeyPair{Public: pub, Private: priv}, nil
}
// LoadPublicKey reads a standalone ".pub" file, for a trust policy that
// must never require (or accept) private key material.
func LoadPublicKey(path string) (minisign.PublicKey, error) {
return minisign.PublicKeyFromFile(path)
}
// MarshalPublicKey encodes pub as a minisign ".pub" file. It is
// aead.dev/minisign's own encoding, except that the comment line carries
// the 16-digit key ID (the library writes it without leading zeros).
func MarshalPublicKey(pub minisign.PublicKey) ([]byte, error) {
data, err := pub.MarshalText()
if err != nil {
return nil, err
}
_, rest, ok := bytes.Cut(data, []byte("\n"))
if !ok {
return data, nil
}
out := fmt.Appendf(nil, "untrusted comment: minisign public key: %s\n", ID(pub))
out = append(out, rest...)
if !bytes.HasSuffix(out, []byte("\n")) {
out = append(out, '\n')
}
return out, nil
}
func writeOwnerOnly(path string, data []byte) error {
return writeFile(path, data, 0o600)
}
func writeFile(path string, data []byte, mode os.FileMode) error {
tmp, err := os.CreateTemp(filepath.Dir(path), ".key-*")
if err != nil {
return err
}
defer func() { _ = os.Remove(tmp.Name()) }()
if err := os.Chmod(tmp.Name(), mode); err != nil {
_ = tmp.Close()
return err
}
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), path)
}
// SignEd25519 signs message with kp as a plain Ed25519 signature
// (minisign's non-prehashed "Ed" algorithm): the raw 64 bytes DSSE
// envelopes carry and cosign and other Ed25519 verifiers check against
// ExportPEM's key. Package signatures (Sign) keep using minisign's own
// format.
func SignEd25519(kp KeyPair, message []byte) ([]byte, error) {
text, err := kp.Private.Sign(nil, message, crypto.Hash(0))
if err != nil {
return nil, err
}
var sig minisign.Signature
if err := sig.UnmarshalText(text); err != nil {
return nil, err
}
if sig.Algorithm != minisign.EdDSA {
return nil, fmt.Errorf("unexpected minisign algorithm %d", sig.Algorithm)
}
return sig.Signature[:], nil
}
// VerifyEd25519 checks an Ed25519 signature over message against pub:
// plain Ed25519 (what SignEd25519 makes) or Ed25519ph with SHA-512
// (what cosign makes with an Ed25519 key).
func VerifyEd25519(pub minisign.PublicKey, message, sig []byte) bool {
raw := Ed25519Key(pub)
if raw == nil || len(sig) != ed25519.SignatureSize {
return false
}
if ed25519.Verify(raw, message, sig) {
return true
}
digest := sha512.Sum512(message)
return ed25519.VerifyWithOptions(raw, digest[:], sig, &ed25519.Options{Hash: crypto.SHA512}) == nil
}
+185
View File
@@ -0,0 +1,185 @@
// Package trust is the verifying half of the Yetano family's publisher
// signatures: the signature payload a referrer carries, its check, the
// host's pinned keys (known-keys.json) and its trust policy
// (trust-policy.json). yet signs and manages keys; every program that
// pulls signed content (yet, yacota, ...) checks it with this package
// against the same files, so a host makes one trust decision.
//
// Signatures use minisign (aead.dev/minisign) over the resolved OCI
// manifest digest, attached as an OCI 1.1 referrer to that digest: a
// signature survives a copy or a mirror and cannot be separated from the
// content it was made for. Moved here from yet/internal/trust
// (2026-11-12), unchanged in behavior and file formats.
package trust
import (
"bytes"
"crypto/ed25519"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"aead.dev/minisign"
)
// KeyID is a short, stable label derived from a public key: the same
// 64-bit key ID minisign itself displays and embeds in a signature (see
// minisign.PublicKey.ID / minisign.Signature.KeyID), always written as 16
// uppercase hex digits, like the minisign reference tool prints it.
//
// yet before 2026-10-04 wrote IDs without leading zeros
// ("974656A68B31489" for "0974656A68B31489"), as aead.dev/minisign does.
// Both forms are accepted wherever an ID is read -- from JSON
// (UnmarshalJSON) or typed by a user (ParseKeyID) -- and normalized to
// the 16-digit form, so an old known-keys.json or trust policy keeps
// matching and is written back in the new form the next time it is
// saved.
type KeyID string
// ParseKeyID parses a key ID in either form (16 digits, or without
// leading zeros), in any case, and returns it in canonical form.
func ParseKeyID(s string) (KeyID, error) {
s = strings.TrimSpace(s)
if s == "" || len(s) > 16 {
return "", fmt.Errorf("invalid key id %q: want up to 16 hex digits", s)
}
v, err := strconv.ParseUint(s, 16, 64)
if err != nil {
return "", fmt.Errorf("invalid key id %q: want up to 16 hex digits", s)
}
return KeyIDFromUint(v), nil
}
// Canonical returns k in canonical 16-digit form, or k upper-cased if it
// is not a valid key ID. Compare IDs with Is, never with ==, so a value
// built in either form still matches.
func (k KeyID) Canonical() KeyID {
if id, err := ParseKeyID(string(k)); err == nil {
return id
}
return KeyID(strings.ToUpper(string(k)))
}
// Is reports whether k and other name the same key, in either form.
func (k KeyID) Is(other KeyID) bool {
return k.Canonical() == other.Canonical()
}
// KeyIDFromUint is the canonical KeyID of minisign's 64-bit key ID.
func KeyIDFromUint(v uint64) KeyID {
return KeyID(fmt.Sprintf("%016X", v))
}
// UnmarshalJSON normalizes a stored ID to canonical form. A value that is
// not a valid key ID is kept as-is (upper-cased) rather than failing the
// whole file: it then simply never matches a real key.
func (k *KeyID) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
if id, err := ParseKeyID(s); err == nil {
*k = id
} else {
*k = KeyID(strings.ToUpper(s))
}
return nil
}
// ID derives a stable identifier for a public key: the same 64-bit ID
// minisign itself uses, as 16 uppercase hex digits (so it matches what
// `minisign -G` prints and what a signature's own embedded KeyID field
// carries).
func ID(pub minisign.PublicKey) KeyID {
return KeyIDFromUint(pub.ID())
}
// KeyText returns pub in its one-line form: the base64 line of a ".pub"
// file, without the comment line. It is what known-keys.json and the
// trust policy record for a pinned key (KnownKey.PublicKey,
// Policy.Keys), and what ParseKeyText reads back.
func KeyText(pub minisign.PublicKey) string {
data, err := pub.MarshalText()
if err != nil {
return ""
}
_, line, ok := bytes.Cut(data, []byte("\n"))
if !ok {
return strings.TrimSpace(string(data))
}
return strings.TrimSpace(string(line))
}
// ParseKeyText parses a public key in KeyText's one-line form or as a
// whole ".pub" file.
func ParseKeyText(s string) (minisign.PublicKey, error) {
var pub minisign.PublicKey
err := pub.UnmarshalText([]byte(strings.TrimSpace(s)))
return pub, err
}
// Ed25519Key returns pub's raw Ed25519 public key. A minisign public key
// is "Ed" + an 8-byte key ID + these 32 bytes.
func Ed25519Key(pub minisign.PublicKey) ed25519.PublicKey {
data, err := pub.MarshalText()
if err != nil {
return nil
}
if _, line, ok := bytes.Cut(data, []byte("\n")); ok {
data = line
}
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(data)))
if err != nil || len(raw) != 2+8+ed25519.PublicKeySize {
return nil
}
return ed25519.PublicKey(raw[10:])
}
// SameKey reports whether a and b are the same Ed25519 key, whatever key
// IDs they carry. This, not KeyID.Is, is what decides that a signature
// was made by a pinned key: a minisign key ID is a free 8-byte label
// that neither the key nor a signature's Ed25519 part covers, so anyone
// can give a key of their own the ID of a key someone else trusts.
func SameKey(a, b minisign.PublicKey) bool {
ka, kb := Ed25519Key(a), Ed25519Key(b)
return ka != nil && kb != nil && ka.Equal(kb)
}
// SameKeyText is SameKey for two keys in KeyText (minisign public key)
// form; false if either does not parse.
func SameKeyText(a, b string) bool {
ka, err := ParseKeyText(a)
if err != nil {
return false
}
kb, err := ParseKeyText(b)
if err != nil {
return false
}
return SameKey(ka, kb)
}
// Fingerprint is pub's key fingerprint, "SHA256:" and the unpadded
// base64 SHA-256 of the raw Ed25519 key (ssh-keygen -l style). Unlike
// the key ID it is derived from the key, so it is what to compare
// against a publisher's out-of-band announcement, and it is the same
// for a key in minisign and in PEM form.
func Fingerprint(pub minisign.PublicKey) string {
raw := Ed25519Key(pub)
if raw == nil {
return ""
}
sum := sha256.Sum256(raw)
return "SHA256:" + base64.RawStdEncoding.EncodeToString(sum[:])
}
// Warn reports a trust warning that is not an error (a key pinned
// after the fact, see Reconcile). A variable so programs can route it
// and tests can silence or capture it.
var Warn = func(format string, args ...any) {
fmt.Fprintf(os.Stderr, "warning: "+format+"\n", args...)
}
+315
View File
@@ -0,0 +1,315 @@
package trust
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
"aead.dev/minisign"
)
// KnownKey is one accepted signing key for a repository -- either the
// first valid signature this host ever saw for it (pinned automatically
// by Reconcile), or one added deliberately with AddKnownKey.
type KnownKey struct {
KeyID KeyID `json:"key_id"`
// PublicKey is the accepted key itself (KeyText form). A signature
// only matches this entry if it was made with this exact key
// (SameKey); the ID alone proves nothing, see SameKey.
//
// Entries written before 2026-10-28 have only the ID. Such an entry
// is completed with the key of the first valid signature carrying
// its ID (with a warning), see Reconcile.
// TODO: drop that fallback (and treat an ID-only entry as matching
// nothing) once every host has re-pinned.
PublicKey string `json:"public_key,omitempty"`
Signer string `json:"signer,omitempty"`
AddedAt time.Time `json:"added_at"`
}
// KnownKeys is a host's pinned-key store, keyed by repository -- the
// "registry/repository" portion of a reference (RepositoryKey), never
// including a tag or digest, since a repository's signing keys are
// expected to stay the same across its own versions. This is
// deliberately keyed differently from Policy.Rule (which matches by
// namespace *pattern* and package type): a known key is pinned per
// concrete repository actually pulled/installed, not pre-declared.
//
// Each repository accepts a *list* of keys, not exactly one -- the same
// way SSH's known_hosts can hold more than one key per host (different
// key types, or two people's keys during a deliberate rotation
// overlap). A pull/install is accepted as long as at least one of its
// currently-valid signatures matches *any* key in the repository's
// list; see Reconcile.
type KnownKeys map[string][]KnownKey
// DefaultKnownKeysPath is where the pinned keys are below home (Home).
func DefaultKnownKeysPath(home string) string { return filepath.Join(home, "known-keys.json") }
// LoadKnownKeys reads the known-keys file, or returns an empty store if
// it does not exist yet (nothing pinned so far -- the first pull of
// anything establishes its first pin).
func LoadKnownKeys(path string) (KnownKeys, error) {
data, err := os.ReadFile(path)
if os.IsNotExist(err) {
return KnownKeys{}, nil
}
if err != nil {
return nil, err
}
var k KnownKeys
if err := json.Unmarshal(data, &k); err != nil {
return nil, err
}
if k == nil {
k = KnownKeys{}
}
return k, nil
}
// SaveKnownKeys atomically writes the known-keys file.
func SaveKnownKeys(path string, k KnownKeys) error {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
data, err := json.MarshalIndent(k, "", " ")
if err != nil {
return err
}
data = append(data, '\n')
tmp, err := os.CreateTemp(filepath.Dir(path), ".known-keys-*.json")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), path)
}
// ForgetKnownKey removes *every* accepted key for repoKey, if any -- the
// deliberate, separate step an operator takes after independently
// verifying a repository's new signing key really is legitimate (see
// docs/security-and-trust.md's "Known-key pinning" section), mirroring
// "ssh-keygen -R host" rather than offering a single "--force" flag that
// would make blindly accepting a changed key one keystroke away.
// Reports whether any keys actually existed to remove. To drop only one
// of several accepted keys (e.g. retiring one half of a rotation
// overlap) without losing the others, use RemoveKnownKey instead.
func ForgetKnownKey(path, repoKey string) (bool, error) {
keys, err := LoadKnownKeys(path)
if err != nil {
return false, err
}
if len(keys[repoKey]) == 0 {
return false, nil
}
delete(keys, repoKey)
return true, SaveKnownKeys(path, keys)
}
// AddKnownKey adds keyID (with an optional signer label) to repoKey's
// accepted list, creating the entry if none exists yet. This is for
// deliberately pre-trusting a key an operator has independently
// verified -- the same as appending "ssh-keyscan" output to known_hosts
// before ever connecting, or accepting a second key during a planned
// rotation overlap -- rather than only ever pinning whatever the first
// pull happens to show. publicKey (KeyText form) is the key itself; an
// empty publicKey (only an ID was given) is pinned by the first valid
// signature carrying that ID, like an entry from before keys were
// recorded. A no-op, not an error, if keyID is already present for
// repoKey with the same key, or without one (then publicKey fills it
// in); an error if it is present with a different key.
func AddKnownKey(path, repoKey string, keyID KeyID, publicKey, signer string) error {
keys, err := LoadKnownKeys(path)
if err != nil {
return err
}
for i, k := range keys[repoKey] {
if !k.KeyID.Is(keyID) {
continue
}
switch {
case publicKey == "" || SameKeyText(k.PublicKey, publicKey):
return nil
case k.PublicKey == "":
keys[repoKey][i].PublicKey = publicKey
return SaveKnownKeys(path, keys)
default:
return fmt.Errorf("%s already accepts a different key with id %s", repoKey, keyID)
}
}
keys[repoKey] = append(keys[repoKey], KnownKey{KeyID: keyID.Canonical(), PublicKey: publicKey, Signer: signer, AddedAt: time.Now().UTC()})
return SaveKnownKeys(path, keys)
}
// KnownPublicKey returns the recorded key (KeyText form) of any accepted
// entry with keyID, in any repository, or "" if none records one. It
// lets a bare key ID typed by an operator be resolved to the key it was
// pinned with.
func KnownPublicKey(keys KnownKeys, keyID KeyID) string {
for _, list := range keys {
for _, k := range list {
if k.KeyID.Is(keyID) && k.PublicKey != "" {
return k.PublicKey
}
}
}
return ""
}
// RemoveKnownKey removes exactly one key from repoKey's accepted list,
// leaving any other accepted keys for that repository in place --
// unlike ForgetKnownKey, which drops the whole list at once. Reports
// whether that key was actually present. Removing every key one at a
// time this way and removing them all via ForgetKnownKey end up
// equivalent, but ForgetKnownKey is the clearer way to say "start over
// from scratch" for one repository.
func RemoveKnownKey(path, repoKey string, keyID KeyID) (bool, error) {
keys, err := LoadKnownKeys(path)
if err != nil {
return false, err
}
existing := keys[repoKey]
kept := existing[:0]
found := false
for _, k := range existing {
if k.KeyID.Is(keyID) {
found = true
continue
}
kept = append(kept, k)
}
if !found {
return false, nil
}
if len(kept) == 0 {
delete(keys, repoKey)
} else {
keys[repoKey] = kept
}
return true, SaveKnownKeys(path, keys)
}
// Reconcile pins repoKey's first valid signer the first time one
// is seen for it, accepts a later pull/install as long as at least one
// of its currently-valid signatures was made with *any* already-accepted
// key (whether pinned automatically or added with AddKnownKey), and
// refuses (ErrRefused) one whose valid signatures match none of
// them. A match means the same key (SameKey), not just the same key ID:
// a signature whose key merely claims an accepted ID is refused. An
// unsigned pull (no valid signature at all) is a no-op either way: TOFU
// pinning only ever protects a repository once it has shown at least one
// real signature, it never demands one out of nothing.
//
// An accepted entry that records only an ID (written before keys were
// recorded) is completed with the key of the first valid signature
// carrying that ID, with a warning. TODO: remove this fallback in a
// later version (see KnownKey.PublicKey).
func Reconcile(path, repoKey string, verified []VerifiedSignature) error {
var valid []VerifiedSignature
for _, v := range verified {
if v.Valid {
valid = append(valid, v)
}
}
if len(valid) == 0 {
return nil
}
keys, err := LoadKnownKeys(path)
if err != nil {
return err
}
accepted := keys[repoKey]
if len(accepted) == 0 {
v := valid[0]
keys[repoKey] = []KnownKey{{KeyID: v.KeyID.Canonical(), PublicKey: v.Key, Signer: v.Signature.Signer, AddedAt: time.Now().UTC()}}
return SaveKnownKeys(path, keys)
}
var forged *VerifiedSignature
for _, v := range valid {
for i, k := range accepted {
if !v.KeyID.Is(k.KeyID) {
continue
}
if k.PublicKey == "" && v.Key != "" {
accepted[i].PublicKey = v.Key
Warn("%s: accepted key %s had no recorded public key; pinned it now to %s (check this fingerprint against the publisher's)", repoKey, k.KeyID, v.Fingerprint)
return SaveKnownKeys(path, keys)
}
if k.PublicKey == "" || SameKeyText(k.PublicKey, v.Key) {
return nil
}
forged = &v
}
}
acceptedIDs := make([]KeyID, len(accepted))
for i, k := range accepted {
acceptedIDs[i] = k.KeyID
}
if forged != nil {
return Refusedf(
"refusing %s: it is signed with a key that claims the accepted key id %s but is a different key (fingerprint %s) -- "+
"a key id is only a label, so this signature does not come from the accepted key",
repoKey, forged.KeyID, forged.Fingerprint)
}
first := valid[0].KeyID
return Refusedf(
"refusing %s: signing key changed -- accepted key(s) %v, but this content is signed with %s (fingerprint %s) instead. "+
"If you have independently verified the new key's fingerprint (e.g. against the publisher's own announcement), either "+
"run \"yet trust known-keys add %s <public-key-file>\" to accept it alongside the existing one(s), or "+
"\"yet trust known-keys forget %s\" to replace them outright, then try again.",
repoKey, acceptedIDs, first, valid[0].Fingerprint, repoKey, repoKey)
}
// RepositoryKey returns ref's "registry/repository" identity, the
// KnownKeys map key -- deliberately excluding any tag or digest, computed
// with no network call.
func RepositoryKey(registry, repository string) string {
return fmt.Sprintf("%s/%s", registry, repository)
}
// AcceptedKeys returns the keys accepted for repoKey that record their
// public key; an ID-only entry (see KnownKey.PublicKey) is not usable
// to check a signature that does not carry its own key, and is skipped.
func AcceptedKeys(keys KnownKeys, repoKey string) []minisign.PublicKey {
var out []minisign.PublicKey
for _, k := range keys[repoKey] {
if pub, err := ParseKeyText(k.PublicKey); k.PublicKey != "" && err == nil {
out = append(out, pub)
}
}
return out
}
// UnrecordedKeys counts the accepted keys known-keys and the trust
// policy name by ID only, without the key itself (see
// KnownKey.PublicKey, Policy.Keys) -- what a doctor reports until they
// are pinned.
func UnrecordedKeys(keys KnownKeys, policy Policy) (known, policyIDs int) {
for _, list := range keys {
for _, k := range list {
if k.PublicKey == "" {
known++
}
}
}
seen := map[KeyID]bool{}
for _, rule := range policy.Rules {
for _, id := range rule.AllowedKeys {
if policy.KeyFor(id) == "" && !seen[id.Canonical()] {
seen[id.Canonical()] = true
policyIDs++
}
}
}
return known, policyIDs
}
+76
View File
@@ -0,0 +1,76 @@
package trust
import (
"encoding/json"
"errors"
"fmt"
"path/filepath"
"testing"
"yetano.dev/yetano/core"
)
func TestVerifyPayloads(t *testing.T) {
kp, err := generateKey()
if err != nil {
t.Fatal(err)
}
digest := "sha256:" + onesDigest()
sig, err := testSign(kp, digest)
if err != nil {
t.Fatal(err)
}
good, _ := json.Marshal(sig)
got := Verify(digest, []Payload{{Data: good}, {Err: errors.New("fetch failed")}, {Data: []byte("{")}})
if len(got) != 3 || !got[0].Valid || got[0].KeyID != ID(kp.Public) || got[1].Error != "fetch failed" || got[2].Valid || got[2].Error == "" {
t.Fatalf("%+v", got)
}
if v := Verify("sha256:"+zeros(), []Payload{{Data: good}}); v[0].Valid {
t.Error("a signature over another digest is valid")
}
}
func TestRefused(t *testing.T) {
err := fmt.Errorf("pull: %w", Refusedf("refusing %s", "x"))
if !errors.Is(err, ErrRefused) || err.Error() != "pull: refusing x" {
t.Fatalf("%v", err)
}
if errors.Is(errors.New("other"), ErrRefused) {
t.Fatal("any error is refused")
}
// What Reconcile returns for a changed key.
path := filepath.Join(t.TempDir(), "known-keys.json")
a, _ := generateKey()
b, _ := generateKey()
d := "sha256:" + onesDigest()
sa, _ := testSign(a, d)
sb, _ := testSign(b, d)
if err := Reconcile(path, "r/x", []VerifiedSignature{VerifySignature(d, sa)}); err != nil {
t.Fatal(err)
}
if err := Reconcile(path, "r/x", []VerifiedSignature{VerifySignature(d, sb)}); !errors.Is(err, ErrRefused) {
t.Fatalf("a changed key: %v", err)
}
}
func TestCuratedAndPinned(t *testing.T) {
p := Policy{Rules: []Rule{{Namespace: "yetano/*", AllowedKeys: []KeyID{"1"}}, {Namespace: "library/nginx"}}}
for name, want := range map[string]bool{"yetano/yet": true, "yetano": false, "library/nginx": true, "library/alpine": false} {
if p.Curated(name) != want {
t.Errorf("Curated(%s) = %v", name, !want)
}
}
keys := KnownKeys{"docker.io/library/nginx": {{KeyID: "1"}}}
if !keys.Pinned("docker.io/library/nginx") || keys.Pinned("docker.io/library/alpine") {
t.Error("Pinned")
}
}
func TestHome(t *testing.T) {
dir := t.TempDir()
t.Setenv("YET_DATA_HOME", dir)
got, err := Home(core.UserScope)
if err != nil || got != dir {
t.Fatalf("Home = %q, %v; want %q (yet's data directory)", got, err, dir)
}
}
+90
View File
@@ -0,0 +1,90 @@
package trust
// Moved from yet's internal/trust with the signing half (2026-11-27).
import (
"crypto/ed25519"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/pem"
"errors"
"fmt"
"strconv"
"aead.dev/minisign"
)
// ExportPEM encodes pub's Ed25519 key as a PEM "PUBLIC KEY" block
// (PKIX), the form cosign, openssl and most other tools read -- e.g.
// "cosign verify-attestation --key exported.pem". Only the key leaves:
// a PEM file has no room for minisign's key ID, and nothing private is
// ever exported.
func ExportPEM(pub minisign.PublicKey) ([]byte, error) {
raw := Ed25519Key(pub)
if raw == nil {
return nil, errors.New("not an Ed25519 minisign public key")
}
der, err := x509.MarshalPKIXPublicKey(raw)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}), nil
}
// ImportPEM reads a PEM "PUBLIC KEY" block holding an Ed25519 key
// (e.g. a cosign.pub made from an Ed25519 key, or ExportPEM's output)
// and returns it as a minisign public key, so it can be pinned and
// trusted like any other (known-keys add, trust policy allow).
//
// PEM carries no key ID, so one is chosen: knownID's answer if it
// returns one for this key (a key this host already knows, e.g. one
// exported earlier, gets its old ID back), otherwise one derived from
// the key (the first 8 bytes of its SHA-256). Either way trust decisions
// compare the key itself, never the ID (see SameKey).
func ImportPEM(data []byte, knownID func(ed25519.PublicKey) (KeyID, bool)) (minisign.PublicKey, error) {
block, _ := pem.Decode(data)
if block == nil {
return minisign.PublicKey{}, errors.New("no PEM block found")
}
if block.Type != "PUBLIC KEY" {
return minisign.PublicKey{}, fmt.Errorf("PEM block is %q, want \"PUBLIC KEY\" (never import a private key)", block.Type)
}
parsed, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return minisign.PublicKey{}, fmt.Errorf("parse public key: %w", err)
}
raw, ok := parsed.(ed25519.PublicKey)
if !ok {
return minisign.PublicKey{}, fmt.Errorf("unsupported key type %T: only Ed25519 keys can be imported (cosign generate-key-pair makes ECDSA P-256 keys)", parsed)
}
var id uint64
if knownID != nil {
if known, ok := knownID(raw); ok {
v, err := ParseKeyID(string(known))
if err == nil {
id = parseUint(v)
}
}
}
if id == 0 {
sum := sha256.Sum256(raw)
id = binary.LittleEndian.Uint64(sum[:8])
}
return minisignKey(id, raw)
}
// minisignKey builds a minisign public key from an ID and a raw key.
func minisignKey(id uint64, raw ed25519.PublicKey) (minisign.PublicKey, error) {
buf := make([]byte, 0, 2+8+ed25519.PublicKeySize)
buf = append(buf, 'E', 'd')
buf = binary.LittleEndian.AppendUint64(buf, id)
buf = append(buf, raw...)
return ParseKeyText(base64.StdEncoding.EncodeToString(buf))
}
func parseUint(id KeyID) uint64 {
v, _ := strconv.ParseUint(string(id), 16, 64)
return v
}
+331
View File
@@ -0,0 +1,331 @@
package trust
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
)
// Rule grants trust to a set of keys for packages matching Namespace and
// (optionally) Type. Namespace is a package name or a "prefix/*" pattern;
// "*" matches every package.
type Rule struct {
Namespace string `json:"namespace"`
Type string `json:"type,omitempty"`
AllowedKeys []KeyID `json:"allowed_keys"`
// Capabilities additionally lets packages this rule covers, signed by
// one of AllowedKeys, have "yet setup apply" perform these kinds of
// declarative install operations (manifest.ExecutableOperations, e.g.
// "desktop-app"). Trusting a publisher to install never implies this:
// a capability is only ever granted by a rule that names it -- see
// AllowsCapability.
Capabilities []string `json:"capabilities,omitempty"`
}
// Policy is a host's local trust policy: which publishers it accepts for
// which packages, and whether an unsigned or untrusted package is allowed
// at all. It is deliberately separate from registry credentials and
// registry-side permissions: a registry account proves who may upload,
// this proves who the host has decided to trust once the bytes are in
// hand.
type Policy struct {
// RequireSignatures, when true, rejects any package with no valid
// signature at all. It does NOT require that signature to match a
// curated Rule below -- known-key (TOFU) pinning (Reconcile)
// already establishes "signed consistently with whatever this
// repository was first seen signed with" before Evaluate ever runs,
// and that is sufficient on its own unless a Rule specifically
// covers this namespace/type (see Evaluate).
//
// 2026-09-20: defaults to true for a host with no policy file at all
// (LoadPolicy) -- requested directly, reversing this project's
// original "unsigned is reported, not blocked" MVP default now that
// TOFU pinning exists to make "require a signature" meaningful
// without first requiring a hand-curated allow-list. An operator who
// wants the old permissive behavior back sets this to false
// explicitly ("yet trust policy require off").
RequireSignatures bool `json:"require_signatures"`
Rules []Rule `json:"rules"`
// Keys records, per key ID a Rule names, the key itself (KeyText
// form). A rule only matches a signature made with exactly that key
// (SameKey) -- a key ID alone is a label anyone can copy. An ID with
// no entry here (a rule from before keys were recorded, or one added
// by bare ID) matches by ID until PinKeys records the key of its
// first valid signature. TODO: drop that fallback in a later version
// and require a key for every allowed ID.
Keys map[KeyID]string `json:"keys,omitempty"`
}
// KeyFor returns the recorded key (KeyText form) for id, or "".
func (p Policy) KeyFor(id KeyID) string {
for k, v := range p.Keys {
if k.Is(id) {
return v
}
}
return ""
}
// SetKey records key (KeyText form) for id.
func (p *Policy) SetKey(id KeyID, key string) {
if p.Keys == nil {
p.Keys = map[KeyID]string{}
}
for k := range p.Keys {
if k.Is(id) {
delete(p.Keys, k)
}
}
p.Keys[id.Canonical()] = key
}
// allows reports whether allowed, an ID a rule names, covers sig: the
// same ID and, once one is recorded, the same key.
func (p Policy) allows(allowed KeyID, sig VerifiedSignature) bool {
if !allowed.Is(sig.KeyID) {
return false
}
recorded := p.KeyFor(allowed)
return recorded == "" || SameKeyText(recorded, sig.Key)
}
// PinKeys records, for every ID without a key yet that a rule covering
// name/pkgType names, the key of the first valid signature in verified
// carrying that ID, warns about each, and reports whether it changed p.
// Only rules covering the package itself: a signature on some other
// package never decides the key of a rule it is not checked against.
// TODO: remove together with the ID-only fallback (see Keys).
func (p *Policy) PinKeys(name, pkgType string, verified []VerifiedSignature) bool {
changed := false
for _, rule := range p.Rules {
if !matchesNamespace(rule.Namespace, name) || (rule.Type != "" && rule.Type != pkgType) {
continue
}
for _, allowed := range rule.AllowedKeys {
if p.KeyFor(allowed) != "" {
continue
}
for _, sig := range verified {
if sig.Valid && sig.Key != "" && allowed.Is(sig.KeyID) {
p.SetKey(allowed, sig.Key)
Warn("trust policy: key %s had no recorded public key; pinned it now to %s (check this fingerprint against the publisher's)", allowed, sig.Fingerprint)
changed = true
break
}
}
}
}
return changed
}
// DropUnusedKeys removes recorded keys no rule names any more.
func (p *Policy) DropUnusedKeys() {
for id := range p.Keys {
used := false
for _, rule := range p.Rules {
if slices.ContainsFunc(rule.AllowedKeys, id.Is) {
used = true
}
}
if !used {
delete(p.Keys, id)
}
}
if len(p.Keys) == 0 {
p.Keys = nil
}
}
// DefaultPolicyPath is where the policy is below home (Home); "yet
// trust policy" edits it.
func DefaultPolicyPath(home string) string { return filepath.Join(home, "trust-policy.json") }
// LoadPolicy reads the policy file, or -- if it does not exist yet, i.e.
// this host has never run "yet trust policy" at all -- returns the
// default policy: RequireSignatures true, no curated Rules. This is a
// deliberate default, not the bare zero value (which stays permissive,
// for callers that construct a Policy directly rather than through
// LoadPolicy); see Policy.RequireSignatures' doc comment for why
// requiring a signature is safe to default to now that TOFU pinning
// (Reconcile, run before Evaluate) exists.
func LoadPolicy(path string) (Policy, error) {
data, err := os.ReadFile(path)
if os.IsNotExist(err) {
return Policy{RequireSignatures: true}, nil
}
if err != nil {
return Policy{}, err
}
var p Policy
if err := json.Unmarshal(data, &p); err != nil {
return Policy{}, err
}
return p, nil
}
// SavePolicy atomically writes the policy file.
func SavePolicy(path string, p Policy) error {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
data, err := json.MarshalIndent(p, "", " ")
if err != nil {
return err
}
data = append(data, '\n')
tmp, err := os.CreateTemp(filepath.Dir(path), ".policy-*.json")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), path)
}
// Decision is the result of evaluating a package's verified signatures
// against the policy.
type Decision struct {
Trusted bool
MatchedKey KeyID
Reason string
}
// Evaluate decides whether name/pkgType is acceptable given its verified
// signatures. It never looks at registry credentials: a package pulled
// anonymously from a public mirror is evaluated the same way as one pulled
// with admin credentials.
//
// A curated Rule (below) is a *stricter*, opt-in restriction, scoped by
// *namespace* -- once any Rule's Namespace matches name at all (any
// Rule, regardless of its own Type), this namespace is considered
// curated for every package type, not just the one(s) that rule's Type
// happens to name: only an AllowedKeys match satisfies it, and TOFU
// pinning never overrides that, so adding a namespace's first plugin
// trust rule does not silently leave that same namespace's generic/pkg
// packages ungoverned. When no Rule's namespace matches name at all (the
// common, out-of-the-box case, since nothing is curated by default),
// RequireSignatures is satisfied by any valid signature on its own -- by
// the time Evaluate runs, known-key (TOFU) pinning (Reconcile) has
// already confirmed that signature is consistent with whatever this
// repository was first seen signed with, which is enough without also
// requiring a hand-curated allow-list entry.
func (p Policy) Evaluate(name, pkgType string, verified []VerifiedSignature) Decision {
var anyValid bool
var ruleCovers bool
for _, sig := range verified {
if !sig.Valid {
continue
}
anyValid = true
}
for _, rule := range p.Rules {
if !matchesNamespace(rule.Namespace, name) {
continue
}
ruleCovers = true
if rule.Type != "" && rule.Type != pkgType {
continue
}
for _, sig := range verified {
if !sig.Valid {
continue
}
for _, allowed := range rule.AllowedKeys {
if p.allows(allowed, sig) {
return Decision{Trusted: true, MatchedKey: sig.KeyID, Reason: "signed by a trusted publisher for " + rule.Namespace}
}
}
}
}
if ruleCovers {
return Decision{Trusted: false, Reason: "a trust policy rule covers this namespace/type, but no allowed key matched"}
}
if !p.RequireSignatures {
return Decision{Trusted: true, Reason: "no trust policy rule matched; signatures are not required"}
}
if anyValid {
return Decision{Trusted: true, Reason: "no curated trust-policy rule covers this namespace, accepted on a valid, TOFU-consistent signature"}
}
return Decision{Trusted: false, Reason: "unsigned, and this host requires a signature for every package by default"}
}
// AllowsCapability decides whether name/pkgType may have "yet setup"
// perform an install operation of kind capability: only a Rule covering
// the namespace (and type, if the rule names one) that lists the
// capability, and one of whose AllowedKeys made a valid signature in
// verified, grants it. RequireSignatures, TOFU pinning and rules without
// the capability never do -- this is deliberately stricter than Evaluate.
func (p Policy) AllowsCapability(name, pkgType, capability string, verified []VerifiedSignature) Decision {
granting := false
for _, rule := range p.Rules {
if !matchesNamespace(rule.Namespace, name) || (rule.Type != "" && rule.Type != pkgType) || !slices.Contains(rule.Capabilities, capability) {
continue
}
granting = true
for _, sig := range verified {
if !sig.Valid {
continue
}
for _, allowed := range rule.AllowedKeys {
if p.allows(allowed, sig) {
return Decision{Trusted: true, MatchedKey: sig.KeyID, Reason: fmt.Sprintf("%q granted for %s, signed by %s", capability, rule.Namespace, sig.KeyID)}
}
}
}
}
if granting {
return Decision{Trusted: false, Reason: fmt.Sprintf("a trust rule grants %q here, but no valid signature by one of its keys was found", capability)}
}
return Decision{Trusted: false, Reason: fmt.Sprintf("no trust rule grants %q for %s", capability, name)}
}
func matchesNamespace(pattern, name string) bool {
if pattern == "*" {
return true
}
if strings.HasSuffix(pattern, "/*") {
return strings.HasPrefix(name, strings.TrimSuffix(pattern, "*"))
}
return pattern == name
}
// WithdrawCapability takes capability away from key in every rule whose
// Namespace is exactly namespace, and reports how many rules it changed.
// The rules themselves stay: key keeps its ordinary trust for the
// namespace, which stays curated, so withdrawing a capability never
// loosens what an install accepts. A rule that also names other keys is
// split, so their capabilities are untouched.
func (p *Policy) WithdrawCapability(namespace string, key KeyID, capability string) int {
changed := 0
var out []Rule
for _, rule := range p.Rules {
i := slices.IndexFunc(rule.AllowedKeys, key.Is)
if rule.Namespace != namespace || i < 0 || !slices.Contains(rule.Capabilities, capability) {
out = append(out, rule)
continue
}
changed++
if others := slices.Delete(slices.Clone(rule.AllowedKeys), i, i+1); len(others) > 0 {
kept := rule
kept.AllowedKeys = others
out = append(out, kept)
}
rule.AllowedKeys = []KeyID{rule.AllowedKeys[i]}
rule.Capabilities = slices.DeleteFunc(slices.Clone(rule.Capabilities), func(c string) bool { return c == capability })
if len(rule.Capabilities) == 0 {
rule.Capabilities = nil
}
out = append(out, rule)
}
p.Rules = out
return changed
}
+32
View File
@@ -0,0 +1,32 @@
package trust
import (
"context"
"fmt"
"yetano.dev/yetano/core/secretref"
)
// KeyFromRef loads a signing key pair from a secret reference
// (secret://, env:, file:, base64: -- core/secretref), for example
// "secret://yabar/evidence/minisign" in yaseva. The value is a minisign
// private key file's contents. passwordRef ("" for none) is the
// reference of the password of an encrypted key. Error messages never
// contain the secret.
func KeyFromRef(ctx context.Context, r *secretref.Resolver, keyRef, passwordRef string) (KeyPair, error) {
data, err := r.Resolve(ctx, keyRef)
if err != nil {
return KeyPair{}, fmt.Errorf("signing key %s: %s", keyRef, r.Redact(err.Error()))
}
var password string
if passwordRef != "" {
if password, err = r.ResolveString(ctx, passwordRef); err != nil {
return KeyPair{}, fmt.Errorf("signing key password %s: %s", passwordRef, r.Redact(err.Error()))
}
}
kp, err := ParsePrivateKey(data, password)
if err != nil {
return KeyPair{}, fmt.Errorf("signing key %s: %s", keyRef, r.Redact(err.Error()))
}
return kp, nil
}
+64
View File
@@ -0,0 +1,64 @@
package trust
import (
"errors"
"fmt"
"strings"
"time"
"aead.dev/minisign"
)
// SignDigest makes the publisher signature of an OCI manifest digest:
// the Signature payload yet pushes as a referrer and VerifySignature
// checks. The trusted comment is "yet package digest: <digest>" (the
// format yet has always written).
func SignDigest(kp KeyPair, digest string) (Signature, error) {
trustedComment := "yet package digest: " + digest
sig := minisign.SignWithComments(kp.Private, []byte(digest), trustedComment, "")
pubText, err := kp.Public.MarshalText()
if err != nil {
return Signature{}, err
}
return Signature{
SchemaVersion: 1,
Algorithm: "minisign",
PublicKey: string(pubText),
Digest: digest,
Value: string(sig),
SignedAt: time.Now().UTC(),
}, nil
}
// Sign makes a detached minisign signature of message: the text of a
// ".minisig" file, which "minisign -V -m <file>" verifies against the
// key's ".pub" file. trustedComment is signed with it (one line);
// untrustedComment is not ("" for minisign's default).
func Sign(kp KeyPair, message []byte, trustedComment, untrustedComment string) ([]byte, error) {
if strings.ContainsAny(trustedComment, "\r\n") || strings.ContainsAny(untrustedComment, "\r\n") {
return nil, errors.New("a minisign comment is one line")
}
return minisign.SignWithComments(kp.Private, message, trustedComment, untrustedComment), nil
}
// ErrBadSignature: a signature does not verify (wrong key, changed
// message or changed trusted comment).
var ErrBadSignature = errors.New("signature does not verify")
// VerifyMessage checks a detached minisign signature (Sign's output, or
// a ".minisig" file from the minisign tool) of message against pub and
// returns its trusted comment, which the signature covers. A signature
// by another key fails, also when its key ID collides with pub's.
func VerifyMessage(pub minisign.PublicKey, message, signature []byte) (trustedComment string, err error) {
var sig minisign.Signature
if err := sig.UnmarshalText(signature); err != nil {
return "", fmt.Errorf("parse signature: %w", err)
}
if sig.KeyID != pub.ID() {
return "", fmt.Errorf("%w: signed by key %s, not %s", ErrBadSignature, KeyIDFromUint(sig.KeyID), ID(pub))
}
if !minisign.Verify(pub, message, signature) {
return "", ErrBadSignature
}
return sig.TrustedComment, nil
}
+165
View File
@@ -0,0 +1,165 @@
package trust
import (
"bytes"
"context"
"encoding/base64"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"aead.dev/minisign"
"yetano.dev/yetano/core/secretref"
)
func vectorKey(t *testing.T) KeyPair {
t.Helper()
kp, err := LoadPrivateKey("testdata/sign-vector.key", "")
if err != nil {
t.Fatal(err)
}
return kp
}
// The golden vector: a fixed key and message give exactly the committed
// .minisig (Ed25519 is deterministic), and it verifies with the .pub.
// "minisign -Vm testdata/sign-vector.msg -p testdata/sign-vector.pub"
// verifies it as well.
func TestSignVector(t *testing.T) {
kp := vectorKey(t)
msg, _ := os.ReadFile("testdata/sign-vector.msg")
want, _ := os.ReadFile("testdata/sign-vector.msg.minisig")
got, err := Sign(kp, msg, "yabar evidence test-vector 00000000000000000000000000000000", "")
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("signature differs from the vector (%v):\n%s", err, got)
}
pub, err := LoadPublicKey("testdata/sign-vector.pub")
if err != nil || !SameKey(pub, kp.Public) {
t.Fatalf("public key: %v", err)
}
tc, err := VerifyMessage(pub, msg, want)
if err != nil || tc != "yabar evidence test-vector 00000000000000000000000000000000" {
t.Fatalf("verify: %q %v", tc, err)
}
}
func TestVerifyMessageRejects(t *testing.T) {
kp := vectorKey(t)
msg := []byte("evidence")
sig, _ := Sign(kp, msg, "trusted", "untrusted")
if _, err := VerifyMessage(kp.Public, []byte("evidencE"), sig); !errors.Is(err, ErrBadSignature) {
t.Fatalf("changed message: %v", err)
}
changed := bytes.Replace(sig, []byte("trusted comment: trusted"), []byte("trusted comment: trustee"), 1)
if _, err := VerifyMessage(kp.Public, msg, changed); !errors.Is(err, ErrBadSignature) {
t.Fatalf("changed trusted comment: %v", err)
}
// The untrusted comment is not covered.
free := bytes.Replace(sig, []byte("untrusted comment: untrusted"), []byte("untrusted comment: whatever"), 1)
if _, err := VerifyMessage(kp.Public, msg, free); err != nil {
t.Fatalf("untrusted comment: %v", err)
}
other, _ := GenerateKey()
if _, err := VerifyMessage(other.Public, msg, sig); !errors.Is(err, ErrBadSignature) {
t.Fatalf("other key: %v", err)
}
if _, err := VerifyMessage(kp.Public, msg, []byte("garbage")); err == nil {
t.Fatal("garbage verified")
}
if _, err := Sign(kp, msg, "two\nlines", ""); err == nil {
t.Fatal("a two-line comment was accepted")
}
}
// What SignDigest makes, VerifySignature (the verifying half every
// consumer uses) accepts, and only for that digest.
func TestSignDigestVerifies(t *testing.T) {
kp := vectorKey(t)
const d = "sha256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
sig, err := SignDigest(kp, d)
if err != nil {
t.Fatal(err)
}
if v := VerifySignature(d, sig); !v.Valid || v.KeyID != ID(kp.Public) {
t.Fatalf("verify: %+v", v)
}
if v := VerifySignature("sha256:"+strings.Repeat("0", 64), sig); v.Valid {
t.Fatal("verified for another digest")
}
tc, err := VerifyMessage(kp.Public, []byte(d), []byte(sig.Value))
if err != nil || tc != "yet package digest: "+d {
t.Fatalf("trusted comment %q %v", tc, err)
}
}
func TestKeyFiles(t *testing.T) {
dir := t.TempDir()
kp, _ := GenerateKey()
for _, pw := range []string{"", "secret"} {
p := filepath.Join(dir, "k"+pw)
if err := SaveKeyPair(p, kp, pw); err != nil {
t.Fatal(err)
}
got, err := LoadPrivateKey(p, pw)
if err != nil || !SameKey(got.Public, kp.Public) {
t.Fatalf("password %q: %v", pw, err)
}
pub, err := LoadPublicKey(p + ".pub")
if err != nil || !SameKey(pub, kp.Public) {
t.Fatalf(".pub: %v", err)
}
if fi, _ := os.Stat(p); os.PathSeparator == '/' && fi.Mode().Perm() != 0o600 {
t.Fatalf("private key mode %v", fi.Mode())
}
}
if _, err := LoadPrivateKey(filepath.Join(dir, "ksecret"), "wrong"); err == nil {
t.Fatal("wrong password accepted")
}
b, _ := MarshalPublicKey(kp.Public)
if !bytes.HasPrefix(b, []byte("untrusted comment: minisign public key: "+string(ID(kp.Public))+"\n")) {
t.Fatalf("public key file: %s", b)
}
}
func TestEd25519AndPEM(t *testing.T) {
kp := vectorKey(t)
sig, err := SignEd25519(kp, []byte("statement"))
if err != nil || !VerifyEd25519(kp.Public, []byte("statement"), sig) || VerifyEd25519(kp.Public, []byte("statemenT"), sig) {
t.Fatalf("ed25519: %v", err)
}
p, err := ExportPEM(kp.Public)
if err != nil {
t.Fatal(err)
}
back, err := ImportPEM(p, nil)
if err != nil || !SameKey(back, kp.Public) {
t.Fatalf("PEM round trip: %v", err)
}
}
func TestKeyFromRef(t *testing.T) {
kp := vectorKey(t)
priv, _ := os.ReadFile("testdata/sign-vector.key")
r := secretref.New("")
got, err := KeyFromRef(context.Background(), r, "base64:"+base64.StdEncoding.EncodeToString(priv), "")
if err != nil || !SameKey(got.Public, kp.Public) {
t.Fatalf("base64 ref: %v", err)
}
enc, _ := minisign.EncryptKey("pw", kp.Private)
t.Setenv("TRUST_TEST_KEY", string(enc))
t.Setenv("TRUST_TEST_PW", "pw")
if got, err = KeyFromRef(context.Background(), r, "env:TRUST_TEST_KEY", "env:TRUST_TEST_PW"); err != nil || !SameKey(got.Public, kp.Public) {
t.Fatalf("encrypted env ref: %v", err)
}
t.Setenv("TRUST_TEST_PW", "wrong-password")
_, err = KeyFromRef(context.Background(), secretref.New(""), "env:TRUST_TEST_KEY", "env:TRUST_TEST_PW")
if err == nil || strings.Contains(err.Error(), "wrong-password") {
t.Fatalf("wrong password: %v", err)
}
if _, err := KeyFromRef(context.Background(), r, "not a reference", ""); err == nil {
t.Fatal("plaintext accepted")
}
}
+2
View File
@@ -0,0 +1,2 @@
untrusted comment: minisign encrypted secret key
RWQAAEIyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMIu3pReIO0jw8qjsUD5/2J9b2y+5BNJ45wLRkzgleRSUugHITToa6mGDGFfLcgDIs+wEX4vFIUfnrLqym+u2yLqBzAYgET+YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+1
View File
@@ -0,0 +1 @@
yabar evidence vector
+4
View File
@@ -0,0 +1,4 @@
untrusted comment:
RWQwi7elF4g7SHc9svLZOCFGGEyXs7gZW6saVrYobxgEdJnDM9hIxHIlC+qxicazJFYu2E6TG3Qq62NTae3k0rDlomfkxxz8oQA=
trusted comment: yabar evidence test-vector 00000000000000000000000000000000
o0/jQwycdwDK6BrI5jc6N47P2ixexYe07twyQ587cJBWapfKNch5EmMgvvwR6thKci3Lg0dpuanBDFdVP9QcCw==
+2
View File
@@ -0,0 +1,2 @@
untrusted comment: minisign public key: 483B8817A5B78B30
RWQwi7elF4g7SGGDGFfLcgDIs+wEX4vFIUfnrLqym+u2yLqBzAYgET+Y
+754
View File
@@ -0,0 +1,754 @@
package trust
import (
"encoding/base64"
"errors"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"aead.dev/minisign"
)
// keyPair, generateKey and testSign stand in for yet's signing side
// (yet/internal/trust), which is not part of this package.
type keyPair struct {
Public minisign.PublicKey
Private minisign.PrivateKey
}
func generateKey() (keyPair, error) {
pub, priv, err := minisign.GenerateKey(nil)
return keyPair{pub, priv}, err
}
// testSign signs digest as yet does.
func testSign(kp keyPair, digest string) (Signature, error) {
sig := minisign.SignWithComments(kp.Private, []byte(digest), "yet package digest: "+digest, "")
pubText, err := kp.Public.MarshalText()
if err != nil {
return Signature{}, err
}
return Signature{SchemaVersion: 1, Algorithm: "minisign", PublicKey: string(pubText), Digest: digest, Value: string(sig), SignedAt: time.Now().UTC()}, nil
}
func mustMarshal(t *testing.T, pub minisign.PublicKey) []byte {
t.Helper()
data, err := pub.MarshalText()
if err != nil {
t.Fatal(err)
}
return data
}
// keyWithLeadingZero generates keys until one's ID has a leading zero
// hex digit (1 in 16), the case the old format got wrong.
func keyWithLeadingZero(t *testing.T) keyPair {
t.Helper()
for range 1000 {
kp, err := generateKey()
if err != nil {
t.Fatal(err)
}
if kp.Public.ID() < 1<<60 {
return kp
}
}
t.Fatal("no key with a leading-zero ID in 1000 tries")
return keyPair{}
}
func TestParseKeyIDAcceptsBothForms(t *testing.T) {
for _, in := range []string{"0974656A68B31489", "974656A68B31489", "974656a68b31489", " 0974656a68b31489\n"} {
got, err := ParseKeyID(in)
if err != nil || got != "0974656A68B31489" {
t.Errorf("ParseKeyID(%q) = %q, %v; want 0974656A68B31489", in, got, err)
}
}
for _, bad := range []string{"", "XYZ", "10974656A68B31489", "0x974656A68B31489"} {
if _, err := ParseKeyID(bad); err == nil {
t.Errorf("ParseKeyID(%q) unexpectedly succeeded", bad)
}
}
}
func TestIDIsSixteenDigits(t *testing.T) {
kp := keyWithLeadingZero(t)
id := ID(kp.Public)
if len(id) != 16 || id[0] != '0' {
t.Fatalf("ID = %q, want 16 digits with the leading zero kept", id)
}
}
func TestOldFormatInKnownKeysAndPolicyStillMatches(t *testing.T) {
kp := keyWithLeadingZero(t)
id := ID(kp.Public)
old := strings.TrimLeft(string(id), "0")
dir := t.TempDir()
knownPath := filepath.Join(dir, "known-keys.json")
if err := os.WriteFile(knownPath, []byte(`{"r/x":[{"key_id":"`+strings.ToLower(old)+`","signer":"s"}]}`), 0o600); err != nil {
t.Fatal(err)
}
keys, err := LoadKnownKeys(knownPath)
if err != nil {
t.Fatal(err)
}
if got := keys["r/x"][0].KeyID; got != id {
t.Fatalf("loaded known key %q, want normalized %q", got, id)
}
// A valid signature by the same key is accepted, not reported as a changed key.
if err := Reconcile(knownPath, "r/x", []VerifiedSignature{{KeyID: id, Valid: true}}); err != nil {
t.Fatalf("old-format pin rejected the same key: %v", err)
}
// Adding it again is a no-op, and the next save writes the new form.
if err := AddKnownKey(knownPath, "r/y", id, "", "s"); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(knownPath)
if !strings.Contains(string(data), `"key_id": "`+string(id)+`"`) || strings.Contains(string(data), `"`+strings.ToLower(old)+`"`) {
t.Fatalf("saved known-keys.json not in canonical form:\n%s", data)
}
if n := len(keys["r/x"]); n != 1 {
t.Fatalf("r/x has %d keys, want 1", n)
}
policyPath := filepath.Join(dir, "trust-policy.json")
if err := os.WriteFile(policyPath, []byte(`{"require_signatures":true,"rules":[{"namespace":"*","allowed_keys":["`+old+`"]}]}`), 0o600); err != nil {
t.Fatal(err)
}
p, err := LoadPolicy(policyPath)
if err != nil {
t.Fatal(err)
}
if got := p.Rules[0].AllowedKeys[0]; got != id {
t.Fatalf("loaded policy key %q, want normalized %q", got, id)
}
}
// forgeID re-labels a minisign text (a ".pub" file or a signature) with
// id: the key ID is bytes 2..10 of the first base64 line after the
// comment, and nothing signs it.
func forgeID(t *testing.T, text string, id uint64) string {
t.Helper()
lines := strings.Split(text, "\n")
raw, err := base64.StdEncoding.DecodeString(lines[1])
if err != nil {
t.Fatal(err)
}
for i := range 8 {
raw[2+i] = byte(id >> (8 * i))
}
lines[1] = base64.StdEncoding.EncodeToString(raw)
return strings.Join(lines, "\n")
}
// forgedSignature is what an attacker with push access can produce: a
// cryptographically valid signature over digest, made with their own
// key, carrying victim's key ID.
func forgedSignature(t *testing.T, victim keyPair, digest string) Signature {
t.Helper()
attacker, err := generateKey()
if err != nil {
t.Fatal(err)
}
sig := signFor(t, attacker, digest)
sig.PublicKey = forgeID(t, sig.PublicKey, victim.Public.ID())
sig.Value = forgeID(t, sig.Value, victim.Public.ID())
return sig
}
func silenceWarnings(t *testing.T) *[]string {
t.Helper()
var got []string
old := Warn
Warn = func(format string, args ...any) { got = append(got, format) }
t.Cleanup(func() { Warn = old })
return &got
}
func TestForgedKeyIDIsCryptographicallyValidButNotTheKey(t *testing.T) {
victim, _ := generateKey()
digest := "sha256:" + zeros()
v := VerifySignature(digest, forgedSignature(t, victim, digest))
if !v.Valid || !v.KeyID.Is(ID(victim.Public)) {
t.Fatalf("precondition: the forgery should verify and claim the victim's id, got %+v", v)
}
forged, _ := ParseKeyText(v.Key)
if SameKey(forged, victim.Public) || v.Fingerprint == Fingerprint(victim.Public) {
t.Fatal("a forged key id must not make the key equal")
}
}
func TestReconcileKnownKeyRefusesForgedKeyID(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
victim, _ := generateKey()
digest := "sha256:" + zeros()
repo := "registry.example/yetano/tool"
if err := Reconcile(path, repo, []VerifiedSignature{VerifySignature(digest, signFor(t, victim, digest))}); err != nil {
t.Fatal(err)
}
keys, _ := LoadKnownKeys(path)
if keys[repo][0].PublicKey != KeyText(victim.Public) {
t.Fatalf("first pin must record the key itself, got %+v", keys[repo])
}
err := Reconcile(path, repo, []VerifiedSignature{VerifySignature(digest, forgedSignature(t, victim, digest))})
if !errors.Is(err, ErrRefused) || !strings.Contains(err.Error(), "different key") {
t.Fatalf("expected a forged key id to be refused, got %v", err)
}
}
func TestReconcileKnownKeyPinsLegacyIDOnlyEntry(t *testing.T) {
warnings := silenceWarnings(t)
path := filepath.Join(t.TempDir(), "known-keys.json")
victim, _ := generateKey()
digest := "sha256:" + zeros()
repo := "registry.example/yetano/tool"
if err := SaveKnownKeys(path, KnownKeys{repo: {{KeyID: ID(victim.Public)}}}); err != nil {
t.Fatal(err)
}
if err := Reconcile(path, repo, []VerifiedSignature{VerifySignature(digest, signFor(t, victim, digest))}); err != nil {
t.Fatal(err)
}
keys, _ := LoadKnownKeys(path)
if keys[repo][0].PublicKey != KeyText(victim.Public) || len(*warnings) != 1 {
t.Fatalf("expected the legacy entry to be pinned with a warning, got %+v, warnings %v", keys[repo], *warnings)
}
// From now on the ID alone is not enough.
if err := Reconcile(path, repo, []VerifiedSignature{VerifySignature(digest, forgedSignature(t, victim, digest))}); err == nil {
t.Fatal("expected the forged key id to be refused once the key is recorded")
}
}
func TestVerifyRejectsConflictingKeysForOneID(t *testing.T) {
victim, _ := generateKey()
digest := "sha256:" + zeros()
results := rejectConflictingIDs([]VerifiedSignature{
VerifySignature(digest, signFor(t, victim, digest)),
VerifySignature(digest, forgedSignature(t, victim, digest)),
})
for _, r := range results {
if r.Valid {
t.Fatalf("two different keys with one id must both be rejected, got %+v", results)
}
}
// The same key twice is no conflict.
results = rejectConflictingIDs([]VerifiedSignature{
VerifySignature(digest, signFor(t, victim, digest)),
VerifySignature(digest, signFor(t, victim, digest)),
})
if !results[0].Valid || !results[1].Valid {
t.Fatalf("expected two signatures by one key to stay valid, got %+v", results)
}
}
func TestPolicyMatchesTheRecordedKeyNotJustItsID(t *testing.T) {
victim, _ := generateKey()
digest := "sha256:" + zeros()
id := ID(victim.Public)
p := Policy{RequireSignatures: true, Rules: []Rule{{Namespace: "acme/*", AllowedKeys: []KeyID{id}, Capabilities: []string{"desktop-app"}}}}
p.SetKey(id, KeyText(victim.Public))
genuine := []VerifiedSignature{VerifySignature(digest, signFor(t, victim, digest))}
forged := []VerifiedSignature{VerifySignature(digest, forgedSignature(t, victim, digest))}
if !p.Evaluate("acme/tool", "pkg", genuine).Trusted || !p.AllowsCapability("acme/tool", "pkg", "desktop-app", genuine).Trusted {
t.Fatal("the recorded key must be trusted")
}
if p.Evaluate("acme/tool", "pkg", forged).Trusted || p.AllowsCapability("acme/tool", "pkg", "desktop-app", forged).Trusted {
t.Fatal("a forged key id must not satisfy a rule that records the key")
}
}
func TestPolicyPinKeysOnlyForCoveringRules(t *testing.T) {
silenceWarnings(t)
victim, _ := generateKey()
digest := "sha256:" + zeros()
id := ID(victim.Public)
p := Policy{Rules: []Rule{{Namespace: "acme/*", AllowedKeys: []KeyID{id}}}}
forged := []VerifiedSignature{VerifySignature(digest, forgedSignature(t, victim, digest))}
if p.PinKeys("evil/tool", "pkg", forged) || p.KeyFor(id) != "" {
t.Fatal("a package outside the rule's namespace must not pin the rule's key")
}
genuine := []VerifiedSignature{VerifySignature(digest, signFor(t, victim, digest))}
if !p.PinKeys("acme/tool", "pkg", genuine) || p.KeyFor(id) != KeyText(victim.Public) {
t.Fatalf("expected the covering rule's key to be pinned, got %q", p.KeyFor(id))
}
if p.Evaluate("acme/tool", "pkg", forged).Trusted {
t.Fatal("once pinned, the forged key id must be refused")
}
p.Rules = nil
p.DropUnusedKeys()
if p.Keys != nil {
t.Fatalf("expected unused keys to be dropped, got %v", p.Keys)
}
}
func TestAddKnownKeyRecordsAndChecksTheKey(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
repo := "registry.example/yetano/tool"
kp, _ := generateKey()
other, _ := generateKey()
id := ID(kp.Public)
if err := AddKnownKey(path, repo, id, "", "s"); err != nil {
t.Fatal(err)
}
if err := AddKnownKey(path, repo, id, KeyText(kp.Public), "s"); err != nil {
t.Fatal(err)
}
keys, _ := LoadKnownKeys(path)
if len(keys[repo]) != 1 || keys[repo][0].PublicKey != KeyText(kp.Public) {
t.Fatalf("expected the id-only entry to be completed, got %+v", keys[repo])
}
forged, err := ParseKeyText(forgeID(t, string(mustMarshal(t, other.Public)), kp.Public.ID()))
if err != nil {
t.Fatal(err)
}
if err := AddKnownKey(path, repo, id, KeyText(forged), "s"); err == nil {
t.Fatal("expected a different key with the same id to be refused")
}
if KnownPublicKey(keys, id) != KeyText(kp.Public) {
t.Fatal("KnownPublicKey must find the recorded key")
}
}
func TestKnownKeysRoundTrip(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
loaded, err := LoadKnownKeys(path)
if err != nil {
t.Fatal(err)
}
if len(loaded) != 0 {
t.Fatalf("expected an empty store for a missing file, got %v", loaded)
}
keys := KnownKeys{"registry.example/yetano/tool": {{KeyID: "ABCDEF1234567890", Signer: "release-bot"}}}
if err := SaveKnownKeys(path, keys); err != nil {
t.Fatal(err)
}
loaded, err = LoadKnownKeys(path)
if err != nil {
t.Fatal(err)
}
got := loaded["registry.example/yetano/tool"]
if len(got) != 1 || got[0].KeyID != "ABCDEF1234567890" || got[0].Signer != "release-bot" {
t.Fatalf("unexpected round-tripped entry: %+v", got)
}
}
func TestForgetKnownKey(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
keys := KnownKeys{"registry.example/yetano/tool": {{KeyID: "ABCDEF1234567890"}}}
if err := SaveKnownKeys(path, keys); err != nil {
t.Fatal(err)
}
removed, err := ForgetKnownKey(path, "registry.example/yetano/tool")
if err != nil {
t.Fatal(err)
}
if !removed {
t.Fatal("expected an existing entry to be reported as removed")
}
loaded, err := LoadKnownKeys(path)
if err != nil {
t.Fatal(err)
}
if len(loaded["registry.example/yetano/tool"]) != 0 {
t.Fatal("expected every accepted key to actually be gone")
}
removed, err = ForgetKnownKey(path, "registry.example/never-pinned")
if err != nil {
t.Fatal(err)
}
if removed {
t.Fatal("expected forgetting a never-pinned repository to report false, not error or succeed silently")
}
}
func TestAddKnownKey(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
// Adding to a repository with nothing accepted yet creates the entry
// -- pre-trusting a key before ever pulling anything.
if err := AddKnownKey(path, "registry.example/yetano/tool", "AAAA", "", "first-signer"); err != nil {
t.Fatal(err)
}
// A second, different key is accepted *alongside* the first, not in
// place of it -- a deliberate rotation overlap.
if err := AddKnownKey(path, "registry.example/yetano/tool", "BBBB", "", "second-signer"); err != nil {
t.Fatal(err)
}
keys, err := LoadKnownKeys(path)
if err != nil {
t.Fatal(err)
}
got := keys["registry.example/yetano/tool"]
if len(got) != 2 {
t.Fatalf("expected both keys to be accepted, got %+v", got)
}
// Adding the exact same key again is a no-op, not a duplicate entry.
if err := AddKnownKey(path, "registry.example/yetano/tool", "AAAA", "", "first-signer"); err != nil {
t.Fatal(err)
}
keys, err = LoadKnownKeys(path)
if err != nil {
t.Fatal(err)
}
if got := keys["registry.example/yetano/tool"]; len(got) != 2 {
t.Fatalf("expected re-adding an already-accepted key to be a no-op, got %+v", got)
}
}
func TestRemoveKnownKey(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
keys := KnownKeys{"registry.example/yetano/tool": {{KeyID: "AAAA"}, {KeyID: "BBBB"}}}
if err := SaveKnownKeys(path, keys); err != nil {
t.Fatal(err)
}
removed, err := RemoveKnownKey(path, "registry.example/yetano/tool", "AAAA")
if err != nil {
t.Fatal(err)
}
if !removed {
t.Fatal("expected an existing key to be reported as removed")
}
loaded, err := LoadKnownKeys(path)
if err != nil {
t.Fatal(err)
}
got := loaded["registry.example/yetano/tool"]
if len(got) != 1 || !got[0].KeyID.Is("BBBB") {
t.Fatalf("expected only the other key to remain, got %+v", got)
}
// Removing the last remaining key drops the repository entry
// entirely, rather than leaving an empty list around.
if _, err := RemoveKnownKey(path, "registry.example/yetano/tool", "BBBB"); err != nil {
t.Fatal(err)
}
loaded, err = LoadKnownKeys(path)
if err != nil {
t.Fatal(err)
}
if _, ok := loaded["registry.example/yetano/tool"]; ok {
t.Fatal("expected the repository entry to be gone once its last key was removed")
}
removed, err = RemoveKnownKey(path, "registry.example/yetano/tool", "CCCC")
if err != nil {
t.Fatal(err)
}
if removed {
t.Fatal("expected removing a key that was never accepted to report false")
}
}
func TestReconcileKnownKeyPinsOnFirstUse(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
verified := []VerifiedSignature{{Valid: true, KeyID: "AAAA", Signature: Signature{Signer: "release-bot"}}}
if err := Reconcile(path, "registry.example/yetano/tool", verified); err != nil {
t.Fatal(err)
}
keys, err := LoadKnownKeys(path)
if err != nil {
t.Fatal(err)
}
got := keys["registry.example/yetano/tool"]
if len(got) != 1 || !got[0].KeyID.Is("AAAA") || got[0].Signer != "release-bot" || got[0].AddedAt.IsZero() {
t.Fatalf("unexpected entry after first use: %+v", got)
}
}
func TestReconcileKnownKeyAcceptsMatchingKeyAgain(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
if err := SaveKnownKeys(path, KnownKeys{"registry.example/yetano/tool": {{KeyID: "AAAA"}}}); err != nil {
t.Fatal(err)
}
verified := []VerifiedSignature{{Valid: true, KeyID: "AAAA"}}
if err := Reconcile(path, "registry.example/yetano/tool", verified); err != nil {
t.Fatalf("expected the same accepted key to be accepted silently, got %v", err)
}
}
func TestReconcileKnownKeyAcceptsSecondKeyAddedViaAddKnownKey(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
// Pin the first key via normal TOFU, then deliberately add a second
// (a planned rotation overlap) via AddKnownKey.
if err := Reconcile(path, "registry.example/yetano/tool", []VerifiedSignature{{Valid: true, KeyID: "AAAA"}}); err != nil {
t.Fatal(err)
}
if err := AddKnownKey(path, "registry.example/yetano/tool", "BBBB", "", "new-signer"); err != nil {
t.Fatal(err)
}
// A pull signed only with the newly added key must now be accepted
// too, without ever having been "pinned" by reconcileKnownKey itself.
if err := Reconcile(path, "registry.example/yetano/tool", []VerifiedSignature{{Valid: true, KeyID: "BBBB"}}); err != nil {
t.Fatalf("expected the deliberately added key to be accepted, got %v", err)
}
}
func TestReconcileKnownKeyRejectsChangedKey(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
if err := SaveKnownKeys(path, KnownKeys{"registry.example/yetano/tool": {{KeyID: "AAAA"}}}); err != nil {
t.Fatal(err)
}
verified := []VerifiedSignature{{Valid: true, KeyID: "BBBB"}}
err := Reconcile(path, "registry.example/yetano/tool", verified)
if err == nil {
t.Fatal("expected a changed signing key to be rejected")
}
if !errors.Is(err, ErrRefused) {
t.Fatalf("expected ExitTrust, got %v", err)
}
// The stale entry must survive a rejection -- forgetting/removing it
// is a separate, deliberate step, never an automatic side effect of
// detecting a mismatch.
keys, err := LoadKnownKeys(path)
if err != nil {
t.Fatal(err)
}
got := keys["registry.example/yetano/tool"]
if len(got) != 1 || !got[0].KeyID.Is("AAAA") {
t.Fatalf("expected the original entry to remain in place, got %+v", got)
}
}
func TestReconcileKnownKeyIgnoresUnsignedContent(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
if err := Reconcile(path, "registry.example/yetano/tool", nil); err != nil {
t.Fatalf("expected no error for unsigned content with no prior entry, got %v", err)
}
if err := SaveKnownKeys(path, KnownKeys{"registry.example/yetano/tool": {{KeyID: "AAAA"}}}); err != nil {
t.Fatal(err)
}
// Even with an existing entry, content carrying no valid signature
// at all is a no-op: TOFU only ever compares keys it can actually
// see, it never demands a signature out of nothing.
if err := Reconcile(path, "registry.example/yetano/tool", nil); err != nil {
t.Fatalf("expected unsigned content to remain a no-op even with an existing entry, got %v", err)
}
}
func TestReconcileKnownKeyAcceptsAnyMatchingSignatureAmongSeveral(t *testing.T) {
path := filepath.Join(t.TempDir(), "known-keys.json")
if err := SaveKnownKeys(path, KnownKeys{"registry.example/yetano/tool": {{KeyID: "AAAA"}}}); err != nil {
t.Fatal(err)
}
// A package co-signed by two publishers: as long as one of the
// valid signatures matches an accepted key, it is accepted.
verified := []VerifiedSignature{{Valid: true, KeyID: "BBBB"}, {Valid: true, KeyID: "AAAA"}}
if err := Reconcile(path, "registry.example/yetano/tool", verified); err != nil {
t.Fatalf("expected a matching signature among several to be accepted, got %v", err)
}
}
func TestVerifyOneDetectsTamperedSignature(t *testing.T) {
kp, err := generateKey()
if err != nil {
t.Fatal(err)
}
digest := "sha256:" + zeros()
sig := signFor(t, kp, digest)
if v := VerifySignature(digest, sig); !v.Valid {
t.Fatalf("expected valid signature, got %+v", v)
}
other := "sha256:" + onesDigest()
if v := VerifySignature(other, sig); v.Valid {
t.Fatal("expected signature over a different digest to fail")
}
}
func TestVerifyOneRejectsUnknownAlgorithm(t *testing.T) {
sig := Signature{Algorithm: "rsa", Digest: "sha256:x"}
if v := VerifySignature("sha256:x", sig); v.Valid || v.Error == "" {
t.Fatalf("expected rejection, got %+v", v)
}
}
func TestVerifyOneMatchesMinisignKeyID(t *testing.T) {
kp, err := generateKey()
if err != nil {
t.Fatal(err)
}
digest := "sha256:" + zeros()
sig := signFor(t, kp, digest)
v := VerifySignature(digest, sig)
if !v.Valid {
t.Fatalf("expected valid signature, got %+v", v)
}
if v.KeyID != ID(kp.Public) {
t.Fatalf("expected key ID %s, got %s", ID(kp.Public), v.KeyID)
}
}
func TestPolicyEvaluate(t *testing.T) {
kp, err := generateKey()
if err != nil {
t.Fatal(err)
}
keyID := ID(kp.Public)
policy := Policy{
RequireSignatures: true,
Rules: []Rule{{Namespace: "yetano/*", Type: "plugin", AllowedKeys: []KeyID{keyID}}},
}
trusted := []VerifiedSignature{{Valid: true, KeyID: keyID}}
if d := policy.Evaluate("yetano/markdown", "plugin", trusted); !d.Trusted {
t.Fatalf("expected trust for matching namespace/type/key, got %+v", d)
}
// A namespace outside any curated rule falls back to the new
// default: any valid (TOFU-consistent, by the time Reconcile reaches
// Evaluate) signature satisfies RequireSignatures on its own.
if d := policy.Evaluate("other/tool", "plugin", trusted); !d.Trusted {
t.Fatalf("expected the new signed-is-enough default outside any curated namespace, got %+v", d)
}
// The *same* namespace, a type the rule doesn't name: the namespace
// is still curated (the rule's own Namespace matched), so this
// falls to the strict "rule covers it, no key approved" rejection,
// not the permissive out-of-namespace fallback above.
if d := policy.Evaluate("yetano/markdown", "pkg", trusted); d.Trusted {
t.Fatalf("expected no trust for a curated namespace's mismatched type, got %+v", d)
}
if d := policy.Evaluate("yetano/markdown", "plugin", nil); d.Trusted {
t.Fatalf("expected RequireSignatures to reject an unsigned package, got %+v", d)
}
}
func TestPolicyEvaluateDefaultRequiresSignatureOutsideAnyRule(t *testing.T) {
policy := Policy{RequireSignatures: true}
if d := policy.Evaluate("anything/at-all", "generic", nil); d.Trusted {
t.Fatalf("expected an unsigned package to be rejected by the new default, got %+v", d)
}
valid := []VerifiedSignature{{Valid: true, KeyID: "AAAA"}}
if d := policy.Evaluate("anything/at-all", "generic", valid); !d.Trusted {
t.Fatalf("expected a validly signed package with no curated rule to be accepted by default, got %+v", d)
}
}
func TestLoadPolicyDefaultsToRequiringSignatures(t *testing.T) {
home := t.TempDir()
p, err := LoadPolicy(DefaultPolicyPath(home))
if err != nil {
t.Fatal(err)
}
if !p.RequireSignatures {
t.Fatalf("expected a never-configured host to default to RequireSignatures: true, got %+v", p)
}
if len(p.Rules) != 0 {
t.Fatalf("expected no curated rules by default, got %+v", p.Rules)
}
// An operator who explicitly opts back into the old permissive
// behavior gets exactly that, unchanged, on every later load.
if err := SavePolicy(DefaultPolicyPath(home), Policy{RequireSignatures: false}); err != nil {
t.Fatal(err)
}
p, err = LoadPolicy(DefaultPolicyPath(home))
if err != nil {
t.Fatal(err)
}
if p.RequireSignatures {
t.Fatalf("expected an explicit require_signatures:false to be honored, got %+v", p)
}
}
func TestPolicyEvaluatePermissiveDefault(t *testing.T) {
var policy Policy
if d := policy.Evaluate("anything", "generic", nil); !d.Trusted {
t.Fatalf("expected the zero-value struct (not LoadPolicy's own default -- see its doc comment) to stay non-enforcing, got %+v", d)
}
}
func TestAllowsCapabilityNeedsAnExplicitGrant(t *testing.T) {
key := KeyID("0123456789ABCDEF")
signed := []VerifiedSignature{{KeyID: key, Valid: true}}
trustOnly := Policy{RequireSignatures: true, Rules: []Rule{{Namespace: "yetano/*", AllowedKeys: []KeyID{key}}}}
if d := trustOnly.AllowsCapability("yetano/yet", "pkg", "desktop-app", signed); d.Trusted {
t.Fatal("trusting a publisher to install must not grant a capability")
}
granted := Policy{Rules: []Rule{{Namespace: "yetano/*", Type: "pkg", AllowedKeys: []KeyID{key}, Capabilities: []string{"desktop-app"}}}}
if d := granted.AllowsCapability("yetano/yet", "pkg", "desktop-app", signed); !d.Trusted || !d.MatchedKey.Is(key) {
t.Fatalf("granted rule: %+v", d)
}
for _, tc := range []struct {
name, typ, capability string
sigs []VerifiedSignature
}{
{"yetano/yet", "plugin", "desktop-app", signed}, // other type
{"other/yet", "pkg", "desktop-app", signed}, // other namespace
{"yetano/yet", "pkg", "service", signed}, // other capability
{"yetano/yet", "pkg", "desktop-app", []VerifiedSignature{{KeyID: key, Valid: false}}}, // invalid signature
{"yetano/yet", "pkg", "desktop-app", nil}, // unsigned
} {
if d := granted.AllowsCapability(tc.name, tc.typ, tc.capability, tc.sigs); d.Trusted {
t.Errorf("%+v should not be granted", tc)
}
}
}
func signFor(t *testing.T, kp keyPair, digest string) Signature {
t.Helper()
sig, err := testSign(kp, digest)
if err != nil {
t.Fatal(err)
}
return sig
}
func zeros() string { return repeat("0", 64) }
func onesDigest() string { return repeat("1", 64) }
func repeat(s string, n int) string {
out := make([]byte, n)
for i := range out {
out[i] = s[0]
}
return string(out)
}
func TestWithdrawCapabilityKeepsTrustAndOtherKeys(t *testing.T) {
const a, b KeyID = "0123456789ABCDEF", "FEDCBA9876543210"
p := Policy{RequireSignatures: true, Rules: []Rule{
{Namespace: "yetano/yet", AllowedKeys: []KeyID{a}, Capabilities: []string{"desktop-app"}},
{Namespace: "yetano/other", AllowedKeys: []KeyID{a, b}, Capabilities: []string{"desktop-app", "service"}},
{Namespace: "tools/*", AllowedKeys: []KeyID{a}, Capabilities: []string{"desktop-app"}},
}}
if n := p.WithdrawCapability("yetano/yet", a, "desktop-app"); n != 1 {
t.Fatalf("changed %d rules, want 1", n)
}
if n := p.WithdrawCapability("yetano/other", "123456789ABCDEF", "desktop-app"); n != 1 {
t.Fatalf("changed %d rules, want 1 (key id without its leading zero)", n)
}
if n := p.WithdrawCapability("yetano/yet", a, "desktop-app"); n != 0 {
t.Fatalf("withdrawing twice changed %d rules", n)
}
want := []Rule{
{Namespace: "yetano/yet", AllowedKeys: []KeyID{a}},
{Namespace: "yetano/other", AllowedKeys: []KeyID{b}, Capabilities: []string{"desktop-app", "service"}},
{Namespace: "yetano/other", AllowedKeys: []KeyID{a}, Capabilities: []string{"service"}},
{Namespace: "tools/*", AllowedKeys: []KeyID{a}, Capabilities: []string{"desktop-app"}},
}
if !reflect.DeepEqual(p.Rules, want) {
t.Fatalf("rules = %+v\nwant %+v", p.Rules, want)
}
sig := []VerifiedSignature{{KeyID: a, Valid: true}}
if p.AllowsCapability("yetano/yet", "pkg", "desktop-app", sig).Trusted {
t.Fatal("capability should be withdrawn")
}
if !p.Evaluate("yetano/yet", "pkg", sig).Trusted || p.Evaluate("yetano/yet", "pkg", []VerifiedSignature{{KeyID: b, Valid: true}}).Trusted {
t.Fatal("the namespace should stay curated, trusting only the key")
}
}
+142
View File
@@ -0,0 +1,142 @@
package trust
import (
"encoding/json"
"errors"
"fmt"
"time"
"aead.dev/minisign"
)
// ArtifactType is the OCI artifactType of a publisher signature referrer,
// MediaType the media type of its payload blob (the same string).
const (
ArtifactType = "application/vnd.yetano.signature.v1+json"
MediaType = ArtifactType
)
// Signature is the payload of one publisher signature, pushed as an OCI 1.1
// referrer on the signed manifest's digest. PublicKey and Value are the
// exact text-format bytes minisign itself reads and writes (the same bytes
// a ".pub" file and a ".minisig" file would contain): either can be
// written to disk verbatim and verified with the standalone `minisign` CLI
// against the digest recorded in Digest.
type Signature struct {
SchemaVersion int `json:"schema_version"`
Signer string `json:"signer,omitempty"`
Algorithm string `json:"algorithm"`
PublicKey string `json:"public_key"`
Digest string `json:"digest"`
Value string `json:"signature"`
SignedAt time.Time `json:"signed_at"`
}
// VerifiedSignature is one signature referrer and the outcome of checking
// it cryptographically against the subject digest it claims to sign.
type VerifiedSignature struct {
Signature Signature
KeyID KeyID
// Key is the signing key in KeyText form and Fingerprint its
// fingerprint, set whenever the key could be decoded. A pin
// compares Key, never just KeyID (see SameKey).
Key string `json:",omitempty"`
Fingerprint string `json:",omitempty"`
Valid bool
Error string
}
// Payload is one signature referrer as fetched: its payload, or why it
// could not be fetched.
type Payload struct {
Data []byte
Err error
}
// Verify checks every signature referrer fetched for the manifest
// subjectDigest. It does not consult a trust policy: Policy.Evaluate and
// Reconcile decide whether a valid signer is trusted. Valid signatures
// that share a key ID but were made with different keys are all made
// invalid (see the comment in the code).
func Verify(subjectDigest string, payloads []Payload) []VerifiedSignature {
results := make([]VerifiedSignature, 0, len(payloads))
for _, p := range payloads {
if p.Err != nil {
results = append(results, VerifiedSignature{Error: p.Err.Error()})
continue
}
results = append(results, VerifyPayload(subjectDigest, p.Data))
}
return rejectConflictingIDs(results)
}
// rejectConflictingIDs invalidates valid signatures that share a key ID
// but were made with different keys: at most one of them can be the
// key the ID belongs to, and which one is not decidable here, so
// neither may count -- otherwise whichever comes first would decide
// what a pin records (see Reconcile).
func rejectConflictingIDs(results []VerifiedSignature) []VerifiedSignature {
for i := range results {
for j := range results {
a, b := &results[i], &results[j]
if i == j || !a.Valid || !b.Valid || !a.KeyID.Is(b.KeyID) || SameKeyText(a.Key, b.Key) {
continue
}
for _, v := range []*VerifiedSignature{a, b} {
v.Valid = false
v.Error = fmt.Sprintf("several different keys claim key id %s", v.KeyID)
}
}
}
return results
}
// VerifyPayload checks one signature referrer's payload (the JSON a
// Signature marshals to) against subjectDigest, the digest of the
// manifest it is attached to. Like Verify it does not consult a trust
// policy.
func VerifyPayload(subjectDigest string, payload []byte) VerifiedSignature {
var sig Signature
if err := json.Unmarshal(payload, &sig); err != nil {
return VerifiedSignature{Error: fmt.Sprintf("parse signature: %v", err)}
}
return VerifySignature(subjectDigest, sig)
}
// VerifySignature checks sig against subjectDigest.
func VerifySignature(subjectDigest string, sig Signature) VerifiedSignature {
if sig.Algorithm != "minisign" {
return VerifiedSignature{Signature: sig, Error: fmt.Sprintf("unsupported algorithm %q", sig.Algorithm)}
}
var pub minisign.PublicKey
if err := pub.UnmarshalText([]byte(sig.PublicKey)); err != nil {
return VerifiedSignature{Signature: sig, Error: fmt.Sprintf("decode public key: %v", err)}
}
v := VerifiedSignature{Signature: sig, KeyID: ID(pub), Key: KeyText(pub), Fingerprint: Fingerprint(pub)}
if sig.Digest != subjectDigest {
v.Error = "signature digest does not match the resolved package digest"
return v
}
if !minisign.Verify(pub, []byte(sig.Digest), []byte(sig.Value)) {
v.Error = "cryptographic verification failed"
return v
}
v.Valid = true
return v
}
// ErrRefused marks an error that refuses content on trust grounds: a
// pinned key that does not match, a policy that rejects it. Programs map
// it to their exit code for a trust refusal (errors.Is).
var ErrRefused = errors.New("refused by the trust policy")
// refused is an error that Is ErrRefused, with its own message.
type refused struct{ msg string }
func (r *refused) Error() string { return r.msg }
func (r *refused) Is(target error) bool { return target == ErrRefused }
// Refusedf is an error that Is ErrRefused.
func Refusedf(format string, args ...any) error {
return &refused{msg: fmt.Sprintf(format, args...)}
}