policy_test.go raw

   1  package policy
   2  
   3  import (
   4  	"strings"
   5  	"testing"
   6  	"time"
   7  
   8  	"git.smesh.lol/torly/pkg/nostr"
   9  )
  10  
  11  const gateway = "1111111111111111111111111111111111111111111111111111111111111111"
  12  const stranger = "2222222222222222222222222222222222222222222222222222222222222222"
  13  
  14  // parse builds an engine from a policy document, failing the test on a parse error.
  15  func parse(t *testing.T, raw string) *Engine {
  16  	t.Helper()
  17  
  18  	engine, err := Parse([]byte(raw))
  19  
  20  	if err != nil {
  21  		t.Fatalf("Parse: %v", err)
  22  	}
  23  
  24  	return engine
  25  }
  26  
  27  // TestNoPolicyAllowsEverything: a relay without a policy file behaves exactly as it always
  28  // has. A nil engine is the default, not an error.
  29  func TestNoPolicyAllowsEverything(t *testing.T) {
  30  	var engine *Engine
  31  
  32  	if verdict := engine.Decide(1, stranger, false, "", nil); !verdict.Allow {
  33  		t.Fatalf("nil engine refused: %+v", verdict)
  34  	}
  35  
  36  	limiter := engine.NewLimiter()
  37  
  38  	for i := 0; i < 100; i++ {
  39  		if !limiter.Allow(0, time.Now()) {
  40  			t.Fatal("nil engine rate-limited")
  41  		}
  42  	}
  43  }
  44  
  45  // TestGatewayKindsNeedAuthAndTheRegisteredKey: the rendezvous rule. The stored kind is
  46  // restricted to one key, and a connection must have authenticated as that key.
  47  func TestGatewayKindsNeedAuthAndTheRegisteredKey(t *testing.T) {
  48  	engine := parse(t, `{
  49  		"version": 1,
  50  		"default": "deny",
  51  		"rules": [
  52  			{"kinds": [30333], "require_auth": true, "authors": ["`+gateway+`"]},
  53  			{"kinds": [23196, 23197]}
  54  		]
  55  	}`)
  56  
  57  	// Unauthenticated: auth-required, not "blocked by author".
  58  	verdict := engine.Decide(30333, gateway, false, "", nil)
  59  
  60  	if verdict.Allow {
  61  		t.Fatal("an unauthenticated presence record was allowed")
  62  	}
  63  
  64  	if !strings.HasPrefix(verdict.Reason, "auth-required:") {
  65  		t.Fatalf("reason = %q", verdict.Reason)
  66  	}
  67  
  68  	// Authenticated as somebody else: refused, because the speaker is not the author.
  69  	verdict = engine.Decide(30333, gateway, true, stranger, nil)
  70  
  71  	if verdict.Allow || !strings.HasPrefix(verdict.Reason, "auth-required:") {
  72  		t.Fatalf("a different authenticated key was allowed: %+v", verdict)
  73  	}
  74  
  75  	// Authenticated as the registered key: allowed.
  76  	if verdict := engine.Decide(30333, gateway, true, gateway, nil); !verdict.Allow {
  77  		t.Fatalf("the registered gateway was refused: %+v", verdict)
  78  	}
  79  
  80  	// Ephemeral frames are open, authenticated or not.
  81  	if verdict := engine.Decide(23196, stranger, false, "", nil); !verdict.Allow {
  82  		t.Fatalf("an ephemeral frame was refused: %+v", verdict)
  83  	}
  84  
  85  	// Anything else is denied by the default.
  86  	verdict = engine.Decide(1, stranger, false, "", nil)
  87  
  88  	if verdict.Allow || !strings.Contains(verdict.Reason, "kind 1") {
  89  		t.Fatalf("an unlisted kind was allowed: %+v", verdict)
  90  	}
  91  }
  92  
  93  // TestOrderDecides: the first matching rule wins, so a specific rule must come before a
  94  // catch-all. That is the property that makes a table readable.
  95  func TestOrderDecides(t *testing.T) {
  96  	engine := parse(t, `{
  97  		"version": 1,
  98  		"rules": [
  99  			{"kinds": [5], "require_auth": true, "authors": ["`+gateway+`"]},
 100  			{}
 101  		]
 102  	}`)
 103  
 104  	if verdict := engine.Decide(5, gateway, false, "", nil); verdict.Allow {
 105  		t.Fatal("the specific rule was not reached first")
 106  	}
 107  
 108  	if verdict := engine.Decide(1, gateway, false, "", nil); !verdict.Allow {
 109  		t.Fatalf("the catch-all did not allow kind 1: %+v", verdict)
 110  	}
 111  }
 112  
 113  // TestAuthorOnlyWithoutAuth: an allowlist without require_auth is still an allowlist; the
 114  // signature is the proof, and authentication is only needed when the connection's identity
 115  // matters as well.
 116  func TestAuthorOnlyWithoutAuth(t *testing.T) {
 117  	engine := parse(t, `{
 118  		"version": 1,
 119  		"rules": [{"kinds": [30333], "authors": ["`+gateway+`"]}]
 120  	}`)
 121  
 122  	if verdict := engine.Decide(30333, gateway, false, "", nil); !verdict.Allow {
 123  		t.Fatalf("the registered key was refused: %+v", verdict)
 124  	}
 125  
 126  	if verdict := engine.Decide(30333, stranger, true, stranger, nil); verdict.Allow {
 127  		t.Fatal("an unregistered key was allowed to sign a restricted kind")
 128  	}
 129  }
 130  
 131  // TestRateIsPerLimiter: two connections have separate budgets, and a bucket refills with time.
 132  func TestRateIsPerLimiter(t *testing.T) {
 133  	engine := parse(t, `{
 134  		"version": 1,
 135  		"rules": [{"kinds": [23196], "rate": {"per_second": 10, "burst": 2}}]
 136  	}`)
 137  
 138  	first := engine.NewLimiter()
 139  	second := engine.NewLimiter()
 140  	now := time.Unix(1_700_000_000, 0)
 141  
 142  	if !first.Allow(0, now) || !first.Allow(0, now) {
 143  		t.Fatal("the burst was refused")
 144  	}
 145  
 146  	if first.Allow(0, now) {
 147  		t.Fatal("a third event slipped past a burst of two")
 148  	}
 149  
 150  	if !second.Allow(0, now) {
 151  		t.Fatal("one connection spent another's budget")
 152  	}
 153  
 154  	// A second later the bucket holds ten more tokens, capped at the burst.
 155  	later := now.Add(time.Second)
 156  
 157  	if !first.Allow(0, later) || !first.Allow(0, later) {
 158  		t.Fatal("the bucket did not refill")
 159  	}
 160  
 161  	if first.Allow(0, later) {
 162  		t.Fatal("the refill exceeded the burst")
 163  	}
 164  }
 165  
 166  // TestMalformedPoliciesAreRefused: a typo in a policy is an error at startup, not a rule that
 167  // quietly does something else.
 168  func TestMalformedPoliciesAreRefused(t *testing.T) {
 169  	cases := map[string]string{
 170  		"no version":        `{"rules": []}`,
 171  		"wrong version":     `{"version": 2, "rules": []}`,
 172  		"unknown field":     `{"version": 1, "rule": []}`,
 173  		"bad default":       `{"version": 1, "default": "maybe", "rules": []}`,
 174  		"kind out of range": `{"version": 1, "rules": [{"kinds": [70000]}]}`,
 175  		"short author":      `{"version": 1, "rules": [{"authors": ["abcd"]}]}`,
 176  		"non-hex author":    `{"version": 1, "rules": [{"authors": ["` + strings.Repeat("zz", 32) + `"]}]}`,
 177  		"zero rate":         `{"version": 1, "rules": [{"rate": {"per_second": 0}}]}`,
 178  		"negative burst":    `{"version": 1, "rules": [{"rate": {"per_second": 10, "burst": -1}}]}`,
 179  	}
 180  
 181  	for name, raw := range cases {
 182  		if _, err := Parse([]byte(raw)); err == nil {
 183  			t.Fatalf("%s: accepted", name)
 184  		}
 185  	}
 186  }
 187  
 188  // TestAnEmptyRulesetWithDeny: a deny-by-default policy with no rules is a relay that accepts
 189  // no writes, which is a legal (if useless) configuration and must not be silently permissive.
 190  func TestAnEmptyRulesetWithDeny(t *testing.T) {
 191  	engine := parse(t, `{"version": 1, "default": "deny", "rules": []}`)
 192  
 193  	if verdict := engine.Decide(1, stranger, false, "", nil); verdict.Allow {
 194  		t.Fatal("a deny-by-default policy allowed a write")
 195  	}
 196  }
 197  
 198  // TestByteBudgetStopsAMaximumSizeTrickle: a count per second alone lets one connection push
 199  // PerSecond × max-event-size bytes; the byte budget is what bounds the bandwidth.
 200  func TestByteBudgetStopsAMaximumSizeTrickle(t *testing.T) {
 201  	engine := parse(t, `{
 202  		"version": 1,
 203  		"rules": [{"kinds": [23196], "rate": {"per_second": 1000, "burst": 1000,
 204  			"bytes_per_second": 1, "bytes_burst": 1500}}]
 205  	}`)
 206  
 207  	limiter := engine.NewLimiter()
 208  	now := time.Unix(1_700_000_000, 0)
 209  
 210  	if !limiter.Allow(0, now) || !limiter.AllowBytes(0, 700, now) {
 211  		t.Fatal("the first event was refused")
 212  	}
 213  
 214  	if !limiter.Allow(0, now) || !limiter.AllowBytes(0, 700, now) {
 215  		t.Fatal("the second event was refused")
 216  	}
 217  
 218  	if !limiter.Allow(0, now) {
 219  		t.Fatal("the event budget was spent by two events")
 220  	}
 221  
 222  	if limiter.AllowBytes(0, 700, now) {
 223  		t.Fatal("a third event slipped past the byte budget")
 224  	}
 225  }
 226  
 227  // TestTagPredicatesSeparateProtocolNotes: one kind can carry a gateway-only rule for a protocol's
 228  // listings and a different rule for every other note of the same kind. Without tags, "only the
 229  // gateway publishes the swap listings" could not be expressed.
 230  func TestTagPredicatesSeparateProtocolNotes(t *testing.T) {
 231  	engine := parse(t, `{
 232  		"version": 1,
 233  		"default": "deny",
 234  		"rules": [
 235  			{"kinds": [1], "tags": {"t": ["blake-swap-market"]},
 236  			 "require_auth": true, "authors": ["`+gateway+`"]},
 237  			{"kinds": [1], "rate": {"per_second": 5, "burst": 10}}
 238  		]
 239  	}`)
 240  
 241  	listing := nostr.Tags{{"t", "blake-swap-market"}, {"base", "BLAKE"}}
 242  
 243  	// The gateway's listing, authenticated: allowed by the first rule.
 244  	if verdict := engine.Decide(1, gateway, true, gateway, listing); !verdict.Allow {
 245  		t.Fatalf("the gateway's listing was refused: %+v", verdict)
 246  	}
 247  
 248  	// The same tags from a different key: refused, even with authentication.
 249  	if verdict := engine.Decide(1, stranger, true, stranger, listing); verdict.Allow {
 250  		t.Fatal("a stranger published the protocol's listing")
 251  	}
 252  
 253  	// A note of the same kind without the tag falls through to the open rule.
 254  	ordinary := nostr.Tags{{"t", "random"}}
 255  
 256  	if verdict := engine.Decide(1, stranger, false, "", ordinary); !verdict.Allow {
 257  		t.Fatalf("an ordinary note was refused: %+v", verdict)
 258  	}
 259  
 260  	// The tag predicate is required: no tag at all does not match the first rule.
 261  	if verdict := engine.Decide(1, gateway, true, gateway, nil); !verdict.Allow {
 262  		t.Fatalf("the fallthrough did not apply: %+v", verdict)
 263  	}
 264  }
 265  
 266  // TestATagWildcardMatchesAnyValue: a rule that says "carries a d tag" is how a relay accepts a
 267  // protocol's directed messages without accepting every note of the same kind.
 268  func TestATagWildcardMatchesAnyValue(t *testing.T) {
 269  	engine := parse(t, `{
 270  		"version": 1,
 271  		"default": "deny",
 272  		"rules": [{"kinds": [1], "tags": {"d": ["*"]}, "rate": {"per_second": 10}}]
 273  	}`)
 274  
 275  	if verdict := engine.Decide(1, stranger, false, "", nostr.Tags{{"d", "a-swap-id"}}); !verdict.Allow {
 276  		t.Fatalf("a directed message was refused: %+v", verdict)
 277  	}
 278  
 279  	if verdict := engine.Decide(1, stranger, false, "", nostr.Tags{{"t", "random"}}); verdict.Allow {
 280  		t.Fatal("a note without the tag was accepted")
 281  	}
 282  }
 283