Debian Codegraph @

server/leafnode_test.go

raw
1 // Copyright 2019-2026 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "bufio"
18 "bytes"
19 "compress/flate"
20 "context"
21 "crypto/tls"
22 "encoding/json"
23 "fmt"
24 "io"
25 "math/rand"
26 "net"
27 "net/http"
28 "net/http/httptest"
29 "net/url"
30 "os"
31 "reflect"
32 "strings"
33 "sync"
34 "sync/atomic"
35 "testing"
36 "time"
37
38 "github.com/nats-io/nkeys"
39
40 "github.com/klauspost/compress/s2"
41 jwt "github.com/nats-io/jwt/v2"
42 "github.com/nats-io/nats.go"
43
44 "github.com/nats-io/nats-server/v2/internal/fastrand"
45 "github.com/nats-io/nats-server/v2/internal/testhelper"
46 )
47
48 type captureLeafNodeRandomIPLogger struct {
49 DummyLogger
50 ch chan struct{}
51 ips [3]int
52 }
53
54 func (c *captureLeafNodeRandomIPLogger) Debugf(format string, v ...any) {
55 msg := fmt.Sprintf(format, v...)
56 if strings.Contains(msg, "hostname_to_resolve") {
57 ippos := strings.Index(msg, "127.0.0.")
58 if ippos != -1 {
59 n := int(msg[ippos+8] - '1')
60 c.ips[n]++
61 for _, v := range c.ips {
62 if v < 2 {
63 return
64 }
65 }
66 // All IPs got at least some hit, we are done.
67 c.ch <- struct{}{}
68 }
69 }
70 }
71
72 func TestLeafNodeRandomIP(t *testing.T) {
73 u, err := url.Parse("nats://hostname_to_resolve:1234")
74 if err != nil {
75 t.Fatalf("Error parsing: %v", err)
76 }
77
78 resolver := &myDummyDNSResolver{ips: []string{"127.0.0.1", "127.0.0.2", "127.0.0.3"}}
79
80 o := DefaultOptions()
81 o.Host = "127.0.0.1"
82 o.Port = -1
83 o.LeafNode.Port = 0
84 o.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}}}
85 o.LeafNode.ReconnectInterval = 50 * time.Millisecond
86 o.LeafNode.resolver = resolver
87 o.LeafNode.DialTimeout = 15 * time.Millisecond
88 s := RunServer(o)
89 defer s.Shutdown()
90
91 l := &captureLeafNodeRandomIPLogger{ch: make(chan struct{})}
92 s.SetLogger(l, true, true)
93
94 select {
95 case <-l.ch:
96 case <-time.After(3 * time.Second):
97 t.Fatalf("Does not seem to have used random IPs")
98 }
99 }
100
101 func TestLeafNodeRandomRemotes(t *testing.T) {
102 // 16! possible permutations.
103 orderedURLs := make([]*url.URL, 0, 16)
104 for i := 0; i < cap(orderedURLs); i++ {
105 orderedURLs = append(orderedURLs, &url.URL{
106 Scheme: "nats-leaf",
107 Host: fmt.Sprintf("host%d:7422", i),
108 })
109 }
110
111 o := DefaultOptions()
112 o.Accounts = append(o.Accounts, NewAccount("A"), NewAccount("B"))
113 o.LeafNode.Remotes = []*RemoteLeafOpts{
114 {NoRandomize: true, LocalAccount: "A"},
115 {NoRandomize: false, LocalAccount: "B"},
116 }
117 o.LeafNode.Remotes[0].URLs = make([]*url.URL, cap(orderedURLs))
118 copy(o.LeafNode.Remotes[0].URLs, orderedURLs)
119 o.LeafNode.Remotes[1].URLs = make([]*url.URL, cap(orderedURLs))
120 copy(o.LeafNode.Remotes[1].URLs, orderedURLs)
121
122 s := RunServer(o)
123 defer s.Shutdown()
124
125 var r1, r2 *leafNodeCfg
126 s.mu.RLock()
127 for r := range s.leafRemoteCfgs {
128 // Verify that the order of urls in the options have not been changed.
129 require_True(t, reflect.DeepEqual(r.URLs, orderedURLs))
130 // Capture the `leafNodeCfg` based on the NoRandomize option.
131 if r.NoRandomize {
132 r1 = r
133 } else {
134 r2 = r
135 }
136 }
137 s.mu.RUnlock()
138
139 r1.RLock()
140 gotOrdered := r1.urls
141 r1.RUnlock()
142 if got, want := len(gotOrdered), len(orderedURLs); got != want {
143 t.Fatalf("Unexpected rem0 len URLs, got %d, want %d", got, want)
144 }
145
146 // These should be IN order.
147 for i := range orderedURLs {
148 if got, want := gotOrdered[i].String(), orderedURLs[i].String(); got != want {
149 t.Fatalf("Unexpected ordered url, got %s, want %s", got, want)
150 }
151 }
152
153 r2.RLock()
154 gotRandom := r2.urls
155 r2.RUnlock()
156 if got, want := len(gotRandom), len(orderedURLs); got != want {
157 t.Fatalf("Unexpected rem1 len URLs, got %d, want %d", got, want)
158 }
159
160 // These should be OUT of order.
161 var random bool
162 for i := range orderedURLs {
163 if gotRandom[i].String() != orderedURLs[i].String() {
164 random = true
165 break
166 }
167 }
168 if !random {
169 t.Fatal("Expected urls to be random")
170 }
171 }
172
173 type testLoopbackResolver struct{}
174
175 func (r *testLoopbackResolver) LookupHost(ctx context.Context, host string) ([]string, error) {
176 return []string{"127.0.0.1"}, nil
177 }
178
179 func TestLeafNodeTLSWithCerts(t *testing.T) {
180 conf1 := createConfFile(t, []byte(`
181 port: -1
182 leaf {
183 listen: "127.0.0.1:-1"
184 tls {
185 ca_file: "../test/configs/certs/tlsauth/ca.pem"
186 cert_file: "../test/configs/certs/tlsauth/server.pem"
187 key_file: "../test/configs/certs/tlsauth/server-key.pem"
188 timeout: 2
189 }
190 }
191 `))
192 s1, o1 := RunServerWithConfig(conf1)
193 defer s1.Shutdown()
194
195 u, err := url.Parse(fmt.Sprintf("nats://localhost:%d", o1.LeafNode.Port))
196 if err != nil {
197 t.Fatalf("Error parsing url: %v", err)
198 }
199 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
200 port: -1
201 leaf {
202 remotes [
203 {
204 url: "%s"
205 tls {
206 ca_file: "../test/configs/certs/tlsauth/ca.pem"
207 cert_file: "../test/configs/certs/tlsauth/client.pem"
208 key_file: "../test/configs/certs/tlsauth/client-key.pem"
209 timeout: 2
210 }
211 }
212 ]
213 }
214 `, u.String())))
215 o2, err := ProcessConfigFile(conf2)
216 if err != nil {
217 t.Fatalf("Error processing config file: %v", err)
218 }
219 o2.NoLog, o2.NoSigs = true, true
220 o2.LeafNode.resolver = &testLoopbackResolver{}
221 s2 := RunServer(o2)
222 defer s2.Shutdown()
223
224 checkFor(t, 3*time.Second, 10*time.Millisecond, func() error {
225 if nln := s1.NumLeafNodes(); nln != 1 {
226 return fmt.Errorf("Number of leaf nodes is %d", nln)
227 }
228 return nil
229 })
230 }
231
232 func TestLeafNodeTLSRemoteWithNoCerts(t *testing.T) {
233 conf1 := createConfFile(t, []byte(`
234 port: -1
235 leaf {
236 listen: "127.0.0.1:-1"
237 tls {
238 ca_file: "../test/configs/certs/tlsauth/ca.pem"
239 cert_file: "../test/configs/certs/tlsauth/server.pem"
240 key_file: "../test/configs/certs/tlsauth/server-key.pem"
241 timeout: 2
242 }
243 }
244 `))
245 s1, o1 := RunServerWithConfig(conf1)
246 defer s1.Shutdown()
247
248 u, err := url.Parse(fmt.Sprintf("nats://localhost:%d", o1.LeafNode.Port))
249 if err != nil {
250 t.Fatalf("Error parsing url: %v", err)
251 }
252 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
253 port: -1
254 leaf {
255 remotes [
256 {
257 url: "%s"
258 tls {
259 ca_file: "../test/configs/certs/tlsauth/ca.pem"
260 timeout: 5
261 }
262 }
263 ]
264 }
265 `, u.String())))
266 o2, err := ProcessConfigFile(conf2)
267 if err != nil {
268 t.Fatalf("Error processing config file: %v", err)
269 }
270
271 if len(o2.LeafNode.Remotes) == 0 {
272 t.Fatal("Expected at least a single leaf remote")
273 }
274
275 var (
276 got float64 = o2.LeafNode.Remotes[0].TLSTimeout
277 expected float64 = 5
278 )
279 if got != expected {
280 t.Fatalf("Expected %v, got: %v", expected, got)
281 }
282 o2.NoLog, o2.NoSigs = true, true
283 o2.LeafNode.resolver = &testLoopbackResolver{}
284 s2 := RunServer(o2)
285 defer s2.Shutdown()
286
287 checkFor(t, 3*time.Second, 10*time.Millisecond, func() error {
288 if nln := s1.NumLeafNodes(); nln != 1 {
289 return fmt.Errorf("Number of leaf nodes is %d", nln)
290 }
291 return nil
292 })
293
294 // Here we only process options without starting the server
295 // and without a root CA for the remote.
296 conf3 := createConfFile(t, []byte(fmt.Sprintf(`
297 port: -1
298 leaf {
299 remotes [
300 {
301 url: "%s"
302 tls {
303 timeout: 10
304 }
305 }
306 ]
307 }
308 `, u.String())))
309 o3, err := ProcessConfigFile(conf3)
310 if err != nil {
311 t.Fatalf("Error processing config file: %v", err)
312 }
313
314 if len(o3.LeafNode.Remotes) == 0 {
315 t.Fatal("Expected at least a single leaf remote")
316 }
317 got = o3.LeafNode.Remotes[0].TLSTimeout
318 expected = 10
319 if got != expected {
320 t.Fatalf("Expected %v, got: %v", expected, got)
321 }
322
323 // Here we only process options without starting the server
324 // and check the default for leafnode remotes.
325 conf4 := createConfFile(t, []byte(fmt.Sprintf(`
326 port: -1
327 leaf {
328 remotes [
329 {
330 url: "%s"
331 tls {
332 ca_file: "../test/configs/certs/tlsauth/ca.pem"
333 }
334 }
335 ]
336 }
337 `, u.String())))
338 o4, err := ProcessConfigFile(conf4)
339 if err != nil {
340 t.Fatalf("Error processing config file: %v", err)
341 }
342
343 if len(o4.LeafNode.Remotes) == 0 {
344 t.Fatal("Expected at least a single leaf remote")
345 }
346 got = o4.LeafNode.Remotes[0].TLSTimeout
347 expected = float64(DEFAULT_LEAF_TLS_TIMEOUT) / float64(time.Second)
348 if int(got) != int(expected) {
349 t.Fatalf("Expected %v, got: %v", expected, got)
350 }
351 }
352
353 type captureErrorLogger struct {
354 DummyLogger
355 errCh chan string
356 }
357
358 func (l *captureErrorLogger) Errorf(format string, v ...any) {
359 select {
360 case l.errCh <- fmt.Sprintf(format, v...):
361 default:
362 }
363 }
364
365 func TestLeafNodeAccountNotFound(t *testing.T) {
366 ob := DefaultOptions()
367 ob.LeafNode.Host = "127.0.0.1"
368 ob.LeafNode.Port = -1
369 sb := RunServer(ob)
370 defer sb.Shutdown()
371
372 u, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", ob.LeafNode.Port))
373
374 oa := DefaultOptions()
375 oa.Cluster.Name = "xyz"
376 oa.LeafNode.ReconnectInterval = 10 * time.Millisecond
377 oa.LeafNode.Remotes = []*RemoteLeafOpts{
378 {
379 LocalAccount: "foo",
380 URLs: []*url.URL{u},
381 },
382 }
383 // Expected to fail
384 if _, err := NewServer(oa); err == nil || !strings.Contains(err.Error(), "local account") {
385 t.Fatalf("Expected server to fail with error about no local account, got %v", err)
386 }
387 oa.Accounts = []*Account{NewAccount("foo")}
388 sa := RunServer(oa)
389 defer sa.Shutdown()
390
391 l := &captureErrorLogger{errCh: make(chan string, 1)}
392 sa.SetLogger(l, false, false)
393
394 checkLeafNodeConnected(t, sa)
395
396 // Now simulate account is removed with config reload, or it expires.
397 sa.accounts.Delete("foo")
398
399 // Restart B (with same Port)
400 sb.Shutdown()
401 sb = RunServer(ob)
402 defer sb.Shutdown()
403
404 // Wait for report of error
405 select {
406 case e := <-l.errCh:
407 if !strings.Contains(e, "Unable to lookup account") {
408 t.Fatalf("Expected error about no local account, got %s", e)
409 }
410 case <-time.After(2 * time.Second):
411 t.Fatalf("Did not get the error")
412 }
413
414 // TODO below test is bogus. Instead add the account, do a reload, and make sure the connection works.
415
416 // For now, sa would try to recreate the connection for ever.
417 // Check that lid is increasing...
418 checkFor(t, 2*time.Second, 100*time.Millisecond, func() error {
419 if lid := atomic.LoadUint64(&sa.gcid); lid < 3 {
420 return fmt.Errorf("Seems like connection was not retried, lid currently only at %d", lid)
421 }
422 return nil
423 })
424 }
425
426 // This test ensures that we can connect using proper user/password
427 // to a LN URL that was discovered through the INFO protocol.
428 // We also check that the password doesn't leak to debug/trace logs.
429 func TestLeafNodeBasicAuthFailover(t *testing.T) {
430 // Something a little longer than "pwd" to prevent false positives amongst many log lines;
431 // don't make it complex enough to be subject to %-escaping, we want a simple needle search.
432 fatalPassword := "pwdfatal"
433
434 content := `
435 listen: "127.0.0.1:-1"
436 cluster {
437 name: "abc"
438 listen: "127.0.0.1:-1"
439 %s
440 }
441 leafnodes {
442 listen: "127.0.0.1:-1"
443 authorization {
444 user: foo
445 password: %s
446 timeout: 1
447 }
448 }
449 `
450 conf := createConfFile(t, []byte(fmt.Sprintf(content, "", fatalPassword)))
451
452 sb1, ob1 := RunServerWithConfig(conf)
453 defer sb1.Shutdown()
454
455 conf = createConfFile(t, []byte(fmt.Sprintf(content, fmt.Sprintf("routes: [nats://127.0.0.1:%d]", ob1.Cluster.Port), fatalPassword)))
456
457 sb2, _ := RunServerWithConfig(conf)
458 defer sb2.Shutdown()
459
460 checkClusterFormed(t, sb1, sb2)
461
462 content = `
463 port: -1
464 accounts {
465 foo {}
466 }
467 leafnodes {
468 listen: "127.0.0.1:-1"
469 remotes [
470 {
471 account: "foo"
472 url: "nats://foo:%[email protected]:%d"
473 }
474 ]
475 }
476 `
477 conf = createConfFile(t, []byte(fmt.Sprintf(content, fatalPassword, ob1.LeafNode.Port)))
478
479 sa, _ := RunServerWithConfig(conf)
480 defer sa.Shutdown()
481
482 l := testhelper.NewDummyLogger(100)
483 sa.SetLogger(l, true, true) // we want debug & trace logs, to check for passwords in them
484
485 checkLeafNodeConnected(t, sa)
486
487 // Shutdown sb1, sa should reconnect to sb2
488 sb1.Shutdown()
489
490 // Wait a bit to make sure there was a disconnect and attempt to reconnect.
491 time.Sleep(250 * time.Millisecond)
492
493 // Should be able to reconnect
494 checkLeafNodeConnected(t, sa)
495
496 // Look at all our logs for the password; at time of writing it doesn't appear
497 // but we want to safe-guard against it.
498 l.CheckForProhibited(t, "fatal password", fatalPassword)
499 }
500
501 func TestLeafNodeRTT(t *testing.T) {
502 ob := DefaultOptions()
503 ob.PingInterval = 15 * time.Millisecond
504 ob.LeafNode.Host = "127.0.0.1"
505 ob.LeafNode.Port = -1
506 sb := RunServer(ob)
507 defer sb.Shutdown()
508
509 lnBURL, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", ob.LeafNode.Port))
510 oa := DefaultOptions()
511 oa.Cluster.Name = "xyz"
512 oa.PingInterval = 15 * time.Millisecond
513 oa.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{lnBURL}}}
514 sa := RunServer(oa)
515 defer sa.Shutdown()
516
517 checkLeafNodeConnected(t, sa)
518
519 checkRTT := func(t *testing.T, s *Server) time.Duration {
520 t.Helper()
521 var ln *client
522 s.mu.Lock()
523 for _, l := range s.leafs {
524 ln = l
525 break
526 }
527 s.mu.Unlock()
528 var rtt time.Duration
529 checkFor(t, 2*firstPingInterval, 15*time.Millisecond, func() error {
530 ln.mu.Lock()
531 rtt = ln.rtt
532 ln.mu.Unlock()
533 if rtt == 0 {
534 return fmt.Errorf("RTT not tracked")
535 }
536 return nil
537 })
538 return rtt
539 }
540
541 prevA := checkRTT(t, sa)
542 prevB := checkRTT(t, sb)
543
544 // Wait to see if RTT is updated
545 checkUpdated := func(t *testing.T, s *Server, prev time.Duration) {
546 attempts := 0
547 timeout := time.Now().Add(2 * firstPingInterval)
548 for time.Now().Before(timeout) {
549 if rtt := checkRTT(t, s); rtt != prev {
550 return
551 }
552 attempts++
553 if attempts == 5 {
554 s.mu.Lock()
555 for _, ln := range s.leafs {
556 ln.mu.Lock()
557 ln.rtt = 0
558 ln.mu.Unlock()
559 break
560 }
561 s.mu.Unlock()
562 }
563 time.Sleep(15 * time.Millisecond)
564 }
565 t.Fatalf("RTT probably not updated")
566 }
567 checkUpdated(t, sa, prevA)
568 checkUpdated(t, sb, prevB)
569
570 sa.Shutdown()
571 sb.Shutdown()
572
573 // Now check that initial RTT is computed prior to first PingInterval
574 // Get new options to avoid possible race changing the ping interval.
575 ob = DefaultOptions()
576 ob.Cluster.Name = "xyz"
577 ob.PingInterval = time.Minute
578 ob.LeafNode.Host = "127.0.0.1"
579 ob.LeafNode.Port = -1
580 sb = RunServer(ob)
581 defer sb.Shutdown()
582
583 lnBURL, _ = url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", ob.LeafNode.Port))
584 oa = DefaultOptions()
585 oa.PingInterval = time.Minute
586 oa.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{lnBURL}}}
587 sa = RunServer(oa)
588 defer sa.Shutdown()
589
590 checkLeafNodeConnected(t, sa)
591
592 checkRTT(t, sa)
593 checkRTT(t, sb)
594 }
595
596 func TestLeafNodeValidateAuthOptions(t *testing.T) {
597 opts := DefaultOptions()
598 opts.LeafNode.Username = "user1"
599 opts.LeafNode.Password = "pwd"
600 opts.LeafNode.Users = []*User{{Username: "user", Password: "pwd"}}
601 if _, err := NewServer(opts); err == nil || !strings.Contains(err.Error(),
602 "can not have a single user/pass and a users array") {
603 t.Fatalf("Expected error about mixing single/multi users, got %v", err)
604 }
605
606 // Check duplicate user names
607 opts.LeafNode.Username = _EMPTY_
608 opts.LeafNode.Password = _EMPTY_
609 opts.LeafNode.Users = append(opts.LeafNode.Users, &User{Username: "user", Password: "pwd"})
610 if _, err := NewServer(opts); err == nil || !strings.Contains(err.Error(), "duplicate user") {
611 t.Fatalf("Expected error about duplicate user, got %v", err)
612 }
613 }
614
615 func TestLeafNodeBasicAuthSingleton(t *testing.T) {
616 opts := DefaultOptions()
617 opts.LeafNode.Port = -1
618 opts.LeafNode.Account = "unknown"
619 if s, err := NewServer(opts); err == nil || !strings.Contains(err.Error(), "cannot find") {
620 if s != nil {
621 s.Shutdown()
622 }
623 t.Fatalf("Expected error about account not found, got %v", err)
624 }
625
626 template := `
627 port: -1
628 accounts: {
629 ACC1: { users = [{user: "user1", password: "user1"}] }
630 ACC2: { users = [{user: "user2", password: "user2"}] }
631 }
632 leafnodes: {
633 port: -1
634 authorization {
635 %s
636 account: "ACC1"
637 }
638 }
639 `
640 for iter, test := range []struct {
641 name string
642 userSpec string
643 lnURLCreds string
644 shouldFail bool
645 }{
646 {"user creds required and no user so fails", "", "", true},
647 {"user creds required and pick user2 associated to ACC2", "", "user2:user2@", false},
648 {"user creds required and unknown user should fail", "", "unknown:user@", true},
649 {"user creds required so binds to ACC1", "user: \"ln\"\npass: \"pwd\"", "ln:pwd@", false},
650 } {
651 t.Run(test.name, func(t *testing.T) {
652
653 conf := createConfFile(t, []byte(fmt.Sprintf(template, test.userSpec)))
654 s1, o1 := RunServerWithConfig(conf)
655 defer s1.Shutdown()
656
657 // Create a sub on "foo" for account ACC1 (user user1), which is the one
658 // bound to the accepted LN connection.
659 ncACC1 := natsConnect(t, fmt.Sprintf("nats://user1:user1@%s:%d", o1.Host, o1.Port))
660 defer ncACC1.Close()
661 sub1 := natsSubSync(t, ncACC1, "foo")
662 natsFlush(t, ncACC1)
663
664 // Create a sub on "foo" for account ACC2 (user user2). This one should
665 // not receive any message.
666 ncACC2 := natsConnect(t, fmt.Sprintf("nats://user2:user2@%s:%d", o1.Host, o1.Port))
667 defer ncACC2.Close()
668 sub2 := natsSubSync(t, ncACC2, "foo")
669 natsFlush(t, ncACC2)
670
671 conf = createConfFile(t, []byte(fmt.Sprintf(`
672 port: -1
673 leafnodes: {
674 remotes = [ { url: "nats-leaf://%s%s:%d" } ]
675 }
676 `, test.lnURLCreds, o1.LeafNode.Host, o1.LeafNode.Port)))
677 s2, _ := RunServerWithConfig(conf)
678 defer s2.Shutdown()
679
680 if test.shouldFail {
681 // Wait a bit and ensure that there is no leaf node connection
682 time.Sleep(100 * time.Millisecond)
683 checkFor(t, time.Second, 15*time.Millisecond, func() error {
684 if n := s1.NumLeafNodes(); n != 0 {
685 return fmt.Errorf("Expected no leafnode connection, got %v", n)
686 }
687 return nil
688 })
689 return
690 }
691
692 checkLeafNodeConnected(t, s2)
693
694 nc := natsConnect(t, s2.ClientURL())
695 defer nc.Close()
696 natsPub(t, nc, "foo", []byte("hello"))
697 // If url contains known user, even when there is no credentials
698 // required, the connection will be bound to the user's account.
699 if iter == 1 {
700 // Should not receive on "ACC1", but should on "ACC2"
701 if _, err := sub1.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
702 t.Fatalf("Expected timeout error, got %v", err)
703 }
704 natsNexMsg(t, sub2, time.Second)
705 } else {
706 // Should receive on "ACC1"...
707 natsNexMsg(t, sub1, time.Second)
708 // but not received on "ACC2" since leafnode bound to account "ACC1".
709 if _, err := sub2.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
710 t.Fatalf("Expected timeout error, got %v", err)
711 }
712 }
713 })
714 }
715 }
716
717 func TestLeafNodeBasicAuthMultiple(t *testing.T) {
718 conf := createConfFile(t, []byte(`
719 port: -1
720 accounts: {
721 S1ACC1: { users = [{user: "user1", password: "user1"}] }
722 S1ACC2: { users = [{user: "user2", password: "user2"}] }
723 }
724 leafnodes: {
725 port: -1
726 authorization {
727 users = [
728 {user: "ln1", password: "ln1", account: "S1ACC1"}
729 {user: "ln2", password: "ln2", account: "S1ACC2"}
730 {user: "ln3", password: "ln3"}
731 ]
732 }
733 }
734 `))
735 s1, o1 := RunServerWithConfig(conf)
736 defer s1.Shutdown()
737
738 // Make sure that we reject a LN connection if user does not match
739 conf = createConfFile(t, []byte(fmt.Sprintf(`
740 port: -1
741 leafnodes: {
742 remotes = [{url: "nats-leaf://wron:user@%s:%d"}]
743 }
744 `, o1.LeafNode.Host, o1.LeafNode.Port)))
745 s2, _ := RunServerWithConfig(conf)
746 defer s2.Shutdown()
747 // Give a chance for s2 to attempt to connect and make sure that s1
748 // did not register a LN connection.
749 time.Sleep(100 * time.Millisecond)
750 if n := s1.NumLeafNodes(); n != 0 {
751 t.Fatalf("Expected no leafnode connection, got %v", n)
752 }
753 s2.Shutdown()
754
755 ncACC1 := natsConnect(t, fmt.Sprintf("nats://user1:user1@%s:%d", o1.Host, o1.Port))
756 defer ncACC1.Close()
757 sub1 := natsSubSync(t, ncACC1, "foo")
758 natsFlush(t, ncACC1)
759
760 ncACC2 := natsConnect(t, fmt.Sprintf("nats://user2:user2@%s:%d", o1.Host, o1.Port))
761 defer ncACC2.Close()
762 sub2 := natsSubSync(t, ncACC2, "foo")
763 natsFlush(t, ncACC2)
764
765 // We will start s2 with 2 LN connections that should bind local account S2ACC1
766 // to account S1ACC1 and S2ACC2 to account S1ACC2 on s1.
767 conf = createConfFile(t, []byte(fmt.Sprintf(`
768 port: -1
769 accounts {
770 S2ACC1 { users = [{user: "user1", password: "user1"}] }
771 S2ACC2 { users = [{user: "user2", password: "user2"}] }
772 }
773 leafnodes: {
774 remotes = [
775 {
776 url: "nats-leaf://ln1:ln1@%s:%d"
777 account: "S2ACC1"
778 }
779 {
780 url: "nats-leaf://ln2:ln2@%s:%d"
781 account: "S2ACC2"
782 }
783 ]
784 }
785 `, o1.LeafNode.Host, o1.LeafNode.Port, o1.LeafNode.Host, o1.LeafNode.Port)))
786 s2, o2 := RunServerWithConfig(conf)
787 defer s2.Shutdown()
788
789 checkFor(t, 5*time.Second, 100*time.Millisecond, func() error {
790 if nln := s2.NumLeafNodes(); nln != 2 {
791 return fmt.Errorf("Expected 2 connected leafnodes for server %q, got %d", s2.ID(), nln)
792 }
793 return nil
794 })
795
796 // Create a user connection on s2 that binds to S2ACC1 (use user1).
797 nc1 := natsConnect(t, fmt.Sprintf("nats://user1:user1@%s:%d", o2.Host, o2.Port))
798 defer nc1.Close()
799
800 // Create an user connection on s2 that binds to S2ACC2 (use user2).
801 nc2 := natsConnect(t, fmt.Sprintf("nats://user2:user2@%s:%d", o2.Host, o2.Port))
802 defer nc2.Close()
803
804 // Now if a message is published from nc1, sub1 should receive it since
805 // their account are bound together.
806 natsPub(t, nc1, "foo", []byte("hello"))
807 natsNexMsg(t, sub1, time.Second)
808 // But sub2 should not receive it since different account.
809 if _, err := sub2.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
810 t.Fatalf("Expected timeout error, got %v", err)
811 }
812
813 // Now use nc2 (S2ACC2) to publish
814 natsPub(t, nc2, "foo", []byte("hello"))
815 // Expect sub2 to receive and sub1 not to.
816 natsNexMsg(t, sub2, time.Second)
817 if _, err := sub1.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
818 t.Fatalf("Expected timeout error, got %v", err)
819 }
820
821 // Now check that we don't panic if no account is specified for
822 // a given user.
823 conf = createConfFile(t, []byte(fmt.Sprintf(`
824 port: -1
825 leafnodes: {
826 remotes = [
827 { url: "nats-leaf://ln3:ln3@%s:%d" }
828 ]
829 }
830 `, o1.LeafNode.Host, o1.LeafNode.Port)))
831 s3, _ := RunServerWithConfig(conf)
832 defer s3.Shutdown()
833 }
834
835 type loopDetectedLogger struct {
836 DummyLogger
837 ch chan string
838 }
839
840 func (l *loopDetectedLogger) Errorf(format string, v ...any) {
841 msg := fmt.Sprintf(format, v...)
842 if strings.Contains(msg, "Loop") {
843 select {
844 case l.ch <- msg:
845 default:
846 }
847 }
848 }
849
850 func TestLeafNodeLoop(t *testing.T) {
851 test := func(t *testing.T, cluster bool) {
852 // This test requires that we set the port to known value because
853 // we want A point to B and B to A.
854 oa := DefaultOptions()
855 oa.ServerName = "A"
856 if !cluster {
857 oa.Cluster.Port = 0
858 oa.Cluster.Name = _EMPTY_
859 }
860 oa.LeafNode.ReconnectInterval = 10 * time.Millisecond
861 oa.LeafNode.Port = 1234
862 ub, _ := url.Parse("nats://127.0.0.1:5678")
863 oa.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{ub}}}
864 oa.LeafNode.connDelay = 50 * time.Millisecond
865 sa := RunServer(oa)
866 defer sa.Shutdown()
867
868 la := &loopDetectedLogger{ch: make(chan string, 1)}
869 sa.SetLogger(la, false, false)
870
871 ob := DefaultOptions()
872 ob.ServerName = "B"
873 if !cluster {
874 ob.Cluster.Port = 0
875 ob.Cluster.Name = _EMPTY_
876 } else {
877 ob.Cluster.Name = "xyz"
878 }
879 ob.LeafNode.ReconnectInterval = 10 * time.Millisecond
880 ob.LeafNode.Port = 5678
881 ua, _ := url.Parse("nats://127.0.0.1:1234")
882 ob.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{ua}}}
883 ob.LeafNode.connDelay = 50 * time.Millisecond
884 sb := RunServer(ob)
885 defer sb.Shutdown()
886
887 lb := &loopDetectedLogger{ch: make(chan string, 1)}
888 sb.SetLogger(lb, false, false)
889
890 select {
891 case <-la.ch:
892 // OK!
893 case <-lb.ch:
894 // OK!
895 case <-time.After(5 * time.Second):
896 t.Fatalf("Did not get any error regarding loop")
897 }
898
899 sb.Shutdown()
900 ob.Port = -1
901 ob.Cluster.Port = -1
902 ob.LeafNode.Remotes = nil
903 sb = RunServer(ob)
904 defer sb.Shutdown()
905
906 checkLeafNodeConnected(t, sa)
907 }
908 t.Run("standalone", func(t *testing.T) { test(t, false) })
909 t.Run("cluster", func(t *testing.T) { test(t, true) })
910 }
911
912 func TestLeafNodeLoopFromDAG(t *testing.T) {
913 // We want B & C to point to A, A itself does not point to any other server.
914 // We need to cancel clustering since now this will suppress on its own.
915 oa := DefaultOptions()
916 oa.ServerName = "A"
917 oa.LeafNode.connDelay = 50 * time.Millisecond
918 oa.LeafNode.ReconnectInterval = 10 * time.Millisecond
919 oa.LeafNode.Port = -1
920 oa.Cluster = ClusterOpts{}
921 sa := RunServer(oa)
922 defer sa.Shutdown()
923
924 ua, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", oa.LeafNode.Port))
925
926 // B will point to A
927 ob := DefaultOptions()
928 ob.ServerName = "B"
929 ob.LeafNode.connDelay = 50 * time.Millisecond
930 ob.LeafNode.ReconnectInterval = 10 * time.Millisecond
931 ob.LeafNode.Port = -1
932 ob.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{ua}}}
933 ob.Cluster = ClusterOpts{}
934 sb := RunServer(ob)
935 defer sb.Shutdown()
936
937 ub, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", ob.LeafNode.Port))
938
939 checkLeafNodeConnected(t, sa)
940 checkLeafNodeConnected(t, sb)
941
942 // C will point to A and B
943 oc := DefaultOptions()
944 oc.ServerName = "C"
945 oc.LeafNode.connDelay = 50 * time.Millisecond
946 oc.LeafNode.ReconnectInterval = 10 * time.Millisecond
947 oc.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{ua}}, {URLs: []*url.URL{ub}}}
948 oc.LeafNode.connDelay = 100 * time.Millisecond // Allow logger to be attached before connecting.
949 oc.Cluster = ClusterOpts{}
950 sc := RunServer(oc)
951
952 lc := &loopDetectedLogger{ch: make(chan string, 1)}
953 sc.SetLogger(lc, false, false)
954
955 // We should get an error.
956 select {
957 case <-lc.ch:
958 // OK
959 case <-time.After(2 * time.Second):
960 t.Fatalf("Did not get any error regarding loop")
961 }
962
963 // C should not be connected to anything.
964 checkLeafNodeConnectedCount(t, sc, 0)
965 // A and B are connected to each other.
966 checkLeafNodeConnectedCount(t, sa, 1)
967 checkLeafNodeConnectedCount(t, sb, 1)
968
969 // Shutdown C and restart without the loop.
970 sc.Shutdown()
971 oc.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{ub}}}
972
973 sc = RunServer(oc)
974 defer sc.Shutdown()
975
976 checkLeafNodeConnectedCount(t, sa, 1)
977 checkLeafNodeConnectedCount(t, sb, 2)
978 checkLeafNodeConnectedCount(t, sc, 1)
979 }
980
981 func TestLeafNodeCloseTLSConnection(t *testing.T) {
982 opts := DefaultOptions()
983 opts.DisableShortFirstPing = true
984 opts.LeafNode.Host = "127.0.0.1"
985 opts.LeafNode.Port = -1
986 opts.LeafNode.TLSTimeout = 100
987 tc := &TLSConfigOpts{
988 CertFile: "./configs/certs/server.pem",
989 KeyFile: "./configs/certs/key.pem",
990 Insecure: true,
991 }
992 tlsConf, err := GenTLSConfig(tc)
993 if err != nil {
994 t.Fatalf("Error generating tls config: %v", err)
995 }
996 opts.LeafNode.TLSConfig = tlsConf
997 opts.NoLog = true
998 opts.NoSigs = true
999 s := RunServer(opts)
1000 defer s.Shutdown()
1001
1002 endpoint := net.JoinHostPort(opts.LeafNode.Host, fmt.Sprintf("%d", opts.LeafNode.Port))
1003 conn, err := net.DialTimeout("tcp", endpoint, 2*time.Second)
1004 if err != nil {
1005 t.Fatalf("Unexpected error on dial: %v", err)
1006 }
1007 defer conn.Close()
1008
1009 br := bufio.NewReaderSize(conn, 100)
1010 if _, err := br.ReadString('\n'); err != nil {
1011 t.Fatalf("Unexpected error reading INFO: %v", err)
1012 }
1013
1014 tlsConn := tls.Client(conn, &tls.Config{InsecureSkipVerify: true})
1015 defer tlsConn.Close()
1016 if err := tlsConn.Handshake(); err != nil {
1017 t.Fatalf("Unexpected error during handshake: %v", err)
1018 }
1019 connectOp := []byte("CONNECT {\"name\":\"leaf\",\"verbose\":false,\"pedantic\":false}\r\n")
1020 if _, err := tlsConn.Write(connectOp); err != nil {
1021 t.Fatalf("Unexpected error writing CONNECT: %v", err)
1022 }
1023 if _, err := tlsConn.Write([]byte("PING\r\n")); err != nil {
1024 t.Fatalf("Unexpected error writing PING: %v", err)
1025 }
1026
1027 checkLeafNodeConnected(t, s)
1028
1029 // Get leaf connection
1030 var leaf *client
1031 s.mu.Lock()
1032 for _, l := range s.leafs {
1033 leaf = l
1034 break
1035 }
1036 s.mu.Unlock()
1037 // Fill the buffer. We want to timeout on write so that nc.Close()
1038 // would block due to a write that cannot complete.
1039 buf := make([]byte, 64*1024)
1040 done := false
1041 for !done {
1042 leaf.nc.SetWriteDeadline(time.Now().Add(time.Second))
1043 if _, err := leaf.nc.Write(buf); err != nil {
1044 done = true
1045 }
1046 leaf.nc.SetWriteDeadline(time.Time{})
1047 }
1048 ch := make(chan bool)
1049 go func() {
1050 select {
1051 case <-ch:
1052 return
1053 case <-time.After(3 * time.Second):
1054 fmt.Println("!!!! closeConnection is blocked, test will hang !!!")
1055 return
1056 }
1057 }()
1058 // Close the route
1059 leaf.closeConnection(SlowConsumerWriteDeadline)
1060 ch <- true
1061 }
1062
1063 func TestLeafNodeTLSSaveName(t *testing.T) {
1064 opts := DefaultOptions()
1065 opts.LeafNode.Host = "127.0.0.1"
1066 opts.LeafNode.Port = -1
1067 tc := &TLSConfigOpts{
1068 CertFile: "../test/configs/certs/server-noip.pem",
1069 KeyFile: "../test/configs/certs/server-key-noip.pem",
1070 Insecure: true,
1071 }
1072 tlsConf, err := GenTLSConfig(tc)
1073 if err != nil {
1074 t.Fatalf("Error generating tls config: %v", err)
1075 }
1076 opts.LeafNode.TLSConfig = tlsConf
1077 s := RunServer(opts)
1078 defer s.Shutdown()
1079
1080 lo := DefaultOptions()
1081 u, _ := url.Parse(fmt.Sprintf("nats://localhost:%d", opts.LeafNode.Port))
1082 lo.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}}}
1083 lo.LeafNode.ReconnectInterval = 15 * time.Millisecond
1084 ln := RunServer(lo)
1085 defer ln.Shutdown()
1086
1087 // We know connection will fail, but it should not fail because of error such as:
1088 // "cannot validate certificate for 127.0.0.1 because it doesn't contain any IP SANs"
1089 // This would mean that we are not saving the hostname to use during the TLS handshake.
1090
1091 le := &captureErrorLogger{errCh: make(chan string, 100)}
1092 ln.SetLogger(le, false, false)
1093
1094 tm := time.NewTimer(time.Second)
1095 var done bool
1096 for !done {
1097 select {
1098 case err := <-le.errCh:
1099 if strings.Contains(err, "doesn't contain any IP SANs") {
1100 t.Fatalf("Got this error: %q", err)
1101 }
1102 case <-tm.C:
1103 done = true
1104 }
1105 }
1106 }
1107
1108 func TestLeafNodeRemoteWrongPort(t *testing.T) {
1109 for _, test1 := range []struct {
1110 name string
1111 clusterAdvertise bool
1112 leafnodeAdvertise bool
1113 }{
1114 {"advertise_on", false, false},
1115 {"cluster_no_advertise", true, false},
1116 {"leafnode_no_advertise", false, true},
1117 } {
1118 t.Run(test1.name, func(t *testing.T) {
1119 oa := DefaultOptions()
1120 // Make sure we have all ports (client, route, gateway) and we will try
1121 // to create a leafnode to connection to each and make sure we get the error.
1122 oa.Cluster.NoAdvertise = test1.clusterAdvertise
1123 oa.Cluster.Name = "A"
1124 oa.Cluster.Host = "127.0.0.1"
1125 oa.Cluster.Port = -1
1126 oa.Gateway.Host = "127.0.0.1"
1127 oa.Gateway.Port = -1
1128 oa.Gateway.Name = "A"
1129 oa.LeafNode.Host = "127.0.0.1"
1130 oa.LeafNode.Port = -1
1131 oa.LeafNode.NoAdvertise = test1.leafnodeAdvertise
1132 oa.Accounts = []*Account{NewAccount("sys")}
1133 oa.SystemAccount = "sys"
1134 sa := RunServer(oa)
1135 defer sa.Shutdown()
1136
1137 ob := DefaultOptions()
1138 ob.Cluster.NoAdvertise = test1.clusterAdvertise
1139 ob.Cluster.Name = "A"
1140 ob.Cluster.Host = "127.0.0.1"
1141 ob.Cluster.Port = -1
1142 ob.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", oa.Cluster.Host, oa.Cluster.Port))
1143 ob.Gateway.Host = "127.0.0.1"
1144 ob.Gateway.Port = -1
1145 ob.Gateway.Name = "A"
1146 ob.LeafNode.Host = "127.0.0.1"
1147 ob.LeafNode.Port = -1
1148 ob.LeafNode.NoAdvertise = test1.leafnodeAdvertise
1149 ob.Accounts = []*Account{NewAccount("sys")}
1150 ob.SystemAccount = "sys"
1151 sb := RunServer(ob)
1152 defer sb.Shutdown()
1153
1154 checkClusterFormed(t, sa, sb)
1155
1156 for _, test := range []struct {
1157 name string
1158 port int
1159 }{
1160 {"client", oa.Port},
1161 {"cluster", oa.Cluster.Port},
1162 {"gateway", oa.Gateway.Port},
1163 } {
1164 t.Run(test.name, func(t *testing.T) {
1165 oc := DefaultOptions()
1166 // Server with the wrong config against non leafnode port.
1167 leafURL, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", test.port))
1168 oc.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{leafURL}}}
1169 oc.LeafNode.ReconnectInterval = 5 * time.Millisecond
1170 sc := RunServer(oc)
1171 defer sc.Shutdown()
1172 l := &captureErrorLogger{errCh: make(chan string, 10)}
1173 sc.SetLogger(l, true, true)
1174
1175 select {
1176 case e := <-l.errCh:
1177 if strings.Contains(e, ErrConnectedToWrongPort.Error()) {
1178 return
1179 }
1180 case <-time.After(2 * time.Second):
1181 t.Fatalf("Did not get any error about connecting to wrong port for %q - %q",
1182 test1.name, test.name)
1183 }
1184 })
1185 }
1186 })
1187 }
1188 }
1189
1190 func TestLeafNodeRemoteIsHub(t *testing.T) {
1191 oa := testDefaultOptionsForGateway("A")
1192 oa.Accounts = []*Account{NewAccount("sys")}
1193 oa.SystemAccount = "sys"
1194 sa := RunServer(oa)
1195 defer sa.Shutdown()
1196
1197 lno := DefaultOptions()
1198 lno.LeafNode.Host = "127.0.0.1"
1199 lno.LeafNode.Port = -1
1200 ln := RunServer(lno)
1201 defer ln.Shutdown()
1202
1203 ob1 := testGatewayOptionsFromToWithServers(t, "B", "A", sa)
1204 ob1.Accounts = []*Account{NewAccount("sys")}
1205 ob1.SystemAccount = "sys"
1206 ob1.Cluster.Host = "127.0.0.1"
1207 ob1.Cluster.Port = -1
1208 ob1.LeafNode.Host = "127.0.0.1"
1209 ob1.LeafNode.Port = -1
1210 u, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", lno.LeafNode.Port))
1211 ob1.LeafNode.Remotes = []*RemoteLeafOpts{
1212 {
1213 URLs: []*url.URL{u},
1214 Hub: true,
1215 },
1216 }
1217 sb1 := RunServer(ob1)
1218 defer sb1.Shutdown()
1219
1220 waitForOutboundGateways(t, sb1, 1, 2*time.Second)
1221 waitForInboundGateways(t, sb1, 1, 2*time.Second)
1222 waitForOutboundGateways(t, sa, 1, 2*time.Second)
1223 waitForInboundGateways(t, sa, 1, 2*time.Second)
1224
1225 checkLeafNodeConnected(t, sb1)
1226
1227 // For now, due to issue 977, let's restart the leafnode so that the
1228 // leafnode connect is propagated in the super-cluster.
1229 ln.Shutdown()
1230 ln = RunServer(lno)
1231 defer ln.Shutdown()
1232 checkLeafNodeConnected(t, sb1)
1233
1234 // Connect another server in cluster B
1235 ob2 := testGatewayOptionsFromToWithServers(t, "B", "A", sa)
1236 ob2.Accounts = []*Account{NewAccount("sys")}
1237 ob2.SystemAccount = "sys"
1238 ob2.Cluster.Host = "127.0.0.1"
1239 ob2.Cluster.Port = -1
1240 ob2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", ob1.Cluster.Port))
1241 sb2 := RunServer(ob2)
1242 defer sb2.Shutdown()
1243
1244 checkClusterFormed(t, sb1, sb2)
1245 waitForOutboundGateways(t, sb2, 1, 2*time.Second)
1246
1247 expectedSubs := ln.NumSubscriptions() + 2
1248
1249 // Create sub on "foo" connected to sa
1250 ncA := natsConnect(t, sa.ClientURL())
1251 defer ncA.Close()
1252 subFoo := natsSubSync(t, ncA, "foo")
1253
1254 // Create sub on "bar" connected to sb2
1255 ncB2 := natsConnect(t, sb2.ClientURL())
1256 defer ncB2.Close()
1257 subBar := natsSubSync(t, ncB2, "bar")
1258
1259 // Make sure subscriptions have propagated to the leafnode.
1260 checkFor(t, time.Second, 10*time.Millisecond, func() error {
1261 if subs := ln.NumSubscriptions(); subs < expectedSubs {
1262 return fmt.Errorf("Number of subs is %d", subs)
1263 }
1264 return nil
1265 })
1266
1267 // Create pub connection on leafnode
1268 ncLN := natsConnect(t, ln.ClientURL())
1269 defer ncLN.Close()
1270
1271 // Publish on foo and make sure it is received.
1272 natsPub(t, ncLN, "foo", []byte("msg"))
1273 natsNexMsg(t, subFoo, time.Second)
1274
1275 // Publish on foo and make sure it is received.
1276 natsPub(t, ncLN, "bar", []byte("msg"))
1277 natsNexMsg(t, subBar, time.Second)
1278 }
1279
1280 func TestLeafNodePermissions(t *testing.T) {
1281 lo1 := DefaultOptions()
1282 lo1.LeafNode.Host = "127.0.0.1"
1283 lo1.LeafNode.Port = -1
1284 ln1 := RunServer(lo1)
1285 defer ln1.Shutdown()
1286
1287 errLog := &captureErrorLogger{errCh: make(chan string, 1)}
1288 ln1.SetLogger(errLog, false, false)
1289
1290 u, _ := url.Parse(fmt.Sprintf("nats://%s:%d", lo1.LeafNode.Host, lo1.LeafNode.Port))
1291 lo2 := DefaultOptions()
1292 lo2.Cluster.Name = "xyz"
1293 lo2.LeafNode.ReconnectInterval = 5 * time.Millisecond
1294 lo2.LeafNode.connDelay = 100 * time.Millisecond
1295 lo2.LeafNode.Remotes = []*RemoteLeafOpts{
1296 {
1297 URLs: []*url.URL{u},
1298 DenyExports: []string{"export.*", "export"},
1299 DenyImports: []string{"import.*", "import"},
1300 },
1301 }
1302 ln2 := RunServer(lo2)
1303 defer ln2.Shutdown()
1304
1305 checkLeafNodeConnected(t, ln1)
1306
1307 // Create clients on ln1 and ln2
1308 nc1, err := nats.Connect(ln1.ClientURL())
1309 if err != nil {
1310 t.Fatalf("Error creating client: %v", err)
1311 }
1312 defer nc1.Close()
1313 nc2, err := nats.Connect(ln2.ClientURL())
1314 if err != nil {
1315 t.Fatalf("Error creating client: %v", err)
1316 }
1317 defer nc2.Close()
1318
1319 checkSubs := func(acc *Account, expected int) {
1320 t.Helper()
1321 checkFor(t, time.Second, 15*time.Millisecond, func() error {
1322 if n := acc.TotalSubs(); n != expected {
1323 return fmt.Errorf("Expected %d subs, got %v", expected, n)
1324 }
1325 return nil
1326 })
1327 }
1328
1329 // Create a sub on ">" on LN1
1330 subAll := natsSubSync(t, nc1, ">")
1331 // this should be registered in LN2 (there is 1 sub for LN1 $LDS subject) + SYS IMPORTS
1332 checkSubs(ln2.globalAccount(), 12)
1333
1334 // Check deny export clause from messages published from LN2
1335 for _, test := range []struct {
1336 name string
1337 subject string
1338 received bool
1339 }{
1340 {"do not send on export.bat", "export.bat", false},
1341 {"do not send on export", "export", false},
1342 {"send on foo", "foo", true},
1343 {"send on export.this.one", "export.this.one", true},
1344 } {
1345 t.Run(test.name, func(t *testing.T) {
1346 nc2.Publish(test.subject, []byte("msg"))
1347 if test.received {
1348 natsNexMsg(t, subAll, time.Second)
1349 } else {
1350 if _, err := subAll.NextMsg(50 * time.Millisecond); err == nil {
1351 t.Fatalf("Should not have received message on %q", test.subject)
1352 }
1353 }
1354 })
1355 }
1356
1357 subAll.Unsubscribe()
1358 // Goes down by 1.
1359 checkSubs(ln2.globalAccount(), 11)
1360
1361 // We used to make sure we would not do subscriptions however that
1362 // was incorrect. We need to check publishes, not the subscriptions.
1363 // For instance if we can publish across a leafnode to foo, and the
1364 // other side has a subsxcription for '*' the message should cross
1365 // the leafnode. The old way would not allow this.
1366
1367 // Now check deny import clause.
1368 // As of now, we don't suppress forwarding of subscriptions on LN2 that
1369 // match the deny import clause to be forwarded to LN1. However, messages
1370 // should still not be able to come back to LN2.
1371 for _, test := range []struct {
1372 name string
1373 subSubject string
1374 pubSubject string
1375 ok bool
1376 }{
1377 {"reject import on import.*", "import.*", "import.bad", false},
1378 {"reject import on import", "import", "import", false},
1379 {"accepts import on foo", "foo", "foo", true},
1380 {"accepts import on import.this.one.ok", "import.*.>", "import.this.one.ok", true},
1381 } {
1382 t.Run(test.name, func(t *testing.T) {
1383 sub := natsSubSync(t, nc2, test.subSubject)
1384 checkSubs(ln2.globalAccount(), 12)
1385
1386 if !test.ok {
1387 nc1.Publish(test.pubSubject, []byte("msg"))
1388 if _, err := sub.NextMsg(50 * time.Millisecond); err == nil {
1389 t.Fatalf("Did not expect to get the message")
1390 }
1391 } else {
1392 checkSubs(ln1.globalAccount(), 11)
1393 nc1.Publish(test.pubSubject, []byte("msg"))
1394 natsNexMsg(t, sub, time.Second)
1395 }
1396 sub.Unsubscribe()
1397 checkSubs(ln1.globalAccount(), 10)
1398 })
1399 }
1400 }
1401
1402 func TestLeafNodePermissionsConcurrentAccess(t *testing.T) {
1403 lo1 := DefaultOptions()
1404 lo1.LeafNode.Host = "127.0.0.1"
1405 lo1.LeafNode.Port = -1
1406 ln1 := RunServer(lo1)
1407 defer ln1.Shutdown()
1408
1409 nc1 := natsConnect(t, ln1.ClientURL())
1410 defer nc1.Close()
1411
1412 natsSub(t, nc1, "_INBOX.>", func(_ *nats.Msg) {})
1413 natsFlush(t, nc1)
1414
1415 ch := make(chan struct{}, 1)
1416 wg := sync.WaitGroup{}
1417 wg.Add(2)
1418
1419 publish := func(nc *nats.Conn) {
1420 defer wg.Done()
1421
1422 for {
1423 select {
1424 case <-ch:
1425 return
1426 default:
1427 nc.Publish(nats.NewInbox(), []byte("hello"))
1428 }
1429 }
1430 }
1431
1432 go publish(nc1)
1433
1434 u, _ := url.Parse(fmt.Sprintf("nats://%s:%d", lo1.LeafNode.Host, lo1.LeafNode.Port))
1435 lo2 := DefaultOptions()
1436 lo2.Cluster.Name = "xyz"
1437 lo2.LeafNode.ReconnectInterval = 5 * time.Millisecond
1438 lo2.LeafNode.connDelay = 500 * time.Millisecond
1439 lo2.LeafNode.Remotes = []*RemoteLeafOpts{
1440 {
1441 URLs: []*url.URL{u},
1442 DenyExports: []string{"foo"},
1443 DenyImports: []string{"bar"},
1444 },
1445 }
1446 ln2 := RunServer(lo2)
1447 defer ln2.Shutdown()
1448
1449 nc2 := natsConnect(t, ln2.ClientURL())
1450 defer nc2.Close()
1451
1452 natsSub(t, nc2, "_INBOX.>", func(_ *nats.Msg) {})
1453 natsFlush(t, nc2)
1454
1455 go publish(nc2)
1456
1457 checkLeafNodeConnected(t, ln1)
1458 checkLeafNodeConnected(t, ln2)
1459
1460 time.Sleep(50 * time.Millisecond)
1461 close(ch)
1462 wg.Wait()
1463 }
1464
1465 func TestLeafNodeInfoPermissionUpdatesRequireSolicitedLeaf(t *testing.T) {
1466 s := &Server{}
1467 s.setOpts(DefaultOptions())
1468 cli, srv := net.Pipe()
1469 defer cli.Close()
1470 defer srv.Close()
1471
1472 c := &client{
1473 kind: LEAF,
1474 srv: s,
1475 nc: cli,
1476 leaf: &leaf{},
1477 }
1478 c.flags.set(infoReceived)
1479 c.flags.set(compressionNegotiated)
1480 c.flags.set(handshakeComplete)
1481
1482 c.processLeafnodeInfo(&Info{
1483 Import: &SubjectPermission{Allow: []string{"import.>"}},
1484 Export: &SubjectPermission{Allow: []string{"export.>"}},
1485 })
1486
1487 require_Equal(t, c.perms, (*permissions)(nil))
1488 }
1489
1490 func TestLeafNodeInfoPermissionUpdatesAllowedForSolicitedLeaf(t *testing.T) {
1491 s := &Server{}
1492 s.setOpts(DefaultOptions())
1493 cli, srv := net.Pipe()
1494 defer cli.Close()
1495 defer srv.Close()
1496
1497 c := &client{
1498 kind: LEAF,
1499 srv: s,
1500 nc: cli,
1501 leaf: &leaf{
1502 remote: &leafNodeCfg{RemoteLeafOpts: &RemoteLeafOpts{}},
1503 },
1504 }
1505 c.flags.set(infoReceived)
1506 c.flags.set(compressionNegotiated)
1507 c.flags.set(handshakeComplete)
1508
1509 c.processLeafnodeInfo(&Info{
1510 Import: &SubjectPermission{Allow: []string{"import.>"}},
1511 Export: &SubjectPermission{Allow: []string{"export.>"}},
1512 })
1513
1514 require_True(t, c.perms != nil)
1515 require_True(t, c.pubAllowed("export.foo"))
1516 require_True(t, c.canSubscribe("import.foo"))
1517 require_False(t, c.pubAllowed("other.foo"))
1518 require_False(t, c.canSubscribe("other.foo"))
1519 }
1520
1521 func TestLeafNodePubAllowedPruning(t *testing.T) {
1522 c := &client{}
1523 c.setPermissions(&Permissions{Publish: &SubjectPermission{Allow: []string{"foo"}}})
1524
1525 gr := 100
1526 wg := sync.WaitGroup{}
1527 wg.Add(gr)
1528 for i := 0; i < gr; i++ {
1529 go func() {
1530 defer wg.Done()
1531 for j := 0; j < 100; j++ {
1532 c.pubAllowed(nats.NewInbox())
1533 }
1534 }()
1535 }
1536
1537 wg.Wait()
1538 // The cache prune function does try for a bit to make sure the cache
1539 // is below the maxPermCacheSize value, but depending on the machine
1540 // this runs on, it may be that it is still a bit over. If so, run
1541 // pubAllowed one more time and we must get below.
1542 if n := int(atomic.LoadInt32(&c.perms.pcsz)); n > maxPermCacheSize {
1543 c.pubAllowed(nats.NewInbox())
1544 }
1545 if n := int(atomic.LoadInt32(&c.perms.pcsz)); n > maxPermCacheSize {
1546 t.Fatalf("Expected size to be less than %v, got %v", maxPermCacheSize, n)
1547 }
1548 if n := atomic.LoadInt32(&c.perms.prun); n != 0 {
1549 t.Fatalf("c.perms.prun should be 0, was %v", n)
1550 }
1551 }
1552
1553 func TestLeafNodeExportPermissionsNotForSpecialSubs(t *testing.T) {
1554 lo1 := DefaultOptions()
1555 lo1.Accounts = []*Account{NewAccount("SYS")}
1556 lo1.SystemAccount = "SYS"
1557 lo1.Cluster.Name = "A"
1558 lo1.Gateway.Name = "A"
1559 lo1.Gateway.Port = -1
1560 lo1.LeafNode.Host = "127.0.0.1"
1561 lo1.LeafNode.Port = -1
1562 ln1 := RunServer(lo1)
1563 defer ln1.Shutdown()
1564
1565 u, _ := url.Parse(fmt.Sprintf("nats://%s:%d", lo1.LeafNode.Host, lo1.LeafNode.Port))
1566 lo2 := DefaultOptions()
1567 lo2.LeafNode.Remotes = []*RemoteLeafOpts{
1568 {
1569 URLs: []*url.URL{u},
1570 DenyExports: []string{">"},
1571 },
1572 }
1573 ln2 := RunServer(lo2)
1574 defer ln2.Shutdown()
1575
1576 checkLeafNodeConnected(t, ln1)
1577
1578 // The deny is totally restrictive, but make sure that we still accept the $LDS, $GR and _GR_ go from LN1.
1579 checkFor(t, time.Second, 15*time.Millisecond, func() error {
1580 // We should have registered the 3 subs from the accepting leafnode.
1581 if n := ln2.globalAccount().TotalSubs(); n != 9 {
1582 return fmt.Errorf("Expected %d subs, got %v", 9, n)
1583 }
1584 return nil
1585 })
1586 }
1587
1588 // Make sure that if the node that detects the loop (and sends the error and
1589 // close the connection) is the accept side, the remote node (the one that solicits)
1590 // properly use the reconnect delay.
1591 func TestLeafNodeLoopDetectedOnAcceptSide(t *testing.T) {
1592 bo := DefaultOptions()
1593 bo.LeafNode.Host = "127.0.0.1"
1594 bo.LeafNode.Port = -1
1595 b := RunServer(bo)
1596 defer b.Shutdown()
1597
1598 l := &loopDetectedLogger{ch: make(chan string, 1)}
1599 b.SetLogger(l, false, false)
1600
1601 u, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", bo.LeafNode.Port))
1602
1603 ao := testDefaultOptionsForGateway("A")
1604 ao.Accounts = []*Account{NewAccount("SYS")}
1605 ao.SystemAccount = "SYS"
1606 ao.LeafNode.ReconnectInterval = 5 * time.Millisecond
1607 ao.LeafNode.Remotes = []*RemoteLeafOpts{
1608 {
1609 URLs: []*url.URL{u},
1610 Hub: true,
1611 },
1612 }
1613 a := RunServer(ao)
1614 defer a.Shutdown()
1615
1616 co := testGatewayOptionsFromToWithServers(t, "C", "A", a)
1617 co.Accounts = []*Account{NewAccount("SYS")}
1618 co.SystemAccount = "SYS"
1619 co.LeafNode.ReconnectInterval = 5 * time.Millisecond
1620 co.LeafNode.Remotes = []*RemoteLeafOpts{
1621 {
1622 URLs: []*url.URL{u},
1623 Hub: true,
1624 },
1625 }
1626 c := RunServer(co)
1627 defer c.Shutdown()
1628
1629 for i := 0; i < 2; i++ {
1630 select {
1631 case <-l.ch:
1632 // OK
1633 case <-time.After(200 * time.Millisecond):
1634 // We are likely to detect from each A and C servers,
1635 // but consider a failure if we did not receive any.
1636 if i == 0 {
1637 t.Fatalf("Should have detected loop")
1638 }
1639 }
1640 }
1641
1642 // The reconnect attempt is set to 5ms, but the default loop delay
1643 // is 30 seconds, so we should not get any new error for that long.
1644 // Check if we are getting more errors..
1645 select {
1646 case e := <-l.ch:
1647 t.Fatalf("Should not have gotten another error, got %q", e)
1648 case <-time.After(50 * time.Millisecond):
1649 // OK!
1650 }
1651 }
1652
1653 func TestLeafNodeHubWithGateways(t *testing.T) {
1654 ao := DefaultOptions()
1655 ao.ServerName = "A"
1656 ao.LeafNode.Host = "127.0.0.1"
1657 ao.LeafNode.Port = -1
1658 a := RunServer(ao)
1659 defer a.Shutdown()
1660
1661 ua, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", ao.LeafNode.Port))
1662
1663 bo := testDefaultOptionsForGateway("B")
1664 bo.ServerName = "B"
1665 bo.Accounts = []*Account{NewAccount("SYS")}
1666 bo.SystemAccount = "SYS"
1667 bo.LeafNode.ReconnectInterval = 5 * time.Millisecond
1668 bo.LeafNode.Remotes = []*RemoteLeafOpts{
1669 {
1670 URLs: []*url.URL{ua},
1671 Hub: true,
1672 },
1673 }
1674 b := RunServer(bo)
1675 defer b.Shutdown()
1676
1677 do := DefaultOptions()
1678 do.ServerName = "D"
1679 do.LeafNode.Host = "127.0.0.1"
1680 do.LeafNode.Port = -1
1681 d := RunServer(do)
1682 defer d.Shutdown()
1683
1684 ud, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", do.LeafNode.Port))
1685
1686 co := testGatewayOptionsFromToWithServers(t, "C", "B", b)
1687 co.ServerName = "C"
1688 co.Accounts = []*Account{NewAccount("SYS")}
1689 co.SystemAccount = "SYS"
1690 co.LeafNode.ReconnectInterval = 5 * time.Millisecond
1691 co.LeafNode.Remotes = []*RemoteLeafOpts{
1692 {
1693 URLs: []*url.URL{ud},
1694 Hub: true,
1695 },
1696 }
1697 c := RunServer(co)
1698 defer c.Shutdown()
1699
1700 waitForInboundGateways(t, b, 1, 2*time.Second)
1701 waitForInboundGateways(t, c, 1, 2*time.Second)
1702 checkLeafNodeConnected(t, a)
1703 checkLeafNodeConnected(t, d)
1704
1705 // Create a responder on D
1706 ncD := natsConnect(t, d.ClientURL())
1707 defer ncD.Close()
1708
1709 ncD.Subscribe("service", func(m *nats.Msg) {
1710 m.Respond([]byte("reply"))
1711 })
1712 ncD.Flush()
1713
1714 checkFor(t, time.Second, 15*time.Millisecond, func() error {
1715 acc := a.globalAccount()
1716 if r := acc.sl.Match("service"); r != nil && len(r.psubs) == 1 {
1717 return nil
1718 }
1719 return fmt.Errorf("subscription still not registered")
1720 })
1721
1722 // Create requestor on A and send the request, expect a reply.
1723 ncA := natsConnect(t, a.ClientURL())
1724 defer ncA.Close()
1725 if msg, err := ncA.Request("service", []byte("request"), time.Second); err != nil {
1726 t.Fatalf("Failed to get reply: %v", err)
1727 } else if string(msg.Data) != "reply" {
1728 t.Fatalf("Unexpected reply: %q", msg.Data)
1729 }
1730 }
1731
1732 func TestLeafNodeTmpClients(t *testing.T) {
1733 ao := DefaultOptions()
1734 ao.LeafNode.Host = "127.0.0.1"
1735 ao.LeafNode.Port = -1
1736 a := RunServer(ao)
1737 defer a.Shutdown()
1738
1739 c, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", ao.LeafNode.Port))
1740 if err != nil {
1741 t.Fatalf("Error connecting: %v", err)
1742 }
1743 defer c.Close()
1744 // Read info
1745 br := bufio.NewReader(c)
1746 br.ReadLine()
1747
1748 checkTmp := func(expected int) {
1749 t.Helper()
1750 checkFor(t, time.Second, 15*time.Millisecond, func() error {
1751 a.grMu.Lock()
1752 l := len(a.grTmpClients)
1753 a.grMu.Unlock()
1754 if l != expected {
1755 return fmt.Errorf("Expected tmp map to have %v entries, got %v", expected, l)
1756 }
1757 return nil
1758 })
1759 }
1760 checkTmp(1)
1761
1762 // Close client and wait check that it is removed.
1763 c.Close()
1764 checkTmp(0)
1765
1766 // Check with normal leafnode connection that once connected,
1767 // the tmp map is also emptied.
1768 bo := DefaultOptions()
1769 bo.Cluster.Name = "xyz"
1770 bo.LeafNode.ReconnectInterval = 5 * time.Millisecond
1771 u, err := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", ao.LeafNode.Port))
1772 if err != nil {
1773 t.Fatalf("Error creating url: %v", err)
1774 }
1775 bo.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}}}
1776 b := RunServer(bo)
1777 defer b.Shutdown()
1778
1779 checkLeafNodeConnected(t, b)
1780 checkTmp(0)
1781 }
1782
1783 func TestLeafNodeTLSVerifyAndMap(t *testing.T) {
1784 accName := "MyAccount"
1785 acc := NewAccount(accName)
1786 certUserName := "CN=example.com,OU=NATS.io"
1787 users := []*User{{Username: certUserName, Account: acc}}
1788
1789 for _, test := range []struct {
1790 name string
1791 leafUsers bool
1792 provideCert bool
1793 }{
1794 {"no users override, provides cert", false, true},
1795 {"no users override, does not provide cert", false, false},
1796 {"users override, provides cert", true, true},
1797 {"users override, does not provide cert", true, false},
1798 } {
1799 t.Run(test.name, func(t *testing.T) {
1800 o := DefaultOptions()
1801 o.Accounts = []*Account{acc}
1802 o.LeafNode.Host = "127.0.0.1"
1803 o.LeafNode.Port = -1
1804 if test.leafUsers {
1805 o.LeafNode.Users = users
1806 } else {
1807 o.Users = users
1808 }
1809 tc := &TLSConfigOpts{
1810 CertFile: "../test/configs/certs/tlsauth/server.pem",
1811 KeyFile: "../test/configs/certs/tlsauth/server-key.pem",
1812 CaFile: "../test/configs/certs/tlsauth/ca.pem",
1813 Verify: true,
1814 }
1815 tlsc, err := GenTLSConfig(tc)
1816 if err != nil {
1817 t.Fatalf("Error creating tls config: %v", err)
1818 }
1819 o.LeafNode.TLSConfig = tlsc
1820 o.LeafNode.TLSMap = true
1821 s := RunServer(o)
1822 defer s.Shutdown()
1823
1824 slo := DefaultOptions()
1825 slo.Cluster.Name = "xyz"
1826
1827 sltlsc := &tls.Config{}
1828 if test.provideCert {
1829 tc := &TLSConfigOpts{
1830 CertFile: "../test/configs/certs/tlsauth/client.pem",
1831 KeyFile: "../test/configs/certs/tlsauth/client-key.pem",
1832 }
1833 var err error
1834 sltlsc, err = GenTLSConfig(tc)
1835 if err != nil {
1836 t.Fatalf("Error generating tls config: %v", err)
1837 }
1838 }
1839 sltlsc.InsecureSkipVerify = true
1840 u, _ := url.Parse(fmt.Sprintf("nats://%s:%d", o.LeafNode.Host, o.LeafNode.Port))
1841 slo.LeafNode.Remotes = []*RemoteLeafOpts{
1842 {
1843 TLSConfig: sltlsc,
1844 URLs: []*url.URL{u},
1845 },
1846 }
1847 sl := RunServer(slo)
1848 defer sl.Shutdown()
1849
1850 if !test.provideCert {
1851 // Wait a bit and make sure we are not connecting
1852 time.Sleep(100 * time.Millisecond)
1853 checkLeafNodeConnectedCount(t, s, 0)
1854 return
1855 }
1856 checkLeafNodeConnected(t, s)
1857
1858 var uname string
1859 var accname string
1860 s.mu.Lock()
1861 for _, c := range s.leafs {
1862 c.mu.Lock()
1863 uname = c.opts.Username
1864 if c.acc != nil {
1865 accname = c.acc.GetName()
1866 }
1867 c.mu.Unlock()
1868 }
1869 s.mu.Unlock()
1870 if uname != certUserName {
1871 t.Fatalf("Expected username %q, got %q", certUserName, uname)
1872 }
1873 if accname != accName {
1874 t.Fatalf("Expected account %q, got %v", accName, accname)
1875 }
1876 })
1877 }
1878 }
1879
1880 type chanLogger struct {
1881 DummyLogger
1882 triggerChan chan string
1883 }
1884
1885 func (l *chanLogger) Warnf(format string, v ...any) {
1886 l.triggerChan <- fmt.Sprintf(format, v...)
1887 }
1888
1889 func (l *chanLogger) Errorf(format string, v ...any) {
1890 l.triggerChan <- fmt.Sprintf(format, v...)
1891 }
1892
1893 const (
1894 testLeafNodeTLSVerifyAndMapSrvA = `
1895 listen: 127.0.0.1:-1
1896 leaf {
1897 listen: "127.0.0.1:-1"
1898 tls {
1899 cert_file: "../test/configs/certs/server-cert.pem"
1900 key_file: "../test/configs/certs/server-key.pem"
1901 ca_file: "../test/configs/certs/ca.pem"
1902 timeout: 2
1903 verify_and_map: true
1904 }
1905 authorization {
1906 users [{
1907 user: "%s"
1908 }]
1909 }
1910 }
1911 `
1912 testLeafNodeTLSVerifyAndMapSrvB = `
1913 listen: -1
1914 leaf {
1915 remotes [
1916 {
1917 url: "tls://user-provided-in-url@localhost:%d"
1918 tls {
1919 cert_file: "../test/configs/certs/server-cert.pem"
1920 key_file: "../test/configs/certs/server-key.pem"
1921 ca_file: "../test/configs/certs/ca.pem"
1922 }
1923 }
1924 ]
1925 }`
1926 )
1927
1928 func TestLeafNodeTLSVerifyAndMapCfgPass(t *testing.T) {
1929 l := &chanLogger{triggerChan: make(chan string, 100)}
1930 defer close(l.triggerChan)
1931
1932 confA := createConfFile(t, []byte(fmt.Sprintf(testLeafNodeTLSVerifyAndMapSrvA, "localhost")))
1933 srvA, optsA := RunServerWithConfig(confA)
1934 defer srvA.Shutdown()
1935 srvA.SetLogger(l, true, true)
1936
1937 confB := createConfFile(t, []byte(fmt.Sprintf(testLeafNodeTLSVerifyAndMapSrvB, optsA.LeafNode.Port)))
1938 ob := LoadConfig(confB)
1939 ob.LeafNode.ReconnectInterval = 50 * time.Millisecond
1940 srvB := RunServer(ob)
1941 defer srvB.Shutdown()
1942
1943 // Now make sure that the leaf node connection is up and the correct account was picked
1944 checkFor(t, 10*time.Second, 10*time.Millisecond, func() error {
1945 for _, srv := range []*Server{srvA, srvB} {
1946 if nln := srv.NumLeafNodes(); nln != 1 {
1947 return fmt.Errorf("Number of leaf nodes is %d", nln)
1948 }
1949 if leafz, err := srv.Leafz(nil); err != nil {
1950 if len(leafz.Leafs) != 1 {
1951 return fmt.Errorf("Number of leaf nodes returned by LEAFZ is not one: %d", len(leafz.Leafs))
1952 } else if leafz.Leafs[0].Account != DEFAULT_GLOBAL_ACCOUNT {
1953 return fmt.Errorf("Account used is not $G: %s", leafz.Leafs[0].Account)
1954 }
1955 }
1956 }
1957 return nil
1958 })
1959 // Make sure that the user name in the url was ignored and a warning printed
1960 for {
1961 select {
1962 case w := <-l.triggerChan:
1963 if w == `User "user-provided-in-url" found in connect proto, but user required from cert` {
1964 return
1965 }
1966 case <-time.After(2 * time.Second):
1967 t.Fatal("Did not get expected warning")
1968 }
1969 }
1970 }
1971
1972 func TestLeafNodeTLSVerifyAndMapCfgFail(t *testing.T) {
1973 l := &chanLogger{triggerChan: make(chan string, 100)}
1974 defer close(l.triggerChan)
1975
1976 // use certificate with SAN localhost, but configure the server to not accept it
1977 // instead provide a name matching the user (to be matched by failed
1978 confA := createConfFile(t, []byte(fmt.Sprintf(testLeafNodeTLSVerifyAndMapSrvA, "user-provided-in-url")))
1979 srvA, optsA := RunServerWithConfig(confA)
1980 defer srvA.Shutdown()
1981 srvA.SetLogger(l, true, true)
1982
1983 confB := createConfFile(t, []byte(fmt.Sprintf(testLeafNodeTLSVerifyAndMapSrvB, optsA.LeafNode.Port)))
1984 ob := LoadConfig(confB)
1985 ob.LeafNode.ReconnectInterval = 50 * time.Millisecond
1986 srvB := RunServer(ob)
1987 defer srvB.Shutdown()
1988
1989 // Now make sure that the leaf node connection is down
1990 checkFor(t, 10*time.Second, 10*time.Millisecond, func() error {
1991 for _, srv := range []*Server{srvA, srvB} {
1992 if nln := srv.NumLeafNodes(); nln != 0 {
1993 return fmt.Errorf("Number of leaf nodes is %d", nln)
1994 }
1995 }
1996 return nil
1997 })
1998 // Make sure that the connection was closed for the right reason
1999 for {
2000 select {
2001 case w := <-l.triggerChan:
2002 if strings.Contains(w, ErrAuthentication.Error()) {
2003 return
2004 }
2005 case <-time.After(2 * time.Second):
2006 t.Fatal("Did not get expected warning")
2007 }
2008 }
2009 }
2010
2011 func TestLeafNodeOriginClusterInfo(t *testing.T) {
2012 hopts := DefaultOptions()
2013 hopts.ServerName = "hub"
2014 hopts.LeafNode.Port = -1
2015
2016 hub := RunServer(hopts)
2017 defer hub.Shutdown()
2018
2019 conf := createConfFile(t, []byte(fmt.Sprintf(`
2020 port: -1
2021 leaf {
2022 remotes [ { url: "nats://127.0.0.1:%d" } ]
2023 }
2024 `, hopts.LeafNode.Port)))
2025
2026 opts, err := ProcessConfigFile(conf)
2027 if err != nil {
2028 t.Fatalf("Error processing config file: %v", err)
2029 }
2030 opts.NoLog, opts.NoSigs = true, true
2031
2032 s := RunServer(opts)
2033 defer s.Shutdown()
2034
2035 checkLeafNodeConnected(t, s)
2036
2037 // Check the info on the leadnode client in the hub.
2038 grabLeaf := func() *client {
2039 var l *client
2040 hub.mu.Lock()
2041 for _, l = range hub.leafs {
2042 break
2043 }
2044 hub.mu.Unlock()
2045 return l
2046 }
2047
2048 l := grabLeaf()
2049 if rc := l.remoteCluster(); rc != "" {
2050 t.Fatalf("Expected an empty remote cluster, got %q", rc)
2051 }
2052
2053 s.Shutdown()
2054
2055 // Now make our leafnode part of a cluster.
2056 conf = createConfFile(t, []byte(fmt.Sprintf(`
2057 port: -1
2058 leaf {
2059 remotes [ { url: "nats://127.0.0.1:%d" } ]
2060 }
2061 cluster {
2062 name: "xyz"
2063 listen: "127.0.0.1:-1"
2064 }
2065 `, hopts.LeafNode.Port)))
2066
2067 opts, err = ProcessConfigFile(conf)
2068 if err != nil {
2069 t.Fatalf("Error processing config file: %v", err)
2070 }
2071 opts.NoLog, opts.NoSigs = true, true
2072
2073 s = RunServer(opts)
2074 defer s.Shutdown()
2075
2076 checkLeafNodeConnected(t, s)
2077
2078 l = grabLeaf()
2079 if rc := l.remoteCluster(); rc != "xyz" {
2080 t.Fatalf("Expected a remote cluster name of \"xyz\", got %q", rc)
2081 }
2082 pcid := l.cid
2083
2084 // Now make sure that if we update our cluster name, simulating the settling
2085 // of dynamic cluster names between competing servers.
2086 s.setClusterName("xyz")
2087 // Make sure we disconnect and reconnect.
2088 checkLeafNodeConnectedCount(t, s, 0)
2089 checkLeafNodeConnected(t, s)
2090 checkLeafNodeConnected(t, hub)
2091
2092 l = grabLeaf()
2093 if rc := l.remoteCluster(); rc != "xyz" {
2094 t.Fatalf("Expected a remote cluster name of \"xyz\", got %q", rc)
2095 }
2096 // Make sure we reconnected and have a new CID.
2097 if l.cid == pcid {
2098 t.Fatalf("Expected a different id, got the same")
2099 }
2100 }
2101
2102 type proxyAcceptDetectFailureLate struct {
2103 sync.Mutex
2104 wg sync.WaitGroup
2105 acceptPort int
2106 l net.Listener
2107 srvs []net.Conn
2108 leaf net.Conn
2109 startChan chan struct{}
2110 }
2111
2112 func (p *proxyAcceptDetectFailureLate) run(t *testing.T) int {
2113 return p.runEx(t, false)
2114 }
2115
2116 func (p *proxyAcceptDetectFailureLate) runEx(t *testing.T, needStart bool) int {
2117 l, err := natsListen("tcp", "127.0.0.1:0")
2118 if err != nil {
2119 t.Fatalf("Error on listen: %v", err)
2120 }
2121 p.Lock()
2122 var startChan chan struct{}
2123 if needStart {
2124 startChan = make(chan struct{})
2125 p.startChan = startChan
2126 }
2127 p.l = l
2128 p.Unlock()
2129 port := l.Addr().(*net.TCPAddr).Port
2130 p.wg.Add(1)
2131 go func() {
2132 defer p.wg.Done()
2133 defer l.Close()
2134 defer func() {
2135 p.Lock()
2136 for _, c := range p.srvs {
2137 c.Close()
2138 }
2139 p.Unlock()
2140 }()
2141 if startChan != nil {
2142 <-startChan
2143 }
2144 for {
2145 c, err := l.Accept()
2146 if err != nil {
2147 return
2148 }
2149 srv, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", p.acceptPort))
2150 if err != nil {
2151 return
2152 }
2153 p.Lock()
2154 p.leaf = c
2155 p.srvs = append(p.srvs, srv)
2156 p.Unlock()
2157
2158 transfer := func(c1, c2 net.Conn) {
2159 var buf [1024]byte
2160 for {
2161 n, err := c1.Read(buf[:])
2162 if err != nil {
2163 return
2164 }
2165 if _, err := c2.Write(buf[:n]); err != nil {
2166 return
2167 }
2168 }
2169 }
2170
2171 go transfer(srv, c)
2172 go transfer(c, srv)
2173 }
2174 }()
2175 return port
2176 }
2177
2178 func (p *proxyAcceptDetectFailureLate) start() {
2179 p.Lock()
2180 if p.startChan != nil {
2181 close(p.startChan)
2182 p.startChan = nil
2183 }
2184 p.Unlock()
2185 }
2186
2187 func (p *proxyAcceptDetectFailureLate) close() {
2188 p.Lock()
2189 if p.startChan != nil {
2190 close(p.startChan)
2191 p.startChan = nil
2192 }
2193 p.l.Close()
2194 p.Unlock()
2195
2196 p.wg.Wait()
2197 }
2198
2199 type oldConnReplacedLogger struct {
2200 DummyLogger
2201 errCh chan string
2202 warnCh chan string
2203 }
2204
2205 func (l *oldConnReplacedLogger) Errorf(format string, v ...any) {
2206 select {
2207 case l.errCh <- fmt.Sprintf(format, v...):
2208 default:
2209 }
2210 }
2211
2212 func (l *oldConnReplacedLogger) Warnf(format string, v ...any) {
2213 select {
2214 case l.warnCh <- fmt.Sprintf(format, v...):
2215 default:
2216 }
2217 }
2218
2219 // This test will simulate that the accept side does not detect the connection
2220 // has been closed early enough. The soliciting side will attempt to reconnect
2221 // and we should not be getting the "loop detected" error.
2222 func TestLeafNodeLoopDetectedDueToReconnect(t *testing.T) {
2223 o := DefaultOptions()
2224 o.LeafNode.Host = "127.0.0.1"
2225 o.LeafNode.Port = -1
2226 s := RunServer(o)
2227 defer s.Shutdown()
2228
2229 l := &oldConnReplacedLogger{errCh: make(chan string, 10), warnCh: make(chan string, 10)}
2230 s.SetLogger(l, false, false)
2231
2232 p := &proxyAcceptDetectFailureLate{acceptPort: o.LeafNode.Port}
2233 defer p.close()
2234 port := p.run(t)
2235
2236 aurl, err := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", port))
2237 if err != nil {
2238 t.Fatalf("Error parsing url: %v", err)
2239 }
2240 ol := DefaultOptions()
2241 ol.Cluster.Name = "cde"
2242 ol.LeafNode.ReconnectInterval = 50 * time.Millisecond
2243 ol.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{aurl}}}
2244 sl := RunServer(ol)
2245 defer sl.Shutdown()
2246
2247 checkLeafNodeConnected(t, s)
2248 checkLeafNodeConnected(t, sl)
2249
2250 // Cause disconnect client side...
2251 p.Lock()
2252 p.leaf.Close()
2253 p.Unlock()
2254
2255 // Make sure we did not get the loop detected error
2256 select {
2257 case e := <-l.errCh:
2258 if strings.Contains(e, "Loop detected") {
2259 t.Fatalf("Loop detected: %v", e)
2260 }
2261 case <-time.After(250 * time.Millisecond):
2262 // We are ok
2263 }
2264
2265 // Now make sure we got the warning
2266 select {
2267 case w := <-l.warnCh:
2268 if !strings.Contains(w, "Replacing connection from same server") {
2269 t.Fatalf("Unexpected warning: %v", w)
2270 }
2271 case <-time.After(time.Second):
2272 t.Fatal("Did not get expected warning")
2273 }
2274
2275 checkLeafNodeConnected(t, s)
2276 checkLeafNodeConnected(t, sl)
2277 }
2278
2279 func TestLeafNodeDetectDuplicateRemotesInOptions(t *testing.T) {
2280 u, err := url.Parse("nats://user1:[email protected]:1234")
2281 require_NoError(t, err)
2282 urls := []*url.URL{u}
2283 for _, test := range []struct {
2284 name string
2285 remote *RemoteLeafOpts
2286 }{
2287 {"same urls", &RemoteLeafOpts{URLs: urls}},
2288 {"same urls/acc", &RemoteLeafOpts{URLs: urls, LocalAccount: "A"}},
2289 {"same urls/acc/creds", &RemoteLeafOpts{URLs: urls, LocalAccount: "A", Credentials: "credsfile"}},
2290 } {
2291 t.Run(test.name, func(t *testing.T) {
2292 opts := DefaultOptions()
2293 opts.Accounts = append(opts.Accounts, NewAccount("A"))
2294 opts.LeafNode.Port = -1
2295 u, err := url.Parse("nats://user2:[email protected]:1235")
2296 require_NoError(t, err)
2297 rlo := &RemoteLeafOpts{URLs: []*url.URL{u}}
2298 opts.LeafNode.Remotes = append(opts.LeafNode.Remotes, test.remote, rlo, test.remote)
2299 _, err = NewServer(opts)
2300 require_Error(t, err)
2301 require_Contains(t, err.Error(), "duplicate remote")
2302 // Ensure url is redacted
2303 require_Contains(t, err.Error(), "user1:xxxxx")
2304 })
2305 }
2306 }
2307
2308 func TestLeafNodeHubRejectDuplicateRemotes(t *testing.T) {
2309 opts := DefaultOptions()
2310 opts.ServerName = "A"
2311 opts.LeafNode.Host = "127.0.0.1"
2312 opts.LeafNode.Port = -1
2313 s := RunServer(opts)
2314 defer s.Shutdown()
2315 l := &captureErrorLogger{errCh: make(chan string, 10)}
2316 s.SetLogger(l, false, false)
2317
2318 tmpl := `
2319 listen: 127.0.0.1:-1
2320 server_name: "B"
2321 leafnodes {
2322 remotes = [{url: nats-leaf://127.0.0.1:%d}]
2323 }
2324 `
2325 conf := createConfFile(t, fmt.Appendf(nil, tmpl, opts.LeafNode.Port))
2326 ln, lno := RunServerWithConfig(conf)
2327 defer ln.Shutdown()
2328
2329 // Since we correctly reject duplicate remotes, we have to manually
2330 // add a duplicate and start soliciting here.
2331 r := *lno.LeafNode.Remotes[0]
2332 ln.solicitLeafNodeRemotes([]*RemoteLeafOpts{&r})
2333
2334 select {
2335 case err := <-l.errCh:
2336 if !strings.Contains(err, DuplicateRemoteLeafnodeConnection.String()) {
2337 t.Fatalf("Did not get expected duplicate connection error: %v", err)
2338 }
2339 case <-time.After(250 * time.Millisecond):
2340 t.Fatal("Did not get expected error")
2341 }
2342 }
2343
2344 func TestLeafNodeNoDuplicateWithinCluster(t *testing.T) {
2345 // This set the cluster name to "abc"
2346 oSrv1 := DefaultOptions()
2347 oSrv1.ServerName = "srv1"
2348 oSrv1.LeafNode.Host = "127.0.0.1"
2349 oSrv1.LeafNode.Port = -1
2350 srv1 := RunServer(oSrv1)
2351 defer srv1.Shutdown()
2352
2353 u, err := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", oSrv1.LeafNode.Port))
2354 if err != nil {
2355 t.Fatalf("Error parsing url: %v", err)
2356 }
2357
2358 oLeaf1 := DefaultOptions()
2359 oLeaf1.ServerName = "leaf1"
2360 oLeaf1.Cluster.Name = "xyz"
2361 oLeaf1.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}}}
2362 leaf1 := RunServer(oLeaf1)
2363 defer leaf1.Shutdown()
2364
2365 leaf1ClusterURL := fmt.Sprintf("nats://127.0.0.1:%d", oLeaf1.Cluster.Port)
2366
2367 oLeaf2 := DefaultOptions()
2368 oLeaf2.ServerName = "leaf2"
2369 oLeaf2.Cluster.Name = "xyz"
2370 oLeaf2.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}}}
2371 oLeaf2.Routes = RoutesFromStr(leaf1ClusterURL)
2372 leaf2 := RunServer(oLeaf2)
2373 defer leaf2.Shutdown()
2374
2375 checkClusterFormed(t, leaf1, leaf2)
2376
2377 checkLeafNodeConnectedCount(t, srv1, 2)
2378 checkLeafNodeConnected(t, leaf1)
2379 checkLeafNodeConnected(t, leaf2)
2380
2381 ncSrv1 := natsConnect(t, srv1.ClientURL())
2382 defer ncSrv1.Close()
2383 natsQueueSub(t, ncSrv1, "foo", "queue", func(m *nats.Msg) {
2384 m.Data = []byte("from srv1")
2385 m.RespondMsg(m)
2386 })
2387
2388 ncLeaf1 := natsConnect(t, leaf1.ClientURL())
2389 defer ncLeaf1.Close()
2390 natsQueueSub(t, ncLeaf1, "foo", "queue", func(m *nats.Msg) {
2391 m.Data = []byte("from leaf1")
2392 m.RespondMsg(m)
2393 })
2394
2395 ncLeaf2 := natsConnect(t, leaf2.ClientURL())
2396 defer ncLeaf2.Close()
2397
2398 // Check that "foo" interest is available everywhere.
2399 for _, s := range []*Server{srv1, leaf1, leaf2} {
2400 gacc := s.GlobalAccount()
2401 checkFor(t, time.Second, 15*time.Millisecond, func() error {
2402 if n := gacc.Interest("foo"); n != 2 {
2403 return fmt.Errorf("Expected interest for %q to be 2, got %v", "foo", n)
2404 }
2405 return nil
2406 })
2407 }
2408
2409 // Send requests (from leaf2). For this test to make sure that
2410 // there is no duplicate, we want to make sure that we check for
2411 // multiple replies and that the reply subject subscription has
2412 // been propagated everywhere.
2413 sub := natsSubSync(t, ncLeaf2, "reply_subj")
2414 natsFlush(t, ncLeaf2)
2415
2416 // Here we have a single sub on "reply_subj" so using checkSubInterest is ok.
2417 checkSubInterest(t, srv1, globalAccountName, "reply_subj", time.Second)
2418 checkSubInterest(t, leaf1, globalAccountName, "reply_subj", time.Second)
2419 checkSubInterest(t, leaf2, globalAccountName, "reply_subj", time.Second)
2420
2421 for i := 0; i < 100; i++ {
2422 // Now send the request
2423 reqID := fmt.Sprintf("req.%d", i)
2424 msg := nats.NewMsg("foo")
2425 msg.Data = []byte("req")
2426 msg.Header.Set("ReqId", reqID)
2427 msg.Reply = sub.Subject
2428 if err := ncLeaf2.PublishMsg(msg); err != nil {
2429 t.Fatalf("Error on publish: %v", err)
2430 }
2431 // Check that we get the reply
2432 replyMsg := natsNexMsg(t, sub, time.Second)
2433 // But make sure no duplicate. We do so by checking that the reply's
2434 // header ReqId matches our current reqID.
2435 if respReqID := replyMsg.Header.Get("ReqId"); respReqID != reqID {
2436 t.Fatalf("Current request is %q, got duplicate with %q", reqID, respReqID)
2437 }
2438 // We also should have preferred the queue sub that is in the leaf cluster.
2439 if string(replyMsg.Data) != "from leaf1" {
2440 t.Fatalf("Expected reply from leaf1, got %q", replyMsg.Data)
2441 }
2442 }
2443 }
2444
2445 func TestLeafNodeLMsgSplit(t *testing.T) {
2446 // This set the cluster name to "abc"
2447 oSrv1 := DefaultOptions()
2448 oSrv1.LeafNode.Host = "127.0.0.1"
2449 oSrv1.LeafNode.Port = -1
2450 srv1 := RunServer(oSrv1)
2451 defer srv1.Shutdown()
2452
2453 oSrv2 := DefaultOptions()
2454 oSrv2.LeafNode.Host = "127.0.0.1"
2455 oSrv2.LeafNode.Port = -1
2456 oSrv2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", oSrv1.Cluster.Port))
2457 srv2 := RunServer(oSrv2)
2458 defer srv2.Shutdown()
2459
2460 checkClusterFormed(t, srv1, srv2)
2461
2462 u1, err := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", oSrv1.LeafNode.Port))
2463 if err != nil {
2464 t.Fatalf("Error parsing url: %v", err)
2465 }
2466 u2, err := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", oSrv2.LeafNode.Port))
2467 if err != nil {
2468 t.Fatalf("Error parsing url: %v", err)
2469 }
2470
2471 oLeaf1 := DefaultOptions()
2472 oLeaf1.Cluster.Name = "xyz"
2473 oLeaf1.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u1, u2}}}
2474 leaf1 := RunServer(oLeaf1)
2475 defer leaf1.Shutdown()
2476
2477 oLeaf2 := DefaultOptions()
2478 oLeaf2.Cluster.Name = "xyz"
2479 oLeaf2.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u1, u2}}}
2480 oLeaf2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", oLeaf1.Cluster.Port))
2481 leaf2 := RunServer(oLeaf2)
2482 defer leaf2.Shutdown()
2483
2484 checkClusterFormed(t, leaf1, leaf2)
2485
2486 checkLeafNodeConnected(t, leaf1)
2487 checkLeafNodeConnected(t, leaf2)
2488
2489 ncSrv2 := natsConnect(t, srv2.ClientURL())
2490 defer ncSrv2.Close()
2491 natsQueueSub(t, ncSrv2, "foo", "queue", func(m *nats.Msg) {
2492 m.Respond([]byte("from srv2"))
2493 })
2494
2495 // Check that "foo" interest is available everywhere.
2496 checkSubInterest(t, srv1, globalAccountName, "foo", time.Second)
2497 checkSubInterest(t, srv2, globalAccountName, "foo", time.Second)
2498 checkSubInterest(t, leaf1, globalAccountName, "foo", time.Second)
2499 checkSubInterest(t, leaf2, globalAccountName, "foo", time.Second)
2500
2501 // Not required, but have a request payload that is more than 100 bytes
2502 reqPayload := make([]byte, 150)
2503 for i := 0; i < len(reqPayload); i++ {
2504 reqPayload[i] = byte((i % 26)) + 'A'
2505 }
2506
2507 // Send repeated requests (from scratch) from leaf-2:
2508 sendReq := func() {
2509 t.Helper()
2510
2511 ncLeaf2 := natsConnect(t, leaf2.ClientURL())
2512 defer ncLeaf2.Close()
2513
2514 if _, err := ncLeaf2.Request("foo", reqPayload, time.Second); err != nil {
2515 t.Fatalf("Did not receive reply: %v", err)
2516 }
2517 }
2518 for i := 0; i < 100; i++ {
2519 sendReq()
2520 }
2521 }
2522
2523 type parseRouteLSUnsubLogger struct {
2524 DummyLogger
2525 gotTrace chan struct{}
2526 gotErr chan error
2527 }
2528
2529 func (l *parseRouteLSUnsubLogger) Errorf(format string, v ...any) {
2530 err := fmt.Errorf(format, v...)
2531 select {
2532 case l.gotErr <- err:
2533 default:
2534 }
2535 }
2536
2537 func (l *parseRouteLSUnsubLogger) Tracef(format string, v ...any) {
2538 trace := fmt.Sprintf(format, v...)
2539 if strings.Contains(trace, "LS- xyz $G foo bar") {
2540 l.gotTrace <- struct{}{}
2541 }
2542 }
2543
2544 func TestLeafNodeRouteParseLSUnsub(t *testing.T) {
2545 // This set the cluster name to "abc"
2546 oSrv1 := DefaultOptions()
2547 oSrv1.LeafNode.Host = "127.0.0.1"
2548 oSrv1.LeafNode.Port = -1
2549 srv1 := RunServer(oSrv1)
2550 defer srv1.Shutdown()
2551
2552 l := &parseRouteLSUnsubLogger{gotTrace: make(chan struct{}, 1), gotErr: make(chan error, 1)}
2553 srv1.SetLogger(l, true, true)
2554
2555 oSrv2 := DefaultOptions()
2556 oSrv2.LeafNode.Host = "127.0.0.1"
2557 oSrv2.LeafNode.Port = -1
2558 oSrv2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", oSrv1.Cluster.Port))
2559 srv2 := RunServer(oSrv2)
2560 defer srv2.Shutdown()
2561
2562 checkClusterFormed(t, srv1, srv2)
2563
2564 u2, err := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", oSrv2.LeafNode.Port))
2565 if err != nil {
2566 t.Fatalf("Error parsing url: %v", err)
2567 }
2568
2569 oLeaf2 := DefaultOptions()
2570 oLeaf2.Cluster.Name = "xyz"
2571 oLeaf2.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u2}}}
2572 leaf2 := RunServer(oLeaf2)
2573 defer leaf2.Shutdown()
2574
2575 checkLeafNodeConnected(t, srv2)
2576 checkLeafNodeConnected(t, leaf2)
2577
2578 ncLeaf2 := natsConnect(t, leaf2.ClientURL())
2579 defer ncLeaf2.Close()
2580
2581 sub := natsQueueSubSync(t, ncLeaf2, "foo", "bar")
2582 // The issue was with the unsubscribe of this queue subscription
2583 natsUnsub(t, sub)
2584
2585 // We should get the trace
2586 select {
2587 case <-l.gotTrace:
2588 // OK!
2589 case <-time.After(100 * time.Millisecond):
2590 t.Fatalf("Did not get LS- trace")
2591 }
2592 // And no error...
2593 select {
2594 case e := <-l.gotErr:
2595 t.Fatalf("There was an error on server 1: %q", e.Error())
2596 case <-time.After(100 * time.Millisecond):
2597 // OK!
2598 }
2599 }
2600
2601 func TestLeafNodeOperatorBadCfg(t *testing.T) {
2602 sysAcc, err := nkeys.CreateAccount()
2603 require_NoError(t, err)
2604 sysAccPk, err := sysAcc.PublicKey()
2605 require_NoError(t, err)
2606 tmpDir := t.TempDir()
2607
2608 configTmpl := `
2609 port: -1
2610 operator: %s
2611 system_account: %s
2612 resolver: {
2613 type: cache
2614 dir: '%s'
2615 }
2616 leafnodes: {
2617 %s
2618 }
2619 `
2620
2621 cases := []struct {
2622 name string
2623 errorText string
2624 cfg string
2625 }{
2626 {
2627 name: "Operator with Leafnode",
2628 errorText: "operator mode does not allow specifying users in leafnode config",
2629 cfg: `
2630 port: -1
2631 authorization {
2632 users = [{user: "u", password: "p"}]
2633 }`,
2634 },
2635 {
2636 name: "Operator with NKey",
2637 errorText: "operator mode and non account nkeys are incompatible",
2638 cfg: `
2639 port: -1
2640 authorization {
2641 account: notankey
2642 }`,
2643 },
2644 {
2645 name: "Operator remote account NKeys",
2646 errorText: "operator mode requires account nkeys in remotes. " +
2647 "Please add an `account` key to each remote in your `leafnodes` section, to assign it to an account. " +
2648 "Each account value should be a 56 character public key, starting with the letter 'A'",
2649 cfg: `remotes: [{url: u}]`,
2650 },
2651 }
2652 for _, c := range cases {
2653 t.Run(c.name, func(t *testing.T) {
2654
2655 conf := createConfFile(t, []byte(fmt.Sprintf(configTmpl, ojwt, sysAccPk, tmpDir, c.cfg)))
2656 opts := LoadConfig(conf)
2657 s, err := NewServer(opts)
2658 if err == nil {
2659 s.Shutdown()
2660 t.Fatal("Expected an error")
2661 }
2662 // Since the server cannot be stopped, since it did not start,
2663 // let's manually close the account resolver to avoid leaking go routines.
2664 opts.AccountResolver.Close()
2665 if err.Error() != c.errorText {
2666 t.Fatalf("Expected error %q but got %q", c.errorText, err)
2667 }
2668 })
2669 }
2670 }
2671
2672 func TestLeafNodeTLSConfigReload(t *testing.T) {
2673 template := `
2674 listen: 127.0.0.1:-1
2675 leaf {
2676 listen: "127.0.0.1:-1"
2677 tls {
2678 cert_file: "../test/configs/certs/server-cert.pem"
2679 key_file: "../test/configs/certs/server-key.pem"
2680 %s
2681 timeout: 2
2682 verify: true
2683 }
2684 }
2685 `
2686 confA := createConfFile(t, []byte(fmt.Sprintf(template, "")))
2687
2688 srvA, optsA := RunServerWithConfig(confA)
2689 defer srvA.Shutdown()
2690
2691 lg := &captureErrorLogger{errCh: make(chan string, 10)}
2692 srvA.SetLogger(lg, false, false)
2693
2694 confB := createConfFile(t, []byte(fmt.Sprintf(`
2695 listen: -1
2696 leaf {
2697 remotes [
2698 {
2699 url: "tls://127.0.0.1:%d"
2700 tls {
2701 cert_file: "../test/configs/certs/server-cert.pem"
2702 key_file: "../test/configs/certs/server-key.pem"
2703 ca_file: "../test/configs/certs/ca.pem"
2704 }
2705 }
2706 ]
2707 }
2708 `, optsA.LeafNode.Port)))
2709
2710 optsB, err := ProcessConfigFile(confB)
2711 if err != nil {
2712 t.Fatalf("Error processing config file: %v", err)
2713 }
2714 optsB.LeafNode.ReconnectInterval = 50 * time.Millisecond
2715 optsB.NoLog, optsB.NoSigs = true, true
2716
2717 srvB := RunServer(optsB)
2718 defer srvB.Shutdown()
2719
2720 // Wait for the error
2721 select {
2722 case err := <-lg.errCh:
2723 // Since Go 1.18, we had to regenerate certs to not have to use GODEBUG="x509sha1=1"
2724 // But on macOS, with our test CA certs, no SCTs included, it will fail
2725 // for the reason "x509: “localhost” certificate is not standards compliant"
2726 // instead of "unknown authority".
2727 if !strings.Contains(err, "unknown") && !strings.Contains(err, "compliant") {
2728 t.Fatalf("Unexpected error: %v", err)
2729 }
2730 case <-time.After(2 * time.Second):
2731 t.Fatalf("Did not get TLS error")
2732 }
2733
2734 // Add the CA to srvA
2735 reloadUpdateConfig(t, srvA, confA, fmt.Sprintf(template, `ca_file: "../test/configs/certs/ca.pem"`))
2736
2737 // Now make sure that srvB can create a LN connection.
2738 checkFor(t, 3*time.Second, 10*time.Millisecond, func() error {
2739 if nln := srvB.NumLeafNodes(); nln != 1 {
2740 return fmt.Errorf("Number of leaf nodes is %d", nln)
2741 }
2742 return nil
2743 })
2744 }
2745
2746 func TestLeafNodeTLSConfigReloadForRemote(t *testing.T) {
2747 confA := createConfFile(t, []byte(`
2748 listen: 127.0.0.1:-1
2749 leaf {
2750 listen: "127.0.0.1:-1"
2751 tls {
2752 cert_file: "../test/configs/certs/server-cert.pem"
2753 key_file: "../test/configs/certs/server-key.pem"
2754 ca_file: "../test/configs/certs/ca.pem"
2755 timeout: 2
2756 verify: true
2757 }
2758 }
2759 `))
2760
2761 srvA, optsA := RunServerWithConfig(confA)
2762 defer srvA.Shutdown()
2763
2764 lg := &captureErrorLogger{errCh: make(chan string, 10)}
2765 srvA.SetLogger(lg, false, false)
2766
2767 template := `
2768 listen: -1
2769 leaf {
2770 remotes [
2771 {
2772 url: "tls://127.0.0.1:%d"
2773 tls {
2774 cert_file: "../test/configs/certs/server-cert.pem"
2775 key_file: "../test/configs/certs/server-key.pem"
2776 %s
2777 }
2778 }
2779 ]
2780 }
2781 `
2782 confB := createConfFile(t, []byte(fmt.Sprintf(template, optsA.LeafNode.Port, "")))
2783
2784 srvB, _ := RunServerWithConfig(confB)
2785 defer srvB.Shutdown()
2786
2787 // Wait for the error
2788 select {
2789 case err := <-lg.errCh:
2790 if !strings.Contains(err, "bad certificate") {
2791 t.Fatalf("Unexpected error: %v", err)
2792 }
2793 case <-time.After(2 * time.Second):
2794 t.Fatalf("Did not get TLS error")
2795 }
2796
2797 // Add the CA to srvB
2798 reloadUpdateConfig(t, srvB, confB, fmt.Sprintf(template, optsA.LeafNode.Port, `ca_file: "../test/configs/certs/ca.pem"`))
2799
2800 // Now make sure that srvB can create a LN connection.
2801 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
2802 if nln := srvB.NumLeafNodes(); nln != 1 {
2803 return fmt.Errorf("Number of leaf nodes is %d", nln)
2804 }
2805 return nil
2806 })
2807 }
2808
2809 func testDefaultLeafNodeWSOptions() *Options {
2810 o := DefaultOptions()
2811 o.Websocket.Host = "127.0.0.1"
2812 o.Websocket.Port = -1
2813 o.Websocket.NoTLS = true
2814 o.LeafNode.Host = "127.0.0.1"
2815 o.LeafNode.Port = -1
2816 return o
2817 }
2818
2819 func testDefaultRemoteLeafNodeWSOptions(t *testing.T, o *Options, tls bool) *Options {
2820 // Use some path in the URL.. we don't use that, but internally
2821 // the server will prefix the path with /leafnode so that the
2822 // WS webserver knows that it needs to create a LEAF connection.
2823 u, _ := url.Parse(fmt.Sprintf("ws://127.0.0.1:%d/some/path", o.Websocket.Port))
2824 lo := DefaultOptions()
2825 lo.Cluster.Name = "LN"
2826 remote := &RemoteLeafOpts{URLs: []*url.URL{u}}
2827 if tls {
2828 tc := &TLSConfigOpts{
2829 CertFile: "../test/configs/certs/server-cert.pem",
2830 KeyFile: "../test/configs/certs/server-key.pem",
2831 CaFile: "../test/configs/certs/ca.pem",
2832 }
2833 tlsConf, err := GenTLSConfig(tc)
2834 if err != nil {
2835 t.Fatalf("Error generating TLS config: %v", err)
2836 }
2837 // GenTLSConfig sets the CA in ClientCAs, but since here we act
2838 // as a client, set RootCAs...
2839 tlsConf.RootCAs = tlsConf.ClientCAs
2840 remote.TLSConfig = tlsConf
2841 }
2842 lo.LeafNode.Remotes = []*RemoteLeafOpts{remote}
2843 return lo
2844 }
2845
2846 func TestLeafNodeWSMixURLs(t *testing.T) {
2847 for _, test := range []struct {
2848 name string
2849 urls []string
2850 }{
2851 {"mix 1", []string{"nats://127.0.0.1:1234", "ws://127.0.0.1:5678", "wss://127.0.0.1:9012"}},
2852 {"mix 2", []string{"ws://127.0.0.1:1234", "nats://127.0.0.1:5678", "wss://127.0.0.1:9012"}},
2853 {"mix 3", []string{"wss://127.0.0.1:1234", "ws://127.0.0.1:5678", "nats://127.0.0.1:9012"}},
2854 {"mix 4", []string{"ws://127.0.0.1:1234", "nats://127.0.0.1:9012"}},
2855 {"mix 5", []string{"nats://127.0.0.1:1234", "ws://127.0.0.1:9012"}},
2856 {"mix 6", []string{"wss://127.0.0.1:1234", "nats://127.0.0.1:9012"}},
2857 {"mix 7", []string{"nats://127.0.0.1:1234", "wss://127.0.0.1:9012"}},
2858 } {
2859 t.Run(test.name, func(t *testing.T) {
2860 o := DefaultOptions()
2861 remote := &RemoteLeafOpts{}
2862 urls := make([]*url.URL, 0, 3)
2863 for _, ustr := range test.urls {
2864 u, err := url.Parse(ustr)
2865 if err != nil {
2866 t.Fatalf("Error parsing url: %v", err)
2867 }
2868 urls = append(urls, u)
2869 }
2870 remote.URLs = urls
2871 o.LeafNode.Remotes = []*RemoteLeafOpts{remote}
2872 s, err := NewServer(o)
2873 if err == nil || !strings.Contains(err.Error(), "mix") {
2874 if s != nil {
2875 s.Shutdown()
2876 }
2877 t.Fatalf("Unexpected error: %v", err)
2878 }
2879 })
2880 }
2881 }
2882
2883 func TestLeafNodeWSFIPSValidation(t *testing.T) {
2884 for _, test := range []struct {
2885 name string
2886 url string
2887 }{
2888 {
2889 name: "no credentials",
2890 url: "wss://127.0.0.1:1234",
2891 },
2892 {
2893 name: "redacted credentials",
2894 url: "wss://user:pass@example:7422",
2895 },
2896 } {
2897 t.Run(test.name, func(t *testing.T) {
2898 u, err := url.Parse(test.url)
2899 if err != nil {
2900 t.Fatalf("Error parsing url: %v", err)
2901 }
2902
2903 o := DefaultOptions()
2904 o.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}}}
2905
2906 err = validateLeafNode(o)
2907 if wsAllowedFIPS() {
2908 if err != nil {
2909 t.Fatalf("Unexpected error: %v", err)
2910 }
2911 return
2912 }
2913 if err == nil {
2914 t.Fatal("Expected FIPS validation error, got none")
2915 }
2916 if strings.Contains(err.Error(), "user:pass") {
2917 t.Fatalf("Password was not redacted: %v", err)
2918 }
2919 if strings.Contains(err.Error(), "user:pass@") {
2920 t.Fatalf("Credentials were not redacted: %v", err)
2921 }
2922 if !strings.Contains(err.Error(), "FIPS-140 mode") {
2923 t.Fatalf("Unexpected error: %v", err)
2924 }
2925 })
2926 }
2927 }
2928
2929 type testConnTrackSize struct {
2930 sync.Mutex
2931 net.Conn
2932 sz int
2933 }
2934
2935 func (c *testConnTrackSize) Write(p []byte) (int, error) {
2936 c.Lock()
2937 defer c.Unlock()
2938 n, err := c.Conn.Write(p)
2939 c.sz += n
2940 return n, err
2941 }
2942
2943 func TestLeafNodeWSBasic(t *testing.T) {
2944 for _, test := range []struct {
2945 name string
2946 masking bool
2947 tls bool
2948 acceptCompression bool
2949 remoteCompression bool
2950 }{
2951 {"masking plain no compression", true, false, false, false},
2952 {"masking plain compression", true, false, true, true},
2953 {"masking plain compression disagree", true, false, false, true},
2954 {"masking plain compression disagree 2", true, false, true, false},
2955 {"masking tls no compression", true, true, false, false},
2956 {"masking tls compression", true, true, true, true},
2957 {"masking tls compression disagree", true, true, false, true},
2958 {"masking tls compression disagree 2", true, true, true, false},
2959 {"no masking plain no compression", false, false, false, false},
2960 {"no masking plain compression", false, false, true, true},
2961 {"no masking plain compression disagree", false, false, false, true},
2962 {"no masking plain compression disagree 2", false, false, true, false},
2963 {"no masking tls no compression", false, true, false, false},
2964 {"no masking tls compression", false, true, true, true},
2965 {"no masking tls compression disagree", false, true, false, true},
2966 {"no masking tls compression disagree 2", false, true, true, false},
2967 } {
2968 t.Run(test.name, func(t *testing.T) {
2969 o := testDefaultLeafNodeWSOptions()
2970 o.Websocket.NoTLS = !test.tls
2971 if test.tls {
2972 tc := &TLSConfigOpts{
2973 CertFile: "../test/configs/certs/server-cert.pem",
2974 KeyFile: "../test/configs/certs/server-key.pem",
2975 CaFile: "../test/configs/certs/ca.pem",
2976 }
2977 tlsConf, err := GenTLSConfig(tc)
2978 if err != nil {
2979 t.Fatalf("Error generating TLS config: %v", err)
2980 }
2981 o.Websocket.TLSConfig = tlsConf
2982 }
2983 o.Websocket.Compression = test.acceptCompression
2984 s := RunServer(o)
2985 defer s.Shutdown()
2986
2987 lo := testDefaultRemoteLeafNodeWSOptions(t, o, test.tls)
2988 lo.LeafNode.Remotes[0].Websocket.Compression = test.remoteCompression
2989 lo.LeafNode.Remotes[0].Websocket.NoMasking = !test.masking
2990 ln := RunServer(lo)
2991 defer ln.Shutdown()
2992
2993 checkLeafNodeConnected(t, s)
2994 checkLeafNodeConnected(t, ln)
2995
2996 var trackSizeConn *testConnTrackSize
2997 if !test.tls {
2998 var cln *client
2999 ln.mu.Lock()
3000 for _, l := range ln.leafs {
3001 cln = l
3002 break
3003 }
3004 ln.mu.Unlock()
3005 cln.mu.Lock()
3006 trackSizeConn = &testConnTrackSize{Conn: cln.nc}
3007 cln.nc = trackSizeConn
3008 cln.mu.Unlock()
3009 }
3010
3011 nc1 := natsConnect(t, s.ClientURL())
3012 defer nc1.Close()
3013 sub1 := natsSubSync(t, nc1, "foo")
3014 natsFlush(t, nc1)
3015
3016 checkSubInterest(t, ln, globalAccountName, "foo", time.Second)
3017
3018 nc2 := natsConnect(t, ln.ClientURL())
3019 defer nc2.Close()
3020 msg1Payload := make([]byte, 2048)
3021 for i := 0; i < len(msg1Payload); i++ {
3022 msg1Payload[i] = 'A'
3023 }
3024 natsPub(t, nc2, "foo", msg1Payload)
3025
3026 msg := natsNexMsg(t, sub1, time.Second)
3027 if !bytes.Equal(msg.Data, msg1Payload) {
3028 t.Fatalf("Invalid message: %q", msg.Data)
3029 }
3030
3031 sub2 := natsSubSync(t, nc2, "bar")
3032 natsFlush(t, nc2)
3033
3034 checkSubInterest(t, s, globalAccountName, "bar", time.Second)
3035
3036 msg2Payload := make([]byte, 2048)
3037 for i := 0; i < len(msg2Payload); i++ {
3038 msg2Payload[i] = 'B'
3039 }
3040 natsPub(t, nc1, "bar", msg2Payload)
3041
3042 msg = natsNexMsg(t, sub2, time.Second)
3043 if !bytes.Equal(msg.Data, msg2Payload) {
3044 t.Fatalf("Invalid message: %q", msg.Data)
3045 }
3046
3047 if !test.tls {
3048 trackSizeConn.Lock()
3049 size := trackSizeConn.sz
3050 trackSizeConn.Unlock()
3051
3052 if test.acceptCompression && test.remoteCompression {
3053 if size >= 1024 {
3054 t.Fatalf("Seems that there was no compression: size=%v", size)
3055 }
3056 } else if size < 2048 {
3057 t.Fatalf("Seems compression was on while it should not: size=%v", size)
3058 }
3059 }
3060 })
3061 }
3062 }
3063
3064 func TestLeafNodeWSRemoteCompressAndMaskingOptions(t *testing.T) {
3065 for _, test := range []struct {
3066 name string
3067 compress bool
3068 compStr string
3069 noMasking bool
3070 noMaskStr string
3071 }{
3072 {"compression masking", true, "true", false, "false"},
3073 {"compression no masking", true, "true", true, "true"},
3074 {"no compression masking", false, "false", false, "false"},
3075 {"no compression no masking", false, "false", true, "true"},
3076 } {
3077 t.Run(test.name, func(t *testing.T) {
3078 conf := createConfFile(t, []byte(fmt.Sprintf(`
3079 port: -1
3080 leafnodes {
3081 remotes [
3082 {url: "ws://127.0.0.1:1234", ws_compression: %s, ws_no_masking: %s}
3083 ]
3084 }
3085 `, test.compStr, test.noMaskStr)))
3086 o, err := ProcessConfigFile(conf)
3087 if err != nil {
3088 t.Fatalf("Error loading conf: %v", err)
3089 }
3090 if nr := len(o.LeafNode.Remotes); nr != 1 {
3091 t.Fatalf("Expected 1 remote, got %v", nr)
3092 }
3093 r := o.LeafNode.Remotes[0]
3094 if cur := r.Websocket.Compression; cur != test.compress {
3095 t.Fatalf("Expected compress to be %v, got %v", test.compress, cur)
3096 }
3097 if cur := r.Websocket.NoMasking; cur != test.noMasking {
3098 t.Fatalf("Expected ws_masking to be %v, got %v", test.noMasking, cur)
3099 }
3100 })
3101 }
3102 }
3103
3104 func TestLeafNodeWSNoMaskingRejected(t *testing.T) {
3105 wsTestRejectNoMasking = true
3106 defer func() { wsTestRejectNoMasking = false }()
3107
3108 o := testDefaultLeafNodeWSOptions()
3109 s := RunServer(o)
3110 defer s.Shutdown()
3111
3112 lo := testDefaultRemoteLeafNodeWSOptions(t, o, false)
3113 lo.LeafNode.Remotes[0].Websocket.NoMasking = true
3114 ln := RunServer(lo)
3115 defer ln.Shutdown()
3116
3117 checkLeafNodeConnected(t, s)
3118 checkLeafNodeConnected(t, ln)
3119
3120 var cln *client
3121 ln.mu.Lock()
3122 for _, l := range ln.leafs {
3123 cln = l
3124 break
3125 }
3126 ln.mu.Unlock()
3127
3128 cln.mu.Lock()
3129 maskWrite := cln.ws.maskwrite
3130 cln.mu.Unlock()
3131
3132 if !maskWrite {
3133 t.Fatal("Leafnode remote connection should mask writes, it does not")
3134 }
3135 }
3136
3137 func TestLeafNodeWSSubPath(t *testing.T) {
3138 o := testDefaultLeafNodeWSOptions()
3139 s := RunServer(o)
3140 defer s.Shutdown()
3141
3142 lo := testDefaultRemoteLeafNodeWSOptions(t, o, false)
3143 ln := RunServer(lo)
3144 defer ln.Shutdown()
3145
3146 // Confirm that it can connect using the subpath.
3147 checkLeafNodeConnected(t, s)
3148 checkLeafNodeConnected(t, ln)
3149
3150 // Add another leafnode that tries to connect to the subpath
3151 // but intercept the attempt for the test.
3152 o2 := testDefaultLeafNodeWSOptions()
3153 lo2 := testDefaultRemoteLeafNodeWSOptions(t, o2, false)
3154 attempts := make(chan string, 2)
3155 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
3156 attempts <- r.URL.String()
3157 }))
3158 defer ts.Close()
3159 u, _ := url.Parse(fmt.Sprintf("%v/some/path", ts.URL))
3160 u.Scheme = "ws"
3161 lo2.LeafNode.Remotes = []*RemoteLeafOpts{
3162 {
3163 URLs: []*url.URL{u},
3164 },
3165 }
3166 ln2 := RunServer(lo2)
3167 defer ln2.Shutdown()
3168
3169 expected := "/some/path/leafnode"
3170 select {
3171 case got := <-attempts:
3172 if got != expected {
3173 t.Fatalf("Expected: %v, got: %v", expected, got)
3174 }
3175 case <-time.After(2 * time.Second):
3176 t.Fatal("Timed out waiting for leaf ws connect attempt")
3177 }
3178 }
3179
3180 func TestLeafNodeWSFailedConnection(t *testing.T) {
3181 o := testDefaultLeafNodeWSOptions()
3182 s := RunServer(o)
3183 defer s.Shutdown()
3184
3185 lo := testDefaultRemoteLeafNodeWSOptions(t, o, true)
3186 lo.LeafNode.ReconnectInterval = 100 * time.Millisecond
3187 ln := RunServer(lo)
3188 defer ln.Shutdown()
3189
3190 el := &captureErrorLogger{errCh: make(chan string, 100)}
3191 ln.SetLogger(el, false, false)
3192
3193 select {
3194 case err := <-el.errCh:
3195 if !strings.Contains(err, "Error soliciting websocket connection") {
3196 t.Fatalf("Unexpected error: %v", err)
3197 }
3198 case <-time.After(time.Second):
3199 t.Fatal("No error reported!")
3200 }
3201 ln.Shutdown()
3202 s.Shutdown()
3203
3204 lst, err := natsListen("tcp", "127.0.0.1:0")
3205 if err != nil {
3206 t.Fatalf("Error starting listener: %v", err)
3207 }
3208 defer lst.Close()
3209
3210 wg := sync.WaitGroup{}
3211 wg.Add(2)
3212
3213 go func() {
3214 defer wg.Done()
3215
3216 for i := 0; i < 10; i++ {
3217 c, err := lst.Accept()
3218 if err != nil {
3219 return
3220 }
3221 time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
3222 if rand.Intn(2) == 1 {
3223 c.Write([]byte("something\r\n"))
3224 }
3225 c.Close()
3226 }
3227 }()
3228
3229 time.Sleep(100 * time.Millisecond)
3230
3231 port := lst.Addr().(*net.TCPAddr).Port
3232 u, _ := url.Parse(fmt.Sprintf("ws://127.0.0.1:%d", port))
3233 lo = DefaultOptions()
3234 lo.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}}}
3235 lo.LeafNode.ReconnectInterval = 10 * time.Millisecond
3236 ln, _ = NewServer(lo)
3237 el = &captureErrorLogger{errCh: make(chan string, 100)}
3238 ln.SetLogger(el, false, false)
3239
3240 go func() {
3241 ln.Start()
3242 wg.Done()
3243 }()
3244
3245 timeout := time.NewTimer(time.Second)
3246 for i := 0; i < 10; i++ {
3247 select {
3248 case err := <-el.errCh:
3249 if !strings.Contains(err, "Error soliciting") {
3250 t.Fatalf("Unexpected error: %v", err)
3251 }
3252 case <-timeout.C:
3253 t.Fatal("No error reported!")
3254 }
3255 }
3256 ln.Shutdown()
3257 lst.Close()
3258 wg.Wait()
3259 }
3260
3261 func TestLeafNodeWSAuth(t *testing.T) {
3262 template := `
3263 port: -1
3264 authorization {
3265 users [
3266 {user: "user", pass: "puser", connection_types: ["%s"]}
3267 {user: "leaf", pass: "pleaf", connection_types: ["%s"%s]}
3268 ]
3269 }
3270 websocket {
3271 port: -1
3272 no_tls: true
3273 }
3274 leafnodes {
3275 port: -1
3276 }
3277 `
3278 s, o, conf := runReloadServerWithContent(t,
3279 []byte(fmt.Sprintf(template, jwt.ConnectionTypeStandard, jwt.ConnectionTypeLeafnode, "")))
3280 defer s.Shutdown()
3281
3282 l := &captureErrorLogger{errCh: make(chan string, 10)}
3283 s.SetLogger(l, false, false)
3284
3285 lo := testDefaultRemoteLeafNodeWSOptions(t, o, false)
3286 u, _ := url.Parse(fmt.Sprintf("ws://leaf:[email protected]:%d", o.Websocket.Port))
3287 remote := &RemoteLeafOpts{URLs: []*url.URL{u}}
3288 lo.LeafNode.Remotes = []*RemoteLeafOpts{remote}
3289 lo.LeafNode.ReconnectInterval = 50 * time.Millisecond
3290 ln := RunServer(lo)
3291 defer ln.Shutdown()
3292
3293 var lasterr string
3294 tm := time.NewTimer(2 * time.Second)
3295 for done := false; !done; {
3296 select {
3297 case lasterr = <-l.errCh:
3298 if strings.Contains(lasterr, "authentication") {
3299 done = true
3300 }
3301 case <-tm.C:
3302 t.Fatalf("Expected auth error, got %v", lasterr)
3303 }
3304 }
3305
3306 ws := fmt.Sprintf(`, "%s"`, jwt.ConnectionTypeLeafnodeWS)
3307 reloadUpdateConfig(t, s, conf, fmt.Sprintf(template,
3308 jwt.ConnectionTypeStandard, jwt.ConnectionTypeLeafnode, ws))
3309
3310 checkLeafNodeConnected(t, s)
3311 checkLeafNodeConnected(t, ln)
3312
3313 nc1 := natsConnect(t, fmt.Sprintf("nats://user:[email protected]:%d", o.Port))
3314 defer nc1.Close()
3315
3316 sub := natsSubSync(t, nc1, "foo")
3317 natsFlush(t, nc1)
3318
3319 checkSubInterest(t, ln, globalAccountName, "foo", time.Second)
3320
3321 nc2 := natsConnect(t, ln.ClientURL())
3322 defer nc2.Close()
3323
3324 natsPub(t, nc2, "foo", []byte("msg1"))
3325 msg := natsNexMsg(t, sub, time.Second)
3326
3327 if md := string(msg.Data); md != "msg1" {
3328 t.Fatalf("Invalid message: %q", md)
3329 }
3330 }
3331
3332 func TestLeafNodeWSGossip(t *testing.T) {
3333 o1 := testDefaultLeafNodeWSOptions()
3334 s1 := RunServer(o1)
3335 defer s1.Shutdown()
3336
3337 // Now connect from a server that knows only about s1
3338 lo := testDefaultRemoteLeafNodeWSOptions(t, o1, false)
3339 lo.LeafNode.ReconnectInterval = 15 * time.Millisecond
3340 ln := RunServer(lo)
3341 defer ln.Shutdown()
3342
3343 checkLeafNodeConnected(t, s1)
3344 checkLeafNodeConnected(t, ln)
3345
3346 // Now add a routed server to s1
3347 o2 := testDefaultLeafNodeWSOptions()
3348 o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port))
3349 s2 := RunServer(o2)
3350 defer s2.Shutdown()
3351
3352 // Wait for cluster to form
3353 checkClusterFormed(t, s1, s2)
3354
3355 // Now shutdown s1 and check that ln is able to reconnect to s2.
3356 s1.Shutdown()
3357
3358 checkLeafNodeConnected(t, s2)
3359 checkLeafNodeConnected(t, ln)
3360
3361 // Make sure that the reconnection was as a WS connection, not simply to
3362 // the regular LN port.
3363 var s2lc *client
3364 s2.mu.Lock()
3365 for _, l := range s2.leafs {
3366 s2lc = l
3367 break
3368 }
3369 s2.mu.Unlock()
3370
3371 s2lc.mu.Lock()
3372 isWS := s2lc.isWebsocket()
3373 s2lc.mu.Unlock()
3374
3375 if !isWS {
3376 t.Fatal("Leafnode connection is not websocket!")
3377 }
3378 }
3379
3380 // This test was showing an issue if one set maxBufSize to very small value,
3381 // such as maxBufSize = 10. With such small value, we would get a corruption
3382 // in that LMSG would arrive with missing bytes. We are now always making
3383 // a copy when dealing with messages that are bigger than maxBufSize.
3384 func TestLeafNodeWSNoBufferCorruption(t *testing.T) {
3385 o := testDefaultLeafNodeWSOptions()
3386 s := RunServer(o)
3387 defer s.Shutdown()
3388
3389 lo1 := testDefaultRemoteLeafNodeWSOptions(t, o, false)
3390 lo1.LeafNode.ReconnectInterval = 15 * time.Millisecond
3391 ln1 := RunServer(lo1)
3392 defer ln1.Shutdown()
3393
3394 lo2 := DefaultOptions()
3395 lo2.Cluster.Name = "LN"
3396 lo2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", lo1.Cluster.Port))
3397 ln2 := RunServer(lo2)
3398 defer ln2.Shutdown()
3399
3400 checkClusterFormed(t, ln1, ln2)
3401
3402 checkLeafNodeConnected(t, s)
3403 checkLeafNodeConnected(t, ln1)
3404
3405 nc := natsConnect(t, s.ClientURL())
3406 defer nc.Close()
3407 sub := natsSubSync(t, nc, "foo")
3408
3409 nc1 := natsConnect(t, ln1.ClientURL())
3410 defer nc1.Close()
3411
3412 nc2 := natsConnect(t, ln2.ClientURL())
3413 defer nc2.Close()
3414 sub2 := natsSubSync(t, nc2, "foo")
3415
3416 checkSubInterest(t, s, globalAccountName, "foo", time.Second)
3417 checkSubInterest(t, ln2, globalAccountName, "foo", time.Second)
3418 checkSubInterest(t, ln1, globalAccountName, "foo", time.Second)
3419
3420 payload := make([]byte, 100*1024)
3421 for i := 0; i < len(payload); i++ {
3422 payload[i] = 'A'
3423 }
3424 natsPub(t, nc1, "foo", payload)
3425
3426 checkMsgRcv := func(sub *nats.Subscription) {
3427 msg := natsNexMsg(t, sub, time.Second)
3428 if !bytes.Equal(msg.Data, payload) {
3429 t.Fatalf("Invalid message content: %q", msg.Data)
3430 }
3431 }
3432 checkMsgRcv(sub2)
3433 checkMsgRcv(sub)
3434 }
3435
3436 func TestLeafNodeWSRemoteNoTLSBlockWithWSSProto(t *testing.T) {
3437 o := testDefaultLeafNodeWSOptions()
3438 o.Websocket.NoTLS = false
3439 tc := &TLSConfigOpts{
3440 CertFile: "../test/configs/certs/server-cert.pem",
3441 KeyFile: "../test/configs/certs/server-key.pem",
3442 CaFile: "../test/configs/certs/ca.pem",
3443 }
3444 tlsConf, err := GenTLSConfig(tc)
3445 if err != nil {
3446 t.Fatalf("Error generating TLS config: %v", err)
3447 }
3448 o.Websocket.TLSConfig = tlsConf
3449 s := RunServer(o)
3450 defer s.Shutdown()
3451
3452 // The test will make sure that if the protocol is "wss://", a TLS handshake must
3453 // be initiated, regardless of the presence of a TLS config block in config file
3454 // or here directly.
3455 // A bug was causing the absence of TLS config block to initiate a non TLS connection
3456 // even if "wss://" proto was specified, which would lead to "invalid websocket connection"
3457 // errors in the log.
3458 // With the fix, the connection will fail because the remote will fail to verify
3459 // the root CA, but at least, we will make sure that this is not an "invalid websocket connection"
3460
3461 u, _ := url.Parse(fmt.Sprintf("wss://127.0.0.1:%d/some/path", o.Websocket.Port))
3462 lo := DefaultOptions()
3463 lo.Cluster.Name = "LN"
3464 remote := &RemoteLeafOpts{URLs: []*url.URL{u}}
3465 lo.LeafNode.Remotes = []*RemoteLeafOpts{remote}
3466 lo.LeafNode.ReconnectInterval = 100 * time.Millisecond
3467 ln := RunServer(lo)
3468 defer ln.Shutdown()
3469
3470 l := &captureErrorLogger{errCh: make(chan string, 10)}
3471 ln.SetLogger(l, false, false)
3472
3473 select {
3474 case e := <-l.errCh:
3475 if strings.Contains(e, "invalid websocket connection") {
3476 t.Fatalf("The remote did not try to create a TLS connection: %v", e)
3477 }
3478 // OK!
3479 return
3480 case <-time.After(2 * time.Second):
3481 t.Fatal("Connection should fail")
3482 }
3483 }
3484
3485 func TestLeafNodeWSNoAuthUser(t *testing.T) {
3486 conf := createConfFile(t, []byte(`
3487 port: -1
3488 accounts {
3489 A { users [ {user: a, password: a} ]}
3490 B { users [ {user: b, password: b} ]}
3491 }
3492 websocket {
3493 port: -1
3494 no_tls: true
3495 no_auth_user: a
3496 }
3497 leafnodes {
3498 port: -1
3499 }
3500 `))
3501 s, o := RunServerWithConfig(conf)
3502 defer s.Shutdown()
3503
3504 nc1 := natsConnect(t, fmt.Sprintf("nats://a:[email protected]:%d", o.Port))
3505 defer nc1.Close()
3506
3507 lconf := createConfFile(t, []byte(fmt.Sprintf(`
3508 port: -1
3509 accounts {
3510 A { users [ {user: a, password: a} ]}
3511 B { users [ {user: b, password: b} ]}
3512 }
3513 leafnodes {
3514 remotes [
3515 {
3516 url: "ws://127.0.0.1:%d"
3517 account: A
3518 }
3519 ]
3520 }
3521 `, o.Websocket.Port)))
3522
3523 ln, lo := RunServerWithConfig(lconf)
3524 defer ln.Shutdown()
3525
3526 checkLeafNodeConnected(t, s)
3527 checkLeafNodeConnected(t, ln)
3528
3529 nc2 := natsConnect(t, fmt.Sprintf("nats://a:[email protected]:%d", lo.Port))
3530 defer nc2.Close()
3531
3532 sub := natsSubSync(t, nc2, "foo")
3533 natsFlush(t, nc2)
3534
3535 checkSubInterest(t, s, "A", "foo", time.Second)
3536
3537 natsPub(t, nc1, "foo", []byte("msg1"))
3538 msg := natsNexMsg(t, sub, time.Second)
3539
3540 if md := string(msg.Data); md != "msg1" {
3541 t.Fatalf("Invalid message: %q", md)
3542 }
3543 }
3544
3545 func TestLeafNodeStreamImport(t *testing.T) {
3546 o1 := DefaultOptions()
3547 o1.LeafNode.Port = -1
3548 accA := NewAccount("A")
3549 o1.Accounts = []*Account{accA}
3550 o1.Users = []*User{{Username: "a", Password: "a", Account: accA}}
3551 o1.LeafNode.Account = "A"
3552 o1.NoAuthUser = "a"
3553 s1 := RunServer(o1)
3554 defer s1.Shutdown()
3555
3556 o2 := DefaultOptions()
3557 o2.LeafNode.Port = -1
3558 o2.Cluster.Name = "xyz"
3559
3560 accB := NewAccount("B")
3561 if err := accB.AddStreamExport(">", nil); err != nil {
3562 t.Fatalf("Error adding stream export: %v", err)
3563 }
3564
3565 accC := NewAccount("C")
3566 if err := accC.AddStreamImport(accB, ">", ""); err != nil {
3567 t.Fatalf("Error adding stream import: %v", err)
3568 }
3569
3570 o2.Accounts = []*Account{accB, accC}
3571 o2.Users = []*User{{Username: "b", Password: "b", Account: accB}, {Username: "c", Password: "c", Account: accC}}
3572 o2.NoAuthUser = "b"
3573 u, err := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", o1.LeafNode.Port))
3574 if err != nil {
3575 t.Fatalf("Error parsing url: %v", err)
3576 }
3577 o2.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}, LocalAccount: "C"}}
3578 s2 := RunServer(o2)
3579 defer s2.Shutdown()
3580
3581 nc1 := natsConnect(t, s1.ClientURL())
3582 defer nc1.Close()
3583
3584 sub := natsSubSync(t, nc1, "a")
3585
3586 checkSubInterest(t, s2, "C", "a", time.Second)
3587
3588 nc2 := natsConnect(t, s2.ClientURL())
3589 defer nc2.Close()
3590
3591 natsPub(t, nc2, "a", []byte("hello?"))
3592
3593 natsNexMsg(t, sub, time.Second)
3594 }
3595
3596 func TestLeafNodeRouteSubWithOrigin(t *testing.T) {
3597 lo1 := DefaultOptions()
3598 lo1.LeafNode.Host = "127.0.0.1"
3599 lo1.LeafNode.Port = -1
3600 lo1.Cluster.Name = "local"
3601 lo1.Cluster.Host = "127.0.0.1"
3602 lo1.Cluster.Port = -1
3603 l1 := RunServer(lo1)
3604 defer l1.Shutdown()
3605
3606 lo2 := DefaultOptions()
3607 lo2.LeafNode.Host = "127.0.0.1"
3608 lo2.LeafNode.Port = -1
3609 lo2.Cluster.Name = "local"
3610 lo2.Cluster.Host = "127.0.0.1"
3611 lo2.Cluster.Port = -1
3612 lo2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", lo1.Cluster.Port))
3613 l2 := RunServer(lo2)
3614 defer l2.Shutdown()
3615
3616 checkClusterFormed(t, l1, l2)
3617
3618 u1, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", lo1.LeafNode.Port))
3619 urls := []*url.URL{u1}
3620
3621 ro1 := DefaultOptions()
3622 ro1.Cluster.Name = "remote"
3623 ro1.Cluster.Host = "127.0.0.1"
3624 ro1.Cluster.Port = -1
3625 ro1.LeafNode.ReconnectInterval = 50 * time.Millisecond
3626 ro1.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: urls}}
3627 r1 := RunServer(ro1)
3628 defer r1.Shutdown()
3629
3630 checkLeafNodeConnected(t, r1)
3631
3632 nc := natsConnect(t, r1.ClientURL(), nats.NoReconnect())
3633 defer nc.Close()
3634 natsSubSync(t, nc, "foo")
3635 natsQueueSubSync(t, nc, "bar", "baz")
3636 checkSubInterest(t, l2, globalAccountName, "foo", time.Second)
3637 checkSubInterest(t, l2, globalAccountName, "bar", time.Second)
3638
3639 // Now shutdown the leafnode and check that any subscription for $G on l2 are gone.
3640 r1.Shutdown()
3641 checkFor(t, time.Second, 15*time.Millisecond, func() error {
3642 acc := l2.GlobalAccount()
3643 if n := acc.TotalSubs(); n != 5 {
3644 return fmt.Errorf("Account %q should have 5 subs, got %v", acc.GetName(), n)
3645 }
3646 return nil
3647 })
3648 }
3649
3650 func TestLeafNodeLoopDetectionWithMultipleClusters(t *testing.T) {
3651 lo1 := DefaultOptions()
3652 lo1.LeafNode.Host = "127.0.0.1"
3653 lo1.LeafNode.Port = -1
3654 lo1.Cluster.Name = "local"
3655 lo1.Cluster.Host = "127.0.0.1"
3656 lo1.Cluster.Port = -1
3657 l1 := RunServer(lo1)
3658 defer l1.Shutdown()
3659
3660 lo2 := DefaultOptions()
3661 lo2.LeafNode.Host = "127.0.0.1"
3662 lo2.LeafNode.Port = -1
3663 lo2.Cluster.Name = "local"
3664 lo2.Cluster.Host = "127.0.0.1"
3665 lo2.Cluster.Port = -1
3666 lo2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", lo1.Cluster.Port))
3667 l2 := RunServer(lo2)
3668 defer l2.Shutdown()
3669
3670 checkClusterFormed(t, l1, l2)
3671
3672 ro1 := DefaultOptions()
3673 ro1.Cluster.Name = "remote"
3674 ro1.Cluster.Host = "127.0.0.1"
3675 ro1.Cluster.Port = -1
3676 ro1.LeafNode.ReconnectInterval = 50 * time.Millisecond
3677 ro1.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{
3678 {Scheme: "nats", Host: fmt.Sprintf("127.0.0.1:%d", lo1.LeafNode.Port)},
3679 {Scheme: "nats", Host: fmt.Sprintf("127.0.0.1:%d", lo2.LeafNode.Port)},
3680 }}}
3681 r1 := RunServer(ro1)
3682 defer r1.Shutdown()
3683
3684 l := &captureErrorLogger{errCh: make(chan string, 100)}
3685 r1.SetLogger(l, false, false)
3686
3687 ro2 := DefaultOptions()
3688 ro2.Cluster.Name = "remote"
3689 ro2.Cluster.Host = "127.0.0.1"
3690 ro2.Cluster.Port = -1
3691 ro2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", ro1.Cluster.Port))
3692 ro2.LeafNode.ReconnectInterval = 50 * time.Millisecond
3693 ro2.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{
3694 {Scheme: "nats", Host: fmt.Sprintf("127.0.0.1:%d", lo1.LeafNode.Port)},
3695 {Scheme: "nats", Host: fmt.Sprintf("127.0.0.1:%d", lo2.LeafNode.Port)},
3696 }}}
3697 r2 := RunServer(ro2)
3698 defer r2.Shutdown()
3699
3700 checkClusterFormed(t, r1, r2)
3701 checkLeafNodeConnected(t, r1)
3702 checkLeafNodeConnected(t, r2)
3703
3704 l1.Shutdown()
3705
3706 // Now wait for r1 and r2 to reconnect, they should not have a problem of loop detection.
3707 checkLeafNodeConnected(t, r1)
3708 checkLeafNodeConnected(t, r2)
3709
3710 // Wait and make sure we don't have a loop error
3711 timeout := time.NewTimer(500 * time.Millisecond)
3712 for {
3713 select {
3714 case err := <-l.errCh:
3715 if strings.Contains(err, "Loop detected") {
3716 t.Fatal(err)
3717 }
3718 case <-timeout.C:
3719 // OK, we are done.
3720 return
3721 }
3722 }
3723 }
3724
3725 func TestLeafNodeUnsubOnRouteDisconnect(t *testing.T) {
3726 lo1 := DefaultOptions()
3727 lo1.LeafNode.Host = "127.0.0.1"
3728 lo1.LeafNode.Port = -1
3729 lo1.Cluster.Name = "local"
3730 lo1.Cluster.Host = "127.0.0.1"
3731 lo1.Cluster.Port = -1
3732 l1 := RunServer(lo1)
3733 defer l1.Shutdown()
3734
3735 lo2 := DefaultOptions()
3736 lo2.LeafNode.Host = "127.0.0.1"
3737 lo2.LeafNode.Port = -1
3738 lo2.Cluster.Name = "local"
3739 lo2.Cluster.Host = "127.0.0.1"
3740 lo2.Cluster.Port = -1
3741 lo2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", lo1.Cluster.Port))
3742 l2 := RunServer(lo2)
3743 defer l2.Shutdown()
3744
3745 checkClusterFormed(t, l1, l2)
3746
3747 u1, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", lo1.LeafNode.Port))
3748 u2, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", lo2.LeafNode.Port))
3749 urls := []*url.URL{u1, u2}
3750
3751 ro1 := DefaultOptions()
3752 // DefaultOptions sets a cluster name, so make sure they are different.
3753 // Also, we don't have r1 and r2 clustered in this test, so set port to 0.
3754 ro1.Cluster.Name = _EMPTY_
3755 ro1.Cluster.Port = 0
3756 ro1.LeafNode.ReconnectInterval = 50 * time.Millisecond
3757 ro1.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: urls}}
3758 r1 := RunServer(ro1)
3759 defer r1.Shutdown()
3760
3761 ro2 := DefaultOptions()
3762 ro1.Cluster.Name = _EMPTY_
3763 ro2.Cluster.Port = 0
3764 ro2.LeafNode.ReconnectInterval = 50 * time.Millisecond
3765 // Have this one point only to l2
3766 ro2.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u2}}}
3767 r2 := RunServer(ro2)
3768 defer r2.Shutdown()
3769
3770 checkLeafNodeConnected(t, r1)
3771 checkLeafNodeConnected(t, r2)
3772
3773 // Create a subscription on r1.
3774 nc := natsConnect(t, r1.ClientURL())
3775 defer nc.Close()
3776 sub := natsSubSync(t, nc, "foo")
3777 natsFlush(t, nc)
3778
3779 checkSubInterest(t, l2, globalAccountName, "foo", time.Second)
3780 checkSubInterest(t, r2, globalAccountName, "foo", time.Second)
3781
3782 nc2 := natsConnect(t, r2.ClientURL())
3783 defer nc2.Close()
3784 natsPub(t, nc, "foo", []byte("msg1"))
3785
3786 // Check message received
3787 natsNexMsg(t, sub, time.Second)
3788
3789 // Now shutdown l1, l2 should update subscription interest to r2.
3790 // When r1 reconnects to l2, subscription should be updated too.
3791 l1.Shutdown()
3792
3793 // Wait a bit (so that the check of interest is not OK just because
3794 // the route would not have been yet detected as broken), and check
3795 // interest still present on r2, l2.
3796 time.Sleep(100 * time.Millisecond)
3797 checkSubInterest(t, l2, globalAccountName, "foo", time.Second)
3798 checkSubInterest(t, r2, globalAccountName, "foo", time.Second)
3799
3800 // Check again that message received ok
3801 natsPub(t, nc, "foo", []byte("msg2"))
3802 natsNexMsg(t, sub, time.Second)
3803
3804 // Now close client. Interest should disappear on r2. Due to a bug,
3805 // it was not.
3806 nc.Close()
3807
3808 checkFor(t, time.Second, 15*time.Millisecond, func() error {
3809 acc := r2.GlobalAccount()
3810 if n := acc.Interest("foo"); n != 0 {
3811 return fmt.Errorf("Still interest on subject: %v", n)
3812 }
3813 return nil
3814 })
3815 }
3816
3817 func TestLeafNodeNoPingBeforeConnect(t *testing.T) {
3818 o := DefaultOptions()
3819 o.LeafNode.Port = -1
3820 o.LeafNode.AuthTimeout = 0.5
3821 // For this test we need to disable compression, because we do use
3822 // the ping timer instead of the auth timer before the negotiation
3823 // is complete.
3824 o.LeafNode.Compression.Mode = CompressionOff
3825 s := RunServer(o)
3826 defer s.Shutdown()
3827
3828 addr := fmt.Sprintf("127.0.0.1:%d", o.LeafNode.Port)
3829 c, err := net.Dial("tcp", addr)
3830 if err != nil {
3831 t.Fatalf("Error on dial: %v", err)
3832 }
3833 defer c.Close()
3834
3835 // Read the info
3836 br := bufio.NewReader(c)
3837 c.SetReadDeadline(time.Now().Add(time.Second))
3838 l, _, err := br.ReadLine()
3839 if err != nil {
3840 t.Fatalf("Error on read: %v", err)
3841 }
3842 if !strings.HasPrefix(string(l), "INFO") {
3843 t.Fatalf("Wrong proto: %q", l)
3844 }
3845
3846 var leaf *client
3847 checkFor(t, time.Second, 15*time.Millisecond, func() error {
3848 s.grMu.Lock()
3849 for _, l := range s.grTmpClients {
3850 leaf = l
3851 break
3852 }
3853 s.grMu.Unlock()
3854 if leaf == nil {
3855 return fmt.Errorf("No leaf connection found")
3856 }
3857 return nil
3858 })
3859
3860 // Make sure that ping timer is not set
3861 leaf.mu.Lock()
3862 ptmrSet := leaf.ping.tmr != nil
3863 leaf.mu.Unlock()
3864
3865 if ptmrSet {
3866 t.Fatal("Ping timer was set before CONNECT was processed")
3867 }
3868
3869 // Send CONNECT
3870 if _, err := c.Write([]byte("CONNECT {}\r\n")); err != nil {
3871 t.Fatalf("Error writing connect: %v", err)
3872 }
3873
3874 // Check that we correctly set the timer now
3875 checkFor(t, time.Second, 15*time.Millisecond, func() error {
3876 leaf.mu.Lock()
3877 ptmrSet := leaf.ping.tmr != nil
3878 leaf.mu.Unlock()
3879 if !ptmrSet {
3880 return fmt.Errorf("Timer still not set")
3881 }
3882 return nil
3883 })
3884
3885 // Reduce the first ping..
3886 leaf.mu.Lock()
3887 leaf.ping.tmr.Reset(15 * time.Millisecond)
3888 leaf.mu.Unlock()
3889
3890 // Now consume that PING (we may get LS+, etc..)
3891 for {
3892 c.SetReadDeadline(time.Now().Add(time.Second))
3893 l, _, err = br.ReadLine()
3894 if err != nil {
3895 t.Fatalf("Error on read: %v", err)
3896 }
3897 if strings.HasPrefix(string(l), "PING") {
3898 checkLeafNodeConnected(t, s)
3899 return
3900 }
3901 }
3902 }
3903
3904 func TestLeafNodeNoMsgLoop(t *testing.T) {
3905 hubConf := `
3906 listen: "127.0.0.1:-1"
3907 accounts {
3908 FOO {
3909 users [
3910 {username: leaf, password: pass}
3911 {username: user, password: pass}
3912 ]
3913 }
3914 }
3915 cluster {
3916 name: "hub"
3917 listen: "127.0.0.1:-1"
3918 %s
3919 }
3920 leafnodes {
3921 listen: "127.0.0.1:-1"
3922 authorization {
3923 account: FOO
3924 }
3925 }
3926 `
3927 configS1 := createConfFile(t, []byte(fmt.Sprintf(hubConf, "")))
3928 s1, o1 := RunServerWithConfig(configS1)
3929 defer s1.Shutdown()
3930
3931 configS2S3 := createConfFile(t, []byte(fmt.Sprintf(hubConf, fmt.Sprintf(`routes: ["nats://127.0.0.1:%d"]`, o1.Cluster.Port))))
3932 s2, o2 := RunServerWithConfig(configS2S3)
3933 defer s2.Shutdown()
3934
3935 s3, _ := RunServerWithConfig(configS2S3)
3936 defer s3.Shutdown()
3937
3938 checkClusterFormed(t, s1, s2, s3)
3939
3940 contentLN := `
3941 listen: "127.0.0.1:%d"
3942 accounts {
3943 FOO {
3944 users [
3945 {username: leaf, password: pass}
3946 {username: user, password: pass}
3947 ]
3948 }
3949 }
3950 leafnodes {
3951 remotes = [
3952 {
3953 url: "nats://leaf:[email protected]:%d"
3954 account: FOO
3955 }
3956 ]
3957 }
3958 `
3959 lnconf := createConfFile(t, []byte(fmt.Sprintf(contentLN, -1, o1.LeafNode.Port)))
3960 sl1, slo1 := RunServerWithConfig(lnconf)
3961 defer sl1.Shutdown()
3962
3963 sl2, slo2 := RunServerWithConfig(lnconf)
3964 defer sl2.Shutdown()
3965
3966 checkLeafNodeConnected(t, sl1)
3967 checkLeafNodeConnected(t, sl2)
3968
3969 // Create users on each leafnode
3970 nc1, err := nats.Connect(fmt.Sprintf("nats://user:[email protected]:%d", slo1.Port))
3971 if err != nil {
3972 t.Fatalf("Error on connect: %v", err)
3973 }
3974 defer nc1.Close()
3975
3976 rch := make(chan struct{}, 1)
3977 nc2, err := nats.Connect(
3978 fmt.Sprintf("nats://user:[email protected]:%d", slo2.Port),
3979 nats.ReconnectWait(50*time.Millisecond),
3980 nats.ReconnectHandler(func(_ *nats.Conn) {
3981 rch <- struct{}{}
3982 }),
3983 )
3984 if err != nil {
3985 t.Fatalf("Error on connect: %v", err)
3986 }
3987 defer nc2.Close()
3988
3989 // Create queue subs on sl2
3990 nc2.QueueSubscribe("foo", "bar", func(_ *nats.Msg) {})
3991 nc2.QueueSubscribe("foo", "bar", func(_ *nats.Msg) {})
3992 nc2.Flush()
3993
3994 // Wait for interest to propagate to sl1
3995 checkSubInterest(t, sl1, "FOO", "foo", 250*time.Millisecond)
3996
3997 // Create sub on sl1
3998 ch := make(chan *nats.Msg, 10)
3999 nc1.Subscribe("foo", func(m *nats.Msg) {
4000 select {
4001 case ch <- m:
4002 default:
4003 }
4004 })
4005 nc1.Flush()
4006
4007 checkSubInterest(t, sl2, "FOO", "foo", 250*time.Millisecond)
4008
4009 // Produce from sl1
4010 nc1.Publish("foo", []byte("msg1"))
4011
4012 // Check message is received by plain sub
4013 select {
4014 case <-ch:
4015 case <-time.After(time.Second):
4016 t.Fatalf("Did not receive message")
4017 }
4018
4019 // Restart leaf node, this time make sure we connect to 2nd server.
4020 sl2.Shutdown()
4021
4022 // Use config file but this time reuse the client port and set the 2nd server for
4023 // the remote leaf node port.
4024 lnconf = createConfFile(t, []byte(fmt.Sprintf(contentLN, slo2.Port, o2.LeafNode.Port)))
4025 sl2, _ = RunServerWithConfig(lnconf)
4026 defer sl2.Shutdown()
4027
4028 checkLeafNodeConnected(t, sl2)
4029
4030 // Wait for client to reconnect
4031 select {
4032 case <-rch:
4033 case <-time.After(time.Second):
4034 t.Fatalf("Did not reconnect")
4035 }
4036
4037 // Produce a new messages
4038 for i := 0; i < 10; i++ {
4039 nc1.Publish("foo", []byte(fmt.Sprintf("msg%d", 2+i)))
4040
4041 // Check sub receives 1 message
4042 select {
4043 case <-ch:
4044 case <-time.After(time.Second):
4045 t.Fatalf("Did not receive message")
4046 }
4047 // Check that there is no more...
4048 select {
4049 case m := <-ch:
4050 t.Fatalf("Loop: received second message %s", m.Data)
4051 case <-time.After(50 * time.Millisecond):
4052 // OK
4053 }
4054 }
4055 }
4056
4057 func TestLeafNodeInterestPropagationDaisychain(t *testing.T) {
4058 aTmpl := `
4059 port: %d
4060 leafnodes {
4061 port: %d
4062 }
4063 `
4064
4065 confA := createConfFile(t, []byte(fmt.Sprintf(aTmpl, -1, -1)))
4066 sA, _ := RunServerWithConfig(confA)
4067 defer sA.Shutdown()
4068
4069 aPort := sA.opts.Port
4070 aLeafPort := sA.opts.LeafNode.Port
4071
4072 confB := createConfFile(t, []byte(fmt.Sprintf(`
4073 port: -1
4074 leafnodes {
4075 port: -1
4076 remotes = [{
4077 url:"nats://127.0.0.1:%d"
4078 }]
4079 }`, aLeafPort)))
4080 sB, _ := RunServerWithConfig(confB)
4081 defer sB.Shutdown()
4082
4083 confC := createConfFile(t, []byte(fmt.Sprintf(`
4084 port: -1
4085 leafnodes {
4086 port: -1
4087 remotes = [{url:"nats://127.0.0.1:%d"}]
4088 }`, sB.opts.LeafNode.Port)))
4089 sC, _ := RunServerWithConfig(confC)
4090 defer sC.Shutdown()
4091
4092 checkLeafNodeConnectedCount(t, sC, 1)
4093 checkLeafNodeConnectedCount(t, sB, 2)
4094 checkLeafNodeConnectedCount(t, sA, 1)
4095
4096 ncC := natsConnect(t, sC.ClientURL())
4097 defer ncC.Close()
4098 _, err := ncC.SubscribeSync("foo")
4099 require_NoError(t, err)
4100 require_NoError(t, ncC.Flush())
4101
4102 checkSubInterest(t, sC, "$G", "foo", time.Second)
4103 checkSubInterest(t, sB, "$G", "foo", time.Second)
4104 checkSubInterest(t, sA, "$G", "foo", time.Second)
4105
4106 ncA := natsConnect(t, sA.ClientURL())
4107 defer ncA.Close()
4108
4109 sA.Shutdown()
4110 sA.WaitForShutdown()
4111
4112 confAA := createConfFile(t, []byte(fmt.Sprintf(aTmpl, aPort, aLeafPort)))
4113 sAA, _ := RunServerWithConfig(confAA)
4114 defer sAA.Shutdown()
4115
4116 checkLeafNodeConnectedCount(t, sAA, 1)
4117 checkLeafNodeConnectedCount(t, sB, 2)
4118 checkLeafNodeConnectedCount(t, sC, 1)
4119
4120 checkSubInterest(t, sC, "$G", "foo", time.Second)
4121 checkSubInterest(t, sB, "$G", "foo", time.Second)
4122 checkSubInterest(t, sAA, "$G", "foo", time.Second) // failure issue 2448
4123 }
4124
4125 func TestLeafNodeQueueGroupDistribution(t *testing.T) {
4126 hc := createClusterWithName(t, "HUB", 3)
4127 defer hc.shutdown()
4128
4129 // Now have a cluster of leafnodes with each one connecting to corresponding HUB(n) node.
4130 c1 := `
4131 server_name: LEAF1
4132 listen: 127.0.0.1:-1
4133 cluster { name: ln22, listen: 127.0.0.1:-1 }
4134 leafnodes { remotes = [{ url: nats-leaf://127.0.0.1:%d }] }
4135 `
4136 lconf1 := createConfFile(t, []byte(fmt.Sprintf(c1, hc.opts[0].LeafNode.Port)))
4137 ln1, lopts1 := RunServerWithConfig(lconf1)
4138 defer ln1.Shutdown()
4139
4140 c2 := `
4141 server_name: LEAF2
4142 listen: 127.0.0.1:-1
4143 cluster { name: ln22, listen: 127.0.0.1:-1, routes = [ nats-route://127.0.0.1:%d] }
4144 leafnodes { remotes = [{ url: nats-leaf://127.0.0.1:%d }] }
4145 `
4146 lconf2 := createConfFile(t, []byte(fmt.Sprintf(c2, lopts1.Cluster.Port, hc.opts[1].LeafNode.Port)))
4147 ln2, _ := RunServerWithConfig(lconf2)
4148 defer ln2.Shutdown()
4149
4150 c3 := `
4151 server_name: LEAF3
4152 listen: 127.0.0.1:-1
4153 cluster { name: ln22, listen: 127.0.0.1:-1, routes = [ nats-route://127.0.0.1:%d] }
4154 leafnodes { remotes = [{ url: nats-leaf://127.0.0.1:%d }] }
4155 `
4156 lconf3 := createConfFile(t, []byte(fmt.Sprintf(c3, lopts1.Cluster.Port, hc.opts[2].LeafNode.Port)))
4157 ln3, _ := RunServerWithConfig(lconf3)
4158 defer ln3.Shutdown()
4159
4160 // Check leaf cluster is formed and all connected to the HUB.
4161 lnServers := []*Server{ln1, ln2, ln3}
4162 checkClusterFormed(t, lnServers...)
4163 for _, s := range lnServers {
4164 checkLeafNodeConnected(t, s)
4165 }
4166 // Check each node in the hub has 1 connection from the leaf cluster.
4167 for i := 0; i < 3; i++ {
4168 checkLeafNodeConnectedCount(t, hc.servers[i], 1)
4169 }
4170
4171 // Create a client and qsub on LEAF1 and LEAF2.
4172 nc1 := natsConnect(t, ln1.ClientURL())
4173 defer nc1.Close()
4174 var qsub1Count atomic.Int32
4175 natsQueueSub(t, nc1, "foo", "queue1", func(_ *nats.Msg) {
4176 qsub1Count.Add(1)
4177 })
4178 natsFlush(t, nc1)
4179
4180 nc2 := natsConnect(t, ln2.ClientURL())
4181 defer nc2.Close()
4182 var qsub2Count atomic.Int32
4183 natsQueueSub(t, nc2, "foo", "queue1", func(_ *nats.Msg) {
4184 qsub2Count.Add(1)
4185 })
4186 natsFlush(t, nc2)
4187
4188 // Make sure that the propagation interest is done before sending.
4189 for _, s := range hc.servers {
4190 gacc := s.GlobalAccount()
4191 checkFor(t, time.Second, 15*time.Millisecond, func() error {
4192 if n := gacc.Interest("foo"); n != 2 {
4193 return fmt.Errorf("Expected interest for %q to be 2, got %v", "foo", n)
4194 }
4195 return nil
4196 })
4197 }
4198
4199 sendAndCheck := func(idx int) {
4200 t.Helper()
4201 nchub := natsConnect(t, hc.servers[idx].ClientURL())
4202 defer nchub.Close()
4203 total := 1000
4204 for i := 0; i < total; i++ {
4205 natsPub(t, nchub, "foo", []byte("from hub"))
4206 }
4207 checkFor(t, time.Second, 15*time.Millisecond, func() error {
4208 if trecv := int(qsub1Count.Load() + qsub2Count.Load()); trecv != total {
4209 return fmt.Errorf("Expected %v messages, got %v", total, trecv)
4210 }
4211 return nil
4212 })
4213 // Now that we have made sure that all messages were received,
4214 // check that qsub1 and qsub2 are getting at least some.
4215 if n := int(qsub1Count.Load()); n <= total/10 {
4216 t.Fatalf("Expected qsub1 to get some messages, but got %v", n)
4217 }
4218 if n := int(qsub2Count.Load()); n <= total/10 {
4219 t.Fatalf("Expected qsub2 to get some messages, but got %v", n)
4220 }
4221 // Reset the counters.
4222 qsub1Count.Store(0)
4223 qsub2Count.Store(0)
4224 }
4225 // Send from HUB1
4226 sendAndCheck(0)
4227 // Send from HUB2
4228 sendAndCheck(1)
4229 // Send from HUB3
4230 sendAndCheck(2)
4231 }
4232
4233 func TestLeafNodeQueueGroupDistributionVariant(t *testing.T) {
4234 hc := createClusterWithName(t, "HUB", 3)
4235 defer hc.shutdown()
4236
4237 // Now have a cluster of leafnodes with LEAF1 and LEAF2 connecting to HUB1.
4238 c1 := `
4239 server_name: LEAF1
4240 listen: 127.0.0.1:-1
4241 cluster { name: ln22, listen: 127.0.0.1:-1 }
4242 leafnodes { remotes = [{ url: nats-leaf://127.0.0.1:%d }] }
4243 `
4244 lconf1 := createConfFile(t, []byte(fmt.Sprintf(c1, hc.opts[0].LeafNode.Port)))
4245 ln1, lopts1 := RunServerWithConfig(lconf1)
4246 defer ln1.Shutdown()
4247
4248 c2 := `
4249 server_name: LEAF2
4250 listen: 127.0.0.1:-1
4251 cluster { name: ln22, listen: 127.0.0.1:-1, routes = [ nats-route://127.0.0.1:%d] }
4252 leafnodes { remotes = [{ url: nats-leaf://127.0.0.1:%d }] }
4253 `
4254 lconf2 := createConfFile(t, []byte(fmt.Sprintf(c2, lopts1.Cluster.Port, hc.opts[0].LeafNode.Port)))
4255 ln2, _ := RunServerWithConfig(lconf2)
4256 defer ln2.Shutdown()
4257
4258 // And LEAF3 to HUB3
4259 c3 := `
4260 server_name: LEAF3
4261 listen: 127.0.0.1:-1
4262 cluster { name: ln22, listen: 127.0.0.1:-1, routes = [ nats-route://127.0.0.1:%d] }
4263 leafnodes { remotes = [{ url: nats-leaf://127.0.0.1:%d }] }
4264 `
4265 lconf3 := createConfFile(t, []byte(fmt.Sprintf(c3, lopts1.Cluster.Port, hc.opts[2].LeafNode.Port)))
4266 ln3, _ := RunServerWithConfig(lconf3)
4267 defer ln3.Shutdown()
4268
4269 // Check leaf cluster is formed and all connected to the HUB.
4270 lnServers := []*Server{ln1, ln2, ln3}
4271 checkClusterFormed(t, lnServers...)
4272 for _, s := range lnServers {
4273 checkLeafNodeConnected(t, s)
4274 }
4275 // Check that HUB1 has 2 leaf connections, HUB2 has 0 and HUB3 has 1.
4276 checkLeafNodeConnectedCount(t, hc.servers[0], 2)
4277 checkLeafNodeConnectedCount(t, hc.servers[1], 0)
4278 checkLeafNodeConnectedCount(t, hc.servers[2], 1)
4279
4280 // Create a client and qsub on LEAF1 and LEAF2.
4281 nc1 := natsConnect(t, ln1.ClientURL())
4282 defer nc1.Close()
4283 var qsub1Count atomic.Int32
4284 natsQueueSub(t, nc1, "foo", "queue1", func(_ *nats.Msg) {
4285 qsub1Count.Add(1)
4286 })
4287 natsFlush(t, nc1)
4288
4289 nc2 := natsConnect(t, ln2.ClientURL())
4290 defer nc2.Close()
4291 var qsub2Count atomic.Int32
4292 natsQueueSub(t, nc2, "foo", "queue1", func(_ *nats.Msg) {
4293 qsub2Count.Add(1)
4294 })
4295 natsFlush(t, nc2)
4296
4297 // Make sure that the propagation interest is done before sending.
4298 for i, s := range hc.servers {
4299 gacc := s.GlobalAccount()
4300 var ei int
4301 switch i {
4302 case 0:
4303 ei = 2
4304 default:
4305 ei = 1
4306 }
4307 checkFor(t, time.Second, 15*time.Millisecond, func() error {
4308 if n := gacc.Interest("foo"); n != ei {
4309 return fmt.Errorf("Expected interest for %q to be %d, got %v", "foo", ei, n)
4310 }
4311 return nil
4312 })
4313 }
4314
4315 sendAndCheck := func(idx int) {
4316 t.Helper()
4317 nchub := natsConnect(t, hc.servers[idx].ClientURL())
4318 defer nchub.Close()
4319 total := 1000
4320 for i := 0; i < total; i++ {
4321 natsPub(t, nchub, "foo", []byte("from hub"))
4322 }
4323 checkFor(t, time.Second, 15*time.Millisecond, func() error {
4324 if trecv := int(qsub1Count.Load() + qsub2Count.Load()); trecv != total {
4325 return fmt.Errorf("Expected %v messages, got %v", total, trecv)
4326 }
4327 return nil
4328 })
4329 // Now that we have made sure that all messages were received,
4330 // check that qsub1 and qsub2 are getting at least some.
4331 if n := int(qsub1Count.Load()); n <= total/10 {
4332 t.Fatalf("Expected qsub1 to get some messages, but got %v (qsub2=%v)", n, qsub2Count.Load())
4333 }
4334 if n := int(qsub2Count.Load()); n <= total/10 {
4335 t.Fatalf("Expected qsub2 to get some messages, but got %v (qsub1=%v)", n, qsub1Count.Load())
4336 }
4337 // Reset the counters.
4338 qsub1Count.Store(0)
4339 qsub2Count.Store(0)
4340 }
4341 // Send from HUB1
4342 sendAndCheck(0)
4343 // Send from HUB2
4344 sendAndCheck(1)
4345 // Send from HUB3
4346 sendAndCheck(2)
4347 }
4348
4349 func TestLeafNodeQueueGroupDistributionWithDaisyChainAndGateway(t *testing.T) {
4350 SetGatewaysSolicitDelay(0)
4351 defer ResetGatewaysSolicitDelay()
4352
4353 // We create a sort of a ladder of servers with connections that look like this:
4354 //
4355 // D1 <--- route ---> D2
4356 // | |
4357 // GW GW
4358 // | |
4359 // C1 <--- route ---> C2
4360 // | |
4361 // Leaf Leaf
4362 // | |
4363 // B1 <--- route ---> B2
4364 // | |
4365 // Leaf Leaf
4366 // | |
4367 // A1 <--- route ---> A2
4368 //
4369 // We will then place queue subscriptions (different sub-tests) on A1, A2
4370 // B1, B2, D1 and D2.
4371
4372 accs := `
4373 accounts {
4374 SYS: {users: [{user:sys, password: pwd}]}
4375 USER: {users: [{user:user, password: pwd}]}
4376 }
4377 system_account: SYS
4378 `
4379 dConf := `
4380 %s
4381 server_name: %s
4382 port: -1
4383 cluster {
4384 name: "D"
4385 port: -1
4386 %s
4387 }
4388 gateway {
4389 name: "D"
4390 port: -1
4391 }
4392 `
4393 d1Conf := createConfFile(t, []byte(fmt.Sprintf(dConf, accs, "GW1", _EMPTY_)))
4394 d1, d1Opts := RunServerWithConfig(d1Conf)
4395 defer d1.Shutdown()
4396
4397 d2Conf := createConfFile(t, []byte(fmt.Sprintf(dConf, accs, "GW2",
4398 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", d1Opts.Cluster.Port))))
4399 d2, d2Opts := RunServerWithConfig(d2Conf)
4400 defer d2.Shutdown()
4401
4402 checkClusterFormed(t, d1, d2)
4403
4404 leafCConf := `
4405 %s
4406 server_name: %s
4407 port: -1
4408 cluster {
4409 name: C
4410 port: -1
4411 %s
4412 }
4413 leafnodes {
4414 port: -1
4415 }
4416 gateway {
4417 name: C
4418 port: -1
4419 gateways [
4420 {
4421 name: D
4422 url: "nats://127.0.0.1:%d"
4423 }
4424 ]
4425 }
4426 `
4427 c1Conf := createConfFile(t, []byte(fmt.Sprintf(leafCConf, accs, "C1", _EMPTY_, d1Opts.Gateway.Port)))
4428 c1, c1Opts := RunServerWithConfig(c1Conf)
4429 defer c1.Shutdown()
4430
4431 waitForOutboundGateways(t, c1, 1, time.Second)
4432 waitForInboundGateways(t, d1, 1, time.Second)
4433
4434 c2Conf := createConfFile(t, []byte(fmt.Sprintf(leafCConf, accs, "C2",
4435 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", c1Opts.Cluster.Port), d2Opts.Gateway.Port)))
4436 c2, c2Opts := RunServerWithConfig(c2Conf)
4437 defer c2.Shutdown()
4438
4439 waitForOutboundGateways(t, c2, 1, time.Second)
4440 waitForInboundGateways(t, d2, 1, time.Second)
4441
4442 checkClusterFormed(t, c1, c2)
4443
4444 leafABConf := `
4445 %s
4446 server_name: %s
4447 port: -1
4448 cluster {
4449 name: %s
4450 port: -1
4451 %s
4452 }
4453 leafnodes {
4454 port: -1
4455 remotes [
4456 {
4457 url: "nats://user:[email protected]:%d"
4458 account: USER
4459 }
4460 ]
4461 }
4462 `
4463 b1Conf := createConfFile(t, []byte(fmt.Sprintf(leafABConf, accs, "B1", "B", _EMPTY_, c1Opts.LeafNode.Port)))
4464 b1, b1Opts := RunServerWithConfig(b1Conf)
4465 defer b1.Shutdown()
4466
4467 checkLeafNodeConnected(t, b1)
4468 checkLeafNodeConnected(t, c1)
4469
4470 b2Conf := createConfFile(t, []byte(fmt.Sprintf(leafABConf, accs, "B2", "B",
4471 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", b1Opts.Cluster.Port), c2Opts.LeafNode.Port)))
4472 b2, b2Opts := RunServerWithConfig(b2Conf)
4473 defer b2.Shutdown()
4474
4475 checkLeafNodeConnected(t, b2)
4476 checkLeafNodeConnected(t, c2)
4477 checkClusterFormed(t, b1, b2)
4478
4479 a1Conf := createConfFile(t, []byte(fmt.Sprintf(leafABConf, accs, "A1", "A", _EMPTY_, b1Opts.LeafNode.Port)))
4480 a1, a1Opts := RunServerWithConfig(a1Conf)
4481 defer a1.Shutdown()
4482
4483 checkLeafNodeConnectedCount(t, b1, 2)
4484 checkLeafNodeConnected(t, a1)
4485
4486 a2Conf := createConfFile(t, []byte(fmt.Sprintf(leafABConf, accs, "A2", "A",
4487 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", a1Opts.Cluster.Port), b2Opts.LeafNode.Port)))
4488 a2, _ := RunServerWithConfig(a2Conf)
4489 defer a2.Shutdown()
4490
4491 checkLeafNodeConnectedCount(t, b2, 2)
4492 checkLeafNodeConnected(t, a2)
4493 checkClusterFormed(t, a1, a2)
4494
4495 // Create our client connections to all servers where we may need to have
4496 // queue subscriptions.
4497 ncD1 := natsConnect(t, d1.ClientURL(), nats.UserInfo("user", "pwd"))
4498 defer ncD1.Close()
4499 ncD2 := natsConnect(t, d2.ClientURL(), nats.UserInfo("user", "pwd"))
4500 defer ncD2.Close()
4501 ncB1 := natsConnect(t, b1.ClientURL(), nats.UserInfo("user", "pwd"))
4502 defer ncB1.Close()
4503 ncB2 := natsConnect(t, b2.ClientURL(), nats.UserInfo("user", "pwd"))
4504 defer ncB2.Close()
4505 ncA1 := natsConnect(t, a1.ClientURL(), nats.UserInfo("user", "pwd"))
4506 defer ncA1.Close()
4507 ncA2 := natsConnect(t, a2.ClientURL(), nats.UserInfo("user", "pwd"))
4508 defer ncA2.Close()
4509
4510 // Helper to check that the interest is propagated to all servers
4511 checkInterest := func(t *testing.T, subj string) {
4512 t.Helper()
4513 for _, s := range []*Server{a1, a2, b1, b2, c1, c2, d1, d2} {
4514 acc, err := s.LookupAccount("USER")
4515 require_NoError(t, err)
4516 checkFor(t, time.Second, 10*time.Millisecond, func() error {
4517 if acc.Interest(subj) != 0 {
4518 return nil
4519 }
4520 return fmt.Errorf("Still no interest on %q in server %q", subj, s)
4521 })
4522 }
4523 }
4524
4525 // Helper to send messages on given subject. We are always sending
4526 // from cluster B in this test, but we pick randomly between B1 and B2.
4527 total := 1000
4528 send := func(t *testing.T, subj string) {
4529 for i := 0; i < total; i++ {
4530 var nc *nats.Conn
4531 if fastrand.Uint32n(2) == 0 {
4532 nc = ncB1
4533 } else {
4534 nc = ncB2
4535 }
4536 natsPub(t, nc, subj, []byte(fmt.Sprintf("msg_%d", i+1)))
4537 }
4538 }
4539
4540 const queue = "queue"
4541
4542 for i, test := range []struct {
4543 name string
4544 a1 bool
4545 a2 bool
4546 b1 bool
4547 b2 bool
4548 d1 bool
4549 d2 bool
4550 }{
4551 // Cases with QSubs in A, B and D
4552 {"A1 __ B1 __ D1 __", true, false, true, false, true, false},
4553 {"A1 __ B1 __ __ D2", true, false, true, false, false, true},
4554 {"A1 __ B1 __ D1 D2", true, false, true, false, true, true},
4555
4556 {"A1 __ __ B2 D1 __", true, false, false, true, true, false},
4557 {"A1 __ __ B2 __ D2", true, false, false, true, false, true},
4558 {"A1 __ __ B2 D1 D2", true, false, false, true, true, true},
4559
4560 {"A1 __ B1 B2 D1 __", true, false, true, true, true, false},
4561 {"A1 __ B1 B2 __ D2", true, false, true, true, false, true},
4562 {"A1 __ B1 B2 D1 D2", true, false, true, true, true, true},
4563
4564 {"__ A2 B1 __ D1 __", false, true, true, false, true, false},
4565 {"__ A2 B1 __ __ D2", false, true, true, false, false, true},
4566 {"__ A2 B1 __ D1 D2", false, true, true, false, true, true},
4567
4568 {"__ A2 __ B2 D1 __", false, true, false, true, true, false},
4569 {"__ A2 __ B2 __ D2", false, true, false, true, false, true},
4570 {"__ A2 __ B2 D1 D2", false, true, false, true, true, true},
4571
4572 {"__ A2 B1 B2 D1 __", false, true, true, true, true, false},
4573 {"__ A2 B1 B2 __ D2", false, true, true, true, false, true},
4574 {"__ A2 B1 B2 D1 D2", false, true, true, true, true, true},
4575
4576 {"A1 A2 B1 __ D1 __", true, true, true, false, true, false},
4577 {"A1 A2 B1 __ __ D2", true, true, true, false, false, true},
4578 {"A1 A2 B1 __ D1 D2", true, true, true, false, true, true},
4579
4580 {"A1 A2 __ B2 D1 __", true, true, false, true, true, false},
4581 {"A1 A2 __ B2 __ D2", true, true, false, true, false, true},
4582 {"A1 A2 __ B2 D1 D2", true, true, false, true, true, true},
4583
4584 {"A1 A2 B1 B2 D1 __", true, true, true, true, true, false},
4585 {"A1 A2 B1 B2 __ D2", true, true, true, true, false, true},
4586 {"A1 A2 B1 B2 D1 D2", true, true, true, true, true, true},
4587
4588 // Now without any QSub in B cluster (so just A and D)
4589 {"A1 __ __ __ D1 __", true, false, false, false, true, false},
4590 {"A1 __ __ __ __ D2", true, false, false, false, false, true},
4591 {"A1 __ __ __ D1 D2", true, false, false, false, true, true},
4592
4593 {"__ A2 __ __ D1 __", false, true, false, false, true, false},
4594 {"__ A2 __ __ __ D2", false, true, false, false, false, true},
4595 {"__ A2 __ __ D1 D2", false, true, false, false, true, true},
4596
4597 {"A1 A2 __ __ D1 __", true, true, false, false, true, false},
4598 {"A1 A2 __ __ __ D2", true, true, false, false, false, true},
4599 {"A1 A2 __ __ D1 D2", true, true, false, false, true, true},
4600 } {
4601 t.Run(test.name, func(t *testing.T) {
4602 subj := fmt.Sprintf("foo.%d", i+1)
4603 var aCount, bCount, dCount atomic.Int32
4604 if test.a1 {
4605 qsA1 := natsQueueSub(t, ncA1, subj, queue, func(_ *nats.Msg) {
4606 aCount.Add(1)
4607 })
4608 defer qsA1.Unsubscribe()
4609 }
4610 if test.a2 {
4611 qsA2 := natsQueueSub(t, ncA2, subj, queue, func(_ *nats.Msg) {
4612 aCount.Add(1)
4613 })
4614 defer qsA2.Unsubscribe()
4615 }
4616 if test.b1 {
4617 qsB1 := natsQueueSub(t, ncB1, subj, queue, func(_ *nats.Msg) {
4618 bCount.Add(1)
4619 })
4620 defer qsB1.Unsubscribe()
4621 }
4622 if test.b2 {
4623 qsB2 := natsQueueSub(t, ncB2, subj, queue, func(_ *nats.Msg) {
4624 bCount.Add(1)
4625 })
4626 defer qsB2.Unsubscribe()
4627 }
4628 if test.d1 {
4629 qsD1 := natsQueueSub(t, ncD1, subj, queue, func(_ *nats.Msg) {
4630 dCount.Add(1)
4631 })
4632 defer qsD1.Unsubscribe()
4633 }
4634 if test.d2 {
4635 qsD2 := natsQueueSub(t, ncD2, subj, queue, func(_ *nats.Msg) {
4636 dCount.Add(1)
4637 })
4638 defer qsD2.Unsubscribe()
4639 }
4640 checkInterest(t, subj)
4641
4642 // Now send messages
4643 send(t, subj)
4644
4645 // Check that appropriate queue subs receive all messages.
4646 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
4647 n := aCount.Load() + bCount.Load() + dCount.Load()
4648 if n == int32(total) {
4649 return nil
4650 }
4651 return fmt.Errorf("Got only %v/%v messages (a=%v b=%v d=%v)", n, total, aCount.Load(), bCount.Load(), dCount.Load())
4652 })
4653 // When there is (are) qsub(s) on b, then only B should
4654 // get the messages. Otherwise, it should be between A and D
4655 if test.b1 || test.b2 {
4656 require_Equal(t, aCount.Load(), 0)
4657 require_Equal(t, dCount.Load(), 0)
4658 } else {
4659 require_Equal(t, bCount.Load(), 0)
4660 // We should have receive some on A and D
4661 require_True(t, aCount.Load() > 0)
4662 require_True(t, dCount.Load() > 0)
4663 }
4664 })
4665 }
4666 }
4667
4668 func TestLeafNodeAndGatewaysSingleMsgPerQueueGroup(t *testing.T) {
4669 SetGatewaysSolicitDelay(0)
4670 defer ResetGatewaysSolicitDelay()
4671
4672 accs := `
4673 accounts {
4674 SYS: {users: [{user:sys, password: pwd}]}
4675 USER: {users: [{user:user, password: pwd}]}
4676 }
4677 system_account: SYS
4678 `
4679 gwUSConfTmpl := `
4680 %s
4681 server_name: GW_US
4682 listen: "127.0.0.1:-1"
4683 gateway {
4684 name: US
4685 listen: "127.0.0.1:-1"
4686 }
4687 leafnodes {
4688 listen: "127.0.0.1:-1"
4689 }
4690 `
4691 gwUSConf := createConfFile(t, []byte(fmt.Sprintf(gwUSConfTmpl, accs)))
4692 gwUS, gwUSOpts := RunServerWithConfig(gwUSConf)
4693 defer gwUS.Shutdown()
4694
4695 gwEUConfTmpl := `
4696 %s
4697 server_name: GW_EU
4698 listen: "127.0.0.1:-1"
4699 gateway {
4700 name: EU
4701 listen: "127.0.0.1:-1"
4702 gateways [
4703 {
4704 name: US
4705 url: "nats://127.0.0.1:%d"
4706 }
4707 ]
4708 }
4709 leafnodes {
4710 listen: "127.0.0.1:-1"
4711 }
4712 `
4713 gwEUConf := createConfFile(t, []byte(fmt.Sprintf(gwEUConfTmpl, accs, gwUSOpts.Gateway.Port)))
4714 gwEU, gwEUOpts := RunServerWithConfig(gwEUConf)
4715 defer gwEU.Shutdown()
4716
4717 waitForOutboundGateways(t, gwUS, 1, time.Second)
4718 waitForOutboundGateways(t, gwEU, 1, time.Second)
4719 waitForInboundGateways(t, gwUS, 1, time.Second)
4720 waitForInboundGateways(t, gwEU, 1, time.Second)
4721
4722 leafConfTmpl := `
4723 %s
4724 server_name: %s
4725 listen: "127.0.0.1:-1"
4726 leafnodes {
4727 remotes [
4728 {
4729 url: "nats://user:[email protected]:%d"
4730 account: USER
4731 }
4732 ]
4733 }
4734 `
4735 leafUSConf := createConfFile(t, []byte(fmt.Sprintf(leafConfTmpl, accs, "LEAF_US", gwUSOpts.LeafNode.Port)))
4736 leafUS, _ := RunServerWithConfig(leafUSConf)
4737 defer leafUS.Shutdown()
4738 checkLeafNodeConnected(t, leafUS)
4739
4740 leafEUConf := createConfFile(t, []byte(fmt.Sprintf(leafConfTmpl, accs, "LEAF_EU", gwEUOpts.LeafNode.Port)))
4741 leafEU, _ := RunServerWithConfig(leafEUConf)
4742 defer leafEU.Shutdown()
4743 checkLeafNodeConnected(t, leafEU)
4744
4745 // Order is important! (see rest of test to understand why)
4746 var usLeafQ, usLeafPS, usGWQ, usGWPS, euGWQ, euGWPS, euLeafQ, euLeafPS, euLeafQBaz atomic.Int32
4747 counters := []*atomic.Int32{&usLeafQ, &usLeafPS, &usGWQ, &usGWPS, &euGWQ, &euGWPS, &euLeafQ, &euLeafPS, &euLeafQBaz}
4748 counterNames := []string{"usLeafQ", "usLeafPS", "usGWQ", "usGWPS", "euGWQ", "euGWPS", "euLeafQ", "euLeafPS", "euLeafQBaz"}
4749 if len(counters) != len(counterNames) {
4750 panic("Fix test!")
4751 }
4752 resetCounters := func() {
4753 for _, a := range counters {
4754 a.Store(0)
4755 }
4756 }
4757
4758 // This test will always produce from the US leaf.
4759 ncProd := natsConnect(t, leafUS.ClientURL(), nats.UserInfo("user", "pwd"))
4760 defer ncProd.Close()
4761
4762 total := int32(1)
4763 check := func(t *testing.T, expected []int32) {
4764 time.Sleep(50 * time.Millisecond)
4765 resetCounters()
4766 for i := 0; i < int(total); i++ {
4767 natsPub(t, ncProd, "foo.1", []byte("hello"))
4768 }
4769 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
4770 for i := 0; i < len(expected); i++ {
4771 if n := counters[i].Load(); n != expected[i] {
4772 return fmt.Errorf("Expected counter %q to be %v, got %v", counterNames[i], expected[i], n)
4773 }
4774 }
4775 return nil
4776 })
4777 }
4778
4779 // "usLeafQ", "usLeafPS", "usGWQ", "usGWPS", "euGWQ", "euGWPS", "euLeafQ", "euLeafPS", "euLeafQBaz"
4780 for _, test := range []struct {
4781 subs []int
4782 expected []int32
4783 }{
4784 // We will always have the qsub on leaf EU, and have some permutations
4785 // of queue and plain subs on other server(s) and check we get the
4786 // expected distribution.
4787
4788 // Simple test firs, qsubs on leaf US and leaf EU, all messages stay in leaf US.
4789 {
4790 []int{1, 0, 0, 0, 0, 0, 1, 0, 0},
4791 []int32{total, 0, 0, 0, 0, 0, 0, 0, 0},
4792 },
4793 // Move the queue sub from leaf US to GW US.
4794 {
4795 []int{0, 0, 1, 0, 0, 0, 1, 0, 0},
4796 []int32{0, 0, total, 0, 0, 0, 0, 0, 0},
4797 },
4798 // Now move it to GW EU.
4799 {
4800 []int{0, 0, 0, 0, 1, 0, 1, 0, 0},
4801 []int32{0, 0, 0, 0, total, 0, 0, 0, 0},
4802 },
4803
4804 // More combinations...
4805 {
4806 []int{1, 1, 0, 0, 0, 0, 1, 0, 0},
4807 []int32{total, total, 0, 0, 0, 0, 0, 0, 0},
4808 },
4809 {
4810 []int{0, 1, 1, 0, 0, 0, 1, 0, 0},
4811 []int32{0, total, total, 0, 0, 0, 0, 0, 0},
4812 },
4813 {
4814 []int{0, 1, 1, 1, 0, 0, 1, 0, 0},
4815 []int32{0, total, total, total, 0, 0, 0, 0, 0},
4816 },
4817 {
4818 []int{0, 1, 0, 1, 1, 0, 1, 0, 0},
4819 []int32{0, total, 0, total, total, 0, 0, 0, 0},
4820 },
4821 {
4822 []int{0, 1, 0, 1, 1, 1, 1, 0, 0},
4823 []int32{0, total, 0, total, total, total, 0, 0, 0},
4824 },
4825 // If we have the qsub in leaf US, does not matter if we have
4826 // qsubs in GW US and EU, only leaf US should receive the messages,
4827 // but plain sub in GW servers should get them too.
4828 {
4829 []int{1, 1, 1, 0, 0, 0, 1, 0, 0},
4830 []int32{total, total, 0, 0, 0, 0, 0, 0, 0},
4831 },
4832 {
4833 []int{1, 1, 1, 1, 0, 0, 1, 0, 0},
4834 []int32{total, total, 0, total, 0, 0, 0, 0, 0},
4835 },
4836 {
4837 []int{1, 1, 1, 1, 1, 0, 1, 0, 0},
4838 []int32{total, total, 0, total, 0, 0, 0, 0, 0},
4839 },
4840 {
4841 []int{1, 1, 1, 1, 1, 1, 1, 0, 0},
4842 []int32{total, total, 0, total, 0, total, 0, 0, 0},
4843 },
4844 // Now back to a qsub on leaf US and leaf EU, but introduce plain sub
4845 // interest in leaf EU
4846 {
4847 []int{1, 0, 0, 0, 0, 0, 1, 1, 0},
4848 []int32{total, 0, 0, 0, 0, 0, 0, total, 0},
4849 },
4850 // And add a different queue group in leaf EU and it should get the messages too.
4851 {
4852 []int{1, 0, 0, 0, 0, 0, 1, 1, 1},
4853 []int32{total, 0, 0, 0, 0, 0, 0, total, total},
4854 },
4855 // Keep plain and baz queue sub interests in leaf EU and add more combinations.
4856 {
4857 []int{1, 1, 0, 0, 0, 0, 1, 1, 1},
4858 []int32{total, total, 0, 0, 0, 0, 0, total, total},
4859 },
4860 {
4861 []int{1, 1, 1, 0, 0, 0, 1, 1, 1},
4862 []int32{total, total, 0, 0, 0, 0, 0, total, total},
4863 },
4864 {
4865 []int{1, 1, 1, 1, 0, 0, 1, 1, 1},
4866 []int32{total, total, 0, total, 0, 0, 0, total, total},
4867 },
4868 {
4869 []int{1, 1, 1, 1, 1, 0, 1, 1, 1},
4870 []int32{total, total, 0, total, 0, 0, 0, total, total},
4871 },
4872 {
4873 []int{1, 1, 1, 1, 1, 1, 1, 1, 1},
4874 []int32{total, total, 0, total, 0, total, 0, total, total},
4875 },
4876 } {
4877 t.Run(_EMPTY_, func(t *testing.T) {
4878 if len(test.subs) != len(counters) || len(test.expected) != len(counters) {
4879 panic("Fix test")
4880 }
4881
4882 ncUS := natsConnect(t, leafUS.ClientURL(), nats.UserInfo("user", "pwd"))
4883 defer ncUS.Close()
4884
4885 ncGWUS := natsConnect(t, gwUS.ClientURL(), nats.UserInfo("user", "pwd"))
4886 defer ncGWUS.Close()
4887
4888 ncGWEU := natsConnect(t, gwEU.ClientURL(), nats.UserInfo("user", "pwd"))
4889 defer ncGWEU.Close()
4890
4891 ncEU := natsConnect(t, leafEU.ClientURL(), nats.UserInfo("user", "pwd"))
4892 defer ncEU.Close()
4893
4894 if test.subs[0] > 0 {
4895 natsQueueSub(t, ncUS, "foo.*", "bar", func(_ *nats.Msg) {
4896 usLeafQ.Add(1)
4897 })
4898 }
4899 if test.subs[1] > 0 {
4900 natsSub(t, ncUS, "foo.>", func(_ *nats.Msg) {
4901 usLeafPS.Add(1)
4902 })
4903 }
4904 natsFlush(t, ncUS)
4905 if test.subs[2] > 0 {
4906 natsQueueSub(t, ncGWUS, "foo.*", "bar", func(_ *nats.Msg) {
4907 usGWQ.Add(1)
4908 })
4909 }
4910 if test.subs[3] > 0 {
4911 natsSub(t, ncGWUS, "foo.>", func(_ *nats.Msg) {
4912 usGWPS.Add(1)
4913 })
4914 }
4915 natsFlush(t, ncGWUS)
4916 if test.subs[4] > 0 {
4917 natsQueueSub(t, ncGWEU, "foo.*", "bar", func(_ *nats.Msg) {
4918 euGWQ.Add(1)
4919 })
4920 }
4921 if test.subs[5] > 0 {
4922 natsSub(t, ncGWEU, "foo.>", func(_ *nats.Msg) {
4923 euGWPS.Add(1)
4924 })
4925 }
4926 natsFlush(t, ncGWEU)
4927 if test.subs[6] > 0 {
4928 natsQueueSub(t, ncEU, "foo.*", "bar", func(_ *nats.Msg) {
4929 euLeafQ.Add(1)
4930 })
4931 }
4932 if test.subs[7] > 0 {
4933 natsSub(t, ncEU, "foo.>", func(_ *nats.Msg) {
4934 euLeafPS.Add(1)
4935 })
4936 }
4937 if test.subs[8] > 0 {
4938 // Create on different group, called "baz"
4939 natsQueueSub(t, ncEU, "foo.*", "baz", func(_ *nats.Msg) {
4940 euLeafQBaz.Add(1)
4941 })
4942 }
4943 natsFlush(t, ncEU)
4944
4945 // Check that we have what we expect.
4946 check(t, test.expected)
4947 })
4948 }
4949 }
4950
4951 func TestLeafNodeQueueGroupWeightCorrectOnConnectionCloseInSuperCluster(t *testing.T) {
4952 SetGatewaysSolicitDelay(0)
4953 defer ResetGatewaysSolicitDelay()
4954
4955 //
4956 // D
4957 // |
4958 // Leaf
4959 // |
4960 // v
4961 // C
4962 // ^ ^
4963 // / \
4964 // GW GW
4965 // / \
4966 // v \
4967 // B1 <--- route ---> B2 <----*----------*
4968 // ^ <---* | |
4969 // | | Leaf Leaf
4970 // Leaf *-- Leaf ---* | |
4971 // | | | |
4972 // A1 <--- route ---> A2 OTHER1 OTHER2
4973 //
4974
4975 accs := `
4976 accounts {
4977 SYS: {users: [{user:sys, password: pwd}]}
4978 USER: {users: [{user:user, password: pwd}]}
4979 }
4980 system_account: SYS
4981 `
4982 bConf := `
4983 %s
4984 server_name: %s
4985 listen: "127.0.0.1:-1"
4986 cluster {
4987 name: "B"
4988 listen: "127.0.0.1:-1"
4989 no_advertise: true
4990 %s
4991 }
4992 gateway {
4993 name: "B"
4994 listen: "127.0.0.1:-1"
4995 }
4996 leafnodes {
4997 listen: "127.0.0.1:-1"
4998 }
4999 `
5000 sb1Conf := createConfFile(t, []byte(fmt.Sprintf(bConf, accs, "B1", _EMPTY_)))
5001 sb1, sb1o := RunServerWithConfig(sb1Conf)
5002 defer sb1.Shutdown()
5003
5004 sb2Conf := createConfFile(t, []byte(fmt.Sprintf(bConf, accs, "B2",
5005 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", sb1o.Cluster.Port))))
5006 sb2, sb2o := RunServerWithConfig(sb2Conf)
5007 defer sb2.Shutdown()
5008
5009 checkClusterFormed(t, sb1, sb2)
5010
5011 cConf := `
5012 %s
5013 server_name: C
5014 listen: "127.0.0.1:-1"
5015 cluster {
5016 name: "C"
5017 listen: "127.0.0.1:-1"
5018 }
5019 gateway {
5020 name: "C"
5021 listen: "127.0.0.1:-1"
5022 gateways [
5023 {
5024 name: B
5025 url: "nats://127.0.0.1:%d"
5026 }
5027 ]
5028 }
5029 leafnodes {
5030 listen: "127.0.0.1:-1"
5031 }
5032 `
5033 scConf := createConfFile(t, []byte(fmt.Sprintf(cConf, accs, sb1o.Gateway.Port)))
5034 sc, sco := RunServerWithConfig(scConf)
5035 defer sc.Shutdown()
5036
5037 waitForOutboundGateways(t, sc, 1, 2*time.Second)
5038 waitForOutboundGateways(t, sb1, 1, 2*time.Second)
5039 waitForOutboundGateways(t, sb2, 1, 2*time.Second)
5040 waitForInboundGateways(t, sc, 2, 2*time.Second)
5041 waitForInboundGateways(t, sb1, 1, 2*time.Second)
5042
5043 dConf := `
5044 %s
5045 server_name: D
5046 listen: "127.0.0.1:-1"
5047 cluster {
5048 name: "D"
5049 listen: "127.0.0.1:-1"
5050 }
5051 leafnodes {
5052 remotes [
5053 {
5054 url: "nats://user:[email protected]:%d"
5055 account: USER
5056 }
5057 ]
5058 }
5059 `
5060 sdConf := createConfFile(t, []byte(fmt.Sprintf(dConf, accs, sco.LeafNode.Port)))
5061 sd, _ := RunServerWithConfig(sdConf)
5062 defer sd.Shutdown()
5063
5064 checkLeafNodeConnected(t, sc)
5065 checkLeafNodeConnected(t, sd)
5066
5067 aConf := `
5068 %s
5069 server_name: %s
5070 listen: "127.0.0.1:-1"
5071 cluster {
5072 name: A
5073 listen: "127.0.0.1:-1"
5074 no_advertise: true
5075 %s
5076 }
5077 leafnodes {
5078 reconnect: "10ms"
5079 remotes [
5080 {
5081 url: "nats://user:[email protected]:%d"
5082 account: USER
5083 }
5084 ]
5085 }
5086 `
5087 a1Conf := createConfFile(t, []byte(fmt.Sprintf(aConf, accs, "A1", _EMPTY_, sb1o.LeafNode.Port)))
5088 sa1, sa1o := RunServerWithConfig(a1Conf)
5089 defer sa1.Shutdown()
5090
5091 checkLeafNodeConnected(t, sa1)
5092 checkLeafNodeConnected(t, sb1)
5093
5094 a2Conf := createConfFile(t, []byte(fmt.Sprintf(aConf, accs, "A2",
5095 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", sa1o.Cluster.Port), sb1o.LeafNode.Port)))
5096 sa2, _ := RunServerWithConfig(a2Conf)
5097 defer sa2.Shutdown()
5098
5099 checkClusterFormed(t, sa1, sa2)
5100 checkLeafNodeConnected(t, sa2)
5101 checkLeafNodeConnectedCount(t, sb1, 2)
5102
5103 otherLeafsConf := `
5104 %s
5105 server_name: %s
5106 listen: "127.0.0.1:-1"
5107 leafnodes {
5108 remotes [
5109 {
5110 url: "nats://user:[email protected]:%d"
5111 account: USER
5112 }
5113 ]
5114 }
5115 `
5116 o1Conf := createConfFile(t, []byte(fmt.Sprintf(otherLeafsConf, accs, "OTHERLEAF1", sb2o.LeafNode.Port)))
5117 so1, _ := RunServerWithConfig(o1Conf)
5118 defer so1.Shutdown()
5119 checkLeafNodeConnected(t, so1)
5120 checkLeafNodeConnectedCount(t, sb2, 1)
5121
5122 o2Conf := createConfFile(t, []byte(fmt.Sprintf(otherLeafsConf, accs, "OTHERLEAF2", sb2o.LeafNode.Port)))
5123 so2, _ := RunServerWithConfig(o2Conf)
5124 defer so2.Shutdown()
5125 checkLeafNodeConnected(t, so2)
5126 checkLeafNodeConnectedCount(t, sb2, 2)
5127
5128 // Helper to check that the interest is propagated to all servers
5129 checkInterest := func(t *testing.T, expected []int, expectedGW int32) {
5130 t.Helper()
5131 subj := "foo"
5132 for i, s := range []*Server{sa1, sa2, so1, so2, sb1, sb2, sc, sd} {
5133 if s == sc || !s.isRunning() {
5134 continue
5135 }
5136 acc, err := s.LookupAccount("USER")
5137 require_NoError(t, err)
5138 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
5139 n := acc.Interest(subj)
5140 if n == expected[i] {
5141 return nil
5142 }
5143 return fmt.Errorf("Expected interest count for server %q to be %v, got %v", s, expected[i], n)
5144 })
5145 }
5146 // For server C, need to check in gateway's account.
5147 checkForRegisteredQSubInterest(t, sc, "B", "USER", "foo", expected[6], time.Second)
5148
5149 // For server B1 and B2, check that we have the proper counts in the map.
5150 for _, s := range []*Server{sb1, sb2} {
5151 if !s.isRunning() {
5152 continue
5153 }
5154 checkFor(t, 2*time.Second, 10*time.Millisecond, func() error {
5155 s.gateway.pasi.Lock()
5156 accMap := s.gateway.pasi.m
5157 st := accMap["USER"]
5158 var n int32
5159 entry, ok := st["foo bar"]
5160 if ok {
5161 n = entry.n
5162 }
5163 s.gateway.pasi.Unlock()
5164 if n == expectedGW {
5165 return nil
5166 }
5167 return fmt.Errorf("Expected GW interest count for server %q to be %v, got %v", s, expectedGW, n)
5168 })
5169 }
5170 }
5171
5172 ncA1 := natsConnect(t, sa1.ClientURL(), nats.UserInfo("user", "pwd"))
5173 defer ncA1.Close()
5174 for i := 0; i < 3; i++ {
5175 natsQueueSubSync(t, ncA1, "foo", "bar")
5176 }
5177 natsFlush(t, ncA1)
5178 // With 3 queue subs on A1, we should have for servers (in order checked in checkInterest)
5179 // for A1: 3 locals, for all others, 1 for the remote sub from A1.
5180 // B1 and B2 GW map will be 3 (1 for each sub)
5181 checkInterest(t, []int{3, 1, 1, 1, 1, 1, 1, 1}, 3)
5182
5183 ncA2 := natsConnect(t, sa2.ClientURL(), nats.UserInfo("user", "pwd"))
5184 defer ncA2.Close()
5185 ncA2qsub1 := natsQueueSubSync(t, ncA2, "foo", "bar")
5186 ncA2qsub2 := natsQueueSubSync(t, ncA2, "foo", "bar")
5187 natsFlush(t, ncA2)
5188 // A1 will have 1 more for remote sub, same for A2 (2 locals + 1 remote).
5189 // B1 will have 2 interest (1 per leaf connection)
5190 // B1 and B2 GW map goes to 5.
5191 checkInterest(t, []int{4, 3, 1, 1, 2, 1, 1, 1}, 5)
5192
5193 ncOther1 := natsConnect(t, so1.ClientURL(), nats.UserInfo("user", "pwd"))
5194 defer ncOther1.Close()
5195 natsQueueSubSync(t, ncOther1, "foo", "bar")
5196 natsQueueSubSync(t, ncOther1, "foo", "bar")
5197 natsFlush(t, ncOther1)
5198 // A1, A2 will have one more because of routed interest
5199 // O1 will have 3 (2 locals + 1 for remote interest)
5200 // O2 has still 1 for remote interest
5201 // B1 has 1 more because of new leaf interest and B2 because of routed interest.
5202 // B1 and B2 GW map goes to 7.
5203 checkInterest(t, []int{5, 4, 3, 1, 3, 2, 1, 1}, 7)
5204
5205 ncOther2 := natsConnect(t, so2.ClientURL(), nats.UserInfo("user", "pwd"))
5206 defer ncOther2.Close()
5207 natsQueueSubSync(t, ncOther2, "foo", "bar")
5208 natsFlush(t, ncOther2)
5209 // O2 1 more for local interest
5210 // B2 1 more for the new leaf interest
5211 // B1 and B2 GW map goes to 8.
5212 checkInterest(t, []int{5, 4, 3, 2, 3, 3, 1, 1}, 8)
5213
5214 // Stop the server so1.
5215 so1.Shutdown()
5216 so1.WaitForShutdown()
5217 checkLeafNodeConnectedCount(t, sb2, 1)
5218 // Now check interest still valid, but wait a little bit to make sure that
5219 // even with the bug where we would send an RS- through the gateway, there
5220 // would be enough time for it to propagate before we check for interest.
5221 time.Sleep(250 * time.Millisecond)
5222 // O1 is stopped, so expect 0
5223 // B2 has 1 less because leaf connection went away.
5224 // B1 and B2 GW map goes down to 6.
5225 checkInterest(t, []int{5, 4, 0, 2, 3, 2, 1, 1}, 6)
5226
5227 // Store server sa1.
5228 sa1.Shutdown()
5229 sa1.WaitForShutdown()
5230 checkLeafNodeConnectedCount(t, sb1, 1)
5231 time.Sleep(250 * time.Millisecond)
5232 // A1 and O1 are gone, so 0
5233 // A2 has 1 less due to loss of routed interest
5234 // B1 has 1 less because 1 leaf connection went away.
5235 // B1 and B2 GW map goes down to 3.
5236 checkInterest(t, []int{0, 3, 0, 2, 2, 2, 1, 1}, 3)
5237
5238 // Now remove the queue subs from A2
5239 ncA2qsub1.Unsubscribe()
5240 natsFlush(t, ncA2)
5241 // A2 has 1 less
5242 checkInterest(t, []int{0, 2, 0, 2, 2, 2, 1, 1}, 2)
5243
5244 ncA2qsub2.Unsubscribe()
5245 natsFlush(t, ncA2)
5246 // A2 has 1 (no more locals but still interest for O2).
5247 // O2 has 1 (no more for remote interest, only local).
5248 // B1, B2 has 1 less since no interest from any of its leaf connections.
5249 checkInterest(t, []int{0, 1, 0, 1, 1, 1, 1, 1}, 1)
5250
5251 // Removing (closing connection) of the sub on O2 will remove
5252 // interest globally.
5253 ncOther2.Close()
5254 checkInterest(t, []int{0, 0, 0, 0, 0, 0, 0, 0}, 0)
5255
5256 // Resubscribe now, and again, interest should be propagated.
5257 natsQueueSubSync(t, ncA2, "foo", "bar")
5258 natsFlush(t, ncA2)
5259 checkInterest(t, []int{0, 1, 0, 1, 1, 1, 1, 1}, 1)
5260
5261 natsQueueSubSync(t, ncA2, "foo", "bar")
5262 natsFlush(t, ncA2)
5263 checkInterest(t, []int{0, 2, 0, 1, 1, 1, 1, 1}, 2)
5264
5265 // Close the client connection that has the 2 queue subs.
5266 ncA2.Close()
5267 checkInterest(t, []int{0, 0, 0, 0, 0, 0, 0, 0}, 0)
5268
5269 // Now we will test when a route is lost on a server that has gateway enabled
5270 // that we update counts properly.
5271 ncB2 := natsConnect(t, sb2.ClientURL(), nats.UserInfo("user", "pwd"))
5272 defer ncB2.Close()
5273 natsQueueSubSync(t, ncB2, "foo", "bar")
5274 natsQueueSubSync(t, ncB2, "foo", "bar")
5275 natsQueueSubSync(t, ncB2, "foo", "bar")
5276 natsFlush(t, ncB2)
5277 checkInterest(t, []int{0, 1, 0, 1, 1, 3, 1, 1}, 3)
5278
5279 ncB1 := natsConnect(t, sb1.ClientURL(), nats.UserInfo("user", "pwd"))
5280 defer ncB1.Close()
5281 natsQueueSubSync(t, ncB1, "foo", "bar")
5282 natsQueueSubSync(t, ncB1, "foo", "bar")
5283 checkInterest(t, []int{0, 1, 0, 1, 3, 4, 1, 1}, 5)
5284
5285 // Now shutdown B2
5286 sb2.Shutdown()
5287 sa1.WaitForShutdown()
5288 time.Sleep(250 * time.Millisecond)
5289 checkInterest(t, []int{0, 1, 0, 0, 2, 0, 1, 1}, 2)
5290
5291 ncB1.Close()
5292 checkInterest(t, []int{0, 0, 0, 0, 0, 0, 0, 0}, 0)
5293
5294 // Now we will create 2 qsubs to sa2 that is still running.
5295 ncA2 = natsConnect(t, sa2.ClientURL(), nats.UserInfo("user", "pwd"))
5296 defer ncA2.Close()
5297 qsub1 := natsQueueSubSync(t, ncA2, "foo", "bar")
5298 qsub2 := natsQueueSubSync(t, ncA2, "foo", "bar")
5299 natsFlush(t, ncA2)
5300 // sa1 is down, so 0, sa2 has 2 queue subs, so1 is down, so 0, so2 is up, so
5301 // 1 for remote interest, same for sb1. Server sb2 is down, so 0, then 1 for
5302 // remote interest for sc and sd. The expected tally for the gateway to "C"
5303 // should be 2.
5304 checkInterest(t, []int{0, 2, 0, 1, 1, 0, 1, 1}, 2)
5305
5306 // Close the leaf connection between sb1 and sa2
5307 sa2.mu.Lock()
5308 for _, l := range sa2.leafs {
5309 l.mu.Lock()
5310 l.nc.Close()
5311 l.mu.Unlock()
5312 }
5313 sa2.mu.Unlock()
5314 time.Sleep(50 * time.Millisecond)
5315 checkLeafNodeConnected(t, sa2)
5316 // Should be the same counts
5317 checkInterest(t, []int{0, 2, 0, 1, 1, 0, 1, 1}, 2)
5318
5319 // Unsubscribe one of the queue sub.
5320 qsub2.Unsubscribe()
5321 natsFlush(t, ncA2)
5322 time.Sleep(50 * time.Millisecond)
5323 // One less for the local interest on sa2 and 1 less for the expected GW count.
5324 checkInterest(t, []int{0, 1, 0, 1, 1, 0, 1, 1}, 1)
5325
5326 // Verify that interest works by publishing from server "C".
5327 ncC := natsConnect(t, sc.ClientURL(), nats.UserInfo("user", "pwd"))
5328 defer ncC.Close()
5329 natsPub(t, ncC, "foo", []byte("hello"))
5330
5331 // Message should be received by qsub1.
5332 natsNexMsg(t, qsub1, time.Second)
5333
5334 // Now stop sa2 and instead start sb2.
5335 ncA2.Close()
5336 sa2.Shutdown()
5337 sa2.WaitForShutdown()
5338
5339 // Wait for counts to go down to 0
5340 checkInterest(t, []int{0, 0, 0, 0, 0, 0, 0, 0}, 0)
5341
5342 // Restart sb2 to form route to sb1.
5343 sb2, _ = RunServerWithConfig(sb2Conf)
5344 defer sb2.Shutdown()
5345
5346 checkClusterFormed(t, sb1, sb2)
5347 waitForOutboundGateways(t, sb2, 1, time.Second)
5348
5349 // Create 2 queue subs on sb2.
5350 ncB2 = natsConnect(t, sb2.ClientURL(), nats.UserInfo("user", "pwd"))
5351 defer ncB2.Close()
5352
5353 qsub1 = natsQueueSubSync(t, ncB2, "foo", "bar")
5354 qsub2 = natsQueueSubSync(t, ncB2, "foo", "bar")
5355 natsFlush(t, ncB2)
5356 // sa1 and sa2 are down, so 0, so1 is down, so 0, so2 is up, so 1 for remote interest,
5357 // same for sb1. Server sb2 has 2 local queue subs, so 2. Servers sc and sd have 1 for
5358 // remote interest. The expected tally for the gateway to "C" should be 2.
5359 checkInterest(t, []int{0, 0, 0, 1, 1, 2, 1, 1}, 2)
5360
5361 // Now close the route(s) between sb1 and sb2.
5362 sb2.mu.Lock()
5363 sb2.forEachRoute(func(r *client) {
5364 r.mu.Lock()
5365 r.nc.Close()
5366 r.mu.Unlock()
5367 })
5368 sb2.mu.Unlock()
5369 time.Sleep(50 * time.Millisecond)
5370 checkClusterFormed(t, sb1, sb2)
5371 // Should be the same counts
5372 checkInterest(t, []int{0, 0, 0, 1, 1, 2, 1, 1}, 2)
5373
5374 // Unsubscribe one of the queue sub.
5375 qsub2.Unsubscribe()
5376 natsFlush(t, ncB2)
5377 time.Sleep(50 * time.Millisecond)
5378 // One less for the local interest on sb2 and 1 less for the expected GW count.
5379 checkInterest(t, []int{0, 0, 0, 1, 1, 1, 1, 1}, 1)
5380
5381 // Verify that interest works by publishing from server "C".
5382 natsPub(t, ncC, "foo", []byte("hello"))
5383
5384 // Message should be received by qsub1.
5385 natsNexMsg(t, qsub1, time.Second)
5386 }
5387
5388 func TestLeafNodeQueueInterestAndWeightCorrectAfterServerRestartOrConnectionClose(t *testing.T) {
5389
5390 // Note that this is not what a normal configuration should be. Users should
5391 // configure each leafnode to have the URLs of both B1 and B2 so that when
5392 // a server fails, the leaf can reconnect to the other running server. But
5393 // we force it to be this way to demonstrate what the issue was and see that
5394 // it is now fixed.
5395 //
5396 // B1 <--- route ---> B2
5397 // | |
5398 // Leaf Leaf
5399 // | |
5400 // A1 <--- route ---> A2
5401 //
5402
5403 for _, test := range []struct {
5404 name string
5405 pinnedAccount string
5406 }{
5407 {"without pinned account", _EMPTY_},
5408 {"with pinned account", "accounts: [\"A\"]"},
5409 } {
5410 t.Run(test.name, func(t *testing.T) {
5411 leafBConf := `
5412 accounts { A { users: [{user:a, password: pwd}] } }
5413 server_name: %s
5414 listen: "127.0.0.1:-1"
5415 cluster {
5416 name: HUB
5417 listen: "127.0.0.1:-1"
5418 %s
5419 %s
5420 }
5421 leafnodes {
5422 listen: "127.0.0.1:-1"
5423 no_advertise: true
5424 }
5425 `
5426 b1Conf := createConfFile(t, []byte(fmt.Sprintf(leafBConf, "B1", _EMPTY_, test.pinnedAccount)))
5427 b1, b1Opts := RunServerWithConfig(b1Conf)
5428 defer b1.Shutdown()
5429
5430 b2Conf := createConfFile(t, []byte(fmt.Sprintf(leafBConf, "B2",
5431 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", b1Opts.Cluster.Port), test.pinnedAccount)))
5432 b2, b2Opts := RunServerWithConfig(b2Conf)
5433 defer b2.Shutdown()
5434
5435 checkClusterFormed(t, b1, b2)
5436
5437 leafAConf := `
5438 accounts { A { users: [{user:a, password: pwd}] } }
5439 server_name: %s
5440 listen: "127.0.0.1:-1"
5441 cluster {
5442 name: LEAF
5443 listen: "127.0.0.1:-1"
5444 %s
5445 %s
5446 }
5447 leafnodes {
5448 listen: "127.0.0.1:-1"
5449 remotes: [
5450 {
5451 url: "nats://a:[email protected]:%d"
5452 account: A
5453 }
5454 ]
5455 no_advertise: true
5456 }
5457 `
5458 a1Conf := createConfFile(t, []byte(fmt.Sprintf(leafAConf, "A1", _EMPTY_, test.pinnedAccount, b1Opts.LeafNode.Port)))
5459 a1, a1Opts := RunServerWithConfig(a1Conf)
5460 defer a1.Shutdown()
5461
5462 checkLeafNodeConnected(t, b1)
5463 checkLeafNodeConnected(t, a1)
5464
5465 a2Conf := createConfFile(t, []byte(fmt.Sprintf(leafAConf, "A2",
5466 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", a1Opts.Cluster.Port), test.pinnedAccount, b2Opts.LeafNode.Port)))
5467 a2, _ := RunServerWithConfig(a2Conf)
5468 defer a2.Shutdown()
5469
5470 checkLeafNodeConnected(t, b2)
5471 checkLeafNodeConnected(t, a2)
5472 checkClusterFormed(t, a1, a2)
5473
5474 // Create a client on A2 and 3 queue subs.
5475 ncA2 := natsConnect(t, a2.ClientURL(), nats.UserInfo("a", "pwd"))
5476 defer ncA2.Close()
5477
5478 var qsubs []*nats.Subscription
5479 for i := 0; i < 3; i++ {
5480 qsubs = append(qsubs, natsQueueSub(t, ncA2, "foo", "queue", func(_ *nats.Msg) {}))
5481 }
5482 natsFlush(t, ncA2)
5483
5484 subj := "foo"
5485 checkInterest := func(expected bool) {
5486 t.Helper()
5487 for _, s := range []*Server{a1, a2, b1, b2} {
5488 acc, err := s.LookupAccount("A")
5489 require_NoError(t, err)
5490 checkFor(t, time.Second, 100*time.Millisecond, func() error {
5491 i := acc.Interest(subj)
5492 if expected && i == 0 {
5493 return fmt.Errorf("Still no interest on %q in server %q", subj, s)
5494 } else if !expected && i > 0 {
5495 return fmt.Errorf("Still interest on %q in server %q", subj, s)
5496 }
5497 return nil
5498 })
5499 }
5500 }
5501 checkInterest(true)
5502
5503 // Check that Leafz from A1 (which connects to B1) has the expected sub
5504 // interest on "foo".
5505 checkLeafA1 := func(expected bool) {
5506 t.Helper()
5507 // We will wait a bit before checking Leafz since with the bug, it would
5508 // take a bit of time after the action to reproduce the issue for the
5509 // LS+ to be sent to the wrong cluster, or the interest to not be removed.
5510 time.Sleep(100 * time.Millisecond)
5511 // Now check Leafz
5512 leafsz, err := a1.Leafz(&LeafzOptions{Subscriptions: true})
5513 require_NoError(t, err)
5514 require_Equal(t, leafsz.NumLeafs, 1)
5515 require_True(t, leafsz.Leafs[0] != nil)
5516 lz := leafsz.Leafs[0]
5517 require_Equal(t, lz.Name, "B1")
5518 require_Equal(t, lz.NumSubs, uint32(len(lz.Subs)))
5519 var ok bool
5520 for _, sub := range lz.Subs {
5521 if sub == "foo" {
5522 if expected {
5523 ok = true
5524 break
5525 }
5526 t.Fatalf("Did not expect to have the %q subscription", sub)
5527 }
5528 }
5529 if expected && !ok {
5530 t.Fatalf("Expected to have the %q subscription", "foo")
5531 }
5532 }
5533 checkLeafA1(false)
5534
5535 // Now restart server "B1". We need to create a conf file with the ports
5536 // that it used.
5537 restartBConf := createConfFile(t, []byte(fmt.Sprintf(`
5538 accounts { A { users: [{user:a, password: pwd}] } }
5539 server_name: B1
5540 listen: "127.0.0.1:%d"
5541 cluster {
5542 name: HUB
5543 listen: "127.0.0.1:%d"
5544 %s
5545 }
5546 leafnodes {
5547 listen: "127.0.0.1:%d"
5548 no_advertise: true
5549 }
5550 `, b1Opts.Port, b1Opts.Cluster.Port, test.pinnedAccount, b1Opts.LeafNode.Port)))
5551 b1.Shutdown()
5552 b1, _ = RunServerWithConfig(restartBConf)
5553 defer b1.Shutdown()
5554
5555 checkLeafNodeConnected(t, b1)
5556 checkLeafNodeConnected(t, a1)
5557
5558 // Stop one of the queue sub.
5559 qsubs[0].Unsubscribe()
5560 natsFlush(t, ncA2)
5561
5562 // Check that "foo" does not show up in the subscription list
5563 // for the leaf from A1 to B1.
5564 checkLeafA1(false)
5565
5566 // Now stop the other 2 and check again.
5567 qsubs[1].Unsubscribe()
5568 qsubs[2].Unsubscribe()
5569 natsFlush(t, ncA2)
5570 checkInterest(false)
5571
5572 checkLeafA1(false)
5573
5574 // Now recreate 3 queue subs.
5575 for i := 0; i < 3; i++ {
5576 natsQueueSub(t, ncA2, "foo", "queue", func(_ *nats.Msg) {})
5577 }
5578 // Check interest is present in all servers
5579 checkInterest(true)
5580 // But A1's leaf to B1 should still not have a sub interest for "foo".
5581 checkLeafA1(false)
5582
5583 // Now stop the client connection instead of removing queue sub
5584 // one at a time. This will ensure that we properly handle an LS-
5585 // on B2 with an interest with a queue weight more than 1 still
5586 // present at the time of processing.
5587 ncA2.Close()
5588 checkInterest(false)
5589
5590 checkLeafA1(false)
5591
5592 // We will now test that if the queue subs are created on B2,
5593 // we have proper interest on A1, but when we close the connection,
5594 // the interest disappears.
5595 ncB2 := natsConnect(t, b2.ClientURL(), nats.UserInfo("a", "pwd"))
5596 defer ncB2.Close()
5597
5598 for i := 0; i < 3; i++ {
5599 natsQueueSub(t, ncB2, "foo", "queue", func(_ *nats.Msg) {})
5600 }
5601 checkInterest(true)
5602 checkLeafA1(true)
5603 // Close the connection, so all queue subs should be removed at once.
5604 ncB2.Close()
5605 checkInterest(false)
5606 checkLeafA1(false)
5607 })
5608 }
5609 }
5610
5611 func TestLeafNodeQueueWeightCorrectOnRestart(t *testing.T) {
5612 leafBConf := `
5613 server_name: %s
5614 listen: "127.0.0.1:-1"
5615 cluster {
5616 name: HUB
5617 listen: "127.0.0.1:-1"
5618 %s
5619 }
5620 leafnodes {
5621 listen: "127.0.0.1:-1"
5622 no_advertise: true
5623 }
5624 `
5625 b1Conf := createConfFile(t, []byte(fmt.Sprintf(leafBConf, "B1", _EMPTY_)))
5626 b1, b1Opts := RunServerWithConfig(b1Conf)
5627 defer b1.Shutdown()
5628
5629 b2Conf := createConfFile(t, []byte(fmt.Sprintf(leafBConf, "B2",
5630 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", b1Opts.Cluster.Port))))
5631 b2, b2Opts := RunServerWithConfig(b2Conf)
5632 defer b2.Shutdown()
5633
5634 checkClusterFormed(t, b1, b2)
5635
5636 leafAConf := `
5637 server_name: LEAF
5638 listen: "127.0.0.1:-1"
5639 leafnodes {
5640 remotes: [{url: "nats://127.0.0.1:%d"}]
5641 reconnect: "50ms"
5642 }
5643 `
5644 aConf := createConfFile(t, []byte(fmt.Sprintf(leafAConf, b2Opts.LeafNode.Port)))
5645 a, _ := RunServerWithConfig(aConf)
5646 defer a.Shutdown()
5647
5648 checkLeafNodeConnected(t, b2)
5649 checkLeafNodeConnected(t, a)
5650
5651 nc := natsConnect(t, a.ClientURL())
5652 defer nc.Close()
5653
5654 for i := 0; i < 2; i++ {
5655 natsQueueSubSync(t, nc, "foo", "queue")
5656 }
5657 natsFlush(t, nc)
5658
5659 checkQueueWeight := func() {
5660 for _, s := range []*Server{b1, b2} {
5661 gacc := s.GlobalAccount()
5662 gacc.mu.RLock()
5663 sl := gacc.sl
5664 gacc.mu.RUnlock()
5665 checkFor(t, time.Second, 10*time.Millisecond, func() error {
5666 // For remote queue interest, Match() will expand to queue weight.
5667 // So we should have 1 group and 2 queue subs present.
5668 res := sl.Match("foo")
5669 for _, qsubs := range res.qsubs {
5670 for _, sub := range qsubs {
5671 if string(sub.subject) == "foo" && string(sub.queue) == "queue" && atomic.LoadInt32(&sub.qw) == 2 {
5672 return nil
5673 }
5674 }
5675 }
5676 return fmt.Errorf("Server %q does not have expected queue interest with expected weight", s)
5677 })
5678 }
5679 }
5680 checkQueueWeight()
5681
5682 // Now restart server "B2". We need to create a conf file with the ports
5683 // that it used.
5684 restartBConf := createConfFile(t, []byte(fmt.Sprintf(`
5685 server_name: B2
5686 listen: "127.0.0.1:%d"
5687 cluster {
5688 name: HUB
5689 listen: "127.0.0.1:%d"
5690 %s
5691 }
5692 leafnodes {
5693 listen: "127.0.0.1:%d"
5694 no_advertise: true
5695 }
5696 `, b2Opts.Port, b2Opts.Cluster.Port, fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", b1Opts.Cluster.Port), b2Opts.LeafNode.Port)))
5697 b2.Shutdown()
5698 b2, _ = RunServerWithConfig(restartBConf)
5699 defer b2.Shutdown()
5700
5701 checkLeafNodeConnected(t, b2)
5702 checkLeafNodeConnected(t, a)
5703 checkQueueWeight()
5704 }
5705
5706 func TestLeafNodeRoutedSubKeyDifferentBetweenLeafSubAndRoutedSub(t *testing.T) {
5707 for _, test := range []struct {
5708 name string
5709 pinnedAccount string
5710 lnocu bool
5711 }{
5712 {"without pinned account", _EMPTY_, true},
5713 {"with pinned account", "accounts: [\"XYZ\"]", true},
5714 {"old server without pinned account", _EMPTY_, false},
5715 {"old server with pinned account", "accounts: [\"XYZ\"]", false},
5716 } {
5717 t.Run(test.name, func(t *testing.T) {
5718 leafBConf := `
5719 accounts: {XYZ {users:[{user:a, password:pwd}]}}
5720 server_name: %s
5721 listen: "127.0.0.1:-1"
5722 cluster {
5723 name: HUB
5724 listen: "127.0.0.1:-1"
5725 %s
5726 %s
5727 }
5728 leafnodes {
5729 listen: "127.0.0.1:-1"
5730 no_advertise: true
5731 }
5732 `
5733 b1Conf := createConfFile(t, []byte(fmt.Sprintf(leafBConf, "B1", _EMPTY_, test.pinnedAccount)))
5734 b1, b1Opts := RunServerWithConfig(b1Conf)
5735 defer b1.Shutdown()
5736
5737 b2Conf := createConfFile(t, []byte(fmt.Sprintf(leafBConf, "B2",
5738 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", b1Opts.Cluster.Port), test.pinnedAccount)))
5739 b2, b2Opts := RunServerWithConfig(b2Conf)
5740 defer b2.Shutdown()
5741
5742 checkClusterFormed(t, b1, b2)
5743
5744 // To make route connections behave like if the server was connected
5745 // to an older server, change the routes' lnocu field.
5746 if !test.lnocu {
5747 for _, s := range []*Server{b1, b2} {
5748 s.mu.RLock()
5749 s.forEachRoute(func(r *client) {
5750 r.mu.Lock()
5751 r.route.lnocu = false
5752 r.mu.Unlock()
5753 })
5754 s.mu.RUnlock()
5755 }
5756 }
5757
5758 // This leaf will have a cluster name that matches an account name.
5759 // The idea is to make sure that hub servers are not using incorrect
5760 // keys to differentiate a routed queue interest on subject "A" with
5761 // queue name "foo" for account "A" in their cluster: "RS+ A A foo"
5762 // with a leafnode plain subscription, which since there is an origin
5763 // would be: "LS+ A A foo", that is, origin is "A", account is "A"
5764 // and subject is "foo".
5765 leafAConf := `
5766 accounts: {XYZ {users:[{user:a, password:pwd}]}}
5767 server_name: LEAF
5768 listen: "127.0.0.1:-1"
5769 cluster {
5770 name: XYZ
5771 listen: "127.0.0.1:-1"
5772 }
5773 leafnodes {
5774 remotes: [
5775 {
5776 url: "nats://a:[email protected]:%d"
5777 account: "XYZ"
5778 }
5779 ]
5780 }
5781 `
5782 aConf := createConfFile(t, []byte(fmt.Sprintf(leafAConf, b2Opts.LeafNode.Port)))
5783 a, _ := RunServerWithConfig(aConf)
5784 defer a.Shutdown()
5785
5786 checkLeafNodeConnected(t, b2)
5787 checkLeafNodeConnected(t, a)
5788
5789 ncB2 := natsConnect(t, b2.ClientURL(), nats.UserInfo("a", "pwd"))
5790 defer ncB2.Close()
5791 // Create a plain sub on "foo"
5792 natsSubSync(t, ncB2, "foo")
5793 // And a queue sub on "XYZ" with queue name "foo"
5794 natsQueueSubSync(t, ncB2, "XYZ", "foo")
5795 natsFlush(t, ncB2)
5796
5797 ncA := natsConnect(t, a.ClientURL(), nats.UserInfo("a", "pwd"))
5798 defer ncA.Close()
5799 // From the leafnode, create a plain sub on "foo"
5800 natsSubSync(t, ncA, "foo")
5801 // And a queue sub on "XYZ" with queue name "foo"
5802 natsQueueSubSync(t, ncA, "XYZ", "foo")
5803 natsFlush(t, ncA)
5804
5805 // Check the acc.rm on B2
5806 b2Acc, err := b2.LookupAccount("XYZ")
5807 require_NoError(t, err)
5808
5809 rsubKey := keyFromSubWithOrigin(&subscription{subject: []byte("foo")})
5810 rqsubKey := keyFromSubWithOrigin(&subscription{subject: []byte("XYZ"), queue: []byte("foo")})
5811 rlsubKey := keyFromSubWithOrigin(&subscription{origin: []byte("XYZ"), subject: []byte("foo")})
5812 rlqsubKey := keyFromSubWithOrigin(&subscription{origin: []byte("XYZ"), subject: []byte("XYZ"), queue: []byte("foo")})
5813 // Ensure all keys are different
5814 require_True(t, rsubKey != rqsubKey && rqsubKey != rlsubKey && rlsubKey != rlqsubKey)
5815
5816 checkFor(t, time.Second, 10*time.Millisecond, func() error {
5817 b2Acc.mu.RLock()
5818 defer b2Acc.mu.RUnlock()
5819 for _, key := range []string{rsubKey, rqsubKey, rlsubKey, rlqsubKey} {
5820 v, ok := b2Acc.rm[key]
5821 if !ok {
5822 return fmt.Errorf("Did not find key %q for sub: %+v", key, sub)
5823 }
5824 if v != 1 {
5825 return fmt.Errorf("Key %q v=%v for sub: %+v", key, v, sub)
5826 }
5827 }
5828 return nil
5829 })
5830
5831 // Now check that on B1, we have 2 distinct subs for the route.
5832 b1Acc, err := b1.LookupAccount("XYZ")
5833 require_NoError(t, err)
5834
5835 var route *client
5836
5837 if test.pinnedAccount == _EMPTY_ {
5838 b1Acc.mu.RLock()
5839 rIdx := b1Acc.routePoolIdx
5840 b1Acc.mu.RUnlock()
5841 b1.mu.RLock()
5842 b1.forEachRouteIdx(rIdx, func(r *client) bool {
5843 route = r
5844 return false
5845 })
5846 b1.mu.RUnlock()
5847 } else {
5848 b1.mu.RLock()
5849 remotes := b1.accRoutes["XYZ"]
5850 for _, r := range remotes {
5851 route = r
5852 break
5853 }
5854 b1.mu.RUnlock()
5855 }
5856
5857 checkFor(t, time.Second, 10*time.Millisecond, func() error {
5858 // Check that route.subs has 4 entries for the subs we
5859 // created in this test.
5860 var entries []string
5861 route.mu.Lock()
5862 for key := range route.subs {
5863 if strings.Contains(key, "foo") {
5864 entries = append(entries, key)
5865 }
5866 }
5867 route.mu.Unlock()
5868 // With new servers, we expect 4 entries, but with older servers,
5869 // we have collisions and have only 2.
5870 var expected int
5871 if test.lnocu {
5872 expected = 4
5873 } else {
5874 expected = 2
5875 }
5876 if len(entries) != expected {
5877 return fmt.Errorf("Expected %d entries with %q, got this: %q", expected, "foo", entries)
5878 }
5879 return nil
5880 })
5881
5882 // Close the connections and expect all gone.
5883 ncB2.Close()
5884 ncA.Close()
5885
5886 checkFor(t, time.Second, 10*time.Millisecond, func() error {
5887 b2Acc.mu.RLock()
5888 defer b2Acc.mu.RUnlock()
5889 for _, key := range []string{rsubKey, rqsubKey, rlsubKey, rlqsubKey} {
5890 if _, ok := b2Acc.rm[key]; ok {
5891 return fmt.Errorf("Key %q still present", key)
5892 }
5893 }
5894 return nil
5895 })
5896 checkFor(t, time.Second, 10*time.Millisecond, func() error {
5897 var entries []string
5898 route.mu.Lock()
5899 for key := range route.subs {
5900 if strings.Contains(key, "foo") {
5901 entries = append(entries, key)
5902 }
5903 }
5904 route.mu.Unlock()
5905 if len(entries) != 0 {
5906 return fmt.Errorf("Still routed subscriptions on %q: %q", "foo", entries)
5907 }
5908 return nil
5909 })
5910 })
5911 }
5912 }
5913
5914 func TestLeafNodeQueueGroupWithLateLNJoin(t *testing.T) {
5915 /*
5916
5917 Topology: A cluster of leafnodes LN2 and LN3, connect
5918 to a cluster C1, C2.
5919
5920 sub(foo) sub(foo)
5921 \ /
5922 C1 <-> C2
5923 ^ ^
5924 | |
5925 LN2 <-> LN3
5926 / \
5927 sub(foo) sub(foo)
5928
5929 Once the above is set, start LN1 that connects to C1.
5930
5931 sub(foo) sub(foo)
5932 \ /
5933 LN1 -> C1 <-> C2
5934 ^ ^
5935 | |
5936 LN2 <-> LN3
5937 / \
5938 sub(foo) sub(foo)
5939
5940 Remove subs to LN3, C2 and C1.
5941
5942 LN1 -> C1 <-> C2
5943 ^ ^
5944 | |
5945 LN2 <-> LN3
5946 /
5947 sub(foo)
5948
5949 Publish from LN1 and verify message is received by sub on LN2.
5950
5951 pub(foo)
5952 \
5953 LN1 -> C1 <-> C2
5954 ^ ^
5955 | |
5956 LN2 <-> LN3
5957 /
5958 sub(foo)
5959 */
5960 co1 := DefaultOptions()
5961 co1.LeafNode.Host = "127.0.0.1"
5962 co1.LeafNode.Port = -1
5963 co1.Cluster.Name = "ngs"
5964 co1.Cluster.Host = "127.0.0.1"
5965 co1.Cluster.Port = -1
5966 c1 := RunServer(co1)
5967 defer c1.Shutdown()
5968
5969 co2 := DefaultOptions()
5970 co2.LeafNode.Host = "127.0.0.1"
5971 co2.LeafNode.Port = -1
5972 co2.Cluster.Name = "ngs"
5973 co2.Cluster.Host = "127.0.0.1"
5974 co2.Cluster.Port = -1
5975 co2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", co1.Cluster.Port))
5976 c2 := RunServer(co2)
5977 defer c2.Shutdown()
5978
5979 checkClusterFormed(t, c1, c2)
5980
5981 lo2 := DefaultOptions()
5982 lo2.Cluster.Name = "local"
5983 lo2.Cluster.Host = "127.0.0.1"
5984 lo2.Cluster.Port = -1
5985 lo2.LeafNode.ReconnectInterval = 50 * time.Millisecond
5986 lo2.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{{Scheme: "nats", Host: fmt.Sprintf("127.0.0.1:%d", co1.LeafNode.Port)}}}}
5987 ln2 := RunServer(lo2)
5988 defer ln2.Shutdown()
5989
5990 lo3 := DefaultOptions()
5991 lo3.Cluster.Name = "local"
5992 lo3.Cluster.Host = "127.0.0.1"
5993 lo3.Cluster.Port = -1
5994 lo3.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", lo2.Cluster.Port))
5995 lo3.LeafNode.ReconnectInterval = 50 * time.Millisecond
5996 lo3.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{{Scheme: "nats", Host: fmt.Sprintf("127.0.0.1:%d", co2.LeafNode.Port)}}}}
5997 ln3 := RunServer(lo3)
5998 defer ln3.Shutdown()
5999
6000 checkClusterFormed(t, ln2, ln3)
6001 checkLeafNodeConnected(t, ln2)
6002 checkLeafNodeConnected(t, ln3)
6003
6004 cln2 := natsConnect(t, ln2.ClientURL())
6005 defer cln2.Close()
6006 sln2 := natsQueueSubSync(t, cln2, "foo", "qgroup")
6007 natsFlush(t, cln2)
6008
6009 cln3 := natsConnect(t, ln3.ClientURL())
6010 defer cln3.Close()
6011 sln3 := natsQueueSubSync(t, cln3, "foo", "qgroup")
6012 natsFlush(t, cln3)
6013
6014 cc1 := natsConnect(t, c1.ClientURL())
6015 defer cc1.Close()
6016 sc1 := natsQueueSubSync(t, cc1, "foo", "qgroup")
6017 natsFlush(t, cc1)
6018
6019 cc2 := natsConnect(t, c2.ClientURL())
6020 defer cc2.Close()
6021 sc2 := natsQueueSubSync(t, cc2, "foo", "qgroup")
6022 natsFlush(t, cc2)
6023
6024 checkSubInterest(t, c1, globalAccountName, "foo", time.Second)
6025 checkSubInterest(t, c2, globalAccountName, "foo", time.Second)
6026 checkSubInterest(t, ln2, globalAccountName, "foo", time.Second)
6027 checkSubInterest(t, ln3, globalAccountName, "foo", time.Second)
6028
6029 lo1 := DefaultOptions()
6030 lo1.LeafNode.ReconnectInterval = 50 * time.Millisecond
6031 lo1.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{{Scheme: "nats", Host: fmt.Sprintf("127.0.0.1:%d", co1.LeafNode.Port)}}}}
6032 ln1 := RunServer(lo1)
6033 defer ln1.Shutdown()
6034
6035 checkLeafNodeConnected(t, ln1)
6036 checkSubInterest(t, ln1, globalAccountName, "foo", time.Second)
6037
6038 sln3.Unsubscribe()
6039 natsFlush(t, cln3)
6040 sc2.Unsubscribe()
6041 natsFlush(t, cc2)
6042 sc1.Unsubscribe()
6043 natsFlush(t, cc1)
6044
6045 cln1 := natsConnect(t, ln1.ClientURL())
6046 defer cln1.Close()
6047
6048 natsPub(t, cln1, "foo", []byte("hello"))
6049 natsNexMsg(t, sln2, time.Second)
6050 }
6051
6052 func TestLeafNodeJetStreamDomainMapCrossTalk(t *testing.T) {
6053 accs := `
6054 accounts :{
6055 A:{ jetstream: enable, users:[ {user:a1,password:a1}]},
6056 SYS:{ users:[ {user:s1,password:s1}]},
6057 }
6058 system_account: SYS
6059 `
6060
6061 sd1 := t.TempDir()
6062 confA := createConfFile(t, []byte(fmt.Sprintf(`
6063 listen: 127.0.0.1:-1
6064 %s
6065 jetstream: { domain: da, store_dir: '%s', max_mem: 50Mb, max_file: 50Mb }
6066 leafnodes: {
6067 listen: 127.0.0.1:-1
6068 no_advertise: true
6069 authorization: {
6070 timeout: 0.5
6071 }
6072 }
6073 `, accs, sd1)))
6074 sA, _ := RunServerWithConfig(confA)
6075 defer sA.Shutdown()
6076
6077 sd2 := t.TempDir()
6078 confL := createConfFile(t, []byte(fmt.Sprintf(`
6079 listen: 127.0.0.1:-1
6080 %s
6081 jetstream: { domain: dl, store_dir: '%s', max_mem: 50Mb, max_file: 50Mb }
6082 leafnodes:{
6083 no_advertise: true
6084 remotes:[{url:nats://a1:[email protected]:%d, account: A},
6085 {url:nats://s1:[email protected]:%d, account: SYS}]
6086 }
6087 `, accs, sd2, sA.opts.LeafNode.Port, sA.opts.LeafNode.Port)))
6088 sL, _ := RunServerWithConfig(confL)
6089 defer sL.Shutdown()
6090
6091 ncA := natsConnect(t, sA.ClientURL(), nats.UserInfo("a1", "a1"))
6092 defer ncA.Close()
6093 ncL := natsConnect(t, sL.ClientURL(), nats.UserInfo("a1", "a1"))
6094 defer ncL.Close()
6095
6096 test := func(jsA, jsL nats.JetStreamContext) {
6097 kvA, err := jsA.CreateKeyValue(&nats.KeyValueConfig{Bucket: "bucket"})
6098 require_NoError(t, err)
6099 kvL, err := jsL.CreateKeyValue(&nats.KeyValueConfig{Bucket: "bucket"})
6100 require_NoError(t, err)
6101
6102 _, err = kvA.Put("A", nil)
6103 require_NoError(t, err)
6104 _, err = kvL.Put("L", nil)
6105 require_NoError(t, err)
6106
6107 // check for unwanted cross talk
6108 _, err = kvA.Get("A")
6109 require_NoError(t, err)
6110 _, err = kvA.Get("l")
6111 require_Error(t, err)
6112 require_True(t, err == nats.ErrKeyNotFound)
6113
6114 _, err = kvL.Get("A")
6115 require_Error(t, err)
6116 require_True(t, err == nats.ErrKeyNotFound)
6117 _, err = kvL.Get("L")
6118 require_NoError(t, err)
6119
6120 err = jsA.DeleteKeyValue("bucket")
6121 require_NoError(t, err)
6122 err = jsL.DeleteKeyValue("bucket")
6123 require_NoError(t, err)
6124 }
6125
6126 jsA, err := ncA.JetStream()
6127 require_NoError(t, err)
6128 jsL, err := ncL.JetStream()
6129 require_NoError(t, err)
6130 test(jsA, jsL)
6131
6132 jsAL, err := ncA.JetStream(nats.Domain("dl"))
6133 require_NoError(t, err)
6134 jsLA, err := ncL.JetStream(nats.Domain("da"))
6135 require_NoError(t, err)
6136 test(jsAL, jsLA)
6137
6138 jsAA, err := ncA.JetStream(nats.Domain("da"))
6139 require_NoError(t, err)
6140 jsLL, err := ncL.JetStream(nats.Domain("dl"))
6141 require_NoError(t, err)
6142 test(jsAA, jsLL)
6143 }
6144
6145 type checkLeafMinVersionLogger struct {
6146 DummyLogger
6147 errCh chan time.Time
6148 connCh chan time.Time
6149 }
6150
6151 func (l *checkLeafMinVersionLogger) Errorf(format string, args ...any) {
6152 msg := fmt.Sprintf(format, args...)
6153 if strings.Contains(msg, "minimum version") {
6154 select {
6155 case l.errCh <- time.Now():
6156 default:
6157 }
6158 }
6159 }
6160
6161 func (l *checkLeafMinVersionLogger) Noticef(format string, args ...any) {
6162 msg := fmt.Sprintf(format, args...)
6163 if strings.Contains(msg, "Leafnode connection created") {
6164 select {
6165 case l.connCh <- time.Now():
6166 default:
6167 }
6168 }
6169 }
6170
6171 func TestLeafNodeMinVersion(t *testing.T) {
6172 conf := createConfFile(t, []byte(`
6173 port: -1
6174 leafnodes {
6175 port: -1
6176 min_version: 2.8.0
6177 }
6178 `))
6179 s, o := RunServerWithConfig(conf)
6180 defer s.Shutdown()
6181
6182 rconf := createConfFile(t, []byte(fmt.Sprintf(`
6183 port: -1
6184 leafnodes {
6185 remotes [
6186 {url: "nats://127.0.0.1:%d" }
6187 ]
6188 }
6189 `, o.LeafNode.Port)))
6190 ln, _ := RunServerWithConfig(rconf)
6191 defer ln.Shutdown()
6192
6193 checkLeafNodeConnected(t, s)
6194 checkLeafNodeConnected(t, ln)
6195
6196 ln.Shutdown()
6197 s.Shutdown()
6198
6199 // Now makes sure we validate options, not just config file.
6200 for _, test := range []struct {
6201 name string
6202 version string
6203 err string
6204 }{
6205 {"invalid version", "abc", "semver"},
6206 {"version too low", "2.7.9", "the minimum version should be at least 2.8.0"},
6207 } {
6208 t.Run(test.name, func(t *testing.T) {
6209 o.Port = -1
6210 o.LeafNode.Port = -1
6211 o.LeafNode.MinVersion = test.version
6212 if s, err := NewServer(o); err == nil || !strings.Contains(err.Error(), test.err) {
6213 if s != nil {
6214 s.Shutdown()
6215 }
6216 t.Fatalf("Expected error to contain %q, got %v", test.err, err)
6217 }
6218 })
6219 }
6220
6221 // Ok, so now to verify that a server rejects a leafnode connection
6222 // we will set the min_version above our current VERSION. So first
6223 // decompose the version:
6224 major, minor, _, err := versionComponents(VERSION)
6225 if err != nil {
6226 t.Fatalf("The current server version %q is not valid: %v", VERSION, err)
6227 }
6228 // Let's make our minimum server an minor version above
6229 mv := fmt.Sprintf("%d.%d.0", major, minor+1)
6230 conf = createConfFile(t, []byte(fmt.Sprintf(`
6231 port: -1
6232 leafnodes {
6233 port: -1
6234 min_version: "%s"
6235 }
6236 `, mv)))
6237 s, o = RunServerWithConfig(conf)
6238 defer s.Shutdown()
6239
6240 l := &checkLeafMinVersionLogger{errCh: make(chan time.Time, 1), connCh: make(chan time.Time, 1)}
6241 s.SetLogger(l, false, false)
6242
6243 rconf = createConfFile(t, []byte(fmt.Sprintf(`
6244 port: -1
6245 leafnodes {
6246 remotes [
6247 {url: "nats://127.0.0.1:%d" }
6248 ]
6249 }
6250 `, o.LeafNode.Port)))
6251 lo := LoadConfig(rconf)
6252 lo.LeafNode.ReconnectInterval = 50 * time.Millisecond
6253 ln = RunServer(lo)
6254 defer ln.Shutdown()
6255
6256 select {
6257 case <-l.connCh:
6258 case <-time.After(time.Second):
6259 t.Fatal("Remote did not try to connect")
6260 }
6261
6262 var rejectAt time.Time
6263 select {
6264 case rejectAt = <-l.errCh:
6265 case <-time.After(time.Second):
6266 t.Fatal("Did not get the minimum version required error")
6267 }
6268
6269 // Since we have a very small reconnect interval, the next attempt should be
6270 // delayed by the dedicated minimum version reconnect delay on the soliciting
6271 // side, not by the normal reconnect interval.
6272 select {
6273 case secondAttemptAt := <-l.connCh:
6274 if elapsed := secondAttemptAt.Sub(rejectAt); elapsed < leafNodeMinVersionReconnectDelay {
6275 t.Fatalf("Expected reconnect attempt after at least %v, got %v", leafNodeMinVersionReconnectDelay, elapsed)
6276 }
6277 case <-time.After(7 * time.Second):
6278 t.Fatal("Did not get the reconnect attempt")
6279 }
6280 }
6281
6282 func TestLeafNodeStreamAndShadowSubs(t *testing.T) {
6283 hubConf := createConfFile(t, []byte(`
6284 port: -1
6285 leafnodes {
6286 port: -1
6287 authorization: {
6288 user: leaf
6289 password: leaf
6290 account: B
6291 }
6292 }
6293 accounts: {
6294 A: {
6295 users = [{user: usrA, password: usrA}]
6296 exports: [{stream: foo.*.>}]
6297 }
6298 B: {
6299 imports: [{stream: {account: A, subject: foo.*.>}}]
6300 }
6301 }
6302 `))
6303 hub, hubo := RunServerWithConfig(hubConf)
6304 defer hub.Shutdown()
6305
6306 leafConfContet := fmt.Sprintf(`
6307 port: -1
6308 leafnodes {
6309 remotes = [
6310 {
6311 url: "nats-leaf://leaf:[email protected]:%d"
6312 account: B
6313 }
6314 ]
6315 }
6316 accounts: {
6317 B: {
6318 exports: [{stream: foo.*.>}]
6319 }
6320 C: {
6321 users: [{user: usrC, password: usrC}]
6322 imports: [{stream: {account: B, subject: foo.bar.>}}]
6323 }
6324 }
6325 `, hubo.LeafNode.Port)
6326 leafConf := createConfFile(t, []byte(leafConfContet))
6327 leafo := LoadConfig(leafConf)
6328 leafo.LeafNode.ReconnectInterval = 50 * time.Millisecond
6329 leaf := RunServer(leafo)
6330 defer leaf.Shutdown()
6331
6332 checkLeafNodeConnected(t, hub)
6333 checkLeafNodeConnected(t, leaf)
6334
6335 subPubAndCheck := func() {
6336 t.Helper()
6337
6338 ncl, err := nats.Connect(leaf.ClientURL(), nats.UserInfo("usrC", "usrC"))
6339 if err != nil {
6340 t.Fatalf("Error connecting: %v", err)
6341 }
6342 defer ncl.Close()
6343
6344 // This will send an LS+ to the "hub" server.
6345 sub, err := ncl.SubscribeSync("foo.*.baz")
6346 if err != nil {
6347 t.Fatalf("Error subscribing: %v", err)
6348 }
6349 ncl.Flush()
6350
6351 ncm, err := nats.Connect(hub.ClientURL(), nats.UserInfo("usrA", "usrA"))
6352 if err != nil {
6353 t.Fatalf("Error connecting: %v", err)
6354 }
6355 defer ncm.Close()
6356
6357 // Try a few times in case subject interest has not propagated yet
6358 for i := 0; i < 5; i++ {
6359 ncm.Publish("foo.bar.baz", []byte("msg"))
6360 if _, err := sub.NextMsg(time.Second); err == nil {
6361 // OK, done!
6362 return
6363 }
6364 }
6365 t.Fatal("Message was not received")
6366 }
6367 subPubAndCheck()
6368
6369 // Now cause a restart of the accepting side so that the leaf connection
6370 // is recreated.
6371 hub.Shutdown()
6372 hub = RunServer(hubo)
6373 defer hub.Shutdown()
6374
6375 checkLeafNodeConnected(t, hub)
6376 checkLeafNodeConnected(t, leaf)
6377
6378 subPubAndCheck()
6379
6380 // Issue a config reload even though we make no modification. There was
6381 // a defect that caused the interest propagation to break.
6382 // Set the ReconnectInterval to the default value so that reload does not complain.
6383 leaf.getOpts().LeafNode.ReconnectInterval = DEFAULT_LEAF_NODE_RECONNECT
6384 reloadUpdateConfig(t, leaf, leafConf, leafConfContet)
6385
6386 // Check again
6387 subPubAndCheck()
6388 }
6389
6390 func TestLeafNodeAuthConfigReload(t *testing.T) {
6391 template := `
6392 listen: 127.0.0.1:-1
6393 accounts { test: {} }
6394 leaf {
6395 listen: "127.0.0.1:7422"
6396 tls {
6397 cert_file: "../test/configs/certs/server-cert.pem"
6398 key_file: "../test/configs/certs/server-key.pem"
6399 ca_file: "../test/configs/certs/ca.pem"
6400 }
6401 authorization {
6402 # These are only fields allowed atm.
6403 users = [ { user: test, password: "s3cret1", account: "test" } ]
6404 }
6405 }
6406 `
6407 conf := createConfFile(t, []byte(template))
6408
6409 s, _ := RunServerWithConfig(conf)
6410 defer s.Shutdown()
6411
6412 lg := &captureErrorLogger{errCh: make(chan string, 10)}
6413 s.SetLogger(lg, false, false)
6414
6415 // Reload here should work ok.
6416 reloadUpdateConfig(t, s, conf, template)
6417 }
6418
6419 func TestLeafNodeSignatureCB(t *testing.T) {
6420 content := `
6421 port: -1
6422 server_name: OP
6423 operator = "../test/configs/nkeys/op.jwt"
6424 resolver = MEMORY
6425 listen: "127.0.0.1:-1"
6426 leafnodes {
6427 listen: "127.0.0.1:-1"
6428 }
6429 `
6430 conf := createConfFile(t, []byte(content))
6431 s, opts := RunServerWithConfig(conf)
6432 defer s.Shutdown()
6433
6434 _, akp := createAccount(s)
6435 kp, _ := nkeys.CreateUser()
6436 pub, _ := kp.PublicKey()
6437 nuc := jwt.NewUserClaims(pub)
6438 ujwt, err := nuc.Encode(akp)
6439 if err != nil {
6440 t.Fatalf("Error generating user JWT: %v", err)
6441 }
6442
6443 dto := DefaultTestOptions
6444 lopts := &dto
6445 u, err := url.Parse(fmt.Sprintf("nats://%s:%d", opts.LeafNode.Host, opts.LeafNode.Port))
6446 if err != nil {
6447 t.Fatalf("Error parsing url: %v", err)
6448 }
6449 remote := &RemoteLeafOpts{URLs: []*url.URL{u}}
6450 remote.SignatureCB = func(nonce []byte) (string, []byte, error) {
6451 return "", nil, fmt.Errorf("on purpose")
6452 }
6453 lopts.LeafNode.Remotes = []*RemoteLeafOpts{remote}
6454 lopts.LeafNode.ReconnectInterval = 100 * time.Millisecond
6455 sl := RunServer(lopts)
6456 defer sl.Shutdown()
6457
6458 slog := &captureErrorLogger{errCh: make(chan string, 10)}
6459 sl.SetLogger(slog, false, false)
6460
6461 // Now check that the leafnode got the error that the callback returned.
6462 select {
6463 case err := <-slog.errCh:
6464 if !strings.Contains(err, "on purpose") {
6465 t.Fatalf("Expected error from cb, got %v", err)
6466 }
6467 case <-time.After(time.Second):
6468 t.Fatal("Did not get expected error")
6469 }
6470
6471 sl.Shutdown()
6472 // Now check what happens if the connection is closed while in the callback.
6473 blockCh := make(chan struct{})
6474 remote.SignatureCB = func(nonce []byte) (string, []byte, error) {
6475 <-blockCh
6476 sig, err := kp.Sign(nonce)
6477 return ujwt, sig, err
6478 }
6479 sl = RunServer(lopts)
6480 defer sl.Shutdown()
6481
6482 // Recreate the logger so that we are sure not to have possible previous errors
6483 slog = &captureErrorLogger{errCh: make(chan string, 10)}
6484 sl.SetLogger(slog, false, false)
6485
6486 // Get the leaf connection from the temp clients map and close it.
6487 checkFor(t, time.Second, 15*time.Millisecond, func() error {
6488 var c *client
6489 sl.grMu.Lock()
6490 for _, cli := range sl.grTmpClients {
6491 c = cli
6492 }
6493 sl.grMu.Unlock()
6494 if c == nil {
6495 return fmt.Errorf("Client still not found in temp map")
6496 }
6497 c.closeConnection(ClientClosed)
6498 return nil
6499 })
6500
6501 // Release the callback, and check we get the appropriate error.
6502 close(blockCh)
6503 select {
6504 case err := <-slog.errCh:
6505 if !strings.Contains(err, ErrConnectionClosed.Error()) {
6506 t.Fatalf("Expected error that connection was closed, got %v", err)
6507 }
6508 case <-time.After(time.Second):
6509 t.Fatal("Did not get expected error")
6510 }
6511
6512 sl.Shutdown()
6513 // Change to a good CB and now it should work
6514 remote.SignatureCB = func(nonce []byte) (string, []byte, error) {
6515 sig, err := kp.Sign(nonce)
6516 return ujwt, sig, err
6517 }
6518 sl = RunServer(lopts)
6519 defer sl.Shutdown()
6520 checkLeafNodeConnected(t, sl)
6521 }
6522
6523 type testLeafTraceLogger struct {
6524 DummyLogger
6525 ch chan string
6526 }
6527
6528 func (l *testLeafTraceLogger) Tracef(format string, v ...any) {
6529 msg := fmt.Sprintf(format, v...)
6530 // We will sub to 'baz' and to 'bar', so filter on 'ba' prefix.
6531 if strings.Contains(msg, "[LS+ ba") {
6532 select {
6533 case l.ch <- msg:
6534 default:
6535 }
6536 }
6537 }
6538
6539 // Make sure permissioned denied subs do not make it to the leafnode even if existing.
6540 func TestLeafNodePermsSuppressSubs(t *testing.T) {
6541 conf := createConfFile(t, []byte(`
6542 listen: 127.0.0.1:-1
6543 authorization {
6544 PERMS = {
6545 publish = "foo"
6546 subscribe = ["_INBOX.>"]
6547 }
6548 users = [
6549 {user: "user", password: "pass"}
6550 {user: "ln", password: "pass" , permissions: $PERMS }
6551 ]
6552 }
6553 no_auth_user: user
6554
6555 leafnodes {
6556 listen: 127.0.0.1:7422
6557 }
6558 `))
6559
6560 lconf := createConfFile(t, []byte(`
6561 listen: 127.0.0.1:-1
6562 leafnodes {
6563 remotes = [ { url: "nats://ln:[email protected]" } ]
6564 }
6565 trace = true
6566 `))
6567
6568 s, _ := RunServerWithConfig(conf)
6569 defer s.Shutdown()
6570
6571 // Connect client to the hub.
6572 nc, err := nats.Connect(s.ClientURL())
6573 require_NoError(t, err)
6574 defer nc.Close()
6575
6576 // This should not be seen on leafnode side since we only allow pub to "foo"
6577 _, err = nc.SubscribeSync("baz")
6578 require_NoError(t, err)
6579
6580 ln, _ := RunServerWithConfig(lconf)
6581 defer ln.Shutdown()
6582
6583 // Setup logger to capture trace events.
6584 l := &testLeafTraceLogger{ch: make(chan string, 10)}
6585 ln.SetLogger(l, true, true)
6586
6587 checkLeafNodeConnected(t, ln)
6588
6589 // Need to have ot reconnect to trigger since logger attaches too late.
6590 ln.mu.Lock()
6591 for _, c := range ln.leafs {
6592 c.mu.Lock()
6593 c.nc.Close()
6594 c.mu.Unlock()
6595 }
6596 ln.mu.Unlock()
6597 checkLeafNodeConnectedCount(t, ln, 0)
6598 checkLeafNodeConnectedCount(t, ln, 1)
6599
6600 select {
6601 case msg := <-l.ch:
6602 t.Fatalf("Unexpected LS+ seen on leafnode: %s", msg)
6603 case <-time.After(50 * time.Millisecond):
6604 // OK
6605 }
6606
6607 // Now double check that new subs also do not propagate.
6608 // This behavior was working already.
6609 _, err = nc.SubscribeSync("bar")
6610 require_NoError(t, err)
6611
6612 select {
6613 case msg := <-l.ch:
6614 t.Fatalf("Unexpected LS+ seen on leafnode: %s", msg)
6615 case <-time.After(50 * time.Millisecond):
6616 // OK
6617 }
6618 }
6619
6620 func TestLeafNodeDuplicateMsg(t *testing.T) {
6621 // This involves 2 clusters with leafnodes to each other with a different
6622 // account, and those accounts import/export a subject that caused
6623 // duplicate messages. This test requires static ports since we need to
6624 // have A->B and B->A.
6625 a1Conf := createConfFile(t, []byte(`
6626 cluster : {
6627 name : A
6628 port : -1
6629 }
6630 leafnodes : {
6631 port : 14333
6632 remotes : [{
6633 account : A
6634 urls : [nats://leafa:[email protected]:24333]
6635 }]
6636 }
6637 port : -1
6638 server_name : A_1
6639
6640 accounts:{
6641 A:{
6642 users:[
6643 {user: leafa, password: pwd},
6644 {user: usera, password: usera, permissions: {
6645 publish:{ allow:["iot.b.topic"] }
6646 subscribe:{ allow:["iot.a.topic"] }
6647 }}
6648 ]
6649 imports:[
6650 {stream:{account:"B", subject:"iot.a.topic"}}
6651 ]
6652 },
6653 B:{
6654 users:[
6655 {user: leafb, password: pwd},
6656 ]
6657 exports:[
6658 {stream: "iot.a.topic", accounts: ["A"]}
6659 ]
6660 }
6661 }
6662 `))
6663 a1, oa1 := RunServerWithConfig(a1Conf)
6664 defer a1.Shutdown()
6665
6666 a2Conf := createConfFile(t, []byte(fmt.Sprintf(`
6667 cluster : {
6668 name : A
6669 port : -1
6670 routes : [nats://127.0.0.1:%d]
6671 }
6672 leafnodes : {
6673 port : 14334
6674 remotes : [{
6675 account : A
6676 urls : [nats://leafa:[email protected]:24334]
6677 }]
6678 }
6679 port : -1
6680 server_name : A_2
6681
6682 accounts:{
6683 A:{
6684 users:[
6685 {user: leafa, password: pwd},
6686 {user: usera, password: usera, permissions: {
6687 publish:{ allow:["iot.b.topic"] }
6688 subscribe:{ allow:["iot.a.topic"] }
6689 }}
6690 ]
6691 imports:[
6692 {stream:{account:"B", subject:"iot.a.topic"}}
6693 ]
6694 },
6695 B:{
6696 users:[
6697 {user: leafb, password: pwd},
6698 ]
6699 exports:[
6700 {stream: "iot.a.topic", accounts: ["A"]}
6701 ]
6702 }
6703 }`, oa1.Cluster.Port)))
6704 a2, _ := RunServerWithConfig(a2Conf)
6705 defer a2.Shutdown()
6706
6707 checkClusterFormed(t, a1, a2)
6708
6709 b1Conf := createConfFile(t, []byte(`
6710 cluster : {
6711 name : B
6712 port : -1
6713 }
6714 leafnodes : {
6715 port : 24333
6716 remotes : [{
6717 account : B
6718 urls : [nats://leafb:[email protected]:14333]
6719 }]
6720 }
6721 port : -1
6722 server_name : B_1
6723
6724 accounts:{
6725 A:{
6726 users:[
6727 {user: leafa, password: pwd},
6728 ]
6729 exports:[
6730 {stream: "iot.b.topic", accounts: ["B"]}
6731 ]
6732 },
6733 B:{
6734 users:[
6735 {user: leafb, password: pwd},
6736 {user: userb, password: userb, permissions: {
6737 publish:{ allow:["iot.a.topic"] },
6738 subscribe:{ allow:["iot.b.topic"] }
6739 }}
6740 ]
6741 imports:[
6742 {stream:{account:"A", subject:"iot.b.topic"}}
6743 ]
6744 }
6745 }`))
6746 b1, ob1 := RunServerWithConfig(b1Conf)
6747 defer b1.Shutdown()
6748
6749 b2Conf := createConfFile(t, []byte(fmt.Sprintf(`
6750 cluster : {
6751 name : B
6752 port : -1
6753 routes : [nats://127.0.0.1:%d]
6754 }
6755 leafnodes : {
6756 port : 24334
6757 remotes : [{
6758 account : B
6759 urls : [nats://leafb:[email protected]:14334]
6760 }]
6761 }
6762 port : -1
6763 server_name : B_2
6764
6765 accounts:{
6766 A:{
6767 users:[
6768 {user: leafa, password: pwd},
6769 ]
6770 exports:[
6771 {stream: "iot.b.topic", accounts: ["B"]}
6772 ]
6773 },
6774 B:{
6775 users:[
6776 {user: leafb, password: pwd},
6777 {user: userb, password: userb, permissions: {
6778 publish:{ allow:["iot.a.topic"] },
6779 subscribe:{ allow:["iot.b.topic"] }
6780 }}
6781 ]
6782 imports:[
6783 {stream:{account:"A", subject:"iot.b.topic"}}
6784 ]
6785 }
6786 }`, ob1.Cluster.Port)))
6787 b2, _ := RunServerWithConfig(b2Conf)
6788 defer b2.Shutdown()
6789
6790 checkClusterFormed(t, b1, b2)
6791
6792 checkLeafNodeConnectedCount(t, a1, 2)
6793 checkLeafNodeConnectedCount(t, a2, 2)
6794 checkLeafNodeConnectedCount(t, b1, 2)
6795 checkLeafNodeConnectedCount(t, b2, 2)
6796
6797 check := func(t *testing.T, subSrv *Server, pubSrv *Server) {
6798
6799 sc := natsConnect(t, subSrv.ClientURL(), nats.UserInfo("userb", "userb"))
6800 defer sc.Close()
6801
6802 subject := "iot.b.topic"
6803 sub := natsSubSync(t, sc, subject)
6804
6805 // Wait for this to be available in A cluster
6806 checkSubInterest(t, a1, "A", subject, time.Second)
6807 checkSubInterest(t, a2, "A", subject, time.Second)
6808
6809 pb := natsConnect(t, pubSrv.ClientURL(), nats.UserInfo("usera", "usera"))
6810 defer pb.Close()
6811
6812 natsPub(t, pb, subject, []byte("msg"))
6813 natsNexMsg(t, sub, time.Second)
6814 // Should be only 1
6815 if msg, err := sub.NextMsg(100 * time.Millisecond); err == nil {
6816 t.Fatalf("Received duplicate on %q: %s", msg.Subject, msg.Data)
6817 }
6818 }
6819 t.Run("sub_b1_pub_a1", func(t *testing.T) { check(t, b1, a1) })
6820 t.Run("sub_b1_pub_a2", func(t *testing.T) { check(t, b1, a2) })
6821 t.Run("sub_b2_pub_a1", func(t *testing.T) { check(t, b2, a1) })
6822 t.Run("sub_b2_pub_a2", func(t *testing.T) { check(t, b2, a2) })
6823 }
6824
6825 func TestLeafNodeTLSHandshakeFirstVerifyNoInfoSent(t *testing.T) {
6826 confHub := createConfFile(t, []byte(`
6827 port : -1
6828 leafnodes : {
6829 port : -1
6830 tls {
6831 cert_file: "../test/configs/certs/server-cert.pem"
6832 key_file: "../test/configs/certs/server-key.pem"
6833 ca_file: "../test/configs/certs/ca.pem"
6834 timeout: 2
6835 handshake_first: true
6836 }
6837 }
6838 `))
6839 s1, o1 := RunServerWithConfig(confHub)
6840 defer s1.Shutdown()
6841
6842 c, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", o1.LeafNode.Port), 2*time.Second)
6843 require_NoError(t, err)
6844 defer c.Close()
6845
6846 buf := make([]byte, 1024)
6847 // We will wait for up to 500ms to see if the server is sending (incorrectly)
6848 // the INFO.
6849 c.SetReadDeadline(time.Now().Add(500 * time.Millisecond))
6850 n, err := c.Read(buf)
6851 c.SetReadDeadline(time.Time{})
6852 // If we did not get an error, this is an issue...
6853 if err == nil {
6854 t.Fatalf("Should not have received anything, got n=%v buf=%s", n, buf[:n])
6855 }
6856 // We expect a timeout error
6857 if ne, ok := err.(net.Error); !ok || !ne.Timeout() {
6858 t.Fatalf("Expected a timeout error, got %v", err)
6859 }
6860 }
6861
6862 func TestLeafNodeTLSHandshakeFirstFallbackDelayConfigValues(t *testing.T) {
6863 tmpl := `
6864 listen: "127.0.0.1:-1"
6865 leafnodes {
6866 listen: "127.0.0.1:-1"
6867 tls {
6868 cert_file: "../test/configs/certs/server-cert.pem"
6869 key_file: "../test/configs/certs/server-key.pem"
6870 timeout: 1
6871 first: %s
6872 }
6873 }
6874 `
6875 for _, test := range []struct {
6876 name string
6877 val string
6878 first bool
6879 delay time.Duration
6880 }{
6881 {"first as boolean true", "true", true, 0},
6882 {"first as boolean false", "false", false, 0},
6883 {"first as string true", "\"true\"", true, 0},
6884 {"first as string false", "\"false\"", false, 0},
6885 {"first as string on", "on", true, 0},
6886 {"first as string off", "off", false, 0},
6887 {"first as string auto", "auto", true, DEFAULT_TLS_HANDSHAKE_FIRST_FALLBACK_DELAY},
6888 {"first as string auto_fallback", "auto_fallback", true, DEFAULT_TLS_HANDSHAKE_FIRST_FALLBACK_DELAY},
6889 {"first as fallback duration", "300ms", true, 300 * time.Millisecond},
6890 } {
6891 t.Run(test.name, func(t *testing.T) {
6892 conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, test.val)))
6893 s, o := RunServerWithConfig(conf)
6894 defer s.Shutdown()
6895
6896 if test.first {
6897 if !o.LeafNode.TLSHandshakeFirst {
6898 t.Fatal("Expected tls first to be true, was not")
6899 }
6900 if test.delay != o.LeafNode.TLSHandshakeFirstFallback {
6901 t.Fatalf("Expected fallback delay to be %v, got %v", test.delay, o.LeafNode.TLSHandshakeFirstFallback)
6902 }
6903 } else {
6904 if o.LeafNode.TLSHandshakeFirst {
6905 t.Fatal("Expected tls first to be false, was not")
6906 }
6907 if o.LeafNode.TLSHandshakeFirstFallback != 0 {
6908 t.Fatalf("Expected fallback delay to be 0, got %v", o.LeafNode.TLSHandshakeFirstFallback)
6909 }
6910 }
6911 })
6912 }
6913 }
6914
6915 func TestLeafNodeTLSHandshakeFirst(t *testing.T) {
6916 tmpl1 := `
6917 port : -1
6918 leafnodes : {
6919 port : -1
6920 tls {
6921 cert_file: "../test/configs/certs/server-cert.pem"
6922 key_file: "../test/configs/certs/server-key.pem"
6923 ca_file: "../test/configs/certs/ca.pem"
6924 timeout: 2
6925 handshake_first: %s
6926 }
6927 }
6928 `
6929 confHub := createConfFile(t, []byte(fmt.Sprintf(tmpl1, "true")))
6930 s1, o1 := RunServerWithConfig(confHub)
6931 defer s1.Shutdown()
6932
6933 tmpl2 := `
6934 port: -1
6935 leafnodes : {
6936 port : -1
6937 remotes : [
6938 {
6939 urls : [tls://127.0.0.1:%d]
6940 tls {
6941 cert_file: "../test/configs/certs/client-cert.pem"
6942 key_file: "../test/configs/certs/client-key.pem"
6943 ca_file: "../test/configs/certs/ca.pem"
6944 timeout: 2
6945 first: %s
6946 }
6947 }
6948 ]
6949 }
6950 `
6951 confSpoke := createConfFile(t, []byte(fmt.Sprintf(tmpl2, o1.LeafNode.Port, "true")))
6952 s2, _ := RunServerWithConfig(confSpoke)
6953 defer s2.Shutdown()
6954
6955 checkLeafNodeConnected(t, s2)
6956
6957 s2.Shutdown()
6958
6959 // Now check that there will be a failure if the remote does not ask for
6960 // handshake first since the hub is configured that way.
6961 // Set a logger on s1 to capture errors
6962 l := &captureErrorLogger{errCh: make(chan string, 10)}
6963 s1.SetLogger(l, false, false)
6964
6965 confSpoke = createConfFile(t, []byte(fmt.Sprintf(tmpl2, o1.LeafNode.Port, "false")))
6966 s2, _ = RunServerWithConfig(confSpoke)
6967 defer s2.Shutdown()
6968
6969 select {
6970 case err := <-l.errCh:
6971 if !strings.Contains(err, "handshake error") {
6972 t.Fatalf("Unexpected error: %v", err)
6973 }
6974 case <-time.After(2 * time.Second):
6975 t.Fatal("Did not get TLS handshake failure")
6976 }
6977
6978 // Check configuration reload for this remote
6979 reloadUpdateConfig(t, s2, confSpoke, fmt.Sprintf(tmpl2, o1.LeafNode.Port, "true"))
6980 checkLeafNodeConnected(t, s2)
6981 s2.Shutdown()
6982
6983 // Drain the logger error channel
6984 for done := false; !done; {
6985 select {
6986 case <-l.errCh:
6987 default:
6988 done = true
6989 }
6990 }
6991
6992 // Now change the config on the hub
6993 reloadUpdateConfig(t, s1, confHub, fmt.Sprintf(tmpl1, "false"))
6994 // Restart s2
6995 s2, _ = RunServerWithConfig(confSpoke)
6996 defer s2.Shutdown()
6997
6998 select {
6999 case err := <-l.errCh:
7000 if !strings.Contains(err, "handshake error") {
7001 t.Fatalf("Unexpected error: %v", err)
7002 }
7003 case <-time.After(2 * time.Second):
7004 t.Fatal("Did not get TLS handshake failure")
7005 }
7006
7007 // Reload again with "true"
7008 reloadUpdateConfig(t, s1, confHub, fmt.Sprintf(tmpl1, "true"))
7009 checkLeafNodeConnected(t, s2)
7010
7011 // Shutdown the remote
7012 s2.Shutdown()
7013
7014 // Reload the hub with handshake_first with a duration
7015 reloadUpdateConfig(t, s1, confHub, fmt.Sprintf(tmpl1, `"250ms"`))
7016
7017 // Now start s2 with a remote that does not use handshake_first (set to false)
7018 confSpoke = createConfFile(t, []byte(fmt.Sprintf(tmpl2, o1.LeafNode.Port, "false")))
7019 s2, _ = RunServerWithConfig(confSpoke)
7020 defer s2.Shutdown()
7021 checkLeafNodeConnected(t, s2)
7022 }
7023
7024 func TestLeafNodeTLSHandshakeEvenForRemoteWithNoTLSBlock(t *testing.T) {
7025 confHub := createConfFile(t, []byte(`
7026 port : -1
7027 leafnodes : {
7028 port : -1
7029 tls {
7030 cert_file: "../test/configs/certs/server-cert.pem"
7031 key_file: "../test/configs/certs/server-key.pem"
7032 ca_file: "../test/configs/certs/ca.pem"
7033 timeout: 2
7034 }
7035 }
7036 `))
7037 s1, o1 := RunServerWithConfig(confHub)
7038 defer s1.Shutdown()
7039
7040 tmpl2 := `
7041 port: -1
7042 leafnodes : {
7043 port : -1
7044 remotes : [
7045 {
7046 urls : [tls://127.0.0.1:%d]
7047 }
7048 ]
7049 }
7050 `
7051 confSpoke := createConfFile(t, []byte(fmt.Sprintf(tmpl2, o1.LeafNode.Port)))
7052 s2, _ := RunServerWithConfig(confSpoke)
7053 defer s2.Shutdown()
7054
7055 l := &captureDebugLogger{dbgCh: make(chan string, 100)}
7056 s2.SetLogger(l, true, false)
7057
7058 tm := time.NewTimer(2 * time.Second)
7059 defer tm.Stop()
7060 for {
7061 select {
7062 case l := <-l.dbgCh:
7063 if strings.Contains(l, "Starting TLS") {
7064 // OK!
7065 return
7066 }
7067 case <-tm.C:
7068 t.Fatalf("Did not perform a TLS handshake")
7069 }
7070 }
7071 }
7072
7073 func TestLeafNodeCompressionOptions(t *testing.T) {
7074 org := testDefaultLeafNodeCompression
7075 testDefaultLeafNodeCompression = _EMPTY_
7076 defer func() { testDefaultLeafNodeCompression = org }()
7077
7078 tmpl := `
7079 port: -1
7080 leafnodes {
7081 port: -1
7082 compression: %s
7083 }
7084 `
7085 for _, test := range []struct {
7086 name string
7087 mode string
7088 rttVals []int
7089 expected string
7090 rtts []time.Duration
7091 }{
7092 {"boolean enabled", "true", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7093 {"string enabled", "enabled", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7094 {"string EnaBled", "EnaBled", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7095 {"string on", "on", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7096 {"string ON", "ON", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7097 {"string fast", "fast", nil, CompressionS2Fast, nil},
7098 {"string Fast", "Fast", nil, CompressionS2Fast, nil},
7099 {"string s2_fast", "s2_fast", nil, CompressionS2Fast, nil},
7100 {"string s2_Fast", "s2_Fast", nil, CompressionS2Fast, nil},
7101 {"boolean disabled", "false", nil, CompressionOff, nil},
7102 {"string disabled", "disabled", nil, CompressionOff, nil},
7103 {"string DisableD", "DisableD", nil, CompressionOff, nil},
7104 {"string off", "off", nil, CompressionOff, nil},
7105 {"string OFF", "OFF", nil, CompressionOff, nil},
7106 {"better", "better", nil, CompressionS2Better, nil},
7107 {"Better", "Better", nil, CompressionS2Better, nil},
7108 {"s2_better", "s2_better", nil, CompressionS2Better, nil},
7109 {"S2_BETTER", "S2_BETTER", nil, CompressionS2Better, nil},
7110 {"best", "best", nil, CompressionS2Best, nil},
7111 {"BEST", "BEST", nil, CompressionS2Best, nil},
7112 {"s2_best", "s2_best", nil, CompressionS2Best, nil},
7113 {"S2_BEST", "S2_BEST", nil, CompressionS2Best, nil},
7114 {"auto no rtts", "auto", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7115 {"s2_auto no rtts", "s2_auto", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7116 {"auto", "{mode: auto, rtt_thresholds: [%s]}", []int{1}, CompressionS2Auto, []time.Duration{time.Millisecond}},
7117 {"Auto", "{Mode: Auto, thresholds: [%s]}", []int{1, 2}, CompressionS2Auto, []time.Duration{time.Millisecond, 2 * time.Millisecond}},
7118 {"s2_auto", "{mode: s2_auto, thresholds: [%s]}", []int{1, 2, 3}, CompressionS2Auto, []time.Duration{time.Millisecond, 2 * time.Millisecond, 3 * time.Millisecond}},
7119 {"s2_AUTO", "{mode: s2_AUTO, thresholds: [%s]}", []int{1, 2, 3, 4}, CompressionS2Auto, []time.Duration{time.Millisecond, 2 * time.Millisecond, 3 * time.Millisecond, 4 * time.Millisecond}},
7120 {"s2_auto:-10,5,10", "{mode: s2_auto, thresholds: [%s]}", []int{-10, 5, 10}, CompressionS2Auto, []time.Duration{0, 5 * time.Millisecond, 10 * time.Millisecond}},
7121 {"s2_auto:5,10,15", "{mode: s2_auto, thresholds: [%s]}", []int{5, 10, 15}, CompressionS2Auto, []time.Duration{5 * time.Millisecond, 10 * time.Millisecond, 15 * time.Millisecond}},
7122 {"s2_auto:0,5,10", "{mode: s2_auto, thresholds: [%s]}", []int{0, 5, 10}, CompressionS2Auto, []time.Duration{0, 5 * time.Millisecond, 10 * time.Millisecond}},
7123 {"s2_auto:5,10,0,20", "{mode: s2_auto, thresholds: [%s]}", []int{5, 10, 0, 20}, CompressionS2Auto, []time.Duration{5 * time.Millisecond, 10 * time.Millisecond, 0, 20 * time.Millisecond}},
7124 {"s2_auto:0,10,0,20", "{mode: s2_auto, thresholds: [%s]}", []int{0, 10, 0, 20}, CompressionS2Auto, []time.Duration{0, 10 * time.Millisecond, 0, 20 * time.Millisecond}},
7125 {"s2_auto:0,0,0,20", "{mode: s2_auto, thresholds: [%s]}", []int{0, 0, 0, 20}, CompressionS2Auto, []time.Duration{0, 0, 0, 20 * time.Millisecond}},
7126 {"s2_auto:0,10,0,0", "{mode: s2_auto, rtt_thresholds: [%s]}", []int{0, 10, 0, 0}, CompressionS2Auto, []time.Duration{0, 10 * time.Millisecond}},
7127 } {
7128 t.Run(test.name, func(t *testing.T) {
7129 var val string
7130 if len(test.rttVals) > 0 {
7131 var rtts string
7132 for i, v := range test.rttVals {
7133 if i > 0 {
7134 rtts += ", "
7135 }
7136 rtts += fmt.Sprintf("%dms", v)
7137 }
7138 val = fmt.Sprintf(test.mode, rtts)
7139 } else {
7140 val = test.mode
7141 }
7142 conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, val)))
7143 s, o := RunServerWithConfig(conf)
7144 defer s.Shutdown()
7145
7146 if cm := o.LeafNode.Compression.Mode; cm != test.expected {
7147 t.Fatalf("Expected compression value to be %q, got %q", test.expected, cm)
7148 }
7149 if !reflect.DeepEqual(test.rtts, o.LeafNode.Compression.RTTThresholds) {
7150 t.Fatalf("Expected RTT tresholds to be %+v, got %+v", test.rtts, o.LeafNode.Compression.RTTThresholds)
7151 }
7152 port := s.getOpts().Port
7153 leafNodePort := s.getOpts().LeafNode.Port
7154 s.Shutdown()
7155
7156 o.Port = port
7157 o.LeafNode.Port = leafNodePort
7158 o.LeafNode.Compression.Mode = test.mode
7159 if len(test.rttVals) > 0 {
7160 o.LeafNode.Compression.Mode = CompressionS2Auto
7161 o.LeafNode.Compression.RTTThresholds = o.LeafNode.Compression.RTTThresholds[:0]
7162 for _, v := range test.rttVals {
7163 o.LeafNode.Compression.RTTThresholds = append(o.LeafNode.Compression.RTTThresholds, time.Duration(v)*time.Millisecond)
7164 }
7165 }
7166 s = RunServer(o)
7167 defer s.Shutdown()
7168 if cm := o.LeafNode.Compression.Mode; cm != test.expected {
7169 t.Fatalf("Expected compression value to be %q, got %q", test.expected, cm)
7170 }
7171 if !reflect.DeepEqual(test.rtts, o.LeafNode.Compression.RTTThresholds) {
7172 t.Fatalf("Expected RTT tresholds to be %+v, got %+v", test.rtts, o.LeafNode.Compression.RTTThresholds)
7173 }
7174 })
7175 }
7176
7177 // Same, but with remotes
7178 tmpl = `
7179 port: -1
7180 leafnodes {
7181 port: -1
7182 remotes [
7183 {
7184 url: "nats://127.0.0.1:1234"
7185 compression: %s
7186 }
7187 ]
7188 }
7189 `
7190 for _, test := range []struct {
7191 name string
7192 mode string
7193 rttVals []int
7194 expected string
7195 rtts []time.Duration
7196 }{
7197 {"boolean enabled", "true", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7198 {"string enabled", "enabled", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7199 {"string EnaBled", "EnaBled", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7200 {"string on", "on", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7201 {"string ON", "ON", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7202 {"string fast", "fast", nil, CompressionS2Fast, nil},
7203 {"string Fast", "Fast", nil, CompressionS2Fast, nil},
7204 {"string s2_fast", "s2_fast", nil, CompressionS2Fast, nil},
7205 {"string s2_Fast", "s2_Fast", nil, CompressionS2Fast, nil},
7206 {"boolean disabled", "false", nil, CompressionOff, nil},
7207 {"string disabled", "disabled", nil, CompressionOff, nil},
7208 {"string DisableD", "DisableD", nil, CompressionOff, nil},
7209 {"string off", "off", nil, CompressionOff, nil},
7210 {"string OFF", "OFF", nil, CompressionOff, nil},
7211 {"better", "better", nil, CompressionS2Better, nil},
7212 {"Better", "Better", nil, CompressionS2Better, nil},
7213 {"s2_better", "s2_better", nil, CompressionS2Better, nil},
7214 {"S2_BETTER", "S2_BETTER", nil, CompressionS2Better, nil},
7215 {"best", "best", nil, CompressionS2Best, nil},
7216 {"BEST", "BEST", nil, CompressionS2Best, nil},
7217 {"s2_best", "s2_best", nil, CompressionS2Best, nil},
7218 {"S2_BEST", "S2_BEST", nil, CompressionS2Best, nil},
7219 {"auto no rtts", "auto", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7220 {"s2_auto no rtts", "s2_auto", nil, CompressionS2Auto, defaultCompressionS2AutoRTTThresholds},
7221 {"auto", "{mode: auto, rtt_thresholds: [%s]}", []int{1}, CompressionS2Auto, []time.Duration{time.Millisecond}},
7222 {"Auto", "{Mode: Auto, thresholds: [%s]}", []int{1, 2}, CompressionS2Auto, []time.Duration{time.Millisecond, 2 * time.Millisecond}},
7223 {"s2_auto", "{mode: s2_auto, thresholds: [%s]}", []int{1, 2, 3}, CompressionS2Auto, []time.Duration{time.Millisecond, 2 * time.Millisecond, 3 * time.Millisecond}},
7224 {"s2_AUTO", "{mode: s2_AUTO, thresholds: [%s]}", []int{1, 2, 3, 4}, CompressionS2Auto, []time.Duration{time.Millisecond, 2 * time.Millisecond, 3 * time.Millisecond, 4 * time.Millisecond}},
7225 {"s2_auto:-10,5,10", "{mode: s2_auto, thresholds: [%s]}", []int{-10, 5, 10}, CompressionS2Auto, []time.Duration{0, 5 * time.Millisecond, 10 * time.Millisecond}},
7226 {"s2_auto:5,10,15", "{mode: s2_auto, thresholds: [%s]}", []int{5, 10, 15}, CompressionS2Auto, []time.Duration{5 * time.Millisecond, 10 * time.Millisecond, 15 * time.Millisecond}},
7227 {"s2_auto:0,5,10", "{mode: s2_auto, thresholds: [%s]}", []int{0, 5, 10}, CompressionS2Auto, []time.Duration{0, 5 * time.Millisecond, 10 * time.Millisecond}},
7228 {"s2_auto:5,10,0,20", "{mode: s2_auto, thresholds: [%s]}", []int{5, 10, 0, 20}, CompressionS2Auto, []time.Duration{5 * time.Millisecond, 10 * time.Millisecond, 0, 20 * time.Millisecond}},
7229 {"s2_auto:0,10,0,20", "{mode: s2_auto, thresholds: [%s]}", []int{0, 10, 0, 20}, CompressionS2Auto, []time.Duration{0, 10 * time.Millisecond, 0, 20 * time.Millisecond}},
7230 {"s2_auto:0,0,0,20", "{mode: s2_auto, thresholds: [%s]}", []int{0, 0, 0, 20}, CompressionS2Auto, []time.Duration{0, 0, 0, 20 * time.Millisecond}},
7231 {"s2_auto:0,10,0,0", "{mode: s2_auto, rtt_thresholds: [%s]}", []int{0, 10, 0, 0}, CompressionS2Auto, []time.Duration{0, 10 * time.Millisecond}},
7232 } {
7233 t.Run("remote leaf "+test.name, func(t *testing.T) {
7234 var val string
7235 if len(test.rttVals) > 0 {
7236 var rtts string
7237 for i, v := range test.rttVals {
7238 if i > 0 {
7239 rtts += ", "
7240 }
7241 rtts += fmt.Sprintf("%dms", v)
7242 }
7243 val = fmt.Sprintf(test.mode, rtts)
7244 } else {
7245 val = test.mode
7246 }
7247 conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, val)))
7248 s, o := RunServerWithConfig(conf)
7249 defer s.Shutdown()
7250
7251 r := o.LeafNode.Remotes[0]
7252
7253 if cm := r.Compression.Mode; cm != test.expected {
7254 t.Fatalf("Expected compression value to be %q, got %q", test.expected, cm)
7255 }
7256 if !reflect.DeepEqual(test.rtts, r.Compression.RTTThresholds) {
7257 t.Fatalf("Expected RTT tresholds to be %+v, got %+v", test.rtts, r.Compression.RTTThresholds)
7258 }
7259 port := s.getOpts().Port
7260 leafNodePort := s.getOpts().LeafNode.Port
7261 s.Shutdown()
7262
7263 o.Port = port
7264 o.LeafNode.Port = leafNodePort
7265 o.LeafNode.Remotes[0].Compression.Mode = test.mode
7266 if len(test.rttVals) > 0 {
7267 o.LeafNode.Remotes[0].Compression.Mode = CompressionS2Auto
7268 o.LeafNode.Remotes[0].Compression.RTTThresholds = o.LeafNode.Remotes[0].Compression.RTTThresholds[:0]
7269 for _, v := range test.rttVals {
7270 o.LeafNode.Remotes[0].Compression.RTTThresholds = append(o.LeafNode.Remotes[0].Compression.RTTThresholds, time.Duration(v)*time.Millisecond)
7271 }
7272 }
7273 s = RunServer(o)
7274 defer s.Shutdown()
7275 if cm := o.LeafNode.Remotes[0].Compression.Mode; cm != test.expected {
7276 t.Fatalf("Expected compression value to be %q, got %q", test.expected, cm)
7277 }
7278 if !reflect.DeepEqual(test.rtts, o.LeafNode.Remotes[0].Compression.RTTThresholds) {
7279 t.Fatalf("Expected RTT tresholds to be %+v, got %+v", test.rtts, o.LeafNode.Remotes[0].Compression.RTTThresholds)
7280 }
7281 })
7282 }
7283
7284 // Test that with no compression specified, we default to "s2_auto"
7285 conf := createConfFile(t, []byte(`
7286 port: -1
7287 leafnodes {
7288 port: -1
7289 }
7290 `))
7291 s, o := RunServerWithConfig(conf)
7292 defer s.Shutdown()
7293 if o.LeafNode.Compression.Mode != CompressionS2Auto {
7294 t.Fatalf("Expected compression value to be %q, got %q", CompressionAccept, o.LeafNode.Compression.Mode)
7295 }
7296 if !reflect.DeepEqual(defaultCompressionS2AutoRTTThresholds, o.LeafNode.Compression.RTTThresholds) {
7297 t.Fatalf("Expected RTT tresholds to be %+v, got %+v", defaultCompressionS2AutoRTTThresholds, o.LeafNode.Compression.RTTThresholds)
7298 }
7299 // Same for remotes
7300 conf = createConfFile(t, []byte(`
7301 port: -1
7302 leafnodes {
7303 port: -1
7304 remotes [ { url: "nats://127.0.0.1:1234" } ]
7305 }
7306 `))
7307 s, o = RunServerWithConfig(conf)
7308 defer s.Shutdown()
7309 if cm := o.LeafNode.Remotes[0].Compression.Mode; cm != CompressionS2Auto {
7310 t.Fatalf("Expected compression value to be %q, got %q", CompressionAccept, cm)
7311 }
7312 if !reflect.DeepEqual(defaultCompressionS2AutoRTTThresholds, o.LeafNode.Remotes[0].Compression.RTTThresholds) {
7313 t.Fatalf("Expected RTT tresholds to be %+v, got %+v", defaultCompressionS2AutoRTTThresholds, o.LeafNode.Remotes[0].Compression.RTTThresholds)
7314 }
7315 for _, test := range []struct {
7316 name string
7317 mode string
7318 rtts []time.Duration
7319 err string
7320 }{
7321 {"unsupported mode", "gzip", nil, "unsupported"},
7322 {"not ascending order", "s2_auto", []time.Duration{
7323 5 * time.Millisecond,
7324 10 * time.Millisecond,
7325 2 * time.Millisecond,
7326 }, "ascending"},
7327 {"too many thresholds", "s2_auto", []time.Duration{
7328 5 * time.Millisecond,
7329 10 * time.Millisecond,
7330 20 * time.Millisecond,
7331 40 * time.Millisecond,
7332 60 * time.Millisecond,
7333 }, "more than 4"},
7334 {"all 0", "s2_auto", []time.Duration{0, 0, 0, 0}, "at least one"},
7335 {"single 0", "s2_auto", []time.Duration{0}, "at least one"},
7336 } {
7337 t.Run(test.name, func(t *testing.T) {
7338 o := DefaultOptions()
7339 o.LeafNode.Port = -1
7340 o.LeafNode.Compression = CompressionOpts{test.mode, test.rtts}
7341 if _, err := NewServer(o); err == nil || !strings.Contains(err.Error(), test.err) {
7342 t.Fatalf("Unexpected error: %v", err)
7343 }
7344 // Same with remotes
7345 o.LeafNode.Compression = CompressionOpts{}
7346 o.LeafNode.Remotes = []*RemoteLeafOpts{{Compression: CompressionOpts{test.mode, test.rtts}}}
7347 if _, err := NewServer(o); err == nil || !strings.Contains(err.Error(), test.err) {
7348 t.Fatalf("Unexpected error: %v", err)
7349 }
7350 })
7351 }
7352 }
7353
7354 func TestLeafNodeCompression(t *testing.T) {
7355 conf1 := createConfFile(t, []byte(`
7356 port: -1
7357 server_name: "Hub"
7358 accounts {
7359 A { users: [{user: a, password: pwd}] }
7360 B { users: [{user: b, password: pwd}] }
7361 C { users: [{user: c, password: pwd}] }
7362 }
7363 leafnodes {
7364 port: -1
7365 compression: s2_fast
7366 }
7367 `))
7368 s1, o1 := RunServerWithConfig(conf1)
7369 defer s1.Shutdown()
7370
7371 port := o1.LeafNode.Port
7372 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
7373 port: -1
7374 server_name: "Spoke"
7375 accounts {
7376 A { users: [{user: a, password: pwd}] }
7377 B { users: [{user: b, password: pwd}] }
7378 C { users: [{user: c, password: pwd}] }
7379 }
7380 leafnodes {
7381 remotes [
7382 { url: "nats://a:[email protected]:%d", account: "A", compression: s2_better }
7383 { url: "nats://b:[email protected]:%d", account: "B", compression: s2_best }
7384 { url: "nats://c:[email protected]:%d", account: "C", compression: off }
7385 ]
7386 }
7387 `, port, port, port)))
7388 s2, _ := RunServerWithConfig(conf2)
7389 defer s2.Shutdown()
7390
7391 checkLeafNodeConnectedCount(t, s1, 3)
7392 checkLeafNodeConnectedCount(t, s2, 3)
7393
7394 s1.mu.RLock()
7395 for _, l := range s1.leafs {
7396 l.mu.Lock()
7397 l.nc = &testConnSentBytes{Conn: l.nc}
7398 l.mu.Unlock()
7399 }
7400 s1.mu.RUnlock()
7401
7402 var payloads [][]byte
7403 totalPayloadSize := 0
7404 count := 26
7405 for i := 0; i < count; i++ {
7406 n := rand.Intn(2048) + 1
7407 p := make([]byte, n)
7408 for j := 0; j < n; j++ {
7409 p[j] = byte(i) + 'A'
7410 }
7411 totalPayloadSize += len(p)
7412 payloads = append(payloads, p)
7413 }
7414
7415 check := func(acc, user, subj string) {
7416 t.Helper()
7417 nc2 := natsConnect(t, s2.ClientURL(), nats.UserInfo(user, "pwd"))
7418 defer nc2.Close()
7419 sub := natsSubSync(t, nc2, subj)
7420 natsFlush(t, nc2)
7421 checkSubInterest(t, s1, acc, subj, time.Second)
7422
7423 nc1 := natsConnect(t, s1.ClientURL(), nats.UserInfo(user, "pwd"))
7424 defer nc1.Close()
7425
7426 for i := 0; i < count; i++ {
7427 natsPub(t, nc1, subj, payloads[i])
7428 }
7429 for i := 0; i < count; i++ {
7430 m := natsNexMsg(t, sub, time.Second)
7431 if !bytes.Equal(m.Data, payloads[i]) {
7432 t.Fatalf("Expected payload %q - got %q", payloads[i], m.Data)
7433 }
7434 }
7435
7436 // Also check that the leafnode stats shows that compression likely occurred
7437 var out int
7438 s1.mu.RLock()
7439 for _, l := range s1.leafs {
7440 l.mu.Lock()
7441 if l.acc.Name == acc && l.nc != nil {
7442 nc := l.nc.(*testConnSentBytes)
7443 nc.Lock()
7444 out = nc.sent
7445 nc.sent = 0
7446 nc.Unlock()
7447 }
7448 l.mu.Unlock()
7449 }
7450 s1.mu.RUnlock()
7451 // Except for account "C", where compression should be off,
7452 // "out" should at least be smaller than totalPayloadSize, use 20%.
7453 if acc == "C" {
7454 if int(out) < totalPayloadSize {
7455 t.Fatalf("Expected s1's sent bytes to be at least payload size (%v), got %v", totalPayloadSize, out)
7456 }
7457 } else {
7458 limit := totalPayloadSize * 80 / 100
7459 if int(out) > limit {
7460 t.Fatalf("Expected s1's sent bytes to be less than %v, got %v (total payload was %v)", limit, out, totalPayloadSize)
7461 }
7462 }
7463 }
7464 check("A", "a", "foo")
7465 check("B", "b", "bar")
7466 check("C", "c", "baz")
7467
7468 // Check compression settings. S1 should always be s2_fast, except for account "C"
7469 // since "C" wanted compression "off"
7470 l, err := s1.Leafz(nil)
7471 require_NoError(t, err)
7472 for _, r := range l.Leafs {
7473 switch r.Account {
7474 case "C":
7475 if r.Compression != CompressionOff {
7476 t.Fatalf("Expected compression of remote for C account to be %q, got %q", CompressionOff, r.Compression)
7477 }
7478 default:
7479 if r.Compression != CompressionS2Fast {
7480 t.Fatalf("Expected compression of remote for %s account to be %q, got %q", r.Account, CompressionS2Fast, r.Compression)
7481 }
7482 }
7483 }
7484
7485 l, err = s2.Leafz(nil)
7486 require_NoError(t, err)
7487 for _, r := range l.Leafs {
7488 switch r.Account {
7489 case "A":
7490 if r.Compression != CompressionS2Better {
7491 t.Fatalf("Expected compression for A account to be %q, got %q", CompressionS2Better, r.Compression)
7492 }
7493 case "B":
7494 if r.Compression != CompressionS2Best {
7495 t.Fatalf("Expected compression for B account to be %q, got %q", CompressionS2Best, r.Compression)
7496 }
7497 case "C":
7498 if r.Compression != CompressionOff {
7499 t.Fatalf("Expected compression for C account to be %q, got %q", CompressionOff, r.Compression)
7500 }
7501 }
7502 }
7503 }
7504
7505 func BenchmarkLeafNodeCompression(b *testing.B) {
7506 conf1 := createConfFile(b, []byte(`
7507 port: -1
7508 server_name: "Hub"
7509 accounts {
7510 A { users: [{user: a, password: pwd}] }
7511 B { users: [{user: b, password: pwd}] }
7512 C { users: [{user: c, password: pwd}] }
7513 D { users: [{user: d, password: pwd}] }
7514 }
7515 leafnodes {
7516 port: -1
7517 }
7518 `))
7519 s1, o1 := RunServerWithConfig(conf1)
7520 defer s1.Shutdown()
7521
7522 port := o1.LeafNode.Port
7523 conf2 := createConfFile(b, []byte(fmt.Sprintf(`
7524 port: -1
7525 server_name: "Spoke"
7526 accounts {
7527 A { users: [{user: a, password: pwd}] }
7528 B { users: [{user: b, password: pwd}] }
7529 C { users: [{user: c, password: pwd}] }
7530 D { users: [{user: d, password: pwd}] }
7531 }
7532 leafnodes {
7533 remotes [
7534 { url: "nats://a:[email protected]:%d", account: "A", compression: s2_better }
7535 { url: "nats://b:[email protected]:%d", account: "B", compression: s2_best }
7536 { url: "nats://c:[email protected]:%d", account: "C", compression: s2_fast }
7537 { url: "nats://d:[email protected]:%d", account: "D", compression: off }
7538 ]
7539 }
7540 `, port, port, port, port)))
7541 s2, _ := RunServerWithConfig(conf2)
7542 defer s2.Shutdown()
7543
7544 checkLeafNodeConnectedCount(b, s1, 4)
7545 checkLeafNodeConnectedCount(b, s2, 4)
7546
7547 l, err := s2.Leafz(nil)
7548 require_NoError(b, err)
7549 for _, r := range l.Leafs {
7550 switch {
7551 case r.Account == "A" && r.Compression == CompressionS2Better:
7552 case r.Account == "B" && r.Compression == CompressionS2Best:
7553 case r.Account == "C" && r.Compression == CompressionS2Fast:
7554 case r.Account == "D" && r.Compression == CompressionOff:
7555 default:
7556 b.Fatalf("Account %q had incorrect compression mode %q on leaf connection", r.Account, r.Compression)
7557 }
7558 }
7559
7560 msg := make([]byte, 1024)
7561 for _, p := range []struct {
7562 algo string
7563 user string
7564 }{
7565 {"Better", "a"},
7566 {"Best", "b"},
7567 {"Fast", "c"},
7568 {"Off", "d"},
7569 } {
7570 nc1 := natsConnect(b, s1.ClientURL(), nats.UserInfo(p.user, "pwd"))
7571 nc2 := natsConnect(b, s2.ClientURL(), nats.UserInfo(p.user, "pwd"))
7572
7573 sub, err := nc1.SubscribeSync("foo")
7574 require_NoError(b, err)
7575
7576 time.Sleep(time.Second)
7577
7578 b.Run(p.algo, func(b *testing.B) {
7579 start := time.Now()
7580
7581 for i := 0; i < b.N; i++ {
7582 err = nc2.Publish("foo", msg)
7583 require_NoError(b, err)
7584
7585 _, err = sub.NextMsg(time.Second)
7586 require_NoError(b, err)
7587 }
7588
7589 b.ReportMetric(float64(len(msg)*b.N)/1024/1024, "MB")
7590 b.ReportMetric(float64(len(msg)*b.N)/1024/1024/float64(time.Since(start).Seconds()), "MB/sec")
7591 })
7592
7593 nc1.Close()
7594 nc2.Close()
7595 }
7596 }
7597
7598 func TestLeafNodeCompressionMatrixModes(t *testing.T) {
7599 for _, test := range []struct {
7600 name string
7601 s1 string
7602 s2 string
7603 s1Expected string
7604 s2Expected string
7605 }{
7606 {"off off", "off", "off", CompressionOff, CompressionOff},
7607 {"off accept", "off", "accept", CompressionOff, CompressionOff},
7608 {"off on", "off", "on", CompressionOff, CompressionOff},
7609 {"off better", "off", "better", CompressionOff, CompressionOff},
7610 {"off best", "off", "best", CompressionOff, CompressionOff},
7611
7612 {"accept off", "accept", "off", CompressionOff, CompressionOff},
7613 {"accept accept", "accept", "accept", CompressionOff, CompressionOff},
7614 // Note: "on", means s2_auto, which will mean uncompressed since RTT is low.
7615 {"accept on", "accept", "on", CompressionS2Fast, CompressionS2Uncompressed},
7616 {"accept better", "accept", "better", CompressionS2Better, CompressionS2Better},
7617 {"accept best", "accept", "best", CompressionS2Best, CompressionS2Best},
7618
7619 {"on off", "on", "off", CompressionOff, CompressionOff},
7620 {"on accept", "on", "accept", CompressionS2Uncompressed, CompressionS2Fast},
7621 {"on on", "on", "on", CompressionS2Uncompressed, CompressionS2Uncompressed},
7622 {"on better", "on", "better", CompressionS2Uncompressed, CompressionS2Better},
7623 {"on best", "on", "best", CompressionS2Uncompressed, CompressionS2Best},
7624
7625 {"better off", "better", "off", CompressionOff, CompressionOff},
7626 {"better accept", "better", "accept", CompressionS2Better, CompressionS2Better},
7627 {"better on", "better", "on", CompressionS2Better, CompressionS2Uncompressed},
7628 {"better better", "better", "better", CompressionS2Better, CompressionS2Better},
7629 {"better best", "better", "best", CompressionS2Better, CompressionS2Best},
7630
7631 {"best off", "best", "off", CompressionOff, CompressionOff},
7632 {"best accept", "best", "accept", CompressionS2Best, CompressionS2Best},
7633 {"best on", "best", "on", CompressionS2Best, CompressionS2Uncompressed},
7634 {"best better", "best", "better", CompressionS2Best, CompressionS2Better},
7635 {"best best", "best", "best", CompressionS2Best, CompressionS2Best},
7636 } {
7637 t.Run(test.name, func(t *testing.T) {
7638 conf1 := createConfFile(t, []byte(fmt.Sprintf(`
7639 port: -1
7640 server_name: "A"
7641 leafnodes {
7642 port: -1
7643 compression: %s
7644 }
7645 `, test.s1)))
7646 s1, o1 := RunServerWithConfig(conf1)
7647 defer s1.Shutdown()
7648
7649 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
7650 port: -1
7651 server_name: "B"
7652 leafnodes {
7653 remotes: [
7654 {url: "nats://127.0.0.1:%d", compression: %s}
7655 ]
7656 }
7657 `, o1.LeafNode.Port, test.s2)))
7658 s2, _ := RunServerWithConfig(conf2)
7659 defer s2.Shutdown()
7660
7661 checkLeafNodeConnected(t, s2)
7662
7663 nc1 := natsConnect(t, s1.ClientURL())
7664 defer nc1.Close()
7665
7666 nc2 := natsConnect(t, s2.ClientURL())
7667 defer nc2.Close()
7668
7669 payload := make([]byte, 128)
7670 check := func(ncp, ncs *nats.Conn, subj string, s *Server) {
7671 t.Helper()
7672 sub := natsSubSync(t, ncs, subj)
7673 checkSubInterest(t, s, globalAccountName, subj, time.Second)
7674 natsPub(t, ncp, subj, payload)
7675 natsNexMsg(t, sub, time.Second)
7676
7677 for _, srv := range []*Server{s1, s2} {
7678 lz, err := srv.Leafz(nil)
7679 require_NoError(t, err)
7680 var expected string
7681 if srv == s1 {
7682 expected = test.s1Expected
7683 } else {
7684 expected = test.s2Expected
7685 }
7686 if cm := lz.Leafs[0].Compression; cm != expected {
7687 t.Fatalf("Server %s - expected compression %q, got %q", srv, expected, cm)
7688 }
7689 }
7690 }
7691 check(nc1, nc2, "foo", s1)
7692 check(nc2, nc1, "bar", s2)
7693 })
7694 }
7695 }
7696
7697 func TestLeafNodeCompressionWithOlderServer(t *testing.T) {
7698 tmpl1 := `
7699 port: -1
7700 server_name: "A"
7701 leafnodes {
7702 port: -1
7703 compression: "%s"
7704 }
7705 `
7706 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl1, CompressionS2Fast)))
7707 s1, o1 := RunServerWithConfig(conf1)
7708 defer s1.Shutdown()
7709
7710 tmpl2 := `
7711 port: -1
7712 server_name: "B"
7713 leafnodes {
7714 remotes [
7715 {url: "nats://127.0.0.1:%d", compression: "%s"}
7716 ]
7717 }
7718 `
7719 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl2, o1.LeafNode.Port, CompressionNotSupported)))
7720 s2, _ := RunServerWithConfig(conf2)
7721 defer s2.Shutdown()
7722
7723 checkLeafNodeConnected(t, s2)
7724
7725 getLeafCompMode := func(s *Server) string {
7726 var cm string
7727 s.mu.RLock()
7728 defer s.mu.RUnlock()
7729 for _, l := range s1.leafs {
7730 l.mu.Lock()
7731 cm = l.leaf.compression
7732 l.mu.Unlock()
7733 return cm
7734 }
7735 return _EMPTY_
7736 }
7737 for _, s := range []*Server{s1, s2} {
7738 if cm := getLeafCompMode(s); cm != CompressionNotSupported {
7739 t.Fatalf("Expected compression not supported, got %q", cm)
7740 }
7741 }
7742
7743 s2.Shutdown()
7744 s1.Shutdown()
7745
7746 conf1 = createConfFile(t, []byte(fmt.Sprintf(tmpl1, CompressionNotSupported)))
7747 s1, o1 = RunServerWithConfig(conf1)
7748 defer s1.Shutdown()
7749
7750 conf2 = createConfFile(t, []byte(fmt.Sprintf(tmpl2, o1.LeafNode.Port, CompressionS2Fast)))
7751 s2, _ = RunServerWithConfig(conf2)
7752 defer s2.Shutdown()
7753
7754 checkLeafNodeConnected(t, s2)
7755 for _, s := range []*Server{s1, s2} {
7756 if cm := getLeafCompMode(s); cm != CompressionNotSupported {
7757 t.Fatalf("Expected compression not supported, got %q", cm)
7758 }
7759 }
7760 }
7761
7762 func TestLeafNodeNoCompressionWithWebsocket(t *testing.T) {
7763 for _, test := range []struct {
7764 name string
7765 acceptWSComp bool
7766 remoteWSComp bool
7767 expectS2 bool
7768 }{
7769 {"both ws compression", true, true, false},
7770 {"only accept ws compression", true, false, true},
7771 {"only remote ws compression", false, true, true},
7772 {"neither ws compression", false, false, true},
7773 } {
7774 t.Run(test.name, func(t *testing.T) {
7775 conf1 := createConfFile(t, []byte(fmt.Sprintf(`
7776 port: -1
7777 server_name: "A"
7778 websocket {
7779 listen: "127.0.0.1:-1"
7780 no_tls: true
7781 compression: %v
7782 }
7783 leafnodes {
7784 port: -1
7785 compression: "s2_fast"
7786 }
7787 `, test.acceptWSComp)))
7788 s1, o1 := RunServerWithConfig(conf1)
7789 defer s1.Shutdown()
7790
7791 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
7792 port: -1
7793 server_name: "B"
7794 leafnodes {
7795 remotes [
7796 {url: "ws://127.0.0.1:%d", ws_compression: %v, compression: "s2_fast"}
7797 ]
7798 }
7799 `, o1.Websocket.Port, test.remoteWSComp)))
7800 s2, _ := RunServerWithConfig(conf2)
7801 defer s2.Shutdown()
7802
7803 checkLeafNodeConnected(t, s2)
7804
7805 getLeafState := func(s *Server) (string, bool) {
7806 var cm string
7807 var wsComp bool
7808 s.mu.RLock()
7809 defer s.mu.RUnlock()
7810 for _, l := range s.leafs {
7811 l.mu.Lock()
7812 cm = l.leaf.compression
7813 if l.ws != nil {
7814 wsComp = l.ws.compress
7815 }
7816 l.mu.Unlock()
7817 return cm, wsComp
7818 }
7819 return _EMPTY_, false
7820 }
7821 expected := CompressionOff
7822 if test.expectS2 {
7823 expected = CompressionS2Fast
7824 }
7825 // WS compression is only actually used when both sides opted in.
7826 wantWSComp := test.acceptWSComp && test.remoteWSComp
7827 for _, s := range []*Server{s1, s2} {
7828 cm, wsComp := getLeafState(s)
7829 if cm != expected {
7830 t.Fatalf("Expected leaf compression to be %q, got %q", expected, cm)
7831 }
7832 if wsComp != wantWSComp {
7833 t.Fatalf("Expected ws.compress to be %v, got %v", wantWSComp, wsComp)
7834 }
7835 }
7836 })
7837 }
7838 }
7839
7840 // Verifies that the initial INFO sent by the accept side over a WS leaf
7841 // connection does not advertise leafnode compression when WS compression is
7842 // negotiated. An older soliciting peer (without the WS-aware patch) would
7843 // honor an advertised mode, switch to S2, and then deadlock waiting for a
7844 // compressed INFO response that we never send.
7845 func TestLeafNodeWSAcceptInitialInfoSuppressesCompression(t *testing.T) {
7846 for _, test := range []struct {
7847 name string
7848 negotiatePMC bool
7849 expectedComp string
7850 }{
7851 {"ws compression negotiated", true, _EMPTY_},
7852 {"ws compression not negotiated", false, CompressionS2Fast},
7853 } {
7854 t.Run(test.name, func(t *testing.T) {
7855 conf := createConfFile(t, []byte(`
7856 port: -1
7857 server_name: "A"
7858 websocket {
7859 listen: "127.0.0.1:-1"
7860 no_tls: true
7861 compression: true
7862 }
7863 leafnodes {
7864 port: -1
7865 compression: "s2_fast"
7866 }
7867 `))
7868 s, o := RunServerWithConfig(conf)
7869 defer s.Shutdown()
7870
7871 addr := fmt.Sprintf("127.0.0.1:%d", o.Websocket.Port)
7872 c, err := net.Dial("tcp", addr)
7873 require_NoError(t, err)
7874 defer c.Close()
7875
7876 wsKey, err := wsMakeChallengeKey()
7877 require_NoError(t, err)
7878
7879 var reqBuf bytes.Buffer
7880 fmt.Fprintf(&reqBuf, "GET %s HTTP/1.1\r\n", leafNodeWSPath)
7881 fmt.Fprintf(&reqBuf, "Host: %s\r\n", addr)
7882 reqBuf.WriteString("Upgrade: websocket\r\n")
7883 reqBuf.WriteString("Connection: Upgrade\r\n")
7884 fmt.Fprintf(&reqBuf, "Sec-WebSocket-Key: %s\r\n", wsKey)
7885 reqBuf.WriteString("Sec-WebSocket-Version: 13\r\n")
7886 if test.negotiatePMC {
7887 fmt.Fprintf(&reqBuf, "Sec-WebSocket-Extensions: %s\r\n", wsPMCReqHeaderValue)
7888 }
7889 reqBuf.WriteString("\r\n")
7890
7891 require_NoError(t, c.SetDeadline(time.Now().Add(2*time.Second)))
7892 _, err = c.Write(reqBuf.Bytes())
7893 require_NoError(t, err)
7894
7895 br := bufio.NewReader(c)
7896 resp, err := http.ReadResponse(br, nil)
7897 require_NoError(t, err)
7898 resp.Body.Close()
7899 require_True(t, resp.StatusCode == http.StatusSwitchingProtocols)
7900
7901 pmcAccepted := strings.Contains(resp.Header.Get("Sec-WebSocket-Extensions"), wsPMCExtension)
7902 if test.negotiatePMC != pmcAccepted {
7903 t.Fatalf("Expected PMC negotiated=%v, got %v", test.negotiatePMC, pmcAccepted)
7904 }
7905
7906 // Read the first WS frame header (binary, possibly compressed).
7907 b0, err := br.ReadByte()
7908 require_NoError(t, err)
7909 require_True(t, b0&wsFinalBit != 0)
7910 require_True(t, wsOpCode(b0&0xF) == wsBinaryMessage)
7911 require_True(t, (b0&wsRsv1Bit != 0) == pmcAccepted)
7912
7913 b1, err := br.ReadByte()
7914 require_NoError(t, err)
7915 require_True(t, b1&wsMaskBit == 0)
7916 plen := int(b1 & 0x7F)
7917 switch plen {
7918 case 126:
7919 var b [2]byte
7920 _, err = io.ReadFull(br, b[:])
7921 require_NoError(t, err)
7922 plen = int(b[0])<<8 | int(b[1])
7923 case 127:
7924 t.Fatalf("Frame too large")
7925 }
7926 payload := make([]byte, plen)
7927 _, err = io.ReadFull(br, payload)
7928 require_NoError(t, err)
7929
7930 if pmcAccepted {
7931 // Append the 4-byte trailer stripped by permessage-deflate plus
7932 // a final empty block so flate.NewReader sees end-of-stream.
7933 payload = append(payload, 0x00, 0x00, 0xff, 0xff, 0x01, 0x00, 0x00, 0xff, 0xff)
7934 fr := flate.NewReader(bytes.NewReader(payload))
7935 payload, err = io.ReadAll(fr)
7936 require_NoError(t, err)
7937 fr.Close()
7938 }
7939
7940 require_True(t, bytes.HasPrefix(payload, []byte("INFO ")))
7941 payload = bytes.TrimSuffix(payload, []byte(_CRLF_))
7942 var info Info
7943 require_NoError(t, json.Unmarshal(payload[5:], &info))
7944 if info.Compression != test.expectedComp {
7945 t.Fatalf("Expected info.Compression=%q, got %q", test.expectedComp, info.Compression)
7946 }
7947 })
7948 }
7949 }
7950
7951 func TestLeafNodeCompressionAuto(t *testing.T) {
7952 for _, test := range []struct {
7953 name string
7954 s1Ping string
7955 s1Compression string
7956 s2Ping string
7957 s2Compression string
7958 checkS1 bool
7959 }{
7960 {"remote side", "10s", CompressionS2Fast, "100ms", "{mode: s2_auto, rtt_thresholds: [10ms, 20ms, 30ms]}", false},
7961 {"accept side", "100ms", "{mode: s2_auto, rtt_thresholds: [10ms, 20ms, 30ms]}", "10s", CompressionS2Fast, true},
7962 } {
7963 t.Run(test.name, func(t *testing.T) {
7964 conf1 := createConfFile(t, []byte(fmt.Sprintf(`
7965 port: -1
7966 server_name: "A"
7967 ping_interval: "%s"
7968 leafnodes {
7969 port: -1
7970 compression: %s
7971 }
7972 `, test.s1Ping, test.s1Compression)))
7973 s1, o1 := RunServerWithConfig(conf1)
7974 defer s1.Shutdown()
7975
7976 // Start with 0ms RTT
7977 np := createNetProxy(0, 1024*1024*1024, 1024*1024*1024, fmt.Sprintf("nats://127.0.0.1:%d", o1.LeafNode.Port), true)
7978
7979 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
7980 port: -1
7981 server_name: "B"
7982 ping_interval: "%s"
7983 leafnodes {
7984 remotes [
7985 {url: %s, compression %s}
7986 ]
7987 }
7988 `, test.s2Ping, np.routeURL(), test.s2Compression)))
7989 s2, _ := RunServerWithConfig(conf2)
7990 defer s2.Shutdown()
7991 defer np.stop()
7992
7993 checkLeafNodeConnected(t, s2)
7994
7995 checkComp := func(expected string) {
7996 t.Helper()
7997 var s *Server
7998 if test.checkS1 {
7999 s = s1
8000 } else {
8001 s = s2
8002 }
8003 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
8004 s.mu.RLock()
8005 defer s.mu.RUnlock()
8006 for _, l := range s.leafs {
8007 l.mu.Lock()
8008 cm := l.leaf.compression
8009 l.mu.Unlock()
8010 if cm != expected {
8011 return fmt.Errorf("Leaf %v compression mode expected to be %q, got %q", l, expected, cm)
8012 }
8013 }
8014 return nil
8015 })
8016 }
8017 checkComp(CompressionS2Uncompressed)
8018
8019 // Change the proxy RTT and we should get compression "fast"
8020 np.updateRTT(15 * time.Millisecond)
8021 checkComp(CompressionS2Fast)
8022
8023 // Now 25ms, and get "better"
8024 np.updateRTT(25 * time.Millisecond)
8025 checkComp(CompressionS2Better)
8026
8027 // Above 35 and we should get "best"
8028 np.updateRTT(35 * time.Millisecond)
8029 checkComp(CompressionS2Best)
8030
8031 // Down to 1ms and again should get "uncompressed"
8032 np.updateRTT(1 * time.Millisecond)
8033 checkComp(CompressionS2Uncompressed)
8034 })
8035 }
8036
8037 // Make sure that if compression is off on one side, the update of RTT does
8038 // not trigger a compression change.
8039 conf1 := createConfFile(t, []byte(`
8040 port: -1
8041 server_name: "A"
8042 leafnodes {
8043 port: -1
8044 compression: off
8045 }
8046 `))
8047 s1, o1 := RunServerWithConfig(conf1)
8048 defer s1.Shutdown()
8049
8050 // Start with 0ms RTT
8051 np := createNetProxy(0, 1024*1024*1024, 1024*1024*1024, fmt.Sprintf("nats://127.0.0.1:%d", o1.LeafNode.Port), true)
8052
8053 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
8054 port: -1
8055 server_name: "B"
8056 ping_interval: "50ms"
8057 leafnodes {
8058 remotes [
8059 {url: %s, compression s2_auto}
8060 ]
8061 }
8062 `, np.routeURL())))
8063 s2, _ := RunServerWithConfig(conf2)
8064 defer s2.Shutdown()
8065 defer np.stop()
8066
8067 checkLeafNodeConnected(t, s2)
8068
8069 // Even with a bug of updating compression level while it should have been
8070 // off, the check done below would almost always pass because after
8071 // reconnecting, there could be a chance to get at first compression set
8072 // to "off". So we will double check that the leaf node CID did not change
8073 // at the end of the test.
8074 getCID := func() uint64 {
8075 s2.mu.RLock()
8076 defer s2.mu.RUnlock()
8077 for _, l := range s2.leafs {
8078 l.mu.Lock()
8079 cid := l.cid
8080 l.mu.Unlock()
8081 return cid
8082 }
8083 return 0
8084 }
8085 oldCID := getCID()
8086
8087 checkCompOff := func() {
8088 t.Helper()
8089 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
8090 s2.mu.RLock()
8091 defer s2.mu.RUnlock()
8092 if len(s2.leafs) != 1 {
8093 return fmt.Errorf("Leaf not currently connected")
8094 }
8095 for _, l := range s2.leafs {
8096 l.mu.Lock()
8097 cm := l.leaf.compression
8098 l.mu.Unlock()
8099 if cm != CompressionOff {
8100 return fmt.Errorf("Leaf %v compression mode expected to be %q, got %q", l, CompressionOff, cm)
8101 }
8102 }
8103 return nil
8104 })
8105 }
8106 checkCompOff()
8107
8108 // Now change RTT and again, make sure that it is still off
8109 np.updateRTT(20 * time.Millisecond)
8110 time.Sleep(100 * time.Millisecond)
8111 checkCompOff()
8112 if cid := getCID(); cid != oldCID {
8113 t.Fatalf("Leafnode has reconnected, cid was %v, now %v", oldCID, cid)
8114 }
8115 }
8116
8117 func TestLeafNodeCompressionWithWSCompression(t *testing.T) {
8118 conf1 := createConfFile(t, []byte(`
8119 port: -1
8120 server_name: "A"
8121 websocket {
8122 port: -1
8123 no_tls: true
8124 compression: true
8125 }
8126 leafnodes {
8127 port: -1
8128 compression: s2_fast
8129 }
8130 `))
8131 s1, o1 := RunServerWithConfig(conf1)
8132 defer s1.Shutdown()
8133
8134 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
8135 port: -1
8136 server_name: "B"
8137 leafnodes {
8138 remotes [
8139 {
8140 url: "ws://127.0.0.1:%d"
8141 ws_compression: true
8142 compression: s2_fast
8143 }
8144 ]
8145 }
8146 `, o1.Websocket.Port)))
8147 s2, _ := RunServerWithConfig(conf2)
8148 defer s2.Shutdown()
8149
8150 checkLeafNodeConnected(t, s2)
8151
8152 nc1 := natsConnect(t, s1.ClientURL())
8153 defer nc1.Close()
8154
8155 sub := natsSubSync(t, nc1, "foo")
8156 checkSubInterest(t, s2, globalAccountName, "foo", time.Second)
8157
8158 nc2 := natsConnect(t, s2.ClientURL())
8159 defer nc2.Close()
8160
8161 payload := make([]byte, 1024)
8162 for i := 0; i < len(payload); i++ {
8163 payload[i] = 'A'
8164 }
8165 natsPub(t, nc2, "foo", payload)
8166 msg := natsNexMsg(t, sub, time.Second)
8167 require_True(t, len(msg.Data) == 1024)
8168 for i := 0; i < len(msg.Data); i++ {
8169 if msg.Data[i] != 'A' {
8170 t.Fatalf("Invalid msg: %s", msg.Data)
8171 }
8172 }
8173 }
8174
8175 func TestLeafNodeCompressionWithWSGetNeedsData(t *testing.T) {
8176 conf1 := createConfFile(t, []byte(`
8177 port: -1
8178 server_name: "A"
8179 websocket {
8180 port: -1
8181 no_tls: true
8182 }
8183 leafnodes {
8184 port: -1
8185 compression: s2_fast
8186 }
8187 `))
8188 srv1, o1 := RunServerWithConfig(conf1)
8189 defer srv1.Shutdown()
8190
8191 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
8192 port: -1
8193 server_name: "B"
8194 leafnodes {
8195 remotes [
8196 {
8197 url: "ws://127.0.0.1:%d"
8198 ws_no_masking: true
8199 compression: s2_fast
8200 }
8201 ]
8202 }
8203 `, o1.Websocket.Port)))
8204 srv2, _ := RunServerWithConfig(conf2)
8205 defer srv2.Shutdown()
8206
8207 checkLeafNodeConnected(t, srv2)
8208
8209 nc1 := natsConnect(t, srv1.ClientURL())
8210 defer nc1.Close()
8211
8212 sub := natsSubSync(t, nc1, "foo")
8213 checkSubInterest(t, srv2, globalAccountName, "foo", time.Second)
8214
8215 // We want to have the payload more than 126 bytes so that the websocket
8216 // code need to read 2 bytes for the length. See below.
8217 payload := "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
8218 sentBytes := []byte("LMSG foo 156\r\n" + payload + "\r\n")
8219 h, _ := wsCreateFrameHeader(false, false, wsBinaryMessage, len(sentBytes))
8220 combined := &bytes.Buffer{}
8221 combined.Write(h)
8222 combined.Write(sentBytes)
8223 toSend := combined.Bytes()
8224
8225 // We will make a compressed block that cuts the websocket header that
8226 // makes the reader want to read bytes directly from the connection.
8227 // We want to make sure that we are not going to get compressed data
8228 // without going through the (de)compress library. So for that, compress
8229 // the first 3 bytes.
8230 b := &bytes.Buffer{}
8231 w := s2.NewWriter(b)
8232 w.Write(toSend[:3])
8233 w.Close()
8234
8235 var nc net.Conn
8236 srv2.mu.RLock()
8237 for _, l := range srv2.leafs {
8238 l.mu.Lock()
8239 nc = l.nc
8240 l.mu.Unlock()
8241 }
8242 srv2.mu.RUnlock()
8243
8244 nc.Write(b.Bytes())
8245
8246 // Pause to make sure other side just gets a partial of the whole WS frame.
8247 time.Sleep(100 * time.Millisecond)
8248
8249 b.Reset()
8250 w.Reset(b)
8251 w.Write(toSend[3:])
8252 w.Close()
8253
8254 nc.Write(b.Bytes())
8255
8256 msg := natsNexMsg(t, sub, time.Second)
8257 require_True(t, len(msg.Data) == 156)
8258 require_Equal(t, string(msg.Data), payload)
8259 }
8260
8261 func TestLeafNodeCompressionAuthTimeout(t *testing.T) {
8262 hconf := createConfFile(t, []byte(`
8263 port: -1
8264 server_name: "hub"
8265 leafnodes {
8266 port: -1
8267 authorization {
8268 timeout: 0.75
8269 }
8270 }
8271 `))
8272 sh, oh := RunServerWithConfig(hconf)
8273 defer sh.Shutdown()
8274
8275 sconfTmpl := `
8276 port: -1
8277 server_name: "%s"
8278 cluster {
8279 port: -1
8280 name: "spoke"
8281 %s
8282 }
8283 leafnodes {
8284 port: -1
8285 remotes [
8286 { url: "nats://127.0.0.1:%d" }
8287 ]
8288 }
8289 `
8290 s1conf := createConfFile(t, []byte(fmt.Sprintf(sconfTmpl, "SP1", _EMPTY_, oh.LeafNode.Port)))
8291 s1, o1 := RunServerWithConfig(s1conf)
8292 defer s1.Shutdown()
8293
8294 s2conf := createConfFile(t, []byte(fmt.Sprintf(sconfTmpl, "SP2", fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port), oh.LeafNode.Port)))
8295 s2, _ := RunServerWithConfig(s2conf)
8296 defer s2.Shutdown()
8297
8298 checkClusterFormed(t, s1, s2)
8299
8300 checkLeafNodeConnected(t, s1)
8301 checkLeafNodeConnected(t, s2)
8302
8303 getCID := func(s *Server) uint64 {
8304 s.mu.RLock()
8305 defer s.mu.RUnlock()
8306 var cid uint64
8307 for _, l := range s.leafs {
8308 l.mu.Lock()
8309 cid = l.cid
8310 l.mu.Unlock()
8311 }
8312 return cid
8313 }
8314 leaf1 := getCID(s1)
8315 leaf2 := getCID(s2)
8316
8317 // Wait for more than auth timeout
8318 time.Sleep(time.Second)
8319
8320 checkLeafNodeConnected(t, s1)
8321 checkLeafNodeConnected(t, s2)
8322 if l1 := getCID(s1); l1 != leaf1 {
8323 t.Fatalf("Leaf connection first connection had CID %v, now %v", leaf1, l1)
8324 }
8325 if l2 := getCID(s2); l2 != leaf2 {
8326 t.Fatalf("Leaf connection first connection had CID %v, now %v", leaf2, l2)
8327 }
8328 }
8329
8330 func TestLeafNodeWithWeightedDQRequestsToSuperClusterWithSeparateAccounts(t *testing.T) {
8331 sc := createJetStreamSuperClusterWithTemplate(t, jsClusterAccountsTempl, 3, 2)
8332 defer sc.shutdown()
8333
8334 // Now create a leafnode cluster that has 2 LNs, one to each cluster but on separate accounts, ONE and TWO.
8335 var lnTmpl = `
8336 listen: 127.0.0.1:-1
8337 server_name: %s
8338 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
8339
8340 {{leaf}}
8341
8342 cluster {
8343 name: %s
8344 listen: 127.0.0.1:%d
8345 routes = [%s]
8346 }
8347
8348 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }}
8349 `
8350
8351 var leafFrag = `
8352 leaf {
8353 listen: 127.0.0.1:-1
8354 remotes [
8355 { urls: [ %s ] }
8356 { urls: [ %s ] }
8357 ]
8358 }`
8359
8360 // We want to have two leaf node connections that join to the same local account on the leafnode servers,
8361 // but connect to different accounts in different clusters.
8362 c1 := sc.clusters[0] // Will connect to account ONE
8363 c2 := sc.clusters[1] // Will connect to account TWO
8364
8365 genLeafTmpl := func(tmpl string) string {
8366 t.Helper()
8367
8368 var ln1, ln2 []string
8369 for _, s := range c1.servers {
8370 if s.ClusterName() != c1.name {
8371 continue
8372 }
8373 ln := s.getOpts().LeafNode
8374 ln1 = append(ln1, fmt.Sprintf("nats://one:p@%s:%d", ln.Host, ln.Port))
8375 }
8376
8377 for _, s := range c2.servers {
8378 if s.ClusterName() != c2.name {
8379 continue
8380 }
8381 ln := s.getOpts().LeafNode
8382 ln2 = append(ln2, fmt.Sprintf("nats://two:p@%s:%d", ln.Host, ln.Port))
8383 }
8384 return strings.Replace(tmpl, "{{leaf}}", fmt.Sprintf(leafFrag, strings.Join(ln1, ", "), strings.Join(ln2, ", ")), 1)
8385 }
8386
8387 tmpl := strings.Replace(lnTmpl, "store_dir:", fmt.Sprintf(`domain: "%s", store_dir:`, "SA"), 1)
8388 tmpl = genLeafTmpl(tmpl)
8389
8390 ln := createJetStreamCluster(t, tmpl, "SA", "SA-", 3, 22280, false)
8391 ln.waitOnClusterReady()
8392 defer ln.shutdown()
8393
8394 for _, s := range ln.servers {
8395 checkLeafNodeConnectedCount(t, s, 2)
8396 }
8397
8398 // Now connect DQ subscribers to each cluster and they separate accounts, and make sure we get the right behavior, balanced between
8399 // them when requests originate from the leaf cluster.
8400
8401 // Create 5 clients for each cluster / account
8402 var c1c, c2c []*nats.Conn
8403 for i := 0; i < 5; i++ {
8404 nc1, _ := jsClientConnect(t, c1.randomServer(), nats.UserInfo("one", "p"))
8405 defer nc1.Close()
8406 c1c = append(c1c, nc1)
8407 nc2, _ := jsClientConnect(t, c2.randomServer(), nats.UserInfo("two", "p"))
8408 defer nc2.Close()
8409 c2c = append(c2c, nc2)
8410 }
8411
8412 createSubs := func(num int, conns []*nats.Conn) (subs []*nats.Subscription) {
8413 for i := 0; i < num; i++ {
8414 nc := conns[rand.Intn(len(conns))]
8415 sub, err := nc.QueueSubscribeSync("REQUEST", "MC")
8416 require_NoError(t, err)
8417 subs = append(subs, sub)
8418 nc.Flush()
8419 }
8420 // Let subs propagate.
8421 time.Sleep(100 * time.Millisecond)
8422 return subs
8423 }
8424 closeSubs := func(subs []*nats.Subscription) {
8425 for _, sub := range subs {
8426 sub.Unsubscribe()
8427 }
8428 }
8429
8430 // Simple test first.
8431 subs1 := createSubs(1, c1c)
8432 defer closeSubs(subs1)
8433 subs2 := createSubs(1, c2c)
8434 defer closeSubs(subs2)
8435
8436 sendRequests := func(num int) {
8437 t.Helper()
8438 // Now connect to the leaf cluster and send some requests.
8439 nc, _ := jsClientConnect(t, ln.randomServer())
8440 defer nc.Close()
8441
8442 for i := 0; i < num; i++ {
8443 require_NoError(t, nc.Publish("REQUEST", []byte("HELP")))
8444 }
8445 nc.Flush()
8446 }
8447
8448 pending := func(subs []*nats.Subscription) (total int) {
8449 t.Helper()
8450 for _, sub := range subs {
8451 n, _, err := sub.Pending()
8452 require_NoError(t, err)
8453 total += n
8454 }
8455 return total
8456 }
8457
8458 num := 1000
8459 checkAllReceived := func() error {
8460 total := pending(subs1) + pending(subs2)
8461 if total == num {
8462 return nil
8463 }
8464 return fmt.Errorf("Not all received: %d vs %d", total, num)
8465 }
8466
8467 checkBalanced := func(total, pc1, pc2 int) {
8468 t.Helper()
8469 tf := float64(total)
8470 e1 := tf * (float64(pc1) / 100.00)
8471 e2 := tf * (float64(pc2) / 100.00)
8472 delta := tf / 10
8473 p1 := float64(pending(subs1))
8474 if p1 < e1-delta || p1 > e1+delta {
8475 t.Fatalf("Value out of range for subs1, expected %v got %v", e1, p1)
8476 }
8477 p2 := float64(pending(subs2))
8478 if p2 < e2-delta || p2 > e2+delta {
8479 t.Fatalf("Value out of range for subs2, expected %v got %v", e2, p2)
8480 }
8481 }
8482
8483 // Now connect to the leaf cluster and send some requests.
8484
8485 // Simple 50/50
8486 sendRequests(num)
8487 checkFor(t, time.Second, 200*time.Millisecond, checkAllReceived)
8488 checkBalanced(num, 50, 50)
8489
8490 closeSubs(subs1)
8491 closeSubs(subs2)
8492
8493 // Now test unbalanced. 10/90
8494 subs1 = createSubs(1, c1c)
8495 defer closeSubs(subs1)
8496 subs2 = createSubs(9, c2c)
8497 defer closeSubs(subs2)
8498
8499 sendRequests(num)
8500 checkFor(t, time.Second, 200*time.Millisecond, checkAllReceived)
8501 checkBalanced(num, 10, 90)
8502
8503 // Now test draining the subs as we are sending from an initial balanced situation simulating a draining of a cluster.
8504
8505 closeSubs(subs1)
8506 closeSubs(subs2)
8507 subs1, subs2 = nil, nil
8508
8509 // These subs slightly different.
8510 var r1, r2 atomic.Uint64
8511 for i := 0; i < 20; i++ {
8512 nc := c1c[rand.Intn(len(c1c))]
8513 sub, err := nc.QueueSubscribe("REQUEST", "MC", func(m *nats.Msg) { r1.Add(1) })
8514 require_NoError(t, err)
8515 subs1 = append(subs1, sub)
8516 nc.Flush()
8517
8518 nc = c2c[rand.Intn(len(c2c))]
8519 sub, err = nc.QueueSubscribe("REQUEST", "MC", func(m *nats.Msg) { r2.Add(1) })
8520 require_NoError(t, err)
8521 subs2 = append(subs2, sub)
8522 nc.Flush()
8523 }
8524 defer closeSubs(subs1)
8525 defer closeSubs(subs2)
8526
8527 nc, _ := jsClientConnect(t, ln.randomServer())
8528 defer nc.Close()
8529
8530 for i, dindex := 0, 1; i < num; i++ {
8531 require_NoError(t, nc.Publish("REQUEST", []byte("HELP")))
8532 // Check if we have more to simulate draining.
8533 // Will drain within first ~100 requests using 20% rand test below.
8534 // Will leave 1 behind.
8535 if dindex < len(subs1)-1 && rand.Intn(6) > 4 {
8536 sub := subs1[dindex]
8537 dindex++
8538 sub.Drain()
8539 }
8540 }
8541 nc.Flush()
8542
8543 checkFor(t, time.Second, 200*time.Millisecond, func() error {
8544 total := int(r1.Load() + r2.Load())
8545 if total == num {
8546 return nil
8547 }
8548 return fmt.Errorf("Not all received: %d vs %d", total, num)
8549 })
8550 require_True(t, r2.Load() > r1.Load())
8551 }
8552
8553 func TestLeafNodeWithWeightedDQRequestsToSuperClusterWithStreamImportAccounts(t *testing.T) {
8554 var tmpl = `
8555 listen: 127.0.0.1:-1
8556
8557 server_name: %s
8558 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
8559
8560 leaf { listen: 127.0.0.1:-1 }
8561
8562 cluster {
8563 name: %s
8564 listen: 127.0.0.1:%d
8565 routes = [%s]
8566 }
8567
8568 accounts {
8569 EFG {
8570 users = [ { user: "efg", pass: "p" } ]
8571 jetstream: enabled
8572 imports [
8573 { stream: { account: STL, subject: "REQUEST"} }
8574 { stream: { account: KSC, subject: "REQUEST"} }
8575 ]
8576 exports [ { stream: "RESPONSE" } ]
8577 }
8578 STL {
8579 users = [ { user: "stl", pass: "p" } ]
8580 exports [ { stream: "REQUEST" } ]
8581 imports [ { stream: { account: EFG, subject: "RESPONSE"} } ]
8582 }
8583 KSC {
8584 users = [ { user: "ksc", pass: "p" } ]
8585 exports [ { stream: "REQUEST" } ]
8586 imports [ { stream: { account: EFG, subject: "RESPONSE"} } ]
8587 }
8588 $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
8589 }`
8590
8591 sc := createJetStreamSuperClusterWithTemplate(t, tmpl, 5, 2)
8592 defer sc.shutdown()
8593
8594 // Now create a leafnode cluster that has 2 LNs, one to each cluster but on separate accounts, STL and KSC.
8595 var lnTmpl = `
8596 listen: 127.0.0.1:-1
8597 server_name: %s
8598 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
8599
8600 {{leaf}}
8601
8602 cluster {
8603 name: %s
8604 listen: 127.0.0.1:%d
8605 routes = [%s]
8606 }
8607
8608 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }}
8609 `
8610
8611 var leafFrag = `
8612 leaf {
8613 listen: 127.0.0.1:-1
8614 remotes [
8615 { urls: [ %s ] }
8616 { urls: [ %s ] }
8617 { urls: [ %s ] ; deny_export: [REQUEST, RESPONSE], deny_import: RESPONSE }
8618 ]
8619 }`
8620
8621 // We want to have two leaf node connections that join to the same local account on the leafnode servers,
8622 // but connect to different accounts in different clusters.
8623 c1 := sc.clusters[0] // Will connect to account KSC
8624 c2 := sc.clusters[1] // Will connect to account STL
8625
8626 genLeafTmpl := func(tmpl string) string {
8627 t.Helper()
8628
8629 var ln1, ln2, ln3 []string
8630 for _, s := range c1.servers {
8631 if s.ClusterName() != c1.name {
8632 continue
8633 }
8634 ln := s.getOpts().LeafNode
8635 ln1 = append(ln1, fmt.Sprintf("nats://ksc:p@%s:%d", ln.Host, ln.Port))
8636 }
8637
8638 for _, s := range c2.servers {
8639 if s.ClusterName() != c2.name {
8640 continue
8641 }
8642 ln := s.getOpts().LeafNode
8643 ln2 = append(ln2, fmt.Sprintf("nats://stl:p@%s:%d", ln.Host, ln.Port))
8644 ln3 = append(ln3, fmt.Sprintf("nats://efg:p@%s:%d", ln.Host, ln.Port))
8645 }
8646 return strings.Replace(tmpl, "{{leaf}}", fmt.Sprintf(leafFrag, strings.Join(ln1, ", "), strings.Join(ln2, ", "), strings.Join(ln3, ", ")), 1)
8647 }
8648
8649 tmpl = strings.Replace(lnTmpl, "store_dir:", fmt.Sprintf(`domain: "%s", store_dir:`, "SA"), 1)
8650 tmpl = genLeafTmpl(tmpl)
8651
8652 ln := createJetStreamCluster(t, tmpl, "SA", "SA-", 3, 22280, false)
8653 ln.waitOnClusterReady()
8654 defer ln.shutdown()
8655
8656 for _, s := range ln.servers {
8657 checkLeafNodeConnectedCount(t, s, 3)
8658 }
8659
8660 // Now connect DQ subscribers to each cluster but to the global account.
8661
8662 // Create 5 clients for each cluster / account
8663 var c1c, c2c []*nats.Conn
8664 for i := 0; i < 5; i++ {
8665 nc1, _ := jsClientConnect(t, c1.randomServer(), nats.UserInfo("efg", "p"))
8666 defer nc1.Close()
8667 c1c = append(c1c, nc1)
8668 nc2, _ := jsClientConnect(t, c2.randomServer(), nats.UserInfo("efg", "p"))
8669 defer nc2.Close()
8670 c2c = append(c2c, nc2)
8671 }
8672
8673 createSubs := func(num int, conns []*nats.Conn) (subs []*nats.Subscription) {
8674 for i := 0; i < num; i++ {
8675 nc := conns[rand.Intn(len(conns))]
8676 sub, err := nc.QueueSubscribeSync("REQUEST", "MC")
8677 require_NoError(t, err)
8678 subs = append(subs, sub)
8679 nc.Flush()
8680 }
8681 // Let subs propagate.
8682 time.Sleep(100 * time.Millisecond)
8683 return subs
8684 }
8685 closeSubs := func(subs []*nats.Subscription) {
8686 for _, sub := range subs {
8687 sub.Unsubscribe()
8688 }
8689 }
8690
8691 // Simple test first.
8692 subs1 := createSubs(1, c1c)
8693 defer closeSubs(subs1)
8694 subs2 := createSubs(1, c2c)
8695 defer closeSubs(subs2)
8696
8697 sendRequests := func(num int) {
8698 t.Helper()
8699 // Now connect to the leaf cluster and send some requests.
8700 nc, _ := jsClientConnect(t, ln.randomServer())
8701 defer nc.Close()
8702
8703 for i := 0; i < num; i++ {
8704 require_NoError(t, nc.Publish("REQUEST", []byte("HELP")))
8705 }
8706 nc.Flush()
8707 }
8708
8709 pending := func(subs []*nats.Subscription) (total int) {
8710 t.Helper()
8711 for _, sub := range subs {
8712 n, _, err := sub.Pending()
8713 require_NoError(t, err)
8714 total += n
8715 }
8716 return total
8717 }
8718
8719 num := 1000
8720 checkAllReceived := func() error {
8721 total := pending(subs1) + pending(subs2)
8722 if total == num {
8723 return nil
8724 }
8725 return fmt.Errorf("Not all received: %d vs %d", total, num)
8726 }
8727
8728 checkBalanced := func(total, pc1, pc2 int) {
8729 t.Helper()
8730 tf := float64(total)
8731 e1 := tf * (float64(pc1) / 100.00)
8732 e2 := tf * (float64(pc2) / 100.00)
8733 delta := tf / 10
8734 p1 := float64(pending(subs1))
8735 if p1 < e1-delta || p1 > e1+delta {
8736 t.Fatalf("Value out of range for subs1, expected %v got %v", e1, p1)
8737 }
8738 p2 := float64(pending(subs2))
8739 if p2 < e2-delta || p2 > e2+delta {
8740 t.Fatalf("Value out of range for subs2, expected %v got %v", e2, p2)
8741 }
8742 }
8743
8744 // Now connect to the leaf cluster and send some requests.
8745
8746 // Simple 50/50
8747 sendRequests(num)
8748 checkFor(t, time.Second, 200*time.Millisecond, checkAllReceived)
8749 checkBalanced(num, 50, 50)
8750
8751 closeSubs(subs1)
8752 closeSubs(subs2)
8753
8754 // Now test unbalanced. 10/90
8755 subs1 = createSubs(1, c1c)
8756 defer closeSubs(subs1)
8757 subs2 = createSubs(9, c2c)
8758 defer closeSubs(subs2)
8759
8760 sendRequests(num)
8761 checkFor(t, time.Second, 200*time.Millisecond, checkAllReceived)
8762 checkBalanced(num, 10, 90)
8763
8764 closeSubs(subs1)
8765 closeSubs(subs2)
8766
8767 // Now test unbalanced. 80/20
8768 subs1 = createSubs(80, c1c)
8769 defer closeSubs(subs1)
8770 subs2 = createSubs(20, c2c)
8771 defer closeSubs(subs2)
8772
8773 sendRequests(num)
8774 checkFor(t, time.Second, 200*time.Millisecond, checkAllReceived)
8775 checkBalanced(num, 80, 20)
8776
8777 // Now test draining the subs as we are sending from an initial balanced situation simulating a draining of a cluster.
8778
8779 closeSubs(subs1)
8780 closeSubs(subs2)
8781 subs1, subs2 = nil, nil
8782
8783 // These subs slightly different.
8784 var r1, r2 atomic.Uint64
8785 for i := 0; i < 20; i++ {
8786 nc := c1c[rand.Intn(len(c1c))]
8787 sub, err := nc.QueueSubscribe("REQUEST", "MC", func(m *nats.Msg) { r1.Add(1) })
8788 require_NoError(t, err)
8789 subs1 = append(subs1, sub)
8790 nc.Flush()
8791
8792 nc = c2c[rand.Intn(len(c2c))]
8793 sub, err = nc.QueueSubscribe("REQUEST", "MC", func(m *nats.Msg) { r2.Add(1) })
8794 require_NoError(t, err)
8795 subs2 = append(subs2, sub)
8796 nc.Flush()
8797 }
8798 // Let's them propagate
8799 time.Sleep(100 * time.Millisecond)
8800 defer closeSubs(subs1)
8801 defer closeSubs(subs2)
8802
8803 nc, _ := jsClientConnect(t, ln.randomServer())
8804 defer nc.Close()
8805
8806 for i, dindex := 0, 1; i < num; i++ {
8807 require_NoError(t, nc.Publish("REQUEST", []byte("HELP")))
8808 // Check if we have more to simulate draining.
8809 // Will drain within first ~100 requests using 20% rand test below.
8810 // Will leave 1 behind.
8811 if dindex < len(subs1)-1 && rand.Intn(6) > 4 {
8812 sub := subs1[dindex]
8813 dindex++
8814 sub.Drain()
8815 }
8816 }
8817 nc.Flush()
8818
8819 // Drain can lose some messages since it only checks pending messages known to the client,
8820 // and is not aware of other messages that are inflight on other servers.
8821 numMin := num * 99 / 100
8822 checkFor(t, time.Second, 200*time.Millisecond, func() error {
8823 total := int(r1.Load() + r2.Load())
8824 if total >= numMin {
8825 return nil
8826 }
8827 return fmt.Errorf("Not all received: %d vs %d (minimum %d)", total, num, numMin)
8828 })
8829 require_True(t, r2.Load() > r1.Load())
8830
8831 // Now check opposite flow for responses.
8832
8833 // Create 10 subscribers.
8834 var rsubs []*nats.Subscription
8835
8836 for i := 0; i < 10; i++ {
8837 nc, _ := jsClientConnect(t, ln.randomServer())
8838 defer nc.Close()
8839 sub, err := nc.QueueSubscribeSync("RESPONSE", "SA")
8840 require_NoError(t, err)
8841 nc.Flush()
8842 rsubs = append(rsubs, sub)
8843 }
8844 // Let's them propagate
8845 time.Sleep(100 * time.Millisecond)
8846
8847 nc, _ = jsClientConnect(t, ln.randomServer())
8848 defer nc.Close()
8849 _, err := nc.SubscribeSync("RESPONSE")
8850 require_NoError(t, err)
8851 nc.Flush()
8852
8853 // Now connect and send responses from EFG in cloud.
8854 nc, _ = jsClientConnect(t, sc.randomServer(), nats.UserInfo("efg", "p"))
8855 defer nc.Close()
8856
8857 for i := 0; i < 100; i++ {
8858 require_NoError(t, nc.Publish("RESPONSE", []byte("OK")))
8859 }
8860 nc.Flush()
8861
8862 checkAllRespReceived := func() error {
8863 p := pending(rsubs)
8864 if p == 100 {
8865 return nil
8866 }
8867 return fmt.Errorf("Not all responses received: %d vs %d", p, 100)
8868 }
8869
8870 checkFor(t, time.Second, 200*time.Millisecond, checkAllRespReceived)
8871 }
8872
8873 func TestLeafNodeWithWeightedDQResponsesWithStreamImportAccountsWithUnsub(t *testing.T) {
8874 var tmpl = `
8875 listen: 127.0.0.1:-1
8876
8877 server_name: %s
8878 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
8879
8880 leaf { listen: 127.0.0.1:-1 }
8881
8882 cluster {
8883 name: %s
8884 listen: 127.0.0.1:%d
8885 routes = [%s]
8886 }
8887
8888 accounts {
8889 EFG {
8890 users = [ { user: "efg", pass: "p" } ]
8891 jetstream: enabled
8892 exports [ { stream: "RESPONSE" } ]
8893 }
8894 STL {
8895 users = [ { user: "stl", pass: "p" } ]
8896 imports [ { stream: { account: EFG, subject: "RESPONSE"} } ]
8897 }
8898 KSC {
8899 users = [ { user: "ksc", pass: "p" } ]
8900 imports [ { stream: { account: EFG, subject: "RESPONSE"} } ]
8901 }
8902 $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
8903 }`
8904
8905 c := createJetStreamClusterWithTemplate(t, tmpl, "US-CENTRAL", 3)
8906 defer c.shutdown()
8907
8908 // Now create a leafnode cluster that has 2 LNs, one to each cluster but on separate accounts, STL and KSC.
8909 var lnTmpl = `
8910 listen: 127.0.0.1:-1
8911 server_name: %s
8912 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
8913
8914 {{leaf}}
8915
8916 cluster {
8917 name: %s
8918 listen: 127.0.0.1:%d
8919 routes = [%s]
8920 }
8921
8922 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }}
8923 `
8924
8925 var leafFrag = `
8926 leaf {
8927 listen: 127.0.0.1:-1
8928 remotes [ { urls: [ %s ] } ]
8929 }`
8930
8931 genLeafTmpl := func(tmpl string) string {
8932 t.Helper()
8933
8934 var ln []string
8935 for _, s := range c.servers {
8936 lno := s.getOpts().LeafNode
8937 ln = append(ln, fmt.Sprintf("nats://ksc:p@%s:%d", lno.Host, lno.Port))
8938 }
8939 return strings.Replace(tmpl, "{{leaf}}", fmt.Sprintf(leafFrag, strings.Join(ln, ", ")), 1)
8940 }
8941
8942 tmpl = strings.Replace(lnTmpl, "store_dir:", fmt.Sprintf(`domain: "%s", store_dir:`, "SA"), 1)
8943 tmpl = genLeafTmpl(tmpl)
8944
8945 ln := createJetStreamCluster(t, tmpl, "SA", "SA-", 3, 22280, false)
8946 ln.waitOnClusterReady()
8947 defer ln.shutdown()
8948
8949 for _, s := range ln.servers {
8950 checkLeafNodeConnectedCount(t, s, 1)
8951 }
8952
8953 // Create 10 subscribers.
8954 var rsubs []*nats.Subscription
8955
8956 closeSubs := func(subs []*nats.Subscription) {
8957 for _, sub := range subs {
8958 sub.Unsubscribe()
8959 }
8960 }
8961
8962 checkAllRespReceived := func() error {
8963 t.Helper()
8964 var total int
8965 for _, sub := range rsubs {
8966 n, _, err := sub.Pending()
8967 require_NoError(t, err)
8968 total += n
8969 }
8970 if total == 100 {
8971 return nil
8972 }
8973 return fmt.Errorf("Not all responses received: %d vs %d", total, 100)
8974 }
8975
8976 s := ln.randomServer()
8977 for i := 0; i < 4; i++ {
8978 nc, _ := jsClientConnect(t, s)
8979 defer nc.Close()
8980 sub, err := nc.QueueSubscribeSync("RESPONSE", "SA")
8981 require_NoError(t, err)
8982 nc.Flush()
8983 rsubs = append(rsubs, sub)
8984 }
8985
8986 // Now connect and send responses from EFG in cloud.
8987 nc, _ := jsClientConnect(t, c.randomServer(), nats.UserInfo("efg", "p"))
8988 defer nc.Close()
8989 for i := 0; i < 100; i++ {
8990 require_NoError(t, nc.Publish("RESPONSE", []byte("OK")))
8991 }
8992 nc.Flush()
8993
8994 // Make sure all received.
8995 checkFor(t, time.Second, 200*time.Millisecond, checkAllRespReceived)
8996
8997 checkAccountInterest := func(s *Server, accName string) *SublistResult {
8998 t.Helper()
8999 acc, err := s.LookupAccount(accName)
9000 require_NoError(t, err)
9001 acc.mu.RLock()
9002 r := acc.sl.Match("RESPONSE")
9003 acc.mu.RUnlock()
9004 return r
9005 }
9006
9007 checkInterest := func() error {
9008 t.Helper()
9009 for _, s := range c.servers {
9010 if r := checkAccountInterest(s, "KSC"); len(r.psubs)+len(r.qsubs) > 0 {
9011 return fmt.Errorf("Subs still present for %q: %+v", "KSC", r)
9012 }
9013 if r := checkAccountInterest(s, "EFG"); len(r.psubs)+len(r.qsubs) > 0 {
9014 return fmt.Errorf("Subs still present for %q: %+v", "EFG", r)
9015 }
9016 }
9017 return nil
9018 }
9019
9020 // Now unsub them and create new ones on a different server.
9021 closeSubs(rsubs)
9022 rsubs = rsubs[:0]
9023
9024 // Also restart the server that we had all the rsubs on.
9025 s.Shutdown()
9026 s.WaitForShutdown()
9027 s = ln.restartServer(s)
9028 ln.waitOnClusterReady()
9029 ln.waitOnServerCurrent(s)
9030
9031 checkFor(t, time.Second, 200*time.Millisecond, checkInterest)
9032
9033 for i := 0; i < 4; i++ {
9034 nc, _ := jsClientConnect(t, s)
9035 defer nc.Close()
9036 sub, err := nc.QueueSubscribeSync("RESPONSE", "SA")
9037 require_NoError(t, err)
9038 nc.Flush()
9039 rsubs = append(rsubs, sub)
9040 }
9041
9042 for i := 0; i < 100; i++ {
9043 require_NoError(t, nc.Publish("RESPONSE", []byte("OK")))
9044 }
9045 nc.Flush()
9046
9047 // Make sure all received.
9048 checkFor(t, time.Second, 200*time.Millisecond, checkAllRespReceived)
9049
9050 closeSubs(rsubs)
9051 checkFor(t, time.Second, 200*time.Millisecond, checkInterest)
9052 }
9053
9054 func TestLeafNodeTwoRemotesToSameHubAccount(t *testing.T) {
9055 conf1 := createConfFile(t, []byte(`
9056 port: -1
9057 server_name: "hub"
9058 accounts {
9059 HA { users: [{user: ha, password: pwd}] }
9060 }
9061 leafnodes {
9062 port: -1
9063 }
9064 `))
9065 s1, o1 := RunServerWithConfig(conf1)
9066 defer s1.Shutdown()
9067
9068 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
9069 port: -1
9070 server_name: "spoke"
9071 accounts {
9072 A { users: [{user: A, password: pwd}] }
9073 B { users: [{user: B, password: pwd}] }
9074 C { users: [{user: C, password: pwd}] }
9075 }
9076 leafnodes {
9077 remotes [
9078 {
9079 url: "nats://ha:[email protected]:%d"
9080 local: "A"
9081 }
9082 {
9083 url: "nats://ha:[email protected]:%d"
9084 local: "C"
9085 }
9086 ]
9087 }
9088 `, o1.LeafNode.Port, o1.LeafNode.Port)))
9089 s2, _ := RunServerWithConfig(conf2)
9090 defer s2.Shutdown()
9091
9092 l := &captureErrorLogger{errCh: make(chan string, 10)}
9093 s2.SetLogger(l, false, false)
9094
9095 checkLeafNodeConnectedCount(t, s2, 2)
9096
9097 // Make sure we don't get duplicate leafnode connection errors
9098 deadline := time.NewTimer(1500 * time.Millisecond)
9099 for done := false; !done; {
9100 select {
9101 case err := <-l.errCh:
9102 if strings.Contains(err, DuplicateRemoteLeafnodeConnection.String()) {
9103 t.Fatalf("Got error: %v", err)
9104 }
9105 case <-deadline.C:
9106 done = true
9107 }
9108 }
9109
9110 nca := natsConnect(t, s2.ClientURL(), nats.UserInfo("A", "pwd"))
9111 defer nca.Close()
9112 suba := natsSubSync(t, nca, "A")
9113 ncb := natsConnect(t, s2.ClientURL(), nats.UserInfo("B", "pwd"))
9114 defer ncb.Close()
9115 subb := natsSubSync(t, ncb, "B")
9116 ncc := natsConnect(t, s2.ClientURL(), nats.UserInfo("C", "pwd"))
9117 defer ncc.Close()
9118 subc := natsSubSync(t, ncc, "C")
9119 subs := map[string]*nats.Subscription{"A": suba, "B": subb, "C": subc}
9120
9121 for _, subj := range []string{"A", "C"} {
9122 checkSubInterest(t, s1, "HA", subj, time.Second)
9123 }
9124
9125 nc := natsConnect(t, s1.ClientURL(), nats.UserInfo("ha", "pwd"))
9126 defer nc.Close()
9127
9128 for _, subj := range []string{"A", "B", "C"} {
9129 natsPub(t, nc, subj, []byte("hello"))
9130 }
9131
9132 for _, subj := range []string{"A", "B", "C"} {
9133 var expected bool
9134 if subj != "B" {
9135 expected = true
9136 }
9137 sub := subs[subj]
9138 if expected {
9139 natsNexMsg(t, sub, time.Second)
9140 } else {
9141 if _, err := sub.NextMsg(50 * time.Millisecond); err != nats.ErrTimeout {
9142 t.Fatalf("Expected timeout error, got %v", err)
9143 }
9144 }
9145 }
9146 }
9147
9148 func TestLeafNodeTwoRemotesToSameHubAccountWithClusters(t *testing.T) {
9149 hubTmpl := `
9150 port: -1
9151 server_name: "%s"
9152 accounts {
9153 HA { users: [{user: HA, password: pwd}] }
9154 }
9155 cluster {
9156 name: "hub"
9157 port: -1
9158 %s
9159 }
9160 leafnodes {
9161 port: -1
9162 }
9163 `
9164 confH1 := createConfFile(t, []byte(fmt.Sprintf(hubTmpl, "H1", _EMPTY_)))
9165 sh1, oh1 := RunServerWithConfig(confH1)
9166 defer sh1.Shutdown()
9167
9168 confH2 := createConfFile(t, []byte(fmt.Sprintf(hubTmpl, "H2", fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", oh1.Cluster.Port))))
9169 sh2, oh2 := RunServerWithConfig(confH2)
9170 defer sh2.Shutdown()
9171
9172 checkClusterFormed(t, sh1, sh2)
9173
9174 spokeTmpl := `
9175 port: -1
9176 server_name: "%s"
9177 accounts {
9178 A { users: [{user: A, password: pwd}] }
9179 B { users: [{user: B, password: pwd}] }
9180 }
9181 cluster {
9182 name: "spoke"
9183 port: -1
9184 %s
9185 }
9186 leafnodes {
9187 remotes [
9188 {
9189 url: "nats://HA:[email protected]:%d"
9190 local: "A"
9191 }
9192 {
9193 url: "nats://HA:[email protected]:%d"
9194 local: "B"
9195 }
9196 ]
9197 }
9198 `
9199 for _, test := range []struct {
9200 name string
9201 sp2Leafport int
9202 }{
9203 {"connect to different hub servers", oh2.LeafNode.Port},
9204 {"connect to same hub server", oh1.LeafNode.Port},
9205 } {
9206 t.Run(test.name, func(t *testing.T) {
9207 confSP1 := createConfFile(t, []byte(fmt.Sprintf(spokeTmpl, "SP1", _EMPTY_, oh1.LeafNode.Port, oh1.LeafNode.Port)))
9208 sp1, osp1 := RunServerWithConfig(confSP1)
9209 defer sp1.Shutdown()
9210
9211 confSP2 := createConfFile(t, []byte(fmt.Sprintf(spokeTmpl, "SP2",
9212 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", osp1.Cluster.Port), test.sp2Leafport, test.sp2Leafport)))
9213 sp2, _ := RunServerWithConfig(confSP2)
9214 defer sp2.Shutdown()
9215
9216 checkClusterFormed(t, sp1, sp2)
9217 checkLeafNodeConnectedCount(t, sp1, 2)
9218 checkLeafNodeConnectedCount(t, sp2, 2)
9219
9220 var conns []*nats.Conn
9221 createConn := func(s *Server, user string) {
9222 t.Helper()
9223 nc := natsConnect(t, s.ClientURL(), nats.UserInfo(user, "pwd"))
9224 conns = append(conns, nc)
9225 }
9226 createConn(sh1, "HA")
9227 createConn(sh2, "HA")
9228 createConn(sp1, "A")
9229 createConn(sp2, "A")
9230 createConn(sp1, "B")
9231 createConn(sp2, "B")
9232 for _, nc := range conns {
9233 defer nc.Close()
9234 }
9235
9236 check := func(subConn *nats.Conn, subj string, checkA, checkB bool) {
9237 t.Helper()
9238 sub := natsSubSync(t, subConn, subj)
9239 defer sub.Unsubscribe()
9240
9241 checkSubInterest(t, sh1, "HA", subj, time.Second)
9242 checkSubInterest(t, sh2, "HA", subj, time.Second)
9243 if checkA {
9244 checkSubInterest(t, sp1, "A", subj, time.Second)
9245 checkSubInterest(t, sp2, "A", subj, time.Second)
9246 }
9247 if checkB {
9248 checkSubInterest(t, sp1, "B", subj, time.Second)
9249 checkSubInterest(t, sp2, "B", subj, time.Second)
9250 }
9251
9252 for i, ncp := range conns {
9253 // Don't publish from account "A" connections if we are
9254 // dealing with account "B", and vice-versa.
9255 if !checkA && i >= 2 && i <= 3 {
9256 continue
9257 }
9258 if !checkB && i >= 4 {
9259 continue
9260 }
9261 natsPub(t, ncp, subj, []byte("hello"))
9262 natsNexMsg(t, sub, time.Second)
9263 // Make sure we don't get a duplicate
9264 if msg, err := sub.NextMsg(50 * time.Millisecond); err != nats.ErrTimeout {
9265 t.Fatalf("Unexpected message or error: msg=%v - err=%v", msg, err)
9266 }
9267 }
9268 }
9269 check(conns[0], "HA.1", true, true)
9270 check(conns[1], "HA.2", true, true)
9271 check(conns[2], "SPA.1", true, false)
9272 check(conns[3], "SPA.2", true, false)
9273 check(conns[4], "SPB.1", false, true)
9274 check(conns[5], "SPB.2", false, true)
9275 })
9276 }
9277 }
9278
9279 func TestLeafNodeSameLocalAccountToMultipleHubs(t *testing.T) {
9280 hub1Conf := createConfFile(t, []byte(`
9281 port: -1
9282 server_name: hub1
9283 accounts {
9284 hub1 { users: [{user: hub1, password: pwd}] }
9285 }
9286 leafnodes {
9287 port: -1
9288 }
9289 `))
9290 sh1, oh1 := RunServerWithConfig(hub1Conf)
9291 defer sh1.Shutdown()
9292
9293 hub2Conf := createConfFile(t, []byte(`
9294 port: -1
9295 server_name: hub2
9296 accounts {
9297 hub2 { users: [{user: hub2, password: pwd}] }
9298 }
9299 leafnodes {
9300 port: -1
9301 }
9302 `))
9303 sh2, oh2 := RunServerWithConfig(hub2Conf)
9304 defer sh2.Shutdown()
9305
9306 lconf := createConfFile(t, []byte(fmt.Sprintf(`
9307 port: -1
9308 server_name: leaf
9309 accounts {
9310 A { users: [{user: A, password: pwd}] }
9311 B { users: [{user: B, password: pwd}] }
9312 C { users: [{user: C, password: pwd}] }
9313 }
9314 leafnodes {
9315 port: -1
9316 remotes [
9317 {
9318 url: nats://hub1:[email protected]:%[1]d
9319 local: "A"
9320 }
9321 {
9322 url: nats://hub1:[email protected]:%[1]d
9323 local: "C"
9324 }
9325 {
9326 url: nats://hub2:[email protected]:%[2]d
9327 local: "A"
9328 }
9329 {
9330 url: nats://hub2:[email protected]:%[2]d
9331 local: "B"
9332 }
9333 ]
9334 }
9335 `, oh1.LeafNode.Port, oh2.LeafNode.Port)))
9336 s, _ := RunServerWithConfig(lconf)
9337 defer s.Shutdown()
9338
9339 // The leafnode to hub1 should have 2 connections (A and C)
9340 // while the one to hub2 should have 2 connections (A and B)
9341 checkLeafNodeConnectedCount(t, sh1, 2)
9342 checkLeafNodeConnectedCount(t, sh2, 2)
9343 checkLeafNodeConnectedCount(t, s, 4)
9344
9345 nca := natsConnect(t, s.ClientURL(), nats.UserInfo("A", "pwd"))
9346 defer nca.Close()
9347 suba := natsSubSync(t, nca, "A")
9348 ncb := natsConnect(t, s.ClientURL(), nats.UserInfo("B", "pwd"))
9349 defer ncb.Close()
9350 subb := natsSubSync(t, ncb, "B")
9351 ncc := natsConnect(t, s.ClientURL(), nats.UserInfo("C", "pwd"))
9352 defer ncc.Close()
9353 subc := natsSubSync(t, ncc, "C")
9354
9355 checkSubInterest(t, sh1, "hub1", "A", time.Second)
9356 checkSubNoInterest(t, sh1, "hub1", "B", time.Second)
9357 checkSubInterest(t, sh1, "hub1", "C", time.Second)
9358
9359 checkSubInterest(t, sh2, "hub2", "A", time.Second)
9360 checkSubInterest(t, sh2, "hub2", "B", time.Second)
9361 checkSubNoInterest(t, sh2, "hub2", "C", time.Second)
9362
9363 nch1 := natsConnect(t, sh1.ClientURL(), nats.UserInfo("hub1", "pwd"))
9364 defer nch1.Close()
9365 nch2 := natsConnect(t, sh2.ClientURL(), nats.UserInfo("hub2", "pwd"))
9366 defer nch2.Close()
9367
9368 checkNoMsg := func(sub *nats.Subscription) {
9369 t.Helper()
9370 if msg, err := sub.NextMsg(50 * time.Millisecond); err != nats.ErrTimeout {
9371 t.Fatalf("Unexpected message: %s", msg.Data)
9372 }
9373 }
9374
9375 checkSub := func(sub *nats.Subscription, subj, payload string) {
9376 t.Helper()
9377 msg := natsNexMsg(t, sub, time.Second)
9378 require_Equal(t, subj, msg.Subject)
9379 require_Equal(t, payload, string(msg.Data))
9380 // Make sure we don't get duplicates
9381 checkNoMsg(sub)
9382 }
9383
9384 natsPub(t, nch1, "A", []byte("msgA1"))
9385 checkSub(suba, "A", "msgA1")
9386 natsPub(t, nch1, "B", []byte("msgB1"))
9387 checkNoMsg(subb)
9388 natsPub(t, nch1, "C", []byte("msgC1"))
9389 checkSub(subc, "C", "msgC1")
9390
9391 natsPub(t, nch2, "A", []byte("msgA2"))
9392 checkSub(suba, "A", "msgA2")
9393 natsPub(t, nch2, "B", []byte("msgB2"))
9394 checkSub(subb, "B", "msgB2")
9395 natsPub(t, nch2, "C", []byte("msgC2"))
9396 checkNoMsg(subc)
9397 }
9398
9399 func TestLeafNodeSlowConsumer(t *testing.T) {
9400 ao := DefaultOptions()
9401 ao.LeafNode.Host = "127.0.0.1"
9402 ao.LeafNode.Port = -1
9403 ao.WriteDeadline = 1 * time.Millisecond
9404 a := RunServer(ao)
9405 defer a.Shutdown()
9406
9407 c, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", ao.LeafNode.Port))
9408 if err != nil {
9409 t.Fatalf("Error connecting: %v", err)
9410 }
9411 time.Sleep(5 * time.Millisecond)
9412 a.mu.Lock()
9413 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
9414 a.grMu.Lock()
9415 defer a.grMu.Unlock()
9416 for _, cli := range a.grTmpClients {
9417 cli.out.wdl = time.Nanosecond
9418 return nil
9419 }
9420 return nil
9421 })
9422 a.mu.Unlock()
9423
9424 // Only leafnode slow consumers that made it past connect are tracked
9425 // in the slow consumers counter.
9426 if _, err := c.Write([]byte("CONNECT {}\r\n")); err != nil {
9427 t.Fatalf("Error writing connect: %v", err)
9428 }
9429 // Read info
9430 br := bufio.NewReader(c)
9431 br.ReadLine()
9432 for i := 0; i < 10; i++ {
9433 if _, err := c.Write([]byte("PING\r\n")); err != nil {
9434 t.Fatalf("Unexpected error writing PING: %v", err)
9435 }
9436 }
9437 defer c.Close()
9438 timeout := time.Now().Add(time.Second)
9439 var (
9440 got uint64
9441 expected uint64 = 1
9442 )
9443 for time.Now().Before(timeout) {
9444 got = a.NumSlowConsumersLeafs()
9445 if got == expected {
9446 return
9447 }
9448 time.Sleep(1 * time.Millisecond)
9449 }
9450 t.Fatalf("Timed out waiting for slow consumer leafnodes, got: %v, expected: %v", got, expected)
9451 }
9452
9453 // https://github.com/nats-io/nats-server/issues/4367
9454 func TestLeafNodeDQMultiAccountExportImport(t *testing.T) {
9455 bConf := createConfFile(t, []byte(`
9456 listen: 127.0.0.1:-1
9457 server_name: cluster-b-0
9458 accounts {
9459 $SYS: { users: [ { user: admin, password: pwd } ] },
9460 AGG: {
9461 exports: [ { service: "PING.>" } ]
9462 users: [ { user: agg, password: agg } ]
9463 }
9464 }
9465 leaf { listen: 127.0.0.1:-1 }
9466 `))
9467
9468 sb, ob := RunServerWithConfig(bConf)
9469 defer sb.Shutdown()
9470
9471 tmpl := `
9472 listen: 127.0.0.1:-1
9473 server_name: %s
9474 jetstream: { store_dir: '%s' }
9475 cluster {
9476 name: %s
9477 listen: 127.0.0.1:%d
9478 routes = [%s]
9479 }
9480 accounts {
9481 $SYS: { users: [ { user: admin, password: pwd } ] },
9482 A: {
9483 mappings: { "A.>" : ">" }
9484 exports: [ { service: A.> } ]
9485 users: [ { user: a, password: a } ]
9486 },
9487 AGG: {
9488 imports: [ { service: { subject: A.>, account: A } } ]
9489 users: [ { user: agg, password: agg } ]
9490 },
9491 }
9492 leaf {
9493 remotes: [ {
9494 urls: [ nats-leaf://agg:[email protected]:{LEAF_PORT} ]
9495 account: AGG
9496 } ]
9497 }
9498 `
9499 tmpl = strings.Replace(tmpl, "{LEAF_PORT}", fmt.Sprintf("%d", ob.LeafNode.Port), 1)
9500 c := createJetStreamCluster(t, tmpl, "cluster-a", "cluster-a-", 3, 22110, false)
9501 defer c.shutdown()
9502
9503 // Make sure all servers are connected via leafnode to the hub, the b server.
9504 for _, s := range c.servers {
9505 checkLeafNodeConnectedCount(t, s, 1)
9506 }
9507
9508 // Connect to a server in the cluster and create a DQ listener.
9509 nc, _ := jsClientConnect(t, c.randomServer(), nats.UserInfo("a", "a"))
9510 defer nc.Close()
9511
9512 var got atomic.Int32
9513
9514 natsQueueSub(t, nc, "PING", "Q", func(m *nats.Msg) {
9515 got.Add(1)
9516 m.Respond([]byte("REPLY"))
9517 })
9518
9519 // Now connect to B and send the request.
9520 ncb, _ := jsClientConnect(t, sb, nats.UserInfo("agg", "agg"))
9521 defer ncb.Close()
9522
9523 _, err := ncb.Request("A.PING", []byte("REQUEST"), time.Second)
9524 require_NoError(t, err)
9525 require_Equal(t, got.Load(), 1)
9526 }
9527
9528 // https://github.com/nats-io/nats-server/issues/4934
9529 func TestLeafNodeServerReloadSubjectMappings(t *testing.T) {
9530 stmpl := `
9531 listen: 127.0.0.1:-1
9532 server_name: test-server
9533 mappings = { "source1": "target" }
9534 leaf { listen: 127.0.0.1:-1 }
9535 `
9536 conf := createConfFile(t, []byte(stmpl))
9537 s, o := RunServerWithConfig(conf)
9538 defer s.Shutdown()
9539
9540 tmpl := `
9541 listen: 127.0.0.1:-1
9542 server_name: test-leaf
9543 leaf {
9544 remotes: [ {
9545 urls: [ nats-leaf://127.0.0.1:{LEAF_PORT} ]
9546 } ]
9547 }
9548 `
9549 tmpl = strings.Replace(tmpl, "{LEAF_PORT}", fmt.Sprintf("%d", o.LeafNode.Port), 1)
9550 lConf := createConfFile(t, []byte(tmpl))
9551 l, _ := RunServerWithConfig(lConf)
9552 defer l.Shutdown()
9553
9554 checkLeafNodeConnected(t, l)
9555
9556 // Create our subscriber.
9557 nc := natsConnect(t, s.ClientURL())
9558 defer nc.Close()
9559 sub := natsSubSync(t, nc, "target")
9560 natsFlush(t, nc)
9561
9562 // Create our publisher.
9563 ncl := natsConnect(t, l.ClientURL())
9564 defer ncl.Close()
9565 // Publish our message.
9566 ncl.Publish("source1", []byte("OK"))
9567
9568 // Make sure we receive it.
9569 checkSubsPending(t, sub, 1)
9570
9571 // Now change mapping.
9572 reloadUpdateConfig(t, s, conf, strings.Replace(stmpl, "source1", "source2", 1))
9573 // Also make sure we do not have subscription interest for source1 on leaf anymore.
9574 checkSubInterest(t, l, globalAccountName, "source2", 2*time.Second)
9575
9576 // Publish our new message.
9577 ncl.Publish("source2", []byte("OK"))
9578
9579 // Make sure we receive it.
9580 checkSubsPending(t, sub, 2)
9581
9582 // Also make sure we do not have subscription interest for source1 on leaf anymore.
9583 checkSubNoInterest(t, l, globalAccountName, "source1", 2*time.Second)
9584 }
9585
9586 // https://github.com/nats-io/nats-server/issues/5099
9587 func TestLeafNodeServerReloadSubjectMappingsWithSameSubject(t *testing.T) {
9588 stmpl := `
9589 listen: 127.0.0.1:-1
9590 server_name: test-server
9591 mappings = { "source": "target1" }
9592 leaf { listen: 127.0.0.1:-1 }
9593 `
9594 conf := createConfFile(t, []byte(stmpl))
9595 s, o := RunServerWithConfig(conf)
9596 defer s.Shutdown()
9597
9598 tmpl := `
9599 listen: 127.0.0.1:-1
9600 server_name: test-leaf
9601 leaf {
9602 remotes: [ { urls: [ nats-leaf://127.0.0.1:{LEAF_PORT} ] } ]
9603 }
9604 `
9605 tmpl = strings.Replace(tmpl, "{LEAF_PORT}", fmt.Sprintf("%d", o.LeafNode.Port), 1)
9606 lConf := createConfFile(t, []byte(tmpl))
9607 l, _ := RunServerWithConfig(lConf)
9608 defer l.Shutdown()
9609
9610 checkLeafNodeConnected(t, l)
9611
9612 // Create our subscriber.
9613 nc := natsConnect(t, s.ClientURL())
9614 defer nc.Close()
9615 sub1 := natsSubSync(t, nc, "target1")
9616 sub2 := natsSubSync(t, nc, "target2")
9617 natsFlush(t, nc)
9618
9619 // Create our publisher.
9620 ncl := natsConnect(t, l.ClientURL())
9621 defer ncl.Close()
9622 // Publish our message.
9623 ncl.Publish("source", []byte("OK"))
9624
9625 // Make sure we receive it.
9626 checkSubsPending(t, sub1, 1)
9627 // Make sure the other does not.
9628 checkSubsPending(t, sub2, 0)
9629
9630 // Now change mapping, but only the "to" subject, keeping same "from"
9631 reloadUpdateConfig(t, s, conf, strings.Replace(stmpl, "target1", "target2", 1))
9632 checkLeafNodeConnected(t, l)
9633
9634 // Publish our new message.
9635 ncl.Publish("source", []byte("OK"))
9636
9637 // Make sure we receive it.
9638 checkSubsPending(t, sub2, 1)
9639 // Make sure the other does not.
9640 checkSubsPending(t, sub1, 1)
9641 }
9642
9643 func TestLeafNodeNkeyAuth(t *testing.T) {
9644 conf := createConfFile(t, []byte(`
9645 listen: 127.0.0.1:-1
9646 server_name: test-server
9647 leaf {
9648 listen: 127.0.0.1:-1
9649 authorization: { nkey: UCSTG5CRF5GEJERAFKUUYRODGABTBVWY2NPE4GGKRQVQOH74PIAKTVKO }
9650 }
9651 `))
9652 s, o := RunServerWithConfig(conf)
9653 defer s.Shutdown()
9654
9655 tmpl := `
9656 listen: 127.0.0.1:-1
9657 server_name: test-leaf
9658 leaf {
9659 remotes: [ {
9660 url: nats-leaf://127.0.0.1:{LEAF_PORT}
9661 seed: SUACJN3OSKWWPQXME4JUNFJ3PARXPO657GGNWNU7PK7G3AUQQYHLW26XH4
9662 } ]
9663 }
9664 `
9665 tmpl = strings.Replace(tmpl, "{LEAF_PORT}", fmt.Sprintf("%d", o.LeafNode.Port), 1)
9666 lConf := createConfFile(t, []byte(tmpl))
9667 l, _ := RunServerWithConfig(lConf)
9668 defer l.Shutdown()
9669
9670 checkLeafNodeConnected(t, l)
9671 }
9672
9673 func TestLeafNodeAccountNkeysAuth(t *testing.T) {
9674 conf := createConfFile(t, []byte(`
9675 listen: 127.0.0.1:-1
9676 server_name: test-server
9677 leaf {
9678 listen: 127.0.0.1:-1
9679 }
9680 accounts {
9681 A { users [ {nkey: UCSTG5CRF5GEJERAFKUUYRODGABTBVWY2NPE4GGKRQVQOH74PIAKTVKO } ] }
9682 }
9683 `))
9684 s, o := RunServerWithConfig(conf)
9685 defer s.Shutdown()
9686
9687 tmpl := `
9688 listen: 127.0.0.1:-1
9689 server_name: test-leaf
9690 leaf {
9691 remotes: [ {
9692 url: nats-leaf://127.0.0.1:{LEAF_PORT}
9693 seed: SUACJN3OSKWWPQXME4JUNFJ3PARXPO657GGNWNU7PK7G3AUQQYHLW26XH4
9694 } ]
9695 }
9696 `
9697 tmpl = strings.Replace(tmpl, "{LEAF_PORT}", fmt.Sprintf("%d", o.LeafNode.Port), 1)
9698 lConf := createConfFile(t, []byte(tmpl))
9699 l, _ := RunServerWithConfig(lConf)
9700 defer l.Shutdown()
9701
9702 checkLeafNodeConnected(t, l)
9703 }
9704
9705 // https://github.com/nats-io/nats-server/issues/5117
9706 func TestLeafNodeLoopDetectionOnActualLoop(t *testing.T) {
9707 // Setup: B --[leaf]--> A C --[leaf]--> A C --[leaf] --> B
9708 accConf := `
9709 accounts: {
9710 APP: {
9711 users: [ { user:u, password: u,
9712 permissions: { publish = "u.>", subscribe = "u.>" }} ]
9713 }
9714 $SYS: { users = [ {user: "s", password: "s"} ] }
9715 }`
9716
9717 confA := createConfFile(t, []byte(fmt.Sprintf(`
9718 server_name: a1
9719 port: -1
9720 cluster: { name: A }
9721 leafnodes {
9722 port: 17422
9723 }
9724 %s`, accConf)))
9725
9726 confB := createConfFile(t, []byte(fmt.Sprintf(`
9727 server_name: b1
9728 port: -1
9729 cluster: { name: B }
9730 leafnodes {
9731 port: 17432
9732 remotes [
9733 { urls: ["nats-leaf://u:u@localhost:17422"], account: "APP" }
9734 ]
9735 reconnect: "2s"
9736 }
9737 %s`, accConf)))
9738
9739 confC := createConfFile(t, []byte(fmt.Sprintf(`
9740 server_name: c1
9741 port: -1
9742 cluster: { name: C }
9743 leafnodes {
9744 port: 17442
9745 remotes [
9746 { urls: ["nats-leaf://u:u@localhost:17422"], account: "APP" }
9747 # This one creates the loop
9748 { urls: ["nats-leaf://u:u@localhost:17432"], account: "APP" }
9749 ]
9750 reconnect: "0.5s"
9751 }
9752 %s`, accConf)))
9753
9754 // Start order will be B -> C -> A
9755 // We will force C to connect to A first before B using different reconnect intervals.
9756 // If B connects first we detect loops fine. If C connects first we do not.
9757
9758 srvB, _ := RunServerWithConfig(confB)
9759 defer srvB.Shutdown()
9760 lb := &loopDetectedLogger{ch: make(chan string, 1)}
9761 srvB.SetLogger(lb, false, false)
9762
9763 srvC, _ := RunServerWithConfig(confC)
9764 defer srvC.Shutdown()
9765 lc := &loopDetectedLogger{ch: make(chan string, 1)}
9766 srvC.SetLogger(lc, false, false)
9767
9768 // C should connect to B
9769 checkLeafNodeConnectedCount(t, srvC, 1)
9770
9771 srvA, _ := RunServerWithConfig(confA)
9772 defer srvA.Shutdown()
9773 la := &loopDetectedLogger{ch: make(chan string, 1)}
9774 srvA.SetLogger(la, false, false)
9775
9776 select {
9777 case <-la.ch:
9778 case <-lb.ch:
9779 case <-lc.ch:
9780 case <-time.After(5 * time.Second):
9781 t.Fatalf("Did not get any error regarding loop")
9782 }
9783 }
9784
9785 func TestLeafNodeConnectionSucceedsEvenWithDelayedFirstINFO(t *testing.T) {
9786 for _, test := range []struct {
9787 name string
9788 websocket bool
9789 }{
9790 {"regular", false},
9791 {"websocket", true},
9792 } {
9793 t.Run(test.name, func(t *testing.T) {
9794 ob := DefaultOptions()
9795 ob.ServerName = "HUB"
9796 ob.LeafNode.Host = "127.0.0.1"
9797 ob.LeafNode.Port = -1
9798 ob.LeafNode.AuthTimeout = 10
9799 if test.websocket {
9800 ob.Websocket.Host = "127.0.0.1"
9801 ob.Websocket.Port = -1
9802 ob.Websocket.HandshakeTimeout = 10 * time.Second
9803 ob.Websocket.AuthTimeout = 10
9804 ob.Websocket.NoTLS = true
9805 }
9806 sb := RunServer(ob)
9807 defer sb.Shutdown()
9808
9809 var port int
9810 var scheme string
9811 if test.websocket {
9812 port = ob.Websocket.Port
9813 scheme = wsSchemePrefix
9814 } else {
9815 port = ob.LeafNode.Port
9816 scheme = "nats"
9817 }
9818
9819 urlStr := fmt.Sprintf("%s://127.0.0.1:%d", scheme, port)
9820 proxy := createNetProxy(1100*time.Millisecond, 1024*1024*1024, 1024*1024*1024, urlStr, true)
9821 defer proxy.stop()
9822 proxyURL := proxy.clientURL()
9823 _, proxyPort, err := net.SplitHostPort(proxyURL[len(scheme)+3:])
9824 require_NoError(t, err)
9825
9826 lnBURL, err := url.Parse(fmt.Sprintf("%s://127.0.0.1:%s", scheme, proxyPort))
9827 require_NoError(t, err)
9828
9829 oa := DefaultOptions()
9830 oa.ServerName = "SPOKE"
9831 oa.Cluster.Name = "xyz"
9832 remote := &RemoteLeafOpts{
9833 URLs: []*url.URL{lnBURL},
9834 FirstInfoTimeout: 3 * time.Second,
9835 }
9836 oa.LeafNode.Remotes = []*RemoteLeafOpts{remote}
9837 sa := RunServer(oa)
9838 defer sa.Shutdown()
9839
9840 checkLeafNodeConnected(t, sa)
9841 })
9842 }
9843 }
9844
9845 type captureLeafConnClosed struct {
9846 DummyLogger
9847 ch chan struct{}
9848 }
9849
9850 func (l *captureLeafConnClosed) Noticef(format string, v ...any) {
9851 msg := fmt.Sprintf(format, v...)
9852 if strings.Contains(msg, "Leafnode connection closed: Read Error") {
9853 select {
9854 case l.ch <- struct{}{}:
9855 default:
9856 }
9857 }
9858 }
9859
9860 func TestLeafNodeDetectsStaleConnectionIfNoInfo(t *testing.T) {
9861 for _, test := range []struct {
9862 name string
9863 websocket bool
9864 }{
9865 {"regular", false},
9866 {"websocket", true},
9867 } {
9868 t.Run(test.name, func(t *testing.T) {
9869 l, err := net.Listen("tcp", "127.0.0.1:0")
9870 require_NoError(t, err)
9871 defer l.Close()
9872
9873 ch := make(chan struct{})
9874 wg := sync.WaitGroup{}
9875 wg.Add(1)
9876 go func() {
9877 defer wg.Done()
9878 c, err := l.Accept()
9879 if err != nil {
9880 return
9881 }
9882 defer c.Close()
9883 <-ch
9884 }()
9885
9886 var scheme string
9887 if test.websocket {
9888 scheme = wsSchemePrefix
9889 } else {
9890 scheme = "nats"
9891 }
9892 urlStr := fmt.Sprintf("%s://%s", scheme, l.Addr())
9893 lnBURL, err := url.Parse(urlStr)
9894 require_NoError(t, err)
9895
9896 oa := DefaultOptions()
9897 oa.ServerName = "SPOKE"
9898 oa.Cluster.Name = "xyz"
9899 remote := &RemoteLeafOpts{
9900 URLs: []*url.URL{lnBURL},
9901 FirstInfoTimeout: 250 * time.Millisecond,
9902 }
9903 oa.LeafNode.Remotes = []*RemoteLeafOpts{remote}
9904 oa.DisableShortFirstPing = false
9905 oa.NoLog = false
9906 sa, err := NewServer(oa)
9907 require_NoError(t, err)
9908 defer sa.Shutdown()
9909
9910 log := &captureLeafConnClosed{ch: make(chan struct{}, 1)}
9911 sa.SetLogger(log, false, false)
9912 sa.Start()
9913
9914 select {
9915 case <-log.ch:
9916 // OK
9917 case <-time.After(750 * time.Millisecond):
9918 t.Fatalf("Connection was not closed")
9919 }
9920
9921 sa.Shutdown()
9922 close(ch)
9923 wg.Wait()
9924 sa.WaitForShutdown()
9925 })
9926 }
9927 }
9928
9929 // https://github.com/nats-io/nats-server/issues/5473
9930 func TestLeafNodeDupeDeliveryQueueSubAndPlainSub(t *testing.T) {
9931 clusterCommonConf := `
9932 accounts: {
9933 tenant: {
9934 users: [ { user:t, password: t } ]
9935 exports: [{stream: system-a.events.>}]
9936 }
9937 system-a: {
9938 users: [ { user:sa, password: sa } ]
9939 imports: [
9940 {stream: {subject: system-a.events.>, account: tenant}, prefix: tenant}
9941 ]
9942 }
9943 $SYS: { users = [ {user: "s", password: "s"} ] }
9944 }
9945 leafnodes {
9946 remotes: [{
9947 urls: [ "nats-leaf://sa:[email protected]:17422" ]
9948 account: system-a
9949 }]
9950 }`
9951
9952 confCluster0 := createConfFile(t, []byte(fmt.Sprintf(`
9953 server_name: a-0
9954 port: -1
9955 cluster: {
9956 name: cluster-a
9957 listen: 127.0.0.1:16122
9958 routes = [ nats://127.0.0.1:16123 ]
9959 pool_size: -1
9960 }
9961 %s`, clusterCommonConf)))
9962
9963 confCluster1 := createConfFile(t, []byte(fmt.Sprintf(`
9964 server_name: a-1
9965 port: -1
9966 cluster: {
9967 name: cluster-a
9968 listen: 127.0.0.1:16123
9969 routes = [ nats://127.0.0.1:16122 ]
9970 pool_size: -1
9971 }
9972 %s`, clusterCommonConf)))
9973
9974 serverB := createConfFile(t, []byte(`
9975 server_name: b
9976 port: -1
9977 leafnodes: { port: 17422 }
9978 accounts: {
9979 system-a: {
9980 users: [ { user: sa, password: sa } ]
9981 exports: [{stream: *.system-a.>}]
9982 }
9983 system-b: {
9984 users: [ { user: sb, password: sb } ]
9985 imports: [ {stream: {subject: *.system-a.>, account: system-a }}]
9986 }
9987 $SYS: { users = [ {user: "s", password: "s"} ] }
9988 }`))
9989
9990 // Start server B
9991 srvB, _ := RunServerWithConfig(serverB)
9992 defer srvB.Shutdown()
9993
9994 // Start the cluster servers.
9995 srvA0, _ := RunServerWithConfig(confCluster0)
9996 defer srvA0.Shutdown()
9997 // Make sure this is connected first before starting the second server in cluster A.
9998 checkLeafNodeConnectedCount(t, srvB, 1)
9999 // Start second A server.
10000 srvA1, _ := RunServerWithConfig(confCluster1)
10001 defer srvA1.Shutdown()
10002 // Make sure they are routed together.
10003 checkNumRoutes(t, srvA0, 1)
10004 checkNumRoutes(t, srvA1, 1)
10005 // Make sure each cluster server is connected to server B.
10006 checkLeafNodeConnectedCount(t, srvB, 2)
10007
10008 // Create plain subscriber on server B attached to system-b account.
10009 ncB := natsConnect(t, srvB.ClientURL(), nats.UserInfo("sb", "sb"))
10010 defer ncB.Close()
10011 sub := natsSubSync(t, ncB, "*.system-a.events.>")
10012 subq := natsQueueSubSync(t, ncB, "*.system-a.events.objectnotfound", "SBQ")
10013 natsFlush(t, ncB)
10014
10015 // Create a subscription on SA1 (we will send from SA0). We want to make sure that
10016 // when subscription on B is removed, this does not affect the subject interest
10017 // in SA0 on behalf of SA1.
10018 ncSAA1 := natsConnect(t, srvA1.ClientURL(), nats.UserInfo("sa", "sa"))
10019 defer ncSAA1.Close()
10020 sub2 := natsSubSync(t, ncSAA1, "*.system-a.events.>")
10021 subq2 := natsQueueSubSync(t, ncSAA1, "*.system-a.events.objectnotfound", "SBQ")
10022 natsFlush(t, ncSAA1)
10023
10024 time.Sleep(250 * time.Millisecond)
10025
10026 // Connect to cluster A on SA0.
10027 ncA := natsConnect(t, srvA0.ClientURL(), nats.UserInfo("t", "t"))
10028 defer ncA.Close()
10029
10030 natsPub(t, ncA, "system-a.events.objectnotfound", []byte("EventA"))
10031 natsFlush(t, ncA)
10032
10033 natsNexMsg(t, sub, time.Second)
10034 natsNexMsg(t, sub2, time.Second)
10035 if _, err := subq.NextMsg(250 * time.Millisecond); err != nil {
10036 natsNexMsg(t, subq2, time.Second)
10037 }
10038
10039 // Unsubscribe the subscriptions from server B.
10040 natsUnsub(t, sub)
10041 natsUnsub(t, subq)
10042 natsFlush(t, ncB)
10043
10044 // Wait for subject propagation.
10045 time.Sleep(250 * time.Millisecond)
10046
10047 // Publish again, subscriptions on SA1 should receive it.
10048 natsPub(t, ncA, "system-a.events.objectnotfound", []byte("EventA"))
10049 natsFlush(t, ncA)
10050
10051 natsNexMsg(t, sub2, time.Second)
10052 natsNexMsg(t, subq2, time.Second)
10053 }
10054
10055 func TestLeafNodeServerKickClient(t *testing.T) {
10056 stmpl := `
10057 listen: 127.0.0.1:-1
10058 server_name: test-server
10059 leaf { listen: 127.0.0.1:-1 }
10060 `
10061 conf := createConfFile(t, []byte(stmpl))
10062 s, o := RunServerWithConfig(conf)
10063 defer s.Shutdown()
10064
10065 tmpl := `
10066 listen: 127.0.0.1:-1
10067 server_name: test-leaf
10068 leaf { remotes: [ { urls: [ nats-leaf://127.0.0.1:{LEAF_PORT} ] } ] }
10069 `
10070 tmpl = strings.Replace(tmpl, "{LEAF_PORT}", fmt.Sprintf("%d", o.LeafNode.Port), 1)
10071 lConf := createConfFile(t, []byte(tmpl))
10072 l, _ := RunServerWithConfig(lConf)
10073 defer l.Shutdown()
10074
10075 checkLeafNodeConnected(t, l)
10076
10077 // We want to make sure we can kick the leafnode connections as well as client connections.
10078 conns, err := s.Connz(&ConnzOptions{Account: globalAccountName})
10079 require_NoError(t, err)
10080 require_Equal(t, len(conns.Conns), 1)
10081 lid := conns.Conns[0].Cid
10082
10083 disconnectTime := time.Now()
10084 err = s.DisconnectClientByID(lid)
10085 require_NoError(t, err)
10086
10087 // Wait until we are reconnected.
10088 checkLeafNodeConnected(t, s)
10089
10090 // Look back up again and make sure start time indicates a restart, meaning kick worked.
10091 conns, err = s.Connz(&ConnzOptions{Account: globalAccountName})
10092 require_NoError(t, err)
10093 require_Equal(t, len(conns.Conns), 1)
10094 ln := conns.Conns[0]
10095 require_True(t, lid != ln.Cid)
10096 require_True(t, ln.Start.After(disconnectTime))
10097 }
10098
10099 func TestLeafNodeBannerNoClusterNameIfNoCluster(t *testing.T) {
10100 u, err := url.Parse("nats://127.0.0.1:1234")
10101 require_NoError(t, err)
10102
10103 opts := DefaultOptions()
10104 opts.ServerName = "LEAF_SERVER"
10105 opts.Cluster.Name = _EMPTY_
10106 opts.Cluster.Port = 0
10107 opts.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}}}
10108 opts.NoLog = false
10109
10110 s, err := NewServer(opts)
10111 require_NoError(t, err)
10112 defer func() {
10113 s.Shutdown()
10114 s.WaitForShutdown()
10115 }()
10116 l := &captureNoticeLogger{}
10117 s.SetLogger(l, false, false)
10118 s.Start()
10119
10120 if !s.ReadyForConnections(time.Second) {
10121 t.Fatal("Server not ready!")
10122 }
10123
10124 l.Lock()
10125 for _, n := range l.notices {
10126 if strings.Contains(n, "Cluster: ") {
10127 l.Unlock()
10128 t.Fatalf("Cluster name should not be displayed, got %q", n)
10129 }
10130 }
10131 l.Unlock()
10132 }
10133
10134 func TestLeafNodeCredFormatting(t *testing.T) {
10135 //create the operator/sys/account tree
10136 oKP, err := nkeys.CreateOperator()
10137 require_NoError(t, err)
10138 oPK, err := oKP.PublicKey()
10139 require_NoError(t, err)
10140
10141 oc := jwt.NewOperatorClaims(oPK)
10142 oc.Name = "O"
10143 oJWT, err := oc.Encode(oKP)
10144 require_NoError(t, err)
10145
10146 sysKP, err := nkeys.CreateAccount()
10147 require_NoError(t, err)
10148 sysPK, err := sysKP.PublicKey()
10149 require_NoError(t, err)
10150
10151 sys := jwt.NewAccountClaims(sysPK)
10152 sys.Name = "SYS"
10153 sysJWT, err := sys.Encode(oKP)
10154 require_NoError(t, err)
10155
10156 aKP, err := nkeys.CreateAccount()
10157 require_NoError(t, err)
10158 aPK, err := aKP.PublicKey()
10159 require_NoError(t, err)
10160
10161 ac := jwt.NewAccountClaims(aPK)
10162 ac.Name = "A"
10163 aJWT, err := ac.Encode(oKP)
10164 require_NoError(t, err)
10165
10166 uKP, err := nkeys.CreateUser()
10167 require_NoError(t, err)
10168 uSeed, err := uKP.Seed()
10169 require_NoError(t, err)
10170 uPK, err := uKP.PublicKey()
10171 require_NoError(t, err)
10172
10173 // build the config
10174 stmpl := fmt.Sprintf(`
10175 listen: 127.0.0.1:-1
10176 operator: %s
10177 system_account: %s
10178 resolver: MEM
10179 resolver_preload: {
10180 %s: %s
10181 %s: %s
10182 }
10183 leaf { listen: 127.0.0.1:-1 }
10184 `, oJWT, sysPK, sysPK, sysJWT, aPK, aJWT)
10185 conf := createConfFile(t, []byte(stmpl))
10186 s, o := RunServerWithConfig(conf)
10187 defer s.Shutdown()
10188
10189 // create the leaf node
10190 // generate the user credentials
10191 uc := jwt.NewUserClaims(uPK)
10192 uc.Name = "U"
10193 uc.Limits.Data = -1
10194 uc.Limits.Payload = -1
10195 uc.Permissions.Pub.Allow.Add(">")
10196 uc.Permissions.Sub.Allow.Add(">")
10197 uJWT, err := uc.Encode(aKP)
10198 require_NoError(t, err)
10199
10200 runLeaf := func(t *testing.T, creds []byte) {
10201 file, err := os.CreateTemp("", "tmp-*.creds")
10202 require_NoError(t, err)
10203 _, err = file.Write(creds)
10204 require_NoError(t, err)
10205 require_NoError(t, file.Close())
10206
10207 template := fmt.Sprintf(`
10208 listen: 127.0.0.1:-1
10209 leafnodes {
10210 remotes: [
10211 {
10212 urls: [ nats-leaf://127.0.0.1:%d ]
10213 credentials: "%s"
10214 }
10215 ]
10216 }`, o.LeafNode.Port, file.Name())
10217 conf := createConfFile(t, []byte(template))
10218 leaf, _ := RunServerWithConfig(conf)
10219 defer leaf.Shutdown()
10220 defer os.Remove(file.Name())
10221 checkLeafNodeConnected(t, leaf)
10222 }
10223
10224 creds, err := jwt.FormatUserConfig(uJWT, uSeed)
10225 require_NoError(t, err)
10226
10227 runLeaf(t, creds)
10228 runLeaf(t, bytes.ReplaceAll(creds, []byte{'\n'}, []byte{'\r', '\n'}))
10229 }
10230
10231 func TestLeafNodePermissionWithLiteralSubjectAndQueueInterest(t *testing.T) {
10232 hconf := createConfFile(t, []byte(`
10233 server_name: "HUB"
10234 listen: "127.0.0.1:-1"
10235 leafnodes {
10236 listen: "127.0.0.1:-1"
10237 }
10238 accounts {
10239 A {
10240 users: [
10241 { user: "user", password: "pwd",
10242 permissions: {
10243 subscribe: { allow: ["_INBOX.>", "my.subject"] }
10244 publish: {allow: [">"]}
10245 }
10246 }
10247 ]
10248 }
10249 }
10250 `))
10251 hub, ohub := RunServerWithConfig(hconf)
10252 defer hub.Shutdown()
10253
10254 lconf := createConfFile(t, []byte(fmt.Sprintf(`
10255 server_name: "LEAF"
10256 listen: "127.0.0.1:-1"
10257 leafnodes {
10258 remotes: [
10259 {url: "nats://user:[email protected]:%d", account: A}
10260 ]
10261 }
10262 accounts {
10263 A { users: [{user: user, password: pwd}] }
10264 }
10265 `, ohub.LeafNode.Port)))
10266 leaf, _ := RunServerWithConfig(lconf)
10267 defer leaf.Shutdown()
10268
10269 checkLeafNodeConnected(t, hub)
10270 checkLeafNodeConnected(t, leaf)
10271
10272 ncLeaf := natsConnect(t, leaf.ClientURL(), nats.UserInfo("user", "pwd"))
10273 defer ncLeaf.Close()
10274 natsQueueSub(t, ncLeaf, "my.subject", "queue", func(m *nats.Msg) {
10275 m.Respond([]byte("OK"))
10276 })
10277 natsFlush(t, ncLeaf)
10278
10279 ncHub := natsConnect(t, hub.ClientURL(), nats.UserInfo("user", "pwd"))
10280 defer ncHub.Close()
10281
10282 var resp *nats.Msg
10283 var err error
10284 checkFor(t, 5*time.Second, time.Second, func() error {
10285 // Make sure we don't fail the test on the first "no responders", might
10286 // take time for the sub to propagate.
10287 resp, err = ncHub.Request("my.subject", []byte("hello"), time.Second)
10288 return err
10289 })
10290 require_Equal(t, "OK", string(resp.Data))
10291 }
10292
10293 func TestLeafNodeQueueScopedImportDenyFiltersBroadQueueInterest(t *testing.T) {
10294 hconf := createConfFile(t, []byte(`
10295 server_name: "HUB"
10296 listen: "127.0.0.1:-1"
10297 leafnodes {
10298 listen: "127.0.0.1:-1"
10299 }
10300 accounts {
10301 A {
10302 users: [
10303 {
10304 user: "leaf"
10305 password: "pwd"
10306 permissions: {
10307 subscribe: {
10308 allow: [">"]
10309 deny: [
10310 "broad.secret workers"
10311 "exact.secret workers"
10312 ]
10313 }
10314 publish: { allow: [">"] }
10315 }
10316 }
10317 { user: "hub", password: "pwd" }
10318 ]
10319 }
10320 }
10321 `))
10322 hub, ohub := RunServerWithConfig(hconf)
10323 defer hub.Shutdown()
10324
10325 lconf := createConfFile(t, []byte(fmt.Sprintf(`
10326 server_name: "LEAF"
10327 listen: "127.0.0.1:-1"
10328 leafnodes {
10329 remotes: [
10330 { url: "nats://leaf:[email protected]:%d", account: A }
10331 ]
10332 }
10333 accounts {
10334 A { users: [{ user: "client", password: "pwd" }] }
10335 }
10336 `, ohub.LeafNode.Port)))
10337 leaf, _ := RunServerWithConfig(lconf)
10338 defer leaf.Shutdown()
10339
10340 checkLeafNodeConnected(t, hub)
10341 checkLeafNodeConnected(t, leaf)
10342
10343 ncLeaf := natsConnect(t, leaf.ClientURL(), nats.UserInfo("client", "pwd"))
10344 defer ncLeaf.Close()
10345 broadWorkers := natsQueueSubSync(t, ncLeaf, "broad.*", "workers")
10346 broadAuditors := natsQueueSubSync(t, ncLeaf, "broad.*", "auditors")
10347 exactWorkers := natsQueueSubSync(t, ncLeaf, "exact.secret", "workers")
10348 exactAuditors := natsQueueSubSync(t, ncLeaf, "exact.secret", "auditors")
10349 natsFlush(t, ncLeaf)
10350
10351 acc, err := hub.LookupAccount("A")
10352 require_NoError(t, err)
10353 checkFor(t, time.Second, 10*time.Millisecond, func() error {
10354 if !acc.sl.HasInterest("broad.public") || !acc.sl.HasInterest("exact.secret") {
10355 return fmt.Errorf("leaf queue interest has not propagated")
10356 }
10357 return nil
10358 })
10359
10360 ncHub := natsConnect(t, hub.ClientURL(), nats.UserInfo("hub", "pwd"))
10361 defer ncHub.Close()
10362 natsPub(t, ncHub, "broad.secret", []byte("broad blocked"))
10363 natsPub(t, ncHub, "broad.public", []byte("broad ok"))
10364 natsPub(t, ncHub, "exact.secret", []byte("exact blocked"))
10365 natsFlush(t, ncHub)
10366
10367 msg := natsNexMsg(t, broadWorkers, time.Second)
10368 require_Equal(t, "broad.public", msg.Subject)
10369 require_Equal(t, "broad ok", string(msg.Data))
10370
10371 msg = natsNexMsg(t, broadAuditors, time.Second)
10372 require_Equal(t, "broad.secret", msg.Subject)
10373 require_Equal(t, "broad blocked", string(msg.Data))
10374 msg = natsNexMsg(t, broadAuditors, time.Second)
10375 require_Equal(t, "broad.public", msg.Subject)
10376 require_Equal(t, "broad ok", string(msg.Data))
10377
10378 if _, err := exactWorkers.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
10379 t.Fatalf("Expected exact workers queue subscription to be denied, got %v", err)
10380 }
10381 msg = natsNexMsg(t, exactAuditors, time.Second)
10382 require_Equal(t, "exact.secret", msg.Subject)
10383 require_Equal(t, "exact blocked", string(msg.Data))
10384 }
10385
10386 func TestLeafNodePermissionWithGateways(t *testing.T) {
10387 usConf := createConfFile(t, []byte(`
10388 server_name: "US"
10389 listen: "127.0.0.1:-1"
10390 gateway {
10391 name: "US"
10392 listen: "127.0.0.1:-1"
10393 }
10394 accounts {
10395 sys { users: [{user: sys, password: sys}] }
10396 leaf { users: [{user: leaf, password: leaf}] }
10397 }
10398 system_account: sys
10399 `))
10400 us, ous := RunServerWithConfig(usConf)
10401 defer us.Shutdown()
10402
10403 euConf := createConfFile(t, fmt.Appendf(nil, `
10404 server_name: "EU"
10405 listen: "127.0.0.1:-1"
10406 gateway {
10407 name: "EU"
10408 listen: "127.0.0.1:-1"
10409 gateways: [
10410 {
10411 name: "US"
10412 urls: ["nats://127.0.0.1:%d"]
10413 }
10414 ]
10415 }
10416 leafnodes {
10417 listen: "127.0.0.1:-1"
10418 }
10419 accounts {
10420 sys { users: [{user: sys, password: sys}] }
10421 leaf {
10422 users: [
10423 {
10424 user: leaf
10425 password: leaf
10426 permissions: {
10427 publish: "bar"
10428 subscribe: "foo"
10429 }
10430 }
10431 ]
10432 }
10433 }
10434 system_account: sys
10435 `, ous.Gateway.Port))
10436 eu, oeu := RunServerWithConfig(euConf)
10437 defer eu.Shutdown()
10438
10439 waitForOutboundGateways(t, us, 1, 2*time.Second)
10440 waitForOutboundGateways(t, eu, 1, 2*time.Second)
10441 waitForInboundGateways(t, us, 1, 2*time.Second)
10442 waitForInboundGateways(t, eu, 1, 2*time.Second)
10443
10444 leafConf := createConfFile(t, fmt.Appendf(nil, `
10445 server_name: "LEAF"
10446 listen: "127.0.0.1:-1"
10447 leafnodes {
10448 remotes: [
10449 { url: "nats://leaf:[email protected]:%d" }
10450 ]
10451 }
10452 `, oeu.LeafNode.Port))
10453 leaf, _ := RunServerWithConfig(leafConf)
10454 defer leaf.Shutdown()
10455
10456 checkLeafNodeConnected(t, leaf)
10457
10458 // Run the service from EU leafnode.
10459 ncEU := natsConnect(t, leaf.ClientURL())
10460 defer ncEU.Close()
10461 natsSub(t, ncEU, "foo", func(m *nats.Msg) {
10462 m.Respond([]byte("response"))
10463 })
10464 natsFlush(t, ncEU)
10465
10466 // Wait for subject interest to propagate.
10467 checkGWInterestOnlyModeInterestOn(t, us, "EU", "leaf", "foo")
10468
10469 // Connect to the US server
10470 ncUS := natsConnect(t, us.ClientURL(), nats.UserInfo("leaf", "leaf"))
10471 defer ncUS.Close()
10472
10473 // Create a subscription on "bar" and send request on "foo"
10474 sub := natsSubSync(t, ncUS, "bar")
10475 // Wait for subject to propagate so we know that EU server
10476 // would know about the "bar" subscription.
10477 checkGWInterestOnlyModeInterestOn(t, eu, "US", "leaf", "bar")
10478 // Send the request and make sure we receive the reply.
10479 natsPubReq(t, ncUS, "foo", "bar", []byte("request"))
10480 reply := natsNexMsg(t, sub, time.Second)
10481 if string(reply.Data) != "response" {
10482 t.Fatalf("Invalid response: %q", reply.Data)
10483 }
10484 // Make sure that we don't blindly accept any reply because there
10485 // is the routing protocol. So create a sub on "baz" that the leaf
10486 // would not be allowed to reply to. We should not get the reply
10487 // to our request.
10488 sub2 := natsSubSync(t, ncUS, "baz")
10489 checkGWInterestOnlyModeInterestOn(t, eu, "US", "leaf", "baz")
10490 // Send the request. We should not get the message since the
10491 // leaf server does not have permission to publish on "baz".
10492 natsPubReq(t, ncUS, "foo", "baz", []byte("request2"))
10493 if msg, err := sub2.NextMsg(250 * time.Millisecond); err == nil {
10494 t.Fatalf("Should not have received the reply, got %q", msg.Data)
10495 }
10496 }
10497
10498 // Test that the inbound LMSG path checks for subject permissions.
10499 // Normally, a leaf node will check for ACLs before sending LMSG messages.
10500 // If it doesn't we still need to perform ACL checks on the hub side.
10501 func TestLeafNodeLMSGHonorsPublishPermissions(t *testing.T) {
10502 hubConf := createConfFile(t, []byte(`
10503 server_name: "HUB"
10504 listen: "127.0.0.1:-1"
10505 accounts {
10506 A {
10507 users = [
10508 { user: "a", password: "a" }
10509 {
10510 user: "leaf"
10511 password: "pwd"
10512 permissions: {
10513 publish: { allow: ["pub.ok"] }
10514 subscribe: { allow: [">"] }
10515 }
10516 }
10517 ]
10518 }
10519 }
10520 leafnodes {
10521 listen: "127.0.0.1:-1"
10522 compression: off
10523 }
10524 `))
10525 hub, ohub := RunServerWithConfig(hubConf)
10526 defer hub.Shutdown()
10527
10528 hlog := &captureErrorLogger{errCh: make(chan string, 4)}
10529 hub.SetLogger(hlog, false, false)
10530
10531 leafConn, err := net.DialTimeout("tcp", net.JoinHostPort(ohub.LeafNode.Host, fmt.Sprintf("%d", ohub.LeafNode.Port)), 2*time.Second)
10532 require_NoError(t, err)
10533 defer leafConn.Close()
10534
10535 br := bufio.NewReader(leafConn)
10536 _, err = br.ReadString('\n')
10537 require_NoError(t, err)
10538
10539 connectOp := fmt.Appendf(nil, "CONNECT {\"name\":\"leaf\",\"user\":%q,\"pass\":%q}\r\n", "leaf", "pwd")
10540 _, err = leafConn.Write(connectOp)
10541 require_NoError(t, err)
10542 _, err = leafConn.Write([]byte("PING\r\n"))
10543 require_NoError(t, err)
10544
10545 checkLeafNodeConnected(t, hub)
10546
10547 ncHub := natsConnect(t, hub.ClientURL(), nats.UserInfo("a", "a"))
10548 defer ncHub.Close()
10549
10550 subOK := natsSubSync(t, ncHub, "pub.ok")
10551 subBlocked := natsSubSync(t, ncHub, "pub.blocked")
10552 natsFlush(t, ncHub)
10553
10554 _, err = fmt.Fprintf(leafConn, "LMSG %s %d\r\n%s\r\n", "pub.ok", len("ok"), "ok")
10555 require_NoError(t, err)
10556 msg := natsNexMsg(t, subOK, time.Second)
10557 require_Equal(t, "ok", string(msg.Data))
10558
10559 _, err = fmt.Fprintf(leafConn, "LMSG %s %d\r\n%s\r\n", "pub.blocked", len("blocked"), "blocked")
10560 require_NoError(t, err)
10561 if msg, err := subBlocked.NextMsg(250 * time.Millisecond); err == nil {
10562 t.Fatalf("Should not have received the blocked publish, got %q", msg.Data)
10563 }
10564
10565 select {
10566 case errMsg := <-hlog.errCh:
10567 if !strings.Contains(errMsg, `Publish Violation on "pub.blocked"`) {
10568 t.Fatalf("Expected publish violation log, got %q", errMsg)
10569 }
10570 case <-time.After(time.Second):
10571 t.Fatal("Did not get expected publish violation log")
10572 }
10573 }
10574
10575 // Test that the hub side inbound leaf check still honors tracked reply
10576 // permissions such as allow_responses after the hub has tracked a reply
10577 // subject for a request sent to the leaf.
10578 func TestLeafNodeHubSideLMSGHonorsAllowResponses(t *testing.T) {
10579 hubConf := createConfFile(t, []byte(`
10580 server_name: "HUB"
10581 listen: "127.0.0.1:-1"
10582 accounts {
10583 A {
10584 users = [
10585 { user: "a", password: "a" }
10586 {
10587 user: "leaf"
10588 password: "pwd"
10589 permissions: {
10590 publish: { allow: ["svc.req"] }
10591 subscribe: { allow: ["svc.req"] }
10592 allow_responses: true
10593 }
10594 }
10595 ]
10596 }
10597 }
10598 leafnodes {
10599 listen: "127.0.0.1:-1"
10600 compression: off
10601 }
10602 `))
10603 hub, ohub := RunServerWithConfig(hubConf)
10604 defer hub.Shutdown()
10605
10606 leafConf := createConfFile(t, fmt.Appendf(nil, `
10607 server_name: "LEAF"
10608 listen: "127.0.0.1:-1"
10609 accounts {
10610 A {
10611 users = [ { user: "a", password: "a" } ]
10612 }
10613 }
10614 leafnodes {
10615 compression: off
10616 remotes = [
10617 {
10618 url: "nats://leaf:[email protected]:%d"
10619 account: A
10620 compression: off
10621 }
10622 ]
10623 }
10624 `, ohub.LeafNode.Port))
10625 leaf, _ := RunServerWithConfig(leafConf)
10626 defer leaf.Shutdown()
10627
10628 checkLeafNodeConnected(t, hub)
10629 checkLeafNodeConnected(t, leaf)
10630
10631 ncLeaf := natsConnect(t, leaf.ClientURL(), nats.UserInfo("a", "a"))
10632 defer ncLeaf.Close()
10633 reqCh := make(chan string, 1)
10634 natsSub(t, ncLeaf, "svc.req", func(m *nats.Msg) {
10635 select {
10636 case reqCh <- m.Reply:
10637 default:
10638 }
10639 })
10640 natsFlush(t, ncLeaf)
10641
10642 ncHub := natsConnect(t, hub.ClientURL(), nats.UserInfo("a", "a"))
10643 defer ncHub.Close()
10644
10645 reply := ncHub.NewRespInbox()
10646 sub := natsSubSync(t, ncHub, reply)
10647 natsFlush(t, ncHub)
10648
10649 natsPubReq(t, ncHub, "svc.req", reply, []byte("request"))
10650
10651 var trackedReply string
10652 select {
10653 case trackedReply = <-reqCh:
10654 case <-time.After(time.Second):
10655 t.Fatal("Did not receive request on leaf side")
10656 }
10657 require_Equal(t, reply, trackedReply)
10658
10659 var leafConn *client
10660 leaf.mu.Lock()
10661 for _, leafConn = range leaf.leafs {
10662 break
10663 }
10664 leaf.mu.Unlock()
10665 if leafConn == nil {
10666 t.Fatal("Expected a leaf connection on leaf side")
10667 }
10668
10669 _, err := fmt.Fprintf(leafConn.nc, "LMSG %s %d\r\n%s\r\n", reply, len("ok"), "ok")
10670 require_NoError(t, err)
10671
10672 resp := natsNexMsg(t, sub, time.Second)
10673 require_Equal(t, "ok", string(resp.Data))
10674 }
10675
10676 // Test that allow_responses works when the tracked reply subject has a
10677 // gateway routing prefix ($GNR...). deliverMsg tracks the reply under
10678 // the GW-routed form, so processInboundLeafMsg must also check
10679 // responseAllowed with the original (non-stripped) subject.
10680 func TestLeafNodeHubSideLMSGHonorsAllowResponsesGatewayRouted(t *testing.T) {
10681 hubConf := createConfFile(t, []byte(`
10682 server_name: "HUB"
10683 listen: "127.0.0.1:-1"
10684 accounts {
10685 A {
10686 users = [
10687 { user: "a", password: "a" }
10688 {
10689 user: "leaf"
10690 password: "pwd"
10691 permissions: {
10692 publish: { allow: ["svc.req"] }
10693 subscribe: { allow: ["svc.req"] }
10694 allow_responses: true
10695 }
10696 }
10697 ]
10698 }
10699 }
10700 leafnodes {
10701 listen: "127.0.0.1:-1"
10702 compression: off
10703 }
10704 `))
10705 hub, ohub := RunServerWithConfig(hubConf)
10706 defer hub.Shutdown()
10707
10708 leafConn, err := net.DialTimeout("tcp",
10709 net.JoinHostPort(ohub.LeafNode.Host, fmt.Sprintf("%d", ohub.LeafNode.Port)),
10710 2*time.Second)
10711 require_NoError(t, err)
10712 defer leafConn.Close()
10713
10714 br := bufio.NewReader(leafConn)
10715 _, err = br.ReadString('\n')
10716 require_NoError(t, err)
10717
10718 connectOp := fmt.Appendf(nil,
10719 "CONNECT {\"name\":\"leaf\",\"user\":%q,\"pass\":%q}\r\n", "leaf", "pwd")
10720 _, err = leafConn.Write(connectOp)
10721 require_NoError(t, err)
10722 _, err = leafConn.Write([]byte("PING\r\n"))
10723 require_NoError(t, err)
10724
10725 checkLeafNodeConnected(t, hub)
10726
10727 // Simulate the tracking that deliverMsg would perform when
10728 // delivering a gateway-routed request to the leaf: it stores
10729 // the reply under the full GW-routed form ($GNR...).
10730 gwRoutedReply := gwReplyPrefix + "AAAAAAA1.BBBBBBB2._INBOX.test"
10731
10732 var hubLeaf *client
10733 hub.mu.Lock()
10734 for _, hubLeaf = range hub.leafs {
10735 break
10736 }
10737 hub.mu.Unlock()
10738 require_NotNil(t, hubLeaf)
10739
10740 hubLeaf.mu.Lock()
10741 hubLeaf.replies[gwRoutedReply] = &resp{t: time.Now()}
10742 hubLeaf.mu.Unlock()
10743
10744 // Subscribe on the hub so we can verify delivery.
10745 ncHub := natsConnect(t, hub.ClientURL(), nats.UserInfo("a", "a"))
10746 defer ncHub.Close()
10747 sub := natsSubSync(t, ncHub, gwRoutedReply)
10748 natsFlush(t, ncHub)
10749
10750 // The leaf sends LMSG with the GW-routed reply as subject.
10751 // processInboundLeafMsg strips the $GNR prefix before the
10752 // permission check but must still find the tracked reply.
10753 _, err = fmt.Fprintf(leafConn, "LMSG %s %d\r\n%s\r\n",
10754 gwRoutedReply, len("ok"), "ok")
10755 require_NoError(t, err)
10756
10757 resp := natsNexMsg(t, sub, time.Second)
10758 require_Equal(t, "ok", string(resp.Data))
10759 }
10760
10761 // A leaf user with publish: { allow: [] } and allow_responses should
10762 // deny arbitrary publishes but still permit tracked reply responses.
10763 func TestLeafNodeHubSideLMSGEmptyAllowWithAllowResponses(t *testing.T) {
10764 hubConf := createConfFile(t, []byte(`
10765 server_name: "HUB"
10766 listen: "127.0.0.1:-1"
10767 accounts {
10768 A {
10769 users = [
10770 { user: "a", password: "a" }
10771 {
10772 user: "leaf"
10773 password: "pwd"
10774 permissions: {
10775 publish: { allow: [] }
10776 subscribe: { allow: [">"] }
10777 allow_responses: true
10778 }
10779 }
10780 ]
10781 }
10782 }
10783 leafnodes {
10784 listen: "127.0.0.1:-1"
10785 compression: off
10786 }
10787 `))
10788 hub, ohub := RunServerWithConfig(hubConf)
10789 defer hub.Shutdown()
10790
10791 leafConn, err := net.DialTimeout("tcp",
10792 net.JoinHostPort(ohub.LeafNode.Host, fmt.Sprintf("%d", ohub.LeafNode.Port)),
10793 2*time.Second)
10794 require_NoError(t, err)
10795 defer leafConn.Close()
10796
10797 br := bufio.NewReader(leafConn)
10798 _, err = br.ReadString('\n')
10799 require_NoError(t, err)
10800
10801 connectOp := fmt.Appendf(nil,
10802 "CONNECT {\"name\":\"leaf\",\"user\":%q,\"pass\":%q}\r\n", "leaf", "pwd")
10803 _, err = leafConn.Write(connectOp)
10804 require_NoError(t, err)
10805 _, err = leafConn.Write([]byte("PING\r\n"))
10806 require_NoError(t, err)
10807
10808 checkLeafNodeConnected(t, hub)
10809
10810 // Simulate a tracked reply: inject a reply entry on the
10811 // hub's leaf connection, then verify the leaf can respond on it.
10812 reply := "_INBOX.test123"
10813
10814 var hubLeaf *client
10815 hub.mu.Lock()
10816 for _, hubLeaf = range hub.leafs {
10817 break
10818 }
10819 hub.mu.Unlock()
10820 require_NotNil(t, hubLeaf)
10821
10822 hubLeaf.mu.Lock()
10823 hubLeaf.replies[reply] = &resp{t: time.Now()}
10824 hubLeaf.mu.Unlock()
10825
10826 ncHub := natsConnect(t, hub.ClientURL(), nats.UserInfo("a", "a"))
10827 defer ncHub.Close()
10828
10829 subReply := natsSubSync(t, ncHub, reply)
10830 natsFlush(t, ncHub)
10831
10832 _, err = fmt.Fprintf(leafConn, "LMSG %s %d\r\n%s\r\n",
10833 reply, len("ok"), "ok")
10834 require_NoError(t, err)
10835
10836 msg := natsNexMsg(t, subReply, time.Second)
10837 require_Equal(t, "ok", string(msg.Data))
10838
10839 // Arbitrary publish should be denied (and closes the connection).
10840 subBlocked := natsSubSync(t, ncHub, "not.allowed")
10841 natsFlush(t, ncHub)
10842
10843 _, err = fmt.Fprintf(leafConn, "LMSG %s %d\r\n%s\r\n",
10844 "not.allowed", len("blocked"), "blocked")
10845 require_NoError(t, err)
10846 if msg, err := subBlocked.NextMsg(250 * time.Millisecond); err == nil {
10847 t.Fatalf("Should not have received arbitrary publish, got %q", msg.Data)
10848 }
10849 }
10850
10851 // Test that the hub side allows JetStream API traffic.
10852 // This guards the regression where the hub rejected $JS.API.*
10853 func TestLeafNodeHubSideLMSGAllowsJSAPI(t *testing.T) {
10854 hubConf := createConfFile(t, []byte(fmt.Sprintf(`
10855 server_name: "HUB"
10856 listen: "127.0.0.1:-1"
10857 jetstream: { store_dir: %q }
10858 accounts {
10859 A {
10860 jetstream: enabled
10861 users = [
10862 { user: "a", password: "a" }
10863 { user: "leaf", password: "pwd" }
10864 ]
10865 }
10866 }
10867 leafnodes {
10868 listen: "127.0.0.1:-1"
10869 compression: off
10870 }
10871 `, t.TempDir())))
10872 hub, ohub := RunServerWithConfig(hubConf)
10873 defer hub.Shutdown()
10874
10875 leafConf := createConfFile(t, fmt.Appendf(nil, `
10876 server_name: "LEAF"
10877 listen: "127.0.0.1:-1"
10878 default_js_domain: {A:""}
10879 accounts {
10880 A {
10881 users = [ { user: "a", password: "a" } ]
10882 }
10883 }
10884 leafnodes {
10885 compression: off
10886 remotes = [
10887 {
10888 url: "nats://leaf:[email protected]:%d"
10889 account: A
10890 compression: off
10891 }
10892 ]
10893 }
10894 `, ohub.LeafNode.Port))
10895 leaf, _ := RunServerWithConfig(leafConf)
10896 defer leaf.Shutdown()
10897
10898 checkLeafNodeConnected(t, hub)
10899 checkLeafNodeConnected(t, leaf)
10900
10901 var l *client
10902 hub.mu.Lock()
10903 for _, l = range hub.leafs {
10904 break
10905 }
10906 hub.mu.Unlock()
10907 if l == nil {
10908 t.Fatal("Expected a leaf connection")
10909 }
10910
10911 l.mu.Lock()
10912 r := l.perms.sub.deny.Match(jsAllAPI)
10913 hasSyntheticJSDeny := len(r.psubs)+len(r.qsubs) > 0
10914 l.mu.Unlock()
10915 if !hasSyntheticJSDeny {
10916 t.Fatal("Expected synthetic JetStream deny on accepted leaf connection")
10917 }
10918
10919 checkSubInterest(t, leaf, "A", JSApiAccountInfo, time.Second)
10920 ncLeaf := natsConnect(t, leaf.ClientURL(), nats.UserInfo("a", "a"))
10921 defer ncLeaf.Close()
10922
10923 msg, err := ncLeaf.Request(JSApiAccountInfo, nil, time.Second)
10924 require_NoError(t, err)
10925 if !bytes.Contains(msg.Data, []byte(JSApiAccountInfoResponseType)) {
10926 t.Fatalf("Expected JetStream account info response, got %q", msg.Data)
10927 }
10928 }
10929
10930 // When the hub has a subject mapping "pub.ok" -> "internal.pub.ok",
10931 // a leaf allowed to publish "pub.ok" must not be rejected just because
10932 // "internal.pub.ok" is not in the allow list. The permission check
10933 // should evaluate the subject the leaf actually sent, not where the
10934 // hub remaps it locally.
10935 func TestLeafNodeLMSGPermissionsUseWireSubjectNotMapped(t *testing.T) {
10936 hubConf := createConfFile(t, []byte(`
10937 server_name: "HUB"
10938 listen: "127.0.0.1:-1"
10939 accounts {
10940 A {
10941 users = [
10942 { user: "a", password: "a" }
10943 {
10944 user: "leaf"
10945 password: "pwd"
10946 permissions: {
10947 publish: { allow: ["pub.ok"] }
10948 subscribe: { allow: [">"] }
10949 }
10950 }
10951 ]
10952 mappings = { "pub.ok": "internal.pub.ok" }
10953 }
10954 }
10955 leafnodes {
10956 listen: "127.0.0.1:-1"
10957 compression: off
10958 }
10959 `))
10960 hub, ohub := RunServerWithConfig(hubConf)
10961 defer hub.Shutdown()
10962
10963 leafConf := createConfFile(t, fmt.Appendf(nil, `
10964 server_name: "LEAF"
10965 listen: "127.0.0.1:-1"
10966 accounts {
10967 A {
10968 users = [ { user: "a", password: "a" } ]
10969 }
10970 }
10971 leafnodes {
10972 compression: off
10973 remotes = [
10974 {
10975 url: "nats://leaf:[email protected]:%d"
10976 account: A
10977 compression: off
10978 }
10979 ]
10980 }
10981 `, ohub.LeafNode.Port))
10982 leaf, _ := RunServerWithConfig(leafConf)
10983 defer leaf.Shutdown()
10984
10985 checkLeafNodeConnected(t, hub)
10986 checkLeafNodeConnected(t, leaf)
10987
10988 ncHub := natsConnect(t, hub.ClientURL(), nats.UserInfo("a", "a"))
10989 defer ncHub.Close()
10990
10991 // Subscribe to the mapped destination.
10992 sub := natsSubSync(t, ncHub, "internal.pub.ok")
10993 natsFlush(t, ncHub)
10994
10995 ncLeaf := natsConnect(t, leaf.ClientURL(), nats.UserInfo("a", "a"))
10996 defer ncLeaf.Close()
10997
10998 // The leaf publishes on the wire subject "pub.ok" which is in
10999 // the export allow list. The hub maps it to "internal.pub.ok"
11000 // for local delivery. The ACL check must use the wire subject.
11001 natsPub(t, ncLeaf, "pub.ok", []byte("hello"))
11002 natsFlush(t, ncLeaf)
11003
11004 msg := natsNexMsg(t, sub, time.Second)
11005 require_Equal(t, "internal.pub.ok", msg.Subject)
11006 require_Equal(t, "hello", string(msg.Data))
11007 }
11008
11009 // Test that a solicited leaf configured with hub: true still uses the
11010 // hub-side export ACLs on inbound LMSG.
11011 func TestLeafNodeSolicitedHubLMSGHonorsExportPermissions(t *testing.T) {
11012 spokeConf := createConfFile(t, []byte(`
11013 server_name: "SPOKE"
11014 listen: "127.0.0.1:-1"
11015 accounts {
11016 A {
11017 users = [
11018 { user: "a", password: "a" }
11019 { user: "leaf", password: "pwd" }
11020 ]
11021 }
11022 }
11023 leafnodes {
11024 listen: "127.0.0.1:-1"
11025 compression: off
11026 }
11027 `))
11028 spoke, ospoke := RunServerWithConfig(spokeConf)
11029 defer spoke.Shutdown()
11030
11031 hubConf := createConfFile(t, fmt.Appendf(nil, `
11032 server_name: "HUB"
11033 listen: "127.0.0.1:-1"
11034 accounts {
11035 A {
11036 users = [ { user: "a", password: "a" } ]
11037 }
11038 }
11039 leafnodes {
11040 compression: off
11041 remotes = [
11042 {
11043 url: "nats://leaf:[email protected]:%d"
11044 account: A
11045 compression: off
11046 hub: true
11047 deny_exports: ["pub.blocked"]
11048 }
11049 ]
11050 }
11051 `, ospoke.LeafNode.Port))
11052 hub, _ := RunServerWithConfig(hubConf)
11053 defer hub.Shutdown()
11054
11055 hlog := &captureErrorLogger{errCh: make(chan string, 4)}
11056 hub.SetLogger(hlog, false, false)
11057
11058 checkLeafNodeConnected(t, hub)
11059 checkLeafNodeConnected(t, spoke)
11060
11061 var hubLeaf *client
11062 hub.mu.Lock()
11063 for _, hubLeaf = range hub.leafs {
11064 break
11065 }
11066 hub.mu.Unlock()
11067 if hubLeaf == nil {
11068 t.Fatal("Expected a leaf connection on hub")
11069 }
11070 hubLeaf.mu.Lock()
11071 require_True(t, hubLeaf.isSolicitedLeafNode())
11072 require_True(t, hubLeaf.isHubLeafNode())
11073 hubLeaf.mu.Unlock()
11074
11075 ncHub := natsConnect(t, hub.ClientURL(), nats.UserInfo("a", "a"))
11076 defer ncHub.Close()
11077
11078 sub := natsSubSync(t, ncHub, "pub.blocked")
11079 natsFlush(t, ncHub)
11080
11081 var spokeLeaf *client
11082 spoke.mu.Lock()
11083 for _, spokeLeaf = range spoke.leafs {
11084 break
11085 }
11086 spoke.mu.Unlock()
11087 if spokeLeaf == nil {
11088 t.Fatal("Expected a leaf connection on spoke")
11089 }
11090
11091 _, err := fmt.Fprintf(spokeLeaf.nc, "LMSG %s %d\r\n%s\r\n", "pub.blocked", len("blocked"), "blocked")
11092 require_NoError(t, err)
11093
11094 if msg, err := sub.NextMsg(250 * time.Millisecond); err == nil {
11095 t.Fatalf("Should not have received the blocked publish, got %q", msg.Data)
11096 }
11097
11098 select {
11099 case errMsg := <-hlog.errCh:
11100 if !strings.Contains(errMsg, `Publish Violation on "pub.blocked"`) {
11101 t.Fatalf("Expected publish violation log, got %q", errMsg)
11102 }
11103 case <-time.After(time.Second):
11104 t.Fatal("Did not get expected publish violation log")
11105 }
11106 }
11107
11108 // Test that when a solicited remote is configured with hub: true, direct LMSG
11109 // sent from that hub still respects the local leaf permissions on the accepting
11110 // spoke server.
11111 func TestLeafNodeSpokeSideLMSGHonorsLocalPermissions(t *testing.T) {
11112 spokeConf := createConfFile(t, []byte(`
11113 server_name: "SPOKE"
11114 listen: "127.0.0.1:-1"
11115 accounts {
11116 A {
11117 users = [
11118 { user: "a", password: "a" }
11119 {
11120 user: "leaf"
11121 password: "pwd"
11122 permissions: {
11123 publish: { allow: ["pub.ok"] }
11124 subscribe: { allow: [">"] }
11125 }
11126 }
11127 ]
11128 }
11129 }
11130 leafnodes {
11131 listen: "127.0.0.1:-1"
11132 compression: off
11133 }
11134 `))
11135 spoke, ospoke := RunServerWithConfig(spokeConf)
11136 defer spoke.Shutdown()
11137
11138 hubConf := createConfFile(t, fmt.Appendf(nil, `
11139 server_name: "HUB"
11140 listen: "127.0.0.1:-1"
11141 accounts {
11142 A {
11143 users = [ { user: "a", password: "a" } ]
11144 }
11145 }
11146 leafnodes {
11147 compression: off
11148 remotes = [
11149 {
11150 url: "nats://leaf:[email protected]:%d"
11151 account: A
11152 compression: off
11153 hub: true
11154 }
11155 ]
11156 }
11157 `, ospoke.LeafNode.Port))
11158 hub, _ := RunServerWithConfig(hubConf)
11159 defer hub.Shutdown()
11160
11161 checkLeafNodeConnected(t, hub)
11162 checkLeafNodeConnected(t, spoke)
11163
11164 var hubLeaf *client
11165 hub.mu.Lock()
11166 for _, hubLeaf = range hub.leafs {
11167 break
11168 }
11169 hub.mu.Unlock()
11170 if hubLeaf == nil {
11171 t.Fatal("Expected a leaf connection on hub")
11172 }
11173 hubLeaf.mu.Lock()
11174 require_True(t, hubLeaf.isSolicitedLeafNode())
11175 require_True(t, hubLeaf.isHubLeafNode())
11176 hubLeaf.mu.Unlock()
11177
11178 var spokeLeaf *client
11179 spoke.mu.Lock()
11180 for _, spokeLeaf = range spoke.leafs {
11181 break
11182 }
11183 spoke.mu.Unlock()
11184 if spokeLeaf == nil {
11185 t.Fatal("Expected a leaf connection on spoke")
11186 }
11187 spokeLeaf.mu.Lock()
11188 require_False(t, spokeLeaf.isSolicitedLeafNode())
11189 require_True(t, spokeLeaf.isSpokeLeafNode())
11190 spokeLeaf.mu.Unlock()
11191
11192 ncSpoke := natsConnect(t, spoke.ClientURL(), nats.UserInfo("a", "a"))
11193 defer ncSpoke.Close()
11194
11195 sub := natsSubSync(t, ncSpoke, "pub.*")
11196 natsFlush(t, ncSpoke)
11197
11198 _, err := fmt.Fprintf(hubLeaf.nc, "LMSG %s %d\r\n%s\r\n", "pub.blocked", len("blocked"), "blocked")
11199 require_NoError(t, err)
11200 _, err = fmt.Fprintf(hubLeaf.nc, "LMSG %s %d\r\n%s\r\n", "pub.ok", len("ok"), "ok")
11201 require_NoError(t, err)
11202
11203 msg := natsNexMsg(t, sub, time.Second)
11204 require_Equal(t, "pub.ok", msg.Subject)
11205 require_Equal(t, "ok", string(msg.Data))
11206 }
11207
11208 // Test that the inbound LMSG path checks for import permissions.
11209 // Normally, the sender side will check ACLs before sending LMSG messages.
11210 // If it doesn't we still need to perform ACL checks on the receiving leaf side.
11211 func TestLeafNodeLMSGHonorsImportPermissions(t *testing.T) {
11212 hubConf := createConfFile(t, []byte(`
11213 server_name: "HUB"
11214 listen: "127.0.0.1:-1"
11215 accounts {
11216 A {
11217 users = [
11218 { user: "a", password: "a" }
11219 { user: "leaf", password: "pwd" }
11220 ]
11221 }
11222 }
11223 leafnodes {
11224 listen: "127.0.0.1:-1"
11225 compression: off
11226 }
11227 `))
11228 hub, ohub := RunServerWithConfig(hubConf)
11229 defer hub.Shutdown()
11230
11231 leafConf := createConfFile(t, fmt.Appendf(nil, `
11232 server_name: "LEAF"
11233 listen: "127.0.0.1:-1"
11234 accounts {
11235 A {
11236 users = [ { user: "a", password: "a" } ]
11237 }
11238 }
11239 leafnodes {
11240 compression: off
11241 remotes = [
11242 {
11243 url: "nats://leaf:[email protected]:%d"
11244 account: A
11245 compression: off
11246 deny_imports: ["imp.blocked"]
11247 }
11248 ]
11249 }
11250 `, ohub.LeafNode.Port))
11251 leaf, _ := RunServerWithConfig(leafConf)
11252 defer leaf.Shutdown()
11253
11254 checkLeafNodeConnected(t, hub)
11255 checkLeafNodeConnected(t, leaf)
11256
11257 ncLeaf := natsConnect(t, leaf.ClientURL(), nats.UserInfo("a", "a"))
11258 defer ncLeaf.Close()
11259
11260 sub := natsSubSync(t, ncLeaf, "imp.*")
11261 natsFlush(t, ncLeaf)
11262
11263 leafConn := func() net.Conn {
11264 var l *client
11265 hub.mu.Lock()
11266 for _, l = range hub.leafs {
11267 break
11268 }
11269 hub.mu.Unlock()
11270 return l.nc
11271 }
11272
11273 ncHubLeaf := leafConn()
11274
11275 _, err := fmt.Fprintf(ncHubLeaf, "LMSG %s %d\r\n%s\r\n", "imp.blocked", len("blocked"), "blocked")
11276 require_NoError(t, err)
11277 checkLeafNodeConnected(t, hub)
11278 checkLeafNodeConnected(t, leaf)
11279 _, err = fmt.Fprintf(ncHubLeaf, "LMSG %s %d\r\n%s\r\n", "imp.ok", len("ok"), "ok")
11280 require_NoError(t, err)
11281
11282 msg := natsNexMsg(t, sub, time.Second)
11283 require_Equal(t, "imp.ok", msg.Subject)
11284 require_Equal(t, "ok", string(msg.Data))
11285 }
11286
11287 func TestLeafNodesDisableRemote(t *testing.T) {
11288 hubConf := createConfFile(t, []byte(`
11289 server_name: "HUB"
11290 listen: "127.0.0.1:-1"
11291 accounts {
11292 leaf1 { users: [{user: leaf1, password: pwd}] }
11293 leaf2 { users: [{user: leaf2, password: pwd}] }
11294 }
11295 leafnodes {
11296 listen: "127.0.0.1:-1"
11297 }
11298 `))
11299 hub, ohub := RunServerWithConfig(hubConf)
11300 defer hub.Shutdown()
11301
11302 port := ohub.LeafNode.Port
11303 leafTmpl := `
11304 server_name: "LEAF"
11305 listen: "127.0.0.1:-1"
11306 leafnodes {
11307 reconnect_interval: "50ms"
11308 remotes: [
11309 {
11310 url: "nats://leaf1:[email protected]:%d"
11311 disabled: %v
11312 }
11313 {
11314 url: "nats://leaf2:[email protected]:%d"
11315 }
11316 ]
11317 }
11318 `
11319 // Start with "disabled: true" to make sure that we don't solicit it
11320 // when starting the server.
11321 leafConf := createConfFile(t, fmt.Appendf(nil, leafTmpl, port, true, port))
11322 leaf, _ := RunServerWithConfig(leafConf)
11323 defer leaf.Shutdown()
11324
11325 // Wait for more than the reconnect interval to make sure that we don't
11326 // reconnect the connection that should have been disabled.
11327 time.Sleep(100 * time.Millisecond)
11328
11329 // Verify that we have only 1 leaf
11330 checkLeafNodeConnected(t, hub)
11331 checkLeafNodeConnected(t, leaf)
11332
11333 reconnectCh := make(chan struct{}, 2)
11334 ncl1 := natsConnect(t, hub.ClientURL(), nats.UserInfo("leaf1", "pwd"),
11335 nats.ReconnectWait(50*time.Millisecond),
11336 nats.ReconnectJitter(time.Millisecond, time.Millisecond),
11337 nats.ReconnectHandler(func(_ *nats.Conn) {
11338 reconnectCh <- struct{}{}
11339 }))
11340 defer ncl1.Close()
11341 sub1 := natsSubSync(t, ncl1, "foo")
11342 natsFlush(t, ncl1)
11343
11344 ncl2 := natsConnect(t, hub.ClientURL(), nats.UserInfo("leaf2", "pwd"),
11345 nats.ReconnectWait(50*time.Millisecond),
11346 nats.ReconnectJitter(time.Millisecond, time.Millisecond),
11347 nats.ReconnectHandler(func(_ *nats.Conn) {
11348 reconnectCh <- struct{}{}
11349 }))
11350 defer ncl2.Close()
11351 sub2 := natsSubSync(t, ncl2, "foo")
11352 natsFlush(t, ncl2)
11353
11354 checkSubInterest(t, leaf, globalAccountName, "foo", time.Second)
11355
11356 nc := natsConnect(t, leaf.ClientURL())
11357 defer nc.Close()
11358
11359 natsPub(t, nc, "foo", []byte("hello"))
11360 natsFlush(t, nc)
11361
11362 // We should not receive on leaf1
11363 _, err := sub1.NextMsg(100 * time.Millisecond)
11364 require_Error(t, err, nats.ErrTimeout)
11365
11366 // But should receive on leaf2.
11367 msg := natsNexMsg(t, sub2, time.Second)
11368 require_Equal(t, string(msg.Data), "hello")
11369
11370 // Enable leaf1, which means set "disabled" to false.
11371 reloadUpdateConfig(t, leaf, leafConf, fmt.Sprintf(leafTmpl, port, false, port))
11372
11373 // Check that we have 2 leaf node connections now.
11374 checkLeafNodeConnectedCount(t, hub, 2)
11375 checkLeafNodeConnectedCount(t, leaf, 2)
11376
11377 // Verify connectivity.
11378 natsPub(t, nc, "foo", []byte("hello2"))
11379
11380 msg = natsNexMsg(t, sub1, time.Second)
11381 require_Equal(t, string(msg.Data), "hello2")
11382
11383 msg = natsNexMsg(t, sub2, time.Second)
11384 require_Equal(t, string(msg.Data), "hello2")
11385
11386 // Disable again.
11387 reloadUpdateConfig(t, leaf, leafConf, fmt.Sprintf(leafTmpl, port, true, port))
11388
11389 // Wait for more than the reconnect interval to make sure that we don't
11390 // reconnect the connection that should have been disabled.
11391 time.Sleep(100 * time.Millisecond)
11392 // Verify that we have only 1 leaf
11393 checkLeafNodeConnected(t, hub)
11394 checkLeafNodeConnected(t, leaf)
11395
11396 // Now send a message again.
11397 natsPub(t, nc, "foo", []byte("hello3"))
11398 natsFlush(t, nc)
11399 // We should not receive on leaf1
11400 _, err = sub1.NextMsg(100 * time.Millisecond)
11401 require_Error(t, err, nats.ErrTimeout)
11402
11403 // We should still receive for leaf2
11404 msg = natsNexMsg(t, sub2, time.Second)
11405 require_Equal(t, string(msg.Data), "hello3")
11406
11407 // Enable again.
11408 reloadUpdateConfig(t, leaf, leafConf, fmt.Sprintf(leafTmpl, port, false, port))
11409
11410 checkLeafNodeConnectedCount(t, hub, 2)
11411 checkLeafNodeConnectedCount(t, leaf, 2)
11412
11413 // Now shutdown hub.
11414 hub.Shutdown()
11415
11416 // Wait to be disconnected
11417 checkLeafNodeConnectedCount(t, leaf, 0)
11418
11419 // Wait at least some reconnect interval.
11420 time.Sleep(100 * time.Millisecond)
11421
11422 // Now disable leaf1 one more time to make sure we stop soliciting when we were
11423 // not currently connected.
11424 reloadUpdateConfig(t, leaf, leafConf, fmt.Sprintf(leafTmpl, port, true, port))
11425
11426 // Restart hub
11427 hub = RunServer(ohub)
11428 defer hub.Shutdown()
11429
11430 // Verify that we have only 1 leaf
11431 checkLeafNodeConnected(t, hub)
11432 checkLeafNodeConnected(t, leaf)
11433
11434 // Wait for clients to reconnect
11435 for range 2 {
11436 select {
11437 case <-reconnectCh:
11438 case <-time.After(time.Second):
11439 t.Fatal("Client failed to reconnect")
11440 }
11441 }
11442
11443 // Wait for subject propagation
11444 checkSubInterest(t, leaf, globalAccountName, "foo", time.Second)
11445
11446 // Now send a message again.
11447 natsPub(t, nc, "foo", []byte("hello4"))
11448 natsFlush(t, nc)
11449 // We should not receive on leaf1
11450 _, err = sub1.NextMsg(100 * time.Millisecond)
11451 require_Error(t, err, nats.ErrTimeout)
11452
11453 // We should still receive for leaf2
11454 msg = natsNexMsg(t, sub2, time.Second)
11455 require_Equal(t, string(msg.Data), "hello4")
11456 }
11457
11458 func TestLeafNodeIsolatedLeafSubjectPropagationGlobal(t *testing.T) {
11459 for tname, isolated := range map[string]bool{
11460 "Isolated": true,
11461 "Normal": false,
11462 } {
11463 t.Run(tname, func(t *testing.T) {
11464 hubTmpl := `
11465 port: -1
11466 server_name: "%s"
11467 accounts {
11468 HA { users: [{user: HA, password: pwd}] }
11469 }
11470 leafnodes {
11471 port: -1
11472 isolate_leafnode_interest: %v
11473 }
11474 `
11475 confH := createConfFile(t, []byte(fmt.Sprintf(hubTmpl, "H1", isolated)))
11476 sh, oh := RunServerWithConfig(confH)
11477 defer sh.Shutdown()
11478
11479 spokeTmpl := `
11480 port: -1
11481 server_name: "%s"
11482 accounts {
11483 A { users: [{user: A, password: pwd}] }
11484 }
11485 leafnodes {
11486 remotes [
11487 {
11488 url: "nats://HA:[email protected]:%d"
11489 local: "A"
11490 }
11491 ]
11492 }
11493 `
11494
11495 confSP1 := createConfFile(t, []byte(fmt.Sprintf(spokeTmpl, "SP1", oh.LeafNode.Port)))
11496 sp1, _ := RunServerWithConfig(confSP1)
11497 defer sp1.Shutdown()
11498
11499 confSP2 := createConfFile(t, []byte(fmt.Sprintf(spokeTmpl, "SP2", oh.LeafNode.Port)))
11500 sp2, _ := RunServerWithConfig(confSP2)
11501 defer sp2.Shutdown()
11502
11503 checkLeafNodeConnectedCount(t, sh, 2)
11504 checkLeafNodeConnectedCount(t, sp1, 1)
11505 checkLeafNodeConnectedCount(t, sp2, 1)
11506
11507 // We expect that the hub side will have answered the request from the spoke for
11508 // isolation if needed, but the spokes themselves will not themselves isolate
11509 // subscription interest in the other direction unless also configured to do so.
11510 for _, c := range sh.leafs {
11511 require_Equal(t, c.leaf.isolated, isolated)
11512 }
11513 for _, c := range sp1.leafs {
11514 require_False(t, c.leaf.isolated)
11515 }
11516 for _, c := range sp2.leafs {
11517 require_False(t, c.leaf.isolated)
11518 }
11519
11520 nch := natsConnect(t, sh.ClientURL(), nats.UserInfo("HA", "pwd"))
11521 nc1 := natsConnect(t, sp1.ClientURL(), nats.UserInfo("A", "pwd"))
11522
11523 // Create a north-south subscription on the hub that should be visible to both spokes.
11524 nssub, err := nch.SubscribeSync("northsouth")
11525 require_NoError(t, err)
11526 checkSubInterest(t, sh, "HA", "northsouth", time.Second) // Visible to the hub.
11527 checkSubInterest(t, sp1, "A", "northsouth", time.Second) // Visible to both spokes.
11528 checkSubInterest(t, sp2, "A", "northsouth", time.Second) // Visible to both spokes.
11529
11530 // The spoke subscriptions should be visible to the hub in all cases, but only
11531 // visible to other spokes if they are not isolated.
11532 ewsub, err := nc1.SubscribeSync("eastwest")
11533 require_NoError(t, err)
11534 checkSubInterest(t, sh, "HA", "eastwest", time.Second) // Visible to the hub.
11535 checkSubInterest(t, sp1, "A", "eastwest", time.Second) // Visible to the spoke with the sub.
11536 if isolated {
11537 checkSubNoInterest(t, sp2, "A", "eastwest", time.Second) // Not visible to the other spoke.
11538 } else {
11539 checkSubInterest(t, sp2, "A", "eastwest", time.Second) // Visible to the other spoke.
11540 }
11541 require_NoError(t, ewsub.Unsubscribe())
11542 checkSubNoInterest(t, sh, "HA", "eastwest", time.Second)
11543 checkSubNoInterest(t, sp1, "A", "eastwest", time.Second)
11544 checkSubNoInterest(t, sp2, "A", "eastwest", time.Second)
11545
11546 // ... but a subscription from the hub should be visible to both.
11547 require_NoError(t, nssub.Unsubscribe())
11548 checkSubNoInterest(t, sh, "HA", "northsouth", time.Second)
11549 checkSubNoInterest(t, sp1, "A", "northsouth", time.Second)
11550 checkSubNoInterest(t, sp2, "A", "northsouth", time.Second)
11551 })
11552 }
11553 }
11554
11555 func TestLeafNodeIsolatedLeafSubjectPropagationRequestIsolation(t *testing.T) {
11556 for tname, isolated := range map[string]bool{
11557 "Isolated": true,
11558 "Normal": false,
11559 } {
11560 t.Run(tname, func(t *testing.T) {
11561 hubTmpl := `
11562 port: -1
11563 server_name: "%s"
11564 accounts {
11565 HA { users: [{user: HA, password: pwd}] }
11566 }
11567 leafnodes {
11568 port: -1
11569 }
11570 `
11571 confH := createConfFile(t, []byte(fmt.Sprintf(hubTmpl, "H1")))
11572 sh, oh := RunServerWithConfig(confH)
11573 defer sh.Shutdown()
11574
11575 spokeTmpl := `
11576 port: -1
11577 server_name: "%s"
11578 accounts {
11579 A { users: [{user: A, password: pwd}] }
11580 }
11581 leafnodes {
11582 remotes [
11583 {
11584 url: "nats://HA:[email protected]:%d"
11585 local: "A"
11586 request_isolation: %v
11587 }
11588 ]
11589 }
11590 `
11591
11592 confSP1 := createConfFile(t, []byte(fmt.Sprintf(spokeTmpl, "SP1", oh.LeafNode.Port, isolated)))
11593 sp1, _ := RunServerWithConfig(confSP1)
11594 defer sp1.Shutdown()
11595
11596 confSP2 := createConfFile(t, []byte(fmt.Sprintf(spokeTmpl, "SP2", oh.LeafNode.Port, isolated)))
11597 sp2, _ := RunServerWithConfig(confSP2)
11598 defer sp2.Shutdown()
11599
11600 checkLeafNodeConnectedCount(t, sh, 2)
11601 checkLeafNodeConnectedCount(t, sp1, 1)
11602 checkLeafNodeConnectedCount(t, sp2, 1)
11603
11604 // We expect that the hub side will have answered the request from the spoke for
11605 // isolation if needed, but the spokes themselves will not themselves isolate
11606 // subscription interest in the other direction unless also configured to do so.
11607 for _, c := range sh.leafs {
11608 require_Equal(t, c.leaf.isolated, isolated)
11609 }
11610 for _, c := range sp1.leafs {
11611 require_False(t, c.leaf.isolated)
11612 }
11613 for _, c := range sp2.leafs {
11614 require_False(t, c.leaf.isolated)
11615 }
11616
11617 nch := natsConnect(t, sh.ClientURL(), nats.UserInfo("HA", "pwd"))
11618 nc1 := natsConnect(t, sp1.ClientURL(), nats.UserInfo("A", "pwd"))
11619
11620 // Create a north-south subscription on the hub that should be visible to both spokes.
11621 nssub, err := nch.SubscribeSync("northsouth")
11622 require_NoError(t, err)
11623 checkSubInterest(t, sh, "HA", "northsouth", time.Second) // Visible to the hub.
11624 checkSubInterest(t, sp1, "A", "northsouth", time.Second) // Visible to both spokes.
11625 checkSubInterest(t, sp2, "A", "northsouth", time.Second) // Visible to both spokes.
11626
11627 // The spoke subscriptions should be visible to the hub in all cases, but only
11628 // visible to other spokes if they are not isolated.
11629 ewsub, err := nc1.SubscribeSync("eastwest")
11630 require_NoError(t, err)
11631 checkSubInterest(t, sh, "HA", "eastwest", time.Second) // Visible to the hub.
11632 checkSubInterest(t, sp1, "A", "eastwest", time.Second) // Visible to the spoke with the sub.
11633 if isolated {
11634 checkSubNoInterest(t, sp2, "A", "eastwest", time.Second) // Not visible to the other spoke.
11635 } else {
11636 checkSubInterest(t, sp2, "A", "eastwest", time.Second) // Visible to the other spoke.
11637 }
11638 require_NoError(t, ewsub.Unsubscribe())
11639 checkSubNoInterest(t, sh, "HA", "eastwest", time.Second)
11640 checkSubNoInterest(t, sp1, "A", "eastwest", time.Second)
11641 checkSubNoInterest(t, sp2, "A", "eastwest", time.Second)
11642
11643 // ... but a subscription from the hub should be visible to both.
11644 require_NoError(t, nssub.Unsubscribe())
11645 checkSubNoInterest(t, sh, "HA", "northsouth", time.Second)
11646 checkSubNoInterest(t, sp1, "A", "northsouth", time.Second)
11647 checkSubNoInterest(t, sp2, "A", "northsouth", time.Second)
11648 })
11649 }
11650 }
11651
11652 func TestLeafNodeIsolatedLeafSubjectPropagationLocalIsolation(t *testing.T) {
11653 for tname, isolated := range map[string]bool{
11654 "Isolated": true,
11655 "Normal": false,
11656 } {
11657 t.Run(tname, func(t *testing.T) {
11658 spokeTmpl := `
11659 port: -1
11660 server_name: "%s"
11661 accounts {
11662 A { users: [{user: A, password: pwd}] }
11663 }
11664 leafnodes {
11665 port: -1
11666 }
11667 `
11668
11669 confSP1 := createConfFile(t, []byte(fmt.Sprintf(spokeTmpl, "SP1")))
11670 sp1, osp1 := RunServerWithConfig(confSP1)
11671 defer sp1.Shutdown()
11672
11673 confSP2 := createConfFile(t, []byte(fmt.Sprintf(spokeTmpl, "SP2")))
11674 sp2, osp2 := RunServerWithConfig(confSP2)
11675 defer sp2.Shutdown()
11676
11677 hubTmpl := `
11678 port: -1
11679 server_name: "%s"
11680 accounts {
11681 HA { users: [{user: HA, password: pwd}] }
11682 }
11683 leafnodes {
11684 port: -1
11685 remotes [
11686 {
11687 url: "nats://A:[email protected]:%d"
11688 local: "HA"
11689 isolate: %v
11690 hub: true
11691 },
11692 {
11693 url: "nats://A:[email protected]:%d"
11694 local: "HA"
11695 isolate: %v
11696 hub: true
11697 }
11698 ]
11699 }
11700 `
11701 confH := createConfFile(t, []byte(fmt.Sprintf(hubTmpl, "H1", osp1.LeafNode.Port, isolated, osp2.LeafNode.Port, isolated)))
11702 sh, _ := RunServerWithConfig(confH)
11703 defer sh.Shutdown()
11704
11705 checkLeafNodeConnectedCount(t, sh, 2)
11706 checkLeafNodeConnectedCount(t, sp1, 1)
11707 checkLeafNodeConnectedCount(t, sp2, 1)
11708
11709 // We expect that the hub side will have answered the request from the spoke for
11710 // isolation if needed, but the spokes themselves will not themselves isolate
11711 // subscription interest in the other direction unless also configured to do so.
11712 for _, c := range sh.leafs {
11713 require_Equal(t, c.leaf.isolated, isolated)
11714 }
11715 for _, c := range sp1.leafs {
11716 require_False(t, c.leaf.isolated)
11717 }
11718 for _, c := range sp2.leafs {
11719 require_False(t, c.leaf.isolated)
11720 }
11721
11722 nch := natsConnect(t, sh.ClientURL(), nats.UserInfo("HA", "pwd"))
11723 nc1 := natsConnect(t, sp1.ClientURL(), nats.UserInfo("A", "pwd"))
11724
11725 // Create a north-south subscription on the hub that should be visible to both spokes.
11726 nssub, err := nch.SubscribeSync("northsouth")
11727 require_NoError(t, err)
11728 checkSubInterest(t, sh, "HA", "northsouth", time.Second) // Visible to the hub.
11729 checkSubInterest(t, sp1, "A", "northsouth", time.Second) // Visible to both spokes.
11730 checkSubInterest(t, sp2, "A", "northsouth", time.Second) // Visible to both spokes.
11731
11732 // The spoke subscriptions should be visible to the hub in all cases, but only
11733 // visible to other spokes if they are not isolated.
11734 ewsub, err := nc1.SubscribeSync("eastwest")
11735 require_NoError(t, err)
11736 checkSubInterest(t, sh, "HA", "eastwest", time.Second) // Visible to the hub.
11737 checkSubInterest(t, sp1, "A", "eastwest", time.Second) // Visible to the spoke with the sub.
11738 if isolated {
11739 checkSubNoInterest(t, sp2, "A", "eastwest", time.Second) // Not visible to the other spoke.
11740 } else {
11741 checkSubInterest(t, sp2, "A", "eastwest", time.Second) // Visible to the other spoke.
11742 }
11743 require_NoError(t, ewsub.Unsubscribe())
11744 checkSubNoInterest(t, sh, "HA", "eastwest", time.Second)
11745 checkSubNoInterest(t, sp1, "A", "eastwest", time.Second)
11746 checkSubNoInterest(t, sp2, "A", "eastwest", time.Second)
11747
11748 // ... but a subscription from the hub should be visible to both.
11749 require_NoError(t, nssub.Unsubscribe())
11750 checkSubNoInterest(t, sh, "HA", "northsouth", time.Second)
11751 checkSubNoInterest(t, sp1, "A", "northsouth", time.Second)
11752 checkSubNoInterest(t, sp2, "A", "northsouth", time.Second)
11753 })
11754 }
11755 }
11756
11757 func TestLeafNodeDaisyChainWithAccountImportExport(t *testing.T) {
11758 hubConf := createConfFile(t, []byte(`
11759 server_name: hub
11760 listen: "127.0.0.1:-1"
11761
11762 leafnodes {
11763 listen: "127.0.0.1:-1"
11764 }
11765 accounts {
11766 SYS: {
11767 users: [{ user: s, password: s}],
11768 },
11769 ODC: {
11770 jetstream: enabled
11771 users: [
11772 {
11773 user: u, password: u,
11774 permissions: {
11775 publish: {deny: ["local.>","hub2leaf.>"]}
11776 subscribe: {deny: ["local.>","leaf2leaf.>"]}
11777 }
11778 }
11779 ]
11780 }
11781 }
11782 `))
11783 hub, ohub := RunServerWithConfig(hubConf)
11784 defer hub.Shutdown()
11785
11786 storeDir := t.TempDir()
11787 leafJSConf := createConfFile(t, fmt.Appendf(nil, `
11788 server_name: leaf-js
11789 listen: "127.0.0.1:-1"
11790
11791 jetstream {
11792 store_dir="%s/leaf-js"
11793 domain=leaf-js
11794 }
11795 accounts {
11796 ODC: {
11797 jetstream: enabled
11798 users: [{ user: u, password: u}]
11799 },
11800 }
11801 leafnodes {
11802 remotes [
11803 {
11804 urls: ["leaf://u:[email protected]:%d"] # connects to hub
11805 account: ODC
11806 }
11807 ]
11808 }
11809 `, storeDir, ohub.LeafNode.Port))
11810 leafJS, _ := RunServerWithConfig(leafJSConf)
11811 defer leafJS.Shutdown()
11812
11813 checkLeafNodeConnected(t, hub)
11814 checkLeafNodeConnected(t, leafJS)
11815
11816 otherConf := createConfFile(t, []byte(`
11817 server_name: other
11818 listen: "127.0.0.1:-1"
11819 leafnodes {
11820 listen: "127.0.0.1:-1"
11821 }
11822 `))
11823 other, oother := RunServerWithConfig(otherConf)
11824 defer other.Shutdown()
11825
11826 tmpl := `
11827 server_name: %s
11828 listen: "127.0.0.1:-1"
11829
11830 leafnodes {
11831 listen: "127.0.0.1:-1"
11832 remotes [
11833 {
11834 urls: ["leaf://u:[email protected]:%d"]
11835 account: ODC_DEV
11836 }
11837 {
11838 urls: ["leaf://127.0.0.1:%d"]
11839 account: ODC_DEV
11840 }
11841 ]
11842 }
11843 cluster {
11844 name: "hubsh"
11845 listen: "127.0.0.1:-1"
11846 %s
11847 }
11848 accounts: {
11849 ODC_DEV: {
11850 users: [
11851 {user: o, password: o}
11852 ]
11853 imports: [
11854 {service: {account: "SH1", subject: "$JS.leaf-sh.API.>"}}
11855 {stream: {account: "SH1", subject: "sync.leaf-sh.jspush.>"}}
11856 ]
11857 exports: [
11858 {stream: ">"}
11859 {service: ">", response_type: "Singleton"}
11860 ]
11861 }
11862 SH1: {
11863 users: [
11864 {user: s, password: s}
11865 ]
11866 exports: [
11867 {service: "$JS.leaf-sh.API.>", response_type: "Stream"}
11868 {stream: "sync.leaf-sh.jspush.>"}
11869 ]
11870 }
11871 }
11872 `
11873 hubSh1Conf := createConfFile(t, fmt.Appendf(nil, tmpl, "hubsh1", ohub.LeafNode.Port, oother.LeafNode.Port, _EMPTY_))
11874 hubSh1, ohubSh1 := RunServerWithConfig(hubSh1Conf)
11875 defer hubSh1.Shutdown()
11876
11877 hubSh2Conf := createConfFile(t, fmt.Appendf(nil, tmpl, "hubsh2", ohub.LeafNode.Port, oother.LeafNode.Port,
11878 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", ohubSh1.Cluster.Port)))
11879 hubSh2, ohubSh2 := RunServerWithConfig(hubSh2Conf)
11880 defer hubSh2.Shutdown()
11881
11882 checkClusterFormed(t, hubSh1, hubSh2)
11883
11884 checkLeafNodeConnectedCount(t, hub, 3)
11885 checkLeafNodeConnectedCount(t, hubSh1, 2)
11886 checkLeafNodeConnectedCount(t, hubSh2, 2)
11887
11888 leafShConf := createConfFile(t, fmt.Appendf(nil, `
11889 server_name: leafsh
11890 listen: "127.0.0.1:-1"
11891
11892 jetstream {
11893 store_dir="%s/leafsh"
11894 domain=leaf-sh
11895 }
11896 accounts {
11897 SH: {
11898 jetstream: enabled
11899 users: [{user: u, password: u}]
11900 }
11901 }
11902 leafnodes {
11903 remotes [
11904 {
11905 urls: ["leaf://s:[email protected]:%d"]
11906 account: SH
11907 }
11908 ]
11909 }
11910 `, storeDir, ohubSh2.LeafNode.Port))
11911 leafSh, _ := RunServerWithConfig(leafShConf)
11912 defer leafSh.Shutdown()
11913
11914 checkLeafNodeConnectedCount(t, hubSh2, 3)
11915 checkLeafNodeConnected(t, leafSh)
11916
11917 ncLeafSh, jsLeafSh := jsClientConnect(t, leafSh, nats.UserInfo("u", "u"))
11918 defer ncLeafSh.Close()
11919
11920 sc := &nats.StreamConfig{
11921 Name: "leaf-sh",
11922 Subjects: []string{"leaf2leaf.>"},
11923 Retention: nats.LimitsPolicy,
11924 Storage: nats.FileStorage,
11925 AllowRollup: true,
11926 AllowDirect: true,
11927 }
11928 _, err := jsLeafSh.AddStream(sc)
11929 require_NoError(t, err)
11930
11931 ncLeafJS, jsLeafJS := jsClientConnect(t, leafJS, nats.UserInfo("u", "u"))
11932 defer ncLeafJS.Close()
11933
11934 sc = &nats.StreamConfig{
11935 Name: "leaf-js",
11936 Retention: nats.LimitsPolicy,
11937 Storage: nats.FileStorage,
11938 AllowRollup: true,
11939 AllowDirect: true,
11940 Sources: []*nats.StreamSource{
11941 {
11942 Name: "leaf-sh",
11943 External: &nats.ExternalStream{
11944 APIPrefix: "$JS.leaf-sh.API",
11945 DeliverPrefix: "sync.leaf-sh.jspush"},
11946 },
11947 },
11948 }
11949 _, err = jsLeafJS.AddStream(sc)
11950 require_NoError(t, err)
11951
11952 for range 10 {
11953 _, err = jsLeafSh.Publish("leaf2leaf.v1.test", []byte("hello"))
11954 require_NoError(t, err)
11955 }
11956
11957 check := func(js nats.JetStreamContext, stream string) {
11958 t.Helper()
11959 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
11960 si, err := js.StreamInfo(stream)
11961 if err != nil {
11962 return err
11963 }
11964 if n := si.State.Msgs; n != 10 {
11965 return fmt.Errorf("Expected 10 messages, got %v", n)
11966 }
11967 return nil
11968 })
11969 }
11970 check(jsLeafSh, "leaf-sh")
11971 check(jsLeafJS, "leaf-js")
11972
11973 acc := other.GlobalAccount()
11974 acc.mu.RLock()
11975 sr := acc.sl.ReverseMatch("sync.leaf-sh.jspush.>")
11976 acc.mu.RUnlock()
11977 require_Len(t, len(sr.psubs), 0)
11978 }
11979
11980 func TestLeafNodeConfigureWriteDeadline(t *testing.T) {
11981 o1, o2 := DefaultOptions(), DefaultOptions()
11982
11983 o1.LeafNode.WriteDeadline = 5 * time.Second
11984 o1.LeafNode.Host = "127.0.0.1"
11985 o1.LeafNode.Port = -1
11986 s1 := RunServer(o1)
11987 defer s1.Shutdown()
11988
11989 s1URL, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", o1.LeafNode.Port))
11990 o2.Cluster.Name = "somethingelse"
11991 o2.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{s1URL}}}
11992 s2 := RunServer(o2)
11993 defer s2.Shutdown()
11994
11995 checkLeafNodeConnected(t, s2)
11996
11997 s1.mu.RLock()
11998 defer s1.mu.RUnlock()
11999
12000 for _, r := range s1.leafs {
12001 require_Equal(t, r.out.wdl, 5*time.Second)
12002 }
12003 }
12004
12005 func TestLeafNodeConfigureWriteTimeoutPolicy(t *testing.T) {
12006 for name, policy := range map[string]WriteTimeoutPolicy{
12007 "Default": WriteTimeoutPolicyDefault,
12008 "Retry": WriteTimeoutPolicyRetry,
12009 "Close": WriteTimeoutPolicyClose,
12010 } {
12011 t.Run(name, func(t *testing.T) {
12012 o1 := testDefaultOptionsForGateway("B")
12013 o1.Gateway.WriteTimeout = policy
12014 s1 := runGatewayServer(o1)
12015 defer s1.Shutdown()
12016
12017 o2 := testGatewayOptionsFromToWithServers(t, "A", "B", s1)
12018 s2 := runGatewayServer(o2)
12019 defer s2.Shutdown()
12020
12021 waitForOutboundGateways(t, s2, 1, time.Second)
12022 waitForInboundGateways(t, s1, 1, time.Second)
12023 waitForOutboundGateways(t, s1, 1, time.Second)
12024
12025 s1.mu.RLock()
12026 defer s1.mu.RUnlock()
12027
12028 for _, r := range s1.leafs {
12029 if policy == WriteTimeoutPolicyDefault {
12030 require_Equal(t, r.out.wtp, WriteTimeoutPolicyRetry)
12031 } else {
12032 require_Equal(t, r.out.wtp, policy)
12033 }
12034 }
12035 })
12036 }
12037 }
12038
12039 // https://github.com/nats-io/nats-server/issues/7441
12040 func TestLeafNodesBasicTokenAuth(t *testing.T) {
12041 hubConf := createConfFile(t, []byte(`
12042 server_name: "HUB"
12043 listen: "127.0.0.1:-1"
12044 authorization {
12045 token: secret
12046 }
12047 leafnodes {
12048 listen: "127.0.0.1:-1"
12049 }
12050 `))
12051 hub, ohub := RunServerWithConfig(hubConf)
12052 defer hub.Shutdown()
12053
12054 port := ohub.LeafNode.Port
12055 leafTmpl := `
12056 server_name: "LEAF"
12057 listen: "127.0.0.1:-1"
12058 leafnodes {
12059 remotes: [
12060 { url: "nats://[email protected]:%d" }
12061 ]
12062 }
12063 `
12064 leafConf := createConfFile(t, fmt.Appendf(nil, leafTmpl, port))
12065 leaf, _ := RunServerWithConfig(leafConf)
12066 defer leaf.Shutdown()
12067
12068 // Verify that we have only 1 leaf
12069 checkLeafNodeConnected(t, hub)
12070 checkLeafNodeConnected(t, leaf)
12071 }
12072
12073 func TestLeafNodeServiceImportRebuildsRequestInfoHeader(t *testing.T) {
12074 hubConf := createConfFile(t, []byte(`
12075 server_name: "HUB"
12076 listen: "127.0.0.1:-1"
12077 accounts {
12078 A {
12079 users = [ { user: "a", pass: "a" }, { user: "leaf", pass: "pwd" } ]
12080 imports = [ { service: { account: B, subject: "svc" } } ]
12081 }
12082 B {
12083 users = [ { user: "b", pass: "b" } ]
12084 exports = [ { service: "svc", accounts: [A] } ]
12085 }
12086 }
12087 leafnodes {
12088 listen: "127.0.0.1:-1"
12089 authorization {
12090 account: A
12091 }
12092 }
12093 `))
12094 hub, ohub := RunServerWithConfig(hubConf)
12095 defer hub.Shutdown()
12096
12097 leafConf := createConfFile(t, []byte(fmt.Sprintf(`
12098 server_name: "LEAF"
12099 listen: "127.0.0.1:-1"
12100 accounts {
12101 A {
12102 users = [ { user: "a", pass: "a" } ]
12103 }
12104 }
12105 leafnodes {
12106 remotes = [
12107 {
12108 url: "nats-leaf://leaf:[email protected]:%d"
12109 account: A
12110 }
12111 ]
12112 }
12113 `, ohub.LeafNode.Port)))
12114 leaf, _ := RunServerWithConfig(leafConf)
12115 defer leaf.Shutdown()
12116
12117 checkLeafNodeConnected(t, hub)
12118 checkLeafNodeConnected(t, leaf)
12119
12120 ncSvc := natsConnect(t, hub.ClientURL(), nats.UserInfo("b", "b"))
12121 defer ncSvc.Close()
12122
12123 rcvCh := make(chan *nats.Msg, 1)
12124 _, err := ncSvc.Subscribe("svc", func(m *nats.Msg) {
12125 rcvCh <- m
12126 require_NoError(t, m.Respond([]byte("ok")))
12127 })
12128 require_NoError(t, err)
12129 require_NoError(t, ncSvc.Flush())
12130
12131 ncLeaf := natsConnect(t, leaf.ClientURL(), nats.UserInfo("a", "a"))
12132 defer ncLeaf.Close()
12133
12134 req := nats.NewMsg("svc")
12135 req.Header = nats.Header{}
12136 req.Header.Set(ClientInfoHdr, `{"acc":"EVIL","user":"mallory","host":"badhost"}`)
12137
12138 _, err = ncLeaf.RequestMsg(req, time.Second)
12139 require_NoError(t, err)
12140
12141 msg := require_ChanRead(t, rcvCh, time.Second)
12142 hdr := msg.Header.Get(ClientInfoHdr)
12143 require_NotEqual(t, hdr, _EMPTY_)
12144
12145 var ci ClientInfo
12146 require_NoError(t, json.Unmarshal([]byte(hdr), &ci))
12147 require_Equal(t, ci.Account, "A")
12148 require_Equal(t, ci.User, _EMPTY_)
12149 require_Equal(t, ci.Host, _EMPTY_)
12150 }
12151
12152 func TestLeafNodeNoAccPanicOnLeafSubBeforeConnect(t *testing.T) {
12153 o := DefaultOptions()
12154 o.LeafNode.Port = -1
12155 // Default compression is s2_auto. This used to bypass the parser's
12156 // pre-CONNECT guard because the handshake timeout was tracked outside
12157 // c.atmr, allowing LS+ through before CONNECT set c.acc.
12158 s := RunServer(o)
12159 defer s.Shutdown()
12160
12161 addr := fmt.Sprintf("127.0.0.1:%d", o.LeafNode.Port)
12162 c, err := net.Dial("tcp", addr)
12163 require_NoError(t, err)
12164 defer c.Close()
12165
12166 // Read the INFO.
12167 br := bufio.NewReader(c)
12168 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12169 l, _, err := br.ReadLine()
12170 require_NoError(t, err)
12171 if !strings.HasPrefix(string(l), "INFO") {
12172 t.Fatalf("Expected INFO, got %q", l)
12173 }
12174
12175 // Send LS+ without CONNECT first. This should not panic the server.
12176 _, err = c.Write([]byte("LS+ test\r\n"))
12177 require_NoError(t, err)
12178
12179 // The server should close the connection.
12180 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12181 buf := make([]byte, 256)
12182 for {
12183 _, err = c.Read(buf)
12184 if err != nil {
12185 break
12186 }
12187 }
12188
12189 // Make sure the server is still running.
12190 s.mu.Lock()
12191 shutdown := s.isShuttingDown()
12192 s.mu.Unlock()
12193 if shutdown {
12194 t.Fatal("Server should not have shutdown")
12195 }
12196 }
12197
12198 func TestLeafNodeNoAccPanicOnLeafUnsubBeforeConnect(t *testing.T) {
12199 o := DefaultOptions()
12200 o.LeafNode.Port = -1
12201 s := RunServer(o)
12202 defer s.Shutdown()
12203
12204 addr := fmt.Sprintf("127.0.0.1:%d", o.LeafNode.Port)
12205 c, err := net.Dial("tcp", addr)
12206 require_NoError(t, err)
12207 defer c.Close()
12208
12209 // Read the INFO.
12210 br := bufio.NewReader(c)
12211 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12212 l, _, err := br.ReadLine()
12213 require_NoError(t, err)
12214 if !strings.HasPrefix(string(l), "INFO") {
12215 t.Fatalf("Expected INFO, got %q", l)
12216 }
12217
12218 // Send LS- without CONNECT first. This should not panic the server.
12219 _, err = c.Write([]byte("LS- test\r\n"))
12220 require_NoError(t, err)
12221
12222 // The server should close the connection.
12223 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12224 buf := make([]byte, 256)
12225 for {
12226 _, err = c.Read(buf)
12227 if err != nil {
12228 break
12229 }
12230 }
12231
12232 // Make sure the server is still running.
12233 s.mu.Lock()
12234 shutdown := s.isShuttingDown()
12235 s.mu.Unlock()
12236 if shutdown {
12237 t.Fatal("Server should not have shutdown")
12238 }
12239 }
12240
12241 func TestLeafNodeNoAccPanicOnLeafErrLoopDetectedBeforeConnect(t *testing.T) {
12242 conf := createConfFile(t, []byte(`
12243 listen: "127.0.0.1:-1"
12244 leafnodes {
12245 listen: "127.0.0.1:-1"
12246 }
12247 `))
12248 s, opts := RunServerWithConfig(conf)
12249 defer s.Shutdown()
12250
12251 addr := fmt.Sprintf("127.0.0.1:%d", opts.LeafNode.Port)
12252 c, err := net.Dial("tcp", addr)
12253 require_NoError(t, err)
12254 defer c.Close()
12255
12256 // Read the INFO.
12257 br := bufio.NewReader(c)
12258 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12259 l, _, err := br.ReadLine()
12260 require_NoError(t, err)
12261 if !strings.HasPrefix(string(l), "INFO") {
12262 t.Fatalf("Expected INFO, got %q", l)
12263 }
12264
12265 // Send the loop-detected error before CONNECT. This should not panic the server.
12266 _, err = c.Write([]byte("-ERR 'Loop detected'\r\n"))
12267 require_NoError(t, err)
12268
12269 // The server should close the connection.
12270 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12271 buf := make([]byte, 256)
12272 for {
12273 _, err = c.Read(buf)
12274 if err != nil {
12275 break
12276 }
12277 }
12278
12279 // Make sure the server is still running.
12280 s.mu.Lock()
12281 shutdown := s.isShuttingDown()
12282 s.mu.Unlock()
12283 if shutdown {
12284 t.Fatal("Server should not have shutdown")
12285 }
12286 }
12287
12288 func TestLeafNodeLeafSubBeforeConnectCompressionEffect(t *testing.T) {
12289 for _, test := range []struct {
12290 name string
12291 compression string
12292 }{
12293 {"compression off", CompressionOff},
12294 {"compression s2_auto", CompressionS2Auto},
12295 } {
12296 t.Run(test.name, func(t *testing.T) {
12297 o := DefaultOptions()
12298 o.LeafNode.Port = -1
12299 o.LeafNode.Compression.Mode = test.compression
12300 s := RunServer(o)
12301 defer s.Shutdown()
12302
12303 addr := fmt.Sprintf("127.0.0.1:%d", o.LeafNode.Port)
12304 c, err := net.Dial("tcp", addr)
12305 require_NoError(t, err)
12306 defer c.Close()
12307
12308 br := bufio.NewReader(c)
12309 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12310 l, _, err := br.ReadLine()
12311 require_NoError(t, err)
12312 if !strings.HasPrefix(string(l), "INFO") {
12313 t.Fatalf("Expected INFO, got %q", l)
12314 }
12315
12316 // Send LS+ without CONNECT.
12317 _, err = c.Write([]byte("LS+ test\r\n"))
12318 require_NoError(t, err)
12319
12320 // Read the error response before the connection is closed.
12321 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12322 l, _, err = br.ReadLine()
12323 require_NoError(t, err)
12324 errMsg := string(l)
12325
12326 if !strings.Contains(errMsg, "Authorization Violation") {
12327 t.Fatalf("Expected auth violation error, got %q", errMsg)
12328 }
12329
12330 // Make sure the server is still running.
12331 s.mu.Lock()
12332 shutdown := s.isShuttingDown()
12333 s.mu.Unlock()
12334 if shutdown {
12335 t.Fatal("Server should not have shutdown")
12336 }
12337 })
12338 }
12339 }
12340
12341 func TestLeafNodeInfoBeforeConnectStillRequiresConnect(t *testing.T) {
12342 o := DefaultOptions()
12343 o.LeafNode.Port = -1
12344 o.LeafNode.Compression.Mode = CompressionS2Auto
12345 s := RunServer(o)
12346 defer s.Shutdown()
12347
12348 addr := fmt.Sprintf("127.0.0.1:%d", o.LeafNode.Port)
12349 c, err := net.Dial("tcp", addr)
12350 require_NoError(t, err)
12351 defer c.Close()
12352
12353 br := bufio.NewReader(c)
12354 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12355 l, _, err := br.ReadLine()
12356 require_NoError(t, err)
12357 require_True(t, strings.HasPrefix(string(l), "INFO"))
12358
12359 // INFO is allowed before CONNECT for compressed leaf-node negotiation.
12360 _, err = c.Write([]byte("INFO {\"compression\":\"off\"}\r\n"))
12361 require_NoError(t, err)
12362
12363 // CONNECT is still required after INFO; other protocols must be rejected.
12364 _, err = c.Write([]byte("LS+ test\r\n"))
12365 require_NoError(t, err)
12366
12367 require_NoError(t, c.SetReadDeadline(time.Now().Add(2*time.Second)))
12368 l, _, err = br.ReadLine()
12369 require_NoError(t, err)
12370 require_True(t, strings.Contains(string(l), "Authorization Violation"))
12371 }
12372
12373 func TestLeafNodeInfoBeforeConnectRejectedWhenCompressionOff(t *testing.T) {
12374 o := DefaultOptions()
12375 o.LeafNode.Port = -1
12376 o.LeafNode.Compression.Mode = CompressionOff
12377 s := RunServer(o)
12378 defer s.Shutdown()
12379
12380 addr := fmt.Sprintf("127.0.0.1:%d", o.LeafNode.Port)
12381 c, err := net.Dial("tcp", addr)
12382 require_NoError(t, err)
12383 defer c.Close()
12384
12385 br := bufio.NewReader(c)
12386 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12387 l, _, err := br.ReadLine()
12388 require_NoError(t, err)
12389 require_True(t, strings.HasPrefix(string(l), "INFO"))
12390
12391 _, err = c.Write([]byte("INFO {\"nonce\":\"attacker\"}\r\n"))
12392 require_NoError(t, err)
12393
12394 require_NoError(t, c.SetReadDeadline(time.Now().Add(2*time.Second)))
12395 l, _, err = br.ReadLine()
12396 require_NoError(t, err)
12397 require_True(t, strings.Contains(string(l), "Authorization Violation"))
12398 }
12399
12400 func TestLeafNodeInboundInfoDoesNotOverrideNonce(t *testing.T) {
12401 o := DefaultOptions()
12402 o.LeafNode.Compression.Mode = CompressionS2Auto
12403 s := New(o)
12404
12405 nonce := []byte("server-issued-nonce")
12406 c := &client{
12407 srv: s,
12408 kind: LEAF,
12409 leaf: &leaf{},
12410 nonce: append([]byte(nil), nonce...),
12411 }
12412 c.flags.set(compressionNegotiated)
12413
12414 c.processLeafnodeInfo(&Info{Nonce: "attacker-controlled"})
12415
12416 require_True(t, bytes.Equal(c.nonce, nonce))
12417 }
12418
12419 func TestLeafNodeSecondInfoBeforeConnectDoesNotPanic(t *testing.T) {
12420 for _, test := range []struct {
12421 name string
12422 secondInfo string
12423 }{
12424 {"remote_account", `INFO {"remote_account":"attacker"}`},
12425 {"connect_info", `INFO {"connect_info":true}`},
12426 } {
12427 t.Run(test.name, func(t *testing.T) {
12428 o := DefaultOptions()
12429 o.LeafNode.Port = -1
12430 o.LeafNode.Compression.Mode = CompressionS2Auto
12431 s := RunServer(o)
12432 defer s.Shutdown()
12433
12434 addr := fmt.Sprintf("127.0.0.1:%d", o.LeafNode.Port)
12435 c, err := net.Dial("tcp", addr)
12436 require_NoError(t, err)
12437 defer c.Close()
12438
12439 br := bufio.NewReader(c)
12440 require_NoError(t, c.SetReadDeadline(time.Now().Add(2*time.Second)))
12441 l, _, err := br.ReadLine()
12442 require_NoError(t, err)
12443 require_True(t, strings.HasPrefix(string(l), "INFO"))
12444
12445 // The first INFO is accepted so inbound compression can negotiate.
12446 _, err = c.Write([]byte("INFO {}\r\n"))
12447 require_NoError(t, err)
12448
12449 // A second INFO before CONNECT used to panic the server.
12450 _, err = c.Write([]byte(test.secondInfo + "\r\n"))
12451 require_NoError(t, err)
12452
12453 // Reject the connection, but keep the server alive.
12454 require_NoError(t, c.SetReadDeadline(time.Now().Add(2*time.Second)))
12455 l, _, err = br.ReadLine()
12456 require_NoError(t, err)
12457 require_True(t, strings.Contains(string(l), "Authorization Violation"))
12458
12459 s.mu.Lock()
12460 shutdown := s.isShuttingDown()
12461 s.mu.Unlock()
12462 if shutdown {
12463 t.Fatal("Server should not have shutdown")
12464 }
12465 })
12466 }
12467 }
12468
12469 func TestLeafNodeNoAccPanicOnLeafSubBeforeConnectOperatorMode(t *testing.T) {
12470 // Setup operator JWT-based server with leafnode port.
12471 // This confirms that even with full operator/JWT auth configured,
12472 // a raw TCP connection can bypass auth and trigger the panic.
12473 sysAcc, _ := nkeys.CreateAccount()
12474 sysAccPub, _ := sysAcc.PublicKey()
12475
12476 okp, _ := nkeys.FromSeed(oSeed)
12477 opub, _ := okp.PublicKey()
12478
12479 // Create operator claim with system account.
12480 oc := jwt.NewOperatorClaims(opub)
12481 oc.SystemAccount = sysAccPub
12482 operatorJwt, err := oc.Encode(okp)
12483 require_NoError(t, err)
12484
12485 // Create the system account JWT.
12486 sysAccClaim := jwt.NewAccountClaims(sysAccPub)
12487 sysAccJwt, err := sysAccClaim.Encode(okp)
12488 require_NoError(t, err)
12489
12490 conf := createConfFile(t, []byte(fmt.Sprintf(`
12491 port: -1
12492 server_name: OP
12493 operator: %s
12494 system_account: %s
12495 resolver: MEMORY
12496 resolver_preload: {
12497 %s: %s
12498 }
12499 leafnodes {
12500 listen: "127.0.0.1:-1"
12501 }
12502 `, operatorJwt, sysAccPub, sysAccPub, sysAccJwt)))
12503 s, opts := RunServerWithConfig(conf)
12504 defer s.Shutdown()
12505
12506 addr := fmt.Sprintf("127.0.0.1:%d", opts.LeafNode.Port)
12507 c, err := net.Dial("tcp", addr)
12508 require_NoError(t, err)
12509 defer c.Close()
12510
12511 // Read the INFO.
12512 br := bufio.NewReader(c)
12513 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12514 l, _, err := br.ReadLine()
12515 require_NoError(t, err)
12516 if !strings.HasPrefix(string(l), "INFO") {
12517 t.Fatalf("Expected INFO, got %q", l)
12518 }
12519
12520 // Send LS+ without CONNECT first, bypassing JWT auth entirely.
12521 // Without the fix this would panic on nil c.acc dereference.
12522 _, err = c.Write([]byte("LS+ test\r\n"))
12523 require_NoError(t, err)
12524
12525 // The server should close the connection.
12526 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12527 buf := make([]byte, 256)
12528 for {
12529 _, err = c.Read(buf)
12530 if err != nil {
12531 break
12532 }
12533 }
12534
12535 // Make sure the server is still running.
12536 s.mu.Lock()
12537 shutdown := s.isShuttingDown()
12538 s.mu.Unlock()
12539 if shutdown {
12540 t.Fatal("Server should not have shutdown")
12541 }
12542 }
12543
12544 func TestLeafNodeNoAccPanicOnProcessLeafNodeConnect(t *testing.T) {
12545 o := DefaultOptions()
12546 o.LeafNode.Port = -1
12547 o.LeafNode.AuthTimeout = 0.001 // Very short auth timeout (1ms)
12548 s := RunServer(o)
12549 defer s.Shutdown()
12550
12551 addr := fmt.Sprintf("127.0.0.1:%d", o.LeafNode.Port)
12552 c, err := net.Dial("tcp", addr)
12553 require_NoError(t, err)
12554 defer c.Close()
12555
12556 // Read the INFO.
12557 br := bufio.NewReader(c)
12558 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12559 l, _, err := br.ReadLine()
12560 require_NoError(t, err)
12561 if !strings.HasPrefix(string(l), "INFO") {
12562 t.Fatalf("Expected INFO, got %q", l)
12563 }
12564
12565 // Wait for the auth timeout to fire, then send CONNECT with cluster.
12566 // This races with the auth timeout closing the connection, which is
12567 // the scenario from #7989 where c.acc ends up nil.
12568 time.Sleep(5 * time.Millisecond)
12569
12570 connect := `CONNECT {"verbose":false,"pedantic":false,"cluster":"test-cluster"}`
12571 c.Write([]byte(connect + "\r\n"))
12572
12573 // The server should close the connection without panicking.
12574 c.SetReadDeadline(time.Now().Add(2 * time.Second))
12575 buf := make([]byte, 256)
12576 for {
12577 _, err = c.Read(buf)
12578 if err != nil {
12579 break
12580 }
12581 }
12582
12583 // Make sure the server is still running (not panicked).
12584 s.mu.Lock()
12585 shutdown := s.isShuttingDown()
12586 s.mu.Unlock()
12587 if shutdown {
12588 t.Fatal("Server should not have shutdown")
12589 }
12590 }
12591
12592 func TestLeafNodeSpokeConnectAdvisory(t *testing.T) {
12593 confHub := createConfFile(t, []byte(`
12594 listen: 127.0.0.1:-1
12595 accounts {
12596 SYS: {users: [{user: sys, password: pwd}]}
12597 USER: {users: [{user: user, password: pwd}]}
12598 }
12599 system_account: SYS
12600 leafnodes {
12601 listen: 127.0.0.1:-1
12602 no_advertise: true
12603 authorization { timeout: 0.5 }
12604 }
12605 `))
12606 hub, hubOpts := RunServerWithConfig(confHub)
12607 defer hub.Shutdown()
12608 hubPort := hubOpts.Port
12609 hubLeafPort := hubOpts.LeafNode.Port
12610
12611 confSpoke := createConfFile(t, []byte(fmt.Sprintf(`
12612 listen: 127.0.0.1:-1
12613 accounts {
12614 SYS: {users: [{user: sys, password: pwd}]}
12615 USER: {users: [{user: user, password: pwd}]}
12616 }
12617 system_account: SYS
12618 leafnodes {
12619 reconnect: "50ms"
12620 remotes: [
12621 {url: "nats://user:[email protected]:%d", account: USER},
12622 {url: "nats://sys:[email protected]:%d", account: SYS},
12623 ]
12624 }
12625 `, hubLeafPort, hubLeafPort)))
12626 spoke, spokeOpts := RunServerWithConfig(confSpoke)
12627 defer spoke.Shutdown()
12628
12629 checkLeafNodeConnectedCount(t, hub, 2)
12630 checkLeafNodeConnectedCount(t, spoke, 2)
12631
12632 // Subscribe on spoke's system account for USER account events
12633 nc := natsConnect(t, fmt.Sprintf("nats://sys:[email protected]:%d", spokeOpts.Port))
12634 defer nc.Close()
12635 cSub := natsSubSync(t, nc, "$SYS.ACCOUNT.USER.CONNECT")
12636 dSub := natsSubSync(t, nc, "$SYS.ACCOUNT.USER.DISCONNECT")
12637 nc.Flush()
12638
12639 // Shut down hub, spoke should emit DISCONNECT
12640 hub.Shutdown()
12641 checkLeafNodeConnectedCount(t, spoke, 0)
12642 msg, err := dSub.NextMsg(time.Second)
12643 require_NoError(t, err)
12644 var dm DisconnectEventMsg
12645 require_NoError(t, json.Unmarshal(msg.Data, &dm))
12646 require_Equal(t, dm.Client.Kind, "Leafnode")
12647
12648 // Restart hub on the same ports so spoke can reconnect
12649 hubOpts.Port = hubPort
12650 hubOpts.LeafNode.Port = hubLeafPort
12651 hub = RunServer(hubOpts)
12652 defer hub.Shutdown()
12653 checkLeafNodeConnectedCount(t, spoke, 2)
12654
12655 // Spoke should emit CONNECT advisory on reconnect
12656 msg, err = cSub.NextMsg(time.Second)
12657 require_NoError(t, err)
12658 var cm ConnectEventMsg
12659 require_NoError(t, json.Unmarshal(msg.Data, &cm))
12660 require_Equal(t, cm.Client.Kind, "Leafnode")
12661 }
12662
12663 func TestLeafNodeRemoteIgnoreGossip(t *testing.T) {
12664 tmpl := `
12665 listen: "127.0.0.1:-1"
12666 accounts {
12667 A { users: [{user: "a", password: "pwd"}] }
12668 B { users: [{user: "b", password: "pwd"}] }
12669 }
12670 cluster {
12671 name: "abc"
12672 listen: "127.0.0.1:-1"
12673 %s
12674 }
12675 leafnodes {
12676 listen: "127.0.0.1:-1"
12677 }
12678 `
12679 conf1 := createConfFile(t, fmt.Appendf(nil, tmpl, _EMPTY_))
12680 sb1, ob1 := RunServerWithConfig(conf1)
12681 defer sb1.Shutdown()
12682
12683 conf2 := createConfFile(t, fmt.Appendf(nil, tmpl,
12684 fmt.Sprintf("routes: [nats://127.0.0.1:%d]", ob1.Cluster.Port)))
12685 sb2, _ := RunServerWithConfig(conf2)
12686 defer sb2.Shutdown()
12687
12688 checkClusterFormed(t, sb1, sb2)
12689
12690 nc1 := natsConnect(t, sb1.ClientURL(), nats.UserInfo("a", "pwd"))
12691 defer nc1.Close()
12692 natsSubSync(t, nc1, "foo")
12693 natsFlush(t, nc1)
12694
12695 nc2 := natsConnect(t, sb2.ClientURL(), nats.UserInfo("b", "pwd"))
12696 defer nc2.Close()
12697 natsSubSync(t, nc2, "bar")
12698 natsFlush(t, nc2)
12699
12700 conf := createConfFile(t, fmt.Appendf(nil, `
12701 listen: "127.0.0.1:-1"
12702 leafnodes {
12703 reconnect_interval: "100ms"
12704 remotes: [
12705 { url: "nats://a:[email protected]:%d", ignore_discovered_servers: true }
12706 { url: "nats://b:[email protected]:%d" }
12707 ]
12708 }
12709 `, ob1.LeafNode.Port, ob1.LeafNode.Port))
12710 leaf, _ := RunServerWithConfig(conf)
12711 defer leaf.Shutdown()
12712
12713 checkLeafNodeConnectedCount(t, leaf, 2)
12714
12715 checkSubInterest(t, leaf, globalAccountName, "foo", time.Second)
12716 checkSubInterest(t, leaf, globalAccountName, "bar", time.Second)
12717
12718 // Now shutdown server sb1. The remote that connects to account "A" should
12719 // fail to reconnect (because it is asked to ignore gossip protocol), while
12720 // the remote that connects to account "B" should be able to reconnect
12721 // because it learned about sb2 thanks to gossip protocol (default behavior).
12722 sb1.Shutdown()
12723
12724 // Wait a bit for the disconnect and reconnect interval to make sure there
12725 // is only one connected remote.
12726 time.Sleep(150 * time.Millisecond)
12727 checkLeafNodeConnectedCount(t, leaf, 1)
12728
12729 checkSubNoInterest(t, leaf, globalAccountName, "foo", time.Second)
12730 checkSubInterest(t, leaf, globalAccountName, "bar", time.Second)
12731 }
12732
12733 // Verify that the dial timeout handed to the dialer is resolved in this order:
12734 // remote's `dial_timeout`, then the leafnodes{} block `dial_timeout`, then
12735 // DEFAULT_ROUTE_DIAL.
12736 //
12737 // We install a test dialer instead of relying on a genuinely slow network,
12738 // because a userspace listener/proxy completes the TCP handshake immediately
12739 // and would therefore never exercise the dial timeout at all. Reproducing a
12740 // real dial timeout requires delaying or dropping the SYN in the kernel (for
12741 // instance with tc/netem), which is not something a unit test can rely on.
12742 func TestLeafNodeDialTimeoutOption(t *testing.T) {
12743 // The remote does not need to exist: the test dialer never connects, it
12744 // just records the timeout it was given and returns an error, which sends
12745 // the connect loop into its normal retry path.
12746 u, err := url.Parse("nats-leaf://127.0.0.1:1234")
12747 require_NoError(t, err)
12748
12749 for _, test := range []struct {
12750 name string
12751 server time.Duration
12752 remote time.Duration
12753 expected time.Duration
12754 }{
12755 {"not set", 0, 0, DEFAULT_ROUTE_DIAL},
12756 {"server level", 3 * time.Second, 0, 3 * time.Second},
12757 {"remote level", 0, 4 * time.Second, 4 * time.Second},
12758 {"remote overrides server", 3 * time.Second, 4 * time.Second, 4 * time.Second},
12759 {"invalid server level", -1, 0, DEFAULT_ROUTE_DIAL},
12760 {"invalid remote level", 3 * time.Second, -1, 3 * time.Second},
12761 } {
12762 t.Run(test.name, func(t *testing.T) {
12763 ch := make(chan time.Duration, 1)
12764
12765 o := DefaultOptions()
12766 o.Host = "127.0.0.1"
12767 o.Port = -1
12768 o.LeafNode.Port = 0
12769 o.LeafNode.ReconnectInterval = 50 * time.Millisecond
12770 o.LeafNode.DialTimeout = test.server
12771 o.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}, DialTimeout: test.remote}}
12772 o.LeafNode.dialer = func(network, address string, timeout time.Duration) (net.Conn, error) {
12773 // Non-blocking send: the connect loop will keep retrying and
12774 // we only care about the first invocation.
12775 select {
12776 case ch <- timeout:
12777 default:
12778 }
12779 return nil, fmt.Errorf("test dialer does not connect")
12780 }
12781 s := RunServer(o)
12782 defer s.Shutdown()
12783
12784 select {
12785 case got := <-ch:
12786 require_Equal(t, got, test.expected)
12787 case <-time.After(2 * time.Second):
12788 t.Fatal("Leafnode dialer was never invoked")
12789 }
12790 })
12791 }
12792 }
12793
12794 // Verify that `dial_timeout` is accepted both in the leafnodes{} block and on
12795 // an individual remote.
12796 func TestLeafNodeDialTimeoutConfig(t *testing.T) {
12797 conf := createConfFile(t, []byte(`
12798 leafnodes {
12799 dial_timeout: "5s"
12800 remotes = [
12801 { url: "nats-leaf://127.0.0.1:1234" }
12802 { url: "nats-leaf://127.0.0.1:5678", dial_timeout: "15s" }
12803 ]
12804 }
12805 `))
12806 o, err := ProcessConfigFile(conf)
12807 require_NoError(t, err)
12808
12809 require_Equal(t, o.LeafNode.DialTimeout, 5*time.Second)
12810 require_Len(t, len(o.LeafNode.Remotes), 2)
12811 // Not set on this remote, so the leafnodes{} block value applies.
12812 require_Equal(t, o.LeafNode.Remotes[0].DialTimeout, time.Duration(0))
12813 require_Equal(t, o.LeafNode.Remotes[1].DialTimeout, 15*time.Second)
12814 }
12815
12816 // An invalid duration should be reported as a config error rather than being
12817 // silently ignored.
12818 func TestLeafNodeDialTimeoutConfigInvalid(t *testing.T) {
12819 for _, test := range []struct {
12820 name string
12821 conf string
12822 }{
12823 {"server level", `
12824 leafnodes {
12825 dial_timeout: abc
12826 }
12827 `},
12828 {"remote level", `
12829 leafnodes {
12830 remotes = [
12831 { url: "nats-leaf://127.0.0.1:1234", dial_timeout: abc }
12832 ]
12833 }
12834 `},
12835 } {
12836 t.Run(test.name, func(t *testing.T) {
12837 conf := createConfFile(t, []byte(test.conf))
12838 if _, err := ProcessConfigFile(conf); err == nil ||
12839 !strings.Contains(err.Error(), "error parsing dial_timeout") {
12840 t.Fatalf("Expected error parsing dial_timeout, got %v", err)
12841 }
12842 })
12843 }
12844 }