Debian Codegraph @

test/routes_test.go

raw
1 // Copyright 2012-2025 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 test
15
16 import (
17 "encoding/json"
18 "fmt"
19 "io"
20 "net"
21 "os"
22 "runtime"
23 "strconv"
24 "sync"
25 "testing"
26 "time"
27
28 "github.com/nats-io/nats-server/v2/internal/testhelper"
29 "github.com/nats-io/nats-server/v2/server"
30 "github.com/nats-io/nats.go"
31 )
32
33 const clientProtoInfo = 1
34
35 func runRouteServer(t *testing.T) (*server.Server, *server.Options) {
36 return RunServerWithConfig("./configs/cluster.conf")
37 }
38
39 func runRouteServerOverrides(t *testing.T, cbo func(*server.Options), cbs func(*server.Server)) (*server.Server, *server.Options) {
40 return RunServerWithConfigOverrides("./configs/cluster.conf", cbo, cbs)
41 }
42
43 func TestRouterListeningSocket(t *testing.T) {
44 s, opts := runRouteServer(t)
45 defer s.Shutdown()
46
47 // Check that the cluster socket is able to be connected.
48 addr := fmt.Sprintf("%s:%d", opts.Cluster.Host, opts.Cluster.Port)
49 checkSocket(t, addr, 2*time.Second)
50 }
51
52 func TestRouteGoServerShutdown(t *testing.T) {
53 base := runtime.NumGoroutine()
54 s, _ := runRouteServer(t)
55 s.Shutdown()
56 time.Sleep(50 * time.Millisecond)
57 delta := (runtime.NumGoroutine() - base)
58 if delta > 1 {
59 t.Fatalf("%d Go routines still exist post Shutdown()", delta)
60 }
61 }
62
63 func TestSendRouteInfoOnConnect(t *testing.T) {
64 s, opts := runRouteServer(t)
65 defer s.Shutdown()
66
67 rc := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
68 defer rc.Close()
69
70 routeID := "RouteID"
71 routeSend, routeExpect := setupRouteEx(t, rc, opts, routeID)
72 buf := routeExpect(infoRe)
73
74 info := server.Info{}
75 if err := json.Unmarshal(buf[4:], &info); err != nil {
76 t.Fatalf("Could not unmarshal route info: %v", err)
77 }
78
79 if !info.AuthRequired {
80 t.Fatal("Expected to see AuthRequired")
81 }
82 if info.Port != opts.Cluster.Port {
83 t.Fatalf("Received wrong information for port, expected %d, got %d",
84 info.Port, opts.Cluster.Port)
85 }
86
87 // Need to send a different INFO than the one received, otherwise the server
88 // will detect as a "cycle" and close the connection.
89 info.ID = routeID
90 info.Name = ""
91 b, err := json.Marshal(info)
92 if err != nil {
93 t.Fatalf("Could not marshal test route info: %v", err)
94 }
95 infoJSON := fmt.Sprintf("INFO %s\r\n", b)
96 routeSend(infoJSON)
97 routeSend("PING\r\n")
98 routeExpect(pongRe)
99 }
100
101 func TestRouteToSelf(t *testing.T) {
102 l := testhelper.NewDummyLogger(100)
103 s, opts := runRouteServerOverrides(t, nil,
104 func(s *server.Server) {
105 s.SetLogger(l, true, true)
106 })
107 defer s.Shutdown()
108
109 rc := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
110 defer rc.Close()
111
112 routeSend, routeExpect := setupRouteEx(t, rc, opts, s.ID())
113 buf := routeExpect(infoRe)
114
115 info := server.Info{}
116 if err := json.Unmarshal(buf[4:], &info); err != nil {
117 t.Fatalf("Could not unmarshal route info: %v", err)
118 }
119
120 if !info.AuthRequired {
121 t.Fatal("Expected to see AuthRequired")
122 }
123 if info.Port != opts.Cluster.Port {
124 t.Fatalf("Received wrong information for port, expected %d, got %d",
125 info.Port, opts.Cluster.Port)
126 }
127
128 // Now send it back and that should be detected as a route to self and the
129 // connection closed.
130 routeSend(string(buf))
131 routeSend("PING\r\n")
132 rc.SetReadDeadline(time.Now().Add(2 * time.Second))
133 if _, err := rc.Read(buf); err == nil {
134 t.Fatal("Expected route connection to be closed")
135 }
136 // This should have been removed by removePassFromTrace(), but we also check debug logs here
137 l.CheckForProhibited(t, "route authorization password found", "top_secret")
138 }
139
140 func TestSendRouteSubAndUnsub(t *testing.T) {
141 s, opts := runRouteServer(t)
142 defer s.Shutdown()
143
144 c := createClientConn(t, opts.Host, opts.Port)
145 defer c.Close()
146
147 send, _ := setupConn(t, c)
148
149 // We connect to the route.
150 rc := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
151 defer rc.Close()
152
153 expectAuthRequired(t, rc)
154 routeSend, routeExpect := setupRouteEx(t, rc, opts, "ROUTER:xyz")
155 routeSend("INFO {\"server_id\":\"ROUTER:xyz\"}\r\n")
156
157 routeSend("PING\r\n")
158 routeExpect(pongRe)
159
160 // Send SUB via client connection
161 send("SUB foo 22\r\n")
162
163 // Make sure the RS+ is broadcast via the route
164 expectResult(t, rc, rsubRe)
165
166 // Send UNSUB via client connection
167 send("UNSUB 22\r\n")
168
169 // Make sure the RS- is broadcast via the route
170 expectResult(t, rc, runsubRe)
171
172 // Explicitly shutdown the server, otherwise this test would
173 // cause following test to fail.
174 s.Shutdown()
175 }
176
177 func TestSendRouteSolicit(t *testing.T) {
178 s, opts := runRouteServer(t)
179 defer s.Shutdown()
180
181 // Listen for a connection from the server on the first route.
182 if len(opts.Routes) <= 0 {
183 t.Fatalf("Need an outbound solicted route for this test")
184 }
185 rURL := opts.Routes[0]
186
187 conn := acceptRouteConn(t, rURL.Host, server.DEFAULT_ROUTE_CONNECT)
188 defer conn.Close()
189
190 // We should receive a connect message right away due to auth.
191 buf := expectResult(t, conn, connectRe)
192
193 // Check INFO follows. Could be inline, with first result, if not
194 // check follow-on buffer.
195 if !infoRe.Match(buf) {
196 expectResult(t, conn, infoRe)
197 }
198 }
199
200 func TestRouteForwardsMsgFromClients(t *testing.T) {
201 s, opts := runRouteServer(t)
202 defer s.Shutdown()
203
204 client := createClientConn(t, opts.Host, opts.Port)
205 defer client.Close()
206
207 clientSend, clientExpect := setupConn(t, client)
208
209 route := acceptRouteConn(t, opts.Routes[0].Host, server.DEFAULT_ROUTE_CONNECT)
210 defer route.Close()
211
212 routeSend, routeExpect := setupRoute(t, route, opts)
213 expectMsgs := expectMsgsCommand(t, routeExpect)
214
215 // Eat the CONNECT and INFO protos
216 buf := routeExpect(connectRe)
217 if !infoRe.Match(buf) {
218 routeExpect(infoRe)
219 }
220
221 // Send SUB via route connection, RS+
222 routeSend("RS+ $G foo\r\nPING\r\n")
223 routeExpect(pongRe)
224
225 // Send PUB via client connection
226 clientSend("PUB foo 2\r\nok\r\nPING\r\n")
227 clientExpect(pongRe)
228
229 matches := expectMsgs(1)
230 checkRmsg(t, matches[0], "$G", "foo", "", "2", "ok")
231 }
232
233 func TestRouteForwardsMsgToClients(t *testing.T) {
234 s, opts := runRouteServer(t)
235 defer s.Shutdown()
236
237 client := createClientConn(t, opts.Host, opts.Port)
238 defer client.Close()
239
240 clientSend, clientExpect := setupConn(t, client)
241 expectMsgs := expectMsgsCommand(t, clientExpect)
242
243 route := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
244 defer route.Close()
245 expectAuthRequired(t, route)
246 routeSend, _ := setupRoute(t, route, opts)
247
248 // Subscribe to foo
249 clientSend("SUB foo 1\r\nPING\r\n")
250 // Use ping roundtrip to make sure its processed.
251 clientExpect(pongRe)
252
253 // Send RMSG proto via route connection
254 routeSend("RMSG $G foo 2\r\nok\r\n")
255
256 matches := expectMsgs(1)
257 checkMsg(t, matches[0], "foo", "1", "", "2", "ok")
258 }
259
260 func TestRouteOneHopSemantics(t *testing.T) {
261 s, opts := runRouteServer(t)
262 defer s.Shutdown()
263
264 route := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
265 defer route.Close()
266
267 expectAuthRequired(t, route)
268 routeSend, _ := setupRoute(t, route, opts)
269
270 // Express interest on this route for foo.
271 routeSend("RS+ $G foo\r\n")
272
273 // Send MSG proto via route connection
274 routeSend("RMSG foo 2\r\nok\r\n")
275
276 // Make sure it does not come back!
277 expectNothing(t, route)
278 }
279
280 func TestRouteOnlySendOnce(t *testing.T) {
281 s, opts := runRouteServer(t)
282 defer s.Shutdown()
283
284 client := createClientConn(t, opts.Host, opts.Port)
285 defer client.Close()
286
287 clientSend, clientExpect := setupConn(t, client)
288
289 route := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
290 defer route.Close()
291
292 expectAuthRequired(t, route)
293 routeSend, routeExpect := setupRoute(t, route, opts)
294 expectMsgs := expectMsgsCommand(t, routeExpect)
295
296 // Express multiple interest on this route for foo.
297 routeSend("RS+ $G foo\r\n")
298 routeSend("RS+ $G foo\r\n")
299 routeSend("PING\r\n")
300 routeExpect(pongRe)
301
302 // Send PUB via client connection
303 clientSend("PUB foo 2\r\nok\r\nPING\r\n")
304 clientExpect(pongRe)
305
306 expectMsgs(1)
307 routeSend("PING\r\n")
308 routeExpect(pongRe)
309 }
310
311 func TestRouteQueueSemantics(t *testing.T) {
312 s, opts := runRouteServer(t)
313 defer s.Shutdown()
314
315 client := createClientConn(t, opts.Host, opts.Port)
316 clientSend, clientExpect := setupConn(t, client)
317 clientExpectMsgs := expectMsgsCommand(t, clientExpect)
318
319 defer client.Close()
320
321 route := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
322 defer route.Close()
323
324 expectAuthRequired(t, route)
325 routeSend, routeExpect := setupRouteEx(t, route, opts, "ROUTER:xyz")
326 routeSend("INFO {\"server_id\":\"ROUTER:xyz\"}\r\n")
327 expectMsgs := expectRmsgsCommand(t, routeExpect)
328
329 // Express multiple interest on this route for foo, queue group bar.
330 routeSend("RS+ $G foo bar 1\r\n")
331 routeSend("RS+ $G foo bar 2\r\n")
332
333 // Use ping roundtrip to make sure its processed.
334 routeSend("PING\r\n")
335 routeExpect(pongRe)
336
337 // Send PUB via client connection
338 clientSend("PUB foo 2\r\nok\r\n")
339 // Use ping roundtrip to make sure its processed.
340 clientSend("PING\r\n")
341 clientExpect(pongRe)
342
343 // Only 1
344 matches := expectMsgs(1)
345 checkRmsg(t, matches[0], "$G", "foo", "| bar", "2", "ok")
346
347 // Add normal Interest as well to route interest.
348 routeSend("RS+ $G foo\r\n")
349
350 // Use ping roundtrip to make sure its processed.
351 routeSend("PING\r\n")
352 routeExpect(pongRe)
353
354 // Send PUB via client connection
355 clientSend("PUB foo 2\r\nok\r\nPING\r\n")
356 // Use ping roundtrip to make sure its processed.
357 clientExpect(pongRe)
358
359 // Should be 1 now for everything. Always receive 1 message.
360 matches = expectMsgs(1)
361 checkRmsg(t, matches[0], "$G", "foo", "| bar", "2", "ok")
362
363 // Now create a queue subscription for the client as well as a normal one.
364 clientSend("SUB foo 1\r\n")
365 // Use ping roundtrip to make sure its processed.
366 clientSend("PING\r\n")
367 clientExpect(pongRe)
368 routeExpect(rsubRe)
369
370 clientSend("SUB foo bar 2\r\nPING\r\n")
371 // Use ping roundtrip to make sure its processed.
372 clientExpect(pongRe)
373 routeExpect(rsubRe)
374
375 // Deliver a MSG from the route itself, make sure the client receives both.
376 routeSend("RMSG $G foo | bar 2\r\nok\r\n")
377
378 // Use ping roundtrip to make sure its processed.
379 routeSend("PING\r\n")
380 routeExpect(pongRe)
381
382 // Should get 2 msgs.
383 matches = clientExpectMsgs(2)
384
385 // Expect first to be the normal subscriber, next will be the queue one.
386 checkMsg(t, matches[0], "foo", "", "", "2", "ok")
387 }
388
389 func TestSolicitRouteReconnect(t *testing.T) {
390 l := testhelper.NewDummyLogger(100)
391 s, opts := runRouteServerOverrides(t, nil,
392 func(s *server.Server) {
393 s.SetLogger(l, true, true)
394 })
395 defer s.Shutdown()
396
397 rURL := opts.Routes[0]
398
399 route := acceptRouteConn(t, rURL.Host, 2*server.DEFAULT_ROUTE_CONNECT)
400
401 // Go ahead and close the Route.
402 route.Close()
403
404 // We expect to get called back..
405 route = acceptRouteConn(t, rURL.Host, 2*server.DEFAULT_ROUTE_CONNECT)
406 route.Close()
407
408 // Now we want to check for the debug logs when it tries to reconnect
409 l.CheckForProhibited(t, "route authorization password found", ":bar")
410 }
411
412 func TestMultipleRoutesSameId(t *testing.T) {
413 s, opts := runRouteServer(t)
414 defer s.Shutdown()
415
416 route1 := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
417 defer route1.Close()
418
419 expectAuthRequired(t, route1)
420 route1Send, route1Expect := setupRouteEx(t, route1, opts, "ROUTE:2222")
421
422 route2 := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
423 defer route2.Close()
424
425 expectAuthRequired(t, route2)
426 route2Send, route2Expect := setupRouteEx(t, route2, opts, "ROUTE:2222")
427
428 // Send SUB via route connections
429 sub := "RS+ $G foo\r\nPING\r\n"
430 route1Send(sub)
431 route2Send(sub)
432 route1Expect(pongRe)
433 route2Expect(pongRe)
434
435 // Make sure we do not get anything on a RMSG send to a router.
436 // Send RMSG proto via route connection
437 route1Send("RMSG $G foo 2\r\nok\r\n")
438
439 expectNothing(t, route1)
440 expectNothing(t, route2)
441
442 // Setup a client
443 client := createClientConn(t, opts.Host, opts.Port)
444 clientSend, clientExpect := setupConn(t, client)
445 defer client.Close()
446
447 // Send PUB via client connection
448 clientSend("PUB foo 2\r\nok\r\nPING\r\n")
449 clientExpect(pongRe)
450
451 // We should only receive on one route, not both.
452 // Check both manually.
453 route1.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
454 buf, _ := io.ReadAll(route1)
455 route1.SetReadDeadline(time.Time{})
456 if len(buf) <= 0 {
457 route2.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
458 buf, _ = io.ReadAll(route2)
459 route2.SetReadDeadline(time.Time{})
460 if len(buf) <= 0 {
461 t.Fatal("Expected to get one message on a route, received none.")
462 }
463 }
464
465 matches := rmsgRe.FindAllSubmatch(buf, -1)
466 if len(matches) != 1 {
467 t.Fatalf("Expected 1 msg, got %d\n", len(matches))
468 }
469 checkRmsg(t, matches[0], "$G", "foo", "", "2", "ok")
470 }
471
472 func TestRouteResendsLocalSubsOnReconnect(t *testing.T) {
473 s, opts := runRouteServer(t)
474 defer s.Shutdown()
475
476 client := createClientConn(t, opts.Host, opts.Port)
477 defer client.Close()
478
479 clientSend, clientExpect := setupConn(t, client)
480
481 // Setup a local subscription, make sure it reaches.
482 clientSend("SUB foo 1\r\n")
483 clientSend("PING\r\n")
484 clientExpect(pongRe)
485
486 route := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
487 defer route.Close()
488 routeSend, routeExpect := setupRouteEx(t, route, opts, "ROUTE:1234")
489
490 // Expect to see the local sub echoed through after we send our INFO.
491 time.Sleep(50 * time.Millisecond)
492 buf := routeExpect(infoRe)
493
494 // Generate our own INFO so we can send one to trigger the local subs.
495 info := server.Info{}
496 if err := json.Unmarshal(buf[4:], &info); err != nil {
497 t.Fatalf("Could not unmarshal route info: %v", err)
498 }
499 info.ID = "ROUTE:1234"
500 info.Name = ""
501 b, err := json.Marshal(info)
502 if err != nil {
503 t.Fatalf("Could not marshal test route info: %v", err)
504 }
505 infoJSON := fmt.Sprintf("INFO %s\r\n", b)
506
507 // Trigger the send of local subs.
508 routeSend(infoJSON)
509
510 routeExpect(rsubRe)
511
512 // Close and then re-open
513 route.Close()
514
515 // Give some time for the route close to be processed before trying to recreate.
516 checkNumRoutes(t, s, 0)
517
518 route = createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
519 defer route.Close()
520
521 routeSend, routeExpect = setupRouteEx(t, route, opts, "ROUTE:1234")
522
523 routeExpect(infoRe)
524
525 routeSend(infoJSON)
526 routeExpect(rsubRe)
527 }
528
529 type ignoreLogger struct{}
530
531 func (l *ignoreLogger) Fatalf(f string, args ...any) {}
532 func (l *ignoreLogger) Errorf(f string, args ...any) {}
533
534 func TestRouteConnectOnShutdownRace(t *testing.T) {
535 s, opts := runRouteServer(t)
536 defer s.Shutdown()
537
538 l := &ignoreLogger{}
539
540 var wg sync.WaitGroup
541
542 cQuit := make(chan bool, 1)
543
544 wg.Add(1)
545
546 go func() {
547 defer wg.Done()
548 for {
549 route := createRouteConn(l, opts.Cluster.Host, opts.Cluster.Port)
550 if route != nil {
551 setupRouteEx(l, route, opts, "ROUTE:1234")
552 route.Close()
553 }
554 select {
555 case <-cQuit:
556 return
557 default:
558 }
559 }
560 }()
561
562 time.Sleep(5 * time.Millisecond)
563 s.Shutdown()
564
565 cQuit <- true
566
567 wg.Wait()
568 }
569
570 func TestRouteSendAsyncINFOToClients(t *testing.T) {
571 f := func(opts *server.Options) {
572 s := RunServer(opts)
573 defer s.Shutdown()
574
575 clientURL := net.JoinHostPort(opts.Host, strconv.Itoa(opts.Port))
576
577 oldClient := createClientConn(t, opts.Host, opts.Port)
578 defer oldClient.Close()
579
580 oldClientSend, oldClientExpect := setupConn(t, oldClient)
581 oldClientSend("PING\r\n")
582 oldClientExpect(pongRe)
583
584 newClient := createClientConn(t, opts.Host, opts.Port)
585 defer newClient.Close()
586
587 newClientSend, newClientExpect := setupConnWithProto(t, newClient, clientProtoInfo)
588 newClientSend("PING\r\n")
589
590 // For new clients, the initial PING (after a CONNECT) will result in a
591 // PONG followed by an INFO, so make sure we receive them separately.
592 getPongAlone := func(c net.Conn) {
593 t.Helper()
594 pongBuf := make([]byte, len("PONG\r\n"))
595 c.SetReadDeadline(time.Now().Add(2 * time.Second))
596 n, err := c.Read(pongBuf)
597 c.SetReadDeadline(time.Time{})
598 if n <= 0 && err != nil {
599 t.Fatalf("Error reading from conn: %v\n", err)
600 }
601 if !pongRe.Match(pongBuf) {
602 t.Fatalf("Response did not match expected: \n\tReceived:'%q'\n\tExpected:'%s'\n", pongBuf, pongRe)
603 }
604 }
605 getPongAlone(newClient)
606 // The new client should receive an INFO with the ConnectInfo boolean set to true.
607 newClientExpect(infoRe)
608
609 routeID := "Server-B"
610
611 createRoute := func() (net.Conn, sendFun, expectFun) {
612 rc := createRouteConn(t, opts.Cluster.Host, opts.Cluster.Port)
613 routeSend, routeExpect := setupRouteEx(t, rc, opts, routeID)
614
615 buf := routeExpect(infoRe)
616
617 info := server.Info{}
618 if err := json.Unmarshal(buf[4:], &info); err != nil {
619 stackFatalf(t, "Could not unmarshal route info: %v", err)
620 }
621 if opts.Cluster.NoAdvertise {
622 if len(info.ClientConnectURLs) != 0 {
623 stackFatalf(t, "Expected ClientConnectURLs to be empty, got %v", info.ClientConnectURLs)
624 }
625 } else {
626 if len(info.ClientConnectURLs) == 0 {
627 stackFatalf(t, "Expected a list of URLs, got none")
628 }
629 if info.ClientConnectURLs[0] != clientURL {
630 stackFatalf(t, "Expected ClientConnectURLs to be %q, got %q", clientURL, info.ClientConnectURLs[0])
631 }
632 }
633
634 return rc, routeSend, routeExpect
635 }
636
637 sendRouteINFO := func(routeSend sendFun, routeExpect expectFun, urls []string) {
638 routeInfo := server.Info{}
639 routeInfo.ID = routeID
640 routeInfo.Cluster = "xyz"
641 routeInfo.Host = "127.0.0.1"
642 routeInfo.Port = 5222
643 routeInfo.ClientConnectURLs = urls
644 b, err := json.Marshal(routeInfo)
645 if err != nil {
646 stackFatalf(t, "Could not marshal test route info: %v", err)
647 }
648 infoJSON := fmt.Sprintf("INFO %s\r\n", b)
649 routeSend(infoJSON)
650 routeSend("PING\r\n")
651 routeExpect(pongRe)
652 }
653
654 checkClientConnectURLS := func(urls, expected []string) {
655 // Order of array is not guaranteed.
656 ok := false
657 if len(urls) == len(expected) {
658 m := make(map[string]struct{}, len(expected))
659 for _, url := range expected {
660 m[url] = struct{}{}
661 }
662 ok = true
663 for _, url := range urls {
664 if _, present := m[url]; !present {
665 ok = false
666 break
667 }
668 }
669 }
670 if !ok {
671 stackFatalf(t, "Expected ClientConnectURLs to be %v, got %v", expected, urls)
672 }
673 }
674
675 var checkConnectInfo bool
676 checkINFOReceived := func(client net.Conn, clientExpect expectFun, expectedURLs []string) {
677 if opts.Cluster.NoAdvertise {
678 if !checkConnectInfo {
679 expectNothing(t, client)
680 return
681 }
682 // Since it is no advertise, but we still get an INFO, the URLs
683 // should be empty.
684 expectedURLs = nil
685 }
686 buf := clientExpect(infoRe)
687 info := server.Info{}
688 if err := json.Unmarshal(buf[4:], &info); err != nil {
689 stackFatalf(t, "Could not unmarshal route info: %v", err)
690 }
691 checkClientConnectURLS(info.ClientConnectURLs, expectedURLs)
692 if checkConnectInfo {
693 if !info.ConnectInfo {
694 stackFatalf(t, "ConnectInfo should have been true")
695 }
696 if info.RemoteAccount != "$G" {
697 stackFatalf(t, "RemoteAccount should be %q, got %q", "$G", info.RemoteAccount)
698 }
699 if info.IsSystemAccount {
700 stackFatalf(t, "IsSystemAccount should have been false")
701 }
702 }
703 }
704
705 // Create a route
706 rc, routeSend, routeExpect := createRoute()
707 defer rc.Close()
708
709 // Send an INFO with single URL
710 routeClientConnectURLs := []string{"127.0.0.1:5222"}
711 sendRouteINFO(routeSend, routeExpect, routeClientConnectURLs)
712
713 // Expect nothing for old clients
714 expectNothing(t, oldClient)
715
716 // We expect to get the one from the server we connect to and the other route.
717 expectedURLs := []string{clientURL, routeClientConnectURLs[0]}
718
719 // Expect new client to receive an INFO (unless disabled)
720 checkINFOReceived(newClient, newClientExpect, expectedURLs)
721
722 // Disconnect the route
723 rc.Close()
724
725 // Expect nothing for old clients
726 expectNothing(t, oldClient)
727
728 // Expect new client to receive an INFO (unless disabled).
729 // The content will now have the disconnected route ClientConnectURLs
730 // removed from the INFO. So it should be the one from the server the
731 // client is connected to.
732 checkINFOReceived(newClient, newClientExpect, []string{clientURL})
733
734 // Reconnect the route.
735 rc, routeSend, routeExpect = createRoute()
736 defer rc.Close()
737
738 // Resend the same route INFO json. The server will now send
739 // the INFO since the disconnected route ClientConnectURLs was
740 // removed in previous step.
741 sendRouteINFO(routeSend, routeExpect, routeClientConnectURLs)
742
743 // Expect nothing for old clients
744 expectNothing(t, oldClient)
745
746 // Expect new client to receive an INFO (unless disabled)
747 checkINFOReceived(newClient, newClientExpect, expectedURLs)
748
749 // Now stop the route and restart with an additional URL
750 rc.Close()
751
752 // On route disconnect, clients will receive an updated INFO
753 expectNothing(t, oldClient)
754 checkINFOReceived(newClient, newClientExpect, []string{clientURL})
755
756 rc, routeSend, routeExpect = createRoute()
757 defer rc.Close()
758
759 // Create a client not sending the CONNECT until after route is added
760 clientNoConnect := createClientConn(t, opts.Host, opts.Port)
761 defer clientNoConnect.Close()
762
763 // Create a client that does not send the first PING yet
764 clientNoPing := createClientConn(t, opts.Host, opts.Port)
765 defer clientNoPing.Close()
766 clientNoPingSend, clientNoPingExpect := setupConnWithProto(t, clientNoPing, clientProtoInfo)
767
768 // The route now has an additional URL
769 routeClientConnectURLs = append(routeClientConnectURLs, "127.0.0.1:7777")
770 expectedURLs = append(expectedURLs, "127.0.0.1:7777")
771 // This causes the server to add the route and send INFO to clients
772 sendRouteINFO(routeSend, routeExpect, routeClientConnectURLs)
773
774 // Expect nothing for old clients
775 expectNothing(t, oldClient)
776
777 // Expect new client to receive an INFO, and verify content as expected.
778 checkINFOReceived(newClient, newClientExpect, expectedURLs)
779
780 // Expect nothing yet for client that did not send the PING
781 expectNothing(t, clientNoPing)
782
783 // Now send the first PING
784 clientNoPingSend("PING\r\n")
785 getPongAlone(clientNoPing)
786 // We should receive an INFO but with ConnectInfo==true, etc..
787 checkConnectInfo = true
788 checkINFOReceived(clientNoPing, clientNoPingExpect, expectedURLs)
789 checkConnectInfo = false
790
791 // Have the client that did not send the connect do it now
792 clientNoConnectSend, clientNoConnectExpect := setupConnWithProto(t, clientNoConnect, clientProtoInfo)
793 // Send the PING
794 clientNoConnectSend("PING\r\n")
795 getPongAlone(clientNoConnect)
796 checkConnectInfo = true
797 checkINFOReceived(clientNoConnect, clientNoConnectExpect, expectedURLs)
798 checkConnectInfo = false
799
800 // Create a client connection and verify content of initial INFO contains array
801 // (but empty if no advertise option is set)
802 cli := createClientConn(t, opts.Host, opts.Port)
803 defer cli.Close()
804 buf := expectResult(t, cli, infoRe)
805 js := infoRe.FindAllSubmatch(buf, 1)[0][1]
806 var sinfo server.Info
807 err := json.Unmarshal(js, &sinfo)
808 if err != nil {
809 t.Fatalf("Could not unmarshal INFO json: %v\n", err)
810 }
811 if opts.Cluster.NoAdvertise {
812 if len(sinfo.ClientConnectURLs) != 0 {
813 t.Fatalf("Expected ClientConnectURLs to be empty, got %v", sinfo.ClientConnectURLs)
814 }
815 } else {
816 checkClientConnectURLS(sinfo.ClientConnectURLs, expectedURLs)
817 }
818
819 // Add a new route
820 routeID = "Server-C"
821 rc2, route2Send, route2Expect := createRoute()
822 defer rc2.Close()
823
824 // Send an INFO with single URL
825 rc2ConnectURLs := []string{"127.0.0.1:8888"}
826 sendRouteINFO(route2Send, route2Expect, rc2ConnectURLs)
827
828 // This is the combined client connect URLs array
829 totalConnectURLs := expectedURLs
830 totalConnectURLs = append(totalConnectURLs, rc2ConnectURLs...)
831
832 // Expect nothing for old clients
833 expectNothing(t, oldClient)
834
835 // Expect new client to receive an INFO (unless disabled)
836 checkINFOReceived(newClient, newClientExpect, totalConnectURLs)
837
838 // Make first route disconnect
839 rc.Close()
840
841 // Expect nothing for old clients
842 expectNothing(t, oldClient)
843
844 // Expect new client to receive an INFO (unless disabled)
845 // The content should be the server client is connected to and the last route
846 checkINFOReceived(newClient, newClientExpect, []string{"127.0.0.1:5242", "127.0.0.1:8888"})
847 }
848
849 opts := LoadConfig("./configs/cluster.conf")
850 // For this test, be explicit about listen spec.
851 opts.Host = "127.0.0.1"
852 opts.Port = 5242
853 opts.DisableShortFirstPing = true
854
855 f(opts)
856 opts.Cluster.NoAdvertise = true
857 f(opts)
858 }
859
860 func TestRouteBasicPermissions(t *testing.T) {
861 srvA, optsA := RunServerWithConfig("./configs/srv_a_perms.conf")
862 defer srvA.Shutdown()
863
864 srvB, optsB := RunServerWithConfig("./configs/srv_b.conf")
865 defer srvB.Shutdown()
866
867 checkClusterFormed(t, srvA, srvB)
868
869 // Create a connection to server B
870 ncb, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", optsB.Port))
871 if err != nil {
872 t.Fatalf("Error on connect: %v", err)
873 }
874 defer ncb.Close()
875 ch := make(chan bool, 1)
876 cb := func(_ *nats.Msg) {
877 ch <- true
878 }
879 // Subscribe on Server B on "bar" and "baz", which should be accepted by server A across the route
880 // Due to allowing "*"
881 subBbar, err := ncb.Subscribe("bar", cb)
882 if err != nil {
883 t.Fatalf("Error on subscribe: %v", err)
884 }
885 defer subBbar.Unsubscribe()
886 subBbaz, err := ncb.Subscribe("baz", cb)
887 if err != nil {
888 t.Fatalf("Error on subscribe: %v", err)
889 }
890 defer subBbaz.Unsubscribe()
891 ncb.Flush()
892 if err := checkExpectedSubs(2, srvA, srvB); err != nil {
893 t.Fatal(err.Error())
894 }
895
896 // Create a connection to server A
897 nca, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", optsA.Port))
898 if err != nil {
899 t.Fatalf("Error on connect: %v", err)
900 }
901 defer nca.Close()
902 // Publish on bar and baz, messages should be received.
903 if err := nca.Publish("bar", []byte("hello")); err != nil {
904 t.Fatalf("Error on publish: %v", err)
905 }
906 if err := nca.Publish("baz", []byte("hello")); err != nil {
907 t.Fatalf("Error on publish: %v", err)
908 }
909 for i := 0; i < 2; i++ {
910 select {
911 case <-ch:
912 case <-time.After(time.Second):
913 t.Fatal("Did not get the messages")
914 }
915 }
916
917 // From B, start a subscription on "foo", which server A should drop since
918 // it only exports on "bar" and "baz"
919 subBfoo, err := ncb.Subscribe("foo", cb)
920 if err != nil {
921 t.Fatalf("Error on subscribe: %v", err)
922 }
923 defer subBfoo.Unsubscribe()
924 ncb.Flush()
925 // B should have now 3 subs
926 if err := checkExpectedSubs(3, srvB); err != nil {
927 t.Fatal(err.Error())
928 }
929 // and A still 2.
930 if err := checkExpectedSubs(2, srvA); err != nil {
931 t.Fatal(err.Error())
932 }
933 // So producing on "foo" from A should not be forwarded to B.
934 if err := nca.Publish("foo", []byte("hello")); err != nil {
935 t.Fatalf("Error on publish: %v", err)
936 }
937 select {
938 case <-ch:
939 t.Fatal("Message should not have been received")
940 case <-time.After(100 * time.Millisecond):
941 }
942
943 // Now on A, create a subscription on something that A does not import,
944 // like "bat".
945 subAbat, err := nca.Subscribe("bat", cb)
946 if err != nil {
947 t.Fatalf("Error on subscribe: %v", err)
948 }
949 defer subAbat.Unsubscribe()
950 nca.Flush()
951 // A should have 3 subs
952 if err := checkExpectedSubs(3, srvA); err != nil {
953 t.Fatal(err.Error())
954 }
955 // And from B, send a message on that subject and make sure it is not received.
956 if err := ncb.Publish("bat", []byte("hello")); err != nil {
957 t.Fatalf("Error on publish: %v", err)
958 }
959 select {
960 case <-ch:
961 t.Fatal("Message should not have been received")
962 case <-time.After(100 * time.Millisecond):
963 }
964
965 // Stop subscription on foo from B
966 subBfoo.Unsubscribe()
967 ncb.Flush()
968 // Back to 2 subs on B
969 if err := checkExpectedSubs(2, srvB); err != nil {
970 t.Fatal(err.Error())
971 }
972
973 // Create subscription on foo from A, this should be forwared to B.
974 subAfoo, err := nca.Subscribe("foo", cb)
975 if err != nil {
976 t.Fatalf("Error on subscribe: %v", err)
977 }
978 defer subAfoo.Unsubscribe()
979 // Create another one so that test the import permissions cache
980 subAfoo2, err := nca.Subscribe("foo", cb)
981 if err != nil {
982 t.Fatalf("Error on subscribe: %v", err)
983 }
984 defer subAfoo2.Unsubscribe()
985 nca.Flush()
986 // A should have 5 subs
987 if err := checkExpectedSubs(5, srvA); err != nil {
988 t.Fatal(err.Error())
989 }
990 // B should have 3 since we coalesce te two for 'foo'
991 if err := checkExpectedSubs(3, srvB); err != nil {
992 t.Fatal(err.Error())
993 }
994 // Send a message from B and check that it is received.
995 if err := ncb.Publish("foo", []byte("hello")); err != nil {
996 t.Fatalf("Error on publish: %v", err)
997 }
998 for i := 0; i < 2; i++ {
999 select {
1000 case <-ch:
1001 case <-time.After(time.Second):
1002 t.Fatal("Did not get the message")
1003 }
1004 }
1005
1006 // Close connection from B, and restart server B too.
1007 // We want to make sure that
1008 ncb.Close()
1009 srvB.Shutdown()
1010
1011 // Since B had 2 local subs, A should still only go from 4 to 3
1012 if err := checkExpectedSubs(3, srvA); err != nil {
1013 t.Fatal(err.Error())
1014 }
1015
1016 // Restart server B
1017 srvB, optsB = RunServerWithConfig("./configs/srv_b.conf")
1018 defer srvB.Shutdown()
1019 // Check that subs from A that can be sent to B are sent.
1020 // That would be 2 (the 2 subscriptions on foo) as one.
1021 if err := checkExpectedSubs(1, srvB); err != nil {
1022 t.Fatal(err.Error())
1023 }
1024
1025 // Connect to B and send on "foo" and make sure we receive
1026 ncb, err = nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", optsB.Port))
1027 if err != nil {
1028 t.Fatalf("Error on connect: %v", err)
1029 }
1030 defer ncb.Close()
1031 if err := ncb.Publish("foo", []byte("hello")); err != nil {
1032 t.Fatalf("Error on publish: %v", err)
1033 }
1034 for i := 0; i < 2; i++ {
1035 select {
1036 case <-ch:
1037 case <-time.After(time.Second):
1038 t.Fatal("Did not get the message")
1039 }
1040 }
1041
1042 // Send on "bat" and make sure that this is not received.
1043 if err := ncb.Publish("bat", []byte("hello")); err != nil {
1044 t.Fatalf("Error on publish: %v", err)
1045 }
1046 select {
1047 case <-ch:
1048 t.Fatal("Message should not have been received")
1049 case <-time.After(100 * time.Millisecond):
1050 }
1051
1052 nca.Close()
1053 ncb.Close()
1054
1055 srvA.Shutdown()
1056 srvB.Shutdown()
1057
1058 optsA.Cluster.Permissions.Export = nil
1059 srvA = RunServer(optsA)
1060 defer srvA.Shutdown()
1061
1062 srvB = RunServer(optsB)
1063 defer srvB.Shutdown()
1064
1065 checkClusterFormed(t, srvA, srvB)
1066
1067 nca, err = nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", optsA.Port))
1068 if err != nil {
1069 t.Fatalf("Error on connect: %v", err)
1070 }
1071 defer nca.Close()
1072 // Subscribe on "bar" which is not imported
1073 if _, err := nca.Subscribe("bar", cb); err != nil {
1074 t.Fatalf("Error on subscribe: %v", err)
1075 }
1076 if err := checkExpectedSubs(1, srvA); err != nil {
1077 t.Fatal(err.Error())
1078 }
1079
1080 // Publish from B, should not be received
1081 ncb, err = nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", optsB.Port))
1082 if err != nil {
1083 t.Fatalf("Error on connect: %v", err)
1084 }
1085 defer ncb.Close()
1086 if err := ncb.Publish("bar", []byte("hello")); err != nil {
1087 t.Fatalf("Error on publish: %v", err)
1088 }
1089 select {
1090 case <-ch:
1091 t.Fatal("Message should not have been received")
1092 case <-time.After(100 * time.Millisecond):
1093 //ok
1094 }
1095 // Subscribe on "baz" on B
1096 if _, err := ncb.Subscribe("baz", cb); err != nil {
1097 t.Fatalf("Error on subscribe: %v", err)
1098 }
1099 if err := checkExpectedSubs(1, srvB); err != nil {
1100 t.Fatal(err.Error())
1101 }
1102 if err := checkExpectedSubs(2, srvA); err != nil {
1103 t.Fatal(err.Error())
1104 }
1105 // Publish from A, since there is no export restriction, message should be received.
1106 if err := nca.Publish("baz", []byte("hello")); err != nil {
1107 t.Fatalf("Error on publish: %v", err)
1108 }
1109 select {
1110 case <-ch:
1111 // ok
1112 case <-time.After(250 * time.Millisecond):
1113 t.Fatal("Message should have been received")
1114 }
1115 }
1116
1117 func createConfFile(t testing.TB, content []byte) string {
1118 t.Helper()
1119 conf := createTempFile(t, "")
1120 fName := conf.Name()
1121 conf.Close()
1122 if err := os.WriteFile(fName, content, 0666); err != nil {
1123 t.Fatalf("Error writing conf file: %v", err)
1124 }
1125 return fName
1126 }
1127
1128 func TestRoutesOnlyImportOrExport(t *testing.T) {
1129 contents := []string{
1130 `import: "foo"`,
1131 `import: {
1132 allow: "foo"
1133 }`,
1134 `import: {
1135 deny: "foo"
1136 }`,
1137 `import: {
1138 allow: "foo"
1139 deny: "foo"
1140 }`,
1141 `export: "foo"`,
1142 `export: {
1143 allow: "foo"
1144 }`,
1145 `export: {
1146 deny: "foo"
1147 }`,
1148 `export: {
1149 allow: "foo"
1150 deny: "foo"
1151 }`,
1152 }
1153 f := func(c string) {
1154 cf := createConfFile(t, []byte(fmt.Sprintf(`
1155 port: -1
1156 cluster {
1157 name: "Z"
1158 port: -1
1159 authorization {
1160 user: ivan
1161 password: pwd
1162 permissions {
1163 %s
1164 }
1165 }
1166 }
1167 `, c)))
1168 s, _ := RunServerWithConfig(cf)
1169 s.Shutdown()
1170 }
1171 for _, c := range contents {
1172 f(c)
1173 }
1174 }