From 35f8b7d18aba6bb631bf0acd8f877e3c0f6432eb Mon Sep 17 00:00:00 2001 From: Bjoern Kalkbrenner Date: Thu, 12 Nov 2026 16:27:35 +0100 Subject: [PATCH] trust: the verifying half of publisher signatures (own module) Moved from yet/internal/trust, behavior and file formats unchanged, so yacota (images) checks against the same trust-policy.json and known-keys.json as yet (packages): the signature payload and its check (Verify over fetched referrers), known keys with TOFU pinning (Reconcile; refusals are ErrRefused), the trust policy (Evaluate, AllowsCapability), Curated, Pinned and Home (yet's data directory). Signing, key storage and the registry side stay in yet. Co-Authored-By: Claude Opus 5.5 --- README.md | 10 +- trust/README.md | 49 +++ trust/go.mod | 13 + trust/go.sum | 12 + trust/home.go | 37 +++ trust/keys.go | 185 +++++++++++ trust/known_keys.go | 315 ++++++++++++++++++ trust/new_test.go | 76 +++++ trust/policy.go | 331 +++++++++++++++++++ trust/trust_test.go | 754 ++++++++++++++++++++++++++++++++++++++++++++ trust/verify.go | 142 +++++++++ 11 files changed, 1921 insertions(+), 3 deletions(-) create mode 100644 trust/README.md create mode 100644 trust/go.mod create mode 100644 trust/go.sum create mode 100644 trust/home.go create mode 100644 trust/keys.go create mode 100644 trust/known_keys.go create mode 100644 trust/new_test.go create mode 100644 trust/policy.go create mode 100644 trust/trust_test.go create mode 100644 trust/verify.go diff --git a/README.md b/README.md index d77f3a4..0227422 100644 --- a/README.md +++ b/README.md @@ -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 @@ -460,8 +463,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 diff --git a/trust/README.md b/trust/README.md new file mode 100644 index 0000000..a984f96 --- /dev/null +++ b/trust/README.md @@ -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. diff --git a/trust/go.mod b/trust/go.mod new file mode 100644 index 0000000..82e943d --- /dev/null +++ b/trust/go.mod @@ -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 +) diff --git a/trust/go.sum b/trust/go.sum new file mode 100644 index 0000000..bfb2ab9 --- /dev/null +++ b/trust/go.sum @@ -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= diff --git a/trust/home.go b/trust/home.go new file mode 100644 index 0000000..5794389 --- /dev/null +++ b/trust/home.go @@ -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 +} diff --git a/trust/keys.go b/trust/keys.go new file mode 100644 index 0000000..584f3a1 --- /dev/null +++ b/trust/keys.go @@ -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...) +} diff --git a/trust/known_keys.go b/trust/known_keys.go new file mode 100644 index 0000000..03f0c22 --- /dev/null +++ b/trust/known_keys.go @@ -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 \" 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 +} diff --git a/trust/new_test.go b/trust/new_test.go new file mode 100644 index 0000000..b0e9956 --- /dev/null +++ b/trust/new_test.go @@ -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) + } +} diff --git a/trust/policy.go b/trust/policy.go new file mode 100644 index 0000000..f65cec1 --- /dev/null +++ b/trust/policy.go @@ -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 +} diff --git a/trust/trust_test.go b/trust/trust_test.go new file mode 100644 index 0000000..3431587 --- /dev/null +++ b/trust/trust_test.go @@ -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") + } +} diff --git a/trust/verify.go b/trust/verify.go new file mode 100644 index 0000000..a243d75 --- /dev/null +++ b/trust/verify.go @@ -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...)} +}