proof.go raw

   1  package deed
   2  
   3  import (
   4  	"fmt"
   5  	"net/url"
   6  	"strconv"
   7  	"strings"
   8  	"sync"
   9  	"time"
  10  
  11  	"git.smesh.lol/orly/pkg/nostr/encoders/event"
  12  	"git.smesh.lol/orly/pkg/nostr/encoders/hex"
  13  	"git.smesh.lol/orly/pkg/nostr/encoders/kind"
  14  )
  15  
  16  // PresentDomain is the required content of a 22243 presentation proof. It is
  17  // the domain separator that stops a signature made for another purpose from
  18  // being replayed as a proof of possession.
  19  const PresentDomain = "musiquay.present:v1"
  20  
  21  // PresentationProof is a parsed kind 22243 event.
  22  type PresentationProof struct {
  23  	Event *event.E
  24  	// DeedID is the deed event id being presented.
  25  	DeedID string
  26  	// AssetID is the asset actually requested.
  27  	AssetID string
  28  	// Server is the host named by the proof.
  29  	Server string
  30  	// Nonce is the client-generated single-use nonce.
  31  	Nonce string
  32  	// Expires is the unix expiration.
  33  	Expires int64
  34  }
  35  
  36  // ParseProof structurally validates a presentation proof: kind, domain
  37  // content, signature, and the presence of its mandatory tags. It does not
  38  // check freshness, binding, or replay.
  39  func ParseProof(ev *event.E) (*PresentationProof, error) {
  40  	if ev == nil {
  41  		return nil, fmt.Errorf("deed: nil presentation proof")
  42  	}
  43  	if ev.Kind != kind.DeedPresentation.ToU16() {
  44  		return nil, fmt.Errorf("deed: kind %d is not a presentation proof", ev.Kind)
  45  	}
  46  	if string(ev.Content) != PresentDomain {
  47  		return nil, fmt.Errorf("deed: presentation proof content is not %q", PresentDomain)
  48  	}
  49  	if valid, err := ev.Verify(); err != nil {
  50  		return nil, fmt.Errorf("deed: verify presentation proof: %w", err)
  51  	} else if !valid {
  52  		return nil, fmt.Errorf("deed: presentation proof signature invalid")
  53  	}
  54  	p := &PresentationProof{
  55  		Event:   ev,
  56  		DeedID:  tagValue(ev, TagDeed),
  57  		AssetID: tagValue(ev, TagAsset),
  58  		Server:  tagValue(ev, TagServer),
  59  		Nonce:   tagValue(ev, TagNonce),
  60  	}
  61  	if len(p.DeedID) != 64 {
  62  		return nil, fmt.Errorf("deed: presentation proof has no valid deed tag")
  63  	}
  64  	if !IsAssetID(p.AssetID) {
  65  		return nil, fmt.Errorf("deed: presentation proof has no valid asset tag")
  66  	}
  67  	if p.Server == "" {
  68  		return nil, fmt.Errorf("deed: presentation proof has no server tag")
  69  	}
  70  	if !validNonce(p.Nonce) {
  71  		return nil, fmt.Errorf("deed: presentation proof has an invalid nonce")
  72  	}
  73  	exp := tagValue(ev, TagExpiration)
  74  	if exp == "" {
  75  		return nil, fmt.Errorf("deed: presentation proof has no expiration")
  76  	}
  77  	n, err := strconv.ParseInt(exp, 10, 64)
  78  	if err != nil {
  79  		return nil, fmt.Errorf("deed: presentation proof has an invalid expiration")
  80  	}
  81  	p.Expires = n
  82  	return p, nil
  83  }
  84  
  85  // validNonce bounds the nonce so a client cannot blow up the cache with one
  86  // enormous value, and rejects whitespace that would confuse logging.
  87  func validNonce(n string) bool {
  88  	if len(n) < 8 || len(n) > 128 {
  89  		return false
  90  	}
  91  	for i := 0; i < len(n); i++ {
  92  		c := n[i]
  93  		if c <= 0x20 || c == 0x7f {
  94  			return false
  95  		}
  96  	}
  97  	return true
  98  }
  99  
 100  // ProofVerifyOptions is everything a host must supply to accept a proof.
 101  type ProofVerifyOptions struct {
 102  	// Deed is the already-verified deed being presented.
 103  	Deed *Deed
 104  	// RequestedAssetID is the asset the request is for.
 105  	RequestedAssetID string
 106  	// Server is this host's domain or origin.
 107  	Server string
 108  	// RequestPubkey is the BUD-11 request identity.
 109  	RequestPubkey []byte
 110  	// Now overrides the clock.
 111  	Now time.Time
 112  	// MaxAge is how old created_at may be. Zero means five minutes.
 113  	MaxAge time.Duration
 114  	// Nonces enforces single use. Required.
 115  	Nonces *NonceCache
 116  }
 117  
 118  // Verify checks binding, freshness, scope, and single use.
 119  //
 120  // The proof must have been signed by the deed's buyer and by the same key that
 121  // signed the request, must name the requested asset, this server, and a fresh
 122  // nonce that has not been seen for that key. Those five checks together stop a
 123  // copied deed, a proof replayed to another host, and a proof captured from
 124  // another request from being useful.
 125  func (p *PresentationProof) Verify(o ProofVerifyOptions) error {
 126  	if o.Deed == nil {
 127  		return fmt.Errorf("deed: presentation proof has no deed to bind to")
 128  	}
 129  	if !equalBytes(p.Event.Pubkey, o.Deed.Buyer) {
 130  		return fmt.Errorf("deed: presentation proof signer is not the deed buyer")
 131  	}
 132  	if len(o.RequestPubkey) != 32 || !equalBytes(p.Event.Pubkey, o.RequestPubkey) {
 133  		return fmt.Errorf("deed: presentation proof signer is not the request identity")
 134  	}
 135  	if !IsAssetID(o.RequestedAssetID) {
 136  		return fmt.Errorf("deed: requested asset id is invalid")
 137  	}
 138  	if p.AssetID != o.RequestedAssetID {
 139  		return fmt.Errorf("deed: presentation proof names asset %s, request is for %s", p.AssetID, o.RequestedAssetID)
 140  	}
 141  	if p.DeedID != o.Deed.ID() {
 142  		return fmt.Errorf("deed: presentation proof names a different deed")
 143  	}
 144  	if o.Server == "" {
 145  		return fmt.Errorf("deed: no server to bind the proof to")
 146  	}
 147  	if !sameServer(p.Server, o.Server) {
 148  		return fmt.Errorf("deed: presentation proof is for server %q, not %q", p.Server, o.Server)
 149  	}
 150  
 151  	now := o.Now
 152  	if now.IsZero() {
 153  		now = time.Now()
 154  	}
 155  	maxAge := o.MaxAge
 156  	if maxAge <= 0 {
 157  		maxAge = 5 * time.Minute
 158  	}
 159  	if p.Event.CreatedAt > now.Add(60*time.Second).Unix() {
 160  		return fmt.Errorf("deed: presentation proof created_at is in the future")
 161  	}
 162  	if p.Event.CreatedAt < now.Add(-maxAge).Unix() {
 163  		return fmt.Errorf("deed: presentation proof is stale")
 164  	}
 165  	if p.Expires <= now.Unix() {
 166  		return fmt.Errorf("deed: presentation proof expired")
 167  	}
 168  	if p.Expires > now.Add(maxAge).Unix() {
 169  		return fmt.Errorf("deed: presentation proof expiration is too far in the future")
 170  	}
 171  	if o.Nonces == nil {
 172  		return fmt.Errorf("deed: presentation proof requires a nonce cache")
 173  	}
 174  	if !o.Nonces.Use(hex.Enc(p.Event.Pubkey), p.Nonce) {
 175  		return fmt.Errorf("deed: presentation proof nonce has already been used")
 176  	}
 177  	return nil
 178  }
 179  
 180  // sameServer compares a proof's server tag with this host. Both may be bare
 181  // hosts or full origins; the host names must match and a named port must match.
 182  func sameServer(a, b string) bool {
 183  	ha, pa := hostPort(a)
 184  	hb, pb := hostPort(b)
 185  	if ha == "" || hb == "" {
 186  		return false
 187  	}
 188  	if !strings.EqualFold(ha, hb) {
 189  		return false
 190  	}
 191  	if pa != "" && pb != "" && pa != pb {
 192  		return false
 193  	}
 194  	return true
 195  }
 196  
 197  func hostPort(raw string) (host, port string) {
 198  	raw = strings.TrimSpace(raw)
 199  	if !strings.Contains(raw, "://") {
 200  		raw = "https://" + raw
 201  	}
 202  	u, err := url.Parse(raw)
 203  	if err != nil || u.Host == "" {
 204  		return "", ""
 205  	}
 206  	return strings.ToLower(u.Hostname()), u.Port()
 207  }
 208  
 209  // NonceCache remembers (pubkey, nonce) pairs for a bounded window.
 210  //
 211  // The cache is deliberately in memory: a durable write per GET is the same
 212  // latency problem the proof replaced. A restart loses the window, which only
 213  // means a proof that was valid at the restart may be accepted once more; the
 214  // proof's own expiration bounds that.
 215  type NonceCache struct {
 216  	mu        sync.Mutex
 217  	ttl       time.Duration
 218  	seen      map[string]int64
 219  	lastFlush time.Time
 220  }
 221  
 222  // NewNonceCache creates a cache whose entries live for ttl.
 223  func NewNonceCache(ttl time.Duration) *NonceCache {
 224  	if ttl <= 0 {
 225  		ttl = 10 * time.Minute
 226  	}
 227  	return &NonceCache{ttl: ttl, seen: make(map[string]int64), lastFlush: time.Now()}
 228  }
 229  
 230  // Use records a nonce and reports whether it was fresh. It is atomic, so two
 231  // concurrent requests with the same proof cannot both succeed.
 232  func (c *NonceCache) Use(pubkeyHex, nonce string) bool {
 233  	key := pubkeyHex + "|" + nonce
 234  	now := time.Now().Unix()
 235  	c.mu.Lock()
 236  	defer c.mu.Unlock()
 237  	c.flushLocked(now)
 238  	if exp, ok := c.seen[key]; ok && exp > now {
 239  		return false
 240  	}
 241  	c.seen[key] = now + int64(c.ttl/time.Second)
 242  	return true
 243  }
 244  
 245  // Flush prunes expired entries. Call it periodically from a service loop.
 246  func (c *NonceCache) Flush() {
 247  	now := time.Now().Unix()
 248  	c.mu.Lock()
 249  	c.flushLocked(now)
 250  	c.mu.Unlock()
 251  }
 252  
 253  func (c *NonceCache) flushLocked(now int64) {
 254  	if now-c.lastFlush.Unix() < 60 && len(c.seen) < 100000 {
 255  		return
 256  	}
 257  	for k, exp := range c.seen {
 258  		if exp <= now {
 259  			delete(c.seen, k)
 260  		}
 261  	}
 262  	c.lastFlush = time.Unix(now, 0)
 263  }
 264  
 265  // Len reports the number of live entries, for tests and metrics.
 266  func (c *NonceCache) Len() int {
 267  	c.mu.Lock()
 268  	defer c.mu.Unlock()
 269  	return len(c.seen)
 270  }
 271