Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
586e76889c | ||
|
|
5dd4a86b68 | ||
|
|
975340b5f7 | ||
|
|
5d141c7cef | ||
|
|
e1495430c5 | ||
|
|
9395fadbf7 | ||
|
|
8513b6db4c | ||
|
|
31dbc347e8 | ||
|
|
c16b871db5 | ||
|
|
35f8b7d18a | ||
|
|
764b6f36ea | ||
|
|
71b4dda990 | ||
|
|
3d286da90d | ||
|
|
131d82642c |
No files matched your search
@@ -1,9 +1,15 @@
|
|||||||
Copyright (c) 2026 yetano. All rights reserved.
|
Copyright (c) 2026 Bjoern Kalkbrenner. All rights reserved.
|
||||||
|
|
||||||
core is proprietary software. No license is granted to use, copy,
|
This software and its documentation are proprietary
|
||||||
modify, merge, publish, distribute, sublicense or sell copies of it, in
|
(SPDX: LicenseRef-Proprietary). No license to use, copy, modify, merge,
|
||||||
whole or in part, except with the prior written permission of the
|
publish, distribute, sublicense or sell copies of this software, in whole
|
||||||
|
or in part, is granted without the prior written permission of the
|
||||||
copyright holder.
|
copyright holder.
|
||||||
|
|
||||||
The Yetano projects are closed source for now; until their license is
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
decided, this notice applies.
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
DEALINGS IN THE SOFTWARE.
|
||||||
@@ -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`
|
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
|
(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
|
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
|
```text
|
||||||
yetano.dev/yetano/core
|
yetano.dev/yetano/core
|
||||||
@@ -30,6 +32,7 @@ yetano.dev/yetano/core/configcmd
|
|||||||
yetano.dev/yetano/core/configfamily
|
yetano.dev/yetano/core/configfamily
|
||||||
yetano.dev/yetano/core/version
|
yetano.dev/yetano/core/version
|
||||||
yetano.dev/yetano/core/secretref
|
yetano.dev/yetano/core/secretref
|
||||||
|
yetano.dev/yetano/core/backup
|
||||||
yetano.dev/yetano/core/cobracmd (separate module)
|
yetano.dev/yetano/core/cobracmd (separate module)
|
||||||
|
|
||||||
yetano.dev/yetano/core/gui (own module, tags gui/vX.Y.Z)
|
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/bridge
|
||||||
yetano.dev/yetano/core/gui/window
|
yetano.dev/yetano/core/gui/window
|
||||||
yetano.dev/yetano/core/tui (own module, tags tui/vX.Y.Z)
|
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
|
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
|
||||||
@@ -321,11 +325,18 @@ docs/program-conventions.md in the meta-repository):
|
|||||||
|
|
||||||
- `completion.Run(program, tree, args, w)` prints a bash, zsh, fish or
|
- `completion.Run(program, tree, args, w)` prints a bash, zsh, fish or
|
||||||
PowerShell completion script generated from a static `completion.Tree`
|
PowerShell completion script generated from a static `completion.Tree`
|
||||||
of the program's commands.
|
of the program's commands. A level that also takes a path (a program
|
||||||
|
without subcommands, started as `<program> [path]`) adds the key
|
||||||
|
`completion.Files`; the script then completes files and directories
|
||||||
|
there besides the command names.
|
||||||
- `doctor.Report` collects the locations the program resolves
|
- `doctor.Report` collects the locations the program resolves
|
||||||
(`AddPaths(app)` adds the standard `core/paths` ones) and named checks;
|
(`AddPaths(app)` adds the standard `core/paths` ones) and named checks;
|
||||||
`Run(args, stdout, stderr)` prints a table or `--json` and returns the
|
`Run(args, stdout, stderr)` prints a table or `--json` and returns the
|
||||||
exit code (0 all good, 1 a check failed, 2 usage).
|
exit code (0 all good, 1 a check failed, 2 usage). A check may carry
|
||||||
|
an `area` (a group such as "config" or "services") and a `hint` (what
|
||||||
|
to do about it), recorded with `Add(doctor.Check{...})`; both are
|
||||||
|
omitted from the JSON when empty, and the table only gets an AREA or
|
||||||
|
HINT column when some check uses it (since v0.10.0).
|
||||||
|
|
||||||
## core/configcmd: "<program> config"
|
## core/configcmd: "<program> config"
|
||||||
|
|
||||||
@@ -353,14 +364,21 @@ os.Exit(configcmd.Run(spec, configFlag, args, os.Stdout, os.Stderr))
|
|||||||
A program's tests call `configcmd.UndocumentedKeys(FullTemplate,
|
A program's tests call `configcmd.UndocumentedKeys(FullTemplate,
|
||||||
config.Config{})` and expect nothing, so every option stays documented
|
config.Config{})` and expect nothing, so every option stays documented
|
||||||
in the full template -- that is what keeps `config upgrade` useful.
|
in the full template -- that is what keeps `config upgrade` useful.
|
||||||
|
A struct whose fields are alternatives (a secret from `env`, `file` or
|
||||||
|
`value`) implements the marker `configcmd.OneOf` (`func (SecretRef)
|
||||||
|
ConfigOneOf() {}`): one alternative in the template documents it, and
|
||||||
|
`upgrade` offers none of the others to a file that already chose one.
|
||||||
`WarnUnknown` (log at startup) and `UnknownCheck` (a doctor check)
|
`WarnUnknown` (log at startup) and `UnknownCheck` (a doctor check)
|
||||||
report options the program ignores. Taken over from
|
report options the program ignores. Taken over from
|
||||||
`yamase-core/pkg/configcmd`, which now wraps it.
|
`yamase-core/pkg/configcmd`, which now wraps it.
|
||||||
|
|
||||||
`config show [--json] [--show-secrets]` prints the configuration with
|
`config show [--json] [--show-secrets]` prints the configuration with
|
||||||
the file every value comes from (`Effective.Show`; secrets -- keys
|
the file every value comes from (`Effective.Show`; secrets -- keys
|
||||||
`secrets`, `secret`, `token`, `password` -- are redacted unless
|
`secrets`, `secret`, `token`, `password`, plus the program's own
|
||||||
`--show-secrets`, references like `env:X` stay visible), and
|
`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
|
`configcmd.Doctor(report, spec, explicit)` is the config part of a
|
||||||
`doctor` command (paths, layers, "config file found", unknown options).
|
`doctor` command (paths, layers, "config file found", unknown options).
|
||||||
|
|
||||||
@@ -448,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
|
Tagged as plain semver on this repository (`v0.1.0`, ...), per the
|
||||||
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
|
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
|
||||||
force-moved to a different commit. The nested `gui` and `tui` modules
|
force-moved to a different commit. The nested `gui`, `tui` and `trust`
|
||||||
have their own prefixed tags (`gui/v0.1.0`, `tui/v0.1.0`, ...); a change
|
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.
|
there needs no main-module tag and vice versa.
|
||||||
|
|
||||||
## core/secretref
|
## core/secretref
|
||||||
@@ -475,6 +494,33 @@ plain values it accepted before checks `IsReference` and treats anything
|
|||||||
else as a literal. Used by yavebu,
|
else as a literal. Used by yavebu,
|
||||||
yacry and yadenes.
|
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)
|
## core/gui (separate module)
|
||||||
|
|
||||||
`yetano.dev/yetano/core/gui` is the native WebView host for desktop
|
`yetano.dev/yetano/core/gui` is the native WebView host for desktop
|
||||||
@@ -493,3 +539,7 @@ pitfalls and the yet-gui migration: [gui/README.md](gui/README.md).
|
|||||||
`slate`/`dialog`/`midnight` and their lipgloss styles, `Paint`/`Outer`,
|
`slate`/`dialog`/`midnight` and their lipgloss styles, `Paint`/`Outer`,
|
||||||
`ListState` and text helpers. No app shell or screens yet -- see
|
`ListState` and text helpers. No app shell or screens yet -- see
|
||||||
[tui/README.md](tui/README.md), which also has the migration steps.
|
[tui/README.md](tui/README.md), which also has the migration steps.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Proprietary (`LicenseRef-Proprietary`), see [LICENSE](LICENSE).
|
||||||
@@ -32,6 +32,14 @@ speculatively.
|
|||||||
- [x] `manual` (v0.2.0), `completion`, `doctor` (v0.3.0), `secretref`
|
- [x] `manual` (v0.2.0), `completion`, `doctor` (v0.3.0), `secretref`
|
||||||
(v0.4.0), `configcmd` and `version` (v0.5.0) -- see
|
(v0.4.0), `configcmd` and `version` (v0.5.0) -- see
|
||||||
docs/program-conventions.md in the meta-repository.
|
docs/program-conventions.md in the meta-repository.
|
||||||
|
- [x] `configcmd.OneOf`: `UndocumentedKeys` and `upgrade` know structs
|
||||||
|
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>`
|
- [x] macOS CLI/Service system-scope `RuntimeDir` is `/var/run/<app>`
|
||||||
(was `/run/<app>`, which macOS does not have) -- v0.5.0.
|
(was `/run/<app>`, which macOS does not have) -- v0.5.0.
|
||||||
- [x] `core/gui`: the native WebView host from
|
- [x] `core/gui`: the native WebView host from
|
||||||
@@ -39,7 +47,36 @@ speculatively.
|
|||||||
`yetano.dev/yetano/core/gui` (`gui/v0.1.0`). The prototype uses it.
|
`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`
|
- [ ] Move yet-gui off its copy in `yet/gui/internal` onto `core/gui`
|
||||||
(steps in [gui/README.md](gui/README.md)).
|
(steps in [gui/README.md](gui/README.md)).
|
||||||
|
- [x] `core/gui` (macOS): the web view accepts the first mouse click in
|
||||||
|
an inactive window (`YTWebView`, `acceptsFirstMouse:` YES;
|
||||||
|
`gui/v0.2.0`, 2026-11-15) -- before, the first click only activated
|
||||||
|
the window, so a dialog shown at start looked dead (yanks).
|
||||||
|
- [x] `core/gui`: `window.Options.FrameFile` keeps the window's position,
|
||||||
|
size and maximized state across starts (macOS and Windows;
|
||||||
|
`gui/v0.2.0`, 2026-11-15).
|
||||||
- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md.
|
- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md.
|
||||||
|
- [ ] `core/gui`: resident app with a prewarmed WebView, for a start
|
||||||
|
under 300 ms (proposal from yamc, 2026-11-29, for its H-STARTUP;
|
||||||
|
see yamc `docs/spec/gui-comparison.md`). Measured on macOS (Apple
|
||||||
|
Silicon, warm): NSApp setup ~65 ms, WKWebView init ~45 ms, window
|
||||||
|
~25 ms, then ~190 ms until the web content process asks for the
|
||||||
|
first resource and ~150 ms for WebKit's first paint -- ~550 ms to
|
||||||
|
the first frame, ~340 ms of it WebKit's own, which only advances
|
||||||
|
while the main run loop runs. Tried without effect (yamc,
|
||||||
|
2026-11-29): `loadRequest` right after the WKWebView exists
|
||||||
|
(before the window is built, also before `finishLaunching`),
|
||||||
|
spinning the run loop after it, building the app's state in
|
||||||
|
parallel -- the first request still comes ~200 ms after the main
|
||||||
|
thread is free. So a fresh process stays at ~500 ms or more.
|
||||||
|
Proposal: keep the process alive after its last window (macOS: a
|
||||||
|
normal Dock app; Windows: a background process), hold one hidden
|
||||||
|
WebView with the page loaded in reserve, and let a new start hand
|
||||||
|
its arguments to the running instance (single instance, e.g. a
|
||||||
|
socket in the runtime dir), which shows the reserve window and
|
||||||
|
prepares the next. Needs several windows per process, a
|
||||||
|
reserve-window API, and the same on WebView2. The first start
|
||||||
|
stays at ~550 ms. Only worth it once a program needs it (yamc's
|
||||||
|
Gio-vs-WebView choice is still open).
|
||||||
- [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer,
|
- [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer,
|
||||||
ListState, text helpers) as the nested module
|
ListState, text helpers) as the nested module
|
||||||
`yetano.dev/yetano/core/tui` (`tui/v0.1.0`).
|
`yetano.dev/yetano/core/tui` (`tui/v0.1.0`).
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,7 +5,12 @@
|
|||||||
//
|
//
|
||||||
// The scripts are deliberately simple, word-based completion of command
|
// The scripts are deliberately simple, word-based completion of command
|
||||||
// and subcommand names (not flag-aware): they join the words typed so far
|
// and subcommand names (not flag-aware): they join the words typed so far
|
||||||
// into a prefix and look up what may follow it.
|
// into a prefix and look up what may follow it. A level that also takes a
|
||||||
|
// file or directory path (a program without subcommands that is started
|
||||||
|
// as "<program> [path]") adds the Files key; the shell then completes
|
||||||
|
// paths there too:
|
||||||
|
//
|
||||||
|
// var tree = completion.Tree{completion.Files: nil, "manual": nil, ...}
|
||||||
//
|
//
|
||||||
// var tree = completion.Tree{
|
// var tree = completion.Tree{
|
||||||
// "serve": nil,
|
// "serve": nil,
|
||||||
@@ -41,6 +46,10 @@ func Leaf(names ...string) Tree {
|
|||||||
return t
|
return t
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Files is a Tree key, not a command: the level it is in also completes
|
||||||
|
// file and directory paths. Its value is ignored.
|
||||||
|
const Files = "<files>"
|
||||||
|
|
||||||
// Shells are the supported shells, in the order help texts list them.
|
// Shells are the supported shells, in the order help texts list them.
|
||||||
var Shells = []string{"bash", "zsh", "fish", "powershell"}
|
var Shells = []string{"bash", "zsh", "fish", "powershell"}
|
||||||
|
|
||||||
@@ -53,6 +62,7 @@ var safeWord = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:+-]*$`)
|
|||||||
type entry struct {
|
type entry struct {
|
||||||
prefix string
|
prefix string
|
||||||
words []string
|
words []string
|
||||||
|
files bool // paths complete here too (Files)
|
||||||
}
|
}
|
||||||
|
|
||||||
func flatten(tree Tree) ([]entry, error) {
|
func flatten(tree Tree) ([]entry, error) {
|
||||||
@@ -60,14 +70,19 @@ func flatten(tree Tree) ([]entry, error) {
|
|||||||
var walk func(prefix string, t Tree) error
|
var walk func(prefix string, t Tree) error
|
||||||
walk = func(prefix string, t Tree) error {
|
walk = func(prefix string, t Tree) error {
|
||||||
names := make([]string, 0, len(t))
|
names := make([]string, 0, len(t))
|
||||||
|
files := false
|
||||||
for n := range t {
|
for n := range t {
|
||||||
|
if n == Files {
|
||||||
|
files = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
if !safeWord.MatchString(n) {
|
if !safeWord.MatchString(n) {
|
||||||
return fmt.Errorf("completion: command name %q is not a plain word", n)
|
return fmt.Errorf("completion: command name %q is not a plain word", n)
|
||||||
}
|
}
|
||||||
names = append(names, n)
|
names = append(names, n)
|
||||||
}
|
}
|
||||||
sort.Strings(names)
|
sort.Strings(names)
|
||||||
out = append(out, entry{prefix, names})
|
out = append(out, entry{prefix, names, files})
|
||||||
for _, n := range names {
|
for _, n := range names {
|
||||||
if sub := t[n]; len(sub) > 0 {
|
if sub := t[n]; len(sub) > 0 {
|
||||||
p := n
|
p := n
|
||||||
@@ -84,6 +99,15 @@ func flatten(tree Tree) ([]entry, error) {
|
|||||||
return out, walk("", tree)
|
return out, walk("", tree)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func anyFiles(entries []entry) bool {
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.files {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// Script returns the completion script for shell.
|
// Script returns the completion script for shell.
|
||||||
func Script(program, shell string, tree Tree) (string, error) {
|
func Script(program, shell string, tree Tree) (string, error) {
|
||||||
if !safeWord.MatchString(program) {
|
if !safeWord.MatchString(program) {
|
||||||
@@ -100,16 +124,30 @@ func Script(program, shell string, tree Tree) (string, error) {
|
|||||||
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", program, program)
|
fmt.Fprintf(&b, "# %s bash completion. Install with:\n# eval \"$(%s completion bash)\" (bash 3.2 on macOS cannot source <(...))\n", program, program)
|
||||||
fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn)
|
fmt.Fprintf(&b, "%s() {\n local cur prefix\n cur=\"${COMP_WORDS[COMP_CWORD]}\"\n prefix=\"${COMP_WORDS[*]:1:COMP_CWORD-1}\"\n case \"$prefix\" in\n", fn)
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\")); return ;;\n", e.prefix, strings.Join(e.words, " "))
|
fmt.Fprintf(&b, " %q) COMPREPLY=($(compgen -W %q -- \"$cur\"))", e.prefix, strings.Join(e.words, " "))
|
||||||
|
if e.files {
|
||||||
|
// One path per line, so names with spaces stay whole;
|
||||||
|
// compopt (bash 4+) adds the trailing "/" and quoting.
|
||||||
|
b.WriteString("\n local IFS=$'\\n'; COMPREPLY+=($(compgen -f -- \"$cur\")); compopt -o filenames 2>/dev/null")
|
||||||
|
}
|
||||||
|
b.WriteString("; return ;;\n")
|
||||||
}
|
}
|
||||||
fmt.Fprintf(&b, " *) COMPREPLY=() ;;\n esac\n}\ncomplete -F %s %s\n", fn, program)
|
fmt.Fprintf(&b, " *) COMPREPLY=() ;;\n esac\n}\ncomplete -F %s %s\n", fn, program)
|
||||||
case "zsh":
|
case "zsh":
|
||||||
fmt.Fprintf(&b, "#compdef %s\n# %s zsh completion. Install with:\n# source <(%s completion zsh)\n", program, program, program)
|
fmt.Fprintf(&b, "#compdef %s\n# %s zsh completion. Install with:\n# source <(%s completion zsh)\n", program, program, program)
|
||||||
fmt.Fprintf(&b, "%s() {\n local prefix=\"${words[2,CURRENT-1]}\"\n local -a completions\n case \"$prefix\" in\n", fn)
|
fmt.Fprintf(&b, "%s() {\n local prefix=\"${words[2,CURRENT-1]}\" files=0\n local -a completions\n case \"$prefix\" in\n", fn)
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
fmt.Fprintf(&b, " %q) completions=(%s) ;;\n", e.prefix, strings.Join(e.words, " "))
|
f := ""
|
||||||
|
if e.files {
|
||||||
|
f = "; files=1"
|
||||||
}
|
}
|
||||||
fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n}\n")
|
fmt.Fprintf(&b, " %q) completions=(%s)%s ;;\n", e.prefix, strings.Join(e.words, " "), f)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(&b, " *) completions=() ;;\n esac\n _describe 'command' completions\n")
|
||||||
|
if anyFiles(entries) {
|
||||||
|
b.WriteString(" (( files )) && _files\n")
|
||||||
|
}
|
||||||
|
b.WriteString("}\n")
|
||||||
fmt.Fprintf(&b, "if (( $+functions[compdef] )); then\n compdef %s %s\nelse\n echo '%s: zsh completion needs \"autoload -U compinit && compinit\" run first (e.g. in ~/.zshrc)' >&2\nfi\n", fn, program, program)
|
fmt.Fprintf(&b, "if (( $+functions[compdef] )); then\n compdef %s %s\nelse\n echo '%s: zsh completion needs \"autoload -U compinit && compinit\" run first (e.g. in ~/.zshrc)' >&2\nfi\n", fn, program, program)
|
||||||
case "fish":
|
case "fish":
|
||||||
fmt.Fprintf(&b, "# %s fish completion. Install with:\n# %s completion fish | source\n", program, program)
|
fmt.Fprintf(&b, "# %s fish completion. Install with:\n# %s completion fish | source\n", program, program)
|
||||||
@@ -125,6 +163,9 @@ func Script(program, shell string, tree Tree) (string, error) {
|
|||||||
quoted[i] = fmt.Sprintf("%q", w)
|
quoted[i] = fmt.Sprintf("%q", w)
|
||||||
}
|
}
|
||||||
fmt.Fprintf(&b, " printf '%%s\\n' %s\n", strings.Join(quoted, " "))
|
fmt.Fprintf(&b, " printf '%%s\\n' %s\n", strings.Join(quoted, " "))
|
||||||
|
if e.files {
|
||||||
|
b.WriteString(" __fish_complete_path (commandline -ct)\n")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
fmt.Fprintf(&b, " end\nend\ncomplete -c %s -f -a '(%s)'\n", program, fn)
|
fmt.Fprintf(&b, " end\nend\ncomplete -c %s -f -a '(%s)'\n", program, fn)
|
||||||
case "powershell":
|
case "powershell":
|
||||||
@@ -143,7 +184,18 @@ func Script(program, shell string, tree Tree) (string, error) {
|
|||||||
}
|
}
|
||||||
b.WriteString(" default { @() }\n }\n")
|
b.WriteString(" default { @() }\n }\n")
|
||||||
b.WriteString(" $candidates | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n")
|
b.WriteString(" $candidates | Where-Object { $_ -like \"$wordToComplete*\" } | ForEach-Object {\n")
|
||||||
b.WriteString(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n}\n")
|
b.WriteString(" [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)\n }\n")
|
||||||
|
var filePrefixes []string
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.files {
|
||||||
|
filePrefixes = append(filePrefixes, "'"+e.prefix+"'")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(filePrefixes) > 0 {
|
||||||
|
fmt.Fprintf(&b, " if (@(%s) -contains $prefix) {\n", strings.Join(filePrefixes, ", "))
|
||||||
|
b.WriteString(" [System.Management.Automation.CompletionCompleters]::CompleteFilename($wordToComplete)\n }\n")
|
||||||
|
}
|
||||||
|
b.WriteString("}\n")
|
||||||
default:
|
default:
|
||||||
return "", fmt.Errorf("%w (unknown shell %q)", ErrUsage, shell)
|
return "", fmt.Errorf("%w (unknown shell %q)", ErrUsage, shell)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ package completion
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
@@ -48,3 +51,66 @@ func TestBashCompletes(t *testing.T) {
|
|||||||
t.Fatalf("bash completion: %v %q", err, out)
|
t.Fatalf("bash completion: %v %q", err, out)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A program without subcommands takes a path as its first argument.
|
||||||
|
var pathTree = Tree{
|
||||||
|
Files: nil,
|
||||||
|
"manual": nil,
|
||||||
|
"config": Leaf("path"),
|
||||||
|
"completion": Leaf(Shells...),
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestScriptsWithFiles(t *testing.T) {
|
||||||
|
want := map[string]string{
|
||||||
|
"bash": "compgen -f",
|
||||||
|
"zsh": "_files",
|
||||||
|
"fish": "__fish_complete_path",
|
||||||
|
"powershell": "CompleteFilename",
|
||||||
|
}
|
||||||
|
for _, shell := range Shells {
|
||||||
|
s, err := Script("tool", shell, pathTree)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(s, want[shell]) {
|
||||||
|
t.Errorf("%s script lacks path completion %q", shell, want[shell])
|
||||||
|
}
|
||||||
|
if strings.Contains(s, Files) {
|
||||||
|
t.Errorf("%s script offers the marker %q as a word", shell, Files)
|
||||||
|
}
|
||||||
|
// Without the marker no level completes paths.
|
||||||
|
s, _ = Script("tool", shell, tree)
|
||||||
|
if strings.Contains(s, want[shell]) {
|
||||||
|
t.Errorf("%s script completes paths without Files", shell)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestBashCompletesPaths runs the generated bash function in a directory
|
||||||
|
// with a file whose name has a space, when bash is there.
|
||||||
|
func TestBashCompletesPaths(t *testing.T) {
|
||||||
|
if _, err := exec.LookPath("bash"); err != nil {
|
||||||
|
t.Skip("no bash")
|
||||||
|
}
|
||||||
|
dir := t.TempDir()
|
||||||
|
for _, name := range []string{"my notes.txt", "manuscript"} {
|
||||||
|
if err := os.WriteFile(filepath.Join(dir, name), nil, 0o600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s, _ := Script("tool", "bash", pathTree)
|
||||||
|
for cword, want := range map[string]string{
|
||||||
|
"m": "manual|manuscript|my notes.txt", // command names and paths
|
||||||
|
"config p": "path", // a level without Files: no paths
|
||||||
|
} {
|
||||||
|
words := strings.Fields("tool " + cword)
|
||||||
|
script := s + "\nCOMP_WORDS=(" + strings.Join(words, " ") + "); COMP_CWORD=" +
|
||||||
|
strconv.Itoa(len(words)-1) + "; _tool_complete; printf '%s\\n' \"${COMPREPLY[@]}\" | sort | paste -sd '|' -"
|
||||||
|
cmd := exec.Command("bash", "-c", script)
|
||||||
|
cmd.Dir = dir
|
||||||
|
out, err := cmd.CombinedOutput()
|
||||||
|
if err != nil || strings.TrimSpace(string(out)) != want {
|
||||||
|
t.Errorf("bash completion of %q: %v %q, want %q", cword, err, out, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
-3
@@ -2,7 +2,7 @@
|
|||||||
// Yetano program standard (docs/program-conventions.md and ADR-0012 in
|
// Yetano program standard (docs/program-conventions.md and ADR-0012 in
|
||||||
// the yetano meta-repository):
|
// the yetano meta-repository):
|
||||||
//
|
//
|
||||||
// <program> config create [--minimal|--full] [--force] [--output <file>]
|
// <program> config create [--minimal|--full] [--force] [--output <file>|-]
|
||||||
// <program> config validate
|
// <program> config validate
|
||||||
// <program> config upgrade [--write]
|
// <program> config upgrade [--write]
|
||||||
// <program> config path
|
// <program> config path
|
||||||
@@ -116,6 +116,14 @@ type Spec struct {
|
|||||||
// options (see Missing). Optional.
|
// options (see Missing). Optional.
|
||||||
Schema any
|
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
|
// Options are passed through to core/config; tests use them to
|
||||||
// inject a platform, environment, root and working directory.
|
// inject a platform, environment, root and working directory.
|
||||||
Options []coreconfig.Option
|
Options []coreconfig.Option
|
||||||
@@ -193,7 +201,7 @@ func usage(s Spec, w io.Writer) {
|
|||||||
}
|
}
|
||||||
fmt.Fprintf(w, `usage: %[1]s config <subcommand> [--config <file>]
|
fmt.Fprintf(w, `usage: %[1]s config <subcommand> [--config <file>]
|
||||||
|
|
||||||
create [--minimal|--full] [--force] [--output <file>]
|
create [--minimal|--full] [--force] [--output <file>|-]
|
||||||
write a commented starter configuration (minimal by default)
|
write a commented starter configuration (minimal by default)
|
||||||
validate check the configuration file the program would use
|
validate check the configuration file the program would use
|
||||||
upgrade [--write]
|
upgrade [--write]
|
||||||
@@ -334,7 +342,7 @@ func (s Spec) create(explicit string, args []string, stdout, stderr io.Writer) i
|
|||||||
minimal := fs.Bool("minimal", false, "write the minimal starter configuration (default)")
|
minimal := fs.Bool("minimal", false, "write the minimal starter configuration (default)")
|
||||||
full := fs.Bool("full", false, "write the fully commented reference configuration")
|
full := fs.Bool("full", false, "write the fully commented reference configuration")
|
||||||
force := fs.Bool("force", false, "overwrite the file if it already exists")
|
force := fs.Bool("force", false, "overwrite the file if it already exists")
|
||||||
output := fs.String("output", "", "file to write (default: --config, else the file the program would use, else "+s.filename()+" in the user config directory -- the system one as root)")
|
output := fs.String("output", "", "file to write, - for stdout (default: --config, else the file the program would use, else "+s.filename()+" in the user config directory -- the system one as root)")
|
||||||
if code := parse(fs, args); code >= 0 {
|
if code := parse(fs, args); code >= 0 {
|
||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
@@ -348,6 +356,10 @@ func (s Spec) create(explicit string, args []string, stdout, stderr io.Writer) i
|
|||||||
}
|
}
|
||||||
|
|
||||||
path := *output
|
path := *output
|
||||||
|
if path == "-" { // the template on stdout, nothing written
|
||||||
|
io.WriteString(stdout, content)
|
||||||
|
return ExitOK
|
||||||
|
}
|
||||||
if path == "" {
|
if path == "" {
|
||||||
var err error
|
var err error
|
||||||
if path, err = s.defaultCreatePath(explicit); err != nil {
|
if path, err = s.defaultCreatePath(explicit); err != nil {
|
||||||
|
|||||||
@@ -190,6 +190,27 @@ func TestCreateExplicitAndOutput(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --output - prints the template and writes no file (not one named "-").
|
||||||
|
func TestCreateOutputStdout(t *testing.T) {
|
||||||
|
root := t.TempDir()
|
||||||
|
s := testSpec(root)
|
||||||
|
work := filepath.Join(root, "work")
|
||||||
|
if err := os.MkdirAll(work, 0o755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Chdir(work)
|
||||||
|
code, out, errOut := run(t, s, "", "create", "--full", "--output", "-")
|
||||||
|
if code != ExitOK || out != fullTemplate || errOut != "" {
|
||||||
|
t.Fatalf("create --output -: exit %d, stdout %q, stderr %q", code, out, errOut)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(filepath.Join(work, "-")); !errors.Is(err, os.ErrNotExist) {
|
||||||
|
t.Errorf("create --output - wrote a file named \"-\": %v", err)
|
||||||
|
}
|
||||||
|
if code, out, _ := run(t, s, "", "create", "--output=-"); code != ExitOK || out != minimalTemplate {
|
||||||
|
t.Errorf("create --output=-: exit %d, stdout %q", code, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestValidate(t *testing.T) {
|
func TestValidate(t *testing.T) {
|
||||||
root := t.TempDir()
|
root := t.TempDir()
|
||||||
s := testSpec(root)
|
s := testSpec(root)
|
||||||
@@ -427,3 +448,74 @@ func TestFilenameAndFind(t *testing.T) {
|
|||||||
t.Fatalf("Find: %v, %v", l.Path, err)
|
t.Fatalf("Find: %v, %v", l.Path, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type secretRef struct {
|
||||||
|
Env string `yaml:"env,omitempty"`
|
||||||
|
File string `yaml:"file,omitempty"`
|
||||||
|
Value string `yaml:"value,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (secretRef) ConfigOneOf() {}
|
||||||
|
|
||||||
|
type oneOfSchema struct {
|
||||||
|
Auth struct {
|
||||||
|
Type string `yaml:"type"`
|
||||||
|
Token secretRef `yaml:"token"`
|
||||||
|
Email *secretRef `yaml:"email"`
|
||||||
|
} `yaml:"auth"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const oneOfTemplate = `auth:
|
||||||
|
type: bearer
|
||||||
|
# exactly one of env, file or value
|
||||||
|
token:
|
||||||
|
env: TOKEN
|
||||||
|
email:
|
||||||
|
file: /run/secrets/email
|
||||||
|
`
|
||||||
|
|
||||||
|
func TestUndocumentedKeysOneOf(t *testing.T) {
|
||||||
|
got, err := UndocumentedKeys(oneOfTemplate, oneOfSchema{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(got) != 0 {
|
||||||
|
t.Errorf("UndocumentedKeys(one alternative set) = %v, want none", got)
|
||||||
|
}
|
||||||
|
// No alternative in the template: every one is undocumented.
|
||||||
|
got, _ = UndocumentedKeys("auth:\n type: bearer\n token: {}\n email:\n env: E\n", oneOfSchema{})
|
||||||
|
if want := "auth.token.env auth.token.file auth.token.value"; strings.Join(got, " ") != want {
|
||||||
|
t.Errorf("UndocumentedKeys(empty token) = %v, want %s", got, want)
|
||||||
|
}
|
||||||
|
// A struct without the marker still needs every field.
|
||||||
|
type plain struct {
|
||||||
|
Token struct {
|
||||||
|
Env string `yaml:"env"`
|
||||||
|
File string `yaml:"file"`
|
||||||
|
} `yaml:"token"`
|
||||||
|
}
|
||||||
|
got, _ = UndocumentedKeys("token:\n env: X\n", plain{})
|
||||||
|
if want := "token.file"; strings.Join(got, " ") != want {
|
||||||
|
t.Errorf("UndocumentedKeys(plain) = %v, want %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMissingOneOfOffersNoOtherAlternative(t *testing.T) {
|
||||||
|
file := "auth:\n type: bearer\n token:\n file: /run/secrets/token\n email:\n value: me@example.org\n"
|
||||||
|
got, err := Missing([]byte(file), []byte(oneOfTemplate), oneOfSchema{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(got) != 0 {
|
||||||
|
t.Errorf("Missing() = %v, want nothing (each secret has its alternative)", got)
|
||||||
|
}
|
||||||
|
// Without the schema the template's alternative is offered as before.
|
||||||
|
got, _ = Missing([]byte(file), []byte(oneOfTemplate), nil)
|
||||||
|
var keys []string
|
||||||
|
for _, a := range got {
|
||||||
|
keys = append(keys, a.Key)
|
||||||
|
}
|
||||||
|
if want := "auth.token.env auth.email.file"; strings.Join(keys, " ") != want {
|
||||||
|
t.Errorf("Missing(no schema) = %v, want %s", keys, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -73,6 +73,9 @@ type Effective struct {
|
|||||||
// Loader is the Layered loader's own value for this configuration
|
// Loader is the Layered loader's own value for this configuration
|
||||||
// (e.g. its richer layer list), for its Unknown hook; nil otherwise.
|
// (e.g. its richer layer list), for its Unknown hook; nil otherwise.
|
||||||
Loader any
|
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.
|
// 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
|
return ExitProblem
|
||||||
}
|
}
|
||||||
used := s.usedFunc()
|
used := s.usedFunc()
|
||||||
|
e.SecretKeys = s.SecretKeys
|
||||||
if err := e.Show(stdout, used, *asJSON, *secrets); err != nil {
|
if err := e.Show(stdout, used, *asJSON, *secrets); err != nil {
|
||||||
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
|
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
|
||||||
return ExitProblem
|
return ExitProblem
|
||||||
|
|||||||
@@ -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 {
|
type inlineBase struct {
|
||||||
Enabled bool `yaml:"enabled"`
|
Enabled bool `yaml:"enabled"`
|
||||||
}
|
}
|
||||||
@@ -211,3 +248,53 @@ func statExistsForTest(path string) bool {
|
|||||||
_, err := os.Stat(path)
|
_, err := os.Stat(path)
|
||||||
return err == nil
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+49
-3
@@ -28,9 +28,12 @@ const DefaultOrigin = "default"
|
|||||||
// Values returns every leaf of e, sorted by key, with its origin.
|
// Values returns every leaf of e, sorted by key, with its origin.
|
||||||
// used reports whether the program reads a key (nil: every key); a
|
// used reports whether the program reads a key (nil: every key); a
|
||||||
// default it does not read is left out. Secret values (keys secrets,
|
// 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:,
|
// 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 {
|
func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value {
|
||||||
var out []Value
|
var out []Value
|
||||||
walkLeaves("", e.Merged, func(key string, v any) {
|
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 {
|
if !u && source == DefaultOrigin {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if !showSecrets && isSecretKey(key) {
|
if !showSecrets {
|
||||||
|
if e.isSecret(key) {
|
||||||
v = redact(v)
|
v = redact(v)
|
||||||
|
} else {
|
||||||
|
v = e.redactWithin(key, v)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
out = append(out, Value{Key: key, Value: v, Source: source, Used: u})
|
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:]] }
|
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
|
// redact replaces secret values, keeping references that only say where
|
||||||
// the secret is.
|
// the secret is.
|
||||||
func redact(v any) any {
|
func redact(v any) any {
|
||||||
|
|||||||
+35
-4
@@ -82,6 +82,9 @@ func docMapping(doc *yaml.Node) *yaml.Node {
|
|||||||
// of file).
|
// of file).
|
||||||
func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent, from, to, afterLine int, lines []string) []Addition {
|
func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent, from, to, afterLine int, lines []string) []Addition {
|
||||||
var out []Addition
|
var out []Addition
|
||||||
|
// A file that chose one alternative of a OneOf struct gets none of
|
||||||
|
// the template's others offered.
|
||||||
|
chosen := isOneOf(t) && len(fmap.Content) > 0
|
||||||
for i := 0; i+1 < len(tmap.Content); i += 2 {
|
for i := 0; i+1 < len(tmap.Content); i += 2 {
|
||||||
tkey, tval := tmap.Content[i], tmap.Content[i+1]
|
tkey, tval := tmap.Content[i], tmap.Content[i+1]
|
||||||
sub := append(append([]string(nil), path...), tkey.Value)
|
sub := append(append([]string(nil), path...), tkey.Value)
|
||||||
@@ -105,7 +108,7 @@ func compare(path []string, t reflect.Type, fmap, tmap *yaml.Node, childIndent,
|
|||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if mentioned(lines, from, to, childIndent, tkey.Value) {
|
if chosen || mentioned(lines, from, to, childIndent, tkey.Value) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
out = append(out, Addition{
|
out = append(out, Addition{
|
||||||
@@ -226,12 +229,36 @@ func Apply(raw []byte, adds []Addition) []byte {
|
|||||||
return []byte(out)
|
return []byte(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// OneOf marks a configuration struct whose fields are alternatives, of
|
||||||
|
// which a file sets exactly one -- a secret taken from env, file or
|
||||||
|
// value, say. The method itself does nothing; implementing it is the
|
||||||
|
// marker:
|
||||||
|
//
|
||||||
|
// func (SecretRef) ConfigOneOf() {}
|
||||||
|
//
|
||||||
|
// UndocumentedKeys then accepts a template that sets one alternative
|
||||||
|
// (and explains the others in comments), and Missing offers none of the
|
||||||
|
// others to a file that already chose one.
|
||||||
|
type OneOf interface{ ConfigOneOf() }
|
||||||
|
|
||||||
|
var oneOfType = reflect.TypeOf((*OneOf)(nil)).Elem()
|
||||||
|
|
||||||
|
// isOneOf reports whether t (or a pointer to it) implements OneOf.
|
||||||
|
func isOneOf(t reflect.Type) bool {
|
||||||
|
if t == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
t = deref(t)
|
||||||
|
return t.Implements(oneOfType) || reflect.PointerTo(t).Implements(oneOfType)
|
||||||
|
}
|
||||||
|
|
||||||
// UndocumentedKeys returns the dotted YAML paths of schema (a struct
|
// UndocumentedKeys returns the dotted YAML paths of schema (a struct
|
||||||
// value, e.g. config.Config{}) that the template does not contain --
|
// value, e.g. config.Config{}) that the template does not contain --
|
||||||
// neither as a key nor, for a list of structs, in the list's first
|
// neither as a key nor, for a list of structs, in the list's first
|
||||||
// item. A program's tests call it with its full template so that a new
|
// item. A struct implementing OneOf counts as documented when the
|
||||||
// option cannot be added without documenting it, which is what keeps
|
// template sets any one of its fields. A program's tests call it with
|
||||||
// "config upgrade" useful.
|
// its full template so that a new option cannot be added without
|
||||||
|
// documenting it, which is what keeps "config upgrade" useful.
|
||||||
func UndocumentedKeys(template string, schema any) ([]string, error) {
|
func UndocumentedKeys(template string, schema any) ([]string, error) {
|
||||||
var doc yaml.Node
|
var doc yaml.Node
|
||||||
if err := yaml.Unmarshal([]byte(template), &doc); err != nil {
|
if err := yaml.Unmarshal([]byte(template), &doc); err != nil {
|
||||||
@@ -251,6 +278,8 @@ func walkSchema(t reflect.Type, m *yaml.Node, path []string, out *[]string) {
|
|||||||
if t.Kind() != reflect.Struct {
|
if t.Kind() != reflect.Struct {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// One alternative set: the others are not missing.
|
||||||
|
chosen := isOneOf(t) && len(m.Content) > 0
|
||||||
for i := range t.NumField() {
|
for i := range t.NumField() {
|
||||||
f := t.Field(i)
|
f := t.Field(i)
|
||||||
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
|
name, opts, _ := strings.Cut(f.Tag.Get("yaml"), ",")
|
||||||
@@ -268,7 +297,9 @@ func walkSchema(t reflect.Type, m *yaml.Node, path []string, out *[]string) {
|
|||||||
sub := append(append([]string(nil), path...), name)
|
sub := append(append([]string(nil), path...), name)
|
||||||
_, val := lookup(m, name)
|
_, val := lookup(m, name)
|
||||||
if val == nil {
|
if val == nil {
|
||||||
|
if !chosen {
|
||||||
*out = append(*out, strings.Join(sub, "."))
|
*out = append(*out, strings.Join(sub, "."))
|
||||||
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
ft := deref(f.Type)
|
ft := deref(f.Type)
|
||||||
|
|||||||
+31
-3
@@ -36,11 +36,16 @@ type Path struct {
|
|||||||
Error string `json:"error,omitempty"`
|
Error string `json:"error,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check is one named check.
|
// Check is one named check. Area (a group such as "config" or
|
||||||
|
// "services") and Hint (what to do about a failed check) are optional
|
||||||
|
// and omitted from the JSON form when empty, so a report without them
|
||||||
|
// looks exactly as before they existed.
|
||||||
type Check struct {
|
type Check struct {
|
||||||
|
Area string `json:"area,omitempty"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
OK bool `json:"ok"`
|
OK bool `json:"ok"`
|
||||||
Note string `json:"note,omitempty"`
|
Note string `json:"note,omitempty"`
|
||||||
|
Hint string `json:"hint,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Report is "<program> doctor --json"'s output.
|
// Report is "<program> doctor --json"'s output.
|
||||||
@@ -110,6 +115,12 @@ func (r *Report) Check(name string, ok bool, note string) {
|
|||||||
r.Checks = append(r.Checks, Check{Name: name, OK: ok, Note: note})
|
r.Checks = append(r.Checks, Check{Name: name, OK: ok, Note: note})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add records a check with all its fields, for a program that groups its
|
||||||
|
// checks into areas or gives hints.
|
||||||
|
func (r *Report) Add(c Check) {
|
||||||
|
r.Checks = append(r.Checks, c)
|
||||||
|
}
|
||||||
|
|
||||||
// Problems counts failed checks.
|
// Problems counts failed checks.
|
||||||
func (r Report) Problems() int {
|
func (r Report) Problems() int {
|
||||||
n := 0
|
n := 0
|
||||||
@@ -148,9 +159,26 @@ func (r Report) Write(w io.Writer, asJSON bool) error {
|
|||||||
}
|
}
|
||||||
fmt.Fprintln(tw)
|
fmt.Fprintln(tw)
|
||||||
}
|
}
|
||||||
fmt.Fprintf(tw, "CHECK\tOK\tNOTE\n")
|
// The AREA and HINT columns only appear when some check uses them,
|
||||||
|
// so the table of a program without them is unchanged.
|
||||||
|
withArea, withHint := false, false
|
||||||
for _, c := range r.Checks {
|
for _, c := range r.Checks {
|
||||||
fmt.Fprintf(tw, "%s\t%s\t%s\n", c.Name, yesNo(c.OK), c.Note)
|
withArea = withArea || c.Area != ""
|
||||||
|
withHint = withHint || c.Hint != ""
|
||||||
|
}
|
||||||
|
row := func(area, name, ok, note, hint string) {
|
||||||
|
cols := []string{name, ok, note}
|
||||||
|
if withArea {
|
||||||
|
cols = append([]string{area}, cols...)
|
||||||
|
}
|
||||||
|
if withHint {
|
||||||
|
cols = append(cols, hint)
|
||||||
|
}
|
||||||
|
fmt.Fprintln(tw, strings.Join(cols, "\t"))
|
||||||
|
}
|
||||||
|
row("AREA", "CHECK", "OK", "NOTE", "HINT")
|
||||||
|
for _, c := range r.Checks {
|
||||||
|
row(c.Area, c.Name, yesNo(c.OK), c.Note, c.Hint)
|
||||||
}
|
}
|
||||||
return tw.Flush()
|
return tw.Flush()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,3 +49,37 @@ func TestAddPaths(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAreaAndHint(t *testing.T) {
|
||||||
|
// Without area/hint neither the JSON nor the table mentions them.
|
||||||
|
plain := Report{Program: "tool"}
|
||||||
|
plain.Check("config valid", true, "")
|
||||||
|
var out strings.Builder
|
||||||
|
if err := plain.Write(&out, true); err != nil || strings.Contains(out.String(), "area") || strings.Contains(out.String(), "hint") {
|
||||||
|
t.Fatalf("plain json: %v %s", err, out.String())
|
||||||
|
}
|
||||||
|
out.Reset()
|
||||||
|
if err := plain.Write(&out, false); err != nil || strings.Contains(out.String(), "AREA") || strings.Contains(out.String(), "HINT") {
|
||||||
|
t.Fatalf("plain table: %v %s", err, out.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
r := Report{Program: "tool"}
|
||||||
|
r.Add(Check{Area: "config", Name: "config loads", OK: false, Note: "line 3", Hint: "run tool config validate"})
|
||||||
|
r.Check("other", true, "")
|
||||||
|
out.Reset()
|
||||||
|
if err := r.Write(&out, true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var got Report
|
||||||
|
if err := json.Unmarshal([]byte(out.String()), &got); err != nil || got.Checks[0].Area != "config" || got.Checks[0].Hint != "run tool config validate" || got.Checks[1].Area != "" {
|
||||||
|
t.Fatalf("json: %v %+v", err, got)
|
||||||
|
}
|
||||||
|
out.Reset()
|
||||||
|
if err := r.Write(&out, false); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
lines := strings.Split(out.String(), "\n")
|
||||||
|
if !strings.HasPrefix(lines[0], "AREA") || !strings.Contains(lines[0], "HINT") || !strings.HasPrefix(lines[1], "config") || !strings.Contains(lines[1], "run tool config validate") {
|
||||||
|
t.Fatalf("table:\n%s", out.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-1
@@ -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/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/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/bridge` | `NewRouter(res)`, `Router.Handle("POST /rpc/x", h)`, `Router.SetDocument`, `Router.ServeNative` (for the window's resource handler), `Router.HTML` (Go-rendered fragments through `document`). `NewSession(router, Options)` speaks protocol v1 with the page (`hello`/`ready`, `req`/`res`, `chunk`/`end` streams, `abort`, generations). `InitScript(PageConfig)` is the page side (`bridge.js`). |
|
||||||
| `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`. |
|
| `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource, FrameFile})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`, `ShowFileDialog` (UI thread) / `ChooseFile` (any goroutine, waits): a native open or save dialog (`FileDialog{Save, Title, Directory, Name, Extensions}`; macOS NSOpenPanel/NSSavePanel as a sheet, Windows GetOpenFileNameW/GetSaveFileNameW), "" when cancelled -- it only returns a path, nothing is read or written. |
|
||||||
|
|
||||||
## Wiring
|
## 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
|
The WebView2 user-data folder (`DataPath`) belongs under the program's
|
||||||
`core/paths` cache or data directory (`%LOCALAPPDATA%`, never roaming).
|
`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
|
## Invariants
|
||||||
|
|
||||||
- **No listener, no ports, no localhost.** After a transport change,
|
- **No listener, no ports, no localhost.** After a transport change,
|
||||||
|
|||||||
+3
-1
@@ -2,7 +2,8 @@
|
|||||||
#define YETANO_WINDOW_DARWIN_H
|
#define YETANO_WINDOW_DARWIN_H
|
||||||
#include <stdint.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_add_script(void *h, const char *js);
|
||||||
void yt_navigate(void *h, const char *url);
|
void yt_navigate(void *h, const char *url);
|
||||||
void yt_eval(void *h, const char *js);
|
void yt_eval(void *h, const char *js);
|
||||||
@@ -17,5 +18,6 @@ void yt_snapshot(void *h, const char *path);
|
|||||||
void yt_set_appearance(void *h, int mode);
|
void yt_set_appearance(void *h, int mode);
|
||||||
void yt_accent_color(char *buf, int n);
|
void yt_accent_color(char *buf, int n);
|
||||||
void yt_set_app_icon(const void *png, int n);
|
void yt_set_app_icon(const void *png, int n);
|
||||||
|
void yt_file_dialog(void *h, int save, const char *title, const char *dir, const char *name, const char *types);
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
+89
-3
@@ -9,6 +9,7 @@
|
|||||||
// marshalled with dispatch_async onto the main queue.
|
// marshalled with dispatch_async onto the main queue.
|
||||||
#import <Cocoa/Cocoa.h>
|
#import <Cocoa/Cocoa.h>
|
||||||
#import <WebKit/WebKit.h>
|
#import <WebKit/WebKit.h>
|
||||||
|
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
|
||||||
#include "darwin.h"
|
#include "darwin.h"
|
||||||
|
|
||||||
// Implemented in Go (window_darwin.go).
|
// Implemented in Go (window_darwin.go).
|
||||||
@@ -18,6 +19,18 @@ extern void ytGoSchemeStop(uintptr_t h, long id);
|
|||||||
extern void ytGoDispatch(uintptr_t fn);
|
extern void ytGoDispatch(uintptr_t fn);
|
||||||
extern void ytGoClosed(uintptr_t h);
|
extern void ytGoClosed(uintptr_t h);
|
||||||
extern void ytGoSnapshotDone(uintptr_t h, const char *err);
|
extern void ytGoSnapshotDone(uintptr_t h, const char *err);
|
||||||
|
extern void ytGoFrame(uintptr_t h, int x, int y, int w, int hgt, int zoomed);
|
||||||
|
extern void ytGoFileDone(uintptr_t h, const char *path);
|
||||||
|
|
||||||
|
// YTWebView takes the first mouse click in an inactive window: without
|
||||||
|
// it the click only activates the window, so a page (a dialog shown at
|
||||||
|
// start) looks dead until clicked twice.
|
||||||
|
@interface YTWebView : WKWebView
|
||||||
|
@end
|
||||||
|
|
||||||
|
@implementation YTWebView
|
||||||
|
- (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
|
||||||
|
@end
|
||||||
|
|
||||||
@interface YTHost : NSObject <WKScriptMessageHandler, WKURLSchemeHandler, NSWindowDelegate>
|
@interface YTHost : NSObject <WKScriptMessageHandler, WKURLSchemeHandler, NSWindowDelegate>
|
||||||
@property (assign) uintptr_t goHandle;
|
@property (assign) uintptr_t goHandle;
|
||||||
@@ -26,6 +39,7 @@ extern void ytGoSnapshotDone(uintptr_t h, const char *err);
|
|||||||
@property (strong) NSMutableDictionary<NSNumber *, id<WKURLSchemeTask>> *tasks;
|
@property (strong) NSMutableDictionary<NSNumber *, id<WKURLSchemeTask>> *tasks;
|
||||||
@property (assign) long nextTask;
|
@property (assign) long nextTask;
|
||||||
@property (assign) BOOL closed;
|
@property (assign) BOOL closed;
|
||||||
|
@property (assign) NSRect normalFrame; // the last frame while not zoomed
|
||||||
@end
|
@end
|
||||||
|
|
||||||
@implementation YTHost
|
@implementation YTHost
|
||||||
@@ -67,7 +81,21 @@ extern void ytGoSnapshotDone(uintptr_t h, const char *err);
|
|||||||
ytGoSchemeStop(self.goHandle, key.longValue);
|
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 {
|
- (void)windowWillClose:(NSNotification *)n {
|
||||||
|
[self reportFrame];
|
||||||
if (self.closed) return;
|
if (self.closed) return;
|
||||||
ytGoClosed(self.goHandle);
|
ytGoClosed(self.goHandle);
|
||||||
yt_stop();
|
yt_stop();
|
||||||
@@ -102,7 +130,19 @@ static void ensureApp(void) {
|
|||||||
[NSApp finishLaunching];
|
[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 {
|
@autoreleasepool {
|
||||||
ensureApp();
|
ensureApp();
|
||||||
YTHost *host = [YTHost new];
|
YTHost *host = [YTHost new];
|
||||||
@@ -115,7 +155,7 @@ void *yt_create(uintptr_t goHandle, const char *title, int width, int height, in
|
|||||||
if (debug) [cfg.preferences setValue:@YES forKey:@"developerExtrasEnabled"];
|
if (debug) [cfg.preferences setValue:@YES forKey:@"developerExtrasEnabled"];
|
||||||
|
|
||||||
NSRect frame = NSMakeRect(0, 0, width, height);
|
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; }
|
if (@available(macOS 13.3, *)) { if (debug) host.webview.inspectable = YES; }
|
||||||
|
|
||||||
host.window = [[NSWindow alloc] initWithContentRect:frame
|
host.window = [[NSWindow alloc] initWithContentRect:frame
|
||||||
@@ -126,9 +166,17 @@ void *yt_create(uintptr_t goHandle, const char *title, int width, int height, in
|
|||||||
host.window.releasedWhenClosed = NO;
|
host.window.releasedWhenClosed = NO;
|
||||||
host.window.title = str(title);
|
host.window.title = str(title);
|
||||||
host.window.contentView = host.webview;
|
host.window.contentView = host.webview;
|
||||||
host.window.delegate = host;
|
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.window center];
|
||||||
|
}
|
||||||
|
host.normalFrame = host.window.frame;
|
||||||
|
host.window.delegate = host;
|
||||||
[host.window makeKeyAndOrderFront:nil];
|
[host.window makeKeyAndOrderFront:nil];
|
||||||
|
if (restore && zoomed && !host.window.isZoomed) [host.window zoom:nil];
|
||||||
[NSApp activateIgnoringOtherApps:YES];
|
[NSApp activateIgnoringOtherApps:YES];
|
||||||
return (__bridge_retained void *)host;
|
return (__bridge_retained void *)host;
|
||||||
}
|
}
|
||||||
@@ -171,6 +219,7 @@ void yt_stop(void) {
|
|||||||
|
|
||||||
void yt_destroy(void *h) {
|
void yt_destroy(void *h) {
|
||||||
YTHost *host = (__bridge_transfer YTHost *)h; // balances __bridge_retained
|
YTHost *host = (__bridge_transfer YTHost *)h; // balances __bridge_retained
|
||||||
|
[host reportFrame]; // a window ended by Terminate, not closed by the user
|
||||||
host.closed = YES;
|
host.closed = YES;
|
||||||
for (NSNumber *k in host.tasks.allKeys) {
|
for (NSNumber *k in host.tasks.allKeys) {
|
||||||
// Remaining tasks are failed so WebKit does not wait forever.
|
// Remaining tasks are failed so WebKit does not wait forever.
|
||||||
@@ -280,3 +329,40 @@ void yt_set_app_icon(const void *png, int n) {
|
|||||||
if (img) NSApp.applicationIconImage = img;
|
if (img) NSApp.applicationIconImage = img;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- file dialogs ------------------------------------------------------------
|
||||||
|
|
||||||
|
// yt_file_dialog shows an open (save = 0) or save panel as a sheet on the
|
||||||
|
// window. dir: the folder to start in, name: a save panel's suggested file
|
||||||
|
// name, types: allowed file extensions, comma-separated ("" = any). The
|
||||||
|
// chosen path, or NULL when cancelled, goes to ytGoFileDone.
|
||||||
|
void yt_file_dialog(void *h, int save, const char *title, const char *dir, const char *name, const char *types) {
|
||||||
|
YTHost *host = (__bridge YTHost *)h;
|
||||||
|
uintptr_t gh = host.goHandle;
|
||||||
|
NSSavePanel *panel;
|
||||||
|
if (save) {
|
||||||
|
panel = [NSSavePanel savePanel];
|
||||||
|
if (name && name[0]) panel.nameFieldStringValue = str(name);
|
||||||
|
} else {
|
||||||
|
NSOpenPanel *open = [NSOpenPanel openPanel];
|
||||||
|
open.canChooseFiles = YES;
|
||||||
|
open.canChooseDirectories = NO;
|
||||||
|
open.allowsMultipleSelection = NO;
|
||||||
|
open.resolvesAliases = YES;
|
||||||
|
panel = open;
|
||||||
|
}
|
||||||
|
if (title && title[0]) { panel.title = str(title); panel.message = str(title); }
|
||||||
|
if (dir && dir[0]) panel.directoryURL = [NSURL fileURLWithPath:str(dir) isDirectory:YES];
|
||||||
|
if (types && types[0]) {
|
||||||
|
NSMutableArray<UTType *> *uts = [NSMutableArray array];
|
||||||
|
for (NSString *ext in [str(types) componentsSeparatedByString:@","]) {
|
||||||
|
UTType *t = [UTType typeWithFilenameExtension:ext];
|
||||||
|
if (t) [uts addObject:t];
|
||||||
|
}
|
||||||
|
if (uts.count) panel.allowedContentTypes = uts;
|
||||||
|
}
|
||||||
|
[panel beginSheetModalForWindow:host.window completionHandler:^(NSModalResponse r) {
|
||||||
|
if (r != NSModalResponseOK || !panel.URL) { ytGoFileDone(gh, NULL); return; }
|
||||||
|
ytGoFileDone(gh, panel.URL.path.fileSystemRepresentation);
|
||||||
|
}];
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package window
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
comdlg32 = windows.NewLazySystemDLL("comdlg32.dll")
|
||||||
|
pGetOpenFile = comdlg32.NewProc("GetOpenFileNameW")
|
||||||
|
pGetSaveFile = comdlg32.NewProc("GetSaveFileNameW")
|
||||||
|
pCommDlgExtErr = comdlg32.NewProc("CommDlgExtendedError")
|
||||||
|
errNoFileDialog = fmt.Errorf("window: file dialog failed")
|
||||||
|
)
|
||||||
|
|
||||||
|
// openFileName is OPENFILENAMEW (commdlg.h).
|
||||||
|
type openFileName struct {
|
||||||
|
lStructSize uint32
|
||||||
|
hwndOwner uintptr
|
||||||
|
hInstance uintptr
|
||||||
|
lpstrFilter *uint16
|
||||||
|
lpstrCustomFilter *uint16
|
||||||
|
nMaxCustFilter uint32
|
||||||
|
nFilterIndex uint32
|
||||||
|
lpstrFile *uint16
|
||||||
|
nMaxFile uint32
|
||||||
|
lpstrFileTitle *uint16
|
||||||
|
nMaxFileTitle uint32
|
||||||
|
lpstrInitialDir *uint16
|
||||||
|
lpstrTitle *uint16
|
||||||
|
flags uint32
|
||||||
|
nFileOffset uint16
|
||||||
|
nFileExtension uint16
|
||||||
|
lpstrDefExt *uint16
|
||||||
|
lCustData uintptr
|
||||||
|
lpfnHook uintptr
|
||||||
|
lpTemplateName *uint16
|
||||||
|
pvReserved uintptr
|
||||||
|
dwReserved uint32
|
||||||
|
flagsEx uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
ofnOverwritePrompt = 0x00000002
|
||||||
|
ofnNoChangeDir = 0x00000008
|
||||||
|
ofnPathMustExist = 0x00000800
|
||||||
|
ofnFileMustExist = 0x00001000
|
||||||
|
ofnExplorer = 0x00080000
|
||||||
|
)
|
||||||
|
|
||||||
|
// fileFilter is the dialog's filter list: the allowed extensions, then
|
||||||
|
// all files; pairs of display text and pattern, each NUL-terminated,
|
||||||
|
// the list ending with an extra NUL.
|
||||||
|
func fileFilter(exts []string) []uint16 {
|
||||||
|
var b strings.Builder
|
||||||
|
if len(exts) > 0 {
|
||||||
|
pats := make([]string, len(exts))
|
||||||
|
for i, e := range exts {
|
||||||
|
pats[i] = "*." + strings.TrimPrefix(e, ".")
|
||||||
|
}
|
||||||
|
p := strings.Join(pats, ";")
|
||||||
|
b.WriteString(p + " (" + p + ")\x00" + p + "\x00")
|
||||||
|
}
|
||||||
|
b.WriteString("All files (*.*)\x00*.*\x00\x00")
|
||||||
|
return windows.StringToUTF16(b.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileDialog shows the common open or save dialog, modal to the window
|
||||||
|
// (it runs its own message loop on the UI thread); done runs right after.
|
||||||
|
func (b *winBackend) FileDialog(d FileDialog, done func(string, error)) {
|
||||||
|
buf := make([]uint16, 32768)
|
||||||
|
if d.Save && d.Name != "" {
|
||||||
|
copy(buf[:len(buf)-1], windows.StringToUTF16(d.Name))
|
||||||
|
}
|
||||||
|
filter := fileFilter(d.Extensions)
|
||||||
|
ofn := openFileName{
|
||||||
|
hwndOwner: b.hwnd,
|
||||||
|
lpstrFilter: &filter[0],
|
||||||
|
nFilterIndex: 1,
|
||||||
|
lpstrFile: &buf[0],
|
||||||
|
nMaxFile: uint32(len(buf)),
|
||||||
|
flags: ofnExplorer | ofnNoChangeDir | ofnPathMustExist,
|
||||||
|
}
|
||||||
|
ofn.lStructSize = uint32(unsafe.Sizeof(ofn))
|
||||||
|
if d.Title != "" {
|
||||||
|
ofn.lpstrTitle, _ = windows.UTF16PtrFromString(d.Title)
|
||||||
|
}
|
||||||
|
if d.Directory != "" {
|
||||||
|
ofn.lpstrInitialDir, _ = windows.UTF16PtrFromString(d.Directory)
|
||||||
|
}
|
||||||
|
proc := pGetOpenFile
|
||||||
|
if d.Save {
|
||||||
|
proc = pGetSaveFile
|
||||||
|
ofn.flags |= ofnOverwritePrompt
|
||||||
|
if len(d.Extensions) > 0 {
|
||||||
|
ofn.lpstrDefExt, _ = windows.UTF16PtrFromString(strings.TrimPrefix(d.Extensions[0], "."))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ofn.flags |= ofnFileMustExist
|
||||||
|
}
|
||||||
|
if r, _, _ := proc.Call(uintptr(unsafe.Pointer(&ofn))); r == 0 {
|
||||||
|
if code, _, _ := pCommDlgExtErr.Call(); code != 0 {
|
||||||
|
done("", fmt.Errorf("%w: CommDlgExtendedError 0x%x", errNoFileDialog, code))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
done("", nil) // cancelled
|
||||||
|
return
|
||||||
|
}
|
||||||
|
done(windows.UTF16ToString(buf), nil)
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package window
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestFileFilter(t *testing.T) {
|
||||||
|
raw := fileFilter([]string{"pdf", ".txt"})
|
||||||
|
s := string(utf16Runes(raw))
|
||||||
|
want := "*.pdf;*.txt (*.pdf;*.txt)\x00*.pdf;*.txt\x00All files (*.*)\x00*.*\x00\x00\x00"
|
||||||
|
if s != want {
|
||||||
|
t.Errorf("filter = %q, want %q", s, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func utf16Runes(u []uint16) []rune {
|
||||||
|
r := make([]rune, len(u))
|
||||||
|
for i, c := range u {
|
||||||
|
r[i] = rune(c)
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
@@ -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...)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package window
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFrameFileRoundTrip(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "state", "window.json")
|
||||||
|
if _, ok := loadFrame(path); ok {
|
||||||
|
t.Fatal("a missing file is a frame")
|
||||||
|
}
|
||||||
|
s := &frameSaver{path: path}
|
||||||
|
s.changed(Frame{X: 10, Y: 20, Width: 300, Height: 200})
|
||||||
|
s.changed(Frame{X: 40, Y: 50, Width: 1200, Height: 800, Maximized: true}) // the last one wins
|
||||||
|
s.flush()
|
||||||
|
f, ok := loadFrame(path)
|
||||||
|
if !ok || f != (Frame{X: 40, Y: 50, Width: 1200, Height: 800, Maximized: true}) {
|
||||||
|
t.Fatalf("loaded %+v, %v", f, ok)
|
||||||
|
}
|
||||||
|
if _, err := os.Stat(path + ".tmp"); !os.IsNotExist(err) {
|
||||||
|
t.Errorf("temp file left behind: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Too small or broken: no frame, the window opens with its default.
|
||||||
|
for _, data := range []string{`{"x":0,"y":0,"width":50,"height":40}`, `not json`, ``} {
|
||||||
|
if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if f, ok := loadFrame(path); ok {
|
||||||
|
t.Errorf("%q loaded as %+v", data, f)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.changed(Frame{Width: 10, Height: 10}) // ignored
|
||||||
|
s.flush()
|
||||||
|
if data, _ := os.ReadFile(path); string(data) != "" {
|
||||||
|
t.Errorf("an unusable frame was written: %q", data)
|
||||||
|
}
|
||||||
|
}
|
||||||
+79
-1
@@ -53,6 +53,16 @@ type Options struct {
|
|||||||
DataPath string // WebView2 user data folder (Windows)
|
DataPath string // WebView2 user data folder (Windows)
|
||||||
OnMessage func(msg string)
|
OnMessage func(msg string)
|
||||||
Resource ResourceHandler // nil: no native resource handler
|
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 {
|
type backend interface {
|
||||||
@@ -67,6 +77,7 @@ type backend interface {
|
|||||||
|
|
||||||
// Window is a guarded native WebView window.
|
// Window is a guarded native WebView window.
|
||||||
type Window struct {
|
type Window struct {
|
||||||
|
frames *frameSaver
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
b backend
|
b backend
|
||||||
alive bool
|
alive bool
|
||||||
@@ -92,11 +103,20 @@ func New(opt Options) (*Window, error) {
|
|||||||
if opt.Width == 0 {
|
if opt.Width == 0 {
|
||||||
opt.Width, opt.Height = 1100, 820
|
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)
|
b, name, base, err := newBackend(opt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
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.
|
// Backend names the native backend.
|
||||||
@@ -156,6 +176,7 @@ func (w *Window) Destroy() {
|
|||||||
w.alive = false
|
w.alive = false
|
||||||
w.mu.Unlock()
|
w.mu.Unlock()
|
||||||
w.b.Destroy()
|
w.b.Destroy()
|
||||||
|
w.frames.flush()
|
||||||
}
|
}
|
||||||
|
|
||||||
// snapshotter is implemented by backends that can render the page to PNG.
|
// snapshotter is implemented by backends that can render the page to PNG.
|
||||||
@@ -198,6 +219,63 @@ func SetAppIcon(png []byte) { setAppIcon(png) }
|
|||||||
// unknown. Safe to call before a window exists.
|
// unknown. Safe to call before a window exists.
|
||||||
func AccentColor() string { return accentColor() }
|
func AccentColor() string { return accentColor() }
|
||||||
|
|
||||||
|
// FileDialog describes a native open or save dialog.
|
||||||
|
type FileDialog struct {
|
||||||
|
Save bool // a save dialog; otherwise open one existing file
|
||||||
|
Title string // the prompt; "" for the system's
|
||||||
|
Directory string // the folder to start in; "" for the system's choice
|
||||||
|
Name string // save: the suggested file name
|
||||||
|
Extensions []string // allowed extensions without the dot ("pdf"); empty: any file
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrDialogOpen: a file dialog of this window is already open.
|
||||||
|
var ErrDialogOpen = errors.New("window: a file dialog is already open")
|
||||||
|
|
||||||
|
// fileDialoger is implemented by backends with native file dialogs.
|
||||||
|
type fileDialoger interface {
|
||||||
|
FileDialog(d FileDialog, done func(path string, err error))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShowFileDialog shows a native open or save dialog for the window (UI
|
||||||
|
// thread; one at a time). done runs on the UI thread with the chosen
|
||||||
|
// path, or "" and a nil error when the user cancelled. A save dialog
|
||||||
|
// has asked about replacing an existing file already; nothing is read
|
||||||
|
// or written here -- that is the program's choice.
|
||||||
|
func (w *Window) ShowFileDialog(d FileDialog, done func(path string, err error)) {
|
||||||
|
f, ok := w.b.(fileDialoger)
|
||||||
|
if !ok {
|
||||||
|
done("", errors.New("window: file dialogs not supported by "+w.name))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
f.FileDialog(d, done)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChooseFile shows a file dialog from any goroutine and waits for the
|
||||||
|
// user: the chosen path, or "" and nil when cancelled. ctx ending (the
|
||||||
|
// request was dropped) stops the wait, not the dialog.
|
||||||
|
func (w *Window) ChooseFile(ctx context.Context, d FileDialog) (string, error) {
|
||||||
|
type result struct {
|
||||||
|
path string
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
ch := make(chan result, 1)
|
||||||
|
w.mu.Lock()
|
||||||
|
alive := w.alive
|
||||||
|
w.mu.Unlock()
|
||||||
|
if !alive {
|
||||||
|
return "", errors.New("window: destroyed")
|
||||||
|
}
|
||||||
|
w.Dispatch(func() {
|
||||||
|
w.ShowFileDialog(d, func(p string, err error) { ch <- result{p, err} })
|
||||||
|
})
|
||||||
|
select {
|
||||||
|
case r := <-ch:
|
||||||
|
return r.path, r.err
|
||||||
|
case <-ctx.Done():
|
||||||
|
return "", ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// DroppedDispatches counts Dispatch calls that arrived after Destroy.
|
// DroppedDispatches counts Dispatch calls that arrived after Destroy.
|
||||||
func (w *Window) DroppedDispatches() int {
|
func (w *Window) DroppedDispatches() int {
|
||||||
w.mu.Lock()
|
w.mu.Lock()
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ package window
|
|||||||
|
|
||||||
/*
|
/*
|
||||||
#cgo CFLAGS: -x objective-c -fobjc-arc
|
#cgo CFLAGS: -x objective-c -fobjc-arc
|
||||||
#cgo LDFLAGS: -framework Cocoa -framework WebKit
|
#cgo LDFLAGS: -framework Cocoa -framework WebKit -framework UniformTypeIdentifiers
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include "darwin.h"
|
#include "darwin.h"
|
||||||
*/
|
*/
|
||||||
@@ -16,6 +16,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"runtime"
|
"runtime"
|
||||||
"runtime/cgo"
|
"runtime/cgo"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
)
|
)
|
||||||
@@ -35,6 +36,7 @@ type darwinBackend struct {
|
|||||||
mu sync.RWMutex // guards h against Destroy while a goroutine calls into ObjC
|
mu sync.RWMutex // guards h against Destroy while a goroutine calls into ObjC
|
||||||
|
|
||||||
snapDone func(error)
|
snapDone func(error)
|
||||||
|
fileDone func(path string, err error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// with runs f with the live host pointer, or not at all after Destroy.
|
// with runs f with the live host pointer, or not at all after Destroy.
|
||||||
@@ -63,7 +65,16 @@ func newBackend(opt Options) (backend, string, string, error) {
|
|||||||
if opt.Debug {
|
if opt.Debug {
|
||||||
debug = 1
|
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 {
|
if b.h == nil {
|
||||||
b.handle.Delete()
|
b.handle.Delete()
|
||||||
return nil, "", "", errUnavailable("WKWebView could not be created")
|
return nil, "", "", errUnavailable("WKWebView could not be created")
|
||||||
@@ -122,6 +133,14 @@ func ytGoDispatch(fn C.uintptr_t) {
|
|||||||
f()
|
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
|
//export ytGoMessage
|
||||||
func ytGoMessage(h C.uintptr_t, msg *C.char) {
|
func ytGoMessage(h C.uintptr_t, msg *C.char) {
|
||||||
b := cgo.Handle(h).Value().(*darwinBackend)
|
b := cgo.Handle(h).Value().(*darwinBackend)
|
||||||
@@ -281,3 +300,49 @@ func (t *darwinTask) Close(err error) {
|
|||||||
}
|
}
|
||||||
t.b.with(func(h unsafe.Pointer) { C.yt_task_finish(h, C.long(t.id), ce) })
|
t.b.with(func(h unsafe.Pointer) { C.yt_task_finish(h, C.long(t.id), ce) })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FileDialog shows a native open or save panel as a sheet on the window;
|
||||||
|
// done runs on the UI thread.
|
||||||
|
func (b *darwinBackend) FileDialog(d FileDialog, done func(string, error)) {
|
||||||
|
b.mu.Lock()
|
||||||
|
if b.fileDone != nil {
|
||||||
|
b.mu.Unlock()
|
||||||
|
done("", ErrDialogOpen)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.fileDone = done
|
||||||
|
b.mu.Unlock()
|
||||||
|
save := 0
|
||||||
|
if d.Save {
|
||||||
|
save = 1
|
||||||
|
}
|
||||||
|
title, dir, name, types := cstr(d.Title), cstr(d.Directory), cstr(d.Name), cstr(strings.Join(d.Extensions, ","))
|
||||||
|
defer func() {
|
||||||
|
for _, c := range []*C.char{title, dir, name, types} {
|
||||||
|
C.free(unsafe.Pointer(c))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if !b.with(func(h unsafe.Pointer) { C.yt_file_dialog(h, C.int(save), title, dir, name, types) }) {
|
||||||
|
b.mu.Lock()
|
||||||
|
b.fileDone = nil
|
||||||
|
b.mu.Unlock()
|
||||||
|
done("", errUnavailable("file dialog: the window is gone"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//export ytGoFileDone
|
||||||
|
func ytGoFileDone(h C.uintptr_t, path *C.char) {
|
||||||
|
b := cgo.Handle(h).Value().(*darwinBackend)
|
||||||
|
b.mu.Lock()
|
||||||
|
done := b.fileDone
|
||||||
|
b.fileDone = nil
|
||||||
|
b.mu.Unlock()
|
||||||
|
if done == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if path == nil {
|
||||||
|
done("", nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
done(C.GoString(path), nil)
|
||||||
|
}
|
||||||
@@ -56,6 +56,9 @@ var (
|
|||||||
pDwmSetAttribute = dwmapi.NewProc("DwmSetWindowAttribute")
|
pDwmSetAttribute = dwmapi.NewProc("DwmSetWindowAttribute")
|
||||||
pSetWindowPos = user32.NewProc("SetWindowPos")
|
pSetWindowPos = user32.NewProc("SetWindowPos")
|
||||||
pGetDpiForSystem = user32.NewProc("GetDpiForSystem")
|
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")
|
func setAppIcon([]byte) {} // the icon comes from the .exe resources (RT_GROUP_ICON "APP")
|
||||||
@@ -64,6 +67,7 @@ const (
|
|||||||
wmDestroy = 0x0002
|
wmDestroy = 0x0002
|
||||||
wmMove = 0x0003
|
wmMove = 0x0003
|
||||||
wmSize = 0x0005
|
wmSize = 0x0005
|
||||||
|
wmSetFocus = 0x0007
|
||||||
wmClose = 0x0010
|
wmClose = 0x0010
|
||||||
wmQuit = 0x0012
|
wmQuit = 0x0012
|
||||||
wmMoving = 0x0216
|
wmMoving = 0x0216
|
||||||
@@ -168,7 +172,9 @@ func newBackend(opt Options) (backend, string, string, error) {
|
|||||||
windowsMu.Lock()
|
windowsMu.Lock()
|
||||||
byHWND[hwnd] = b
|
byHWND[hwnd] = b
|
||||||
windowsMu.Unlock()
|
windowsMu.Unlock()
|
||||||
|
if f := opt.restore; f == nil || !restorePlacement(hwnd, *f) {
|
||||||
pShowWindow.Call(hwnd, swShow)
|
pShowWindow.Call(hwnd, swShow)
|
||||||
|
}
|
||||||
pUpdateWindow.Call(hwnd)
|
pUpdateWindow.Call(hwnd)
|
||||||
pSetFocus.Call(hwnd)
|
pSetFocus.Call(hwnd)
|
||||||
|
|
||||||
@@ -188,6 +194,7 @@ func newBackend(opt Options) (backend, string, string, error) {
|
|||||||
return nil, "", "", errors.New("window: WebView2 could not be created (is the Microsoft Edge WebView2 Runtime installed?)")
|
return nil, "", "", errors.New("window: WebView2 could not be created (is the Microsoft Edge WebView2 Runtime installed?)")
|
||||||
}
|
}
|
||||||
c.Resize()
|
c.Resize()
|
||||||
|
c.Focus() // the window got WM_SETFOCUS before the control existed
|
||||||
if s, err := c.GetSettings(); err == nil {
|
if s, err := c.GetSettings(); err == nil {
|
||||||
_ = s.PutAreDevToolsEnabled(opt.Debug)
|
_ = s.PutAreDevToolsEnabled(opt.Debug)
|
||||||
_ = s.PutAreDefaultContextMenusEnabled(opt.Debug)
|
_ = s.PutAreDefaultContextMenusEnabled(opt.Debug)
|
||||||
@@ -209,14 +216,25 @@ func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
|
|||||||
if b.chromium != nil {
|
if b.chromium != nil {
|
||||||
b.chromium.Resize()
|
b.chromium.Resize()
|
||||||
}
|
}
|
||||||
|
b.reportFrame()
|
||||||
case wmMove, wmMoving:
|
case wmMove, wmMoving:
|
||||||
if b.chromium != nil {
|
if b.chromium != nil {
|
||||||
_ = b.chromium.NotifyParentWindowPositionChanged()
|
_ = b.chromium.NotifyParentWindowPositionChanged()
|
||||||
}
|
}
|
||||||
|
b.reportFrame()
|
||||||
|
case wmSetFocus:
|
||||||
|
// The keyboard focus belongs in the WebView2 control (its own
|
||||||
|
// child window): without this a page gets no keys after the
|
||||||
|
// start or after Alt-Tab until it is clicked.
|
||||||
|
if b.chromium != nil {
|
||||||
|
b.chromium.Focus()
|
||||||
|
}
|
||||||
|
return 0
|
||||||
case wmApp:
|
case wmApp:
|
||||||
b.runQueue()
|
b.runQueue()
|
||||||
return 0
|
return 0
|
||||||
case wmClose:
|
case wmClose:
|
||||||
|
b.reportFrame()
|
||||||
pDestroyWindow.Call(hwnd)
|
pDestroyWindow.Call(hwnd)
|
||||||
return 0
|
return 0
|
||||||
case wmDestroy:
|
case wmDestroy:
|
||||||
@@ -233,6 +251,57 @@ func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
|
|||||||
return r
|
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() {
|
func (b *winBackend) runQueue() {
|
||||||
b.mu.Lock()
|
b.mu.Lock()
|
||||||
q := b.queue
|
q := b.queue
|
||||||
@@ -277,6 +346,7 @@ func (b *winBackend) Destroy() {
|
|||||||
b.destroying = true
|
b.destroying = true
|
||||||
b.mu.Unlock()
|
b.mu.Unlock()
|
||||||
if ok, _, _ := pIsWindow.Call(b.hwnd); ok != 0 {
|
if ok, _, _ := pIsWindow.Call(b.hwnd); ok != 0 {
|
||||||
|
b.reportFrame() // a window ended by Terminate, not closed by the user
|
||||||
pDestroyWindow.Call(b.hwnd)
|
pDestroyWindow.Call(b.hwnd)
|
||||||
}
|
}
|
||||||
windowsMu.Lock()
|
windowsMu.Lock()
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
# yetano.dev/yetano/core/trust
|
||||||
|
|
||||||
|
The family's minisign (Ed25519) signatures: verifying, shared by every
|
||||||
|
program that pulls signed content -- yet (packages) and yacota (images)
|
||||||
|
check against the same files, so a host makes one trust decision -- and
|
||||||
|
signing, shared by every program that signs: yet (packages,
|
||||||
|
attestations) and yabar (evidence records, ADR-0037 there).
|
||||||
|
|
||||||
|
```text
|
||||||
|
module yetano.dev/yetano/core/trust tags: trust/v0.1.0, trust/v0.2.0, ... go 1.25
|
||||||
|
```
|
||||||
|
|
||||||
|
A nested module of the core repository, like `core/tui`, so the main core
|
||||||
|
module stays free of minisign. Depends on `aead.dev/minisign` (MIT) and
|
||||||
|
core (`core/paths`, for `Home`; `core/secretref`, for `KeyFromRef`).
|
||||||
|
Moved from `yet/internal/trust` without changing behavior or file
|
||||||
|
formats: the verifying half on 2026-11-12 (trust/v0.1.0), the signing
|
||||||
|
half on 2026-11-27 (trust/v0.2.0). Pushing signatures to a registry and
|
||||||
|
where auto-sign keeps its keys stay in yet.
|
||||||
|
|
||||||
|
## What it is
|
||||||
|
|
||||||
|
- **Signatures:** minisign (Ed25519) over the resolved OCI manifest
|
||||||
|
digest, as the JSON payload (`Signature`, media and artifact type
|
||||||
|
`application/vnd.yetano.signature.v1+json`) of an OCI 1.1 referrer
|
||||||
|
on that digest. `Verify(subjectDigest, payloads)` checks fetched
|
||||||
|
referrers (the caller fetches them with its own registry client);
|
||||||
|
valid signatures whose key IDs collide are made invalid.
|
||||||
|
- **Known keys** (`known-keys.json`, TOFU like SSH's known_hosts):
|
||||||
|
`Reconcile` pins a repository's first valid signer and refuses later
|
||||||
|
content signed only by other keys (an error that `errors.Is`
|
||||||
|
`ErrRefused`). A key is compared as the key (`SameKey`), never by its
|
||||||
|
ID alone.
|
||||||
|
- **Trust policy** (`trust-policy.json`, edited with `yet trust
|
||||||
|
policy`): rules per namespace pattern naming allowed keys,
|
||||||
|
`require_signatures`; `Evaluate`, `AllowsCapability`, `Curated`.
|
||||||
|
- **Where:** `Home(scope)` is yet's data directory (core/paths' DataDir
|
||||||
|
for "yet"), `DefaultPolicyPath(home)`, `DefaultKnownKeysPath(home)`.
|
||||||
|
|
||||||
|
- **Keys:** `KeyPair`, `GenerateKey`, `SaveKeyPair(path, kp, password)`
|
||||||
|
(private key owner-only, `<path>.pub` beside it; the minisign CLI's
|
||||||
|
formats, scrypt-encrypted with a password), `LoadPrivateKey`,
|
||||||
|
`ParsePrivateKey`, `LoadPublicKey`, `MarshalPublicKey`, and
|
||||||
|
`KeyFromRef(ctx, resolver, keyRef, passwordRef)` for a key held as a
|
||||||
|
secret reference (`secret://...` in yaseva, `env:`, `file:`).
|
||||||
|
- **Signing:** `SignDigest(kp, digest)` makes the package signature
|
||||||
|
`VerifySignature` checks; `Sign(kp, message, trustedComment,
|
||||||
|
untrustedComment)` makes a detached `.minisig` over any bytes, and
|
||||||
|
`VerifyMessage(pub, message, sig)` checks it and returns the trusted
|
||||||
|
comment (`minisign -Vm` checks it too); `SignEd25519`/`VerifyEd25519`
|
||||||
|
are plain Ed25519 for DSSE envelopes; `ExportPEM`/`ImportPEM` for
|
||||||
|
cosign and openssl.
|
||||||
|
- **Vector:** `testdata/sign-vector.*` -- a published test key, a
|
||||||
|
message and its signature; every version must produce and accept it.
|
||||||
|
|
||||||
|
## Use
|
||||||
|
|
||||||
|
```go
|
||||||
|
home, _ := trust.Home(core.UserScope)
|
||||||
|
verified := trust.Verify(manifestDigest, payloads) // fetched referrers
|
||||||
|
if err := trust.Reconcile(trust.DefaultKnownKeysPath(home), "registry/repo", verified); err != nil {
|
||||||
|
return err // errors.Is(err, trust.ErrRefused): the pinned key changed
|
||||||
|
}
|
||||||
|
policy, _ := trust.LoadPolicy(trust.DefaultPolicyPath(home))
|
||||||
|
if d := policy.Evaluate(name, kind, verified); !d.Trusted { ... }
|
||||||
|
```
|
||||||
|
|
||||||
|
Signing:
|
||||||
|
|
||||||
|
```go
|
||||||
|
kp, err := trust.KeyFromRef(ctx, secretref.New(""), "secret://yabar/evidence/minisign", "")
|
||||||
|
sig, err := trust.Sign(kp, recordBytes, "yabar evidence <test_id> <repository_id>", "")
|
||||||
|
comment, err := trust.VerifyMessage(pub, recordBytes, sig)
|
||||||
|
```
|
||||||
|
|
||||||
|
`Warn` (a variable) reports warnings that are not errors, on standard
|
||||||
|
error by default.
|
||||||
@@ -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
|
||||||
|
)
|
||||||
@@ -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=
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,191 @@
|
|||||||
|
package trust
|
||||||
|
|
||||||
|
// The signing half of publisher signatures, moved from yet's
|
||||||
|
// internal/trust (2026-11-27, YABAR-036a) without changing behavior or
|
||||||
|
// file formats: key pairs in minisign's own file formats, the package
|
||||||
|
// signature over an OCI digest (SignDigest), detached signatures over
|
||||||
|
// any bytes (Sign, VerifyMessage), plain Ed25519 for DSSE envelopes,
|
||||||
|
// and PEM for cosign and openssl. Where keys are kept for auto-signing
|
||||||
|
// and pushing signatures to a registry stay in yet.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"crypto"
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/sha512"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"aead.dev/minisign"
|
||||||
|
)
|
||||||
|
|
||||||
|
// KeyPair is a minisign key pair. The private key never leaves the host's
|
||||||
|
// filesystem; only the public key is shared with other hosts (as a plain
|
||||||
|
// ".pub" file) and embedded in signatures.
|
||||||
|
type KeyPair struct {
|
||||||
|
Public minisign.PublicKey
|
||||||
|
Private minisign.PrivateKey
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateKey creates a new minisign key pair.
|
||||||
|
func GenerateKey() (KeyPair, error) {
|
||||||
|
pub, priv, err := minisign.GenerateKey(nil)
|
||||||
|
if err != nil {
|
||||||
|
return KeyPair{}, err
|
||||||
|
}
|
||||||
|
return KeyPair{Public: pub, Private: priv}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveKeyPair writes kp's private key to path (owner-only permissions) and
|
||||||
|
// its public key to path+".pub" (world-readable: it is meant to be shared).
|
||||||
|
// This mirrors the real minisign CLI's `-p file.pub -s file` convention, so
|
||||||
|
// `trust policy allow` only ever needs the ".pub" file, never the private
|
||||||
|
// key -- a relying party registering a publisher's trust never needs (and
|
||||||
|
// should never be handed) their private key.
|
||||||
|
//
|
||||||
|
// If password is non-empty, the private key is scrypt-encrypted exactly as
|
||||||
|
// `minisign -G` with a passphrase would; if empty, it is written
|
||||||
|
// unencrypted, matching the minisign CLI's own behavior when a blank
|
||||||
|
// passphrase is given. Either way the file is only ever readable by its
|
||||||
|
// owner; a password additionally protects it if the file itself leaks.
|
||||||
|
func SaveKeyPair(path string, kp KeyPair, password string) error {
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
var privData []byte
|
||||||
|
var err error
|
||||||
|
if password != "" {
|
||||||
|
privData, err = minisign.EncryptKey(password, kp.Private)
|
||||||
|
} else {
|
||||||
|
privData, err = kp.Private.MarshalText()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("encode private key: %w", err)
|
||||||
|
}
|
||||||
|
if err := writeOwnerOnly(path, privData); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
pubData, err := MarshalPublicKey(kp.Public)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("encode public key: %w", err)
|
||||||
|
}
|
||||||
|
return writeFile(path+".pub", pubData, 0o644)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadPrivateKey reads a key pair previously written by SaveKeyPair,
|
||||||
|
// decrypting it with password if it is encrypted (password is ignored, and
|
||||||
|
// may be empty, for an unencrypted key).
|
||||||
|
func LoadPrivateKey(path, password string) (KeyPair, error) {
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return KeyPair{}, err
|
||||||
|
}
|
||||||
|
return ParsePrivateKey(data, password)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParsePrivateKey parses a minisign private key file's contents, the
|
||||||
|
// same bytes LoadPrivateKey reads from disk, so a key can also come from
|
||||||
|
// somewhere other than a file (a yaseva secret, see KeyStore).
|
||||||
|
func ParsePrivateKey(data []byte, password string) (KeyPair, error) {
|
||||||
|
var err error
|
||||||
|
var priv minisign.PrivateKey
|
||||||
|
if minisign.IsEncrypted(data) {
|
||||||
|
priv, err = minisign.DecryptKey(password, data)
|
||||||
|
if err != nil {
|
||||||
|
return KeyPair{}, fmt.Errorf("decrypt private key (wrong password?): %w", err)
|
||||||
|
}
|
||||||
|
} else if err := priv.UnmarshalText(data); err != nil {
|
||||||
|
return KeyPair{}, fmt.Errorf("parse private key: %w", err)
|
||||||
|
}
|
||||||
|
pub, ok := priv.Public().(minisign.PublicKey)
|
||||||
|
if !ok {
|
||||||
|
return KeyPair{}, fmt.Errorf("derive public key: unexpected type %T", priv.Public())
|
||||||
|
}
|
||||||
|
return KeyPair{Public: pub, Private: priv}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadPublicKey reads a standalone ".pub" file, for a trust policy that
|
||||||
|
// must never require (or accept) private key material.
|
||||||
|
func LoadPublicKey(path string) (minisign.PublicKey, error) {
|
||||||
|
return minisign.PublicKeyFromFile(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MarshalPublicKey encodes pub as a minisign ".pub" file. It is
|
||||||
|
// aead.dev/minisign's own encoding, except that the comment line carries
|
||||||
|
// the 16-digit key ID (the library writes it without leading zeros).
|
||||||
|
func MarshalPublicKey(pub minisign.PublicKey) ([]byte, error) {
|
||||||
|
data, err := pub.MarshalText()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
_, rest, ok := bytes.Cut(data, []byte("\n"))
|
||||||
|
if !ok {
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
out := fmt.Appendf(nil, "untrusted comment: minisign public key: %s\n", ID(pub))
|
||||||
|
out = append(out, rest...)
|
||||||
|
if !bytes.HasSuffix(out, []byte("\n")) {
|
||||||
|
out = append(out, '\n')
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeOwnerOnly(path string, data []byte) error {
|
||||||
|
return writeFile(path, data, 0o600)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeFile(path string, data []byte, mode os.FileMode) error {
|
||||||
|
tmp, err := os.CreateTemp(filepath.Dir(path), ".key-*")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() { _ = os.Remove(tmp.Name()) }()
|
||||||
|
if err := os.Chmod(tmp.Name(), mode); err != nil {
|
||||||
|
_ = tmp.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := tmp.Write(data); err != nil {
|
||||||
|
_ = tmp.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tmp.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.Rename(tmp.Name(), path)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SignEd25519 signs message with kp as a plain Ed25519 signature
|
||||||
|
// (minisign's non-prehashed "Ed" algorithm): the raw 64 bytes DSSE
|
||||||
|
// envelopes carry and cosign and other Ed25519 verifiers check against
|
||||||
|
// ExportPEM's key. Package signatures (Sign) keep using minisign's own
|
||||||
|
// format.
|
||||||
|
func SignEd25519(kp KeyPair, message []byte) ([]byte, error) {
|
||||||
|
text, err := kp.Private.Sign(nil, message, crypto.Hash(0))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var sig minisign.Signature
|
||||||
|
if err := sig.UnmarshalText(text); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if sig.Algorithm != minisign.EdDSA {
|
||||||
|
return nil, fmt.Errorf("unexpected minisign algorithm %d", sig.Algorithm)
|
||||||
|
}
|
||||||
|
return sig.Signature[:], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyEd25519 checks an Ed25519 signature over message against pub:
|
||||||
|
// plain Ed25519 (what SignEd25519 makes) or Ed25519ph with SHA-512
|
||||||
|
// (what cosign makes with an Ed25519 key).
|
||||||
|
func VerifyEd25519(pub minisign.PublicKey, message, sig []byte) bool {
|
||||||
|
raw := Ed25519Key(pub)
|
||||||
|
if raw == nil || len(sig) != ed25519.SignatureSize {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if ed25519.Verify(raw, message, sig) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
digest := sha512.Sum512(message)
|
||||||
|
return ed25519.VerifyWithOptions(raw, digest[:], sig, &ed25519.Options{Hash: crypto.SHA512}) == nil
|
||||||
|
}
|
||||||
+185
@@ -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...)
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package trust
|
||||||
|
|
||||||
|
// Moved from yet's internal/trust with the signing half (2026-11-27).
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ed25519"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/x509"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/binary"
|
||||||
|
"encoding/pem"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"aead.dev/minisign"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ExportPEM encodes pub's Ed25519 key as a PEM "PUBLIC KEY" block
|
||||||
|
// (PKIX), the form cosign, openssl and most other tools read -- e.g.
|
||||||
|
// "cosign verify-attestation --key exported.pem". Only the key leaves:
|
||||||
|
// a PEM file has no room for minisign's key ID, and nothing private is
|
||||||
|
// ever exported.
|
||||||
|
func ExportPEM(pub minisign.PublicKey) ([]byte, error) {
|
||||||
|
raw := Ed25519Key(pub)
|
||||||
|
if raw == nil {
|
||||||
|
return nil, errors.New("not an Ed25519 minisign public key")
|
||||||
|
}
|
||||||
|
der, err := x509.MarshalPKIXPublicKey(raw)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ImportPEM reads a PEM "PUBLIC KEY" block holding an Ed25519 key
|
||||||
|
// (e.g. a cosign.pub made from an Ed25519 key, or ExportPEM's output)
|
||||||
|
// and returns it as a minisign public key, so it can be pinned and
|
||||||
|
// trusted like any other (known-keys add, trust policy allow).
|
||||||
|
//
|
||||||
|
// PEM carries no key ID, so one is chosen: knownID's answer if it
|
||||||
|
// returns one for this key (a key this host already knows, e.g. one
|
||||||
|
// exported earlier, gets its old ID back), otherwise one derived from
|
||||||
|
// the key (the first 8 bytes of its SHA-256). Either way trust decisions
|
||||||
|
// compare the key itself, never the ID (see SameKey).
|
||||||
|
func ImportPEM(data []byte, knownID func(ed25519.PublicKey) (KeyID, bool)) (minisign.PublicKey, error) {
|
||||||
|
block, _ := pem.Decode(data)
|
||||||
|
if block == nil {
|
||||||
|
return minisign.PublicKey{}, errors.New("no PEM block found")
|
||||||
|
}
|
||||||
|
if block.Type != "PUBLIC KEY" {
|
||||||
|
return minisign.PublicKey{}, fmt.Errorf("PEM block is %q, want \"PUBLIC KEY\" (never import a private key)", block.Type)
|
||||||
|
}
|
||||||
|
parsed, err := x509.ParsePKIXPublicKey(block.Bytes)
|
||||||
|
if err != nil {
|
||||||
|
return minisign.PublicKey{}, fmt.Errorf("parse public key: %w", err)
|
||||||
|
}
|
||||||
|
raw, ok := parsed.(ed25519.PublicKey)
|
||||||
|
if !ok {
|
||||||
|
return minisign.PublicKey{}, fmt.Errorf("unsupported key type %T: only Ed25519 keys can be imported (cosign generate-key-pair makes ECDSA P-256 keys)", parsed)
|
||||||
|
}
|
||||||
|
var id uint64
|
||||||
|
if knownID != nil {
|
||||||
|
if known, ok := knownID(raw); ok {
|
||||||
|
v, err := ParseKeyID(string(known))
|
||||||
|
if err == nil {
|
||||||
|
id = parseUint(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if id == 0 {
|
||||||
|
sum := sha256.Sum256(raw)
|
||||||
|
id = binary.LittleEndian.Uint64(sum[:8])
|
||||||
|
}
|
||||||
|
return minisignKey(id, raw)
|
||||||
|
}
|
||||||
|
|
||||||
|
// minisignKey builds a minisign public key from an ID and a raw key.
|
||||||
|
func minisignKey(id uint64, raw ed25519.PublicKey) (minisign.PublicKey, error) {
|
||||||
|
buf := make([]byte, 0, 2+8+ed25519.PublicKeySize)
|
||||||
|
buf = append(buf, 'E', 'd')
|
||||||
|
buf = binary.LittleEndian.AppendUint64(buf, id)
|
||||||
|
buf = append(buf, raw...)
|
||||||
|
return ParseKeyText(base64.StdEncoding.EncodeToString(buf))
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseUint(id KeyID) uint64 {
|
||||||
|
v, _ := strconv.ParseUint(string(id), 16, 64)
|
||||||
|
return v
|
||||||
|
}
|
||||||
+331
@@ -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
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package trust
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/secretref"
|
||||||
|
)
|
||||||
|
|
||||||
|
// KeyFromRef loads a signing key pair from a secret reference
|
||||||
|
// (secret://, env:, file:, base64: -- core/secretref), for example
|
||||||
|
// "secret://yabar/evidence/minisign" in yaseva. The value is a minisign
|
||||||
|
// private key file's contents. passwordRef ("" for none) is the
|
||||||
|
// reference of the password of an encrypted key. Error messages never
|
||||||
|
// contain the secret.
|
||||||
|
func KeyFromRef(ctx context.Context, r *secretref.Resolver, keyRef, passwordRef string) (KeyPair, error) {
|
||||||
|
data, err := r.Resolve(ctx, keyRef)
|
||||||
|
if err != nil {
|
||||||
|
return KeyPair{}, fmt.Errorf("signing key %s: %s", keyRef, r.Redact(err.Error()))
|
||||||
|
}
|
||||||
|
var password string
|
||||||
|
if passwordRef != "" {
|
||||||
|
if password, err = r.ResolveString(ctx, passwordRef); err != nil {
|
||||||
|
return KeyPair{}, fmt.Errorf("signing key password %s: %s", passwordRef, r.Redact(err.Error()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
kp, err := ParsePrivateKey(data, password)
|
||||||
|
if err != nil {
|
||||||
|
return KeyPair{}, fmt.Errorf("signing key %s: %s", keyRef, r.Redact(err.Error()))
|
||||||
|
}
|
||||||
|
return kp, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package trust
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"aead.dev/minisign"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SignDigest makes the publisher signature of an OCI manifest digest:
|
||||||
|
// the Signature payload yet pushes as a referrer and VerifySignature
|
||||||
|
// checks. The trusted comment is "yet package digest: <digest>" (the
|
||||||
|
// format yet has always written).
|
||||||
|
func SignDigest(kp KeyPair, digest string) (Signature, error) {
|
||||||
|
trustedComment := "yet package digest: " + digest
|
||||||
|
sig := minisign.SignWithComments(kp.Private, []byte(digest), trustedComment, "")
|
||||||
|
pubText, err := kp.Public.MarshalText()
|
||||||
|
if err != nil {
|
||||||
|
return Signature{}, err
|
||||||
|
}
|
||||||
|
return Signature{
|
||||||
|
SchemaVersion: 1,
|
||||||
|
Algorithm: "minisign",
|
||||||
|
PublicKey: string(pubText),
|
||||||
|
Digest: digest,
|
||||||
|
Value: string(sig),
|
||||||
|
SignedAt: time.Now().UTC(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sign makes a detached minisign signature of message: the text of a
|
||||||
|
// ".minisig" file, which "minisign -V -m <file>" verifies against the
|
||||||
|
// key's ".pub" file. trustedComment is signed with it (one line);
|
||||||
|
// untrustedComment is not ("" for minisign's default).
|
||||||
|
func Sign(kp KeyPair, message []byte, trustedComment, untrustedComment string) ([]byte, error) {
|
||||||
|
if strings.ContainsAny(trustedComment, "\r\n") || strings.ContainsAny(untrustedComment, "\r\n") {
|
||||||
|
return nil, errors.New("a minisign comment is one line")
|
||||||
|
}
|
||||||
|
return minisign.SignWithComments(kp.Private, message, trustedComment, untrustedComment), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrBadSignature: a signature does not verify (wrong key, changed
|
||||||
|
// message or changed trusted comment).
|
||||||
|
var ErrBadSignature = errors.New("signature does not verify")
|
||||||
|
|
||||||
|
// VerifyMessage checks a detached minisign signature (Sign's output, or
|
||||||
|
// a ".minisig" file from the minisign tool) of message against pub and
|
||||||
|
// returns its trusted comment, which the signature covers. A signature
|
||||||
|
// by another key fails, also when its key ID collides with pub's.
|
||||||
|
func VerifyMessage(pub minisign.PublicKey, message, signature []byte) (trustedComment string, err error) {
|
||||||
|
var sig minisign.Signature
|
||||||
|
if err := sig.UnmarshalText(signature); err != nil {
|
||||||
|
return "", fmt.Errorf("parse signature: %w", err)
|
||||||
|
}
|
||||||
|
if sig.KeyID != pub.ID() {
|
||||||
|
return "", fmt.Errorf("%w: signed by key %s, not %s", ErrBadSignature, KeyIDFromUint(sig.KeyID), ID(pub))
|
||||||
|
}
|
||||||
|
if !minisign.Verify(pub, message, signature) {
|
||||||
|
return "", ErrBadSignature
|
||||||
|
}
|
||||||
|
return sig.TrustedComment, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package trust
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"aead.dev/minisign"
|
||||||
|
|
||||||
|
"yetano.dev/yetano/core/secretref"
|
||||||
|
)
|
||||||
|
|
||||||
|
func vectorKey(t *testing.T) KeyPair {
|
||||||
|
t.Helper()
|
||||||
|
kp, err := LoadPrivateKey("testdata/sign-vector.key", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return kp
|
||||||
|
}
|
||||||
|
|
||||||
|
// The golden vector: a fixed key and message give exactly the committed
|
||||||
|
// .minisig (Ed25519 is deterministic), and it verifies with the .pub.
|
||||||
|
// "minisign -Vm testdata/sign-vector.msg -p testdata/sign-vector.pub"
|
||||||
|
// verifies it as well.
|
||||||
|
func TestSignVector(t *testing.T) {
|
||||||
|
kp := vectorKey(t)
|
||||||
|
msg, _ := os.ReadFile("testdata/sign-vector.msg")
|
||||||
|
want, _ := os.ReadFile("testdata/sign-vector.msg.minisig")
|
||||||
|
got, err := Sign(kp, msg, "yabar evidence test-vector 00000000000000000000000000000000", "")
|
||||||
|
if err != nil || !bytes.Equal(got, want) {
|
||||||
|
t.Fatalf("signature differs from the vector (%v):\n%s", err, got)
|
||||||
|
}
|
||||||
|
pub, err := LoadPublicKey("testdata/sign-vector.pub")
|
||||||
|
if err != nil || !SameKey(pub, kp.Public) {
|
||||||
|
t.Fatalf("public key: %v", err)
|
||||||
|
}
|
||||||
|
tc, err := VerifyMessage(pub, msg, want)
|
||||||
|
if err != nil || tc != "yabar evidence test-vector 00000000000000000000000000000000" {
|
||||||
|
t.Fatalf("verify: %q %v", tc, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestVerifyMessageRejects(t *testing.T) {
|
||||||
|
kp := vectorKey(t)
|
||||||
|
msg := []byte("evidence")
|
||||||
|
sig, _ := Sign(kp, msg, "trusted", "untrusted")
|
||||||
|
if _, err := VerifyMessage(kp.Public, []byte("evidencE"), sig); !errors.Is(err, ErrBadSignature) {
|
||||||
|
t.Fatalf("changed message: %v", err)
|
||||||
|
}
|
||||||
|
changed := bytes.Replace(sig, []byte("trusted comment: trusted"), []byte("trusted comment: trustee"), 1)
|
||||||
|
if _, err := VerifyMessage(kp.Public, msg, changed); !errors.Is(err, ErrBadSignature) {
|
||||||
|
t.Fatalf("changed trusted comment: %v", err)
|
||||||
|
}
|
||||||
|
// The untrusted comment is not covered.
|
||||||
|
free := bytes.Replace(sig, []byte("untrusted comment: untrusted"), []byte("untrusted comment: whatever"), 1)
|
||||||
|
if _, err := VerifyMessage(kp.Public, msg, free); err != nil {
|
||||||
|
t.Fatalf("untrusted comment: %v", err)
|
||||||
|
}
|
||||||
|
other, _ := GenerateKey()
|
||||||
|
if _, err := VerifyMessage(other.Public, msg, sig); !errors.Is(err, ErrBadSignature) {
|
||||||
|
t.Fatalf("other key: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := VerifyMessage(kp.Public, msg, []byte("garbage")); err == nil {
|
||||||
|
t.Fatal("garbage verified")
|
||||||
|
}
|
||||||
|
if _, err := Sign(kp, msg, "two\nlines", ""); err == nil {
|
||||||
|
t.Fatal("a two-line comment was accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// What SignDigest makes, VerifySignature (the verifying half every
|
||||||
|
// consumer uses) accepts, and only for that digest.
|
||||||
|
func TestSignDigestVerifies(t *testing.T) {
|
||||||
|
kp := vectorKey(t)
|
||||||
|
const d = "sha256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
|
||||||
|
sig, err := SignDigest(kp, d)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if v := VerifySignature(d, sig); !v.Valid || v.KeyID != ID(kp.Public) {
|
||||||
|
t.Fatalf("verify: %+v", v)
|
||||||
|
}
|
||||||
|
if v := VerifySignature("sha256:"+strings.Repeat("0", 64), sig); v.Valid {
|
||||||
|
t.Fatal("verified for another digest")
|
||||||
|
}
|
||||||
|
tc, err := VerifyMessage(kp.Public, []byte(d), []byte(sig.Value))
|
||||||
|
if err != nil || tc != "yet package digest: "+d {
|
||||||
|
t.Fatalf("trusted comment %q %v", tc, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKeyFiles(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
kp, _ := GenerateKey()
|
||||||
|
for _, pw := range []string{"", "secret"} {
|
||||||
|
p := filepath.Join(dir, "k"+pw)
|
||||||
|
if err := SaveKeyPair(p, kp, pw); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := LoadPrivateKey(p, pw)
|
||||||
|
if err != nil || !SameKey(got.Public, kp.Public) {
|
||||||
|
t.Fatalf("password %q: %v", pw, err)
|
||||||
|
}
|
||||||
|
pub, err := LoadPublicKey(p + ".pub")
|
||||||
|
if err != nil || !SameKey(pub, kp.Public) {
|
||||||
|
t.Fatalf(".pub: %v", err)
|
||||||
|
}
|
||||||
|
if fi, _ := os.Stat(p); os.PathSeparator == '/' && fi.Mode().Perm() != 0o600 {
|
||||||
|
t.Fatalf("private key mode %v", fi.Mode())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := LoadPrivateKey(filepath.Join(dir, "ksecret"), "wrong"); err == nil {
|
||||||
|
t.Fatal("wrong password accepted")
|
||||||
|
}
|
||||||
|
b, _ := MarshalPublicKey(kp.Public)
|
||||||
|
if !bytes.HasPrefix(b, []byte("untrusted comment: minisign public key: "+string(ID(kp.Public))+"\n")) {
|
||||||
|
t.Fatalf("public key file: %s", b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEd25519AndPEM(t *testing.T) {
|
||||||
|
kp := vectorKey(t)
|
||||||
|
sig, err := SignEd25519(kp, []byte("statement"))
|
||||||
|
if err != nil || !VerifyEd25519(kp.Public, []byte("statement"), sig) || VerifyEd25519(kp.Public, []byte("statemenT"), sig) {
|
||||||
|
t.Fatalf("ed25519: %v", err)
|
||||||
|
}
|
||||||
|
p, err := ExportPEM(kp.Public)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
back, err := ImportPEM(p, nil)
|
||||||
|
if err != nil || !SameKey(back, kp.Public) {
|
||||||
|
t.Fatalf("PEM round trip: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestKeyFromRef(t *testing.T) {
|
||||||
|
kp := vectorKey(t)
|
||||||
|
priv, _ := os.ReadFile("testdata/sign-vector.key")
|
||||||
|
r := secretref.New("")
|
||||||
|
got, err := KeyFromRef(context.Background(), r, "base64:"+base64.StdEncoding.EncodeToString(priv), "")
|
||||||
|
if err != nil || !SameKey(got.Public, kp.Public) {
|
||||||
|
t.Fatalf("base64 ref: %v", err)
|
||||||
|
}
|
||||||
|
enc, _ := minisign.EncryptKey("pw", kp.Private)
|
||||||
|
t.Setenv("TRUST_TEST_KEY", string(enc))
|
||||||
|
t.Setenv("TRUST_TEST_PW", "pw")
|
||||||
|
if got, err = KeyFromRef(context.Background(), r, "env:TRUST_TEST_KEY", "env:TRUST_TEST_PW"); err != nil || !SameKey(got.Public, kp.Public) {
|
||||||
|
t.Fatalf("encrypted env ref: %v", err)
|
||||||
|
}
|
||||||
|
t.Setenv("TRUST_TEST_PW", "wrong-password")
|
||||||
|
_, err = KeyFromRef(context.Background(), secretref.New(""), "env:TRUST_TEST_KEY", "env:TRUST_TEST_PW")
|
||||||
|
if err == nil || strings.Contains(err.Error(), "wrong-password") {
|
||||||
|
t.Fatalf("wrong password: %v", err)
|
||||||
|
}
|
||||||
|
if _, err := KeyFromRef(context.Background(), r, "not a reference", ""); err == nil {
|
||||||
|
t.Fatal("plaintext accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+2
@@ -0,0 +1,2 @@
|
|||||||
|
untrusted comment: minisign encrypted secret key
|
||||||
|
RWQAAEIyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMIu3pReIO0jw8qjsUD5/2J9b2y+5BNJ45wLRkzgleRSUugHITToa6mGDGFfLcgDIs+wEX4vFIUfnrLqym+u2yLqBzAYgET+YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||||
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
yabar evidence vector
|
||||||
+4
@@ -0,0 +1,4 @@
|
|||||||
|
untrusted comment:
|
||||||
|
RWQwi7elF4g7SHc9svLZOCFGGEyXs7gZW6saVrYobxgEdJnDM9hIxHIlC+qxicazJFYu2E6TG3Qq62NTae3k0rDlomfkxxz8oQA=
|
||||||
|
trusted comment: yabar evidence test-vector 00000000000000000000000000000000
|
||||||
|
o0/jQwycdwDK6BrI5jc6N47P2ixexYe07twyQ587cJBWapfKNch5EmMgvvwR6thKci3Lg0dpuanBDFdVP9QcCw==
|
||||||
Vendored
+2
@@ -0,0 +1,2 @@
|
|||||||
|
untrusted comment: minisign public key: 483B8817A5B78B30
|
||||||
|
RWQwi7elF4g7SGGDGFfLcgDIs+wEX4vFIUfnrLqym+u2yLqBzAYgET+Y
|
||||||
@@ -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
@@ -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...)}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user