Debian Codegraph @

server/reload_test.go

raw
1 // Copyright 2017-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "bytes"
18 "crypto/tls"
19 "encoding/base64"
20 "encoding/json"
21 "errors"
22 "flag"
23 "fmt"
24 "io"
25 "log"
26 "maps"
27 "net"
28 "net/http"
29 "net/http/httptest"
30 "net/url"
31 "os"
32 "path/filepath"
33 "reflect"
34 "runtime"
35 "strings"
36 "sync"
37 "testing"
38 "time"
39
40 "github.com/nats-io/jwt/v2"
41 "github.com/nats-io/nats.go"
42 "github.com/nats-io/nkeys"
43 )
44
45 func newServerWithConfig(t *testing.T, configFile string) (*Server, *Options, string) {
46 t.Helper()
47 content, err := os.ReadFile(configFile)
48 if err != nil {
49 t.Fatalf("Error loading file: %v", err)
50 }
51 return newServerWithContent(t, content)
52 }
53
54 func newServerWithContent(t *testing.T, content []byte) (*Server, *Options, string) {
55 t.Helper()
56 opts, tmpFile := newOptionsFromContent(t, content)
57 return New(opts), opts, tmpFile
58 }
59
60 func newOptionsFromContent(t *testing.T, content []byte) (*Options, string) {
61 t.Helper()
62 tmpFile := createConfFile(t, content)
63 opts, err := ProcessConfigFile(tmpFile)
64 if err != nil {
65 t.Fatalf("Error processing config file: %v", err)
66 }
67 opts.NoSigs = true
68 return opts, tmpFile
69 }
70
71 func createConfFile(t testing.TB, content []byte) string {
72 t.Helper()
73 conf := createTempFile(t, _EMPTY_)
74 fName := conf.Name()
75 conf.Close()
76 if err := os.WriteFile(fName, content, 0666); err != nil {
77 t.Fatalf("Error writing conf file: %v", err)
78 }
79 return fName
80 }
81
82 func runReloadServerWithConfig(t *testing.T, configFile string) (*Server, *Options, string) {
83 t.Helper()
84 content, err := os.ReadFile(configFile)
85 if err != nil {
86 t.Fatalf("Error loading file: %v", err)
87 }
88 return runReloadServerWithContent(t, content)
89 }
90
91 func runReloadServerWithContent(t *testing.T, content []byte) (*Server, *Options, string) {
92 t.Helper()
93 opts, tmpFile := newOptionsFromContent(t, content)
94 opts.NoLog = true
95 opts.NoSigs = true
96 s := RunServer(opts)
97 return s, opts, tmpFile
98 }
99
100 func changeCurrentConfigContent(t *testing.T, curConfig, newConfig string) {
101 t.Helper()
102 content, err := os.ReadFile(newConfig)
103 if err != nil {
104 t.Fatalf("Error loading file: %v", err)
105 }
106 changeCurrentConfigContentWithNewContent(t, curConfig, content)
107 }
108
109 func changeCurrentConfigContentWithNewContent(t *testing.T, curConfig string, content []byte) {
110 t.Helper()
111 if err := os.WriteFile(curConfig, content, 0666); err != nil {
112 t.Fatalf("Error writing config: %v", err)
113 }
114 }
115
116 // Ensure Reload returns an error when attempting to reload a server that did
117 // not start with a config file.
118 func TestConfigReloadNoConfigFile(t *testing.T) {
119 server := New(&Options{NoSigs: true})
120 loaded := server.ConfigTime()
121 if server.Reload() == nil {
122 t.Fatal("Expected Reload to return an error")
123 }
124 if reloaded := server.ConfigTime(); reloaded != loaded {
125 t.Fatalf("ConfigTime is incorrect.\nexpected: %s\ngot: %s", loaded, reloaded)
126 }
127 }
128
129 // Ensure Reload returns an error when attempting to change an option which
130 // does not support reloading.
131 func TestConfigReloadUnsupported(t *testing.T) {
132 server, _, config := newServerWithConfig(t, "./configs/reload/test.conf")
133 defer server.Shutdown()
134
135 loaded := server.ConfigTime()
136
137 golden := &Options{
138 ConfigFile: config,
139 Host: "0.0.0.0",
140 Port: 2233,
141 AuthTimeout: float64(AUTH_TIMEOUT / time.Second),
142 Debug: false,
143 Trace: false,
144 Logtime: false,
145 MaxControlLine: 4096,
146 MaxPayload: 1048576,
147 MaxConn: 65536,
148 PingInterval: 2 * time.Minute,
149 MaxPingsOut: 2,
150 WriteDeadline: 10 * time.Second,
151 Cluster: ClusterOpts{
152 Name: "abc",
153 Host: "127.0.0.1",
154 Port: -1,
155 },
156 NoSigs: true,
157 configDigest: "sha256:3c5c4141f56274bcfa801f2d7326ec64d5eabddd9e6d4f9a06ed167315a57f55",
158 }
159 setBaselineOptions(golden)
160
161 checkOptionsEqual(t, golden, server.getOpts())
162
163 // Change config file to bad config.
164 changeCurrentConfigContent(t, config, "./configs/reload/reload_unsupported.conf")
165
166 // This should fail because `cluster` host cannot be changed.
167 if err := server.Reload(); err == nil {
168 t.Fatal("Expected Reload to return an error")
169 }
170
171 // Ensure config didn't change.
172 checkOptionsEqual(t, golden, server.getOpts())
173
174 if reloaded := server.ConfigTime(); reloaded != loaded {
175 t.Fatalf("ConfigTime is incorrect.\nexpected: %s\ngot: %s", loaded, reloaded)
176 }
177 }
178
179 // This checks that if we change an option that does not support hot-swapping
180 // we get an error. Using `listen` for now (test may need to be updated if
181 // server is changed to support change of listen spec).
182 func TestConfigReloadUnsupportedHotSwapping(t *testing.T) {
183 server, _, config := newServerWithContent(t, []byte("listen: 127.0.0.1:-1"))
184 defer server.Shutdown()
185
186 loaded := server.ConfigTime()
187
188 time.Sleep(time.Millisecond)
189
190 // Change config file with unsupported option hot-swap
191 changeCurrentConfigContentWithNewContent(t, config, []byte("listen: 127.0.0.1:9999"))
192
193 // This should fail because `listen` host cannot be changed.
194 if err := server.Reload(); err == nil || !strings.Contains(err.Error(), "not supported") {
195 t.Fatalf("Expected Reload to return a not supported error, got %v", err)
196 }
197
198 if reloaded := server.ConfigTime(); reloaded != loaded {
199 t.Fatalf("ConfigTime is incorrect.\nexpected: %s\ngot: %s", loaded, reloaded)
200 }
201 }
202
203 // Ensure Reload returns an error when reloading from a bad config file.
204 func TestConfigReloadInvalidConfig(t *testing.T) {
205 server, _, config := newServerWithConfig(t, "./configs/reload/test.conf")
206 defer server.Shutdown()
207
208 loaded := server.ConfigTime()
209
210 golden := &Options{
211 ConfigFile: config,
212 Host: "0.0.0.0",
213 Port: 2233,
214 AuthTimeout: float64(AUTH_TIMEOUT / time.Second),
215 Debug: false,
216 Trace: false,
217 Logtime: false,
218 MaxControlLine: 4096,
219 MaxPayload: 1048576,
220 MaxConn: 65536,
221 PingInterval: 2 * time.Minute,
222 MaxPingsOut: 2,
223 WriteDeadline: 10 * time.Second,
224 Cluster: ClusterOpts{
225 Name: "abc",
226 Host: "127.0.0.1",
227 Port: -1,
228 },
229 NoSigs: true,
230 configDigest: "sha256:3c5c4141f56274bcfa801f2d7326ec64d5eabddd9e6d4f9a06ed167315a57f55",
231 }
232 setBaselineOptions(golden)
233
234 checkOptionsEqual(t, golden, server.getOpts())
235
236 // Change config file to bad config.
237 changeCurrentConfigContent(t, config, "./configs/reload/invalid.conf")
238
239 // This should fail because the new config should not parse.
240 if err := server.Reload(); err == nil {
241 t.Fatal("Expected Reload to return an error")
242 }
243
244 // Ensure config didn't change.
245 checkOptionsEqual(t, golden, server.getOpts())
246
247 if reloaded := server.ConfigTime(); reloaded != loaded {
248 t.Fatalf("ConfigTime is incorrect.\nexpected: %s\ngot: %s", loaded, reloaded)
249 }
250 }
251
252 // Ensure Reload returns nil and the config is changed on success.
253 func TestConfigReload(t *testing.T) {
254 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/test.conf")
255 defer removeFile(t, "nats-server.pid")
256 defer removeFile(t, "nats-server.log")
257 defer server.Shutdown()
258
259 var content []byte
260 if runtime.GOOS != "windows" {
261 content = []byte(`
262 remote_syslog: "udp://127.0.0.1:514" # change on reload
263 syslog: true # enable on reload
264 `)
265 }
266 platformConf := filepath.Join(filepath.Dir(config), "platform.conf")
267 if err := os.WriteFile(platformConf, content, 0666); err != nil {
268 t.Fatalf("Unable to write config file: %v", err)
269 }
270
271 loaded := server.ConfigTime()
272
273 golden := &Options{
274 ConfigFile: config,
275 Host: "0.0.0.0",
276 Port: 2233,
277 AuthTimeout: float64(AUTH_TIMEOUT / time.Second),
278 Debug: false,
279 Trace: false,
280 NoLog: true,
281 Logtime: false,
282 MaxControlLine: 4096,
283 MaxPayload: 1048576,
284 MaxConn: 65536,
285 PingInterval: 2 * time.Minute,
286 MaxPingsOut: 2,
287 WriteDeadline: 10 * time.Second,
288 Cluster: ClusterOpts{
289 Name: "abc",
290 Host: "127.0.0.1",
291 Port: server.ClusterAddr().Port,
292 },
293 NoSigs: true,
294 configDigest: "sha256:3c5c4141f56274bcfa801f2d7326ec64d5eabddd9e6d4f9a06ed167315a57f55",
295 }
296 setBaselineOptions(golden)
297
298 checkOptionsEqual(t, golden, opts)
299
300 // Change config file to new config.
301 changeCurrentConfigContent(t, config, "./configs/reload/reload.conf")
302
303 if err := server.Reload(); err != nil {
304 t.Fatalf("Error reloading config: %v", err)
305 }
306
307 // Ensure config changed.
308 updated := server.getOpts()
309 if !updated.Trace {
310 t.Fatal("Expected Trace to be true")
311 }
312 if !updated.Debug {
313 t.Fatal("Expected Debug to be true")
314 }
315 if !updated.Logtime {
316 t.Fatal("Expected Logtime to be true")
317 }
318 if !updated.LogtimeUTC {
319 t.Fatal("Expected LogtimeUTC to be true")
320 }
321 if runtime.GOOS != "windows" {
322 if !updated.Syslog {
323 t.Fatal("Expected Syslog to be true")
324 }
325 if updated.RemoteSyslog != "udp://127.0.0.1:514" {
326 t.Fatalf("RemoteSyslog is incorrect.\nexpected: udp://127.0.0.1:514\ngot: %s", updated.RemoteSyslog)
327 }
328 }
329 if updated.LogFile != "nats-server.log" {
330 t.Fatalf("LogFile is incorrect.\nexpected: nats-server.log\ngot: %s", updated.LogFile)
331 }
332 if updated.TLSConfig == nil {
333 t.Fatal("Expected TLSConfig to be non-nil")
334 }
335 if !server.info.TLSRequired {
336 t.Fatal("Expected TLSRequired to be true")
337 }
338 if !server.info.TLSVerify {
339 t.Fatal("Expected TLSVerify to be true")
340 }
341 if updated.Username != "tyler" {
342 t.Fatalf("Username is incorrect.\nexpected: tyler\ngot: %s", updated.Username)
343 }
344 if updated.Password != "T0pS3cr3t" {
345 t.Fatalf("Password is incorrect.\nexpected: T0pS3cr3t\ngot: %s", updated.Password)
346 }
347 if updated.AuthTimeout != 2 {
348 t.Fatalf("AuthTimeout is incorrect.\nexpected: 2\ngot: %f", updated.AuthTimeout)
349 }
350 if !server.info.AuthRequired {
351 t.Fatal("Expected AuthRequired to be true")
352 }
353 if !updated.Cluster.NoAdvertise {
354 t.Fatal("Expected NoAdvertise to be true")
355 }
356 if updated.Cluster.PingInterval != 20*time.Second {
357 t.Fatalf("Cluster PingInterval is incorrect.\nexpected: 20s\ngot: %v", updated.Cluster.PingInterval)
358 }
359 if updated.Cluster.MaxPingsOut != 8 {
360 t.Fatalf("Cluster MaxPingsOut is incorrect.\nexpected: 6\ngot: %v", updated.Cluster.MaxPingsOut)
361 }
362 if updated.PidFile != "nats-server.pid" {
363 t.Fatalf("PidFile is incorrect.\nexpected: nats-server.pid\ngot: %s", updated.PidFile)
364 }
365 if updated.MaxControlLine != 512 {
366 t.Fatalf("MaxControlLine is incorrect.\nexpected: 512\ngot: %d", updated.MaxControlLine)
367 }
368 if updated.PingInterval != 5*time.Second {
369 t.Fatalf("PingInterval is incorrect.\nexpected 5s\ngot: %s", updated.PingInterval)
370 }
371 if updated.MaxPingsOut != 1 {
372 t.Fatalf("MaxPingsOut is incorrect.\nexpected 1\ngot: %d", updated.MaxPingsOut)
373 }
374 if updated.WriteDeadline != 3*time.Second {
375 t.Fatalf("WriteDeadline is incorrect.\nexpected 3s\ngot: %s", updated.WriteDeadline)
376 }
377 if updated.MaxPayload != 1024 {
378 t.Fatalf("MaxPayload is incorrect.\nexpected 1024\ngot: %d", updated.MaxPayload)
379 }
380 expectedMetadata := map[string]string{"key1": "value1", "key2": "value2"}
381 if !reflect.DeepEqual(expectedMetadata, updated.Metadata) {
382 t.Fatalf("Metadata is incorrect.\nexpected: %v\ngot: %v", expectedMetadata, updated.Metadata)
383 }
384
385 if reloaded := server.ConfigTime(); !reloaded.After(loaded) {
386 t.Fatalf("ConfigTime is incorrect.\nexpected greater than: %s\ngot: %s", loaded, reloaded)
387 }
388 }
389
390 // Ensure Reload supports TLS config changes. Test this by starting a server
391 // with TLS enabled, connect to it to verify, reload config using a different
392 // key pair and client verification enabled, ensure reconnect fails, then
393 // ensure reconnect succeeds when the client provides a cert.
394 func TestConfigReloadRotateTLS(t *testing.T) {
395 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/tls_test.conf")
396 defer server.Shutdown()
397
398 // Ensure we can connect as a sanity check.
399 addr := fmt.Sprintf("nats://%s:%d", opts.Host, server.Addr().(*net.TCPAddr).Port)
400
401 nc, err := nats.Connect(addr, nats.Secure(&tls.Config{InsecureSkipVerify: true}))
402 if err != nil {
403 t.Fatalf("Error creating client: %v", err)
404 }
405 defer nc.Close()
406 sub, err := nc.SubscribeSync("foo")
407 if err != nil {
408 t.Fatalf("Error subscribing: %v", err)
409 }
410 defer sub.Unsubscribe()
411
412 // Rotate cert and enable client verification.
413 changeCurrentConfigContent(t, config, "./configs/reload/tls_verify_test.conf")
414 if err := server.Reload(); err != nil {
415 t.Fatalf("Error reloading config: %v", err)
416 }
417
418 // Ensure connecting fails.
419 if _, err := nats.Connect(addr, nats.Secure(&tls.Config{InsecureSkipVerify: true})); err == nil {
420 t.Fatal("Expected connect to fail")
421 }
422
423 // Ensure connecting succeeds when client presents cert.
424 cert := nats.ClientCert("./configs/certs/cert.new.pem", "./configs/certs/key.new.pem")
425 conn, err := nats.Connect(addr, cert, nats.RootCAs("./configs/certs/cert.new.pem"))
426 if err != nil {
427 t.Fatalf("Error creating client: %v", err)
428 }
429 conn.Close()
430
431 // Ensure the original connection can still publish/receive.
432 if err := nc.Publish("foo", []byte("hello")); err != nil {
433 t.Fatalf("Error publishing: %v", err)
434 }
435 nc.Flush()
436 msg, err := sub.NextMsg(2 * time.Second)
437 if err != nil {
438 t.Fatalf("Error receiving msg: %v", err)
439 }
440 if string(msg.Data) != "hello" {
441 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("hello"), msg.Data)
442 }
443 }
444
445 // Ensure Reload supports enabling TLS. Test this by starting a server without
446 // TLS enabled, connect to it to verify, reload config with TLS enabled, ensure
447 // reconnect fails, then ensure reconnect succeeds when using secure.
448 func TestConfigReloadEnableTLS(t *testing.T) {
449 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/basic.conf")
450 defer server.Shutdown()
451
452 // Ensure we can connect as a sanity check.
453 addr := fmt.Sprintf("nats://%s:%d", opts.Host, server.Addr().(*net.TCPAddr).Port)
454 nc, err := nats.Connect(addr)
455 if err != nil {
456 t.Fatalf("Error creating client: %v", err)
457 }
458 nc.Close()
459
460 // Enable TLS.
461 changeCurrentConfigContent(t, config, "./configs/reload/tls_test.conf")
462 if err := server.Reload(); err != nil {
463 t.Fatalf("Error reloading config: %v", err)
464 }
465
466 // Ensure connecting is OK (we need to skip server cert verification since
467 // the library is not doing that by default now).
468 nc, err = nats.Connect(addr, nats.Secure(&tls.Config{InsecureSkipVerify: true}))
469 if err != nil {
470 t.Fatalf("Error creating client: %v", err)
471 }
472 nc.Close()
473 }
474
475 // Ensure Reload supports disabling TLS. Test this by starting a server with
476 // TLS enabled, connect to it to verify, reload config with TLS disabled,
477 // ensure reconnect fails, then ensure reconnect succeeds when connecting
478 // without secure.
479 func TestConfigReloadDisableTLS(t *testing.T) {
480 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/tls_test.conf")
481 defer server.Shutdown()
482
483 // Ensure we can connect as a sanity check.
484 addr := fmt.Sprintf("nats://%s:%d", opts.Host, server.Addr().(*net.TCPAddr).Port)
485 nc, err := nats.Connect(addr, nats.Secure(&tls.Config{InsecureSkipVerify: true}))
486 if err != nil {
487 t.Fatalf("Error creating client: %v", err)
488 }
489 nc.Close()
490
491 // Disable TLS.
492 changeCurrentConfigContent(t, config, "./configs/reload/basic.conf")
493 if err := server.Reload(); err != nil {
494 t.Fatalf("Error reloading config: %v", err)
495 }
496
497 // Ensure connecting fails.
498 if _, err := nats.Connect(addr, nats.Secure(&tls.Config{InsecureSkipVerify: true})); err == nil {
499 t.Fatal("Expected connect to fail")
500 }
501
502 // Ensure connecting succeeds when not using secure.
503 nc, err = nats.Connect(addr)
504 if err != nil {
505 t.Fatalf("Error creating client: %v", err)
506 }
507 nc.Close()
508 }
509
510 func TestConfigReloadRotateTLSMultiCert(t *testing.T) {
511 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/tls_multi_cert_1.conf")
512 defer server.Shutdown()
513
514 // Ensure we can connect as a sanity check.
515 addr := fmt.Sprintf("nats://%s:%d", opts.Host, server.Addr().(*net.TCPAddr).Port)
516
517 rawCerts := make(chan []byte, 3)
518 nc, err := nats.Connect(addr, nats.Secure(&tls.Config{
519 VerifyConnection: func(s tls.ConnectionState) error {
520 rawCerts <- s.PeerCertificates[0].Raw
521 return nil
522 },
523 InsecureSkipVerify: true,
524 }))
525 if err != nil {
526 t.Fatalf("Error creating client: %v", err)
527 }
528 defer nc.Close()
529 sub, err := nc.SubscribeSync("foo")
530 if err != nil {
531 t.Fatalf("Error subscribing: %v", err)
532 }
533 defer sub.Unsubscribe()
534
535 // Rotate cert and enable client verification.
536 changeCurrentConfigContent(t, config, "./configs/reload/tls_multi_cert_2.conf")
537 if err := server.Reload(); err != nil {
538 t.Fatalf("Error reloading config: %v", err)
539 }
540
541 // Ensure connecting fails.
542 if _, err := nats.Connect(addr, nats.Secure(&tls.Config{InsecureSkipVerify: true})); err == nil {
543 t.Fatal("Expected connect to fail")
544 }
545
546 // Ensure connecting succeeds when client presents cert.
547 cert := nats.ClientCert("../test/configs/certs/client-cert.pem", "../test/configs/certs/client-key.pem")
548 conn, err := nats.Connect(addr, cert, nats.RootCAs("../test/configs/certs/ca.pem"), nats.Secure(&tls.Config{
549 VerifyConnection: func(s tls.ConnectionState) error {
550 rawCerts <- s.PeerCertificates[0].Raw
551 return nil
552 },
553 }))
554 if err != nil {
555 t.Fatalf("Error creating client: %v", err)
556 }
557 conn.Close()
558
559 // Ensure the original connection can still publish/receive.
560 if err := nc.Publish("foo", []byte("hello")); err != nil {
561 t.Fatalf("Error publishing: %v", err)
562 }
563 nc.Flush()
564 msg, err := sub.NextMsg(2 * time.Second)
565 if err != nil {
566 t.Fatalf("Error receiving msg: %v", err)
567 }
568 if string(msg.Data) != "hello" {
569 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("hello"), msg.Data)
570 }
571
572 // Rotate cert and disable client verification.
573 changeCurrentConfigContent(t, config, "./configs/reload/tls_multi_cert_3.conf")
574 if err := server.Reload(); err != nil {
575 t.Fatalf("Error reloading config: %v", err)
576 }
577
578 nc, err = nats.Connect(addr, nats.Secure(&tls.Config{
579 VerifyConnection: func(s tls.ConnectionState) error {
580 rawCerts <- s.PeerCertificates[0].Raw
581 return nil
582 },
583 InsecureSkipVerify: true,
584 }))
585 if err != nil {
586 t.Fatalf("Error creating client: %v", err)
587 }
588 defer nc.Close()
589 sub, err = nc.SubscribeSync("foo")
590 if err != nil {
591 t.Fatalf("Error subscribing: %v", err)
592 }
593 defer sub.Unsubscribe()
594
595 certA := <-rawCerts
596 certB := <-rawCerts
597 certC := <-rawCerts
598 if !bytes.Equal(certA, certB) {
599 t.Error("Expected the same cert")
600 }
601 if bytes.Equal(certB, certC) {
602 t.Error("Expected a different cert")
603 }
604 }
605
606 func TestConfigReloadTrustedOperatorAndTrustedKeysUnsupported(t *testing.T) {
607 kp, _ := nkeys.CreateAccount()
608 aPub, _ := kp.PublicKey()
609 claim := jwt.NewAccountClaims(aPub)
610 aJwt, err := claim.Encode(oKp)
611 require_NoError(t, err)
612 tmpl := `
613 listen: 127.0.0.1:-1
614 %s
615 resolver: MEM
616 resolver_preload: {
617 %s: %s
618 }
619 `
620 conf := createConfFile(t, fmt.Appendf(nil, tmpl, fmt.Sprintf("operator: %s", ojwt), aPub, aJwt))
621 s, o := RunServerWithConfig(conf)
622 defer s.Shutdown()
623
624 // The server fills the TrustedKeys with the operators' signing keys.
625 require_True(t, len(o.TrustedKeys) > 0)
626
627 keysConf := strings.Builder{}
628 keysConf.WriteByte('[')
629 for i, k := range o.TrustedKeys {
630 if i > 0 {
631 keysConf.WriteString(", ")
632 }
633 keysConf.WriteByte('"')
634 keysConf.WriteString(k)
635 keysConf.WriteByte('"')
636 }
637 keysConf.WriteByte(']')
638
639 err = os.WriteFile(conf, fmt.Appendf(nil, tmpl, _EMPTY_, aPub, aJwt), 0666)
640 require_NoError(t, err)
641 err = s.Reload()
642 require_Error(t, err)
643 require_Contains(t, err.Error(), "not supported for TrustedOperator")
644
645 // We used to wipe the TrustedKeys, we no longer do that.
646 require_True(t, len(o.TrustedKeys) > 0)
647
648 s.Shutdown()
649 conf = createConfFile(t,
650 fmt.Appendf(nil, tmpl, fmt.Sprintf("trusted_keys: %s", keysConf.String()), aPub, aJwt))
651 s, o = RunServerWithConfig(conf)
652 defer s.Shutdown()
653
654 err = os.WriteFile(conf, fmt.Appendf(nil, tmpl, _EMPTY_, aPub, aJwt), 0666)
655 require_NoError(t, err)
656 err = s.Reload()
657 require_Error(t, err)
658 require_Contains(t, err.Error(), "not supported for TrustedKeys")
659
660 require_True(t, len(o.TrustedKeys) > 0)
661 }
662
663 func TestConfigReloadDefaultSentinel(t *testing.T) {
664 var err error
665 preload := make(map[string]string)
666
667 _, sysPub, sysAC := NewJwtAccountClaim("SYS")
668 preload[sysPub], err = sysAC.Encode(oKp)
669 require_NoError(t, err)
670
671 aKP, aPub, aAC := NewJwtAccountClaim("A")
672 preload[aPub], err = aAC.Encode(oKp)
673 require_NoError(t, err)
674
675 preloadConfig, err := json.MarshalIndent(preload, "", " ")
676 require_NoError(t, err)
677
678 uKP, err := nkeys.CreateUser()
679 require_NoError(t, err)
680 uPub, err := uKP.PublicKey()
681 require_NoError(t, err)
682 uc := jwt.NewUserClaims(uPub)
683 uc.BearerToken = true
684 uc.Name = "sentinel"
685 sentinelToken, err := uc.Encode(aKP)
686 require_NoError(t, err)
687 content := func() []byte {
688 return []byte(fmt.Sprintf(`
689 listen: 127.0.0.1:4747
690 operator: %s
691 system_account: %s
692 resolver: MEM
693 resolver_preload: %s
694 default_sentinel: %s
695 `, ojwt, sysPub, preloadConfig, sentinelToken))
696 }
697
698 server, opts, config := runReloadServerWithContent(t, content())
699 defer server.Shutdown()
700 require_Equal(t, opts.DefaultSentinel, sentinelToken)
701
702 uc.Name = "sentinel-updated"
703 sentinelToken, err = uc.Encode(aKP)
704 require_NoError(t, err)
705 changeCurrentConfigContentWithNewContent(t, config, content())
706 if err := server.Reload(); err != nil {
707 t.Fatalf("Error reloading config: %v", err)
708 }
709 opts = server.getOpts()
710 require_Equal(t, opts.DefaultSentinel, sentinelToken)
711 }
712
713 // Ensure Reload supports single user authentication config changes. Test this
714 // by starting a server with authentication enabled, connect to it to verify,
715 // reload config using a different username/password, ensure reconnect fails,
716 // then ensure reconnect succeeds when using the correct credentials.
717 func TestConfigReloadRotateUserAuthentication(t *testing.T) {
718 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/single_user_authentication_1.conf")
719 defer server.Shutdown()
720
721 // Ensure we can connect as a sanity check.
722 addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
723 nc, err := nats.Connect(addr, nats.UserInfo("tyler", "T0pS3cr3t"))
724 if err != nil {
725 t.Fatalf("Error creating client: %v", err)
726 }
727 defer nc.Close()
728 disconnected := make(chan struct{}, 1)
729 asyncErr := make(chan error, 1)
730 nc.SetErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
731 asyncErr <- err
732 })
733 nc.SetDisconnectHandler(func(*nats.Conn) {
734 disconnected <- struct{}{}
735 })
736
737 // Change user credentials.
738 changeCurrentConfigContent(t, config, "./configs/reload/single_user_authentication_2.conf")
739 if err := server.Reload(); err != nil {
740 t.Fatalf("Error reloading config: %v", err)
741 }
742
743 // Ensure connecting fails.
744 if _, err := nats.Connect(addr, nats.UserInfo("tyler", "T0pS3cr3t")); err == nil {
745 t.Fatal("Expected connect to fail")
746 }
747
748 // Ensure connecting succeeds when using new credentials.
749 conn, err := nats.Connect(addr, nats.UserInfo("derek", "passw0rd"))
750 if err != nil {
751 t.Fatalf("Error creating client: %v", err)
752 }
753 conn.Close()
754
755 // Ensure the previous connection received an authorization error.
756 // Note that it is possible that client gets EOF and not able to
757 // process async error, so don't fail if we don't get it.
758 select {
759 case err := <-asyncErr:
760 if err != nats.ErrAuthorization {
761 t.Fatalf("Expected ErrAuthorization, got %v", err)
762 }
763 case <-time.After(time.Second):
764 // Give it up to 1 sec.
765 }
766
767 // Ensure the previous connection was disconnected.
768 select {
769 case <-disconnected:
770 case <-time.After(2 * time.Second):
771 t.Fatal("Expected connection to be disconnected")
772 }
773 }
774
775 // Ensure Reload supports enabling single user authentication. Test this by
776 // starting a server with authentication disabled, connect to it to verify,
777 // reload config using with a username/password, ensure reconnect fails, then
778 // ensure reconnect succeeds when using the correct credentials.
779 func TestConfigReloadEnableUserAuthentication(t *testing.T) {
780 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/basic.conf")
781 defer server.Shutdown()
782
783 // Ensure we can connect as a sanity check.
784 addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
785 nc, err := nats.Connect(addr)
786 if err != nil {
787 t.Fatalf("Error creating client: %v", err)
788 }
789 defer nc.Close()
790 disconnected := make(chan struct{}, 1)
791 asyncErr := make(chan error, 1)
792 nc.SetErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
793 asyncErr <- err
794 })
795 nc.SetDisconnectHandler(func(*nats.Conn) {
796 disconnected <- struct{}{}
797 })
798
799 // Enable authentication.
800 changeCurrentConfigContent(t, config, "./configs/reload/single_user_authentication_1.conf")
801 if err := server.Reload(); err != nil {
802 t.Fatalf("Error reloading config: %v", err)
803 }
804
805 // Ensure connecting fails.
806 if _, err := nats.Connect(addr); err == nil {
807 t.Fatal("Expected connect to fail")
808 }
809
810 // Ensure connecting succeeds when using new credentials.
811 conn, err := nats.Connect(addr, nats.UserInfo("tyler", "T0pS3cr3t"))
812 if err != nil {
813 t.Fatalf("Error creating client: %v", err)
814 }
815 conn.Close()
816
817 // Ensure the previous connection received an authorization error.
818 // Note that it is possible that client gets EOF and not able to
819 // process async error, so don't fail if we don't get it.
820 select {
821 case err := <-asyncErr:
822 if err != nats.ErrAuthorization {
823 t.Fatalf("Expected ErrAuthorization, got %v", err)
824 }
825 case <-time.After(time.Second):
826 }
827
828 // Ensure the previous connection was disconnected.
829 select {
830 case <-disconnected:
831 case <-time.After(2 * time.Second):
832 t.Fatal("Expected connection to be disconnected")
833 }
834 }
835
836 // Ensure Reload supports disabling single user authentication. Test this by
837 // starting a server with authentication enabled, connect to it to verify,
838 // reload config using with authentication disabled, then ensure connecting
839 // with no credentials succeeds.
840 func TestConfigReloadDisableUserAuthentication(t *testing.T) {
841 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/single_user_authentication_1.conf")
842 defer server.Shutdown()
843
844 // Ensure we can connect as a sanity check.
845 addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
846 nc, err := nats.Connect(addr, nats.UserInfo("tyler", "T0pS3cr3t"))
847 if err != nil {
848 t.Fatalf("Error creating client: %v", err)
849 }
850 defer nc.Close()
851 nc.SetErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
852 t.Fatalf("Client received an unexpected error: %v", err)
853 })
854
855 // Disable authentication.
856 changeCurrentConfigContent(t, config, "./configs/reload/basic.conf")
857 if err := server.Reload(); err != nil {
858 t.Fatalf("Error reloading config: %v", err)
859 }
860
861 // Ensure connecting succeeds with no credentials.
862 conn, err := nats.Connect(addr)
863 if err != nil {
864 t.Fatalf("Error creating client: %v", err)
865 }
866 conn.Close()
867 }
868
869 // Ensure Reload supports token authentication config changes. Test this by
870 // starting a server with token authentication enabled, connect to it to
871 // verify, reload config using a different token, ensure reconnect fails, then
872 // ensure reconnect succeeds when using the correct token.
873 func TestConfigReloadRotateTokenAuthentication(t *testing.T) {
874 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/token_authentication_1.conf")
875 defer server.Shutdown()
876
877 disconnected := make(chan struct{})
878 asyncErr := make(chan error)
879 eh := func(nc *nats.Conn, sub *nats.Subscription, err error) { asyncErr <- err }
880 dh := func(*nats.Conn) { disconnected <- struct{}{} }
881
882 // Ensure we can connect as a sanity check.
883 addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
884 nc, err := nats.Connect(addr, nats.Token("T0pS3cr3t"), nats.ErrorHandler(eh), nats.DisconnectHandler(dh))
885 if err != nil {
886 t.Fatalf("Error creating client: %v", err)
887 }
888 defer nc.Close()
889
890 // Change authentication token.
891 changeCurrentConfigContent(t, config, "./configs/reload/token_authentication_2.conf")
892 if err := server.Reload(); err != nil {
893 t.Fatalf("Error reloading config: %v", err)
894 }
895
896 // Ensure connecting fails.
897 if _, err := nats.Connect(addr, nats.Token("T0pS3cr3t")); err == nil {
898 t.Fatal("Expected connect to fail")
899 }
900
901 // Ensure connecting succeeds when using new credentials.
902 conn, err := nats.Connect(addr, nats.Token("passw0rd"))
903 if err != nil {
904 t.Fatalf("Error creating client: %v", err)
905 }
906 conn.Close()
907
908 // Ensure the previous connection received an authorization error.
909 select {
910 case err := <-asyncErr:
911 if err != nats.ErrAuthorization {
912 t.Fatalf("Expected ErrAuthorization, got %v", err)
913 }
914 case <-time.After(2 * time.Second):
915 t.Fatal("Expected authorization error")
916 }
917
918 // Ensure the previous connection was disconnected.
919 select {
920 case <-disconnected:
921 case <-time.After(2 * time.Second):
922 t.Fatal("Expected connection to be disconnected")
923 }
924 }
925
926 // Ensure Reload supports enabling token authentication. Test this by starting
927 // a server with authentication disabled, connect to it to verify, reload
928 // config using with a token, ensure reconnect fails, then ensure reconnect
929 // succeeds when using the correct token.
930 func TestConfigReloadEnableTokenAuthentication(t *testing.T) {
931 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/basic.conf")
932 defer server.Shutdown()
933
934 // Ensure we can connect as a sanity check.
935 addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
936 nc, err := nats.Connect(addr)
937 if err != nil {
938 t.Fatalf("Error creating client: %v", err)
939 }
940 defer nc.Close()
941 disconnected := make(chan struct{}, 1)
942 asyncErr := make(chan error, 1)
943 nc.SetErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
944 asyncErr <- err
945 })
946 nc.SetDisconnectHandler(func(*nats.Conn) {
947 disconnected <- struct{}{}
948 })
949
950 // Enable authentication.
951 changeCurrentConfigContent(t, config, "./configs/reload/token_authentication_1.conf")
952 if err := server.Reload(); err != nil {
953 t.Fatalf("Error reloading config: %v", err)
954 }
955
956 // Ensure connecting fails.
957 if _, err := nats.Connect(addr); err == nil {
958 t.Fatal("Expected connect to fail")
959 }
960
961 // Ensure connecting succeeds when using new credentials.
962 conn, err := nats.Connect(addr, nats.Token("T0pS3cr3t"))
963 if err != nil {
964 t.Fatalf("Error creating client: %v", err)
965 }
966 conn.Close()
967
968 // Ensure the previous connection received an authorization error.
969 // Note that it is possible that client gets EOF and not able to
970 // process async error, so don't fail if we don't get it.
971 select {
972 case err := <-asyncErr:
973 if err != nats.ErrAuthorization {
974 t.Fatalf("Expected ErrAuthorization, got %v", err)
975 }
976 case <-time.After(time.Second):
977 }
978
979 // Ensure the previous connection was disconnected.
980 select {
981 case <-disconnected:
982 case <-time.After(2 * time.Second):
983 t.Fatal("Expected connection to be disconnected")
984 }
985 }
986
987 // Ensure Reload supports disabling single token authentication. Test this by
988 // starting a server with authentication enabled, connect to it to verify,
989 // reload config using with authentication disabled, then ensure connecting
990 // with no token succeeds.
991 func TestConfigReloadDisableTokenAuthentication(t *testing.T) {
992 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/token_authentication_1.conf")
993 defer server.Shutdown()
994
995 // Ensure we can connect as a sanity check.
996 addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
997 nc, err := nats.Connect(addr, nats.Token("T0pS3cr3t"))
998 if err != nil {
999 t.Fatalf("Error creating client: %v", err)
1000 }
1001 defer nc.Close()
1002 nc.SetErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
1003 t.Fatalf("Client received an unexpected error: %v", err)
1004 })
1005
1006 // Disable authentication.
1007 changeCurrentConfigContent(t, config, "./configs/reload/basic.conf")
1008 if err := server.Reload(); err != nil {
1009 t.Fatalf("Error reloading config: %v", err)
1010 }
1011
1012 // Ensure connecting succeeds with no credentials.
1013 conn, err := nats.Connect(addr)
1014 if err != nil {
1015 t.Fatalf("Error creating client: %v", err)
1016 }
1017 conn.Close()
1018 }
1019
1020 // Ensure Reload supports users authentication config changes. Test this by
1021 // starting a server with users authentication enabled, connect to it to
1022 // verify, reload config using a different user, ensure reconnect fails, then
1023 // ensure reconnect succeeds when using the correct credentials.
1024 func TestConfigReloadRotateUsersAuthentication(t *testing.T) {
1025 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/multiple_users_1.conf")
1026 defer server.Shutdown()
1027
1028 // Ensure we can connect as a sanity check.
1029 addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1030 nc, err := nats.Connect(addr, nats.UserInfo("alice", "foo"))
1031 if err != nil {
1032 t.Fatalf("Error creating client: %v", err)
1033 }
1034 defer nc.Close()
1035 disconnected := make(chan struct{}, 1)
1036 asyncErr := make(chan error, 1)
1037 nc.SetErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
1038 asyncErr <- err
1039 })
1040 nc.SetDisconnectHandler(func(*nats.Conn) {
1041 disconnected <- struct{}{}
1042 })
1043
1044 // These credentials won't change.
1045 nc2, err := nats.Connect(addr, nats.UserInfo("bob", "bar"))
1046 if err != nil {
1047 t.Fatalf("Error creating client: %v", err)
1048 }
1049 defer nc2.Close()
1050 sub, err := nc2.SubscribeSync("foo")
1051 if err != nil {
1052 t.Fatalf("Error subscribing: %v", err)
1053 }
1054 defer sub.Unsubscribe()
1055
1056 // Change users credentials.
1057 changeCurrentConfigContent(t, config, "./configs/reload/multiple_users_2.conf")
1058 if err := server.Reload(); err != nil {
1059 t.Fatalf("Error reloading config: %v", err)
1060 }
1061
1062 // Ensure connecting fails.
1063 if _, err := nats.Connect(addr, nats.UserInfo("alice", "foo")); err == nil {
1064 t.Fatal("Expected connect to fail")
1065 }
1066
1067 // Ensure connecting succeeds when using new credentials.
1068 conn, err := nats.Connect(addr, nats.UserInfo("alice", "baz"))
1069 if err != nil {
1070 t.Fatalf("Error creating client: %v", err)
1071 }
1072 conn.Close()
1073
1074 // Ensure the previous connection received an authorization error.
1075 // Note that it is possible that client gets EOF and not able to
1076 // process async error, so don't fail if we don't get it.
1077 select {
1078 case err := <-asyncErr:
1079 if err != nats.ErrAuthorization {
1080 t.Fatalf("Expected ErrAuthorization, got %v", err)
1081 }
1082 case <-time.After(time.Second):
1083 }
1084
1085 // Ensure the previous connection was disconnected.
1086 select {
1087 case <-disconnected:
1088 case <-time.After(2 * time.Second):
1089 t.Fatal("Expected connection to be disconnected")
1090 }
1091
1092 // Ensure the connection using unchanged credentials can still
1093 // publish/receive.
1094 if err := nc2.Publish("foo", []byte("hello")); err != nil {
1095 t.Fatalf("Error publishing: %v", err)
1096 }
1097 nc2.Flush()
1098 msg, err := sub.NextMsg(2 * time.Second)
1099 if err != nil {
1100 t.Fatalf("Error receiving msg: %v", err)
1101 }
1102 if string(msg.Data) != "hello" {
1103 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("hello"), msg.Data)
1104 }
1105 }
1106
1107 // Ensure Reload supports enabling users authentication. Test this by starting
1108 // a server with authentication disabled, connect to it to verify, reload
1109 // config using with users, ensure reconnect fails, then ensure reconnect
1110 // succeeds when using the correct credentials.
1111 func TestConfigReloadEnableUsersAuthentication(t *testing.T) {
1112 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/basic.conf")
1113 defer server.Shutdown()
1114
1115 // Ensure we can connect as a sanity check.
1116 addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1117 nc, err := nats.Connect(addr)
1118 if err != nil {
1119 t.Fatalf("Error creating client: %v", err)
1120 }
1121 defer nc.Close()
1122 disconnected := make(chan struct{}, 1)
1123 asyncErr := make(chan error, 1)
1124 nc.SetErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
1125 asyncErr <- err
1126 })
1127 nc.SetDisconnectHandler(func(*nats.Conn) {
1128 disconnected <- struct{}{}
1129 })
1130
1131 // Enable authentication.
1132 changeCurrentConfigContent(t, config, "./configs/reload/multiple_users_1.conf")
1133 if err := server.Reload(); err != nil {
1134 t.Fatalf("Error reloading config: %v", err)
1135 }
1136
1137 // Ensure connecting fails.
1138 if _, err := nats.Connect(addr); err == nil {
1139 t.Fatal("Expected connect to fail")
1140 }
1141
1142 // Ensure connecting succeeds when using new credentials.
1143 conn, err := nats.Connect(addr, nats.UserInfo("alice", "foo"))
1144 if err != nil {
1145 t.Fatalf("Error creating client: %v", err)
1146 }
1147 conn.Close()
1148
1149 // Ensure the previous connection received an authorization error.
1150 // Note that it is possible that client gets EOF and not able to
1151 // process async error, so don't fail if we don't get it.
1152 select {
1153 case err := <-asyncErr:
1154 if err != nats.ErrAuthorization {
1155 t.Fatalf("Expected ErrAuthorization, got %v", err)
1156 }
1157 case <-time.After(time.Second):
1158 }
1159
1160 // Ensure the previous connection was disconnected.
1161 select {
1162 case <-disconnected:
1163 case <-time.After(5 * time.Second):
1164 t.Fatal("Expected connection to be disconnected")
1165 }
1166 }
1167
1168 // Ensure Reload supports disabling users authentication. Test this by starting
1169 // a server with authentication enabled, connect to it to verify,
1170 // reload config using with authentication disabled, then ensure connecting
1171 // with no credentials succeeds.
1172 func TestConfigReloadDisableUsersAuthentication(t *testing.T) {
1173 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/multiple_users_1.conf")
1174 defer server.Shutdown()
1175
1176 // Ensure we can connect as a sanity check.
1177 addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1178 nc, err := nats.Connect(addr, nats.UserInfo("alice", "foo"))
1179 if err != nil {
1180 t.Fatalf("Error creating client: %v", err)
1181 }
1182 defer nc.Close()
1183 nc.SetErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
1184 t.Fatalf("Client received an unexpected error: %v", err)
1185 })
1186
1187 // Disable authentication.
1188 changeCurrentConfigContent(t, config, "./configs/reload/basic.conf")
1189 if err := server.Reload(); err != nil {
1190 t.Fatalf("Error reloading config: %v", err)
1191 }
1192
1193 // Ensure connecting succeeds with no credentials.
1194 conn, err := nats.Connect(addr)
1195 if err != nil {
1196 t.Fatalf("Error creating client: %v", err)
1197 }
1198 conn.Close()
1199 }
1200
1201 // Ensure Reload supports changing permissions. Test this by starting a server
1202 // with a user configured with certain permissions, test publish and subscribe,
1203 // reload config with new permissions, ensure the previous subscription was
1204 // closed and publishes fail, then ensure the new permissions succeed.
1205 func TestConfigReloadChangePermissions(t *testing.T) {
1206 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/authorization_1.conf")
1207 defer server.Shutdown()
1208
1209 addr := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1210 nc, err := nats.Connect(addr, nats.UserInfo("bob", "bar"))
1211 if err != nil {
1212 t.Fatalf("Error creating client: %v", err)
1213 }
1214 defer nc.Close()
1215 asyncErr := make(chan error, 1)
1216 nc.SetErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
1217 asyncErr <- err
1218 })
1219 // Ensure we can publish and receive messages as a sanity check.
1220 sub, err := nc.SubscribeSync("_INBOX.>")
1221 if err != nil {
1222 t.Fatalf("Error subscribing: %v", err)
1223 }
1224 nc.Flush()
1225
1226 conn, err := nats.Connect(addr, nats.UserInfo("alice", "foo"))
1227 if err != nil {
1228 t.Fatalf("Error creating client: %v", err)
1229 }
1230 defer conn.Close()
1231
1232 sub2, err := conn.SubscribeSync("req.foo")
1233 if err != nil {
1234 t.Fatalf("Error subscribing: %v", err)
1235 }
1236 if err := conn.Publish("_INBOX.foo", []byte("hello")); err != nil {
1237 t.Fatalf("Error publishing message: %v", err)
1238 }
1239 conn.Flush()
1240
1241 msg, err := sub.NextMsg(2 * time.Second)
1242 if err != nil {
1243 t.Fatalf("Error receiving msg: %v", err)
1244 }
1245 if string(msg.Data) != "hello" {
1246 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("hello"), msg.Data)
1247 }
1248
1249 if err := nc.Publish("req.foo", []byte("world")); err != nil {
1250 t.Fatalf("Error publishing message: %v", err)
1251 }
1252 nc.Flush()
1253
1254 msg, err = sub2.NextMsg(2 * time.Second)
1255 if err != nil {
1256 t.Fatalf("Error receiving msg: %v", err)
1257 }
1258 if string(msg.Data) != "world" {
1259 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("world"), msg.Data)
1260 }
1261
1262 // Susan will subscribe to two subjects, both will succeed but a send to foo.bar should not succeed
1263 // however PUBLIC.foo should.
1264 sconn, err := nats.Connect(addr, nats.UserInfo("susan", "baz"))
1265 if err != nil {
1266 t.Fatalf("Error creating client: %v", err)
1267 }
1268 defer sconn.Close()
1269
1270 asyncErr2 := make(chan error, 1)
1271 sconn.SetErrorHandler(func(nc *nats.Conn, sub *nats.Subscription, err error) {
1272 asyncErr2 <- err
1273 })
1274
1275 fooSub, err := sconn.SubscribeSync("foo.*")
1276 if err != nil {
1277 t.Fatalf("Error subscribing: %v", err)
1278 }
1279 sconn.Flush()
1280
1281 // Publishing from bob on foo.bar should not come through.
1282 if err := conn.Publish("foo.bar", []byte("hello")); err != nil {
1283 t.Fatalf("Error publishing message: %v", err)
1284 }
1285 conn.Flush()
1286
1287 _, err = fooSub.NextMsg(100 * time.Millisecond)
1288 if err != nats.ErrTimeout {
1289 t.Fatalf("Received a message we shouldn't have")
1290 }
1291
1292 pubSub, err := sconn.SubscribeSync("PUBLIC.*")
1293 if err != nil {
1294 t.Fatalf("Error subscribing: %v", err)
1295 }
1296 sconn.Flush()
1297
1298 select {
1299 case err := <-asyncErr2:
1300 t.Fatalf("Received unexpected error for susan: %v", err)
1301 default:
1302 }
1303
1304 // This should work ok with original config.
1305 if err := conn.Publish("PUBLIC.foo", []byte("hello monkey")); err != nil {
1306 t.Fatalf("Error publishing message: %v", err)
1307 }
1308 conn.Flush()
1309
1310 msg, err = pubSub.NextMsg(2 * time.Second)
1311 if err != nil {
1312 t.Fatalf("Error receiving msg: %v", err)
1313 }
1314 if string(msg.Data) != "hello monkey" {
1315 t.Fatalf("Msg is incorrect.\nexpected: %q\ngot: %q", "hello monkey", msg.Data)
1316 }
1317
1318 ///////////////////////////////////////////
1319 // Change permissions.
1320 ///////////////////////////////////////////
1321
1322 changeCurrentConfigContent(t, config, "./configs/reload/authorization_2.conf")
1323 if err := server.Reload(); err != nil {
1324 t.Fatalf("Error reloading config: %v", err)
1325 }
1326
1327 // Ensure we receive an error for the subscription that is no longer authorized.
1328 // In this test, since connection is not closed by the server,
1329 // the client must receive an -ERR
1330 select {
1331 case err := <-asyncErr:
1332 if !strings.Contains(strings.ToLower(err.Error()), "permissions violation for subscription to \"_inbox.>\"") {
1333 t.Fatalf("Expected permissions violation error, got %v", err)
1334 }
1335 case <-time.After(5 * time.Second):
1336 t.Fatal("Expected permissions violation error")
1337 }
1338
1339 // Ensure we receive an error when publishing to req.foo and we no longer
1340 // receive messages on _INBOX.>.
1341 if err := nc.Publish("req.foo", []byte("hola")); err != nil {
1342 t.Fatalf("Error publishing message: %v", err)
1343 }
1344 nc.Flush()
1345 if err := conn.Publish("_INBOX.foo", []byte("mundo")); err != nil {
1346 t.Fatalf("Error publishing message: %v", err)
1347 }
1348 conn.Flush()
1349
1350 select {
1351 case err := <-asyncErr:
1352 if !strings.Contains(strings.ToLower(err.Error()), "permissions violation for publish to \"req.foo\"") {
1353 t.Fatalf("Expected permissions violation error, got %v", err)
1354 }
1355 case <-time.After(5 * time.Second):
1356 t.Fatal("Expected permissions violation error")
1357 }
1358
1359 queued, _, err := sub2.Pending()
1360 if err != nil {
1361 t.Fatalf("Failed to get pending messaged: %v", err)
1362 }
1363 if queued != 0 {
1364 t.Fatalf("Pending is incorrect.\nexpected: 0\ngot: %d", queued)
1365 }
1366
1367 queued, _, err = sub.Pending()
1368 if err != nil {
1369 t.Fatalf("Failed to get pending messaged: %v", err)
1370 }
1371 if queued != 0 {
1372 t.Fatalf("Pending is incorrect.\nexpected: 0\ngot: %d", queued)
1373 }
1374
1375 // Ensure we can publish to _INBOX.foo.bar and subscribe to _INBOX.foo.>.
1376 sub, err = nc.SubscribeSync("_INBOX.foo.>")
1377 if err != nil {
1378 t.Fatalf("Error subscribing: %v", err)
1379 }
1380 nc.Flush()
1381 if err := nc.Publish("_INBOX.foo.bar", []byte("testing")); err != nil {
1382 t.Fatalf("Error publishing message: %v", err)
1383 }
1384 nc.Flush()
1385 msg, err = sub.NextMsg(2 * time.Second)
1386 if err != nil {
1387 t.Fatalf("Error receiving msg: %v", err)
1388 }
1389 if string(msg.Data) != "testing" {
1390 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("testing"), msg.Data)
1391 }
1392
1393 select {
1394 case err := <-asyncErr:
1395 t.Fatalf("Received unexpected error: %v", err)
1396 default:
1397 }
1398
1399 // Now check susan again.
1400 //
1401 // This worked ok with original config but should not deliver a message now.
1402 if err := conn.Publish("PUBLIC.foo", []byte("hello monkey")); err != nil {
1403 t.Fatalf("Error publishing message: %v", err)
1404 }
1405 conn.Flush()
1406
1407 _, err = pubSub.NextMsg(100 * time.Millisecond)
1408 if err != nats.ErrTimeout {
1409 t.Fatalf("Received a message we shouldn't have")
1410 }
1411
1412 // Now check foo.bar, which did not work before but should work now..
1413 if err := conn.Publish("foo.bar", []byte("hello?")); err != nil {
1414 t.Fatalf("Error publishing message: %v", err)
1415 }
1416 conn.Flush()
1417
1418 msg, err = fooSub.NextMsg(2 * time.Second)
1419 if err != nil {
1420 t.Fatalf("Error receiving msg: %v", err)
1421 }
1422 if string(msg.Data) != "hello?" {
1423 t.Fatalf("Msg is incorrect.\nexpected: %q\ngot: %q", "hello?", msg.Data)
1424 }
1425
1426 // Once last check for no errors.
1427 sconn.Flush()
1428
1429 select {
1430 case err := <-asyncErr2:
1431 t.Fatalf("Received unexpected error for susan: %v", err)
1432 default:
1433 }
1434 }
1435
1436 func TestConfigReloadRevokesQueueSubscriptionWithQueueScopedDeny(t *testing.T) {
1437 config := func(deny string) []byte {
1438 return fmt.Appendf(nil, `
1439 listen: 127.0.0.1:-1
1440 authorization {
1441 users: [
1442 {
1443 user: attacker
1444 password: pass
1445 permissions: {
1446 subscribe: {
1447 allow: [">"]
1448 %s
1449 }
1450 }
1451 }
1452 ]
1453 }
1454 `, deny)
1455 }
1456
1457 s, opts, configFile := runReloadServerWithContent(t, config(""))
1458 defer s.Shutdown()
1459
1460 asyncErr := make(chan error, 1)
1461 nc := natsConnect(t, fmt.Sprintf("nats://127.0.0.1:%d", opts.Port),
1462 nats.UserInfo("attacker", "pass"),
1463 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
1464 asyncErr <- err
1465 }))
1466 defer nc.Close()
1467
1468 sub := natsQueueSubSync(t, nc, "admin.secret", "workers")
1469 natsFlush(t, nc)
1470
1471 changeCurrentConfigContentWithNewContent(t, configFile, config(`deny: ["admin.secret workers"]`))
1472 require_NoError(t, s.Reload())
1473
1474 select {
1475 case err := <-asyncErr:
1476 if !strings.Contains(strings.ToLower(err.Error()), `permissions violation for subscription to "admin.secret" using queue "workers"`) {
1477 t.Fatalf("Expected queue subscription permission violation, got %v", err)
1478 }
1479 case <-time.After(5 * time.Second):
1480 t.Fatal("Expected queue subscription to be revoked")
1481 }
1482 natsPub(t, nc, "admin.secret", []byte("blocked"))
1483 natsFlush(t, nc)
1484 if _, err := sub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
1485 t.Fatalf("Expected revoked queue subscription not to receive messages, got %v", err)
1486 }
1487 }
1488
1489 // Ensure Reload returns an error when attempting to change cluster address
1490 // host.
1491 func TestConfigReloadClusterHostUnsupported(t *testing.T) {
1492 server, _, config := runReloadServerWithConfig(t, "./configs/reload/srv_a_1.conf")
1493 defer server.Shutdown()
1494
1495 // Attempt to change cluster listen host.
1496 changeCurrentConfigContent(t, config, "./configs/reload/srv_c_1.conf")
1497
1498 // This should fail because cluster address cannot be changed.
1499 if err := server.Reload(); err == nil {
1500 t.Fatal("Expected Reload to return an error")
1501 }
1502 }
1503
1504 // Ensure Reload returns an error when attempting to change cluster address
1505 // port.
1506 func TestConfigReloadClusterPortUnsupported(t *testing.T) {
1507 server, _, config := runReloadServerWithConfig(t, "./configs/reload/srv_a_1.conf")
1508 defer server.Shutdown()
1509
1510 // Attempt to change cluster listen port.
1511 changeCurrentConfigContent(t, config, "./configs/reload/srv_b_1.conf")
1512
1513 // This should fail because cluster address cannot be changed.
1514 if err := server.Reload(); err == nil {
1515 t.Fatal("Expected Reload to return an error")
1516 }
1517 }
1518
1519 // Ensure Reload supports enabling route authorization. Test this by starting
1520 // two servers in a cluster without authorization, ensuring messages flow
1521 // between them, then reloading with authorization and ensuring messages no
1522 // longer flow until reloading with the correct credentials.
1523 func TestConfigReloadEnableClusterAuthorization(t *testing.T) {
1524 srvb, srvbOpts, srvbConfig := runReloadServerWithConfig(t, "./configs/reload/srv_b_1.conf")
1525 defer srvb.Shutdown()
1526
1527 srva, srvaOpts, srvaConfig := runReloadServerWithConfig(t, "./configs/reload/srv_a_1.conf")
1528 defer srva.Shutdown()
1529
1530 checkClusterFormed(t, srva, srvb)
1531
1532 srvaAddr := fmt.Sprintf("nats://%s:%d", srvaOpts.Host, srvaOpts.Port)
1533 srvaConn, err := nats.Connect(srvaAddr)
1534 if err != nil {
1535 t.Fatalf("Error creating client: %v", err)
1536 }
1537 defer srvaConn.Close()
1538 sub, err := srvaConn.SubscribeSync("foo")
1539 if err != nil {
1540 t.Fatalf("Error subscribing: %v", err)
1541 }
1542 defer sub.Unsubscribe()
1543 if err := srvaConn.Flush(); err != nil {
1544 t.Fatalf("Error flushing: %v", err)
1545 }
1546
1547 srvbAddr := fmt.Sprintf("nats://%s:%d", srvbOpts.Host, srvbOpts.Port)
1548 srvbConn, err := nats.Connect(srvbAddr)
1549 if err != nil {
1550 t.Fatalf("Error creating client: %v", err)
1551 }
1552 defer srvbConn.Close()
1553
1554 if numRoutes := srvb.NumRoutes(); numRoutes != DEFAULT_ROUTE_POOL_SIZE {
1555 t.Fatalf("Expected %d route, got %d", DEFAULT_ROUTE_POOL_SIZE, numRoutes)
1556 }
1557
1558 // Ensure messages flow through the cluster as a sanity check.
1559 if err := srvbConn.Publish("foo", []byte("hello")); err != nil {
1560 t.Fatalf("Error publishing: %v", err)
1561 }
1562 srvbConn.Flush()
1563 msg, err := sub.NextMsg(2 * time.Second)
1564 if err != nil {
1565 t.Fatalf("Error receiving message: %v", err)
1566 }
1567 if string(msg.Data) != "hello" {
1568 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("hello"), msg.Data)
1569 }
1570
1571 // Enable route authorization.
1572 changeCurrentConfigContent(t, srvbConfig, "./configs/reload/srv_b_2.conf")
1573 if err := srvb.Reload(); err != nil {
1574 t.Fatalf("Error reloading config: %v", err)
1575 }
1576
1577 checkNumRoutes(t, srvb, 0)
1578
1579 // Ensure messages no longer flow through the cluster.
1580 for i := 0; i < 5; i++ {
1581 if err := srvbConn.Publish("foo", []byte("world")); err != nil {
1582 t.Fatalf("Error publishing: %v", err)
1583 }
1584 srvbConn.Flush()
1585 }
1586 if _, err := sub.NextMsg(50 * time.Millisecond); err != nats.ErrTimeout {
1587 t.Fatalf("Expected ErrTimeout, got %v", err)
1588 }
1589
1590 // Reload Server A with correct route credentials.
1591 changeCurrentConfigContent(t, srvaConfig, "./configs/reload/srv_a_2.conf")
1592 if err := srva.Reload(); err != nil {
1593 t.Fatalf("Error reloading config: %v", err)
1594 }
1595 checkClusterFormed(t, srva, srvb)
1596
1597 if numRoutes := srvb.NumRoutes(); numRoutes != DEFAULT_ROUTE_POOL_SIZE {
1598 t.Fatalf("Expected %d route, got %d", DEFAULT_ROUTE_POOL_SIZE, numRoutes)
1599 }
1600
1601 // Ensure messages flow through the cluster now.
1602 if err := srvbConn.Publish("foo", []byte("hola")); err != nil {
1603 t.Fatalf("Error publishing: %v", err)
1604 }
1605 srvbConn.Flush()
1606 msg, err = sub.NextMsg(2 * time.Second)
1607 if err != nil {
1608 t.Fatalf("Error receiving message: %v", err)
1609 }
1610 if string(msg.Data) != "hola" {
1611 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("hola"), msg.Data)
1612 }
1613 }
1614
1615 // Ensure Reload supports disabling route authorization. Test this by starting
1616 // two servers in a cluster with authorization, ensuring messages flow
1617 // between them, then reloading without authorization and ensuring messages
1618 // still flow.
1619 func TestConfigReloadDisableClusterAuthorization(t *testing.T) {
1620 srvb, srvbOpts, srvbConfig := runReloadServerWithConfig(t, "./configs/reload/srv_b_2.conf")
1621 defer srvb.Shutdown()
1622
1623 srva, srvaOpts, _ := runReloadServerWithConfig(t, "./configs/reload/srv_a_2.conf")
1624 defer srva.Shutdown()
1625
1626 checkClusterFormed(t, srva, srvb)
1627
1628 srvaAddr := fmt.Sprintf("nats://%s:%d", srvaOpts.Host, srvaOpts.Port)
1629 srvaConn, err := nats.Connect(srvaAddr)
1630 if err != nil {
1631 t.Fatalf("Error creating client: %v", err)
1632 }
1633 defer srvaConn.Close()
1634
1635 sub, err := srvaConn.SubscribeSync("foo")
1636 if err != nil {
1637 t.Fatalf("Error subscribing: %v", err)
1638 }
1639 defer sub.Unsubscribe()
1640 if err := srvaConn.Flush(); err != nil {
1641 t.Fatalf("Error flushing: %v", err)
1642 }
1643
1644 srvbAddr := fmt.Sprintf("nats://%s:%d", srvbOpts.Host, srvbOpts.Port)
1645 srvbConn, err := nats.Connect(srvbAddr)
1646 if err != nil {
1647 t.Fatalf("Error creating client: %v", err)
1648 }
1649 defer srvbConn.Close()
1650
1651 if numRoutes := srvb.NumRoutes(); numRoutes != DEFAULT_ROUTE_POOL_SIZE {
1652 t.Fatalf("Expected %d route, got %d", DEFAULT_ROUTE_POOL_SIZE, numRoutes)
1653 }
1654
1655 // Ensure messages flow through the cluster as a sanity check.
1656 if err := srvbConn.Publish("foo", []byte("hello")); err != nil {
1657 t.Fatalf("Error publishing: %v", err)
1658 }
1659 srvbConn.Flush()
1660 msg, err := sub.NextMsg(2 * time.Second)
1661 if err != nil {
1662 t.Fatalf("Error receiving message: %v", err)
1663 }
1664 if string(msg.Data) != "hello" {
1665 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("hello"), msg.Data)
1666 }
1667
1668 // Disable route authorization.
1669 changeCurrentConfigContent(t, srvbConfig, "./configs/reload/srv_b_1.conf")
1670 if err := srvb.Reload(); err != nil {
1671 t.Fatalf("Error reloading config: %v", err)
1672 }
1673
1674 checkClusterFormed(t, srva, srvb)
1675
1676 if numRoutes := srvb.NumRoutes(); numRoutes != DEFAULT_ROUTE_POOL_SIZE {
1677 t.Fatalf("Expected %d route, got %d", DEFAULT_ROUTE_POOL_SIZE, numRoutes)
1678 }
1679
1680 // Ensure messages still flow through the cluster.
1681 if err := srvbConn.Publish("foo", []byte("hola")); err != nil {
1682 t.Fatalf("Error publishing: %v", err)
1683 }
1684 srvbConn.Flush()
1685 msg, err = sub.NextMsg(2 * time.Second)
1686 if err != nil {
1687 t.Fatalf("Error receiving message: %v", err)
1688 }
1689 if string(msg.Data) != "hola" {
1690 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("hola"), msg.Data)
1691 }
1692 }
1693
1694 // Ensure Reload supports changing cluster routes. Test this by starting
1695 // two servers in a cluster, ensuring messages flow between them, then
1696 // reloading with a different route and ensuring messages flow through the new
1697 // cluster.
1698 func TestConfigReloadClusterRoutes(t *testing.T) {
1699 srvb, srvbOpts, _ := runReloadServerWithConfig(t, "./configs/reload/srv_b_1.conf")
1700 defer srvb.Shutdown()
1701
1702 srva, srvaOpts, srvaConfig := runReloadServerWithConfig(t, "./configs/reload/srv_a_1.conf")
1703 defer srva.Shutdown()
1704
1705 checkClusterFormed(t, srva, srvb)
1706
1707 srvcOpts, err := ProcessConfigFile("./configs/reload/srv_c_1.conf")
1708 if err != nil {
1709 t.Fatalf("Error processing config file: %v", err)
1710 }
1711 srvcOpts.NoLog = true
1712 srvcOpts.NoSigs = true
1713
1714 srvc := RunServer(srvcOpts)
1715 defer srvc.Shutdown()
1716
1717 srvaAddr := fmt.Sprintf("nats://%s:%d", srvaOpts.Host, srvaOpts.Port)
1718 srvaConn, err := nats.Connect(srvaAddr)
1719 if err != nil {
1720 t.Fatalf("Error creating client: %v", err)
1721 }
1722 defer srvaConn.Close()
1723
1724 sub, err := srvaConn.SubscribeSync("foo")
1725 if err != nil {
1726 t.Fatalf("Error subscribing: %v", err)
1727 }
1728 defer sub.Unsubscribe()
1729 if err := srvaConn.Flush(); err != nil {
1730 t.Fatalf("Error flushing: %v", err)
1731 }
1732
1733 srvbAddr := fmt.Sprintf("nats://%s:%d", srvbOpts.Host, srvbOpts.Port)
1734 srvbConn, err := nats.Connect(srvbAddr)
1735 if err != nil {
1736 t.Fatalf("Error creating client: %v", err)
1737 }
1738 defer srvbConn.Close()
1739
1740 if numRoutes := srvb.NumRoutes(); numRoutes != DEFAULT_ROUTE_POOL_SIZE {
1741 t.Fatalf("Expected %d route, got %d", DEFAULT_ROUTE_POOL_SIZE, numRoutes)
1742 }
1743
1744 // Ensure consumer on srvA is propagated to srvB
1745 checkExpectedSubs(t, 1, srvb)
1746
1747 // Ensure messages flow through the cluster as a sanity check.
1748 if err := srvbConn.Publish("foo", []byte("hello")); err != nil {
1749 t.Fatalf("Error publishing: %v", err)
1750 }
1751 srvbConn.Flush()
1752 msg, err := sub.NextMsg(2 * time.Second)
1753 if err != nil {
1754 t.Fatalf("Error receiving message: %v", err)
1755 }
1756 if string(msg.Data) != "hello" {
1757 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("hello"), msg.Data)
1758 }
1759
1760 // Reload cluster routes.
1761 changeCurrentConfigContent(t, srvaConfig, "./configs/reload/srv_a_3.conf")
1762 if err := srva.Reload(); err != nil {
1763 t.Fatalf("Error reloading config: %v", err)
1764 }
1765
1766 // Kill old route server.
1767 srvbConn.Close()
1768 srvb.Shutdown()
1769
1770 checkClusterFormed(t, srva, srvc)
1771
1772 srvcAddr := fmt.Sprintf("nats://%s:%d", srvcOpts.Host, srvcOpts.Port)
1773 srvcConn, err := nats.Connect(srvcAddr)
1774 if err != nil {
1775 t.Fatalf("Error creating client: %v", err)
1776 }
1777 defer srvcConn.Close()
1778
1779 // Ensure messages flow through the new cluster.
1780 for i := 0; i < 5; i++ {
1781 if err := srvcConn.Publish("foo", []byte("hola")); err != nil {
1782 t.Fatalf("Error publishing: %v", err)
1783 }
1784 srvcConn.Flush()
1785 }
1786 msg, err = sub.NextMsg(2 * time.Second)
1787 if err != nil {
1788 t.Fatalf("Error receiving message: %v", err)
1789 }
1790 if string(msg.Data) != "hola" {
1791 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("hola"), msg.Data)
1792 }
1793 }
1794
1795 // Ensure Reload supports removing a solicited route. In this case from A->B
1796 // Test this by starting two servers in a cluster, ensuring messages flow between them.
1797 // Then stop server B, and have server A continue to try to connect. Reload A with a config
1798 // that removes the route and make sure it does not connect to server B when its restarted.
1799 func TestConfigReloadClusterRemoveSolicitedRoutes(t *testing.T) {
1800 srvb, srvbOpts := RunServerWithConfig("./configs/reload/srv_b_1.conf")
1801 defer srvb.Shutdown()
1802
1803 srva, srvaOpts, srvaConfig := runReloadServerWithConfig(t, "./configs/reload/srv_a_1.conf")
1804 defer srva.Shutdown()
1805
1806 checkClusterFormed(t, srva, srvb)
1807
1808 srvaAddr := fmt.Sprintf("nats://%s:%d", srvaOpts.Host, srvaOpts.Port)
1809 srvaConn, err := nats.Connect(srvaAddr)
1810 if err != nil {
1811 t.Fatalf("Error creating client: %v", err)
1812 }
1813 defer srvaConn.Close()
1814 sub, err := srvaConn.SubscribeSync("foo")
1815 if err != nil {
1816 t.Fatalf("Error subscribing: %v", err)
1817 }
1818 defer sub.Unsubscribe()
1819 if err := srvaConn.Flush(); err != nil {
1820 t.Fatalf("Error flushing: %v", err)
1821 }
1822 checkExpectedSubs(t, 1, srvb)
1823
1824 srvbAddr := fmt.Sprintf("nats://%s:%d", srvbOpts.Host, srvbOpts.Port)
1825 srvbConn, err := nats.Connect(srvbAddr)
1826 if err != nil {
1827 t.Fatalf("Error creating client: %v", err)
1828 }
1829 defer srvbConn.Close()
1830
1831 if err := srvbConn.Publish("foo", []byte("hello")); err != nil {
1832 t.Fatalf("Error publishing: %v", err)
1833 }
1834 srvbConn.Flush()
1835 msg, err := sub.NextMsg(5 * time.Second)
1836 if err != nil {
1837 t.Fatalf("Error receiving message: %v", err)
1838 }
1839 if string(msg.Data) != "hello" {
1840 t.Fatalf("Msg is incorrect.\nexpected: %+v\ngot: %+v", []byte("hello"), msg.Data)
1841 }
1842
1843 // Now stop server B.
1844 srvb.Shutdown()
1845
1846 // Wait til route is dropped.
1847 checkNumRoutes(t, srva, 0)
1848
1849 // Now change config for server A to not solicit a route to server B.
1850 changeCurrentConfigContent(t, srvaConfig, "./configs/reload/srv_a_4.conf")
1851 if err := srva.Reload(); err != nil {
1852 t.Fatalf("Error reloading config: %v", err)
1853 }
1854
1855 // Restart server B.
1856 srvb, _ = RunServerWithConfig("./configs/reload/srv_b_1.conf")
1857 defer srvb.Shutdown()
1858
1859 // We should not have a cluster formed here.
1860 numRoutes := 0
1861 deadline := time.Now().Add(2 * DEFAULT_ROUTE_RECONNECT)
1862 for time.Now().Before(deadline) {
1863 if numRoutes = srva.NumRoutes(); numRoutes != 0 {
1864 break
1865 } else {
1866 time.Sleep(100 * time.Millisecond)
1867 }
1868 }
1869 if numRoutes != 0 {
1870 t.Fatalf("Expected 0 routes for server A, got %d", numRoutes)
1871 }
1872 }
1873
1874 func reloadUpdateConfig(t *testing.T, s *Server, conf, content string) {
1875 t.Helper()
1876 if err := os.WriteFile(conf, []byte(content), 0666); err != nil {
1877 t.Fatalf("Error creating config file: %v", err)
1878 }
1879 if err := s.Reload(); err != nil {
1880 t.Fatalf("Error on reload: %v", err)
1881 }
1882 }
1883
1884 func TestConfigReloadClusterAdvertise(t *testing.T) {
1885 s, _, conf := runReloadServerWithContent(t, []byte(`
1886 listen: "0.0.0.0:-1"
1887 cluster: {
1888 listen: "0.0.0.0:-1"
1889 }
1890 `))
1891 defer s.Shutdown()
1892
1893 orgClusterPort := s.ClusterAddr().Port
1894
1895 verify := func(expectedHost string, expectedPort int, expectedIP string) {
1896 s.mu.Lock()
1897 routeInfo := s.routeInfo
1898 rij := generateInfoJSON(&routeInfo)
1899 s.mu.Unlock()
1900 if routeInfo.Host != expectedHost || routeInfo.Port != expectedPort || routeInfo.IP != expectedIP {
1901 t.Fatalf("Expected host/port/IP to be %s:%v, %q, got %s:%d, %q",
1902 expectedHost, expectedPort, expectedIP, routeInfo.Host, routeInfo.Port, routeInfo.IP)
1903 }
1904 routeInfoJSON := Info{}
1905 err := json.Unmarshal(rij[5:], &routeInfoJSON) // Skip "INFO "
1906 if err != nil {
1907 t.Fatalf("Error on Unmarshal: %v", err)
1908 }
1909 // Check that server routeInfoJSON was updated too
1910 if !reflect.DeepEqual(routeInfo, routeInfoJSON) {
1911 t.Fatalf("Expected routeInfoJSON to be %+v, got %+v", routeInfo, routeInfoJSON)
1912 }
1913 }
1914
1915 // Update config with cluster_advertise
1916 reloadUpdateConfig(t, s, conf, `
1917 listen: "0.0.0.0:-1"
1918 cluster: {
1919 listen: "0.0.0.0:-1"
1920 cluster_advertise: "me:1"
1921 }
1922 `)
1923 verify("me", 1, "nats-route://me:1/")
1924
1925 // Update config with cluster_advertise (no port specified)
1926 reloadUpdateConfig(t, s, conf, `
1927 listen: "0.0.0.0:-1"
1928 cluster: {
1929 listen: "0.0.0.0:-1"
1930 cluster_advertise: "me"
1931 }
1932 `)
1933 verify("me", orgClusterPort, fmt.Sprintf("nats-route://me:%d/", orgClusterPort))
1934
1935 // Update config with cluster_advertise (-1 port specified)
1936 reloadUpdateConfig(t, s, conf, `
1937 listen: "0.0.0.0:-1"
1938 cluster: {
1939 listen: "0.0.0.0:-1"
1940 cluster_advertise: "me:-1"
1941 }
1942 `)
1943 verify("me", orgClusterPort, fmt.Sprintf("nats-route://me:%d/", orgClusterPort))
1944
1945 // Update to remove cluster_advertise
1946 reloadUpdateConfig(t, s, conf, `
1947 listen: "0.0.0.0:-1"
1948 cluster: {
1949 listen: "0.0.0.0:-1"
1950 }
1951 `)
1952 verify("0.0.0.0", orgClusterPort, "")
1953 }
1954
1955 func TestConfigReloadClusterNoAdvertise(t *testing.T) {
1956 s, _, conf := runReloadServerWithContent(t, []byte(`
1957 listen: "0.0.0.0:-1"
1958 client_advertise: "me:1"
1959 cluster: {
1960 listen: "0.0.0.0:-1"
1961 }
1962 `))
1963 defer s.Shutdown()
1964
1965 s.mu.Lock()
1966 ccurls := s.routeInfo.ClientConnectURLs
1967 s.mu.Unlock()
1968 if len(ccurls) != 1 && ccurls[0] != "me:1" {
1969 t.Fatalf("Unexpected routeInfo.ClientConnectURLS: %v", ccurls)
1970 }
1971
1972 // Update config with no_advertise
1973 reloadUpdateConfig(t, s, conf, `
1974 listen: "0.0.0.0:-1"
1975 client_advertise: "me:1"
1976 cluster: {
1977 listen: "0.0.0.0:-1"
1978 no_advertise: true
1979 }
1980 `)
1981
1982 s.mu.Lock()
1983 ccurls = s.routeInfo.ClientConnectURLs
1984 s.mu.Unlock()
1985 if len(ccurls) != 0 {
1986 t.Fatalf("Unexpected routeInfo.ClientConnectURLS: %v", ccurls)
1987 }
1988
1989 // Update config with cluster_advertise (no port specified)
1990 reloadUpdateConfig(t, s, conf, `
1991 listen: "0.0.0.0:-1"
1992 client_advertise: "me:1"
1993 cluster: {
1994 listen: "0.0.0.0:-1"
1995 }
1996 `)
1997 s.mu.Lock()
1998 ccurls = s.routeInfo.ClientConnectURLs
1999 s.mu.Unlock()
2000 if len(ccurls) != 1 && ccurls[0] != "me:1" {
2001 t.Fatalf("Unexpected routeInfo.ClientConnectURLS: %v", ccurls)
2002 }
2003 }
2004
2005 func TestConfigReloadClusterName(t *testing.T) {
2006 s, _, conf := runReloadServerWithContent(t, []byte(`
2007 listen: "0.0.0.0:-1"
2008 cluster: {
2009 name: "abc"
2010 listen: "0.0.0.0:-1"
2011 }
2012 `))
2013 defer s.Shutdown()
2014
2015 // Update config with a new cluster name.
2016 reloadUpdateConfig(t, s, conf, `
2017 listen: "0.0.0.0:-1"
2018 cluster: {
2019 name: "xyz"
2020 listen: "0.0.0.0:-1"
2021 }
2022 `)
2023
2024 if s.ClusterName() != "xyz" {
2025 t.Fatalf("Expected update clustername of \"xyz\", got %q", s.ClusterName())
2026 }
2027 }
2028
2029 func TestConfigReloadMaxSubsUnsupported(t *testing.T) {
2030 s, _, conf := runReloadServerWithContent(t, []byte(`
2031 port: -1
2032 max_subs: 1
2033 `))
2034 defer s.Shutdown()
2035
2036 if err := os.WriteFile(conf, []byte(`max_subs: 10`), 0666); err != nil {
2037 t.Fatalf("Error writing config file: %v", err)
2038 }
2039 if err := s.Reload(); err == nil {
2040 t.Fatal("Expected Reload to return an error")
2041 }
2042 }
2043
2044 func TestConfigReloadClientAdvertise(t *testing.T) {
2045 s, _, conf := runReloadServerWithContent(t, []byte(`listen: "0.0.0.0:-1"`))
2046 defer s.Shutdown()
2047
2048 orgPort := s.Addr().(*net.TCPAddr).Port
2049
2050 verify := func(expectedHost string, expectedPort int) {
2051 s.mu.Lock()
2052 info := s.info
2053 s.mu.Unlock()
2054 if info.Host != expectedHost || info.Port != expectedPort {
2055 stackFatalf(t, "Expected host/port to be %s:%d, got %s:%d",
2056 expectedHost, expectedPort, info.Host, info.Port)
2057 }
2058 }
2059
2060 // Update config with ClientAdvertise (port specified)
2061 reloadUpdateConfig(t, s, conf, `
2062 listen: "0.0.0.0:-1"
2063 client_advertise: "me:1"
2064 `)
2065 verify("me", 1)
2066
2067 // Update config with ClientAdvertise (no port specified)
2068 reloadUpdateConfig(t, s, conf, `
2069 listen: "0.0.0.0:-1"
2070 client_advertise: "me"
2071 `)
2072 verify("me", orgPort)
2073
2074 // Update config with ClientAdvertise (-1 port specified)
2075 reloadUpdateConfig(t, s, conf, `
2076 listen: "0.0.0.0:-1"
2077 client_advertise: "me:-1"
2078 `)
2079 verify("me", orgPort)
2080
2081 // Now remove ClientAdvertise to check that original values
2082 // are restored.
2083 reloadUpdateConfig(t, s, conf, `listen: "0.0.0.0:-1"`)
2084 verify("0.0.0.0", orgPort)
2085 }
2086
2087 // Ensure Reload supports changing the max connections. Test this by starting a
2088 // server with no max connections, connecting two clients, reloading with a
2089 // max connections of one, and ensuring one client is disconnected.
2090 func TestConfigReloadMaxConnections(t *testing.T) {
2091 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/basic.conf")
2092 defer server.Shutdown()
2093
2094 // Make two connections.
2095 addr := fmt.Sprintf("nats://%s:%d", opts.Host, server.Addr().(*net.TCPAddr).Port)
2096 nc1, err := nats.Connect(addr)
2097 if err != nil {
2098 t.Fatalf("Error creating client: %v", err)
2099 }
2100 defer nc1.Close()
2101 closed := make(chan struct{}, 1)
2102 nc1.SetDisconnectHandler(func(*nats.Conn) {
2103 closed <- struct{}{}
2104 })
2105 nc2, err := nats.Connect(addr)
2106 if err != nil {
2107 t.Fatalf("Error creating client: %v", err)
2108 }
2109 defer nc2.Close()
2110 nc2.SetDisconnectHandler(func(*nats.Conn) {
2111 closed <- struct{}{}
2112 })
2113
2114 if numClients := server.NumClients(); numClients != 2 {
2115 t.Fatalf("Expected 2 clients, got %d", numClients)
2116 }
2117
2118 // Set max connections to one.
2119 changeCurrentConfigContent(t, config, "./configs/reload/max_connections.conf")
2120 if err := server.Reload(); err != nil {
2121 t.Fatalf("Error reloading config: %v", err)
2122 }
2123
2124 // Ensure one connection was closed.
2125 select {
2126 case <-closed:
2127 case <-time.After(5 * time.Second):
2128 t.Fatal("Expected to be disconnected")
2129 }
2130
2131 checkClientsCount(t, server, 1)
2132
2133 // Ensure new connections fail.
2134 _, err = nats.Connect(addr)
2135 if err == nil {
2136 t.Fatal("Expected error on connect")
2137 }
2138 }
2139
2140 // Ensure Reload supports refusing all connections. Test this by starting a
2141 // server with no max connections, connecting two clients, reloading with a
2142 // max connections of one, and ensuring one client is disconnected.
2143 func TestConfigReloadMaxConnectionsPreventAll(t *testing.T) {
2144 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/basic.conf")
2145 defer server.Shutdown()
2146
2147 // Make two connections.
2148 addr := fmt.Sprintf("nats://%s:%d", opts.Host, server.Addr().(*net.TCPAddr).Port)
2149 nc1, err := nats.Connect(addr)
2150 if err != nil {
2151 t.Fatalf("Error creating client: %v", err)
2152 }
2153 defer nc1.Close()
2154 closed := make(chan struct{}, 1)
2155 nc1.SetDisconnectHandler(func(*nats.Conn) {
2156 closed <- struct{}{}
2157 })
2158 nc2, err := nats.Connect(addr)
2159 if err != nil {
2160 t.Fatalf("Error creating client: %v", err)
2161 }
2162 defer nc2.Close()
2163 nc2.SetDisconnectHandler(func(*nats.Conn) {
2164 closed <- struct{}{}
2165 })
2166
2167 if numClients := server.NumClients(); numClients != 2 {
2168 t.Fatalf("Expected 2 clients, got %d", numClients)
2169 }
2170
2171 // Set max connections to one.
2172 changeCurrentConfigContent(t, config, "./configs/reload/max_connections_refuse_all.conf")
2173 if err := server.Reload(); err != nil {
2174 t.Fatalf("Error reloading config: %v", err)
2175 }
2176
2177 // Ensure one connection was closed.
2178 select {
2179 case <-closed:
2180 case <-time.After(5 * time.Second):
2181 t.Fatal("Expected to be disconnected")
2182 }
2183
2184 checkClientsCount(t, server, 0)
2185
2186 // Ensure new connections fail.
2187 _, err = nats.Connect(addr)
2188 if err == nil {
2189 t.Fatal("Expected error on connect")
2190 }
2191 }
2192
2193 // Ensure reload supports changing the max payload size. Test this by starting
2194 // a server with the default size limit, ensuring publishes work, reloading
2195 // with a restrictive limit, and ensuring publishing an oversized message fails
2196 // and disconnects the client.
2197 func TestConfigReloadMaxPayload(t *testing.T) {
2198 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/basic.conf")
2199 defer server.Shutdown()
2200
2201 addr := fmt.Sprintf("nats://%s:%d", opts.Host, server.Addr().(*net.TCPAddr).Port)
2202 nc, err := nats.Connect(addr)
2203 if err != nil {
2204 t.Fatalf("Error creating client: %v", err)
2205 }
2206 defer nc.Close()
2207 closed := make(chan struct{})
2208 nc.SetDisconnectHandler(func(*nats.Conn) {
2209 closed <- struct{}{}
2210 })
2211
2212 conn, err := nats.Connect(addr)
2213 if err != nil {
2214 t.Fatalf("Error creating client: %v", err)
2215 }
2216 defer conn.Close()
2217 sub, err := conn.SubscribeSync("foo")
2218 if err != nil {
2219 t.Fatalf("Error subscribing: %v", err)
2220 }
2221 conn.Flush()
2222
2223 // Ensure we can publish as a sanity check.
2224 if err := nc.Publish("foo", []byte("hello")); err != nil {
2225 t.Fatalf("Error publishing: %v", err)
2226 }
2227 nc.Flush()
2228 _, err = sub.NextMsg(2 * time.Second)
2229 if err != nil {
2230 t.Fatalf("Error receiving message: %v", err)
2231 }
2232
2233 // Set max payload to one.
2234 changeCurrentConfigContent(t, config, "./configs/reload/max_payload.conf")
2235 if err := server.Reload(); err != nil {
2236 t.Fatalf("Error reloading config: %v", err)
2237 }
2238
2239 // Ensure oversized messages don't get delivered and the client is
2240 // disconnected.
2241 if err := nc.Publish("foo", []byte("hello")); err != nil {
2242 t.Fatalf("Error publishing: %v", err)
2243 }
2244 nc.Flush()
2245 _, err = sub.NextMsg(20 * time.Millisecond)
2246 if err != nats.ErrTimeout {
2247 t.Fatalf("Expected ErrTimeout, got: %v", err)
2248 }
2249
2250 select {
2251 case <-closed:
2252 case <-time.After(5 * time.Second):
2253 t.Fatal("Expected to be disconnected")
2254 }
2255 }
2256
2257 // Ensure reload supports rotating out files. Test this by starting
2258 // a server with log and pid files, reloading new ones, then check that
2259 // we can rename and delete the old log/pid files.
2260 func TestConfigReloadRotateFiles(t *testing.T) {
2261 server, _, config := runReloadServerWithConfig(t, "./configs/reload/file_rotate.conf")
2262 defer func() {
2263 removeFile(t, "log1.txt")
2264 removeFile(t, "nats-server1.pid")
2265 }()
2266 defer server.Shutdown()
2267
2268 // Configure the logger to enable actual logging
2269 opts := server.getOpts()
2270 opts.NoLog = false
2271 server.ConfigureLogger()
2272
2273 // Load a config that renames the files.
2274 changeCurrentConfigContent(t, config, "./configs/reload/file_rotate1.conf")
2275 if err := server.Reload(); err != nil {
2276 t.Fatalf("Error reloading config: %v", err)
2277 }
2278
2279 // Make sure the new files exist.
2280 if _, err := os.Stat("log1.txt"); os.IsNotExist(err) {
2281 t.Fatalf("Error reloading config, no new file: %v", err)
2282 }
2283 if _, err := os.Stat("nats-server1.pid"); os.IsNotExist(err) {
2284 t.Fatalf("Error reloading config, no new file: %v", err)
2285 }
2286
2287 // Check that old file can be renamed.
2288 if err := os.Rename("log.txt", "log_old.txt"); err != nil {
2289 t.Fatalf("Error reloading config, cannot rename file: %v", err)
2290 }
2291 if err := os.Rename("nats-server.pid", "nats-server_old.pid"); err != nil {
2292 t.Fatalf("Error reloading config, cannot rename file: %v", err)
2293 }
2294
2295 // Check that the old files can be removed after rename.
2296 removeFile(t, "log_old.txt")
2297 removeFile(t, "nats-server_old.pid")
2298 }
2299
2300 func TestConfigReloadClusterWorks(t *testing.T) {
2301 confBTemplate := `
2302 listen: -1
2303 cluster: {
2304 listen: 127.0.0.1:7244
2305 authorization {
2306 user: ruser
2307 password: pwd
2308 timeout: %d
2309 }
2310 routes = [
2311 nats-route://ruser:[email protected]:7246
2312 ]
2313 }`
2314 confB := createConfFile(t, []byte(fmt.Sprintf(confBTemplate, 3)))
2315
2316 confATemplate := `
2317 listen: -1
2318 cluster: {
2319 listen: 127.0.0.1:7246
2320 authorization {
2321 user: ruser
2322 password: pwd
2323 timeout: %d
2324 }
2325 routes = [
2326 nats-route://ruser:[email protected]:7244
2327 ]
2328 }`
2329 confA := createConfFile(t, []byte(fmt.Sprintf(confATemplate, 3)))
2330
2331 srvb, _ := RunServerWithConfig(confB)
2332 defer srvb.Shutdown()
2333
2334 srva, _ := RunServerWithConfig(confA)
2335 defer srva.Shutdown()
2336
2337 // Wait for the cluster to form and capture the connection IDs of each route
2338 checkClusterFormed(t, srva, srvb)
2339
2340 getCID := func(s *Server) uint64 {
2341 s.mu.Lock()
2342 defer s.mu.Unlock()
2343 if r := getFirstRoute(s); r != nil {
2344 return r.cid
2345 }
2346 return 0
2347 }
2348 acid := getCID(srva)
2349 bcid := getCID(srvb)
2350
2351 // Update auth timeout to force a check of the connected route auth
2352 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBTemplate, 5))
2353 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, 5))
2354
2355 // Wait a little bit to ensure that there is no issue with connection
2356 // breaking at this point (this was an issue before).
2357 time.Sleep(100 * time.Millisecond)
2358
2359 // Cluster should still exist
2360 checkClusterFormed(t, srva, srvb)
2361
2362 // Check that routes were not re-created
2363 newacid := getCID(srva)
2364 newbcid := getCID(srvb)
2365
2366 if newacid != acid {
2367 t.Fatalf("Expected server A route ID to be %v, got %v", acid, newacid)
2368 }
2369 if newbcid != bcid {
2370 t.Fatalf("Expected server B route ID to be %v, got %v", bcid, newbcid)
2371 }
2372 }
2373
2374 func TestConfigReloadClusterPerms(t *testing.T) {
2375 confATemplate := `
2376 port: -1
2377 cluster {
2378 listen: 127.0.0.1:-1
2379 permissions {
2380 import {
2381 allow: %s
2382 }
2383 export {
2384 allow: %s
2385 }
2386 }
2387 }
2388 no_sys_acc: true
2389 `
2390 confA := createConfFile(t, []byte(fmt.Sprintf(confATemplate, `"foo"`, `"foo"`)))
2391 srva, _ := RunServerWithConfig(confA)
2392 defer srva.Shutdown()
2393
2394 confBTemplate := `
2395 port: -1
2396 cluster {
2397 listen: 127.0.0.1:-1
2398 permissions {
2399 import {
2400 allow: %s
2401 }
2402 export {
2403 allow: %s
2404 }
2405 }
2406 routes = [
2407 "nats://127.0.0.1:%d"
2408 ]
2409 }
2410 no_sys_acc: true
2411 `
2412 confB := createConfFile(t, []byte(fmt.Sprintf(confBTemplate, `"foo"`, `"foo"`, srva.ClusterAddr().Port)))
2413 srvb, _ := RunServerWithConfig(confB)
2414 defer srvb.Shutdown()
2415
2416 checkClusterFormed(t, srva, srvb)
2417
2418 // Create a connection on A
2419 nca, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", srva.Addr().(*net.TCPAddr).Port))
2420 if err != nil {
2421 t.Fatalf("Error on connect: %v", err)
2422 }
2423 defer nca.Close()
2424 // Create a subscription on "foo" and "bar", only "foo" will be also on server B.
2425 subFooOnA, err := nca.SubscribeSync("foo")
2426 if err != nil {
2427 t.Fatalf("Error on subscribe: %v", err)
2428 }
2429 subBarOnA, err := nca.SubscribeSync("bar")
2430 if err != nil {
2431 t.Fatalf("Error on subscribe: %v", err)
2432 }
2433
2434 // Connect on B and do the same
2435 ncb, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", srvb.Addr().(*net.TCPAddr).Port))
2436 if err != nil {
2437 t.Fatalf("Error on connect: %v", err)
2438 }
2439 defer ncb.Close()
2440 // Create a subscription on "foo" and "bar", only "foo" will be also on server B.
2441 subFooOnB, err := ncb.SubscribeSync("foo")
2442 if err != nil {
2443 t.Fatalf("Error on subscribe: %v", err)
2444 }
2445 subBarOnB, err := ncb.SubscribeSync("bar")
2446 if err != nil {
2447 t.Fatalf("Error on subscribe: %v", err)
2448 }
2449
2450 // Check subscriptions on each server. There should be 3 on each server,
2451 // foo and bar locally and foo from remote server.
2452 checkExpectedSubs(t, 3, srva, srvb)
2453
2454 sendMsg := func(t *testing.T, subj string, nc *nats.Conn) {
2455 t.Helper()
2456 if err := nc.Publish(subj, []byte("msg")); err != nil {
2457 t.Fatalf("Error on publish: %v", err)
2458 }
2459 }
2460
2461 checkSub := func(t *testing.T, sub *nats.Subscription, shouldReceive bool) {
2462 t.Helper()
2463 _, err := sub.NextMsg(100 * time.Millisecond)
2464 if shouldReceive && err != nil {
2465 t.Fatalf("Expected message on %q, got %v", sub.Subject, err)
2466 } else if !shouldReceive && err == nil {
2467 t.Fatalf("Expected no message on %q, got one", sub.Subject)
2468 }
2469 }
2470
2471 // Produce from A and check received on both sides
2472 sendMsg(t, "foo", nca)
2473 checkSub(t, subFooOnA, true)
2474 checkSub(t, subFooOnB, true)
2475 // Now from B:
2476 sendMsg(t, "foo", ncb)
2477 checkSub(t, subFooOnA, true)
2478 checkSub(t, subFooOnB, true)
2479
2480 // Publish on bar from A and make sure only local sub receives
2481 sendMsg(t, "bar", nca)
2482 checkSub(t, subBarOnA, true)
2483 checkSub(t, subBarOnB, false)
2484
2485 // Publish on bar from B and make sure only local sub receives
2486 sendMsg(t, "bar", ncb)
2487 checkSub(t, subBarOnA, false)
2488 checkSub(t, subBarOnB, true)
2489
2490 // We will now both import/export foo and bar. Start with reloading A.
2491 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `["foo", "bar"]`, `["foo", "bar"]`))
2492
2493 // Since B has not been updated yet, the state should remain the same,
2494 // that is 3 subs on each server.
2495 checkExpectedSubs(t, 3, srva, srvb)
2496
2497 // Now update and reload B. Add "baz" for another test down below
2498 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBTemplate, `["foo", "bar", "baz"]`, `["foo", "bar", "baz"]`, srva.ClusterAddr().Port))
2499
2500 // Now 4 on each server
2501 checkExpectedSubs(t, 4, srva, srvb)
2502
2503 // Make sure that we can receive all messages
2504 sendMsg(t, "foo", nca)
2505 checkSub(t, subFooOnA, true)
2506 checkSub(t, subFooOnB, true)
2507 sendMsg(t, "foo", ncb)
2508 checkSub(t, subFooOnA, true)
2509 checkSub(t, subFooOnB, true)
2510
2511 sendMsg(t, "bar", nca)
2512 checkSub(t, subBarOnA, true)
2513 checkSub(t, subBarOnB, true)
2514 sendMsg(t, "bar", ncb)
2515 checkSub(t, subBarOnA, true)
2516 checkSub(t, subBarOnB, true)
2517
2518 // Create subscription on baz on server B.
2519 subBazOnB, err := ncb.SubscribeSync("baz")
2520 if err != nil {
2521 t.Fatalf("Error on subscribe: %v", err)
2522 }
2523 // Check subscriptions count
2524 checkExpectedSubs(t, 5, srvb)
2525 checkExpectedSubs(t, 4, srva)
2526
2527 sendMsg(t, "baz", nca)
2528 checkSub(t, subBazOnB, false)
2529 sendMsg(t, "baz", ncb)
2530 checkSub(t, subBazOnB, true)
2531
2532 // Test UNSUB by denying something that was previously imported
2533 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `"foo"`, `["foo", "bar"]`))
2534 // Since A no longer imports "bar", we should have one less subscription
2535 // on B (B will have received an UNSUB for bar)
2536 checkExpectedSubs(t, 4, srvb)
2537 // A, however, should still have same number of subs.
2538 checkExpectedSubs(t, 4, srva)
2539
2540 // Remove all permissions from A.
2541 reloadUpdateConfig(t, srva, confA, `
2542 port: -1
2543 cluster {
2544 listen: 127.0.0.1:-1
2545 }
2546 no_sys_acc: true
2547 `)
2548 // Server A should now have baz sub
2549 checkExpectedSubs(t, 5, srvb)
2550 checkExpectedSubs(t, 5, srva)
2551
2552 sendMsg(t, "baz", nca)
2553 checkSub(t, subBazOnB, true)
2554 sendMsg(t, "baz", ncb)
2555 checkSub(t, subBazOnB, true)
2556
2557 // Finally, remove permissions from B
2558 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(`
2559 port: -1
2560 cluster {
2561 listen: 127.0.0.1:-1
2562 routes = [
2563 "nats://127.0.0.1:%d"
2564 ]
2565 }
2566 no_sys_acc: true
2567 `, srva.ClusterAddr().Port))
2568 // Check expected subscriptions count.
2569 checkExpectedSubs(t, 5, srvb)
2570 checkExpectedSubs(t, 5, srva)
2571 }
2572
2573 func TestConfigReloadClusterPermsImport(t *testing.T) {
2574 confATemplate := `
2575 port: -1
2576 cluster {
2577 listen: 127.0.0.1:-1
2578 permissions {
2579 import: {
2580 allow: %s
2581 }
2582 }
2583 }
2584 no_sys_acc: true
2585 `
2586 confA := createConfFile(t, []byte(fmt.Sprintf(confATemplate, `["foo", "bar"]`)))
2587 srva, _ := RunServerWithConfig(confA)
2588 defer srva.Shutdown()
2589
2590 confBTemplate := `
2591 port: -1
2592 cluster {
2593 listen: 127.0.0.1:-1
2594 routes = [
2595 "nats://127.0.0.1:%d"
2596 ]
2597 }
2598 no_sys_acc: true
2599 `
2600 confB := createConfFile(t, []byte(fmt.Sprintf(confBTemplate, srva.ClusterAddr().Port)))
2601 srvb, _ := RunServerWithConfig(confB)
2602 defer srvb.Shutdown()
2603
2604 checkClusterFormed(t, srva, srvb)
2605
2606 // Create a connection on A
2607 nca, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", srva.Addr().(*net.TCPAddr).Port))
2608 if err != nil {
2609 t.Fatalf("Error on connect: %v", err)
2610 }
2611 defer nca.Close()
2612 // Create a subscription on "foo" and "bar"
2613 if _, err := nca.SubscribeSync("foo"); err != nil {
2614 t.Fatalf("Error on subscribe: %v", err)
2615 }
2616 if _, err := nca.SubscribeSync("bar"); err != nil {
2617 t.Fatalf("Error on subscribe: %v", err)
2618 }
2619
2620 checkExpectedSubs(t, 2, srva, srvb)
2621
2622 // Drop foo
2623 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `"bar"`))
2624 checkExpectedSubs(t, 2, srva)
2625 checkExpectedSubs(t, 1, srvb)
2626
2627 // Add it back
2628 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `["foo", "bar"]`))
2629 checkExpectedSubs(t, 2, srva, srvb)
2630
2631 // Empty Import means implicit allow
2632 reloadUpdateConfig(t, srva, confA, `
2633 port: -1
2634 cluster {
2635 listen: 127.0.0.1:-1
2636 permissions {
2637 export: ">"
2638 }
2639 }
2640 no_sys_acc: true
2641 `)
2642 checkExpectedSubs(t, 2, srva, srvb)
2643
2644 confATemplate = `
2645 port: -1
2646 cluster {
2647 listen: 127.0.0.1:-1
2648 permissions {
2649 import: {
2650 allow: ["foo", "bar"]
2651 deny: %s
2652 }
2653 }
2654 }
2655 no_sys_acc: true
2656 `
2657 // Now deny all:
2658 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `["foo", "bar"]`))
2659 checkExpectedSubs(t, 2, srva)
2660 checkExpectedSubs(t, 0, srvb)
2661
2662 // Drop foo from the deny list
2663 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `"bar"`))
2664 checkExpectedSubs(t, 2, srva)
2665 checkExpectedSubs(t, 1, srvb)
2666 }
2667
2668 func TestConfigReloadClusterPermsExport(t *testing.T) {
2669 confATemplate := `
2670 port: -1
2671 cluster {
2672 listen: 127.0.0.1:-1
2673 permissions {
2674 export: {
2675 allow: %s
2676 }
2677 }
2678 }
2679 no_sys_acc: true
2680 `
2681 confA := createConfFile(t, []byte(fmt.Sprintf(confATemplate, `["foo", "bar"]`)))
2682 srva, _ := RunServerWithConfig(confA)
2683 defer srva.Shutdown()
2684
2685 confBTemplate := `
2686 port: -1
2687 cluster {
2688 listen: 127.0.0.1:-1
2689 routes = [
2690 "nats://127.0.0.1:%d"
2691 ]
2692 }
2693 no_sys_acc: true
2694 `
2695 confB := createConfFile(t, []byte(fmt.Sprintf(confBTemplate, srva.ClusterAddr().Port)))
2696 srvb, _ := RunServerWithConfig(confB)
2697 defer srvb.Shutdown()
2698
2699 checkClusterFormed(t, srva, srvb)
2700
2701 // Create a connection on B
2702 ncb, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", srvb.Addr().(*net.TCPAddr).Port))
2703 if err != nil {
2704 t.Fatalf("Error on connect: %v", err)
2705 }
2706 defer ncb.Close()
2707 // Create a subscription on "foo" and "bar"
2708 if _, err := ncb.SubscribeSync("foo"); err != nil {
2709 t.Fatalf("Error on subscribe: %v", err)
2710 }
2711 if _, err := ncb.SubscribeSync("bar"); err != nil {
2712 t.Fatalf("Error on subscribe: %v", err)
2713 }
2714
2715 checkExpectedSubs(t, 2, srva, srvb)
2716
2717 // Drop foo
2718 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `"bar"`))
2719 checkExpectedSubs(t, 2, srvb)
2720 checkExpectedSubs(t, 1, srva)
2721
2722 // Add it back
2723 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `["foo", "bar"]`))
2724 checkExpectedSubs(t, 2, srva, srvb)
2725
2726 // Empty Export means implicit allow
2727 reloadUpdateConfig(t, srva, confA, `
2728 port: -1
2729 cluster {
2730 listen: 127.0.0.1:-1
2731 permissions {
2732 import: ">"
2733 }
2734 }
2735 no_sys_acc: true
2736 `)
2737 checkExpectedSubs(t, 2, srva, srvb)
2738
2739 confATemplate = `
2740 port: -1
2741 cluster {
2742 listen: 127.0.0.1:-1
2743 permissions {
2744 export: {
2745 allow: ["foo", "bar"]
2746 deny: %s
2747 }
2748 }
2749 }
2750 no_sys_acc: true
2751 `
2752 // Now deny all:
2753 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `["foo", "bar"]`))
2754 checkExpectedSubs(t, 0, srva)
2755 checkExpectedSubs(t, 2, srvb)
2756
2757 // Drop foo from the deny list
2758 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `"bar"`))
2759 checkExpectedSubs(t, 1, srva)
2760 checkExpectedSubs(t, 2, srvb)
2761 }
2762
2763 func TestConfigReloadClusterPermsOldServer(t *testing.T) {
2764 confATemplate := `
2765 port: -1
2766 cluster {
2767 listen: 127.0.0.1:-1
2768 permissions {
2769 export: {
2770 allow: %s
2771 }
2772 }
2773 }
2774 `
2775 confA := createConfFile(t, []byte(fmt.Sprintf(confATemplate, `["foo", "bar"]`)))
2776 srva, _ := RunServerWithConfig(confA)
2777 defer srva.Shutdown()
2778
2779 optsB := DefaultOptions()
2780 optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srva.ClusterAddr().Port))
2781 // Make server B behave like an old server
2782 optsB.overrideProto = setServerProtoForTest(RouteProtoZero)
2783 srvb := RunServer(optsB)
2784 defer srvb.Shutdown()
2785
2786 checkClusterFormed(t, srva, srvb)
2787
2788 // Get the route's connection ID
2789 getRouteRID := func() uint64 {
2790 rid := uint64(0)
2791 srvb.mu.Lock()
2792 if r := getFirstRoute(srvb); r != nil {
2793 r.mu.Lock()
2794 rid = r.cid
2795 r.mu.Unlock()
2796 }
2797 srvb.mu.Unlock()
2798 return rid
2799 }
2800 orgRID := getRouteRID()
2801
2802 // Cause a config reload on A
2803 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `"bar"`))
2804
2805 // Check that new route gets created
2806 check := func(t *testing.T) {
2807 t.Helper()
2808 checkFor(t, 3*time.Second, 15*time.Millisecond, func() error {
2809 if rid := getRouteRID(); rid == orgRID {
2810 return fmt.Errorf("Route does not seem to have been recreated")
2811 }
2812 return nil
2813 })
2814 }
2815 check(t)
2816
2817 // Save the current value
2818 orgRID = getRouteRID()
2819
2820 // Add another server that supports INFO updates
2821
2822 optsC := DefaultOptions()
2823 optsC.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", srva.ClusterAddr().Port))
2824 srvc := RunServer(optsC)
2825 defer srvc.Shutdown()
2826
2827 checkClusterFormed(t, srva, srvb, srvc)
2828
2829 // Cause a config reload on A
2830 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `"foo"`))
2831 // Check that new route gets created
2832 check(t)
2833 }
2834
2835 func TestConfigReloadAccountUsers(t *testing.T) {
2836 conf := createConfFile(t, []byte(`
2837 listen: "127.0.0.1:-1"
2838 accounts {
2839 synadia {
2840 users = [
2841 {user: derek, password: derek}
2842 {user: foo, password: foo}
2843 ]
2844 }
2845 nats.io {
2846 users = [
2847 {user: ivan, password: ivan}
2848 {user: bar, password: bar}
2849 ]
2850 }
2851 acc_deleted_after_reload {
2852 users = [
2853 {user: gone, password: soon}
2854 {user: baz, password: baz}
2855 {user: bat, password: bat}
2856 ]
2857 }
2858 }
2859 `))
2860 s, opts := RunServerWithConfig(conf)
2861 defer s.Shutdown()
2862
2863 // Connect as exisiting users, should work.
2864 nc, err := nats.Connect(fmt.Sprintf("nats://derek:derek@%s:%d", opts.Host, opts.Port))
2865 if err != nil {
2866 t.Fatalf("Error on connect: %v", err)
2867 }
2868 defer nc.Close()
2869 ch := make(chan bool, 2)
2870 cb := func(_ *nats.Conn) {
2871 ch <- true
2872 }
2873 nc2, err := nats.Connect(
2874 fmt.Sprintf("nats://ivan:ivan@%s:%d", opts.Host, opts.Port),
2875 nats.NoReconnect(),
2876 nats.ClosedHandler(cb))
2877 if err != nil {
2878 t.Fatalf("Error on connect: %v", err)
2879 }
2880 defer nc2.Close()
2881 nc3, err := nats.Connect(
2882 fmt.Sprintf("nats://gone:soon@%s:%d", opts.Host, opts.Port),
2883 nats.NoReconnect(),
2884 nats.ClosedHandler(cb))
2885 if err != nil {
2886 t.Fatalf("Error on connect: %v", err)
2887 }
2888 defer nc3.Close()
2889 // These users will be moved from an account to another (to a specific or to global account)
2890 // We will create subscriptions to ensure that they are moved to proper sublists too.
2891 rch := make(chan bool, 4)
2892 rcb := func(_ *nats.Conn) {
2893 rch <- true
2894 }
2895 nc4, err := nats.Connect(fmt.Sprintf("nats://foo:foo@%s:%d", opts.Host, opts.Port),
2896 nats.ReconnectWait(50*time.Millisecond), nats.ReconnectHandler(rcb))
2897 if err != nil {
2898 t.Fatalf("Error on connect: %v", err)
2899 }
2900 defer nc4.Close()
2901 if _, err := nc4.SubscribeSync("foo"); err != nil {
2902 t.Fatalf("Error on subscribe: %v", err)
2903 }
2904 nc5, err := nats.Connect(fmt.Sprintf("nats://bar:bar@%s:%d", opts.Host, opts.Port),
2905 nats.ReconnectWait(50*time.Millisecond), nats.ReconnectHandler(rcb))
2906 if err != nil {
2907 t.Fatalf("Error on connect: %v", err)
2908 }
2909 defer nc5.Close()
2910 if _, err := nc5.SubscribeSync("bar"); err != nil {
2911 t.Fatalf("Error on subscribe: %v", err)
2912 }
2913 nc6, err := nats.Connect(fmt.Sprintf("nats://baz:baz@%s:%d", opts.Host, opts.Port),
2914 nats.ReconnectWait(50*time.Millisecond), nats.ReconnectHandler(rcb))
2915 if err != nil {
2916 t.Fatalf("Error on connect: %v", err)
2917 }
2918 defer nc6.Close()
2919 if _, err := nc6.SubscribeSync("baz"); err != nil {
2920 t.Fatalf("Error on subscribe: %v", err)
2921 }
2922 nc7, err := nats.Connect(fmt.Sprintf("nats://bat:bat@%s:%d", opts.Host, opts.Port),
2923 nats.ReconnectWait(50*time.Millisecond), nats.ReconnectHandler(rcb))
2924 if err != nil {
2925 t.Fatalf("Error on connect: %v", err)
2926 }
2927 defer nc7.Close()
2928 if _, err := nc7.SubscribeSync("bat"); err != nil {
2929 t.Fatalf("Error on subscribe: %v", err)
2930 }
2931
2932 // confirm subscriptions before and after reload.
2933 var expectedSubs uint32 = 5
2934 sAcc, err := s.LookupAccount("synadia")
2935 require_NoError(t, err)
2936 sAcc.mu.RLock()
2937 n := sAcc.sl.Count()
2938 sAcc.mu.RUnlock()
2939 if n != expectedSubs {
2940 t.Errorf("Synadia account should have %d sub, got %v", expectedSubs, n)
2941 }
2942 nAcc, err := s.LookupAccount("nats.io")
2943 require_NoError(t, err)
2944 nAcc.mu.RLock()
2945 n = nAcc.sl.Count()
2946 nAcc.mu.RUnlock()
2947 if n != expectedSubs {
2948 t.Errorf("Nats.io account should have %d sub, got %v", expectedSubs, n)
2949 }
2950
2951 // Remove user from account and whole account
2952 reloadUpdateConfig(t, s, conf, `
2953 listen: "127.0.0.1:-1"
2954 authorization {
2955 users = [
2956 {user: foo, password: foo}
2957 {user: baz, password: baz}
2958 ]
2959 }
2960 accounts {
2961 synadia {
2962 users = [
2963 {user: derek, password: derek}
2964 {user: bar, password: bar}
2965 ]
2966 }
2967 nats.io {
2968 users = [
2969 {user: bat, password: bat}
2970 ]
2971 }
2972 }
2973 `)
2974 // nc2 and nc3 should be closed
2975 if err := wait(ch); err != nil {
2976 t.Fatal("Did not get the closed callback")
2977 }
2978 if err := wait(ch); err != nil {
2979 t.Fatal("Did not get the closed callback")
2980 }
2981 // And first connection should still be connected
2982 if !nc.IsConnected() {
2983 t.Fatal("First connection should still be connected")
2984 }
2985
2986 // Old account should be gone
2987 if _, err := s.LookupAccount("acc_deleted_after_reload"); err == nil {
2988 t.Fatal("old account should be gone")
2989 }
2990
2991 // Check subscriptions. Since most of the users have been
2992 // moving accounts, make sure we account for the reconnect
2993 for i := 0; i < 4; i++ {
2994 if err := wait(rch); err != nil {
2995 t.Fatal("Did not get the reconnect cb")
2996 }
2997 }
2998 // Still need to do the tests in a checkFor() because clients
2999 // being reconnected does not mean that resent of subscriptions
3000 // has already been processed.
3001 checkFor(t, 2*time.Second, 100*time.Millisecond, func() error {
3002 gAcc, err := s.LookupAccount(globalAccountName)
3003 require_NoError(t, err)
3004 gAcc.mu.RLock()
3005 n := gAcc.sl.Count()
3006 fooMatch := gAcc.sl.Match("foo")
3007 bazMatch := gAcc.sl.Match("baz")
3008 gAcc.mu.RUnlock()
3009 // The number of subscriptions should be 4 ($SYS.REQ.USER.INFO,
3010 // $SYS.REQ.ACCOUNT.PING.CONNZ, $SYS.REQ.ACCOUNT.PING.STATZ,
3011 // $SYS.REQ.SERVER.PING.CONNZ) + 2 (foo and baz)
3012 if n != 6 {
3013 return fmt.Errorf("Global account should have 6 subs, got %v", n)
3014 }
3015 if len(fooMatch.psubs) != 1 {
3016 return fmt.Errorf("Global account should have foo sub")
3017 }
3018 if len(bazMatch.psubs) != 1 {
3019 return fmt.Errorf("Global account should have baz sub")
3020 }
3021
3022 sAcc, err := s.LookupAccount("synadia")
3023 require_NoError(t, err)
3024 sAcc.mu.RLock()
3025 n = sAcc.sl.Count()
3026 barMatch := sAcc.sl.Match("bar")
3027
3028 sAcc.mu.RUnlock()
3029 if n != expectedSubs {
3030 return fmt.Errorf("Synadia account should have %d sub, got %v", expectedSubs, n)
3031 }
3032 if len(barMatch.psubs) != 1 {
3033 return fmt.Errorf("Synadia account should have bar sub")
3034 }
3035
3036 nAcc, err := s.LookupAccount("nats.io")
3037 require_NoError(t, err)
3038 nAcc.mu.RLock()
3039 n = nAcc.sl.Count()
3040 batMatch := nAcc.sl.Match("bat")
3041 nAcc.mu.RUnlock()
3042 if n != expectedSubs {
3043 return fmt.Errorf("Nats.io account should have %d sub, got %v", expectedSubs, n)
3044 }
3045 if len(batMatch.psubs) != 1 {
3046 return fmt.Errorf("Synadia account should have bar sub")
3047 }
3048 return nil
3049 })
3050 }
3051
3052 func TestConfigReloadAccountWithNoChanges(t *testing.T) {
3053 conf := createConfFile(t, []byte(`
3054 listen: "127.0.0.1:-1"
3055 system_account: sys
3056 accounts {
3057 A {
3058 users = [{ user: a }]
3059 }
3060 B {
3061 users = [{ user: b }]
3062 }
3063 C {
3064 users = [{ user: c }]
3065 }
3066 sys {
3067 users = [{ user: sys }]
3068 }
3069 }
3070 `))
3071 s, opts := RunServerWithConfig(conf)
3072 defer s.Shutdown()
3073
3074 ncA, err := nats.Connect(fmt.Sprintf("nats://a:@%s:%d", opts.Host, opts.Port))
3075 if err != nil {
3076 t.Fatalf("Error on connect: %v", err)
3077 }
3078 defer ncA.Close()
3079
3080 // Confirm default service imports are ok.
3081 checkSubs := func(t *testing.T) {
3082 resp, err := ncA.Request("$SYS.REQ.ACCOUNT.PING.CONNZ", nil, time.Second)
3083 if err != nil {
3084 t.Error(err)
3085 }
3086 if resp == nil || !strings.Contains(string(resp.Data), `"num_connections":1`) {
3087 t.Fatal("unexpected data in connz response")
3088 }
3089 resp, err = ncA.Request("$SYS.REQ.SERVER.PING.CONNZ", nil, time.Second)
3090 if err != nil {
3091 t.Error(err)
3092 }
3093 if resp == nil || !strings.Contains(string(resp.Data), `"num_connections":1`) {
3094 t.Fatal("unexpected data in connz response")
3095 }
3096 resp, err = ncA.Request("$SYS.REQ.ACCOUNT.PING.STATZ", nil, time.Second)
3097 if err != nil {
3098 t.Error(err)
3099 }
3100 if resp == nil || !strings.Contains(string(resp.Data), `"conns":1`) {
3101 t.Fatal("unexpected data in connz response")
3102 }
3103 }
3104 checkSubs(t)
3105 before := s.NumSubscriptions()
3106 s.Reload()
3107 after := s.NumSubscriptions()
3108 if before != after {
3109 t.Errorf("Number of subscriptions changed after reload: %d -> %d", before, after)
3110 }
3111
3112 // Confirm this still works after a reload...
3113 checkSubs(t)
3114 before = s.NumSubscriptions()
3115 s.Reload()
3116 after = s.NumSubscriptions()
3117 if before != after {
3118 t.Errorf("Number of subscriptions changed after reload: %d -> %d", before, after)
3119 }
3120
3121 // Do another extra reload just in case.
3122 checkSubs(t)
3123 before = s.NumSubscriptions()
3124 s.Reload()
3125 after = s.NumSubscriptions()
3126 if before != after {
3127 t.Errorf("Number of subscriptions changed after reload: %d -> %d", before, after)
3128 }
3129 }
3130
3131 func TestConfigReloadAccountNKeyUsers(t *testing.T) {
3132 conf := createConfFile(t, []byte(`
3133 listen: "127.0.0.1:-1"
3134 accounts {
3135 synadia {
3136 users = [
3137 # Derek
3138 {nkey : UCNGL4W5QX66CFX6A6DCBVDH5VOHMI7B2UZZU7TXAUQQSI2JPHULCKBR}
3139 ]
3140 }
3141 nats.io {
3142 users = [
3143 # Ivan
3144 {nkey : UDPGQVFIWZ7Q5UH4I5E6DBCZULQS6VTVBG6CYBD7JV3G3N2GMQOMNAUH}
3145 ]
3146 }
3147 }
3148 `))
3149 s, _ := RunServerWithConfig(conf)
3150 defer s.Shutdown()
3151
3152 synadia, _ := s.LookupAccount("synadia")
3153 nats, _ := s.LookupAccount("nats.io")
3154
3155 seed1 := []byte("SUAPM67TC4RHQLKBX55NIQXSMATZDOZK6FNEOSS36CAYA7F7TY66LP4BOM")
3156 seed2 := []byte("SUAIS5JPX4X4GJ7EIIJEQ56DH2GWPYJRPWN5XJEDENJOZHCBLI7SEPUQDE")
3157
3158 kp, _ := nkeys.FromSeed(seed1)
3159 pubKey, _ := kp.PublicKey()
3160
3161 c, cr, l := newClientForServer(s)
3162 defer c.close()
3163 // Check for Nonce
3164 var info nonceInfo
3165 if err := json.Unmarshal([]byte(l[5:]), &info); err != nil {
3166 t.Fatalf("Could not parse INFO json: %v\n", err)
3167 }
3168 if info.Nonce == "" {
3169 t.Fatalf("Expected a non-empty nonce with nkeys defined")
3170 }
3171 sigraw, err := kp.Sign([]byte(info.Nonce))
3172 if err != nil {
3173 t.Fatalf("Failed signing nonce: %v", err)
3174 }
3175 sig := base64.RawURLEncoding.EncodeToString(sigraw)
3176
3177 // PING needed to flush the +OK to us.
3178 cs := fmt.Sprintf("CONNECT {\"nkey\":%q,\"sig\":\"%s\",\"verbose\":true,\"pedantic\":true}\r\nPING\r\n", pubKey, sig)
3179 c.parseAsync(cs)
3180 l, _ = cr.ReadString('\n')
3181 if !strings.HasPrefix(l, "+OK") {
3182 t.Fatalf("Expected an OK, got: %v", l)
3183 }
3184 if c.acc != synadia {
3185 t.Fatalf("Expected the nkey client's account to match 'synadia', got %v", c.acc)
3186 }
3187
3188 // Now nats account nkey user.
3189 kp, _ = nkeys.FromSeed(seed2)
3190 pubKey, _ = kp.PublicKey()
3191
3192 c, cr, l = newClientForServer(s)
3193 defer c.close()
3194 // Check for Nonce
3195 err = json.Unmarshal([]byte(l[5:]), &info)
3196 if err != nil {
3197 t.Fatalf("Could not parse INFO json: %v\n", err)
3198 }
3199 if info.Nonce == "" {
3200 t.Fatalf("Expected a non-empty nonce with nkeys defined")
3201 }
3202 sigraw, err = kp.Sign([]byte(info.Nonce))
3203 if err != nil {
3204 t.Fatalf("Failed signing nonce: %v", err)
3205 }
3206 sig = base64.RawURLEncoding.EncodeToString(sigraw)
3207
3208 // PING needed to flush the +OK to us.
3209 cs = fmt.Sprintf("CONNECT {\"nkey\":%q,\"sig\":\"%s\",\"verbose\":true,\"pedantic\":true}\r\nPING\r\n", pubKey, sig)
3210 c.parseAsync(cs)
3211 l, _ = cr.ReadString('\n')
3212 if !strings.HasPrefix(l, "+OK") {
3213 t.Fatalf("Expected an OK, got: %v", l)
3214 }
3215 if c.acc != nats {
3216 t.Fatalf("Expected the nkey client's account to match 'nats', got %v", c.acc)
3217 }
3218
3219 // Remove user from account and whole account
3220 reloadUpdateConfig(t, s, conf, `
3221 listen: "127.0.0.1:-1"
3222 authorization {
3223 users = [
3224 # Ivan
3225 {nkey : UDPGQVFIWZ7Q5UH4I5E6DBCZULQS6VTVBG6CYBD7JV3G3N2GMQOMNAUH}
3226 ]
3227 }
3228 accounts {
3229 nats.io {
3230 users = [
3231 # Derek
3232 {nkey : UCNGL4W5QX66CFX6A6DCBVDH5VOHMI7B2UZZU7TXAUQQSI2JPHULCKBR}
3233 ]
3234 }
3235 }
3236 `)
3237
3238 s.mu.Lock()
3239 nkeys := s.nkeys
3240 globalAcc := s.gacc
3241 s.mu.Unlock()
3242
3243 if n := len(nkeys); n != 2 {
3244 t.Fatalf("NKeys map should have 2 users, got %v", n)
3245 }
3246 derek := nkeys["UCNGL4W5QX66CFX6A6DCBVDH5VOHMI7B2UZZU7TXAUQQSI2JPHULCKBR"]
3247 if derek == nil {
3248 t.Fatal("NKey for user Derek not found")
3249 }
3250 if derek.Account == nil || derek.Account.Name != "nats.io" {
3251 t.Fatalf("Invalid account for user Derek: %#v", derek.Account)
3252 }
3253 ivan := nkeys["UDPGQVFIWZ7Q5UH4I5E6DBCZULQS6VTVBG6CYBD7JV3G3N2GMQOMNAUH"]
3254 if ivan == nil {
3255 t.Fatal("NKey for user Ivan not found")
3256 }
3257 if ivan.Account != globalAcc {
3258 t.Fatalf("Invalid account for user Ivan: %#v", ivan.Account)
3259 }
3260 if _, err := s.LookupAccount("synadia"); err == nil {
3261 t.Fatal("Account Synadia should have been removed")
3262 }
3263 }
3264
3265 func TestConfigReloadAccountStreamsImportExport(t *testing.T) {
3266 template := `
3267 listen: "127.0.0.1:-1"
3268 accounts {
3269 synadia {
3270 users [{user: derek, password: foo}]
3271 exports = [
3272 {stream: "private.>", accounts: [nats.io]}
3273 {stream: %s}
3274 ]
3275 }
3276 nats.io {
3277 users [
3278 {user: ivan, password: bar, permissions: {subscribe: {deny: %s}}}
3279 ]
3280 imports = [
3281 {stream: {account: "synadia", subject: %s}}
3282 {stream: {account: "synadia", subject: "private.natsio.*"}, prefix: %s}
3283 ]
3284 }
3285 }
3286 no_sys_acc: true
3287 `
3288 // synadia account exports "private.>" to nats.io
3289 // synadia account exports "foo.*"
3290 // user ivan denies subscription on "xxx"
3291 // nats.io account imports "foo.*" from synadia
3292 // nats.io account imports "private.natsio.*" from synadia with prefix "ivan"
3293 conf := createConfFile(t, []byte(fmt.Sprintf(template, `"foo.*"`, `"xxx"`, `"foo.*"`, `"ivan"`)))
3294 s, opts := RunServerWithConfig(conf)
3295 defer s.Shutdown()
3296
3297 derek, err := nats.Connect(fmt.Sprintf("nats://derek:foo@%s:%d", opts.Host, opts.Port))
3298 if err != nil {
3299 t.Fatalf("Error on connect: %v", err)
3300 }
3301 defer derek.Close()
3302 checkClientsCount(t, s, 1)
3303
3304 ch := make(chan bool, 1)
3305 ivan, err := nats.Connect(fmt.Sprintf("nats://ivan:bar@%s:%d", opts.Host, opts.Port),
3306 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
3307 if strings.Contains(strings.ToLower(err.Error()), "permissions violation") {
3308 ch <- true
3309 }
3310 }))
3311 if err != nil {
3312 t.Fatalf("Error on connect: %v", err)
3313 }
3314 defer ivan.Close()
3315 checkClientsCount(t, s, 2)
3316
3317 subscribe := func(t *testing.T, nc *nats.Conn, subj string) *nats.Subscription {
3318 t.Helper()
3319 s, err := nc.SubscribeSync(subj)
3320 if err != nil {
3321 t.Fatalf("Error on subscribe: %v", err)
3322 }
3323 return s
3324 }
3325
3326 subFooBar := subscribe(t, ivan, "foo.bar")
3327 subFooBaz := subscribe(t, ivan, "foo.baz")
3328 subFooBat := subscribe(t, ivan, "foo.bat")
3329 subPriv := subscribe(t, ivan, "ivan.private.natsio.*")
3330 ivan.Flush()
3331
3332 publish := func(t *testing.T, nc *nats.Conn, subj string) {
3333 t.Helper()
3334 if err := nc.Publish(subj, []byte("hello")); err != nil {
3335 t.Fatalf("Error on publish: %v", err)
3336 }
3337 }
3338
3339 nextMsg := func(t *testing.T, sub *nats.Subscription, expected bool) {
3340 t.Helper()
3341 dur := 100 * time.Millisecond
3342 if expected {
3343 dur = time.Second
3344 }
3345 _, err := sub.NextMsg(dur)
3346 if expected && err != nil {
3347 t.Fatalf("Expected a message on %s, got %v", sub.Subject, err)
3348 } else if !expected && err != nats.ErrTimeout {
3349 t.Fatalf("Expected a timeout on %s, got %v", sub.Subject, err)
3350 }
3351 }
3352
3353 // Checks the derek's user sublist for presence of given subject
3354 // interest. Boolean says if interest is expected or not.
3355 checkSublist := func(t *testing.T, subject string, shouldBeThere bool) {
3356 t.Helper()
3357 dcli := s.getClient(1)
3358 dcli.mu.Lock()
3359 r := dcli.acc.sl.Match(subject)
3360 dcli.mu.Unlock()
3361 if shouldBeThere && len(r.psubs) != 1 {
3362 t.Fatalf("%s should have 1 match in derek's sublist, got %v", subject, len(r.psubs))
3363 } else if !shouldBeThere && len(r.psubs) > 0 {
3364 t.Fatalf("%s should not be in derek's sublist", subject)
3365 }
3366 }
3367
3368 // Publish on all subjects and the subs should receive and
3369 // subjects should be in sublist
3370 publish(t, derek, "foo.bar")
3371 nextMsg(t, subFooBar, true)
3372 checkSublist(t, "foo.bar", true)
3373
3374 publish(t, derek, "foo.baz")
3375 nextMsg(t, subFooBaz, true)
3376 checkSublist(t, "foo.baz", true)
3377
3378 publish(t, derek, "foo.bat")
3379 nextMsg(t, subFooBat, true)
3380 checkSublist(t, "foo.bat", true)
3381
3382 publish(t, derek, "private.natsio.foo")
3383 nextMsg(t, subPriv, true)
3384 checkSublist(t, "private.natsio.foo", true)
3385
3386 // Also make sure that intra-account subscription works OK
3387 ivanSub := subscribe(t, ivan, "ivan.sub")
3388 publish(t, ivan, "ivan.sub")
3389 nextMsg(t, ivanSub, true)
3390 derekSub := subscribe(t, derek, "derek.sub")
3391 publish(t, derek, "derek.sub")
3392 nextMsg(t, derekSub, true)
3393
3394 // synadia account exports "private.>" to nats.io
3395 // synadia account exports "foo.*"
3396 // user ivan denies subscription on "foo.bat"
3397 // nats.io account imports "foo.baz" from synadia
3398 // nats.io account imports "private.natsio.*" from synadia with prefix "yyyy"
3399 reloadUpdateConfig(t, s, conf, fmt.Sprintf(template, `"foo.*"`, `"foo.bat"`, `"foo.baz"`, `"yyyy"`))
3400
3401 // Sub on foo.bar should now fail to receive
3402 publish(t, derek, "foo.bar")
3403 nextMsg(t, subFooBar, false)
3404 checkSublist(t, "foo.bar", false)
3405 // But foo.baz should be received
3406 publish(t, derek, "foo.baz")
3407 nextMsg(t, subFooBaz, true)
3408 checkSublist(t, "foo.baz", true)
3409 // Due to permissions, foo.bat should not
3410 publish(t, derek, "foo.bat")
3411 nextMsg(t, subFooBat, false)
3412 checkSublist(t, "foo.bat", false)
3413 // Prefix changed, so should not be received
3414 publish(t, derek, "private.natsio.foo")
3415 nextMsg(t, subPriv, false)
3416 checkSublist(t, "private.natsio.foo", false)
3417
3418 // Wait for client notification of permissions error
3419 if err := wait(ch); err != nil {
3420 t.Fatal("Did not the permissions error")
3421 }
3422
3423 publish(t, ivan, "ivan.sub")
3424 nextMsg(t, ivanSub, true)
3425 publish(t, derek, "derek.sub")
3426 nextMsg(t, derekSub, true)
3427
3428 // Change export so that foo.* is no longer exported
3429 // synadia account exports "private.>" to nats.io
3430 // synadia account exports "xxx"
3431 // user ivan denies subscription on "foo.bat"
3432 // nats.io account imports "xxx" from synadia
3433 // nats.io account imports "private.natsio.*" from synadia with prefix "ivan"
3434 reloadUpdateConfig(t, s, conf, fmt.Sprintf(template, `"xxx"`, `"foo.bat"`, `"xxx"`, `"ivan"`))
3435
3436 publish(t, derek, "foo.bar")
3437 nextMsg(t, subFooBar, false)
3438 checkSublist(t, "foo.bar", false)
3439
3440 publish(t, derek, "foo.baz")
3441 nextMsg(t, subFooBaz, false)
3442 checkSublist(t, "foo.baz", false)
3443
3444 publish(t, derek, "foo.bat")
3445 nextMsg(t, subFooBat, false)
3446 checkSublist(t, "foo.bat", false)
3447
3448 // Prefix changed back, so should receive
3449 publish(t, derek, "private.natsio.foo")
3450 nextMsg(t, subPriv, true)
3451 checkSublist(t, "private.natsio.foo", true)
3452
3453 publish(t, ivan, "ivan.sub")
3454 nextMsg(t, ivanSub, true)
3455 publish(t, derek, "derek.sub")
3456 nextMsg(t, derekSub, true)
3457 }
3458
3459 func TestConfigReloadAccountServicesImportExport(t *testing.T) {
3460 conf := createConfFile(t, []byte(`
3461 listen: "127.0.0.1:-1"
3462 accounts {
3463 synadia {
3464 users [{user: derek, password: foo}]
3465 exports = [
3466 {service: "pub.request"}
3467 {service: "pub.special.request", accounts: [nats.io]}
3468 ]
3469 }
3470 nats.io {
3471 users [{user: ivan, password: bar}]
3472 imports = [
3473 {service: {account: "synadia", subject: "pub.special.request"}, to: "foo"}
3474 {service: {account: "synadia", subject: "pub.request"}, to: "bar"}
3475 ]
3476 }
3477 }
3478 cluster {
3479 name: "abc"
3480 port: -1
3481 }
3482 `))
3483 s, opts := RunServerWithConfig(conf)
3484 defer s.Shutdown()
3485
3486 opts2 := DefaultOptions()
3487 opts2.Cluster.Name = "abc"
3488 opts2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", opts.Cluster.Port))
3489 s2 := RunServer(opts2)
3490 defer s2.Shutdown()
3491
3492 checkClusterFormed(t, s, s2)
3493
3494 derek, err := nats.Connect(fmt.Sprintf("nats://derek:foo@%s:%d", opts.Host, opts.Port))
3495 if err != nil {
3496 t.Fatalf("Error on connect: %v", err)
3497 }
3498 defer derek.Close()
3499 checkClientsCount(t, s, 1)
3500
3501 ivan, err := nats.Connect(fmt.Sprintf("nats://ivan:bar@%s:%d", opts.Host, opts.Port))
3502 if err != nil {
3503 t.Fatalf("Error on connect: %v", err)
3504 }
3505 defer ivan.Close()
3506 checkClientsCount(t, s, 2)
3507
3508 if _, err := derek.Subscribe("pub.special.request", func(m *nats.Msg) {
3509 derek.Publish(m.Reply, []byte("reply1"))
3510 }); err != nil {
3511 t.Fatalf("Error on subscribe: %v", err)
3512 }
3513 if _, err := derek.Subscribe("pub.request", func(m *nats.Msg) {
3514 derek.Publish(m.Reply, []byte("reply2"))
3515 }); err != nil {
3516 t.Fatalf("Error on subscribe: %v", err)
3517 }
3518 if _, err := derek.Subscribe("pub.special.request.new", func(m *nats.Msg) {
3519 derek.Publish(m.Reply, []byte("reply3"))
3520 }); err != nil {
3521 t.Fatalf("Error on subscribe: %v", err)
3522 }
3523 // Also create one that will be used for intra-account communication
3524 if _, err := derek.Subscribe("derek.sub", func(m *nats.Msg) {
3525 derek.Publish(m.Reply, []byte("private"))
3526 }); err != nil {
3527 t.Fatalf("Error on subscribe: %v", err)
3528 }
3529 derek.Flush()
3530
3531 // Create an intra-account sub for ivan too
3532 if _, err := ivan.Subscribe("ivan.sub", func(m *nats.Msg) {
3533 ivan.Publish(m.Reply, []byte("private"))
3534 }); err != nil {
3535 t.Fatalf("Error on subscribe: %v", err)
3536 }
3537 // This subscription is just to make sure that we can update
3538 // route map without locking issues during reload.
3539 natsSubSync(t, ivan, "bar")
3540
3541 req := func(t *testing.T, nc *nats.Conn, subj string, reply string) {
3542 t.Helper()
3543 var timeout time.Duration
3544 if reply != "" {
3545 timeout = time.Second
3546 } else {
3547 timeout = 100 * time.Millisecond
3548 }
3549 msg, err := nc.Request(subj, []byte("request"), timeout)
3550 if reply != "" {
3551 if err != nil {
3552 t.Fatalf("Expected reply %s on subject %s, got %v", reply, subj, err)
3553 }
3554 if string(msg.Data) != reply {
3555 t.Fatalf("Expected reply %s on subject %s, got %s", reply, subj, msg.Data)
3556 }
3557 } else if err != nats.ErrTimeout && err != nats.ErrNoResponders {
3558 t.Fatalf("Expected timeout on subject %s, got %v", subj, err)
3559 }
3560 }
3561
3562 req(t, ivan, "foo", "reply1")
3563 req(t, ivan, "bar", "reply2")
3564 // This not exported/imported, so should timeout
3565 req(t, ivan, "baz", "")
3566
3567 // Check intra-account communication
3568 req(t, ivan, "ivan.sub", "private")
3569 req(t, derek, "derek.sub", "private")
3570
3571 reloadUpdateConfig(t, s, conf, `
3572 listen: "127.0.0.1:-1"
3573 accounts {
3574 synadia {
3575 users [{user: derek, password: foo}]
3576 exports = [
3577 {service: "pub.request"}
3578 {service: "pub.special.request", accounts: [nats.io]}
3579 {service: "pub.special.request.new", accounts: [nats.io]}
3580 ]
3581 }
3582 nats.io {
3583 users [{user: ivan, password: bar}]
3584 imports = [
3585 {service: {account: "synadia", subject: "pub.special.request"}, to: "foo"}
3586 {service: {account: "synadia", subject: "pub.special.request.new"}, to: "baz"}
3587 ]
3588 }
3589 }
3590 cluster {
3591 name: "abc"
3592 port: -1
3593 }
3594 `)
3595 // This still should work
3596 req(t, ivan, "foo", "reply1")
3597 // This should not
3598 req(t, ivan, "bar", "")
3599 // This now should work
3600 req(t, ivan, "baz", "reply3")
3601
3602 // Check intra-account communication
3603 req(t, ivan, "ivan.sub", "private")
3604 req(t, derek, "derek.sub", "private")
3605 }
3606
3607 // As of now, config reload does not support changes for gateways.
3608 // However, ensure that if a gateway is defined, one can still
3609 // do reload as long as we don't change the gateway spec.
3610 func TestConfigReloadNotPreventedByGateways(t *testing.T) {
3611 confTemplate := `
3612 listen: "127.0.0.1:-1"
3613 %s
3614 gateway {
3615 name: "A"
3616 listen: "127.0.0.1:-1"
3617 tls {
3618 cert_file: "configs/certs/server.pem"
3619 key_file: "configs/certs/key.pem"
3620 timeout: %s
3621 }
3622 gateways [
3623 {
3624 name: "B"
3625 url: "nats://localhost:8888"
3626 }
3627 ]
3628 }
3629 no_sys_acc: true
3630 `
3631 conf := createConfFile(t, []byte(fmt.Sprintf(confTemplate, "", "5")))
3632 s, _ := RunServerWithConfig(conf)
3633 defer s.Shutdown()
3634
3635 // Cause reload with adding a param that is supported
3636 reloadUpdateConfig(t, s, conf, fmt.Sprintf(confTemplate, "max_payload: 100000", "5"))
3637
3638 // Now update gateway, should fail to reload.
3639 changeCurrentConfigContentWithNewContent(t, conf, []byte(fmt.Sprintf(confTemplate, "max_payload: 100000", "3")))
3640 if err := s.Reload(); err == nil || !strings.Contains(err.Error(), "not supported for Gateway") {
3641 t.Fatalf("Expected Reload to return a not supported error, got %v", err)
3642 }
3643 }
3644
3645 func TestConfigReloadBoolFlags(t *testing.T) {
3646 defer func() { FlagSnapshot = nil }()
3647
3648 logfile := filepath.Join(t.TempDir(), "logtime.log")
3649 template := `
3650 listen: "127.0.0.1:-1"
3651 logfile: "%s"
3652 %s
3653 `
3654
3655 var opts *Options
3656 var err error
3657
3658 for _, test := range []struct {
3659 name string
3660 content string
3661 cmdLine []string
3662 expected bool
3663 val func() bool
3664 }{
3665 // Logtime
3666 {
3667 "logtime_not_in_config_no_override",
3668 "",
3669 nil,
3670 true,
3671 func() bool { return opts.Logtime },
3672 },
3673 {
3674 "logtime_not_in_config_override_short_true",
3675 "",
3676 []string{"-T"},
3677 true,
3678 func() bool { return opts.Logtime },
3679 },
3680 {
3681 "logtime_not_in_config_override_true",
3682 "",
3683 []string{"-logtime"},
3684 true,
3685 func() bool { return opts.Logtime },
3686 },
3687 {
3688 "logtime_false_in_config_no_override",
3689 "logtime: false",
3690 nil,
3691 false,
3692 func() bool { return opts.Logtime },
3693 },
3694 {
3695 "logtime_false_in_config_override_short_true",
3696 "logtime: false",
3697 []string{"-T"},
3698 true,
3699 func() bool { return opts.Logtime },
3700 },
3701 {
3702 "logtime_false_in_config_override_true",
3703 "logtime: false",
3704 []string{"-logtime"},
3705 true,
3706 func() bool { return opts.Logtime },
3707 },
3708 {
3709 "logtime_true_in_config_no_override",
3710 "logtime: true",
3711 nil,
3712 true,
3713 func() bool { return opts.Logtime },
3714 },
3715 {
3716 "logtime_true_in_config_override_short_false",
3717 "logtime: true",
3718 []string{"-T=false"},
3719 false,
3720 func() bool { return opts.Logtime },
3721 },
3722 {
3723 "logtime_true_in_config_override_false",
3724 "logtime: true",
3725 []string{"-logtime=false"},
3726 false,
3727 func() bool { return opts.Logtime },
3728 },
3729 // Debug
3730 {
3731 "debug_not_in_config_no_override",
3732 "",
3733 nil,
3734 false,
3735 func() bool { return opts.Debug },
3736 },
3737 {
3738 "debug_not_in_config_override_short_true",
3739 "",
3740 []string{"-D"},
3741 true,
3742 func() bool { return opts.Debug },
3743 },
3744 {
3745 "debug_not_in_config_override_true",
3746 "",
3747 []string{"-debug"},
3748 true,
3749 func() bool { return opts.Debug },
3750 },
3751 {
3752 "debug_false_in_config_no_override",
3753 "debug: false",
3754 nil,
3755 false,
3756 func() bool { return opts.Debug },
3757 },
3758 {
3759 "debug_false_in_config_override_short_true",
3760 "debug: false",
3761 []string{"-D"},
3762 true,
3763 func() bool { return opts.Debug },
3764 },
3765 {
3766 "debug_false_in_config_override_true",
3767 "debug: false",
3768 []string{"-debug"},
3769 true,
3770 func() bool { return opts.Debug },
3771 },
3772 {
3773 "debug_true_in_config_no_override",
3774 "debug: true",
3775 nil,
3776 true,
3777 func() bool { return opts.Debug },
3778 },
3779 {
3780 "debug_true_in_config_override_short_false",
3781 "debug: true",
3782 []string{"-D=false"},
3783 false,
3784 func() bool { return opts.Debug },
3785 },
3786 {
3787 "debug_true_in_config_override_false",
3788 "debug: true",
3789 []string{"-debug=false"},
3790 false,
3791 func() bool { return opts.Debug },
3792 },
3793 // Trace
3794 {
3795 "trace_not_in_config_no_override",
3796 "",
3797 nil,
3798 false,
3799 func() bool { return opts.Trace },
3800 },
3801 {
3802 "trace_not_in_config_override_short_true",
3803 "",
3804 []string{"-V"},
3805 true,
3806 func() bool { return opts.Trace },
3807 },
3808 {
3809 "trace_not_in_config_override_true",
3810 "",
3811 []string{"-trace"},
3812 true,
3813 func() bool { return opts.Trace },
3814 },
3815 {
3816 "trace_false_in_config_no_override",
3817 "trace: false",
3818 nil,
3819 false,
3820 func() bool { return opts.Trace },
3821 },
3822 {
3823 "trace_false_in_config_override_short_true",
3824 "trace: false",
3825 []string{"-V"},
3826 true,
3827 func() bool { return opts.Trace },
3828 },
3829 {
3830 "trace_false_in_config_override_true",
3831 "trace: false",
3832 []string{"-trace"},
3833 true,
3834 func() bool { return opts.Trace },
3835 },
3836 {
3837 "trace_true_in_config_no_override",
3838 "trace: true",
3839 nil,
3840 true,
3841 func() bool { return opts.Trace },
3842 },
3843 {
3844 "trace_true_in_config_override_short_false",
3845 "trace: true",
3846 []string{"-V=false"},
3847 false,
3848 func() bool { return opts.Trace },
3849 },
3850 {
3851 "trace_true_in_config_override_false",
3852 "trace: true",
3853 []string{"-trace=false"},
3854 false,
3855 func() bool { return opts.Trace },
3856 },
3857 // Syslog
3858 {
3859 "syslog_not_in_config_no_override",
3860 "",
3861 nil,
3862 false,
3863 func() bool { return opts.Syslog },
3864 },
3865 {
3866 "syslog_not_in_config_override_short_true",
3867 "",
3868 []string{"-s"},
3869 true,
3870 func() bool { return opts.Syslog },
3871 },
3872 {
3873 "syslog_not_in_config_override_true",
3874 "",
3875 []string{"-syslog"},
3876 true,
3877 func() bool { return opts.Syslog },
3878 },
3879 {
3880 "syslog_false_in_config_no_override",
3881 "syslog: false",
3882 nil,
3883 false,
3884 func() bool { return opts.Syslog },
3885 },
3886 {
3887 "syslog_false_in_config_override_short_true",
3888 "syslog: false",
3889 []string{"-s"},
3890 true,
3891 func() bool { return opts.Syslog },
3892 },
3893 {
3894 "syslog_false_in_config_override_true",
3895 "syslog: false",
3896 []string{"-syslog"},
3897 true,
3898 func() bool { return opts.Syslog },
3899 },
3900 {
3901 "syslog_true_in_config_no_override",
3902 "syslog: true",
3903 nil,
3904 true,
3905 func() bool { return opts.Syslog },
3906 },
3907 {
3908 "syslog_true_in_config_override_short_false",
3909 "syslog: true",
3910 []string{"-s=false"},
3911 false,
3912 func() bool { return opts.Syslog },
3913 },
3914 {
3915 "syslog_true_in_config_override_false",
3916 "syslog: true",
3917 []string{"-syslog=false"},
3918 false,
3919 func() bool { return opts.Syslog },
3920 },
3921 // Cluster.NoAdvertise
3922 {
3923 "cluster_no_advertise_not_in_config_no_override",
3924 `cluster {
3925 port: -1
3926 }`,
3927 nil,
3928 false,
3929 func() bool { return opts.Cluster.NoAdvertise },
3930 },
3931 {
3932 "cluster_no_advertise_not_in_config_override_true",
3933 `cluster {
3934 port: -1
3935 }`,
3936 []string{"-no_advertise"},
3937 true,
3938 func() bool { return opts.Cluster.NoAdvertise },
3939 },
3940 {
3941 "cluster_no_advertise_false_in_config_no_override",
3942 `cluster {
3943 port: -1
3944 no_advertise: false
3945 }`,
3946 nil,
3947 false,
3948 func() bool { return opts.Cluster.NoAdvertise },
3949 },
3950 {
3951 "cluster_no_advertise_false_in_config_override_true",
3952 `cluster {
3953 port: -1
3954 no_advertise: false
3955 }`,
3956 []string{"-no_advertise"},
3957 true,
3958 func() bool { return opts.Cluster.NoAdvertise },
3959 },
3960 {
3961 "cluster_no_advertise_true_in_config_no_override",
3962 `cluster {
3963 port: -1
3964 no_advertise: true
3965 }`,
3966 nil,
3967 true,
3968 func() bool { return opts.Cluster.NoAdvertise },
3969 },
3970 {
3971 "cluster_no_advertise_true_in_config_override_false",
3972 `cluster {
3973 port: -1
3974 no_advertise: true
3975 }`,
3976 []string{"-no_advertise=false"},
3977 false,
3978 func() bool { return opts.Syslog },
3979 },
3980 // -DV override
3981 {
3982 "debug_trace_not_in_config_dv_override_true",
3983 "",
3984 []string{"-DV"},
3985 true,
3986 func() bool { return opts.Debug && opts.Trace },
3987 },
3988 {
3989 "debug_trace_false_in_config_dv_override_true",
3990 `debug: false
3991 trace: false
3992 `,
3993 []string{"-DV"},
3994 true,
3995 func() bool { return opts.Debug && opts.Trace },
3996 },
3997 {
3998 "debug_trace_true_in_config_dv_override_false",
3999 `debug: true
4000 trace: true
4001 `,
4002 []string{"-DV=false"},
4003 false,
4004 func() bool { return opts.Debug && opts.Trace },
4005 },
4006 {
4007 "trace_verbose_true_in_config_override_true",
4008 `trace_verbose: true
4009 `,
4010 nil,
4011 true,
4012 func() bool { return opts.Trace && opts.TraceVerbose },
4013 },
4014 {
4015 "trace_verbose_true_in_config_override_false",
4016 `trace_verbose: true
4017 `,
4018 []string{"--VV=false"},
4019 true,
4020 func() bool { return !opts.TraceVerbose },
4021 },
4022 {
4023 "trace_verbose_true_in_config_override_false",
4024 `trace_verbose: false
4025 `,
4026 []string{"--VV=true"},
4027 true,
4028 func() bool { return opts.TraceVerbose },
4029 },
4030 // --js override
4031 {
4032 "jetstream_not_in_config_no_override",
4033 "",
4034 nil,
4035 false,
4036 func() bool { return opts.JetStream },
4037 },
4038 {
4039 "jetstream_not_in_config_override_true",
4040 "",
4041 []string{"--js"},
4042 true,
4043 func() bool { return opts.JetStream },
4044 },
4045 {
4046 "jetstream_false_in_config_no_override",
4047 "jetstream: false",
4048 nil,
4049 false,
4050 func() bool { return opts.JetStream },
4051 },
4052 {
4053 "jetstream_false_in_config_override_true",
4054 "jetstream: false",
4055 []string{"--js"},
4056 true,
4057 func() bool { return opts.JetStream },
4058 },
4059 {
4060 "jetstream_true_in_config_no_override",
4061 "jetstream: true",
4062 nil,
4063 true,
4064 func() bool { return opts.JetStream },
4065 },
4066 {
4067 "jetstream_true_in_config_override_false",
4068 "jetstream: true",
4069 []string{"--js=false"},
4070 false,
4071 func() bool { return opts.JetStream },
4072 },
4073 } {
4074 t.Run(test.name, func(t *testing.T) {
4075 content := fmt.Sprintf(template, logfile, test.content)
4076 conf := createConfFile(t, []byte(content))
4077
4078 fs := flag.NewFlagSet("test", flag.ContinueOnError)
4079 var args []string
4080 args = append(args, "-c", conf)
4081 if test.cmdLine != nil {
4082 args = append(args, test.cmdLine...)
4083 }
4084 opts, err = ConfigureOptions(fs, args, nil, nil, nil)
4085 if err != nil {
4086 t.Fatalf("Error processing config: %v", err)
4087 }
4088 opts.NoSigs = true
4089 s := RunServer(opts)
4090 defer s.Shutdown()
4091
4092 if test.val() != test.expected {
4093 t.Fatalf("Expected to be set to %v, got %v", test.expected, test.val())
4094 }
4095 // Do a config reload with a modified config file so that s.Reload()
4096 // actually does something (otherwise it would not because config
4097 // digest would not have changed). We could alternatively change
4098 // s.opts.configDigest to the empty string.
4099 reloadUpdateConfig(t, s, conf, content+`
4100 max_connections: 1000
4101 `)
4102 // Have `opts` now point to the new options after the Reload()
4103 opts = s.getOpts()
4104 if test.val() != test.expected {
4105 t.Fatalf("Expected to be set to %v, got %v", test.expected, test.val())
4106 }
4107 })
4108 }
4109 }
4110
4111 func TestConfigReloadMaxControlLineWithClients(t *testing.T) {
4112 server, opts, config := runReloadServerWithConfig(t, "./configs/reload/basic.conf")
4113 defer server.Shutdown()
4114
4115 // Ensure we can connect as a sanity check.
4116 addr := fmt.Sprintf("nats://%s:%d", opts.Host, server.Addr().(*net.TCPAddr).Port)
4117 nc, err := nats.Connect(addr)
4118 if err != nil {
4119 t.Fatalf("Error creating client: %v", err)
4120 }
4121 defer nc.Close()
4122
4123 // Now grab server's internal client that matches.
4124 cid, _ := nc.GetClientID()
4125 c := server.getClient(cid)
4126 if c == nil {
4127 t.Fatalf("Could not look up internal client")
4128 }
4129
4130 // Check that we have the correct mcl snapshotted into the connected client.
4131 getMcl := func(c *client) int32 {
4132 c.mu.Lock()
4133 defer c.mu.Unlock()
4134 return c.mcl
4135 }
4136 if mcl := getMcl(c); mcl != opts.MaxControlLine {
4137 t.Fatalf("Expected snapshot in client for mcl to be same as opts.MaxControlLine, got %d vs %d",
4138 mcl, opts.MaxControlLine)
4139 }
4140
4141 changeCurrentConfigContentWithNewContent(t, config, []byte("listen: 127.0.0.1:-1; max_control_line: 222"))
4142 if err := server.Reload(); err != nil {
4143 t.Fatalf("Expected Reload to succeed, got %v", err)
4144 }
4145
4146 // Refresh properly.
4147 opts = server.getOpts()
4148
4149 if mcl := getMcl(c); mcl != opts.MaxControlLine {
4150 t.Fatalf("Expected snapshot in client for mcl to be same as new opts.MaxControlLine, got %d vs %d",
4151 mcl, opts.MaxControlLine)
4152 }
4153 }
4154
4155 type testCustomAuth struct{}
4156
4157 func (ca *testCustomAuth) Check(c ClientAuthentication) bool { return true }
4158
4159 func TestConfigReloadIgnoreCustomAuth(t *testing.T) {
4160 conf := createConfFile(t, []byte(`
4161 port: -1
4162 `))
4163 opts := LoadConfig(conf)
4164
4165 ca := &testCustomAuth{}
4166 opts.CustomClientAuthentication = ca
4167 opts.CustomRouterAuthentication = ca
4168
4169 s := RunServer(opts)
4170 defer s.Shutdown()
4171
4172 if err := s.Reload(); err != nil {
4173 t.Fatalf("Error during reload: %v", err)
4174 }
4175
4176 if s.getOpts().CustomClientAuthentication != ca || s.getOpts().CustomRouterAuthentication != ca {
4177 t.Fatalf("Custom auth missing")
4178 }
4179 }
4180
4181 func TestConfigReloadLeafNodeRandomPort(t *testing.T) {
4182 conf := createConfFile(t, []byte(`
4183 port: -1
4184 leafnodes {
4185 port: -1
4186 }
4187 `))
4188 s, _ := RunServerWithConfig(conf)
4189 defer s.Shutdown()
4190
4191 s.mu.Lock()
4192 lnPortBefore := s.leafNodeListener.Addr().(*net.TCPAddr).Port
4193 s.mu.Unlock()
4194
4195 if err := s.Reload(); err != nil {
4196 t.Fatalf("Error during reload: %v", err)
4197 }
4198
4199 s.mu.Lock()
4200 lnPortAfter := s.leafNodeListener.Addr().(*net.TCPAddr).Port
4201 s.mu.Unlock()
4202
4203 if lnPortBefore != lnPortAfter {
4204 t.Fatalf("Expected leafnodes listen port to be same, was %v is now %v", lnPortBefore, lnPortAfter)
4205 }
4206 }
4207
4208 func TestConfigReloadLeafNodeWithTLS(t *testing.T) {
4209 template := `
4210 port: -1
4211 %s
4212 leaf {
4213 listen: "127.0.0.1:-1"
4214 tls: {
4215 ca_file: "../test/configs/certs/tlsauth/ca.pem"
4216 cert_file: "../test/configs/certs/tlsauth/server.pem"
4217 key_file: "../test/configs/certs/tlsauth/server-key.pem"
4218 timeout: 3
4219 }
4220 }
4221 `
4222 conf1 := createConfFile(t, []byte(fmt.Sprintf(template, "")))
4223 s1, o1 := RunServerWithConfig(conf1)
4224 defer s1.Shutdown()
4225
4226 u, err := url.Parse(fmt.Sprintf("nats://localhost:%d", o1.LeafNode.Port))
4227 if err != nil {
4228 t.Fatalf("Error creating url: %v", err)
4229 }
4230 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
4231 port: -1
4232 leaf {
4233 remotes [
4234 {
4235 url: "%s"
4236 tls {
4237 ca_file: "../test/configs/certs/tlsauth/ca.pem"
4238 cert_file: "../test/configs/certs/tlsauth/client.pem"
4239 key_file: "../test/configs/certs/tlsauth/client-key.pem"
4240 timeout: 2
4241 }
4242 }
4243 ]
4244 }
4245 `, u.String())))
4246 o2, err := ProcessConfigFile(conf2)
4247 if err != nil {
4248 t.Fatalf("Error processing config file: %v", err)
4249 }
4250 o2.NoLog, o2.NoSigs = true, true
4251 o2.LeafNode.resolver = &testLoopbackResolver{}
4252 s2 := RunServer(o2)
4253 defer s2.Shutdown()
4254
4255 checkFor(t, 3*time.Second, 15*time.Millisecond, func() error {
4256 if n := s1.NumLeafNodes(); n != 1 {
4257 return fmt.Errorf("Expected 1 leaf node, got %v", n)
4258 }
4259 return nil
4260 })
4261
4262 changeCurrentConfigContentWithNewContent(t, conf1, []byte(fmt.Sprintf(template, "debug: false")))
4263
4264 if err := s1.Reload(); err != nil {
4265 t.Fatalf("Error during reload: %v", err)
4266 }
4267 }
4268
4269 func TestConfigReloadLeafNodeWithRemotesNoChanges(t *testing.T) {
4270 template := `
4271 port: -1
4272 cluster {
4273 port: -1
4274 name: "%s"
4275 }
4276 leaf {
4277 remotes [
4278 {
4279 urls: [
4280 "nats://127.0.0.1:1234",
4281 "nats://127.0.0.1:1235",
4282 "nats://127.0.0.1:1236",
4283 "nats://127.0.0.1:1237",
4284 "nats://127.0.0.1:1238",
4285 "nats://127.0.0.1:1239",
4286 ]
4287 }
4288 ]
4289 }
4290 `
4291 config := fmt.Sprintf(template, "A")
4292 conf := createConfFile(t, []byte(config))
4293 o, err := ProcessConfigFile(conf)
4294 if err != nil {
4295 t.Fatalf("Error processing config file: %v", err)
4296 }
4297 o.NoLog, o.NoSigs = true, false
4298 s := RunServer(o)
4299 defer s.Shutdown()
4300
4301 config = fmt.Sprintf(template, "B")
4302 changeCurrentConfigContentWithNewContent(t, conf, []byte(config))
4303
4304 if err := s.Reload(); err != nil {
4305 t.Fatalf("Error during reload: %v", err)
4306 }
4307 }
4308
4309 func TestConfigReloadAndVarz(t *testing.T) {
4310 template := `
4311 port: -1
4312 %s
4313 `
4314 conf := createConfFile(t, []byte(fmt.Sprintf(template, "")))
4315 s, _ := RunServerWithConfig(conf)
4316 defer s.Shutdown()
4317
4318 s.mu.Lock()
4319 initConfigTime := s.configTime
4320 s.mu.Unlock()
4321
4322 v, _ := s.Varz(nil)
4323 if !v.ConfigLoadTime.Equal(initConfigTime) {
4324 t.Fatalf("ConfigLoadTime should be %v, got %v", initConfigTime, v.ConfigLoadTime)
4325 }
4326 if v.MaxConn != DEFAULT_MAX_CONNECTIONS {
4327 t.Fatalf("MaxConn should be %v, got %v", DEFAULT_MAX_CONNECTIONS, v.MaxConn)
4328 }
4329 got := v.ConfigDigest
4330 expected := "sha256:7ea4cc5c6864139d814ce940a40ee6546b7ac5285eec3c390a4ce11e34dc1102"
4331 if got != expected {
4332 t.Fatalf("got: %v, expected: %v", got, expected)
4333 }
4334
4335 changeCurrentConfigContentWithNewContent(t, conf, []byte(fmt.Sprintf(template, "max_connections: 10")))
4336
4337 // Make sure we wait a bit so config load time has a chance to change.
4338 time.Sleep(15 * time.Millisecond)
4339
4340 if err := s.Reload(); err != nil {
4341 t.Fatalf("Error during reload: %v", err)
4342 }
4343
4344 v, _ = s.Varz(nil)
4345 if v.ConfigLoadTime.Equal(initConfigTime) {
4346 t.Fatalf("ConfigLoadTime should be different from %v", initConfigTime)
4347 }
4348 if v.MaxConn != 10 {
4349 t.Fatalf("MaxConn should be 10, got %v", v.MaxConn)
4350 }
4351 got = v.ConfigDigest
4352 expected = "sha256:508a26309068f62c3022aa8951e712ed8ff5dd6f2360f727ad8242a2a233176e"
4353 if got != expected {
4354 t.Fatalf("got: %v, expected: %v", got, expected)
4355 }
4356 }
4357
4358 func TestConfigReloadConnectErrReports(t *testing.T) {
4359 template := `
4360 port: -1
4361 %s
4362 %s
4363 `
4364 conf := createConfFile(t, []byte(fmt.Sprintf(template, "", "")))
4365 s, _ := RunServerWithConfig(conf)
4366 defer s.Shutdown()
4367
4368 opts := s.getOpts()
4369 if cer := opts.ConnectErrorReports; cer != DEFAULT_CONNECT_ERROR_REPORTS {
4370 t.Fatalf("Expected ConnectErrorReports to be %v, got %v", DEFAULT_CONNECT_ERROR_REPORTS, cer)
4371 }
4372 if rer := opts.ReconnectErrorReports; rer != DEFAULT_RECONNECT_ERROR_REPORTS {
4373 t.Fatalf("Expected ReconnectErrorReports to be %v, got %v", DEFAULT_RECONNECT_ERROR_REPORTS, rer)
4374 }
4375
4376 changeCurrentConfigContentWithNewContent(t, conf,
4377 []byte(fmt.Sprintf(template, "connect_error_reports: 2", "reconnect_error_reports: 3")))
4378
4379 if err := s.Reload(); err != nil {
4380 t.Fatalf("Error during reload: %v", err)
4381 }
4382
4383 opts = s.getOpts()
4384 if cer := opts.ConnectErrorReports; cer != 2 {
4385 t.Fatalf("Expected ConnectErrorReports to be %v, got %v", 2, cer)
4386 }
4387 if rer := opts.ReconnectErrorReports; rer != 3 {
4388 t.Fatalf("Expected ReconnectErrorReports to be %v, got %v", 3, rer)
4389 }
4390 }
4391
4392 func TestConfigReloadAuthDoesNotBreakRouteInterest(t *testing.T) {
4393 s, opts := RunServerWithConfig("./configs/seed_tls.conf")
4394 defer s.Shutdown()
4395
4396 // Create client and sub interest on seed server.
4397 urlSeed := fmt.Sprintf("nats://%s:%d/", opts.Host, opts.Port)
4398 nc, err := nats.Connect(urlSeed)
4399 if err != nil {
4400 t.Fatalf("Error creating client: %v\n", err)
4401 }
4402 defer nc.Close()
4403
4404 ch := make(chan bool)
4405 nc.Subscribe("foo", func(m *nats.Msg) { ch <- true })
4406 nc.Flush()
4407
4408 // Use this to check for message.
4409 checkForMsg := func() {
4410 t.Helper()
4411 select {
4412 case <-ch:
4413 case <-time.After(2 * time.Second):
4414 t.Fatal("Timeout waiting for message across route")
4415 }
4416 }
4417
4418 // Create second server and form cluster. We will send from here.
4419 urlRoute := fmt.Sprintf("nats://%s:%d", opts.Cluster.Host, opts.Cluster.Port)
4420 optsA := nextServerOpts(opts)
4421 optsA.Routes = RoutesFromStr(urlRoute)
4422
4423 sa := RunServer(optsA)
4424 defer sa.Shutdown()
4425
4426 checkClusterFormed(t, s, sa)
4427 checkSubInterest(t, sa, globalAccountName, "foo", time.Second)
4428
4429 // Create second client and send message from this one. Interest should be here.
4430 urlA := fmt.Sprintf("nats://%s:%d/", optsA.Host, optsA.Port)
4431 nc2, err := nats.Connect(urlA)
4432 if err != nil {
4433 t.Fatalf("Error creating client: %v\n", err)
4434 }
4435 defer nc2.Close()
4436
4437 // Check that we can send messages.
4438 nc2.Publish("foo", nil)
4439 checkForMsg()
4440
4441 // Now shutdown nc2 and srvA.
4442 nc2.Close()
4443 sa.Shutdown()
4444
4445 // Now force reload on seed server of auth.
4446 s.reloadAuthorization()
4447
4448 // Restart both server A and client 2.
4449 sa = RunServer(optsA)
4450 defer sa.Shutdown()
4451
4452 checkClusterFormed(t, s, sa)
4453 checkSubInterest(t, sa, globalAccountName, "foo", time.Second)
4454
4455 nc2, err = nats.Connect(urlA)
4456 if err != nil {
4457 t.Fatalf("Error creating client: %v\n", err)
4458 }
4459 defer nc2.Close()
4460
4461 // Check that we can still send messages.
4462 nc2.Publish("foo", nil)
4463 checkForMsg()
4464 }
4465
4466 func TestConfigReloadAccountResolverTLSConfig(t *testing.T) {
4467 kp, _ := nkeys.FromSeed(oSeed)
4468 akp, _ := nkeys.CreateAccount()
4469 apub, _ := akp.PublicKey()
4470 nac := jwt.NewAccountClaims(apub)
4471 ajwt, err := nac.Encode(kp)
4472 if err != nil {
4473 t.Fatalf("Error generating account JWT: %v", err)
4474 }
4475 pub, _ := kp.PublicKey()
4476
4477 tc := &TLSConfigOpts{
4478 CertFile: "../test/configs/certs/server-cert.pem",
4479 KeyFile: "../test/configs/certs/server-key.pem",
4480 CaFile: "../test/configs/certs/ca.pem",
4481 }
4482 tlsConfig, err := GenTLSConfig(tc)
4483 if err != nil {
4484 t.Fatalf("Error generating tls config: %v", err)
4485 }
4486 ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
4487 w.Write([]byte(ajwt))
4488 }))
4489 ts.TLS = tlsConfig
4490 ts.StartTLS()
4491 defer ts.Close()
4492 // Set a dummy logger to prevent tls bad certificate output to stderr.
4493 ts.Config.ErrorLog = log.New(&bytes.Buffer{}, "", 0)
4494
4495 confTemplate := `
4496 listen: -1
4497 trusted_keys: %s
4498 resolver: URL("%s/ngs/v1/accounts/jwt/")
4499 %s
4500 `
4501 conf := createConfFile(t, []byte(fmt.Sprintf(confTemplate, pub, ts.URL, `
4502 resolver_tls {
4503 cert_file: "../test/configs/certs/client-cert.pem"
4504 key_file: "../test/configs/certs/client-key.pem"
4505 ca_file: "../test/configs/certs/ca.pem"
4506 }
4507 `)))
4508
4509 s, _ := RunServerWithConfig(conf)
4510 defer s.Shutdown()
4511
4512 changeCurrentConfigContentWithNewContent(t, conf, []byte(fmt.Sprintf(confTemplate, pub, ts.URL, "")))
4513 if err := s.Reload(); err != nil {
4514 t.Fatalf("Error during reload: %v", err)
4515 }
4516
4517 if _, err := s.LookupAccount(apub); err == nil {
4518 t.Fatal("Expected error during lookup, did not get one")
4519 }
4520
4521 changeCurrentConfigContentWithNewContent(t, conf, []byte(fmt.Sprintf(confTemplate, pub, ts.URL, `
4522 resolver_tls {
4523 insecure: true
4524 }
4525 `)))
4526 if err := s.Reload(); err != nil {
4527 t.Fatalf("Error during reload: %v", err)
4528 }
4529
4530 acc, err := s.LookupAccount(apub)
4531 if err != nil {
4532 t.Fatalf("Error during lookup: %v", err)
4533 }
4534 if acc == nil {
4535 t.Fatalf("Expected to receive an account")
4536 }
4537 if acc.Name != apub {
4538 t.Fatalf("Account name did not match claim key")
4539 }
4540 }
4541
4542 func TestConfigReloadLogging(t *testing.T) {
4543 // This test basically starts a server and causes it's configuration to be reloaded 3 times.
4544 // Each time, a new log file is created and trace levels are turned, off - on - off.
4545
4546 // At the end of the test, all 3 log files are inspected for certain traces.
4547 countMatches := func(log []byte, stmts ...string) int {
4548 matchCnt := 0
4549 for _, stmt := range stmts {
4550 if strings.Contains(string(log), stmt) {
4551 matchCnt++
4552 }
4553 }
4554 return matchCnt
4555 }
4556
4557 traces := []string{"[TRC]", "[DBG]", "SYSTEM", "MSG_PAYLOAD", "$SYS.SERVER.ACCOUNT"}
4558
4559 didTrace := func(log []byte) bool {
4560 return countMatches(log, "[INF] Reloaded server configuration") == 1
4561 }
4562
4563 tracingAbsent := func(log []byte) bool {
4564 return countMatches(log, traces...) == 0 && didTrace(log)
4565 }
4566
4567 tracingPresent := func(log []byte) bool {
4568 return len(traces) == countMatches(log, traces...) && didTrace(log)
4569 }
4570
4571 check := func(filename string, valid func([]byte) bool) {
4572 t.Helper()
4573 log, err := os.ReadFile(filename)
4574 if err != nil {
4575 t.Fatalf("Error reading log file %s: %v\n", filename, err)
4576 }
4577 if !valid(log) {
4578 t.Fatalf("%s is not valid: %s", filename, log)
4579 }
4580 //t.Logf("%s contains: %s\n", filename, log)
4581 }
4582
4583 // common configuration setting up system accounts. trace_verbose needs this to cause traces
4584 commonCfg := `
4585 port: -1
4586 system_account: sys
4587 accounts {
4588 sys { users = [ {user: sys, pass: "" } ] }
4589 nats.io: { users = [ { user : bar, pass: "pwd" } ] }
4590 }
4591 `
4592
4593 conf := createConfFile(t, []byte(commonCfg))
4594
4595 defer removeFile(t, "off-pre.log")
4596 defer removeFile(t, "on.log")
4597 defer removeFile(t, "off-post.log")
4598
4599 s, opts := RunServerWithConfig(conf)
4600 defer s.Shutdown()
4601
4602 reload := func(change string) {
4603 t.Helper()
4604 changeCurrentConfigContentWithNewContent(t, conf, []byte(commonCfg+`
4605 `+change+`
4606 `))
4607
4608 if err := s.Reload(); err != nil {
4609 t.Fatalf("Error during reload: %v", err)
4610 }
4611 }
4612
4613 traffic := func(cnt int) {
4614 t.Helper()
4615 // Create client and sub interest on server and create traffic
4616 urlSeed := fmt.Sprintf("nats://bar:pwd@%s:%d/", opts.Host, opts.Port)
4617 nc, err := nats.Connect(urlSeed)
4618 if err != nil {
4619 t.Fatalf("Error creating client: %v\n", err)
4620 }
4621 defer nc.Close()
4622
4623 msgs := make(chan *nats.Msg, 1)
4624 defer close(msgs)
4625
4626 sub, err := nc.ChanSubscribe("foo", msgs)
4627 if err != nil {
4628 t.Fatalf("Error creating subscriber: %v\n", err)
4629 }
4630
4631 nc.Flush()
4632
4633 for i := 0; i < cnt; i++ {
4634 if err := nc.Publish("foo", []byte("bar")); err == nil {
4635 <-msgs
4636 }
4637 }
4638
4639 sub.Unsubscribe()
4640 nc.Close()
4641 }
4642
4643 reload("log_file: off-pre.log")
4644
4645 traffic(10) // generate NO trace/debug entries in off-pre.log
4646
4647 reload(`
4648 log_file: on.log
4649 debug: true
4650 trace_verbose: true
4651 `)
4652
4653 traffic(10) // generate trace/debug entries in on.log
4654
4655 reload(`
4656 log_file: off-post.log
4657 debug: false
4658 trace_verbose: false
4659 `)
4660
4661 traffic(10) // generate trace/debug entries in off-post.log
4662
4663 // check resulting log files for expected content
4664 check("off-pre.log", tracingAbsent)
4665 check("on.log", tracingPresent)
4666 check("off-post.log", tracingAbsent)
4667 }
4668
4669 func TestConfigReloadValidate(t *testing.T) {
4670 confFileName := createConfFile(t, []byte(`
4671 listen: "127.0.0.1:-1"
4672 no_auth_user: a
4673 authorization {
4674 users [
4675 {user: "a", password: "a"},
4676 {user: "b", password: "b"}
4677 ]
4678 }
4679 `))
4680 srv, _ := RunServerWithConfig(confFileName)
4681 defer srv.Shutdown()
4682 // Induce error by removing the user no_auth_user points to
4683 changeCurrentConfigContentWithNewContent(t, confFileName, []byte(`
4684 listen: "127.0.0.1:-1"
4685 no_auth_user: a
4686 authorization {
4687 users [
4688 {user: "b", password: "b"}
4689 ]
4690 }
4691 `))
4692 if err := srv.Reload(); err == nil {
4693 t.Fatal("Expected error on reload, got none")
4694 } else if !strings.HasPrefix(err.Error(), "no_auth_user:") {
4695 t.Logf("Expected no_auth_user error, got different one %s", err)
4696 }
4697 }
4698
4699 func TestConfigReloadAccounts(t *testing.T) {
4700 conf := createConfFile(t, []byte(`
4701 listen: "127.0.0.1:-1"
4702 system_account: SYS
4703 accounts {
4704 SYS {
4705 users = [
4706 {user: sys, password: pwd}
4707 ]
4708 }
4709 ACC {
4710 users = [
4711 {user: usr, password: pwd}
4712 ]
4713 }
4714 acc_deleted_after_reload_will_trigger_reload_of_all_accounts {
4715 users = [
4716 {user: notused, password: soon}
4717 ]
4718 }
4719 }
4720 `))
4721 s, o := RunServerWithConfig(conf)
4722 defer s.Shutdown()
4723
4724 urlSys := fmt.Sprintf("nats://sys:pwd@%s:%d", o.Host, o.Port)
4725 urlUsr := fmt.Sprintf("nats://usr:pwd@%s:%d", o.Host, o.Port)
4726 oldAcci, ok := s.accounts.Load("SYS")
4727 if !ok {
4728 t.Fatal("No SYS account")
4729 }
4730 oldAcc := oldAcci.(*Account)
4731
4732 testSrvState := func(oldAcc *Account) {
4733 t.Helper()
4734 sysAcc := s.SystemAccount()
4735 s.mu.Lock()
4736 defer s.mu.Unlock()
4737 if s.sys == nil || sysAcc == nil {
4738 t.Fatal("Expected sys.account to be non-nil")
4739 }
4740 if sysAcc.Name != "SYS" {
4741 t.Fatal("Found wrong sys.account")
4742 }
4743 if s.opts.SystemAccount != "SYS" {
4744 t.Fatal("Found wrong sys.account")
4745 }
4746 ai, ok := s.accounts.Load(s.opts.SystemAccount)
4747 if !ok {
4748 t.Fatalf("System account %q not found in s.accounts map", s.opts.SystemAccount)
4749 }
4750 acc := ai.(*Account)
4751 if acc != oldAcc {
4752 t.Fatalf("System account pointer was changed during reload, was %p now %p", oldAcc, acc)
4753 }
4754 if s.sys.client == nil {
4755 t.Fatal("Expected sys.client to be non-nil")
4756 }
4757 s.sys.client.mu.Lock()
4758 defer s.sys.client.mu.Unlock()
4759 if s.sys.client.acc.Name != "SYS" {
4760 t.Fatal("Found wrong sys.account")
4761 }
4762 if s.sys.client.echo {
4763 t.Fatal("Internal clients should always have echo false")
4764 }
4765 s.sys.account.mu.Lock()
4766 if _, ok := s.sys.account.clients[s.sys.client]; !ok {
4767 s.sys.account.mu.Unlock()
4768 t.Fatal("internal client not present")
4769 }
4770 s.sys.account.mu.Unlock()
4771 }
4772
4773 // Below tests use connection names so that they can be checked for.
4774 // The test subscribes to ACC only. This avoids receiving own messages.
4775 subscribe := func(name string) (*nats.Conn, *nats.Subscription, *nats.Subscription) {
4776 t.Helper()
4777 c, err := nats.Connect(urlSys, nats.Name(name))
4778 if err != nil {
4779 t.Fatalf("Error on connect: %v", err)
4780 }
4781 subCon, err := c.SubscribeSync("$SYS.ACCOUNT.ACC.CONNECT")
4782 if err != nil {
4783 t.Fatalf("Error on subscribe CONNECT: %v", err)
4784 }
4785 subDis, err := c.SubscribeSync("$SYS.ACCOUNT.ACC.DISCONNECT")
4786 if err != nil {
4787 t.Fatalf("Error on subscribe DISCONNECT: %v", err)
4788 }
4789 c.Flush()
4790 return c, subCon, subDis
4791 }
4792 recv := func(name string, sub *nats.Subscription) {
4793 t.Helper()
4794 if msg, err := sub.NextMsg(1 * time.Second); err != nil {
4795 t.Fatalf("%s Error on next: %v", name, err)
4796 } else {
4797 cMsg := ConnectEventMsg{}
4798 json.Unmarshal(msg.Data, &cMsg)
4799 if cMsg.Client.Name != name {
4800 t.Fatalf("%s wrong message: %s", name, string(msg.Data))
4801 }
4802 }
4803 }
4804 triggerSysEvent := func(name string, subs []*nats.Subscription) {
4805 t.Helper()
4806 ncs1, err := nats.Connect(urlUsr, nats.Name(name))
4807 if err != nil {
4808 t.Fatalf("Error on connect: %v", err)
4809 }
4810 ncs1.Close()
4811 for _, sub := range subs {
4812 recv(name, sub)
4813 // Make sure they are empty.
4814 if pending, _, _ := sub.Pending(); pending != 0 {
4815 t.Fatalf("Expected no pending, got %d for %+v", pending, sub)
4816 }
4817 }
4818 }
4819
4820 testSrvState(oldAcc)
4821 c1, s1C, s1D := subscribe("SYS1")
4822 defer c1.Close()
4823 defer s1C.Unsubscribe()
4824 defer s1D.Unsubscribe()
4825 triggerSysEvent("BEFORE1", []*nats.Subscription{s1C, s1D})
4826 triggerSysEvent("BEFORE2", []*nats.Subscription{s1C, s1D})
4827
4828 // Remove account to trigger account reload
4829 reloadUpdateConfig(t, s, conf, `
4830 listen: "127.0.0.1:-1"
4831 system_account: SYS
4832 accounts {
4833 SYS {
4834 users = [
4835 {user: sys, password: pwd}
4836 ]
4837 }
4838 ACC {
4839 users = [
4840 {user: usr, password: pwd}
4841 ]
4842 }
4843 }
4844 `)
4845
4846 testSrvState(oldAcc)
4847 c2, s2C, s2D := subscribe("SYS2")
4848 defer c2.Close()
4849 defer s2C.Unsubscribe()
4850 defer s2D.Unsubscribe()
4851 // test new and existing subscriptions
4852 triggerSysEvent("AFTER1", []*nats.Subscription{s1C, s1D, s2C, s2D})
4853 triggerSysEvent("AFTER2", []*nats.Subscription{s1C, s1D, s2C, s2D})
4854 }
4855
4856 func TestConfigReloadDefaultSystemAccount(t *testing.T) {
4857 conf := createConfFile(t, []byte(`
4858 listen: "127.0.0.1:-1"
4859 accounts {
4860 ACC {
4861 users = [
4862 {user: usr, password: pwd}
4863 ]
4864 }
4865 }
4866 `))
4867 s, _ := RunServerWithConfig(conf)
4868 defer s.Shutdown()
4869
4870 sysAcc := s.SystemAccount()
4871 if sysAcc == nil {
4872 t.Fatalf("Expected system account to be present")
4873 }
4874 numSubs := sysAcc.TotalSubs()
4875
4876 sname := sysAcc.GetName()
4877 testInAccounts := func() {
4878 t.Helper()
4879 var found bool
4880 s.accounts.Range(func(k, v any) bool {
4881 acc := v.(*Account)
4882 if acc.GetName() == sname {
4883 found = true
4884 return false
4885 }
4886 return true
4887 })
4888 if !found {
4889 t.Fatalf("System account not found in accounts list")
4890 }
4891 }
4892 testInAccounts()
4893
4894 if err := s.Reload(); err != nil {
4895 t.Fatalf("Unexpected error reloading: %v", err)
4896 }
4897
4898 sysAcc = s.SystemAccount()
4899 if sysAcc == nil {
4900 t.Fatalf("Expected system account to still be present")
4901 }
4902 if sysAcc.TotalSubs() != numSubs {
4903 t.Fatalf("Expected %d subs, got %d", numSubs, sysAcc.TotalSubs())
4904 }
4905 testInAccounts()
4906 }
4907
4908 func TestConfigReloadAccountMappings(t *testing.T) {
4909 conf := createConfFile(t, []byte(`
4910 listen: "127.0.0.1:-1"
4911 accounts {
4912 ACC {
4913 users = [{user: usr, password: pwd}]
4914 mappings = { foo: bar }
4915 }
4916 }
4917 `))
4918 s, opts := RunServerWithConfig(conf)
4919 defer s.Shutdown()
4920
4921 reloadUpdateConfig(t, s, conf, `
4922 listen: "127.0.0.1:-1"
4923 accounts {
4924 ACC {
4925 users = [{user: usr, password: pwd}]
4926 mappings = { foo: baz }
4927 }
4928 }
4929 `)
4930
4931 nc := natsConnect(t, fmt.Sprintf("nats://usr:pwd@%s:%d", opts.Host, opts.Port))
4932 defer nc.Close()
4933
4934 fsub, _ := nc.SubscribeSync("foo")
4935 sub, _ := nc.SubscribeSync("baz")
4936 nc.Publish("foo", nil)
4937 nc.Flush()
4938
4939 checkPending := func(sub *nats.Subscription, expected int) {
4940 t.Helper()
4941 if n, _, _ := sub.Pending(); n != expected {
4942 t.Fatalf("Expected %d msgs for %q, but got %d", expected, sub.Subject, n)
4943 }
4944 }
4945 checkPending(fsub, 0)
4946 checkPending(sub, 1)
4947
4948 // Drain it off
4949 if _, err := sub.NextMsg(2 * time.Second); err != nil {
4950 t.Fatalf("Error receiving msg: %v", err)
4951 }
4952
4953 reloadUpdateConfig(t, s, conf, `
4954 listen: "127.0.0.1:-1"
4955 accounts {
4956 ACC {
4957 users = [{user: usr, password: pwd}]
4958 }
4959 }
4960 `)
4961
4962 nc.Publish("foo", nil)
4963 nc.Flush()
4964
4965 checkPending(fsub, 1)
4966 checkPending(sub, 0)
4967 }
4968
4969 func TestConfigReloadWithSysAccountOnly(t *testing.T) {
4970 conf := createConfFile(t, []byte(`
4971 listen: "127.0.0.1:-1"
4972 accounts {
4973 $SYS {
4974 users = [{user: "system",pass: "password"}, {user: "system2",pass: "password2"}]
4975 }
4976 }
4977 `))
4978 defer os.Remove(conf)
4979 s, _ := RunServerWithConfig(conf)
4980 defer s.Shutdown()
4981
4982 dch := make(chan struct{}, 1)
4983 nc := natsConnect(t,
4984 s.ClientURL(),
4985 nats.DisconnectErrHandler(func(_ *nats.Conn, _ error) {
4986 dch <- struct{}{}
4987 }),
4988 nats.NoCallbacksAfterClientClose())
4989 defer nc.Close()
4990
4991 // Just reload...
4992 if err := s.Reload(); err != nil {
4993 t.Fatalf("Error on reload: %v", err)
4994 }
4995
4996 // Make sure we did not get disconnected
4997 select {
4998 case <-dch:
4999 t.Fatal("Got disconnected!")
5000 case <-time.After(500 * time.Millisecond):
5001 // ok
5002 }
5003 }
5004
5005 func TestConfigReloadRouteImportPermissionsWithAccounts(t *testing.T) {
5006 for _, test := range []struct {
5007 name string
5008 poolSize string
5009 accounts string
5010 }{
5011 {"regular", "pool_size: -1", _EMPTY_},
5012 {"pooling", "pool_size: 5", _EMPTY_},
5013 {"per-account", _EMPTY_, "accounts: [\"A\"]"},
5014 {"pool and per-account", "pool_size: 3", "accounts: [\"A\"]"},
5015 } {
5016 t.Run("import "+test.name, func(t *testing.T) {
5017 confATemplate := `
5018 server_name: "A"
5019 port: -1
5020 accounts {
5021 A { users: [{user: "user1", password: "pwd"}] }
5022 B { users: [{user: "user2", password: "pwd"}] }
5023 C { users: [{user: "user3", password: "pwd"}] }
5024 D { users: [{user: "user4", password: "pwd"}] }
5025 }
5026 cluster {
5027 name: "local"
5028 listen: 127.0.0.1:-1
5029 permissions {
5030 import {
5031 allow: %s
5032 }
5033 export {
5034 allow: ">"
5035 }
5036 }
5037 %s
5038 %s
5039 }
5040 `
5041 confA := createConfFile(t, []byte(fmt.Sprintf(confATemplate, `"foo"`, test.poolSize, test.accounts)))
5042 srva, optsA := RunServerWithConfig(confA)
5043 defer srva.Shutdown()
5044
5045 confBTemplate := `
5046 server_name: "B"
5047 port: -1
5048 accounts {
5049 A { users: [{user: "user1", password: "pwd"}] }
5050 B { users: [{user: "user2", password: "pwd"}] }
5051 C { users: [{user: "user3", password: "pwd"}] }
5052 D { users: [{user: "user4", password: "pwd"}] }
5053 }
5054 cluster {
5055 listen: 127.0.0.1:-1
5056 name: "local"
5057 permissions {
5058 import {
5059 allow: %s
5060 }
5061 export {
5062 allow: ">"
5063 }
5064 }
5065 routes = [
5066 "nats://127.0.0.1:%d"
5067 ]
5068 %s
5069 %s
5070 }
5071 `
5072 confB := createConfFile(t, []byte(fmt.Sprintf(confBTemplate, `"foo"`, optsA.Cluster.Port, test.poolSize, test.accounts)))
5073 srvb, _ := RunServerWithConfig(confB)
5074 defer srvb.Shutdown()
5075
5076 checkClusterFormed(t, srva, srvb)
5077
5078 ncA := natsConnect(t, srva.ClientURL(), nats.UserInfo("user1", "pwd"))
5079 defer ncA.Close()
5080
5081 sub1Foo := natsSubSync(t, ncA, "foo")
5082 sub2Foo := natsSubSync(t, ncA, "foo")
5083
5084 sub1Bar := natsSubSync(t, ncA, "bar")
5085 sub2Bar := natsSubSync(t, ncA, "bar")
5086
5087 natsFlush(t, ncA)
5088
5089 checkSubInterest(t, srvb, "A", "foo", 2*time.Second)
5090 checkSubNoInterest(t, srvb, "A", "bar", 2*time.Second)
5091
5092 ncB := natsConnect(t, srvb.ClientURL(), nats.UserInfo("user1", "pwd"))
5093 defer ncB.Close()
5094
5095 check := func(sub *nats.Subscription, expected bool) {
5096 t.Helper()
5097 if expected {
5098 natsNexMsg(t, sub, time.Second)
5099 } else {
5100 if msg, err := sub.NextMsg(50 * time.Millisecond); err == nil {
5101 t.Fatalf("Should not have gotten the message, got %s/%s", msg.Subject, msg.Data)
5102 }
5103 }
5104 }
5105
5106 // Should receive on "foo"
5107 natsPub(t, ncB, "foo", []byte("foo1"))
5108 check(sub1Foo, true)
5109 check(sub2Foo, true)
5110
5111 // But not on "bar"
5112 natsPub(t, ncB, "bar", []byte("bar1"))
5113 check(sub1Bar, false)
5114 check(sub2Bar, false)
5115
5116 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `"bar"`, test.poolSize, test.accounts))
5117 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBTemplate, `"bar"`, optsA.Cluster.Port, test.poolSize, test.accounts))
5118
5119 checkClusterFormed(t, srva, srvb)
5120
5121 checkSubNoInterest(t, srvb, "A", "foo", 2*time.Second)
5122 checkSubInterest(t, srvb, "A", "bar", 2*time.Second)
5123
5124 // Should not receive on foo
5125 natsPub(t, ncB, "foo", []byte("foo2"))
5126 check(sub1Foo, false)
5127 check(sub2Foo, false)
5128
5129 // Should be able to receive on bar
5130 natsPub(t, ncB, "bar", []byte("bar2"))
5131 check(sub1Bar, true)
5132 check(sub2Bar, true)
5133
5134 // Restore "foo"
5135 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `"foo"`, test.poolSize, test.accounts))
5136 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBTemplate, `"foo"`, optsA.Cluster.Port, test.poolSize, test.accounts))
5137
5138 checkClusterFormed(t, srva, srvb)
5139
5140 checkSubInterest(t, srvb, "A", "foo", 2*time.Second)
5141 checkSubNoInterest(t, srvb, "A", "bar", 2*time.Second)
5142
5143 // Should receive on "foo"
5144 natsPub(t, ncB, "foo", []byte("foo3"))
5145 check(sub1Foo, true)
5146 check(sub2Foo, true)
5147 // But make sure there are no more than what we expect
5148 check(sub1Foo, false)
5149 check(sub2Foo, false)
5150
5151 // And now "bar" should fail
5152 natsPub(t, ncB, "bar", []byte("bar3"))
5153 check(sub1Bar, false)
5154 check(sub2Bar, false)
5155 })
5156 }
5157 // Check export now
5158 for _, test := range []struct {
5159 name string
5160 poolSize string
5161 accounts string
5162 }{
5163 {"regular", "pool_size: -1", _EMPTY_},
5164 {"pooling", "pool_size: 5", _EMPTY_},
5165 {"per-account", _EMPTY_, "accounts: [\"A\"]"},
5166 {"pool and per-account", "pool_size: 3", "accounts: [\"A\"]"},
5167 } {
5168 t.Run("export "+test.name, func(t *testing.T) {
5169 confATemplate := `
5170 server_name: "A"
5171 port: -1
5172 accounts {
5173 A { users: [{user: "user1", password: "pwd"}] }
5174 B { users: [{user: "user2", password: "pwd"}] }
5175 C { users: [{user: "user3", password: "pwd"}] }
5176 D { users: [{user: "user4", password: "pwd"}] }
5177 }
5178 cluster {
5179 name: "local"
5180 listen: 127.0.0.1:-1
5181 permissions {
5182 import {
5183 allow: ">"
5184 }
5185 export {
5186 allow: %s
5187 }
5188 }
5189 %s
5190 %s
5191 }
5192 `
5193 confA := createConfFile(t, []byte(fmt.Sprintf(confATemplate, `"foo"`, test.poolSize, test.accounts)))
5194 srva, optsA := RunServerWithConfig(confA)
5195 defer srva.Shutdown()
5196
5197 confBTemplate := `
5198 server_name: "B"
5199 port: -1
5200 accounts {
5201 A { users: [{user: "user1", password: "pwd"}] }
5202 B { users: [{user: "user2", password: "pwd"}] }
5203 C { users: [{user: "user3", password: "pwd"}] }
5204 D { users: [{user: "user4", password: "pwd"}] }
5205 }
5206 cluster {
5207 listen: 127.0.0.1:-1
5208 name: "local"
5209 permissions {
5210 import {
5211 allow: ">"
5212 }
5213 export {
5214 allow: %s
5215 }
5216 }
5217 routes = [
5218 "nats://127.0.0.1:%d"
5219 ]
5220 %s
5221 %s
5222 }
5223 `
5224 confB := createConfFile(t, []byte(fmt.Sprintf(confBTemplate, `"foo"`, optsA.Cluster.Port, test.poolSize, test.accounts)))
5225 srvb, _ := RunServerWithConfig(confB)
5226 defer srvb.Shutdown()
5227
5228 checkClusterFormed(t, srva, srvb)
5229
5230 ncA := natsConnect(t, srva.ClientURL(), nats.UserInfo("user1", "pwd"))
5231 defer ncA.Close()
5232
5233 sub1Foo := natsSubSync(t, ncA, "foo")
5234 sub2Foo := natsSubSync(t, ncA, "foo")
5235
5236 sub1Bar := natsSubSync(t, ncA, "bar")
5237 sub2Bar := natsSubSync(t, ncA, "bar")
5238
5239 natsFlush(t, ncA)
5240
5241 checkSubInterest(t, srvb, "A", "foo", 2*time.Second)
5242 checkSubNoInterest(t, srvb, "A", "bar", 2*time.Second)
5243
5244 ncB := natsConnect(t, srvb.ClientURL(), nats.UserInfo("user1", "pwd"))
5245 defer ncB.Close()
5246
5247 check := func(sub *nats.Subscription, expected bool) {
5248 t.Helper()
5249 if expected {
5250 natsNexMsg(t, sub, time.Second)
5251 } else {
5252 if msg, err := sub.NextMsg(50 * time.Millisecond); err == nil {
5253 t.Fatalf("Should not have gotten the message, got %s/%s", msg.Subject, msg.Data)
5254 }
5255 }
5256 }
5257
5258 // Should receive on "foo"
5259 natsPub(t, ncB, "foo", []byte("foo1"))
5260 check(sub1Foo, true)
5261 check(sub2Foo, true)
5262
5263 // But not on "bar"
5264 natsPub(t, ncB, "bar", []byte("bar1"))
5265 check(sub1Bar, false)
5266 check(sub2Bar, false)
5267
5268 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `["foo", "bar"]`, test.poolSize, test.accounts))
5269 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBTemplate, `["foo", "bar"]`, optsA.Cluster.Port, test.poolSize, test.accounts))
5270
5271 checkClusterFormed(t, srva, srvb)
5272
5273 checkSubInterest(t, srvb, "A", "foo", 2*time.Second)
5274 checkSubInterest(t, srvb, "A", "bar", 2*time.Second)
5275
5276 // Should receive on foo and bar
5277 natsPub(t, ncB, "foo", []byte("foo2"))
5278 check(sub1Foo, true)
5279 check(sub2Foo, true)
5280
5281 natsPub(t, ncB, "bar", []byte("bar2"))
5282 check(sub1Bar, true)
5283 check(sub2Bar, true)
5284
5285 // Remove "bar"
5286 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, `"foo"`, test.poolSize, test.accounts))
5287 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBTemplate, `"foo"`, optsA.Cluster.Port, test.poolSize, test.accounts))
5288
5289 checkClusterFormed(t, srva, srvb)
5290
5291 checkSubInterest(t, srvb, "A", "foo", 2*time.Second)
5292 checkSubNoInterest(t, srvb, "A", "bar", 2*time.Second)
5293
5294 // Should receive on "foo"
5295 natsPub(t, ncB, "foo", []byte("foo3"))
5296 check(sub1Foo, true)
5297 check(sub2Foo, true)
5298 // But make sure there are no more than what we expect
5299 check(sub1Foo, false)
5300 check(sub2Foo, false)
5301
5302 // And now "bar" should fail
5303 natsPub(t, ncB, "bar", []byte("bar3"))
5304 check(sub1Bar, false)
5305 check(sub2Bar, false)
5306 })
5307 }
5308 }
5309
5310 func TestConfigReloadRoutePoolAndPerAccount(t *testing.T) {
5311 confATemplate := `
5312 port: -1
5313 server_name: "A"
5314 accounts {
5315 A { users: [{user: "user1", password: "pwd"}] }
5316 B { users: [{user: "user2", password: "pwd"}] }
5317 C { users: [{user: "user3", password: "pwd"}] }
5318 D { users: [{user: "user4", password: "pwd"}] }
5319 }
5320 cluster {
5321 name: "local"
5322 listen: 127.0.0.1:-1
5323 %s
5324 %s
5325 }
5326 `
5327 confA := createConfFile(t, []byte(fmt.Sprintf(confATemplate, "pool_size: 3", "accounts: [\"A\"]")))
5328 srva, optsA := RunServerWithConfig(confA)
5329 defer srva.Shutdown()
5330
5331 confBCTemplate := `
5332 port: -1
5333 server_name: "%s"
5334 accounts {
5335 A { users: [{user: "user1", password: "pwd"}] }
5336 B { users: [{user: "user2", password: "pwd"}] }
5337 C { users: [{user: "user3", password: "pwd"}] }
5338 D { users: [{user: "user4", password: "pwd"}] }
5339 }
5340 cluster {
5341 listen: 127.0.0.1:-1
5342 name: "local"
5343 routes = [
5344 "nats://127.0.0.1:%d"
5345 ]
5346 %s
5347 %s
5348 }
5349 `
5350 confB := createConfFile(t, []byte(fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, "pool_size: 3", "accounts: [\"A\"]")))
5351 srvb, _ := RunServerWithConfig(confB)
5352 defer srvb.Shutdown()
5353 confC := createConfFile(t, []byte(fmt.Sprintf(confBCTemplate, "C", optsA.Cluster.Port, "pool_size: 3", "accounts: [\"A\"]")))
5354 srvc, _ := RunServerWithConfig(confC)
5355 defer srvc.Shutdown()
5356
5357 checkClusterFormed(t, srva, srvb, srvc)
5358
5359 // We will also create subscriptions for accounts A, B and C on all sides
5360 // just to make sure that interest is properly propagated after a reload.
5361 // The conns slices will contain connections for accounts A on srva, srvb,
5362 // srvc, then B on srva, srvb, etc.. and the subs slices will contain
5363 // subscriptions for account A on foo on srva, bar on srvb, baz on srvc,
5364 // then for account B on foo on srva, etc...
5365 var conns []*nats.Conn
5366 var subs []*nats.Subscription
5367 for _, user := range []string{"user1", "user2", "user3"} {
5368 nc := natsConnect(t, srva.ClientURL(), nats.UserInfo(user, "pwd"))
5369 defer nc.Close()
5370 conns = append(conns, nc)
5371 sub := natsSubSync(t, nc, "foo")
5372 subs = append(subs, sub)
5373 nc = natsConnect(t, srvb.ClientURL(), nats.UserInfo(user, "pwd"))
5374 defer nc.Close()
5375 conns = append(conns, nc)
5376 sub = natsSubSync(t, nc, "bar")
5377 subs = append(subs, sub)
5378 nc = natsConnect(t, srvc.ClientURL(), nats.UserInfo(user, "pwd"))
5379 defer nc.Close()
5380 conns = append(conns, nc)
5381 sub = natsSubSync(t, nc, "baz")
5382 subs = append(subs, sub)
5383 }
5384
5385 checkCluster := func() {
5386 t.Helper()
5387 checkClusterFormed(t, srva, srvb, srvc)
5388
5389 for _, acc := range []string{"A", "B", "C"} {
5390 // On server A, there should be interest for bar/baz
5391 checkSubInterest(t, srva, acc, "bar", 2*time.Second)
5392 checkSubInterest(t, srva, acc, "baz", 2*time.Second)
5393 // On serer B, there should be interest on foo/baz
5394 checkSubInterest(t, srvb, acc, "foo", 2*time.Second)
5395 checkSubInterest(t, srvb, acc, "baz", 2*time.Second)
5396 // And on server C, interest on foo/bar
5397 checkSubInterest(t, srvc, acc, "foo", 2*time.Second)
5398 checkSubInterest(t, srvc, acc, "bar", 2*time.Second)
5399 }
5400 }
5401 checkCluster()
5402
5403 getAccRouteID := func(acc string) uint64 {
5404 s := srva
5405 var id uint64
5406 srvbId := srvb.ID()
5407 s.mu.RLock()
5408 if remotes, ok := s.accRoutes[acc]; ok {
5409 // For this test, we will take a single remote, say srvb
5410 if r := remotes[srvbId]; r != nil {
5411 r.mu.Lock()
5412 if string(r.route.accName) == acc {
5413 id = r.cid
5414 }
5415 r.mu.Unlock()
5416 }
5417 }
5418 s.mu.RUnlock()
5419 return id
5420 }
5421 // Capture the route for account "A"
5422 raid := getAccRouteID("A")
5423 if raid == 0 {
5424 t.Fatal("Did not find route for account A")
5425 }
5426
5427 getRouteIDForAcc := func(acc string) uint64 {
5428 s := srva
5429 a, _ := s.LookupAccount(acc)
5430 if a == nil {
5431 return 0
5432 }
5433 a.mu.RLock()
5434 pidx := a.routePoolIdx
5435 a.mu.RUnlock()
5436 var id uint64
5437 s.mu.RLock()
5438 // For this test, we will take a single remote, say srvb
5439 srvbId := srvb.ID()
5440 if conns, ok := s.routes[srvbId]; ok {
5441 if r := conns[pidx]; r != nil {
5442 r.mu.Lock()
5443 id = r.cid
5444 r.mu.Unlock()
5445 }
5446 }
5447 s.mu.RUnlock()
5448 return id
5449 }
5450 rbid := getRouteIDForAcc("B")
5451 if rbid == 0 {
5452 t.Fatal("Did not find route for account B")
5453 }
5454 rcid := getRouteIDForAcc("C")
5455 if rcid == 0 {
5456 t.Fatal("Did not find route for account C")
5457 }
5458 rdid := getRouteIDForAcc("D")
5459 if rdid == 0 {
5460 t.Fatal("Did not find route for account D")
5461 }
5462
5463 sendAndRecv := func(msg string) {
5464 t.Helper()
5465 for accIdx := 0; accIdx < 9; accIdx += 3 {
5466 natsPub(t, conns[accIdx], "bar", []byte(msg))
5467 m := natsNexMsg(t, subs[accIdx+1], time.Second)
5468 checkMsg := func(m *nats.Msg, subj string) {
5469 t.Helper()
5470 if string(m.Data) != msg {
5471 t.Fatalf("For accIdx=%v, subject %q, expected message %q, got %q", accIdx, subj, msg, m.Data)
5472 }
5473 }
5474 checkMsg(m, "bar")
5475 natsPub(t, conns[accIdx+1], "baz", []byte(msg))
5476 m = natsNexMsg(t, subs[accIdx+2], time.Second)
5477 checkMsg(m, "baz")
5478 natsPub(t, conns[accIdx+2], "foo", []byte(msg))
5479 m = natsNexMsg(t, subs[accIdx], time.Second)
5480 checkMsg(m, "foo")
5481 }
5482 }
5483 sendAndRecv("0")
5484
5485 // Now add accounts "B" and "D" and do a config reload.
5486 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, "pool_size: 3", "accounts: [\"A\",\"B\",\"D\"]"))
5487
5488 // reloadClusterPoolAndAccounts must not let srva's Reload() return until the
5489 // remotes have confirmed they processed the per-account route additions.
5490 for _, s := range []*Server{srvb, srvc} {
5491 for _, acc := range []string{"B", "D"} {
5492 s.mu.RLock()
5493 _, hasRoute := s.accRoutes[acc]
5494 a, found := s.accounts.Load(acc)
5495 s.mu.RUnlock()
5496 if !hasRoute {
5497 t.Fatalf("%s.Reload() returned before remote %s set up the per-account route for %q; the route confirmation wait was skipped", srva, s, acc)
5498 }
5499 if !found {
5500 t.Fatalf("Remote %s does not know account %q", s, acc)
5501 }
5502 acc := a.(*Account)
5503 acc.mu.RLock()
5504 rpi := acc.routePoolIdx
5505 acc.mu.RUnlock()
5506 if rpi != accTransitioningToDedicatedRoute {
5507 t.Fatalf("%s.Reload() returned before remote %s marked account %q transitioning (routePoolIdx=%d); the route confirmation wait was skipped", srva, s, acc.Name, rpi)
5508 }
5509 }
5510 }
5511
5512 // Even before reloading srvb and srvc, we should already have per-account
5513 // routes for accounts B and D being established. The accounts routePoolIdx
5514 // should be marked as transitioning.
5515 checkAccPoolIdx := func(s *Server, acc string, expected int) {
5516 t.Helper()
5517 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
5518 s.mu.RLock()
5519 defer s.mu.RUnlock()
5520 if a, ok := s.accounts.Load(acc); ok {
5521 acc := a.(*Account)
5522 acc.mu.RLock()
5523 rpi := acc.routePoolIdx
5524 acc.mu.RUnlock()
5525 if rpi != expected {
5526 return fmt.Errorf("Server %q - Account %q routePoolIdx should be %v, but is %v", s, acc, expected, rpi)
5527 }
5528 return nil
5529 }
5530 return fmt.Errorf("Server %q - Account %q not found", s, acc)
5531 })
5532 }
5533 checkRoutePerAccAlreadyEstablished := func(s *Server, acc string) {
5534 t.Helper()
5535 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
5536 s.mu.RLock()
5537 defer s.mu.RUnlock()
5538 if _, ok := s.accRoutes[acc]; !ok {
5539 return fmt.Errorf("Route for account %q still not established", acc)
5540 }
5541 return nil
5542 })
5543 checkAccPoolIdx(s, acc, accTransitioningToDedicatedRoute)
5544 }
5545 // Check srvb and srvc for both accounts.
5546 for _, s := range []*Server{srvb, srvc} {
5547 for _, acc := range []string{"B", "D"} {
5548 checkRoutePerAccAlreadyEstablished(s, acc)
5549 }
5550 }
5551 // On srva, the accounts should already have their routePoolIdx set to
5552 // the accDedicatedRoute value.
5553 for _, acc := range []string{"B", "D"} {
5554 checkAccPoolIdx(srva, acc, accDedicatedRoute)
5555 }
5556 // Now reload the other servers
5557 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, "pool_size: 3", "accounts: [\"A\",\"B\",\"D\"]"))
5558 reloadUpdateConfig(t, srvc, confC, fmt.Sprintf(confBCTemplate, "C", optsA.Cluster.Port, "pool_size: 3", "accounts: [\"A\",\"B\",\"D\"]"))
5559
5560 checkCluster()
5561 // Now check that the accounts B and D are no longer transitioning
5562 for _, s := range []*Server{srva, srvb, srvc} {
5563 for _, acc := range []string{"B", "D"} {
5564 checkAccPoolIdx(s, acc, accDedicatedRoute)
5565 }
5566 }
5567
5568 checkRouteForADidNotChange := func() {
5569 t.Helper()
5570 if id := getAccRouteID("A"); id != raid {
5571 t.Fatalf("Route id for account 'A' was %d, is now %d", raid, id)
5572 }
5573 }
5574 // Verify that the route for account "A" did not change.
5575 checkRouteForADidNotChange()
5576
5577 // Verify that account "B" has now its own route
5578 if id := getAccRouteID("B"); id == 0 {
5579 t.Fatal("Did not find route for account B")
5580 }
5581 // Same for "D".
5582 if id := getAccRouteID("D"); id == 0 {
5583 t.Fatal("Did not find route for account D")
5584 }
5585
5586 checkRouteStillPresent := func(id uint64) {
5587 t.Helper()
5588 srva.mu.RLock()
5589 defer srva.mu.RUnlock()
5590 srvbId := srvb.ID()
5591 for _, r := range srva.routes[srvbId] {
5592 if r != nil {
5593 r.mu.Lock()
5594 found := r.cid == id
5595 r.mu.Unlock()
5596 if found {
5597 return
5598 }
5599 }
5600 }
5601 t.Fatalf("Route id %v has been disconnected", id)
5602 }
5603 // Verify that routes that were dealing with "B", and "D" were not disconnected.
5604 // Of course, since "C" was not involved, that route should still be present too.
5605 checkRouteStillPresent(rbid)
5606 checkRouteStillPresent(rcid)
5607 checkRouteStillPresent(rdid)
5608
5609 sendAndRecv("1")
5610
5611 // Now remove "B" and "D" and verify that route for "A" did not change.
5612 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, "pool_size: 3", "accounts: [\"A\"]"))
5613 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, "pool_size: 3", "accounts: [\"A\"]"))
5614 reloadUpdateConfig(t, srvc, confC, fmt.Sprintf(confBCTemplate, "C", optsA.Cluster.Port, "pool_size: 3", "accounts: [\"A\"]"))
5615
5616 checkCluster()
5617
5618 // Verify that the route for account "A" did not change.
5619 checkRouteForADidNotChange()
5620
5621 // Verify that there is no dedicated route for account "B"
5622 if id := getAccRouteID("B"); id != 0 {
5623 t.Fatal("Should not have found a route for account B")
5624 }
5625 // It should instead be in one of the pooled route, and same
5626 // than it was before.
5627 if id := getRouteIDForAcc("B"); id != rbid {
5628 t.Fatalf("Account B's route was %d, it is now %d", rbid, id)
5629 }
5630 // Same for "D"
5631 if id := getAccRouteID("D"); id != 0 {
5632 t.Fatal("Should not have found a route for account D")
5633 }
5634 if id := getRouteIDForAcc("D"); id != rdid {
5635 t.Fatalf("Account D's route was %d, it is now %d", rdid, id)
5636 }
5637
5638 sendAndRecv("2")
5639
5640 // Finally, change pool size and make sure that routes handling B, C and D
5641 // were disconnected/reconnected, and that A did not change.
5642 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, "pool_size: 5", "accounts: [\"A\"]"))
5643 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, "pool_size: 5", "accounts: [\"A\"]"))
5644 reloadUpdateConfig(t, srvc, confC, fmt.Sprintf(confBCTemplate, "C", optsA.Cluster.Port, "pool_size: 5", "accounts: [\"A\"]"))
5645
5646 checkCluster()
5647
5648 checkRouteForADidNotChange()
5649
5650 checkRouteDisconnected := func(acc string, oldID uint64) {
5651 t.Helper()
5652 if id := getRouteIDForAcc(acc); id == oldID {
5653 t.Fatalf("Route that was handling account %q did not change", acc)
5654 }
5655 }
5656 checkRouteDisconnected("B", rbid)
5657 checkRouteDisconnected("C", rcid)
5658 checkRouteDisconnected("D", rdid)
5659
5660 sendAndRecv("3")
5661
5662 // Now check that there were no duplicates and that all subs have 0 pending messages.
5663 for i, sub := range subs {
5664 if n, _, _ := sub.Pending(); n != 0 {
5665 t.Fatalf("Expected 0 pending messages, got %v for accIdx=%d sub=%q", n, i, sub.Subject)
5666 }
5667 }
5668 }
5669
5670 func TestConfigReloadRoutePoolAndPerAccountNoPanicIfFirstAdded(t *testing.T) {
5671 tmpl := `
5672 port: -1
5673 server_name: "%s"
5674 accounts {
5675 A { users: [{user: "user1", password: "pwd"}] }
5676 B { users: [{user: "user2", password: "pwd"}] }
5677 }
5678 cluster {
5679 name: "local"
5680 listen: 127.0.0.1:-1
5681 pool_size: 2
5682 %s
5683 %s
5684 }
5685 no_sys_acc: true
5686 `
5687 conf1 := createConfFile(t, fmt.Appendf(nil, tmpl, "A", _EMPTY_, _EMPTY_))
5688 s1, o1 := RunServerWithConfig(conf1)
5689 defer s1.Shutdown()
5690
5691 route := fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port)
5692 conf2 := createConfFile(t, fmt.Appendf(nil, tmpl, "B", _EMPTY_, route))
5693 s2, _ := RunServerWithConfig(conf2)
5694 defer s2.Shutdown()
5695
5696 checkClusterFormed(t, s1, s2)
5697
5698 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", "accounts:[\"A\"]", _EMPTY_))
5699 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", "accounts:[\"A\"]", route))
5700
5701 time.Sleep(50 * time.Millisecond)
5702 checkClusterFormed(t, s1, s2)
5703 }
5704
5705 func TestConfigReloadRoutePoolCannotBeDisabledIfAccountsPresent(t *testing.T) {
5706 tmpl := `
5707 port: -1
5708 server_name: "%s"
5709 accounts {
5710 A { users: [{user: "user1", password: "pwd"}] }
5711 B { users: [{user: "user2", password: "pwd"}] }
5712 }
5713 cluster {
5714 name: "local"
5715 listen: 127.0.0.1:-1
5716 %s
5717 %s
5718 %s
5719 }
5720 `
5721 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "A", "accounts: [\"A\"]", _EMPTY_, _EMPTY_)))
5722 s1, o1 := RunServerWithConfig(conf1)
5723 defer s1.Shutdown()
5724
5725 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "B", "accounts: [\"A\"]", _EMPTY_,
5726 fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port))))
5727 s2, _ := RunServerWithConfig(conf2)
5728 defer s2.Shutdown()
5729
5730 checkClusterFormed(t, s1, s2)
5731
5732 err := os.WriteFile(conf1, []byte(fmt.Sprintf(tmpl, "A", "accounts: [\"A\"]", "pool_size: -1", _EMPTY_)), 0666)
5733 require_NoError(t, err)
5734 if err := s1.Reload(); err == nil || !strings.Contains(err.Error(), "accounts") {
5735 t.Fatalf("Expected error regarding presence of accounts, got %v", err)
5736 }
5737
5738 // Now remove the accounts too and reload, this should work
5739 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", _EMPTY_, "pool_size: -1", _EMPTY_))
5740 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", _EMPTY_, "pool_size: -1", fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port)))
5741 checkClusterFormed(t, s1, s2)
5742
5743 ncs2 := natsConnect(t, s2.ClientURL(), nats.UserInfo("user1", "pwd"))
5744 defer ncs2.Close()
5745 sub := natsSubSync(t, ncs2, "foo")
5746 checkSubInterest(t, s1, "A", "foo", time.Second)
5747
5748 ncs1 := natsConnect(t, s1.ClientURL(), nats.UserInfo("user1", "pwd"))
5749 defer ncs1.Close()
5750 natsPub(t, ncs1, "foo", []byte("hello"))
5751 natsNexMsg(t, sub, time.Second)
5752
5753 // Wait a bit and make sure there are no duplicates
5754 time.Sleep(50 * time.Millisecond)
5755 if n, _, _ := sub.Pending(); n != 0 {
5756 t.Fatalf("Expected no pending messages, got %v", n)
5757 }
5758
5759 // Finally, verify that the system account is no longer bound to
5760 // a dedicated route. For that matter, s.accRoutes should be nil.
5761 for _, s := range []*Server{s1, s2} {
5762 sys := s.SystemAccount()
5763 if sys == nil {
5764 t.Fatal("No system account found")
5765 }
5766 sys.mu.RLock()
5767 rpi := sys.routePoolIdx
5768 sys.mu.RUnlock()
5769 if rpi != 0 {
5770 t.Fatalf("Server %q - expected account's routePoolIdx to be 0, got %v", s, rpi)
5771 }
5772 s.mu.RLock()
5773 arNil := s.accRoutes == nil
5774 s.mu.RUnlock()
5775 if !arNil {
5776 t.Fatalf("Server %q - accRoutes expected to be nil, it was not", s)
5777 }
5778 }
5779 }
5780
5781 func TestConfigReloadRoutePoolAndPerAccountWithOlderServer(t *testing.T) {
5782 confATemplate := `
5783 port: -1
5784 server_name: "A"
5785 accounts {
5786 A { users: [{user: "user1", password: "pwd"}] }
5787 }
5788 cluster {
5789 name: "local"
5790 listen: 127.0.0.1:-1
5791 %s
5792 %s
5793 }
5794 `
5795 confA := createConfFile(t, []byte(fmt.Sprintf(confATemplate, "pool_size: 3", _EMPTY_)))
5796 srva, optsA := RunServerWithConfig(confA)
5797 defer srva.Shutdown()
5798
5799 confBCTemplate := `
5800 port: -1
5801 server_name: "%s"
5802 accounts {
5803 A { users: [{user: "user1", password: "pwd"}] }
5804 }
5805 cluster {
5806 listen: 127.0.0.1:-1
5807 name: "local"
5808 routes = [
5809 "nats://127.0.0.1:%d"
5810 ]
5811 %s
5812 %s
5813 }
5814 `
5815 confB := createConfFile(t, []byte(fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, "pool_size: 3", _EMPTY_)))
5816 srvb, _ := RunServerWithConfig(confB)
5817 defer srvb.Shutdown()
5818 confC := createConfFile(t, []byte(fmt.Sprintf(confBCTemplate, "C", optsA.Cluster.Port, "pool_size: -1", _EMPTY_)))
5819 srvc, _ := RunServerWithConfig(confC)
5820 defer srvc.Shutdown()
5821
5822 checkClusterFormed(t, srva, srvb, srvc)
5823
5824 // Create a connection and sub on B and C
5825 ncB := natsConnect(t, srvb.ClientURL(), nats.UserInfo("user1", "pwd"))
5826 defer ncB.Close()
5827 subB := natsSubSync(t, ncB, "foo")
5828
5829 ncC := natsConnect(t, srvc.ClientURL(), nats.UserInfo("user1", "pwd"))
5830 defer ncC.Close()
5831 subC := natsSubSync(t, ncC, "bar")
5832
5833 // Check that on server B, there is interest on "bar" for account A
5834 // (coming from server C), and on server C, there is interest on "foo"
5835 // for account A (coming from server B).
5836 checkCluster := func() {
5837 t.Helper()
5838 checkClusterFormed(t, srva, srvb, srvc)
5839 checkSubInterest(t, srvb, "A", "bar", 2*time.Second)
5840 checkSubInterest(t, srvc, "A", "foo", 2*time.Second)
5841 }
5842 checkCluster()
5843
5844 sendAndRecv := func(msg string) {
5845 t.Helper()
5846 natsPub(t, ncB, "bar", []byte(msg))
5847 if m := natsNexMsg(t, subC, time.Second); string(m.Data) != msg {
5848 t.Fatalf("Expected message %q on %q, got %q", msg, "bar", m.Data)
5849 }
5850 natsPub(t, ncC, "foo", []byte(msg))
5851 if m := natsNexMsg(t, subB, time.Second); string(m.Data) != msg {
5852 t.Fatalf("Expected message %q on %q, got %q", msg, "foo", m.Data)
5853 }
5854 }
5855 sendAndRecv("0")
5856
5857 // Now add account "A" and do a config reload. We do this only on
5858 // server srva and srb since server C really does not change.
5859 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, "pool_size: 3", "accounts: [\"A\"]"))
5860 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, "pool_size: 3", "accounts: [\"A\"]"))
5861 checkCluster()
5862 sendAndRecv("1")
5863
5864 // Remove "A" from the accounts list
5865 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, "pool_size: 3", _EMPTY_))
5866 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, "pool_size: 3", _EMPTY_))
5867 checkCluster()
5868 sendAndRecv("2")
5869
5870 // Change the pool size
5871 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, "pool_size: 5", _EMPTY_))
5872 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, "pool_size: 5", _EMPTY_))
5873 checkCluster()
5874 sendAndRecv("3")
5875
5876 // Add account "A" and change the pool size
5877 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, "pool_size: 4", "accounts: [\"A\"]"))
5878 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, "pool_size: 4", "accounts: [\"A\"]"))
5879 checkCluster()
5880 sendAndRecv("4")
5881
5882 // Remove account "A" and change the pool size
5883 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, "pool_size: 3", _EMPTY_))
5884 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, "pool_size: 3", _EMPTY_))
5885 checkCluster()
5886 sendAndRecv("5")
5887 }
5888
5889 func TestConfigReloadRoutePoolAndPerAccountNoDuplicateSub(t *testing.T) {
5890 confATemplate := `
5891 port: -1
5892 server_name: "A"
5893 accounts {
5894 A { users: [{user: "user1", password: "pwd"}] }
5895 }
5896 cluster {
5897 name: "local"
5898 listen: 127.0.0.1:-1
5899 pool_size: 3
5900 %s
5901 }
5902 `
5903 confA := createConfFile(t, []byte(fmt.Sprintf(confATemplate, _EMPTY_)))
5904 srva, optsA := RunServerWithConfig(confA)
5905 defer srva.Shutdown()
5906
5907 confBCTemplate := `
5908 port: -1
5909 server_name: "%s"
5910 accounts {
5911 A { users: [{user: "user1", password: "pwd"}] }
5912 }
5913 cluster {
5914 listen: 127.0.0.1:-1
5915 name: "local"
5916 routes = [
5917 "nats://127.0.0.1:%d"
5918 ]
5919 pool_size: 3
5920 %s
5921 }
5922 `
5923 confB := createConfFile(t, []byte(fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, _EMPTY_)))
5924 srvb, _ := RunServerWithConfig(confB)
5925 defer srvb.Shutdown()
5926 confC := createConfFile(t, []byte(fmt.Sprintf(confBCTemplate, "C", optsA.Cluster.Port, _EMPTY_)))
5927 srvc, _ := RunServerWithConfig(confC)
5928 defer srvc.Shutdown()
5929
5930 checkClusterFormed(t, srva, srvb, srvc)
5931
5932 ncC := natsConnect(t, srvc.ClientURL(), nats.UserInfo("user1", "pwd"))
5933 defer ncC.Close()
5934
5935 ch := make(chan struct{})
5936 wg := sync.WaitGroup{}
5937 wg.Add(1)
5938 var subs []*nats.Subscription
5939 go func() {
5940 defer wg.Done()
5941 // Limit the number of subscriptions. From experimentation, the issue would
5942 // arise around subscriptions ~700.
5943 for i := 0; i < 1000; i++ {
5944 if sub, err := ncC.SubscribeSync(fmt.Sprintf("foo.%d", i)); err == nil {
5945 subs = append(subs, sub)
5946 }
5947 select {
5948 case <-ch:
5949 return
5950 default:
5951 if i%100 == 0 {
5952 time.Sleep(5 * time.Millisecond)
5953 }
5954 }
5955 }
5956 }()
5957
5958 // Wait a tiny bit before doing the configuration reload.
5959 time.Sleep(100 * time.Millisecond)
5960
5961 reloadUpdateConfig(t, srva, confA, fmt.Sprintf(confATemplate, "accounts: [\"A\"]"))
5962 reloadUpdateConfig(t, srvb, confB, fmt.Sprintf(confBCTemplate, "B", optsA.Cluster.Port, "accounts: [\"A\"]"))
5963 reloadUpdateConfig(t, srvc, confC, fmt.Sprintf(confBCTemplate, "C", optsA.Cluster.Port, "accounts: [\"A\"]"))
5964
5965 checkClusterFormed(t, srva, srvb, srvc)
5966
5967 close(ch)
5968 wg.Wait()
5969
5970 for _, sub := range subs {
5971 checkSubInterest(t, srvb, "A", sub.Subject, 500*time.Millisecond)
5972 }
5973
5974 ncB := natsConnect(t, srvb.ClientURL(), nats.UserInfo("user1", "pwd"))
5975 defer ncB.Close()
5976
5977 for _, sub := range subs {
5978 natsPub(t, ncB, sub.Subject, []byte("hello"))
5979 }
5980
5981 // Now make sure that there is only 1 pending message for each sub.
5982 // Wait a bit to give a chance to duplicate messages to arrive if
5983 // there was a bug that would lead to a sub on each route (the pooled
5984 // and the per-account)
5985 time.Sleep(250 * time.Millisecond)
5986 for _, sub := range subs {
5987 if n, _, _ := sub.Pending(); n != 1 {
5988 t.Fatalf("Expected only 1 message for subscription on %q, got %v", sub.Subject, n)
5989 }
5990 }
5991 }
5992
5993 func TestConfigReloadGlobalAccountWithMappingAndJetStream(t *testing.T) {
5994 tmpl := `
5995 listen: 127.0.0.1:-1
5996 server_name: %s
5997 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
5998
5999 mappings {
6000 subj.orig: subj.mapped.before.reload
6001 }
6002
6003 leaf {
6004 listen: 127.0.0.1:-1
6005 }
6006
6007 cluster {
6008 name: %s
6009 listen: 127.0.0.1:%d
6010 routes = [%s]
6011 }
6012
6013 # For access to system account.
6014 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } }
6015 `
6016 c := createJetStreamClusterWithTemplate(t, tmpl, "R3S", 3)
6017 defer c.shutdown()
6018
6019 nc, js := jsClientConnect(t, c.randomServer())
6020 defer nc.Close()
6021
6022 // Verify that mapping works
6023 checkMapping := func(expectedSubj string) {
6024 t.Helper()
6025 sub := natsSubSync(t, nc, "subj.>")
6026 defer sub.Unsubscribe()
6027 natsPub(t, nc, "subj.orig", nil)
6028 msg := natsNexMsg(t, sub, time.Second)
6029 if msg.Subject != expectedSubj {
6030 t.Fatalf("Expected subject to have been mapped to %q, got %q", expectedSubj, msg.Subject)
6031 }
6032 }
6033 checkMapping("subj.mapped.before.reload")
6034
6035 // Create a stream and check that we can get the INFO
6036 _, err := js.AddStream(&nats.StreamConfig{
6037 Name: "TEST",
6038 Replicas: 3,
6039 Subjects: []string{"foo"},
6040 Retention: nats.InterestPolicy,
6041 })
6042 require_NoError(t, err)
6043 c.waitOnStreamLeader(globalAccountName, "TEST")
6044
6045 _, err = js.StreamInfo("TEST")
6046 require_NoError(t, err)
6047
6048 // Change mapping on all servers and issue reload
6049 for i, s := range c.servers {
6050 opts := c.opts[i]
6051 content, err := os.ReadFile(opts.ConfigFile)
6052 require_NoError(t, err)
6053 reloadUpdateConfig(t, s, opts.ConfigFile, strings.Replace(string(content), "subj.mapped.before.reload", "subj.mapped.after.reload", 1))
6054 }
6055 // Make sure the cluster is still formed
6056 checkClusterFormed(t, c.servers...)
6057 // Now repeat the test for the subject mapping and stream info
6058 checkMapping("subj.mapped.after.reload")
6059 _, err = js.StreamInfo("TEST")
6060 require_NoError(t, err)
6061 }
6062
6063 func TestConfigReloadRouteCompression(t *testing.T) {
6064 org := testDefaultClusterCompression
6065 testDefaultClusterCompression = _EMPTY_
6066 defer func() { testDefaultClusterCompression = org }()
6067
6068 tmpl := `
6069 port: -1
6070 server_name: "%s"
6071 cluster {
6072 port: -1
6073 name: "local"
6074 %s
6075 %s
6076 }
6077 `
6078 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "A", _EMPTY_, _EMPTY_)))
6079 s1, o1 := RunServerWithConfig(conf1)
6080 defer s1.Shutdown()
6081
6082 routes := fmt.Sprintf("routes: [\"nats://127.0.0.1:%d\"]", o1.Cluster.Port)
6083 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "B", routes, _EMPTY_)))
6084 s2, _ := RunServerWithConfig(conf2)
6085 defer s2.Shutdown()
6086
6087 // Run a 3rd server but make it as if it was an old server. We want to
6088 // make sure that reload of s1 and s2 will not affect routes from s3 to
6089 // s1/s2 because these do not support compression.
6090 conf3 := createConfFile(t, []byte(fmt.Sprintf(tmpl, "C", routes, "compression: \"not supported\"")))
6091 s3, _ := RunServerWithConfig(conf3)
6092 defer s3.Shutdown()
6093
6094 checkClusterFormed(t, s1, s2, s3)
6095
6096 // Collect routes' cid from servers so we can check if routes are
6097 // recreated when they should and are not when they should not.
6098 collect := func(s *Server) map[uint64]struct{} {
6099 m := make(map[uint64]struct{})
6100 s.mu.RLock()
6101 defer s.mu.RUnlock()
6102 s.forEachRoute(func(r *client) {
6103 r.mu.Lock()
6104 m[r.cid] = struct{}{}
6105 r.mu.Unlock()
6106 })
6107 return m
6108 }
6109 s1RouteIDs := collect(s1)
6110 s2RouteIDs := collect(s2)
6111 s3ID := s3.ID()
6112
6113 servers := []*Server{s1, s2}
6114 checkCompMode := func(s1Expected, s2Expected string, shouldBeNew bool) {
6115 t.Helper()
6116 // We wait a bit to make sure that we have routes closed before
6117 // checking that the cluster has (re)formed.
6118 time.Sleep(100 * time.Millisecond)
6119 // First, make sure that the cluster is formed
6120 checkClusterFormed(t, s1, s2, s3)
6121 // Then check that all routes are with the expected mode. We need to
6122 // possibly wait a bit since there is negotiation going on.
6123 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
6124 for _, s := range servers {
6125 var err error
6126 s.mu.RLock()
6127 s.forEachRoute(func(r *client) {
6128 if err != nil {
6129 return
6130 }
6131 r.mu.Lock()
6132 var exp string
6133 var m map[uint64]struct{}
6134 if r.route.remoteID == s3ID {
6135 exp = CompressionNotSupported
6136 } else if s == s1 {
6137 exp = s1Expected
6138 } else {
6139 exp = s2Expected
6140 }
6141 if s == s1 {
6142 m = s1RouteIDs
6143 } else {
6144 m = s2RouteIDs
6145 }
6146 _, present := m[r.cid]
6147 cm := r.route.compression
6148 r.mu.Unlock()
6149 if cm != exp {
6150 err = fmt.Errorf("Expected route %v for server %s to have compression mode %q, got %q", r, s, exp, cm)
6151 }
6152 sbn := shouldBeNew
6153 if exp == CompressionNotSupported {
6154 // Override for routes to s3
6155 sbn = false
6156 }
6157 if sbn && present {
6158 err = fmt.Errorf("Expected route %v for server %s to be a new route, but it was already present", r, s)
6159 } else if !sbn && !present {
6160 err = fmt.Errorf("Expected route %v for server %s to not be new", r, s)
6161 }
6162 })
6163 s.mu.RUnlock()
6164 if err != nil {
6165 return err
6166 }
6167 }
6168 s1RouteIDs = collect(s1)
6169 s2RouteIDs = collect(s2)
6170 return nil
6171 })
6172 }
6173 // Since both started without any compression setting, we default to
6174 // "accept" which means that a server can accept/switch to compression
6175 // but not initiate compression, so they should both be "off"
6176 checkCompMode(CompressionOff, CompressionOff, false)
6177
6178 // Now reload s1 with "on" (s2_fast), since s2 is *configured* with "accept",
6179 // they should both be CompressionS2Fast, even before we reload s2.
6180 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", _EMPTY_, "compression: on"))
6181 checkCompMode(CompressionS2Fast, CompressionS2Fast, true)
6182 // Now reload s2
6183 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", routes, "compression: on"))
6184 checkCompMode(CompressionS2Fast, CompressionS2Fast, false)
6185
6186 // Move on with "better"
6187 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", _EMPTY_, "compression: s2_better"))
6188 // s1 should be at "better", but s2 still at "fast"
6189 checkCompMode(CompressionS2Better, CompressionS2Fast, false)
6190 // Now reload s2
6191 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", routes, "compression: s2_better"))
6192 checkCompMode(CompressionS2Better, CompressionS2Better, false)
6193
6194 // Move to "best"
6195 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", _EMPTY_, "compression: s2_best"))
6196 checkCompMode(CompressionS2Best, CompressionS2Better, false)
6197 // Now reload s2
6198 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", routes, "compression: s2_best"))
6199 checkCompMode(CompressionS2Best, CompressionS2Best, false)
6200
6201 // Now turn off
6202 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", _EMPTY_, "compression: off"))
6203 checkCompMode(CompressionOff, CompressionOff, true)
6204 // Now reload s2
6205 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", routes, "compression: off"))
6206 checkCompMode(CompressionOff, CompressionOff, false)
6207
6208 // When "off" (and not "accept"), enabling 1 is not enough, the reload
6209 // has to be done on both to take effect.
6210 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", _EMPTY_, "compression: s2_better"))
6211 checkCompMode(CompressionOff, CompressionOff, true)
6212 // Now reload s2
6213 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", routes, "compression: s2_better"))
6214 checkCompMode(CompressionS2Better, CompressionS2Better, true)
6215
6216 // Try now to have different ones
6217 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", _EMPTY_, "compression: s2_best"))
6218 // S1 should be "best" but S2 should have stayed at "better"
6219 checkCompMode(CompressionS2Best, CompressionS2Better, false)
6220
6221 // If we remove the compression setting, it defaults to "accept", which
6222 // in that case we want to have a negotiation and use the remote's compression
6223 // level. So connections should be re-created.
6224 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl, "A", _EMPTY_, _EMPTY_))
6225 checkCompMode(CompressionS2Better, CompressionS2Better, true)
6226
6227 // To avoid flapping, add a little sleep here to make sure we have things
6228 // settled before reloading s2.
6229 time.Sleep(100 * time.Millisecond)
6230 // And if we do the same with s2, then we will end-up with no compression.
6231 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl, "B", routes, _EMPTY_))
6232 checkCompMode(CompressionOff, CompressionOff, true)
6233 }
6234
6235 func TestConfigReloadRouteCompressionS2Auto(t *testing.T) {
6236 // This test checks s2_auto specific behavior. It makes sure that we update
6237 // only if the rtt_thresholds and current RTT value warrants a change and
6238 // also that we actually save in c.route.compression the actual compression
6239 // level (not s2_auto).
6240 tmpl1 := `
6241 port: -1
6242 server_name: "A"
6243 cluster {
6244 port: -1
6245 name: "local"
6246 pool_size: -1
6247 compression: {mode: s2_auto, rtt_thresholds: [%s]}
6248 }
6249 `
6250 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl1, "50ms, 100ms, 150ms")))
6251 s1, o1 := RunServerWithConfig(conf1)
6252 defer s1.Shutdown()
6253
6254 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
6255 port: -1
6256 server_name: "B"
6257 cluster {
6258 port: -1
6259 name: "local"
6260 pool_size: -1
6261 compression: s2_fast
6262 routes: ["nats://127.0.0.1:%d"]
6263 }
6264 `, o1.Cluster.Port)))
6265 s2, _ := RunServerWithConfig(conf2)
6266 defer s2.Shutdown()
6267
6268 checkClusterFormed(t, s1, s2)
6269
6270 getCompInfo := func() (string, io.Writer) {
6271 var cm string
6272 var cw io.Writer
6273 s1.mu.RLock()
6274 // There should be only 1 route...
6275 s1.forEachRemote(func(r *client) {
6276 r.mu.Lock()
6277 cm = r.route.compression
6278 cw = r.out.cw
6279 r.mu.Unlock()
6280 })
6281 s1.mu.RUnlock()
6282 return cm, cw
6283 }
6284 // Capture the s2 writer from s1 to s2
6285 cm, cw := getCompInfo()
6286
6287 // We do a reload but really the mode is still s2_auto (even if the current
6288 // compression level may be "uncompressed", "better", etc.. so we don't
6289 // expect the writer to have changed.
6290 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl1, "100ms, 200ms, 300ms"))
6291 if ncm, ncw := getCompInfo(); ncm != cm || ncw != cw {
6292 t.Fatalf("Expected compression info to have stayed the same, was %q - %p, got %q - %p", cm, cw, ncm, ncw)
6293 }
6294 }
6295
6296 func TestConfigReloadLeafNodeCompression(t *testing.T) {
6297 org := testDefaultLeafNodeCompression
6298 testDefaultLeafNodeCompression = _EMPTY_
6299 defer func() { testDefaultLeafNodeCompression = org }()
6300
6301 tmpl1 := `
6302 port: -1
6303 server_name: "A"
6304 leafnodes {
6305 port: -1
6306 %s
6307 }
6308 `
6309 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl1, "compression: accept")))
6310 s1, o1 := RunServerWithConfig(conf1)
6311 defer s1.Shutdown()
6312
6313 port := o1.LeafNode.Port
6314
6315 tmpl2 := `
6316 port: -1
6317 server_name: "%s"
6318 leafnodes {
6319 remotes [
6320 {
6321 url: "nats://127.0.0.1:%d"
6322 %s
6323 }
6324 ]
6325 }
6326 `
6327 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl2, "B", port, "compression: accept")))
6328 s2, _ := RunServerWithConfig(conf2)
6329 defer s2.Shutdown()
6330
6331 // Run a 3rd server but make it as if it was an old server. We want to
6332 // make sure that reload of s1 and s2 will not affect leafnodes from s3 to
6333 // s1/s2 because these do not support compression.
6334 conf3 := createConfFile(t, []byte(fmt.Sprintf(tmpl2, "C", port, "compression: \"not supported\"")))
6335 s3, _ := RunServerWithConfig(conf3)
6336 defer s3.Shutdown()
6337
6338 checkLeafNodeConnected(t, s2)
6339 checkLeafNodeConnected(t, s3)
6340 checkLeafNodeConnectedCount(t, s1, 2)
6341
6342 // Collect leafnodes' cid from servers so we can check if connections are
6343 // recreated when they should and are not when they should not.
6344 collect := func(s *Server) map[uint64]struct{} {
6345 m := make(map[uint64]struct{})
6346 s.mu.RLock()
6347 defer s.mu.RUnlock()
6348 for _, l := range s.leafs {
6349 l.mu.Lock()
6350 m[l.cid] = struct{}{}
6351 l.mu.Unlock()
6352 }
6353 return m
6354 }
6355 s1LeafNodeIDs := collect(s1)
6356 s2LeafNodeIDs := collect(s2)
6357
6358 servers := []*Server{s1, s2}
6359 checkCompMode := func(s1Expected, s2Expected string, shouldBeNew bool) {
6360 t.Helper()
6361 // We wait a bit to make sure that we have leaf connections closed
6362 // before checking that they are properly reconnected.
6363 time.Sleep(100 * time.Millisecond)
6364 checkLeafNodeConnected(t, s2)
6365 checkLeafNodeConnected(t, s3)
6366 checkLeafNodeConnectedCount(t, s1, 2)
6367 // Check that all leafnodes are with the expected mode. We need to
6368 // possibly wait a bit since there is negotiation going on.
6369 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
6370 for _, s := range servers {
6371 var err error
6372 s.mu.RLock()
6373 for _, l := range s.leafs {
6374 l.mu.Lock()
6375 var exp string
6376 var m map[uint64]struct{}
6377 if l.leaf.remoteServer == "C" {
6378 exp = CompressionNotSupported
6379 } else if s == s1 {
6380 exp = s1Expected
6381 } else {
6382 exp = s2Expected
6383 }
6384 if s == s1 {
6385 m = s1LeafNodeIDs
6386 } else {
6387 m = s2LeafNodeIDs
6388 }
6389 _, present := m[l.cid]
6390 cm := l.leaf.compression
6391 l.mu.Unlock()
6392 if cm != exp {
6393 err = fmt.Errorf("Expected leaf %v for server %s to have compression mode %q, got %q", l, s, exp, cm)
6394 }
6395 sbn := shouldBeNew
6396 if exp == CompressionNotSupported {
6397 // Override for routes to s3
6398 sbn = false
6399 }
6400 if sbn && present {
6401 err = fmt.Errorf("Expected leaf %v for server %s to be a new leaf, but it was already present", l, s)
6402 } else if !sbn && !present {
6403 err = fmt.Errorf("Expected leaf %v for server %s to not be new", l, s)
6404 }
6405 if err != nil {
6406 break
6407 }
6408 }
6409 s.mu.RUnlock()
6410 if err != nil {
6411 return err
6412 }
6413 }
6414 s1LeafNodeIDs = collect(s1)
6415 s2LeafNodeIDs = collect(s2)
6416 return nil
6417 })
6418 }
6419 // Since both started with compression "accept", they should both be set to "off"
6420 checkCompMode(CompressionOff, CompressionOff, false)
6421
6422 // Now reload s1 with "on" (s2_auto), since s2 is *configured* with "accept",
6423 // s1 should be "uncompressed" (due to low RTT), and s2 is in that case set
6424 // to s2_fast.
6425 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl1, "compression: on"))
6426 checkCompMode(CompressionS2Uncompressed, CompressionS2Fast, true)
6427 // Now reload s2
6428 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, "B", port, "compression: on"))
6429 checkCompMode(CompressionS2Uncompressed, CompressionS2Uncompressed, false)
6430
6431 // Move on with "better"
6432 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl1, "compression: s2_better"))
6433 // s1 should be at "better", but s2 still at "uncompressed"
6434 checkCompMode(CompressionS2Better, CompressionS2Uncompressed, false)
6435 // Now reload s2
6436 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, "B", port, "compression: s2_better"))
6437 checkCompMode(CompressionS2Better, CompressionS2Better, false)
6438
6439 // Move to "best"
6440 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl1, "compression: s2_best"))
6441 checkCompMode(CompressionS2Best, CompressionS2Better, false)
6442 // Now reload s2
6443 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, "B", port, "compression: s2_best"))
6444 checkCompMode(CompressionS2Best, CompressionS2Best, false)
6445
6446 // Now turn off
6447 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl1, "compression: off"))
6448 checkCompMode(CompressionOff, CompressionOff, true)
6449 // Now reload s2
6450 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, "B", port, "compression: off"))
6451 checkCompMode(CompressionOff, CompressionOff, false)
6452
6453 // When "off" (and not "accept"), enabling 1 is not enough, the reload
6454 // has to be done on both to take effect.
6455 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl1, "compression: s2_better"))
6456 checkCompMode(CompressionOff, CompressionOff, true)
6457 // Now reload s2
6458 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, "B", port, "compression: s2_better"))
6459 checkCompMode(CompressionS2Better, CompressionS2Better, true)
6460
6461 // Try now to have different ones
6462 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl1, "compression: s2_best"))
6463 // S1 should be "best" but S2 should have stayed at "better"
6464 checkCompMode(CompressionS2Best, CompressionS2Better, false)
6465
6466 // Change the setting to "accept", which in that case we want to have a
6467 // negotiation and use the remote's compression level. So connections
6468 // should be re-created.
6469 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl1, "compression: accept"))
6470 checkCompMode(CompressionS2Better, CompressionS2Better, true)
6471
6472 // To avoid flapping, add a little sleep here to make sure we have things
6473 // settled before reloading s2.
6474 time.Sleep(100 * time.Millisecond)
6475 // And if we do the same with s2, then we will end-up with no compression.
6476 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, "B", port, "compression: accept"))
6477 checkCompMode(CompressionOff, CompressionOff, true)
6478
6479 // Now remove completely and we should default to s2_auto, which means that
6480 // s1 should be at "uncompressed" and s2 to "fast".
6481 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl1, _EMPTY_))
6482 checkCompMode(CompressionS2Uncompressed, CompressionS2Fast, true)
6483
6484 // Now with s2, both will be "uncompressed"
6485 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, "B", port, _EMPTY_))
6486 checkCompMode(CompressionS2Uncompressed, CompressionS2Uncompressed, false)
6487 }
6488
6489 func TestConfigReloadLeafNodeCompressionS2Auto(t *testing.T) {
6490 // This test checks s2_auto specific behavior. It makes sure that we update
6491 // only if the rtt_thresholds and current RTT value warrants a change and
6492 // also that we actually save in c.leaf.compression the actual compression
6493 // level (not s2_auto).
6494 tmpl1 := `
6495 port: -1
6496 server_name: "A"
6497 leafnodes {
6498 port: -1
6499 compression: {mode: s2_auto, rtt_thresholds: [%s]}
6500 }
6501 `
6502 conf1 := createConfFile(t, []byte(fmt.Sprintf(tmpl1, "50ms, 100ms, 150ms")))
6503 s1, o1 := RunServerWithConfig(conf1)
6504 defer s1.Shutdown()
6505
6506 conf2 := createConfFile(t, []byte(fmt.Sprintf(`
6507 port: -1
6508 server_name: "B"
6509 leafnodes {
6510 remotes [{ url: "nats://127.0.0.1:%d", compression: s2_fast}]
6511 }
6512 `, o1.LeafNode.Port)))
6513 s2, _ := RunServerWithConfig(conf2)
6514 defer s2.Shutdown()
6515
6516 checkLeafNodeConnected(t, s2)
6517
6518 getCompInfo := func() (string, io.Writer) {
6519 var cm string
6520 var cw io.Writer
6521 s1.mu.RLock()
6522 // There should be only 1 leaf...
6523 for _, l := range s1.leafs {
6524 l.mu.Lock()
6525 cm = l.leaf.compression
6526 cw = l.out.cw
6527 l.mu.Unlock()
6528 }
6529 s1.mu.RUnlock()
6530 return cm, cw
6531 }
6532 // Capture the s2 writer from s1 to s2
6533 cm, cw := getCompInfo()
6534
6535 // We do a reload but really the mode is still s2_auto (even if the current
6536 // compression level may be "uncompressed", "better", etc.. so we don't
6537 // expect the writer to have changed.
6538 reloadUpdateConfig(t, s1, conf1, fmt.Sprintf(tmpl1, "100ms, 200ms, 300ms"))
6539 if ncm, ncw := getCompInfo(); ncm != cm || ncw != cw {
6540 t.Fatalf("Expected compression info to have stayed the same, was %q - %p, got %q - %p", cm, cw, ncm, ncw)
6541 }
6542 }
6543
6544 func TestConfigReloadGetRemoteLeafOpts(t *testing.T) {
6545 u1, err := url.Parse("nats://127.0.0.1:1234")
6546 require_NoError(t, err)
6547 u2, err := url.Parse("nats://127.0.0.1:1235")
6548 require_NoError(t, err)
6549 u3, err := url.Parse("nats://127.0.0.1:1236")
6550 require_NoError(t, err)
6551
6552 rlo1 := &RemoteLeafOpts{URLs: []*url.URL{u1}}
6553 rlo2 := &RemoteLeafOpts{URLs: []*url.URL{u2}}
6554 rlo3 := &RemoteLeafOpts{URLs: []*url.URL{u3}}
6555
6556 for _, test := range []struct {
6557 name string
6558 search *RemoteLeafOpts
6559 listIn []*RemoteLeafOpts
6560 result *RemoteLeafOpts
6561 listOut []*RemoteLeafOpts
6562 }{
6563 {"list empty", rlo1, nil, nil, nil},
6564 {"list of one and found", rlo1, []*RemoteLeafOpts{rlo1}, rlo1, nil},
6565 {"list of one and not found", rlo2, []*RemoteLeafOpts{rlo1}, nil, []*RemoteLeafOpts{rlo1}},
6566 {"list of two and found at pos 1", rlo1, []*RemoteLeafOpts{rlo1, rlo2}, rlo1, []*RemoteLeafOpts{rlo2}},
6567 {"list of two and found at pos 2", rlo2, []*RemoteLeafOpts{rlo1, rlo2}, rlo2, []*RemoteLeafOpts{rlo1}},
6568 {"list of two and not found", rlo3, []*RemoteLeafOpts{rlo1, rlo2}, nil, []*RemoteLeafOpts{rlo1, rlo2}},
6569 // When finding an element, we take the last from the list and move it in place of the found one and reduce the list size.
6570 {"list of three and found at pos 1", rlo1, []*RemoteLeafOpts{rlo1, rlo2, rlo3}, rlo1, []*RemoteLeafOpts{rlo3, rlo2}},
6571 {"list of three and found at pos 2", rlo2, []*RemoteLeafOpts{rlo1, rlo2, rlo3}, rlo2, []*RemoteLeafOpts{rlo1, rlo3}},
6572 {"list of three and found at pos 3", rlo3, []*RemoteLeafOpts{rlo1, rlo2, rlo3}, rlo3, []*RemoteLeafOpts{rlo1, rlo2}},
6573 } {
6574 t.Run(test.name, func(t *testing.T) {
6575 rlo, list := getRemoteLeafOpts(test.search.name(), test.listIn)
6576 require_True(t, reflect.DeepEqual(list, test.listOut))
6577 require_Equal(t, rlo, test.result)
6578 })
6579 }
6580 }
6581
6582 func TestConfigReloadGetLeafNodeOptionsChanges(t *testing.T) {
6583 u, err := url.Parse("nats://127.0.0.1:7222")
6584 require_NoError(t, err)
6585 remote := &RemoteLeafOpts{
6586 URLs: []*url.URL{u},
6587 Compression: CompressionOpts{Mode: CompressionS2Fast},
6588 }
6589 cfg := &leafNodeCfg{RemoteLeafOpts: remote}
6590 s := &Server{}
6591 s.leafRemoteCfgs = make(map[*leafNodeCfg]struct{})
6592 s.leafRemoteCfgs[cfg] = struct{}{}
6593
6594 changedRemotes := make(map[*leafNodeCfg]*remoteLeafOption)
6595 changedRemotes[cfg] = &remoteLeafOption{opts: remote}
6596
6597 changedRemotesTLSFirst := make(map[*leafNodeCfg]*remoteLeafOption)
6598 tlsFirstRemote := *remote
6599 tlsFirstRemote.TLSHandshakeFirst = true
6600 changedRemotesTLSFirst[cfg] = &remoteLeafOption{tlsFirstChanged: true, opts: &tlsFirstRemote}
6601
6602 changedRemotesCompression := make(map[*leafNodeCfg]*remoteLeafOption)
6603 compressionRemote := *remote
6604 compressionRemote.Compression = CompressionOpts{Mode: CompressionS2Best}
6605 changedRemotesCompression[cfg] = &remoteLeafOption{compressionChanged: true, opts: &compressionRemote}
6606
6607 changedRemotesDisabled := make(map[*leafNodeCfg]*remoteLeafOption)
6608 disabledRemote := *remote
6609 disabledRemote.Disabled = true
6610 changedRemotesDisabled[cfg] = &remoteLeafOption{disabledChanged: true, opts: &disabledRemote}
6611
6612 u2, err := url.Parse("nats://127.0.0.1:7223")
6613 require_NoError(t, err)
6614 addedRemote := &RemoteLeafOpts{
6615 URLs: []*url.URL{u2},
6616 Compression: CompressionOpts{Mode: CompressionS2Fast},
6617 LocalAccount: "A",
6618 }
6619
6620 addedRemoteDueToDifferentAccount := &RemoteLeafOpts{
6621 URLs: []*url.URL{u},
6622 Compression: CompressionOpts{Mode: CompressionS2Fast},
6623 LocalAccount: "A",
6624 }
6625 addedRemoteDueToDifferentCreds := &RemoteLeafOpts{
6626 URLs: []*url.URL{u},
6627 Compression: CompressionOpts{Mode: CompressionS2Fast},
6628 Credentials: "credsfile",
6629 }
6630 addedRemoteDueToDifferentNkey := &RemoteLeafOpts{
6631 URLs: []*url.URL{u},
6632 Compression: CompressionOpts{Mode: CompressionS2Fast},
6633 Credentials: "SUACJN3OSKWWPQXME4JUNFJ3PARXPO657GGNWNU7PK7G3AUQQYHLW26XH4",
6634 }
6635
6636 acc1 := &Account{Name: "A1"}
6637 acc2 := &Account{Name: "A2"}
6638
6639 for _, test := range []struct {
6640 name string
6641 genCfg func() (*Server, *LeafNodeOpts, *LeafNodeOpts)
6642 lo *leafNodeOption
6643 errTxt string
6644 }{
6645 {
6646 "no change no remote",
6647 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6648 ts := &Server{}
6649 old := &LeafNodeOpts{
6650 Users: []*User{{Username: "a", Password: "pwd"}},
6651 Compression: CompressionOpts{Mode: CompressionS2Fast},
6652 TLSHandshakeFirst: true,
6653 }
6654 new := &LeafNodeOpts{
6655 Users: []*User{{Username: "a", Password: "pwd"}},
6656 Compression: CompressionOpts{Mode: CompressionS2Fast},
6657 TLSHandshakeFirst: true,
6658 }
6659 return ts, old, new
6660 },
6661 nil,
6662 _EMPTY_,
6663 },
6664 {
6665 "no change with remote",
6666 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6667 ts := &Server{}
6668 ts.leafRemoteCfgs = maps.Clone(s.leafRemoteCfgs)
6669 old := &LeafNodeOpts{
6670 Users: []*User{{Username: "a", Password: "pwd"}},
6671 Compression: CompressionOpts{Mode: CompressionS2Fast},
6672 TLSHandshakeFirst: true,
6673 Remotes: []*RemoteLeafOpts{remote},
6674 }
6675 r := *remote
6676 new := &LeafNodeOpts{
6677 Users: []*User{{Username: "a", Password: "pwd"}},
6678 Compression: CompressionOpts{Mode: CompressionS2Fast},
6679 TLSHandshakeFirst: true,
6680 Remotes: []*RemoteLeafOpts{&r},
6681 }
6682 return ts, old, new
6683 },
6684 &leafNodeOption{changed: changedRemotes},
6685 _EMPTY_,
6686 },
6687 {
6688 "users order changed but equivalent",
6689 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6690 ts := &Server{}
6691 old := &LeafNodeOpts{
6692 Users: []*User{
6693 {Username: "a", Password: "pwd"},
6694 {Username: "b", Password: "pwd"},
6695 },
6696 Compression: CompressionOpts{Mode: CompressionS2Fast},
6697 TLSHandshakeFirst: true,
6698 }
6699 new := &LeafNodeOpts{
6700 Users: []*User{
6701 {Username: "b", Password: "pwd"},
6702 {Username: "a", Password: "pwd"},
6703 },
6704 Compression: CompressionOpts{Mode: CompressionS2Fast},
6705 TLSHandshakeFirst: true,
6706 }
6707 return ts, old, new
6708 },
6709 nil,
6710 _EMPTY_,
6711 },
6712 {
6713 "users different length",
6714 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6715 ts := &Server{}
6716 old := &LeafNodeOpts{
6717 Users: []*User{{Username: "a", Password: "pwd"}},
6718 Compression: CompressionOpts{Mode: CompressionS2Fast},
6719 TLSHandshakeFirst: true,
6720 }
6721 new := &LeafNodeOpts{
6722 Users: []*User{
6723 {Username: "a", Password: "pwd"},
6724 {Username: "b", Password: "pwd"},
6725 },
6726 Compression: CompressionOpts{Mode: CompressionS2Fast},
6727 TLSHandshakeFirst: true,
6728 }
6729 return ts, old, new
6730 },
6731 nil,
6732 "field \"Users\": old=",
6733 },
6734 {
6735 "users different pwd",
6736 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6737 ts := &Server{}
6738 old := &LeafNodeOpts{
6739 Users: []*User{{Username: "a", Password: "pwd"}},
6740 Compression: CompressionOpts{Mode: CompressionS2Fast},
6741 TLSHandshakeFirst: true,
6742 }
6743 new := &LeafNodeOpts{
6744 Users: []*User{{Username: "a", Password: "changedpwd"}},
6745 Compression: CompressionOpts{Mode: CompressionS2Fast},
6746 TLSHandshakeFirst: true,
6747 }
6748 return ts, old, new
6749 },
6750 nil,
6751 "field \"Users\": old=",
6752 },
6753 {
6754 "users different account",
6755 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6756 ts := &Server{}
6757 old := &LeafNodeOpts{
6758 Users: []*User{{Username: "a", Password: "pwd", Account: acc1}},
6759 Compression: CompressionOpts{Mode: CompressionS2Fast},
6760 TLSHandshakeFirst: true,
6761 }
6762 new := &LeafNodeOpts{
6763 Users: []*User{{Username: "a", Password: "pwd", Account: acc2}},
6764 Compression: CompressionOpts{Mode: CompressionS2Fast},
6765 TLSHandshakeFirst: true,
6766 }
6767 return ts, old, new
6768 },
6769 nil,
6770 "field \"Users\": old=",
6771 },
6772 {
6773 "user not found",
6774 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6775 ts := &Server{}
6776 old := &LeafNodeOpts{
6777 Users: []*User{{Username: "a", Password: "pwd"}},
6778 Compression: CompressionOpts{Mode: CompressionS2Fast},
6779 TLSHandshakeFirst: true,
6780 }
6781 new := &LeafNodeOpts{
6782 Users: []*User{{Username: "b", Password: "pwd"}},
6783 Compression: CompressionOpts{Mode: CompressionS2Fast},
6784 TLSHandshakeFirst: true,
6785 }
6786 return ts, old, new
6787 },
6788 nil,
6789 "field \"Users\": old=",
6790 },
6791 {
6792 "unsupported change",
6793 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6794 ts := &Server{}
6795 old := &LeafNodeOpts{
6796 Users: []*User{{Username: "a", Password: "pwd"}},
6797 Compression: CompressionOpts{Mode: CompressionS2Fast},
6798 TLSHandshakeFirst: true,
6799 Port: 1234,
6800 }
6801 new := &LeafNodeOpts{
6802 Users: []*User{{Username: "a", Password: "pwd"}},
6803 Compression: CompressionOpts{Mode: CompressionS2Fast},
6804 TLSHandshakeFirst: true,
6805 // Pick some field that is not Compression or TLSHandshakeFirst
6806 Port: 5678,
6807 }
6808 return ts, old, new
6809 },
6810 nil,
6811 "field \"Port\": old=1234, new=5678",
6812 },
6813 {
6814 "tlsfirst changed",
6815 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6816 ts := &Server{}
6817 old := &LeafNodeOpts{
6818 Users: []*User{{Username: "a", Password: "pwd"}},
6819 Compression: CompressionOpts{Mode: CompressionS2Fast},
6820 TLSHandshakeFirst: true,
6821 }
6822 new := &LeafNodeOpts{
6823 Users: []*User{{Username: "a", Password: "pwd"}},
6824 Compression: CompressionOpts{Mode: CompressionS2Fast},
6825 TLSHandshakeFirst: false,
6826 }
6827 return ts, old, new
6828 },
6829 &leafNodeOption{tlsFirstChanged: true},
6830 _EMPTY_,
6831 },
6832 {
6833 "compression changed",
6834 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6835 ts := &Server{}
6836 old := &LeafNodeOpts{
6837 Users: []*User{{Username: "a", Password: "pwd"}},
6838 Compression: CompressionOpts{Mode: CompressionS2Fast},
6839 TLSHandshakeFirst: true,
6840 }
6841 new := &LeafNodeOpts{
6842 Users: []*User{{Username: "a", Password: "pwd"}},
6843 Compression: CompressionOpts{Mode: CompressionS2Best},
6844 TLSHandshakeFirst: true,
6845 }
6846 return ts, old, new
6847 },
6848 &leafNodeOption{compressionChanged: true},
6849 _EMPTY_,
6850 },
6851 {
6852 "tlsfirst and compression changed",
6853 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6854 ts := &Server{}
6855 old := &LeafNodeOpts{
6856 Users: []*User{{Username: "a", Password: "pwd"}},
6857 Compression: CompressionOpts{Mode: CompressionS2Fast},
6858 TLSHandshakeFirst: true,
6859 }
6860 new := &LeafNodeOpts{
6861 Users: []*User{{Username: "a", Password: "pwd"}},
6862 Compression: CompressionOpts{Mode: CompressionS2Best},
6863 TLSHandshakeFirst: false,
6864 }
6865 return ts, old, new
6866 },
6867 &leafNodeOption{tlsFirstChanged: true, compressionChanged: true},
6868 _EMPTY_,
6869 },
6870 {
6871 "unsupported remote change",
6872 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6873 ts := &Server{}
6874 ts.leafRemoteCfgs = maps.Clone(s.leafRemoteCfgs)
6875 old := &LeafNodeOpts{
6876 Users: []*User{{Username: "a", Password: "pwd"}},
6877 Compression: CompressionOpts{Mode: CompressionS2Fast},
6878 TLSHandshakeFirst: true,
6879 Remotes: []*RemoteLeafOpts{remote},
6880 }
6881 r := *remote
6882 // Set something that cannot be changed.
6883 r.Hub = true
6884 new := &LeafNodeOpts{
6885 Users: []*User{{Username: "a", Password: "pwd"}},
6886 Compression: CompressionOpts{Mode: CompressionS2Best},
6887 TLSHandshakeFirst: false,
6888 Remotes: []*RemoteLeafOpts{&r},
6889 }
6890 return ts, old, new
6891 },
6892 nil,
6893 fmt.Sprintf("remote %s: field %q: old=false, new=true", remote.safeName(), "Hub"),
6894 },
6895 {
6896 "remote tlsfirst changed",
6897 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6898 ts := &Server{}
6899 ts.leafRemoteCfgs = maps.Clone(s.leafRemoteCfgs)
6900 old := &LeafNodeOpts{
6901 Users: []*User{{Username: "a", Password: "pwd"}},
6902 Compression: CompressionOpts{Mode: CompressionS2Fast},
6903 Remotes: []*RemoteLeafOpts{remote},
6904 }
6905 new := &LeafNodeOpts{
6906 Users: []*User{{Username: "a", Password: "pwd"}},
6907 // At the same time, change compression for the LeafNodeOpts block.
6908 Compression: CompressionOpts{Mode: CompressionS2Best},
6909 Remotes: []*RemoteLeafOpts{&tlsFirstRemote},
6910 }
6911 return ts, old, new
6912 },
6913 &leafNodeOption{
6914 compressionChanged: true,
6915 changed: changedRemotesTLSFirst,
6916 },
6917 _EMPTY_,
6918 },
6919 {
6920 "remote compression changed",
6921 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6922 ts := &Server{}
6923 ts.leafRemoteCfgs = maps.Clone(s.leafRemoteCfgs)
6924 old := &LeafNodeOpts{
6925 Users: []*User{{Username: "a", Password: "pwd"}},
6926 Compression: CompressionOpts{Mode: CompressionS2Fast},
6927 Remotes: []*RemoteLeafOpts{remote},
6928 }
6929 new := &LeafNodeOpts{
6930 Users: []*User{{Username: "a", Password: "pwd"}},
6931 Compression: CompressionOpts{Mode: CompressionS2Fast},
6932 // At the same time, change tls first for the LeafNodeOpts block.
6933 TLSHandshakeFirst: true,
6934 Remotes: []*RemoteLeafOpts{&compressionRemote},
6935 }
6936 return ts, old, new
6937 },
6938 &leafNodeOption{
6939 tlsFirstChanged: true,
6940 changed: changedRemotesCompression,
6941 },
6942 _EMPTY_,
6943 },
6944 {
6945 "remote disabled changed",
6946 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6947 ts := &Server{}
6948 ts.leafRemoteCfgs = maps.Clone(s.leafRemoteCfgs)
6949 old := &LeafNodeOpts{
6950 Users: []*User{{Username: "a", Password: "pwd"}},
6951 Compression: CompressionOpts{Mode: CompressionS2Fast},
6952 Remotes: []*RemoteLeafOpts{remote},
6953 }
6954 new := &LeafNodeOpts{
6955 Users: []*User{{Username: "a", Password: "pwd"}},
6956 Compression: CompressionOpts{Mode: CompressionS2Fast},
6957 // At the same time, change tls first for the LeafNodeOpts block.
6958 TLSHandshakeFirst: true,
6959 Remotes: []*RemoteLeafOpts{&disabledRemote},
6960 }
6961 return ts, old, new
6962 },
6963 &leafNodeOption{
6964 tlsFirstChanged: true,
6965 changed: changedRemotesDisabled,
6966 },
6967 _EMPTY_,
6968 },
6969 {
6970 "remote removed",
6971 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6972 ts := &Server{}
6973 ts.leafRemoteCfgs = maps.Clone(s.leafRemoteCfgs)
6974 old := &LeafNodeOpts{
6975 Users: []*User{{Username: "a", Password: "pwd"}},
6976 Compression: CompressionOpts{Mode: CompressionS2Fast},
6977 Remotes: []*RemoteLeafOpts{remote},
6978 }
6979 new := &LeafNodeOpts{
6980 Users: []*User{{Username: "a", Password: "pwd"}},
6981 Compression: CompressionOpts{Mode: CompressionS2Fast},
6982 // At the same time, change tls first for the LeafNodeOpts block.
6983 TLSHandshakeFirst: true,
6984 }
6985 return ts, old, new
6986 },
6987 &leafNodeOption{tlsFirstChanged: true},
6988 _EMPTY_,
6989 },
6990 {
6991 "remote added",
6992 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
6993 ts := &Server{}
6994 ts.leafRemoteCfgs = maps.Clone(s.leafRemoteCfgs)
6995 old := &LeafNodeOpts{
6996 Users: []*User{{Username: "a", Password: "pwd"}},
6997 Compression: CompressionOpts{Mode: CompressionS2Fast},
6998 Remotes: []*RemoteLeafOpts{remote},
6999 }
7000 new := &LeafNodeOpts{
7001 Users: []*User{{Username: "a", Password: "pwd"}},
7002 Compression: CompressionOpts{Mode: CompressionS2Fast},
7003 // At the same time, change tls first for the LeafNodeOpts block.
7004 TLSHandshakeFirst: true,
7005 Remotes: []*RemoteLeafOpts{remote, addedRemote},
7006 }
7007 return ts, old, new
7008 },
7009 &leafNodeOption{
7010 tlsFirstChanged: true,
7011 added: []*RemoteLeafOpts{addedRemote},
7012 changed: changedRemotes,
7013 },
7014 _EMPTY_,
7015 },
7016 {
7017 "remote added due to different account",
7018 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
7019 ts := &Server{}
7020 ts.leafRemoteCfgs = maps.Clone(s.leafRemoteCfgs)
7021 old := &LeafNodeOpts{
7022 Users: []*User{{Username: "a", Password: "pwd"}},
7023 Compression: CompressionOpts{Mode: CompressionS2Fast},
7024 Remotes: []*RemoteLeafOpts{remote},
7025 }
7026 new := &LeafNodeOpts{
7027 Users: []*User{{Username: "a", Password: "pwd"}},
7028 Compression: CompressionOpts{Mode: CompressionS2Fast},
7029 // At the same time, change tls first for the LeafNodeOpts block.
7030 TLSHandshakeFirst: true,
7031 Remotes: []*RemoteLeafOpts{addedRemoteDueToDifferentAccount},
7032 }
7033 return ts, old, new
7034 },
7035 &leafNodeOption{
7036 tlsFirstChanged: true,
7037 added: []*RemoteLeafOpts{addedRemoteDueToDifferentAccount},
7038 },
7039 _EMPTY_,
7040 },
7041 {
7042 "remote added due to different creds",
7043 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
7044 ts := &Server{}
7045 ts.leafRemoteCfgs = maps.Clone(s.leafRemoteCfgs)
7046 old := &LeafNodeOpts{
7047 Users: []*User{{Username: "a", Password: "pwd"}},
7048 Compression: CompressionOpts{Mode: CompressionS2Fast},
7049 Remotes: []*RemoteLeafOpts{remote},
7050 }
7051 new := &LeafNodeOpts{
7052 Users: []*User{{Username: "a", Password: "pwd"}},
7053 Compression: CompressionOpts{Mode: CompressionS2Fast},
7054 // At the same time, change tls first for the LeafNodeOpts block.
7055 TLSHandshakeFirst: true,
7056 Remotes: []*RemoteLeafOpts{addedRemoteDueToDifferentCreds},
7057 }
7058 return ts, old, new
7059 },
7060 &leafNodeOption{
7061 tlsFirstChanged: true,
7062 added: []*RemoteLeafOpts{addedRemoteDueToDifferentCreds},
7063 },
7064 _EMPTY_,
7065 },
7066 {
7067 "remote added due to different nkey",
7068 func() (*Server, *LeafNodeOpts, *LeafNodeOpts) {
7069 ts := &Server{}
7070 ts.leafRemoteCfgs = maps.Clone(s.leafRemoteCfgs)
7071 old := &LeafNodeOpts{
7072 Users: []*User{{Username: "a", Password: "pwd"}},
7073 Compression: CompressionOpts{Mode: CompressionS2Fast},
7074 Remotes: []*RemoteLeafOpts{remote},
7075 }
7076 new := &LeafNodeOpts{
7077 Users: []*User{{Username: "a", Password: "pwd"}},
7078 Compression: CompressionOpts{Mode: CompressionS2Fast},
7079 // At the same time, change tls first for the LeafNodeOpts block.
7080 TLSHandshakeFirst: true,
7081 Remotes: []*RemoteLeafOpts{addedRemoteDueToDifferentNkey},
7082 }
7083 return ts, old, new
7084 },
7085 &leafNodeOption{
7086 tlsFirstChanged: true,
7087 added: []*RemoteLeafOpts{addedRemoteDueToDifferentNkey},
7088 },
7089 _EMPTY_,
7090 },
7091 } {
7092 t.Run(test.name, func(t *testing.T) {
7093 s, old, new := test.genCfg()
7094 lo, err := getLeafNodeOptionsChanges(s, old, new)
7095 if test.errTxt != _EMPTY_ {
7096 if err == nil || !strings.Contains(err.Error(), test.errTxt) {
7097 t.Fatalf("Expected error containing %q, got %q", test.errTxt, err)
7098 }
7099 return
7100 }
7101 if !reflect.DeepEqual(lo, test.lo) {
7102 t.Fatalf("Expected result to be %+v, got %+v", test.lo, lo)
7103 }
7104 })
7105 }
7106 }
7107
7108 func TestConfigReloadLeafNodeUnsupportedChangesFail(t *testing.T) {
7109 conf1 := createConfFile(t, []byte(`
7110 port: -1
7111 server_name: "A"
7112 leafnodes {
7113 port: -1
7114 }
7115 `))
7116 s1, o1 := RunServerWithConfig(conf1)
7117 defer s1.Shutdown()
7118
7119 tmpl2 := `
7120 port: -1
7121 server_name: "B"
7122 leafnodes {
7123 port: %d
7124 remotes [
7125 { url: "nats://127.0.0.1:%d", deny_imports: ["%s"], deny_exports: ["%s"]%s }
7126 %s
7127 ]
7128 }
7129 `
7130 conf2 := createConfFile(t,
7131 fmt.Appendf(nil, tmpl2, -1, o1.LeafNode.Port, "foo", "bar", _EMPTY_, _EMPTY_))
7132 s2, o2 := RunServerWithConfig(conf2)
7133 defer s2.Shutdown()
7134
7135 checkLeafNodeConnectedCount(t, s2, 1)
7136
7137 remote := o2.LeafNode.Remotes[0]
7138 require_NotNil(t, remote)
7139 remoteName := remote.safeName()
7140 require_NotEqual(t, remoteName, _EMPTY_)
7141
7142 checkConfigReload := func(content []byte, errTxt string) {
7143 t.Helper()
7144 err := os.WriteFile(conf2, content, 0666)
7145 require_NoError(t, err)
7146 err = s2.Reload()
7147 require_Error(t, err)
7148 require_Contains(t, err.Error(), errTxt)
7149 }
7150
7151 // Make a change that is not supported in the main block
7152 checkConfigReload(fmt.Appendf(nil, tmpl2, 1234, o1.LeafNode.Port, "foo", "bar", _EMPTY_, _EMPTY_),
7153 "not supported for LeafNode: field \"Port\": old=")
7154
7155 // Now make one in the remote block
7156 checkConfigReload(fmt.Appendf(nil, tmpl2, -1, o1.LeafNode.Port, "foo", "bar", ", hub: true", _EMPTY_),
7157 fmt.Sprintf("not supported for LeafNode: remote %s: field %q: old=false, new=true",
7158 remoteName, "Hub"))
7159
7160 // Check we now correctly fail a change in deny_imports
7161 checkConfigReload(fmt.Appendf(nil, tmpl2, -1, o1.LeafNode.Port, "xxx", "bar", _EMPTY_, _EMPTY_),
7162 fmt.Sprintf("not supported for LeafNode: remote %s: field %q: old=[foo], new=[xxx]",
7163 remoteName, "DenyImports"))
7164
7165 // Check we now correctly fail a change in deny_exports
7166 checkConfigReload(fmt.Appendf(nil, tmpl2, -1, o1.LeafNode.Port, "foo", "xxx", _EMPTY_, _EMPTY_),
7167 fmt.Sprintf("not supported for LeafNode: remote %s: field %q: old=[bar], new=[xxx]",
7168 remoteName, "DenyExports"))
7169
7170 // Try with a duplicate, it should fail too.
7171 duplicate := fmt.Sprintf(`{ url: "nats://127.0.0.1:%d" }`, o1.LeafNode.Port)
7172 checkConfigReload(fmt.Appendf(nil, tmpl2, -1, o1.LeafNode.Port, "foo", "bar", _EMPTY_, duplicate),
7173 fmt.Sprintf("duplicate remote %s", remoteName))
7174
7175 // Now repeat with s.ReloadOptions()
7176 checkOptionsReload := func(o *Options, errTxt string) {
7177 t.Helper()
7178 err := s2.ReloadOptions(o)
7179 require_Error(t, err)
7180 require_Contains(t, err.Error(), errTxt)
7181 }
7182 err := os.WriteFile(conf2, fmt.Appendf(nil, tmpl2, -1, o1.LeafNode.Port, "foo", "bar", _EMPTY_, _EMPTY_), 0666)
7183 require_NoError(t, err)
7184 o := LoadConfig(conf2)
7185 o.LeafNode.Port = 1234
7186 checkOptionsReload(o, "not supported for LeafNode: field \"Port\"")
7187
7188 o = LoadConfig(conf2)
7189 o.LeafNode.Remotes[0].Hub = true
7190 checkOptionsReload(o,
7191 fmt.Sprintf("not supported for LeafNode: remote %s: field %q: old=false, new=true",
7192 remoteName, "Hub"))
7193
7194 o = LoadConfig(conf2)
7195 duplicateRemote := *o.LeafNode.Remotes[0]
7196 o.LeafNode.Remotes = append(o.LeafNode.Remotes, &duplicateRemote)
7197 checkOptionsReload(o, fmt.Sprintf("duplicate remote %s", remoteName))
7198
7199 o = LoadConfig(conf2)
7200 o.LeafNode.Remotes[0].DenyImports = []string{"xxx"}
7201 checkOptionsReload(o, fmt.Sprintf("not supported for LeafNode: remote %s: field %q: old=[foo], new=[xxx]",
7202 remoteName, "DenyImports"))
7203
7204 o = LoadConfig(conf2)
7205 o.LeafNode.Remotes[0].DenyExports = []string{"xxx"}
7206 checkOptionsReload(o, fmt.Sprintf("not supported for LeafNode: remote %s: field %q: old=[bar], new=[xxx]",
7207 remoteName, "DenyExports"))
7208 }
7209
7210 func TestConfigReloadLeafNodeRemotesReorderOk(t *testing.T) {
7211 conf1 := createConfFile(t, []byte(`
7212 port: -1
7213 server_name: "A"
7214 accounts {
7215 A: {users:[{user: "A", password: "pwd"}]}
7216 B: {users:[{user: "B", password: "pwd"}]}
7217 }
7218 leafnodes {
7219 port: -1
7220 }
7221 `))
7222 s1, o1 := RunServerWithConfig(conf1)
7223 defer s1.Shutdown()
7224
7225 tmpl2 := `
7226 port: -1
7227 server_name: "B"
7228 leafnodes {
7229 remotes [
7230 { url: "nats://%s:[email protected]:%d"%s }
7231 { url: "nats://%s:[email protected]:%d" }
7232 ]
7233 }
7234 `
7235 conf2 := createConfFile(t, []byte(fmt.Sprintf(tmpl2,
7236 "A", o1.LeafNode.Port, _EMPTY_, "B", o1.LeafNode.Port)))
7237 s2, _ := RunServerWithConfig(conf2)
7238 defer s2.Shutdown()
7239
7240 checkLeafNodeConnectedCount(t, s2, 2)
7241
7242 // Flip the order of the remotes, and disable "B". We should have only
7243 // one leafnode connected on s1, and it should be for account "A".
7244 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2,
7245 "B", o1.LeafNode.Port, ", disabled: true", "A", o1.LeafNode.Port))
7246
7247 checkLeafNodeConnectedCount(t, s1, 1)
7248 checkLeafNodeConnectedCount(t, s2, 1)
7249 var leaf *client
7250 s2.mu.RLock()
7251 for _, l := range s2.leafs {
7252 leaf = l
7253 break
7254 }
7255 s2.mu.RUnlock()
7256 require_NotNil(t, leaf)
7257 leaf.mu.Lock()
7258 acc := leaf.leaf.remoteAccName
7259 leaf.mu.Unlock()
7260 require_Equal(t, "A", acc)
7261 }
7262
7263 func TestConfigReloadAddRemoveRemoteLeafNodes(t *testing.T) {
7264 conf1 := createConfFile(t, []byte(`
7265 port: -1
7266 server_name: "A"
7267 leafnodes {
7268 port: -1
7269 }
7270 `))
7271 s1, o1 := RunServerWithConfig(conf1)
7272 defer s1.Shutdown()
7273
7274 tmpl2 := `
7275 port: -1
7276 server_name: "B"
7277 accounts {
7278 A: {users:[{user: "A", password: "pwd"}]}
7279 B: {users:[{user: "B", password: "pwd"}]}
7280 C: {users:[{user: "C", password: "pwd"}]}
7281 }
7282 leafnodes {
7283 remotes [
7284 %s
7285 %s
7286 %s
7287 ]
7288 }
7289 `
7290 remoteTmpl := fmt.Sprintf(`{ url: "nats://127.0.0.1:%d"`, o1.LeafNode.Port) + ", account=%q}"
7291 accA := fmt.Sprintf(remoteTmpl, "A")
7292 accB := fmt.Sprintf(remoteTmpl, "B")
7293 accC := fmt.Sprintf(remoteTmpl, "C")
7294 conf2 := createConfFile(t, fmt.Appendf(nil, tmpl2, accA, _EMPTY_, _EMPTY_))
7295 s2, _ := RunServerWithConfig(conf2)
7296 defer s2.Shutdown()
7297
7298 checkLeafs := func(accs []string) {
7299 t.Helper()
7300 s2.mu.RLock()
7301 defer s2.mu.RUnlock()
7302 require_Len(t, len(accs), len(s2.leafRemoteCfgs))
7303 for _, acc := range accs {
7304 var ok bool
7305 for cfg := range s2.leafRemoteCfgs {
7306 cfg.RLock()
7307 ok = cfg.LocalAccount == acc
7308 cfg.RUnlock()
7309 if ok {
7310 break
7311 }
7312 }
7313 if !ok {
7314 t.Fatalf("Did not find account %q in the remote configs", acc)
7315 }
7316 }
7317 }
7318
7319 checkLeafNodeConnectedCount(t, s2, 1)
7320 checkLeafs([]string{"A"})
7321
7322 // Add a remote with local account "B" and "C"
7323 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, accA, accB, accC))
7324
7325 checkLeafNodeConnectedCount(t, s2, 3)
7326 checkLeafs([]string{"A", "B", "C"})
7327
7328 // Remove remote with local account "A" and "C"
7329 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, _EMPTY_, accB, _EMPTY_))
7330
7331 checkLeafNodeConnectedCount(t, s2, 1)
7332 checkLeafs([]string{"B"})
7333
7334 // Remove all now
7335 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, _EMPTY_, _EMPTY_, _EMPTY_))
7336 checkLeafNodeConnectedCount(t, s2, 0)
7337 checkLeafs(nil)
7338 }
7339
7340 func TestConfigReloadAddRemoveRemoteLeafNodesVarz(t *testing.T) {
7341 conf1 := createConfFile(t, []byte(`
7342 port: -1
7343 server_name: "A"
7344 leafnodes {
7345 port: -1
7346 }
7347 `))
7348 s1, o1 := RunServerWithConfig(conf1)
7349 defer s1.Shutdown()
7350
7351 tmpl2 := `
7352 port: -1
7353 http: -1
7354 server_name: "B"
7355 accounts {
7356 A: {users:[{user: "A", password: "pwd"}]}
7357 B: {users:[{user: "B", password: "pwd"}]}
7358 }
7359 leafnodes {
7360 remotes [
7361 %s
7362 %s
7363 ]
7364 }
7365 `
7366 remoteTmpl := fmt.Sprintf(`{ url: "nats://127.0.0.1:%d"`, o1.LeafNode.Port) + ", account=%q}"
7367 accA := fmt.Sprintf(remoteTmpl, "A")
7368 accB := fmt.Sprintf(remoteTmpl, "B")
7369 conf2 := createConfFile(t, fmt.Appendf(nil, tmpl2, accA, _EMPTY_))
7370 s2, _ := RunServerWithConfig(conf2)
7371 defer s2.Shutdown()
7372
7373 checkLeafNodeConnectedCount(t, s2, 1)
7374
7375 checkRemotes := func(accs ...string) {
7376 t.Helper()
7377 // Check both the HTTP endpoint (mode 0), which caches the Varz
7378 // object, and the programmatic API (mode 1).
7379 url := fmt.Sprintf("http://127.0.0.1:%d/varz", s2.MonitorAddr().Port)
7380 for mode := 0; mode < 2; mode++ {
7381 v := pollVarz(t, s2, mode, url, nil)
7382 require_Len(t, len(v.LeafNode.Remotes), len(accs))
7383 for _, acc := range accs {
7384 var ok bool
7385 for _, r := range v.LeafNode.Remotes {
7386 if r.LocalAccount == acc {
7387 ok = true
7388 break
7389 }
7390 }
7391 if !ok {
7392 t.Fatalf("Mode %d: did not find account %q in varz remotes: %+v", mode, acc, v.LeafNode.Remotes)
7393 }
7394 }
7395 }
7396 }
7397 // This will also populate the cached s.varz used by the HTTP endpoint.
7398 checkRemotes("A")
7399
7400 // Add a remote with local account "B".
7401 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, accA, accB))
7402 checkLeafNodeConnectedCount(t, s2, 2)
7403 checkRemotes("A", "B")
7404
7405 // Remove the remote with local account "A".
7406 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, _EMPTY_, accB))
7407 checkLeafNodeConnectedCount(t, s2, 1)
7408 checkRemotes("B")
7409 }
7410
7411 func TestConfigReloadRemoteLeafNodeNkeyChange(t *testing.T) {
7412 conf1 := createConfFile(t, []byte(`
7413 listen: "127.0.0.1:-1"
7414 server_name: "A"
7415 leaf {
7416 listen: 127.0.0.1:-1
7417 authorization: { nkey: UCSTG5CRF5GEJERAFKUUYRODGABTBVWY2NPE4GGKRQVQOH74PIAKTVKO }
7418 }
7419 `))
7420 s1, o1 := RunServerWithConfig(conf1)
7421 defer s1.Shutdown()
7422
7423 tmpl2 := `
7424 listen: "127.0.0.1:-1"
7425 server_name: "B"
7426 leaf {
7427 reconnect_interval: "50ms"
7428 remotes: [
7429 {
7430 url: "nats-leaf://127.0.0.1:%d"
7431 nkey: %s
7432 }
7433 ]
7434 }
7435 `
7436 conf2 := createConfFile(t, fmt.Appendf(nil, tmpl2, o1.LeafNode.Port,
7437 "SUAPM67TC4RHQLKBX55NIQXSMATZDOZK6FNEOSS36CAYA7F7TY66LP4BOM"))
7438 s2, _ := RunServerWithConfig(conf2)
7439 defer s2.Shutdown()
7440
7441 // Should not be able to connect...
7442 time.Sleep(70 * time.Millisecond)
7443 checkLeafNodeConnectedCount(t, s2, 0)
7444
7445 reloadUpdateConfig(t, s2, conf2, fmt.Sprintf(tmpl2, o1.LeafNode.Port,
7446 "SUACJN3OSKWWPQXME4JUNFJ3PARXPO657GGNWNU7PK7G3AUQQYHLW26XH4"))
7447
7448 checkLeafNodeConnectedCount(t, s2, 1)
7449 }
7450
7451 func TestConfigReloadNoPanicOnShutdown(t *testing.T) {
7452 tmpl := `
7453 port: -1
7454 jetstream: true
7455 accounts {
7456 A {
7457 users: [{user: A, password: pwd}]
7458 %s
7459 }
7460 B {
7461 users: [{user: B, password: pwd}]
7462 }
7463 }
7464 `
7465 for i := 0; i < 50; i++ {
7466 conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, _EMPTY_)))
7467 s, _ := RunServerWithConfig(conf)
7468 // Don't use a defer s.Shutdown() here since it would prevent the panic
7469 // to be reported (but the test would still fail because of a runtime timeout).
7470
7471 err := os.WriteFile(conf, []byte(fmt.Sprintf(tmpl, "jetstream: true")), 0666)
7472 require_NoError(t, err)
7473
7474 wg := sync.WaitGroup{}
7475 wg.Add(1)
7476 go func() {
7477 defer wg.Done()
7478 time.Sleep(10 * time.Millisecond)
7479 s.Shutdown()
7480 }()
7481
7482 time.Sleep(8 * time.Millisecond)
7483 err = s.Reload()
7484 require_NoError(t, err)
7485 wg.Wait()
7486 }
7487 }
7488
7489 func TestJetStreamReloadPreservesMaxConcurrentIOOnDisable(t *testing.T) {
7490 storeDir := t.TempDir()
7491 initialLimit := 128
7492 disabledConfig := `listen: 127.0.0.1:-1`
7493 jsConfig := fmt.Sprintf(`
7494 listen: 127.0.0.1:-1
7495 jetstream: {
7496 max_mem_store: 2MB
7497 max_file_store: 8MB
7498 store_dir: '%s'
7499 max_concurrent_io: %d
7500 }
7501 `, storeDir, initialLimit)
7502 conf := createConfFile(t, []byte(jsConfig))
7503
7504 s, _ := RunServerWithConfig(conf)
7505 defer s.Shutdown()
7506
7507 require_True(t, s.ReadyForConnections(5*time.Second))
7508 require_Equal(t, s.dios.cap(), initialLimit)
7509 require_Equal(t, s.getOpts().JetStreamConcurrentIOs, initialLimit)
7510
7511 // disabling JS is OK
7512 reloadUpdateConfig(t, s, conf, disabledConfig)
7513 require_Equal(t, s.dios.cap(), initialLimit)
7514 require_Equal(t, s.getOpts().JetStreamConcurrentIOs, initialLimit)
7515
7516 // disabling JS repeatedly is OK
7517 reloadUpdateConfig(t, s, conf, disabledConfig)
7518 require_Equal(t, s.dios.cap(), initialLimit)
7519 require_Equal(t, s.getOpts().JetStreamConcurrentIOs, initialLimit)
7520
7521 // renabling with the same values is OK
7522 reloadUpdateConfig(t, s, conf, jsConfig)
7523 require_Equal(t, s.dios.cap(), initialLimit)
7524 require_Equal(t, s.getOpts().JetStreamConcurrentIOs, initialLimit)
7525
7526 // changing value not OK
7527 jsConfig = strings.Replace(jsConfig,
7528 fmt.Sprintf("max_concurrent_io: %d", initialLimit),
7529 "max_concurrent_io: 256", 1)
7530 require_NoError(t, os.WriteFile(conf, []byte(jsConfig), 0666))
7531 err := s.Reload()
7532 require_Error(t, err)
7533 require_Contains(t, err.Error(), "JetStreamConcurrentIOs")
7534 require_Equal(t, s.dios.cap(), initialLimit)
7535 require_Equal(t, s.getOpts().JetStreamConcurrentIOs, initialLimit)
7536 }
7537
7538 func TestJetStreamReloadMaxMemAndStore(t *testing.T) {
7539 tdir := t.TempDir()
7540 template := `
7541 listen: 127.0.0.1:-1
7542 http: 127.0.0.1:-1
7543 jetstream {
7544 max_mem_store: %s
7545 max_file_store: %s
7546 store_dir = %q
7547 }
7548 `
7549 conf := createConfFile(t, []byte(fmt.Sprintf(template, "128MB", "128MB", tdir)))
7550
7551 s, _ := RunServerWithConfig(conf)
7552 defer s.Shutdown()
7553
7554 varzURL := fmt.Sprintf("http://127.0.0.1:%d/varz", s.MonitorAddr().Port)
7555
7556 // Verify initial config.
7557 cfg := s.JetStreamConfig()
7558 require_Equal(t, cfg.MaxMemory, 128*1024*1024)
7559 require_Equal(t, cfg.MaxStore, 128*1024*1024)
7560
7561 cfg = pollVarz(t, s, 0, varzURL, nil).JetStream.Config
7562 require_Equal(t, cfg.MaxMemory, 128*1024*1024)
7563 require_Equal(t, cfg.MaxStore, 128*1024*1024)
7564
7565 nc, js := jsClientConnect(t, s)
7566 defer nc.Close()
7567
7568 scfg := &nats.StreamConfig{MaxBytes: 128 * 1024 * 1024}
7569 storageTypes := []nats.StorageType{nats.FileStorage, nats.MemoryStorage}
7570 for _, st := range storageTypes {
7571 scfg.Name = fmt.Sprintf("TEST-%s", st)
7572 scfg.Storage = st
7573 _, err := js.AddStream(scfg)
7574 require_NoError(t, err)
7575 }
7576
7577 for _, st := range storageTypes {
7578 scfg.Name = fmt.Sprintf("TEST2-%s", st)
7579 scfg.Storage = st
7580 _, err := js.AddStream(scfg)
7581 if st == nats.FileStorage {
7582 require_Error(t, err, NewJSStorageResourcesExceededError())
7583 } else {
7584 require_Error(t, err, NewJSMemoryResourcesExceededError())
7585 }
7586 }
7587
7588 // Reload with increased limits.
7589 err := os.WriteFile(conf, []byte(fmt.Sprintf(template, "512MB", "512MB", tdir)), 0666)
7590 require_NoError(t, err)
7591 err = s.Reload()
7592 require_NoError(t, err)
7593 cfg = s.JetStreamConfig()
7594 require_Equal(t, cfg.MaxMemory, 512*1024*1024)
7595 require_Equal(t, cfg.MaxStore, 512*1024*1024)
7596
7597 cfg = pollVarz(t, s, 0, varzURL, nil).JetStream.Config
7598 require_Equal(t, cfg.MaxMemory, 512*1024*1024)
7599 require_Equal(t, cfg.MaxStore, 512*1024*1024)
7600
7601 // We should now be able to create the stream.
7602 for _, st := range storageTypes {
7603 scfg.Name = fmt.Sprintf("TEST2-%s", st)
7604 scfg.Storage = st
7605 _, err := js.AddStream(scfg)
7606 require_NoError(t, err)
7607 }
7608
7609 // Decreasing the limits should fail.
7610 err = os.WriteFile(conf, []byte(fmt.Sprintf(template, "511MB", "511MB", tdir)), 0666)
7611 require_NoError(t, err)
7612 err = s.Reload()
7613 require_Error(t, err, errors.New("config reload not supported for decreasing jetstream max memory and store"))
7614
7615 // Config should remain the same.
7616 cfg = s.JetStreamConfig()
7617 require_Equal(t, cfg.MaxMemory, 512*1024*1024)
7618 require_Equal(t, cfg.MaxStore, 512*1024*1024)
7619
7620 cfg = pollVarz(t, s, 0, varzURL, nil).JetStream.Config
7621 require_Equal(t, cfg.MaxMemory, 512*1024*1024)
7622 require_Equal(t, cfg.MaxStore, 512*1024*1024)
7623
7624 }