package relay import ( "encoding/json" "fmt" "strings" "testing" "git.smesh.lol/torly/pkg/config" "git.smesh.lol/torly/pkg/nostr" "git.smesh.lol/torly/pkg/policy" ) // gatewayKey is the registered gateway in the tests. testEvent derives keys from a seed byte, // so the same seed is the same key. const gatewaySeed = 7 // policyRelay starts a relay whose write policy is the rendezvous shape: stored gateway record // restricted to one authenticated key, ephemeral frames open but rate limited, everything else // refused. func policyRelay(t *testing.T) (*testRelay, *policy.Engine) { t.Helper() engine, err := policy.Parse([]byte(`{ "version": 1, "default": "deny", "rules": [ {"kinds": [30333], "require_auth": true, "authors": ["` + gatewayKeyHex(t) + `"]}, {"kinds": [23196, 23197], "rate": {"per_second": 1, "burst": 2}} ] }`)) if err != nil { t.Fatal(err) } tr := startTestRelayWith(t, false, func(cfg *config.Config) { cfg.Policy = engine }) return tr, engine } // gatewayKeyHex is the hex public key testEvent(gatewaySeed) signs with. func gatewayKeyHex(t *testing.T) string { t.Helper() ev := testEvent(t, gatewaySeed, 1, nil, "") return nostr.Hex(ev.PubKey[:]) } // publish sends an event and returns the OK message. func publish(t *testing.T, c *testWS, ev *nostr.Event) string { t.Helper() msg := append([]byte(`["EVENT",`), ev.AppendJSON(nil)...) msg = append(msg, ']') c.writeText(msg) return c.expect(`["OK","` + nostr.Hex(ev.ID[:]) + `"`) } // challengeOf reads the AUTH challenge the relay sends on connect. func challengeOf(t *testing.T, c *testWS) string { t.Helper() challengeMsg := c.expect(`["AUTH"`) var parts []json.RawMessage if err := json.Unmarshal([]byte(challengeMsg), &parts); err != nil { t.Fatal(err) } var challenge string json.Unmarshal(parts[1], &challenge) return challenge } // authenticate answers a challenge with the given seed's key. func authenticate(t *testing.T, tr *testRelay, c *testWS, seed byte, challenge string) { t.Helper() auth := testEvent(t, seed, 22242, nostr.Tags{ {"relay", tr.cfg.RelayURL}, {"challenge", challenge}, }, "") msg := append([]byte(`["AUTH",`), auth.AppendJSON(nil)...) msg = append(msg, ']') c.writeText(msg) if ok := c.expect(`["OK","` + nostr.Hex(auth.ID[:]) + `"`); !strings.Contains(ok, "true") { t.Fatalf("auth rejected: %s", ok) } } // TestPolicyRefusesAnUnlistedKind: deny by default is the difference between a rendezvous // relay and a general one. func TestPolicyRefusesAnUnlistedKind(t *testing.T) { tr, _ := policyRelay(t) c := dialWS(t, tr.addr) defer c.close() challengeOf(t, c) reply := publish(t, c, testEvent(t, 9, 1, nil, "not this relay's business")) if !strings.Contains(reply, ",false,") || !strings.Contains(reply, "blocked:") { t.Fatalf("an unlisted kind was accepted: %s", reply) } } // TestPolicyRequiresAuthAndTheRegisteredKeyForStoredKinds: the presence record is the // rendezvous, so it is the one thing that must only come from the gateway. func TestPolicyRequiresAuthAndTheRegisteredKeyForStoredKinds(t *testing.T) { tr, _ := policyRelay(t) c := dialWS(t, tr.addr) defer c.close() challenge := challengeOf(t, c) presence := testEvent(t, gatewaySeed, 30333, nostr.Tags{{"d", gatewayKeyHex(t)}}, `{"uri":"nostr+chaindata://x"}`) reply := publish(t, c, presence) if !strings.Contains(reply, "auth-required:") { t.Fatalf("an unauthenticated presence record was not refused for auth: %s", reply) } // Authenticated as somebody else: still refused, because the speaker is not the author. authenticate(t, tr, c, 9, challenge) reply = publish(t, c, presence) if !strings.Contains(reply, ",false,") || !strings.Contains(reply, "auth-required:") { t.Fatalf("a presence record from another authenticated key was accepted: %s", reply) } // Authenticated as the gateway: accepted and stored, so a later reader finds it. c2 := dialWS(t, tr.addr) defer c2.close() authenticate(t, tr, c2, gatewaySeed, challengeOf(t, c2)) reply = publish(t, c2, testEvent(t, gatewaySeed, 30333, nostr.Tags{{"d", gatewayKeyHex(t)}}, `{"uri":"nostr+chaindata://x"}`)) if !strings.Contains(reply, ",true,") { t.Fatalf("the registered gateway was refused: %s", reply) } if count, _ := countFilter(t, tr.addr, `{"kinds":[30333]}`); count != 1 { t.Fatalf("the stored presence record was not queryable: %d", count) } } // TestPolicyRateLimitsEphemeralFrames: the frame kinds are open, so the only thing standing // between a flood and the relay is the per-connection budget. func TestPolicyRateLimitsEphemeralFrames(t *testing.T) { tr, _ := policyRelay(t) c := dialWS(t, tr.addr) defer c.close() challengeOf(t, c) // The burst is two; the third in the same instant is refused. for i := 0; i < 2; i++ { reply := publish(t, c, testEvent(t, byte(20+i), 23196, nil, "frame")) if !strings.Contains(reply, ",true,") { t.Fatalf("frame %d was refused: %s", i, reply) } } reply := publish(t, c, testEvent(t, 22, 23196, nil, "frame")) if !strings.Contains(reply, "rate-limited:") { t.Fatalf("a flooded frame was accepted: %s", reply) } // A second connection has its own budget, so one busy client does not starve another. other := dialWS(t, tr.addr) defer other.close() challengeOf(t, other) if reply := publish(t, other, testEvent(t, 23, 23197, nil, "frame")); !strings.Contains(reply, ",true,") { t.Fatalf("a second connection was starved: %s", reply) } } // TestPolicyMessageNamesTheRule: the refusals are NIP-01 machine-readable prefixes, so a // client can tell "not for this relay" from "authenticate" from "slow down". func TestPolicyMessageNamesTheRule(t *testing.T) { tr, _ := policyRelay(t) c := dialWS(t, tr.addr) defer c.close() challengeOf(t, c) reply := publish(t, c, testEvent(t, 30, 7, nil, "reaction")) for _, want := range []string{"blocked:", fmt.Sprintf("kind %d", 7)} { if !strings.Contains(reply, want) { t.Fatalf("the refusal does not say %q: %s", want, reply) } } } // TestGatewayFramesAreNotThrottled: the bulk direction is the gateway's frames to the wallet. // They are gateway-only and deliberately not rate-limited, so a sync is bounded by the line and // not by a policy budget — and a wallet cannot publish that kind at all. func TestGatewayFramesAreNotThrottled(t *testing.T) { engine, err := policy.Parse([]byte(`{ "version": 1, "default": "deny", "rules": [ {"kinds": [23197], "require_auth": true, "authors": ["` + gatewayKeyHex(t) + `"]}, {"kinds": [23196], "rate": {"per_second": 5, "burst": 10}} ] }`)) if err != nil { t.Fatal(err) } tr := startTestRelayWith(t, false, func(cfg *config.Config) { cfg.Policy = engine }) sub := dialWS(t, tr.addr) defer sub.close() sub.expect(`["AUTH"`) sub.writeText([]byte(`["REQ","frames",{"kinds":[23197]}]`)) sub.expect(`["EOSE","frames"`) gw := dialWS(t, tr.addr) defer gw.close() authenticate(t, tr, gw, gatewaySeed, challengeOf(t, gw)) // A frame at the tunnel's maximum MTU, encrypted: 96 KiB of content. It is accepted, and a // subscriber receives it. big := strings.Repeat("x", 96<<10) for i := 0; i < 3; i++ { ev := testEvent(t, gatewaySeed, 23197, nostr.Tags{{"p", strings.Repeat("33", 32)}}, big) if reply := publish(t, gw, ev); !strings.Contains(reply, ",true,") { t.Fatalf("gateway frame %d was throttled: %s", i, reply) } } got := sub.expect(`["EVENT","frames"`) if !strings.Contains(got, big[:64]) { t.Fatal("the subscriber did not receive the frame") } // The same kind from a wallet is not its to publish. wallet := dialWS(t, tr.addr) defer wallet.close() challenge := challengeOf(t, wallet) authenticate(t, tr, wallet, 9, challenge) if reply := publish(t, wallet, testEvent(t, 9, 23197, nil, "not the gateway")); !strings.Contains(reply, ",false,") { t.Fatalf("a wallet published a gateway frame: %s", reply) } } // TestInboundCeilingDropsAndCloses: the relay-wide ceiling is checked on the raw message before // the JSON is parsed. A connection that keeps exceeding it is closed, and nothing it sent was // stored. func TestInboundCeilingDropsAndCloses(t *testing.T) { tr := startTestRelayWith(t, false, func(cfg *config.Config) { cfg.InboundBytesPerSec = 64 cfg.AbuseCloseAfter = 1 }) c := dialWS(t, tr.addr) defer c.close() challengeOf(t, c) ev := testEvent(t, 4, 1, nil, strings.Repeat("y", 500)) msg := append([]byte(`["EVENT",`), ev.AppendJSON(nil)...) msg = append(msg, ']') c.writeText(msg) // The message is over the ceiling, so it is dropped and the connection is closed: the next // read sees the relay's close frame. if _, err := c.read(); err == nil { t.Fatal("the connection was not closed after exceeding the ceiling") } // The dropped event was never stored, and the relay still serves a new connection. if count, _ := countFilter(t, tr.addr, `{"kinds":[1]}`); count != 0 { t.Fatalf("%d events were stored from a dropped message", count) } } // TestQueryBudgetStopsAReply: a client asking for listings faster than its budget gets nothing // sent back, and a client that keeps asking is closed. func TestQueryBudgetStopsAReply(t *testing.T) { tr := startTestRelayWith(t, false, func(cfg *config.Config) { cfg.QueryPerSec = 1 cfg.QueryBurst = 1 cfg.AbuseCloseAfter = 1 }) c := dialWS(t, tr.addr) defer c.close() challengeOf(t, c) // The first request is inside the burst and is answered. c.writeText([]byte(`["REQ","first",{"kinds":[1]}]`)) c.expect(`["EOSE","first"`) // The second is over the budget: no EOSE, no CLOSED, and with AbuseCloseAfter=1 the // connection is closed. c.writeText([]byte(`["REQ","second",{"kinds":[1]}]`)) if _, err := c.read(); err == nil { t.Fatal("an over-budget request was answered") } } // TestPacedDeliveryKeepsTheStream: a delivery rate slows a connection down but never loses a // frame, because a gap in the tunnel's sequence numbers would ask for it again. func TestPacedDeliveryKeepsTheStream(t *testing.T) { tr := startTestRelayWith(t, false, func(cfg *config.Config) { // 64 KiB/s with a one-second burst: the first ~64 KiB is immediate, the rest is paced. cfg.OutboundBytesPerSec = 64 << 10 }) sub := dialWS(t, tr.addr) defer sub.close() sub.expect(`["AUTH"`) sub.writeText([]byte(`["REQ","paced",{"kinds":[1]}]`)) sub.expect(`["EOSE","paced"`) pub := dialWS(t, tr.addr) defer pub.close() pub.expect(`["AUTH"`) body := strings.Repeat("z", 40<<10) for i := 0; i < 4; i++ { ev := testEvent(t, byte(40+i), 1, nil, body) msg := append([]byte(`["EVENT",`), ev.AppendJSON(nil)...) msg = append(msg, ']') pub.writeText(msg) pub.expect(`["OK","` + nostr.Hex(ev.ID[:]) + `"`) } // All four arrive, in order, even though the connection's budget is 64 KiB/s and the // payload is 160 KiB. for i := 0; i < 4; i++ { got := sub.expect(`["EVENT","paced"`) if !strings.Contains(got, body[:64]) { t.Fatalf("frame %d is not the published event", i) } } }