File: tls_test.go

package info (click to toggle)
nats-server 2.12.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 13,452 kB
  • sloc: sh: 720; makefile: 3
file content (2024 lines) | stat: -rw-r--r-- 54,175 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
// Copyright 2015-2025 The NATS Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package test

import (
	"bufio"
	"crypto/tls"
	"crypto/x509"
	"errors"
	"fmt"
	"net"
	"net/url"
	"os"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/nats-io/nats.go"

	"github.com/nats-io/nats-server/v2/server"
)

var noOpErrHandler = func(_ *nats.Conn, _ *nats.Subscription, _ error) {}

func TestTLSConnection(t *testing.T) {
	srv, opts := RunServerWithConfig("./configs/tls.conf")
	defer srv.Shutdown()

	endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
	nurl := fmt.Sprintf("tls://%s:%s@%s/", opts.Username, opts.Password, endpoint)
	nc, err := nats.Connect(nurl)
	if err == nil {
		nc.Close()
		t.Fatalf("Expected error trying to connect to secure server")
	}

	// Do simple SecureConnect
	nc, err = nats.Connect(fmt.Sprintf("tls://%s/", endpoint))
	if err == nil {
		nc.Close()
		t.Fatalf("Expected error trying to connect to secure server with no auth")
	}

	// Now do more advanced checking, verifying servername and using rootCA.

	nc, err = nats.Connect(nurl, nats.RootCAs("./configs/certs/ca.pem"))
	if err != nil {
		t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err)
	}
	defer nc.Close()

	subj := "foo-tls"
	sub, _ := nc.SubscribeSync(subj)

	nc.Publish(subj, []byte("We are Secure!"))
	nc.Flush()
	nmsgs, _, _ := sub.Pending()
	if nmsgs != 1 {
		t.Fatalf("Expected to receive a message over the TLS connection")
	}
}

// TestTLSInProcessConnection checks that even if TLS is enabled on the server,
// that an in-process connection that does *not* use TLS still connects successfully.
func TestTLSInProcessConnection(t *testing.T) {
	srv, opts := RunServerWithConfig("./configs/tls.conf")
	defer srv.Shutdown()

	nc, err := nats.Connect("", nats.InProcessServer(srv), nats.UserInfo(opts.Username, opts.Password))
	if err != nil {
		t.Fatal(err)
	}
	defer nc.Close()

	if nc.TLSRequired() {
		t.Fatalf("Shouldn't have required TLS for in-process connection")
	}

	if _, err = nc.TLSConnectionState(); err == nil {
		t.Fatal("Should have got an error retrieving TLS connection state")
	}
}

func TestTLSClientCertificate(t *testing.T) {
	srv, opts := RunServerWithConfig("./configs/tlsverify.conf")
	defer srv.Shutdown()

	nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)

	_, err := nats.Connect(nurl)
	if err == nil {
		t.Fatalf("Expected error trying to connect to secure server without a certificate")
	}

	// Load client certificate to successfully connect.
	certFile := "./configs/certs/client-cert.pem"
	keyFile := "./configs/certs/client-key.pem"
	cert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		t.Fatalf("error parsing X509 certificate/key pair: %v", err)
	}

	// Load in root CA for server verification
	rootPEM, err := os.ReadFile("./configs/certs/ca.pem")
	if err != nil || rootPEM == nil {
		t.Fatalf("failed to read root certificate")
	}
	pool := x509.NewCertPool()
	ok := pool.AppendCertsFromPEM([]byte(rootPEM))
	if !ok {
		t.Fatalf("failed to parse root certificate")
	}

	config := &tls.Config{
		Certificates: []tls.Certificate{cert},
		ServerName:   opts.Host,
		RootCAs:      pool,
		MinVersion:   tls.VersionTLS12,
	}

	copts := nats.GetDefaultOptions()
	copts.Url = nurl
	copts.Secure = true
	copts.TLSConfig = config

	nc, err := copts.Connect()
	if err != nil {
		t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err)
	}
	nc.Flush()
	defer nc.Close()
}

func TestTLSClientCertificateHasUserID(t *testing.T) {
	srv, opts := RunServerWithConfig("./configs/tls_cert_id.conf")
	defer srv.Shutdown()
	nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
	nc, err := nats.Connect(nurl,
		nats.ClientCert("./configs/certs/client-id-auth-cert.pem", "./configs/certs/client-id-auth-key.pem"),
		nats.RootCAs("./configs/certs/ca.pem"))
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer nc.Close()
}

func TestTLSClientCertificateCheckWithAllowedConnectionTypes(t *testing.T) {
	conf := createConfFile(t, []byte(
		`
		listen: "127.0.0.1:-1"
		tls {
			cert_file: "./configs/certs/server-cert.pem"
			key_file:  "./configs/certs/server-key.pem"
			timeout: 2
			ca_file:   "./configs/certs/ca.pem"
			verify_and_map: true
		}
		authorization {
			users = [
				{user: derek@nats.io, permissions: { publish:"foo" }, allowed_connection_types: ["WEBSOCKET"]}
			]
		}
	`))
	s, o := RunServerWithConfig(conf)
	defer s.Shutdown()

	nurl := fmt.Sprintf("tls://%s:%d", o.Host, o.Port)
	nc, err := nats.Connect(nurl,
		nats.ClientCert("./configs/certs/client-id-auth-cert.pem", "./configs/certs/client-id-auth-key.pem"),
		nats.RootCAs("./configs/certs/ca.pem"))
	if err == nil {
		if nc != nil {
			nc.Close()
		}
		t.Fatal("Expected connection to fail, it did not")
	}
}

func TestTLSClientCertificateCNBasedAuth(t *testing.T) {
	srv, opts := RunServerWithConfig("./configs/tls_cert_cn.conf")
	defer srv.Shutdown()
	nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
	errCh1 := make(chan error)
	errCh2 := make(chan error)

	// Using the default permissions
	nc1, err := nats.Connect(nurl,
		nats.ClientCert("./configs/certs/tlsauth/client.pem", "./configs/certs/tlsauth/client-key.pem"),
		nats.RootCAs("./configs/certs/tlsauth/ca.pem"),
		nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
			errCh1 <- err
		}),
	)
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer nc1.Close()

	// Admin permissions can publish to '>'
	nc2, err := nats.Connect(nurl,
		nats.ClientCert("./configs/certs/tlsauth/client2.pem", "./configs/certs/tlsauth/client2-key.pem"),
		nats.RootCAs("./configs/certs/tlsauth/ca.pem"),
		nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
			errCh2 <- err
		}),
	)
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer nc2.Close()

	err = nc1.Publish("foo.bar", []byte("hi"))
	if err != nil {
		t.Fatal(err)
	}
	_, err = nc1.SubscribeSync("foo.>")
	if err != nil {
		t.Fatal(err)
	}
	nc1.Flush()

	sub, err := nc2.SubscribeSync(">")
	if err != nil {
		t.Fatal(err)
	}
	nc2.Flush()
	err = nc2.Publish("hello", []byte("hi"))
	if err != nil {
		t.Fatal(err)
	}
	nc2.Flush()

	_, err = sub.NextMsg(1 * time.Second)
	if err != nil {
		t.Fatalf("Error during wait for next message: %s", err)
	}

	// Wait for a couple of errors
	var count int
Loop:
	for {
		select {
		case err := <-errCh1:
			if err != nil {
				count++
			}
			if count == 2 {
				break Loop
			}
		case err := <-errCh2:
			if err != nil {
				t.Fatalf("Received unexpected auth error from client: %s", err)
			}
		case <-time.After(2 * time.Second):
			t.Fatalf("Timed out expecting auth errors")
		}
	}
}

func TestTLSClientCertificateSANsBasedAuth(t *testing.T) {
	// In this test we have 3 clients, one with permissions defined
	// for SAN 'app.nats.dev', other for SAN 'app.nats.prod' and another
	// one without the default permissions for the CN.
	srv, opts := RunServerWithConfig("./configs/tls_cert_san_auth.conf")
	defer srv.Shutdown()
	nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
	defaultErrCh := make(chan error)
	devErrCh := make(chan error)
	prodErrCh := make(chan error)

	// default: Using the default permissions (no SANs)
	//
	//    Subject: CN = www.nats.io
	//
	defaultc, err := nats.Connect(nurl,
		nats.ClientCert("./configs/certs/sans/client.pem", "./configs/certs/sans/client-key.pem"),
		nats.RootCAs("./configs/certs/sans/ca.pem"),
		nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
			defaultErrCh <- err
		}),
	)
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer defaultc.Close()

	// dev: Using SAN 'app.nats.dev' with permissions to its own sandbox.
	//
	//    Subject: CN = www.nats.io
	//
	//    X509v3 Subject Alternative Name:
	//        DNS:app.nats.dev, DNS:*.app.nats.dev
	//
	devc, err := nats.Connect(nurl,
		nats.ClientCert("./configs/certs/sans/dev.pem", "./configs/certs/sans/dev-key.pem"),
		nats.RootCAs("./configs/certs/sans/ca.pem"),
		nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
			devErrCh <- err
		}),
	)
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer devc.Close()

	// prod: Using SAN 'app.nats.prod' with all permissions.
	//
	//    Subject: CN = www.nats.io
	//
	//    X509v3 Subject Alternative Name:
	//        DNS:app.nats.prod, DNS:*.app.nats.prod
	//
	prodc, err := nats.Connect(nurl,
		nats.ClientCert("./configs/certs/sans/prod.pem", "./configs/certs/sans/prod-key.pem"),
		nats.RootCAs("./configs/certs/sans/ca.pem"),
		nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
			prodErrCh <- err
		}),
	)
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer prodc.Close()

	// No permissions to publish or subscribe on foo.>
	err = devc.Publish("foo.bar", []byte("hi"))
	if err != nil {
		t.Fatal(err)
	}
	_, err = devc.SubscribeSync("foo.>")
	if err != nil {
		t.Fatal(err)
	}
	devc.Flush()

	prodSub, err := prodc.SubscribeSync(">")
	if err != nil {
		t.Fatal(err)
	}
	prodc.Flush()
	err = prodc.Publish("hello", []byte("hi"))
	if err != nil {
		t.Fatal(err)
	}
	prodc.Flush()

	// prod: can receive message on wildcard subscription.
	_, err = prodSub.NextMsg(1 * time.Second)
	if err != nil {
		t.Fatalf("Error during wait for next message: %s", err)
	}

	// dev: enough permissions to publish to sandbox subject.
	devSub, err := devc.SubscribeSync("sandbox.>")
	if err != nil {
		t.Fatal(err)
	}
	devc.Flush()
	err = devc.Publish("sandbox.foo.bar", []byte("hi!"))
	if err != nil {
		t.Fatal(err)
	}
	// both dev and prod clients can receive message
	_, err = devSub.NextMsg(1 * time.Second)
	if err != nil {
		t.Fatalf("Error during wait for next message: %s", err)
	}
	_, err = prodSub.NextMsg(1 * time.Second)
	if err != nil {
		t.Fatalf("Error during wait for next message: %s", err)
	}

	// default: no enough permissions
	_, err = defaultc.SubscribeSync("sandbox.>")
	if err != nil {
		t.Fatal(err)
	}
	defaultSub, err := defaultc.SubscribeSync("public.>")
	if err != nil {
		t.Fatal(err)
	}
	defaultc.Flush()
	err = devc.Publish("public.foo.bar", []byte("hi!"))
	if err != nil {
		t.Fatal(err)
	}
	_, err = defaultSub.NextMsg(1 * time.Second)
	if err != nil {
		t.Fatalf("Error during wait for next message: %s", err)
	}

	// Wait for a couple of errors
	var count int
Loop:
	for {
		select {
		case err := <-defaultErrCh:
			if err != nil {
				count++
			}
			if count == 3 {
				break Loop
			}
		case err := <-devErrCh:
			if err != nil {
				count++
			}
			if count == 3 {
				break Loop
			}
		case err := <-prodErrCh:
			if err != nil {
				t.Fatalf("Received unexpected auth error from client: %s", err)
			}
		case <-time.After(2 * time.Second):
			t.Fatalf("Timed out expecting auth errors")
		}
	}
}

func TestTLSClientCertificateTLSAuthMultipleOptions(t *testing.T) {
	srv, opts := RunServerWithConfig("./configs/tls_cert_san_emails.conf")
	defer srv.Shutdown()
	nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
	defaultErrCh := make(chan error)
	devErrCh := make(chan error)
	prodErrCh := make(chan error)

	// default: Using the default permissions, there are SANs
	// present in the cert but they are not users in the NATS config
	// so the subject is used instead.
	//
	//    Subject: CN = www.nats.io
	//
	//    X509v3 Subject Alternative Name:
	//        DNS:app.nats.dev, DNS:*.app.nats.dev
	//
	defaultc, err := nats.Connect(nurl,
		nats.ClientCert("./configs/certs/sans/dev.pem", "./configs/certs/sans/dev-key.pem"),
		nats.RootCAs("./configs/certs/sans/ca.pem"),
		nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
			defaultErrCh <- err
		}),
	)
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer defaultc.Close()

	// dev: Using SAN to validate user, even if emails are present in the config.
	//
	//    Subject: CN = www.nats.io
	//
	//    X509v3 Subject Alternative Name:
	//        DNS:app.nats.dev, email:admin@app.nats.dev, email:root@app.nats.dev
	//
	devc, err := nats.Connect(nurl,
		nats.ClientCert("./configs/certs/sans/dev-email.pem", "./configs/certs/sans/dev-email-key.pem"),
		nats.RootCAs("./configs/certs/sans/ca.pem"),
		nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
			devErrCh <- err
		}),
	)
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer devc.Close()

	// prod: Using SAN '*.app.nats.prod' with all permissions, which is not the first SAN.
	//
	//    Subject: CN = www.nats.io
	//
	//    X509v3 Subject Alternative Name:
	//        DNS:app.nats.prod, DNS:*.app.nats.prod
	//
	prodc, err := nats.Connect(nurl,
		nats.ClientCert("./configs/certs/sans/prod.pem", "./configs/certs/sans/prod-key.pem"),
		nats.RootCAs("./configs/certs/sans/ca.pem"),
		nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) {
			prodErrCh <- err
		}),
	)
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer prodc.Close()

	// No permissions to publish or subscribe on foo.>
	err = devc.Publish("foo.bar", []byte("hi"))
	if err != nil {
		t.Fatal(err)
	}
	_, err = devc.SubscribeSync("foo.>")
	if err != nil {
		t.Fatal(err)
	}
	devc.Flush()

	prodSub, err := prodc.SubscribeSync(">")
	if err != nil {
		t.Fatal(err)
	}
	prodc.Flush()
	err = prodc.Publish("hello", []byte("hi"))
	if err != nil {
		t.Fatal(err)
	}
	prodc.Flush()

	// prod: can receive message on wildcard subscription.
	_, err = prodSub.NextMsg(1 * time.Second)
	if err != nil {
		t.Fatalf("Error during wait for next message: %s", err)
	}

	// dev: enough permissions to publish to sandbox subject.
	devSub, err := devc.SubscribeSync("sandbox.>")
	if err != nil {
		t.Fatal(err)
	}
	devc.Flush()
	err = devc.Publish("sandbox.foo.bar", []byte("hi!"))
	if err != nil {
		t.Fatal(err)
	}
	// both dev and prod clients can receive message
	_, err = devSub.NextMsg(1 * time.Second)
	if err != nil {
		t.Fatalf("Error during wait for next message: %s", err)
	}
	_, err = prodSub.NextMsg(1 * time.Second)
	if err != nil {
		t.Fatalf("Error during wait for next message: %s", err)
	}

	// default: no enough permissions
	_, err = defaultc.SubscribeSync("sandbox.>")
	if err != nil {
		t.Fatal(err)
	}
	defaultSub, err := defaultc.SubscribeSync("public.>")
	if err != nil {
		t.Fatal(err)
	}
	defaultc.Flush()
	err = devc.Publish("public.foo.bar", []byte("hi!"))
	if err != nil {
		t.Fatal(err)
	}
	_, err = defaultSub.NextMsg(1 * time.Second)
	if err != nil {
		t.Fatalf("Error during wait for next message: %s", err)
	}

	// Wait for a couple of errors
	var count int
Loop:
	for {
		select {
		case err := <-defaultErrCh:
			if err != nil {
				count++
			}
			if count == 3 {
				break Loop
			}
		case err := <-devErrCh:
			if err != nil {
				count++
			}
			if count == 3 {
				break Loop
			}
		case err := <-prodErrCh:
			if err != nil {
				t.Fatalf("Received unexpected auth error from client: %s", err)
			}
		case <-time.After(2 * time.Second):
			t.Fatalf("Timed out expecting auth errors")
		}
	}
}

func TestTLSRoutesCertificateCNBasedAuth(t *testing.T) {
	// Base config for the servers
	optsA := LoadConfig("./configs/tls_cert_cn_routes.conf")
	optsB := LoadConfig("./configs/tls_cert_cn_routes.conf")
	optsC := LoadConfig("./configs/tls_cert_cn_routes_invalid_auth.conf")

	// TLS map should have been enabled
	if !optsA.Cluster.TLSMap || !optsB.Cluster.TLSMap || !optsC.Cluster.TLSMap {
		t.Error("Expected Cluster TLS verify and map feature to be activated")
	}

	routeURLs := "nats://localhost:9935, nats://localhost:9936, nats://localhost:9937"

	optsA.Host = "127.0.0.1"
	optsA.Port = 9335
	optsA.Cluster.Name = "xyz"
	optsA.Cluster.Host = optsA.Host
	optsA.Cluster.Port = 9935
	optsA.Routes = server.RoutesFromStr(routeURLs)
	optsA.NoSystemAccount = true
	srvA := RunServer(optsA)
	defer srvA.Shutdown()

	optsB.Host = "127.0.0.1"
	optsB.Port = 9336
	optsB.Cluster.Name = "xyz"
	optsB.Cluster.Host = optsB.Host
	optsB.Cluster.Port = 9936
	optsB.Routes = server.RoutesFromStr(routeURLs)
	optsB.NoSystemAccount = true
	srvB := RunServer(optsB)
	defer srvB.Shutdown()

	optsC.Host = "127.0.0.1"
	optsC.Port = 9337
	optsC.Cluster.Name = "xyz"
	optsC.Cluster.Host = optsC.Host
	optsC.Cluster.Port = 9937
	optsC.Routes = server.RoutesFromStr(routeURLs)
	optsC.NoSystemAccount = true
	srvC := RunServer(optsC)
	defer srvC.Shutdown()

	// srvC is not connected to srvA and srvB due to wrong cert
	checkClusterFormed(t, srvA, srvB)

	nc1, err := nats.Connect(fmt.Sprintf("%s:%d", optsA.Host, optsA.Port), nats.Name("A"))
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer nc1.Close()

	nc2, err := nats.Connect(fmt.Sprintf("%s:%d", optsB.Host, optsB.Port), nats.Name("B"))
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer nc2.Close()

	// This client is partitioned from rest of cluster due to using wrong cert.
	nc3, err := nats.Connect(fmt.Sprintf("%s:%d", optsC.Host, optsC.Port), nats.Name("C"))
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer nc3.Close()

	// Allowed via permissions to broadcast to other members of cluster.
	publicSub, err := nc1.SubscribeSync("public.>")
	if err != nil {
		t.Fatal(err)
	}

	// Not part of cluster permissions so message is not forwarded.
	privateSub, err := nc1.SubscribeSync("private.>")
	if err != nil {
		t.Fatal(err)
	}
	// This ensures that srvA has received the sub, not srvB
	nc1.Flush()

	checkFor(t, time.Second, 15*time.Millisecond, func() error {
		if n := srvB.NumSubscriptions(); n != 1 {
			return fmt.Errorf("Expected 1 sub, got %v", n)
		}
		return nil
	})

	// Not forwarded by cluster so won't be received.
	err = nc2.Publish("private.foo", []byte("private message on server B"))
	if err != nil {
		t.Fatal(err)
	}
	err = nc2.Publish("public.foo", []byte("public message from server B to server A"))
	if err != nil {
		t.Fatal(err)
	}
	nc2.Flush()
	err = nc3.Publish("public.foo", []byte("dropped message since unauthorized server"))
	if err != nil {
		t.Fatal(err)
	}
	nc3.Flush()

	// Message will be received since allowed via permissions
	_, err = publicSub.NextMsg(1 * time.Second)
	if err != nil {
		t.Fatalf("Error during wait for next message: %s", err)
	}
	msg, err := privateSub.NextMsg(500 * time.Millisecond)
	if err == nil {
		t.Errorf("Received unexpected message from private sub: %+v", msg)
	}
	msg, err = publicSub.NextMsg(500 * time.Millisecond)
	if err == nil {
		t.Errorf("Received unexpected message from private sub: %+v", msg)
	}
}

func TestTLSGatewaysCertificateCNBasedAuth(t *testing.T) {
	// Base config for the servers
	optsA := LoadConfig("./configs/tls_cert_cn_gateways.conf")
	optsB := LoadConfig("./configs/tls_cert_cn_gateways.conf")
	optsC := LoadConfig("./configs/tls_cert_cn_gateways_invalid_auth.conf")

	// TLS map should have been enabled
	if !optsA.Gateway.TLSMap || !optsB.Gateway.TLSMap || !optsC.Gateway.TLSMap {
		t.Error("Expected Cluster TLS verify and map feature to be activated")
	}

	gwA, err := url.Parse("nats://localhost:9995")
	if err != nil {
		t.Fatal(err)
	}
	gwB, err := url.Parse("nats://localhost:9996")
	if err != nil {
		t.Fatal(err)
	}
	gwC, err := url.Parse("nats://localhost:9997")
	if err != nil {
		t.Fatal(err)
	}

	optsA.Host = "127.0.0.1"
	optsA.Port = -1
	optsA.Gateway.Name = "A"
	optsA.Gateway.Port = 9995

	optsB.Host = "127.0.0.1"
	optsB.Port = -1
	optsB.Gateway.Name = "B"
	optsB.Gateway.Port = 9996

	optsC.Host = "127.0.0.1"
	optsC.Port = -1
	optsC.Gateway.Name = "C"
	optsC.Gateway.Port = 9997

	gateways := make([]*server.RemoteGatewayOpts, 3)
	gateways[0] = &server.RemoteGatewayOpts{
		Name: optsA.Gateway.Name,
		URLs: []*url.URL{gwA},
	}
	gateways[1] = &server.RemoteGatewayOpts{
		Name: optsB.Gateway.Name,
		URLs: []*url.URL{gwB},
	}
	gateways[2] = &server.RemoteGatewayOpts{
		Name: optsC.Gateway.Name,
		URLs: []*url.URL{gwC},
	}
	optsA.Gateway.Gateways = gateways
	optsB.Gateway.Gateways = gateways
	optsC.Gateway.Gateways = gateways

	server.SetGatewaysSolicitDelay(100 * time.Millisecond)
	defer server.ResetGatewaysSolicitDelay()

	srvA := RunServer(optsA)
	defer srvA.Shutdown()

	srvB := RunServer(optsB)
	defer srvB.Shutdown()

	srvC := RunServer(optsC)
	defer srvC.Shutdown()

	// Because we need to use "localhost" in the gw URLs (to match
	// hostname in the user/CN), the server may try to connect to
	// a [::1], etc.. that may or may not work, so give a lot of
	// time for that to complete ok.
	waitForOutboundGateways(t, srvA, 1, 5*time.Second)
	waitForOutboundGateways(t, srvB, 1, 5*time.Second)

	nc1, err := nats.Connect(srvA.Addr().String(), nats.Name("A"))
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer nc1.Close()

	nc2, err := nats.Connect(srvB.Addr().String(), nats.Name("B"))
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer nc2.Close()

	nc3, err := nats.Connect(srvC.Addr().String(), nats.Name("C"))
	if err != nil {
		t.Fatalf("Expected to connect, got %v", err)
	}
	defer nc3.Close()

	received := make(chan *nats.Msg)
	_, err = nc1.Subscribe("foo", func(msg *nats.Msg) {
		select {
		case received <- msg:
		default:
		}
	})
	if err != nil {
		t.Error(err)
	}
	_, err = nc3.Subscribe("help", func(msg *nats.Msg) {
		nc3.Publish(msg.Reply, []byte("response"))
	})
	if err != nil {
		t.Error(err)
	}

	go func() {
		for range time.NewTicker(10 * time.Millisecond).C {
			if nc2.IsClosed() {
				return
			}
			nc2.Publish("foo", []byte("bar"))
		}
	}()

	select {
	case <-received:
	case <-time.After(2 * time.Second):
		t.Error("Timed out waiting for gateway messages")
	}

	msg, err := nc2.Request("help", []byte("should fail"), 100*time.Millisecond)
	if err == nil {
		t.Errorf("Expected to not receive any messages, got: %+v", msg)
	}
}

func TestTLSVerifyClientCertificate(t *testing.T) {
	srv, opts := RunServerWithConfig("./configs/tlsverify_noca.conf")
	defer srv.Shutdown()

	nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)

	// The client is configured properly, but the server has no CA
	// to verify the client certificate. Connection should fail.
	nc, err := nats.Connect(nurl,
		nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem"),
		nats.RootCAs("./configs/certs/ca.pem"))
	if err == nil {
		nc.Close()
		t.Fatal("Expected failure to connect, did not")
	}
}

func TestTLSConnectionTimeout(t *testing.T) {
	opts := LoadConfig("./configs/tls.conf")
	opts.TLSTimeout = 0.25

	srv := RunServer(opts)
	defer srv.Shutdown()

	// Dial with normal TCP
	endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
	conn, err := net.Dial("tcp", endpoint)
	if err != nil {
		t.Fatalf("Could not connect to %q", endpoint)
	}
	defer conn.Close()

	// Read deadlines
	conn.SetReadDeadline(time.Now().Add(2 * time.Second))

	// Read the INFO string.
	br := bufio.NewReader(conn)
	info, err := br.ReadString('\n')
	if err != nil {
		t.Fatalf("Failed to read INFO - %v", err)
	}
	if !strings.HasPrefix(info, "INFO ") {
		t.Fatalf("INFO response incorrect: %s\n", info)
	}
	wait := time.Duration(opts.TLSTimeout * float64(time.Second))
	time.Sleep(wait)
	// Read deadlines
	conn.SetReadDeadline(time.Now().Add(2 * time.Second))
	tlsErr, err := br.ReadString('\n')
	if err == nil && !strings.Contains(tlsErr, "-ERR 'Secure Connection - TLS Required") {
		t.Fatalf("TLS Timeout response incorrect: %q\n", tlsErr)
	}
}

// Ensure there is no race between authorization timeout and TLS handshake.
func TestTLSAuthorizationShortTimeout(t *testing.T) {
	opts := LoadConfig("./configs/tls.conf")
	opts.AuthTimeout = 0.001

	srv := RunServer(opts)
	defer srv.Shutdown()

	endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
	nurl := fmt.Sprintf("tls://%s:%s@%s/", opts.Username, opts.Password, endpoint)

	// Expect an error here (no CA) but not a TLS oversized record error which
	// indicates the authorization timeout fired too soon.
	_, err := nats.Connect(nurl)
	if err == nil {
		t.Fatal("Expected error trying to connect to secure server")
	}
	if strings.Contains(err.Error(), "oversized record") {
		t.Fatal("Corrupted TLS handshake:", err)
	}
}

func TestClientTLSAndNonTLSConnections(t *testing.T) {
	s, opts := RunServerWithConfig("./configs/tls_mixed.conf")
	defer s.Shutdown()

	surl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)
	nc, err := nats.Connect(surl, nats.RootCAs("./configs/certs/ca.pem"))
	if err != nil {
		t.Fatalf("Failed to connect with TLS: %v", err)
	}
	defer nc.Close()

	// Now also make sure we can connect through plain text.
	nurl := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)
	nc2, err := nats.Connect(nurl)
	if err != nil {
		t.Fatalf("Failed to connect without TLS: %v", err)
	}
	defer nc2.Close()

	// Make sure they can go back and forth.
	sub, err := nc.SubscribeSync("foo")
	if err != nil {
		t.Fatalf("Error subscribing: %v", err)
	}
	sub2, err := nc2.SubscribeSync("bar")
	if err != nil {
		t.Fatalf("Error subscribing: %v", err)
	}
	nc.Flush()
	nc2.Flush()

	nmsgs := 100
	for i := 0; i < nmsgs; i++ {
		nc2.Publish("foo", []byte("HELLO FROM PLAINTEXT"))
		nc.Publish("bar", []byte("HELLO FROM TLS"))
	}
	// Now wait for the messages.
	checkFor(t, time.Second, 10*time.Millisecond, func() error {
		if msgs, _, err := sub.Pending(); err != nil || msgs != nmsgs {
			return fmt.Errorf("Did not receive the correct number of messages: %d", msgs)
		}
		if msgs, _, err := sub2.Pending(); err != nil || msgs != nmsgs {
			return fmt.Errorf("Did not receive the correct number of messages: %d", msgs)
		}
		return nil
	})

}

func stressConnect(t *testing.T, wg *sync.WaitGroup, errCh chan error, url string, index int) {
	defer wg.Done()

	subName := fmt.Sprintf("foo.%d", index)

	for i := 0; i < 33; i++ {
		nc, err := nats.Connect(url, nats.RootCAs("./configs/certs/ca.pem"))
		if err != nil {
			errCh <- fmt.Errorf("Unable to create TLS connection: %v\n", err)
			return
		}
		defer nc.Close()

		sub, err := nc.SubscribeSync(subName)
		if err != nil {
			errCh <- fmt.Errorf("Unable to subscribe on '%s': %v\n", subName, err)
			return
		}

		if err := nc.Publish(subName, []byte("secure data")); err != nil {
			errCh <- fmt.Errorf("Unable to send on '%s': %v\n", subName, err)
		}

		if _, err := sub.NextMsg(2 * time.Second); err != nil {
			errCh <- fmt.Errorf("Unable to get next message: %v\n", err)
		}

		nc.Close()
	}

	errCh <- nil
}

func TestTLSStressConnect(t *testing.T) {
	opts, err := server.ProcessConfigFile("./configs/tls.conf")
	if err != nil {
		panic(fmt.Sprintf("Error processing configuration file: %v", err))
	}
	opts.NoSigs, opts.NoLog = true, true

	// For this test, remove the authorization
	opts.Username = ""
	opts.Password = ""

	// Increase ssl timeout
	opts.TLSTimeout = 2.0

	srv := RunServer(opts)
	defer srv.Shutdown()

	nurl := fmt.Sprintf("tls://%s:%d", opts.Host, opts.Port)

	threadCount := 3

	errCh := make(chan error, threadCount)

	var wg sync.WaitGroup
	wg.Add(threadCount)

	for i := 0; i < threadCount; i++ {
		go stressConnect(t, &wg, errCh, nurl, i)
	}

	wg.Wait()

	var lastError error
	for i := 0; i < threadCount; i++ {
		err := <-errCh
		if err != nil {
			lastError = err
		}
	}

	if lastError != nil {
		t.Fatalf("%v\n", lastError)
	}
}

func TestTLSBadAuthError(t *testing.T) {
	srv, opts := RunServerWithConfig("./configs/tls.conf")
	defer srv.Shutdown()

	endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
	nurl := fmt.Sprintf("tls://%s:%s@%s/", opts.Username, "NOT_THE_PASSWORD", endpoint)

	_, err := nats.Connect(nurl, nats.RootCAs("./configs/certs/ca.pem"))
	if err == nil {
		t.Fatalf("Expected error trying to connect to secure server")
	}
	if strings.ToLower(err.Error()) != nats.ErrAuthorization.Error() {
		t.Fatalf("Expected and auth violation, got %v\n", err)
	}
}

func TestTLSConnectionCurvePref(t *testing.T) {
	srv, opts := RunServerWithConfig("./configs/tls_curve_pref.conf")
	defer srv.Shutdown()

	if len(opts.TLSConfig.CurvePreferences) != 1 {
		t.Fatal("Invalid curve preference loaded.")
	}

	if opts.TLSConfig.CurvePreferences[0] != tls.CurveP256 {
		t.Fatalf("Invalid curve preference loaded [%v].", opts.TLSConfig.CurvePreferences[0])
	}

	endpoint := fmt.Sprintf("%s:%d", opts.Host, opts.Port)
	nurl := fmt.Sprintf("tls://%s:%s@%s/", opts.Username, opts.Password, endpoint)
	nc, err := nats.Connect(nurl)
	if err == nil {
		nc.Close()
		t.Fatalf("Expected error trying to connect to secure server")
	}

	// Do simple SecureConnect
	nc, err = nats.Connect(fmt.Sprintf("tls://%s/", endpoint))
	if err == nil {
		nc.Close()
		t.Fatalf("Expected error trying to connect to secure server with no auth")
	}

	// Now do more advanced checking, verifying servername and using rootCA.

	nc, err = nats.Connect(nurl, nats.RootCAs("./configs/certs/ca.pem"))
	if err != nil {
		t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err)
	}
	defer nc.Close()

	subj := "foo-tls"
	sub, _ := nc.SubscribeSync(subj)

	nc.Publish(subj, []byte("We are Secure!"))
	nc.Flush()
	nmsgs, _, _ := sub.Pending()
	if nmsgs != 1 {
		t.Fatalf("Expected to receive a message over the TLS connection")
	}
}

type captureSlowConsumerLogger struct {
	dummyLogger
	ch    chan string
	gotIt bool
}

func (l *captureSlowConsumerLogger) Noticef(format string, v ...any) {
	msg := fmt.Sprintf(format, v...)
	if strings.Contains(msg, "Slow Consumer") {
		l.Lock()
		if !l.gotIt {
			l.gotIt = true
			l.ch <- msg
		}
		l.Unlock()
	}
}

func TestTLSTimeoutNotReportSlowConsumer(t *testing.T) {
	oa, err := server.ProcessConfigFile("./configs/srv_a_tls.conf")
	if err != nil {
		t.Fatalf("Unable to load config file: %v", err)
	}

	// Override TLSTimeout to very small value so that handshake fails
	oa.Cluster.TLSTimeout = 0.0000001
	sa := RunServer(oa)
	defer sa.Shutdown()

	ch := make(chan string, 1)
	cscl := &captureSlowConsumerLogger{ch: ch}
	sa.SetLogger(cscl, false, false)

	ob, err := server.ProcessConfigFile("./configs/srv_b_tls.conf")
	if err != nil {
		t.Fatalf("Unable to load config file: %v", err)
	}

	sb := RunServer(ob)
	defer sb.Shutdown()

	// Watch the logger for a bit and make sure we don't get any
	// Slow Consumer error.
	select {
	case e := <-ch:
		t.Fatalf("Unexpected slow consumer error: %s", e)
	case <-time.After(500 * time.Millisecond):
		// ok
	}
}

func TestTLSHandshakeFailureMemUsage(t *testing.T) {
	for i, test := range []struct {
		name   string
		config string
	}{
		{
			"connect to TLS client port",
			`
				port: -1
				%s
			`,
		},
		{
			"connect to TLS route port",
			`
				port: -1
				cluster {
					port: -1
					%s
				}
			`,
		},
		{
			"connect to TLS gateway port",
			`
				port: -1
				gateway {
					name: "A"
					port: -1
					%s
				}
			`,
		},
	} {
		t.Run(test.name, func(t *testing.T) {
			content := fmt.Sprintf(test.config, `
				tls {
					cert_file: "configs/certs/server-cert.pem"
					key_file: "configs/certs/server-key.pem"
					ca_file: "configs/certs/ca.pem"
					timeout: 5
				}
			`)
			conf := createConfFile(t, []byte(content))
			s, opts := RunServerWithConfig(conf)
			defer s.Shutdown()

			var port int
			switch i {
			case 0:
				port = opts.Port
			case 1:
				port = s.ClusterAddr().Port
			case 2:
				port = s.GatewayAddr().Port
			}

			varz, _ := s.Varz(nil)
			base := varz.Mem
			buf := make([]byte, 1024*1024)
			for i := 0; i < 100; i++ {
				conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port))
				if err != nil {
					t.Fatalf("Error on dial: %v", err)
				}
				conn.SetWriteDeadline(time.Now().Add(10 * time.Millisecond))
				conn.Write(buf)
				conn.Close()
			}

			varz, _ = s.Varz(nil)
			newval := (varz.Mem - base) / (1024 * 1024)
			// May need to adjust that, but right now, with 100 clients
			// we are at about 20MB for client port, 11MB for route
			// and 6MB for gateways, so pick 50MB as the threshold
			if newval >= 50 {
				t.Fatalf("Consumed too much memory: %v MB", newval)
			}
		})
	}
}

func TestTLSClientAuthWithRDNSequence(t *testing.T) {
	for _, test := range []struct {
		name   string
		config string
		certs  nats.Option
		err    error
		rerr   error
	}{
		// To generate certs for these tests:
		// USE `regenerate_rdns_svid.sh` TO REGENERATE
		//
		// ```
		// 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
		// 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
		// ```
		//
		// To confirm subject from cert:
		//
		// ```
		// openssl x509 -in client-$CLIENT_ID.pem -text | grep Subject:
		// ```
		//
		{
			"connect with tls using full RDN sequence",
			`
                                port: -1
                                %s

                                authorization {
                                  users = [
                                    { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=foo1,DC=foo2" }
                                  ]
                                }
                        `,
			// C = US, ST = CA, L = Los Angeles, O = NATS, OU = NATS, CN = localhost, DC = foo1, DC = foo2
			nats.ClientCert("./configs/certs/rdns/client-a.pem", "./configs/certs/rdns/client-a.key"),
			nil,
			nil,
		},
		{
			"connect with tls using full RDN sequence in original order",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "DC=foo2,DC=foo1,CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US" }
				  ]
				}
			`,
			// C = US, ST = CA, L = Los Angeles, O = NATS, OU = NATS, CN = localhost, DC = foo1, DC = foo2
			nats.ClientCert("./configs/certs/rdns/client-a.pem", "./configs/certs/rdns/client-a.key"),
			nil,
			nil,
		},
		{
			"connect with tls using partial RDN sequence has different permissions",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "DC=foo2,DC=foo1,CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US" },
				    { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=foo1,DC=foo2" },
				    { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US",
                                      permissions = { subscribe = { deny = ">" }} }
				  ]
				}
			`,
			// C = US, ST = California, L = Los Angeles, O = NATS, OU = NATS, CN = localhost
			nats.ClientCert("./configs/certs/rdns/client-b.pem", "./configs/certs/rdns/client-b.key"),
			nil,
			errors.New("nats: timeout"),
		},
		{
			"connect with tls and RDN sequence partially matches",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "DC=foo2,DC=foo1,CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US" }
				    { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=foo1,DC=foo2" }
				    { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US"},
				  ]
				}
			`,
			// Cert is:
			//
			// C = US, ST = CA, L = Los Angeles, O = NATS, OU = NATS, CN = localhost, DC = foo3, DC = foo4
			//
			// but it will actually match the user without DCs so will not get an error:
			//
			// C = US, ST = CA, L = Los Angeles, O = NATS, OU = NATS, CN = localhost
			//
			nats.ClientCert("./configs/certs/rdns/client-c.pem", "./configs/certs/rdns/client-c.key"),
			nil,
			nil,
		},
		{
			"connect with tls and RDN sequence does not match",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=foo1,DC=foo2" },
				    { user = "DC=foo2,DC=foo1,CN=localhost,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US" }
				  ]
				}
			`,
			// C = US, ST = California, L = Los Angeles, O = NATS, OU = NATS, CN = localhost, DC = foo3, DC = foo4
			//
			nats.ClientCert("./configs/certs/rdns/client-c.pem", "./configs/certs/rdns/client-c.key"),
			errors.New("nats: Authorization Violation"),
			nil,
		},
		{
			"connect with tls and RDN sequence with space after comma not should matter",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "DC=foo2, DC=foo1, CN=localhost, OU=NATS, O=NATS, L=Los Angeles, ST=CA, C=US" }
				  ]
				}
			`,
			// C=US/ST=California/L=Los Angeles/O=NATS/OU=NATS/CN=localhost/DC=foo1/DC=foo2
			//
			nats.ClientCert("./configs/certs/rdns/client-a.pem", "./configs/certs/rdns/client-a.key"),
			nil,
			nil,
		},
		{
			"connect with tls and full RDN sequence respects order",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "DC=com, DC=example, CN=*.example.com, O=NATS, OU=NATS, L=Los Angeles, ST=CA, C=US" }
				  ]
				}
			`,
			//
			// C = US, ST = CA, L = Los Angeles, OU = NATS, O = NATS, CN = *.example.com, DC = example, DC = com
			//
			nats.ClientCert("./configs/certs/rdns/client-d.pem", "./configs/certs/rdns/client-d.key"),
			nil,
			nil,
		},
		{
			"connect with tls and full RDN sequence with added domainComponents and spaces also matches",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "CN=*.example.com,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=example,DC=com" }
				  ]
				}
			`,
			//
			// C = US, ST = CA, L = Los Angeles, OU = NATS, O = NATS, CN = *.example.com, DC = example, DC = com
			//
			nats.ClientCert("./configs/certs/rdns/client-d.pem", "./configs/certs/rdns/client-d.key"),
			nil,
			nil,
		},
		{
			"connect with tls and full RDN sequence with correct order takes precedence over others matches",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "CN=*.example.com,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US,DC=example,DC=com",
                                        permissions = { subscribe = { deny = ">" }} }

				    # This should take precedence since it is in the RFC2253 order.
				    { user = "DC=com,DC=example,CN=*.example.com,O=NATS,OU=NATS,L=Los Angeles,ST=CA,C=US" }

				    { user = "CN=*.example.com,OU=NATS,O=NATS,L=Los Angeles,ST=CA,C=US",
                                        permissions = { subscribe = { deny = ">" }} }
				  ]
				}
			`,
			//
			// C = US, ST = CA, L = Los Angeles, OU = NATS, O = NATS, CN = *.example.com, DC = example, DC = com
			//
			nats.ClientCert("./configs/certs/rdns/client-d.pem", "./configs/certs/rdns/client-d.key"),
			nil,
			nil,
		},
		{
			"connect with tls and RDN includes multiple CN elements",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "DC=com,DC=acme,OU=Organic Units,OU=Users,CN=jdoe,CN=123456,CN=John Doe" }
                                  ]
				}
			`,
			//
			// OpenSSL: -subj "/CN=John Doe/CN=123456/CN=jdoe/OU=Users/OU=Organic Units/DC=acme/DC=com"
			// Go:       CN=jdoe,OU=Users+OU=Organic Units
			// RFC2253:  DC=com,DC=acme,OU=Organic Units,OU=Users,CN=jdoe,CN=123456,CN=John Doe
			//
			nats.ClientCert("./configs/certs/rdns/client-e.pem", "./configs/certs/rdns/client-e.key"),
			nil,
			nil,
		},
		{
			"connect with tls and DN includes a multi value RDN",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org" }
                                  ]
				}
			`,
			//
			// OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
			// Go:       CN=John Doe,O=users
			// RFC2253:  CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
			//
			nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
			nil,
			nil,
		},
		{
			"connect with tls and DN includes a multi value RDN but there is no match",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "CN=John Doe,DC=DEV,DC=OpenSSL,DC=org" }
                                  ]
				}
			`,
			//
			// OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
			// Go:       CN=John Doe,O=users
			// RFC2253:  CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
			//
			nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
			errors.New("nats: Authorization Violation"),
			nil,
		},
		{
			"connect with tls and DN includes a multi value RDN that are reordered",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "CN=John Doe,O=users+DC=DEV,DC=OpenSSL,DC=org" }
                                  ]
				}
			`,
			//
			// OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
			// Go:       CN=John Doe,O=users
			// RFC2253:  CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
			//
			nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
			nil,
			nil,
		},
	} {
		t.Run(test.name, func(t *testing.T) {
			content := fmt.Sprintf(test.config, `
				tls {
					cert_file: "configs/certs/rdns/server.pem"
					key_file: "configs/certs/rdns/server.key"
					ca_file: "configs/certs/rdns/ca.pem"
					timeout: 5
					verify_and_map: true
				}
			`)
			conf := createConfFile(t, []byte(content))
			s, opts := RunServerWithConfig(conf)
			defer s.Shutdown()

			nc, err := nats.Connect(fmt.Sprintf("tls://localhost:%d", opts.Port),
				test.certs,
				nats.RootCAs("./configs/certs/rdns/ca.pem"),
				nats.ErrorHandler(noOpErrHandler),
			)
			if test.err == nil && err != nil {
				t.Errorf("Expected to connect, got %v", err)
			} else if test.err != nil && err == nil {
				t.Errorf("Expected error on connect")
			} else if test.err != nil && err != nil {
				// Error on connect was expected
				if test.err.Error() != err.Error() {
					t.Errorf("Expected error %s, got: %s", test.err, err)
				}
				return
			}
			defer nc.Close()

			nc.Subscribe("ping", func(m *nats.Msg) {
				m.Respond([]byte("pong"))
			})
			nc.Flush()

			_, err = nc.Request("ping", []byte("ping"), 250*time.Millisecond)
			if test.rerr != nil && err == nil {
				t.Errorf("Expected error getting response")
			} else if test.rerr == nil && err != nil {
				t.Errorf("Expected response")
			}
		})
	}
}

func TestTLSClientAuthWithRDNSequenceReordered(t *testing.T) {
	for _, test := range []struct {
		name   string
		config string
		certs  nats.Option
		err    error
		rerr   error
	}{
		{
			"connect with tls and DN includes a multi value RDN that are reordered",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "DC=org,DC=OpenSSL,O=users+DC=DEV,CN=John Doe" }
                                  ]
				}
			`,
			//
			// OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
			// Go:       CN=John Doe,O=users
			// RFC2253:  CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
			//
			nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
			nil,
			nil,
		},
		{
			"connect with tls and DN includes a multi value RDN that are reordered but not equal RDNs",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "DC=org,DC=OpenSSL,O=users,CN=John Doe" }
                                  ]
				}
			`,
			//
			// OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
			// Go:       CN=John Doe,O=users
			// RFC2253:  CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
			//
			nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
			errors.New("nats: Authorization Violation"),
			nil,
		},
		{
			"connect with tls and DN includes a multi value RDN that are reordered but not equal RDNs",
			`
				port: -1
				%s

				authorization {
				  users = [
				    { user = "DC=OpenSSL, DC=org, O=users, CN=John Doe" }
                                  ]
				}
			`,
			//
			// OpenSSL: -subj "/DC=org/DC=OpenSSL/DC=DEV+O=users/CN=John Doe" -multivalue-rdn
			// Go:       CN=John Doe,O=users
			// RFC2253:  CN=John Doe,DC=DEV+O=users,DC=OpenSSL,DC=org
			//
			nats.ClientCert("./configs/certs/rdns/client-f.pem", "./configs/certs/rdns/client-f.key"),
			errors.New("nats: Authorization Violation"),
			nil,
		},
	} {
		t.Run(test.name, func(t *testing.T) {
			content := fmt.Sprintf(test.config, `
				tls {
					cert_file: "configs/certs/rdns/server.pem"
					key_file: "configs/certs/rdns/server.key"
					ca_file: "configs/certs/rdns/ca.pem"
					timeout: 5
					verify_and_map: true
				}
			`)
			conf := createConfFile(t, []byte(content))
			s, opts := RunServerWithConfig(conf)
			defer s.Shutdown()

			nc, err := nats.Connect(fmt.Sprintf("tls://localhost:%d", opts.Port),
				test.certs,
				nats.RootCAs("./configs/certs/rdns/ca.pem"),
			)
			if test.err == nil && err != nil {
				t.Errorf("Expected to connect, got %v", err)
			} else if test.err != nil && err == nil {
				t.Errorf("Expected error on connect")
			} else if test.err != nil && err != nil {
				// Error on connect was expected
				if test.err.Error() != err.Error() {
					t.Errorf("Expected error %s, got: %s", test.err, err)
				}
				return
			}
			defer nc.Close()

			nc.Subscribe("ping", func(m *nats.Msg) {
				m.Respond([]byte("pong"))
			})
			nc.Flush()

			_, err = nc.Request("ping", []byte("ping"), 250*time.Millisecond)
			if test.rerr != nil && err == nil {
				t.Errorf("Expected error getting response")
			} else if test.rerr == nil && err != nil {
				t.Errorf("Expected response")
			}
		})
	}
}

func TestTLSClientSVIDAuth(t *testing.T) {
	for _, test := range []struct {
		name   string
		config string
		certs  nats.Option
		err    error
		rerr   error
	}{
		{
			"connect with tls using certificate with URIs",
			`
				port: -1
				%s

				authorization {
				  users = [
				    {
                                      user = "spiffe://localhost/my-nats-service/user-a"
                                    }
				  ]
				}
			`,
			nats.ClientCert("./configs/certs/svid/client-a.pem", "./configs/certs/svid/client-a.key"),
			nil,
			nil,
		},
		{
			"connect with tls using certificate with limited different permissions",
			`
				port: -1
				%s

				authorization {
				  users = [
				    {
                                      user = "spiffe://localhost/my-nats-service/user-a"
                                    },
				    {
                                      user = "spiffe://localhost/my-nats-service/user-b"
                                      permissions = { subscribe = { deny = ">" }}
                                    }
				  ]
				}
			`,
			nats.ClientCert("./configs/certs/svid/client-b.pem", "./configs/certs/svid/client-b.key"),
			nil,
			errors.New("nats: timeout"),
		},
		{
			"connect with tls without URIs in permissions will still match SAN",
			`
				port: -1
				%s

				authorization {
				  users = [
				    {
                                      user = "O=SPIRE,C=US"
                                    }
				  ]
				}
			`,
			nats.ClientCert("./configs/certs/svid/client-b.pem", "./configs/certs/svid/client-b.key"),
			nil,
			nil,
		},
		{
			"connect with tls but no permissions",
			`
				port: -1
				%s

				authorization {
				  users = [
				    {
                                      user = "spiffe://localhost/my-nats-service/user-c"
                                    }
				  ]
				}
			`,
			nats.ClientCert("./configs/certs/svid/client-a.pem", "./configs/certs/svid/client-a.key"),
			errors.New("nats: Authorization Violation"),
			nil,
		},
	} {
		t.Run(test.name, func(t *testing.T) {
			content := fmt.Sprintf(test.config, `
				tls {
					cert_file: "configs/certs/svid/server.pem"
					key_file: "configs/certs/svid/server.key"
					ca_file: "configs/certs/svid/ca.pem"
					timeout: 5
                                        insecure: true
					verify_and_map: true
				}
			`)
			conf := createConfFile(t, []byte(content))
			s, opts := RunServerWithConfig(conf)
			defer s.Shutdown()

			nc, err := nats.Connect(fmt.Sprintf("tls://localhost:%d", opts.Port),
				test.certs,
				nats.RootCAs("./configs/certs/svid/ca.pem"),
				nats.ErrorHandler(noOpErrHandler),
			)
			if test.err == nil && err != nil {
				t.Errorf("Expected to connect, got %v", err)
			} else if test.err != nil && err == nil {
				t.Errorf("Expected error on connect")
			} else if test.err != nil && err != nil {
				// Error on connect was expected
				if test.err.Error() != err.Error() {
					t.Errorf("Expected error %s, got: %s", test.err, err)
				}
				return
			}
			defer nc.Close()

			nc.Subscribe("ping", func(m *nats.Msg) {
				m.Respond([]byte("pong"))
			})
			nc.Flush()

			_, err = nc.Request("ping", []byte("ping"), 250*time.Millisecond)
			if test.rerr != nil && err == nil {
				t.Errorf("Expected error getting response")
			} else if test.rerr == nil && err != nil {
				t.Errorf("Expected response")
			}
		})
	}
}

func TestTLSPinnedCertsClient(t *testing.T) {
	tmpl := `
	host: localhost
	port: -1
	tls {
		ca_file: "configs/certs/ca.pem"
		cert_file: "configs/certs/server-cert.pem"
		key_file: "configs/certs/server-key.pem"
		# Require a client certificate and map user id from certificate
		verify: true
		pinned_certs: ["%s"]
	}`

	confFileName := createConfFile(t, []byte(fmt.Sprintf(tmpl, "aaaaaaaa09fde09451411ba3b42c0f74727d61a974c69fd3cf5257f39c75f0e9")))
	srv, o := RunServerWithConfig(confFileName)
	defer srv.Shutdown()

	if len(o.TLSPinnedCerts) != 1 {
		t.Fatal("expected one pinned cert")
	}

	opts := []nats.Option{
		nats.RootCAs("configs/certs/ca.pem"),
		nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem"),
	}

	nc, err := nats.Connect(srv.ClientURL(), opts...)
	if err == nil {
		nc.Close()
		t.Fatalf("Expected error trying to connect without a certificate in pinned_certs")
	}

	os.WriteFile(confFileName, []byte(fmt.Sprintf(tmpl, "bf6f821f09fde09451411ba3b42c0f74727d61a974c69fd3cf5257f39c75f0e9")), 0660)
	if err := srv.Reload(); err != nil {
		t.Fatalf("on Reload got %v", err)
	}
	// reload pinned to the certs used
	nc, err = nats.Connect(srv.ClientURL(), opts...)
	if err != nil {
		t.Fatalf("Expected no error, got: %v", err)
	}
	nc.Close()
}

type captureWarnLogger struct {
	dummyLogger
	receive chan string
}

func newCaptureWarnLogger() *captureWarnLogger {
	return &captureWarnLogger{
		receive: make(chan string, 100),
	}
}

func (l *captureWarnLogger) Warnf(format string, v ...any) {
	l.receive <- fmt.Sprintf(format, v...)
}

func (l *captureWarnLogger) waitFor(expect string, timeout time.Duration) bool {
	for {
		select {
		case msg := <-l.receive:
			if strings.Contains(msg, expect) {
				return true
			}
		case <-time.After(timeout):
			return false
		}
	}
}

func TestTLSConnectionRate(t *testing.T) {
	config := `
		listen: "127.0.0.1:-1"
		tls {
			cert_file: "./configs/certs/server-cert.pem"
			key_file:  "./configs/certs/server-key.pem"
			connection_rate_limit: 3
		}
	`

	confFileName := createConfFile(t, []byte(config))

	srv, _ := RunServerWithConfig(confFileName)
	logger := newCaptureWarnLogger()
	srv.SetLogger(logger, false, false)
	defer srv.Shutdown()

	var err error
	count := 0
	for count < 10 {
		var nc *nats.Conn
		nc, err = nats.Connect(srv.ClientURL(), nats.RootCAs("./configs/certs/ca.pem"))

		if err != nil {
			break
		}
		nc.Close()
		count++
	}

	if count != 3 {
		t.Fatalf("Expected 3 connections per second, got %d (%v)", count, err)
	}

	if !logger.waitFor("connections due to TLS rate limiting", time.Second) {
		t.Fatalf("did not log 'TLS rate limiting' warning")
	}
}

func TestTLSPinnedCertsRoute(t *testing.T) {
	tmplSeed := `
	host: localhost
	port: -1
	cluster {
		port: -1
		pool_size: -1
		tls {
			ca_file: "configs/certs/ca.pem"
			cert_file: "configs/certs/server-cert.pem"
			key_file: "configs/certs/server-key.pem"
		}
	}`
	// this server connects to seed, but is set up to not trust seeds cert
	tmplSrv := `
	host: localhost
	port: -1
	cluster {
		port: -1
		routes = [nats-route://localhost:%d]
		tls {
			ca_file: "configs/certs/ca.pem"
			cert_file: "configs/certs/server-cert.pem"
			key_file: "configs/certs/server-key.pem"
			# Require a client certificate and map user id from certificate
			verify: true
			# expected to fail the seed server
			pinned_certs: ["%s"]
		}
	}`

	confSeed := createConfFile(t, []byte(tmplSeed))
	srvSeed, o := RunServerWithConfig(confSeed)
	defer srvSeed.Shutdown()

	confSrv := createConfFile(t, []byte(fmt.Sprintf(tmplSrv, o.Cluster.Port, "89386860ea1222698ea676fc97310bdf2bff6f7e2b0420fac3b3f8f5a08fede5")))
	srv, _ := RunServerWithConfig(confSrv)
	defer srv.Shutdown()

	checkClusterFormed(t, srvSeed, srv)

	// this change will result in the server being and remaining disconnected
	os.WriteFile(confSrv, []byte(fmt.Sprintf(tmplSrv, o.Cluster.Port, "aaaaaaaa09fde09451411ba3b42c0f74727d61a974c69fd3cf5257f39c75f0e9")), 0660)
	if err := srv.Reload(); err != nil {
		t.Fatalf("on Reload got %v", err)
	}

	checkNumRoutes(t, srvSeed, 0)
	checkNumRoutes(t, srv, 0)
}

func TestAllowNonTLSReload(t *testing.T) {
	tmpl := `
		listen: "127.0.0.1:-1"
		ping_interval: "%s"
		tls {
			ca_file: "configs/certs/ca.pem"
			cert_file: "configs/certs/server-cert.pem"
			key_file: "configs/certs/server-key.pem"
		}
		allow_non_tls: true
	`
	conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, "10s")))
	s, o := RunServerWithConfig(conf)
	defer s.Shutdown()

	check := func() {
		t.Helper()
		nc := createClientConn(t, "127.0.0.1", o.Port)
		defer nc.Close()
		info := checkInfoMsg(t, nc)
		if !info.TLSAvailable {
			t.Fatal("TLSAvailable should be true, was false")
		}
		if info.TLSRequired {
			t.Fatal("TLSRequired should be false, was true")
		}
	}
	check()

	os.WriteFile(conf, []byte(fmt.Sprintf(tmpl, "20s")), 0660)
	if err := s.Reload(); err != nil {
		t.Fatalf("Error on reload: %v", err)
	}
	check()
}