Debian Codegraph @

test/client_auth_test.go

raw
1 // Copyright 2016-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 test
15
16 import (
17 "encoding/base64"
18 "fmt"
19 "net"
20 "os"
21 "strings"
22 "testing"
23 "time"
24
25 "github.com/nats-io/nats-server/v2/server"
26 "github.com/nats-io/nats.go"
27 "github.com/nats-io/nkeys"
28 )
29
30 func TestMultipleUserAuth(t *testing.T) {
31 srv, opts := RunServerWithConfig("./configs/multi_user.conf")
32 defer srv.Shutdown()
33
34 if opts.Users == nil {
35 t.Fatal("Expected a user array that is not nil")
36 }
37 if len(opts.Users) != 2 {
38 t.Fatal("Expected a user array that had 2 users")
39 }
40
41 // Test first user
42 url := fmt.Sprintf("nats://%s:%s@%s:%d/",
43 opts.Users[0].Username,
44 opts.Users[0].Password,
45 opts.Host, opts.Port)
46
47 nc, err := nats.Connect(url)
48 if err != nil {
49 t.Fatalf("Expected a successful connect, got %v\n", err)
50 }
51 defer nc.Close()
52
53 if !nc.AuthRequired() {
54 t.Fatal("Expected auth to be required for the server")
55 }
56
57 // Test second user
58 url = fmt.Sprintf("nats://%s:%s@%s:%d/",
59 opts.Users[1].Username,
60 opts.Users[1].Password,
61 opts.Host, opts.Port)
62
63 nc, err = nats.Connect(url)
64 if err != nil {
65 t.Fatalf("Expected a successful connect, got %v\n", err)
66 }
67 defer nc.Close()
68 }
69
70 // Resolves to "test"
71 const testToken = "$2a$05$3sSWEVA1eMCbV0hWavDjXOx.ClBjI6u1CuUdLqf22cbJjXsnzz8/."
72
73 func TestTokenInConfig(t *testing.T) {
74 content := `
75 listen: 127.0.0.1:4567
76 authorization={
77 token: ` + testToken + `
78 timeout: 5
79 }`
80 confFile := createConfFile(t, []byte(content))
81 if err := os.WriteFile(confFile, []byte(content), 0666); err != nil {
82 t.Fatalf("Error writing config file: %v", err)
83 }
84 s, opts := RunServerWithConfig(confFile)
85 defer s.Shutdown()
86
87 url := fmt.Sprintf("nats://test@%s:%d/", opts.Host, opts.Port)
88 nc, err := nats.Connect(url)
89 if err != nil {
90 t.Fatalf("Expected a successful connect, got %v\n", err)
91 }
92 defer nc.Close()
93 if !nc.AuthRequired() {
94 t.Fatal("Expected auth to be required for the server")
95 }
96 }
97
98 func TestClientConnectInfo(t *testing.T) {
99 for _, test := range []struct {
100 name string
101 sys string
102 hasSys bool
103 protocol int
104 }{
105 {"async info support with explicit system account", "system_account: SYS", true, server.ClientProtoInfo},
106 {"async info support without explicit system account", "", false, server.ClientProtoInfo},
107 {"no async info support with explicit system account", "system_account: SYS", true, server.ClientProtoZero},
108 {"no async info support without explicit system account", "", false, server.ClientProtoZero},
109 } {
110 t.Run(test.name, func(t *testing.T) {
111 conf := createConfFile(t, []byte(fmt.Sprintf(`
112 port: -1
113 %s
114 accounts {
115 SYS: { users: [{ user: sys, password: pwd}] }
116 A: { users: [{ user: a, password: pwd}] }
117 B: { users: [{ user: b, password: pwd}] }
118 }
119 `, test.sys)))
120 hub, oHub := RunServerWithConfig(conf)
121 defer hub.Shutdown()
122
123 checkInfoOnConnect := func(user, acc string, isSys bool) {
124 t.Helper()
125 cc := createClientConn(t, oHub.Host, oHub.Port)
126 defer cc.Close()
127
128 checkInfoMsg(t, cc)
129 sendProto(t, cc, fmt.Sprintf("CONNECT {\"user\":%q,\"pass\":\"pwd\",\"pedantic\":false,\"verbose\":false,\"protocol\":%d}\r\nPING\r\n", user, test.protocol))
130 // Since the PONG and INFO may be receive as a single TCP read,
131 // make sure we consume the pong alone here.
132 pongBuf := make([]byte, len("PONG\r\n"))
133 cc.SetReadDeadline(time.Now().Add(2 * time.Second))
134 n, err := cc.Read(pongBuf)
135 cc.SetReadDeadline(time.Time{})
136 if n <= 0 && err != nil {
137 t.Fatalf("Error reading from conn: %v\n", err)
138 }
139 if !pongRe.Match(pongBuf) {
140 t.Fatalf("Response did not match expected: \n\tReceived:'%q'\n\tExpected:'%s'\n", pongBuf, pongRe)
141 }
142 if test.protocol < server.ClientProtoInfo {
143 expectNothing(t, cc)
144 } else {
145 info := checkInfoMsg(t, cc)
146 if !info.ConnectInfo {
147 t.Fatal("Expected ConnectInfo to be true")
148 }
149 if an := info.RemoteAccount; an != acc {
150 t.Fatalf("Expected account %q, got %q", acc, info.RemoteAccount)
151 }
152 if ais := info.IsSystemAccount; ais != isSys {
153 t.Fatalf("Expected IsSystemAccount to be %v, got %v", isSys, ais)
154 }
155 }
156 }
157 checkInfoOnConnect("a", "A", false)
158 checkInfoOnConnect("sys", "SYS", test.hasSys)
159 checkInfoOnConnect("b", "B", false)
160 })
161 }
162 }
163
164 type captureProxiesReloadLogger struct {
165 dummyLogger
166 ch chan string
167 }
168
169 func (l *captureProxiesReloadLogger) Noticef(format string, args ...any) {
170 msg := fmt.Sprintf(format, args...)
171 if strings.Contains(msg, "proxies trusted keys") {
172 l.ch <- msg
173 }
174 }
175
176 func TestProxyKeyVerification(t *testing.T) {
177 u1, _ := nkeys.CreateUser()
178 u1Pub, _ := u1.PublicKey()
179
180 u2, _ := nkeys.CreateUser()
181 u2Pub, _ := u2.PublicKey()
182
183 u3, _ := nkeys.CreateUser()
184 u3Pub, _ := u3.PublicKey()
185
186 tmpl := `
187 listen: "127.0.0.1:-1"
188 proxies {
189 trusted [
190 {key: %q}
191 {key: %q}
192 ]
193 }
194 leafnodes {
195 listen: "127.0.0.1:-1"
196 }
197 `
198 conf := createConfFile(t, fmt.Appendf(nil, tmpl, u1Pub, u2Pub))
199 s, o := RunServerWithConfig(conf)
200 defer s.Shutdown()
201
202 varz, err := s.Varz(nil)
203 if err != nil {
204 t.Fatalf("Error getting varz: %v", err)
205 }
206 vproxies := varz.Proxies
207 if vproxies == nil {
208 t.Fatal("Expected proxies to be not nil")
209 }
210 trusted := vproxies.Trusted
211 if len(trusted) != 2 {
212 t.Fatalf("Expected 2 trusted proxies, got %+v", trusted)
213 }
214 if k := trusted[0].Key; k != u1Pub {
215 t.Fatalf("Expected key to be %q, got %q", u1Pub, k)
216 }
217 if k := trusted[1].Key; k != u2Pub {
218 t.Fatalf("Expected key to be %q, got %q", u2Pub, k)
219 }
220
221 var currentCID uint64
222 connect := func(t *testing.T, kp nkeys.KeyPair, bsig bool, port int, isClient bool, user string) (expectFun, net.Conn) {
223 c := createClientConn(t, "127.0.0.1", port)
224 expect := expectCommand(t, c)
225 info := checkInfoMsg(t, c)
226 currentCID = info.CID
227 if info.Nonce == "" {
228 c.Close()
229 t.Fatalf("Expected nonce from INFO, got %+v", info)
230 }
231 if info.JSApiLevel != server.JSApiLevel {
232 c.Close()
233 t.Fatalf("Expected JSApiLevel to be set to %v, got %v", server.JSApiLevel, info.JSApiLevel)
234 }
235 sig, err := kp.Sign([]byte(info.Nonce))
236 if err != nil {
237 c.Close()
238 t.Fatalf("Error signing nonce %q: %v", info.Nonce, err)
239 }
240 encodedSig := make([]byte, base64.RawURLEncoding.EncodedLen(len(sig)))
241 base64.RawURLEncoding.Encode(encodedSig, sig)
242 if bsig {
243 encodedSig[0] = '*'
244 }
245 sendProto(t, c,
246 fmt.Sprintf("CONNECT {\"pedantic\":false,\"verbose\":false,\"user\":%q,\"pass\":\"pwd\",\"proxy_sig\":\"%s\"}\r\n",
247 user, string(encodedSig)))
248 if isClient {
249 sendProto(t, c, "PING\r\n")
250 }
251 return expect, c
252 }
253
254 checkClosedState := func(t *testing.T, cid uint64, reason server.ClosedState) {
255 // Closed connection getting in the closed state is done in a go routine
256 // so make sure we wait for it.
257 checkFor(t, time.Second, 100*time.Millisecond, func() error {
258 connz, err := s.Connz(&server.ConnzOptions{
259 CID: cid,
260 State: server.ConnClosed,
261 })
262 if err != nil {
263 return fmt.Errorf("Error getting connz for closed connection %v: %v", cid, err)
264 }
265 if len(connz.Conns) != 1 {
266 return fmt.Errorf("Expected 1 connection, got %v", connz.Conns)
267 }
268 conn := connz.Conns[0]
269 if conn.Reason != reason.String() {
270 return fmt.Errorf("Expected reason %q, got %q", reason.String(), conn.Reason)
271 }
272 return nil
273 })
274 }
275
276 for _, test := range []struct {
277 name string
278 kp nkeys.KeyPair
279 bsig bool
280 ok bool
281 }{
282 {"key present first", u1, false, true},
283 {"key present last", u2, false, true},
284 {"key not present", u3, false, false},
285 {"bad signature", u2, true, false},
286 } {
287 t.Run(test.name, func(t *testing.T) {
288 for _, subTest := range []struct {
289 name string
290 port int
291 isClient bool
292 }{
293 {"client", o.Port, true},
294 {"leafnodes", o.LeafNode.Port, false},
295 } {
296 t.Run(subTest.name, func(t *testing.T) {
297 expect, c := connect(t, test.kp, test.bsig, subTest.port, subTest.isClient, "user")
298 defer c.Close()
299 if test.ok {
300 var p *server.ProxyInfo
301 if subTest.isClient {
302 expect(pongRe)
303
304 connz, err := s.Connz(nil)
305 if err != nil {
306 t.Fatalf("Error getting connz: %v", err)
307 }
308 if n := len(connz.Conns); n != 1 {
309 t.Fatalf("Expected 1 ConnInfo, got %v", n)
310 }
311 ci := connz.Conns[0]
312 p = ci.Proxy
313 } else {
314 expect(infoRe)
315
316 leafz, err := s.Leafz(nil)
317 if err != nil {
318 t.Fatalf("Error getting leafz: %v", err)
319 }
320 if n := len(leafz.Leafs); n != 1 {
321 t.Fatalf("Expected 1 LeafInfo, got %v", n)
322 }
323 li := leafz.Leafs[0]
324 if li.Proxy == nil {
325 t.Fatalf("Required Proxy to be present, was not: %+v", li)
326 }
327 p = li.Proxy
328 }
329 if p == nil {
330 t.Fatalf("Required Proxy to be present, was not")
331 }
332 pub, _ := test.kp.PublicKey()
333 if p.Key != pub {
334 t.Fatalf("Expected public key to be %q, got %q", pub, p.Key)
335 }
336 } else {
337 expect(errRe)
338 checkClosedState(t, currentCID, server.ProxyNotTrusted)
339 }
340 })
341 }
342 })
343 }
344
345 // Create a connection using u1Pub and we will config reload and remove
346 // that key from the list. The client should get disconnected.
347 expectc, c := connect(t, u1, false, o.Port, true, "user")
348 defer c.Close()
349 expectc(pongRe)
350 // Capture this connection CID before the next connect.
351 cid1 := currentCID
352
353 expectl, l := connect(t, u1, false, o.LeafNode.Port, false, "user")
354 defer l.Close()
355 expectl(infoRe)
356 cid2 := currentCID
357 checkLeafNodeConnected(t, s)
358
359 logger := &captureProxiesReloadLogger{ch: make(chan string, 10)}
360 s.SetLogger(logger, false, false)
361
362 os.WriteFile(conf, fmt.Appendf(nil, tmpl, u3Pub, u2Pub), 0660)
363 if err := s.Reload(); err != nil {
364 t.Fatalf("Reload failed: %v", err)
365 }
366 for range 2 {
367 select {
368 case str := <-logger.ch:
369 if strings.Contains(str, "removed") {
370 if !strings.Contains(str, u1Pub) {
371 t.Fatalf("Expected removed trace to include %q, it did not: %s", u1Pub, str)
372 }
373 } else if strings.Contains(str, "added") {
374 if !strings.Contains(str, u3Pub) {
375 t.Fatalf("Expected added trace to include %q, it did not: %s", u3Pub, str)
376 }
377 } else {
378 t.Fatalf("Unexpected log: %q", str)
379 }
380 default:
381 t.Fatal("Expected a log, did not get one")
382 }
383 }
384
385 // Connections should get disconnected.
386 // We need to consume what is sent by the server, but for leaf we may
387 // get some LS+, etc... so just consumer until we get the io.EOF
388 readAll := func(c net.Conn) {
389 for {
390 var buf [1024]byte
391 if _, err := c.Read(buf[:]); err != nil {
392 break
393 }
394 }
395 }
396 readAll(c)
397 expectDisconnect(t, c)
398 readAll(l)
399 expectDisconnect(t, l)
400 c.Close()
401 l.Close()
402
403 // Now check that the connection with CID `cid` was closed because the
404 // proxy is (no longer) trusted.
405 checkClosedState(t, cid1, server.ProxyNotTrusted)
406 checkClosedState(t, cid2, server.ProxyNotTrusted)
407
408 varz, err = s.Varz(nil)
409 if err != nil {
410 t.Fatalf("Error getting varz: %v", err)
411 }
412 vproxies = varz.Proxies
413 if vproxies == nil {
414 t.Fatal("Expected proxies to be not nil")
415 }
416 trusted = vproxies.Trusted
417 if len(trusted) != 2 {
418 t.Fatalf("Expected 2 trusted proxies, got %+v", trusted)
419 }
420 if k := trusted[0].Key; k != u3Pub {
421 t.Fatalf("Expected key to be %q, got %q", u3Pub, k)
422 }
423 if k := trusted[1].Key; k != u2Pub {
424 t.Fatalf("Expected key to be %q, got %q", u2Pub, k)
425 }
426
427 // And we should be able to connect using u3 key pair.
428 expectc, c = connect(t, u3, false, o.Port, true, "user")
429 expectc(pongRe)
430 c.Close()
431 expectl, l = connect(t, u3, false, o.LeafNode.Port, false, "user")
432 expectl(infoRe)
433 l.Close()
434
435 // But now using u1 key pair should fail.
436 expectc, c = connect(t, u1, false, o.Port, true, "user")
437 expectc(errRe)
438 c.Close()
439 expectl, l = connect(t, u1, false, o.LeafNode.Port, false, "user")
440 expectl(errRe)
441 l.Close()
442
443 s.Shutdown()
444
445 // Now check that if no trusted proxy are provided, a proxy connection is
446 // accepted. Use leafnodes since we always send NONCE for this type of connection.
447 conf = createConfFile(t, []byte(`
448 port: -1
449 leafnodes {
450 port: -1
451 }
452 `))
453 s, o = RunServerWithConfig(conf)
454 defer s.Shutdown()
455
456 for _, test := range []struct {
457 name string
458 bsig bool
459 }{
460 {"no trusted proxy and correct signature", false},
461 {"no trusted proxy and invalid signature", true},
462 } {
463 t.Run(test.name, func(t *testing.T) {
464 expect, c := connect(t, u1, test.bsig, o.LeafNode.Port, false, "user")
465 defer c.Close()
466 // Does not matter if bad signature, since there is no trusted keys
467 // in the server, we accept without signature check.
468 expect(infoRe)
469 })
470 }
471
472 s.Shutdown()
473
474 // Finally, check that if there are no configured trusted proxies
475 // and a user requires a proxy connection, then the connection will fail.
476 conf = createConfFile(t, []byte(`
477 port: -1
478 leafnodes {
479 port: -1
480 authorization {
481 users [
482 {user: u1, password: pwd}
483 {user: u2, password: pwd, proxy_required: true}
484 ]
485 }
486 }
487 `))
488 s, o = RunServerWithConfig(conf)
489 defer s.Shutdown()
490
491 for _, test := range []struct {
492 name string
493 user string
494 ok bool
495 }{
496 {"no trusted proxy configured no proxy required", "u1", true},
497 {"no trusted proxy configured and proxy required", "u2", false},
498 } {
499 t.Run(test.name, func(t *testing.T) {
500 // We can use any key pair here, it is not important.
501 expect, c := connect(t, u1, false, o.LeafNode.Port, false, test.user)
502 defer c.Close()
503 if test.ok {
504 expect(infoRe)
505 } else {
506 expect(errRe)
507 // Check that the reason is "proxy required"
508 checkClosedState(t, currentCID, server.ProxyRequired)
509 }
510 })
511 }
512
513 // Same test, but the "proxy_required" is at the authorization{} to-level,
514 // so any user should fail.
515 conf = createConfFile(t, []byte(`
516 port: -1
517 leafnodes {
518 port: -1
519 authorization {
520 users [
521 {user: u1, password: pwd}
522 {user: u2, password: pwd}
523 ]
524 proxy_required: true
525 }
526 }
527 `))
528 s, o = RunServerWithConfig(conf)
529 defer s.Shutdown()
530
531 t.Run("all users required to use trusted proxy", func(t *testing.T) {
532 for _, user := range []string{"u1", "u2"} {
533 // We can use any key pair here, it is not important.
534 expect, c := connect(t, u1, false, o.LeafNode.Port, false, user)
535 defer c.Close()
536 expect(errRe)
537 // Check that the reason is "proxy required"
538 checkClosedState(t, currentCID, server.ProxyRequired)
539 }
540 })
541
542 varz, err = s.Varz(nil)
543 if err != nil {
544 t.Fatalf("Error getting varz: %v", err)
545 }
546 vproxies = varz.Proxies
547 if vproxies != nil {
548 t.Fatalf("Expected proxies to be nil, got %+v", vproxies)
549 }
550 }