- Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathopts.go
6058 lines (5729 loc) · 182 KB
/
opts.go
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
// Copyright 2012-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 server
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"flag"
"fmt"
"math"
"net"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/nats-io/jwt/v2"
"github.com/nats-io/nats-server/v2/conf"
"github.com/nats-io/nats-server/v2/server/certidp"
"github.com/nats-io/nats-server/v2/server/certstore"
"github.com/nats-io/nkeys"
)
varallowUnknownTopLevelField=int32(0)
// NoErrOnUnknownFields can be used to change the behavior the processing
// of a configuration file. By default, an error is reported if unknown
// fields are found. If `noError` is set to true, no error will be reported
// if top-level unknown fields are found.
funcNoErrOnUnknownFields(noErrorbool) {
varvalint32
ifnoError {
val=int32(1)
}
atomic.StoreInt32(&allowUnknownTopLevelField, val)
}
// PinnedCertSet is a set of lower case hex-encoded sha256 of DER encoded SubjectPublicKeyInfo
typePinnedCertSetmap[string]struct{}
// ClusterOpts are options for clusters.
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
typeClusterOptsstruct {
Namestring`json:"-"`
Hoststring`json:"addr,omitempty"`
Portint`json:"cluster_port,omitempty"`
Usernamestring`json:"-"`
Passwordstring`json:"-"`
AuthTimeoutfloat64`json:"auth_timeout,omitempty"`
Permissions*RoutePermissions`json:"-"`
TLSTimeoutfloat64`json:"-"`
TLSConfig*tls.Config`json:"-"`
TLSMapbool`json:"-"`
TLSCheckKnownURLsbool`json:"-"`
TLSPinnedCertsPinnedCertSet`json:"-"`
ListenStrstring`json:"-"`
Advertisestring`json:"-"`
NoAdvertisebool`json:"-"`
ConnectRetriesint`json:"-"`
PoolSizeint`json:"-"`
PinnedAccounts []string`json:"-"`
CompressionCompressionOpts`json:"-"`
PingInterval time.Duration`json:"-"`
MaxPingsOutint`json:"-"`
// Not exported (used in tests)
resolvernetResolver
// Snapshot of configured TLS options.
tlsConfigOpts*TLSConfigOpts
}
// CompressionOpts defines the compression mode and optional configuration.
typeCompressionOptsstruct {
Modestring
// If `Mode` is set to CompressionS2Auto, RTTThresholds provides the
// thresholds at which the compression level will go from
// CompressionS2Uncompressed to CompressionS2Fast, CompressionS2Better
// or CompressionS2Best. If a given level is not desired, specify 0
// for this slot. For instance, the slice []{0, 10ms, 20ms} means that
// for any RTT up to 10ms included the compression level will be
// CompressionS2Fast, then from ]10ms..20ms], the level will be selected
// as CompressionS2Better. Anything above 20ms will result in picking
// the CompressionS2Best compression level.
RTTThresholds []time.Duration
}
// GatewayOpts are options for gateways.
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
typeGatewayOptsstruct {
Namestring`json:"name"`
Hoststring`json:"addr,omitempty"`
Portint`json:"port,omitempty"`
Usernamestring`json:"-"`
Passwordstring`json:"-"`
AuthTimeoutfloat64`json:"auth_timeout,omitempty"`
TLSConfig*tls.Config`json:"-"`
TLSTimeoutfloat64`json:"tls_timeout,omitempty"`
TLSMapbool`json:"-"`
TLSCheckKnownURLsbool`json:"-"`
TLSPinnedCertsPinnedCertSet`json:"-"`
Advertisestring`json:"advertise,omitempty"`
ConnectRetriesint`json:"connect_retries,omitempty"`
Gateways []*RemoteGatewayOpts`json:"gateways,omitempty"`
RejectUnknownbool`json:"reject_unknown,omitempty"`// config got renamed to reject_unknown_cluster
// Not exported, for tests.
resolvernetResolver
sendQSubsBufSizeint
// Snapshot of configured TLS options.
tlsConfigOpts*TLSConfigOpts
}
// RemoteGatewayOpts are options for connecting to a remote gateway
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
typeRemoteGatewayOptsstruct {
Namestring`json:"name"`
TLSConfig*tls.Config`json:"-"`
TLSTimeoutfloat64`json:"tls_timeout,omitempty"`
URLs []*url.URL`json:"urls,omitempty"`
tlsConfigOpts*TLSConfigOpts
}
// LeafNodeOpts are options for a given server to accept leaf node connections and/or connect to a remote cluster.
typeLeafNodeOptsstruct {
Hoststring`json:"addr,omitempty"`
Portint`json:"port,omitempty"`
Usernamestring`json:"-"`
Passwordstring`json:"-"`
Nkeystring`json:"-"`
Accountstring`json:"-"`
Users []*User`json:"-"`
AuthTimeoutfloat64`json:"auth_timeout,omitempty"`
TLSConfig*tls.Config`json:"-"`
TLSTimeoutfloat64`json:"tls_timeout,omitempty"`
TLSMapbool`json:"-"`
TLSPinnedCertsPinnedCertSet`json:"-"`
// When set to true, the server will perform the TLS handshake before
// sending the INFO protocol. For remote leafnodes that are not configured
// with a similar option, their connection will fail with some sort
// of timeout or EOF error since they are expecting to receive an
// INFO protocol first.
TLSHandshakeFirstbool`json:"-"`
// If TLSHandshakeFirst is true and this value is strictly positive,
// the server will wait for that amount of time for the TLS handshake
// to start before falling back to previous behavior of sending the
// INFO protocol first. It allows for a mix of newer remote leafnodes
// that can require a TLS handshake first, and older that can't.
TLSHandshakeFirstFallback time.Duration`json:"-"`
Advertisestring`json:"-"`
NoAdvertisebool`json:"-"`
ReconnectInterval time.Duration`json:"-"`
// Compression options
CompressionCompressionOpts`json:"-"`
// For solicited connections to other clusters/superclusters.
Remotes []*RemoteLeafOpts`json:"remotes,omitempty"`
// This is the minimum version that is accepted for remote connections.
// Note that since the server version in the CONNECT protocol was added
// only starting at v2.8.0, any version below that will be rejected
// (since empty version string in CONNECT would fail the "version at
// least" test).
MinVersionstring
// Not exported, for tests.
resolvernetResolver
dialTimeout time.Duration
connDelay time.Duration
// Snapshot of configured TLS options.
tlsConfigOpts*TLSConfigOpts
}
// SignatureHandler is used to sign a nonce from the server while
// authenticating with Nkeys. The callback should sign the nonce and
// return the JWT and the raw signature.
typeSignatureHandlerfunc([]byte) (string, []byte, error)
// RemoteLeafOpts are options for connecting to a remote server as a leaf node.
typeRemoteLeafOptsstruct {
LocalAccountstring`json:"local_account,omitempty"`
NoRandomizebool`json:"-"`
URLs []*url.URL`json:"urls,omitempty"`
Credentialsstring`json:"-"`
Nkeystring`json:"-"`
SignatureCBSignatureHandler`json:"-"`
TLSbool`json:"-"`
TLSConfig*tls.Config`json:"-"`
TLSTimeoutfloat64`json:"tls_timeout,omitempty"`
TLSHandshakeFirstbool`json:"-"`
Hubbool`json:"hub,omitempty"`
DenyImports []string`json:"-"`
DenyExports []string`json:"-"`
// FirstInfoTimeout is the amount of time the server will wait for the
// initial INFO protocol from the remote server before closing the
// connection.
FirstInfoTimeout time.Duration`json:"-"`
// Compression options for this remote. Each remote could have a different
// setting and also be different from the LeafNode options.
CompressionCompressionOpts`json:"-"`
// When an URL has the "ws" (or "wss") scheme, then the server will initiate the
// connection as a websocket connection. By default, the websocket frames will be
// masked (as if this server was a websocket client to the remote server). The
// NoMasking option will change this behavior and will send umasked frames.
Websocketstruct {
Compressionbool`json:"-"`
NoMaskingbool`json:"-"`
}
tlsConfigOpts*TLSConfigOpts
// If we are clustered and our local account has JetStream, if apps are accessing
// a stream or consumer leader through this LN and it gets dropped, the apps will
// not be able to work. This tells the system to migrate the leaders away from this server.
// This only changes leader for R>1 assets.
JetStreamClusterMigratebool`json:"jetstream_cluster_migrate,omitempty"`
// If JetStreamClusterMigrate is set to true, this is the time after which the leader
// will be migrated away from this server if still disconnected.
JetStreamClusterMigrateDelay time.Duration`json:"jetstream_cluster_migrate_delay,omitempty"`
}
typeJSLimitOptsstruct {
MaxRequestBatchint`json:"max_request_batch,omitempty"`
MaxAckPendingint`json:"max_ack_pending,omitempty"`
MaxHAAssetsint`json:"max_ha_assets,omitempty"`
Duplicates time.Duration`json:"max_duplicate_window,omitempty"`
}
typeJSTpmOptsstruct {
KeysFilestring
KeyPasswordstring
SrkPasswordstring
Pcrint
}
// AuthCallout option used to map external AuthN to NATS based AuthZ.
typeAuthCalloutstruct {
// Must be a public account Nkey.
Issuerstring
// Account to be used for sending requests.
Accountstring
// Users that will bypass auth_callout and be used for the auth service itself.
AuthUsers []string
// XKey is a public xkey for the authorization service.
// This will enable encryption for server requests and the authorization service responses.
XKeystring
// AllowedAccounts that will be delegated to the auth service.
// If empty then all accounts will be delegated.
AllowedAccounts []string
}
// Options block for nats-server.
// NOTE: This structure is no longer used for monitoring endpoints
// and json tags are deprecated and may be removed in the future.
typeOptionsstruct {
ConfigFilestring`json:"-"`
ServerNamestring`json:"server_name"`
Hoststring`json:"addr"`
Portint`json:"port"`
DontListenbool`json:"dont_listen"`
ClientAdvertisestring`json:"-"`
Tracebool`json:"-"`
Debugbool`json:"-"`
TraceVerbosebool`json:"-"`
// TraceHeaders if true will only trace message headers, not the payload
TraceHeadersbool`json:"-"`
NoLogbool`json:"-"`
NoSigsbool`json:"-"`
NoSublistCachebool`json:"-"`
NoHeaderSupportbool`json:"-"`
DisableShortFirstPingbool`json:"-"`
Logtimebool`json:"-"`
LogtimeUTCbool`json:"-"`
MaxConnint`json:"max_connections"`
MaxSubsint`json:"max_subscriptions,omitempty"`
MaxSubTokensuint8`json:"-"`
Nkeys []*NkeyUser`json:"-"`
Users []*User`json:"-"`
Accounts []*Account`json:"-"`
NoAuthUserstring`json:"-"`
DefaultSentinelstring`json:"-"`
SystemAccountstring`json:"-"`
NoSystemAccountbool`json:"-"`
Usernamestring`json:"-"`
Passwordstring`json:"-"`
Authorizationstring`json:"-"`
AuthCallout*AuthCallout`json:"-"`
PingInterval time.Duration`json:"ping_interval"`
MaxPingsOutint`json:"ping_max"`
HTTPHoststring`json:"http_host"`
HTTPPortint`json:"http_port"`
HTTPBasePathstring`json:"http_base_path"`
HTTPSPortint`json:"https_port"`
AuthTimeoutfloat64`json:"auth_timeout"`
MaxControlLineint32`json:"max_control_line"`
MaxPayloadint32`json:"max_payload"`
MaxPendingint64`json:"max_pending"`
NoFastProducerStallbool`json:"-"`
ClusterClusterOpts`json:"cluster,omitempty"`
GatewayGatewayOpts`json:"gateway,omitempty"`
LeafNodeLeafNodeOpts`json:"leaf,omitempty"`
JetStreambool`json:"jetstream"`
JetStreamStrictbool`json:"-"`
JetStreamMaxMemoryint64`json:"-"`
JetStreamMaxStoreint64`json:"-"`
JetStreamDomainstring`json:"-"`
JetStreamExtHintstring`json:"-"`
JetStreamKeystring`json:"-"`
JetStreamOldKeystring`json:"-"`
JetStreamCipherStoreCipher`json:"-"`
JetStreamUniqueTagstring
JetStreamLimitsJSLimitOpts
JetStreamTpmJSTpmOpts
JetStreamMaxCatchupint64
JetStreamRequestQueueLimitint64
StreamMaxBufferedMsgsint`json:"-"`
StreamMaxBufferedSizeint64`json:"-"`
StoreDirstring`json:"-"`
SyncInterval time.Duration`json:"-"`
SyncAlwaysbool`json:"-"`
JsAccDefaultDomainmap[string]string`json:"-"`// account to domain name mapping
WebsocketWebsocketOpts`json:"-"`
MQTTMQTTOpts`json:"-"`
ProfPortint`json:"-"`
ProfBlockRateint`json:"-"`
PidFilestring`json:"-"`
PortsFileDirstring`json:"-"`
LogFilestring`json:"-"`
LogSizeLimitint64`json:"-"`
LogMaxFilesint64`json:"-"`
Syslogbool`json:"-"`
RemoteSyslogstring`json:"-"`
Routes []*url.URL`json:"-"`
RoutesStrstring`json:"-"`
TLSTimeoutfloat64`json:"tls_timeout"`
TLSbool`json:"-"`
TLSVerifybool`json:"-"`
TLSMapbool`json:"-"`
TLSCertstring`json:"-"`
TLSKeystring`json:"-"`
TLSCaCertstring`json:"-"`
TLSConfig*tls.Config`json:"-"`
TLSPinnedCertsPinnedCertSet`json:"-"`
TLSRateLimitint64`json:"-"`
// When set to true, the server will perform the TLS handshake before
// sending the INFO protocol. For clients that are not configured
// with a similar option, their connection will fail with some sort
// of timeout or EOF error since they are expecting to receive an
// INFO protocol first.
TLSHandshakeFirstbool`json:"-"`
// If TLSHandshakeFirst is true and this value is strictly positive,
// the server will wait for that amount of time for the TLS handshake
// to start before falling back to previous behavior of sending the
// INFO protocol first. It allows for a mix of newer clients that can
// require a TLS handshake first, and older clients that can't.
TLSHandshakeFirstFallback time.Duration`json:"-"`
AllowNonTLSbool`json:"-"`
WriteDeadline time.Duration`json:"-"`
MaxClosedClientsint`json:"-"`
LameDuckDuration time.Duration`json:"-"`
LameDuckGracePeriod time.Duration`json:"-"`
// MaxTracedMsgLen is the maximum printable length for traced messages.
MaxTracedMsgLenint`json:"-"`
// Operating a trusted NATS server
TrustedKeys []string`json:"-"`
TrustedOperators []*jwt.OperatorClaims`json:"-"`
AccountResolverAccountResolver`json:"-"`
AccountResolverTLSConfig*tls.Config`json:"-"`
// AlwaysEnableNonce will always present a nonce to new connections
// typically used by custom Authentication implementations who embeds
// the server and so not presented as a configuration option
AlwaysEnableNoncebool
CustomClientAuthenticationAuthentication`json:"-"`
CustomRouterAuthenticationAuthentication`json:"-"`
// CheckConfig configuration file syntax test was successful and exit.
CheckConfigbool`json:"-"`
// DisableJetStreamBanner will not print the ascii art on startup for JetStream enabled servers
DisableJetStreamBannerbool`json:"-"`
// ConnectErrorReports specifies the number of failed attempts
// at which point server should report the failure of an initial
// connection to a route, gateway or leaf node.
// See DEFAULT_CONNECT_ERROR_REPORTS for default value.
ConnectErrorReportsint
// ReconnectErrorReports is similar to ConnectErrorReports except
// that this applies to reconnect events.
ReconnectErrorReportsint
// Tags describing the server. They will be included in varz
// and used as a filter criteria for some system requests.
Tags jwt.TagList`json:"-"`
// OCSPConfig enables OCSP Stapling in the server.
OCSPConfig*OCSPConfig
tlsConfigOpts*TLSConfigOpts
// private fields, used to know if bool options are explicitly
// defined in config and/or command line params.
inConfigmap[string]bool
inCmdLinemap[string]bool
// private fields for operator mode
operatorJWT []string
resolverPreloadsmap[string]string
resolverPinnedAccountsmap[string]struct{}
// private fields, used for testing
gatewaysSolicitDelay time.Duration
overrideProtoint
// JetStream
maxMemSetbool
maxStoreSetbool
syncSetbool
// OCSP Cache config enables next-gen cache for OCSP features
OCSPCacheConfig*OCSPResponseCacheConfig
// Used to mark that we had a top level authorization block.
authBlockDefinedbool
// configDigest represents the state of configuration.
configDigeststring
}
// WebsocketOpts are options for websocket
typeWebsocketOptsstruct {
// The server will accept websocket client connections on this hostname/IP.
Hoststring
// The server will accept websocket client connections on this port.
Portint
// The host:port to advertise to websocket clients in the cluster.
Advertisestring
// If no user name is provided when a client connects, will default to the
// matching user from the global list of users in `Options.Users`.
NoAuthUserstring
// Name of the cookie, which if present in WebSocket upgrade headers,
// will be treated as JWT during CONNECT phase as long as
// "jwt" specified in the CONNECT options is missing or empty.
JWTCookiestring
// Name of the cookie, which if present in WebSocket upgrade headers,
// will be treated as Username during CONNECT phase as long as
// "user" specified in the CONNECT options is missing or empty.
UsernameCookiestring
// Name of the cookie, which if present in WebSocket upgrade headers,
// will be treated as Password during CONNECT phase as long as
// "pass" specified in the CONNECT options is missing or empty.
PasswordCookiestring
// Name of the cookie, which if present in WebSocket upgrade headers,
// will be treated as Token during CONNECT phase as long as
// "auth_token" specified in the CONNECT options is missing or empty.
// Note that when this is useful for passing a JWT to an cuth callout
// when the server uses delegated authentication ("operator mode") or
// when using delegated authentication, but the auth callout validates some
// other JWT or string. Note that this does map to an actual server-wide
// "auth_token", note that using it for that purpose is greatly discouraged.
TokenCookiestring
// Authentication section. If anything is configured in this section,
// it will override the authorization configuration of regular clients.
Usernamestring
Passwordstring
Tokenstring
// Timeout for the authentication process.
AuthTimeoutfloat64
// By default the server will enforce the use of TLS. If no TLS configuration
// is provided, you need to explicitly set NoTLS to true to allow the server
// to start without TLS configuration. Note that if a TLS configuration is
// present, this boolean is ignored and the server will run the Websocket
// server with that TLS configuration.
// Running without TLS is less secure since Websocket clients that use bearer
// tokens will send them in clear. So this should not be used in production.
NoTLSbool
// TLS configuration is required.
TLSConfig*tls.Config
// If true, map certificate values for authentication purposes.
TLSMapbool
// When present, accepted client certificates (verify/verify_and_map) must be in this list
TLSPinnedCertsPinnedCertSet
// If true, the Origin header must match the request's host.
SameOriginbool
// Only origins in this list will be accepted. If empty and
// SameOrigin is false, any origin is accepted.
AllowedOrigins []string
// If set to true, the server will negotiate with clients
// if compression can be used. If this is false, no compression
// will be used (both in server and clients) since it has to
// be negotiated between both endpoints
Compressionbool
// Total time allowed for the server to read the client request
// and write the response back to the client. This include the
// time needed for the TLS Handshake.
HandshakeTimeout time.Duration
// Headers to be added to the upgrade response.
// Useful for adding custom headers like Strict-Transport-Security.
Headersmap[string]string
// Snapshot of configured TLS options.
tlsConfigOpts*TLSConfigOpts
}
// MQTTOpts are options for MQTT
typeMQTTOptsstruct {
// The server will accept MQTT client connections on this hostname/IP.
Hoststring
// The server will accept MQTT client connections on this port.
Portint
// If no user name is provided when a client connects, will default to the
// matching user from the global list of users in `Options.Users`.
NoAuthUserstring
// Authentication section. If anything is configured in this section,
// it will override the authorization configuration of regular clients.
Usernamestring
Passwordstring
Tokenstring
// JetStream domain mqtt is supposed to pick up
JsDomainstring
// Number of replicas for MQTT streams.
// Negative or 0 value means that the server(s) will pick a replica
// number based on the known size of the cluster (but capped at 3).
// Note that if an account was already connected, the stream's replica
// count is not modified. Use the NATS CLI to update the count if desired.
StreamReplicasint
// Number of replicas for MQTT consumers.
// Negative or 0 value means that there is no override and the consumer
// will have the same replica factor that the stream it belongs to.
// If a value is specified, it will require to be lower than the stream
// replicas count (lower than StreamReplicas if specified, but also lower
// than the automatic value determined by cluster size).
// Note that existing consumers are not modified.
//
// UPDATE: This is no longer used while messages stream has interest policy retention
// which requires consumer replica count to match the parent stream.
ConsumerReplicasint
// Indicate if the consumers should be created with memory storage.
// Note that existing consumers are not modified.
ConsumerMemoryStoragebool
// If specified will have the system auto-cleanup the consumers after being
// inactive for the specified amount of time.
ConsumerInactiveThreshold time.Duration
// Timeout for the authentication process.
AuthTimeoutfloat64
// TLS configuration is required.
TLSConfig*tls.Config
// If true, map certificate values for authentication purposes.
TLSMapbool
// Timeout for the TLS handshake
TLSTimeoutfloat64
// Set of allowable certificates
TLSPinnedCertsPinnedCertSet
// AckWait is the amount of time after which a QoS 1 or 2 message sent to a
// client is redelivered as a DUPLICATE if the server has not received the
// PUBACK on the original Packet Identifier. The same value applies to
// PubRel redelivery. The value has to be positive. Zero will cause the
// server to use the default value (30 seconds). Note that changes to this
// option is applied only to new MQTT subscriptions (or sessions for
// PubRels).
AckWait time.Duration
// MaxAckPending is the amount of QoS 1 and 2 messages (combined) the server
// can send to a subscription without receiving any PUBACK for those
// messages. The valid range is [0..65535].
//
// The total of subscriptions' MaxAckPending on a given session cannot
// exceed 65535. Attempting to create a subscription that would bring the
// total above the limit would result in the server returning 0x80 in the
// SUBACK for this subscription.
//
// Due to how the NATS Server handles the MQTT "#" wildcard, each
// subscription ending with "#" will use 2 times the MaxAckPending value.
// Note that changes to this option is applied only to new subscriptions.
MaxAckPendinguint16
// Snapshot of configured TLS options.
tlsConfigOpts*TLSConfigOpts
// rejectQoS2Pub tells the MQTT client to not accept QoS2 PUBLISH, instead
// error and terminate the connection.
rejectQoS2Pubbool
// downgradeQOS2Sub tells the MQTT client to downgrade QoS2 SUBSCRIBE
// requests to QoS1.
downgradeQoS2Subbool
}
typenetResolverinterface {
LookupHost(ctx context.Context, hoststring) ([]string, error)
}
// Clone performs a deep copy of the Options struct, returning a new clone
// with all values copied.
func (o*Options) Clone() *Options {
ifo==nil {
returnnil
}
clone:=&Options{}
*clone=*o
ifo.Users!=nil {
clone.Users=make([]*User, len(o.Users))
fori, user:=rangeo.Users {
clone.Users[i] =user.clone()
}
}
ifo.Nkeys!=nil {
clone.Nkeys=make([]*NkeyUser, len(o.Nkeys))
fori, nkey:=rangeo.Nkeys {
clone.Nkeys[i] =nkey.clone()
}
}
ifo.Routes!=nil {
clone.Routes=deepCopyURLs(o.Routes)
}
ifo.TLSConfig!=nil {
clone.TLSConfig=o.TLSConfig.Clone()
}
ifo.Cluster.TLSConfig!=nil {
clone.Cluster.TLSConfig=o.Cluster.TLSConfig.Clone()
}
ifo.Gateway.TLSConfig!=nil {
clone.Gateway.TLSConfig=o.Gateway.TLSConfig.Clone()
}
iflen(o.Gateway.Gateways) >0 {
clone.Gateway.Gateways=make([]*RemoteGatewayOpts, len(o.Gateway.Gateways))
fori, g:=rangeo.Gateway.Gateways {
clone.Gateway.Gateways[i] =g.clone()
}
}
// FIXME(dlc) - clone leaf node stuff.
returnclone
}
funcdeepCopyURLs(urls []*url.URL) []*url.URL {
ifurls==nil {
returnnil
}
curls:=make([]*url.URL, len(urls))
fori, u:=rangeurls {
cu:=&url.URL{}
*cu=*u
curls[i] =cu
}
returncurls
}
// Configuration file authorization section.
typeauthorizationstruct {
// Singles
userstring
passstring
tokenstring
nkeystring
accstring
// Multiple Nkeys/Users
nkeys []*NkeyUser
users []*User
timeoutfloat64
defaultPermissions*Permissions
// Auth Callouts
callout*AuthCallout
}
// TLSConfigOpts holds the parsed tls config information,
// used with flag parsing
typeTLSConfigOptsstruct {
CertFilestring
KeyFilestring
CaFilestring
Verifybool
Insecurebool
Mapbool
TLSCheckKnownURLsbool
HandshakeFirstbool// Indicate that the TLS handshake should occur first, before sending the INFO protocol.
FallbackDelay time.Duration// Where supported, indicates how long to wait for the handshake before falling back to sending the INFO protocol first.
Timeoutfloat64
RateLimitint64
Ciphers []uint16
CurvePreferences []tls.CurveID
PinnedCertsPinnedCertSet
CertStore certstore.StoreType
CertMatchBy certstore.MatchByType
CertMatchstring
CertMatchSkipInvalidbool
CaCertsMatch []string
OCSPPeerConfig*certidp.OCSPPeerConfig
Certificates []*TLSCertPairOpt
MinVersionuint16
}
// TLSCertPairOpt are the paths to a certificate and private key.
typeTLSCertPairOptstruct {
CertFilestring
KeyFilestring
}
// OCSPConfig represents the options of OCSP stapling options.
typeOCSPConfigstruct {
// Mode defines the policy for OCSP stapling.
ModeOCSPMode
// OverrideURLs is the http URL endpoint used to get OCSP staples.
OverrideURLs []string
}
vartlsUsage=`
TLS configuration is specified in the tls section of a configuration file:
e.g.
tls {
cert_file: "./certs/server-cert.pem"
key_file: "./certs/server-key.pem"
ca_file: "./certs/ca.pem"
verify: true
verify_and_map: true
cipher_suites: [
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
]
curve_preferences: [
"CurveP256",
"CurveP384",
"CurveP521"
]
}
Available cipher suites include:
`
// ProcessConfigFile processes a configuration file.
// FIXME(dlc): A bit hacky
funcProcessConfigFile(configFilestring) (*Options, error) {
opts:=&Options{}
iferr:=opts.ProcessConfigFile(configFile); err!=nil {
// If only warnings then continue and return the options.
ifcerr, ok:=err.(*processConfigErr); ok&&len(cerr.Errors()) ==0 {
returnopts, nil
}
returnnil, err
}
returnopts, nil
}
// token is an item parsed from the configuration.
typetokeninterface {
Value() any
Line() int
IsUsedVariable() bool
SourceFile() string
Position() int
}
// unwrapValue can be used to get the token and value from an item
// to be able to report the line number in case of an incorrect
// configuration.
// also stores the token in lastToken for use in convertPanicToError
funcunwrapValue(vany, lastToken*token) (token, any) {
switchtk:=v.(type) {
casetoken:
iflastToken!=nil {
*lastToken=tk
}
returntk, tk.Value()
default:
returnnil, v
}
}
// use in defer to recover from panic and turn it into an error associated with last token
funcconvertPanicToErrorList(lastToken*token, errors*[]error) {
// only recover if an error can be stored
iferrors==nil {
return
} elseiferr:=recover(); err==nil {
return
} elseiflastToken!=nil&&*lastToken!=nil {
*errors=append(*errors, &configErr{*lastToken, fmt.Sprint(err)})
} else {
*errors=append(*errors, fmt.Errorf("encountered panic without a token %v", err))
}
}
// use in defer to recover from panic and turn it into an error associated with last token
funcconvertPanicToError(lastToken*token, e*error) {
// only recover if an error can be stored
ife==nil||*e!=nil {
return
} elseiferr:=recover(); err==nil {
return
} elseiflastToken!=nil&&*lastToken!=nil {
*e=&configErr{*lastToken, fmt.Sprint(err)}
} else {
*e=fmt.Errorf("%v", err)
}
}
// configureSystemAccount configures a system account
// if present in the configuration.
funcconfigureSystemAccount(o*Options, mmap[string]any) (retErrerror) {
varlttoken
deferconvertPanicToError(<, &retErr)
configure:=func(vany) error {
tk, v:=unwrapValue(v, <)
sa, ok:=v.(string)
if!ok {
return&configErr{tk, "system account name must be a string"}
}
o.SystemAccount=sa
returnnil
}
ifv, ok:=m["system_account"]; ok {
returnconfigure(v)
} elseifv, ok:=m["system"]; ok {
returnconfigure(v)
}
returnnil
}
// ProcessConfigFile updates the Options structure with options
// present in the given configuration file.
// This version is convenient if one wants to set some default
// options and then override them with what is in the config file.
// For instance, this version allows you to do something such as:
//
// opts := &Options{Debug: true}
// opts.ProcessConfigFile(myConfigFile)
//
// If the config file contains "debug: false", after this call,
// opts.Debug would really be false. It would be impossible to
// achieve that with the non receiver ProcessConfigFile() version,
// since one would not know after the call if "debug" was not present
// or was present but set to false.
func (o*Options) ProcessConfigFile(configFilestring) error {
o.ConfigFile=configFile
ifconfigFile==_EMPTY_ {
returnnil
}
m, digest, err:=conf.ParseFileWithChecksDigest(configFile)
iferr!=nil {
returnerr
}
o.configDigest=digest
returno.processConfigFile(configFile, m)
}
// ProcessConfigString is the same as ProcessConfigFile, but expects the
// contents of the config file to be passed in rather than the file name.
func (o*Options) ProcessConfigString(datastring) error {
m, err:=conf.ParseWithChecks(data)
iferr!=nil {
returnerr
}
returno.processConfigFile(_EMPTY_, m)
}
// ConfigDigest returns the digest representing the configuration.
func (o*Options) ConfigDigest() string {
returno.configDigest
}
func (o*Options) processConfigFile(configFilestring, mmap[string]any) error {
// Collect all errors and warnings and report them all together.
errors:=make([]error, 0)
warnings:=make([]error, 0)
iflen(m) ==0 {
warnings=append(warnings, fmt.Errorf("%s: config has no values or is empty", configFile))
}
// First check whether a system account has been defined,
// as that is a condition for other features to be enabled.
iferr:=configureSystemAccount(o, m); err!=nil {
errors=append(errors, err)
}
fork, v:=rangem {
o.processConfigFileLine(k, v, &errors, &warnings)
}
// Post-process: check auth callout allowed accounts against configured accounts.
ifo.AuthCallout!=nil {
accounts:=make(map[string]struct{})
for_, acc:=rangeo.Accounts {
accounts[acc.Name] =struct{}{}
}
for_, acc:=rangeo.AuthCallout.AllowedAccounts {
if_, ok:=accounts[acc]; !ok {
err:=&configErr{nil, fmt.Sprintf("auth_callout allowed account %q not found in configured accounts", acc)}
errors=append(errors, err)
}
}
}
iflen(errors) >0||len(warnings) >0 {
return&processConfigErr{
errors: errors,
warnings: warnings,
}
}
returnnil
}
func (o*Options) processConfigFileLine(kstring, vany, errors*[]error, warnings*[]error) {
varlttoken
deferconvertPanicToErrorList(<, errors)
tk, v:=unwrapValue(v, <)
switchstrings.ToLower(k) {
case"listen":
hp, err:=parseListen(v)
iferr!=nil {
*errors=append(*errors, &configErr{tk, err.Error()})
return
}
o.Host=hp.host
o.Port=hp.port
case"client_advertise":
o.ClientAdvertise=v.(string)
case"port":
o.Port=int(v.(int64))
case"server_name":
sn:=v.(string)
ifstrings.Contains(sn, " ") {
err:=&configErr{tk, ErrServerNameHasSpaces.Error()}
*errors=append(*errors, err)
return
}
o.ServerName=sn
case"host", "net":
o.Host=v.(string)
case"debug":
o.Debug=v.(bool)
trackExplicitVal(&o.inConfig, "Debug", o.Debug)
case"trace":