Debian Codegraph @

server/accounts_test.go

raw
1 // Copyright 2018-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 "encoding/base64"
18 "encoding/json"
19 "fmt"
20 "io"
21 "net/http"
22 "slices"
23 "strconv"
24 "strings"
25 "sync"
26 "sync/atomic"
27 "testing"
28 "time"
29
30 "github.com/nats-io/jwt/v2"
31 "github.com/nats-io/nats.go"
32 "github.com/nats-io/nkeys"
33 )
34
35 func simpleAccountServer(t *testing.T) (*Server, *Account, *Account) {
36 opts := defaultServerOptions
37 s := New(&opts)
38
39 // Now create two accounts.
40 f, err := s.RegisterAccount("$foo")
41 if err != nil {
42 t.Fatalf("Error creating account 'foo': %v", err)
43 }
44 b, err := s.RegisterAccount("$bar")
45 if err != nil {
46 t.Fatalf("Error creating account 'bar': %v", err)
47 }
48 return s, f, b
49 }
50
51 func TestRegisterDuplicateAccounts(t *testing.T) {
52 s, _, _ := simpleAccountServer(t)
53 if _, err := s.RegisterAccount("$foo"); err == nil {
54 t.Fatal("Expected an error registering 'foo' twice")
55 }
56 }
57
58 func TestAccountIsolation(t *testing.T) {
59 s, fooAcc, barAcc := simpleAccountServer(t)
60 cfoo, crFoo, _ := newClientForServer(s)
61 defer cfoo.close()
62 if err := cfoo.registerWithAccount(fooAcc); err != nil {
63 t.Fatalf("Error register client with 'foo' account: %v", err)
64 }
65 cbar, crBar, _ := newClientForServer(s)
66 defer cbar.close()
67 if err := cbar.registerWithAccount(barAcc); err != nil {
68 t.Fatalf("Error register client with 'bar' account: %v", err)
69 }
70
71 // Make sure they are different accounts/sl.
72 if cfoo.acc == cbar.acc {
73 t.Fatalf("Error, accounts the same for both clients")
74 }
75
76 // Now do quick test that makes sure messages do not cross over.
77 // setup bar as a foo subscriber.
78 cbar.parseAsync("SUB foo 1\r\nPING\r\nPING\r\n")
79 l, err := crBar.ReadString('\n')
80 if err != nil {
81 t.Fatalf("Error for client 'bar' from server: %v", err)
82 }
83 if !strings.HasPrefix(l, "PONG\r\n") {
84 t.Fatalf("PONG response incorrect: %q", l)
85 }
86
87 cfoo.parseAsync("SUB foo 1\r\nPUB foo 5\r\nhello\r\nPING\r\n")
88 l, err = crFoo.ReadString('\n')
89 if err != nil {
90 t.Fatalf("Error for client 'foo' from server: %v", err)
91 }
92
93 matches := msgPat.FindAllStringSubmatch(l, -1)[0]
94 if matches[SUB_INDEX] != "foo" {
95 t.Fatalf("Did not get correct subject: '%s'\n", matches[SUB_INDEX])
96 }
97 if matches[SID_INDEX] != "1" {
98 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
99 }
100 checkPayload(crFoo, []byte("hello\r\n"), t)
101
102 // Now make sure nothing shows up on bar.
103 l, err = crBar.ReadString('\n')
104 if err != nil {
105 t.Fatalf("Error for client 'bar' from server: %v", err)
106 }
107 if !strings.HasPrefix(l, "PONG\r\n") {
108 t.Fatalf("PONG response incorrect: %q", l)
109 }
110 }
111
112 func TestAccountIsolationExportImport(t *testing.T) {
113 checkIsolation := func(t *testing.T, pubSubj string, ncExp, ncImp *nats.Conn) {
114 // We keep track of 2 subjects.
115 // One subject (pubSubj) is based off the stream import.
116 // The other subject "fizz" is not imported and should be isolated.
117
118 gotSubjs := map[string]int{
119 pubSubj: 0,
120 "fizz": 0,
121 }
122 count := int32(0)
123 ch := make(chan struct{}, 1)
124 if _, err := ncImp.Subscribe(">", func(m *nats.Msg) {
125 gotSubjs[m.Subject] += 1
126 if n := atomic.AddInt32(&count, 1); n == 3 {
127 ch <- struct{}{}
128 }
129 }); err != nil {
130 t.Fatalf("Error on subscribe: %v", err)
131 }
132 // Since both prod and cons use same server, flushing here will ensure
133 // that the interest is registered and known at the time we publish.
134 ncImp.Flush()
135
136 if err := ncExp.Publish(pubSubj, []byte(fmt.Sprintf("ncExp pub %s", pubSubj))); err != nil {
137 t.Fatal(err)
138 }
139 if err := ncImp.Publish(pubSubj, []byte(fmt.Sprintf("ncImp pub %s", pubSubj))); err != nil {
140 t.Fatal(err)
141 }
142
143 if err := ncExp.Publish("fizz", []byte("ncExp pub fizz")); err != nil {
144 t.Fatal(err)
145 }
146 if err := ncImp.Publish("fizz", []byte("ncImp pub fizz")); err != nil {
147 t.Fatal(err)
148 }
149
150 wantSubjs := map[string]int{
151 // Subscriber ncImp should receive publishes from ncExp and ncImp.
152 pubSubj: 2,
153 // Subscriber ncImp should only receive the publish from ncImp.
154 "fizz": 1,
155 }
156
157 // Wait for at least the 3 expected messages
158 select {
159 case <-ch:
160 case <-time.After(time.Second):
161 t.Fatalf("Expected 3 messages, got %v", atomic.LoadInt32(&count))
162 }
163 // But now wait a bit to see if subscription receives more than expected.
164 time.Sleep(50 * time.Millisecond)
165
166 if got, want := len(gotSubjs), len(wantSubjs); got != want {
167 t.Fatalf("unexpected subjs len, got=%d; want=%d", got, want)
168 }
169
170 for key, gotCnt := range gotSubjs {
171 if wantCnt := wantSubjs[key]; gotCnt != wantCnt {
172 t.Errorf("unexpected receive count for subject %q, got=%d, want=%d", key, gotCnt, wantCnt)
173 }
174 }
175 }
176
177 cases := []struct {
178 name string
179 exp, imp string
180 pubSubj string
181 }{
182 {
183 name: "export literal, import literal",
184 exp: "foo", imp: "foo",
185 pubSubj: "foo",
186 },
187 {
188 name: "export full wildcard, import literal",
189 exp: "foo.>", imp: "foo.bar",
190 pubSubj: "foo.bar",
191 },
192 {
193 name: "export full wildcard, import sublevel full wildcard",
194 exp: "foo.>", imp: "foo.bar.>",
195 pubSubj: "foo.bar.whizz",
196 },
197 {
198 name: "export full wildcard, import full wildcard",
199 exp: "foo.>", imp: "foo.>",
200 pubSubj: "foo.bar",
201 },
202 {
203 name: "export partial wildcard, import partial wildcard",
204 exp: "foo.*", imp: "foo.*",
205 pubSubj: "foo.bar",
206 },
207 {
208 name: "export mid partial wildcard, import mid partial wildcard",
209 exp: "foo.*.bar", imp: "foo.*.bar",
210 pubSubj: "foo.whizz.bar",
211 },
212 }
213 for _, c := range cases {
214 t.Run(fmt.Sprintf("%s jwt", c.name), func(t *testing.T) {
215 // Setup NATS server.
216 s := opTrustBasicSetup()
217 defer s.Shutdown()
218 s.Start()
219 if err := s.readyForConnections(5 * time.Second); err != nil {
220 t.Fatal(err)
221 }
222 buildMemAccResolver(s)
223
224 // Setup exporter account.
225 accExpPair, accExpPub := createKey(t)
226 accExpClaims := jwt.NewAccountClaims(accExpPub)
227 if c.exp != "" {
228 accExpClaims.Limits.WildcardExports = true
229 accExpClaims.Exports.Add(&jwt.Export{
230 Name: fmt.Sprintf("%s-stream-export", c.exp),
231 Subject: jwt.Subject(c.exp),
232 Type: jwt.Stream,
233 })
234 }
235 accExpJWT, err := accExpClaims.Encode(oKp)
236 require_NoError(t, err)
237 addAccountToMemResolver(s, accExpPub, accExpJWT)
238
239 // Setup importer account.
240 accImpPair, accImpPub := createKey(t)
241 accImpClaims := jwt.NewAccountClaims(accImpPub)
242 if c.imp != "" {
243 accImpClaims.Imports.Add(&jwt.Import{
244 Name: fmt.Sprintf("%s-stream-import", c.imp),
245 Subject: jwt.Subject(c.imp),
246 Account: accExpPub,
247 Type: jwt.Stream,
248 })
249 }
250 accImpJWT, err := accImpClaims.Encode(oKp)
251 require_NoError(t, err)
252 addAccountToMemResolver(s, accImpPub, accImpJWT)
253
254 // Connect with different accounts.
255 ncExp := natsConnect(t, s.ClientURL(), createUserCreds(t, nil, accExpPair),
256 nats.Name(fmt.Sprintf("nc-exporter-%s", c.exp)))
257 defer ncExp.Close()
258 ncImp := natsConnect(t, s.ClientURL(), createUserCreds(t, nil, accImpPair),
259 nats.Name(fmt.Sprintf("nc-importer-%s", c.imp)))
260 defer ncImp.Close()
261
262 checkIsolation(t, c.pubSubj, ncExp, ncImp)
263 if t.Failed() {
264 t.Logf("exported=%q; imported=%q", c.exp, c.imp)
265 }
266 })
267
268 t.Run(fmt.Sprintf("%s conf", c.name), func(t *testing.T) {
269 // Setup NATS server.
270 cf := createConfFile(t, []byte(fmt.Sprintf(`
271 port: -1
272
273 accounts: {
274 accExp: {
275 users: [{user: accExp, password: accExp}]
276 exports: [{stream: %q}]
277 }
278 accImp: {
279 users: [{user: accImp, password: accImp}]
280 imports: [{stream: {account: accExp, subject: %q}}]
281 }
282 }
283 `,
284 c.exp, c.imp,
285 )))
286 s, _ := RunServerWithConfig(cf)
287 defer s.Shutdown()
288
289 // Connect with different accounts.
290 ncExp := natsConnect(t, s.ClientURL(), nats.UserInfo("accExp", "accExp"),
291 nats.Name(fmt.Sprintf("nc-exporter-%s", c.exp)))
292 defer ncExp.Close()
293 ncImp := natsConnect(t, s.ClientURL(), nats.UserInfo("accImp", "accImp"),
294 nats.Name(fmt.Sprintf("nc-importer-%s", c.imp)))
295 defer ncImp.Close()
296
297 checkIsolation(t, c.pubSubj, ncExp, ncImp)
298 if t.Failed() {
299 t.Logf("exported=%q; imported=%q", c.exp, c.imp)
300 }
301 })
302 }
303 }
304
305 func TestMultiAccountsIsolation(t *testing.T) {
306 conf := createConfFile(t, []byte(`
307 listen: 127.0.0.1:-1
308 accounts: {
309 PUBLIC: {
310 users:[{user: public, password: public}]
311 exports: [
312 { stream: orders.client.stream.> }
313 { stream: orders.client2.stream.> }
314 ]
315 }
316 CLIENT: {
317 users:[{user: client, password: client}]
318 imports: [
319 { stream: { account: PUBLIC, subject: orders.client.stream.> }}
320 ]
321 }
322 CLIENT2: {
323 users:[{user: client2, password: client2}]
324 imports: [
325 { stream: { account: PUBLIC, subject: orders.client2.stream.> }}
326 ]
327 }
328 }`))
329
330 s, _ := RunServerWithConfig(conf)
331 if config := s.JetStreamConfig(); config != nil {
332 defer removeDir(t, config.StoreDir)
333 }
334 defer s.Shutdown()
335
336 // Create a connection for CLIENT and subscribe on orders.>
337 clientnc := natsConnect(t, s.ClientURL(), nats.UserInfo("client", "client"))
338 defer clientnc.Close()
339
340 clientsub := natsSubSync(t, clientnc, "orders.>")
341 natsFlush(t, clientnc)
342
343 // Now same for CLIENT2.
344 client2nc := natsConnect(t, s.ClientURL(), nats.UserInfo("client2", "client2"))
345 defer client2nc.Close()
346
347 client2sub := natsSubSync(t, client2nc, "orders.>")
348 natsFlush(t, client2nc)
349
350 // Now create a connection for PUBLIC
351 publicnc := natsConnect(t, s.ClientURL(), nats.UserInfo("public", "public"))
352 defer publicnc.Close()
353 // Publish on 'orders.client.stream.entry', so only CLIENT should receive it.
354 natsPub(t, publicnc, "orders.client.stream.entry", []byte("test1"))
355
356 // Verify that clientsub gets it.
357 msg := natsNexMsg(t, clientsub, time.Second)
358 require_Equal(t, string(msg.Data), "test1")
359
360 // And also verify that client2sub does NOT get it.
361 _, err := client2sub.NextMsg(100 * time.Microsecond)
362 require_Error(t, err, nats.ErrTimeout)
363
364 clientsub.Unsubscribe()
365 natsFlush(t, clientnc)
366 client2sub.Unsubscribe()
367 natsFlush(t, client2nc)
368
369 // Now have both accounts subscribe to "orders.*.stream.entry"
370 clientsub = natsSubSync(t, clientnc, "orders.*.stream.entry")
371 natsFlush(t, clientnc)
372
373 client2sub = natsSubSync(t, client2nc, "orders.*.stream.entry")
374 natsFlush(t, client2nc)
375
376 // Using the PUBLIC account, publish on the "CLIENT" subject
377 natsPub(t, publicnc, "orders.client.stream.entry", []byte("test2"))
378 natsFlush(t, publicnc)
379
380 msg = natsNexMsg(t, clientsub, time.Second)
381 require_Equal(t, string(msg.Data), "test2")
382
383 _, err = client2sub.NextMsg(100 * time.Microsecond)
384 require_Error(t, err, nats.ErrTimeout)
385 }
386
387 func TestAccountFromOptions(t *testing.T) {
388 opts := defaultServerOptions
389 opts.Accounts = []*Account{NewAccount("foo"), NewAccount("bar")}
390 s := New(&opts)
391 defer s.Shutdown()
392
393 ta := s.numReservedAccounts() + 2
394 if la := s.numAccounts(); la != ta {
395 t.Fatalf("Expected to have a server with %d active accounts, got %v", ta, la)
396 }
397 // Check that sl is filled in.
398 fooAcc, _ := s.LookupAccount("foo")
399 barAcc, _ := s.LookupAccount("bar")
400 if fooAcc == nil || barAcc == nil {
401 t.Fatalf("Error retrieving accounts for 'foo' and 'bar'")
402 }
403 if fooAcc.sl == nil || barAcc.sl == nil {
404 t.Fatal("Expected Sublists to be filled in on Opts.Accounts")
405 }
406 }
407
408 // Clients used to be able to ask that the account be forced to be new.
409 // This was for dynamic sandboxes for demo environments but was never really used.
410 // Make sure it always errors if set.
411 func TestNewAccountAndRequireNewAlwaysError(t *testing.T) {
412 conf := createConfFile(t, []byte(`
413 listen: 127.0.0.1:-1
414 accounts: {
415 A: { users: [ {user: ua, password: pa} ] },
416 B: { users: [ {user: ub, password: pb} ] },
417 }
418 `))
419
420 s, _ := RunServerWithConfig(conf)
421 defer s.Shutdown()
422
423 // Success case
424 c, _, _ := newClientForServer(s)
425 connectOp := "CONNECT {\"user\":\"ua\", \"pass\":\"pa\"}\r\n"
426 err := c.parse([]byte(connectOp))
427 require_NoError(t, err)
428 c.close()
429
430 // Simple cases, any setting of account or new_account always errors.
431 // Even with proper auth.
432 c, cr, _ := newClientForServer(s)
433 connectOp = "CONNECT {\"user\":\"ua\", \"pass\":\"pa\", \"account\":\"ANY\"}\r\n"
434 c.parseAsync(connectOp)
435 l, _ := cr.ReadString('\n')
436 if !strings.HasPrefix(l, "-ERR 'Authorization Violation'") {
437 t.Fatalf("Expected an error, got %q", l)
438 }
439 c.close()
440
441 // new_account with proper credentials.
442 c, cr, _ = newClientForServer(s)
443 connectOp = "CONNECT {\"user\":\"ua\", \"pass\":\"pa\", \"new_account\":true}\r\n"
444 c.parseAsync(connectOp)
445 l, _ = cr.ReadString('\n')
446 if !strings.HasPrefix(l, "-ERR 'Authorization Violation'") {
447 t.Fatalf("Expected an error, got %q", l)
448 }
449 c.close()
450
451 // switch acccounts with proper credentials.
452 c, cr, _ = newClientForServer(s)
453 connectOp = "CONNECT {\"user\":\"ua\", \"pass\":\"pa\", \"account\":\"B\"}\r\n"
454 c.parseAsync(connectOp)
455 l, _ = cr.ReadString('\n')
456 if !strings.HasPrefix(l, "-ERR 'Authorization Violation'") {
457 t.Fatalf("Expected an error, got %q", l)
458 }
459 c.close()
460
461 // Even if correct account designation, still make sure we error.
462 c, cr, _ = newClientForServer(s)
463 connectOp = "CONNECT {\"user\":\"ua\", \"pass\":\"pa\", \"account\":\"A\"}\r\n"
464 c.parseAsync(connectOp)
465 l, _ = cr.ReadString('\n')
466 if !strings.HasPrefix(l, "-ERR 'Authorization Violation'") {
467 t.Fatalf("Expected an error, got %q", l)
468 }
469 c.close()
470 }
471
472 func accountNameExists(name string, accounts []*Account) bool {
473 for _, acc := range accounts {
474 if strings.Compare(acc.Name, name) == 0 {
475 return true
476 }
477 }
478 return false
479 }
480
481 func TestAccountSimpleConfig(t *testing.T) {
482 cfg1 := `
483 accounts = [foo, bar]
484 `
485
486 confFileName := createConfFile(t, []byte(cfg1))
487 opts, err := ProcessConfigFile(confFileName)
488 if err != nil {
489 t.Fatalf("Received an error processing config file: %v", err)
490 }
491 if la := len(opts.Accounts); la != 2 {
492 t.Fatalf("Expected to see 2 accounts in opts, got %d", la)
493 }
494 if !accountNameExists("foo", opts.Accounts) {
495 t.Fatal("Expected a 'foo' account")
496 }
497 if !accountNameExists("bar", opts.Accounts) {
498 t.Fatal("Expected a 'bar' account")
499 }
500
501 cfg2 := `
502 accounts = [foo, foo]
503 `
504
505 // Make sure double entries is an error.
506 confFileName = createConfFile(t, []byte(cfg2))
507 _, err = ProcessConfigFile(confFileName)
508 if err == nil {
509 t.Fatalf("Expected an error with double account entries")
510 }
511 }
512
513 func TestAccountParseConfig(t *testing.T) {
514 traceDest := "my.trace.dest"
515 traceSampling := 50
516 confFileName := createConfFile(t, []byte(fmt.Sprintf(`
517 accounts {
518 synadia {
519 users = [
520 {user: alice, password: foo}
521 {user: bob, password: bar}
522 ]
523 }
524 nats.io {
525 msg_trace: {dest: %q, sampling: %d%%}
526 users = [
527 {user: derek, password: foo}
528 {user: ivan, password: bar}
529 ]
530 }
531 }
532 `, traceDest, traceSampling)))
533 opts, err := ProcessConfigFile(confFileName)
534 if err != nil {
535 t.Fatalf("Received an error processing config file: %v", err)
536 }
537
538 if la := len(opts.Accounts); la != 2 {
539 t.Fatalf("Expected to see 2 accounts in opts, got %d", la)
540 }
541
542 if lu := len(opts.Users); lu != 4 {
543 t.Fatalf("Expected 4 total Users, got %d", lu)
544 }
545
546 var natsAcc *Account
547 for _, acc := range opts.Accounts {
548 if acc.Name == "nats.io" {
549 natsAcc = acc
550 break
551 }
552 }
553 if natsAcc == nil {
554 t.Fatalf("Error retrieving account for 'nats.io'")
555 }
556 td, tds := natsAcc.getTraceDestAndSampling()
557 require_Equal[string](t, td, traceDest)
558 require_Equal[int](t, tds, traceSampling)
559
560 for _, u := range opts.Users {
561 if u.Username == "derek" {
562 if u.Account != natsAcc {
563 t.Fatalf("Expected to see the 'nats.io' account, but received %+v", u.Account)
564 }
565 }
566 }
567 }
568
569 func TestAccountParseConfigDuplicateUsers(t *testing.T) {
570 confFileName := createConfFile(t, []byte(`
571 accounts {
572 synadia {
573 users = [
574 {user: alice, password: foo}
575 {user: bob, password: bar}
576 ]
577 }
578 nats.io {
579 users = [
580 {user: alice, password: bar}
581 ]
582 }
583 }
584 `))
585 _, err := ProcessConfigFile(confFileName)
586 if err == nil {
587 t.Fatalf("Expected an error with double user entries")
588 }
589 }
590
591 func TestAccountParseConfigImportsExports(t *testing.T) {
592 opts, err := ProcessConfigFile("./configs/accounts.conf")
593 if err != nil {
594 t.Fatal("parsing failed: ", err)
595 }
596 if la := len(opts.Accounts); la != 3 {
597 t.Fatalf("Expected to see 3 accounts in opts, got %d", la)
598 }
599 if lu := len(opts.Nkeys); lu != 4 {
600 t.Fatalf("Expected 4 total Nkey users, got %d", lu)
601 }
602 if lu := len(opts.Users); lu != 0 {
603 t.Fatalf("Expected no Users, got %d", lu)
604 }
605 var natsAcc, synAcc *Account
606 for _, acc := range opts.Accounts {
607 if acc.Name == "nats.io" {
608 natsAcc = acc
609 } else if acc.Name == "synadia" {
610 synAcc = acc
611 }
612 }
613 if natsAcc == nil {
614 t.Fatalf("Error retrieving account for 'nats.io'")
615 }
616 if natsAcc.Nkey != "AB5UKNPVHDWBP5WODG742274I3OGY5FM3CBIFCYI4OFEH7Y23GNZPXFE" {
617 t.Fatalf("Expected nats account to have an nkey, got %q\n", natsAcc.Nkey)
618 }
619 // Check user assigned to the correct account.
620 for _, nk := range opts.Nkeys {
621 if nk.Nkey == "UBRYMDSRTC6AVJL6USKKS3FIOE466GMEU67PZDGOWYSYHWA7GSKO42VW" {
622 if nk.Account != natsAcc {
623 t.Fatalf("Expected user to be associated with natsAcc, got %q\n", nk.Account.Name)
624 }
625 break
626 }
627 }
628
629 // Now check for the imports and exports of streams and services.
630 if lis := len(natsAcc.imports.streams); lis != 2 {
631 t.Fatalf("Expected 2 imported streams, got %d\n", lis)
632 }
633 for _, si := range natsAcc.imports.streams {
634 if si.from == "public.synadia" {
635 require_True(t, si.atrc)
636 } else {
637 require_False(t, si.atrc)
638 }
639 }
640 if lis := len(natsAcc.imports.services); lis != 1 {
641 t.Fatalf("Expected 1 imported service, got %d\n", lis)
642 }
643 if les := len(natsAcc.exports.services); les != 4 {
644 t.Fatalf("Expected 4 exported services, got %d\n", les)
645 }
646 if les := len(natsAcc.exports.streams); les != 0 {
647 t.Fatalf("Expected no exported streams, got %d\n", les)
648 }
649
650 ea := natsAcc.exports.services["nats.time"]
651 if ea == nil {
652 t.Fatalf("Expected to get a non-nil exportAuth for service")
653 }
654 if ea.respType != Streamed {
655 t.Fatalf("Expected to get a Streamed response type, got %q", ea.respType)
656 }
657 require_True(t, ea.atrc)
658 ea = natsAcc.exports.services["nats.photo"]
659 if ea == nil {
660 t.Fatalf("Expected to get a non-nil exportAuth for service")
661 }
662 if ea.respType != Chunked {
663 t.Fatalf("Expected to get a Chunked response type, got %q", ea.respType)
664 }
665 require_False(t, ea.atrc)
666 ea = natsAcc.exports.services["nats.add"]
667 if ea == nil {
668 t.Fatalf("Expected to get a non-nil exportAuth for service")
669 }
670 if ea.respType != Singleton {
671 t.Fatalf("Expected to get a Singleton response type, got %q", ea.respType)
672 }
673 require_True(t, ea.atrc)
674
675 if synAcc == nil {
676 t.Fatalf("Error retrieving account for 'synadia'")
677 }
678
679 if lis := len(synAcc.imports.streams); lis != 0 {
680 t.Fatalf("Expected no imported streams, got %d\n", lis)
681 }
682 if lis := len(synAcc.imports.services); lis != 1 {
683 t.Fatalf("Expected 1 imported service, got %d\n", lis)
684 }
685 if les := len(synAcc.exports.services); les != 2 {
686 t.Fatalf("Expected 2 exported service, got %d\n", les)
687 }
688 if les := len(synAcc.exports.streams); les != 2 {
689 t.Fatalf("Expected 2 exported streams, got %d\n", les)
690 }
691 }
692
693 func TestImportExportConfigFailures(t *testing.T) {
694 // Import from unknow account
695 cf := createConfFile(t, []byte(`
696 accounts {
697 nats.io {
698 imports = [{stream: {account: "synadia", subject:"foo"}}]
699 }
700 }
701 `))
702 if _, err := ProcessConfigFile(cf); err == nil {
703 t.Fatalf("Expected an error with import from unknown account")
704 }
705 // Import a service with no account.
706 cf = createConfFile(t, []byte(`
707 accounts {
708 nats.io {
709 imports = [{service: subject:"foo.*"}]
710 }
711 }
712 `))
713 if _, err := ProcessConfigFile(cf); err == nil {
714 t.Fatalf("Expected an error with import of a service with no account")
715 }
716 // Import a service with a wildcard subject.
717 cf = createConfFile(t, []byte(`
718 accounts {
719 nats.io {
720 imports = [{service: {account: "nats.io", subject:"foo.*"}]
721 }
722 }
723 `))
724 if _, err := ProcessConfigFile(cf); err == nil {
725 t.Fatalf("Expected an error with import of a service with wildcard subject")
726 }
727 // Export with unknown keyword.
728 cf = createConfFile(t, []byte(`
729 accounts {
730 nats.io {
731 exports = [{service: "foo.*", wat:true}]
732 }
733 }
734 `))
735 if _, err := ProcessConfigFile(cf); err == nil {
736 t.Fatalf("Expected an error with export with unknown keyword")
737 }
738 // Import with unknown keyword.
739 cf = createConfFile(t, []byte(`
740 accounts {
741 nats.io {
742 imports = [{stream: {account: nats.io, subject: "foo.*"}, wat:true}]
743 }
744 }
745 `))
746 if _, err := ProcessConfigFile(cf); err == nil {
747 t.Fatalf("Expected an error with import with unknown keyword")
748 }
749 // Export with an account.
750 cf = createConfFile(t, []byte(`
751 accounts {
752 nats.io {
753 exports = [{service: {account: nats.io, subject:"foo.*"}}]
754 }
755 }
756 `))
757 if _, err := ProcessConfigFile(cf); err == nil {
758 t.Fatalf("Expected an error with export with account")
759 }
760 }
761
762 func TestImportAuthorized(t *testing.T) {
763 _, foo, bar := simpleAccountServer(t)
764
765 checkBool(foo.checkStreamImportAuthorized(bar, "foo", nil), false, t)
766 checkBool(foo.checkStreamImportAuthorized(bar, "*", nil), false, t)
767 checkBool(foo.checkStreamImportAuthorized(bar, ">", nil), false, t)
768 checkBool(foo.checkStreamImportAuthorized(bar, "foo.*", nil), false, t)
769 checkBool(foo.checkStreamImportAuthorized(bar, "foo.>", nil), false, t)
770
771 foo.AddStreamExport("foo", IsPublicExport)
772 checkBool(foo.checkStreamImportAuthorized(bar, "foo", nil), true, t)
773 checkBool(foo.checkStreamImportAuthorized(bar, "bar", nil), false, t)
774 checkBool(foo.checkStreamImportAuthorized(bar, "*", nil), false, t)
775
776 foo.AddStreamExport("*", []*Account{bar})
777 checkBool(foo.checkStreamImportAuthorized(bar, "foo", nil), true, t)
778 checkBool(foo.checkStreamImportAuthorized(bar, "bar", nil), true, t)
779 checkBool(foo.checkStreamImportAuthorized(bar, "baz", nil), true, t)
780 checkBool(foo.checkStreamImportAuthorized(bar, "foo.bar", nil), false, t)
781 checkBool(foo.checkStreamImportAuthorized(bar, ">", nil), false, t)
782 checkBool(foo.checkStreamImportAuthorized(bar, "*", nil), true, t)
783 checkBool(foo.checkStreamImportAuthorized(bar, "foo.*", nil), false, t)
784 checkBool(foo.checkStreamImportAuthorized(bar, "*.*", nil), false, t)
785 checkBool(foo.checkStreamImportAuthorized(bar, "*.>", nil), false, t)
786
787 // Reset and test '>' public export
788 _, foo, bar = simpleAccountServer(t)
789 foo.AddStreamExport(">", nil)
790 // Everything should work.
791 checkBool(foo.checkStreamImportAuthorized(bar, "foo", nil), true, t)
792 checkBool(foo.checkStreamImportAuthorized(bar, "bar", nil), true, t)
793 checkBool(foo.checkStreamImportAuthorized(bar, "baz", nil), true, t)
794 checkBool(foo.checkStreamImportAuthorized(bar, "foo.bar", nil), true, t)
795 checkBool(foo.checkStreamImportAuthorized(bar, ">", nil), true, t)
796 checkBool(foo.checkStreamImportAuthorized(bar, "*", nil), true, t)
797 checkBool(foo.checkStreamImportAuthorized(bar, "foo.*", nil), true, t)
798 checkBool(foo.checkStreamImportAuthorized(bar, "*.*", nil), true, t)
799 checkBool(foo.checkStreamImportAuthorized(bar, "*.>", nil), true, t)
800
801 _, foo, bar = simpleAccountServer(t)
802 foo.addStreamExportWithAccountPos("foo.*", []*Account{}, 2)
803 foo.addStreamExportWithAccountPos("bar.*.foo", []*Account{}, 2)
804 if err := foo.addStreamExportWithAccountPos("baz.*.>", []*Account{}, 3); err == nil {
805 t.Fatal("expected error")
806 }
807 checkBool(foo.checkStreamImportAuthorized(bar, fmt.Sprintf("foo.%s", bar.Name), nil), true, t)
808 checkBool(foo.checkStreamImportAuthorized(bar, fmt.Sprintf("bar.%s.foo", bar.Name), nil), true, t)
809 checkBool(foo.checkStreamImportAuthorized(bar, fmt.Sprintf("baz.foo.%s", bar.Name), nil), false, t)
810 checkBool(foo.checkStreamImportAuthorized(bar, "foo.X", nil), false, t)
811 checkBool(foo.checkStreamImportAuthorized(bar, "bar.X.foo", nil), false, t)
812 checkBool(foo.checkStreamImportAuthorized(bar, "baz.foo.X", nil), false, t)
813
814 foo.addServiceExportWithAccountPos("a.*", []*Account{}, 2)
815 foo.addServiceExportWithAccountPos("b.*.a", []*Account{}, 2)
816 if err := foo.addServiceExportWithAccountPos("c.*.>", []*Account{}, 3); err == nil {
817 t.Fatal("expected error")
818 }
819 checkBool(foo.checkServiceImportAuthorized(bar, fmt.Sprintf("a.%s", bar.Name), nil), true, t)
820 checkBool(foo.checkServiceImportAuthorized(bar, fmt.Sprintf("b.%s.a", bar.Name), nil), true, t)
821 checkBool(foo.checkServiceImportAuthorized(bar, fmt.Sprintf("c.a.%s", bar.Name), nil), false, t)
822 checkBool(foo.checkServiceImportAuthorized(bar, "a.X", nil), false, t)
823 checkBool(foo.checkServiceImportAuthorized(bar, "b.X.a", nil), false, t)
824 checkBool(foo.checkServiceImportAuthorized(bar, "c.a.X", nil), false, t)
825
826 // Reset and test pwc and fwc
827 s, foo, bar := simpleAccountServer(t)
828 foo.AddStreamExport("foo.*.baz.>", []*Account{bar})
829 checkBool(foo.checkStreamImportAuthorized(bar, "foo.bar.baz.1", nil), true, t)
830 checkBool(foo.checkStreamImportAuthorized(bar, "foo.bar.baz.*", nil), true, t)
831 checkBool(foo.checkStreamImportAuthorized(bar, "foo.*.baz.1.1", nil), true, t)
832 checkBool(foo.checkStreamImportAuthorized(bar, "foo.22.baz.22", nil), true, t)
833 checkBool(foo.checkStreamImportAuthorized(bar, "foo.bar.baz", nil), false, t)
834 checkBool(foo.checkStreamImportAuthorized(bar, "", nil), false, t)
835 checkBool(foo.checkStreamImportAuthorized(bar, "foo.bar.*.*", nil), false, t)
836
837 // Make sure we match the account as well
838
839 fb, _ := s.RegisterAccount("foobar")
840 bz, _ := s.RegisterAccount("baz")
841
842 checkBool(foo.checkStreamImportAuthorized(fb, "foo.bar.baz.1", nil), false, t)
843 checkBool(foo.checkStreamImportAuthorized(bz, "foo.bar.baz.1", nil), false, t)
844 }
845
846 func TestSimpleMapping(t *testing.T) {
847 s, fooAcc, barAcc := simpleAccountServer(t)
848 defer s.Shutdown()
849
850 cfoo, _, _ := newClientForServer(s)
851 defer cfoo.close()
852
853 if err := cfoo.registerWithAccount(fooAcc); err != nil {
854 t.Fatalf("Error registering client with 'foo' account: %v", err)
855 }
856 cbar, crBar, _ := newClientForServer(s)
857 defer cbar.close()
858
859 if err := cbar.registerWithAccount(barAcc); err != nil {
860 t.Fatalf("Error registering client with 'bar' account: %v", err)
861 }
862
863 // Test first that trying to import with no matching export permission returns an error.
864 if err := cbar.acc.AddStreamImport(fooAcc, "foo", "import"); err != ErrStreamImportAuthorization {
865 t.Fatalf("Expected error of ErrAccountImportAuthorization but got %v", err)
866 }
867
868 // Now map the subject space between foo and bar.
869 // Need to do export first.
870 if err := cfoo.acc.AddStreamExport("foo", nil); err != nil { // Public with no accounts defined.
871 t.Fatalf("Error adding account export to client foo: %v", err)
872 }
873 if err := cbar.acc.AddStreamImport(fooAcc, "foo", "import"); err != nil {
874 t.Fatalf("Error adding account import to client bar: %v", err)
875 }
876
877 // Normal and Queue Subscription on bar client.
878 if err := cbar.parse([]byte("SUB import.foo 1\r\nSUB import.foo bar 2\r\n")); err != nil {
879 t.Fatalf("Error for client 'bar' from server: %v", err)
880 }
881
882 // Now publish our message.
883 cfoo.parseAsync("PUB foo 5\r\nhello\r\n")
884
885 checkMsg := func(l, sid string) {
886 t.Helper()
887 mraw := msgPat.FindAllStringSubmatch(l, -1)
888 if len(mraw) == 0 {
889 t.Fatalf("No message received")
890 }
891 matches := mraw[0]
892 if matches[SUB_INDEX] != "import.foo" {
893 t.Fatalf("Did not get correct subject: wanted %q, got %q", "import.foo", matches[SUB_INDEX])
894 }
895 if matches[SID_INDEX] != sid {
896 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
897 }
898 }
899
900 // Now check we got the message from normal subscription.
901 l, err := crBar.ReadString('\n')
902 if err != nil {
903 t.Fatalf("Error reading from client 'bar': %v", err)
904 }
905 checkMsg(l, "1")
906 checkPayload(crBar, []byte("hello\r\n"), t)
907
908 l, err = crBar.ReadString('\n')
909 if err != nil {
910 t.Fatalf("Error reading from client 'bar': %v", err)
911 }
912 checkMsg(l, "2")
913 checkPayload(crBar, []byte("hello\r\n"), t)
914
915 // We should have 2 subscriptions in both. Normal and Queue Subscriber
916 // for barAcc which are local, and 2 that are shadowed in fooAcc.
917 // Now make sure that when we unsubscribe we clean up properly for both.
918 if bslc := barAcc.sl.Count(); bslc != 2 {
919 t.Fatalf("Expected 2 normal subscriptions on barAcc, got %d", bslc)
920 }
921 if fslc := fooAcc.sl.Count(); fslc != 2 {
922 t.Fatalf("Expected 2 shadowed subscriptions on fooAcc, got %d", fslc)
923 }
924
925 // Now unsubscribe.
926 if err := cbar.parse([]byte("UNSUB 1\r\nUNSUB 2\r\n")); err != nil {
927 t.Fatalf("Error for client 'bar' from server: %v", err)
928 }
929
930 // We should have zero on both.
931 if bslc := barAcc.sl.Count(); bslc != 0 {
932 t.Fatalf("Expected no normal subscriptions on barAcc, got %d", bslc)
933 }
934 if fslc := fooAcc.sl.Count(); fslc != 0 {
935 t.Fatalf("Expected no shadowed subscriptions on fooAcc, got %d", fslc)
936 }
937 }
938
939 // https://github.com/nats-io/nats-server/issues/1159
940 func TestStreamImportLengthBug(t *testing.T) {
941 s, fooAcc, barAcc := simpleAccountServer(t)
942 defer s.Shutdown()
943
944 cfoo, _, _ := newClientForServer(s)
945 defer cfoo.close()
946
947 if err := cfoo.registerWithAccount(fooAcc); err != nil {
948 t.Fatalf("Error registering client with 'foo' account: %v", err)
949 }
950 cbar, _, _ := newClientForServer(s)
951 defer cbar.close()
952
953 if err := cbar.registerWithAccount(barAcc); err != nil {
954 t.Fatalf("Error registering client with 'bar' account: %v", err)
955 }
956
957 if err := cfoo.acc.AddStreamExport("client.>", nil); err != nil {
958 t.Fatalf("Error adding account export to client foo: %v", err)
959 }
960 if err := cbar.acc.AddStreamImport(fooAcc, "client.>", "events.>"); err == nil {
961 t.Fatalf("Expected an error when using a stream import prefix with a wildcard")
962 }
963
964 if err := cbar.acc.AddStreamImport(fooAcc, "client.>", "events"); err != nil {
965 t.Fatalf("Error adding account import to client bar: %v", err)
966 }
967
968 if err := cbar.parse([]byte("SUB events.> 1\r\n")); err != nil {
969 t.Fatalf("Error for client 'bar' from server: %v", err)
970 }
971
972 // Also make sure that we will get an error from a config version.
973 // JWT will be updated separately.
974 cf := createConfFile(t, []byte(`
975 accounts {
976 foo {
977 exports = [{stream: "client.>"}]
978 }
979 bar {
980 imports = [{stream: {account: "foo", subject:"client.>"}, prefix:"events.>"}]
981 }
982 }
983 `))
984 if _, err := ProcessConfigFile(cf); err == nil {
985 t.Fatalf("Expected an error with import with wildcard prefix")
986 }
987 }
988
989 func TestShadowSubsCleanupOnClientClose(t *testing.T) {
990 s, fooAcc, barAcc := simpleAccountServer(t)
991 defer s.Shutdown()
992
993 // Now map the subject space between foo and bar.
994 // Need to do export first.
995 if err := fooAcc.AddStreamExport("foo", nil); err != nil { // Public with no accounts defined.
996 t.Fatalf("Error adding account export to client foo: %v", err)
997 }
998 if err := barAcc.AddStreamImport(fooAcc, "foo", "import"); err != nil {
999 t.Fatalf("Error adding account import to client bar: %v", err)
1000 }
1001
1002 cbar, _, _ := newClientForServer(s)
1003 defer cbar.close()
1004
1005 if err := cbar.registerWithAccount(barAcc); err != nil {
1006 t.Fatalf("Error registering client with 'bar' account: %v", err)
1007 }
1008
1009 // Normal and Queue Subscription on bar client.
1010 if err := cbar.parse([]byte("SUB import.foo 1\r\nSUB import.foo bar 2\r\n")); err != nil {
1011 t.Fatalf("Error for client 'bar' from server: %v", err)
1012 }
1013
1014 if fslc := fooAcc.sl.Count(); fslc != 2 {
1015 t.Fatalf("Expected 2 shadowed subscriptions on fooAcc, got %d", fslc)
1016 }
1017
1018 // Now close cbar and make sure we remove shadows.
1019 cbar.closeConnection(ClientClosed)
1020
1021 checkFor(t, time.Second, 10*time.Millisecond, func() error {
1022 if fslc := fooAcc.sl.Count(); fslc != 0 {
1023 return fmt.Errorf("Number of shadow subscriptions is %d", fslc)
1024 }
1025 return nil
1026 })
1027 }
1028
1029 func TestNoPrefixWildcardMapping(t *testing.T) {
1030 s, fooAcc, barAcc := simpleAccountServer(t)
1031 defer s.Shutdown()
1032
1033 cfoo, _, _ := newClientForServer(s)
1034 defer cfoo.close()
1035
1036 if err := cfoo.registerWithAccount(fooAcc); err != nil {
1037 t.Fatalf("Error registering client with 'foo' account: %v", err)
1038 }
1039 cbar, crBar, _ := newClientForServer(s)
1040 defer cbar.close()
1041
1042 if err := cbar.registerWithAccount(barAcc); err != nil {
1043 t.Fatalf("Error registering client with 'bar' account: %v", err)
1044 }
1045
1046 if err := cfoo.acc.AddStreamExport(">", []*Account{barAcc}); err != nil {
1047 t.Fatalf("Error adding stream export to client foo: %v", err)
1048 }
1049 if err := cbar.acc.AddStreamImport(fooAcc, "*", ""); err != nil {
1050 t.Fatalf("Error adding stream import to client bar: %v", err)
1051 }
1052
1053 // Normal Subscription on bar client for literal "foo".
1054 cbar.parseAsync("SUB foo 1\r\nPING\r\n")
1055 _, err := crBar.ReadString('\n') // Make sure subscriptions were processed.
1056 if err != nil {
1057 t.Fatalf("Error for client 'bar' from server: %v", err)
1058 }
1059
1060 // Now publish our message.
1061 cfoo.parseAsync("PUB foo 5\r\nhello\r\n")
1062
1063 // Now check we got the message from normal subscription.
1064 l, err := crBar.ReadString('\n')
1065 if err != nil {
1066 t.Fatalf("Error reading from client 'bar': %v", err)
1067 }
1068 mraw := msgPat.FindAllStringSubmatch(l, -1)
1069 if len(mraw) == 0 {
1070 t.Fatalf("No message received")
1071 }
1072 matches := mraw[0]
1073 if matches[SUB_INDEX] != "foo" {
1074 t.Fatalf("Did not get correct subject: '%s'", matches[SUB_INDEX])
1075 }
1076 if matches[SID_INDEX] != "1" {
1077 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1078 }
1079 checkPayload(crBar, []byte("hello\r\n"), t)
1080 }
1081
1082 func TestPrefixWildcardMapping(t *testing.T) {
1083 s, fooAcc, barAcc := simpleAccountServer(t)
1084 defer s.Shutdown()
1085
1086 cfoo, _, _ := newClientForServer(s)
1087 defer cfoo.close()
1088
1089 if err := cfoo.registerWithAccount(fooAcc); err != nil {
1090 t.Fatalf("Error registering client with 'foo' account: %v", err)
1091 }
1092 cbar, crBar, _ := newClientForServer(s)
1093 defer cbar.close()
1094
1095 if err := cbar.registerWithAccount(barAcc); err != nil {
1096 t.Fatalf("Error registering client with 'bar' account: %v", err)
1097 }
1098
1099 if err := cfoo.acc.AddStreamExport(">", []*Account{barAcc}); err != nil {
1100 t.Fatalf("Error adding stream export to client foo: %v", err)
1101 }
1102 // Checking that trailing '.' is accepted, tested that it is auto added above.
1103 if err := cbar.acc.AddStreamImport(fooAcc, "*", "pub.imports."); err != nil {
1104 t.Fatalf("Error adding stream import to client bar: %v", err)
1105 }
1106
1107 // Normal Subscription on bar client for wildcard.
1108 cbar.parseAsync("SUB pub.imports.* 1\r\nPING\r\n")
1109 _, err := crBar.ReadString('\n') // Make sure subscriptions were processed.
1110 if err != nil {
1111 t.Fatalf("Error for client 'bar' from server: %v", err)
1112 }
1113
1114 // Now publish our message.
1115 cfoo.parseAsync("PUB foo 5\r\nhello\r\n")
1116
1117 // Now check we got the messages from wildcard subscription.
1118 l, err := crBar.ReadString('\n')
1119 if err != nil {
1120 t.Fatalf("Error reading from client 'bar': %v", err)
1121 }
1122 mraw := msgPat.FindAllStringSubmatch(l, -1)
1123 if len(mraw) == 0 {
1124 t.Fatalf("No message received")
1125 }
1126 matches := mraw[0]
1127 if matches[SUB_INDEX] != "pub.imports.foo" {
1128 t.Fatalf("Did not get correct subject: '%s'", matches[SUB_INDEX])
1129 }
1130 if matches[SID_INDEX] != "1" {
1131 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1132 }
1133 checkPayload(crBar, []byte("hello\r\n"), t)
1134 }
1135
1136 func TestPrefixWildcardMappingWithLiteralSub(t *testing.T) {
1137 s, fooAcc, barAcc := simpleAccountServer(t)
1138 defer s.Shutdown()
1139
1140 cfoo, _, _ := newClientForServer(s)
1141 defer cfoo.close()
1142
1143 if err := cfoo.registerWithAccount(fooAcc); err != nil {
1144 t.Fatalf("Error registering client with 'foo' account: %v", err)
1145 }
1146 cbar, crBar, _ := newClientForServer(s)
1147 defer cbar.close()
1148
1149 if err := cbar.registerWithAccount(barAcc); err != nil {
1150 t.Fatalf("Error registering client with 'bar' account: %v", err)
1151 }
1152
1153 if err := fooAcc.AddStreamExport(">", []*Account{barAcc}); err != nil {
1154 t.Fatalf("Error adding stream export to client foo: %v", err)
1155 }
1156 if err := barAcc.AddStreamImport(fooAcc, "*", "pub.imports."); err != nil {
1157 t.Fatalf("Error adding stream import to client bar: %v", err)
1158 }
1159
1160 // Normal Subscription on bar client for wildcard.
1161 cbar.parseAsync("SUB pub.imports.foo 1\r\nPING\r\n")
1162 _, err := crBar.ReadString('\n') // Make sure subscriptions were processed.
1163 if err != nil {
1164 t.Fatalf("Error for client 'bar' from server: %v", err)
1165 }
1166
1167 // Now publish our message.
1168 cfoo.parseAsync("PUB foo 5\r\nhello\r\n")
1169
1170 // Now check we got the messages from wildcard subscription.
1171 l, err := crBar.ReadString('\n')
1172 if err != nil {
1173 t.Fatalf("Error reading from client 'bar': %v", err)
1174 }
1175 mraw := msgPat.FindAllStringSubmatch(l, -1)
1176 if len(mraw) == 0 {
1177 t.Fatalf("No message received")
1178 }
1179 matches := mraw[0]
1180 if matches[SUB_INDEX] != "pub.imports.foo" {
1181 t.Fatalf("Did not get correct subject: '%s'", matches[SUB_INDEX])
1182 }
1183 if matches[SID_INDEX] != "1" {
1184 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1185 }
1186 checkPayload(crBar, []byte("hello\r\n"), t)
1187 }
1188
1189 func TestMultipleImportsAndSingleWCSub(t *testing.T) {
1190 s, fooAcc, barAcc := simpleAccountServer(t)
1191 defer s.Shutdown()
1192
1193 cfoo, _, _ := newClientForServer(s)
1194 defer cfoo.close()
1195
1196 if err := cfoo.registerWithAccount(fooAcc); err != nil {
1197 t.Fatalf("Error registering client with 'foo' account: %v", err)
1198 }
1199 cbar, crBar, _ := newClientForServer(s)
1200 defer cbar.close()
1201
1202 if err := cbar.registerWithAccount(barAcc); err != nil {
1203 t.Fatalf("Error registering client with 'bar' account: %v", err)
1204 }
1205
1206 if err := fooAcc.AddStreamExport("foo", []*Account{barAcc}); err != nil {
1207 t.Fatalf("Error adding stream export to account foo: %v", err)
1208 }
1209 if err := fooAcc.AddStreamExport("bar", []*Account{barAcc}); err != nil {
1210 t.Fatalf("Error adding stream export to account foo: %v", err)
1211 }
1212
1213 if err := barAcc.AddStreamImport(fooAcc, "foo", "pub."); err != nil {
1214 t.Fatalf("Error adding stream import to account bar: %v", err)
1215 }
1216 if err := barAcc.AddStreamImport(fooAcc, "bar", "pub."); err != nil {
1217 t.Fatalf("Error adding stream import to account bar: %v", err)
1218 }
1219
1220 // Wildcard Subscription on bar client for both imports.
1221 cbar.parse([]byte("SUB pub.* 1\r\n"))
1222
1223 // Now publish a message on 'foo' and 'bar'
1224 cfoo.parseAsync("PUB foo 5\r\nhello\r\nPUB bar 5\r\nworld\r\n")
1225
1226 // Now check we got the messages from the wildcard subscription.
1227 l, err := crBar.ReadString('\n')
1228 if err != nil {
1229 t.Fatalf("Error reading from client 'bar': %v", err)
1230 }
1231 mraw := msgPat.FindAllStringSubmatch(l, -1)
1232 if len(mraw) == 0 {
1233 t.Fatalf("No message received")
1234 }
1235 matches := mraw[0]
1236 if matches[SUB_INDEX] != "pub.foo" {
1237 t.Fatalf("Did not get correct subject: '%s'", matches[SUB_INDEX])
1238 }
1239 if matches[SID_INDEX] != "1" {
1240 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1241 }
1242 checkPayload(crBar, []byte("hello\r\n"), t)
1243
1244 l, err = crBar.ReadString('\n')
1245 if err != nil {
1246 t.Fatalf("Error reading from client 'bar': %v", err)
1247 }
1248 mraw = msgPat.FindAllStringSubmatch(l, -1)
1249 if len(mraw) == 0 {
1250 t.Fatalf("No message received")
1251 }
1252 matches = mraw[0]
1253 if matches[SUB_INDEX] != "pub.bar" {
1254 t.Fatalf("Did not get correct subject: '%s'", matches[SUB_INDEX])
1255 }
1256 if matches[SID_INDEX] != "1" {
1257 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1258 }
1259 checkPayload(crBar, []byte("world\r\n"), t)
1260
1261 // Check subscription count.
1262 if fslc := fooAcc.sl.Count(); fslc != 2 {
1263 t.Fatalf("Expected 2 shadowed subscriptions on fooAcc, got %d", fslc)
1264 }
1265 if bslc := barAcc.sl.Count(); bslc != 1 {
1266 t.Fatalf("Expected 1 normal subscriptions on barAcc, got %d", bslc)
1267 }
1268
1269 // Now unsubscribe.
1270 if err := cbar.parse([]byte("UNSUB 1\r\n")); err != nil {
1271 t.Fatalf("Error for client 'bar' from server: %v", err)
1272 }
1273 // We should have zero on both.
1274 if bslc := barAcc.sl.Count(); bslc != 0 {
1275 t.Fatalf("Expected no normal subscriptions on barAcc, got %d", bslc)
1276 }
1277 if fslc := fooAcc.sl.Count(); fslc != 0 {
1278 t.Fatalf("Expected no shadowed subscriptions on fooAcc, got %d", fslc)
1279 }
1280 }
1281
1282 // Make sure the AddServiceExport function is additive if called multiple times.
1283 func TestAddServiceExport(t *testing.T) {
1284 s, fooAcc, barAcc := simpleAccountServer(t)
1285 bazAcc, err := s.RegisterAccount("$baz")
1286 if err != nil {
1287 t.Fatalf("Error creating account 'baz': %v", err)
1288 }
1289 defer s.Shutdown()
1290
1291 if err := fooAcc.AddServiceExport("test.request", nil); err != nil {
1292 t.Fatalf("Error adding account service export to client foo: %v", err)
1293 }
1294 tr := fooAcc.exports.services["test.request"]
1295 if len(tr.approved) != 0 {
1296 t.Fatalf("Expected no authorized accounts, got %d", len(tr.approved))
1297 }
1298 if err := fooAcc.AddServiceExport("test.request", []*Account{barAcc}); err != nil {
1299 t.Fatalf("Error adding account service export to client foo: %v", err)
1300 }
1301 tr = fooAcc.exports.services["test.request"]
1302 if tr == nil {
1303 t.Fatalf("Expected authorized accounts, got nil")
1304 }
1305 if ls := len(tr.approved); ls != 1 {
1306 t.Fatalf("Expected 1 authorized accounts, got %d", ls)
1307 }
1308 if err := fooAcc.AddServiceExport("test.request", []*Account{bazAcc}); err != nil {
1309 t.Fatalf("Error adding account service export to client foo: %v", err)
1310 }
1311 tr = fooAcc.exports.services["test.request"]
1312 if tr == nil {
1313 t.Fatalf("Expected authorized accounts, got nil")
1314 }
1315 if ls := len(tr.approved); ls != 2 {
1316 t.Fatalf("Expected 2 authorized accounts, got %d", ls)
1317 }
1318 }
1319
1320 func TestServiceExportWithWildcards(t *testing.T) {
1321 for _, test := range []struct {
1322 name string
1323 public bool
1324 }{
1325 {
1326 name: "public",
1327 public: true,
1328 },
1329 {
1330 name: "private",
1331 public: false,
1332 },
1333 } {
1334 t.Run(test.name, func(t *testing.T) {
1335 s, fooAcc, barAcc := simpleAccountServer(t)
1336 defer s.Shutdown()
1337
1338 var accs []*Account
1339 if !test.public {
1340 accs = []*Account{barAcc}
1341 }
1342 // Add service export with a wildcard
1343 if err := fooAcc.AddServiceExport("ngs.update.*", accs); err != nil {
1344 t.Fatalf("Error adding account service export: %v", err)
1345 }
1346 // Import on bar account
1347 if err := barAcc.AddServiceImport(fooAcc, "ngs.update", "ngs.update.$bar"); err != nil {
1348 t.Fatalf("Error adding account service import: %v", err)
1349 }
1350
1351 cfoo, crFoo, _ := newClientForServer(s)
1352 defer cfoo.close()
1353
1354 if err := cfoo.registerWithAccount(fooAcc); err != nil {
1355 t.Fatalf("Error registering client with 'foo' account: %v", err)
1356 }
1357 cbar, crBar, _ := newClientForServer(s)
1358 defer cbar.close()
1359
1360 if err := cbar.registerWithAccount(barAcc); err != nil {
1361 t.Fatalf("Error registering client with 'bar' account: %v", err)
1362 }
1363
1364 // Now setup the responder under cfoo
1365 cfoo.parse([]byte("SUB ngs.update.* 1\r\n"))
1366
1367 // Now send the request. Remember we expect the request on our local ngs.update.
1368 // We added the route with that "from" and will map it to "ngs.update.$bar"
1369 cbar.parseAsync("SUB reply 11\r\nPUB ngs.update reply 4\r\nhelp\r\n")
1370
1371 // Now read the request from crFoo
1372 l, err := crFoo.ReadString('\n')
1373 if err != nil {
1374 t.Fatalf("Error reading from client 'bar': %v", err)
1375 }
1376
1377 mraw := msgPat.FindAllStringSubmatch(l, -1)
1378 if len(mraw) == 0 {
1379 t.Fatalf("No message received")
1380 }
1381 matches := mraw[0]
1382 if matches[SUB_INDEX] != "ngs.update.$bar" {
1383 t.Fatalf("Did not get correct subject: '%s'", matches[SUB_INDEX])
1384 }
1385 if matches[SID_INDEX] != "1" {
1386 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1387 }
1388 // Make sure this looks like _INBOX
1389 if !strings.HasPrefix(matches[REPLY_INDEX], "_R_.") {
1390 t.Fatalf("Expected an _R_.* like reply, got '%s'", matches[REPLY_INDEX])
1391 }
1392 checkPayload(crFoo, []byte("help\r\n"), t)
1393
1394 replyOp := fmt.Sprintf("PUB %s 2\r\n22\r\n", matches[REPLY_INDEX])
1395 cfoo.parseAsync(replyOp)
1396
1397 // Now read the response from crBar
1398 l, err = crBar.ReadString('\n')
1399 if err != nil {
1400 t.Fatalf("Error reading from client 'bar': %v", err)
1401 }
1402 mraw = msgPat.FindAllStringSubmatch(l, -1)
1403 if len(mraw) == 0 {
1404 t.Fatalf("No message received")
1405 }
1406 matches = mraw[0]
1407 if matches[SUB_INDEX] != "reply" {
1408 t.Fatalf("Did not get correct subject: '%s'", matches[SUB_INDEX])
1409 }
1410 if matches[SID_INDEX] != "11" {
1411 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1412 }
1413 if matches[REPLY_INDEX] != "" {
1414 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1415 }
1416 checkPayload(crBar, []byte("22\r\n"), t)
1417
1418 if nr := barAcc.NumPendingAllResponses(); nr != 0 {
1419 t.Fatalf("Expected no responses on barAcc, got %d", nr)
1420 }
1421 })
1422 }
1423 }
1424
1425 func TestAccountAddServiceImportRace(t *testing.T) {
1426 s, fooAcc, barAcc := simpleAccountServer(t)
1427 defer s.Shutdown()
1428
1429 if err := fooAcc.AddServiceExport("foo.*", nil); err != nil {
1430 t.Fatalf("Error adding account service export to client foo: %v", err)
1431 }
1432
1433 total := 100
1434 errCh := make(chan error, total)
1435 for i := 0; i < 100; i++ {
1436 go func(i int) {
1437 err := barAcc.AddServiceImport(fooAcc, fmt.Sprintf("foo.%d", i), "")
1438 errCh <- err // nil is a valid value.
1439 }(i)
1440 }
1441
1442 for i := 0; i < 100; i++ {
1443 err := <-errCh
1444 if err != nil {
1445 t.Fatalf("Error adding account service import: %v", err)
1446 }
1447 }
1448
1449 barAcc.mu.Lock()
1450 lens := len(barAcc.imports.services)
1451 c := barAcc.internalClient()
1452 barAcc.mu.Unlock()
1453 if lens != total {
1454 t.Fatalf("Expected %d imported services, got %d", total, lens)
1455 }
1456 c.mu.Lock()
1457 lens = len(c.subs)
1458 c.mu.Unlock()
1459 if lens != total {
1460 t.Fatalf("Expected %d subscriptions in internal client, got %d", total, lens)
1461 }
1462 }
1463
1464 func TestServiceImportWithWildcards(t *testing.T) {
1465 s, fooAcc, barAcc := simpleAccountServer(t)
1466 defer s.Shutdown()
1467
1468 if err := fooAcc.AddServiceExport("test.*", nil); err != nil {
1469 t.Fatalf("Error adding account service export to client foo: %v", err)
1470 }
1471 // We can not map wildcards atm, so if we supply a to mapping and a wildcard we should fail.
1472 if err := barAcc.AddServiceImport(fooAcc, "test.*", "foo"); err == nil {
1473 t.Fatalf("Expected error adding account service import with wildcard and mapping, got none")
1474 }
1475 if err := barAcc.AddServiceImport(fooAcc, "test.>", ""); err == nil {
1476 t.Fatalf("Expected error adding account service import with broader wildcard, got none")
1477 }
1478 // This should work.
1479 if err := barAcc.AddServiceImport(fooAcc, "test.*", ""); err != nil {
1480 t.Fatalf("Error adding account service import: %v", err)
1481 }
1482 // Make sure we can send and receive.
1483 cfoo, crFoo, _ := newClientForServer(s)
1484 defer cfoo.close()
1485
1486 if err := cfoo.registerWithAccount(fooAcc); err != nil {
1487 t.Fatalf("Error registering client with 'foo' account: %v", err)
1488 }
1489
1490 // Now setup the resonder under cfoo
1491 cfoo.parse([]byte("SUB test.* 1\r\n"))
1492
1493 cbar, crBar, _ := newClientForServer(s)
1494 defer cbar.close()
1495
1496 if err := cbar.registerWithAccount(barAcc); err != nil {
1497 t.Fatalf("Error registering client with 'bar' account: %v", err)
1498 }
1499
1500 // Now send the request.
1501 go cbar.parse([]byte("SUB bar 11\r\nPUB test.22 bar 4\r\nhelp\r\n"))
1502
1503 // Now read the request from crFoo
1504 l, err := crFoo.ReadString('\n')
1505 if err != nil {
1506 t.Fatalf("Error reading from client 'bar': %v", err)
1507 }
1508
1509 mraw := msgPat.FindAllStringSubmatch(l, -1)
1510 if len(mraw) == 0 {
1511 t.Fatalf("No message received")
1512 }
1513 matches := mraw[0]
1514 if matches[SUB_INDEX] != "test.22" {
1515 t.Fatalf("Did not get correct subject: '%s'", matches[SUB_INDEX])
1516 }
1517 if matches[SID_INDEX] != "1" {
1518 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1519 }
1520 // Make sure this looks like _INBOX
1521 if !strings.HasPrefix(matches[REPLY_INDEX], "_R_.") {
1522 t.Fatalf("Expected an _R_.* like reply, got '%s'", matches[REPLY_INDEX])
1523 }
1524 checkPayload(crFoo, []byte("help\r\n"), t)
1525
1526 replyOp := fmt.Sprintf("PUB %s 2\r\n22\r\n", matches[REPLY_INDEX])
1527 go cfoo.parse([]byte(replyOp))
1528
1529 // Now read the response from crBar
1530 l, err = crBar.ReadString('\n')
1531 if err != nil {
1532 t.Fatalf("Error reading from client 'bar': %v", err)
1533 }
1534 mraw = msgPat.FindAllStringSubmatch(l, -1)
1535 if len(mraw) == 0 {
1536 t.Fatalf("No message received")
1537 }
1538 matches = mraw[0]
1539 if matches[SUB_INDEX] != "bar" {
1540 t.Fatalf("Did not get correct subject: '%s'", matches[SUB_INDEX])
1541 }
1542 if matches[SID_INDEX] != "11" {
1543 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1544 }
1545 if matches[REPLY_INDEX] != "" {
1546 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1547 }
1548 checkPayload(crBar, []byte("22\r\n"), t)
1549
1550 // Remove the service import with the wildcard and make sure hasWC is cleared.
1551 barAcc.removeServiceImport(fooAcc.Name, "test.*")
1552
1553 barAcc.mu.Lock()
1554 defer barAcc.mu.Unlock()
1555 if len(barAcc.imports.services) != 0 {
1556 t.Fatalf("Expected no imported services, got %d", len(barAcc.imports.services))
1557 }
1558 }
1559
1560 // Make sure the AddStreamExport function is additive if called multiple times.
1561 func TestAddStreamExport(t *testing.T) {
1562 s, fooAcc, barAcc := simpleAccountServer(t)
1563 bazAcc, err := s.RegisterAccount("$baz")
1564 if err != nil {
1565 t.Fatalf("Error creating account 'baz': %v", err)
1566 }
1567 defer s.Shutdown()
1568
1569 if err := fooAcc.AddStreamExport("test.request", nil); err != nil {
1570 t.Fatalf("Error adding account service export to client foo: %v", err)
1571 }
1572 tr := fooAcc.exports.streams["test.request"]
1573 if tr != nil {
1574 t.Fatalf("Expected no authorized accounts, got %d", len(tr.approved))
1575 }
1576 if err := fooAcc.AddStreamExport("test.request", []*Account{barAcc}); err != nil {
1577 t.Fatalf("Error adding account service export to client foo: %v", err)
1578 }
1579 tr = fooAcc.exports.streams["test.request"]
1580 if tr == nil {
1581 t.Fatalf("Expected authorized accounts, got nil")
1582 }
1583 if ls := len(tr.approved); ls != 1 {
1584 t.Fatalf("Expected 1 authorized accounts, got %d", ls)
1585 }
1586 if err := fooAcc.AddStreamExport("test.request", []*Account{bazAcc}); err != nil {
1587 t.Fatalf("Error adding account service export to client foo: %v", err)
1588 }
1589 tr = fooAcc.exports.streams["test.request"]
1590 if tr == nil {
1591 t.Fatalf("Expected authorized accounts, got nil")
1592 }
1593 if ls := len(tr.approved); ls != 2 {
1594 t.Fatalf("Expected 2 authorized accounts, got %d", ls)
1595 }
1596 }
1597
1598 func TestCrossAccountRequestReply(t *testing.T) {
1599 s, fooAcc, barAcc := simpleAccountServer(t)
1600 defer s.Shutdown()
1601
1602 cfoo, crFoo, _ := newClientForServer(s)
1603 defer cfoo.close()
1604
1605 if err := cfoo.registerWithAccount(fooAcc); err != nil {
1606 t.Fatalf("Error registering client with 'foo' account: %v", err)
1607 }
1608
1609 cbar, crBar, _ := newClientForServer(s)
1610 defer cbar.close()
1611
1612 if err := cbar.registerWithAccount(barAcc); err != nil {
1613 t.Fatalf("Error registering client with 'bar' account: %v", err)
1614 }
1615
1616 // Add in the service export for the requests. Make it public.
1617 if err := cfoo.acc.AddServiceExport("test.request", nil); err != nil {
1618 t.Fatalf("Error adding account service export to client foo: %v", err)
1619 }
1620
1621 // Test addServiceImport to make sure it requires accounts.
1622 if err := cbar.acc.AddServiceImport(nil, "foo", "test.request"); err != ErrMissingAccount {
1623 t.Fatalf("Expected ErrMissingAccount but received %v.", err)
1624 }
1625 if err := cbar.acc.AddServiceImport(fooAcc, "foo", "test..request."); err != ErrInvalidSubject {
1626 t.Fatalf("Expected ErrInvalidSubject but received %v.", err)
1627 }
1628
1629 // Now add in the route mapping for request to be routed to the foo account.
1630 if err := cbar.acc.AddServiceImport(fooAcc, "foo", "test.request"); err != nil {
1631 t.Fatalf("Error adding account service import to client bar: %v", err)
1632 }
1633
1634 // Now setup the resonder under cfoo
1635 cfoo.parse([]byte("SUB test.request 1\r\n"))
1636
1637 // Now send the request. Remember we expect the request on our local foo. We added the route
1638 // with that "from" and will map it to "test.request"
1639 cbar.parseAsync("SUB bar 11\r\nPUB foo bar 4\r\nhelp\r\n")
1640
1641 // Now read the request from crFoo
1642 l, err := crFoo.ReadString('\n')
1643 if err != nil {
1644 t.Fatalf("Error reading from client 'bar': %v", err)
1645 }
1646
1647 mraw := msgPat.FindAllStringSubmatch(l, -1)
1648 if len(mraw) == 0 {
1649 t.Fatalf("No message received")
1650 }
1651 matches := mraw[0]
1652 if matches[SUB_INDEX] != "test.request" {
1653 t.Fatalf("Did not get correct subject: '%s'", matches[SUB_INDEX])
1654 }
1655 if matches[SID_INDEX] != "1" {
1656 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1657 }
1658 // Make sure this looks like _INBOX
1659 if !strings.HasPrefix(matches[REPLY_INDEX], "_R_.") {
1660 t.Fatalf("Expected an _R_.* like reply, got '%s'", matches[REPLY_INDEX])
1661 }
1662 checkPayload(crFoo, []byte("help\r\n"), t)
1663
1664 replyOp := fmt.Sprintf("PUB %s 2\r\n22\r\n", matches[REPLY_INDEX])
1665 cfoo.parseAsync(replyOp)
1666
1667 // Now read the response from crBar
1668 l, err = crBar.ReadString('\n')
1669 if err != nil {
1670 t.Fatalf("Error reading from client 'bar': %v", err)
1671 }
1672 mraw = msgPat.FindAllStringSubmatch(l, -1)
1673 if len(mraw) == 0 {
1674 t.Fatalf("No message received")
1675 }
1676 matches = mraw[0]
1677 if matches[SUB_INDEX] != "bar" {
1678 t.Fatalf("Did not get correct subject: '%s'", matches[SUB_INDEX])
1679 }
1680 if matches[SID_INDEX] != "11" {
1681 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1682 }
1683 if matches[REPLY_INDEX] != "" {
1684 t.Fatalf("Did not get correct sid: '%s'", matches[SID_INDEX])
1685 }
1686 checkPayload(crBar, []byte("22\r\n"), t)
1687
1688 if nr := barAcc.NumPendingAllResponses(); nr != 0 {
1689 t.Fatalf("Expected no responses on barAcc, got %d", nr)
1690 }
1691 }
1692
1693 func TestAccountRequestReplyTrackLatency(t *testing.T) {
1694 s, fooAcc, barAcc := simpleAccountServer(t)
1695 defer s.Shutdown()
1696
1697 // Run server in Go routine. We need this one running for internal sending of msgs.
1698 s.Start()
1699 // Wait for accept loop(s) to be started
1700 if err := s.readyForConnections(10 * time.Second); err != nil {
1701 t.Fatal(err)
1702 }
1703
1704 cfoo, crFoo, _ := newClientForServer(s)
1705 defer cfoo.close()
1706
1707 if err := cfoo.registerWithAccount(fooAcc); err != nil {
1708 t.Fatalf("Error registering client with 'foo' account: %v", err)
1709 }
1710
1711 cbar, crBar, _ := newClientForServer(s)
1712 defer cbar.close()
1713
1714 if err := cbar.registerWithAccount(barAcc); err != nil {
1715 t.Fatalf("Error registering client with 'bar' account: %v", err)
1716 }
1717
1718 // Add in the service export for the requests. Make it public.
1719 if err := fooAcc.AddServiceExport("track.service", nil); err != nil {
1720 t.Fatalf("Error adding account service export to client foo: %v", err)
1721 }
1722
1723 // Now let's add in tracking
1724
1725 // First check we get an error if service does not exist.
1726 if err := fooAcc.TrackServiceExport("track.wrong", "results"); err != ErrMissingService {
1727 t.Fatalf("Expected error enabling tracking latency for wrong service")
1728 }
1729 // Check results should be a valid subject
1730 if err := fooAcc.TrackServiceExport("track.service", "results.*"); err != ErrBadPublishSubject {
1731 t.Fatalf("Expected error enabling tracking latency for bad results subject")
1732 }
1733 // Make sure we can not loop around on ourselves..
1734 if err := fooAcc.TrackServiceExport("track.service", "track.service"); err != ErrBadPublishSubject {
1735 t.Fatalf("Expected error enabling tracking latency for same subject")
1736 }
1737 // Check bad sampling
1738 if err := fooAcc.TrackServiceExportWithSampling("track.service", "results", -1); err != ErrBadSampling {
1739 t.Fatalf("Expected error enabling tracking latency for bad sampling")
1740 }
1741 if err := fooAcc.TrackServiceExportWithSampling("track.service", "results", 101); err != ErrBadSampling {
1742 t.Fatalf("Expected error enabling tracking latency for bad sampling")
1743 }
1744
1745 // Now let's add in tracking for real. This will be 100%
1746 if err := fooAcc.TrackServiceExport("track.service", "results"); err != nil {
1747 t.Fatalf("Error enabling tracking latency: %v", err)
1748 }
1749
1750 // Now add in the route mapping for request to be routed to the foo account.
1751 if err := barAcc.AddServiceImport(fooAcc, "req", "track.service"); err != nil {
1752 t.Fatalf("Error adding account service import to client bar: %v", err)
1753 }
1754
1755 // Now setup the responder under cfoo and the listener for the results
1756 cfoo.parse([]byte("SUB track.service 1\r\nSUB results 2\r\n"))
1757
1758 readFooMsg := func() ([]byte, string) {
1759 t.Helper()
1760 l, err := crFoo.ReadString('\n')
1761 if err != nil {
1762 t.Fatalf("Error reading from client 'foo': %v", err)
1763 }
1764 mraw := msgPat.FindAllStringSubmatch(l, -1)
1765 if len(mraw) == 0 {
1766 t.Fatalf("No message received")
1767 }
1768 msg := mraw[0]
1769 msgSize, _ := strconv.Atoi(msg[LEN_INDEX])
1770 return grabPayload(crFoo, msgSize), msg[REPLY_INDEX]
1771 }
1772
1773 start := time.Now()
1774
1775 // Now send the request. Remember we expect the request on our local foo. We added the route
1776 // with that "from" and will map it to "test.request"
1777 cbar.parseAsync("SUB resp 11\r\nPUB req resp 4\r\nhelp\r\n")
1778
1779 // Now read the request from crFoo
1780 _, reply := readFooMsg()
1781 replyOp := fmt.Sprintf("PUB %s 2\r\n22\r\n", reply)
1782
1783 serviceTime := 25 * time.Millisecond
1784
1785 // We will wait a bit to check latency results
1786 go func() {
1787 time.Sleep(serviceTime)
1788 cfoo.parseAsync(replyOp)
1789 }()
1790
1791 // Now read the response from crBar
1792 _, err := crBar.ReadString('\n')
1793 if err != nil {
1794 t.Fatalf("Error reading from client 'bar': %v", err)
1795 }
1796
1797 // Now let's check that we got the sampling results
1798 rMsg, _ := readFooMsg()
1799
1800 // Unmarshal and check it.
1801 var sl ServiceLatency
1802 err = json.Unmarshal(rMsg, &sl)
1803 if err != nil {
1804 t.Fatalf("Could not parse latency json: %v\n", err)
1805 }
1806 startDelta := sl.RequestStart.Sub(start)
1807 if startDelta > 5*time.Millisecond {
1808 t.Fatalf("Bad start delta %v", startDelta)
1809 }
1810 if sl.ServiceLatency < serviceTime {
1811 t.Fatalf("Bad service latency: %v", sl.ServiceLatency)
1812 }
1813 if sl.TotalLatency < sl.ServiceLatency {
1814 t.Fatalf("Bad total latency: %v", sl.ServiceLatency)
1815 }
1816 }
1817
1818 // This will test for leaks in the remote latency tracking via client.rrTracking
1819 func TestAccountTrackLatencyRemoteLeaks(t *testing.T) {
1820 optsA, err := ProcessConfigFile("./configs/seed.conf")
1821 require_NoError(t, err)
1822 optsA.NoSigs, optsA.NoLog = true, true
1823 optsA.ServerName = "A"
1824 srvA := RunServer(optsA)
1825 defer srvA.Shutdown()
1826 optsB := nextServerOpts(optsA)
1827 optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host, optsA.Cluster.Port))
1828 optsB.ServerName = "B"
1829 srvB := RunServer(optsB)
1830 defer srvB.Shutdown()
1831
1832 checkClusterFormed(t, srvA, srvB)
1833 srvs := []*Server{srvA, srvB}
1834
1835 // Now add in the accounts and setup tracking.
1836 for _, s := range srvs {
1837 s.SetSystemAccount(globalAccountName)
1838 fooAcc, _ := s.RegisterAccount("$foo")
1839 fooAcc.AddServiceExport("track.service", nil)
1840 fooAcc.TrackServiceExport("track.service", "results")
1841 barAcc, _ := s.RegisterAccount("$bar")
1842 if err := barAcc.AddServiceImport(fooAcc, "req", "track.service"); err != nil {
1843 t.Fatalf("Failed to import: %v", err)
1844 }
1845 }
1846
1847 getClient := func(s *Server, name string) *client {
1848 t.Helper()
1849 s.mu.Lock()
1850 defer s.mu.Unlock()
1851 for _, c := range s.clients {
1852 c.mu.Lock()
1853 n := c.opts.Name
1854 c.mu.Unlock()
1855 if n == name {
1856 return c
1857 }
1858 }
1859 t.Fatalf("Did not find client %q on server %q", name, s.info.ID)
1860 return nil
1861 }
1862
1863 // Test with a responder on second server, srvB. but they will not respond.
1864 cfooNC := natsConnect(t, srvB.ClientURL(), nats.Name("foo"))
1865 defer cfooNC.Close()
1866 cfoo := getClient(srvB, "foo")
1867 fooAcc, _ := srvB.LookupAccount("$foo")
1868 if err := cfoo.registerWithAccount(fooAcc); err != nil {
1869 t.Fatalf("Error registering client with 'foo' account: %v", err)
1870 }
1871
1872 // Set new limits
1873 for _, srv := range srvs {
1874 fooAcc, _ := srv.LookupAccount("$foo")
1875 err := fooAcc.SetServiceExportResponseThreshold("track.service", 5*time.Millisecond)
1876 if err != nil {
1877 t.Fatalf("Error setting response threshold: %v", err)
1878 }
1879 }
1880
1881 // Now setup the responder under cfoo and the listener for the results
1882 time.Sleep(50 * time.Millisecond)
1883 baseSubs := int(srvA.NumSubscriptions())
1884 fooSub := natsSubSync(t, cfooNC, "track.service")
1885 natsFlush(t, cfooNC)
1886 // Wait for it to propagate.
1887 checkExpectedSubs(t, baseSubs+1, srvA)
1888
1889 cbarNC := natsConnect(t, srvA.ClientURL(), nats.Name("bar"))
1890 defer cbarNC.Close()
1891 cbar := getClient(srvA, "bar")
1892
1893 barAcc, _ := srvA.LookupAccount("$bar")
1894 if err := cbar.registerWithAccount(barAcc); err != nil {
1895 t.Fatalf("Error registering client with 'bar' account: %v", err)
1896 }
1897
1898 readFooMsg := func() {
1899 t.Helper()
1900 if _, err := fooSub.NextMsg(time.Second); err != nil {
1901 t.Fatalf("Did not receive foo msg: %v", err)
1902 }
1903 }
1904
1905 // Send 2 requests
1906 natsSubSync(t, cbarNC, "resp")
1907
1908 natsPubReq(t, cbarNC, "req", "resp", []byte("help"))
1909 natsPubReq(t, cbarNC, "req", "resp", []byte("help"))
1910
1911 readFooMsg()
1912 readFooMsg()
1913
1914 var rc *client
1915 // Pull out first client
1916 srvB.mu.Lock()
1917 for _, rc = range srvB.clients {
1918 if rc != nil {
1919 break
1920 }
1921 }
1922 srvB.mu.Unlock()
1923
1924 tracking := func() int {
1925 rc.mu.Lock()
1926 var nt int
1927 if rc.rrTracking != nil {
1928 nt = len(rc.rrTracking.rmap)
1929 }
1930 rc.mu.Unlock()
1931 return nt
1932 }
1933
1934 expectTracking := func(expected int) {
1935 t.Helper()
1936 checkFor(t, time.Second, 10*time.Millisecond, func() error {
1937 if numTracking := tracking(); numTracking != expected {
1938 return fmt.Errorf("Expected to have %d tracking replies, got %d", expected, numTracking)
1939 }
1940 return nil
1941 })
1942 }
1943
1944 expectTracking(2)
1945 // Make sure these remote tracking replies honor the current respThresh for a service export.
1946 time.Sleep(10 * time.Millisecond)
1947 expectTracking(0)
1948 // Also make sure tracking is removed
1949 rc.mu.Lock()
1950 removed := rc.rrTracking == nil
1951 rc.mu.Unlock()
1952 if !removed {
1953 t.Fatalf("Expected the rrTracking to be removed")
1954 }
1955
1956 // Now let's test that a lower response threshold is picked up.
1957 fSub := natsSubSync(t, cfooNC, "foo")
1958 natsFlush(t, cfooNC)
1959
1960 // Wait for it to propagate.
1961 checkExpectedSubs(t, baseSubs+4, srvA)
1962
1963 // queue up some first. We want to test changing when rrTracking exists.
1964 natsPubReq(t, cbarNC, "req", "resp", []byte("help"))
1965 readFooMsg()
1966 expectTracking(1)
1967
1968 for _, s := range srvs {
1969 fooAcc, _ := s.LookupAccount("$foo")
1970 barAcc, _ := s.LookupAccount("$bar")
1971 fooAcc.AddServiceExport("foo", nil)
1972 fooAcc.TrackServiceExport("foo", "foo.results")
1973 fooAcc.SetServiceExportResponseThreshold("foo", time.Millisecond)
1974 barAcc.AddServiceImport(fooAcc, "foo", "foo")
1975 }
1976
1977 natsSubSync(t, cbarNC, "reply")
1978 natsPubReq(t, cbarNC, "foo", "reply", []byte("help"))
1979 if _, err := fSub.NextMsg(time.Second); err != nil {
1980 t.Fatalf("Did not receive foo msg: %v", err)
1981 }
1982 expectTracking(2)
1983
1984 rc.mu.Lock()
1985 lrt := rc.rrTracking.lrt
1986 rc.mu.Unlock()
1987 if lrt != time.Millisecond {
1988 t.Fatalf("Expected lrt of %v, got %v", time.Millisecond, lrt)
1989 }
1990
1991 // Now make sure we clear on close.
1992 rc.closeConnection(ClientClosed)
1993
1994 // Actual tear down will be not inline.
1995 checkFor(t, time.Second, 5*time.Millisecond, func() error {
1996 rc.mu.Lock()
1997 removed = rc.rrTracking == nil
1998 rc.mu.Unlock()
1999 if !removed {
2000 return fmt.Errorf("Expected the rrTracking to be removed after client close")
2001 }
2002 return nil
2003 })
2004 }
2005
2006 func TestCrossAccountServiceResponseTypes(t *testing.T) {
2007 s, fooAcc, barAcc := simpleAccountServer(t)
2008 defer s.Shutdown()
2009
2010 cfoo, crFoo, _ := newClientForServer(s)
2011 defer cfoo.close()
2012
2013 if err := cfoo.registerWithAccount(fooAcc); err != nil {
2014 t.Fatalf("Error registering client with 'foo' account: %v", err)
2015 }
2016 cbar, crBar, _ := newClientForServer(s)
2017 defer cbar.close()
2018
2019 if err := cbar.registerWithAccount(barAcc); err != nil {
2020 t.Fatalf("Error registering client with 'bar' account: %v", err)
2021 }
2022
2023 // Add in the service export for the requests. Make it public.
2024 if err := fooAcc.AddServiceExportWithResponse("test.request", Streamed, nil); err != nil {
2025 t.Fatalf("Error adding account service export to client foo: %v", err)
2026 }
2027 // Now add in the route mapping for request to be routed to the foo account.
2028 if err := barAcc.AddServiceImport(fooAcc, "foo", "test.request"); err != nil {
2029 t.Fatalf("Error adding account service import to client bar: %v", err)
2030 }
2031
2032 // Now setup the resonder under cfoo
2033 cfoo.parse([]byte("SUB test.request 1\r\n"))
2034
2035 // Now send the request. Remember we expect the request on our local foo. We added the route
2036 // with that "from" and will map it to "test.request"
2037 cbar.parseAsync("SUB bar 11\r\nPUB foo bar 4\r\nhelp\r\n")
2038
2039 // Now read the request from crFoo
2040 l, err := crFoo.ReadString('\n')
2041 if err != nil {
2042 t.Fatalf("Error reading from client 'bar': %v", err)
2043 }
2044
2045 mraw := msgPat.FindAllStringSubmatch(l, -1)
2046 if len(mraw) == 0 {
2047 t.Fatalf("No message received")
2048 }
2049 matches := mraw[0]
2050 reply := matches[REPLY_INDEX]
2051 if !strings.HasPrefix(reply, "_R_.") {
2052 t.Fatalf("Expected an _R_.* like reply, got '%s'", reply)
2053 }
2054 crFoo.ReadString('\n')
2055
2056 replyOp := fmt.Sprintf("PUB %s 2\r\n22\r\n", matches[REPLY_INDEX])
2057 var mReply []byte
2058 for i := 0; i < 10; i++ {
2059 mReply = append(mReply, replyOp...)
2060 }
2061
2062 cfoo.parseAsync(string(mReply))
2063
2064 var buf []byte
2065 for i := 0; i < 20; i++ {
2066 b, err := crBar.ReadBytes('\n')
2067 if err != nil {
2068 t.Fatalf("Error reading response: %v", err)
2069 }
2070 buf = append(buf[:], b...)
2071 if mraw = msgPat.FindAllStringSubmatch(string(buf), -1); len(mraw) == 10 {
2072 break
2073 }
2074 }
2075 if len(mraw) != 10 {
2076 t.Fatalf("Expected a response but got %d", len(mraw))
2077 }
2078
2079 // Also make sure the response map gets cleaned up when interest goes away.
2080 cbar.closeConnection(ClientClosed)
2081
2082 checkFor(t, time.Second, 10*time.Millisecond, func() error {
2083 if nr := barAcc.NumPendingAllResponses(); nr != 0 {
2084 return fmt.Errorf("Number of responses is %d", nr)
2085 }
2086 return nil
2087 })
2088
2089 // Now test bogus reply subjects are handled and do not accumulate the response maps.
2090 cbar, _, _ = newClientForServer(s)
2091 defer cbar.close()
2092
2093 if err := cbar.registerWithAccount(barAcc); err != nil {
2094 t.Fatalf("Error registering client with 'bar' account: %v", err)
2095 }
2096
2097 // Do not create any interest in the reply subject 'bar'. Just send a request.
2098 cbar.parseAsync("PUB foo bar 4\r\nhelp\r\n")
2099
2100 // Now read the request from crFoo
2101 l, err = crFoo.ReadString('\n')
2102 if err != nil {
2103 t.Fatalf("Error reading from client 'bar': %v", err)
2104 }
2105 mraw = msgPat.FindAllStringSubmatch(l, -1)
2106 if len(mraw) == 0 {
2107 t.Fatalf("No message received")
2108 }
2109 matches = mraw[0]
2110 reply = matches[REPLY_INDEX]
2111 if !strings.HasPrefix(reply, "_R_.") {
2112 t.Fatalf("Expected an _R_.* like reply, got '%s'", reply)
2113 }
2114 crFoo.ReadString('\n')
2115
2116 replyOp = fmt.Sprintf("PUB %s 2\r\n22\r\n", matches[REPLY_INDEX])
2117
2118 cfoo.parseAsync(replyOp)
2119
2120 // Now wait for a bit, the reply should trip a no interest condition
2121 // which should clean this up.
2122 checkFor(t, time.Second, 10*time.Millisecond, func() error {
2123 if nr := fooAcc.NumPendingAllResponses(); nr != 0 {
2124 return fmt.Errorf("Number of responses is %d", nr)
2125 }
2126 return nil
2127 })
2128
2129 // Also make sure the response map entry is gone as well.
2130 fooAcc.mu.RLock()
2131 lrm := len(fooAcc.exports.responses)
2132 fooAcc.mu.RUnlock()
2133
2134 if lrm != 0 {
2135 t.Fatalf("Expected the responses to be cleared, got %d entries", lrm)
2136 }
2137 }
2138
2139 func TestAccountMapsUsers(t *testing.T) {
2140 // Used for the nkey users to properly sign.
2141 seed1 := "SUAPM67TC4RHQLKBX55NIQXSMATZDOZK6FNEOSS36CAYA7F7TY66LP4BOM"
2142 seed2 := "SUAIS5JPX4X4GJ7EIIJEQ56DH2GWPYJRPWN5XJEDENJOZHCBLI7SEPUQDE"
2143
2144 confFileName := createConfFile(t, []byte(`
2145 accounts {
2146 synadia {
2147 users = [
2148 {user: derek, password: foo},
2149 {nkey: UCNGL4W5QX66CFX6A6DCBVDH5VOHMI7B2UZZU7TXAUQQSI2JPHULCKBR}
2150 ]
2151 }
2152 nats {
2153 users = [
2154 {user: ivan, password: bar},
2155 {nkey: UDPGQVFIWZ7Q5UH4I5E6DBCZULQS6VTVBG6CYBD7JV3G3N2GMQOMNAUH}
2156 ]
2157 }
2158 }
2159 `))
2160 opts, err := ProcessConfigFile(confFileName)
2161 if err != nil {
2162 t.Fatalf("Unexpected error parsing config file: %v", err)
2163 }
2164 opts.NoSigs = true
2165 s := New(opts)
2166 defer s.Shutdown()
2167 synadia, _ := s.LookupAccount("synadia")
2168 nats, _ := s.LookupAccount("nats")
2169
2170 if synadia == nil || nats == nil {
2171 t.Fatalf("Expected non nil accounts during lookup")
2172 }
2173
2174 // Make sure a normal log in maps the accounts correctly.
2175 c, _, _ := newClientForServer(s)
2176 defer c.close()
2177 connectOp := []byte("CONNECT {\"user\":\"derek\",\"pass\":\"foo\"}\r\n")
2178 c.parse(connectOp)
2179 if c.acc != synadia {
2180 t.Fatalf("Expected the client's account to match 'synadia', got %v", c.acc)
2181 }
2182
2183 c, _, _ = newClientForServer(s)
2184 defer c.close()
2185 connectOp = []byte("CONNECT {\"user\":\"ivan\",\"pass\":\"bar\"}\r\n")
2186 c.parse(connectOp)
2187 if c.acc != nats {
2188 t.Fatalf("Expected the client's account to match 'nats', got %v", c.acc)
2189 }
2190
2191 // Now test nkeys as well.
2192 kp, _ := nkeys.FromSeed([]byte(seed1))
2193 pubKey, _ := kp.PublicKey()
2194
2195 c, cr, l := newClientForServer(s)
2196 defer c.close()
2197 // Check for Nonce
2198 var info nonceInfo
2199 err = json.Unmarshal([]byte(l[5:]), &info)
2200 if err != nil {
2201 t.Fatalf("Could not parse INFO json: %v\n", err)
2202 }
2203 if info.Nonce == "" {
2204 t.Fatalf("Expected a non-empty nonce with nkeys defined")
2205 }
2206 sigraw, err := kp.Sign([]byte(info.Nonce))
2207 if err != nil {
2208 t.Fatalf("Failed signing nonce: %v", err)
2209 }
2210 sig := base64.RawURLEncoding.EncodeToString(sigraw)
2211
2212 // PING needed to flush the +OK to us.
2213 cs := fmt.Sprintf("CONNECT {\"nkey\":%q,\"sig\":\"%s\",\"verbose\":true,\"pedantic\":true}\r\nPING\r\n", pubKey, sig)
2214 c.parseAsync(cs)
2215 l, _ = cr.ReadString('\n')
2216 if !strings.HasPrefix(l, "+OK") {
2217 t.Fatalf("Expected an OK, got: %v", l)
2218 }
2219 if c.acc != synadia {
2220 t.Fatalf("Expected the nkey client's account to match 'synadia', got %v", c.acc)
2221 }
2222
2223 // Now nats account nkey user.
2224 kp, _ = nkeys.FromSeed([]byte(seed2))
2225 pubKey, _ = kp.PublicKey()
2226
2227 c, cr, l = newClientForServer(s)
2228 defer c.close()
2229 // Check for Nonce
2230 err = json.Unmarshal([]byte(l[5:]), &info)
2231 if err != nil {
2232 t.Fatalf("Could not parse INFO json: %v\n", err)
2233 }
2234 if info.Nonce == "" {
2235 t.Fatalf("Expected a non-empty nonce with nkeys defined")
2236 }
2237 sigraw, err = kp.Sign([]byte(info.Nonce))
2238 if err != nil {
2239 t.Fatalf("Failed signing nonce: %v", err)
2240 }
2241 sig = base64.RawURLEncoding.EncodeToString(sigraw)
2242
2243 // PING needed to flush the +OK to us.
2244 cs = fmt.Sprintf("CONNECT {\"nkey\":%q,\"sig\":\"%s\",\"verbose\":true,\"pedantic\":true}\r\nPING\r\n", pubKey, sig)
2245 c.parseAsync(cs)
2246 l, _ = cr.ReadString('\n')
2247 if !strings.HasPrefix(l, "+OK") {
2248 t.Fatalf("Expected an OK, got: %v", l)
2249 }
2250 if c.acc != nats {
2251 t.Fatalf("Expected the nkey client's account to match 'nats', got %v", c.acc)
2252 }
2253 }
2254
2255 func TestAccountGlobalDefault(t *testing.T) {
2256 opts := defaultServerOptions
2257 s := New(&opts)
2258
2259 if acc, _ := s.LookupAccount(globalAccountName); acc == nil {
2260 t.Fatalf("Expected a global default account on a new server, got none.")
2261 }
2262 // Make sure we can not create one with same name..
2263 if _, err := s.RegisterAccount(globalAccountName); err == nil {
2264 t.Fatalf("Expected error trying to create a new reserved account")
2265 }
2266
2267 // Make sure we can not define one in a config file either.
2268 confFileName := createConfFile(t, []byte(`accounts { $G {} }`))
2269
2270 if _, err := ProcessConfigFile(confFileName); err == nil {
2271 t.Fatalf("Expected an error parsing config file with reserved account")
2272 }
2273 }
2274
2275 func TestAccountCheckStreamImportsEqual(t *testing.T) {
2276 // Create bare accounts for this test
2277 fooAcc := NewAccount("foo")
2278 if err := fooAcc.AddStreamExport(">", nil); err != nil {
2279 t.Fatalf("Error adding stream export: %v", err)
2280 }
2281
2282 barAcc := NewAccount("bar")
2283 if err := barAcc.AddStreamImport(fooAcc, "foo", "myPrefix"); err != nil {
2284 t.Fatalf("Error adding stream import: %v", err)
2285 }
2286 bazAcc := NewAccount("baz")
2287 if err := bazAcc.AddStreamImport(fooAcc, "foo", "myPrefix"); err != nil {
2288 t.Fatalf("Error adding stream import: %v", err)
2289 }
2290 if !barAcc.checkStreamImportsEqual(bazAcc) {
2291 t.Fatal("Expected stream imports to be the same")
2292 }
2293
2294 if err := bazAcc.AddStreamImport(fooAcc, "foo.>", ""); err != nil {
2295 t.Fatalf("Error adding stream import: %v", err)
2296 }
2297 if barAcc.checkStreamImportsEqual(bazAcc) {
2298 t.Fatal("Expected stream imports to be different")
2299 }
2300 if err := barAcc.AddStreamImport(fooAcc, "foo.>", ""); err != nil {
2301 t.Fatalf("Error adding stream import: %v", err)
2302 }
2303 if !barAcc.checkStreamImportsEqual(bazAcc) {
2304 t.Fatal("Expected stream imports to be the same")
2305 }
2306
2307 // Create another account that is named "foo". We want to make sure
2308 // that the comparison still works (based on account name, not pointer)
2309 newFooAcc := NewAccount("foo")
2310 if err := newFooAcc.AddStreamExport(">", nil); err != nil {
2311 t.Fatalf("Error adding stream export: %v", err)
2312 }
2313 batAcc := NewAccount("bat")
2314 if err := batAcc.AddStreamImport(newFooAcc, "foo", "myPrefix"); err != nil {
2315 t.Fatalf("Error adding stream import: %v", err)
2316 }
2317 if err := batAcc.AddStreamImport(newFooAcc, "foo.>", ""); err != nil {
2318 t.Fatalf("Error adding stream import: %v", err)
2319 }
2320 if !batAcc.checkStreamImportsEqual(barAcc) {
2321 t.Fatal("Expected stream imports to be the same")
2322 }
2323 if !batAcc.checkStreamImportsEqual(bazAcc) {
2324 t.Fatal("Expected stream imports to be the same")
2325 }
2326
2327 // Test with account with different "from"
2328 expAcc := NewAccount("new_acc")
2329 if err := expAcc.AddStreamExport(">", nil); err != nil {
2330 t.Fatalf("Error adding stream export: %v", err)
2331 }
2332 aAcc := NewAccount("a")
2333 if err := aAcc.AddStreamImport(expAcc, "bar", ""); err != nil {
2334 t.Fatalf("Error adding stream import: %v", err)
2335 }
2336 bAcc := NewAccount("b")
2337 if err := bAcc.AddStreamImport(expAcc, "baz", ""); err != nil {
2338 t.Fatalf("Error adding stream import: %v", err)
2339 }
2340 if aAcc.checkStreamImportsEqual(bAcc) {
2341 t.Fatal("Expected stream imports to be different")
2342 }
2343
2344 // Test with account with different "prefix"
2345 aAcc = NewAccount("a")
2346 if err := aAcc.AddStreamImport(expAcc, "bar", "prefix"); err != nil {
2347 t.Fatalf("Error adding stream import: %v", err)
2348 }
2349 bAcc = NewAccount("b")
2350 if err := bAcc.AddStreamImport(expAcc, "bar", "diff_prefix"); err != nil {
2351 t.Fatalf("Error adding stream import: %v", err)
2352 }
2353 if aAcc.checkStreamImportsEqual(bAcc) {
2354 t.Fatal("Expected stream imports to be different")
2355 }
2356
2357 // Test with account with different "name"
2358 expAcc = NewAccount("diff_name")
2359 if err := expAcc.AddStreamExport(">", nil); err != nil {
2360 t.Fatalf("Error adding stream export: %v", err)
2361 }
2362 bAcc = NewAccount("b")
2363 if err := bAcc.AddStreamImport(expAcc, "bar", "prefix"); err != nil {
2364 t.Fatalf("Error adding stream import: %v", err)
2365 }
2366 if aAcc.checkStreamImportsEqual(bAcc) {
2367 t.Fatal("Expected stream imports to be different")
2368 }
2369 }
2370
2371 func TestAccountNoDeadlockOnQueueSubRouteMapUpdate(t *testing.T) {
2372 opts := DefaultOptions()
2373 s := RunServer(opts)
2374 defer s.Shutdown()
2375
2376 nc, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port))
2377 if err != nil {
2378 t.Fatalf("Error on connect: %v", err)
2379 }
2380 defer nc.Close()
2381
2382 nc.QueueSubscribeSync("foo", "bar")
2383
2384 var accs []*Account
2385 for i := 0; i < 10; i++ {
2386 acc, _ := s.RegisterAccount(fmt.Sprintf("acc%d", i))
2387 acc.mu.Lock()
2388 accs = append(accs, acc)
2389 }
2390
2391 opts2 := DefaultOptions()
2392 opts2.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", opts.Cluster.Host, opts.Cluster.Port))
2393 s2 := RunServer(opts2)
2394 defer s2.Shutdown()
2395
2396 wg := sync.WaitGroup{}
2397 wg.Add(1)
2398 go func() {
2399 time.Sleep(100 * time.Millisecond)
2400 for _, acc := range accs {
2401 acc.mu.Unlock()
2402 }
2403 wg.Done()
2404 }()
2405
2406 nc.QueueSubscribeSync("foo", "bar")
2407 nc.Flush()
2408
2409 wg.Wait()
2410 }
2411
2412 func TestAccountDuplicateServiceImportSubject(t *testing.T) {
2413 opts := DefaultOptions()
2414 s := RunServer(opts)
2415 defer s.Shutdown()
2416
2417 fooAcc, _ := s.RegisterAccount("foo")
2418 fooAcc.AddServiceExport("remote1", nil)
2419 fooAcc.AddServiceExport("remote2", nil)
2420
2421 barAcc, _ := s.RegisterAccount("bar")
2422 if err := barAcc.AddServiceImport(fooAcc, "foo", "remote1"); err != nil {
2423 t.Fatalf("Error adding service import: %v", err)
2424 }
2425 if err := barAcc.AddServiceImport(fooAcc, "foo", "remote2"); err == nil || !strings.Contains(err.Error(), "duplicate") {
2426 t.Fatalf("Expected an error about duplicate service import subject, got %q", err)
2427 }
2428
2429 // However, it is allowed to add more than one service import
2430 // on the same subject for different exporting accounts
2431 bazAcc, _ := s.RegisterAccount("baz")
2432 bazAcc.AddServiceExport("remote1", nil)
2433 if err := barAcc.AddServiceImport(bazAcc, "foo", "remote1"); err != nil {
2434 t.Fatalf("Error adding service import: %v", err)
2435 }
2436 batAcc, _ := s.RegisterAccount("bat")
2437 batAcc.AddServiceExport("remote1", nil)
2438 if err := barAcc.AddServiceImport(batAcc, "foo", "remote1"); err != nil {
2439 t.Fatalf("Error adding service import: %v", err)
2440 }
2441
2442 // But again, can't add for one that has been already added, say bazAcc.
2443 if err := barAcc.AddServiceImport(bazAcc, "foo", "remote1"); err == nil || !strings.Contains(err.Error(), "duplicate") {
2444 t.Fatalf("Expected an error about duplicate service import subject, got %q", err)
2445 }
2446 }
2447
2448 func TestAccountRemoveServiceImport(t *testing.T) {
2449 opts := DefaultOptions()
2450 s := RunServer(opts)
2451 defer s.Shutdown()
2452
2453 fooAcc, _ := s.RegisterAccount("foo")
2454 fooAcc.AddServiceExport("remote1", nil)
2455
2456 barAcc, _ := s.RegisterAccount("bar")
2457 err := barAcc.AddServiceImport(fooAcc, "foo", "remote1")
2458 require_NoError(t, err)
2459
2460 bazAcc, _ := s.RegisterAccount("baz")
2461 bazAcc.AddServiceExport("remote1", nil)
2462 err = barAcc.AddServiceImport(bazAcc, "foo", "remote1")
2463 require_NoError(t, err)
2464
2465 batAcc, _ := s.RegisterAccount("bat")
2466 batAcc.AddServiceExport("remote1", nil)
2467 err = barAcc.AddServiceImport(batAcc, "foo", "remote1")
2468 require_NoError(t, err)
2469
2470 // Check that we can get the service import we expect
2471 checkGetSI := func(acc, subj string) bool {
2472 barAcc.mu.RLock()
2473 defer barAcc.mu.RUnlock()
2474 si := barAcc.getServiceImportForAccountLocked(acc, subj)
2475 if si == nil {
2476 return false
2477 }
2478 return si.acc.Name == acc
2479 }
2480 require_False(t, checkGetSI("nonsense", "foo"))
2481 require_False(t, checkGetSI("foo", "nonsense"))
2482 require_True(t, checkGetSI("foo", "foo"))
2483 require_True(t, checkGetSI("baz", "foo"))
2484 require_True(t, checkGetSI("bat", "foo"))
2485
2486 // Remove service imports one by one and check expected map content.
2487
2488 // Try first to remove one that does not exists, because of subject
2489 // or because of account.
2490 barAcc.removeServiceImport("nonsense", "foo")
2491 require_True(t, checkGetSI("foo", "foo"))
2492 require_True(t, checkGetSI("baz", "foo"))
2493 require_True(t, checkGetSI("bat", "foo"))
2494 barAcc.removeServiceImport("baz", "nonsense")
2495 require_True(t, checkGetSI("foo", "foo"))
2496 require_True(t, checkGetSI("baz", "foo"))
2497 require_True(t, checkGetSI("bat", "foo"))
2498
2499 // Remove the 2nd account that was added
2500 barAcc.removeServiceImport("baz", "foo")
2501 require_False(t, checkGetSI("baz", "foo"))
2502 require_True(t, checkGetSI("foo", "foo"))
2503 require_True(t, checkGetSI("bat", "foo"))
2504
2505 // Remove the last account that was added
2506 barAcc.removeServiceImport("bat", "foo")
2507 require_False(t, checkGetSI("baz", "foo"))
2508 require_False(t, checkGetSI("bat", "foo"))
2509 require_True(t, checkGetSI("foo", "foo"))
2510
2511 // There is only one left, make sure that we still properly check
2512 // for appropriate subject and account name.
2513 barAcc.removeServiceImport("nonsense", "foo")
2514 require_False(t, checkGetSI("baz", "foo"))
2515 require_False(t, checkGetSI("bat", "foo"))
2516 require_True(t, checkGetSI("foo", "foo"))
2517 barAcc.removeServiceImport("foo", "nonsense")
2518 require_False(t, checkGetSI("baz", "foo"))
2519 require_False(t, checkGetSI("bat", "foo"))
2520 require_True(t, checkGetSI("foo", "foo"))
2521
2522 // Remove the first account that was added
2523 barAcc.removeServiceImport("foo", "foo")
2524 require_False(t, checkGetSI("baz", "foo"))
2525 require_False(t, checkGetSI("bat", "foo"))
2526 require_False(t, checkGetSI("foo", "foo"))
2527
2528 // Make sure that the service import map is cleared
2529 barAcc.mu.RLock()
2530 sis, ok := barAcc.imports.services["foo"]
2531 barAcc.mu.RUnlock()
2532 require_False(t, ok)
2533 require_Len(t, len(sis), 0)
2534 }
2535
2536 func TestAccountMultipleServiceImportsWithSameSubjectFromDifferentAccounts(t *testing.T) {
2537 conf := createConfFile(t, []byte(`
2538 accounts: {
2539 SVC-E: {
2540 users: [ { user:svc-e, password:svc-e } ]
2541 exports: [ { accounts: [CLIENTS], service: "SvcReq.>", response_type: singleton } ]
2542 }
2543
2544 SVC-W: {
2545 users: [ { user:svc-w, password:svc-w } ]
2546 exports: [ { accounts: [CLIENTS], service: "SvcReq.>", response_type: singleton } ]
2547 }
2548
2549 CLIENTS: {
2550 users: [ { user:cl, password:cl } ]
2551 imports: [
2552 { service: { account: SVC-E, subject: "SvcReq.>" } }
2553 { service: { account: SVC-W, subject: "SvcReq.>" } }
2554 ]
2555 }
2556 }
2557 listen: "127.0.0.1:-1"
2558 `))
2559 s, _ := RunServerWithConfig(conf)
2560 defer s.Shutdown()
2561
2562 ncE := natsConnect(t, s.ClientURL(), nats.UserInfo("svc-e", "svc-e"))
2563 defer ncE.Close()
2564 natsSub(t, ncE, "SvcReq.>", func(m *nats.Msg) {
2565 m.Respond([]byte("From SVC-E"))
2566 })
2567 natsFlush(t, ncE)
2568
2569 ncW := natsConnect(t, s.ClientURL(), nats.UserInfo("svc-w", "svc-w"))
2570 defer ncW.Close()
2571 natsSub(t, ncW, "SvcReq.>", func(m *nats.Msg) {
2572 m.Respond([]byte("From SVC-W"))
2573 })
2574 natsFlush(t, ncW)
2575
2576 nc := natsConnect(t, s.ClientURL(), nats.UserInfo("cl", "cl"))
2577 defer nc.Close()
2578 sub := natsSubSync(t, nc, nats.NewInbox())
2579 natsPubReq(t, nc, "SvcReq.Test", sub.Subject, []byte("test"))
2580 msg1 := natsNexMsg(t, sub, time.Second)
2581 msg2 := natsNexMsg(t, sub, time.Second)
2582 m1 := string(msg1.Data)
2583 m2 := string(msg2.Data)
2584 if (m1 == "From SVC-E" && m2 == "From SVC-W") || (m1 == "From SVC-W" && m2 == "From SVC-E") {
2585 // Ok
2586 return
2587 }
2588 t.Fatalf("Unexpected responses: m1=%s m2=%s", m1, m2)
2589 }
2590
2591 func TestMultipleStreamImportsWithSameSubjectDifferentPrefix(t *testing.T) {
2592 opts := DefaultOptions()
2593 s := RunServer(opts)
2594 defer s.Shutdown()
2595
2596 fooAcc, _ := s.RegisterAccount("foo")
2597 fooAcc.AddStreamExport("test", nil)
2598
2599 barAcc, _ := s.RegisterAccount("bar")
2600 barAcc.AddStreamExport("test", nil)
2601
2602 importAcc, _ := s.RegisterAccount("import")
2603
2604 if err := importAcc.AddStreamImport(fooAcc, "test", "foo"); err != nil {
2605 t.Fatalf("Unexpected error: %v", err)
2606 }
2607 if err := importAcc.AddStreamImport(barAcc, "test", "bar"); err != nil {
2608 t.Fatalf("Unexpected error: %v", err)
2609 }
2610
2611 // Now make sure we can see messages from both.
2612 cimport, crImport, _ := newClientForServer(s)
2613 defer cimport.close()
2614 if err := cimport.registerWithAccount(importAcc); err != nil {
2615 t.Fatalf("Error registering client with 'import' account: %v", err)
2616 }
2617 if err := cimport.parse([]byte("SUB *.test 1\r\n")); err != nil {
2618 t.Fatalf("Error for client 'import' from server: %v", err)
2619 }
2620
2621 cfoo, _, _ := newClientForServer(s)
2622 defer cfoo.close()
2623 if err := cfoo.registerWithAccount(fooAcc); err != nil {
2624 t.Fatalf("Error registering client with 'foo' account: %v", err)
2625 }
2626
2627 cbar, _, _ := newClientForServer(s)
2628 defer cbar.close()
2629 if err := cbar.registerWithAccount(barAcc); err != nil {
2630 t.Fatalf("Error registering client with 'bar' account: %v", err)
2631 }
2632
2633 readMsg := func() {
2634 t.Helper()
2635 l, err := crImport.ReadString('\n')
2636 if err != nil {
2637 t.Fatalf("Error reading msg header from client 'import': %v", err)
2638 }
2639 mraw := msgPat.FindAllStringSubmatch(l, -1)
2640 if len(mraw) == 0 {
2641 t.Fatalf("No message received")
2642 }
2643 // Consume msg body too.
2644 if _, err = crImport.ReadString('\n'); err != nil {
2645 t.Fatalf("Error reading msg body from client 'import': %v", err)
2646 }
2647 }
2648
2649 cbar.parseAsync("PUB test 9\r\nhello-bar\r\n")
2650 readMsg()
2651
2652 cfoo.parseAsync("PUB test 9\r\nhello-foo\r\n")
2653 readMsg()
2654 }
2655
2656 // This should work with prefixes that are different but we also want it to just work with same subject
2657 // being imported from multiple accounts.
2658 func TestMultipleStreamImportsWithSameSubject(t *testing.T) {
2659 opts := DefaultOptions()
2660 s := RunServer(opts)
2661 defer s.Shutdown()
2662
2663 fooAcc, _ := s.RegisterAccount("foo")
2664 fooAcc.AddStreamExport("test", nil)
2665
2666 barAcc, _ := s.RegisterAccount("bar")
2667 barAcc.AddStreamExport("test", nil)
2668
2669 importAcc, _ := s.RegisterAccount("import")
2670
2671 if err := importAcc.AddStreamImport(fooAcc, "test", ""); err != nil {
2672 t.Fatalf("Unexpected error: %v", err)
2673 }
2674 // Since we allow this now, make sure we do detect a duplicate import from same account etc.
2675 // That should be not allowed.
2676 if err := importAcc.AddStreamImport(fooAcc, "test", ""); err != ErrStreamImportDuplicate {
2677 t.Fatalf("Expected ErrStreamImportDuplicate but got %v", err)
2678 }
2679
2680 if err := importAcc.AddStreamImport(barAcc, "test", ""); err != nil {
2681 t.Fatalf("Unexpected error: %v", err)
2682 }
2683
2684 // Now make sure we can see messages from both.
2685 cimport, crImport, _ := newClientForServer(s)
2686 defer cimport.close()
2687 if err := cimport.registerWithAccount(importAcc); err != nil {
2688 t.Fatalf("Error registering client with 'import' account: %v", err)
2689 }
2690 if err := cimport.parse([]byte("SUB test 1\r\n")); err != nil {
2691 t.Fatalf("Error for client 'import' from server: %v", err)
2692 }
2693
2694 cfoo, _, _ := newClientForServer(s)
2695 defer cfoo.close()
2696 if err := cfoo.registerWithAccount(fooAcc); err != nil {
2697 t.Fatalf("Error registering client with 'foo' account: %v", err)
2698 }
2699
2700 cbar, _, _ := newClientForServer(s)
2701 defer cbar.close()
2702 if err := cbar.registerWithAccount(barAcc); err != nil {
2703 t.Fatalf("Error registering client with 'bar' account: %v", err)
2704 }
2705
2706 readMsg := func() {
2707 t.Helper()
2708 l, err := crImport.ReadString('\n')
2709 if err != nil {
2710 t.Fatalf("Error reading msg header from client 'import': %v", err)
2711 }
2712 mraw := msgPat.FindAllStringSubmatch(l, -1)
2713 if len(mraw) == 0 {
2714 t.Fatalf("No message received")
2715 }
2716 // Consume msg body too.
2717 if _, err = crImport.ReadString('\n'); err != nil {
2718 t.Fatalf("Error reading msg body from client 'import': %v", err)
2719 }
2720 }
2721
2722 cbar.parseAsync("PUB test 9\r\nhello-bar\r\n")
2723 readMsg()
2724
2725 cfoo.parseAsync("PUB test 9\r\nhello-foo\r\n")
2726 readMsg()
2727 }
2728
2729 func TestAccountBasicRouteMapping(t *testing.T) {
2730 opts := DefaultOptions()
2731 opts.Port = -1
2732 s := RunServer(opts)
2733 defer s.Shutdown()
2734
2735 acc, _ := s.LookupAccount(DEFAULT_GLOBAL_ACCOUNT)
2736 acc.AddMapping("foo", "bar")
2737
2738 nc := natsConnect(t, s.ClientURL())
2739 defer nc.Close()
2740
2741 fsub, _ := nc.SubscribeSync("foo")
2742 bsub, _ := nc.SubscribeSync("bar")
2743 nc.Publish("foo", nil)
2744 nc.Flush()
2745
2746 checkPending := func(sub *nats.Subscription, expected int) {
2747 t.Helper()
2748 if n, _, _ := sub.Pending(); n != expected {
2749 t.Fatalf("Expected %d msgs for %q, but got %d", expected, sub.Subject, n)
2750 }
2751 }
2752
2753 checkPending(fsub, 0)
2754 checkPending(bsub, 1)
2755
2756 acc.RemoveMapping("foo")
2757
2758 nc.Publish("foo", nil)
2759 nc.Flush()
2760
2761 checkPending(fsub, 1)
2762 checkPending(bsub, 1)
2763 }
2764
2765 func TestAccountWildcardRouteMapping(t *testing.T) {
2766 opts := DefaultOptions()
2767 opts.Port = -1
2768 s := RunServer(opts)
2769 defer s.Shutdown()
2770
2771 acc, _ := s.LookupAccount(DEFAULT_GLOBAL_ACCOUNT)
2772
2773 addMap := func(src, dest string) {
2774 t.Helper()
2775 if err := acc.AddMapping(src, dest); err != nil {
2776 t.Fatalf("Error adding mapping: %v", err)
2777 }
2778 }
2779
2780 addMap("foo.*.*", "bar.$2.$1")
2781 addMap("bar.*.>", "baz.$1.>")
2782
2783 nc := natsConnect(t, s.ClientURL())
2784 defer nc.Close()
2785
2786 pub := func(subj string) {
2787 t.Helper()
2788 err := nc.Publish(subj, nil)
2789 if err == nil {
2790 err = nc.Flush()
2791 }
2792 if err != nil {
2793 t.Fatalf("Error publishing: %v", err)
2794 }
2795 }
2796
2797 fsub, _ := nc.SubscribeSync("foo.>")
2798 bsub, _ := nc.SubscribeSync("bar.>")
2799 zsub, _ := nc.SubscribeSync("baz.>")
2800
2801 checkPending := func(sub *nats.Subscription, expected int) {
2802 t.Helper()
2803 if n, _, _ := sub.Pending(); n != expected {
2804 t.Fatalf("Expected %d msgs for %q, but got %d", expected, sub.Subject, n)
2805 }
2806 }
2807
2808 pub("foo.1.2")
2809
2810 checkPending(fsub, 0)
2811 checkPending(bsub, 1)
2812 checkPending(zsub, 0)
2813 }
2814
2815 func TestAccountRouteMappingChangesAfterClientStart(t *testing.T) {
2816 opts := DefaultOptions()
2817 opts.Port = -1
2818 s := RunServer(opts)
2819 defer s.Shutdown()
2820
2821 // Create the client first then add in mapping.
2822 nc := natsConnect(t, s.ClientURL())
2823 defer nc.Close()
2824
2825 nc.Flush()
2826
2827 acc, _ := s.LookupAccount(DEFAULT_GLOBAL_ACCOUNT)
2828 acc.AddMapping("foo", "bar")
2829
2830 fsub, _ := nc.SubscribeSync("foo")
2831 bsub, _ := nc.SubscribeSync("bar")
2832 nc.Publish("foo", nil)
2833 nc.Flush()
2834
2835 checkPending := func(sub *nats.Subscription, expected int) {
2836 t.Helper()
2837 if n, _, _ := sub.Pending(); n != expected {
2838 t.Fatalf("Expected %d msgs for %q, but got %d", expected, sub.Subject, n)
2839 }
2840 }
2841
2842 checkPending(fsub, 0)
2843 checkPending(bsub, 1)
2844
2845 acc.RemoveMapping("foo")
2846
2847 nc.Publish("foo", nil)
2848 nc.Flush()
2849
2850 checkPending(fsub, 1)
2851 checkPending(bsub, 1)
2852 }
2853
2854 func TestAccountSimpleWeightedRouteMapping(t *testing.T) {
2855 opts := DefaultOptions()
2856 opts.Port = -1
2857 s := RunServer(opts)
2858 defer s.Shutdown()
2859
2860 acc, _ := s.LookupAccount(DEFAULT_GLOBAL_ACCOUNT)
2861 acc.AddWeightedMappings("foo", NewMapDest("bar", 50))
2862
2863 nc := natsConnect(t, s.ClientURL())
2864 defer nc.Close()
2865
2866 fsub, _ := nc.SubscribeSync("foo")
2867 bsub, _ := nc.SubscribeSync("bar")
2868
2869 total := 500
2870 for i := 0; i < total; i++ {
2871 nc.Publish("foo", nil)
2872 }
2873 nc.Flush()
2874
2875 fpending, _, _ := fsub.Pending()
2876 bpending, _, _ := bsub.Pending()
2877
2878 h := total / 2
2879 tp := h / 5
2880 min, max := h-tp, h+tp
2881 if fpending < min || fpending > max {
2882 t.Fatalf("Expected about %d msgs, got %d and %d", h, fpending, bpending)
2883 }
2884 }
2885
2886 func TestAccountMultiWeightedRouteMappings(t *testing.T) {
2887 opts := DefaultOptions()
2888 opts.Port = -1
2889 s := RunServer(opts)
2890 defer s.Shutdown()
2891
2892 acc, _ := s.LookupAccount(DEFAULT_GLOBAL_ACCOUNT)
2893
2894 // Check failures for bad weights.
2895 shouldErr := func(rds ...*MapDest) {
2896 t.Helper()
2897 if acc.AddWeightedMappings("foo", rds...) == nil {
2898 t.Fatalf("Expected an error, got none")
2899 }
2900 }
2901 shouldNotErr := func(rds ...*MapDest) {
2902 t.Helper()
2903 if err := acc.AddWeightedMappings("foo", rds...); err != nil {
2904 t.Fatalf("Unexpected error: %v", err)
2905 }
2906 }
2907
2908 shouldErr(NewMapDest("bar", 150))
2909 shouldNotErr(NewMapDest("bar", 50))
2910 shouldNotErr(NewMapDest("bar", 50), NewMapDest("baz", 50))
2911 // Same dest duplicated should error.
2912 shouldErr(NewMapDest("bar", 50), NewMapDest("bar", 50))
2913 // total over 100
2914 shouldErr(NewMapDest("bar", 50), NewMapDest("baz", 60))
2915
2916 acc.RemoveMapping("foo")
2917
2918 // 20 for original, you can leave it off will be auto-added.
2919 shouldNotErr(NewMapDest("bar", 50), NewMapDest("baz", 30))
2920
2921 nc := natsConnect(t, s.ClientURL())
2922 defer nc.Close()
2923
2924 fsub, _ := nc.SubscribeSync("foo")
2925 bsub, _ := nc.SubscribeSync("bar")
2926 zsub, _ := nc.SubscribeSync("baz")
2927
2928 // For checking later.
2929 rds := []struct {
2930 sub *nats.Subscription
2931 w uint8
2932 }{
2933 {fsub, 20},
2934 {bsub, 50},
2935 {zsub, 30},
2936 }
2937
2938 total := 5000
2939 for i := 0; i < total; i++ {
2940 nc.Publish("foo", nil)
2941 }
2942 nc.Flush()
2943
2944 for _, rd := range rds {
2945 pending, _, _ := rd.sub.Pending()
2946 expected := total / int(100/rd.w)
2947 tp := expected / 5 // 20%
2948 min, max := expected-tp, expected+tp
2949 if pending < min || pending > max {
2950 t.Fatalf("Expected about %d msgs for %q, got %d", expected, rd.sub.Subject, pending)
2951 }
2952 }
2953 }
2954
2955 func TestGlobalAccountRouteMappingsConfiguration(t *testing.T) {
2956 cf := createConfFile(t, []byte(`
2957 port: -1
2958 mappings = {
2959 foo: bar
2960 foo.*: [ { dest: bar.v1.$1, weight: 40% }, { destination: baz.v2.$1, weight: 20 } ]
2961 bar.*.*: RAB.$2.$1
2962 }
2963 `))
2964
2965 s, _ := RunServerWithConfig(cf)
2966 defer s.Shutdown()
2967
2968 nc := natsConnect(t, s.ClientURL())
2969 defer nc.Close()
2970
2971 bsub, _ := nc.SubscribeSync("bar")
2972 fsub1, _ := nc.SubscribeSync("bar.v1.>")
2973 fsub2, _ := nc.SubscribeSync("baz.v2.>")
2974 zsub, _ := nc.SubscribeSync("RAB.>")
2975 f22sub, _ := nc.SubscribeSync("foo.*")
2976
2977 checkPending := func(sub *nats.Subscription, expected int) {
2978 t.Helper()
2979 if n, _, _ := sub.Pending(); n != expected {
2980 t.Fatalf("Expected %d msgs for %q, but got %d", expected, sub.Subject, n)
2981 }
2982 }
2983
2984 nc.Publish("foo", nil)
2985 nc.Publish("bar.11.22", nil)
2986
2987 total := 500
2988 for i := 0; i < total; i++ {
2989 nc.Publish("foo.22", nil)
2990 }
2991 nc.Flush()
2992
2993 checkPending(bsub, 1)
2994 checkPending(zsub, 1)
2995
2996 fpending, _, _ := f22sub.Pending()
2997 fpending1, _, _ := fsub1.Pending()
2998 fpending2, _, _ := fsub2.Pending()
2999
3000 if fpending1 < fpending2 || fpending < fpending2 {
3001 t.Fatalf("Loadbalancing seems off for the foo.* mappings: %d and %d and %d", fpending, fpending1, fpending2)
3002 }
3003 }
3004
3005 func TestAccountRouteMappingsConfiguration(t *testing.T) {
3006 cf := createConfFile(t, []byte(`
3007 port: -1
3008 accounts {
3009 synadia {
3010 users = [{user: derek, password: foo}]
3011 mappings = {
3012 foo: bar
3013 foo.*: [ { dest: bar.v1.$1, weight: 40% }, { destination: baz.v2.$1, weight: 20 } ]
3014 bar.*.*: RAB.$2.$1
3015 }
3016 }
3017 }
3018 `))
3019
3020 s, _ := RunServerWithConfig(cf)
3021 defer s.Shutdown()
3022
3023 // We test functionality above, so for this one just make sure we have mappings for the account.
3024 acc, _ := s.LookupAccount("synadia")
3025 if !acc.hasMappings() {
3026 t.Fatalf("Account %q does not have mappings", "synadia")
3027 }
3028
3029 az, err := s.Accountz(&AccountzOptions{"synadia"})
3030 if err != nil {
3031 t.Fatalf("Error getting Accountz: %v", err)
3032 }
3033 if az.Account == nil {
3034 t.Fatalf("Expected an Account")
3035 }
3036 if len(az.Account.Mappings) != 3 {
3037 t.Fatalf("Expected %d mappings, saw %d", 3, len(az.Account.Mappings))
3038 }
3039 }
3040
3041 func TestAccountRouteMappingsWithLossInjection(t *testing.T) {
3042 cf := createConfFile(t, []byte(`
3043 port: -1
3044 mappings = {
3045 foo: { dest: foo, weight: 80% }
3046 bar: { dest: bar, weight: 0% }
3047 }
3048 `))
3049
3050 s, _ := RunServerWithConfig(cf)
3051 defer s.Shutdown()
3052
3053 nc := natsConnect(t, s.ClientURL())
3054 defer nc.Close()
3055
3056 sub, _ := nc.SubscribeSync("foo")
3057
3058 total := 1000
3059 for i := 0; i < total; i++ {
3060 nc.Publish("foo", nil)
3061 }
3062 nc.Flush()
3063
3064 if pending, _, _ := sub.Pending(); pending == total {
3065 t.Fatalf("Expected some loss and pending to not be same as sent")
3066 }
3067
3068 sub, _ = nc.SubscribeSync("bar")
3069 for i := 0; i < total; i++ {
3070 nc.Publish("bar", nil)
3071 }
3072 nc.Flush()
3073
3074 if pending, _, _ := sub.Pending(); pending != 0 {
3075 t.Fatalf("Expected all messages to be dropped and pending to be 0, got %d", pending)
3076 }
3077 }
3078
3079 func TestAccountRouteMappingsWithOriginClusterFilter(t *testing.T) {
3080 cf := createConfFile(t, []byte(`
3081 port: -1
3082 mappings = {
3083 foo: { dest: bar, cluster: SYN, weight: 100% }
3084 }
3085 `))
3086
3087 s, _ := RunServerWithConfig(cf)
3088 defer s.Shutdown()
3089
3090 nc := natsConnect(t, s.ClientURL())
3091 defer nc.Close()
3092
3093 sub, _ := nc.SubscribeSync("foo")
3094
3095 total := 1000
3096 for i := 0; i < total; i++ {
3097 nc.Publish("foo", nil)
3098 }
3099 nc.Flush()
3100
3101 if pending, _, _ := sub.Pending(); pending != total {
3102 t.Fatalf("Expected pending to be %d, got %d", total, pending)
3103 }
3104
3105 s.setClusterName("SYN")
3106 sub, _ = nc.SubscribeSync("bar")
3107 for i := 0; i < total; i++ {
3108 nc.Publish("foo", nil)
3109 }
3110 nc.Flush()
3111
3112 if pending, _, _ := sub.Pending(); pending != total {
3113 t.Fatalf("Expected pending to be %d, got %d", total, pending)
3114 }
3115 }
3116
3117 func TestAccountServiceImportWithRouteMappings(t *testing.T) {
3118 cf := createConfFile(t, []byte(`
3119 port: -1
3120 accounts {
3121 foo {
3122 users = [{user: derek, password: foo}]
3123 exports = [{service: "request"}]
3124 }
3125 bar {
3126 users = [{user: ivan, password: bar}]
3127 imports = [{service: {account: "foo", subject:"request"}}]
3128 }
3129 }
3130 `))
3131
3132 s, opts := RunServerWithConfig(cf)
3133 defer s.Shutdown()
3134
3135 acc, _ := s.LookupAccount("foo")
3136 acc.AddMapping("request", "request.v2")
3137
3138 // Create the service client first.
3139 ncFoo := natsConnect(t, fmt.Sprintf("nats://derek:foo@%s:%d", opts.Host, opts.Port))
3140 defer ncFoo.Close()
3141
3142 fooSub := natsSubSync(t, ncFoo, "request.v2")
3143 ncFoo.Flush()
3144
3145 // Requestor
3146 ncBar := natsConnect(t, fmt.Sprintf("nats://ivan:bar@%s:%d", opts.Host, opts.Port))
3147 defer ncBar.Close()
3148
3149 ncBar.Publish("request", nil)
3150 ncBar.Flush()
3151
3152 checkFor(t, time.Second, 10*time.Millisecond, func() error {
3153 if n, _, _ := fooSub.Pending(); n != 1 {
3154 return fmt.Errorf("Expected a request for %q, but got %d", fooSub.Subject, n)
3155 }
3156 return nil
3157 })
3158 }
3159
3160 func TestAccountImportsWithWildcardSupport(t *testing.T) {
3161 cf := createConfFile(t, []byte(`
3162 port: -1
3163 accounts {
3164 foo {
3165 users = [{user: derek, password: foo}]
3166 exports = [
3167 { service: "request.*" }
3168 { stream: "events.>" }
3169 { stream: "info.*.*.>" }
3170 ]
3171 }
3172 bar {
3173 users = [{user: ivan, password: bar}]
3174 imports = [
3175 { service: {account: "foo", subject:"request.*"}, to:"my.request.*"}
3176 { stream: {account: "foo", subject:"events.>"}, to:"foo.events.>"}
3177 { stream: {account: "foo", subject:"info.*.*.>"}, to:"foo.info.$2.$1.>"}
3178 ]
3179 }
3180 }
3181 `))
3182
3183 s, opts := RunServerWithConfig(cf)
3184 defer s.Shutdown()
3185
3186 ncFoo := natsConnect(t, fmt.Sprintf("nats://derek:foo@%s:%d", opts.Host, opts.Port))
3187 defer ncFoo.Close()
3188
3189 ncBar := natsConnect(t, fmt.Sprintf("nats://ivan:bar@%s:%d", opts.Host, opts.Port))
3190 defer ncBar.Close()
3191
3192 // Create subscriber for the service endpoint in foo.
3193 _, err := ncFoo.QueueSubscribe("request.*", "t22", func(m *nats.Msg) {
3194 if m.Subject != "request.22" {
3195 t.Fatalf("Expected literal subject for request, got %q", m.Subject)
3196 }
3197 m.Respond([]byte("yes!"))
3198 })
3199 if err != nil {
3200 t.Fatalf("Error on subscribe: %v", err)
3201 }
3202 ncFoo.Flush()
3203
3204 // Now test service import.
3205 resp, err := ncBar.Request("my.request.22", []byte("yes?"), time.Second)
3206 if err != nil {
3207 t.Fatalf("Expected a response")
3208 }
3209 if string(resp.Data) != "yes!" {
3210 t.Fatalf("Expected a response of %q, got %q", "yes!", resp.Data)
3211 }
3212
3213 // Now test stream imports.
3214 esub, _ := ncBar.SubscribeSync("foo.events.*") // subset
3215 isub, _ := ncBar.SubscribeSync("foo.info.>")
3216 ncBar.Flush()
3217
3218 // Now publish some stream events.
3219 ncFoo.Publish("events.22", nil)
3220 ncFoo.Publish("info.11.22.bar", nil)
3221 ncFoo.Flush()
3222
3223 checkPending := func(sub *nats.Subscription, expected int) {
3224 t.Helper()
3225 checkFor(t, time.Second, 10*time.Millisecond, func() error {
3226 if n, _, _ := sub.Pending(); n != expected {
3227 return fmt.Errorf("Expected %d msgs for %q, but got %d", expected, sub.Subject, n)
3228 }
3229 return nil
3230 })
3231 }
3232
3233 checkPending(esub, 1)
3234 checkPending(isub, 1)
3235
3236 // Now check to make sure the subjects are correct etc.
3237 m, err := esub.NextMsg(time.Second)
3238 if err != nil {
3239 t.Fatalf("Unexpected error: %v", err)
3240 }
3241 if m.Subject != "foo.events.22" {
3242 t.Fatalf("Incorrect subject for stream import, expected %q, got %q", "foo.events.22", m.Subject)
3243 }
3244
3245 m, err = isub.NextMsg(time.Second)
3246 if err != nil {
3247 t.Fatalf("Unexpected error: %v", err)
3248 }
3249 if m.Subject != "foo.info.22.11.bar" {
3250 t.Fatalf("Incorrect subject for stream import, expected %q, got %q", "foo.info.22.11.bar", m.Subject)
3251 }
3252 }
3253
3254 // duplicates TestJWTAccountImportsWithWildcardSupport (jwt_test.go) in config
3255 func TestAccountImportsWithWildcardSupportStreamAndService(t *testing.T) {
3256 cf := createConfFile(t, []byte(`
3257 port: -1
3258 accounts {
3259 foo {
3260 users = [{user: derek, password: foo}]
3261 exports = [
3262 { service: "$request.*.$in.*.>" }
3263 { stream: "$events.*.$in.*.>" }
3264 ]
3265 }
3266 bar {
3267 users = [{user: ivan, password: bar}]
3268 imports = [
3269 { service: {account: "foo", subject:"$request.*.$in.*.>"}, to:"my.request.$2.$1.>"}
3270 { stream: {account: "foo", subject:"$events.*.$in.*.>"}, to:"my.events.$2.$1.>"}
3271 ]
3272 }
3273 }
3274 `))
3275
3276 s, opts := RunServerWithConfig(cf)
3277 defer s.Shutdown()
3278
3279 ncFoo := natsConnect(t, fmt.Sprintf("nats://derek:foo@%s:%d", opts.Host, opts.Port))
3280 defer ncFoo.Close()
3281
3282 ncBar := natsConnect(t, fmt.Sprintf("nats://ivan:bar@%s:%d", opts.Host, opts.Port))
3283 defer ncBar.Close()
3284
3285 // Create subscriber for the service endpoint in foo.
3286 _, err := ncFoo.Subscribe("$request.>", func(m *nats.Msg) {
3287 if m.Subject != "$request.2.$in.1.bar" {
3288 t.Fatalf("Expected literal subject for request, got %q", m.Subject)
3289 }
3290 m.Respond([]byte("yes!"))
3291 })
3292 if err != nil {
3293 t.Fatalf("Error on subscribe: %v", err)
3294 }
3295 ncFoo.Flush()
3296
3297 // Now test service import.
3298 if resp, err := ncBar.Request("my.request.1.2.bar", []byte("yes?"), time.Second); err != nil {
3299 t.Fatalf("Expected a response")
3300 } else if string(resp.Data) != "yes!" {
3301 t.Fatalf("Expected a response of %q, got %q", "yes!", resp.Data)
3302 }
3303 subBar, err := ncBar.SubscribeSync("my.events.>")
3304 if err != nil {
3305 t.Fatalf("Expected a response")
3306 }
3307 ncBar.Flush()
3308
3309 ncFoo.Publish("$events.1.$in.2.bar", nil)
3310
3311 m, err := subBar.NextMsg(time.Second)
3312 if err != nil {
3313 t.Fatalf("Expected a response")
3314 }
3315 if m.Subject != "my.events.2.1.bar" {
3316 t.Fatalf("Expected literal subject for request, got %q", m.Subject)
3317 }
3318 }
3319
3320 func BenchmarkNewRouteReply(b *testing.B) {
3321 opts := defaultServerOptions
3322 s := New(&opts)
3323 g := s.globalAccount()
3324 b.ResetTimer()
3325 for i := 0; i < b.N; i++ {
3326 g.newServiceReply(false)
3327 }
3328 }
3329
3330 func TestSamplingHeader(t *testing.T) {
3331 test := func(expectSampling bool, h http.Header) {
3332 t.Helper()
3333 b := strings.Builder{}
3334 b.WriteString("\r\n") // simulate status line
3335 h.Write(&b)
3336 b.WriteString("\r\n")
3337 hdrString := b.String()
3338 c := &client{parseState: parseState{msgBuf: []byte(hdrString), pa: pubArg{hdr: len(hdrString)}}}
3339 sample, hdr := shouldSample(&serviceLatency{0, "foo"}, c)
3340 if expectSampling {
3341 if !sample {
3342 t.Fatal("Expected to sample")
3343 } else if hdr == nil {
3344 t.Fatal("Expected a header")
3345 }
3346 for k, v := range h {
3347 if hdr.Get(k) != v[0] {
3348 t.Fatal("Expect header to match")
3349 }
3350 }
3351 } else {
3352 if sample {
3353 t.Fatal("Expected not to sample")
3354 } else if hdr != nil {
3355 t.Fatal("Expected no header")
3356 }
3357 }
3358 }
3359
3360 test(false, http.Header{"Uber-Trace-Id": []string{"0:0:0:0"}})
3361 test(false, http.Header{"Uber-Trace-Id": []string{"0:0:0:00"}}) // one byte encoded as two hex digits
3362 test(true, http.Header{"Uber-Trace-Id": []string{"0:0:0:1"}})
3363 test(true, http.Header{"Uber-Trace-Id": []string{"0:0:0:01"}})
3364 test(true, http.Header{"Uber-Trace-Id": []string{"0:0:0:5"}}) // debug and sample
3365 test(true, http.Header{"Uber-Trace-Id": []string{"479fefe9525eddb:5adb976bfc1f95c1:479fefe9525eddb:1"}})
3366 test(true, http.Header{"Uber-Trace-Id": []string{"479fefe9525eddb:479fefe9525eddb:0:1"}})
3367 test(false, http.Header{"Uber-Trace-Id": []string{"479fefe9525eddb:5adb976bfc1f95c1:479fefe9525eddb:0"}})
3368 test(false, http.Header{"Uber-Trace-Id": []string{"479fefe9525eddb:479fefe9525eddb:0:0"}})
3369
3370 test(true, http.Header{"X-B3-Sampled": []string{"1"}})
3371 test(false, http.Header{"X-B3-Sampled": []string{"0"}})
3372 test(true, http.Header{"X-B3-TraceId": []string{"80f198ee56343ba864fe8b2a57d3eff7"}}) // decision left to recipient
3373 test(false, http.Header{"X-B3-TraceId": []string{"80f198ee56343ba864fe8b2a57d3eff7"}, "X-B3-Sampled": []string{"0"}})
3374 test(true, http.Header{"X-B3-TraceId": []string{"80f198ee56343ba864fe8b2a57d3eff7"}, "X-B3-Sampled": []string{"1"}})
3375
3376 test(false, http.Header{"B3": []string{"0"}}) // deny only
3377 test(false, http.Header{"B3": []string{"0-0-0-0"}})
3378 test(false, http.Header{"B3": []string{"0-0-0"}})
3379 test(true, http.Header{"B3": []string{"0-0-1-0"}})
3380 test(true, http.Header{"B3": []string{"0-0-1"}})
3381 test(true, http.Header{"B3": []string{"0-0-d"}}) // debug is not a deny
3382 test(true, http.Header{"B3": []string{"80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1-1"}})
3383 test(true, http.Header{"B3": []string{"80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1-1-05e3ac9a4f6e3b90"}})
3384 test(false, http.Header{"B3": []string{"80f198ee56343ba864fe8b2a57d3eff7-e457b5a2e4d86bd1-0-05e3ac9a4f6e3b90"}})
3385
3386 test(true, http.Header{"traceparent": []string{"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"}})
3387 test(true, http.Header{"traceparent": []string{"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-27"}})
3388 test(false, http.Header{"traceparent": []string{"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00"}})
3389 test(false, http.Header{"traceparent": []string{"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-22"}})
3390 }
3391
3392 func TestAccountSystemPermsWithGlobalAccess(t *testing.T) {
3393 conf := createConfFile(t, []byte(`
3394 listen: 127.0.0.1:-1
3395 accounts {
3396 $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
3397 }
3398 `))
3399
3400 s, _ := RunServerWithConfig(conf)
3401 defer s.Shutdown()
3402
3403 // Make sure we can connect with no auth to global account as normal.
3404 nc, err := nats.Connect(s.ClientURL())
3405 if err != nil {
3406 t.Fatalf("Failed to create client: %v", err)
3407 }
3408 defer nc.Close()
3409
3410 // Make sure we can connect to the system account with correct credentials.
3411 sc, err := nats.Connect(s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"))
3412 if err != nil {
3413 t.Fatalf("Failed to create system client: %v", err)
3414 }
3415 defer sc.Close()
3416 }
3417
3418 const importSubscriptionOverlapTemplate = `
3419 listen: 127.0.0.1:-1
3420 accounts: {
3421 ACCOUNT_X: {
3422 users: [
3423 {user: publisher}
3424 ]
3425 exports: [
3426 {stream: %s}
3427 ]
3428 },
3429 ACCOUNT_Y: {
3430 users: [
3431 {user: subscriber}
3432 ]
3433 imports: [
3434 {stream: {account: ACCOUNT_X, subject: %s }, %s}
3435 ]
3436 }
3437 }`
3438
3439 func TestImportSubscriptionPartialOverlapWithPrefix(t *testing.T) {
3440 cf := createConfFile(t, []byte(fmt.Sprintf(importSubscriptionOverlapTemplate, ">", ">", "prefix: myprefix")))
3441
3442 s, opts := RunServerWithConfig(cf)
3443 defer s.Shutdown()
3444
3445 ncX := natsConnect(t, fmt.Sprintf("nats://%s:%[email protected]:%d", "publisher", "", opts.Port))
3446 defer ncX.Close()
3447
3448 ncY := natsConnect(t, fmt.Sprintf("nats://%s:%[email protected]:%d", "subscriber", "", opts.Port))
3449 defer ncY.Close()
3450
3451 for _, subj := range []string{">", "myprefix.*", "myprefix.>", "myprefix.test", "*.>", "*.*", "*.test"} {
3452 t.Run(subj, func(t *testing.T) {
3453 sub, err := ncY.SubscribeSync(subj)
3454 sub.AutoUnsubscribe(1)
3455 require_NoError(t, err)
3456 require_NoError(t, ncY.Flush())
3457
3458 ncX.Publish("test", []byte("hello"))
3459
3460 m, err := sub.NextMsg(time.Second)
3461 require_NoError(t, err)
3462 require_True(t, string(m.Data) == "hello")
3463 })
3464 }
3465 }
3466
3467 func TestImportSubscriptionPartialOverlapWithTransform(t *testing.T) {
3468 cf := createConfFile(t, []byte(fmt.Sprintf(importSubscriptionOverlapTemplate, "*.*.>", "*.*.>", "to: myprefix.$2.$1.>")))
3469
3470 s, opts := RunServerWithConfig(cf)
3471 defer s.Shutdown()
3472
3473 ncX := natsConnect(t, fmt.Sprintf("nats://%s:%[email protected]:%d", "publisher", "", opts.Port))
3474 defer ncX.Close()
3475
3476 ncY := natsConnect(t, fmt.Sprintf("nats://%s:%[email protected]:%d", "subscriber", "", opts.Port))
3477 defer ncY.Close()
3478
3479 for _, subj := range []string{">", "*.*.*.>", "*.2.*.>", "*.*.1.>", "*.2.1.>", "*.*.*.*", "*.2.1.*", "*.*.*.test",
3480 "*.*.1.test", "*.2.*.test", "*.2.1.test", "myprefix.*.*.*", "myprefix.>", "myprefix.*.>", "myprefix.*.*.>",
3481 "myprefix.2.>", "myprefix.2.1.>", "myprefix.*.1.>", "myprefix.2.*.>", "myprefix.2.1.*", "myprefix.*.*.test",
3482 "myprefix.2.1.test"} {
3483 t.Run(subj, func(t *testing.T) {
3484 sub, err := ncY.SubscribeSync(subj)
3485 sub.AutoUnsubscribe(1)
3486 require_NoError(t, err)
3487 require_NoError(t, ncY.Flush())
3488
3489 ncX.Publish("1.2.test", []byte("hello"))
3490
3491 m, err := sub.NextMsg(time.Second)
3492 require_NoError(t, err)
3493 require_True(t, string(m.Data) == "hello")
3494 require_Equal(t, m.Subject, "myprefix.2.1.test")
3495 })
3496 }
3497 }
3498
3499 func TestAccountLimitsServerConfig(t *testing.T) {
3500 cf := createConfFile(t, []byte(`
3501 port: -1
3502 max_connections: 10
3503 accounts {
3504 MAXC {
3505 users = [{user: derek, password: foo}]
3506 limits {
3507 max_connections: 5
3508 max_subs: 10
3509 max_payload: 32k
3510 max_leafnodes: 1
3511 }
3512 }
3513 }
3514 `))
3515
3516 s, _ := RunServerWithConfig(cf)
3517 defer s.Shutdown()
3518
3519 acc, err := s.lookupAccount("MAXC")
3520 require_NoError(t, err)
3521
3522 if mc := acc.MaxActiveConnections(); mc != 5 {
3523 t.Fatalf("Did not set MaxActiveConnections properly, expected 5, got %d", mc)
3524 }
3525 if mlc := acc.MaxActiveLeafNodes(); mlc != 1 {
3526 t.Fatalf("Did not set MaxActiveLeafNodes properly, expected 1, got %d", mlc)
3527 }
3528
3529 // Do quick test on connections, but if they are registered above should be good.
3530 for i := 0; i < 5; i++ {
3531 c, err := nats.Connect(s.ClientURL(), nats.UserInfo("derek", "foo"))
3532 require_NoError(t, err)
3533 defer c.Close()
3534 }
3535
3536 // Should fail.
3537 _, err = nats.Connect(s.ClientURL(), nats.UserInfo("derek", "foo"))
3538 require_Error(t, err)
3539 }
3540
3541 // Connections being closed should be the newer ones in case of JWT limits.
3542 func TestAccountMaxConnectionsDisconnectsNewestFirst(t *testing.T) {
3543 cf := createConfFile(t, []byte(`
3544 port: -1
3545 server_name: A
3546 accounts {
3547 TEST {
3548 users = [
3549 {user: user1, password: foo}
3550 {user: user2, password: foo}
3551 {user: user3, password: foo}
3552 ]
3553 limits {
3554 max_connections: 3
3555 }
3556 }
3557 }
3558 `))
3559 s, _ := RunServerWithConfig(cf)
3560 defer s.Shutdown()
3561
3562 var conns []*nats.Conn
3563
3564 disconnects := make([]chan error, 0)
3565 for i := 1; i <= 3; i++ {
3566 disconnectCh := make(chan error)
3567 c, err := nats.Connect(
3568 s.ClientURL(),
3569 nats.UserInfo(fmt.Sprintf("user%d", i), "foo"),
3570 nats.DisconnectErrHandler(func(_ *nats.Conn, err error) {
3571 disconnectCh <- err
3572 }),
3573 nats.NoReconnect(),
3574 )
3575 require_NoError(t, err)
3576 defer c.Close()
3577 conns = append(conns, c)
3578 disconnects = append(disconnects, disconnectCh)
3579 // Small delay to ensure distinct start times.
3580 time.Sleep(10 * time.Millisecond)
3581 }
3582 acc, err := s.lookupAccount("TEST")
3583 require_NoError(t, err)
3584 require_Equal(t, acc.NumConnections(), 3)
3585
3586 // Force account update to trigger connection limit enforcement.
3587 accClaims := jwt.NewAccountClaims(acc.Name)
3588 accClaims.Limits.Conn = 2
3589 s.UpdateAccountClaims(acc, accClaims)
3590
3591 // Wait for disconnections from the most recent client.
3592 disconnectCh := disconnects[2]
3593 select {
3594 case <-disconnectCh:
3595 case <-time.After(2 * time.Second):
3596 t.Fatal("Expected newest connection to disconnect!")
3597 }
3598
3599 // Check which connections are still active
3600 // The newest connection (last one created) should be disconnected first.
3601 activeConnections := 0
3602 var connected []int
3603 for i, conn := range conns {
3604 if !conn.IsClosed() {
3605 activeConnections++
3606 connected = append(connected, i)
3607 }
3608 }
3609 require_Equal(t, activeConnections, 2)
3610 require_Equal(t, len(connected), 2)
3611
3612 // The first two connections should still be connected.
3613 require_Equal(t, connected[0], 0)
3614 require_Equal(t, connected[1], 1)
3615
3616 // The newest connection should be closed.
3617 require_True(t, conns[2].IsClosed())
3618 }
3619
3620 func TestAccountUpdateRemoteServerDisconnectsNewestFirst(t *testing.T) {
3621 cf := createConfFile(t, []byte(`
3622 port: -1
3623 accounts {
3624 TEST {
3625 users = [{user: dummy, password: foo}]
3626 limits {
3627 max_connections: 5
3628 }
3629 }
3630 }
3631 `))
3632
3633 s, _ := RunServerWithConfig(cf)
3634 defer s.Shutdown()
3635
3636 acc, err := s.lookupAccount("TEST")
3637 require_NoError(t, err)
3638
3639 for i := 0; i < 3; i++ {
3640 c, err := nats.Connect(s.ClientURL(), nats.UserInfo("dummy", "foo"))
3641 require_NoError(t, err)
3642 defer c.Close()
3643
3644 // Small delay to ensure distinct start times.
3645 time.Sleep(10 * time.Millisecond)
3646 }
3647 require_Equal(t, acc.NumConnections(), 3)
3648
3649 // Simulate remote server reporting connections that would exceed the limit.
3650 // Remote has 4 + we have 3, meaning that 2 will have to be disconnected.
3651 remoteServerMsg := &AccountNumConns{
3652 Server: ServerInfo{
3653 ID: "fake-server-1",
3654 Name: "fake-nats-1",
3655 },
3656 AccountStat: AccountStat{
3657 Account: "TEST",
3658 Conns: 4,
3659 },
3660 }
3661 toDisconnect := acc.updateRemoteServer(remoteServerMsg)
3662
3663 // Should want to disconnect 2 clients (7 total - 5 max conns limit = 2 over).
3664 require_Equal(t, len(toDisconnect), 2)
3665
3666 // Verify the returned clients are in reverse chronological order.
3667 var startTimes []time.Time
3668 for _, c := range toDisconnect {
3669 startTimes = append(startTimes, c.start)
3670 }
3671 if !startTimes[0].After(startTimes[1]) {
3672 t.Fatalf("Expected clients to be in reverse chronological order: %v is before %v", startTimes[0], startTimes[1])
3673 }
3674
3675 // The clients to disconnect should be the newest ones we created.
3676 disconnected := make(map[uint64]bool)
3677 for _, c := range toDisconnect {
3678 disconnected[c.cid] = true
3679 }
3680
3681 // Get all current clients and find the oldest ones.
3682 allClients := acc.getClients()
3683 byStartTime := make([]*client, len(allClients))
3684 copy(byStartTime, allClients)
3685 slices.SortFunc(byStartTime, func(i, j *client) int {
3686 return i.start.Compare(j.start)
3687 })
3688
3689 // The last two clients in the sorted list should be the ones selected for disconnection.
3690 require_False(t, disconnected[byStartTime[0].cid])
3691 require_True(t, disconnected[byStartTime[1].cid])
3692 require_True(t, disconnected[byStartTime[2].cid])
3693 }
3694
3695 func TestAccountMaxConnectionsDuringLameDuckMode(t *testing.T) {
3696 cf := createConfFile(t, []byte(`
3697 port: -1
3698 accounts {
3699 TEST {
3700 users = [
3701 {user: user, password: user}
3702 ]
3703 limits {
3704 max_connections: 3
3705 }
3706 }
3707 }
3708 cluster {
3709 listen: 127.0.0.1:7248
3710 name: "abc"
3711 }
3712 no_auth_user: user
3713 lame_duck_grace_period: 1s
3714 `))
3715
3716 optsA, err := ProcessConfigFile(cf)
3717 require_NoError(t, err)
3718 optsA.NoSigs, optsA.NoLog = true, true
3719 optsA.ServerName = "A"
3720 srvA := RunServer(optsA)
3721 defer srvA.Shutdown()
3722 optsB := nextServerOpts(optsA)
3723 optsB.Routes = RoutesFromStr(fmt.Sprintf("nats://%s:%d", optsA.Cluster.Host, optsA.Cluster.Port))
3724 optsB.ServerName = "B"
3725 srvB := RunServer(optsB)
3726 defer srvB.Shutdown()
3727
3728 checkClusterFormed(t, srvA, srvB)
3729
3730 disconnects := make([]chan error, 0)
3731 for range 3 {
3732 disconnectCh := make(chan error)
3733 c, err := nats.Connect(
3734 srvA.ClientURL(),
3735 nats.UserInfo("user", "user"),
3736 nats.DisconnectErrHandler(func(c *nats.Conn, err error) {
3737 disconnectCh <- err
3738 }),
3739 )
3740 require_NoError(t, err)
3741 defer c.Close()
3742 disconnects = append(disconnects, disconnectCh)
3743 // Small delay to ensure distinct start times.
3744 time.Sleep(10 * time.Millisecond)
3745 }
3746 acc, err := srvA.lookupAccount("TEST")
3747 require_NoError(t, err)
3748 require_Equal(t, acc.NumConnections(), 3)
3749
3750 go srvA.LameDuckShutdown()
3751
3752 for _, disconnectCh := range disconnects {
3753 select {
3754 case err := <-disconnectCh:
3755 require_Equal(t, err.Error(), "EOF")
3756 case <-time.After(5 * time.Second):
3757 t.Fatal("Expected LDM reconnect")
3758 }
3759 }
3760 }
3761
3762 func TestAccountUserSubPermsWithQueueGroups(t *testing.T) {
3763 cf := createConfFile(t, []byte(`
3764 listen: 127.0.0.1:-1
3765
3766 authorization {
3767 users = [
3768 { user: user, password: "pass",
3769 permissions: {
3770 publish: "foo.restricted"
3771 subscribe: { allow: "foo.>", deny: "foo.restricted" }
3772 allow_responses: { max: 1, ttl: 0s }
3773 }
3774 }
3775 ]}
3776 `))
3777
3778 s, _ := RunServerWithConfig(cf)
3779 defer s.Shutdown()
3780
3781 nc, err := nats.Connect(s.ClientURL(), nats.UserInfo("user", "pass"))
3782 require_NoError(t, err)
3783 defer nc.Close()
3784
3785 // qsub solo.
3786 qsub, err := nc.QueueSubscribeSync("foo.>", "qg")
3787 require_NoError(t, err)
3788
3789 err = nc.Publish("foo.restricted", []byte("RESTRICTED"))
3790 require_NoError(t, err)
3791 nc.Flush()
3792
3793 // Expect no msgs.
3794 checkSubsPending(t, qsub, 0)
3795 }
3796
3797 func TestAccountImportCycle(t *testing.T) {
3798 tmpl := `
3799 port: -1
3800 accounts: {
3801 CP: {
3802 users: [
3803 {user: cp, password: cp},
3804 ],
3805 exports: [
3806 {service: "q1.>", response_type: Singleton},
3807 {service: "q2.>", response_type: Singleton},
3808 %s
3809 ],
3810 },
3811 A: {
3812 users: [
3813 {user: a, password: a},
3814 ],
3815 imports: [
3816 {service: {account: CP, subject: "q1.>"}},
3817 {service: {account: CP, subject: "q2.>"}},
3818 %s
3819 ]
3820 },
3821 }
3822 `
3823 cf := createConfFile(t, []byte(fmt.Sprintf(tmpl, _EMPTY_, _EMPTY_)))
3824 s, _ := RunServerWithConfig(cf)
3825 defer s.Shutdown()
3826 ncCp, err := nats.Connect(s.ClientURL(), nats.UserInfo("cp", "cp"))
3827 require_NoError(t, err)
3828 defer ncCp.Close()
3829 ncA, err := nats.Connect(s.ClientURL(), nats.UserInfo("a", "a"))
3830 require_NoError(t, err)
3831 defer ncA.Close()
3832 // setup responder
3833 natsSub(t, ncCp, "q1.>", func(m *nats.Msg) { m.Respond([]byte("reply")) })
3834 // setup requestor
3835 ib := "q2.inbox"
3836 subAResp, err := ncA.SubscribeSync(ib)
3837 ncA.Flush()
3838 require_NoError(t, err)
3839 req := func() {
3840 t.Helper()
3841 // send request
3842 err = ncA.PublishRequest("q1.a", ib, []byte("test"))
3843 ncA.Flush()
3844 require_NoError(t, err)
3845 mRep, err := subAResp.NextMsg(time.Second)
3846 require_NoError(t, err)
3847 require_Equal(t, string(mRep.Data), "reply")
3848 }
3849 req()
3850
3851 // Update the config and do a config reload and make sure it all still work
3852 changeCurrentConfigContentWithNewContent(t, cf, []byte(
3853 fmt.Sprintf(tmpl, `{service: "q3.>", response_type: Singleton},`, `{service: {account: CP, subject: "q3.>"}},`)))
3854 err = s.Reload()
3855 require_NoError(t, err)
3856 req()
3857 }
3858
3859 func TestAccountImportOwnExport(t *testing.T) {
3860 conf := createConfFile(t, []byte(`
3861 port: -1
3862 accounts: {
3863 A: {
3864 exports: [
3865 { service: echo, accounts: [A], latency: { subject: "latency.echo" } }
3866 ],
3867 imports: [
3868 { service: { account: A, subject: echo } }
3869 ]
3870
3871 users: [
3872 { user: user, pass: pass }
3873 ]
3874 }
3875 }
3876 `))
3877 s, _ := RunServerWithConfig(conf)
3878 defer s.Shutdown()
3879
3880 nc := natsConnect(t, s.ClientURL(), nats.UserInfo("user", "pass"))
3881 defer nc.Close()
3882
3883 natsSub(t, nc, "echo", func(m *nats.Msg) { m.Respond(nil) })
3884 _, err := nc.Request("echo", []byte("request"), time.Second)
3885 require_NoError(t, err)
3886 }
3887
3888 // Test for a bug that would cause duplicate deliveries in certain situations when
3889 // service export/imports and leafnodes involved.
3890 // https://github.com/nats-io/nats-server/issues/3191
3891 func TestAccountImportDuplicateResponseDeliveryWithLeafnodes(t *testing.T) {
3892 conf := createConfFile(t, []byte(`
3893 port: -1
3894 accounts: {
3895 A: {
3896 users = [{user: A, password: P}]
3897 exports: [ { service: "foo", response_type: stream } ]
3898 }
3899 B: {
3900 users = [{user: B, password: P}]
3901 imports: [ { service: {account: "A", subject:"foo"} } ]
3902 }
3903 }
3904 leaf { listen: "127.0.0.1:17222" }
3905 `))
3906 s, _ := RunServerWithConfig(conf)
3907 defer s.Shutdown()
3908
3909 // Requestors will connect to account B.
3910 nc, err := nats.Connect(s.ClientURL(), nats.UserInfo("B", "P"))
3911 require_NoError(t, err)
3912 defer nc.Close()
3913
3914 // By sending a request (regardless of no responders), this will trigger a wildcard _R_ subscription since
3915 // we do not have a leafnode connected.
3916 nc.PublishRequest("foo", "reply", nil)
3917 nc.Flush()
3918
3919 // Now connect the LN. This will be where the service responder lives.
3920 conf = createConfFile(t, []byte(`
3921 port: -1
3922 leaf {
3923 remotes [ { url: "nats://A:[email protected]:17222" } ]
3924 }
3925 `))
3926 ln, _ := RunServerWithConfig(conf)
3927 defer ln.Shutdown()
3928 checkLeafNodeConnected(t, s)
3929
3930 // Now attach a responder to the LN.
3931 lnc, err := nats.Connect(ln.ClientURL())
3932 require_NoError(t, err)
3933 defer lnc.Close()
3934
3935 lnc.Subscribe("foo", func(m *nats.Msg) {
3936 m.Respond([]byte("bar"))
3937 })
3938 lnc.Flush()
3939 checkSubInterest(t, s, "A", "foo", time.Second)
3940
3941 // Make sure it works, but request only wants one, so need second test to show failure, but
3942 // want to make sure we are wired up correctly.
3943 _, err = nc.Request("foo", nil, time.Second)
3944 require_NoError(t, err)
3945
3946 // Now setup inbox reply so we can check if we get multiple responses.
3947 reply := nats.NewInbox()
3948 sub, err := nc.SubscribeSync(reply)
3949 require_NoError(t, err)
3950
3951 nc.PublishRequest("foo", reply, nil)
3952
3953 // Do another to make sure we know the other request will have been processed too.
3954 _, err = nc.Request("foo", nil, time.Second)
3955 require_NoError(t, err)
3956
3957 if n, _, _ := sub.Pending(); n > 1 {
3958 t.Fatalf("Expected only 1 response, got %d", n)
3959 }
3960 }
3961
3962 func TestAccountReloadServiceImportPanic(t *testing.T) {
3963 conf := createConfFile(t, []byte(`
3964 listen: 127.0.0.1:-1
3965 accounts {
3966 A {
3967 users = [ { user: "a", pass: "p" } ]
3968 exports [ { service: "HELP" } ]
3969 }
3970 B {
3971 users = [ { user: "b", pass: "p" } ]
3972 imports [ { service: { account: A, subject: "HELP"} } ]
3973 }
3974 $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
3975 }
3976 `))
3977
3978 s, _ := RunServerWithConfig(conf)
3979 defer s.Shutdown()
3980
3981 // Now connect up the subscriber for HELP. No-op for this test.
3982 nc, _ := jsClientConnect(t, s, nats.UserInfo("a", "p"))
3983 defer nc.Close()
3984
3985 _, err := nc.Subscribe("HELP", func(m *nats.Msg) { m.Respond([]byte("OK")) })
3986 require_NoError(t, err)
3987 // Make sure the subscription is processed before using a new connection to publish.
3988 natsFlush(t, nc)
3989
3990 // Now create connection to account b where we will publish to HELP.
3991 nc, _ = jsClientConnect(t, s, nats.UserInfo("b", "p"))
3992 defer nc.Close()
3993
3994 // We want to continually be publishing messages that will trigger the service import while calling reload.
3995 done := make(chan bool)
3996 var wg sync.WaitGroup
3997 wg.Add(1)
3998
3999 var requests, responses atomic.Uint64
4000 reply := nats.NewInbox()
4001 _, err = nc.Subscribe(reply, func(m *nats.Msg) { responses.Add(1) })
4002 require_NoError(t, err)
4003
4004 go func() {
4005 defer wg.Done()
4006 for {
4007 select {
4008 case <-done:
4009 return
4010 default:
4011 nc.PublishRequest("HELP", reply, []byte("HELP"))
4012 requests.Add(1)
4013 }
4014 }
4015 }()
4016
4017 // Perform a bunch of reloads.
4018 for i := 0; i < 1000; i++ {
4019 require_NoError(t, s.Reload())
4020 }
4021
4022 close(done)
4023 wg.Wait()
4024
4025 totalRequests := requests.Load()
4026 checkFor(t, 20*time.Second, 250*time.Millisecond, func() error {
4027 resp := responses.Load()
4028 if resp == totalRequests {
4029 return nil
4030 }
4031 return fmt.Errorf("Have not received all responses, want %d got %d", totalRequests, resp)
4032 })
4033 }
4034
4035 // https://github.com/nats-io/nats-server/issues/4674
4036 func TestAccountServiceAndStreamExportDoubleDelivery(t *testing.T) {
4037 conf := createConfFile(t, []byte(`
4038 listen: 127.0.0.1:-1
4039 accounts: {
4040 tenant1: {
4041 jetstream: enabled
4042 users: [ { user: "one", password: "one" } ]
4043 exports: [
4044 { stream: "DW.>" }
4045 { service: "DW.>" }
4046 ]
4047 }
4048 global: {
4049 jetstream: enabled
4050 users: [ { user: "global", password: "global" } ]
4051 imports: [
4052 { stream: { account: tenant1, subject: "DW.>" }, prefix: tenant1 }
4053 { service: { account: tenant1, subject: "DW.>" }, to: "tenant1.DW.>" }
4054 ]
4055 }
4056 $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
4057 }
4058 `))
4059
4060 s, _ := RunServerWithConfig(conf)
4061 defer s.Shutdown()
4062
4063 // Now connect up the subscriber for HELP. No-op for this test.
4064 nc, _ := jsClientConnect(t, s, nats.UserInfo("one", "one"))
4065 defer nc.Close()
4066
4067 var msgs atomic.Int32
4068 _, err := nc.Subscribe(">", func(m *nats.Msg) {
4069 msgs.Add(1)
4070 })
4071 require_NoError(t, err)
4072
4073 nc.Publish("DW.test.123", []byte("test"))
4074 time.Sleep(200 * time.Millisecond)
4075 require_Equal(t, msgs.Load(), 1)
4076 }
4077
4078 func TestAccountServiceImportNoResponders(t *testing.T) {
4079 // Setup NATS server.
4080 cf := createConfFile(t, []byte(`
4081 port: -1
4082 accounts: {
4083 accExp: {
4084 users: [{user: accExp, password: accExp}]
4085 exports: [{service: "foo"}]
4086 }
4087 accImp: {
4088 users: [{user: accImp, password: accImp}]
4089 imports: [{service: {account: accExp, subject: "foo"}}]
4090 }
4091 }
4092 `))
4093
4094 s, _ := RunServerWithConfig(cf)
4095 defer s.Shutdown()
4096
4097 // Connect to the import account. We will not setup any responders, so a request should
4098 // error out with ErrNoResponders.
4099 nc := natsConnect(t, s.ClientURL(), nats.UserInfo("accImp", "accImp"))
4100 defer nc.Close()
4101
4102 _, err := nc.Request("foo", []byte("request"), 250*time.Millisecond)
4103 require_Error(t, err, nats.ErrNoResponders)
4104 }
4105
4106 // Test that service import replies are delivered when the requester's reply inbox
4107 // is subscribed on a different cluster node.
4108 func TestAccountServiceImportReplyDroppedAcrossClusterRoutes(t *testing.T) {
4109 tmpl := `
4110 server_name: %s
4111 listen: 127.0.0.1:-1
4112 cluster {
4113 name: test
4114 listen: 127.0.0.1:-1
4115 %s
4116 }
4117 accounts {
4118 A {
4119 users = [{ user: a, password: a }]
4120 imports = [{ service: { account: B, subject: svc } }]
4121 }
4122 B {
4123 users = [{ user: b, password: b }]
4124 exports = [{ service: svc, accounts: [A] }]
4125 }
4126 }
4127 `
4128 confA := createConfFile(t, []byte(fmt.Sprintf(tmpl, "node-A", "")))
4129 srvA, optsA := RunServerWithConfig(confA)
4130 defer srvA.Shutdown()
4131
4132 confB := createConfFile(t, []byte(fmt.Sprintf(tmpl, "node-B",
4133 fmt.Sprintf(`routes = ["nats-route://127.0.0.1:%d"]`, optsA.Cluster.Port))))
4134 srvB, _ := RunServerWithConfig(confB)
4135 defer srvB.Shutdown()
4136
4137 checkClusterFormed(t, srvA, srvB)
4138
4139 // Responder on node-A, account B.
4140 ncB := natsConnect(t, srvA.ClientURL(), nats.UserInfo("b", "b"))
4141 defer ncB.Close()
4142 natsSub(t, ncB, "svc", func(m *nats.Msg) { m.Respond([]byte("pong")) })
4143 natsFlush(t, ncB)
4144
4145 // Wait for B's "svc" sub to propagate to node-B so it can route the request.
4146 checkSubInterest(t, srvB, "B", "svc", time.Second)
4147
4148 // Subscriber on node-A, account A: explicit reply inbox.
4149 // This subscription will be a ROUTE sub on node-B once it propagates.
4150 ncSub := natsConnect(t, srvA.ClientURL(), nats.UserInfo("a", "a"))
4151 defer ncSub.Close()
4152 inbox := "_INBOX.xroute.reply"
4153 replyCh := make(chan *nats.Msg, 1)
4154 _, err := ncSub.Subscribe(inbox, func(m *nats.Msg) { replyCh <- m })
4155 require_NoError(t, err)
4156 natsFlush(t, ncSub)
4157
4158 // Wait for the inbox to appear as a ROUTE sub on node-B.
4159 checkSubInterest(t, srvB, "A", inbox, time.Second)
4160
4161 // Publisher on node-B, account A: publish with explicit cross-node reply.
4162 // The response service import on node-B receives the reply via route
4163 // (c.kind==ROUTER) and must forward it back to the ROUTE sub for the inbox.
4164 ncPub := natsConnect(t, srvB.ClientURL(), nats.UserInfo("a", "a"))
4165 defer ncPub.Close()
4166 err = ncPub.PublishMsg(&nats.Msg{Subject: "svc", Reply: inbox, Data: []byte("ping")})
4167 require_NoError(t, err)
4168
4169 select {
4170 case msg := <-replyCh:
4171 require_Equal(t, string(msg.Data), "pong")
4172 case <-time.After(3 * time.Second):
4173 t.Fatal("reply not received — service import reply was dropped across cluster routes")
4174 }
4175
4176 // Reverse: subscribe on node-B, publish from node-A.
4177 ncSub2 := natsConnect(t, srvB.ClientURL(), nats.UserInfo("a", "a"))
4178 defer ncSub2.Close()
4179 inbox2 := "_INBOX.xroute.reply2"
4180 replyCh2 := make(chan *nats.Msg, 1)
4181 _, err = ncSub2.Subscribe(inbox2, func(m *nats.Msg) { replyCh2 <- m })
4182 require_NoError(t, err)
4183 natsFlush(t, ncSub2)
4184 checkSubInterest(t, srvA, "A", inbox2, time.Second)
4185
4186 err = ncSub.PublishMsg(&nats.Msg{Subject: "svc", Reply: inbox2, Data: []byte("ping")})
4187 require_NoError(t, err)
4188
4189 select {
4190 case msg := <-replyCh2:
4191 require_Equal(t, string(msg.Data), "pong")
4192 case <-time.After(3 * time.Second):
4193 t.Fatal("reverse reply not received — service import reply was dropped across cluster routes")
4194 }
4195 }
4196
4197 func TestStreamActivationExpiredNoMatchDoesNotInvalidate(t *testing.T) {
4198 // Account performing the import.
4199 a := NewAccount("importer")
4200 // The account we will pass as the (non-matching) export account.
4201 exportAcc := NewAccount("exporter")
4202 // A different, still-valid stream import that does NOT match the
4203 // (exportAcc, subject) pair passed to streamActivationExpired.
4204 otherAcc := NewAccount("other")
4205 si := &streamImport{
4206 acc: otherAcc,
4207 from: "other.subject",
4208 // claim is nil, so checkActivation would return false and the
4209 // buggy code would wrongly mark this import invalid.
4210 claim: nil,
4211 }
4212 a.imports.streams = []*streamImport{si}
4213
4214 // No matching import.
4215 a.streamActivationExpired(exportAcc, "nomatch.subject")
4216 if si.invalid {
4217 t.Fatalf("unrelated stream import was wrongly invalidated on no match")
4218 }
4219 }
4220
4221 func TestRemoveAllServiceImportSubsNoRaceUnderConcurrentReaders(t *testing.T) {
4222 for range 2000 {
4223 a := &Account{}
4224 a.imports.services = make(map[string][]*serviceImport)
4225 for i := 0; i < 8; i++ {
4226 si := &serviceImport{sid: []byte("sid")}
4227 a.imports.services[fmt.Sprintf("svc.%d", i)] = []*serviceImport{si}
4228 }
4229
4230 var wg sync.WaitGroup
4231 wg.Add(2)
4232
4233 // Reader: mimics updateAccountClaimsWithRefresh reading a.ic and
4234 // iterating si.sid under a read lock.
4235 go func() {
4236 defer wg.Done()
4237 a.mu.RLock()
4238 _ = a.ic
4239 for _, sis := range a.imports.services {
4240 for _, si := range sis {
4241 _ = si.sid
4242 }
4243 }
4244 a.mu.RUnlock()
4245 }()
4246
4247 // Writer: nils si.sid and a.ic. a.ic is nil so the post-unlock
4248 // path returns early and does not touch a real client.
4249 go func() {
4250 defer wg.Done()
4251 a.removeAllServiceImportSubs()
4252 }()
4253
4254 wg.Wait()
4255 }
4256 }
4257
4258 func TestAccountDefaultPermsRaceDuringAuth(t *testing.T) {
4259 acc := NewAccount("foo")
4260
4261 // User claims with no permissions so buildInternalNkeyUser hits the
4262 // acc.defaultPerms read path (p == nil).
4263 uc := jwt.NewUserClaims("U" + strings.Repeat("A", 51))
4264
4265 var someClaims jwt.Permissions
4266 someClaims.Pub.Allow.Add("foo")
4267
4268 var wg sync.WaitGroup
4269 wg.Add(2)
4270
4271 // Reader: mimics authentication path.
4272 go func() {
4273 defer wg.Done()
4274 for range 1000 {
4275 _ = buildInternalNkeyUser(uc, nil, acc)
4276 }
4277 }()
4278
4279 // Writer: mimics updateAccountClaimsWithRefresh refreshing defaultPerms.
4280 go func() {
4281 defer wg.Done()
4282 for range 1000 {
4283 acc.mu.Lock()
4284 acc.defaultPerms = buildPermissionsFromJwt(&someClaims)
4285 acc.mu.Unlock()
4286 }
4287 }()
4288
4289 wg.Wait()
4290 }
4291
4292 // Must be run with -race.
4293 func TestAccountRemoveCbJSWriteRace(t *testing.T) {
4294 opts := DefaultTestOptions
4295 opts.Port = -1
4296 opts.JetStream = true
4297 opts.StoreDir = t.TempDir()
4298 s := RunServer(&opts)
4299 defer s.Shutdown()
4300
4301 for i := range 50 {
4302 name := fmt.Sprintf("ACC_%d", i)
4303 acc, _ := s.LookupOrRegisterAccount(name)
4304 require_NoError(t, acc.EnableJetStream(nil, nil))
4305 // Confirm a.js is set, so removeCb will reach the `a.js = nil` write.
4306 if !acc.JetStreamEnabled() {
4307 t.Fatalf("expected JetStream enabled (a.js != nil) for %s", name)
4308 }
4309
4310 var stop atomic.Bool
4311 done := make(chan struct{})
4312 // Reader: read a.js under a.mu.RLock, exactly like maxBytesLimits does.
4313 go func(a *Account) {
4314 defer close(done)
4315 for !stop.Load() {
4316 a.mu.RLock()
4317 _ = a.js
4318 a.mu.RUnlock()
4319 }
4320 }(acc)
4321
4322 // Writer: removeCb sets `a.js = nil`, which must synchronize with the
4323 // locked read above.
4324 removeCb(s, name)
4325
4326 stop.Store(true)
4327 <-done
4328 }
4329 }
4330
4331 // Must be run with -race.
4332 func TestAccountSendTrackingLatencyRcRace(t *testing.T) {
4333 a := NewAccount("A")
4334 rc := &client{kind: CLIENT}
4335 responder := &client{kind: SYSTEM}
4336
4337 si := &serviceImport{
4338 acc: a,
4339 rc: rc,
4340 share: false,
4341 ts: time.Now().UnixNano(),
4342 tracking: true,
4343 latency: &serviceLatency{subject: "latency.subj"},
4344 }
4345
4346 const iters = 1000
4347 var wg sync.WaitGroup
4348 wg.Add(2)
4349
4350 // Reader goroutine: exercises the unlocked re-read of si.rc.
4351 go func() {
4352 defer wg.Done()
4353 for range iters {
4354 a.sendTrackingLatency(si, responder)
4355 a.mu.Lock()
4356 si.m1 = nil
4357 a.mu.Unlock()
4358 }
4359 }()
4360
4361 // Writer goroutine: mimics sendLatencyResult writing si.rc under a.mu.Lock.
4362 go func() {
4363 defer wg.Done()
4364 for range iters {
4365 a.mu.Lock()
4366 si.rc = rc
4367 a.mu.Unlock()
4368 }
4369 }()
4370
4371 wg.Wait()
4372 }
4373
4374 // sharedInboxRequests stands up a foo/bar service export/import pair and has
4375 // bar send numReqs requests that all share one reply subject. The responder
4376 // never answers, so every response is left outstanding under that single rrMap
4377 // key. Returns both accounts and the shared reply subject.
4378 func sharedInboxRequests(t *testing.T, numReqs int) (*Account, *Account, string) {
4379 t.Helper()
4380
4381 s, fooAcc, barAcc := simpleAccountServer(t)
4382 t.Cleanup(s.Shutdown)
4383
4384 if err := fooAcc.AddServiceExport("test", nil); err != nil {
4385 t.Fatalf("Error adding service export: %v", err)
4386 }
4387 if err := barAcc.AddServiceImport(fooAcc, "test", _EMPTY_); err != nil {
4388 t.Fatalf("Error adding service import: %v", err)
4389 }
4390
4391 // Both connections are net.Pipe, so anything the server writes blocks until
4392 // it is read. Drain them, otherwise the write loops sit on the flush
4393 // deadline and shutdown takes ten seconds.
4394 cfoo, rfoo, _ := newClientForServer(s)
4395 t.Cleanup(cfoo.close)
4396 go io.Copy(io.Discard, rfoo)
4397 if err := cfoo.registerWithAccount(fooAcc); err != nil {
4398 t.Fatalf("Error registering client with 'foo' account: %v", err)
4399 }
4400 // Responder never answers, so the entries stay outstanding.
4401 cfoo.parse([]byte("SUB test 1\r\n"))
4402
4403 cbar, rbar, _ := newClientForServer(s)
4404 t.Cleanup(cbar.close)
4405 go io.Copy(io.Discard, rbar)
4406 if err := cbar.registerWithAccount(barAcc); err != nil {
4407 t.Fatalf("Error registering client with 'bar' account: %v", err)
4408 }
4409
4410 const inbox = "my.inbox"
4411 cbar.parse([]byte("SUB my.inbox 11\r\n"))
4412 for i := 0; i < numReqs; i++ {
4413 cbar.parse([]byte("PUB test my.inbox 4\r\nhelp\r\n"))
4414 }
4415
4416 return fooAcc, barAcc, inbox
4417 }
4418
4419 // A client is allowed to reuse a single reply subject across many concurrent
4420 // service import requests, which piles every outstanding response entry under
4421 // one rrMap key. Make sure those entries are tracked and removed correctly in
4422 // both the small (unindexed) and large (indexed) cases.
4423 func TestServiceImportReverseEntriesSharedReplySubject(t *testing.T) {
4424 for _, test := range []struct {
4425 name string
4426 numReqs int
4427 indexed bool
4428 }{
4429 {"below index threshold", rrIndexThreshold - 1, false},
4430 {"above index threshold", rrIndexThreshold * 100, true},
4431 } {
4432 t.Run(test.name, func(t *testing.T) {
4433 fooAcc, barAcc, inbox := sharedInboxRequests(t, test.numReqs)
4434
4435 barAcc.mu.RLock()
4436 re, ok := barAcc.imports.rrMap[inbox]
4437 numEntries, indexed := len(re.list), re.idx != nil
4438 barAcc.mu.RUnlock()
4439
4440 if !ok {
4441 t.Fatalf("Expected a reverse entry for %q", inbox)
4442 }
4443 if numEntries != test.numReqs {
4444 t.Fatalf("Expected %d reverse entries, got %d", test.numReqs, numEntries)
4445 }
4446 if indexed != test.indexed {
4447 t.Fatalf("Expected indexed to be %v, got %v", test.indexed, indexed)
4448 }
4449
4450 // Now expire them the way the response threshold timer does, and make
4451 // sure every entry is accounted for as we go.
4452 fooAcc.mu.RLock()
4453 var expired []*serviceImport
4454 for _, si := range fooAcc.exports.responses {
4455 expired = append(expired, si)
4456 }
4457 fooAcc.mu.RUnlock()
4458
4459 if len(expired) != test.numReqs {
4460 t.Fatalf("Expected %d outstanding responses, got %d", test.numReqs, len(expired))
4461 }
4462
4463 for i, si := range expired {
4464 fooAcc.removeRespServiceImport(si, rsiTimeout)
4465 barAcc.mu.RLock()
4466 re, ok := barAcc.imports.rrMap[inbox]
4467 remaining := len(re.list)
4468 idxLen := len(re.idx)
4469 barAcc.mu.RUnlock()
4470
4471 if expect := test.numReqs - i - 1; remaining != expect {
4472 t.Fatalf("After %d removals expected %d entries, got %d", i+1, expect, remaining)
4473 } else if expect == 0 {
4474 if ok {
4475 t.Fatalf("Expected the reverse entry for %q to be removed once empty", inbox)
4476 }
4477 } else if re.idx != nil && idxLen != remaining {
4478 t.Fatalf("Index out of sync with list: %d vs %d", idxLen, remaining)
4479 }
4480 }
4481
4482 fooAcc.mu.RLock()
4483 left := len(fooAcc.exports.responses)
4484 fooAcc.mu.RUnlock()
4485 if left != 0 {
4486 t.Fatalf("Expected no outstanding responses left, got %d", left)
4487 }
4488 })
4489 }
4490 }
4491
4492 // The other removal path drops a whole reply subject at once instead of one
4493 // entry at a time. That is what runs when interest in the reply subject goes
4494 // away, so it is the path a disconnecting requestor takes.
4495 func TestServiceImportReverseEntriesBulkRemoval(t *testing.T) {
4496 for _, test := range []struct {
4497 name string
4498 numReqs int
4499 }{
4500 {"below index threshold", rrIndexThreshold - 1},
4501 {"above index threshold", rrIndexThreshold * 100},
4502 } {
4503 t.Run(test.name, func(t *testing.T) {
4504 fooAcc, barAcc, inbox := sharedInboxRequests(t, test.numReqs)
4505
4506 fooAcc.mu.RLock()
4507 outstanding := len(fooAcc.exports.responses)
4508 fooAcc.mu.RUnlock()
4509 if outstanding != test.numReqs {
4510 t.Fatalf("Expected %d outstanding responses, got %d", test.numReqs, outstanding)
4511 }
4512
4513 // A nil si means drop every entry under this reply subject and clean
4514 // up the responses they point at on the exporting account.
4515 barAcc.checkForReverseEntry(inbox, nil, false)
4516
4517 barAcc.mu.RLock()
4518 _, ok := barAcc.imports.rrMap[inbox]
4519 remaining := len(barAcc.imports.rrMap)
4520 barAcc.mu.RUnlock()
4521 if ok {
4522 t.Fatalf("Expected the reverse entry for %q to be gone", inbox)
4523 }
4524 if remaining != 0 {
4525 t.Fatalf("Expected no reverse entries left, got %d", remaining)
4526 }
4527
4528 fooAcc.mu.RLock()
4529 outstanding = len(fooAcc.exports.responses)
4530 fooAcc.mu.RUnlock()
4531 if outstanding != 0 {
4532 t.Fatalf("Expected every outstanding response to be cleaned up, got %d", outstanding)
4533 }
4534 })
4535 }
4536 }
4537
4538 // Guards the cost of clearing outstanding responses. Each iteration clears the
4539 // whole set, so ns/op is the cost of draining n entries, not of one removal.
4540 // The shared case is the one that used to go quadratic; the unique case is the
4541 // common one and should stay where it is.
4542 func BenchmarkReverseRespMapRemoval(b *testing.B) {
4543 for _, bench := range []struct {
4544 name string
4545 shared bool
4546 }{
4547 {"SharedReplySubject", true},
4548 {"UniqueReplySubjects", false},
4549 } {
4550 for _, n := range []int{1000, 10000, 40000} {
4551 b.Run(fmt.Sprintf("%s/%d", bench.name, n), func(b *testing.B) {
4552 replies, sis := make([]string, n), make([]*serviceImport, n)
4553 for i := 0; i < n; i++ {
4554 if bench.shared {
4555 replies[i] = "my.inbox"
4556 } else {
4557 replies[i] = fmt.Sprintf("my.inbox.%d", i)
4558 }
4559 sis[i] = &serviceImport{from: fmt.Sprintf("_R_.%d", i), to: replies[i]}
4560 }
4561
4562 b.ReportAllocs()
4563 for i := 0; i < b.N; i++ {
4564 b.StopTimer()
4565 acc := NewAccount("bar")
4566 for j := 0; j < n; j++ {
4567 acc.addReverseRespMapEntry(acc, replies[j], sis[j].from)
4568 }
4569 b.StartTimer()
4570
4571 for j := 0; j < n; j++ {
4572 acc.checkForReverseEntry(replies[j], sis[j], false)
4573 }
4574
4575 if left := len(acc.imports.rrMap); left != 0 {
4576 b.Fatalf("Expected no reverse entries left, got %d", left)
4577 }
4578 }
4579 })
4580 }
4581 }
4582 }