6 Commits
Author SHA1 Message Date
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
26 changed files with 3196 additions and 17 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
+9
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,6 +47,13 @@ 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.
- [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer,
ListState, text helpers) as the nested module
+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)
}
}
}
+8
View File
@@ -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
+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`. |
## 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,
+2 -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);
+50 -3
View File
@@ -18,6 +18,17 @@ 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);
// 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 +37,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 +79,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 +128,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 +153,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 +164,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 +217,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.
+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)
}
}
+22 -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.
+18 -1
View File
@@ -63,7 +63,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 +131,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)
+61 -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")
@@ -168,7 +171,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)
@@ -209,14 +214,17 @@ 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 wmApp:
b.runQueue()
return 0
case wmClose:
b.reportFrame()
pDestroyWindow.Call(hwnd)
return 0
case wmDestroy:
@@ -233,6 +241,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 +336,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()
+49
View File
@@ -0,0 +1,49 @@
# yetano.dev/yetano/core/trust
The verifying half of the family's publisher signatures, 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.
```text
module yetano.dev/yetano/core/trust tags: trust/v0.1.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`). Moved from `yet/internal/trust`
(2026-11-12) without changing behavior or file formats; signing, key
storage, PEM and the registry side 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)`.
## 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 { ... }
```
`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
}
+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)
}
}
+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
}
+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...)}
}