Debian Codegraph @

test/tls_test.go

raw
1 // Copyright 2015-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 "bufio"
18 "crypto/ed25519"
19 "crypto/rand"
20 "crypto/tls"
21 "crypto/x509"
22 "crypto/x509/pkix"
23 "encoding/pem"
24 "errors"
25 "fmt"
26 "math/big"
27 "net"
28 "net/url"
29 "os"
30 "path/filepath"
31 "strings"
32 "sync"
33 "testing"
34 "time"
35
36 "github.com/nats-io/nats.go"
37
38 "github.com/nats-io/nats-server/v2/server"
39 )
40
41 var noOpErrHandler = func(_ *nats.Conn, _ *nats.Subscription, _ error) {}
42
43 func TestTLSConnection(t *testing.T) {
44 srv, opts := RunServerWithConfig("./configs/tls.conf")
45 defer srv.Shutdown()
46
47 endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
48 nurl := fmt.Sprintf("tls://%s:%s@%s/", opts.Username, opts.Password, endpoint)
49 nc, err := nats.Connect(nurl)
50 if err == nil {
51 nc.Close()
52 t.Fatalf("Expected error trying to connect to secure server")
53 }
54
55 // Do simple SecureConnect
56 nc, err = nats.Connect(fmt.Sprintf("tls://%s/", endpoint))
57 if err == nil {
58 nc.Close()
59 t.Fatalf("Expected error trying to connect to secure server with no auth")
60 }
61
62 // Now do more advanced checking, verifying servername and using rootCA.
63
64 nc, err = nats.Connect(nurl, nats.RootCAs("./configs/certs/ca.pem"))
65 if err != nil {
66 t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err)
67 }
68 defer nc.Close()
69
70 subj := "foo-tls"
71 sub, _ := nc.SubscribeSync(subj)
72
73 nc.Publish(subj, []byte("We are Secure!"))
74 nc.Flush()
75 nmsgs, _, _ := sub.Pending()
76 if nmsgs != 1 {
77 t.Fatalf("Expected to receive a message over the TLS connection")
78 }
79 }
80
81 // TestTLSInProcessConnection checks that even if TLS is enabled on the server,
82 // that an in-process connection that does *not* use TLS still connects successfully.
83 func TestTLSInProcessConnection(t *testing.T) {
84 srv, opts := RunServerWithConfig("./configs/tls.conf")
85 defer srv.Shutdown()
86
87 nc, err := nats.Connect("", nats.InProcessServer(srv), nats.UserInfo(opts.Username, opts.Password))
88 if err != nil {
89 t.Fatal(err)
90 }
91 defer nc.Close()
92
93 if nc.TLSRequired() {
94 t.Fatalf("Shouldn't have required TLS for in-process connection")
95 }
96
97 if _, err = nc.TLSConnectionState(); err == nil {
98 t.Fatal("Should have got an error retrieving TLS connection state")
99 }
100 }
101
102 func TestTLSClientCertificate(t *testing.T) {
103 srv, opts := RunServerWithConfig("./configs/tlsverify.conf")
104 defer srv.Shutdown()
105
106 nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
107
108 _, err := nats.Connect(nurl)
109 if err == nil {
110 t.Fatalf("Expected error trying to connect to secure server without a certificate")
111 }
112
113 // Load client certificate to successfully connect.
114 certFile := "./configs/certs/client-cert.pem"
115 keyFile := "./configs/certs/client-key.pem"
116 cert, err := tls.LoadX509KeyPair(certFile, keyFile)
117 if err != nil {
118 t.Fatalf("error parsing X509 certificate/key pair: %v", err)
119 }
120
121 // Load in root CA for server verification
122 rootPEM, err := os.ReadFile("./configs/certs/ca.pem")
123 if err != nil || rootPEM == nil {
124 t.Fatalf("failed to read root certificate")
125 }
126 pool := x509.NewCertPool()
127 ok := pool.AppendCertsFromPEM([]byte(rootPEM))
128 if !ok {
129 t.Fatalf("failed to parse root certificate")
130 }
131
132 config := &tls.Config{
133 Certificates: []tls.Certificate{cert},
134 ServerName: opts.Host,
135 RootCAs: pool,
136 MinVersion: tls.VersionTLS12,
137 }
138
139 copts := nats.GetDefaultOptions()
140 copts.Url = nurl
141 copts.Secure = true
142 copts.TLSConfig = config
143
144 nc, err := copts.Connect()
145 if err != nil {
146 t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err)
147 }
148 nc.Flush()
149 defer nc.Close()
150 }
151
152 func TestTLSClientCertificateHasUserID(t *testing.T) {
153 srv, opts := RunServerWithConfig("./configs/tls_cert_id.conf")
154 defer srv.Shutdown()
155 nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
156 nc, err := nats.Connect(nurl,
157 nats.ClientCert("./configs/certs/client-id-auth-cert.pem", "./configs/certs/client-id-auth-key.pem"),
158 nats.RootCAs("./configs/certs/ca.pem"))
159 if err != nil {
160 t.Fatalf("Expected to connect, got %v", err)
161 }
162 defer nc.Close()
163 }
164
165 func TestTLSClientCertificateCheckWithAllowedConnectionTypes(t *testing.T) {
166 conf := createConfFile(t, []byte(
167 `
168 listen: "127.0.0.1:-1"
169 tls {
170 cert_file: "./configs/certs/server-cert.pem"
171 key_file: "./configs/certs/server-key.pem"
172 timeout: 2
173 ca_file: "./configs/certs/ca.pem"
174 verify_and_map: true
175 }
176 authorization {
177 users = [
178 {user: [email protected], permissions: { publish:"foo" }, allowed_connection_types: ["WEBSOCKET"]}
179 ]
180 }
181 `))
182 s, o := RunServerWithConfig(conf)
183 defer s.Shutdown()
184
185 nurl := fmt.Sprintf("tls://%s:%d", o.Host, o.Port)
186 nc, err := nats.Connect(nurl,
187 nats.ClientCert("./configs/certs/client-id-auth-cert.pem", "./configs/certs/client-id-auth-key.pem"),
188 nats.RootCAs("./configs/certs/ca.pem"))
189 if err == nil {
190 if nc != nil {
191 nc.Close()
192 }
193 t.Fatal("Expected connection to fail, it did not")
194 }
195 }
196
197 func TestTLSClientCertificateCNBasedAuth(t *testing.T) {
198 srv, opts := RunServerWithConfig("./configs/tls_cert_cn.conf")
199 defer srv.Shutdown()
200 nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
201 errCh1 := make(chan error)
202 errCh2 := make(chan error)
203
204 // Using the default permissions
205 nc1, err := nats.Connect(nurl,
206 nats.ClientCert("./configs/certs/tlsauth/client.pem", "./configs/certs/tlsauth/client-key.pem"),
207 nats.RootCAs("./configs/certs/tlsauth/ca.pem"),
208 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
209 errCh1 <- err
210 }),
211 )
212 if err != nil {
213 t.Fatalf("Expected to connect, got %v", err)
214 }
215 defer nc1.Close()
216
217 // Admin permissions can publish to '>'
218 nc2, err := nats.Connect(nurl,
219 nats.ClientCert("./configs/certs/tlsauth/client2.pem", "./configs/certs/tlsauth/client2-key.pem"),
220 nats.RootCAs("./configs/certs/tlsauth/ca.pem"),
221 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
222 errCh2 <- err
223 }),
224 )
225 if err != nil {
226 t.Fatalf("Expected to connect, got %v", err)
227 }
228 defer nc2.Close()
229
230 err = nc1.Publish("foo.bar", []byte("hi"))
231 if err != nil {
232 t.Fatal(err)
233 }
234 _, err = nc1.SubscribeSync("foo.>")
235 if err != nil {
236 t.Fatal(err)
237 }
238 nc1.Flush()
239
240 sub, err := nc2.SubscribeSync(">")
241 if err != nil {
242 t.Fatal(err)
243 }
244 nc2.Flush()
245 err = nc2.Publish("hello", []byte("hi"))
246 if err != nil {
247 t.Fatal(err)
248 }
249 nc2.Flush()
250
251 _, err = sub.NextMsg(1 * time.Second)
252 if err != nil {
253 t.Fatalf("Error during wait for next message: %s", err)
254 }
255
256 // Wait for a couple of errors
257 var count int
258 Loop:
259 for {
260 select {
261 case err := <-errCh1:
262 if err != nil {
263 count++
264 }
265 if count == 2 {
266 break Loop
267 }
268 case err := <-errCh2:
269 if err != nil {
270 t.Fatalf("Received unexpected auth error from client: %s", err)
271 }
272 case <-time.After(2 * time.Second):
273 t.Fatalf("Timed out expecting auth errors")
274 }
275 }
276 }
277
278 func TestTLSClientCertificateSANsBasedAuth(t *testing.T) {
279 // In this test we have 3 clients, one with permissions defined
280 // for SAN 'app.nats.dev', other for SAN 'app.nats.prod' and another
281 // one without the default permissions for the CN.
282 srv, opts := RunServerWithConfig("./configs/tls_cert_san_auth.conf")
283 defer srv.Shutdown()
284 nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
285 defaultErrCh := make(chan error)
286 devErrCh := make(chan error)
287 prodErrCh := make(chan error)
288
289 // default: Using the default permissions (no SANs)
290 //
291 // Subject: CN = www.nats.io
292 //
293 defaultc, err := nats.Connect(nurl,
294 nats.ClientCert("./configs/certs/sans/client.pem", "./configs/certs/sans/client-key.pem"),
295 nats.RootCAs("./configs/certs/sans/ca.pem"),
296 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
297 defaultErrCh <- err
298 }),
299 )
300 if err != nil {
301 t.Fatalf("Expected to connect, got %v", err)
302 }
303 defer defaultc.Close()
304
305 // dev: Using SAN 'app.nats.dev' with permissions to its own sandbox.
306 //
307 // Subject: CN = www.nats.io
308 //
309 // X509v3 Subject Alternative Name:
310 // DNS:app.nats.dev, DNS:*.app.nats.dev
311 //
312 devc, err := nats.Connect(nurl,
313 nats.ClientCert("./configs/certs/sans/dev.pem", "./configs/certs/sans/dev-key.pem"),
314 nats.RootCAs("./configs/certs/sans/ca.pem"),
315 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
316 devErrCh <- err
317 }),
318 )
319 if err != nil {
320 t.Fatalf("Expected to connect, got %v", err)
321 }
322 defer devc.Close()
323
324 // prod: Using SAN 'app.nats.prod' with all permissions.
325 //
326 // Subject: CN = www.nats.io
327 //
328 // X509v3 Subject Alternative Name:
329 // DNS:app.nats.prod, DNS:*.app.nats.prod
330 //
331 prodc, err := nats.Connect(nurl,
332 nats.ClientCert("./configs/certs/sans/prod.pem", "./configs/certs/sans/prod-key.pem"),
333 nats.RootCAs("./configs/certs/sans/ca.pem"),
334 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
335 prodErrCh <- err
336 }),
337 )
338 if err != nil {
339 t.Fatalf("Expected to connect, got %v", err)
340 }
341 defer prodc.Close()
342
343 // No permissions to publish or subscribe on foo.>
344 err = devc.Publish("foo.bar", []byte("hi"))
345 if err != nil {
346 t.Fatal(err)
347 }
348 _, err = devc.SubscribeSync("foo.>")
349 if err != nil {
350 t.Fatal(err)
351 }
352 devc.Flush()
353
354 prodSub, err := prodc.SubscribeSync(">")
355 if err != nil {
356 t.Fatal(err)
357 }
358 prodc.Flush()
359 err = prodc.Publish("hello", []byte("hi"))
360 if err != nil {
361 t.Fatal(err)
362 }
363 prodc.Flush()
364
365 // prod: can receive message on wildcard subscription.
366 _, err = prodSub.NextMsg(1 * time.Second)
367 if err != nil {
368 t.Fatalf("Error during wait for next message: %s", err)
369 }
370
371 // dev: enough permissions to publish to sandbox subject.
372 devSub, err := devc.SubscribeSync("sandbox.>")
373 if err != nil {
374 t.Fatal(err)
375 }
376 devc.Flush()
377 err = devc.Publish("sandbox.foo.bar", []byte("hi!"))
378 if err != nil {
379 t.Fatal(err)
380 }
381 // both dev and prod clients can receive message
382 _, err = devSub.NextMsg(1 * time.Second)
383 if err != nil {
384 t.Fatalf("Error during wait for next message: %s", err)
385 }
386 _, err = prodSub.NextMsg(1 * time.Second)
387 if err != nil {
388 t.Fatalf("Error during wait for next message: %s", err)
389 }
390
391 // default: no enough permissions
392 _, err = defaultc.SubscribeSync("sandbox.>")
393 if err != nil {
394 t.Fatal(err)
395 }
396 defaultSub, err := defaultc.SubscribeSync("public.>")
397 if err != nil {
398 t.Fatal(err)
399 }
400 defaultc.Flush()
401 err = devc.Publish("public.foo.bar", []byte("hi!"))
402 if err != nil {
403 t.Fatal(err)
404 }
405 _, err = defaultSub.NextMsg(1 * time.Second)
406 if err != nil {
407 t.Fatalf("Error during wait for next message: %s", err)
408 }
409
410 // Wait for a couple of errors
411 var count int
412 Loop:
413 for {
414 select {
415 case err := <-defaultErrCh:
416 if err != nil {
417 count++
418 }
419 if count == 3 {
420 break Loop
421 }
422 case err := <-devErrCh:
423 if err != nil {
424 count++
425 }
426 if count == 3 {
427 break Loop
428 }
429 case err := <-prodErrCh:
430 if err != nil {
431 t.Fatalf("Received unexpected auth error from client: %s", err)
432 }
433 case <-time.After(2 * time.Second):
434 t.Fatalf("Timed out expecting auth errors")
435 }
436 }
437 }
438
439 func TestTLSClientCertificateNoSubjectWithSANAuth(t *testing.T) {
440 // A certificate with an empty Subject DN but a DNS SAN should be accepted
441 // and mapped to the SAN value, exercising the hasSANs branch in
442 // checkClientTLSCertSubject.
443 dir := t.TempDir()
444 ca := issueCert(t, dir, "ca", nil, pkix.Name{CommonName: "test-ca"}, nil, nil)
445 server := issueCert(t, dir, "server", ca, pkix.Name{CommonName: "localhost"}, []string{"localhost"}, []net.IP{net.ParseIP("127.0.0.1")})
446 client := issueCert(t, dir, "client-nosubj", ca, pkix.Name{}, []string{"localhost"}, nil)
447
448 conf := createConfFile(t, []byte(fmt.Sprintf(`
449 listen: "127.0.0.1:-1"
450 tls {
451 cert_file: %q
452 key_file: %q
453 ca_file: %q
454 verify_and_map: true
455 }
456 authorization {
457 users = [
458 { user: "localhost" }
459 ]
460 }
461 `, server.certPath, server.keyPath, ca.certPath)))
462 srv, opts := RunServerWithConfig(conf)
463 defer srv.Shutdown()
464 nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
465
466 t.Run("no-subject cert with SAN connects", func(t *testing.T) {
467 nc, err := nats.Connect(nurl,
468 nats.ClientCert(client.certPath, client.keyPath),
469 nats.RootCAs(ca.certPath),
470 )
471 if err != nil {
472 t.Fatalf("Expected to connect with no-subject cert, got %v", err)
473 }
474 defer nc.Close()
475 })
476
477 t.Run("no client cert is rejected", func(t *testing.T) {
478 nc, err := nats.Connect(nurl, nats.RootCAs(ca.certPath))
479 if err == nil {
480 nc.Close()
481 t.Fatal("Expected connection without client cert to fail, but it succeeded")
482 }
483 })
484 }
485
486 type issuedCert struct {
487 cert *x509.Certificate
488 key ed25519.PrivateKey
489 certPath string
490 keyPath string
491 }
492
493 // issueCert generates an Ed25519 keypair and an X.509 certificate written under
494 // dir as <name>-cert.pem and <name>-key.pem. parent==nil produces a self-signed
495 // CA; otherwise the cert is signed by parent and gets server+client EKU.
496 func issueCert(t *testing.T, dir, name string, parent *issuedCert, subject pkix.Name, dnsNames []string, ips []net.IP) *issuedCert {
497 t.Helper()
498 _, key, err := ed25519.GenerateKey(rand.Reader)
499 if err != nil {
500 t.Fatal(err)
501 }
502 tmpl := &x509.Certificate{
503 SerialNumber: big.NewInt(time.Now().UnixNano()),
504 Subject: subject,
505 NotBefore: time.Now().Add(-time.Hour),
506 NotAfter: time.Now().Add(24 * time.Hour),
507 KeyUsage: x509.KeyUsageDigitalSignature,
508 DNSNames: dnsNames,
509 IPAddresses: ips,
510 }
511 parentCert, parentKey := tmpl, key
512 if parent == nil {
513 tmpl.IsCA = true
514 tmpl.BasicConstraintsValid = true
515 tmpl.KeyUsage |= x509.KeyUsageCertSign
516 } else {
517 tmpl.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth}
518 parentCert, parentKey = parent.cert, parent.key
519 }
520 der, err := x509.CreateCertificate(rand.Reader, tmpl, parentCert, key.Public(), parentKey)
521 if err != nil {
522 t.Fatal(err)
523 }
524 cert, err := x509.ParseCertificate(der)
525 if err != nil {
526 t.Fatal(err)
527 }
528 keyDER, err := x509.MarshalPKCS8PrivateKey(key)
529 if err != nil {
530 t.Fatal(err)
531 }
532 out := &issuedCert{
533 cert: cert,
534 key: key,
535 certPath: filepath.Join(dir, name+"-cert.pem"),
536 keyPath: filepath.Join(dir, name+"-key.pem"),
537 }
538 if err := os.WriteFile(out.certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0644); err != nil {
539 t.Fatal(err)
540 }
541 if err := os.WriteFile(out.keyPath, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}), 0600); err != nil {
542 t.Fatal(err)
543 }
544 return out
545 }
546
547 func TestTLSClientCertificateTLSAuthMultipleOptions(t *testing.T) {
548 srv, opts := RunServerWithConfig("./configs/tls_cert_san_emails.conf")
549 defer srv.Shutdown()
550 nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
551 defaultErrCh := make(chan error)
552 devErrCh := make(chan error)
553 prodErrCh := make(chan error)
554
555 // default: Using the default permissions, there are SANs
556 // present in the cert but they are not users in the NATS config
557 // so the subject is used instead.
558 //
559 // Subject: CN = www.nats.io
560 //
561 // X509v3 Subject Alternative Name:
562 // DNS:app.nats.dev, DNS:*.app.nats.dev
563 //
564 defaultc, err := nats.Connect(nurl,
565 nats.ClientCert("./configs/certs/sans/dev.pem", "./configs/certs/sans/dev-key.pem"),
566 nats.RootCAs("./configs/certs/sans/ca.pem"),
567 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
568 defaultErrCh <- err
569 }),
570 )
571 if err != nil {
572 t.Fatalf("Expected to connect, got %v", err)
573 }
574 defer defaultc.Close()
575
576 // dev: Using SAN to validate user, even if emails are present in the config.
577 //
578 // Subject: CN = www.nats.io
579 //
580 // X509v3 Subject Alternative Name:
581 // DNS:app.nats.dev, email:[email protected], email:[email protected]
582 //
583 devc, err := nats.Connect(nurl,
584 nats.ClientCert("./configs/certs/sans/dev-email.pem", "./configs/certs/sans/dev-email-key.pem"),
585 nats.RootCAs("./configs/certs/sans/ca.pem"),
586 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
587 devErrCh <- err
588 }),
589 )
590 if err != nil {
591 t.Fatalf("Expected to connect, got %v", err)
592 }
593 defer devc.Close()
594
595 // prod: Using SAN '*.app.nats.prod' with all permissions, which is not the first SAN.
596 //
597 // Subject: CN = www.nats.io
598 //
599 // X509v3 Subject Alternative Name:
600 // DNS:app.nats.prod, DNS:*.app.nats.prod
601 //
602 prodc, err := nats.Connect(nurl,
603 nats.ClientCert("./configs/certs/sans/prod.pem", "./configs/certs/sans/prod-key.pem"),
604 nats.RootCAs("./configs/certs/sans/ca.pem"),
605 nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
606 prodErrCh <- err
607 }),
608 )
609 if err != nil {
610 t.Fatalf("Expected to connect, got %v", err)
611 }
612 defer prodc.Close()
613
614 // No permissions to publish or subscribe on foo.>
615 err = devc.Publish("foo.bar", []byte("hi"))
616 if err != nil {
617 t.Fatal(err)
618 }
619 _, err = devc.SubscribeSync("foo.>")
620 if err != nil {
621 t.Fatal(err)
622 }
623 devc.Flush()
624
625 prodSub, err := prodc.SubscribeSync(">")
626 if err != nil {
627 t.Fatal(err)
628 }
629 prodc.Flush()
630 err = prodc.Publish("hello", []byte("hi"))
631 if err != nil {
632 t.Fatal(err)
633 }
634 prodc.Flush()
635
636 // prod: can receive message on wildcard subscription.
637 _, err = prodSub.NextMsg(1 * time.Second)
638 if err != nil {
639 t.Fatalf("Error during wait for next message: %s", err)
640 }
641
642 // dev: enough permissions to publish to sandbox subject.
643 devSub, err := devc.SubscribeSync("sandbox.>")
644 if err != nil {
645 t.Fatal(err)
646 }
647 devc.Flush()
648 err = devc.Publish("sandbox.foo.bar", []byte("hi!"))
649 if err != nil {
650 t.Fatal(err)
651 }
652 // both dev and prod clients can receive message
653 _, err = devSub.NextMsg(1 * time.Second)
654 if err != nil {
655 t.Fatalf("Error during wait for next message: %s", err)
656 }
657 _, err = prodSub.NextMsg(1 * time.Second)
658 if err != nil {
659 t.Fatalf("Error during wait for next message: %s", err)
660 }
661
662 // default: no enough permissions
663 _, err = defaultc.SubscribeSync("sandbox.>")
664 if err != nil {
665 t.Fatal(err)
666 }
667 defaultSub, err := defaultc.SubscribeSync("public.>")
668 if err != nil {
669 t.Fatal(err)
670 }
671 defaultc.Flush()
672 err = devc.Publish("public.foo.bar", []byte("hi!"))
673 if err != nil {
674 t.Fatal(err)
675 }
676 _, err = defaultSub.NextMsg(1 * time.Second)
677 if err != nil {
678 t.Fatalf("Error during wait for next message: %s", err)
679 }
680
681 // Wait for a couple of errors
682 var count int
683 Loop:
684 for {
685 select {
686 case err := <-defaultErrCh:
687 if err != nil {
688 count++
689 }
690 if count == 3 {
691 break Loop
692 }
693 case err := <-devErrCh:
694 if err != nil {
695 count++
696 }
697 if count == 3 {
698 break Loop
699 }
700 case err := <-prodErrCh:
701 if err != nil {
702 t.Fatalf("Received unexpected auth error from client: %s", err)
703 }
704 case <-time.After(2 * time.Second):
705 t.Fatalf("Timed out expecting auth errors")
706 }
707 }
708 }
709
710 func TestTLSRoutesCertificateCNBasedAuth(t *testing.T) {
711 // Base config for the servers
712 optsA := LoadConfig("./configs/tls_cert_cn_routes.conf")
713 optsB := LoadConfig("./configs/tls_cert_cn_routes.conf")
714 optsC := LoadConfig("./configs/tls_cert_cn_routes_invalid_auth.conf")
715
716 // TLS map should have been enabled
717 if !optsA.Cluster.TLSMap || !optsB.Cluster.TLSMap || !optsC.Cluster.TLSMap {
718 t.Error("Expected Cluster TLS verify and map feature to be activated")
719 }
720
721 routeURLs := "nats://localhost:9935, nats://localhost:9936, nats://localhost:9937"
722
723 optsA.Host = "127.0.0.1"
724 optsA.Port = 9335
725 optsA.Cluster.Name = "xyz"
726 optsA.Cluster.Host = optsA.Host
727 optsA.Cluster.Port = 9935
728 optsA.Routes = server.RoutesFromStr(routeURLs)
729 optsA.NoSystemAccount = true
730 srvA := RunServer(optsA)
731 defer srvA.Shutdown()
732
733 optsB.Host = "127.0.0.1"
734 optsB.Port = 9336
735 optsB.Cluster.Name = "xyz"
736 optsB.Cluster.Host = optsB.Host
737 optsB.Cluster.Port = 9936
738 optsB.Routes = server.RoutesFromStr(routeURLs)
739 optsB.NoSystemAccount = true
740 srvB := RunServer(optsB)
741 defer srvB.Shutdown()
742
743 optsC.Host = "127.0.0.1"
744 optsC.Port = 9337
745 optsC.Cluster.Name = "xyz"
746 optsC.Cluster.Host = optsC.Host
747 optsC.Cluster.Port = 9937
748 optsC.Routes = server.RoutesFromStr(routeURLs)
749 optsC.NoSystemAccount = true
750 srvC := RunServer(optsC)
751 defer srvC.Shutdown()
752
753 // srvC is not connected to srvA and srvB due to wrong cert
754 checkClusterFormed(t, srvA, srvB)
755
756 nc1, err := nats.Connect(fmt.Sprintf("%s:%d", optsA.Host, optsA.Port), nats.Name("A"))
757 if err != nil {
758 t.Fatalf("Expected to connect, got %v", err)
759 }
760 defer nc1.Close()
761
762 nc2, err := nats.Connect(fmt.Sprintf("%s:%d", optsB.Host, optsB.Port), nats.Name("B"))
763 if err != nil {
764 t.Fatalf("Expected to connect, got %v", err)
765 }
766 defer nc2.Close()
767
768 // This client is partitioned from rest of cluster due to using wrong cert.
769 nc3, err := nats.Connect(fmt.Sprintf("%s:%d", optsC.Host, optsC.Port), nats.Name("C"))
770 if err != nil {
771 t.Fatalf("Expected to connect, got %v", err)
772 }
773 defer nc3.Close()
774
775 // Allowed via permissions to broadcast to other members of cluster.
776 publicSub, err := nc1.SubscribeSync("public.>")
777 if err != nil {
778 t.Fatal(err)
779 }
780
781 // Not part of cluster permissions so message is not forwarded.
782 privateSub, err := nc1.SubscribeSync("private.>")
783 if err != nil {
784 t.Fatal(err)
785 }
786 // This ensures that srvA has received the sub, not srvB
787 nc1.Flush()
788
789 checkFor(t, time.Second, 15*time.Millisecond, func() error {
790 if n := srvB.NumSubscriptions(); n != 1 {
791 return fmt.Errorf("Expected 1 sub, got %v", n)
792 }
793 return nil
794 })
795
796 // Not forwarded by cluster so won't be received.
797 err = nc2.Publish("private.foo", []byte("private message on server B"))
798 if err != nil {
799 t.Fatal(err)
800 }
801 err = nc2.Publish("public.foo", []byte("public message from server B to server A"))
802 if err != nil {
803 t.Fatal(err)
804 }
805 nc2.Flush()
806 err = nc3.Publish("public.foo", []byte("dropped message since unauthorized server"))
807 if err != nil {
808 t.Fatal(err)
809 }
810 nc3.Flush()
811
812 // Message will be received since allowed via permissions
813 _, err = publicSub.NextMsg(1 * time.Second)
814 if err != nil {
815 t.Fatalf("Error during wait for next message: %s", err)
816 }
817 msg, err := privateSub.NextMsg(500 * time.Millisecond)
818 if err == nil {
819 t.Errorf("Received unexpected message from private sub: %+v", msg)
820 }
821 msg, err = publicSub.NextMsg(500 * time.Millisecond)
822 if err == nil {
823 t.Errorf("Received unexpected message from private sub: %+v", msg)
824 }
825 }
826
827 func TestTLSGatewaysCertificateCNBasedAuth(t *testing.T) {
828 // Base config for the servers
829 optsA := LoadConfig("./configs/tls_cert_cn_gateways.conf")
830 optsB := LoadConfig("./configs/tls_cert_cn_gateways.conf")
831 optsC := LoadConfig("./configs/tls_cert_cn_gateways_invalid_auth.conf")
832
833 // TLS map should have been enabled
834 if !optsA.Gateway.TLSMap || !optsB.Gateway.TLSMap || !optsC.Gateway.TLSMap {
835 t.Error("Expected Cluster TLS verify and map feature to be activated")
836 }
837
838 gwA, err := url.Parse("nats://localhost:9995")
839 if err != nil {
840 t.Fatal(err)
841 }
842 gwB, err := url.Parse("nats://localhost:9996")
843 if err != nil {
844 t.Fatal(err)
845 }
846 gwC, err := url.Parse("nats://localhost:9997")
847 if err != nil {
848 t.Fatal(err)
849 }
850
851 optsA.Host = "127.0.0.1"
852 optsA.Port = -1
853 optsA.Gateway.Name = "A"
854 optsA.Gateway.Port = 9995
855
856 optsB.Host = "127.0.0.1"
857 optsB.Port = -1
858 optsB.Gateway.Name = "B"
859 optsB.Gateway.Port = 9996
860
861 optsC.Host = "127.0.0.1"
862 optsC.Port = -1
863 optsC.Gateway.Name = "C"
864 optsC.Gateway.Port = 9997
865
866 gateways := make([]*server.RemoteGatewayOpts, 3)
867 gateways[0] = &server.RemoteGatewayOpts{
868 Name: optsA.Gateway.Name,
869 URLs: []*url.URL{gwA},
870 }
871 gateways[1] = &server.RemoteGatewayOpts{
872 Name: optsB.Gateway.Name,
873 URLs: []*url.URL{gwB},
874 }
875 gateways[2] = &server.RemoteGatewayOpts{
876 Name: optsC.Gateway.Name,
877 URLs: []*url.URL{gwC},
878 }
879 optsA.Gateway.Gateways = gateways
880 optsB.Gateway.Gateways = gateways
881 optsC.Gateway.Gateways = gateways
882
883 server.SetGatewaysSolicitDelay(100 * time.Millisecond)
884 defer server.ResetGatewaysSolicitDelay()
885
886 srvA := RunServer(optsA)
887 defer srvA.Shutdown()
888
889 srvB := RunServer(optsB)
890 defer srvB.Shutdown()
891
892 srvC := RunServer(optsC)
893 defer srvC.Shutdown()
894
895 // Because we need to use "localhost" in the gw URLs (to match
896 // hostname in the user/CN), the server may try to connect to
897 // a [::1], etc.. that may or may not work, so give a lot of
898 // time for that to complete ok.
899 waitForOutboundGateways(t, srvA, 1, 5*time.Second)
900 waitForOutboundGateways(t, srvB, 1, 5*time.Second)
901
902 nc1, err := nats.Connect(srvA.Addr().String(), nats.Name("A"))
903 if err != nil {
904 t.Fatalf("Expected to connect, got %v", err)
905 }
906 defer nc1.Close()
907
908 nc2, err := nats.Connect(srvB.Addr().String(), nats.Name("B"))
909 if err != nil {
910 t.Fatalf("Expected to connect, got %v", err)
911 }
912 defer nc2.Close()
913
914 nc3, err := nats.Connect(srvC.Addr().String(), nats.Name("C"))
915 if err != nil {
916 t.Fatalf("Expected to connect, got %v", err)
917 }
918 defer nc3.Close()
919
920 received := make(chan *nats.Msg)
921 _, err = nc1.Subscribe("foo", func(msg *nats.Msg) {
922 select {
923 case received <- msg:
924 default:
925 }
926 })
927 if err != nil {
928 t.Error(err)
929 }
930 _, err = nc3.Subscribe("help", func(msg *nats.Msg) {
931 nc3.Publish(msg.Reply, []byte("response"))
932 })
933 if err != nil {
934 t.Error(err)
935 }
936
937 go func() {
938 for range time.NewTicker(10 * time.Millisecond).C {
939 if nc2.IsClosed() {
940 return
941 }
942 nc2.Publish("foo", []byte("bar"))
943 }
944 }()
945
946 select {
947 case <-received:
948 case <-time.After(2 * time.Second):
949 t.Error("Timed out waiting for gateway messages")
950 }
951
952 msg, err := nc2.Request("help", []byte("should fail"), 100*time.Millisecond)
953 if err == nil {
954 t.Errorf("Expected to not receive any messages, got: %+v", msg)
955 }
956 }
957
958 func TestTLSVerifyClientCertificate(t *testing.T) {
959 srv, opts := RunServerWithConfig("./configs/tlsverify_noca.conf")
960 defer srv.Shutdown()
961
962 nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
963
964 // The client is configured properly, but the server has no CA
965 // to verify the client certificate. Connection should fail.
966 nc, err := nats.Connect(nurl,
967 nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem"),
968 nats.RootCAs("./configs/certs/ca.pem"))
969 if err == nil {
970 nc.Close()
971 t.Fatal("Expected failure to connect, did not")
972 }
973 }
974
975 func TestTLSConnectionTimeout(t *testing.T) {
976 opts := LoadConfig("./configs/tls.conf")
977 opts.TLSTimeout = 0.25
978
979 srv := RunServer(opts)
980 defer srv.Shutdown()
981
982 // Dial with normal TCP
983 endpoint := net.JoinHostPort(opts.Host, fmt.Sprintf("%d", opts.Port))
984 conn, err := net.Dial("tcp", endpoint)
985 if err != nil {
986 t.Fatalf("Could not connect to %q", endpoint)
987 }
988 defer conn.Close()
989
990 // Read deadlines
991 conn.SetReadDeadline(time.Now().Add(2 * time.Second))
992
993 // Read the INFO string.
994 br := bufio.NewReader(conn)
995 info, err := br.ReadString('\n')
996 if err != nil {
997 t.Fatalf("Failed to read INFO - %v", err)
998 }
999 if !strings.HasPrefix(info, "INFO ") {
1000 t.Fatalf("INFO response incorrect: %s\n", info)
1001 }
1002 wait := time.Duration(opts.TLSTimeout * float64(time.Second))
1003 time.Sleep(wait)
1004 // Read deadlines
1005 conn.SetReadDeadline(time.Now().Add(2 * time.Second))
1006 tlsErr, err := br.ReadString('\n')
1007 if err == nil && !strings.Contains(tlsErr, "-ERR 'Secure Connection - TLS Required") {
1008 t.Fatalf("TLS Timeout response incorrect: %q\n", tlsErr)
1009 }
1010 }
1011
1012 // Ensure there is no race between authorization timeout and TLS handshake.
1013 func TestTLSAuthorizationShortTimeout(t *testing.T) {
1014 opts := LoadConfig("./configs/tls.conf")
1015 opts.AuthTimeout = 0.001
1016
1017 srv := RunServer(opts)
1018 defer srv.Shutdown()
1019
1020 endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
1021 nurl := fmt.Sprintf("tls://%s:%s@%s/", opts.Username, opts.Password, endpoint)
1022
1023 // Expect an error here (no CA) but not a TLS oversized record error which
1024 // indicates the authorization timeout fired too soon.
1025 _, err := nats.Connect(nurl)
1026 if err == nil {
1027 t.Fatal("Expected error trying to connect to secure server")
1028 }
1029 if strings.Contains(err.Error(), "oversized record") {
1030 t.Fatal("Corrupted TLS handshake:", err)
1031 }
1032 }
1033
1034 func TestClientTLSAndNonTLSConnections(t *testing.T) {
1035 s, opts := RunServerWithConfig("./configs/tls_mixed.conf")
1036 defer s.Shutdown()
1037
1038 surl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
1039 nc, err := nats.Connect(surl, nats.RootCAs("./configs/certs/ca.pem"))
1040 if err != nil {
1041 t.Fatalf("Failed to connect with TLS: %v", err)
1042 }
1043 defer nc.Close()
1044
1045 // Now also make sure we can connect through plain text.
1046 nurl := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
1047 nc2, err := nats.Connect(nurl)
1048 if err != nil {
1049 t.Fatalf("Failed to connect without TLS: %v", err)
1050 }
1051 defer nc2.Close()
1052
1053 // Make sure they can go back and forth.
1054 sub, err := nc.SubscribeSync("foo")
1055 if err != nil {
1056 t.Fatalf("Error subscribing: %v", err)
1057 }
1058 sub2, err := nc2.SubscribeSync("bar")
1059 if err != nil {
1060 t.Fatalf("Error subscribing: %v", err)
1061 }
1062 nc.Flush()
1063 nc2.Flush()
1064
1065 nmsgs := 100
1066 for i := 0; i < nmsgs; i++ {
1067 nc2.Publish("foo", []byte("HELLO FROM PLAINTEXT"))
1068 nc.Publish("bar", []byte("HELLO FROM TLS"))
1069 }
1070 // Now wait for the messages.
1071 checkFor(t, time.Second, 10*time.Millisecond, func() error {
1072 if msgs, _, err := sub.Pending(); err != nil || msgs != nmsgs {
1073 return fmt.Errorf("Did not receive the correct number of messages: %d", msgs)
1074 }
1075 if msgs, _, err := sub2.Pending(); err != nil || msgs != nmsgs {
1076 return fmt.Errorf("Did not receive the correct number of messages: %d", msgs)
1077 }
1078 return nil
1079 })
1080
1081 }
1082
1083 func stressConnect(t *testing.T, wg *sync.WaitGroup, errCh chan error, url string, index int) {
1084 defer wg.Done()
1085
1086 subName := fmt.Sprintf("foo.%d", index)
1087
1088 for i := 0; i < 33; i++ {
1089 nc, err := nats.Connect(url, nats.RootCAs("./configs/certs/ca.pem"))
1090 if err != nil {
1091 errCh <- fmt.Errorf("Unable to create TLS connection: %v\n", err)
1092 return
1093 }
1094 defer nc.Close()
1095
1096 sub, err := nc.SubscribeSync(subName)
1097 if err != nil {
1098 errCh <- fmt.Errorf("Unable to subscribe on '%s': %v\n", subName, err)
1099 return
1100 }
1101
1102 if err := nc.Publish(subName, []byte("secure data")); err != nil {
1103 errCh <- fmt.Errorf("Unable to send on '%s': %v\n", subName, err)
1104 }
1105
1106 if _, err := sub.NextMsg(2 * time.Second); err != nil {
1107 errCh <- fmt.Errorf("Unable to get next message: %v\n", err)
1108 }
1109
1110 nc.Close()
1111 }
1112
1113 errCh <- nil
1114 }
1115
1116 func TestTLSStressConnect(t *testing.T) {
1117 opts, err := server.ProcessConfigFile("./configs/tls.conf")
1118 if err != nil {
1119 panic(fmt.Sprintf("Error processing configuration file: %v", err))
1120 }
1121 opts.NoSigs, opts.NoLog = true, true
1122
1123 // For this test, remove the authorization
1124 opts.Username = ""
1125 opts.Password = ""
1126
1127 // Increase ssl timeout
1128 opts.TLSTimeout = 2.0
1129
1130 srv := RunServer(opts)
1131 defer srv.Shutdown()
1132
1133 nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
1134
1135 threadCount := 3
1136
1137 errCh := make(chan error, threadCount)
1138
1139 var wg sync.WaitGroup
1140 wg.Add(threadCount)
1141
1142 for i := 0; i < threadCount; i++ {
1143 go stressConnect(t, &wg, errCh, nurl, i)
1144 }
1145
1146 wg.Wait()
1147
1148 var lastError error
1149 for i := 0; i < threadCount; i++ {
1150 err := <-errCh
1151 if err != nil {
1152 lastError = err
1153 }
1154 }
1155
1156 if lastError != nil {
1157 t.Fatalf("%v\n", lastError)
1158 }
1159 }
1160
1161 func TestTLSBadAuthError(t *testing.T) {
1162 srv, opts := RunServerWithConfig("./configs/tls.conf")
1163 defer srv.Shutdown()
1164
1165 endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
1166 nurl := fmt.Sprintf("tls://%s:%s@%s/", opts.Username, "NOT_THE_PASSWORD", endpoint)
1167
1168 _, err := nats.Connect(nurl, nats.RootCAs("./configs/certs/ca.pem"))
1169 if err == nil {
1170 t.Fatalf("Expected error trying to connect to secure server")
1171 }
1172 if strings.ToLower(err.Error()) != nats.ErrAuthorization.Error() {
1173 t.Fatalf("Expected and auth violation, got %v\n", err)
1174 }
1175 }
1176
1177 func TestTLSConnectionCurvePref(t *testing.T) {
1178 srv, opts := RunServerWithConfig("./configs/tls_curve_pref.conf")
1179 defer srv.Shutdown()
1180
1181 if len(opts.TLSConfig.CurvePreferences) != 1 {
1182 t.Fatal("Invalid curve preference loaded.")
1183 }
1184
1185 if opts.TLSConfig.CurvePreferences[0] != tls.CurveP256 {
1186 t.Fatalf("Invalid curve preference loaded [%v].", opts.TLSConfig.CurvePreferences[0])
1187 }
1188
1189 endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
1190 nurl := fmt.Sprintf("tls://%s:%s@%s/", opts.Username, opts.Password, endpoint)
1191 nc, err := nats.Connect(nurl)
1192 if err == nil {
1193 nc.Close()
1194 t.Fatalf("Expected error trying to connect to secure server")
1195 }
1196
1197 // Do simple SecureConnect
1198 nc, err = nats.Connect(fmt.Sprintf("tls://%s/", endpoint))
1199 if err == nil {
1200 nc.Close()
1201 t.Fatalf("Expected error trying to connect to secure server with no auth")
1202 }
1203
1204 // Now do more advanced checking, verifying servername and using rootCA.
1205
1206 nc, err = nats.Connect(nurl, nats.RootCAs("./configs/certs/ca.pem"))
1207 if err != nil {
1208 t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err)
1209 }
1210 defer nc.Close()
1211
1212 subj := "foo-tls"
1213 sub, _ := nc.SubscribeSync(subj)
1214
1215 nc.Publish(subj, []byte("We are Secure!"))
1216 nc.Flush()
1217 nmsgs, _, _ := sub.Pending()
1218 if nmsgs != 1 {
1219 t.Fatalf("Expected to receive a message over the TLS connection")
1220 }
1221 }
1222
1223 type captureSlowConsumerLogger struct {
1224 dummyLogger
1225 ch chan string
1226 gotIt bool
1227 }
1228
1229 func (l *captureSlowConsumerLogger) Noticef(format string, v ...any) {
1230 msg := fmt.Sprintf(format, v...)
1231 if strings.Contains(msg, "Slow Consumer") {
1232 l.Lock()
1233 if !l.gotIt {
1234 l.gotIt = true
1235 l.ch <- msg
1236 }
1237 l.Unlock()
1238 }
1239 }
1240
1241 func TestTLSTimeoutNotReportSlowConsumer(t *testing.T) {
1242 oa, err := server.ProcessConfigFile("./configs/srv_a_tls.conf")
1243 if err != nil {
1244 t.Fatalf("Unable to load config file: %v", err)
1245 }
1246
1247 // Override TLSTimeout to very small value so that handshake fails
1248 oa.Cluster.TLSTimeout = 0.0000001
1249 sa := RunServer(oa)
1250 defer sa.Shutdown()
1251
1252 ch := make(chan string, 1)
1253 cscl := &captureSlowConsumerLogger{ch: ch}
1254 sa.SetLogger(cscl, false, false)
1255
1256 ob, err := server.ProcessConfigFile("./configs/srv_b_tls.conf")
1257 if err != nil {
1258 t.Fatalf("Unable to load config file: %v", err)
1259 }
1260
1261 sb := RunServer(ob)
1262 defer sb.Shutdown()
1263
1264 // Watch the logger for a bit and make sure we don't get any
1265 // Slow Consumer error.
1266 select {
1267 case e := <-ch:
1268 t.Fatalf("Unexpected slow consumer error: %s", e)
1269 case <-time.After(500 * time.Millisecond):
1270 // ok
1271 }
1272 }
1273
1274 func TestTLSHandshakeFailureMemUsage(t *testing.T) {
1275 for i, test := range []struct {
1276 name string
1277 config string
1278 }{
1279 {
1280 "connect to TLS client port",
1281 `
1282 port: -1
1283 %s
1284 `,
1285 },
1286 {
1287 "connect to TLS route port",
1288 `
1289 port: -1
1290 cluster {
1291 port: -1
1292 %s
1293 }
1294 `,
1295 },
1296 {
1297 "connect to TLS gateway port",
1298 `
1299 port: -1
1300 gateway {
1301 name: "A"
1302 port: -1
1303 %s
1304 }
1305 `,
1306 },
1307 } {
1308 t.Run(test.name, func(t *testing.T) {
1309 content := fmt.Sprintf(test.config, `
1310 tls {
1311 cert_file: "configs/certs/server-cert.pem"
1312 key_file: "configs/certs/server-key.pem"
1313 ca_file: "configs/certs/ca.pem"
1314 timeout: 5
1315 }
1316 `)
1317 conf := createConfFile(t, []byte(content))
1318 s, opts := RunServerWithConfig(conf)
1319 defer s.Shutdown()
1320
1321 var port int
1322 switch i {
1323 case 0:
1324 port = opts.Port
1325 case 1:
1326 port = s.ClusterAddr().Port
1327 case 2:
1328 port = s.GatewayAddr().Port
1329 }
1330
1331 varz, _ := s.Varz(nil)
1332 base := varz.Mem
1333 buf := make([]byte, 1024*1024)
1334 for i := 0; i < 100; i++ {
1335 conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))
1336 if err != nil {
1337 t.Fatalf("Error on dial: %v", err)
1338 }
1339 conn.SetWriteDeadline(time.Now().Add(10 * time.Millisecond))
1340 conn.Write(buf)
1341 conn.Close()
1342 }
1343
1344 varz, _ = s.Varz(nil)
1345 newval := (varz.Mem - base) / (1024 * 1024)
1346 // May need to adjust that, but right now, with 100 clients
1347 // we are at about 20MB for client port, 11MB for route
1348 // and 6MB for gateways, so pick 50MB as the threshold
1349 if newval >= 50 {
1350 t.Fatalf("Consumed too much memory: %v MB", newval)
1351 }
1352 })
1353 }
1354 }
1355
1356 func TestTLSClientAuthWithRDNSequence(t *testing.T) {
1357 for _, test := range []struct {
1358 name string
1359 config string
1360 certs nats.Option
1361 err error
1362 rerr error
1363 }{
1364 // To generate certs for these tests:
1365 // USE `regenerate_rdns_svid.sh` TO REGENERATE
1366 //
1367 // ```
1368 // openssl req -newkey rsa:2048 -nodes -keyout client-$CLIENT_ID.key -subj "/C=US/ST=CA/L=Los Angeles/OU=NATS/O=NATS/CN=*.example.com/DC=example/DC=com" -addext extendedKeyUsage=clientAuth -out client-$CLIENT_ID.csr
1369 // openssl x509 -req -extfile <(printf "subjectAltName=DNS:localhost,DNS:example.com,DNS:www.example.com") -days 1825 -in client-$CLIENT_ID.csr -CA ca.pem -CAkey ca.key -CAcreateserial -out client-$CLIENT_ID.pem
1370 // ```
1371 //
1372 // To confirm subject from cert:
1373 //
1374 // ```
1375 // openssl x509 -in client-$CLIENT_ID.pem -text | grep Subject:
1376 // ```
1377 //
1378 {
1379 "connect with tls using full RDN sequence",
1380 `
1381 port: -1
1382 %s
1383
1384 authorization {
1385 users = [
1386 { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=foo1,DC=foo2" }
1387 ]
1388 }
1389 `,
1390 // C = US, ST = CA, L = Los Angeles, O = NATS, OU = NATS, CN = localhost, DC = foo1, DC = foo2
1391 nats.ClientCert("./configs/certs/rdns/client-a.pem", "./configs/certs/rdns/client-a.key"),
1392 nil,
1393 nil,
1394 },
1395 {
1396 "connect with tls using full RDN sequence in original order",
1397 `
1398 port: -1
1399 %s
1400
1401 authorization {
1402 users = [
1403 { user = "DC=foo2,DC=foo1,CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US" }
1404 ]
1405 }
1406 `,
1407 // C = US, ST = CA, L = Los Angeles, O = NATS, OU = NATS, CN = localhost, DC = foo1, DC = foo2
1408 nats.ClientCert("./configs/certs/rdns/client-a.pem", "./configs/certs/rdns/client-a.key"),
1409 nil,
1410 nil,
1411 },
1412 {
1413 "connect with tls using partial RDN sequence has different permissions",
1414 `
1415 port: -1
1416 %s
1417
1418 authorization {
1419 users = [
1420 { user = "DC=foo2,DC=foo1,CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US" },
1421 { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=foo1,DC=foo2" },
1422 { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US",
1423 permissions = { subscribe = { deny = ">" }} }
1424 ]
1425 }
1426 `,
1427 // C = US, ST = California, L = Los Angeles, O = NATS, OU = NATS, CN = localhost
1428 nats.ClientCert("./configs/certs/rdns/client-b.pem", "./configs/certs/rdns/client-b.key"),
1429 nil,
1430 errors.New("nats: timeout"),
1431 },
1432 {
1433 "connect with tls and RDN sequence partially matches",
1434 `
1435 port: -1
1436 %s
1437
1438 authorization {
1439 users = [
1440 { user = "DC=foo2,DC=foo1,CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US" }
1441 { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=foo1,DC=foo2" }
1442 { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US"},
1443 ]
1444 }
1445 `,
1446 // Cert is:
1447 //
1448 // C = US, ST = CA, L = Los Angeles, O = NATS, OU = NATS, CN = localhost, DC = foo3, DC = foo4
1449 //
1450 // but it will actually match the user without DCs so will not get an error:
1451 //
1452 // C = US, ST = CA, L = Los Angeles, O = NATS, OU = NATS, CN = localhost
1453 //
1454 nats.ClientCert("./configs/certs/rdns/client-c.pem", "./configs/certs/rdns/client-c.key"),
1455 nil,
1456 nil,
1457 },
1458 {
1459 "connect with tls and RDN sequence does not match",
1460 `
1461 port: -1
1462 %s
1463
1464 authorization {
1465 users = [
1466 { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=foo1,DC=foo2" },
1467 { user = "DC=foo2,DC=foo1,CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US" }
1468 ]
1469 }
1470 `,
1471 // C = US, ST = California, L = Los Angeles, O = NATS, OU = NATS, CN = localhost, DC = foo3, DC = foo4
1472 //
1473 nats.ClientCert("./configs/certs/rdns/client-c.pem", "./configs/certs/rdns/client-c.key"),
1474 errors.New("nats: Authorization Violation"),
1475 nil,
1476 },
1477 {
1478 "connect with tls and RDN sequence with space after comma not should matter",
1479 `
1480 port: -1
1481 %s
1482
1483 authorization {
1484 users = [
1485 { user = "DC=foo2, DC=foo1, CN=localhost, OU=NATS, O=NATS, L=Los Angeles, ST=CA, C=US" }
1486 ]
1487 }
1488 `,
1489 // C=US/ST=California/L=Los Angeles/O=NATS/OU=NATS/CN=localhost/DC=foo1/DC=foo2
1490 //
1491 nats.ClientCert("./configs/certs/rdns/client-a.pem", "./configs/certs/rdns/client-a.key"),
1492 nil,
1493 nil,
1494 },
1495 {
1496 "connect with tls and full RDN sequence respects order",
1497 `
1498 port: -1
1499 %s
1500
1501 authorization {
1502 users = [
1503 { user = "DC=com, DC=example, CN=*.example.com, O=NATS, OU=NATS, L=Los Angeles, ST=CA, C=US" }
1504 ]
1505 }
1506 `,
1507 //
1508 // C = US, ST = CA, L = Los Angeles, OU = NATS, O = NATS, CN = *.example.com, DC = example, DC = com
1509 //
1510 nats.ClientCert("./configs/certs/rdns/client-d.pem", "./configs/certs/rdns/client-d.key"),
1511 nil,
1512 nil,
1513 },
1514 {
1515 "connect with tls and full RDN sequence with added domainComponents and spaces also matches",
1516 `
1517 port: -1
1518 %s
1519
1520 authorization {
1521 users = [
1522 { user = "CN=*.example.com,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=example,DC=com" }
1523 ]
1524 }
1525 `,
1526 //
1527 // C = US, ST = CA, L = Los Angeles, OU = NATS, O = NATS, CN = *.example.com, DC = example, DC = com
1528 //
1529 nats.ClientCert("./configs/certs/rdns/client-d.pem", "./configs/certs/rdns/client-d.key"),
1530 nil,
1531 nil,
1532 },
1533 {
1534 "connect with tls and full RDN sequence with correct order takes precedence over others matches",
1535 `
1536 port: -1
1537 %s
1538
1539 authorization {
1540 users = [
1541 { user = "CN=*.example.com,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=example,DC=com",
1542 permissions = { subscribe = { deny = ">" }} }
1543
1544 # This should take precedence since it is in the RFC2253 order.
1545 { user = "DC=com,DC=example,CN=*.example.com,O=NATS,OU=NATS,L=Los Angeles,ST=CA,C=US" }
1546
1547 { user = "CN=*.example.com,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US",
1548 permissions = { subscribe = { deny = ">" }} }
1549 ]
1550 }
1551 `,
1552 //
1553 // C = US, ST = CA, L = Los Angeles, OU = NATS, O = NATS, CN = *.example.com, DC = example, DC = com
1554 //
1555 nats.ClientCert("./configs/certs/rdns/client-d.pem", "./configs/certs/rdns/client-d.key"),
1556 nil,
1557 nil,
1558 },
1559 {
1560 "connect with tls and RDN includes multiple CN elements",
1561 `
1562 port: -1
1563 %s
1564
1565 authorization {
1566 users = [
1567 { user = "DC=com,DC=acme,OU=Organic Units,OU=Users,CN=jdoe,CN=123456,CN=John Doe" }
1568 ]
1569 }
1570 `,
1571 //
1572 // OpenSSL: -subj "/CN=John Doe/CN=123456/CN=jdoe/OU=Users/OU=Organic Units/DC=acme/DC=com"
1573 // Go: CN=jdoe,OU=Users+OU=Organic Units
1574 // RFC2253: DC=com,DC=acme,OU=Organic Units,OU=Users,CN=jdoe,CN=123456,CN=John Doe
1575 //
1576 nats.ClientCert("./configs/certs/rdns/client-e.pem", "./configs/certs/rdns/client-e.key"),
1577 nil,
1578 nil,
1579 },
1580 {
1581 "connect with tls and DN includes a multi value RDN",
1582 `
1583 port: -1
1584 %s
1585
1586 authorization {
1587 users = [
1588 { user = "CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org" }
1589 ]
1590 }
1591 `,
1592 //
1593 // OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
1594 // Go: CN=John Doe,O=users
1595 // RFC2253: CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
1596 //
1597 nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
1598 nil,
1599 nil,
1600 },
1601 {
1602 "connect with tls and DN includes a multi value RDN but there is no match",
1603 `
1604 port: -1
1605 %s
1606
1607 authorization {
1608 users = [
1609 { user = "CN=John Doe,DC=DEV,DC=OpenSSL,DC=org" }
1610 ]
1611 }
1612 `,
1613 //
1614 // OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
1615 // Go: CN=John Doe,O=users
1616 // RFC2253: CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
1617 //
1618 nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
1619 errors.New("nats: Authorization Violation"),
1620 nil,
1621 },
1622 {
1623 "connect with tls and DN includes a multi value RDN that are reordered",
1624 `
1625 port: -1
1626 %s
1627
1628 authorization {
1629 users = [
1630 { user = "CN=John Doe,O=users+DC=DEV,DC=OpenSSL,DC=org" }
1631 ]
1632 }
1633 `,
1634 //
1635 // OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
1636 // Go: CN=John Doe,O=users
1637 // RFC2253: CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
1638 //
1639 nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
1640 nil,
1641 nil,
1642 },
1643 } {
1644 t.Run(test.name, func(t *testing.T) {
1645 content := fmt.Sprintf(test.config, `
1646 tls {
1647 cert_file: "configs/certs/rdns/server.pem"
1648 key_file: "configs/certs/rdns/server.key"
1649 ca_file: "configs/certs/rdns/ca.pem"
1650 timeout: 5
1651 verify_and_map: true
1652 }
1653 `)
1654 conf := createConfFile(t, []byte(content))
1655 s, opts := RunServerWithConfig(conf)
1656 defer s.Shutdown()
1657
1658 nc, err := nats.Connect(fmt.Sprintf("tls://localhost:%d", opts.Port),
1659 test.certs,
1660 nats.RootCAs("./configs/certs/rdns/ca.pem"),
1661 nats.ErrorHandler(noOpErrHandler),
1662 )
1663 if test.err == nil && err != nil {
1664 t.Errorf("Expected to connect, got %v", err)
1665 } else if test.err != nil && err == nil {
1666 t.Errorf("Expected error on connect")
1667 } else if test.err != nil && err != nil {
1668 // Error on connect was expected
1669 if test.err.Error() != err.Error() {
1670 t.Errorf("Expected error %s, got: %s", test.err, err)
1671 }
1672 return
1673 }
1674 defer nc.Close()
1675
1676 nc.Subscribe("ping", func(m *nats.Msg) {
1677 m.Respond([]byte("pong"))
1678 })
1679 nc.Flush()
1680
1681 _, err = nc.Request("ping", []byte("ping"), 250*time.Millisecond)
1682 if test.rerr != nil && err == nil {
1683 t.Errorf("Expected error getting response")
1684 } else if test.rerr == nil && err != nil {
1685 t.Errorf("Expected response")
1686 }
1687 })
1688 }
1689 }
1690
1691 func TestTLSClientAuthWithRDNSequenceReordered(t *testing.T) {
1692 for _, test := range []struct {
1693 name string
1694 config string
1695 certs nats.Option
1696 err error
1697 rerr error
1698 }{
1699 {
1700 "connect with tls and DN includes a multi value RDN that are reordered",
1701 `
1702 port: -1
1703 %s
1704
1705 authorization {
1706 users = [
1707 { user = "DC=org,DC=OpenSSL,O=users+DC=DEV,CN=John Doe" }
1708 ]
1709 }
1710 `,
1711 //
1712 // OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
1713 // Go: CN=John Doe,O=users
1714 // RFC2253: CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
1715 //
1716 nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
1717 nil,
1718 nil,
1719 },
1720 {
1721 "connect with tls and DN includes a multi value RDN that are reordered but not equal RDNs",
1722 `
1723 port: -1
1724 %s
1725
1726 authorization {
1727 users = [
1728 { user = "DC=org,DC=OpenSSL,O=users,CN=John Doe" }
1729 ]
1730 }
1731 `,
1732 //
1733 // OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
1734 // Go: CN=John Doe,O=users
1735 // RFC2253: CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
1736 //
1737 nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
1738 errors.New("nats: Authorization Violation"),
1739 nil,
1740 },
1741 {
1742 "connect with tls and DN includes a multi value RDN that are reordered but not equal RDNs",
1743 `
1744 port: -1
1745 %s
1746
1747 authorization {
1748 users = [
1749 { user = "DC=OpenSSL, DC=org, O=users, CN=John Doe" }
1750 ]
1751 }
1752 `,
1753 //
1754 // OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
1755 // Go: CN=John Doe,O=users
1756 // RFC2253: CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
1757 //
1758 nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
1759 errors.New("nats: Authorization Violation"),
1760 nil,
1761 },
1762 } {
1763 t.Run(test.name, func(t *testing.T) {
1764 content := fmt.Sprintf(test.config, `
1765 tls {
1766 cert_file: "configs/certs/rdns/server.pem"
1767 key_file: "configs/certs/rdns/server.key"
1768 ca_file: "configs/certs/rdns/ca.pem"
1769 timeout: 5
1770 verify_and_map: true
1771 }
1772 `)
1773 conf := createConfFile(t, []byte(content))
1774 s, opts := RunServerWithConfig(conf)
1775 defer s.Shutdown()
1776
1777 nc, err := nats.Connect(fmt.Sprintf("tls://localhost:%d", opts.Port),
1778 test.certs,
1779 nats.RootCAs("./configs/certs/rdns/ca.pem"),
1780 )
1781 if test.err == nil && err != nil {
1782 t.Errorf("Expected to connect, got %v", err)
1783 } else if test.err != nil && err == nil {
1784 t.Errorf("Expected error on connect")
1785 } else if test.err != nil && err != nil {
1786 // Error on connect was expected
1787 if test.err.Error() != err.Error() {
1788 t.Errorf("Expected error %s, got: %s", test.err, err)
1789 }
1790 return
1791 }
1792 defer nc.Close()
1793
1794 nc.Subscribe("ping", func(m *nats.Msg) {
1795 m.Respond([]byte("pong"))
1796 })
1797 nc.Flush()
1798
1799 _, err = nc.Request("ping", []byte("ping"), 250*time.Millisecond)
1800 if test.rerr != nil && err == nil {
1801 t.Errorf("Expected error getting response")
1802 } else if test.rerr == nil && err != nil {
1803 t.Errorf("Expected response")
1804 }
1805 })
1806 }
1807 }
1808
1809 func TestTLSClientSVIDAuth(t *testing.T) {
1810 for _, test := range []struct {
1811 name string
1812 config string
1813 certs nats.Option
1814 err error
1815 rerr error
1816 }{
1817 {
1818 "connect with tls using certificate with URIs",
1819 `
1820 port: -1
1821 %s
1822
1823 authorization {
1824 users = [
1825 {
1826 user = "spiffe://localhost/my-nats-service/user-a"
1827 }
1828 ]
1829 }
1830 `,
1831 nats.ClientCert("./configs/certs/svid/client-a.pem", "./configs/certs/svid/client-a.key"),
1832 nil,
1833 nil,
1834 },
1835 {
1836 "connect with tls using certificate with limited different permissions",
1837 `
1838 port: -1
1839 %s
1840
1841 authorization {
1842 users = [
1843 {
1844 user = "spiffe://localhost/my-nats-service/user-a"
1845 },
1846 {
1847 user = "spiffe://localhost/my-nats-service/user-b"
1848 permissions = { subscribe = { deny = ">" }}
1849 }
1850 ]
1851 }
1852 `,
1853 nats.ClientCert("./configs/certs/svid/client-b.pem", "./configs/certs/svid/client-b.key"),
1854 nil,
1855 errors.New("nats: timeout"),
1856 },
1857 {
1858 "connect with tls without URIs in permissions will still match SAN",
1859 `
1860 port: -1
1861 %s
1862
1863 authorization {
1864 users = [
1865 {
1866 user = "O=SPIRE,C=US"
1867 }
1868 ]
1869 }
1870 `,
1871 nats.ClientCert("./configs/certs/svid/client-b.pem", "./configs/certs/svid/client-b.key"),
1872 nil,
1873 nil,
1874 },
1875 {
1876 "connect with tls but no permissions",
1877 `
1878 port: -1
1879 %s
1880
1881 authorization {
1882 users = [
1883 {
1884 user = "spiffe://localhost/my-nats-service/user-c"
1885 }
1886 ]
1887 }
1888 `,
1889 nats.ClientCert("./configs/certs/svid/client-a.pem", "./configs/certs/svid/client-a.key"),
1890 errors.New("nats: Authorization Violation"),
1891 nil,
1892 },
1893 } {
1894 t.Run(test.name, func(t *testing.T) {
1895 content := fmt.Sprintf(test.config, `
1896 tls {
1897 cert_file: "configs/certs/svid/server.pem"
1898 key_file: "configs/certs/svid/server.key"
1899 ca_file: "configs/certs/svid/ca.pem"
1900 timeout: 5
1901 insecure: true
1902 verify_and_map: true
1903 }
1904 `)
1905 conf := createConfFile(t, []byte(content))
1906 s, opts := RunServerWithConfig(conf)
1907 defer s.Shutdown()
1908
1909 nc, err := nats.Connect(fmt.Sprintf("tls://localhost:%d", opts.Port),
1910 test.certs,
1911 nats.RootCAs("./configs/certs/svid/ca.pem"),
1912 nats.ErrorHandler(noOpErrHandler),
1913 )
1914 if test.err == nil && err != nil {
1915 t.Errorf("Expected to connect, got %v", err)
1916 } else if test.err != nil && err == nil {
1917 t.Errorf("Expected error on connect")
1918 } else if test.err != nil && err != nil {
1919 // Error on connect was expected
1920 if test.err.Error() != err.Error() {
1921 t.Errorf("Expected error %s, got: %s", test.err, err)
1922 }
1923 return
1924 }
1925 defer nc.Close()
1926
1927 nc.Subscribe("ping", func(m *nats.Msg) {
1928 m.Respond([]byte("pong"))
1929 })
1930 nc.Flush()
1931
1932 _, err = nc.Request("ping", []byte("ping"), 250*time.Millisecond)
1933 if test.rerr != nil && err == nil {
1934 t.Errorf("Expected error getting response")
1935 } else if test.rerr == nil && err != nil {
1936 t.Errorf("Expected response")
1937 }
1938 })
1939 }
1940 }
1941
1942 func TestTLSPinnedCertsClient(t *testing.T) {
1943 tmpl := `
1944 host: localhost
1945 port: -1
1946 tls {
1947 ca_file: "configs/certs/ca.pem"
1948 cert_file: "configs/certs/server-cert.pem"
1949 key_file: "configs/certs/server-key.pem"
1950 # Require a client certificate and map user id from certificate
1951 verify: true
1952 pinned_certs: ["%s"]
1953 }`
1954
1955 confFileName := createConfFile(t, []byte(fmt.Sprintf(tmpl, "aaaaaaaa09fde09451411ba3b42c0f74727d61a974c69fd3cf5257f39c75f0e9")))
1956 srv, o := RunServerWithConfig(confFileName)
1957 defer srv.Shutdown()
1958
1959 if len(o.TLSPinnedCerts) != 1 {
1960 t.Fatal("expected one pinned cert")
1961 }
1962
1963 opts := []nats.Option{
1964 nats.RootCAs("configs/certs/ca.pem"),
1965 nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem"),
1966 }
1967
1968 nc, err := nats.Connect(srv.ClientURL(), opts...)
1969 if err == nil {
1970 nc.Close()
1971 t.Fatalf("Expected error trying to connect without a certificate in pinned_certs")
1972 }
1973
1974 os.WriteFile(confFileName, []byte(fmt.Sprintf(tmpl, "bf6f821f09fde09451411ba3b42c0f74727d61a974c69fd3cf5257f39c75f0e9")), 0660)
1975 if err := srv.Reload(); err != nil {
1976 t.Fatalf("on Reload got %v", err)
1977 }
1978 // reload pinned to the certs used
1979 nc, err = nats.Connect(srv.ClientURL(), opts...)
1980 if err != nil {
1981 t.Fatalf("Expected no error, got: %v", err)
1982 }
1983 nc.Close()
1984 }
1985
1986 type captureWarnLogger struct {
1987 dummyLogger
1988 receive chan string
1989 }
1990
1991 func newCaptureWarnLogger() *captureWarnLogger {
1992 return &captureWarnLogger{
1993 receive: make(chan string, 100),
1994 }
1995 }
1996
1997 func (l *captureWarnLogger) Warnf(format string, v ...any) {
1998 l.receive <- fmt.Sprintf(format, v...)
1999 }
2000
2001 func (l *captureWarnLogger) waitFor(expect string, timeout time.Duration) bool {
2002 for {
2003 select {
2004 case msg := <-l.receive:
2005 if strings.Contains(msg, expect) {
2006 return true
2007 }
2008 case <-time.After(timeout):
2009 return false
2010 }
2011 }
2012 }
2013
2014 func TestTLSConnectionRate(t *testing.T) {
2015 config := `
2016 listen: "127.0.0.1:-1"
2017 tls {
2018 cert_file: "./configs/certs/server-cert.pem"
2019 key_file: "./configs/certs/server-key.pem"
2020 connection_rate_limit: 3
2021 }
2022 `
2023
2024 confFileName := createConfFile(t, []byte(config))
2025
2026 srv, _ := RunServerWithConfig(confFileName)
2027 logger := newCaptureWarnLogger()
2028 srv.SetLogger(logger, false, false)
2029 defer srv.Shutdown()
2030
2031 var err error
2032 count := 0
2033 for count < 10 {
2034 var nc *nats.Conn
2035 nc, err = nats.Connect(srv.ClientURL(), nats.RootCAs("./configs/certs/ca.pem"))
2036
2037 if err != nil {
2038 break
2039 }
2040 nc.Close()
2041 count++
2042 }
2043
2044 if count != 3 {
2045 t.Fatalf("Expected 3 connections per second, got %d (%v)", count, err)
2046 }
2047
2048 if !logger.waitFor("connections due to TLS rate limiting", time.Second) {
2049 t.Fatalf("did not log 'TLS rate limiting' warning")
2050 }
2051 }
2052
2053 func TestTLSPinnedCertsRoute(t *testing.T) {
2054 tmplSeed := `
2055 host: localhost
2056 port: -1
2057 cluster {
2058 port: -1
2059 pool_size: -1
2060 tls {
2061 ca_file: "configs/certs/ca.pem"
2062 cert_file: "configs/certs/server-cert.pem"
2063 key_file: "configs/certs/server-key.pem"
2064 }
2065 }`
2066 // this server connects to seed, but is set up to not trust seeds cert
2067 tmplSrv := `
2068 host: localhost
2069 port: -1
2070 cluster {
2071 port: -1
2072 routes = [nats-route://localhost:%d]
2073 tls {
2074 ca_file: "configs/certs/ca.pem"
2075 cert_file: "configs/certs/server-cert.pem"
2076 key_file: "configs/certs/server-key.pem"
2077 # Require a client certificate and map user id from certificate
2078 verify: true
2079 # expected to fail the seed server
2080 pinned_certs: ["%s"]
2081 }
2082 }`
2083
2084 confSeed := createConfFile(t, []byte(tmplSeed))
2085 srvSeed, o := RunServerWithConfig(confSeed)
2086 defer srvSeed.Shutdown()
2087
2088 confSrv := createConfFile(t, []byte(fmt.Sprintf(tmplSrv, o.Cluster.Port, "89386860ea1222698ea676fc97310bdf2bff6f7e2b0420fac3b3f8f5a08fede5")))
2089 srv, _ := RunServerWithConfig(confSrv)
2090 defer srv.Shutdown()
2091
2092 checkClusterFormed(t, srvSeed, srv)
2093
2094 // this change will result in the server being and remaining disconnected
2095 os.WriteFile(confSrv, []byte(fmt.Sprintf(tmplSrv, o.Cluster.Port, "aaaaaaaa09fde09451411ba3b42c0f74727d61a974c69fd3cf5257f39c75f0e9")), 0660)
2096 if err := srv.Reload(); err != nil {
2097 t.Fatalf("on Reload got %v", err)
2098 }
2099
2100 checkNumRoutes(t, srvSeed, 0)
2101 checkNumRoutes(t, srv, 0)
2102 }
2103
2104 func TestAllowNonTLSReload(t *testing.T) {
2105 tmpl := `
2106 listen: "127.0.0.1:-1"
2107 ping_interval: "%s"
2108 tls {
2109 ca_file: "configs/certs/ca.pem"
2110 cert_file: "configs/certs/server-cert.pem"
2111 key_file: "configs/certs/server-key.pem"
2112 }
2113 allow_non_tls: true
2114 `
2115 conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, "10s")))
2116 s, o := RunServerWithConfig(conf)
2117 defer s.Shutdown()
2118
2119 check := func() {
2120 t.Helper()
2121 nc := createClientConn(t, "127.0.0.1", o.Port)
2122 defer nc.Close()
2123 info := checkInfoMsg(t, nc)
2124 if !info.TLSAvailable {
2125 t.Fatal("TLSAvailable should be true, was false")
2126 }
2127 if info.TLSRequired {
2128 t.Fatal("TLSRequired should be false, was true")
2129 }
2130 }
2131 check()
2132
2133 os.WriteFile(conf, []byte(fmt.Sprintf(tmpl, "20s")), 0660)
2134 if err := s.Reload(); err != nil {
2135 t.Fatalf("Error on reload: %v", err)
2136 }
2137 check()
2138 }