Debian Codegraph @

server/auth_test.go

raw
1 // Copyright 2012-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package server
15
16 import (
17 "bufio"
18 "context"
19 "encoding/base64"
20 "encoding/json"
21 "errors"
22 "fmt"
23 "net"
24 "net/url"
25 "os"
26 "reflect"
27 "strings"
28 "testing"
29 "time"
30
31 "github.com/nats-io/jwt/v2"
32 "github.com/nats-io/nats.go"
33 "github.com/nats-io/nkeys"
34 )
35
36 func TestUserCloneNilPermissions(t *testing.T) {
37 user := &User{
38 Username: "foo",
39 Password: "bar",
40 }
41
42 clone := user.clone()
43
44 if !reflect.DeepEqual(user, clone) {
45 t.Fatalf("Cloned Users are incorrect.\nexpected: %+v\ngot: %+v",
46 user, clone)
47 }
48
49 clone.Password = "baz"
50 if reflect.DeepEqual(user, clone) {
51 t.Fatal("Expected Users to be different")
52 }
53 }
54
55 func TestUserClone(t *testing.T) {
56 user := &User{
57 Username: "foo",
58 Password: "bar",
59 Permissions: &Permissions{
60 Publish: &SubjectPermission{
61 Allow: []string{"foo"},
62 },
63 Subscribe: &SubjectPermission{
64 Allow: []string{"bar"},
65 },
66 },
67 }
68
69 clone := user.clone()
70
71 if !reflect.DeepEqual(user, clone) {
72 t.Fatalf("Cloned Users are incorrect.\nexpected: %+v\ngot: %+v",
73 user, clone)
74 }
75
76 clone.Permissions.Subscribe.Allow = []string{"baz"}
77 if reflect.DeepEqual(user, clone) {
78 t.Fatal("Expected Users to be different")
79 }
80 }
81
82 func TestUserClonePermissionsNoLists(t *testing.T) {
83 user := &User{
84 Username: "foo",
85 Password: "bar",
86 Permissions: &Permissions{},
87 }
88
89 clone := user.clone()
90
91 if clone.Permissions.Publish != nil {
92 t.Fatalf("Expected Publish to be nil, got: %v", clone.Permissions.Publish)
93 }
94 if clone.Permissions.Subscribe != nil {
95 t.Fatalf("Expected Subscribe to be nil, got: %v", clone.Permissions.Subscribe)
96 }
97 }
98
99 func TestUserCloneNoPermissions(t *testing.T) {
100 user := &User{
101 Username: "foo",
102 Password: "bar",
103 }
104
105 clone := user.clone()
106
107 if clone.Permissions != nil {
108 t.Fatalf("Expected Permissions to be nil, got: %v", clone.Permissions)
109 }
110 }
111
112 func TestUserCloneNil(t *testing.T) {
113 user := (*User)(nil)
114 clone := user.clone()
115 if clone != nil {
116 t.Fatalf("Expected nil, got: %+v", clone)
117 }
118 }
119
120 func TestUserUnknownAllowedConnectionType(t *testing.T) {
121 o := DefaultOptions()
122 o.Users = []*User{{
123 Username: "user",
124 Password: "pwd",
125 AllowedConnectionTypes: testCreateAllowedConnectionTypes([]string{jwt.ConnectionTypeStandard, "someNewType"}),
126 }}
127 _, err := NewServer(o)
128 if err == nil || !strings.Contains(err.Error(), "connection type") {
129 t.Fatalf("Expected error about unknown connection type, got %v", err)
130 }
131
132 o.Users[0].AllowedConnectionTypes = testCreateAllowedConnectionTypes([]string{"websocket"})
133 s, err := NewServer(o)
134 if err != nil {
135 t.Fatalf("Unexpected error: %v", err)
136 }
137 s.mu.Lock()
138 user := s.opts.Users[0]
139 s.mu.Unlock()
140 for act := range user.AllowedConnectionTypes {
141 if act != jwt.ConnectionTypeWebsocket {
142 t.Fatalf("Expected map to have been updated with proper case, got %v", act)
143 }
144 }
145 // Same with NKey user now.
146 o.Users = nil
147 o.Nkeys = []*NkeyUser{{
148 Nkey: "somekey",
149 AllowedConnectionTypes: testCreateAllowedConnectionTypes([]string{jwt.ConnectionTypeStandard, "someNewType"}),
150 }}
151 _, err = NewServer(o)
152 if err == nil || !strings.Contains(err.Error(), "connection type") {
153 t.Fatalf("Expected error about unknown connection type, got %v", err)
154 }
155 o.Nkeys[0].AllowedConnectionTypes = testCreateAllowedConnectionTypes([]string{"websocket"})
156 s, err = NewServer(o)
157 if err != nil {
158 t.Fatalf("Unexpected error: %v", err)
159 }
160 s.mu.Lock()
161 nkey := s.opts.Nkeys[0]
162 s.mu.Unlock()
163 for act := range nkey.AllowedConnectionTypes {
164 if act != jwt.ConnectionTypeWebsocket {
165 t.Fatalf("Expected map to have been updated with proper case, got %v", act)
166 }
167 }
168 }
169
170 func TestDNSAltNameMatching(t *testing.T) {
171 for idx, test := range []struct {
172 altName string
173 urls []string
174 match bool
175 }{
176 {"foo", []string{"FOO"}, true},
177 {"foo", []string{".."}, false},
178 {"foo", []string{"."}, false},
179 {"Foo", []string{"foO"}, true},
180 {"FOO", []string{"foo"}, true},
181 {"foo1", []string{"bar"}, false},
182 {"multi", []string{"m", "mu", "mul", "multi"}, true},
183 {"multi", []string{"multi", "m", "mu", "mul"}, true},
184 {"foo.bar", []string{"foo", "foo.bar.bar", "foo.baz"}, false},
185 {"foo.Bar", []string{"foo", "bar.foo", "Foo.Bar"}, true},
186 {"foo.*", []string{"foo", "bar.foo", "Foo.Bar"}, false}, // only match left most
187 {"f*.bar", []string{"foo", "bar.foo", "Foo.Bar"}, false},
188 {"*.bar", []string{"foo.bar"}, true},
189 {"*", []string{"baz.bar", "bar", "z.y"}, true},
190 {"*", []string{"bar"}, true},
191 {"*", []string{"."}, false},
192 {"*", []string{""}, true},
193 {"*", []string{"*"}, true},
194 {"bar.*", []string{"bar.*"}, true},
195 {"*.Y-X-red-mgmt.default.svc", []string{"A.Y-X-red-mgmt.default.svc"}, true},
196 {"*.Y-X-green-mgmt.default.svc", []string{"A.Y-X-green-mgmt.default.svc"}, true},
197 {"*.Y-X-blue-mgmt.default.svc", []string{"A.Y-X-blue-mgmt.default.svc"}, true},
198 {"Y-X-red-mgmt", []string{"Y-X-red-mgmt"}, true},
199 {"Y-X-red-mgmt", []string{"X-X-red-mgmt"}, false},
200 {"Y-X-red-mgmt", []string{"Y-X-green-mgmt"}, false},
201 {"Y-X-red-mgmt", []string{"Y"}, false},
202 {"Y-X-red-mgmt", []string{"Y-X"}, false},
203 {"Y-X-red-mgmt", []string{"Y-X-red"}, false},
204 {"Y-X-red-mgmt", []string{"X-red-mgmt"}, false},
205 {"Y-X-green-mgmt", []string{"Y-X-green-mgmt"}, true},
206 {"Y-X-blue-mgmt", []string{"Y-X-blue-mgmt"}, true},
207 {"connect.Y.local", []string{"connect.Y.local"}, true},
208 {"connect.Y.local", []string{".Y.local"}, false},
209 {"connect.Y.local", []string{"..local"}, false},
210 {"gcp.Y.local", []string{"gcp.Y.local"}, true},
211 {"uswest1.gcp.Y.local", []string{"uswest1.gcp.Y.local"}, true},
212 } {
213 urlSet := make([]*url.URL, len(test.urls))
214 for i, u := range test.urls {
215 var err error
216 urlSet[i], err = url.Parse("nats://" + u)
217 if err != nil {
218 t.Fatal(err)
219 }
220 }
221 if dnsAltNameMatches(dnsAltNameLabels(test.altName), urlSet) != test.match {
222 t.Fatal("Test", idx, "Match miss match, expected:", test.match)
223 }
224 }
225 }
226
227 func TestProcessUserPermissionsTemplateMalformedOpDoesNotPanic(t *testing.T) {
228 defer require_NoPanic(t)
229
230 lim := jwt.UserPermissionLimits{}
231 lim.Permissions.Sub.Deny = jwt.StringList{"foo.{{x}}"}
232
233 _, err := processUserPermissionsTemplate(lim, &jwt.UserClaims{}, &Account{})
234 require_Error(t, err)
235 }
236
237 func TestProcessUserPermissionsTemplateUnknownAllowOpDoesNotPanic(t *testing.T) {
238 defer require_NoPanic(t)
239
240 lim := jwt.UserPermissionLimits{}
241 lim.Permissions.Pub.Allow = jwt.StringList{"foo.{{unknown()}}"}
242
243 _, err := processUserPermissionsTemplate(lim, &jwt.UserClaims{}, &Account{})
244 require_Error(t, err)
245 }
246
247 func TestProcessUserPermissionsTemplateRejectsExcessiveTagExpansions(t *testing.T) {
248 defer require_NoPanic(t)
249
250 lim := jwt.UserPermissionLimits{}
251 lim.Permissions.Pub.Allow = jwt.StringList{"foo.{{tag(a)}}.{{tag(b)}}"}
252
253 uc := &jwt.UserClaims{}
254 for i := range 128 {
255 uc.Tags = append(uc.Tags, fmt.Sprintf("a:v%d", i))
256 uc.Tags = append(uc.Tags, fmt.Sprintf("b:v%d", i))
257 }
258
259 _, err := processUserPermissionsTemplate(lim, uc, &Account{})
260 require_Error(t, err)
261 }
262
263 func TestNoAuthUser(t *testing.T) {
264 conf := createConfFile(t, []byte(`
265 listen: "127.0.0.1:-1"
266 accounts {
267 FOO { users [{user: "foo", password: "pwd1"}] }
268 BAR { users [{user: "bar", password: "pwd2"}] }
269 }
270 no_auth_user: "foo"
271 `))
272 defer os.Remove(conf)
273 s, o := RunServerWithConfig(conf)
274 defer s.Shutdown()
275
276 for _, test := range []struct {
277 name string
278 usrInfo string
279 ok bool
280 account string
281 }{
282 {"valid user/pwd", "bar:pwd2@", true, "BAR"},
283 {"invalid pwd", "bar:wrong@", false, _EMPTY_},
284 {"some token", "sometoken@", false, _EMPTY_},
285 {"user used without pwd", "bar@", false, _EMPTY_}, // will be treated as a token
286 {"user with empty password", "bar:@", false, _EMPTY_},
287 {"no user", _EMPTY_, true, "FOO"},
288 } {
289 t.Run(test.name, func(t *testing.T) {
290 url := fmt.Sprintf("nats://%s127.0.0.1:%d", test.usrInfo, o.Port)
291 nc, err := nats.Connect(url)
292 if err != nil {
293 if test.ok {
294 t.Fatalf("Unexpected error: %v", err)
295 }
296 return
297 } else if !test.ok {
298 nc.Close()
299 t.Fatalf("Should have failed, did not")
300 }
301 var accName string
302 s.mu.Lock()
303 for _, c := range s.clients {
304 c.mu.Lock()
305 if c.acc != nil {
306 accName = c.acc.Name
307 }
308 c.mu.Unlock()
309 break
310 }
311 s.mu.Unlock()
312 nc.Close()
313 checkClientsCount(t, s, 0)
314 if accName != test.account {
315 t.Fatalf("The account should have been %q, got %q", test.account, accName)
316 }
317 })
318 }
319 }
320
321 func TestNoAuthUserNkey(t *testing.T) {
322 conf := createConfFile(t, []byte(`
323 listen: "127.0.0.1:-1"
324 accounts {
325 FOO { users [{user: "foo", password: "pwd1"}] }
326 BAR { users [{nkey: "UBO2MQV67TQTVIRV3XFTEZOACM4WLOCMCDMAWN5QVN5PI2N6JHTVDRON"}] }
327 }
328 no_auth_user: "UBO2MQV67TQTVIRV3XFTEZOACM4WLOCMCDMAWN5QVN5PI2N6JHTVDRON"
329 `))
330 s, _ := RunServerWithConfig(conf)
331 defer s.Shutdown()
332
333 // Make sure we connect ok and to the correct account.
334 nc := natsConnect(t, s.ClientURL())
335 defer nc.Close()
336 resp, err := nc.Request(userDirectInfoSubj, nil, time.Second)
337 require_NoError(t, err)
338 response := ServerAPIResponse{Data: &UserInfo{}}
339 err = json.Unmarshal(resp.Data, &response)
340 require_NoError(t, err)
341 userInfo := response.Data.(*UserInfo)
342 require_Equal(t, userInfo.UserID, "UBO2MQV67TQTVIRV3XFTEZOACM4WLOCMCDMAWN5QVN5PI2N6JHTVDRON")
343 require_Equal(t, userInfo.Account, "BAR")
344 }
345
346 func TestUserConnectionDeadline(t *testing.T) {
347 clientAuth := &DummyAuth{
348 t: t,
349 register: true,
350 deadline: time.Now().Add(50 * time.Millisecond),
351 }
352
353 opts := DefaultOptions()
354 opts.CustomClientAuthentication = clientAuth
355
356 s := RunServer(opts)
357 defer s.Shutdown()
358
359 var dcerr error
360
361 ctx, cancel := context.WithTimeout(context.Background(), time.Second)
362
363 nc, err := nats.Connect(
364 s.ClientURL(),
365 nats.UserInfo("valid", _EMPTY_),
366 nats.NoReconnect(),
367 nats.ErrorHandler(func(nc *nats.Conn, _ *nats.Subscription, err error) {
368 dcerr = err
369 cancel()
370 }))
371 if err != nil {
372 t.Fatalf("Expected client to connect, got: %s", err)
373 }
374
375 <-ctx.Done()
376
377 checkFor(t, 2*time.Second, 100*time.Millisecond, func() error {
378 if nc.IsConnected() {
379 return fmt.Errorf("Expected to be disconnected")
380 }
381 return nil
382 })
383
384 if dcerr == nil || dcerr.Error() != "nats: authentication expired" {
385 t.Fatalf("Expected a auth expired error: got: %v", dcerr)
386 }
387 }
388
389 func TestNoAuthUserNoConnectProto(t *testing.T) {
390 conf := createConfFile(t, []byte(`
391 listen: "127.0.0.1:-1"
392 accounts {
393 A { users [{user: "foo", password: "pwd"}] }
394 }
395 authorization { timeout: 1 }
396 no_auth_user: "foo"
397 `))
398 defer os.Remove(conf)
399 s, o := RunServerWithConfig(conf)
400 defer s.Shutdown()
401
402 checkClients := func(n int) {
403 t.Helper()
404 time.Sleep(100 * time.Millisecond)
405 if nc := s.NumClients(); nc != n {
406 t.Fatalf("Expected %d clients, got %d", n, nc)
407 }
408 }
409
410 conn, err := net.Dial("tcp", net.JoinHostPort(o.Host, fmt.Sprintf("%d", o.Port)))
411 require_NoError(t, err)
412 defer conn.Close()
413 checkClientsCount(t, s, 1)
414
415 // With no auth user we should not require a CONNECT.
416 // Make sure we are good on not sending CONN first.
417 _, err = conn.Write([]byte("PUB foo 2\r\nok\r\n"))
418 require_NoError(t, err)
419 checkClients(1)
420 conn.Close()
421
422 // Now make sure we still do get timed out though.
423 conn, err = net.Dial("tcp", net.JoinHostPort(o.Host, fmt.Sprintf("%d", o.Port)))
424 require_NoError(t, err)
425 defer conn.Close()
426 checkClientsCount(t, s, 1)
427
428 time.Sleep(1200 * time.Millisecond)
429 checkClientsCount(t, s, 0)
430 }
431
432 type captureProxyRequiredLogger struct {
433 DummyLogger
434 ch chan string
435 }
436
437 func (l *captureProxyRequiredLogger) Debugf(format string, args ...any) {
438 msg := fmt.Sprintf(format, args...)
439 if strings.Contains(msg, ErrAuthProxyRequired.Error()) {
440 select {
441 case l.ch <- msg:
442 default:
443 }
444 }
445 }
446
447 func TestAuthProxyRequired(t *testing.T) {
448 conf := createConfFile(t, []byte(`
449 port: -1
450 authorization {
451 user: user
452 password: pwd
453 proxy_required: true
454 }
455 `))
456 s, _ := RunServerWithConfig(conf)
457 defer s.Shutdown()
458
459 l := &captureProxyRequiredLogger{ch: make(chan string, 1)}
460 s.SetLogger(l, true, false)
461
462 _, err := nats.Connect(s.ClientURL(), nats.UserInfo("user", "pwd"))
463 require_True(t, errors.Is(err, nats.ErrAuthorization))
464
465 checkLog := func() {
466 t.Helper()
467 select {
468 case <-l.ch:
469 return
470 case <-time.After(time.Second):
471 t.Fatal("Did not get log statement")
472 }
473 }
474 checkLog()
475
476 drainLog := func() {
477 for {
478 select {
479 case <-l.ch:
480 default:
481 return
482 }
483 }
484 }
485 s.Shutdown()
486 drainLog()
487
488 nkUsr1, err := nkeys.CreateUser()
489 require_NoError(t, err)
490 nkPub1, err := nkUsr1.PublicKey()
491 require_NoError(t, err)
492
493 nkUsr2, err := nkeys.CreateUser()
494 require_NoError(t, err)
495 nkPub2, err := nkUsr2.PublicKey()
496 require_NoError(t, err)
497
498 conf = createConfFile(t, fmt.Appendf(nil, `
499 port: -1
500 authorization {
501 users: [
502 {user: user1, password: pwd1}
503 {user: user2, password: pwd2, proxy_required: true}
504 {user: user3, password: pwd3, proxy_required: false}
505 {nkey: "%s", proxy_required: true}
506 {nkey: "%s", proxy_required: false}
507 ]
508 }
509 `, nkPub1, nkPub2))
510 s, _ = RunServerWithConfig(conf)
511 defer s.Shutdown()
512
513 s.SetLogger(l, true, false)
514
515 checkClients := func() {
516 t.Helper()
517 // Should connect ok.
518 nc := natsConnect(t, s.ClientURL(), nats.UserInfo("user1", "pwd1"))
519 nc.Close()
520
521 // Should not, since it requires going through proxy.
522 _, err = nats.Connect(s.ClientURL(), nats.UserInfo("user2", "pwd2"))
523 require_True(t, errors.Is(err, nats.ErrAuthorization))
524 checkLog()
525
526 // Should connect ok.
527 nc = natsConnect(t, s.ClientURL(), nats.UserInfo("user3", "pwd3"))
528 nc.Close()
529
530 // Should not, since it requires going through proxy.
531 _, err = nats.Connect(s.ClientURL(), nats.Nkey(nkPub1, func(nonce []byte) ([]byte, error) {
532 return nkUsr1.Sign(nonce)
533 }))
534 require_True(t, errors.Is(err, nats.ErrAuthorization))
535 checkLog()
536
537 // Should connect ok.
538 nc = natsConnect(t, s.ClientURL(), nats.Nkey(nkPub2, func(nonce []byte) ([]byte, error) {
539 return nkUsr2.Sign(nonce)
540 }))
541 nc.Close()
542 }
543 checkClients()
544 s.Shutdown()
545 drainLog()
546
547 conf = createConfFile(t, fmt.Appendf(nil, `
548 port: -1
549 accounts {
550 A {
551 users: [
552 {user: user1, password: pwd1}
553 {user: user2, password: pwd2, proxy_required: true}
554 {user: user3, password: pwd3, proxy_required: false}
555 {nkey: "%s", proxy_required: true}
556 {nkey: "%s", proxy_required: false}
557 ]
558 }
559 SYS { users: [ {user:sys, password: pwd} ] }
560 }
561 system_account: SYS
562 `, nkPub1, nkPub2))
563 s, _ = RunServerWithConfig(conf)
564 defer s.Shutdown()
565
566 s.SetLogger(l, true, false)
567
568 snc := natsConnect(t, s.ClientURL(), nats.UserInfo("sys", "pwd"))
569 defer snc.Close()
570 sub := natsSubSync(t, snc, "$SYS.SERVER.*.CLIENT.AUTH.ERR")
571 sub2 := natsSubSync(t, snc, "$SYS.ACCOUNT.A.DISCONNECT")
572 natsFlush(t, snc)
573
574 checkClients()
575
576 // We should get 2 authentication error messages, saying that
577 // the reason is "ProxyRequired".
578 for range 2 {
579 var de DisconnectEventMsg
580 msg := natsNexMsg(t, sub, time.Second)
581 err = json.Unmarshal(msg.Data, &de)
582 require_NoError(t, err)
583 require_Equal(t, de.Reason, ProxyRequired.String())
584 }
585
586 // We should get 3 disconnect events since only 3 have connected
587 // ok and then just closed.
588 for range 3 {
589 var de DisconnectEventMsg
590 msg := natsNexMsg(t, sub2, time.Second)
591 err = json.Unmarshal(msg.Data, &de)
592 require_NoError(t, err)
593 require_Equal(t, de.Reason, ClientClosed.String())
594 }
595 // Make sure there is no more.
596 if msg, err := sub2.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout {
597 t.Fatalf("Should have received only 3 disconnect messages, got another: %s", msg.Data)
598 }
599
600 s.Shutdown()
601 drainLog()
602
603 conf = createConfFile(t, []byte(`
604 port: -1
605 leafnodes: {
606 port: -1
607 authorization {
608 user: user
609 password: pwd
610 proxy_required: true
611 }
612 }
613 `))
614 s, o := RunServerWithConfig(conf)
615 defer s.Shutdown()
616
617 s.SetLogger(l, true, false)
618
619 lconf := createConfFile(t, fmt.Appendf(nil, `
620 port: -1
621 leafnodes {
622 reconnect_interval: "50ms"
623 remotes [ {url: "nats://user:[email protected]:%d"} ]
624 }
625 `, o.LeafNode.Port))
626 leaf, _ := RunServerWithConfig(lconf)
627 defer leaf.Shutdown()
628
629 time.Sleep(125 * time.Millisecond)
630 checkLeafNodeConnectedCount(t, leaf, 0)
631 checkLog()
632 leaf.Shutdown()
633 s.Shutdown()
634 drainLog()
635
636 conf = createConfFile(t, []byte(`
637 port: -1
638 leafnodes: {
639 port: -1
640 reconnect_interval: "50ms"
641 authorization {
642 users: [
643 {user: user1, password: pwd1}
644 {user: user2, password: pwd2, proxy_required: true}
645 {user: user3, password: pwd3, proxy_required: false}
646 ]
647 }
648 }
649 `))
650 s, o = RunServerWithConfig(conf)
651 defer s.Shutdown()
652
653 s.SetLogger(l, true, false)
654
655 lconf = createConfFile(t, fmt.Appendf(nil, `
656 port: -1
657 leafnodes {
658 reconnect_interval: "50ms"
659 remotes [ {url: "nats://user2:[email protected]:%d"} ]
660 }
661 `, o.LeafNode.Port))
662 leaf, _ = RunServerWithConfig(lconf)
663 defer leaf.Shutdown()
664
665 time.Sleep(125 * time.Millisecond)
666 checkLeafNodeConnectedCount(t, leaf, 0)
667 checkLog()
668 leaf.Shutdown()
669 s.Shutdown()
670 drainLog()
671
672 conf = createConfFile(t, fmt.Appendf(nil, `
673 port: -1
674 leafnodes: {
675 port: -1
676 authorization {
677 nkey: %s
678 proxy_required: true
679 }
680 }
681 `, nkPub1))
682 s, o = RunServerWithConfig(conf)
683 defer s.Shutdown()
684
685 s.SetLogger(l, true, false)
686
687 nkSeed1, err := nkUsr1.Seed()
688 require_NoError(t, err)
689
690 lconf = createConfFile(t, fmt.Appendf(nil, `
691 port: -1
692 leafnodes {
693 reconnect_interval: "50ms"
694 remotes [
695 {
696 url: "nats://127.0.0.1:%d"
697 nkey: "%s"
698 }
699 ]
700 }
701 `, o.LeafNode.Port, nkSeed1))
702 leaf, _ = RunServerWithConfig(lconf)
703 defer leaf.Shutdown()
704
705 time.Sleep(125 * time.Millisecond)
706 checkLeafNodeConnectedCount(t, leaf, 0)
707 checkLog()
708 leaf.Shutdown()
709 s.Shutdown()
710 drainLog()
711
712 // Check with operator mode.
713 conf = createConfFile(t, []byte(`
714 port: -1
715 server_name: OP
716 operator = "../test/configs/nkeys/op.jwt"
717 resolver = MEMORY
718 listen: "127.0.0.1:-1"
719 leafnodes {
720 listen: "127.0.0.1:-1"
721 }
722 `))
723 s, o = RunServerWithConfig(conf)
724 defer s.Shutdown()
725
726 s.SetLogger(l, true, false)
727
728 _, akp := createAccount(s)
729 kp, err := nkeys.CreateUser()
730 require_NoError(t, err)
731 pub, err := kp.PublicKey()
732 require_NoError(t, err)
733 nuc := jwt.NewUserClaims(pub)
734 nuc.ProxyRequired = true
735 ujwt, err := nuc.Encode(akp)
736 require_NoError(t, err)
737
738 dto := DefaultTestOptions
739 lopts := &dto
740 u, err := url.Parse(fmt.Sprintf("nats://%s:%d", o.LeafNode.Host, o.LeafNode.Port))
741 require_NoError(t, err)
742 remote := &RemoteLeafOpts{URLs: []*url.URL{u}}
743 remote.SignatureCB = func(nonce []byte) (string, []byte, error) {
744 sig, err := kp.Sign(nonce)
745 return ujwt, sig, err
746 }
747 lopts.LeafNode.Remotes = []*RemoteLeafOpts{remote}
748 lopts.LeafNode.ReconnectInterval = 100 * time.Millisecond
749 leaf = RunServer(lopts)
750 defer leaf.Shutdown()
751
752 time.Sleep(125 * time.Millisecond)
753 checkLeafNodeConnectedCount(t, leaf, 0)
754 checkLog()
755 leaf.Shutdown()
756
757 // Try with an user.
758 drainLog()
759
760 _, err = nats.Connect(s.ClientURL(), createUserCredsEx(t, nuc, akp))
761 require_True(t, errors.Is(err, nats.ErrAuthorization))
762 checkLog()
763
764 drainLog()
765
766 // Try with creds file.
767 kp, err = nkeys.CreateUser()
768 require_NoError(t, err)
769 useed, err := kp.Seed()
770 require_NoError(t, err)
771 pub, err = kp.PublicKey()
772 require_NoError(t, err)
773 nuc = jwt.NewUserClaims(pub)
774 nuc.ProxyRequired = true
775 ujwt, err = nuc.Encode(akp)
776 require_NoError(t, err)
777 credsFile := genCredsFile(t, ujwt, useed)
778
779 lconf = createConfFile(t, fmt.Appendf(nil, `
780 port: -1
781 leafnodes {
782 reconnect_interval: "50ms"
783 remotes [
784 {
785 url: "nats://127.0.0.1:%d"
786 credentials: '%s'
787 }
788 ]
789 }
790 `, o.LeafNode.Port, credsFile))
791 leaf, _ = RunServerWithConfig(lconf)
792 defer leaf.Shutdown()
793
794 time.Sleep(125 * time.Millisecond)
795 checkLeafNodeConnectedCount(t, leaf, 0)
796 checkLog()
797 leaf.Shutdown()
798
799 s.Shutdown()
800 drainLog()
801 }
802
803 func TestAuthProxyCheckConnClosedDuringAuth(t *testing.T) {
804 pkp, err := nkeys.CreateUser()
805 require_NoError(t, err)
806 pub, err := pkp.PublicKey()
807 require_NoError(t, err)
808
809 o := DefaultOptions()
810 o.Proxies = &ProxiesConfig{Trusted: []*ProxyConfig{{Key: pub}}}
811 s := RunServer(o)
812 defer s.Shutdown()
813
814 c, _, _ := newClientForServer(s)
815 defer c.close()
816
817 // Sign the connection's nonce as the trusted proxy would and store
818 // the signature in the connect options.
819 c.mu.Lock()
820 sig, err := pkp.Sign(c.nonce)
821 if err == nil {
822 c.opts.ProxySig = base64.RawURLEncoding.EncodeToString(sig)
823 }
824 c.mu.Unlock()
825 require_NoError(t, err)
826
827 // Simulate the connection being closed concurrently (write error,
828 // shutdown, kick, etc..) while the readLoop is still authenticating:
829 // closeConnection invokes removeClient, which tries to remove the
830 // connection from s.proxiedConns before proxyCheck registered it.
831 c.client.closeConnection(ClientClosed)
832
833 // Now run proxyCheck as checkAuthentication would on the readLoop.
834 proxied, ok := s.proxyCheck(c.client, s.getOpts())
835 require_True(t, proxied)
836 require_True(t, ok)
837
838 // Since the connection is already closed and removeClient already ran,
839 // the client must not have been registered in s.proxiedConns, since
840 // nothing would ever remove it.
841 s.mu.RLock()
842 conns := s.proxiedConns[pub]
843 s.mu.RUnlock()
844 require_Len(t, len(conns), 0)
845 }
846
847 const (
848 authViolation = "-ERR 'Authorization Violation'"
849 authAccepted = "PONG\r\n"
850 )
851
852 // testAuthWSConnect sends a websocket CONNECT with the given user and password
853 // followed by a PING, and checks that the first protocol frame the server sends
854 // back starts with expect. Going through the raw protocol rather than a
855 // nats.Conn keeps the failure deterministic: the server closes right after
856 // writing the error, so a client would race it and may surface the closed
857 // connection instead.
858 func testAuthWSConnect(t *testing.T, o *Options, user, pass, expect string) {
859 t.Helper()
860 wsc, br, _ := testNewWSClient(t, testWSClientOptions{
861 host: o.Websocket.Host,
862 port: o.Websocket.Port,
863 noTLS: true,
864 })
865 defer wsc.Close()
866
867 proto := fmt.Sprintf("CONNECT {\"verbose\":false,\"protocol\":1,\"user\":%q,\"pass\":%q}\r\nPING\r\n", user, pass)
868 if _, err := wsc.Write(testWSCreateClientMsg(wsBinaryMessage, 1, true, false, []byte(proto))); err != nil {
869 t.Fatalf("Error sending message: %v", err)
870 }
871 if msg := string(testWSReadFrame(t, br)); !strings.HasPrefix(msg, expect) {
872 t.Fatalf("Expected %q, got %q", expect, msg)
873 }
874 }
875
876 func TestAuthCertMappedUserNotPasswordAuthenticatable(t *testing.T) {
877 const certUser = "CN=example.com,OU=NATS.io"
878
879 // The client port has to be reachable under a name the test certificates
880 // carry a SAN for, hence localhost rather than 127.0.0.1.
881 conf := createConfFile(t, []byte(fmt.Sprintf(`
882 listen: "localhost:-1"
883 server_name: "S1"
884 tls {
885 cert_file: "../test/configs/certs/tlsauth/server.pem"
886 key_file: "../test/configs/certs/tlsauth/server-key.pem"
887 ca_file: "../test/configs/certs/tlsauth/ca.pem"
888 verify_and_map: true
889 }
890 leafnodes { listen: "127.0.0.1:-1" }
891 websocket { listen: "127.0.0.1:-1", no_tls: true }
892 authorization {
893 users [
894 { user = "CN=other.example.com,OU=NATS.io" }
895 { user = "%s" }
896 ]
897 }
898 `, certUser)))
899 s, o := RunServerWithConfig(conf)
900 defer s.Shutdown()
901
902 for _, test := range []struct {
903 name string
904 user string
905 pass string
906 }{
907 {"empty password", certUser, _EMPTY_},
908 {"wrong password", certUser, "wrongpassword"},
909 {"unknown user", "CN=attacker.com,OU=NATS.io", _EMPTY_},
910 {"anonymous", _EMPTY_, _EMPTY_},
911 } {
912 t.Run(test.name, func(t *testing.T) {
913 t.Run("leafnode", func(t *testing.T) {
914 c, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", o.LeafNode.Port))
915 require_NoError(t, err)
916 defer c.Close()
917
918 br := bufio.NewReader(c)
919 c.SetDeadline(time.Now().Add(2 * time.Second))
920 // Consume the INFO the server sends on accept.
921 _, _, err = br.ReadLine()
922 require_NoError(t, err)
923
924 _, err = fmt.Fprintf(c, "CONNECT {\"user\":%q,\"pass\":%q}\r\nPING\r\n", test.user, test.pass)
925 require_NoError(t, err)
926
927 line, _, err := br.ReadLine()
928 require_NoError(t, err)
929 require_Contains(t, string(line), authViolation)
930 })
931
932 // The mqtt listener is covered by
933 // TestMQTTCertMappedUserNotPasswordAuthenticatable, its helpers are
934 // behind the skip_mqtt_tests build tag.
935 t.Run("websocket", func(t *testing.T) {
936 testAuthWSConnect(t, o, test.user, test.pass, authViolation)
937 })
938 })
939 }
940
941 // The certificate based login on the mapped listener must still work.
942 nc := natsConnect(t, s.ClientURL(),
943 nats.ClientCert("../test/configs/certs/tlsauth/client.pem", "../test/configs/certs/tlsauth/client-key.pem"),
944 nats.RootCAs("../test/configs/certs/tlsauth/ca.pem"))
945 defer nc.Close()
946 natsFlush(t, nc)
947 }
948
949 func TestAuthCertMappedUserWithPassword(t *testing.T) {
950 const certUser = "CN=example.com,OU=NATS.io"
951
952 conf := createConfFile(t, []byte(`
953 listen: "localhost:-1"
954 tls {
955 cert_file: "../test/configs/certs/tlsauth/server.pem"
956 key_file: "../test/configs/certs/tlsauth/server-key.pem"
957 ca_file: "../test/configs/certs/tlsauth/ca.pem"
958 verify_and_map: true
959 }
960 websocket { listen: "127.0.0.1:-1", no_tls: true }
961 authorization {
962 users [
963 { user = "CN=other.example.com,OU=NATS.io" }
964 { user = "CN=example.com,OU=NATS.io", password = "s3cr3t" }
965 ]
966 }
967 `))
968 s, o := RunServerWithConfig(conf)
969 defer s.Shutdown()
970
971 certOpts := []nats.Option{
972 nats.ClientCert("../test/configs/certs/tlsauth/client.pem", "../test/configs/certs/tlsauth/client-key.pem"),
973 nats.RootCAs("../test/configs/certs/tlsauth/ca.pem"),
974 }
975
976 // The certificate on its own does not authenticate: the configured password
977 // is still compared against what the client sent.
978 if bad, err := nats.Connect(s.ClientURL(), certOpts...); err == nil {
979 bad.Close()
980 t.Fatal("Expected connection without the password to fail, it did not")
981 }
982
983 // The certificate together with the password does.
984 nc := natsConnect(t, s.ClientURL(), append(certOpts, nats.UserInfo(_EMPTY_, "s3cr3t"))...)
985 defer nc.Close()
986 natsFlush(t, nc)
987
988 // On the listener that does not map, the password is what authenticates.
989 testAuthWSConnect(t, o, certUser, "s3cr3t", authAccepted)
990
991 // But an empty one still does not.
992 testAuthWSConnect(t, o, certUser, _EMPTY_, authViolation)
993 }
994
995 func TestAuthNoAuthUserWithoutPasswordAndCertMapping(t *testing.T) {
996 conf := createConfFile(t, []byte(`
997 listen: "127.0.0.1:-1"
998 tls {
999 cert_file: "../test/configs/certs/tlsauth/server.pem"
1000 key_file: "../test/configs/certs/tlsauth/server-key.pem"
1001 ca_file: "../test/configs/certs/tlsauth/ca.pem"
1002 verify_and_map: true
1003 }
1004 websocket { listen: "127.0.0.1:-1", no_tls: true }
1005 authorization {
1006 users [
1007 { user = "CN=example.com,OU=NATS.io" }
1008 { user = "guest" }
1009 ]
1010 }
1011 no_auth_user: "guest"
1012 `))
1013 s, o := RunServerWithConfig(conf)
1014 defer s.Shutdown()
1015
1016 // No credentials at all, so the server selects the no_auth_user itself.
1017 testAuthWSConnect(t, o, _EMPTY_, _EMPTY_, authAccepted)
1018
1019 // Naming the no_auth_user explicitly is equivalent, it is reachable without
1020 // credentials either way.
1021 testAuthWSConnect(t, o, "guest", _EMPTY_, authAccepted)
1022
1023 // The other passwordless user is a certificate identity, so naming it
1024 // explicitly must not authenticate.
1025 testAuthWSConnect(t, o, "CN=example.com,OU=NATS.io", _EMPTY_, authViolation)
1026 }
1027
1028 func TestAuthCertMappedLeafNodeUsersScope(t *testing.T) {
1029 const (
1030 certUser = "CN=example.com,OU=NATS.io"
1031 leafTLS = `tls {
1032 cert_file: "../test/configs/certs/tlsauth/server.pem"
1033 key_file: "../test/configs/certs/tlsauth/server-key.pem"
1034 ca_file: "../test/configs/certs/tlsauth/ca.pem"
1035 verify_and_map: true
1036 }`
1037 )
1038
1039 // A leafnode block with its own users never consults the server's users
1040 // table, so its mapping says nothing about the users defined there. A
1041 // passwordless user in the top-level authorization block is not a
1042 // certificate identity here and must still authenticate.
1043 t.Run("leafnode users", func(t *testing.T) {
1044 conf := createConfFile(t, []byte(fmt.Sprintf(`
1045 listen: "127.0.0.1:-1"
1046 websocket { listen: "127.0.0.1:-1", no_tls: true }
1047 leafnodes {
1048 listen: "127.0.0.1:-1"
1049 %s
1050 authorization { users = [ { user = %q } ] }
1051 }
1052 authorization { users = [ { user = "telemetry" } ] }
1053 `, leafTLS, certUser)))
1054 s, o := RunServerWithConfig(conf)
1055 defer s.Shutdown()
1056
1057 testAuthWSConnect(t, o, "telemetry", _EMPTY_, authAccepted)
1058 })
1059
1060 // Without a leafnode authorization block the leafnode listener falls back to
1061 // the server's users table, so its mapping does make the passwordless users
1062 // there certificate identities.
1063 t.Run("no leafnode users", func(t *testing.T) {
1064 conf := createConfFile(t, []byte(fmt.Sprintf(`
1065 listen: "127.0.0.1:-1"
1066 websocket { listen: "127.0.0.1:-1", no_tls: true }
1067 leafnodes {
1068 listen: "127.0.0.1:-1"
1069 %s
1070 }
1071 authorization { users = [ { user = %q } ] }
1072 `, leafTLS, certUser)))
1073 s, o := RunServerWithConfig(conf)
1074 defer s.Shutdown()
1075
1076 testAuthWSConnect(t, o, certUser, _EMPTY_, authViolation)
1077 })
1078 }
1079
1080 // testAuthConnect performs the same CONNECT/PING exchange as testAuthWSConnect,
1081 // but over the plain client port.
1082 func testAuthConnect(t *testing.T, o *Options, user, pass, expect string) {
1083 t.Helper()
1084 c, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", o.Port))
1085 require_NoError(t, err)
1086 defer c.Close()
1087
1088 br := bufio.NewReader(c)
1089 c.SetDeadline(time.Now().Add(5 * time.Second))
1090 // Consume the INFO the server sends on accept.
1091 _, err = br.ReadString('\n')
1092 require_NoError(t, err)
1093
1094 _, err = fmt.Fprintf(c, "CONNECT {\"verbose\":false,\"protocol\":1,\"user\":%q,\"pass\":%q}\r\nPING\r\n", user, pass)
1095 require_NoError(t, err)
1096
1097 msg, err := br.ReadString('\n')
1098 require_NoError(t, err)
1099 if !strings.HasPrefix(msg, expect) {
1100 t.Fatalf("Expected %q, got %q", expect, msg)
1101 }
1102 }
1103
1104 func TestAuthCertMappedUserConnectionTypeScope(t *testing.T) {
1105 // Only the client listener maps, so a passwordless user is a certificate
1106 // identity only if the mapping lookup there could have selected it, which it
1107 // cannot once allowed_connection_types excludes STANDARD.
1108 for _, test := range []struct {
1109 name string
1110 types string
1111 expect string
1112 }{
1113 {"unscoped", _EMPTY_, authViolation},
1114 {"standard and websocket", `, allowed_connection_types: ["STANDARD","WEBSOCKET"]`, authViolation},
1115 {"websocket only", `, allowed_connection_types: ["WEBSOCKET"]`, authAccepted},
1116 {"mqtt and websocket", `, allowed_connection_types: ["MQTT","WEBSOCKET"]`, authAccepted},
1117 } {
1118 t.Run(test.name, func(t *testing.T) {
1119 conf := createConfFile(t, []byte(fmt.Sprintf(`
1120 listen: "127.0.0.1:-1"
1121 tls {
1122 cert_file: "../test/configs/certs/tlsauth/server.pem"
1123 key_file: "../test/configs/certs/tlsauth/server-key.pem"
1124 ca_file: "../test/configs/certs/tlsauth/ca.pem"
1125 verify_and_map: true
1126 }
1127 websocket { listen: "127.0.0.1:-1", no_tls: true }
1128 authorization {
1129 users [
1130 { user = "CN=example.com,OU=NATS.io" }
1131 { user = "scoped"%s }
1132 ]
1133 }
1134 `, test.types)))
1135 s, o := RunServerWithConfig(conf)
1136 defer s.Shutdown()
1137
1138 testAuthWSConnect(t, o, "scoped", _EMPTY_, test.expect)
1139 })
1140 }
1141 }
1142
1143 func TestAuthCertMappedUserOnOtherListeners(t *testing.T) {
1144 const certs = `
1145 cert_file: "../test/configs/certs/tlsauth/server.pem"
1146 key_file: "../test/configs/certs/tlsauth/server-key.pem"
1147 ca_file: "../test/configs/certs/tlsauth/ca.pem"
1148 verify_and_map: true`
1149
1150 wsMapped := fmt.Sprintf(`websocket { listen: "127.0.0.1:-1", tls {%s} }`, certs)
1151 mqttMapped := fmt.Sprintf(`mqtt { listen: "127.0.0.1:-1", tls {%s} }`, certs)
1152
1153 // The same blocks without a listen, so the listener never starts.
1154 wsDisabled := fmt.Sprintf(`websocket { tls {%s} }`, certs)
1155 mqttDisabled := fmt.Sprintf(`mqtt { tls {%s} }`, certs)
1156 leafDisabled := fmt.Sprintf(`leafnodes { tls {%s} }`, certs)
1157
1158 // The client listener never maps here, so whether the passwordless user is a
1159 // certificate identity depends entirely on the listener that does.
1160 for _, test := range []struct {
1161 name string
1162 listener string
1163 types string
1164 expect string
1165 }{
1166 {"websocket mapped", wsMapped, _EMPTY_, authViolation},
1167 {"websocket mapped, standard only", wsMapped, `, allowed_connection_types: ["STANDARD"]`, authAccepted},
1168 {"mqtt mapped", mqttMapped, _EMPTY_, authViolation},
1169 {"mqtt mapped, standard only", mqttMapped, `, allowed_connection_types: ["STANDARD"]`, authAccepted},
1170 // A block without a listener is inert, its mapping can select nobody.
1171 {"websocket mapped but disabled", wsDisabled, _EMPTY_, authAccepted},
1172 {"mqtt mapped but disabled", mqttDisabled, _EMPTY_, authAccepted},
1173 {"leafnode mapped but disabled", leafDisabled, _EMPTY_, authAccepted},
1174 } {
1175 t.Run(test.name, func(t *testing.T) {
1176 conf := createConfFile(t, []byte(fmt.Sprintf(`
1177 listen: "127.0.0.1:-1"
1178 jetstream { store_dir: %q }
1179 %s
1180 authorization {
1181 users [
1182 { user = "CN=example.com,OU=NATS.io" }
1183 { user = "scoped"%s }
1184 ]
1185 }
1186 `, t.TempDir(), test.listener, test.types)))
1187 s, o := RunServerWithConfig(conf)
1188 defer s.Shutdown()
1189
1190 testAuthConnect(t, o, "scoped", _EMPTY_, test.expect)
1191 })
1192 }
1193 }
1194
1195 func TestAuthCertMappedUserOverWebsocketTransport(t *testing.T) {
1196 const certs = `
1197 cert_file: "../test/configs/certs/tlsauth/server.pem"
1198 key_file: "../test/configs/certs/tlsauth/server-key.pem"
1199 ca_file: "../test/configs/certs/tlsauth/ca.pem"`
1200
1201 mqttMapped := fmt.Sprintf(`mqtt { listen: "127.0.0.1:-1", tls {%s
1202 verify_and_map: true} }`, certs)
1203 leafMapped := fmt.Sprintf(`leafnodes { listen: "127.0.0.1:-1", tls {%s
1204 verify_and_map: true} }`, certs)
1205 // Only the second websocket listener can collect a client certificate.
1206 wsPlain := `websocket { listen: "127.0.0.1:-1", no_tls: true }`
1207 wsCerts := fmt.Sprintf(`websocket { listen: "127.0.0.1:-1", tls {%s
1208 verify: true} }`, certs)
1209
1210 // Mqtt and leafnode connections over websocket are mapped with their own
1211 // listener, but can only present a certificate if the websocket listener
1212 // asks for one.
1213 for _, test := range []struct {
1214 name string
1215 mapped string
1216 ws string
1217 types string
1218 expect string
1219 }{
1220 {"mqtt, plain websocket", mqttMapped, wsPlain, `"STANDARD","MQTT_WS"`, authAccepted},
1221 {"mqtt, websocket with client certs", mqttMapped, wsCerts, `"STANDARD","MQTT_WS"`, authViolation},
1222 {"mqtt, direct mqtt allowed", mqttMapped, wsPlain, `"STANDARD","MQTT"`, authViolation},
1223 {"leafnode, plain websocket", leafMapped, wsPlain, `"STANDARD","LEAFNODE_WS"`, authAccepted},
1224 {"leafnode, websocket with client certs", leafMapped, wsCerts, `"STANDARD","LEAFNODE_WS"`, authViolation},
1225 {"leafnode, direct leafnode allowed", leafMapped, wsPlain, `"STANDARD","LEAFNODE"`, authViolation},
1226 } {
1227 t.Run(test.name, func(t *testing.T) {
1228 conf := createConfFile(t, []byte(fmt.Sprintf(`
1229 listen: "127.0.0.1:-1"
1230 jetstream { store_dir: %q }
1231 %s
1232 %s
1233 authorization {
1234 users [
1235 { user = "CN=example.com,OU=NATS.io" }
1236 { user = "scoped", allowed_connection_types: [%s] }
1237 ]
1238 }
1239 `, t.TempDir(), test.mapped, test.ws, test.types)))
1240 s, o := RunServerWithConfig(conf)
1241 defer s.Shutdown()
1242
1243 testAuthConnect(t, o, "scoped", _EMPTY_, test.expect)
1244 })
1245 }
1246 }