policy_test.go raw
1 package relay
2
3 import (
4 "encoding/json"
5 "fmt"
6 "strings"
7 "testing"
8
9 "git.smesh.lol/torly/pkg/config"
10 "git.smesh.lol/torly/pkg/nostr"
11 "git.smesh.lol/torly/pkg/policy"
12 )
13
14 // gatewayKey is the registered gateway in the tests. testEvent derives keys from a seed byte,
15 // so the same seed is the same key.
16 const gatewaySeed = 7
17
18 // policyRelay starts a relay whose write policy is the rendezvous shape: stored gateway record
19 // restricted to one authenticated key, ephemeral frames open but rate limited, everything else
20 // refused.
21 func policyRelay(t *testing.T) (*testRelay, *policy.Engine) {
22 t.Helper()
23
24 engine, err := policy.Parse([]byte(`{
25 "version": 1,
26 "default": "deny",
27 "rules": [
28 {"kinds": [30333], "require_auth": true, "authors": ["` + gatewayKeyHex(t) + `"]},
29 {"kinds": [23196, 23197], "rate": {"per_second": 1, "burst": 2}}
30 ]
31 }`))
32
33 if err != nil {
34 t.Fatal(err)
35 }
36
37 tr := startTestRelayWith(t, false, func(cfg *config.Config) {
38 cfg.Policy = engine
39 })
40
41 return tr, engine
42 }
43
44 // gatewayKeyHex is the hex public key testEvent(gatewaySeed) signs with.
45 func gatewayKeyHex(t *testing.T) string {
46 t.Helper()
47
48 ev := testEvent(t, gatewaySeed, 1, nil, "")
49
50 return nostr.Hex(ev.PubKey[:])
51 }
52
53 // publish sends an event and returns the OK message.
54 func publish(t *testing.T, c *testWS, ev *nostr.Event) string {
55 t.Helper()
56
57 msg := append([]byte(`["EVENT",`), ev.AppendJSON(nil)...)
58 msg = append(msg, ']')
59 c.writeText(msg)
60
61 return c.expect(`["OK","` + nostr.Hex(ev.ID[:]) + `"`)
62 }
63
64 // challengeOf reads the AUTH challenge the relay sends on connect.
65 func challengeOf(t *testing.T, c *testWS) string {
66 t.Helper()
67
68 challengeMsg := c.expect(`["AUTH"`)
69 var parts []json.RawMessage
70
71 if err := json.Unmarshal([]byte(challengeMsg), &parts); err != nil {
72 t.Fatal(err)
73 }
74
75 var challenge string
76 json.Unmarshal(parts[1], &challenge)
77
78 return challenge
79 }
80
81 // authenticate answers a challenge with the given seed's key.
82 func authenticate(t *testing.T, tr *testRelay, c *testWS, seed byte, challenge string) {
83 t.Helper()
84
85 auth := testEvent(t, seed, 22242, nostr.Tags{
86 {"relay", tr.cfg.RelayURL},
87 {"challenge", challenge},
88 }, "")
89 msg := append([]byte(`["AUTH",`), auth.AppendJSON(nil)...)
90 msg = append(msg, ']')
91 c.writeText(msg)
92
93 if ok := c.expect(`["OK","` + nostr.Hex(auth.ID[:]) + `"`); !strings.Contains(ok, "true") {
94 t.Fatalf("auth rejected: %s", ok)
95 }
96 }
97
98 // TestPolicyRefusesAnUnlistedKind: deny by default is the difference between a rendezvous
99 // relay and a general one.
100 func TestPolicyRefusesAnUnlistedKind(t *testing.T) {
101 tr, _ := policyRelay(t)
102
103 c := dialWS(t, tr.addr)
104 defer c.close()
105 challengeOf(t, c)
106
107 reply := publish(t, c, testEvent(t, 9, 1, nil, "not this relay's business"))
108
109 if !strings.Contains(reply, ",false,") || !strings.Contains(reply, "blocked:") {
110 t.Fatalf("an unlisted kind was accepted: %s", reply)
111 }
112 }
113
114 // TestPolicyRequiresAuthAndTheRegisteredKeyForStoredKinds: the presence record is the
115 // rendezvous, so it is the one thing that must only come from the gateway.
116 func TestPolicyRequiresAuthAndTheRegisteredKeyForStoredKinds(t *testing.T) {
117 tr, _ := policyRelay(t)
118
119 c := dialWS(t, tr.addr)
120 defer c.close()
121 challenge := challengeOf(t, c)
122
123 presence := testEvent(t, gatewaySeed, 30333, nostr.Tags{{"d", gatewayKeyHex(t)}}, `{"uri":"nostr+chaindata://x"}`)
124
125 reply := publish(t, c, presence)
126
127 if !strings.Contains(reply, "auth-required:") {
128 t.Fatalf("an unauthenticated presence record was not refused for auth: %s", reply)
129 }
130
131 // Authenticated as somebody else: still refused, because the speaker is not the author.
132 authenticate(t, tr, c, 9, challenge)
133
134 reply = publish(t, c, presence)
135
136 if !strings.Contains(reply, ",false,") || !strings.Contains(reply, "auth-required:") {
137 t.Fatalf("a presence record from another authenticated key was accepted: %s", reply)
138 }
139
140 // Authenticated as the gateway: accepted and stored, so a later reader finds it.
141 c2 := dialWS(t, tr.addr)
142 defer c2.close()
143 authenticate(t, tr, c2, gatewaySeed, challengeOf(t, c2))
144
145 reply = publish(t, c2, testEvent(t, gatewaySeed, 30333, nostr.Tags{{"d", gatewayKeyHex(t)}}, `{"uri":"nostr+chaindata://x"}`))
146
147 if !strings.Contains(reply, ",true,") {
148 t.Fatalf("the registered gateway was refused: %s", reply)
149 }
150
151 if count, _ := countFilter(t, tr.addr, `{"kinds":[30333]}`); count != 1 {
152 t.Fatalf("the stored presence record was not queryable: %d", count)
153 }
154 }
155
156 // TestPolicyRateLimitsEphemeralFrames: the frame kinds are open, so the only thing standing
157 // between a flood and the relay is the per-connection budget.
158 func TestPolicyRateLimitsEphemeralFrames(t *testing.T) {
159 tr, _ := policyRelay(t)
160
161 c := dialWS(t, tr.addr)
162 defer c.close()
163 challengeOf(t, c)
164
165 // The burst is two; the third in the same instant is refused.
166 for i := 0; i < 2; i++ {
167 reply := publish(t, c, testEvent(t, byte(20+i), 23196, nil, "frame"))
168
169 if !strings.Contains(reply, ",true,") {
170 t.Fatalf("frame %d was refused: %s", i, reply)
171 }
172 }
173
174 reply := publish(t, c, testEvent(t, 22, 23196, nil, "frame"))
175
176 if !strings.Contains(reply, "rate-limited:") {
177 t.Fatalf("a flooded frame was accepted: %s", reply)
178 }
179
180 // A second connection has its own budget, so one busy client does not starve another.
181 other := dialWS(t, tr.addr)
182 defer other.close()
183 challengeOf(t, other)
184
185 if reply := publish(t, other, testEvent(t, 23, 23197, nil, "frame")); !strings.Contains(reply, ",true,") {
186 t.Fatalf("a second connection was starved: %s", reply)
187 }
188 }
189
190 // TestPolicyMessageNamesTheRule: the refusals are NIP-01 machine-readable prefixes, so a
191 // client can tell "not for this relay" from "authenticate" from "slow down".
192 func TestPolicyMessageNamesTheRule(t *testing.T) {
193 tr, _ := policyRelay(t)
194
195 c := dialWS(t, tr.addr)
196 defer c.close()
197 challengeOf(t, c)
198
199 reply := publish(t, c, testEvent(t, 30, 7, nil, "reaction"))
200
201 for _, want := range []string{"blocked:", fmt.Sprintf("kind %d", 7)} {
202 if !strings.Contains(reply, want) {
203 t.Fatalf("the refusal does not say %q: %s", want, reply)
204 }
205 }
206 }
207
208 // TestGatewayFramesAreNotThrottled: the bulk direction is the gateway's frames to the wallet.
209 // They are gateway-only and deliberately not rate-limited, so a sync is bounded by the line and
210 // not by a policy budget — and a wallet cannot publish that kind at all.
211 func TestGatewayFramesAreNotThrottled(t *testing.T) {
212 engine, err := policy.Parse([]byte(`{
213 "version": 1,
214 "default": "deny",
215 "rules": [
216 {"kinds": [23197], "require_auth": true, "authors": ["` + gatewayKeyHex(t) + `"]},
217 {"kinds": [23196], "rate": {"per_second": 5, "burst": 10}}
218 ]
219 }`))
220
221 if err != nil {
222 t.Fatal(err)
223 }
224
225 tr := startTestRelayWith(t, false, func(cfg *config.Config) {
226 cfg.Policy = engine
227 })
228
229 sub := dialWS(t, tr.addr)
230 defer sub.close()
231 sub.expect(`["AUTH"`)
232 sub.writeText([]byte(`["REQ","frames",{"kinds":[23197]}]`))
233 sub.expect(`["EOSE","frames"`)
234
235 gw := dialWS(t, tr.addr)
236 defer gw.close()
237 authenticate(t, tr, gw, gatewaySeed, challengeOf(t, gw))
238
239 // A frame at the tunnel's maximum MTU, encrypted: 96 KiB of content. It is accepted, and a
240 // subscriber receives it.
241 big := strings.Repeat("x", 96<<10)
242
243 for i := 0; i < 3; i++ {
244 ev := testEvent(t, gatewaySeed, 23197, nostr.Tags{{"p", strings.Repeat("33", 32)}}, big)
245
246 if reply := publish(t, gw, ev); !strings.Contains(reply, ",true,") {
247 t.Fatalf("gateway frame %d was throttled: %s", i, reply)
248 }
249 }
250
251 got := sub.expect(`["EVENT","frames"`)
252
253 if !strings.Contains(got, big[:64]) {
254 t.Fatal("the subscriber did not receive the frame")
255 }
256
257 // The same kind from a wallet is not its to publish.
258 wallet := dialWS(t, tr.addr)
259 defer wallet.close()
260 challenge := challengeOf(t, wallet)
261 authenticate(t, tr, wallet, 9, challenge)
262
263 if reply := publish(t, wallet, testEvent(t, 9, 23197, nil, "not the gateway")); !strings.Contains(reply, ",false,") {
264 t.Fatalf("a wallet published a gateway frame: %s", reply)
265 }
266 }
267
268 // TestInboundCeilingDropsAndCloses: the relay-wide ceiling is checked on the raw message before
269 // the JSON is parsed. A connection that keeps exceeding it is closed, and nothing it sent was
270 // stored.
271 func TestInboundCeilingDropsAndCloses(t *testing.T) {
272 tr := startTestRelayWith(t, false, func(cfg *config.Config) {
273 cfg.InboundBytesPerSec = 64
274 cfg.AbuseCloseAfter = 1
275 })
276
277 c := dialWS(t, tr.addr)
278 defer c.close()
279 challengeOf(t, c)
280
281 ev := testEvent(t, 4, 1, nil, strings.Repeat("y", 500))
282 msg := append([]byte(`["EVENT",`), ev.AppendJSON(nil)...)
283 msg = append(msg, ']')
284 c.writeText(msg)
285
286 // The message is over the ceiling, so it is dropped and the connection is closed: the next
287 // read sees the relay's close frame.
288 if _, err := c.read(); err == nil {
289 t.Fatal("the connection was not closed after exceeding the ceiling")
290 }
291
292 // The dropped event was never stored, and the relay still serves a new connection.
293 if count, _ := countFilter(t, tr.addr, `{"kinds":[1]}`); count != 0 {
294 t.Fatalf("%d events were stored from a dropped message", count)
295 }
296 }
297
298 // TestQueryBudgetStopsAReply: a client asking for listings faster than its budget gets nothing
299 // sent back, and a client that keeps asking is closed.
300 func TestQueryBudgetStopsAReply(t *testing.T) {
301 tr := startTestRelayWith(t, false, func(cfg *config.Config) {
302 cfg.QueryPerSec = 1
303 cfg.QueryBurst = 1
304 cfg.AbuseCloseAfter = 1
305 })
306
307 c := dialWS(t, tr.addr)
308 defer c.close()
309 challengeOf(t, c)
310
311 // The first request is inside the burst and is answered.
312 c.writeText([]byte(`["REQ","first",{"kinds":[1]}]`))
313 c.expect(`["EOSE","first"`)
314
315 // The second is over the budget: no EOSE, no CLOSED, and with AbuseCloseAfter=1 the
316 // connection is closed.
317 c.writeText([]byte(`["REQ","second",{"kinds":[1]}]`))
318
319 if _, err := c.read(); err == nil {
320 t.Fatal("an over-budget request was answered")
321 }
322 }
323
324 // TestPacedDeliveryKeepsTheStream: a delivery rate slows a connection down but never loses a
325 // frame, because a gap in the tunnel's sequence numbers would ask for it again.
326 func TestPacedDeliveryKeepsTheStream(t *testing.T) {
327 tr := startTestRelayWith(t, false, func(cfg *config.Config) {
328 // 64 KiB/s with a one-second burst: the first ~64 KiB is immediate, the rest is paced.
329 cfg.OutboundBytesPerSec = 64 << 10
330 })
331
332 sub := dialWS(t, tr.addr)
333 defer sub.close()
334 sub.expect(`["AUTH"`)
335 sub.writeText([]byte(`["REQ","paced",{"kinds":[1]}]`))
336 sub.expect(`["EOSE","paced"`)
337
338 pub := dialWS(t, tr.addr)
339 defer pub.close()
340 pub.expect(`["AUTH"`)
341
342 body := strings.Repeat("z", 40<<10)
343
344 for i := 0; i < 4; i++ {
345 ev := testEvent(t, byte(40+i), 1, nil, body)
346 msg := append([]byte(`["EVENT",`), ev.AppendJSON(nil)...)
347 msg = append(msg, ']')
348 pub.writeText(msg)
349 pub.expect(`["OK","` + nostr.Hex(ev.ID[:]) + `"`)
350 }
351
352 // All four arrive, in order, even though the connection's budget is 64 KiB/s and the
353 // payload is 160 KiB.
354 for i := 0; i < 4; i++ {
355 got := sub.expect(`["EVENT","paced"`)
356 if !strings.Contains(got, body[:64]) {
357 t.Fatalf("frame %d is not the published event", i)
358 }
359 }
360 }
361