Debian Codegraph @

test/nats_test.go

raw
1 // Copyright 2023-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 test
15
16 import (
17 "bytes"
18 "fmt"
19 "net"
20 "os"
21 "runtime"
22 "strings"
23 "sync"
24 "sync/atomic"
25 "testing"
26 "time"
27
28 "github.com/nats-io/nats.go"
29 "github.com/nats-io/nkeys"
30 testservice "github.com/synadia-io/orbit.go/ntf-client"
31 )
32
33 // Reuse seeds/JWT declared in reconnect_testservice_test.go (tsOSeed, tsASeed,
34 // tsUSeed, tsAJWT) and the trustServerOpts helper.
35
36 // uJWT is the user JWT used by the trust-server-based tests below.
37 var nstsUJWT = "eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJBSFQzRzNXRElDS1FWQ1FUWFJUTldPRlVVUFRWNE00RFZQV0JGSFpJQUROWEZIWEpQR0FBIiwiaWF0IjoxNTQ0MDcxODg5LCJpc3MiOiJBQVBRSlFVUEtWWEdXNUNaSDVHMkhGSlVMWVNLREVMQVpSVldKQTI2VkRaTzdXU0JVTklZUkZOUSIsInN1YiI6IlVBVDZCV0NTQ1dMVUtKVDZLNk1CSkpPRU9UWFo1QUpET1lLTkVWUkZDN1ZOTzZPQTQzTjRUUk5PIiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ._8A1XM88Q2kp7XVJZ42bQuO9E3QPsNAGKtVjAkDycj8A5PtRPby9UpqBUZzBwiJQQO3TUcD5GGqSvsMm6X8hCQ"
38
39 // nstsChained is a chained credentials file body used by the auth tests.
40 var nstsChained = `
41 -----BEGIN NATS USER JWT-----
42 eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJBSFQzRzNXRElDS1FWQ1FUWFJUTldPRlVVUFRWNE00RFZQV0JGSFpJQUROWEZIWEpQR0FBIiwiaWF0IjoxNTQ0MDcxODg5LCJpc3MiOiJBQVBRSlFVUEtWWEdXNUNaSDVHMkhGSlVMWVNLREVMQVpSVldKQTI2VkRaTzdXU0JVTklZUkZOUSIsInN1YiI6IlVBVDZCV0NTQ1dMVUtKVDZLNk1CSkpPRU9UWFo1QUpET1lLTkVWUkZDN1ZOTzZPQTQzTjRUUk5PIiwidHlwZSI6InVzZXIiLCJuYXRzIjp7InB1YiI6e30sInN1YiI6e319fQ._8A1XM88Q2kp7XVJZ42bQuO9E3QPsNAGKtVjAkDycj8A5PtRPby9UpqBUZzBwiJQQO3TUcD5GGqSvsMm6X8hCQ
43 ------END NATS USER JWT------
44
45 ************************* IMPORTANT *************************
46 NKEY Seed printed below can be used to sign and prove identity.
47 NKEYs are sensitive and should be treated as secrets.
48
49 -----BEGIN USER NKEY SEED-----
50 SUAMK2FG4MI6UE3ACF3FK3OIQBCEIEZV7NSWFFEW63UXMRLFM2XLAXK4GY
51 ------END USER NKEY SEED------
52 `
53
54 // createTmpFileTS writes content to a freshly-created temp file and returns
55 // its path.
56 func createTmpFileTS(t *testing.T, content []byte) string {
57 t.Helper()
58 conf, err := os.CreateTemp("", "")
59 if err != nil {
60 t.Fatalf("Error creating conf file: %v", err)
61 }
62 fName := conf.Name()
63 conf.Close()
64 if err := os.WriteFile(fName, content, 0666); err != nil {
65 os.Remove(fName)
66 t.Fatalf("Error writing conf file: %v", err)
67 }
68 return fName
69 }
70
71 func TestMaxConnectionsReconnect(t *testing.T) {
72 c := newTester(t)
73 maxConns := func(n int) string {
74 return fmt.Sprintf("max_connections: %d", n)
75 }
76 inst := c.CreateCluster(t, 2, false, testservice.WithTopLevel(maxConns(2)))
77 t.Cleanup(func() { inst.Destroy(t) })
78
79 s1URL := inst.Servers[0].URL
80
81 errCh := make(chan error, 2)
82 reconnectCh := make(chan *nats.Conn, 2)
83 opts := []nats.Option{
84 nats.MaxReconnects(2),
85 nats.ReconnectWait(10 * time.Millisecond),
86 nats.Timeout(200 * time.Millisecond),
87 nats.DisconnectErrHandler(func(_ *nats.Conn, err error) {
88 if err != nil {
89 errCh <- err
90 }
91 }),
92 nats.ReconnectHandler(func(nc *nats.Conn) {
93 reconnectCh <- nc
94 }),
95 }
96
97 nc1, err := nats.Connect(s1URL, opts...)
98 if err != nil {
99 t.Fatalf("Failed to connect first client: %v", err)
100 }
101 defer nc1.Close()
102 nc1.Flush()
103
104 nc2, err := nats.Connect(s1URL, opts...)
105 if err != nil {
106 t.Fatalf("Failed to connect second client: %v", err)
107 }
108 defer nc2.Close()
109 nc2.Flush()
110
111 // Lower s1's max_connections to 1 via reload — kicks one client.
112 inst.UpdateServer(t, inst.Servers[0], testservice.WithTopLevel(maxConns(1)))
113 inst.ReloadServer(t, inst.Servers[0])
114
115 select {
116 case err := <-errCh:
117 if err != nats.ErrMaxConnectionsExceeded {
118 t.Fatalf("Unexpected error %v", err)
119 }
120 case <-time.After(2 * time.Second):
121 t.Fatal("Timed out waiting for disconnect event")
122 }
123
124 select {
125 case reconn := <-reconnectCh:
126 // Kicked client must land on the second cluster node — s1 still has
127 // max_connections=1 and is occupied by the survivor.
128 if got := reconn.ConnectedUrl(); got == s1URL {
129 t.Fatalf("Expected kicked client to reconnect to s2, got %s", got)
130 }
131 case <-time.After(2 * time.Second):
132 t.Fatal("Timed out waiting for reconnect event")
133 }
134 }
135
136 func TestNoEcho(t *testing.T) {
137 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
138 nc, err := nats.Connect(inst.Servers[0].URL, nats.NoEcho())
139 if err != nil {
140 t.Fatalf("Error on connect: %v", err)
141 }
142 defer nc.Close()
143
144 r := int32(0)
145 _, err = nc.Subscribe("foo", func(m *nats.Msg) {
146 atomic.AddInt32(&r, 1)
147 })
148 if err != nil {
149 t.Fatalf("Error on subscribe: %v", err)
150 }
151
152 err = nc.Publish("foo", []byte("Hello World"))
153 if err != nil {
154 t.Fatalf("Error on publish: %v", err)
155 }
156 nc.Flush()
157 nc.Flush()
158
159 if nr := atomic.LoadInt32(&r); nr != 0 {
160 t.Fatalf("Expected no messages echoed back, received %d\n", nr)
161 }
162 })
163 }
164
165 func TestBasicUserJWTAuth(t *testing.T) {
166 c := newTester(t)
167 inst := c.CreateServer(t, false, trustServerOpts(t)...)
168 t.Cleanup(func() { inst.Destroy(t) })
169
170 clientURL := inst.Servers[0].URL
171 _, err := nats.Connect(clientURL)
172 if err == nil {
173 t.Fatalf("Expecting an error on connect")
174 }
175
176 jwtCB := func() (string, error) {
177 return nstsUJWT, nil
178 }
179 sigCB := func(nonce []byte) ([]byte, error) {
180 kp, _ := nkeys.FromSeed(tsUSeed)
181 sig, _ := kp.Sign(nonce)
182 return sig, nil
183 }
184
185 // Try with user jwt but no sig
186 _, err = nats.Connect(clientURL, nats.UserJWT(jwtCB, nil))
187 if err == nil {
188 t.Fatalf("Expecting an error on connect")
189 }
190
191 // Try with user callback
192 _, err = nats.Connect(clientURL, nats.UserJWT(nil, sigCB))
193 if err == nil {
194 t.Fatalf("Expecting an error on connect")
195 }
196
197 nc, err := nats.Connect(clientURL, nats.UserJWT(jwtCB, sigCB))
198 if err != nil {
199 t.Fatalf("Expected to connect, got %v", err)
200 }
201 nc.Close()
202 }
203
204 func TestUserCredentialsTwoFiles(t *testing.T) {
205 c := newTester(t)
206 inst := c.CreateServer(t, false, trustServerOpts(t)...)
207 t.Cleanup(func() { inst.Destroy(t) })
208
209 userJWTFile := createTmpFileTS(t, []byte(nstsUJWT))
210 defer os.Remove(userJWTFile)
211 userSeedFile := createTmpFileTS(t, tsUSeed)
212 defer os.Remove(userSeedFile)
213
214 nc, err := nats.Connect(inst.Servers[0].URL, nats.UserCredentials(userJWTFile, userSeedFile))
215 if err != nil {
216 t.Fatalf("Expected to connect, got %v", err)
217 }
218 nc.Close()
219 }
220
221 func TestUserCredentialsChainedFile(t *testing.T) {
222 c := newTester(t)
223 inst := c.CreateServer(t, false, trustServerOpts(t)...)
224 t.Cleanup(func() { inst.Destroy(t) })
225
226 chainedFile := createTmpFileTS(t, []byte(nstsChained))
227 defer os.Remove(chainedFile)
228
229 clientURL := inst.Servers[0].URL
230 nc, err := nats.Connect(clientURL, nats.UserCredentials(chainedFile))
231 if err != nil {
232 t.Fatalf("Expected to connect, got %v", err)
233 }
234 nc.Close()
235
236 chainedFile = createTmpFileTS(t, []byte("invalid content"))
237 defer os.Remove(chainedFile)
238 nc, err = nats.Connect(clientURL, nats.UserCredentials(chainedFile))
239 if err == nil || !strings.Contains(err.Error(),
240 "error signing nonce: unable to extract key pair from file") {
241 if nc != nil {
242 nc.Close()
243 }
244 t.Fatalf("Expected error about invalid creds file, got %q", err)
245 }
246 }
247
248 func TestReconnectMissingCredentials(t *testing.T) {
249 c := newTester(t)
250 inst := c.CreateServer(t, false, trustServerOpts(t)...)
251 t.Cleanup(func() { inst.Destroy(t) })
252
253 chainedFile := createTmpFileTS(t, []byte(nstsChained))
254 defer os.Remove(chainedFile)
255
256 clientURL := inst.Servers[0].URL
257 errs := make(chan error, 1)
258 nc, err := nats.Connect(clientURL, nats.UserCredentials(chainedFile), nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
259 errs <- err
260 }))
261 if err != nil {
262 t.Fatalf("Expected to connect, got %v", err)
263 }
264 defer nc.Close()
265 os.Remove(chainedFile)
266 // Bounce the server so the client must reconnect and re-load the (now
267 // missing) credentials file. testservice StartServer reuses the same port.
268 inst.StopServer(t, inst.Servers[0])
269 inst.StartServer(t, inst.Servers[0])
270
271 select {
272 case err := <-errs:
273 if !strings.Contains(err.Error(), "no such file or directory") {
274 t.Fatalf("Expected error about missing creds file, got %q", err)
275 }
276 case <-time.After(5 * time.Second):
277 t.Fatal("Did not get error about missing creds file")
278 }
279 }
280
281 func TestUserJWTAndSeed(t *testing.T) {
282 c := newTester(t)
283 inst := c.CreateServer(t, false, trustServerOpts(t)...)
284 t.Cleanup(func() { inst.Destroy(t) })
285
286 nc, err := nats.Connect(inst.Servers[0].URL, nats.UserJWTAndSeed(nstsUJWT, string(tsUSeed)))
287 if err != nil {
288 t.Fatalf("Expected to connect, got %v", err)
289 }
290 nc.Close()
291 }
292
293 func TestUserCredentialBytes(t *testing.T) {
294 c := newTester(t)
295 inst := c.CreateServer(t, false, trustServerOpts(t)...)
296 t.Cleanup(func() { inst.Destroy(t) })
297
298 clientURL := inst.Servers[0].URL
299
300 // Test with JWT and seed as byte slices
301 jwtBytes := []byte(nstsUJWT)
302 seedBytes := tsUSeed
303
304 nc, err := nats.Connect(clientURL, nats.UserCredentialBytes(jwtBytes, seedBytes))
305 if err != nil {
306 t.Fatalf("Expected to connect with separate JWT and seed bytes, got %v", err)
307 }
308 nc.Close()
309
310 // Test with chained credentials (JWT and seed in same byte slice)
311 nc2, err := nats.Connect(clientURL, nats.UserCredentialBytes([]byte(nstsChained)))
312 if err != nil {
313 t.Fatalf("Expected to connect with chained credentials bytes, got %v", err)
314 }
315 nc2.Close()
316 }
317
318 // If we are using TLS and have multiple servers we try to match the IP
319 // from a discovered server with the expected hostname for certs without IP
320 // designations. In certain cases where there is a not authorized error and
321 // we were trying the second server with the IP only and getting an error
322 // that was hard to understand for the end user. This did require
323 // Opts.Secure = false, but the fix removed the check on Opts.Secure to decide
324 // if we need to save off the hostname that we connected to first.
325 func TestUserCredentialsChainedFileNotFoundError(t *testing.T) {
326 c := newTester(t)
327 // Trust-server config with managed server-only TLS; SANs intentionally
328 // exclude IPs.
329 sans := []string{"localhost"}
330 if h := testerHost(t); h != "localhost" {
331 sans = append(sans, h)
332 }
333 opts := append(trustServerOpts(t),
334 testservice.WithGeneratedTLS(testservice.TLSServerOnly(), testservice.TLSSANs(sans...)),
335 )
336 inst := c.CreateCluster(t, 2, false, opts...)
337 t.Cleanup(func() { inst.Destroy(t) })
338 caPath, _, _ := tlsCertFiles(t, inst)
339
340 clientURL := inst.Servers[0].URL
341
342 // Make sure we get the right error here.
343 nc, err := nats.Connect(clientURL,
344 nats.RootCAs(caPath),
345 nats.UserCredentials("filenotfound.creds"))
346
347 if err == nil {
348 nc.Close()
349 t.Fatalf("Expected an error on missing credentials file")
350 }
351 if !strings.Contains(err.Error(), "no such file or directory") &&
352 !strings.Contains(err.Error(), "The system cannot find the file specified") {
353 t.Fatalf("Expected a missing file error, got %q", err)
354 }
355 }
356
357 func TestNkeyAuth(t *testing.T) {
358 seed := []byte("SUAKYRHVIOREXV7EUZTBHUHL7NUMHPMAS7QMDU3GTIUWEI5LDNOXD43IZY")
359 kp, _ := nkeys.FromSeed(seed)
360 pub, _ := kp.PublicKey()
361
362 authBody := fmt.Sprintf(`authorization {
363 users: [
364 { nkey: %q }
365 ]
366 }`, string(pub))
367
368 c := newTester(t)
369 inst := c.CreateServer(t, false, singleUserPassOpts(authBody)...)
370 t.Cleanup(func() { inst.Destroy(t) })
371
372 clientURL := inst.Servers[0].URL
373
374 baseOpts := func() nats.Options {
375 o := nats.GetDefaultOptions()
376 o.Url = clientURL
377 o.AllowReconnect = true
378 o.MaxReconnect = 10
379 o.ReconnectWait = 100 * time.Millisecond
380 o.Timeout = nats.DefaultTimeout
381 return o
382 }
383
384 opts := baseOpts()
385 if _, err := opts.Connect(); err == nil {
386 t.Fatalf("Expected to fail with no nkey auth defined")
387 }
388 opts.Nkey = string(pub)
389 if _, err := opts.Connect(); err != nats.ErrNkeyButNoSigCB {
390 t.Fatalf("Expected to fail with nkey defined but no signature callback, got %v", err)
391 }
392 badSign := func(nonce []byte) ([]byte, error) {
393 return []byte("VALID?"), nil
394 }
395 opts.SignatureCB = badSign
396 if _, err := opts.Connect(); err == nil {
397 t.Fatalf("Expected to fail with nkey and bad signature callback")
398 }
399 goodSign := func(nonce []byte) ([]byte, error) {
400 sig, err := kp.Sign(nonce)
401 if err != nil {
402 t.Fatalf("Failed signing nonce: %v", err)
403 }
404 return sig, nil
405 }
406 opts.SignatureCB = goodSign
407 nc, err := opts.Connect()
408 if err != nil {
409 t.Fatalf("Expected to succeed but got %v", err)
410 }
411 defer nc.Close()
412
413 // Now disconnect by killing the server and restarting.
414 inst.StopServer(t, inst.Servers[0])
415 inst.StartServer(t, inst.Servers[0])
416
417 if err := nc.FlushTimeout(5 * time.Second); err != nil {
418 t.Fatalf("Error on Flush: %v", err)
419 }
420 }
421
422 // These drive the server-pool shuffle with a comma-joined two-URL pool. The
423 // DNS multi-IP path (net.LookupHost returning several addresses for one host)
424 // reaches the same srvPool shuffle but is not covered directly: the tester
425 // cannot bind two servers to one port across address families.
426
427 func TestLookupHostResultIsRandomized(t *testing.T) {
428 c := newTester(t)
429 s1 := c.CreateServer(t, false)
430 t.Cleanup(func() { s1.Destroy(t) })
431 s2 := c.CreateServer(t, false)
432 t.Cleanup(func() { s2.Destroy(t) })
433
434 urls := s1.Servers[0].URL + "," + s2.Servers[0].URL
435
436 const total = 100
437 conns := make([]*nats.Conn, 0, total)
438 for i := 0; i < total; i++ {
439 nc, err := nats.Connect(urls)
440 if err != nil {
441 t.Fatalf("Error on connect (i=%d): %v", i, err)
442 }
443 conns = append(conns, nc)
444 }
445 t.Cleanup(func() {
446 for _, nc := range conns {
447 nc.Close()
448 }
449 })
450
451 // Tally which server each connection ended up on.
452 var n1, n2 int
453 for _, nc := range conns {
454 switch nc.ConnectedUrl() {
455 case s1.Servers[0].URL:
456 n1++
457 case s2.Servers[0].URL:
458 n2++
459 default:
460 t.Fatalf("Unexpected ConnectedUrl: %q (expected %q or %q)", nc.ConnectedUrl(), s1.Servers[0].URL, s2.Servers[0].URL)
461 }
462 }
463 if n1 < 35 || n1 > 65 {
464 t.Fatalf("Does not seem balanced between servers: s1=%d, s2=%d", n1, n2)
465 }
466 }
467
468 func TestLookupHostResultIsNotRandomizedWithNoRandom(t *testing.T) {
469 c := newTester(t)
470 s1 := c.CreateServer(t, false)
471 t.Cleanup(func() { s1.Destroy(t) })
472 s2 := c.CreateServer(t, false)
473 t.Cleanup(func() { s2.Destroy(t) })
474
475 urls := s1.Servers[0].URL + "," + s2.Servers[0].URL
476
477 const total = 100
478 conns := make([]*nats.Conn, 0, total)
479 for i := 0; i < total; i++ {
480 nc, err := nats.Connect(urls, nats.DontRandomize())
481 if err != nil {
482 t.Fatalf("Error on connect (i=%d): %v", i, err)
483 }
484 conns = append(conns, nc)
485 }
486 t.Cleanup(func() {
487 for _, nc := range conns {
488 nc.Close()
489 }
490 })
491
492 // With DontRandomize, every connection should hit s1 (the first URL).
493 for i, nc := range conns {
494 if got, want := nc.ConnectedUrl(), s1.Servers[0].URL; got != want {
495 t.Fatalf("Connection %d: expected %q, got %q (DontRandomize should pin to first URL)", i, want, got)
496 }
497 }
498 }
499
500 func TestConnectedAddr(t *testing.T) {
501 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
502 var nilNC *nats.Conn
503 if addr := nilNC.ConnectedAddr(); addr != "" {
504 t.Fatalf("Expected empty result for nil connection, got %q", addr)
505 }
506 nc, err := nats.Connect(inst.Servers[0].URL)
507 if err != nil {
508 t.Fatalf("Error connecting: %v", err)
509 }
510 // We cannot compare against s.Addr().String() (no in-process server
511 // here). Verify the connected addr is non-empty, has host:port form,
512 // and reports the same port we dialed.
513 addr := nc.ConnectedAddr()
514 if addr == "" {
515 t.Fatalf("Expected non-empty connected address")
516 }
517 _, port, err := net.SplitHostPort(addr)
518 if err != nil {
519 t.Fatalf("Expected host:port format, got %q: %v", addr, err)
520 }
521 wantPort := fmt.Sprintf("%d", inst.Servers[0].Port)
522 if port != wantPort {
523 t.Fatalf("Expected port %s, got %s (addr %q)", wantPort, port, addr)
524 }
525 nc.Close()
526 if addr := nc.ConnectedAddr(); addr != "" {
527 t.Fatalf("Expected empty result for closed connection, got %q", addr)
528 }
529 })
530 }
531
532 func TestLocalAddr(t *testing.T) {
533 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
534 var nilNC *nats.Conn
535 if addr := nilNC.LocalAddr(); addr != "" {
536 t.Fatalf("Expected empty result for nil connection, got %q", addr)
537 }
538 nc, err := nats.Connect(inst.Servers[0].URL)
539 if err != nil {
540 t.Fatalf("Error connecting: %v", err)
541 }
542 addr := nc.LocalAddr()
543 if addr == "" {
544 t.Fatalf("Expected non-empty local address")
545 }
546 // Verify it's a valid address format
547 host, port, err := net.SplitHostPort(addr)
548 if err != nil {
549 t.Fatalf("Expected valid host:port format, got %q: %v", addr, err)
550 }
551 if host == "" {
552 t.Fatalf("Expected non-empty host in address %q", addr)
553 }
554 if port == "" {
555 t.Fatalf("Expected non-empty port in address %q", addr)
556 }
557 nc.Close()
558 if addr := nc.LocalAddr(); addr != "" {
559 t.Fatalf("Expected empty result for closed connection, got %q", addr)
560 }
561 })
562 }
563
564 func TestSubscribeSyncRace(t *testing.T) {
565 withServer(t, func(t *testing.T, nc *nats.Conn) {
566 go func() {
567 time.Sleep(time.Millisecond)
568 nc.Close()
569 }()
570
571 subj := "foo.sync.race"
572 for range 10000 {
573 if _, err := nc.SubscribeSync(subj); err != nil {
574 break
575 }
576 if _, err := nc.QueueSubscribeSync(subj, "gc"); err != nil {
577 break
578 }
579 }
580 })
581 }
582
583 func TestBadSubjectsAndQueueNames(t *testing.T) {
584 withServer(t, func(t *testing.T, nc *nats.Conn) {
585 // Make sure we get errors on bad subjects (spaces, etc)
586 // We want the client to protect the user.
587 badSubs := []string{"foo bar", "foo..bar", ".foo", "bar.baz.", "baz\t.foo"}
588 for _, subj := range badSubs {
589 if _, err := nc.SubscribeSync(subj); err != nats.ErrBadSubject {
590 t.Fatalf("Expected an error of ErrBadSubject for %q, got %v", subj, err)
591 }
592 }
593
594 badQueues := []string{"foo group", "group\t1", "g1\r\n2"}
595 for _, q := range badQueues {
596 if _, err := nc.QueueSubscribeSync("foo", q); err != nats.ErrBadQueueName {
597 t.Fatalf("Expected an error of ErrBadQueueName for %q, got %v", q, err)
598 }
599 }
600 })
601 }
602
603 func TestTypeSubscription(t *testing.T) {
604 withServer(t, func(t *testing.T, nc *nats.Conn) {
605 // Make sure that ConsumerInfo() returns invalid subscription type error
606 sub, err := nc.Subscribe("foo", func(_ *nats.Msg) {})
607 if err != nil {
608 t.Fatalf("Error subscribing: %v", err)
609 }
610
611 if _, err := sub.ConsumerInfo(); err != nats.ErrTypeSubscription {
612 t.Fatalf("Expected an error about invalid subscription type, got %v", err)
613 }
614 })
615 }
616
617 func TestAuthErrorOnReconnect(t *testing.T) {
618 // This is a bit of an artificial test, but it is to demonstrate
619 // that if the client is disconnected from a server (not due to an auth error),
620 // it will still correctly stop the reconnection logic if it gets twice an
621 // auth error from the same server.
622
623 c := newTester(t)
624
625 s1Inst := c.CreateServer(t, false)
626 t.Cleanup(func() { s1Inst.Destroy(t) })
627
628 authBody := `authorization {
629 user: ivan
630 password: pwd
631 }`
632 s2Inst := c.CreateServer(t, false, singleUserPassOpts(authBody)...)
633 t.Cleanup(func() { s2Inst.Destroy(t) })
634
635 dch := make(chan bool)
636 cch := make(chan bool)
637
638 urls := fmt.Sprintf("%s, %s", s1Inst.Servers[0].URL, s2Inst.Servers[0].URL)
639 nc, err := nats.Connect(urls,
640 nats.ReconnectWait(25*time.Millisecond),
641 nats.ReconnectJitter(0, 0),
642 nats.MaxReconnects(-1),
643 nats.DontRandomize(),
644 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, _ error) {}),
645 nats.DisconnectErrHandler(func(_ *nats.Conn, e error) {
646 dch <- true
647 }),
648 nats.ClosedHandler(func(_ *nats.Conn) {
649 cch <- true
650 }))
651 if err != nil {
652 t.Fatalf("Expected to connect, got err: %v\n", err)
653 }
654 defer nc.Close()
655
656 s1Inst.StopServer(t, s1Inst.Servers[0])
657
658 // wait for disconnect
659 if e := WaitTime(dch, 5*time.Second); e != nil {
660 t.Fatal("Did not receive a disconnect callback message")
661 }
662
663 // Wait for ClosedCB
664 if e := WaitTime(cch, 5*time.Second); e != nil {
665 reconnects := nc.Stats().Reconnects
666 t.Fatalf("Did not receive a closed callback message, #reconnects: %v", reconnects)
667 }
668
669 // Reconnects counts TCP-level successes, not auth outcomes. The abort
670 // fires after 2 auth violations, but StopServer's listener-drain window
671 // lets a stopping server briefly accept TCP as well, so the range is 2
672 // (auth errors) to 2*len(pool) = 4 for this 2-server pool.
673 if reconnects := nc.Stats().Reconnects; reconnects < 2 || reconnects > 4 {
674 t.Fatalf("Expected 2-4 reconnects (2 auth errors + up to 2 drain-window TCP successes), got %v", reconnects)
675 }
676
677 // Expect connection to be closed...
678 if !nc.IsClosed() {
679 t.Fatalf("Wrong status: %d\n", nc.Status())
680 }
681 }
682
683 func TestStatsRace(t *testing.T) {
684 withServer(t, func(t *testing.T, nc *nats.Conn) {
685 wg := sync.WaitGroup{}
686 wg.Add(1)
687 ch := make(chan bool)
688 go func() {
689 defer wg.Done()
690 for {
691 select {
692 case <-ch:
693 return
694 default:
695 nc.Stats()
696 }
697 }
698 }()
699
700 nc.Subscribe("foo", func(_ *nats.Msg) {})
701 for range 1000 {
702 nc.Publish("foo", []byte("hello"))
703 }
704
705 close(ch)
706 wg.Wait()
707 })
708 }
709
710 func TestRequestLeaksMapEntries(t *testing.T) {
711 withServer(t, func(t *testing.T, nc *nats.Conn) {
712 response := []byte("I will help you")
713 nc.Subscribe("foo", func(m *nats.Msg) {
714 nc.Publish(m.Reply, response)
715 })
716
717 for range 100 {
718 msg, err := nc.Request("foo", nil, 500*time.Millisecond)
719 if err != nil {
720 t.Fatalf("Received an error on Request test: %s", err)
721 }
722 if !bytes.Equal(msg.Data, response) {
723 t.Fatalf("Received invalid response")
724 }
725 }
726 })
727 }
728
729 func TestRequestMultipleReplies(t *testing.T) {
730 withServerInstance(t, func(t *testing.T, nc *nats.Conn, inst *testservice.Instance) {
731 response := []byte("I will help you")
732 nc.Subscribe("foo", func(m *nats.Msg) {
733 m.Respond(response)
734 m.Respond(response)
735 })
736 nc.Flush()
737
738 nc2, err := nats.Connect(inst.Servers[0].URL)
739 if err != nil {
740 t.Fatalf("Error on connect: %v", err)
741 }
742 defer nc2.Close()
743
744 errCh := make(chan error, 1)
745 // Send a request on bar and expect nothing
746 go func() {
747 if m, err := nc2.Request("bar", nil, 500*time.Millisecond); m != nil || err == nil {
748 errCh <- fmt.Errorf("Expected no reply, got m=%+v err=%v", m, err)
749 return
750 }
751 errCh <- nil
752 }()
753
754 // Send a request on foo, we use only one of the 2 replies
755 if _, err := nc2.Request("foo", nil, time.Second); err != nil {
756 t.Fatalf("Received an error on Request test: %s", err)
757 }
758 if e := <-errCh; e != nil {
759 t.Fatal(e.Error())
760 }
761 })
762 }
763
764 func TestGetRTT(t *testing.T) {
765 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
766 nc, err := nats.Connect(inst.Servers[0].URL, nats.ReconnectWait(10*time.Millisecond), nats.ReconnectJitter(0, 0))
767 if err != nil {
768 t.Fatalf("Expected to connect to server, got %v", err)
769 }
770 defer nc.Close()
771
772 rtt, err := nc.RTT()
773 if err != nil {
774 t.Fatalf("Unexpected error getting RTT: %v", err)
775 }
776 if rtt > time.Second {
777 t.Fatalf("RTT value too large: %v", rtt)
778 }
779 // We should not get a value when in any disconnected state.
780 inst.StopServer(t, inst.Servers[0])
781 time.Sleep(5 * time.Millisecond)
782 if _, err = nc.RTT(); err != nats.ErrDisconnected {
783 t.Fatalf("Expected disconnected error getting RTT when disconnected, got %v", err)
784 }
785 })
786 }
787
788 func TestGetClientIP(t *testing.T) {
789 withServer(t, func(t *testing.T, nc *nats.Conn) {
790 ip, err := nc.GetClientIP()
791 if err != nil {
792 t.Fatalf("Got error looking up IP: %v", err)
793 }
794 // In the testservice topology the client may be reaching the server
795 // through a non-loopback address (docker bridge or a routed host).
796 // Verify the IP is non-nil instead of strict IsLoopback.
797 if ip == nil {
798 t.Fatalf("Expected non-nil IP")
799 }
800 nc.Close()
801 if _, err := nc.GetClientIP(); err != nats.ErrConnectionClosed {
802 t.Fatalf("Expected a connection closed error, got %v", err)
803 }
804 })
805 }
806
807 func TestReconnectWaitJitter(t *testing.T) {
808 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
809 rch := make(chan time.Time, 1)
810 nc, err := nats.Connect(inst.Servers[0].URL,
811 nats.ReconnectWait(100*time.Millisecond),
812 nats.ReconnectJitter(500*time.Millisecond, 0),
813 nats.ReconnectHandler(func(_ *nats.Conn) {
814 rch <- time.Now()
815 }),
816 )
817 if err != nil {
818 t.Fatalf("Error during connect: %v", err)
819 }
820 defer nc.Close()
821
822 inst.StopServer(t, inst.Servers[0])
823 start := time.Now()
824 // Wait a bit so that the library tries a first time without waiting.
825 time.Sleep(50 * time.Millisecond)
826 inst.StartServer(t, inst.Servers[0])
827 select {
828 case end := <-rch:
829 dur := end.Sub(start)
830 // We should wait at least the reconnect wait + random up to 500ms.
831 // Account for a bit of variation since we rely on the reconnect
832 // handler which is not invoked in place.
833 if dur < 90*time.Millisecond || dur > 800*time.Millisecond {
834 t.Fatalf("Wrong wait: %v", dur)
835 }
836 case <-time.After(5 * time.Second):
837 t.Fatalf("Should have reconnected")
838 }
839 nc.Close()
840
841 // Use a long reconnect wait
842 nc, err = nats.Connect(inst.Servers[0].URL, nats.ReconnectWait(10*time.Minute))
843 if err != nil {
844 t.Fatalf("Error during connect: %v", err)
845 }
846 defer nc.Close()
847
848 // Cause a disconnect
849 inst.StopServer(t, inst.Servers[0])
850 // Wait a bit for the reconnect loop to go into wait mode.
851 time.Sleep(50 * time.Millisecond)
852 inst.StartServer(t, inst.Servers[0])
853 // Now close and expect the reconnect go routine to return..
854 nc.Close()
855 // Wait for the doReconnect goroutine to exit. The 50ms used by the
856 // exit; poll up to 2s since a fixed short sleep is racy under -race.
857 deadline := time.Now().Add(2 * time.Second)
858 var found bool
859 var snapshot []byte
860 for time.Now().Before(deadline) {
861 buf := make([]byte, 100000)
862 n := runtime.Stack(buf, true)
863 if !strings.Contains(string(buf[:n]), "doReconnect") {
864 found = true
865 break
866 }
867 snapshot = buf[:n]
868 time.Sleep(20 * time.Millisecond)
869 }
870 if !found {
871 t.Fatalf("doReconnect go routine still running:\n%s", snapshot)
872 }
873 })
874 }
875
876 func TestCustomReconnectDelay(t *testing.T) {
877 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
878 expectedAttempt := 1
879 errCh := make(chan error, 1)
880 cCh := make(chan bool, 1)
881 nc, err := nats.Connect(inst.Servers[0].URL,
882 nats.Timeout(100*time.Millisecond), // Need to lower for Windows tests
883 nats.CustomReconnectDelay(func(n int) time.Duration {
884 var err error
885 var delay time.Duration
886 if n != expectedAttempt {
887 err = fmt.Errorf("Expected attempt to be %v, got %v", expectedAttempt, n)
888 } else {
889 expectedAttempt++
890 if n <= 4 {
891 delay = 100 * time.Millisecond
892 }
893 }
894 if err != nil {
895 select {
896 case errCh <- err:
897 default:
898 }
899 }
900 return delay
901 }),
902 nats.MaxReconnects(4),
903 nats.ClosedHandler(func(_ *nats.Conn) {
904 cCh <- true
905 }),
906 )
907 if err != nil {
908 t.Fatalf("Error during connect: %v", err)
909 }
910 defer nc.Close()
911
912 // Cause disconnect
913 inst.StopServer(t, inst.Servers[0])
914
915 // We should be trying to reconnect 4 times
916 start := time.Now()
917
918 // Wait on error or completion of test.
919 select {
920 case e := <-errCh:
921 if e != nil {
922 t.Fatal(e.Error())
923 }
924 case <-cCh:
925 case <-time.After(2 * time.Second):
926 t.Fatalf("No CB invoked")
927 }
928 // On Windows, a failed connect attempt will last as much as Timeout(),
929 // so we need to take that into account.
930 max := 500 * time.Millisecond
931 if runtime.GOOS == "windows" {
932 max = time.Second
933 }
934 if dur := time.Since(start); dur >= max {
935 t.Fatalf("Waited too long on each reconnect: %v", dur)
936 }
937 })
938 }
939
940 func TestMsg_RespondMsg(t *testing.T) {
941 withServer(t, func(t *testing.T, nc *nats.Conn) {
942 sub, err := nc.SubscribeSync(nats.NewInbox())
943 if err != nil {
944 t.Fatalf("subscribe failed: %s", err)
945 }
946
947 nc.PublishMsg(&nats.Msg{Reply: sub.Subject, Subject: sub.Subject, Data: []byte("request")})
948 req, err := sub.NextMsg(time.Second)
949 if err != nil {
950 t.Fatalf("NextMsg failed: %s", err)
951 }
952
953 // verifies that RespondMsg sets the reply subject on msg based on req
954 err = req.RespondMsg(&nats.Msg{Data: []byte("response")})
955 if err != nil {
956 t.Fatalf("RespondMsg failed: %s", err)
957 }
958
959 resp, err := sub.NextMsg(time.Second)
960 if err != nil {
961 t.Fatalf("NextMsg failed: %s", err)
962 }
963
964 if !bytes.Equal(resp.Data, []byte("response")) {
965 t.Fatalf("did not get correct response: %q", resp.Data)
966 }
967 })
968 }
969
970 func TestCustomInboxPrefix(t *testing.T) {
971 opts := &nats.Options{}
972 for _, p := range []string{"$BOB.", "$BOB.*", "$BOB.>", ">", ".", "", "BOB.*.X", "BOB.>.X"} {
973 err := nats.CustomInboxPrefix(p)(opts)
974 if err == nil {
975 t.Fatalf("Expected error for %q", p)
976 }
977 }
978
979 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
980 nc, err := nats.Connect(inst.Servers[0].URL, nats.CustomInboxPrefix("$BOB"))
981 if err != nil {
982 t.Fatalf("Expected to connect to server, got %v", err)
983 }
984 defer nc.Close()
985
986 sub, err := nc.Subscribe(nats.NewInbox(), func(msg *nats.Msg) {
987 if !strings.HasPrefix(msg.Reply, "$BOB.") {
988 t.Fatalf("invalid inbox subject %q received", msg.Reply)
989 }
990
991 if len(strings.Split(msg.Reply, ".")) != 3 {
992 t.Fatalf("invalid number tokens in %s", msg.Reply)
993 }
994
995 msg.Respond([]byte("ok"))
996 })
997 if err != nil {
998 t.Fatalf("subscribe failed: %s", err)
999 }
1000
1001 resp, err := nc.Request(sub.Subject, nil, time.Second)
1002 if err != nil {
1003 t.Fatalf("request failed: %s", err)
1004 }
1005
1006 if !bytes.Equal(resp.Data, []byte("ok")) {
1007 t.Fatalf("did not receive ok: %q", resp.Data)
1008 }
1009 })
1010 }
1011
1012 func TestRespInbox(t *testing.T) {
1013 withServer(t, func(t *testing.T, nc *nats.Conn) {
1014 if _, err := nc.Subscribe("foo", func(msg *nats.Msg) {
1015 lastDot := strings.LastIndex(msg.Reply, ".")
1016 if lastDot == -1 {
1017 msg.Respond([]byte(fmt.Sprintf("Invalid reply subject: %q", msg.Reply)))
1018 return
1019 }
1020 lastToken := msg.Reply[lastDot+1:]
1021 replySuffixLen := 8
1022 if len(lastToken) != replySuffixLen {
1023 msg.Respond([]byte(fmt.Sprintf("Invalid last token: %q", lastToken)))
1024 return
1025 }
1026 msg.Respond(nil)
1027 }); err != nil {
1028 t.Fatalf("subscribe failed: %s", err)
1029 }
1030 resp, err := nc.Request("foo", []byte("check inbox"), time.Second)
1031 if err != nil {
1032 t.Fatalf("Request failed: %v", err)
1033 }
1034 if len(resp.Data) > 0 {
1035 t.Fatalf("Error: %s", resp.Data)
1036 }
1037 })
1038 }
1039
1040 func TestSkipSubjectValidation(t *testing.T) {
1041 withServerInstance(t, func(t *testing.T, _ *nats.Conn, inst *testservice.Instance) {
1042 nc, err := nats.Connect(inst.Servers[0].URL, nats.SkipSubjectValidation())
1043 if err != nil {
1044 t.Fatalf("Expected to connect to server, got %v", err)
1045 }
1046 defer nc.Close()
1047
1048 // Try to publish to a bad subject.
1049 badSubj := "foo bar"
1050 if err := nc.Publish(badSubj, []byte("hello")); err != nil {
1051 t.Fatalf("Expected to publish to bad subject %q, got error: %v", badSubj, err)
1052 }
1053 })
1054 }
1055
1056 func BenchmarkNextMsgNoTimeout(b *testing.B) {
1057 c := newTester(b)
1058 inst := c.CreateServer(b, false)
1059 b.Cleanup(func() { inst.Destroy(b) })
1060 url := inst.Servers[0].URL
1061
1062 ncp, err := nats.Connect(url)
1063 if err != nil {
1064 b.Fatalf("Error connecting: %v", err)
1065 }
1066 defer ncp.Close()
1067 ncs, err := nats.Connect(url, nats.SyncQueueLen(b.N))
1068 if err != nil {
1069 b.Fatalf("Error connecting: %v", err)
1070 }
1071 defer ncs.Close()
1072
1073 // Test processing speed so no long subject or payloads.
1074 subj := "a"
1075
1076 sub, err := ncs.SubscribeSync(subj)
1077 if err != nil {
1078 b.Fatalf("Error subscribing: %v", err)
1079 }
1080 ncs.Flush()
1081
1082 // Set it up so we can internally queue all the messages.
1083 sub.SetPendingLimits(b.N, b.N*1000)
1084
1085 for range b.N {
1086 ncp.Publish(subj, nil)
1087 }
1088 ncp.Flush()
1089
1090 // Wait for them to all be queued up, testing NextMsg not server here.
1091 // Only wait at most one second.
1092 wait := time.Now().Add(time.Second)
1093 for time.Now().Before(wait) {
1094 nm, _, err := sub.Pending()
1095 if err != nil {
1096 b.Fatalf("Error on Pending() - %v", err)
1097 }
1098 if nm >= b.N {
1099 break
1100 }
1101 time.Sleep(10 * time.Millisecond)
1102 }
1103
1104 b.ResetTimer()
1105 for i := range b.N {
1106 if _, err := sub.NextMsg(10 * time.Millisecond); err != nil {
1107 b.Fatalf("Error getting message[%d]: %v", i, err)
1108 }
1109 }
1110 }