// Package policy is torly's write policy: which event kinds a relay accepts, which of them // need an authenticated identity, which are restricted to a set of authors, and how fast any of // them may arrive. // // It exists because "a relay for one job" is a configuration, not a fork. A rendezvous relay // wants a stored, gateway-signed presence record and rate-limited ephemeral frames; a market // relay wants signed notes from anybody; a private relay wants a handful of keys. All three // are the same four questions asked with different answers: // // - is this kind accepted at all, // - must the connection be authenticated (NIP-42), // - must the author be one of a registered set, // - and how many of them per second. // // The policy is a file, because per-kind rules do not belong in environment variables: the // answer is a small table, and a table in an env var is a parser for a format nobody can read. // Rates are per connection, so one busy client cannot spend another client's budget. package policy import ( "bytes" "encoding/hex" "encoding/json" "errors" "fmt" "math" "os" "strings" "time" "git.smesh.lol/torly/pkg/nostr" ) // Version is the policy file format this tree reads. const Version = 1 // Engine is a parsed policy. A nil Engine accepts everything, which is what a relay with no // policy file has always done. type Engine struct { rules []Rule def bool // the answer when no rule matches defText string } // Rule is one line of the table. type Rule struct { // Kinds are the kinds this rule matches. Empty matches every kind. Kinds []int `json:"kinds,omitempty"` // RequireAuth makes NIP-42 authentication mandatory, and requires the authenticated // identity to be the event's author. A signed event proves who wrote it; authentication // proves who is speaking, and a restricted kind wants both. RequireAuth bool `json:"require_auth,omitempty"` // Authors, when set, is the only set of keys allowed to publish the matched kinds. Hex, // case-insensitive. Authors []string `json:"authors,omitempty"` // Tags, when set, narrows the rule to events carrying the named tags: every name must be // present with one of the listed values. A value of "*" matches any value, which is how a // rule says "carries this tag at all". It is what separates a protocol's notes from every // other note of the same kind, so one kind can have a gateway-only rule for a protocol's // listings and a different rule for everything else. Tags map[string][]string `json:"tags,omitempty"` // Rate, when set, is the token bucket a single connection gets for the matched kinds. Rate *Rate `json:"rate,omitempty"` authors map[string]struct{} } // Rate is one connection's budget for a rule: Burst events at once, then PerSecond sustained, // and optionally the same shape measured in bytes. The byte budget is what stops a trickle of // maximum-size events from being cheap: a count alone would let one connection push // PerSecond × MaxEventBytes every second. type Rate struct { PerSecond int `json:"per_second"` Burst int `json:"burst,omitempty"` // BytesPerSecond and BytesBurst are the byte budget. Zero disables it. BytesPerSecond int `json:"bytes_per_second,omitempty"` BytesBurst int `json:"bytes_burst,omitempty"` } // Verdict is what the policy says about one event. type Verdict struct { // Allow is the decision. Allow bool // Rule is the index of the rule that decided, or -1 for the default. Rule int // Reason is a NIP-01 machine-readable prefix and a sentence, for an OK false. Reason string } // file is the on-disk form. type file struct { Version int `json:"version"` Default string `json:"default,omitempty"` Rules []Rule `json:"rules"` } // Load reads a policy file. func Load(path string) (*Engine, error) { raw, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("policy: %w", err) } engine, err := Parse(raw) if err != nil { return nil, fmt.Errorf("policy: %s: %w", path, err) } return engine, nil } // Parse reads a policy from JSON. Unknown fields are refused, so a typo in a rule is an error // at startup rather than a rule that silently does something else. func Parse(raw []byte) (*Engine, error) { var doc file decoder := json.NewDecoder(bytes.NewReader(raw)) decoder.DisallowUnknownFields() if err := decoder.Decode(&doc); err != nil { return nil, fmt.Errorf("json: %w", err) } if doc.Version != Version { return nil, fmt.Errorf("version %d, this tree reads %d", doc.Version, Version) } engine := &Engine{def: true, defText: "allow"} switch strings.ToLower(strings.TrimSpace(doc.Default)) { case "", "allow": case "deny": engine.def = false engine.defText = "deny" default: return nil, fmt.Errorf("default is %q, want allow or deny", doc.Default) } for index, rule := range doc.Rules { if err := rule.validate(); err != nil { return nil, fmt.Errorf("rule %d: %w", index, err) } engine.rules = append(engine.rules, rule) } return engine, nil } // validate checks one rule and prepares its author set. func (r *Rule) validate() error { for _, kind := range r.Kinds { if kind < 0 || kind > 65535 { return fmt.Errorf("kind %d is out of range", kind) } } if r.RequireAuth && len(r.Authors) == 0 { // Authentication without an allowlist is a valid policy (any authenticated key), so // this is not an error; it is only worth saying out loud in the documentation. _ = r } for name, values := range r.Tags { if strings.TrimSpace(name) == "" || len(values) == 0 { return fmt.Errorf("a tag predicate needs a name and at least one value") } for _, value := range values { if value == "" { return fmt.Errorf("tag %q has an empty value", name) } } } if len(r.Authors) > 0 { r.authors = make(map[string]struct{}, len(r.Authors)) for _, author := range r.Authors { text := strings.ToLower(strings.TrimSpace(author)) if len(text) != 64 { return fmt.Errorf("author %q is not 32 bytes of hex", author) } if _, err := hex.DecodeString(text); err != nil { return fmt.Errorf("author %q: %w", author, err) } r.authors[text] = struct{}{} } } if r.Rate != nil { if r.Rate.PerSecond < 1 { return fmt.Errorf("rate per_second must be at least 1") } if r.Rate.Burst == 0 { r.Rate.Burst = r.Rate.PerSecond } if r.Rate.Burst < 1 { return fmt.Errorf("rate burst must be at least 1") } if r.Rate.BytesPerSecond < 0 || r.Rate.BytesBurst < 0 { return fmt.Errorf("rate byte budgets cannot be negative") } if r.Rate.BytesPerSecond > 0 && r.Rate.BytesBurst == 0 { r.Rate.BytesBurst = r.Rate.BytesPerSecond } if r.Rate.BytesPerSecond == 0 && r.Rate.BytesBurst > 0 { return fmt.Errorf("rate bytes_burst needs bytes_per_second") } } return nil } // matches reports whether the rule covers an event: its kind, and every tag predicate. func (r Rule) matches(kind int, tags nostr.Tags) bool { if len(r.Kinds) > 0 { matched := false for _, candidate := range r.Kinds { if candidate == kind { matched = true break } } if !matched { return false } } for name, values := range r.Tags { found := false for _, value := range values { if value == "*" { if tags.HasName(name) { found = true break } continue } if tags.Has(name, value) { found = true break } } if !found { return false } } return true } // Decide answers one write. author and authedAuthor are hex; authedAuthor is empty when the // connection has not authenticated. tags is the event's tag list, which only rules that name a // tag predicate look at. The first matching rule decides, so order is significant and a // catch-all rule belongs last. func (e *Engine) Decide(kind int, author string, authed bool, authedAuthor string, tags nostr.Tags) Verdict { if e == nil { return Verdict{Allow: true, Rule: -1} } author = strings.ToLower(author) authedAuthor = strings.ToLower(authedAuthor) for index, rule := range e.rules { if !rule.matches(kind, tags) { continue } if rule.RequireAuth { if !authed { return denied(index, "auth-required: this kind may only be published by an authenticated key") } if authedAuthor == "" || authedAuthor != author { return denied(index, "auth-required: the authenticated key is not this event's author") } } if rule.authors != nil { if _, ok := rule.authors[author]; !ok { return denied(index, "blocked: this key is not registered to publish this kind") } } return Verdict{Allow: true, Rule: index} } if !e.def { return Verdict{Rule: -1, Reason: fmt.Sprintf("blocked: this relay does not accept kind %d", kind)} } return Verdict{Allow: true, Rule: -1} } // denied builds the refusal for a rule. func denied(rule int, reason string) Verdict { return Verdict{Rule: rule, Reason: reason} } // Rates reports the rate of a rule, and whether it has one. A caller that is about to spend a // token asks this once per event. func (e *Engine) Rate(rule int) (*Rate, bool) { if e == nil || rule < 0 || rule >= len(e.rules) { return nil, false } return e.rules[rule].Rate, e.rules[rule].Rate != nil } // Rules returns the parsed table, for tests and for a startup log line. func (e *Engine) Rules() []Rule { if e == nil { return nil } return e.rules } // Limiter is one connection's rate state: an event bucket and a byte bucket per rule. type Limiter struct { buckets []bucket bytes []bucket } // bucket is a token bucket. type bucket struct { tokens float64 last time.Time rate float64 burst float64 init bool } // NewLimiter returns a limiter with an empty bucket for every rule. One limiter belongs to one // connection, which is what makes the budget per client rather than per relay. func (e *Engine) NewLimiter() *Limiter { limiter := &Limiter{} if e == nil { return limiter } limiter.buckets = make([]bucket, len(e.rules)) limiter.bytes = make([]bucket, len(e.rules)) for index, rule := range e.rules { if rule.Rate == nil { continue } limiter.buckets[index] = bucket{ rate: float64(rule.Rate.PerSecond), burst: float64(rule.Rate.Burst), } limiter.bytes[index] = bucket{ rate: float64(rule.Rate.BytesPerSecond), burst: float64(rule.Rate.BytesBurst), } } return limiter } // Allow spends one event token from a rule's bucket, refilling it for the time that has passed. // A rule with no event rate always allows. The burst is available immediately, which is what a // client sending a burst of frames after a reconnect needs. func (l *Limiter) Allow(rule int, now time.Time) bool { if l == nil || rule < 0 || rule >= len(l.buckets) { return true } return spend(&l.buckets[rule], 1, now) } // AllowBytes spends size bytes from a rule's byte bucket. A rule with no byte budget always // allows, and a rule with one is charged after its event budget, so a refusal names the budget // that ran out. func (l *Limiter) AllowBytes(rule int, size int, now time.Time) bool { if l == nil || rule < 0 || rule >= len(l.bytes) { return true } return spend(&l.bytes[rule], float64(size), now) } // spend takes tokens from a bucket, refilling it first. A bucket with no rate is unlimited. func spend(b *bucket, tokens float64, now time.Time) bool { if b.rate == 0 || b.burst == 0 { return true } if !b.init { b.tokens = b.burst b.last = now b.init = true } else { elapsed := now.Sub(b.last).Seconds() if elapsed > 0 { b.tokens = math.Min(b.burst, b.tokens+elapsed*b.rate) b.last = now } } if b.tokens < tokens { return false } b.tokens -= tokens return true } // ErrNoPolicy is returned by a caller that needs an engine and has none. var ErrNoPolicy = errors.New("policy: no policy configured")