policy.go raw

   1  // Package policy is torly's write policy: which event kinds a relay accepts, which of them
   2  // need an authenticated identity, which are restricted to a set of authors, and how fast any of
   3  // them may arrive.
   4  //
   5  // It exists because "a relay for one job" is a configuration, not a fork. A rendezvous relay
   6  // wants a stored, gateway-signed presence record and rate-limited ephemeral frames; a market
   7  // relay wants signed notes from anybody; a private relay wants a handful of keys. All three
   8  // are the same four questions asked with different answers:
   9  //
  10  //   - is this kind accepted at all,
  11  //   - must the connection be authenticated (NIP-42),
  12  //   - must the author be one of a registered set,
  13  //   - and how many of them per second.
  14  //
  15  // The policy is a file, because per-kind rules do not belong in environment variables: the
  16  // answer is a small table, and a table in an env var is a parser for a format nobody can read.
  17  // Rates are per connection, so one busy client cannot spend another client's budget.
  18  package policy
  19  
  20  import (
  21  	"bytes"
  22  	"encoding/hex"
  23  	"encoding/json"
  24  	"errors"
  25  	"fmt"
  26  	"math"
  27  	"os"
  28  	"strings"
  29  	"time"
  30  
  31  	"git.smesh.lol/torly/pkg/nostr"
  32  )
  33  
  34  // Version is the policy file format this tree reads.
  35  const Version = 1
  36  
  37  // Engine is a parsed policy. A nil Engine accepts everything, which is what a relay with no
  38  // policy file has always done.
  39  type Engine struct {
  40  	rules   []Rule
  41  	def     bool // the answer when no rule matches
  42  	defText string
  43  }
  44  
  45  // Rule is one line of the table.
  46  type Rule struct {
  47  	// Kinds are the kinds this rule matches. Empty matches every kind.
  48  	Kinds []int `json:"kinds,omitempty"`
  49  	// RequireAuth makes NIP-42 authentication mandatory, and requires the authenticated
  50  	// identity to be the event's author. A signed event proves who wrote it; authentication
  51  	// proves who is speaking, and a restricted kind wants both.
  52  	RequireAuth bool `json:"require_auth,omitempty"`
  53  	// Authors, when set, is the only set of keys allowed to publish the matched kinds. Hex,
  54  	// case-insensitive.
  55  	Authors []string `json:"authors,omitempty"`
  56  	// Tags, when set, narrows the rule to events carrying the named tags: every name must be
  57  	// present with one of the listed values. A value of "*" matches any value, which is how a
  58  	// rule says "carries this tag at all". It is what separates a protocol's notes from every
  59  	// other note of the same kind, so one kind can have a gateway-only rule for a protocol's
  60  	// listings and a different rule for everything else.
  61  	Tags map[string][]string `json:"tags,omitempty"`
  62  	// Rate, when set, is the token bucket a single connection gets for the matched kinds.
  63  	Rate *Rate `json:"rate,omitempty"`
  64  
  65  	authors map[string]struct{}
  66  }
  67  
  68  // Rate is one connection's budget for a rule: Burst events at once, then PerSecond sustained,
  69  // and optionally the same shape measured in bytes. The byte budget is what stops a trickle of
  70  // maximum-size events from being cheap: a count alone would let one connection push
  71  // PerSecond × MaxEventBytes every second.
  72  type Rate struct {
  73  	PerSecond int `json:"per_second"`
  74  	Burst     int `json:"burst,omitempty"`
  75  	// BytesPerSecond and BytesBurst are the byte budget. Zero disables it.
  76  	BytesPerSecond int `json:"bytes_per_second,omitempty"`
  77  	BytesBurst     int `json:"bytes_burst,omitempty"`
  78  }
  79  
  80  // Verdict is what the policy says about one event.
  81  type Verdict struct {
  82  	// Allow is the decision.
  83  	Allow bool
  84  	// Rule is the index of the rule that decided, or -1 for the default.
  85  	Rule int
  86  	// Reason is a NIP-01 machine-readable prefix and a sentence, for an OK false.
  87  	Reason string
  88  }
  89  
  90  // file is the on-disk form.
  91  type file struct {
  92  	Version int    `json:"version"`
  93  	Default string `json:"default,omitempty"`
  94  	Rules   []Rule `json:"rules"`
  95  }
  96  
  97  // Load reads a policy file.
  98  func Load(path string) (*Engine, error) {
  99  	raw, err := os.ReadFile(path)
 100  	if err != nil {
 101  		return nil, fmt.Errorf("policy: %w", err)
 102  	}
 103  
 104  	engine, err := Parse(raw)
 105  
 106  	if err != nil {
 107  		return nil, fmt.Errorf("policy: %s: %w", path, err)
 108  	}
 109  
 110  	return engine, nil
 111  }
 112  
 113  // Parse reads a policy from JSON. Unknown fields are refused, so a typo in a rule is an error
 114  // at startup rather than a rule that silently does something else.
 115  func Parse(raw []byte) (*Engine, error) {
 116  	var doc file
 117  
 118  	decoder := json.NewDecoder(bytes.NewReader(raw))
 119  	decoder.DisallowUnknownFields()
 120  
 121  	if err := decoder.Decode(&doc); err != nil {
 122  		return nil, fmt.Errorf("json: %w", err)
 123  	}
 124  
 125  	if doc.Version != Version {
 126  		return nil, fmt.Errorf("version %d, this tree reads %d", doc.Version, Version)
 127  	}
 128  
 129  	engine := &Engine{def: true, defText: "allow"}
 130  
 131  	switch strings.ToLower(strings.TrimSpace(doc.Default)) {
 132  	case "", "allow":
 133  	case "deny":
 134  		engine.def = false
 135  		engine.defText = "deny"
 136  	default:
 137  		return nil, fmt.Errorf("default is %q, want allow or deny", doc.Default)
 138  	}
 139  
 140  	for index, rule := range doc.Rules {
 141  		if err := rule.validate(); err != nil {
 142  			return nil, fmt.Errorf("rule %d: %w", index, err)
 143  		}
 144  
 145  		engine.rules = append(engine.rules, rule)
 146  	}
 147  
 148  	return engine, nil
 149  }
 150  
 151  // validate checks one rule and prepares its author set.
 152  func (r *Rule) validate() error {
 153  	for _, kind := range r.Kinds {
 154  		if kind < 0 || kind > 65535 {
 155  			return fmt.Errorf("kind %d is out of range", kind)
 156  		}
 157  	}
 158  
 159  	if r.RequireAuth && len(r.Authors) == 0 {
 160  		// Authentication without an allowlist is a valid policy (any authenticated key), so
 161  		// this is not an error; it is only worth saying out loud in the documentation.
 162  		_ = r
 163  	}
 164  
 165  	for name, values := range r.Tags {
 166  		if strings.TrimSpace(name) == "" || len(values) == 0 {
 167  			return fmt.Errorf("a tag predicate needs a name and at least one value")
 168  		}
 169  
 170  		for _, value := range values {
 171  			if value == "" {
 172  				return fmt.Errorf("tag %q has an empty value", name)
 173  			}
 174  		}
 175  	}
 176  
 177  	if len(r.Authors) > 0 {
 178  		r.authors = make(map[string]struct{}, len(r.Authors))
 179  
 180  		for _, author := range r.Authors {
 181  			text := strings.ToLower(strings.TrimSpace(author))
 182  
 183  			if len(text) != 64 {
 184  				return fmt.Errorf("author %q is not 32 bytes of hex", author)
 185  			}
 186  
 187  			if _, err := hex.DecodeString(text); err != nil {
 188  				return fmt.Errorf("author %q: %w", author, err)
 189  			}
 190  
 191  			r.authors[text] = struct{}{}
 192  		}
 193  	}
 194  
 195  	if r.Rate != nil {
 196  		if r.Rate.PerSecond < 1 {
 197  			return fmt.Errorf("rate per_second must be at least 1")
 198  		}
 199  
 200  		if r.Rate.Burst == 0 {
 201  			r.Rate.Burst = r.Rate.PerSecond
 202  		}
 203  
 204  		if r.Rate.Burst < 1 {
 205  			return fmt.Errorf("rate burst must be at least 1")
 206  		}
 207  
 208  		if r.Rate.BytesPerSecond < 0 || r.Rate.BytesBurst < 0 {
 209  			return fmt.Errorf("rate byte budgets cannot be negative")
 210  		}
 211  
 212  		if r.Rate.BytesPerSecond > 0 && r.Rate.BytesBurst == 0 {
 213  			r.Rate.BytesBurst = r.Rate.BytesPerSecond
 214  		}
 215  
 216  		if r.Rate.BytesPerSecond == 0 && r.Rate.BytesBurst > 0 {
 217  			return fmt.Errorf("rate bytes_burst needs bytes_per_second")
 218  		}
 219  	}
 220  
 221  	return nil
 222  }
 223  
 224  // matches reports whether the rule covers an event: its kind, and every tag predicate.
 225  func (r Rule) matches(kind int, tags nostr.Tags) bool {
 226  	if len(r.Kinds) > 0 {
 227  		matched := false
 228  
 229  		for _, candidate := range r.Kinds {
 230  			if candidate == kind {
 231  				matched = true
 232  
 233  				break
 234  			}
 235  		}
 236  
 237  		if !matched {
 238  			return false
 239  		}
 240  	}
 241  
 242  	for name, values := range r.Tags {
 243  		found := false
 244  
 245  		for _, value := range values {
 246  			if value == "*" {
 247  				if tags.HasName(name) {
 248  					found = true
 249  
 250  					break
 251  				}
 252  
 253  				continue
 254  			}
 255  
 256  			if tags.Has(name, value) {
 257  				found = true
 258  
 259  				break
 260  			}
 261  		}
 262  
 263  		if !found {
 264  			return false
 265  		}
 266  	}
 267  
 268  	return true
 269  }
 270  
 271  // Decide answers one write. author and authedAuthor are hex; authedAuthor is empty when the
 272  // connection has not authenticated. tags is the event's tag list, which only rules that name a
 273  // tag predicate look at. The first matching rule decides, so order is significant and a
 274  // catch-all rule belongs last.
 275  func (e *Engine) Decide(kind int, author string, authed bool, authedAuthor string, tags nostr.Tags) Verdict {
 276  	if e == nil {
 277  		return Verdict{Allow: true, Rule: -1}
 278  	}
 279  
 280  	author = strings.ToLower(author)
 281  	authedAuthor = strings.ToLower(authedAuthor)
 282  
 283  	for index, rule := range e.rules {
 284  		if !rule.matches(kind, tags) {
 285  			continue
 286  		}
 287  
 288  		if rule.RequireAuth {
 289  			if !authed {
 290  				return denied(index, "auth-required: this kind may only be published by an authenticated key")
 291  			}
 292  
 293  			if authedAuthor == "" || authedAuthor != author {
 294  				return denied(index, "auth-required: the authenticated key is not this event's author")
 295  			}
 296  		}
 297  
 298  		if rule.authors != nil {
 299  			if _, ok := rule.authors[author]; !ok {
 300  				return denied(index, "blocked: this key is not registered to publish this kind")
 301  			}
 302  		}
 303  
 304  		return Verdict{Allow: true, Rule: index}
 305  	}
 306  
 307  	if !e.def {
 308  		return Verdict{Rule: -1, Reason: fmt.Sprintf("blocked: this relay does not accept kind %d", kind)}
 309  	}
 310  
 311  	return Verdict{Allow: true, Rule: -1}
 312  }
 313  
 314  // denied builds the refusal for a rule.
 315  func denied(rule int, reason string) Verdict {
 316  	return Verdict{Rule: rule, Reason: reason}
 317  }
 318  
 319  // Rates reports the rate of a rule, and whether it has one. A caller that is about to spend a
 320  // token asks this once per event.
 321  func (e *Engine) Rate(rule int) (*Rate, bool) {
 322  	if e == nil || rule < 0 || rule >= len(e.rules) {
 323  		return nil, false
 324  	}
 325  
 326  	return e.rules[rule].Rate, e.rules[rule].Rate != nil
 327  }
 328  
 329  // Rules returns the parsed table, for tests and for a startup log line.
 330  func (e *Engine) Rules() []Rule {
 331  	if e == nil {
 332  		return nil
 333  	}
 334  
 335  	return e.rules
 336  }
 337  
 338  // Limiter is one connection's rate state: an event bucket and a byte bucket per rule.
 339  type Limiter struct {
 340  	buckets []bucket
 341  	bytes   []bucket
 342  }
 343  
 344  // bucket is a token bucket.
 345  type bucket struct {
 346  	tokens float64
 347  	last   time.Time
 348  	rate   float64
 349  	burst  float64
 350  	init   bool
 351  }
 352  
 353  // NewLimiter returns a limiter with an empty bucket for every rule. One limiter belongs to one
 354  // connection, which is what makes the budget per client rather than per relay.
 355  func (e *Engine) NewLimiter() *Limiter {
 356  	limiter := &Limiter{}
 357  
 358  	if e == nil {
 359  		return limiter
 360  	}
 361  
 362  	limiter.buckets = make([]bucket, len(e.rules))
 363  	limiter.bytes = make([]bucket, len(e.rules))
 364  
 365  	for index, rule := range e.rules {
 366  		if rule.Rate == nil {
 367  			continue
 368  		}
 369  
 370  		limiter.buckets[index] = bucket{
 371  			rate:  float64(rule.Rate.PerSecond),
 372  			burst: float64(rule.Rate.Burst),
 373  		}
 374  
 375  		limiter.bytes[index] = bucket{
 376  			rate:  float64(rule.Rate.BytesPerSecond),
 377  			burst: float64(rule.Rate.BytesBurst),
 378  		}
 379  	}
 380  
 381  	return limiter
 382  }
 383  
 384  // Allow spends one event token from a rule's bucket, refilling it for the time that has passed.
 385  // A rule with no event rate always allows. The burst is available immediately, which is what a
 386  // client sending a burst of frames after a reconnect needs.
 387  func (l *Limiter) Allow(rule int, now time.Time) bool {
 388  	if l == nil || rule < 0 || rule >= len(l.buckets) {
 389  		return true
 390  	}
 391  
 392  	return spend(&l.buckets[rule], 1, now)
 393  }
 394  
 395  // AllowBytes spends size bytes from a rule's byte bucket. A rule with no byte budget always
 396  // allows, and a rule with one is charged after its event budget, so a refusal names the budget
 397  // that ran out.
 398  func (l *Limiter) AllowBytes(rule int, size int, now time.Time) bool {
 399  	if l == nil || rule < 0 || rule >= len(l.bytes) {
 400  		return true
 401  	}
 402  
 403  	return spend(&l.bytes[rule], float64(size), now)
 404  }
 405  
 406  // spend takes tokens from a bucket, refilling it first. A bucket with no rate is unlimited.
 407  func spend(b *bucket, tokens float64, now time.Time) bool {
 408  	if b.rate == 0 || b.burst == 0 {
 409  		return true
 410  	}
 411  
 412  	if !b.init {
 413  		b.tokens = b.burst
 414  		b.last = now
 415  		b.init = true
 416  	} else {
 417  		elapsed := now.Sub(b.last).Seconds()
 418  
 419  		if elapsed > 0 {
 420  			b.tokens = math.Min(b.burst, b.tokens+elapsed*b.rate)
 421  			b.last = now
 422  		}
 423  	}
 424  
 425  	if b.tokens < tokens {
 426  		return false
 427  	}
 428  
 429  	b.tokens -= tokens
 430  
 431  	return true
 432  }
 433  
 434  // ErrNoPolicy is returned by a caller that needs an engine and has none.
 435  var ErrNoPolicy = errors.New("policy: no policy configured")
 436