Files

331 lines
12 KiB
Go
Raw Permalink Normal View History

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
}