Debian Codegraph @

nats_test.go

raw
1 // Copyright 2012-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 nats
15
16 // //////////////////////////////////////////////////////////////////////////////
17 // Package scoped specific tests here..
18 // //////////////////////////////////////////////////////////////////////////////
19
20 import (
21 "bufio"
22 "bytes"
23 "crypto/ecdsa"
24 "crypto/elliptic"
25 "crypto/rand"
26 "crypto/tls"
27 "crypto/x509"
28 "crypto/x509/pkix"
29 "encoding/json"
30 "errors"
31 "fmt"
32 "math/big"
33 "net"
34 "net/http"
35 "net/url"
36 "os"
37 "reflect"
38 "regexp"
39 "runtime"
40 "strconv"
41 "strings"
42 "sync"
43 "sync/atomic"
44 "testing"
45 "time"
46
47 "github.com/nats-io/nkeys"
48 )
49
50 func TestVersion(t *testing.T) {
51 // Semantic versioning
52 verRe := regexp.MustCompile(`\d+.\d+.\d+(-\S+)?`)
53 if !verRe.MatchString(Version) {
54 t.Fatalf("Version not compatible with semantic versioning: %q", Version)
55 }
56 }
57
58 // Dumb wait program to sync on callbacks, etc... Will timeout
59 func Wait(ch chan bool) error {
60 return WaitTime(ch, 5*time.Second)
61 }
62
63 func WaitTime(ch chan bool, timeout time.Duration) error {
64 select {
65 case <-ch:
66 return nil
67 case <-time.After(timeout):
68 }
69 return errors.New("timeout")
70 }
71
72 func stackFatalf(t *testing.T, f string, args ...any) {
73 lines := make([]string, 0, 32)
74 msg := fmt.Sprintf(f, args...)
75 lines = append(lines, msg)
76
77 // Generate the Stack of callers: Skip us and verify* frames.
78 for i := 1; true; i++ {
79 _, file, line, ok := runtime.Caller(i)
80 if !ok {
81 break
82 }
83 msg := fmt.Sprintf("%d - %s:%d", i, file, line)
84 lines = append(lines, msg)
85 }
86 t.Fatalf("%s", strings.Join(lines, "\n"))
87 }
88
89 // Check the error channel for an error and if one is present,
90 // calls t.Fatal(e.Error()). Note that this supports tests that
91 // send nil to the error channel and so report error only if
92 // e is != nil.
93 func checkErrChannel(t *testing.T, errCh chan error) {
94 t.Helper()
95 select {
96 case e := <-errCh:
97 if e != nil {
98 t.Fatal(e.Error())
99 }
100 default:
101 }
102 }
103
104 func TestVersionMatchesTag(t *testing.T) {
105 refType := os.Getenv("GITHUB_REF_TYPE")
106 if refType != "tag" {
107 t.SkipNow()
108 }
109 tag := os.Getenv("GITHUB_REF_NAME")
110 // We expect a tag of the form vX.Y.Z. If that's not the case,
111 // we need someone to have a look. So fail if first letter is not
112 // a `v`
113 if tag[0] != 'v' {
114 t.Fatalf("Expect tag to start with `v`, tag is: %s", tag)
115 }
116 // Strip the `v` from the tag for the version comparison.
117 if Version != tag[1:] {
118 t.Fatalf("Version (%s) does not match tag (%s)", Version, tag[1:])
119 }
120 }
121
122 func TestExpandPath(t *testing.T) {
123 if runtime.GOOS == "windows" {
124 origUserProfile := os.Getenv("USERPROFILE")
125 origHomeDrive, origHomePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH")
126 defer func() {
127 os.Setenv("USERPROFILE", origUserProfile)
128 os.Setenv("HOMEDRIVE", origHomeDrive)
129 os.Setenv("HOMEPATH", origHomePath)
130 }()
131
132 cases := []struct {
133 path string
134 userProfile string
135 homeDrive string
136 homePath string
137
138 wantPath string
139 wantErr bool
140 }{
141 // Missing HOMEDRIVE and HOMEPATH.
142 {path: "/Foo/Bar", userProfile: `C:\Foo\Bar`, wantPath: "/Foo/Bar"},
143 {path: "Foo/Bar", userProfile: `C:\Foo\Bar`, wantPath: "Foo/Bar"},
144 {path: "~/Fizz", userProfile: `C:\Foo\Bar`, wantPath: `C:\Foo\Bar\Fizz`},
145
146 // Missing USERPROFILE.
147 {path: "~/Fizz", homeDrive: "X:", homePath: `\Foo\Bar`, wantPath: `X:\Foo\Bar\Fizz`},
148
149 // Set all environment variables. HOMEDRIVE and HOMEPATH take
150 // precedence.
151 {path: "~/Fizz", userProfile: `C:\Foo\Bar`,
152 homeDrive: "X:", homePath: `\Foo\Bar`, wantPath: `X:\Foo\Bar\Fizz`},
153
154 // Missing all environment variables.
155 {path: "~/Fizz", wantErr: true},
156 }
157 for i, c := range cases {
158 t.Run(fmt.Sprintf("windows case %d", i), func(t *testing.T) {
159 os.Setenv("USERPROFILE", c.userProfile)
160 os.Setenv("HOMEDRIVE", c.homeDrive)
161 os.Setenv("HOMEPATH", c.homePath)
162
163 gotPath, err := expandPath(c.path)
164 if !c.wantErr && err != nil {
165 t.Fatalf("unexpected error: got=%v; want=%v", err, nil)
166 } else if c.wantErr && err == nil {
167 t.Fatalf("unexpected success: got=%v; want=%v", nil, "err")
168 }
169
170 if gotPath != c.wantPath {
171 t.Fatalf("unexpected path: got=%v; want=%v", gotPath, c.wantPath)
172 }
173 })
174 }
175
176 return
177 }
178
179 // Unix tests
180
181 origHome := os.Getenv("HOME")
182 defer os.Setenv("HOME", origHome)
183
184 cases := []struct {
185 path string
186 home string
187 testEnv string
188
189 wantPath string
190 wantErr bool
191 }{
192 {path: "/foo/bar", home: "/fizz/buzz", wantPath: "/foo/bar"},
193 {path: "foo/bar", home: "/fizz/buzz", wantPath: "foo/bar"},
194 {path: "~/fizz", home: "/foo/bar", wantPath: "/foo/bar/fizz"},
195 {path: "$HOME/fizz", home: "/foo/bar", wantPath: "/foo/bar/fizz"},
196
197 // missing HOME env var
198 {path: "~/fizz", wantErr: true},
199 }
200 for i, c := range cases {
201 t.Run(fmt.Sprintf("unix case %d", i), func(t *testing.T) {
202 os.Setenv("HOME", c.home)
203
204 gotPath, err := expandPath(c.path)
205 if !c.wantErr && err != nil {
206 t.Fatalf("unexpected error: got=%v; want=%v", err, nil)
207 } else if c.wantErr && err == nil {
208 t.Fatalf("unexpected success: got=%v; want=%v", nil, "err")
209 }
210
211 if gotPath != c.wantPath {
212 t.Fatalf("unexpected path: got=%v; want=%v", gotPath, c.wantPath)
213 }
214 })
215 }
216 }
217
218 // //////////////////////////////////////////////////////////////////////////////
219 // ServerPool tests
220 // //////////////////////////////////////////////////////////////////////////////
221
222 var testServers = []string{
223 "nats://localhost:1222",
224 "nats://localhost:1223",
225 "nats://localhost:1224",
226 "nats://localhost:1225",
227 "nats://localhost:1226",
228 "nats://localhost:1227",
229 "nats://localhost:1228",
230 }
231
232 func TestSimplifiedURLs(t *testing.T) {
233 for _, test := range []struct {
234 name string
235 servers []string
236 expected []string
237 }{
238 {
239 "nats",
240 []string{
241 "nats://host1:1234/",
242 "nats://host1:1234",
243 "nats://host2:",
244 "nats://host3",
245 "host4:1234",
246 "host5:",
247 "host6",
248 "nats://[::1:2:3:4]:1234",
249 "nats://[::5:6:7:8]:",
250 "nats://[::9:10:11:12]",
251 "[::13:14:15:16]:",
252 "[::17:18:19:20]:1234",
253 },
254 []string{
255 "nats://host1:1234/",
256 "nats://host1:1234",
257 "nats://host2:4222",
258 "nats://host3:4222",
259 "nats://host4:1234",
260 "nats://host5:4222",
261 "nats://host6:4222",
262 "nats://[::1:2:3:4]:1234",
263 "nats://[::5:6:7:8]:4222",
264 "nats://[::9:10:11:12]:4222",
265 "nats://[::13:14:15:16]:4222",
266 "nats://[::17:18:19:20]:1234",
267 },
268 },
269 {
270 "ws",
271 []string{
272 "ws://host1:1234",
273 "ws://host2:",
274 "ws://host3",
275 "ws://[::1:2:3:4]:1234",
276 "ws://[::5:6:7:8]:",
277 "ws://[::9:10:11:12]",
278 },
279 []string{
280 "ws://host1:1234",
281 "ws://host2:80",
282 "ws://host3:80",
283 "ws://[::1:2:3:4]:1234",
284 "ws://[::5:6:7:8]:80",
285 "ws://[::9:10:11:12]:80",
286 },
287 },
288 {
289 "wss",
290 []string{
291 "wss://host1:1234",
292 "wss://host2:",
293 "wss://host3",
294 "wss://[::1:2:3:4]:1234",
295 "wss://[::5:6:7:8]:",
296 "wss://[::9:10:11:12]",
297 },
298 []string{
299 "wss://host1:1234",
300 "wss://host2:443",
301 "wss://host3:443",
302 "wss://[::1:2:3:4]:1234",
303 "wss://[::5:6:7:8]:443",
304 "wss://[::9:10:11:12]:443",
305 },
306 },
307 } {
308 t.Run(test.name, func(t *testing.T) {
309 opts := GetDefaultOptions()
310 opts.NoRandomize = true
311 opts.Servers = test.servers
312
313 nc := &Conn{Opts: opts}
314 if err := nc.setupServerPool(); err != nil {
315 t.Fatalf("Problem setting up Server Pool: %v\n", err)
316 }
317 // Check server pool directly
318 for i, u := range nc.srvPool {
319 if u.URL.String() != test.expected[i] {
320 t.Fatalf("Expected url %q, got %q", test.expected[i], u.URL.String())
321 }
322 }
323 })
324 }
325 }
326
327 func TestServersRandomize(t *testing.T) {
328 opts := GetDefaultOptions()
329 opts.Servers = testServers
330 nc := &Conn{Opts: opts}
331 if err := nc.setupServerPool(); err != nil {
332 t.Fatalf("Problem setting up Server Pool: %v\n", err)
333 }
334 // Build []string from srvPool
335 clientServers := []string{}
336 for _, s := range nc.srvPool {
337 clientServers = append(clientServers, s.URL.String())
338 }
339 // In theory this could happen..
340 if reflect.DeepEqual(testServers, clientServers) {
341 t.Fatalf("ServerPool list not randomized\n")
342 }
343
344 // Now test that we do not randomize if proper flag is set.
345 opts = GetDefaultOptions()
346 opts.Servers = testServers
347 opts.NoRandomize = true
348 nc = &Conn{Opts: opts}
349 if err := nc.setupServerPool(); err != nil {
350 t.Fatalf("Problem setting up Server Pool: %v\n", err)
351 }
352 // Build []string from srvPool
353 clientServers = []string{}
354 for _, s := range nc.srvPool {
355 clientServers = append(clientServers, s.URL.String())
356 }
357 if !reflect.DeepEqual(testServers, clientServers) {
358 t.Fatalf("ServerPool list should not be randomized\n")
359 }
360
361 // Although the original intent was that if Opts.Url is
362 // set, Opts.Servers is not (and vice versa), the behavior
363 // is that Opts.Url is always first, even when randomization
364 // is enabled. So make sure that this is still the case.
365 opts = GetDefaultOptions()
366 opts.Url = DefaultURL
367 opts.Servers = testServers
368 nc = &Conn{Opts: opts}
369 if err := nc.setupServerPool(); err != nil {
370 t.Fatalf("Problem setting up Server Pool: %v\n", err)
371 }
372 // Build []string from srvPool
373 clientServers = []string{}
374 for _, s := range nc.srvPool {
375 clientServers = append(clientServers, s.URL.String())
376 }
377 // In theory this could happen..
378 if reflect.DeepEqual(testServers, clientServers) {
379 t.Fatalf("ServerPool list not randomized\n")
380 }
381 if clientServers[0] != DefaultURL {
382 t.Fatalf("Options.Url should be first in the array, got %v", clientServers[0])
383 }
384 }
385
386 func TestSelectNextServer(t *testing.T) {
387 opts := GetDefaultOptions()
388 opts.Servers = testServers
389 opts.NoRandomize = true
390 nc := &Conn{Opts: opts}
391 if err := nc.setupServerPool(); err != nil {
392 t.Fatalf("Problem setting up Server Pool: %v\n", err)
393 }
394 if nc.current != nc.srvPool[0] {
395 t.Fatalf("Wrong default selection: %v\n", nc.current.URL)
396 }
397
398 sel, err := nc.selectNextServer()
399 if err != nil {
400 t.Fatalf("Got an err: %v\n", err)
401 }
402 // Check that we are now looking at #2, and current is now last.
403 if len(nc.srvPool) != len(testServers) {
404 t.Fatalf("List is incorrect size: %d vs %d\n", len(nc.srvPool), len(testServers))
405 }
406 if nc.current.URL.String() != testServers[1] {
407 t.Fatalf("Selection incorrect: %v vs %v\n", nc.current.URL, testServers[1])
408 }
409 if nc.srvPool[len(nc.srvPool)-1].URL.String() != testServers[0] {
410 t.Fatalf("Did not push old to last position\n")
411 }
412 if sel != nc.srvPool[0] {
413 t.Fatalf("Did not return correct server: %v vs %v\n", sel.URL, nc.srvPool[0].URL)
414 }
415
416 // Test that we do not keep servers where we have tried to reconnect past our limit.
417 nc.srvPool[0].Reconnects = int(opts.MaxReconnect)
418 if _, err := nc.selectNextServer(); err != nil {
419 t.Fatalf("Got an err: %v\n", err)
420 }
421 // Check that we are now looking at #3, and current is not in the list.
422 if len(nc.srvPool) != len(testServers)-1 {
423 t.Fatalf("List is incorrect size: %d vs %d\n", len(nc.srvPool), len(testServers)-1)
424 }
425 if nc.current.URL.String() != testServers[2] {
426 t.Fatalf("Selection incorrect: %v vs %v\n", nc.current.URL, testServers[2])
427 }
428 if nc.srvPool[len(nc.srvPool)-1].URL.String() == testServers[1] {
429 t.Fatalf("Did not throw away the last server correctly\n")
430 }
431 }
432
433 // This will test that comma separated url strings work properly for
434 // the Connect() command.
435 func TestUrlArgument(t *testing.T) {
436 check := func(url string, expected []string) {
437 if !reflect.DeepEqual(processUrlString(url), expected) {
438 t.Fatalf("Got wrong response processing URL: %q, RES: %#v\n", url, processUrlString(url))
439 }
440 }
441 // This is normal case
442 oneExpected := []string{"nats://localhost:1222"}
443
444 check("nats://localhost:1222", oneExpected)
445 check("nats://localhost:1222 ", oneExpected)
446 check(" nats://localhost:1222", oneExpected)
447 check(" nats://localhost:1222 ", oneExpected)
448 check("nats://localhost:1222/", oneExpected)
449
450 var multiExpected = []string{
451 "nats://localhost:1222",
452 "nats://localhost:1223",
453 "nats://localhost:1224",
454 }
455
456 check("nats://localhost:1222,nats://localhost:1223,nats://localhost:1224", multiExpected)
457 check("nats://localhost:1222, nats://localhost:1223, nats://localhost:1224", multiExpected)
458 check(" nats://localhost:1222, nats://localhost:1223, nats://localhost:1224 ", multiExpected)
459 check("nats://localhost:1222, nats://localhost:1223 ,nats://localhost:1224", multiExpected)
460 check("nats://localhost:1222/,nats://localhost:1223/,nats://localhost:1224/", multiExpected)
461 }
462
463 func TestParserPing(t *testing.T) {
464 c := &Conn{}
465 c.newReaderWriter()
466 c.bw.switchToPending()
467
468 c.ps = &parseState{}
469
470 if c.ps.state != OP_START {
471 t.Fatalf("Expected OP_START vs %d\n", c.ps.state)
472 }
473 ping := []byte("PING\r\n")
474 err := c.parse(ping[:1])
475 if err != nil || c.ps.state != OP_P {
476 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
477 }
478 err = c.parse(ping[1:2])
479 if err != nil || c.ps.state != OP_PI {
480 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
481 }
482 err = c.parse(ping[2:3])
483 if err != nil || c.ps.state != OP_PIN {
484 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
485 }
486 err = c.parse(ping[3:4])
487 if err != nil || c.ps.state != OP_PING {
488 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
489 }
490 err = c.parse(ping[4:5])
491 if err != nil || c.ps.state != OP_PING {
492 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
493 }
494 err = c.parse(ping[5:6])
495 if err != nil || c.ps.state != OP_START {
496 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
497 }
498 err = c.parse(ping)
499 if err != nil || c.ps.state != OP_START {
500 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
501 }
502 // Should tolerate spaces
503 ping = []byte("PING \r")
504 err = c.parse(ping)
505 if err != nil || c.ps.state != OP_PING {
506 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
507 }
508 c.ps.state = OP_START
509 ping = []byte("PING \r \n")
510 err = c.parse(ping)
511 if err != nil || c.ps.state != OP_START {
512 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
513 }
514 }
515
516 func TestParserErr(t *testing.T) {
517 c := &Conn{}
518 c.status = CLOSED
519 c.newReaderWriter()
520 c.bw.switchToPending()
521
522 c.ps = &parseState{}
523
524 // This test focuses on the parser only, not how the error is
525 // actually processed by the upper layer.
526
527 if c.ps.state != OP_START {
528 t.Fatalf("Expected OP_START vs %d\n", c.ps.state)
529 }
530
531 expectedError := "'Any kind of error'"
532 errProto := []byte("-ERR " + expectedError + "\r\n")
533 err := c.parse(errProto[:1])
534 if err != nil || c.ps.state != OP_MINUS {
535 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
536 }
537 err = c.parse(errProto[1:2])
538 if err != nil || c.ps.state != OP_MINUS_E {
539 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
540 }
541 err = c.parse(errProto[2:3])
542 if err != nil || c.ps.state != OP_MINUS_ER {
543 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
544 }
545 err = c.parse(errProto[3:4])
546 if err != nil || c.ps.state != OP_MINUS_ERR {
547 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
548 }
549 err = c.parse(errProto[4:5])
550 if err != nil || c.ps.state != OP_MINUS_ERR_SPC {
551 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
552 }
553 err = c.parse(errProto[5:6])
554 if err != nil || c.ps.state != OP_MINUS_ERR_SPC {
555 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
556 }
557
558 // Check with split arg buffer
559 err = c.parse(errProto[6:7])
560 if err != nil || c.ps.state != MINUS_ERR_ARG {
561 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
562 }
563 err = c.parse(errProto[7:10])
564 if err != nil || c.ps.state != MINUS_ERR_ARG {
565 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
566 }
567 err = c.parse(errProto[10 : len(errProto)-2])
568 if err != nil || c.ps.state != MINUS_ERR_ARG {
569 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
570 }
571 if c.ps.argBuf == nil {
572 t.Fatal("ArgBuf should not be nil")
573 }
574 s := string(c.ps.argBuf)
575 if s != expectedError {
576 t.Fatalf("Expected %v, got %v", expectedError, s)
577 }
578 err = c.parse(errProto[len(errProto)-2:])
579 if err != nil || c.ps.state != OP_START {
580 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
581 }
582
583 // Check without split arg buffer
584 errProto = []byte("-ERR 'Any error'\r\n")
585 err = c.parse(errProto)
586 if err != nil || c.ps.state != OP_START {
587 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
588 }
589 }
590
591 func TestParserOK(t *testing.T) {
592 c := &Conn{}
593 c.ps = &parseState{}
594
595 if c.ps.state != OP_START {
596 t.Fatalf("Expected OP_START vs %d\n", c.ps.state)
597 }
598 errProto := []byte("+OKay\r\n")
599 err := c.parse(errProto[:1])
600 if err != nil || c.ps.state != OP_PLUS {
601 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
602 }
603 err = c.parse(errProto[1:2])
604 if err != nil || c.ps.state != OP_PLUS_O {
605 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
606 }
607 err = c.parse(errProto[2:3])
608 if err != nil || c.ps.state != OP_PLUS_OK {
609 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
610 }
611 err = c.parse(errProto[3:])
612 if err != nil || c.ps.state != OP_START {
613 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
614 }
615 }
616
617 func TestParserShouldFail(t *testing.T) {
618 c := &Conn{}
619 c.ps = &parseState{}
620
621 if err := c.parse([]byte(" PING")); err == nil {
622 t.Fatal("Should have received a parse error")
623 }
624 c.ps.state = OP_START
625 if err := c.parse([]byte("POO")); err == nil {
626 t.Fatal("Should have received a parse error")
627 }
628 c.ps.state = OP_START
629 if err := c.parse([]byte("Px")); err == nil {
630 t.Fatal("Should have received a parse error")
631 }
632 c.ps.state = OP_START
633 if err := c.parse([]byte("PIx")); err == nil {
634 t.Fatal("Should have received a parse error")
635 }
636 c.ps.state = OP_START
637 if err := c.parse([]byte("PINx")); err == nil {
638 t.Fatal("Should have received a parse error")
639 }
640 // Stop here because 'PING' protos are tolerant for anything between PING and \n
641
642 c.ps.state = OP_START
643 if err := c.parse([]byte("POx")); err == nil {
644 t.Fatal("Should have received a parse error")
645 }
646 c.ps.state = OP_START
647 if err := c.parse([]byte("PONx")); err == nil {
648 t.Fatal("Should have received a parse error")
649 }
650 // Stop here because 'PONG' protos are tolerant for anything between PONG and \n
651
652 c.ps.state = OP_START
653 if err := c.parse([]byte("ZOO")); err == nil {
654 t.Fatal("Should have received a parse error")
655 }
656 c.ps.state = OP_START
657 if err := c.parse([]byte("Mx\r\n")); err == nil {
658 t.Fatal("Should have received a parse error")
659 }
660 c.ps.state = OP_START
661 if err := c.parse([]byte("MSx\r\n")); err == nil {
662 t.Fatal("Should have received a parse error")
663 }
664 c.ps.state = OP_START
665 if err := c.parse([]byte("MSGx\r\n")); err == nil {
666 t.Fatal("Should have received a parse error")
667 }
668 c.ps.state = OP_START
669 if err := c.parse([]byte("MSG foo\r\n")); err == nil {
670 t.Fatal("Should have received a parse error")
671 }
672 c.ps.state = OP_START
673 if err := c.parse([]byte("MSG \r\n")); err == nil {
674 t.Fatal("Should have received a parse error")
675 }
676 c.ps.state = OP_START
677 if err := c.parse([]byte("MSG foo 1\r\n")); err == nil {
678 t.Fatal("Should have received a parse error")
679 }
680 c.ps.state = OP_START
681 if err := c.parse([]byte("MSG foo bar 1\r\n")); err == nil {
682 t.Fatal("Should have received a parse error")
683 }
684 c.ps.state = OP_START
685 if err := c.parse([]byte("MSG foo bar 1 baz\r\n")); err == nil {
686 t.Fatal("Should have received a parse error")
687 }
688 c.ps.state = OP_START
689 if err := c.parse([]byte("MSG foo 1 bar baz\r\n")); err == nil {
690 t.Fatal("Should have received a parse error")
691 }
692 c.ps.state = OP_START
693 if err := c.parse([]byte("+x\r\n")); err == nil {
694 t.Fatal("Should have received a parse error")
695 }
696 c.ps.state = OP_START
697 if err := c.parse([]byte("+Ox\r\n")); err == nil {
698 t.Fatal("Should have received a parse error")
699 }
700 c.ps.state = OP_START
701 if err := c.parse([]byte("-x\r\n")); err == nil {
702 t.Fatal("Should have received a parse error")
703 }
704 c.ps.state = OP_START
705 if err := c.parse([]byte("-Ex\r\n")); err == nil {
706 t.Fatal("Should have received a parse error")
707 }
708 c.ps.state = OP_START
709 if err := c.parse([]byte("-ERx\r\n")); err == nil {
710 t.Fatal("Should have received a parse error")
711 }
712 c.ps.state = OP_START
713 if err := c.parse([]byte("-ERRx\r\n")); err == nil {
714 t.Fatal("Should have received a parse error")
715 }
716 }
717
718 func TestParserSplitMsg(t *testing.T) {
719 nc := &Conn{}
720 nc.ps = &parseState{}
721
722 buf := []byte("MSG a\r\n")
723 err := nc.parse(buf)
724 if err == nil {
725 t.Fatal("Expected an error")
726 }
727 nc.ps = &parseState{}
728
729 buf = []byte("MSG a b c\r\n")
730 err = nc.parse(buf)
731 if err == nil {
732 t.Fatal("Expected an error")
733 }
734 nc.ps = &parseState{}
735
736 expectedCount := uint64(1)
737 expectedSize := uint64(3)
738
739 buf = []byte("MSG a")
740 err = nc.parse(buf)
741 if err != nil {
742 t.Fatalf("Parser error: %v", err)
743 }
744 if nc.ps.argBuf == nil {
745 t.Fatal("Arg buffer should have been created")
746 }
747
748 buf = []byte(" 1 3\r\nf")
749 err = nc.parse(buf)
750 if err != nil {
751 t.Fatalf("Parser error: %v", err)
752 }
753 if nc.ps.ma.size != 3 {
754 t.Fatalf("Wrong msg size: %d instead of 3", nc.ps.ma.size)
755 }
756 if nc.ps.ma.sid != 1 {
757 t.Fatalf("Wrong sid: %d instead of 1", nc.ps.ma.sid)
758 }
759 if string(nc.ps.ma.subject) != "a" {
760 t.Fatalf("Wrong subject: '%s' instead of 'a'", string(nc.ps.ma.subject))
761 }
762 if nc.ps.msgBuf == nil {
763 t.Fatal("Msg buffer should have been created")
764 }
765
766 buf = []byte("oo\r\n")
767 err = nc.parse(buf)
768 if err != nil {
769 t.Fatalf("Parser error: %v", err)
770 }
771 if (nc.Statistics.InMsgs != expectedCount) || (nc.Statistics.InBytes != expectedSize) {
772 t.Fatalf("Wrong stats: %d - %d instead of %d - %d", nc.Statistics.InMsgs, nc.Statistics.InBytes, expectedCount, expectedSize)
773 }
774 if (nc.ps.argBuf != nil) || (nc.ps.msgBuf != nil) {
775 t.Fatal("Buffers should be nil now")
776 }
777
778 buf = []byte("MSG a 1 3\r\nfo")
779 err = nc.parse(buf)
780 if err != nil {
781 t.Fatalf("Parser error: %v", err)
782 }
783 if nc.ps.ma.size != 3 {
784 t.Fatalf("Wrong msg size: %d instead of 3", nc.ps.ma.size)
785 }
786 if nc.ps.ma.sid != 1 {
787 t.Fatalf("Wrong sid: %d instead of 1", nc.ps.ma.sid)
788 }
789 if string(nc.ps.ma.subject) != "a" {
790 t.Fatalf("Wrong subject: '%s' instead of 'a'", string(nc.ps.ma.subject))
791 }
792 if nc.ps.argBuf == nil {
793 t.Fatal("Arg buffer should have been created")
794 }
795 if nc.ps.msgBuf == nil {
796 t.Fatal("Msg buffer should have been created")
797 }
798
799 expectedCount++
800 expectedSize += 3
801
802 buf = []byte("o\r\n")
803 err = nc.parse(buf)
804 if err != nil {
805 t.Fatalf("Parser error: %v", err)
806 }
807 if (nc.Statistics.InMsgs != expectedCount) || (nc.Statistics.InBytes != expectedSize) {
808 t.Fatalf("Wrong stats: %d - %d instead of %d - %d", nc.Statistics.InMsgs, nc.Statistics.InBytes, expectedCount, expectedSize)
809 }
810 if (nc.ps.argBuf != nil) || (nc.ps.msgBuf != nil) {
811 t.Fatal("Buffers should be nil now")
812 }
813
814 buf = []byte("MSG a 1 6\r\nfo")
815 err = nc.parse(buf)
816 if err != nil {
817 t.Fatalf("Parser error: %v", err)
818 }
819 if nc.ps.ma.size != 6 {
820 t.Fatalf("Wrong msg size: %d instead of 3", nc.ps.ma.size)
821 }
822 if nc.ps.ma.sid != 1 {
823 t.Fatalf("Wrong sid: %d instead of 1", nc.ps.ma.sid)
824 }
825 if string(nc.ps.ma.subject) != "a" {
826 t.Fatalf("Wrong subject: '%s' instead of 'a'", string(nc.ps.ma.subject))
827 }
828 if nc.ps.argBuf == nil {
829 t.Fatal("Arg buffer should have been created")
830 }
831 if nc.ps.msgBuf == nil {
832 t.Fatal("Msg buffer should have been created")
833 }
834
835 buf = []byte("ob")
836 err = nc.parse(buf)
837 if err != nil {
838 t.Fatalf("Parser error: %v", err)
839 }
840
841 expectedCount++
842 expectedSize += 6
843
844 buf = []byte("ar\r\n")
845 err = nc.parse(buf)
846 if err != nil {
847 t.Fatalf("Parser error: %v", err)
848 }
849 if (nc.Statistics.InMsgs != expectedCount) || (nc.Statistics.InBytes != expectedSize) {
850 t.Fatalf("Wrong stats: %d - %d instead of %d - %d", nc.Statistics.InMsgs, nc.Statistics.InBytes, expectedCount, expectedSize)
851 }
852 if (nc.ps.argBuf != nil) || (nc.ps.msgBuf != nil) {
853 t.Fatal("Buffers should be nil now")
854 }
855
856 // Let's have a msg that is bigger than the parser's scratch size.
857 // Since we prepopulate the msg with 'foo', adding 3 to the size.
858 msgSize := cap(nc.ps.scratch) + 100 + 3
859 buf = []byte(fmt.Sprintf("MSG a 1 b %d\r\nfoo", msgSize))
860 err = nc.parse(buf)
861 if err != nil {
862 t.Fatalf("Parser error: %v", err)
863 }
864 if nc.ps.ma.size != msgSize {
865 t.Fatalf("Wrong msg size: %d instead of %d", nc.ps.ma.size, msgSize)
866 }
867 if nc.ps.ma.sid != 1 {
868 t.Fatalf("Wrong sid: %d instead of 1", nc.ps.ma.sid)
869 }
870 if string(nc.ps.ma.subject) != "a" {
871 t.Fatalf("Wrong subject: '%s' instead of 'a'", string(nc.ps.ma.subject))
872 }
873 if string(nc.ps.ma.reply) != "b" {
874 t.Fatalf("Wrong reply: '%s' instead of 'b'", string(nc.ps.ma.reply))
875 }
876 if nc.ps.argBuf == nil {
877 t.Fatal("Arg buffer should have been created")
878 }
879 if nc.ps.msgBuf == nil {
880 t.Fatal("Msg buffer should have been created")
881 }
882
883 expectedCount++
884 expectedSize += uint64(msgSize)
885
886 bufSize := msgSize - 3
887
888 buf = make([]byte, bufSize)
889 for i := 0; i < bufSize; i++ {
890 buf[i] = byte('a' + (i % 26))
891 }
892
893 err = nc.parse(buf)
894 if err != nil {
895 t.Fatalf("Parser error: %v", err)
896 }
897 if nc.ps.state != MSG_PAYLOAD {
898 t.Fatalf("Wrong state: %v instead of %v", nc.ps.state, MSG_PAYLOAD)
899 }
900 if nc.ps.ma.size != msgSize {
901 t.Fatalf("Wrong (ma) msg size: %d instead of %d", nc.ps.ma.size, msgSize)
902 }
903 if len(nc.ps.msgBuf) != msgSize {
904 t.Fatalf("Wrong msg size: %d instead of %d", len(nc.ps.msgBuf), msgSize)
905 }
906 // Check content:
907 if string(nc.ps.msgBuf[0:3]) != "foo" {
908 t.Fatalf("Wrong msg content: %s", string(nc.ps.msgBuf))
909 }
910 for k := 3; k < nc.ps.ma.size; k++ {
911 if nc.ps.msgBuf[k] != byte('a'+((k-3)%26)) {
912 t.Fatalf("Wrong msg content: %s", string(nc.ps.msgBuf))
913 }
914 }
915
916 buf = []byte("\r\n")
917 if err := nc.parse(buf); err != nil {
918 t.Fatalf("Unexpected error during parsing: %v", err)
919 }
920 if (nc.Statistics.InMsgs != expectedCount) || (nc.Statistics.InBytes != expectedSize) {
921 t.Fatalf("Wrong stats: %d - %d instead of %d - %d", nc.Statistics.InMsgs, nc.Statistics.InBytes, expectedCount, expectedSize)
922 }
923 if (nc.ps.argBuf != nil) || (nc.ps.msgBuf != nil) {
924 t.Fatal("Buffers should be nil now")
925 }
926 if nc.ps.state != OP_START {
927 t.Fatalf("Wrong state: %v", nc.ps.state)
928 }
929 }
930
931 func TestNormalizeError(t *testing.T) {
932 expected := "Typical Error"
933 if s := normalizeErr("-ERR '" + expected + "'"); s != expected {
934 t.Fatalf("Expected '%s', got '%s'", expected, s)
935 }
936
937 expected = "Trim Surrounding Spaces"
938 if s := normalizeErr("-ERR '" + expected + "' "); s != expected {
939 t.Fatalf("Expected '%s', got '%s'", expected, s)
940 }
941
942 expected = "Trim Surrounding Spaces Without Quotes"
943 if s := normalizeErr("-ERR " + expected + " "); s != expected {
944 t.Fatalf("Expected '%s', got '%s'", expected, s)
945 }
946
947 expected = "Error Without Quotes"
948 if s := normalizeErr("-ERR " + expected); s != expected {
949 t.Fatalf("Expected '%s', got '%s'", expected, s)
950 }
951
952 expected = "Error With Quote Only On Left"
953 if s := normalizeErr("-ERR '" + expected); s != expected {
954 t.Fatalf("Expected '%s', got '%s'", expected, s)
955 }
956
957 expected = "Error With Quote Only On Right"
958 if s := normalizeErr("-ERR " + expected + "'"); s != expected {
959 t.Fatalf("Expected '%s', got '%s'", expected, s)
960 }
961 }
962
963 func TestAsyncINFO(t *testing.T) {
964 opts := GetDefaultOptions()
965 c := &Conn{Opts: opts}
966
967 c.ps = &parseState{}
968
969 if c.ps.state != OP_START {
970 t.Fatalf("Expected OP_START vs %d\n", c.ps.state)
971 }
972
973 info := []byte("INFO {}\r\n")
974 if c.ps.state != OP_START {
975 t.Fatalf("Expected OP_START vs %d\n", c.ps.state)
976 }
977 err := c.parse(info[:1])
978 if err != nil || c.ps.state != OP_I {
979 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
980 }
981 err = c.parse(info[1:2])
982 if err != nil || c.ps.state != OP_IN {
983 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
984 }
985 err = c.parse(info[2:3])
986 if err != nil || c.ps.state != OP_INF {
987 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
988 }
989 err = c.parse(info[3:4])
990 if err != nil || c.ps.state != OP_INFO {
991 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
992 }
993 err = c.parse(info[4:5])
994 if err != nil || c.ps.state != OP_INFO_SPC {
995 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
996 }
997 err = c.parse(info[5:])
998 if err != nil || c.ps.state != OP_START {
999 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
1000 }
1001
1002 // All at once
1003 err = c.parse(info)
1004 if err != nil || c.ps.state != OP_START {
1005 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
1006 }
1007
1008 // Server pool needs to be setup
1009 c.setupServerPool()
1010
1011 // Partials requiring argBuf
1012 expectedServer := ServerInfo{
1013 ID: "test",
1014 Host: "localhost",
1015 Port: 4222,
1016 AuthRequired: true,
1017 TLSRequired: true,
1018 MaxPayload: 2 * 1024 * 1024,
1019 ConnectURLs: []string{"localhost:5222", "localhost:6222"},
1020 }
1021 // Set NoRandomize so that the check with expectedServer info
1022 // matches.
1023 c.Opts.NoRandomize = true
1024
1025 b, _ := json.Marshal(expectedServer)
1026 info = []byte(fmt.Sprintf("INFO %s\r\n", b))
1027 if c.ps.state != OP_START {
1028 t.Fatalf("Expected OP_START vs %d\n", c.ps.state)
1029 }
1030 err = c.parse(info[:9])
1031 if err != nil || c.ps.state != INFO_ARG || c.ps.argBuf == nil {
1032 t.Fatalf("Unexpected: %d err: %v argBuf: %v\n", c.ps.state, err, c.ps.argBuf)
1033 }
1034 err = c.parse(info[9:11])
1035 if err != nil || c.ps.state != INFO_ARG || c.ps.argBuf == nil {
1036 t.Fatalf("Unexpected: %d err: %v argBuf: %v\n", c.ps.state, err, c.ps.argBuf)
1037 }
1038 err = c.parse(info[11:])
1039 if err != nil || c.ps.state != OP_START || c.ps.argBuf != nil {
1040 t.Fatalf("Unexpected: %d err: %v argBuf: %v\n", c.ps.state, err, c.ps.argBuf)
1041 }
1042 if !reflect.DeepEqual(c.info, expectedServer) {
1043 t.Fatalf("Expected server info to be: %v, got: %v", expectedServer, c.info)
1044 }
1045
1046 // Good INFOs
1047 good := []string{"INFO {}\r\n", "INFO {}\r\n", "INFO {} \r\n", "INFO { \"server_id\": \"test\" } \r\n", "INFO {\"connect_urls\":[]}\r\n"}
1048 for _, gi := range good {
1049 c.ps = &parseState{}
1050 err = c.parse([]byte(gi))
1051 if err != nil || c.ps.state != OP_START {
1052 t.Fatalf("Protocol %q should be fine. Err=%v state=%v", gi, err, c.ps.state)
1053 }
1054 }
1055
1056 // Wrong INFOs
1057 wrong := []string{"IxNFO {}\r\n", "INxFO {}\r\n", "INFxO {}\r\n", "INFOx {}\r\n", "INFO{}\r\n", "INFO {}"}
1058 for _, wi := range wrong {
1059 c.ps = &parseState{}
1060 err = c.parse([]byte(wi))
1061 if err == nil && c.ps.state == OP_START {
1062 t.Fatalf("Protocol %q should have failed", wi)
1063 }
1064 }
1065
1066 checkPool := func(urls ...string) {
1067 // Check both pool and urls map
1068 if len(c.srvPool) != len(urls) {
1069 stackFatalf(t, "Pool should have %d elements, has %d", len(urls), len(c.srvPool))
1070 }
1071 if len(c.urls) != len(urls) {
1072 stackFatalf(t, "Map should have %d elements, has %d", len(urls), len(c.urls))
1073 }
1074 for _, url := range urls {
1075 if _, present := c.urls[url]; !present {
1076 stackFatalf(t, "Pool should have %q", url)
1077 }
1078 }
1079 }
1080
1081 // Now test the decoding of "connect_urls"
1082
1083 // Reset the pool
1084 c.setupServerPool()
1085 // Reinitialize the parser
1086 c.ps = &parseState{}
1087
1088 info = []byte("INFO {\"connect_urls\":[\"localhost:4222\", \"localhost:5222\"]}\r\n")
1089 err = c.parse(info)
1090 if err != nil || c.ps.state != OP_START {
1091 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
1092 }
1093 // Pool now should contain 127.0.0.1:4222 (the default URL), localhost:4222 and localhost:5222
1094 checkPool("127.0.0.1:4222", "localhost:4222", "localhost:5222")
1095
1096 // Make sure that if client receives the same, it is not added again.
1097 err = c.parse(info)
1098 if err != nil || c.ps.state != OP_START {
1099 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
1100 }
1101 // Pool should still contain 127.0.0.1:4222 (the default URL), localhost:4222 and localhost:5222
1102 checkPool("127.0.0.1:4222", "localhost:4222", "localhost:5222")
1103
1104 // Receive a new URL
1105 info = []byte("INFO {\"connect_urls\":[\"localhost:4222\", \"localhost:5222\", \"localhost:6222\"]}\r\n")
1106 err = c.parse(info)
1107 if err != nil || c.ps.state != OP_START {
1108 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
1109 }
1110 // Pool now should contain 127.0.0.1:4222 (the default URL), localhost:4222, localhost:5222 and localhost:6222
1111 checkPool("127.0.0.1:4222", "localhost:4222", "localhost:5222", "localhost:6222")
1112
1113 // Check that pool may be randomized on setup, but new URLs are always
1114 // added at end of pool.
1115 c.Opts.NoRandomize = false
1116 c.Opts.Servers = testServers
1117 // Reset the pool
1118 c.setupServerPool()
1119 // Reinitialize the parser
1120 c.ps = &parseState{}
1121 // Capture the pool sequence after randomization
1122 urlsAfterPoolSetup := make([]string, 0, len(c.srvPool))
1123 for _, srv := range c.srvPool {
1124 urlsAfterPoolSetup = append(urlsAfterPoolSetup, srv.URL.Host)
1125 }
1126 checkNewURLsAddedRandomly := func() {
1127 t.Helper()
1128 var ok bool
1129 for i := 0; i < len(urlsAfterPoolSetup); i++ {
1130 if c.srvPool[i].URL.Host != urlsAfterPoolSetup[i] {
1131 ok = true
1132 break
1133 }
1134 }
1135 if !ok {
1136 t.Fatalf("New URLs were not added randmonly: %q", c.Servers())
1137 }
1138 }
1139 // Add new urls
1140 newURLs := "\"impA:4222\", \"impB:4222\", \"impC:4222\", " +
1141 "\"impD:4222\", \"impE:4222\", \"impF:4222\", \"impG:4222\", " +
1142 "\"impH:4222\", \"impI:4222\", \"impJ:4222\""
1143 info = []byte("INFO {\"connect_urls\":[" + newURLs + "]}\r\n")
1144 err = c.parse(info)
1145 if err != nil || c.ps.state != OP_START {
1146 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
1147 }
1148 checkNewURLsAddedRandomly()
1149 // Check that we have not moved the first URL
1150 if u := c.srvPool[0].URL.Host; u != urlsAfterPoolSetup[0] {
1151 t.Fatalf("Expected first URL to be %q, got %q", urlsAfterPoolSetup[0], u)
1152 }
1153 }
1154
1155 func TestConnServers(t *testing.T) {
1156 opts := GetDefaultOptions()
1157 c := &Conn{Opts: opts}
1158 c.ps = &parseState{}
1159 c.setupServerPool()
1160
1161 validateURLs := func(serverUrls []string, expectedUrls ...string) {
1162 var found bool
1163 if len(serverUrls) != len(expectedUrls) {
1164 stackFatalf(t, "Array should have %d elements, has %d", len(expectedUrls), len(serverUrls))
1165 }
1166
1167 for _, ev := range expectedUrls {
1168 found = false
1169 for _, av := range serverUrls {
1170 if ev == av {
1171 found = true
1172 break
1173 }
1174 }
1175 if !found {
1176 stackFatalf(t, "array is missing %q in %v", ev, serverUrls)
1177 }
1178 }
1179 }
1180
1181 // check the default url
1182 validateURLs(c.Servers(), "nats://127.0.0.1:4222")
1183 if len(c.DiscoveredServers()) != 0 {
1184 t.Fatalf("Expected no discovered servers")
1185 }
1186
1187 // Add a new URL
1188 err := c.parse([]byte("INFO {\"connect_urls\":[\"localhost:5222\"]}\r\n"))
1189 if err != nil {
1190 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
1191 }
1192 // Server list should now contain both the default and the new url.
1193 validateURLs(c.Servers(), "nats://127.0.0.1:4222", "nats://localhost:5222")
1194 // Discovered servers should only contain the new url.
1195 validateURLs(c.DiscoveredServers(), "nats://localhost:5222")
1196
1197 // verify user credentials are stripped out.
1198 opts.Servers = []string{"nats://user:pass@localhost:4333", "nats://token@localhost:4444"}
1199 c = &Conn{Opts: opts}
1200 c.ps = &parseState{}
1201 c.setupServerPool()
1202
1203 validateURLs(c.Servers(), "nats://localhost:4333", "nats://localhost:4444")
1204 }
1205
1206 func TestIgnoreDiscoveredServers(t *testing.T) {
1207 opts := GetDefaultOptions()
1208 opts.IgnoreDiscoveredServers = true
1209 c := &Conn{Opts: opts}
1210 c.ps = &parseState{}
1211 c.setupServerPool()
1212
1213 if len(c.Servers()) != 1 {
1214 t.Fatalf("Expected 1 server, got %d", len(c.Servers()))
1215 }
1216
1217 err := c.parse([]byte("INFO {\"connect_urls\":[\"localhost:5222\", \"localhost:6222\"]}\r\n"))
1218 if err != nil {
1219 t.Fatalf("Unexpected: %d : %v\n", c.ps.state, err)
1220 }
1221
1222 if len(c.Servers()) != 1 {
1223 t.Fatalf("Expected 1 server, got %d: %v", len(c.Servers()), c.Servers())
1224 }
1225 if len(c.DiscoveredServers()) != 0 {
1226 t.Fatalf("Expected no discovered servers, got %v", c.DiscoveredServers())
1227 }
1228 }
1229
1230 func TestNoEchoOldServer(t *testing.T) {
1231 opts := GetDefaultOptions()
1232 opts.Url = DefaultURL
1233 opts.NoEcho = true
1234
1235 nc := &Conn{Opts: opts}
1236 if err := nc.setupServerPool(); err != nil {
1237 t.Fatalf("Problem setting up Server Pool: %v\n", err)
1238 }
1239
1240 // Old style with no proto, meaning 0. We need Proto:1 for NoEcho support.
1241 oldInfo := "{\"server_id\":\"22\",\"version\":\"1.1.0\",\"go\":\"go1.10.2\",\"port\":4222,\"max_payload\":1048576}"
1242
1243 err := nc.processInfo(oldInfo)
1244 if err != nil {
1245 t.Fatalf("Error processing old style INFO: %v\n", err)
1246 }
1247
1248 // Make sure connectProto generates an error.
1249 _, err = nc.connectProto()
1250 if err == nil {
1251 t.Fatalf("Expected an error but got none\n")
1252 }
1253 }
1254
1255 func TestExpiredAuthentication(t *testing.T) {
1256 // The goal of these tests was to check how a client with an expiring JWT
1257 // behaves. It should receive an async -ERR indicating that the auth
1258 // has expired, which will trigger reconnects. There, the lib should
1259 // received -ERR for auth violation in response to the CONNECT (instead
1260 // of the PONG). The library should close the connection after receiving
1261 // twice the same auth error.
1262 // If we use an actual JWT that expires, the way the JWT library expires
1263 // a JWT cause the server to send the async -ERR first but then accepts
1264 // the CONNECT (since JWT lib does not say that it has expired), but
1265 // when the server sets up the expire callback, that callback fires right
1266 // away and so client receives async -ERR again.
1267 // So for a deterministic test, we won't use an actual NATS Server.
1268 // Instead, we will use a mock that simply returns appropriate -ERR and
1269 // ensure the client behaves as expected.
1270 for _, test := range []struct {
1271 name string
1272 expectedProto string
1273 expectedErr error
1274 ignoreAbort bool
1275 }{
1276 {"expired users credentials", AUTHENTICATION_EXPIRED_ERR, ErrAuthExpired, false},
1277 {"revoked users credentials", AUTHENTICATION_REVOKED_ERR, ErrAuthRevoked, false},
1278 {"expired account", ACCOUNT_AUTHENTICATION_EXPIRED_ERR, ErrAccountAuthExpired, false},
1279 {"expired users credentials", AUTHENTICATION_EXPIRED_ERR, ErrAuthExpired, true},
1280 {"revoked users credentials", AUTHENTICATION_REVOKED_ERR, ErrAuthRevoked, true},
1281 {"expired account", ACCOUNT_AUTHENTICATION_EXPIRED_ERR, ErrAccountAuthExpired, true},
1282 } {
1283 t.Run(test.name, func(t *testing.T) {
1284 l, e := net.Listen("tcp", "127.0.0.1:0")
1285 if e != nil {
1286 t.Fatal("Could not listen on an ephemeral port")
1287 }
1288 tl := l.(*net.TCPListener)
1289 defer tl.Close()
1290
1291 addr := tl.Addr().(*net.TCPAddr)
1292
1293 wg := sync.WaitGroup{}
1294 wg.Add(1)
1295
1296 go func() {
1297 defer wg.Done()
1298 connect := 0
1299 for {
1300 conn, err := l.Accept()
1301 if err != nil {
1302 return
1303 }
1304 defer conn.Close()
1305
1306 info := "INFO {\"server_id\":\"foobar\",\"nonce\":\"anonce\"}\r\n"
1307 conn.Write([]byte(info))
1308
1309 // Read connect and ping commands sent from the client
1310 br := bufio.NewReaderSize(conn, 10*1024)
1311 br.ReadLine()
1312 br.ReadLine()
1313
1314 if connect++; connect == 1 {
1315 conn.Write([]byte(fmt.Sprintf("%s%s", _PONG_OP_, _CRLF_)))
1316 time.Sleep(300 * time.Millisecond)
1317 conn.Write([]byte(fmt.Sprintf("-ERR '%s'\r\n", test.expectedProto)))
1318 } else {
1319 conn.Write([]byte(fmt.Sprintf("-ERR '%s'\r\n", AUTHORIZATION_ERR)))
1320 }
1321 conn.Close()
1322 }
1323 }()
1324
1325 ch := make(chan bool)
1326 errCh := make(chan error, 10)
1327
1328 url := fmt.Sprintf("nats://127.0.0.1:%d", addr.Port)
1329 opts := []Option{
1330 ReconnectWait(25 * time.Millisecond),
1331 ReconnectJitter(0, 0),
1332 MaxReconnects(-1),
1333 ErrorHandler(func(_ *Conn, _ *Subscription, e error) {
1334 select {
1335 case errCh <- e:
1336 default:
1337 }
1338 }),
1339 ClosedHandler(func(nc *Conn) {
1340 ch <- true
1341 }),
1342 }
1343 if test.ignoreAbort {
1344 opts = append(opts, IgnoreAuthErrorAbort())
1345 }
1346 nc, err := Connect(url, opts...)
1347 if err != nil {
1348 t.Fatalf("Expected to connect, got %v", err)
1349 }
1350 defer nc.Close()
1351
1352 if test.ignoreAbort {
1353 // We expect more than 3 errors, as the connect attempt should not be aborted after 2 failed attempts.
1354 for i := 0; i < 4; i++ {
1355 select {
1356 case e := <-errCh:
1357 if i == 0 && e != test.expectedErr {
1358 t.Fatalf("Expected error %q, got %q", test.expectedErr, e)
1359 } else if i > 0 && e != ErrAuthorization {
1360 t.Fatalf("Expected error %q, got %q", ErrAuthorization, e)
1361 }
1362 case <-time.After(time.Second):
1363 if i == 0 {
1364 t.Fatalf("Missing %q error", test.expectedErr)
1365 } else {
1366 t.Fatalf("Missing %q error", ErrAuthorization)
1367 }
1368 }
1369 }
1370 return
1371 }
1372 // We should give up since we get the same error on both tries.
1373 if err := WaitTime(ch, 2*time.Second); err != nil {
1374 t.Fatal("Should have closed after multiple failed attempts.")
1375 }
1376 if stats := nc.Stats(); stats.Reconnects > 2 {
1377 t.Fatalf("Expected at most 2 reconnects, got %d", stats.Reconnects)
1378 }
1379
1380 // We expect 3 errors, the expired auth/revoke error, then 2 AUTHORIZATION_ERR
1381 // before the connection is closed.
1382 for i := 0; i < 3; i++ {
1383 select {
1384 case e := <-errCh:
1385 if i == 0 && e != test.expectedErr {
1386 t.Fatalf("Expected error %q, got %q", test.expectedErr, e)
1387 } else if i > 0 && e != ErrAuthorization {
1388 t.Fatalf("Expected error %q, got %q", ErrAuthorization, e)
1389 }
1390 default:
1391 if i == 0 {
1392 t.Fatalf("Missing %q error", test.expectedErr)
1393 } else {
1394 t.Fatalf("Missing %q error", ErrAuthorization)
1395 }
1396 }
1397 }
1398 // We should not have any more error
1399 select {
1400 case e := <-errCh:
1401 t.Fatalf("Extra error: %v", e)
1402 default:
1403 }
1404 // Close the listener and wait for go routine to end.
1405 l.Close()
1406 wg.Wait()
1407 })
1408 }
1409 }
1410
1411 func createTmpFile(t *testing.T, content []byte) string {
1412 t.Helper()
1413 conf, err := os.CreateTemp("", "")
1414 if err != nil {
1415 t.Fatalf("Error creating conf file: %v", err)
1416 }
1417 fName := conf.Name()
1418 conf.Close()
1419 if err := os.WriteFile(fName, content, 0666); err != nil {
1420 os.Remove(fName)
1421 t.Fatalf("Error writing conf file: %v", err)
1422 }
1423 return fName
1424 }
1425
1426 func TestNKeyOptionFromSeed(t *testing.T) {
1427 if _, err := NkeyOptionFromSeed("file_that_does_not_exist"); err == nil {
1428 t.Fatal("Expected error got none")
1429 }
1430
1431 seedFile := createTmpFile(t, []byte(`
1432 # No seed
1433 THIS_NOT_A_NKEY_SEED
1434 `))
1435 defer os.Remove(seedFile)
1436 if _, err := NkeyOptionFromSeed(seedFile); err == nil || !strings.Contains(err.Error(), "seed found") {
1437 t.Fatalf("Expected error about seed not found, got %v", err)
1438 }
1439 os.Remove(seedFile)
1440
1441 seedFile = createTmpFile(t, []byte(`
1442 # Invalid seed
1443 SUBADSEED
1444 `))
1445 // Make sure that we detect SU (trim space) but it still fails because
1446 // this is not a valid NKey.
1447 if _, err := NkeyOptionFromSeed(seedFile); err == nil || strings.Contains(err.Error(), "seed found") {
1448 t.Fatalf("Expected error about invalid key, got %v", err)
1449 }
1450 os.Remove(seedFile)
1451
1452 kp, _ := nkeys.CreateUser()
1453 seed, _ := kp.Seed()
1454 seedFile = createTmpFile(t, seed)
1455 opt, err := NkeyOptionFromSeed(seedFile)
1456 if err != nil {
1457 t.Fatalf("Error: %v", err)
1458 }
1459
1460 l, e := net.Listen("tcp", "127.0.0.1:0")
1461 if e != nil {
1462 t.Fatal("Could not listen on an ephemeral port")
1463 }
1464 tl := l.(*net.TCPListener)
1465 defer tl.Close()
1466
1467 addr := tl.Addr().(*net.TCPAddr)
1468
1469 ch := make(chan bool, 1)
1470 errCh := make(chan error, 1)
1471 rs := func(ch chan bool) {
1472 conn, err := l.Accept()
1473 if err != nil {
1474 errCh <- fmt.Errorf("error accepting client connection: %v", err)
1475 return
1476 }
1477 defer conn.Close()
1478 info := "INFO {\"server_id\":\"foobar\",\"nonce\":\"anonce\"}\r\n"
1479 conn.Write([]byte(info))
1480
1481 // Read connect and ping commands sent from the client
1482 br := bufio.NewReaderSize(conn, 10*1024)
1483 line, _, err := br.ReadLine()
1484 if err != nil {
1485 errCh <- fmt.Errorf("expected CONNECT and PING from client, got: %s", err)
1486 return
1487 }
1488 // If client got an error reading the seed, it will not send it
1489 if bytes.Contains(line, []byte(`"sig":`)) {
1490 conn.Write([]byte("PONG\r\n"))
1491 } else {
1492 conn.Write([]byte(`-ERR go away\r\n`))
1493 conn.Close()
1494 }
1495 // Now wait to be notified that we can finish
1496 <-ch
1497 errCh <- nil
1498 }
1499 go rs(ch)
1500
1501 nc, err := Connect(fmt.Sprintf("nats://127.0.0.1:%d", addr.Port), opt)
1502 if err != nil {
1503 t.Fatalf("Error on connect: %v", err)
1504 }
1505 nc.Close()
1506 close(ch)
1507
1508 checkErrChannel(t, errCh)
1509
1510 // Now that option is already created, change content of file
1511 os.WriteFile(seedFile, []byte(`xxxxx`), 0666)
1512 ch = make(chan bool, 1)
1513 go rs(ch)
1514
1515 if _, err := Connect(fmt.Sprintf("nats://127.0.0.1:%d", addr.Port), opt); err == nil {
1516 t.Fatal("Expected error, got none")
1517 }
1518 close(ch)
1519 checkErrChannel(t, errCh)
1520 }
1521
1522 func TestNoPanicOnSrvPoolSizeChanging(t *testing.T) {
1523 listeners := []net.Listener{}
1524 ports := []int{}
1525
1526 for i := 0; i < 3; i++ {
1527 l, err := net.Listen("tcp", "127.0.0.1:0")
1528 if err != nil {
1529 t.Fatalf("Could not listen on an ephemeral port: %v", err)
1530 }
1531 defer l.Close()
1532 tl := l.(*net.TCPListener)
1533 ports = append(ports, tl.Addr().(*net.TCPAddr).Port)
1534 listeners = append(listeners, l)
1535 }
1536
1537 wg := sync.WaitGroup{}
1538 wg.Add(len(listeners))
1539
1540 connect := int32(0)
1541 srv := func(l net.Listener) {
1542 defer wg.Done()
1543 for {
1544 conn, err := l.Accept()
1545 if err != nil {
1546 return
1547 }
1548 defer conn.Close()
1549
1550 var info string
1551
1552 reject := atomic.AddInt32(&connect, 1) <= 2
1553 if reject {
1554 // Sends a list of 3 servers, where the second does not actually run.
1555 // This server is going to reject the connect (with auth error), so
1556 // client will move to 2nd, fail, then go to third...
1557 info = fmt.Sprintf("INFO {\"server_id\":\"foobar\",\"connect_urls\":[\"127.0.0.1:%d\",\"127.0.0.1:%d\",\"127.0.0.1:%d\"]}\r\n",
1558 ports[0], ports[1], ports[2])
1559 } else {
1560 // This third server will return the INFO with only the original server
1561 // and the third one, which will make the srvPool size shrink down to 2.
1562 info = fmt.Sprintf("INFO {\"server_id\":\"foobar\",\"connect_urls\":[\"127.0.0.1:%d\",\"127.0.0.1:%d\"]}\r\n",
1563 ports[0], ports[2])
1564 }
1565 conn.Write([]byte(info))
1566
1567 // Read connect and ping commands sent from the client
1568 br := bufio.NewReaderSize(conn, 10*1024)
1569 br.ReadLine()
1570 br.ReadLine()
1571
1572 if reject {
1573 conn.Write([]byte(fmt.Sprintf("-ERR '%s'\r\n", AUTHORIZATION_ERR)))
1574 conn.Close()
1575 } else {
1576 conn.Write([]byte(pongProto))
1577 br.ReadLine()
1578 }
1579 }
1580 }
1581
1582 for _, l := range listeners {
1583 go srv(l)
1584 }
1585
1586 time.Sleep(250 * time.Millisecond)
1587
1588 nc, err := Connect(fmt.Sprintf("nats://127.0.0.1:%d", ports[0]))
1589 if err != nil {
1590 t.Fatalf("Error on connect: %v", err)
1591 }
1592 nc.Close()
1593 for _, l := range listeners {
1594 l.Close()
1595 }
1596 wg.Wait()
1597 }
1598
1599 func TestHeaderParser(t *testing.T) {
1600 shouldErr := func(hdr string) {
1601 t.Helper()
1602 if _, err := DecodeHeadersMsg([]byte(hdr)); err == nil {
1603 t.Fatalf("Expected an error")
1604 }
1605 }
1606 shouldErr("NATS/1.0")
1607 shouldErr("NATS/1.0\r\n")
1608 shouldErr("NATS/1.0\r\nk1:v1")
1609 shouldErr("NATS/1.0\r\nk1:v1\r\n")
1610 shouldErr("NATS/1.0 5\r\n\r\n")
1611 shouldErr("NATS/1.0 41\r\n\r\n")
1612 shouldErr("NATS/1.0 \r\n\r\n")
1613
1614 // Check that we can do inline status and descriptions
1615 checkStatus := func(hdr string, status int, description string) {
1616 t.Helper()
1617 hdrs, err := DecodeHeadersMsg([]byte(hdr + "\r\n\r\n"))
1618 if err != nil {
1619 t.Fatalf("Unexpected error: %v", err)
1620 }
1621 if code, err := strconv.Atoi(hdrs.Get(statusHdr)); err != nil || code != status {
1622 t.Fatalf("Expected status of %d, got %s", status, hdrs.Get(statusHdr))
1623 }
1624 if len(description) > 0 {
1625 if descr := hdrs.Get(descrHdr); err != nil || descr != description {
1626 t.Fatalf("Expected description of %q, got %q", description, descr)
1627 }
1628 }
1629 }
1630
1631 checkStatus("NATS/1.0 503", 503, "")
1632 checkStatus("NATS/1.0 503 No Responders", 503, "No Responders")
1633 checkStatus("NATS/1.0 404 No Messages", 404, "No Messages")
1634 }
1635
1636 func TestHeaderMultiLine(t *testing.T) {
1637 m := NewMsg("foo")
1638 m.Header = Header{
1639 "CorrelationID": []string{"123"},
1640 "Msg-ID": []string{"456"},
1641 "X-NATS-Keys": []string{"A", "B", "C"},
1642 "X-Test-Keys": []string{"D", "E", "F"},
1643 }
1644 // Users can opt-in to canonicalize like http.Header does
1645 // by using http.Header#Set or http.Header#Add.
1646 http.Header(m.Header).Set("accept-encoding", "json")
1647 http.Header(m.Header).Add("AUTHORIZATION", "s3cr3t")
1648
1649 // Multi Value Header becomes represented as multi-lines in the wire
1650 m.Header.Set("X-Test", "First")
1651 m.Header.Add("X-Test", "Second")
1652 m.Header.Add("X-Test", "Third")
1653
1654 b, err := m.headerBytes()
1655 if err != nil {
1656 t.Fatal(err)
1657 }
1658 result := string(b)
1659
1660 // Require the header string to have a known prefix and suffix
1661 if !strings.HasPrefix(result, "NATS/1.0\r\n") {
1662 t.Fatalf("header prefix not present")
1663 }
1664 if !strings.HasSuffix(result, "\r\n\r\n") {
1665 t.Fatalf("header suffix not present")
1666 }
1667
1668 // Require the header string to contain each of the following rows. Note
1669 // that headers can be written in any order.
1670 expectedHeaderLines := []string{
1671 "Accept-Encoding: json\r\n",
1672 "Authorization: s3cr3t\r\n",
1673 "CorrelationID: 123\r\n",
1674 "Msg-ID: 456\r\n",
1675 "X-NATS-Keys: A\r\n",
1676 "X-NATS-Keys: B\r\n",
1677 "X-NATS-Keys: C\r\n",
1678 "X-Test: First\r\n",
1679 "X-Test: Second\r\n",
1680 "X-Test: Third\r\n",
1681 "X-Test-Keys: D\r\n",
1682 "X-Test-Keys: E\r\n",
1683 "X-Test-Keys: F\r\n",
1684 }
1685 for _, h := range expectedHeaderLines {
1686 if !strings.Contains(result, h) {
1687 t.Fatalf("expected header line '%s' to be present", h)
1688 }
1689 }
1690 }
1691
1692 func TestHeaderValidKeys(t *testing.T) {
1693 const validChars = "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~"
1694
1695 m := NewMsg("foo")
1696 m.Header = Header{
1697 validChars: []string{"value"},
1698 }
1699 if _, err := m.headerBytes(); err != nil {
1700 t.Fatal(err.Error())
1701 }
1702 }
1703
1704 func TestHeaderInvalidKeys(t *testing.T) {
1705 testKeys := []string{
1706 "", // Empty string
1707 ":", // Illegal printable ASCII character
1708 "\r", // Non-printable ASCII character
1709 "\n", // Non-printable ASCII character
1710 "\t", // Non-printable ASCII character
1711 "\x00", // Non-printable ASCII character
1712 "→", // Standard Unicode character
1713 "\u200b", // Non-printable Unicode character
1714 }
1715 for _, key := range testKeys {
1716 m := NewMsg("foo")
1717 m.Header = Header{
1718 key: []string{"value"},
1719 }
1720 if _, err := m.headerBytes(); err == nil {
1721 t.Fatalf("expected error for key '%s'", key)
1722 }
1723 }
1724 }
1725
1726 func TestHeaderValidValues(t *testing.T) {
1727 testValues := []string{
1728 "!\"#$%&'()*+,-./0123456789;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", // Printable ASCII characters
1729 "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1c\x1d\x1e\x1f", // Invisible ASCII characters (except CR/LF)
1730 "→", // Standard Unicode characters
1731 "\u200b", // Non-printable Unicode characters
1732 }
1733 for _, v := range testValues {
1734 m := NewMsg(v)
1735 m.Header = Header{
1736 "key": []string{v},
1737 }
1738 if _, err := m.headerBytes(); err != nil {
1739 t.Fatal(err.Error())
1740 }
1741 }
1742 }
1743
1744 func TestHeaderNewlineValue(t *testing.T) {
1745 m := NewMsg("foo")
1746 m.Header.Set("X-Test", "line1\nline2\rline3")
1747
1748 b, err := m.headerBytes()
1749 if err != nil {
1750 t.Fatal(err.Error())
1751 }
1752 out := string(b)
1753 if !strings.Contains(out, "X-Test: line1 line2 line3") {
1754 t.Fatalf("expected sanitized 'X-Test: line1 line2 line3', got: %q", out)
1755 }
1756 }
1757
1758 func TestLameDuckMode(t *testing.T) {
1759 l, err := net.Listen("tcp", "127.0.0.1:0")
1760 if err != nil {
1761 t.Fatalf("Could not listen on an ephemeral port: %v", err)
1762 }
1763 tl := l.(*net.TCPListener)
1764 defer tl.Close()
1765
1766 addr := tl.Addr().(*net.TCPAddr)
1767
1768 wg := sync.WaitGroup{}
1769 wg.Add(1)
1770 go func() {
1771 defer wg.Done()
1772 ldmInfos := []string{"INFO {\"ldm\":true}\r\n", "INFO {\"connect_urls\":[\"127.0.0.1:1234\"],\"ldm\":true}\r\n"}
1773 for _, ldmInfo := range ldmInfos {
1774 conn, err := l.Accept()
1775 if err != nil {
1776 return
1777 }
1778 defer conn.Close()
1779
1780 info := "INFO {\"server_id\":\"foobar\"}\r\n"
1781 conn.Write([]byte(info))
1782
1783 // Read connect and ping commands sent from the client
1784 br := bufio.NewReaderSize(conn, 10*1024)
1785 br.ReadLine()
1786 br.ReadLine()
1787 conn.Write([]byte(pongProto))
1788
1789 // Wait a bit and then send a INFO with LDM
1790 time.Sleep(100 * time.Millisecond)
1791 conn.Write([]byte(ldmInfo))
1792 br.ReadLine()
1793 conn.Close()
1794 }
1795 }()
1796
1797 url := fmt.Sprintf("nats://127.0.0.1:%d", addr.Port)
1798 time.Sleep(100 * time.Millisecond)
1799
1800 for _, test := range []struct {
1801 name string
1802 curls bool
1803 }{
1804 {"without connect urls", false},
1805 {"with connect urls", true},
1806 } {
1807 t.Run(test.name, func(t *testing.T) {
1808 ch := make(chan bool, 1)
1809 errCh := make(chan error, 1)
1810 nc, err := Connect(url,
1811 DiscoveredServersHandler(func(nc *Conn) {
1812 ds := nc.DiscoveredServers()
1813 if !reflect.DeepEqual(ds, []string{"nats://127.0.0.1:1234"}) {
1814 errCh <- fmt.Errorf("wrong discovered servers: %q", ds)
1815 } else {
1816 errCh <- nil
1817 }
1818 }),
1819 LameDuckModeHandler(func(_ *Conn) {
1820 ch <- true
1821 }),
1822 )
1823 if err != nil {
1824 t.Fatalf("Expected to connect, got %v", err)
1825 }
1826 defer nc.Close()
1827
1828 select {
1829 case <-ch:
1830 case <-time.After(2 * time.Second):
1831 t.Fatal("should have been notified of LDM")
1832 }
1833 select {
1834 case e := <-errCh:
1835 if !test.curls {
1836 t.Fatal("should not have received connect urls")
1837 } else if e != nil {
1838 t.Fatal(e.Error())
1839 }
1840 default:
1841 if test.curls {
1842 t.Fatal("should have received notification about discovered servers")
1843 }
1844 }
1845
1846 nc.Close()
1847 })
1848 }
1849 wg.Wait()
1850 }
1851
1852 func BenchmarkHeaderDecode(b *testing.B) {
1853 benchmarks := []struct {
1854 name string
1855 header Header
1856 }{
1857 {"Small - 25", Header{
1858 "Msg-ID": []string{"123"}},
1859 },
1860 {"Medium - 141", Header{
1861 "CorrelationID": []string{"123"},
1862 "Msg-ID": []string{"456"},
1863 "X-NATS-Keys": []string{"A", "B", "C"},
1864 "X-Test-Keys": []string{"D", "E", "F"},
1865 }},
1866 {"Large - 368", Header{
1867 "CorrelationID": []string{"123"},
1868 "Msg-ID": []string{"456"},
1869 "X-NATS-Keys": []string{"A", "B", "C"},
1870 "X-Test-Keys": []string{"D", "E", "F"},
1871 "X-A-Long-Header-1": []string{strings.Repeat("A", 100)},
1872 "X-A-Long-Header-2": []string{strings.Repeat("A", 100)},
1873 }},
1874 }
1875 for _, bm := range benchmarks {
1876 b.Run(bm.name, func(b *testing.B) {
1877 b.ReportAllocs()
1878
1879 m := NewMsg("foo")
1880 m.Header = bm.header
1881 hdr, err := m.headerBytes()
1882 if err != nil {
1883 b.Fatalf("Unexpected error: %v", err)
1884 }
1885
1886 for i := 0; i < b.N; i++ {
1887 if _, err := DecodeHeadersMsg(hdr); err != nil {
1888 b.Fatalf("Unexpected error: %v", err)
1889 }
1890 }
1891 })
1892 }
1893 }
1894
1895 // mockConn simulates a network connection that can fail and recover
1896 // after a number of attempts.
1897 type mockConn struct {
1898 failures int
1899 temporaryFailures int
1900 data []byte
1901 }
1902
1903 func (mc *mockConn) Write(p []byte) (int, error) {
1904 if mc.failures < mc.temporaryFailures {
1905 mc.failures++
1906 return 0, &net.OpError{Op: "write", Net: "tcp", Err: errors.New("i/o timeout")}
1907 }
1908 mc.data = append(mc.data, p...)
1909 return len(p), nil
1910 }
1911
1912 func (mc *mockConn) SetWriteDeadline(t time.Time) error { return nil }
1913 func (mc *mockConn) Read(b []byte) (int, error) { return 0, nil }
1914 func (mc *mockConn) Close() error { return nil }
1915 func (mc *mockConn) LocalAddr() net.Addr { return nil }
1916 func (mc *mockConn) RemoteAddr() net.Addr { return nil }
1917 func (mc *mockConn) SetDeadline(t time.Time) error { return nil }
1918 func (mc *mockConn) SetReadDeadline(t time.Time) error { return nil }
1919
1920 func TestTimeoutWriterRecovery(t *testing.T) {
1921 mc := &mockConn{temporaryFailures: 2}
1922 tw := &timeoutWriter{
1923 timeout: time.Second,
1924 conn: mc,
1925 }
1926 n, err := tw.Write([]byte("foo"))
1927 if err == nil {
1928 t.Fatal("Unexpected success")
1929 }
1930 if n != 0 {
1931 t.Fatalf("Expected 0 bytes, got %d", n)
1932 }
1933 n, err = tw.Write([]byte("bar"))
1934 if err == nil {
1935 t.Fatal("Unexpected success")
1936 }
1937 if n != 0 {
1938 t.Fatalf("Expected 0 bytes, got: %d", n)
1939 }
1940
1941 // Should succeed since it was a temporary error.
1942 testData := []byte("quux")
1943 n, err = tw.Write(testData)
1944 if err != nil {
1945 t.Fatalf("Expected success, got: %v", err)
1946 }
1947 if n != len(testData) {
1948 t.Fatalf("Expected %d, got: %d", len(testData), n)
1949 }
1950 if !bytes.Equal(mc.data, testData) {
1951 t.Fatalf("Expected %q, got: %q", testData, mc.data)
1952 }
1953 testData2 := []byte("quuz")
1954 n, err = tw.Write(testData2)
1955 if err != nil {
1956 t.Fatalf("Expected success, got: %v", err)
1957 }
1958 if n != len(testData2) {
1959 t.Fatalf("Expected %d bytes written, got %d", len(testData2), n)
1960 }
1961 expectedData := append(testData, testData2...)
1962 if !bytes.Equal(mc.data, expectedData) {
1963 t.Fatalf("Expected data %q, got %q", expectedData, mc.data)
1964 }
1965 }
1966
1967 func TestValidateSubject(t *testing.T) {
1968 tests := []struct {
1969 name string
1970 subject string
1971 wantErr bool
1972 }{
1973 {"valid short", "foo", false},
1974 {"valid with dots", "foo.bar.baz", false},
1975 {"valid long", "metrics.production.server01.cpu.usage.percent", false},
1976 {"empty string", "", true},
1977 {"contains space", "foo bar", true},
1978 {"contains tab", "foo\tbar", true},
1979 {"contains CR", "foo\rbar", true},
1980 {"contains LF", "foo\nbar", true},
1981 {"space at start", " foo", true},
1982 {"space at end", "foo ", true},
1983 {"tab at start", "\tfoo", true},
1984 {"newline at end", "foo\n", true},
1985 {"valid with wildcards", "foo.*.bar.>", false},
1986 {"valid with hyphen", "foo-bar-baz", false},
1987 {"valid with underscore", "foo_bar_baz", false},
1988 }
1989
1990 for _, tt := range tests {
1991 t.Run(tt.name, func(t *testing.T) {
1992 err := validateSubject(tt.subject)
1993 if tt.wantErr {
1994 if !errors.Is(err, ErrBadSubject) {
1995 t.Errorf("validateSubject(%q) error = %v, want ErrBadSubject", tt.subject, err)
1996 }
1997 return
1998 }
1999 if err != nil {
2000 t.Errorf("validateSubject(%q) unexpected error: %v", tt.subject, err)
2001 }
2002 })
2003 }
2004 }
2005
2006 func TestWriteBufferSize(t *testing.T) {
2007 opts := GetDefaultOptions()
2008 opts.WriteBufferSize = 64 * 1024
2009 opts.Servers = []string{"nats://127.0.0.1:4222"}
2010 nc := &Conn{Opts: opts}
2011 nc.newReaderWriter()
2012
2013 if nc.bw.limit != 64*1024 {
2014 t.Fatalf("Expected write buffer limit of %d, got %d", 64*1024, nc.bw.limit)
2015 }
2016 if len(nc.br.buf) != defaultBufSize {
2017 t.Fatalf("Expected read buffer size of %d, got %d", defaultBufSize, len(nc.br.buf))
2018 }
2019 }
2020
2021 func TestWriteBufferSizeDefault(t *testing.T) {
2022 opts := GetDefaultOptions()
2023 opts.WriteBufferSize = DefaultWriteBufSize
2024 opts.Servers = []string{"nats://127.0.0.1:4222"}
2025 nc := &Conn{Opts: opts}
2026 nc.newReaderWriter()
2027
2028 if nc.bw.limit != defaultBufSize {
2029 t.Fatalf("Expected default write buffer limit of %d, got %d", defaultBufSize, nc.bw.limit)
2030 }
2031 }
2032
2033 // errInProcessProvider is a stub InProcessConnProvider that always fails. Used
2034 // to confirm Connect routes through InProcessConn and surfaces its errors.
2035 type errInProcessProvider struct{ err error }
2036
2037 func (e *errInProcessProvider) InProcessConn() (net.Conn, error) { return nil, e.err }
2038
2039 // TestInProcessServerOption verifies that nats.InProcessServer wires the
2040 // provider into Options. The happy path — reaching CONNECTED over an
2041 // in-process conn — needs an in-process server and is not covered.
2042 func TestInProcessServerOption(t *testing.T) {
2043 provider := &errInProcessProvider{err: errors.New("placeholder")}
2044 opts := Options{}
2045 if err := InProcessServer(provider)(&opts); err != nil {
2046 t.Fatalf("InProcessServer option returned error: %v", err)
2047 }
2048 if opts.InProcessServer == nil {
2049 t.Fatal("Expected InProcessServer to be stored on Options")
2050 }
2051 if opts.InProcessServer != InProcessConnProvider(provider) {
2052 t.Fatal("Expected stored provider to equal supplied provider")
2053 }
2054 }
2055
2056 // TestInProcessServerConnectError verifies that errors from the provider's
2057 // InProcessConn() call surface from Connect (wrapped, errors.Is-compatible).
2058 func TestInProcessServerConnectError(t *testing.T) {
2059 providerErr := errors.New("provider broken")
2060 provider := &errInProcessProvider{err: providerErr}
2061
2062 // URL is required for Options parsing but ignored when InProcessServer is set.
2063 _, err := Connect("nats://placeholder:4222", InProcessServer(provider))
2064 if err == nil {
2065 t.Fatal("Expected error from Connect when provider fails")
2066 }
2067 if !errors.Is(err, providerErr) {
2068 t.Fatalf("Expected error to wrap %v, got: %v", providerErr, err)
2069 }
2070 }
2071
2072 // TestParseServerURLPreservesTLSName covers the implicit-IP-URL → preserved-
2073 // hostname behavior in parseServerURL: when a gossiped (implicit) server URL
2074 // is an IP and the connection is secure, the entry's tlsName is set to the
2075 // hostname of the currently-connected URL so the TLS handshake (later, at
2076 // nats.go:2533) uses that hostname for ServerName verification instead of
2077 // the dialed IP. This is the same invariant the integration test
2078 // TestReconnectTLSHostNoIP exercises end-to-end (skipped: needs per-server
2079 // cluster config asymmetry the testservice does not expose); the white-box
2080 // form covers the same 14-line correctness boundary without the scaffolding.
2081 func TestParseServerURLPreservesTLSName(t *testing.T) {
2082 current, err := url.Parse("tls://localhost:5222")
2083 if err != nil {
2084 t.Fatalf("could not parse current URL: %v", err)
2085 }
2086 nc := &Conn{current: &Server{URL: current}}
2087
2088 cases := []struct {
2089 name string
2090 input string
2091 implicit bool
2092 saveTLSName bool
2093 expectedName string
2094 }{
2095 {"gossiped IP secure", "tls://127.0.0.1:5224", true, true, "localhost"},
2096 {"gossiped hostname secure", "tls://other.example.com:5224", true, true, ""},
2097 {"gossiped IP insecure", "tls://127.0.0.1:5224", true, false, ""},
2098 {"explicit IP", "tls://127.0.0.1:5224", false, true, ""},
2099 }
2100 for _, tc := range cases {
2101 t.Run(tc.name, func(t *testing.T) {
2102 s, err := nc.parseServerURL(tc.input, tc.implicit, tc.saveTLSName)
2103 if err != nil {
2104 t.Fatalf("parseServerURL: %v", err)
2105 }
2106 if s.tlsName != tc.expectedName {
2107 t.Fatalf("tlsName = %q, want %q", s.tlsName, tc.expectedName)
2108 }
2109 if s.isImplicit != tc.implicit {
2110 t.Fatalf("isImplicit = %v, want %v", s.isImplicit, tc.implicit)
2111 }
2112 })
2113 }
2114 }
2115
2116 // hostOnlyTLSCert mints a self-signed cert carrying a single "localhost" DNS
2117 // SAN and deliberately no IP SANs, so verifying it against an IP-form
2118 // ServerName fails. Returns the server cert and a pool trusting it.
2119 func hostOnlyTLSCert(t *testing.T) (tls.Certificate, *x509.CertPool) {
2120 t.Helper()
2121 key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
2122 if err != nil {
2123 t.Fatalf("GenerateKey: %v", err)
2124 }
2125 tmpl := &x509.Certificate{
2126 SerialNumber: big.NewInt(1),
2127 Subject: pkix.Name{CommonName: "localhost"},
2128 NotBefore: time.Now().Add(-time.Hour),
2129 NotAfter: time.Now().Add(time.Hour),
2130 KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
2131 ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
2132 BasicConstraintsValid: true,
2133 IsCA: true,
2134 DNSNames: []string{"localhost"},
2135 }
2136 der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
2137 if err != nil {
2138 t.Fatalf("CreateCertificate: %v", err)
2139 }
2140 leaf, err := x509.ParseCertificate(der)
2141 if err != nil {
2142 t.Fatalf("ParseCertificate: %v", err)
2143 }
2144 pool := x509.NewCertPool()
2145 pool.AddCert(leaf)
2146 return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: leaf}, pool
2147 }
2148
2149 // TestMakeTLSConnUsesPreservedTLSName covers the consumer side of the tlsName
2150 // invariant: parseServerURL records the originally-dialed hostname on a pool
2151 // entry (see TestParseServerURLPreservesTLSName), and makeTLSConn must use it
2152 // as the TLS ServerName rather than the IP it is dialing.
2153 //
2154 // This is what lets a client reconnect over TLS to a server the cluster
2155 // gossiped as a bare IP, against a cert that only has hostname SANs.
2156 func TestMakeTLSConnUsesPreservedTLSName(t *testing.T) {
2157 for _, tc := range []struct {
2158 name string
2159 tlsName string
2160 expectErr bool
2161 }{
2162 // Dialed by IP, but tlsName carries the hostname the pool entry was
2163 // discovered from: handshake must verify against "localhost".
2164 {"preserved name is used", "localhost", false},
2165 // Without it, ServerName falls back to the dialed IP, which the cert
2166 // does not cover. Guards against the assignment being dropped.
2167 {"no preserved name fails against IP", "", true},
2168 } {
2169 t.Run(tc.name, func(t *testing.T) {
2170 srvCert, pool := hostOnlyTLSCert(t)
2171
2172 ln, err := net.Listen("tcp", "127.0.0.1:0")
2173 if err != nil {
2174 t.Fatalf("Listen: %v", err)
2175 }
2176 defer ln.Close()
2177
2178 sniCh := make(chan string, 1)
2179 go func() {
2180 conn, err := ln.Accept()
2181 if err != nil {
2182 return
2183 }
2184 defer conn.Close()
2185 srv := tls.Server(conn, &tls.Config{
2186 Certificates: []tls.Certificate{srvCert},
2187 GetConfigForClient: func(chi *tls.ClientHelloInfo) (*tls.Config, error) {
2188 sniCh <- chi.ServerName
2189 return nil, nil
2190 },
2191 })
2192 srv.Handshake()
2193 }()
2194
2195 raw, err := net.Dial("tcp", ln.Addr().String())
2196 if err != nil {
2197 t.Fatalf("Dial: %v", err)
2198 }
2199 defer raw.Close()
2200
2201 u, err := url.Parse("tls://" + ln.Addr().String())
2202 if err != nil {
2203 t.Fatalf("Parse: %v", err)
2204 }
2205 nc := &Conn{
2206 Opts: Options{TLSConfig: &tls.Config{RootCAs: pool}},
2207 conn: raw,
2208 current: &Server{URL: u, tlsName: tc.tlsName},
2209 }
2210 nc.newReaderWriter()
2211
2212 err = nc.makeTLSConn()
2213 if tc.expectErr {
2214 if err == nil {
2215 t.Fatal("Expected TLS handshake to fail without a preserved tlsName")
2216 }
2217 return
2218 }
2219 if err != nil {
2220 t.Fatalf("makeTLSConn: %v", err)
2221 }
2222
2223 select {
2224 case sni := <-sniCh:
2225 if sni != "localhost" {
2226 t.Fatalf("SNI = %q, want %q", sni, "localhost")
2227 }
2228 case <-time.After(2 * time.Second):
2229 t.Fatal("Did not receive ClientHello")
2230 }
2231 })
2232 }
2233 }