package policy import ( "strings" "testing" "time" "git.smesh.lol/torly/pkg/nostr" ) const gateway = "1111111111111111111111111111111111111111111111111111111111111111" const stranger = "2222222222222222222222222222222222222222222222222222222222222222" // parse builds an engine from a policy document, failing the test on a parse error. func parse(t *testing.T, raw string) *Engine { t.Helper() engine, err := Parse([]byte(raw)) if err != nil { t.Fatalf("Parse: %v", err) } return engine } // TestNoPolicyAllowsEverything: a relay without a policy file behaves exactly as it always // has. A nil engine is the default, not an error. func TestNoPolicyAllowsEverything(t *testing.T) { var engine *Engine if verdict := engine.Decide(1, stranger, false, "", nil); !verdict.Allow { t.Fatalf("nil engine refused: %+v", verdict) } limiter := engine.NewLimiter() for i := 0; i < 100; i++ { if !limiter.Allow(0, time.Now()) { t.Fatal("nil engine rate-limited") } } } // TestGatewayKindsNeedAuthAndTheRegisteredKey: the rendezvous rule. The stored kind is // restricted to one key, and a connection must have authenticated as that key. func TestGatewayKindsNeedAuthAndTheRegisteredKey(t *testing.T) { engine := parse(t, `{ "version": 1, "default": "deny", "rules": [ {"kinds": [30333], "require_auth": true, "authors": ["`+gateway+`"]}, {"kinds": [23196, 23197]} ] }`) // Unauthenticated: auth-required, not "blocked by author". verdict := engine.Decide(30333, gateway, false, "", nil) if verdict.Allow { t.Fatal("an unauthenticated presence record was allowed") } if !strings.HasPrefix(verdict.Reason, "auth-required:") { t.Fatalf("reason = %q", verdict.Reason) } // Authenticated as somebody else: refused, because the speaker is not the author. verdict = engine.Decide(30333, gateway, true, stranger, nil) if verdict.Allow || !strings.HasPrefix(verdict.Reason, "auth-required:") { t.Fatalf("a different authenticated key was allowed: %+v", verdict) } // Authenticated as the registered key: allowed. if verdict := engine.Decide(30333, gateway, true, gateway, nil); !verdict.Allow { t.Fatalf("the registered gateway was refused: %+v", verdict) } // Ephemeral frames are open, authenticated or not. if verdict := engine.Decide(23196, stranger, false, "", nil); !verdict.Allow { t.Fatalf("an ephemeral frame was refused: %+v", verdict) } // Anything else is denied by the default. verdict = engine.Decide(1, stranger, false, "", nil) if verdict.Allow || !strings.Contains(verdict.Reason, "kind 1") { t.Fatalf("an unlisted kind was allowed: %+v", verdict) } } // TestOrderDecides: the first matching rule wins, so a specific rule must come before a // catch-all. That is the property that makes a table readable. func TestOrderDecides(t *testing.T) { engine := parse(t, `{ "version": 1, "rules": [ {"kinds": [5], "require_auth": true, "authors": ["`+gateway+`"]}, {} ] }`) if verdict := engine.Decide(5, gateway, false, "", nil); verdict.Allow { t.Fatal("the specific rule was not reached first") } if verdict := engine.Decide(1, gateway, false, "", nil); !verdict.Allow { t.Fatalf("the catch-all did not allow kind 1: %+v", verdict) } } // TestAuthorOnlyWithoutAuth: an allowlist without require_auth is still an allowlist; the // signature is the proof, and authentication is only needed when the connection's identity // matters as well. func TestAuthorOnlyWithoutAuth(t *testing.T) { engine := parse(t, `{ "version": 1, "rules": [{"kinds": [30333], "authors": ["`+gateway+`"]}] }`) if verdict := engine.Decide(30333, gateway, false, "", nil); !verdict.Allow { t.Fatalf("the registered key was refused: %+v", verdict) } if verdict := engine.Decide(30333, stranger, true, stranger, nil); verdict.Allow { t.Fatal("an unregistered key was allowed to sign a restricted kind") } } // TestRateIsPerLimiter: two connections have separate budgets, and a bucket refills with time. func TestRateIsPerLimiter(t *testing.T) { engine := parse(t, `{ "version": 1, "rules": [{"kinds": [23196], "rate": {"per_second": 10, "burst": 2}}] }`) first := engine.NewLimiter() second := engine.NewLimiter() now := time.Unix(1_700_000_000, 0) if !first.Allow(0, now) || !first.Allow(0, now) { t.Fatal("the burst was refused") } if first.Allow(0, now) { t.Fatal("a third event slipped past a burst of two") } if !second.Allow(0, now) { t.Fatal("one connection spent another's budget") } // A second later the bucket holds ten more tokens, capped at the burst. later := now.Add(time.Second) if !first.Allow(0, later) || !first.Allow(0, later) { t.Fatal("the bucket did not refill") } if first.Allow(0, later) { t.Fatal("the refill exceeded the burst") } } // TestMalformedPoliciesAreRefused: a typo in a policy is an error at startup, not a rule that // quietly does something else. func TestMalformedPoliciesAreRefused(t *testing.T) { cases := map[string]string{ "no version": `{"rules": []}`, "wrong version": `{"version": 2, "rules": []}`, "unknown field": `{"version": 1, "rule": []}`, "bad default": `{"version": 1, "default": "maybe", "rules": []}`, "kind out of range": `{"version": 1, "rules": [{"kinds": [70000]}]}`, "short author": `{"version": 1, "rules": [{"authors": ["abcd"]}]}`, "non-hex author": `{"version": 1, "rules": [{"authors": ["` + strings.Repeat("zz", 32) + `"]}]}`, "zero rate": `{"version": 1, "rules": [{"rate": {"per_second": 0}}]}`, "negative burst": `{"version": 1, "rules": [{"rate": {"per_second": 10, "burst": -1}}]}`, } for name, raw := range cases { if _, err := Parse([]byte(raw)); err == nil { t.Fatalf("%s: accepted", name) } } } // TestAnEmptyRulesetWithDeny: a deny-by-default policy with no rules is a relay that accepts // no writes, which is a legal (if useless) configuration and must not be silently permissive. func TestAnEmptyRulesetWithDeny(t *testing.T) { engine := parse(t, `{"version": 1, "default": "deny", "rules": []}`) if verdict := engine.Decide(1, stranger, false, "", nil); verdict.Allow { t.Fatal("a deny-by-default policy allowed a write") } } // TestByteBudgetStopsAMaximumSizeTrickle: a count per second alone lets one connection push // PerSecond × max-event-size bytes; the byte budget is what bounds the bandwidth. func TestByteBudgetStopsAMaximumSizeTrickle(t *testing.T) { engine := parse(t, `{ "version": 1, "rules": [{"kinds": [23196], "rate": {"per_second": 1000, "burst": 1000, "bytes_per_second": 1, "bytes_burst": 1500}}] }`) limiter := engine.NewLimiter() now := time.Unix(1_700_000_000, 0) if !limiter.Allow(0, now) || !limiter.AllowBytes(0, 700, now) { t.Fatal("the first event was refused") } if !limiter.Allow(0, now) || !limiter.AllowBytes(0, 700, now) { t.Fatal("the second event was refused") } if !limiter.Allow(0, now) { t.Fatal("the event budget was spent by two events") } if limiter.AllowBytes(0, 700, now) { t.Fatal("a third event slipped past the byte budget") } } // TestTagPredicatesSeparateProtocolNotes: one kind can carry a gateway-only rule for a protocol's // listings and a different rule for every other note of the same kind. Without tags, "only the // gateway publishes the swap listings" could not be expressed. func TestTagPredicatesSeparateProtocolNotes(t *testing.T) { engine := parse(t, `{ "version": 1, "default": "deny", "rules": [ {"kinds": [1], "tags": {"t": ["blake-swap-market"]}, "require_auth": true, "authors": ["`+gateway+`"]}, {"kinds": [1], "rate": {"per_second": 5, "burst": 10}} ] }`) listing := nostr.Tags{{"t", "blake-swap-market"}, {"base", "BLAKE"}} // The gateway's listing, authenticated: allowed by the first rule. if verdict := engine.Decide(1, gateway, true, gateway, listing); !verdict.Allow { t.Fatalf("the gateway's listing was refused: %+v", verdict) } // The same tags from a different key: refused, even with authentication. if verdict := engine.Decide(1, stranger, true, stranger, listing); verdict.Allow { t.Fatal("a stranger published the protocol's listing") } // A note of the same kind without the tag falls through to the open rule. ordinary := nostr.Tags{{"t", "random"}} if verdict := engine.Decide(1, stranger, false, "", ordinary); !verdict.Allow { t.Fatalf("an ordinary note was refused: %+v", verdict) } // The tag predicate is required: no tag at all does not match the first rule. if verdict := engine.Decide(1, gateway, true, gateway, nil); !verdict.Allow { t.Fatalf("the fallthrough did not apply: %+v", verdict) } } // TestATagWildcardMatchesAnyValue: a rule that says "carries a d tag" is how a relay accepts a // protocol's directed messages without accepting every note of the same kind. func TestATagWildcardMatchesAnyValue(t *testing.T) { engine := parse(t, `{ "version": 1, "default": "deny", "rules": [{"kinds": [1], "tags": {"d": ["*"]}, "rate": {"per_second": 10}}] }`) if verdict := engine.Decide(1, stranger, false, "", nostr.Tags{{"d", "a-swap-id"}}); !verdict.Allow { t.Fatalf("a directed message was refused: %+v", verdict) } if verdict := engine.Decide(1, stranger, false, "", nostr.Tags{{"t", "random"}}); verdict.Allow { t.Fatal("a note without the tag was accepted") } }