Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9395fadbf7 | ||
|
|
8513b6db4c | ||
|
|
31dbc347e8 | ||
|
|
c16b871db5 | ||
|
|
35f8b7d18a |
No files matched your search
@@ -17,7 +17,9 @@ Two **separate, nested modules** keep this module at its single
|
||||
dependency: the native WebView GUI host `yetano.dev/yetano/core/gui`
|
||||
(tags `gui/vX.Y.Z`, cgo, see [gui/README.md](gui/README.md)) and the
|
||||
shared terminal-UI kernel `yetano.dev/yetano/core/tui` (tags
|
||||
`tui/vX.Y.Z`, Charm lipgloss v2, see [tui/README.md](tui/README.md)).
|
||||
`tui/vX.Y.Z`, Charm lipgloss v2, see [tui/README.md](tui/README.md)), and
|
||||
the publisher-signature check `yetano.dev/yetano/core/trust` (tags
|
||||
`trust/vX.Y.Z`, minisign, see [trust/README.md](trust/README.md)).
|
||||
|
||||
```text
|
||||
yetano.dev/yetano/core
|
||||
@@ -39,6 +41,7 @@ yetano.dev/yetano/core/gui/document
|
||||
yetano.dev/yetano/core/gui/bridge
|
||||
yetano.dev/yetano/core/gui/window
|
||||
yetano.dev/yetano/core/tui (own module, tags tui/vX.Y.Z)
|
||||
yetano.dev/yetano/core/trust (own module, tags trust/vX.Y.Z)
|
||||
```
|
||||
|
||||
Target platforms: Linux, FreeBSD, macOS, Windows. No Unix assumptions
|
||||
@@ -371,8 +374,11 @@ report options the program ignores. Taken over from
|
||||
|
||||
`config show [--json] [--show-secrets]` prints the configuration with
|
||||
the file every value comes from (`Effective.Show`; secrets -- keys
|
||||
`secrets`, `secret`, `token`, `password` -- are redacted unless
|
||||
`--show-secrets`, references like `env:X` stay visible), and
|
||||
`secrets`, `secret`, `token`, `password`, plus the program's own
|
||||
`Spec.SecretKeys` such as `database.url` (a key covers everything below
|
||||
it) -- are redacted unless `--show-secrets`, references like `env:X`
|
||||
stay visible; inside a list the same rule applies to every entry's
|
||||
fields, a Spec key naming them without the index: `admins.password`), and
|
||||
`configcmd.Doctor(report, spec, explicit)` is the config part of a
|
||||
`doctor` command (paths, layers, "config file found", unknown options).
|
||||
|
||||
@@ -460,8 +466,9 @@ one-line form for log lines and web UI footers.
|
||||
|
||||
Tagged as plain semver on this repository (`v0.1.0`, ...), per the
|
||||
meta-repo `AGENTS.md`'s versioning rules: an existing tag is never
|
||||
force-moved to a different commit. The nested `gui` and `tui` modules
|
||||
have their own prefixed tags (`gui/v0.1.0`, `tui/v0.1.0`, ...); a change
|
||||
force-moved to a different commit. The nested `gui`, `tui` and `trust`
|
||||
modules have their own prefixed tags (`gui/v0.1.0`, `tui/v0.1.0`,
|
||||
`trust/v0.1.0`, ...); a change
|
||||
there needs no main-module tag and vice versa.
|
||||
|
||||
## core/secretref
|
||||
|
||||
@@ -47,6 +47,13 @@ speculatively.
|
||||
`yetano.dev/yetano/core/gui` (`gui/v0.1.0`). The prototype uses it.
|
||||
- [ ] Move yet-gui off its copy in `yet/gui/internal` onto `core/gui`
|
||||
(steps in [gui/README.md](gui/README.md)).
|
||||
- [x] `core/gui` (macOS): the web view accepts the first mouse click in
|
||||
an inactive window (`YTWebView`, `acceptsFirstMouse:` YES;
|
||||
`gui/v0.2.0`, 2026-11-15) -- before, the first click only activated
|
||||
the window, so a dialog shown at start looked dead (yanks).
|
||||
- [x] `core/gui`: `window.Options.FrameFile` keeps the window's position,
|
||||
size and maximized state across starts (macOS and Windows;
|
||||
`gui/v0.2.0`, 2026-11-15).
|
||||
- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md.
|
||||
- [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer,
|
||||
ListState, text helpers) as the nested module
|
||||
|
||||
@@ -116,6 +116,14 @@ type Spec struct {
|
||||
// options (see Missing). Optional.
|
||||
Schema any
|
||||
|
||||
// SecretKeys are the program's own secret options, as dotted keys
|
||||
// ("database.url", "oidc.client_secret"): "config show" redacts them
|
||||
// like the keys it always treats as secret (a last segment secrets,
|
||||
// secret, token or password). A key also covers everything below it.
|
||||
// Fields of list entries are named without the index
|
||||
// ("admins.password" for every entry of the list admins).
|
||||
SecretKeys []string
|
||||
|
||||
// Options are passed through to core/config; tests use them to
|
||||
// inject a platform, environment, root and working directory.
|
||||
Options []coreconfig.Option
|
||||
|
||||
@@ -73,6 +73,9 @@ type Effective struct {
|
||||
// Loader is the Layered loader's own value for this configuration
|
||||
// (e.g. its richer layer list), for its Unknown hook; nil otherwise.
|
||||
Loader any
|
||||
// SecretKeys are redacted by Values and Show in addition to the
|
||||
// default secret names (Spec.SecretKeys).
|
||||
SecretKeys []string
|
||||
}
|
||||
|
||||
// Used returns the layers that contributed, highest priority first.
|
||||
@@ -233,6 +236,7 @@ func (s Spec) show(explicit string, args []string, stdout, stderr io.Writer) int
|
||||
return ExitProblem
|
||||
}
|
||||
used := s.usedFunc()
|
||||
e.SecretKeys = s.SecretKeys
|
||||
if err := e.Show(stdout, used, *asJSON, *secrets); err != nil {
|
||||
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
|
||||
return ExitProblem
|
||||
|
||||
@@ -174,6 +174,43 @@ func TestValuesRedaction(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestValuesProgramSecrets: Spec.SecretKeys (on Effective) redacts a
|
||||
// program's own secret options and everything below one; other keys and
|
||||
// a key that only shares a prefix stay.
|
||||
func TestValuesProgramSecrets(t *testing.T) {
|
||||
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
|
||||
"database": map[string]any{"url": "postgres://app:pw@db/x", "owner_url": "file:/run/o", "urls": "kept"},
|
||||
"smtp": map[string]any{"url": "smtps://u:pw@mail", "from": "a@b"},
|
||||
"vault": map[string]any{"inner": map[string]any{"key": "deep"}},
|
||||
}})
|
||||
e := &Effective{Name: "p", Merged: merged, Origins: origins, SecretKeys: []string{"database.url", "database.owner_url", "smtp.url", "vault"}}
|
||||
got := map[string]any{}
|
||||
for _, v := range e.Values(nil, false) {
|
||||
got[v.Key] = v.Value
|
||||
}
|
||||
want := map[string]any{
|
||||
"database.url": "<redacted>", "database.owner_url": "file:/run/o", "database.urls": "kept",
|
||||
"smtp.url": "<redacted>", "smtp.from": "a@b", "vault.inner.key": "<redacted>",
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Values = %v, want %v", got, want)
|
||||
}
|
||||
for _, v := range e.Values(nil, true) {
|
||||
if v.Key == "smtp.url" && v.Value != "smtps://u:pw@mail" {
|
||||
t.Errorf("show-secrets: %v", v.Value)
|
||||
}
|
||||
}
|
||||
|
||||
// Through "config show": the Spec's keys reach the output.
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
s.SecretKeys = []string{"log-level"}
|
||||
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"), minimalTemplate+"log-level: debug\n")
|
||||
if code, out, errOut := run(t, s, "", "show"); code != ExitOK || strings.Contains(out, `"debug"`) || !strings.Contains(out, `log-level: "<redacted>"`) {
|
||||
t.Errorf("show: exit %d\n%s%s", code, out, errOut)
|
||||
}
|
||||
}
|
||||
|
||||
type inlineBase struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
}
|
||||
@@ -211,3 +248,53 @@ func statExistsForTest(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// TestValuesRedactionInLists: a list leaf is printed as one value, so
|
||||
// the secret fields of its entries are redacted inside it -- by default
|
||||
// name and by a Spec key without the index -- and the rest stays.
|
||||
func TestValuesRedactionInLists(t *testing.T) {
|
||||
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
|
||||
"admins": []any{
|
||||
map[string]any{"username": "admin", "password": "changeme"},
|
||||
map[string]any{"username": "ops", "password": "env:OPS_PW", "tags": []any{"a"}},
|
||||
},
|
||||
"ids": []any{map[string]any{"name": "gc", "nested": map[string]any{"token": "t0k"}, "url": "pg://u:pw@h"}},
|
||||
"plain": []any{"x", "y"},
|
||||
}})
|
||||
e := &Effective{Name: "p", Merged: merged, Origins: origins, SecretKeys: []string{"ids.url"}}
|
||||
got := map[string]any{}
|
||||
for _, v := range e.Values(nil, false) {
|
||||
got[v.Key] = v.Value
|
||||
}
|
||||
want := map[string]any{
|
||||
"admins": []any{
|
||||
map[string]any{"username": "admin", "password": "<redacted>"},
|
||||
map[string]any{"username": "ops", "password": "env:OPS_PW", "tags": []any{"a"}},
|
||||
},
|
||||
"ids": []any{map[string]any{"name": "gc", "nested": map[string]any{"token": "<redacted>"}, "url": "<redacted>"}},
|
||||
"plain": []any{"x", "y"},
|
||||
}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Errorf("Values = %v\nwant %v", got, want)
|
||||
}
|
||||
if merged["admins"].([]any)[0].(map[string]any)["password"] != "changeme" {
|
||||
t.Error("the merged configuration was changed")
|
||||
}
|
||||
for _, v := range e.Values(nil, true) {
|
||||
if v.Key == "admins" && !strings.Contains(renderValue(v.Value), "changeme") {
|
||||
t.Errorf("show-secrets: %v", v.Value)
|
||||
}
|
||||
}
|
||||
|
||||
// Through "config show" from a file, YAML and JSON.
|
||||
root := t.TempDir()
|
||||
s := testSpec(root)
|
||||
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"),
|
||||
minimalTemplate+"users:\n - name: a\n password: hunter2\n")
|
||||
for _, args := range [][]string{{"show"}, {"show", "--json"}} {
|
||||
code, out, errOut := run(t, s, "", args...)
|
||||
if code != ExitOK || strings.Contains(out, "hunter2") || !strings.Contains(out, "<redacted>") || !strings.Contains(out, `"name"`) {
|
||||
t.Errorf("%v: exit %d\n%s%s", args, code, out, errOut)
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
-3
@@ -28,9 +28,12 @@ const DefaultOrigin = "default"
|
||||
// Values returns every leaf of e, sorted by key, with its origin.
|
||||
// used reports whether the program reads a key (nil: every key); a
|
||||
// default it does not read is left out. Secret values (keys secrets,
|
||||
// secret, token, password) are replaced by "<redacted>" unless
|
||||
// secret, token, password, and e.SecretKeys) are replaced by "<redacted>" unless
|
||||
// showSecrets; a reference that only says where a secret is (env:,
|
||||
// file:, secret://) is shown.
|
||||
// file:, secret://) is shown. A leaf that is a list is printed as one
|
||||
// value, so the same rule is applied inside it: a field of a list entry
|
||||
// is secret by its name or by its key without the index ("admins.password"
|
||||
// for the field password of every entry of the list admins).
|
||||
func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value {
|
||||
var out []Value
|
||||
walkLeaves("", e.Merged, func(key string, v any) {
|
||||
@@ -42,8 +45,12 @@ func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value {
|
||||
if !u && source == DefaultOrigin {
|
||||
return
|
||||
}
|
||||
if !showSecrets && isSecretKey(key) {
|
||||
if !showSecrets {
|
||||
if e.isSecret(key) {
|
||||
v = redact(v)
|
||||
} else {
|
||||
v = e.redactWithin(key, v)
|
||||
}
|
||||
}
|
||||
out = append(out, Value{Key: key, Value: v, Source: source, Used: u})
|
||||
})
|
||||
@@ -117,6 +124,45 @@ var secretKeys = map[string]bool{"secrets": true, "secret": true, "token": true,
|
||||
|
||||
func isSecretKey(key string) bool { return secretKeys[key[strings.LastIndex(key, ".")+1:]] }
|
||||
|
||||
// isSecret: a default secret name, or one of e.SecretKeys or a key below
|
||||
// one.
|
||||
func (e *Effective) isSecret(key string) bool {
|
||||
if isSecretKey(key) {
|
||||
return true
|
||||
}
|
||||
for _, k := range e.SecretKeys {
|
||||
if key == k || strings.HasPrefix(key, k+".") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// redactWithin redacts the secret fields of the maps inside a list (or
|
||||
// a map) leaf at key, by the same rule as isSecret. A list entry adds no
|
||||
// segment to the key. v is copied, never changed.
|
||||
func (e *Effective) redactWithin(key string, v any) any {
|
||||
switch x := v.(type) {
|
||||
case []any:
|
||||
out := make([]any, len(x))
|
||||
for i, el := range x {
|
||||
out[i] = e.redactWithin(key, el)
|
||||
}
|
||||
return out
|
||||
case map[string]any:
|
||||
out := make(map[string]any, len(x))
|
||||
for k, el := range x {
|
||||
if sub := key + "." + k; e.isSecret(sub) {
|
||||
out[k] = redact(el)
|
||||
} else {
|
||||
out[k] = e.redactWithin(sub, el)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// redact replaces secret values, keeping references that only say where
|
||||
// the secret is.
|
||||
func redact(v any) any {
|
||||
|
||||
+9
-1
@@ -38,7 +38,7 @@ the main module's `vX.Y.Z` tags do not version this one. Never move a tag.
|
||||
| `gui/assets` | `NewResolver(sources...)` over `NewFSSource` (embed.FS), `NewDirSource` (os.Root), `NewZipFileSource`/`NewZipBytesSource`; first source that has a file wins, a read error does not fall through. `ValidatePath` (checked, never cleaned), `Join`, `DetectMIME`. |
|
||||
| `gui/document` | `Prepare(ctx, res, entry, html, Options{Link})`: rewrites `assets:` / relative references in HTML and CSS (`img`, `srcset`, `script`, `link`, `style`, CSS `url()`/`@import`). Link mode -> `/assets/...` URLs, validated against the resolver; inline mode -> typed `data:` URLs (entry <= 1.5 MiB). |
|
||||
| `gui/bridge` | `NewRouter(res)`, `Router.Handle("POST /rpc/x", h)`, `Router.SetDocument`, `Router.ServeNative` (for the window's resource handler), `Router.HTML` (Go-rendered fragments through `document`). `NewSession(router, Options)` speaks protocol v1 with the page (`hello`/`ready`, `req`/`res`, `chunk`/`end` streams, `abort`, generations). `InitScript(PageConfig)` is the page side (`bridge.js`). |
|
||||
| `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`. |
|
||||
| `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource, FrameFile})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`. |
|
||||
|
||||
## Wiring
|
||||
|
||||
@@ -70,6 +70,14 @@ w.Destroy() // then: native window, on the UI thread
|
||||
The WebView2 user-data folder (`DataPath`) belongs under the program's
|
||||
`core/paths` cache or data directory (`%LOCALAPPDATA%`, never roaming).
|
||||
|
||||
`FrameFile` (since `gui/v0.2.0`) keeps the window's position, size and
|
||||
maximized state across starts: a small JSON file the program places in
|
||||
its `core/paths` state directory. It is read at `New` -- a frame that is
|
||||
on no connected screen any more is ignored and the window opens
|
||||
centered -- and written shortly after every move or resize and at
|
||||
`Destroy`. The coordinates are the platform's own (macOS: points from
|
||||
the bottom left; Windows: `WINDOWPLACEMENT`'s normal position).
|
||||
|
||||
## Invariants
|
||||
|
||||
- **No listener, no ports, no localhost.** After a transport change,
|
||||
|
||||
+2
-1
@@ -2,7 +2,8 @@
|
||||
#define YETANO_WINDOW_DARWIN_H
|
||||
#include <stdint.h>
|
||||
|
||||
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme);
|
||||
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme,
|
||||
int hasFrame, int fx, int fy, int fw, int fh, int zoomed);
|
||||
void yt_add_script(void *h, const char *js);
|
||||
void yt_navigate(void *h, const char *url);
|
||||
void yt_eval(void *h, const char *js);
|
||||
|
||||
+50
-3
@@ -18,6 +18,17 @@ extern void ytGoSchemeStop(uintptr_t h, long id);
|
||||
extern void ytGoDispatch(uintptr_t fn);
|
||||
extern void ytGoClosed(uintptr_t h);
|
||||
extern void ytGoSnapshotDone(uintptr_t h, const char *err);
|
||||
extern void ytGoFrame(uintptr_t h, int x, int y, int w, int hgt, int zoomed);
|
||||
|
||||
// YTWebView takes the first mouse click in an inactive window: without
|
||||
// it the click only activates the window, so a page (a dialog shown at
|
||||
// start) looks dead until clicked twice.
|
||||
@interface YTWebView : WKWebView
|
||||
@end
|
||||
|
||||
@implementation YTWebView
|
||||
- (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
|
||||
@end
|
||||
|
||||
@interface YTHost : NSObject <WKScriptMessageHandler, WKURLSchemeHandler, NSWindowDelegate>
|
||||
@property (assign) uintptr_t goHandle;
|
||||
@@ -26,6 +37,7 @@ extern void ytGoSnapshotDone(uintptr_t h, const char *err);
|
||||
@property (strong) NSMutableDictionary<NSNumber *, id<WKURLSchemeTask>> *tasks;
|
||||
@property (assign) long nextTask;
|
||||
@property (assign) BOOL closed;
|
||||
@property (assign) NSRect normalFrame; // the last frame while not zoomed
|
||||
@end
|
||||
|
||||
@implementation YTHost
|
||||
@@ -67,7 +79,21 @@ extern void ytGoSnapshotDone(uintptr_t h, const char *err);
|
||||
ytGoSchemeStop(self.goHandle, key.longValue);
|
||||
}
|
||||
|
||||
// The frame is reported after every move and resize; while zoomed, the
|
||||
// normal frame underneath is kept, so un-zooming returns to it.
|
||||
- (void)reportFrame {
|
||||
if (self.closed || !self.window) return;
|
||||
BOOL zoomed = self.window.isZoomed;
|
||||
if (!zoomed) self.normalFrame = self.window.frame;
|
||||
NSRect f = self.normalFrame;
|
||||
if (f.size.width <= 0) return;
|
||||
ytGoFrame(self.goHandle, (int)f.origin.x, (int)f.origin.y, (int)f.size.width, (int)f.size.height, zoomed ? 1 : 0);
|
||||
}
|
||||
- (void)windowDidMove:(NSNotification *)n { [self reportFrame]; }
|
||||
- (void)windowDidResize:(NSNotification *)n { [self reportFrame]; }
|
||||
|
||||
- (void)windowWillClose:(NSNotification *)n {
|
||||
[self reportFrame];
|
||||
if (self.closed) return;
|
||||
ytGoClosed(self.goHandle);
|
||||
yt_stop();
|
||||
@@ -102,7 +128,19 @@ static void ensureApp(void) {
|
||||
[NSApp finishLaunching];
|
||||
}
|
||||
|
||||
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme) {
|
||||
// onScreen: at least a 120 x 60 point piece of the frame (with its title
|
||||
// bar) is on a connected screen -- a frame saved on a display that is
|
||||
// gone is not restored off screen.
|
||||
static BOOL onScreen(NSRect f) {
|
||||
for (NSScreen *s in [NSScreen screens]) {
|
||||
NSRect i = NSIntersectionRect(f, s.visibleFrame);
|
||||
if (i.size.width >= 120 && i.size.height >= 60) return YES;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme,
|
||||
int hasFrame, int fx, int fy, int fw, int fh, int zoomed) {
|
||||
@autoreleasepool {
|
||||
ensureApp();
|
||||
YTHost *host = [YTHost new];
|
||||
@@ -115,7 +153,7 @@ void *yt_create(uintptr_t goHandle, const char *title, int width, int height, in
|
||||
if (debug) [cfg.preferences setValue:@YES forKey:@"developerExtrasEnabled"];
|
||||
|
||||
NSRect frame = NSMakeRect(0, 0, width, height);
|
||||
host.webview = [[WKWebView alloc] initWithFrame:frame configuration:cfg];
|
||||
host.webview = [[YTWebView alloc] initWithFrame:frame configuration:cfg];
|
||||
if (@available(macOS 13.3, *)) { if (debug) host.webview.inspectable = YES; }
|
||||
|
||||
host.window = [[NSWindow alloc] initWithContentRect:frame
|
||||
@@ -126,9 +164,17 @@ void *yt_create(uintptr_t goHandle, const char *title, int width, int height, in
|
||||
host.window.releasedWhenClosed = NO;
|
||||
host.window.title = str(title);
|
||||
host.window.contentView = host.webview;
|
||||
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.normalFrame = host.window.frame;
|
||||
host.window.delegate = host;
|
||||
[host.window makeKeyAndOrderFront:nil];
|
||||
if (restore && zoomed && !host.window.isZoomed) [host.window zoom:nil];
|
||||
[NSApp activateIgnoringOtherApps:YES];
|
||||
return (__bridge_retained void *)host;
|
||||
}
|
||||
@@ -171,6 +217,7 @@ void yt_stop(void) {
|
||||
|
||||
void yt_destroy(void *h) {
|
||||
YTHost *host = (__bridge_transfer YTHost *)h; // balances __bridge_retained
|
||||
[host reportFrame]; // a window ended by Terminate, not closed by the user
|
||||
host.closed = YES;
|
||||
for (NSNumber *k in host.tasks.allKeys) {
|
||||
// Remaining tasks are failed so WebKit does not wait forever.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+22
-1
@@ -53,6 +53,16 @@ type Options struct {
|
||||
DataPath string // WebView2 user data folder (Windows)
|
||||
OnMessage func(msg string)
|
||||
Resource ResourceHandler // nil: no native resource handler
|
||||
// FrameFile, if set, keeps the window's position and size across
|
||||
// starts: read at New (a frame that is no longer on any screen is
|
||||
// ignored), written a moment after every move or resize and at
|
||||
// Destroy. A small JSON file (Frame); the program picks the path,
|
||||
// e.g. in its state directory.
|
||||
FrameFile string
|
||||
|
||||
// Set by New for the backend.
|
||||
restore *Frame // the frame to open with, nil: default, centered
|
||||
onFrame func(Frame) // the backend reports a moved or resized window
|
||||
}
|
||||
|
||||
type backend interface {
|
||||
@@ -67,6 +77,7 @@ type backend interface {
|
||||
|
||||
// Window is a guarded native WebView window.
|
||||
type Window struct {
|
||||
frames *frameSaver
|
||||
mu sync.Mutex
|
||||
b backend
|
||||
alive bool
|
||||
@@ -92,11 +103,20 @@ func New(opt Options) (*Window, error) {
|
||||
if opt.Width == 0 {
|
||||
opt.Width, opt.Height = 1100, 820
|
||||
}
|
||||
var frames *frameSaver
|
||||
if opt.FrameFile != "" {
|
||||
frames = &frameSaver{path: opt.FrameFile}
|
||||
if f, ok := loadFrame(opt.FrameFile); ok {
|
||||
opt.restore = &f
|
||||
frames.last = f
|
||||
}
|
||||
opt.onFrame = frames.changed
|
||||
}
|
||||
b, name, base, err := newBackend(opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Window{b: b, alive: true, name: name, base: base}, nil
|
||||
return &Window{b: b, alive: true, name: name, base: base, frames: frames}, nil
|
||||
}
|
||||
|
||||
// Backend names the native backend.
|
||||
@@ -156,6 +176,7 @@ func (w *Window) Destroy() {
|
||||
w.alive = false
|
||||
w.mu.Unlock()
|
||||
w.b.Destroy()
|
||||
w.frames.flush()
|
||||
}
|
||||
|
||||
// snapshotter is implemented by backends that can render the page to PNG.
|
||||
|
||||
@@ -63,7 +63,16 @@ func newBackend(opt Options) (backend, string, string, error) {
|
||||
if opt.Debug {
|
||||
debug = 1
|
||||
}
|
||||
b.h = C.yt_create(C.uintptr_t(b.handle), title, C.int(opt.Width), C.int(opt.Height), C.int(debug), scheme)
|
||||
var has, zoomed C.int
|
||||
var f Frame
|
||||
if opt.restore != nil {
|
||||
has, f = 1, *opt.restore
|
||||
if f.Maximized {
|
||||
zoomed = 1
|
||||
}
|
||||
}
|
||||
b.h = C.yt_create(C.uintptr_t(b.handle), title, C.int(opt.Width), C.int(opt.Height), C.int(debug), scheme,
|
||||
has, C.int(f.X), C.int(f.Y), C.int(f.Width), C.int(f.Height), zoomed)
|
||||
if b.h == nil {
|
||||
b.handle.Delete()
|
||||
return nil, "", "", errUnavailable("WKWebView could not be created")
|
||||
@@ -122,6 +131,14 @@ func ytGoDispatch(fn C.uintptr_t) {
|
||||
f()
|
||||
}
|
||||
|
||||
//export ytGoFrame
|
||||
func ytGoFrame(h C.uintptr_t, x, y, w, hgt, zoomed C.int) {
|
||||
b := cgo.Handle(h).Value().(*darwinBackend)
|
||||
if b.opt.onFrame != nil {
|
||||
b.opt.onFrame(Frame{X: int(x), Y: int(y), Width: int(w), Height: int(hgt), Maximized: zoomed != 0})
|
||||
}
|
||||
}
|
||||
|
||||
//export ytGoMessage
|
||||
func ytGoMessage(h C.uintptr_t, msg *C.char) {
|
||||
b := cgo.Handle(h).Value().(*darwinBackend)
|
||||
|
||||
@@ -56,6 +56,9 @@ var (
|
||||
pDwmSetAttribute = dwmapi.NewProc("DwmSetWindowAttribute")
|
||||
pSetWindowPos = user32.NewProc("SetWindowPos")
|
||||
pGetDpiForSystem = user32.NewProc("GetDpiForSystem")
|
||||
pGetPlacement = user32.NewProc("GetWindowPlacement")
|
||||
pSetPlacement = user32.NewProc("SetWindowPlacement")
|
||||
pMonitorFromRect = user32.NewProc("MonitorFromRect")
|
||||
)
|
||||
|
||||
func setAppIcon([]byte) {} // the icon comes from the .exe resources (RT_GROUP_ICON "APP")
|
||||
@@ -168,7 +171,9 @@ func newBackend(opt Options) (backend, string, string, error) {
|
||||
windowsMu.Lock()
|
||||
byHWND[hwnd] = b
|
||||
windowsMu.Unlock()
|
||||
if f := opt.restore; f == nil || !restorePlacement(hwnd, *f) {
|
||||
pShowWindow.Call(hwnd, swShow)
|
||||
}
|
||||
pUpdateWindow.Call(hwnd)
|
||||
pSetFocus.Call(hwnd)
|
||||
|
||||
@@ -209,14 +214,17 @@ func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
|
||||
if b.chromium != nil {
|
||||
b.chromium.Resize()
|
||||
}
|
||||
b.reportFrame()
|
||||
case wmMove, wmMoving:
|
||||
if b.chromium != nil {
|
||||
_ = b.chromium.NotifyParentWindowPositionChanged()
|
||||
}
|
||||
b.reportFrame()
|
||||
case wmApp:
|
||||
b.runQueue()
|
||||
return 0
|
||||
case wmClose:
|
||||
b.reportFrame()
|
||||
pDestroyWindow.Call(hwnd)
|
||||
return 0
|
||||
case wmDestroy:
|
||||
@@ -233,6 +241,57 @@ func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
|
||||
return r
|
||||
}
|
||||
|
||||
// windowPlacement is WINDOWPLACEMENT. rcNormalPosition is the restored
|
||||
// (not maximized) frame in workspace coordinates; Get and Set use the
|
||||
// same ones, so a saved frame comes back where it was.
|
||||
type windowPlacement struct {
|
||||
length uint32
|
||||
flags uint32
|
||||
showCmd uint32
|
||||
ptMinPosition [2]int32
|
||||
ptMaxPosition [2]int32
|
||||
rcNormalPosition [4]int32 // left, top, right, bottom
|
||||
}
|
||||
|
||||
const (
|
||||
swShowNormal = 1
|
||||
swShowMinimized = 2
|
||||
swShowMaximized = 3
|
||||
wpfRestoreToMaximize = 0x0002
|
||||
)
|
||||
|
||||
// reportFrame hands the window's normal frame and maximized state to
|
||||
// Options.FrameFile's saver.
|
||||
func (b *winBackend) reportFrame() {
|
||||
if b.opt.onFrame == nil {
|
||||
return
|
||||
}
|
||||
var wp windowPlacement
|
||||
wp.length = uint32(unsafe.Sizeof(wp))
|
||||
if r, _, _ := pGetPlacement.Call(b.hwnd, uintptr(unsafe.Pointer(&wp))); r == 0 {
|
||||
return
|
||||
}
|
||||
rc := wp.rcNormalPosition
|
||||
maximized := wp.showCmd == swShowMaximized || (wp.showCmd == swShowMinimized && wp.flags&wpfRestoreToMaximize != 0)
|
||||
b.opt.onFrame(Frame{X: int(rc[0]), Y: int(rc[1]), Width: int(rc[2] - rc[0]), Height: int(rc[3] - rc[1]), Maximized: maximized})
|
||||
}
|
||||
|
||||
// restorePlacement shows the window with a saved frame, when that frame
|
||||
// is still on a monitor (MONITOR_DEFAULTTONULL); false: show it as new.
|
||||
func restorePlacement(hwnd uintptr, f Frame) bool {
|
||||
rc := [4]int32{int32(f.X), int32(f.Y), int32(f.X + f.Width), int32(f.Y + f.Height)}
|
||||
if m, _, _ := pMonitorFromRect.Call(uintptr(unsafe.Pointer(&rc)), 0); m == 0 {
|
||||
return false
|
||||
}
|
||||
wp := windowPlacement{showCmd: swShowNormal, rcNormalPosition: rc}
|
||||
if f.Maximized {
|
||||
wp.showCmd = swShowMaximized
|
||||
}
|
||||
wp.length = uint32(unsafe.Sizeof(wp))
|
||||
r, _, _ := pSetPlacement.Call(hwnd, uintptr(unsafe.Pointer(&wp)))
|
||||
return r != 0
|
||||
}
|
||||
|
||||
func (b *winBackend) runQueue() {
|
||||
b.mu.Lock()
|
||||
q := b.queue
|
||||
@@ -277,6 +336,7 @@ func (b *winBackend) Destroy() {
|
||||
b.destroying = true
|
||||
b.mu.Unlock()
|
||||
if ok, _, _ := pIsWindow.Call(b.hwnd); ok != 0 {
|
||||
b.reportFrame() // a window ended by Terminate, not closed by the user
|
||||
pDestroyWindow.Call(b.hwnd)
|
||||
}
|
||||
windowsMu.Lock()
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# yetano.dev/yetano/core/trust
|
||||
|
||||
The verifying half of the family's publisher signatures, shared by every
|
||||
program that pulls signed content: yet (packages) and yacota (images)
|
||||
check against the same files, so a host makes one trust decision.
|
||||
|
||||
```text
|
||||
module yetano.dev/yetano/core/trust tags: trust/v0.1.0, ... go 1.25
|
||||
```
|
||||
|
||||
A nested module of the core repository, like `core/tui`, so the main core
|
||||
module stays free of minisign. Depends on `aead.dev/minisign` (MIT) and
|
||||
core (`core/paths`, for `Home`). Moved from `yet/internal/trust`
|
||||
(2026-11-12) without changing behavior or file formats; signing, key
|
||||
storage, PEM and the registry side stay in yet.
|
||||
|
||||
## What it is
|
||||
|
||||
- **Signatures:** minisign (Ed25519) over the resolved OCI manifest
|
||||
digest, as the JSON payload (`Signature`, media and artifact type
|
||||
`application/vnd.yetano.signature.v1+json`) of an OCI 1.1 referrer
|
||||
on that digest. `Verify(subjectDigest, payloads)` checks fetched
|
||||
referrers (the caller fetches them with its own registry client);
|
||||
valid signatures whose key IDs collide are made invalid.
|
||||
- **Known keys** (`known-keys.json`, TOFU like SSH's known_hosts):
|
||||
`Reconcile` pins a repository's first valid signer and refuses later
|
||||
content signed only by other keys (an error that `errors.Is`
|
||||
`ErrRefused`). A key is compared as the key (`SameKey`), never by its
|
||||
ID alone.
|
||||
- **Trust policy** (`trust-policy.json`, edited with `yet trust
|
||||
policy`): rules per namespace pattern naming allowed keys,
|
||||
`require_signatures`; `Evaluate`, `AllowsCapability`, `Curated`.
|
||||
- **Where:** `Home(scope)` is yet's data directory (core/paths' DataDir
|
||||
for "yet"), `DefaultPolicyPath(home)`, `DefaultKnownKeysPath(home)`.
|
||||
|
||||
## Use
|
||||
|
||||
```go
|
||||
home, _ := trust.Home(core.UserScope)
|
||||
verified := trust.Verify(manifestDigest, payloads) // fetched referrers
|
||||
if err := trust.Reconcile(trust.DefaultKnownKeysPath(home), "registry/repo", verified); err != nil {
|
||||
return err // errors.Is(err, trust.ErrRefused): the pinned key changed
|
||||
}
|
||||
policy, _ := trust.LoadPolicy(trust.DefaultPolicyPath(home))
|
||||
if d := policy.Evaluate(name, kind, verified); !d.Trusted { ... }
|
||||
```
|
||||
|
||||
`Warn` (a variable) reports warnings that are not errors, on standard
|
||||
error by default.
|
||||
@@ -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
|
||||
}
|
||||
+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)
|
||||
}
|
||||
}
|
||||
+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,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