zap_test.go raw
1 package main
2
3 import (
4 "encoding/hex"
5 "encoding/json"
6 "os"
7 "path/filepath"
8 "testing"
9 "time"
10
11 "github.com/nbd-wtf/go-nostr"
12 )
13
14 // A real invoice produced by this wallet, with the payment hash as recorded by
15 // the wallet itself (Alby Hub's transactions table). The payment hash is
16 // sha256(preimage), so the two are independent and this is a true oracle.
17 const (
18 testInvoice = "lnbc90n1p4vk36jhp5h7w2vtz3jnqd5h8thhr9qs3fpa8k2uczf5df68205da3rfp9nmaqnp4qf0pqvflcvcn99wjr5kq45nsffzpjfqmac3f7nm6ddph6uqzn5stqpp59lav9jkvznj78ucrjns040wzf0c24vg6m8wturzrmlalmle68w9qsp5cdscre7tducplmzqapx5v4ur22kldulxzw9vn8jvvpryt3h643ks9qyysgqcqzp2xqyz5vqrzjqvdnqyc82a9maxu6c7mee0shqr33u4z9z04wpdwhf96gxzpln8jcrapyqqqqqqzx4cqqqqqqqqqqqqqq2qrzjqw9fu4j39mycmg440ztkraa03u5qhtuc5zfgydsv6ml38qd4azymlapyqqqqqqq67yqqqqlgqqqq86qqjq8eu3n2yr4hhfyvak0lrn2akanqhp7kknn43qcy99q9gldgxkaeu529xfzzxpv8ysm794nauhtd4auwly2c6t43427mvezrapswr88rcp6un06y"
19 testPaymentHash = "2ffac2cacc14e5e3f30394e0fabdc24bf0aab11ad9dcbe0c43dffbfdff3a3b8a"
20 )
21
22 func TestPaymentHashFromInvoice(t *testing.T) {
23 got, err := paymentHashFromInvoice(testInvoice)
24 if err != nil {
25 t.Fatalf("paymentHashFromInvoice: %v", err)
26 }
27 if got != testPaymentHash {
28 t.Fatalf("payment hash mismatch\n got: %s\nwant: %s", got, testPaymentHash)
29 }
30 }
31
32 func TestPaymentHashFromInvoiceRejectsGarbage(t *testing.T) {
33 for _, bad := range []string{"", "notaninvoice", "lnbc1", "lnbc90n1qqqqqqqq"} {
34 if _, err := paymentHashFromInvoice(bad); err == nil {
35 t.Fatalf("expected an error for %q", bad)
36 }
37 }
38 }
39
40 // buildZapRequest creates a signed zap request for tests.
41 func buildZapRequest(t *testing.T, sk string, amountMsat int64, tags [][]string) (string, *ZapRequest) {
42 t.Helper()
43 ev := nostr.Event{
44 Kind: zapRequestKind,
45 CreatedAt: nostr.Now(),
46 Content: "test zap",
47 }
48 for _, tg := range tags {
49 ev.Tags = append(ev.Tags, nostr.Tag(tg))
50 }
51 // amount tag must match the query amount when present.
52 ev.Tags = append(ev.Tags, nostr.Tag{"amount", itoa(amountMsat)})
53 ev.Tags = append(ev.Tags, nostr.Tag{"relays", "wss://relay.example.com"})
54 if err := ev.Sign(sk); err != nil {
55 t.Fatalf("sign zap request: %v", err)
56 }
57 raw := ev.String()
58 var zr ZapRequest
59 if err := json.Unmarshal([]byte(raw), &zr); err != nil {
60 t.Fatalf("unmarshal zap request: %v", err)
61 }
62 return raw, &zr
63 }
64
65 func itoa(n int64) string {
66 if n == 0 {
67 return "0"
68 }
69 neg := n < 0
70 if neg {
71 n = -n
72 }
73 var b [20]byte
74 i := len(b)
75 for n > 0 {
76 i--
77 b[i] = byte('0' + n%10)
78 n /= 10
79 }
80 if neg {
81 i--
82 b[i] = '-'
83 }
84 return string(b[i:])
85 }
86
87 func TestValidateZapRequest(t *testing.T) {
88 sk := nostr.GeneratePrivateKey()
89 pk, _ := nostr.GetPublicKey(sk)
90 amount := int64(21000)
91
92 raw, zr := buildZapRequest(t, sk, amount, [][]string{{"p", pk}})
93 _ = raw
94
95 relays, err := validateZapRequest(zr, uint64(amount), "")
96 if err != nil {
97 t.Fatalf("valid zap request rejected: %v", err)
98 }
99 if len(relays) != 1 || relays[0] != "wss://relay.example.com" {
100 t.Fatalf("unexpected relays: %v", relays)
101 }
102
103 // Amount mismatch must be rejected.
104 if _, err := validateZapRequest(zr, uint64(amount)+1, ""); err == nil {
105 t.Fatal("expected an amount mismatch error")
106 }
107
108 // Tampered signature must be rejected.
109 bad := *zr
110 bad.Sig = "00" + zr.Sig[2:]
111 if _, err := validateZapRequest(&bad, uint64(amount), ""); err == nil {
112 t.Fatal("expected an invalid signature error")
113 }
114
115 // Missing p tag must be rejected.
116 _, zrNoP := buildZapRequest(t, sk, amount, nil)
117 if _, err := validateZapRequest(zrNoP, uint64(amount), ""); err == nil {
118 t.Fatal("expected a missing p tag error")
119 }
120
121 // Stale created_at must be rejected.
122 _, zrStale := buildZapRequest(t, sk, amount, [][]string{{"p", pk}})
123 zrStale.CreatedAt = time.Now().Add(-48 * time.Hour).Unix()
124 if _, err := validateZapRequest(zrStale, uint64(amount), ""); err == nil {
125 t.Fatal("expected a stale created_at error")
126 }
127 }
128
129 // TestReceiptMatchesAdvertisedKey is the property clients enforce: the receipt
130 // must be signed by the pubkey the payRequest advertised, and its description
131 // tag must hash to the invoice's description hash.
132 func TestReceiptMatchesAdvertisedKey(t *testing.T) {
133 dir := t.TempDir()
134 z, err := newZapServer("aa"+repeat("bb", 31), filepath.Join(dir, "zaps.json"))
135 if err != nil {
136 t.Fatalf("newZapServer: %v", err)
137 }
138
139 sk := nostr.GeneratePrivateKey()
140 pk, _ := nostr.GetPublicKey(sk)
141 raw, zr := buildZapRequest(t, sk, 21000, [][]string{{"p", pk}, {"e", repeat("ab", 32)}})
142
143 ev, err := z.buildReceipt(zr, raw, testInvoice, "deadbeef", time.Now())
144 if err != nil {
145 t.Fatalf("buildReceipt: %v", err)
146 }
147 if ev.PubKey != z.pubkey {
148 t.Fatalf("receipt pubkey %s != advertised %s", ev.PubKey, z.pubkey)
149 }
150 if ok, err := ev.CheckSignature(); err != nil || !ok {
151 t.Fatalf("receipt signature invalid: ok=%v err=%v", ok, err)
152 }
153
154 // Appendix E: kind, empty content, description == the zap request, P tag.
155 if ev.Kind != zapReceiptKind {
156 t.Fatalf("receipt kind = %d, want %d", ev.Kind, zapReceiptKind)
157 }
158 if ev.Content != "" {
159 t.Fatalf("receipt content should be empty, got %q", ev.Content)
160 }
161 var desc, bolt11, pTag string
162 var pUpper bool
163 for _, tg := range ev.Tags {
164 switch tg[0] {
165 case "description":
166 desc = tg[1]
167 case "bolt11":
168 bolt11 = tg[1]
169 case "P":
170 pUpper = true
171 case "p":
172 pTag = tg[1]
173 }
174 }
175 if desc != raw {
176 t.Fatal("description tag is not the exact zap request bytes")
177 }
178 if bolt11 != testInvoice {
179 t.Fatal("bolt11 tag does not match the invoice")
180 }
181 if !pUpper {
182 t.Fatal("receipt is missing the P (sender) tag")
183 }
184 if pTag != pk {
185 t.Fatalf("receipt p tag = %s, want the recipient %s", pTag, pk)
186 }
187 }
188
189 // TestZapStateRoundTrip covers persistence and the do-not-receipt-twice guard.
190 func TestZapStateRoundTrip(t *testing.T) {
191 dir := t.TempDir()
192 path := filepath.Join(dir, "zaps.json")
193
194 z, err := newZapServer("cc"+repeat("dd", 31), path)
195 if err != nil {
196 t.Fatalf("newZapServer: %v", err)
197 }
198 p := &pendingZap{
199 PaymentHash: testPaymentHash,
200 ZapRequest: `{"kind":9734}`,
201 Relays: []string{"wss://relay.example.com"},
202 AmountMsat: 21000,
203 Invoice: testInvoice,
204 CreatedAt: time.Now(),
205 }
206 if err := z.remember(p); err != nil {
207 t.Fatalf("remember: %v", err)
208 }
209 if !z.hasPending(testPaymentHash) {
210 t.Fatal("pending zap not recorded")
211 }
212
213 // Reload from disk.
214 z2, err := newZapServer("cc"+repeat("dd", 31), path)
215 if err != nil {
216 t.Fatalf("reload: %v", err)
217 }
218 got := z2.pending(testPaymentHash)
219 if got == nil {
220 t.Fatal("pending zap did not survive a reload")
221 }
222 if got.Invoice != testInvoice || got.AmountMsat != 21000 {
223 t.Fatalf("reloaded zap mismatch: %+v", got)
224 }
225
226 if err := z2.markReceipted(testPaymentHash, "eventid"); err != nil {
227 t.Fatalf("markReceipted: %v", err)
228 }
229 if z2.hasPending(testPaymentHash) {
230 t.Fatal("zap still pending after being receipted")
231 }
232 if !z2.alreadyReceipted(testPaymentHash) {
233 t.Fatal("receipt not recorded")
234 }
235 }
236
237 // TestParseAndValidateZapCanonicalises is a regression test for a real hole
238 // found in manual testing: the description hash was originally taken over the
239 // raw `nostr` query bytes, so a client could pair a valid signed event with
240 // arbitrary extra JSON and get an invoice committing to text no receipt could
241 // ever match. The hash must cover the canonical encoding the id/signature sign.
242 func TestParseAndValidateZapCanonicalises(t *testing.T) {
243 sk := nostr.GeneratePrivateKey()
244 pk, _ := nostr.GetPublicKey(sk)
245 amount := int64(21000)
246 raw, _ := buildZapRequest(t, sk, amount, [][]string{{"p", pk}})
247
248 zr, canonical, relays, err := parseAndValidateZap(raw, uint64(amount))
249 if err != nil {
250 t.Fatalf("valid zap request rejected: %v", err)
251 }
252 if len(relays) == 0 {
253 t.Fatal("no relays returned")
254 }
255
256 // The canonical form must round-trip to an event that still verifies; that
257 // is what makes it safe to hash.
258 var reZR ZapRequest
259 if err := json.Unmarshal([]byte(canonical), &reZR); err != nil {
260 t.Fatalf("canonical form is not JSON: %v", err)
261 }
262 if reZR.ID != zr.ID || reZR.Sig != zr.Sig || reZR.PubKey != zr.PubKey {
263 t.Fatalf("canonical form changed the identity:\n %+v\n %+v", reZR, zr)
264 }
265 if ok, err := zapEvent(&reZR).CheckSignature(); err != nil || !ok {
266 t.Fatalf("canonical form does not verify: ok=%v err=%v", ok, err)
267 }
268
269 // Trailing whitespace must not change the canonical form or the hash.
270 _, canonical2, _, err := parseAndValidateZap(raw+"\n ", uint64(amount))
271 if err != nil {
272 t.Fatalf("whitespace-padded request rejected: %v", err)
273 }
274 if canonical2 != canonical {
275 t.Fatal("whitespace changed the canonical form")
276 }
277
278 // A tampered id (whose signature no longer matches) must be rejected. This
279 // is the case that exposed the original bug during manual testing.
280 var tampered ZapRequest
281 if err := json.Unmarshal([]byte(raw), &tampered); err != nil {
282 t.Fatal(err)
283 }
284 if tampered.ID[0] == '1' {
285 tampered.ID = "2" + tampered.ID[1:]
286 } else {
287 tampered.ID = "1" + tampered.ID[1:]
288 }
289 tamperedRaw, err := json.Marshal(tampered)
290 if err != nil {
291 t.Fatal(err)
292 }
293 if _, _, _, err := parseAndValidateZap(string(tamperedRaw), uint64(amount)); err == nil {
294 t.Fatal("tampered event id was accepted")
295 }
296 }
297
298 func repeat(s string, n int) string {
299 out := make([]byte, 0, len(s)*n)
300 for i := 0; i < n; i++ {
301 out = append(out, s...)
302 }
303 return string(out)
304 }
305
306 // TestZapKeyIsStable ensures the advertised nostrPubkey does not change across
307 // restarts, since clients reject a receipt signed by a different key.
308 func TestZapKeyIsStable(t *testing.T) {
309 secret := "ee" + repeat("ff", 31)
310 a, err := loadOrCreateZapKey(secret)
311 if err != nil {
312 t.Fatalf("loadOrCreateZapKey: %v", err)
313 }
314 b, err := loadOrCreateZapKey(secret)
315 if err != nil {
316 t.Fatalf("loadOrCreateZapKey: %v", err)
317 }
318 if a != b {
319 t.Fatal("derived zap key is not stable")
320 }
321 c, _ := loadOrCreateZapKey("11" + repeat("22", 31))
322 if a == c {
323 t.Fatal("different NWC secrets produced the same zap key")
324 }
325
326 os.Setenv("ZAP_SECRET", secret)
327 defer os.Unsetenv("ZAP_SECRET")
328 explicit, err := loadOrCreateZapKey("ignored")
329 if err != nil {
330 t.Fatalf("explicit ZAP_SECRET: %v", err)
331 }
332 if explicit != secret {
333 t.Fatal("ZAP_SECRET was not honoured")
334 }
335 }
336
337 // TestPublicHostRefusesUnknownHosts covers a real hole: the Host header was
338 // reflected verbatim into the callback and metadata, so a request could mint a
339 // payRequest (and an invoice from this wallet) claiming to be a lightning
340 // address on someone else's domain.
341 func TestPublicHostRefusesUnknownHosts(t *testing.T) {
342 saveDomain, saveAllowed, saveUser := config.Domain, config.AllowedHosts, config.Username
343 defer func() {
344 config.Domain, config.AllowedHosts, config.Username = saveDomain, saveAllowed, saveUser
345 }()
346 config.Domain = "mleku.dev"
347 config.AllowedHosts = []string{"mleku.dev", "smesh.lol"}
348 config.Username = "me"
349
350 // Served hosts are accepted, including with a port (which must be stripped).
351 for in, want := range map[string]string{
352 "mleku.dev": "mleku.dev",
353 "smesh.lol": "smesh.lol",
354 "MLEKU.DEV": "mleku.dev",
355 "mleku.dev:443": "mleku.dev",
356 "mleku.dev:8096": "mleku.dev",
357 "mleku.dev.": "mleku.dev",
358 } {
359 got, err := publicHost(in)
360 if err != nil {
361 t.Fatalf("publicHost(%q) rejected a served host: %v", in, err)
362 }
363 if got != want {
364 t.Fatalf("publicHost(%q) = %q, want %q", in, got, want)
365 }
366 }
367
368 // Anything else must be refused rather than reflected.
369 for _, bad := range []string{
370 "evil.com", "mleku.dev.evil.com", "evil.com#mleku.dev",
371 "mleku.dev/path", "not a host", "a..b", "-x.dev", "mleku..dev",
372 } {
373 if got, err := publicHost(bad); err == nil {
374 t.Fatalf("publicHost(%q) accepted an unserved host as %q", bad, got)
375 }
376 }
377
378 // No Host at all falls back to the configured domain.
379 got, err := publicHost("")
380 if err != nil || got != "mleku.dev" {
381 t.Fatalf("empty host = %q, %v; want mleku.dev", got, err)
382 }
383 }
384
385 // TestValidUsername ensures the catch-all route cannot invent addresses such as
386 // the empty username (which produced "@mleku.dev") or arbitrary users.
387 func TestValidUsername(t *testing.T) {
388 saveUser := config.Username
389 defer func() { config.Username = saveUser }()
390 config.Username = "me"
391
392 if err := validUsername("me"); err != nil {
393 t.Fatalf("configured username rejected: %v", err)
394 }
395 for _, bad := range []string{"", "someoneelse", "ME", "me ", "../me", "@"} {
396 if err := validUsername(bad); err == nil {
397 t.Fatalf("username %q was accepted", bad)
398 }
399 }
400 }
401
402 // TestPendingCap bounds unpaid-zap state so invoice spam cannot grow it forever.
403 func TestPendingCap(t *testing.T) {
404 dir := t.TempDir()
405 z, err := newZapServer("ab"+repeat("cd", 31), filepath.Join(dir, "zaps.json"))
406 if err != nil {
407 t.Fatal(err)
408 }
409 for i := 0; i < maxPendingZaps; i++ {
410 h := repeat("00", 32)
411 h = hex.EncodeToString(append([]byte{byte(i >> 8), byte(i)}, make([]byte, 30)...))
412 if err := z.remember(&pendingZap{PaymentHash: h, CreatedAt: time.Now()}); err != nil {
413 t.Fatalf("remember %d: %v", i, err)
414 }
415 }
416 if err := z.remember(&pendingZap{PaymentHash: repeat("ff", 32), CreatedAt: time.Now()}); err == nil {
417 t.Fatal("expected the pending cap to reject a new zap")
418 }
419 // Re-remembering an existing hash must still succeed once full.
420 if err := z.remember(&pendingZap{PaymentHash: repeat("00", 32), CreatedAt: time.Now()}); err != nil {
421 t.Fatalf("updating an existing pending zap failed: %v", err)
422 }
423 }
424