| 1 |
// Copyright 2012-2025 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package server |
| 15 |
|
| 16 |
import ( |
| 17 |
"context" |
| 18 |
"crypto/fips140" |
| 19 |
"crypto/tls" |
| 20 |
"crypto/x509" |
| 21 |
"errors" |
| 22 |
"flag" |
| 23 |
"fmt" |
| 24 |
"math" |
| 25 |
"net" |
| 26 |
"net/url" |
| 27 |
"os" |
| 28 |
"path" |
| 29 |
"path/filepath" |
| 30 |
"reflect" |
| 31 |
"regexp" |
| 32 |
"runtime" |
| 33 |
"strconv" |
| 34 |
"strings" |
| 35 |
"sync/atomic" |
| 36 |
"time" |
| 37 |
|
| 38 |
"github.com/nats-io/jwt/v2" |
| 39 |
"github.com/nats-io/nats-server/v2/conf" |
| 40 |
"github.com/nats-io/nats-server/v2/server/certidp" |
| 41 |
"github.com/nats-io/nats-server/v2/server/certstore" |
| 42 |
"github.com/nats-io/nkeys" |
| 43 |
) |
| 44 |
|
| 45 |
var allowUnknownTopLevelField = int32(0) |
| 46 |
|
| 47 |
// NoErrOnUnknownFields can be used to change the behavior the processing |
| 48 |
// of a configuration file. By default, an error is reported if unknown |
| 49 |
// fields are found. If `noError` is set to true, no error will be reported |
| 50 |
// if top-level unknown fields are found. |
| 51 |
func NoErrOnUnknownFields(noError bool) { |
| 52 |
var val int32 |
| 53 |
if noError { |
| 54 |
val = int32(1) |
| 55 |
} |
| 56 |
atomic.StoreInt32(&allowUnknownTopLevelField, val) |
| 57 |
} |
| 58 |
|
| 59 |
// PinnedCertSet is a set of lower case hex-encoded sha256 of DER encoded SubjectPublicKeyInfo |
| 60 |
type PinnedCertSet map[string]struct{} |
| 61 |
|
| 62 |
// ClusterOpts are options for clusters. |
| 63 |
// NOTE: This structure is no longer used for monitoring endpoints |
| 64 |
// and json tags are deprecated and may be removed in the future. |
| 65 |
type ClusterOpts struct { |
| 66 |
Name string `json:"-"` |
| 67 |
Host string `json:"addr,omitempty"` |
| 68 |
Port int `json:"cluster_port,omitempty"` |
| 69 |
Username string `json:"-"` |
| 70 |
Password string `json:"-"` |
| 71 |
AuthTimeout float64 `json:"auth_timeout,omitempty"` |
| 72 |
Permissions *RoutePermissions `json:"-"` |
| 73 |
TLSTimeout float64 `json:"-"` |
| 74 |
TLSConfig *tls.Config `json:"-"` |
| 75 |
TLSMap bool `json:"-"` |
| 76 |
TLSCheckKnownURLs bool `json:"-"` |
| 77 |
TLSPinnedCerts PinnedCertSet `json:"-"` |
| 78 |
ListenStr string `json:"-"` |
| 79 |
Advertise string `json:"-"` |
| 80 |
NoAdvertise bool `json:"-"` |
| 81 |
ConnectRetries int `json:"-"` |
| 82 |
ConnectBackoff bool `json:"-"` |
| 83 |
PoolSize int `json:"-"` |
| 84 |
PinnedAccounts []string `json:"-"` |
| 85 |
Compression CompressionOpts `json:"-"` |
| 86 |
PingInterval time.Duration `json:"-"` |
| 87 |
MaxPingsOut int `json:"-"` |
| 88 |
WriteDeadline time.Duration `json:"-"` |
| 89 |
WriteTimeout WriteTimeoutPolicy `json:"-"` |
| 90 |
|
| 91 |
// Not exported (used in tests) |
| 92 |
resolver netResolver |
| 93 |
// Snapshot of configured TLS options. |
| 94 |
tlsConfigOpts *TLSConfigOpts |
| 95 |
} |
| 96 |
|
| 97 |
// CompressionOpts defines the compression mode and optional configuration. |
| 98 |
type CompressionOpts struct { |
| 99 |
Mode string |
| 100 |
// If `Mode` is set to CompressionS2Auto, RTTThresholds provides the |
| 101 |
// thresholds at which the compression level will go from |
| 102 |
// CompressionS2Uncompressed to CompressionS2Fast, CompressionS2Better |
| 103 |
// or CompressionS2Best. If a given level is not desired, specify 0 |
| 104 |
// for this slot. For instance, the slice []{0, 10ms, 20ms} means that |
| 105 |
// for any RTT up to 10ms included the compression level will be |
| 106 |
// CompressionS2Fast, then from ]10ms..20ms], the level will be selected |
| 107 |
// as CompressionS2Better. Anything above 20ms will result in picking |
| 108 |
// the CompressionS2Best compression level. |
| 109 |
RTTThresholds []time.Duration |
| 110 |
} |
| 111 |
|
| 112 |
func (c1 *CompressionOpts) equals(c2 *CompressionOpts) bool { |
| 113 |
if c1 == c2 { |
| 114 |
return true |
| 115 |
} |
| 116 |
if (c1 == nil && c2 != nil) || (c1 != nil && c2 == nil) { |
| 117 |
return false |
| 118 |
} |
| 119 |
if c1.Mode != c2.Mode { |
| 120 |
return false |
| 121 |
} |
| 122 |
// For s2_auto, if one has an empty RTTThresholds, it is equivalent |
| 123 |
// to the defaultCompressionS2AutoRTTThresholds array, so compare with that. |
| 124 |
if c1.Mode == CompressionS2Auto { |
| 125 |
rtts1 := c1.RTTThresholds |
| 126 |
if len(rtts1) == 0 { |
| 127 |
rtts1 = defaultCompressionS2AutoRTTThresholds |
| 128 |
} |
| 129 |
rtts2 := c2.RTTThresholds |
| 130 |
if len(rtts2) == 0 { |
| 131 |
rtts2 = defaultCompressionS2AutoRTTThresholds |
| 132 |
} |
| 133 |
if !reflect.DeepEqual(rtts1, rtts2) { |
| 134 |
return false |
| 135 |
} |
| 136 |
} |
| 137 |
return true |
| 138 |
} |
| 139 |
|
| 140 |
// GatewayOpts are options for gateways. |
| 141 |
// NOTE: This structure is no longer used for monitoring endpoints |
| 142 |
// and json tags are deprecated and may be removed in the future. |
| 143 |
type GatewayOpts struct { |
| 144 |
Name string `json:"name"` |
| 145 |
Host string `json:"addr,omitempty"` |
| 146 |
Port int `json:"port,omitempty"` |
| 147 |
Username string `json:"-"` |
| 148 |
Password string `json:"-"` |
| 149 |
AuthTimeout float64 `json:"auth_timeout,omitempty"` |
| 150 |
TLSConfig *tls.Config `json:"-"` |
| 151 |
TLSTimeout float64 `json:"tls_timeout,omitempty"` |
| 152 |
TLSMap bool `json:"-"` |
| 153 |
TLSCheckKnownURLs bool `json:"-"` |
| 154 |
TLSPinnedCerts PinnedCertSet `json:"-"` |
| 155 |
Advertise string `json:"advertise,omitempty"` |
| 156 |
ConnectRetries int `json:"connect_retries,omitempty"` |
| 157 |
ConnectBackoff bool `json:"connect_backoff,omitempty"` |
| 158 |
Gateways []*RemoteGatewayOpts `json:"gateways,omitempty"` |
| 159 |
RejectUnknown bool `json:"reject_unknown,omitempty"` // config got renamed to reject_unknown_cluster |
| 160 |
WriteDeadline time.Duration `json:"-"` |
| 161 |
WriteTimeout WriteTimeoutPolicy `json:"-"` |
| 162 |
|
| 163 |
// Not exported, for tests. |
| 164 |
resolver netResolver |
| 165 |
sendQSubsBufSize int |
| 166 |
|
| 167 |
// Snapshot of configured TLS options. |
| 168 |
tlsConfigOpts *TLSConfigOpts |
| 169 |
} |
| 170 |
|
| 171 |
// RemoteGatewayOpts are options for connecting to a remote gateway |
| 172 |
// NOTE: This structure is no longer used for monitoring endpoints |
| 173 |
// and json tags are deprecated and may be removed in the future. |
| 174 |
type RemoteGatewayOpts struct { |
| 175 |
Name string `json:"name"` |
| 176 |
TLSConfig *tls.Config `json:"-"` |
| 177 |
TLSTimeout float64 `json:"tls_timeout,omitempty"` |
| 178 |
URLs []*url.URL `json:"urls,omitempty"` |
| 179 |
tlsConfigOpts *TLSConfigOpts |
| 180 |
} |
| 181 |
|
| 182 |
// LeafNodeOpts are options for a given server to accept leaf node connections and/or connect to a remote cluster. |
| 183 |
type LeafNodeOpts struct { |
| 184 |
Host string `json:"addr,omitempty"` |
| 185 |
Port int `json:"port,omitempty"` |
| 186 |
Username string `json:"-"` |
| 187 |
Password string `json:"-"` |
| 188 |
ProxyRequired bool `json:"-"` |
| 189 |
Nkey string `json:"-"` |
| 190 |
Account string `json:"-"` |
| 191 |
Users []*User `json:"-"` |
| 192 |
AuthTimeout float64 `json:"auth_timeout,omitempty"` |
| 193 |
TLSConfig *tls.Config `json:"-"` |
| 194 |
TLSTimeout float64 `json:"tls_timeout,omitempty"` |
| 195 |
TLSMap bool `json:"-"` |
| 196 |
TLSPinnedCerts PinnedCertSet `json:"-"` |
| 197 |
// When set to true, the server will perform the TLS handshake before |
| 198 |
// sending the INFO protocol. For remote leafnodes that are not configured |
| 199 |
// with a similar option, their connection will fail with some sort |
| 200 |
// of timeout or EOF error since they are expecting to receive an |
| 201 |
// INFO protocol first. |
| 202 |
TLSHandshakeFirst bool `json:"-"` |
| 203 |
// If TLSHandshakeFirst is true and this value is strictly positive, |
| 204 |
// the server will wait for that amount of time for the TLS handshake |
| 205 |
// to start before falling back to previous behavior of sending the |
| 206 |
// INFO protocol first. It allows for a mix of newer remote leafnodes |
| 207 |
// that can require a TLS handshake first, and older that can't. |
| 208 |
TLSHandshakeFirstFallback time.Duration `json:"-"` |
| 209 |
Advertise string `json:"-"` |
| 210 |
NoAdvertise bool `json:"-"` |
| 211 |
ReconnectInterval time.Duration `json:"-"` |
| 212 |
WriteDeadline time.Duration `json:"-"` |
| 213 |
WriteTimeout WriteTimeoutPolicy `json:"-"` |
| 214 |
|
| 215 |
// Compression options |
| 216 |
Compression CompressionOpts `json:"-"` |
| 217 |
|
| 218 |
// For solicited connections to other clusters/superclusters. |
| 219 |
Remotes []*RemoteLeafOpts `json:"remotes,omitempty"` |
| 220 |
|
| 221 |
// This is the minimum version that is accepted for remote connections. |
| 222 |
// Note that since the server version in the CONNECT protocol was added |
| 223 |
// only starting at v2.8.0, any version below that will be rejected |
| 224 |
// (since empty version string in CONNECT would fail the "version at |
| 225 |
// least" test). |
| 226 |
MinVersion string |
| 227 |
|
| 228 |
// Isolate subject interest from other leafnode connections, preventing |
| 229 |
// east-west propagation. |
| 230 |
IsolateLeafnodeInterest bool `json:"-"` |
| 231 |
|
| 232 |
// DialTimeout is the amount of time the server will wait for the TCP |
| 233 |
// connection to a remote server to be established. This is useful on high |
| 234 |
// latency links where the default (DEFAULT_ROUTE_DIAL, 1 second) is not |
| 235 |
// enough for the handshake to complete. It applies to all remotes, but can |
| 236 |
// be overridden on a per-remote basis with RemoteLeafOpts.DialTimeout. |
| 237 |
// If not set (or <= 0), DEFAULT_ROUTE_DIAL is used. |
| 238 |
DialTimeout time.Duration `json:"-"` |
| 239 |
|
| 240 |
// Not exported, for tests. |
| 241 |
resolver netResolver |
| 242 |
connDelay time.Duration |
| 243 |
dialer leafNodeDialer |
| 244 |
|
| 245 |
// Snapshot of configured TLS options. |
| 246 |
tlsConfigOpts *TLSConfigOpts |
| 247 |
} |
| 248 |
|
| 249 |
// SignatureHandler is used to sign a nonce from the server while |
| 250 |
// authenticating with Nkeys. The callback should sign the nonce and |
| 251 |
// return the JWT and the raw signature. |
| 252 |
type SignatureHandler func([]byte) (string, []byte, error) |
| 253 |
|
| 254 |
// RemoteLeafOpts are options for connecting to a remote server as a leaf node. |
| 255 |
type RemoteLeafOpts struct { |
| 256 |
LocalAccount string `json:"local_account,omitempty"` |
| 257 |
NoRandomize bool `json:"-"` |
| 258 |
URLs []*url.URL `json:"urls,omitempty"` |
| 259 |
Credentials string `json:"-"` |
| 260 |
Nkey string `json:"-"` |
| 261 |
SignatureCB SignatureHandler `json:"-"` |
| 262 |
TLS bool `json:"-"` |
| 263 |
TLSConfig *tls.Config `json:"-"` |
| 264 |
TLSTimeout float64 `json:"tls_timeout,omitempty"` |
| 265 |
TLSHandshakeFirst bool `json:"-"` |
| 266 |
Hub bool `json:"hub,omitempty"` |
| 267 |
DenyImports []string `json:"-"` |
| 268 |
DenyExports []string `json:"-"` |
| 269 |
|
| 270 |
// FirstInfoTimeout is the amount of time the server will wait for the |
| 271 |
// initial INFO protocol from the remote server before closing the |
| 272 |
// connection. |
| 273 |
FirstInfoTimeout time.Duration `json:"-"` |
| 274 |
|
| 275 |
// DialTimeout is the amount of time the server will wait for the TCP |
| 276 |
// connection to this remote server to be established. This is useful on |
| 277 |
// high latency links where the default is not enough for the handshake to |
| 278 |
// complete. If not set (or <= 0), the server-wide LeafNodeOpts.DialTimeout |
| 279 |
// is used, which itself defaults to DEFAULT_ROUTE_DIAL (1 second). |
| 280 |
DialTimeout time.Duration `json:"-"` |
| 281 |
|
| 282 |
// Compression options for this remote. Each remote could have a different |
| 283 |
// setting and also be different from the LeafNode options. |
| 284 |
Compression CompressionOpts `json:"-"` |
| 285 |
|
| 286 |
// When an URL has the "ws" (or "wss") scheme, then the server will initiate the |
| 287 |
// connection as a websocket connection. By default, the websocket frames will be |
| 288 |
// masked (as if this server was a websocket client to the remote server). The |
| 289 |
// NoMasking option will change this behavior and will send umasked frames. |
| 290 |
Websocket struct { |
| 291 |
Compression bool `json:"-"` |
| 292 |
NoMasking bool `json:"-"` |
| 293 |
} |
| 294 |
|
| 295 |
// HTTP Proxy configuration for WebSocket connections |
| 296 |
Proxy struct { |
| 297 |
// URL of the HTTP proxy server (e.g., "http://proxy.example.com:8080") |
| 298 |
URL string `json:"-"` |
| 299 |
// Username for proxy authentication |
| 300 |
Username string `json:"-"` |
| 301 |
// Password for proxy authentication |
| 302 |
Password string `json:"-"` |
| 303 |
// Timeout for proxy connection |
| 304 |
Timeout time.Duration `json:"-"` |
| 305 |
} |
| 306 |
|
| 307 |
tlsConfigOpts *TLSConfigOpts |
| 308 |
|
| 309 |
// If we are clustered and our local account has JetStream, if apps are accessing |
| 310 |
// a stream or consumer leader through this LN and it gets dropped, the apps will |
| 311 |
// not be able to work. This tells the system to migrate the leaders away from this server. |
| 312 |
// This only changes leader for R>1 assets. |
| 313 |
JetStreamClusterMigrate bool `json:"jetstream_cluster_migrate,omitempty"` |
| 314 |
|
| 315 |
// If JetStreamClusterMigrate is set to true, this is the time after which the leader |
| 316 |
// will be migrated away from this server if still disconnected. |
| 317 |
JetStreamClusterMigrateDelay time.Duration `json:"jetstream_cluster_migrate_delay,omitempty"` |
| 318 |
|
| 319 |
// LocalIsolation isolates this remote from east-west subject interest originating locally. |
| 320 |
LocalIsolation bool `json:"local_isolation,omitempty"` |
| 321 |
|
| 322 |
// RequestIsolation asks the remote side to isolate us from their east-west subject interest. |
| 323 |
RequestIsolation bool `json:"request_isolation,omitempty"` |
| 324 |
|
| 325 |
// If this is set to true, the connection to this remote will not be solicited. |
| 326 |
// During a configuration reload, if this is changed from `false` to `true`, the |
| 327 |
// existing connection will be closed and not solicited again (until it is changed |
| 328 |
// to `false` again. |
| 329 |
Disabled bool `json:"-"` |
| 330 |
|
| 331 |
// If this is set to true, this remote will ignore any server leafnode URLs |
| 332 |
// returned by the hub, allowing the user to fully manage the servers this |
| 333 |
// remote can connect to. |
| 334 |
IgnoreDiscoveredServers bool `json:"-"` |
| 335 |
} |
| 336 |
|
| 337 |
// Returns a string representation of this `RemoteLeafOpts` object, containing |
| 338 |
// the URLs (unredacted), the account (or "$G" if none is specified) and, if present, |
| 339 |
// the credentials filename. |
| 340 |
func (r *RemoteLeafOpts) name() string { |
| 341 |
return generateRemoteLeafOptsName(r, false) |
| 342 |
} |
| 343 |
|
| 344 |
// Same than RemoteLeafOpts.name() but uses redacted URLs. This is to be used for logging. |
| 345 |
func (r *RemoteLeafOpts) safeName() string { |
| 346 |
return generateRemoteLeafOptsName(r, true) |
| 347 |
} |
| 348 |
|
| 349 |
func generateRemoteLeafOptsName(r *RemoteLeafOpts, redacted bool) string { |
| 350 |
acc := r.LocalAccount |
| 351 |
if acc == _EMPTY_ { |
| 352 |
acc = globalAccountName |
| 353 |
} |
| 354 |
var optional string |
| 355 |
// There could be Credentials or NKey, not both (would be caught as a misconfig) |
| 356 |
if c := r.Credentials; c != _EMPTY_ { |
| 357 |
optional = fmt.Sprintf(", credentials=%q", c) |
| 358 |
} else if nk := r.Nkey; nk != _EMPTY_ { |
| 359 |
if redacted { |
| 360 |
optional = ", nkey=\"[REDACTED]\"" |
| 361 |
} else { |
| 362 |
optional = fmt.Sprintf(", nkey=%q", nk) |
| 363 |
} |
| 364 |
} |
| 365 |
var urls []*url.URL |
| 366 |
if redacted { |
| 367 |
urls = redactURLList(r.URLs) |
| 368 |
} else { |
| 369 |
urls = r.URLs |
| 370 |
} |
| 371 |
return fmt.Sprintf("urls=%q, account=%q%s", urls, acc, optional) |
| 372 |
} |
| 373 |
|
| 374 |
// JSLimitOpts are active limits for the meta cluster |
| 375 |
type JSLimitOpts struct { |
| 376 |
MaxRequestBatch int `json:"max_request_batch,omitempty"` // MaxRequestBatch is the maximum amount of updates that can be sent in a batch |
| 377 |
MaxAckPending int `json:"max_ack_pending,omitempty"` // MaxAckPending is the server limit for maximum amount of outstanding Acks |
| 378 |
MaxHAAssets int `json:"max_ha_assets,omitempty"` // MaxHAAssets is the maximum of Streams and Consumers that may have more than 1 replica |
| 379 |
Duplicates time.Duration `json:"max_duplicate_window,omitempty"` // Duplicates is the maximum value for duplicate tracking on Streams |
| 380 |
MaxBatchInflightPerStream int `json:"max_batch_inflight_per_stream,omitempty"` // MaxBatchInflightPerStream is the maximum amount of open batches per stream |
| 381 |
MaxBatchInflightTotal int `json:"max_batch_inflight_total,omitempty"` // MaxBatchInflightTotal is the maximum amount of total open batches per server |
| 382 |
MaxBatchSize int `json:"max_batch_size,omitempty"` // MaxBatchSize is the maximum amount of messages allowed in a batch publish to a Stream |
| 383 |
MaxBatchTimeout time.Duration `json:"max_batch_timeout,omitempty"` // MaxBatchTimeout is the maximum time to receive the commit message after receiving the first message of a batch |
| 384 |
} |
| 385 |
|
| 386 |
type JSTpmOpts struct { |
| 387 |
KeysFile string |
| 388 |
KeyPassword string |
| 389 |
SrkPassword string |
| 390 |
Pcr int |
| 391 |
} |
| 392 |
|
| 393 |
// AuthCallout option used to map external AuthN to NATS based AuthZ. |
| 394 |
type AuthCallout struct { |
| 395 |
// Must be a public account Nkey. |
| 396 |
Issuer string |
| 397 |
// Account to be used for sending requests. |
| 398 |
Account string |
| 399 |
// Users that will bypass auth_callout and be used for the auth service itself. |
| 400 |
AuthUsers []string |
| 401 |
// XKey is a public xkey for the authorization service. |
| 402 |
// This will enable encryption for server requests and the authorization service responses. |
| 403 |
XKey string |
| 404 |
// AllowedAccounts that will be delegated to the auth service. |
| 405 |
// If empty then all accounts will be delegated. |
| 406 |
AllowedAccounts []string |
| 407 |
} |
| 408 |
|
| 409 |
// Options block for nats-server. |
| 410 |
// NOTE: This structure is no longer used for monitoring endpoints |
| 411 |
// and json tags are deprecated and may be removed in the future. |
| 412 |
type Options struct { |
| 413 |
ConfigFile string `json:"-"` |
| 414 |
ServerName string `json:"server_name"` |
| 415 |
Host string `json:"addr"` |
| 416 |
Port int `json:"port"` |
| 417 |
DontListen bool `json:"dont_listen"` |
| 418 |
ClientAdvertise string `json:"-"` |
| 419 |
Trace bool `json:"-"` |
| 420 |
Debug bool `json:"-"` |
| 421 |
TraceVerbose bool `json:"-"` |
| 422 |
|
| 423 |
// TraceHeaders if true will only trace message headers, not the payload. |
| 424 |
TraceHeaders bool `json:"-"` |
| 425 |
NoLog bool `json:"-"` |
| 426 |
NoSigs bool `json:"-"` |
| 427 |
NoSublistCache bool `json:"-"` |
| 428 |
NoHeaderSupport bool `json:"-"` |
| 429 |
DisableShortFirstPing bool `json:"-"` |
| 430 |
Logtime bool `json:"-"` |
| 431 |
LogtimeUTC bool `json:"-"` |
| 432 |
MaxConn int `json:"max_connections"` |
| 433 |
MaxSubs int `json:"max_subscriptions,omitempty"` |
| 434 |
MaxSubTokens uint8 `json:"-"` |
| 435 |
Nkeys []*NkeyUser `json:"-"` |
| 436 |
Users []*User `json:"-"` |
| 437 |
Accounts []*Account `json:"-"` |
| 438 |
NoAuthUser string `json:"-"` |
| 439 |
DefaultSentinel string `json:"-"` |
| 440 |
SystemAccount string `json:"-"` |
| 441 |
NoSystemAccount bool `json:"-"` |
| 442 |
Username string `json:"-"` |
| 443 |
Password string `json:"-"` |
| 444 |
ProxyRequired bool `json:"-"` |
| 445 |
ProxyProtocol bool `json:"-"` |
| 446 |
Authorization string `json:"-"` |
| 447 |
AuthCallout *AuthCallout `json:"-"` |
| 448 |
PingInterval time.Duration `json:"ping_interval"` |
| 449 |
MaxPingsOut int `json:"ping_max"` |
| 450 |
HTTPHost string `json:"http_host"` |
| 451 |
HTTPPort int `json:"http_port"` |
| 452 |
HTTPBasePath string `json:"http_base_path"` |
| 453 |
HTTPSPort int `json:"https_port"` |
| 454 |
AuthTimeout float64 `json:"auth_timeout"` |
| 455 |
MaxControlLine int32 `json:"max_control_line"` |
| 456 |
MaxPayload int32 `json:"max_payload"` |
| 457 |
MaxPending int64 `json:"max_pending"` |
| 458 |
NoFastProducerStall bool `json:"-"` |
| 459 |
Cluster ClusterOpts `json:"cluster,omitempty"` |
| 460 |
Gateway GatewayOpts `json:"gateway,omitempty"` |
| 461 |
LeafNode LeafNodeOpts `json:"leaf,omitempty"` |
| 462 |
JetStream bool `json:"jetstream"` |
| 463 |
NoJetStreamStrict bool `json:"-"` // Strict by default. |
| 464 |
JetStreamMaxMemory int64 `json:"-"` |
| 465 |
JetStreamMaxStore int64 `json:"-"` |
| 466 |
JetStreamDomain string `json:"-"` |
| 467 |
JetStreamExtHint string `json:"-"` |
| 468 |
JetStreamKey string `json:"-"` |
| 469 |
JetStreamOldKey string `json:"-"` |
| 470 |
JetStreamCipher StoreCipher `json:"-"` |
| 471 |
JetStreamUniqueTag string |
| 472 |
JetStreamLimits JSLimitOpts |
| 473 |
JetStreamTpm JSTpmOpts |
| 474 |
JetStreamMaxCatchup int64 |
| 475 |
JetStreamRequestQueueLimit int64 |
| 476 |
JetStreamInfoQueueLimit int64 |
| 477 |
JetStreamMetaCompact uint64 |
| 478 |
JetStreamMetaCompactSize uint64 |
| 479 |
JetStreamMetaCompactSync bool |
| 480 |
JetStreamConcurrentIOs int |
| 481 |
StreamMaxBufferedMsgs int `json:"-"` |
| 482 |
StreamMaxBufferedSize int64 `json:"-"` |
| 483 |
StoreDir string `json:"-"` |
| 484 |
SyncInterval time.Duration `json:"-"` |
| 485 |
SyncAlways bool `json:"-"` |
| 486 |
JsAccDefaultDomain map[string]string `json:"-"` // account to domain name mapping |
| 487 |
Websocket WebsocketOpts `json:"-"` |
| 488 |
MQTT MQTTOpts `json:"-"` |
| 489 |
ProfPort int `json:"-"` |
| 490 |
ProfBlockRate int `json:"-"` |
| 491 |
PidFile string `json:"-"` |
| 492 |
PortsFileDir string `json:"-"` |
| 493 |
LogFile string `json:"-"` |
| 494 |
LogSizeLimit int64 `json:"-"` |
| 495 |
LogMaxFiles int64 `json:"-"` |
| 496 |
Syslog bool `json:"-"` |
| 497 |
RemoteSyslog string `json:"-"` |
| 498 |
Routes []*url.URL `json:"-"` |
| 499 |
RoutesStr string `json:"-"` |
| 500 |
TLSTimeout float64 `json:"tls_timeout"` |
| 501 |
TLS bool `json:"-"` |
| 502 |
TLSVerify bool `json:"-"` |
| 503 |
TLSMap bool `json:"-"` |
| 504 |
TLSCert string `json:"-"` |
| 505 |
TLSKey string `json:"-"` |
| 506 |
TLSCaCert string `json:"-"` |
| 507 |
TLSConfig *tls.Config `json:"-"` |
| 508 |
TLSPinnedCerts PinnedCertSet `json:"-"` |
| 509 |
TLSRateLimit int64 `json:"-"` |
| 510 |
// When set to true, the server will perform the TLS handshake before |
| 511 |
// sending the INFO protocol. For clients that are not configured |
| 512 |
// with a similar option, their connection will fail with some sort |
| 513 |
// of timeout or EOF error since they are expecting to receive an |
| 514 |
// INFO protocol first. |
| 515 |
TLSHandshakeFirst bool `json:"-"` |
| 516 |
// If TLSHandshakeFirst is true and this value is strictly positive, |
| 517 |
// the server will wait for that amount of time for the TLS handshake |
| 518 |
// to start before falling back to previous behavior of sending the |
| 519 |
// INFO protocol first. It allows for a mix of newer clients that can |
| 520 |
// require a TLS handshake first, and older clients that can't. |
| 521 |
TLSHandshakeFirstFallback time.Duration `json:"-"` |
| 522 |
AllowNonTLS bool `json:"-"` |
| 523 |
WriteDeadline time.Duration `json:"-"` |
| 524 |
WriteTimeout WriteTimeoutPolicy `json:"-"` |
| 525 |
MaxClosedClients int `json:"-"` |
| 526 |
LameDuckDuration time.Duration `json:"-"` |
| 527 |
LameDuckGracePeriod time.Duration `json:"-"` |
| 528 |
|
| 529 |
// MaxTracedMsgLen is the maximum printable length for traced messages. |
| 530 |
MaxTracedMsgLen int `json:"-"` |
| 531 |
|
| 532 |
// Operating a trusted NATS server |
| 533 |
TrustedKeys []string `json:"-"` |
| 534 |
TrustedOperators []*jwt.OperatorClaims `json:"-"` |
| 535 |
AccountResolver AccountResolver `json:"-"` |
| 536 |
AccountResolverTLSConfig *tls.Config `json:"-"` |
| 537 |
|
| 538 |
// AlwaysEnableNonce will always present a nonce to new connections |
| 539 |
// typically used by custom Authentication implementations who embeds |
| 540 |
// the server and so not presented as a configuration option |
| 541 |
AlwaysEnableNonce bool |
| 542 |
|
| 543 |
CustomClientAuthentication Authentication `json:"-"` |
| 544 |
CustomRouterAuthentication Authentication `json:"-"` |
| 545 |
|
| 546 |
// CheckConfig configuration file syntax test was successful and exit. |
| 547 |
CheckConfig bool `json:"-"` |
| 548 |
|
| 549 |
// DisableJetStreamBanner will not print the ascii art on startup for JetStream enabled servers |
| 550 |
DisableJetStreamBanner bool `json:"-"` |
| 551 |
|
| 552 |
// ConnectErrorReports specifies the number of failed attempts |
| 553 |
// at which point server should report the failure of an initial |
| 554 |
// connection to a route, gateway or leaf node. |
| 555 |
// See DEFAULT_CONNECT_ERROR_REPORTS for default value. |
| 556 |
ConnectErrorReports int |
| 557 |
|
| 558 |
// ReconnectErrorReports is similar to ConnectErrorReports except |
| 559 |
// that this applies to reconnect events. |
| 560 |
ReconnectErrorReports int |
| 561 |
|
| 562 |
// Tags describing the server. They will be included in varz |
| 563 |
// and used as a filter criteria for some system requests. |
| 564 |
Tags jwt.TagList `json:"-"` |
| 565 |
|
| 566 |
// Metadata describing the server. They will be included in 'Z' responses. |
| 567 |
Metadata map[string]string `json:"-"` |
| 568 |
|
| 569 |
// FeatureFlags the server opts-in to (or opts-out of). They will be included in 'Z' responses. |
| 570 |
FeatureFlags map[string]bool `json:"-"` |
| 571 |
|
| 572 |
// OCSPConfig enables OCSP Stapling in the server. |
| 573 |
OCSPConfig *OCSPConfig |
| 574 |
tlsConfigOpts *TLSConfigOpts |
| 575 |
|
| 576 |
// Proxies configuration. |
| 577 |
Proxies *ProxiesConfig |
| 578 |
|
| 579 |
// private fields, used to know if bool options are explicitly |
| 580 |
// defined in config and/or command line params. |
| 581 |
inConfig map[string]bool |
| 582 |
inCmdLine map[string]bool |
| 583 |
|
| 584 |
// private fields for operator mode |
| 585 |
operatorJWT []string |
| 586 |
resolverPreloads map[string]string |
| 587 |
resolverPinnedAccounts map[string]struct{} |
| 588 |
|
| 589 |
// private fields, used for testing |
| 590 |
gatewaysSolicitDelay time.Duration |
| 591 |
overrideProto int |
| 592 |
|
| 593 |
// JetStream |
| 594 |
maxMemSet bool |
| 595 |
maxStoreSet bool |
| 596 |
syncSet bool |
| 597 |
|
| 598 |
// OCSP Cache config enables next-gen cache for OCSP features |
| 599 |
OCSPCacheConfig *OCSPResponseCacheConfig |
| 600 |
|
| 601 |
// Used to mark that we had a top level authorization block. |
| 602 |
authBlockDefined bool |
| 603 |
|
| 604 |
// configDigest represents the state of configuration. |
| 605 |
configDigest string |
| 606 |
} |
| 607 |
|
| 608 |
// WebsocketOpts are options for websocket |
| 609 |
type WebsocketOpts struct { |
| 610 |
// The server will accept websocket client connections on this hostname/IP. |
| 611 |
Host string |
| 612 |
// The server will accept websocket client connections on this port. |
| 613 |
Port int |
| 614 |
// The host:port to advertise to websocket clients in the cluster. |
| 615 |
Advertise string |
| 616 |
|
| 617 |
// If no user name is provided when a client connects, will default to the |
| 618 |
// matching user from the global list of users in `Options.Users`. |
| 619 |
NoAuthUser string |
| 620 |
|
| 621 |
// Name of the cookie, which if present in WebSocket upgrade headers, |
| 622 |
// will be treated as JWT during CONNECT phase as long as |
| 623 |
// "jwt" specified in the CONNECT options is missing or empty. |
| 624 |
JWTCookie string |
| 625 |
|
| 626 |
// Name of the cookie, which if present in WebSocket upgrade headers, |
| 627 |
// will be treated as Username during CONNECT phase as long as |
| 628 |
// "user" specified in the CONNECT options is missing or empty. |
| 629 |
UsernameCookie string |
| 630 |
|
| 631 |
// Name of the cookie, which if present in WebSocket upgrade headers, |
| 632 |
// will be treated as Password during CONNECT phase as long as |
| 633 |
// "pass" specified in the CONNECT options is missing or empty. |
| 634 |
PasswordCookie string |
| 635 |
|
| 636 |
// Name of the cookie, which if present in WebSocket upgrade headers, |
| 637 |
// will be treated as Token during CONNECT phase as long as |
| 638 |
// "auth_token" specified in the CONNECT options is missing or empty. |
| 639 |
// Note that when this is useful for passing a JWT to an cuth callout |
| 640 |
// when the server uses delegated authentication ("operator mode") or |
| 641 |
// when using delegated authentication, but the auth callout validates some |
| 642 |
// other JWT or string. Note that this does map to an actual server-wide |
| 643 |
// "auth_token", note that using it for that purpose is greatly discouraged. |
| 644 |
TokenCookie string |
| 645 |
|
| 646 |
// Authentication section. If anything is configured in this section, |
| 647 |
// it will override the authorization configuration of regular clients. |
| 648 |
Username string |
| 649 |
Password string |
| 650 |
Token string |
| 651 |
|
| 652 |
// Timeout for the authentication process. |
| 653 |
AuthTimeout float64 |
| 654 |
|
| 655 |
// By default the server will enforce the use of TLS. If no TLS configuration |
| 656 |
// is provided, you need to explicitly set NoTLS to true to allow the server |
| 657 |
// to start without TLS configuration. Note that if a TLS configuration is |
| 658 |
// present, this boolean is ignored and the server will run the Websocket |
| 659 |
// server with that TLS configuration. |
| 660 |
// Running without TLS is less secure since Websocket clients that use bearer |
| 661 |
// tokens will send them in clear. So this should not be used in production. |
| 662 |
NoTLS bool |
| 663 |
|
| 664 |
// TLS configuration is required. |
| 665 |
TLSConfig *tls.Config |
| 666 |
// If true, map certificate values for authentication purposes. |
| 667 |
TLSMap bool |
| 668 |
|
| 669 |
// When present, accepted client certificates (verify/verify_and_map) must be in this list |
| 670 |
TLSPinnedCerts PinnedCertSet |
| 671 |
|
| 672 |
// If true, the Origin header must match the request's host. |
| 673 |
SameOrigin bool |
| 674 |
|
| 675 |
// Only origins in this list will be accepted. If empty and |
| 676 |
// SameOrigin is false, any origin is accepted. |
| 677 |
AllowedOrigins []string |
| 678 |
|
| 679 |
// If set to true, the server will negotiate with clients |
| 680 |
// if compression can be used. If this is false, no compression |
| 681 |
// will be used (both in server and clients) since it has to |
| 682 |
// be negotiated between both endpoints |
| 683 |
Compression bool |
| 684 |
|
| 685 |
// Total time allowed for the server to read the client request |
| 686 |
// and write the response back to the client. This include the |
| 687 |
// time needed for the TLS Handshake. |
| 688 |
HandshakeTimeout time.Duration |
| 689 |
|
| 690 |
// How often to send pings to WebSocket clients. When set to a non-zero |
| 691 |
// duration, this overrides the default PingInterval for WebSocket connections. |
| 692 |
// If not set or zero, the server's default PingInterval will be used. |
| 693 |
PingInterval time.Duration |
| 694 |
|
| 695 |
// Headers to be added to the upgrade response. |
| 696 |
// Useful for adding custom headers like Strict-Transport-Security. |
| 697 |
Headers map[string]string |
| 698 |
|
| 699 |
// Snapshot of configured TLS options. |
| 700 |
tlsConfigOpts *TLSConfigOpts |
| 701 |
} |
| 702 |
|
| 703 |
// MQTTOpts are options for MQTT |
| 704 |
type MQTTOpts struct { |
| 705 |
// The server will accept MQTT client connections on this hostname/IP. |
| 706 |
Host string |
| 707 |
// The server will accept MQTT client connections on this port. |
| 708 |
Port int |
| 709 |
|
| 710 |
// If no user name is provided when a client connects, will default to the |
| 711 |
// matching user from the global list of users in `Options.Users`. |
| 712 |
NoAuthUser string |
| 713 |
|
| 714 |
// Authentication section. If anything is configured in this section, |
| 715 |
// it will override the authorization configuration of regular clients. |
| 716 |
Username string |
| 717 |
Password string |
| 718 |
Token string |
| 719 |
|
| 720 |
// JetStream domain mqtt is supposed to pick up |
| 721 |
JsDomain string |
| 722 |
|
| 723 |
// Number of replicas for MQTT streams. |
| 724 |
// Negative or 0 value means that the server(s) will pick a replica |
| 725 |
// number based on the known size of the cluster (but capped at 3). |
| 726 |
// Note that if an account was already connected, the stream's replica |
| 727 |
// count is not modified. Use the NATS CLI to update the count if desired. |
| 728 |
StreamReplicas int |
| 729 |
|
| 730 |
// Number of replicas for MQTT consumers. |
| 731 |
// Negative or 0 value means that there is no override and the consumer |
| 732 |
// will have the same replica factor that the stream it belongs to. |
| 733 |
// If a value is specified, it will require to be lower than the stream |
| 734 |
// replicas count (lower than StreamReplicas if specified, but also lower |
| 735 |
// than the automatic value determined by cluster size). |
| 736 |
// Note that existing consumers are not modified. |
| 737 |
// |
| 738 |
// UPDATE: This is no longer used while messages stream has interest policy retention |
| 739 |
// which requires consumer replica count to match the parent stream. |
| 740 |
ConsumerReplicas int |
| 741 |
|
| 742 |
// Indicate if the consumers should be created with memory storage. |
| 743 |
// Note that existing consumers are not modified. |
| 744 |
ConsumerMemoryStorage bool |
| 745 |
|
| 746 |
// If specified will have the system auto-cleanup the consumers after being |
| 747 |
// inactive for the specified amount of time. |
| 748 |
ConsumerInactiveThreshold time.Duration |
| 749 |
|
| 750 |
// Timeout for the authentication process. |
| 751 |
AuthTimeout float64 |
| 752 |
|
| 753 |
// TLS configuration is required. |
| 754 |
TLSConfig *tls.Config |
| 755 |
// If true, map certificate values for authentication purposes. |
| 756 |
TLSMap bool |
| 757 |
// Timeout for the TLS handshake |
| 758 |
TLSTimeout float64 |
| 759 |
// Set of allowable certificates |
| 760 |
TLSPinnedCerts PinnedCertSet |
| 761 |
|
| 762 |
// AckWait is the amount of time after which a QoS 1 or 2 message sent to a |
| 763 |
// client is redelivered as a DUPLICATE if the server has not received the |
| 764 |
// PUBACK on the original Packet Identifier. The same value applies to |
| 765 |
// PubRel redelivery. The value has to be positive. Zero will cause the |
| 766 |
// server to use the default value (30 seconds). Note that changes to this |
| 767 |
// option is applied only to new MQTT subscriptions (or sessions for |
| 768 |
// PubRels). |
| 769 |
AckWait time.Duration |
| 770 |
|
| 771 |
// JSAPITimeout defines timeout for JetStream api calls (default is 5 seconds) |
| 772 |
JSAPITimeout time.Duration |
| 773 |
|
| 774 |
// MaxAckPending is the amount of QoS 1 and 2 messages (combined) the server |
| 775 |
// can send to a subscription without receiving any PUBACK for those |
| 776 |
// messages. The valid range is [0..65535]. |
| 777 |
// |
| 778 |
// The total of subscriptions' MaxAckPending on a given session cannot |
| 779 |
// exceed 65535. Attempting to create a subscription that would bring the |
| 780 |
// total above the limit would result in the server returning 0x80 in the |
| 781 |
// SUBACK for this subscription. |
| 782 |
// |
| 783 |
// Due to how the NATS Server handles the MQTT "#" wildcard, each |
| 784 |
// subscription ending with "#" will use 2 times the MaxAckPending value. |
| 785 |
// Note that changes to this option is applied only to new subscriptions. |
| 786 |
MaxAckPending uint16 |
| 787 |
|
| 788 |
// Snapshot of configured TLS options. |
| 789 |
tlsConfigOpts *TLSConfigOpts |
| 790 |
|
| 791 |
// rejectQoS2Pub tells the MQTT client to not accept QoS2 PUBLISH, instead |
| 792 |
// error and terminate the connection. |
| 793 |
rejectQoS2Pub bool |
| 794 |
|
| 795 |
// downgradeQOS2Sub tells the MQTT client to downgrade QoS2 SUBSCRIBE |
| 796 |
// requests to QoS1. |
| 797 |
downgradeQoS2Sub bool |
| 798 |
} |
| 799 |
|
| 800 |
type netResolver interface { |
| 801 |
LookupHost(ctx context.Context, host string) ([]string, error) |
| 802 |
} |
| 803 |
|
| 804 |
// Clone performs a deep copy of the Options struct, returning a new clone |
| 805 |
// with all values copied. |
| 806 |
func (o *Options) Clone() *Options { |
| 807 |
if o == nil { |
| 808 |
return nil |
| 809 |
} |
| 810 |
clone := &Options{} |
| 811 |
*clone = *o |
| 812 |
if o.Users != nil { |
| 813 |
clone.Users = make([]*User, len(o.Users)) |
| 814 |
for i, user := range o.Users { |
| 815 |
clone.Users[i] = user.clone() |
| 816 |
} |
| 817 |
} |
| 818 |
if o.Nkeys != nil { |
| 819 |
clone.Nkeys = make([]*NkeyUser, len(o.Nkeys)) |
| 820 |
for i, nkey := range o.Nkeys { |
| 821 |
clone.Nkeys[i] = nkey.clone() |
| 822 |
} |
| 823 |
} |
| 824 |
|
| 825 |
if o.Routes != nil { |
| 826 |
clone.Routes = deepCopyURLs(o.Routes) |
| 827 |
} |
| 828 |
if o.TLSConfig != nil { |
| 829 |
clone.TLSConfig = o.TLSConfig.Clone() |
| 830 |
} |
| 831 |
if o.Cluster.TLSConfig != nil { |
| 832 |
clone.Cluster.TLSConfig = o.Cluster.TLSConfig.Clone() |
| 833 |
} |
| 834 |
if o.Gateway.TLSConfig != nil { |
| 835 |
clone.Gateway.TLSConfig = o.Gateway.TLSConfig.Clone() |
| 836 |
} |
| 837 |
if len(o.Gateway.Gateways) > 0 { |
| 838 |
clone.Gateway.Gateways = make([]*RemoteGatewayOpts, len(o.Gateway.Gateways)) |
| 839 |
for i, g := range o.Gateway.Gateways { |
| 840 |
clone.Gateway.Gateways[i] = g.clone() |
| 841 |
} |
| 842 |
} |
| 843 |
// FIXME(dlc) - clone leaf node stuff. |
| 844 |
return clone |
| 845 |
} |
| 846 |
|
| 847 |
func deepCopyURLs(urls []*url.URL) []*url.URL { |
| 848 |
if urls == nil { |
| 849 |
return nil |
| 850 |
} |
| 851 |
curls := make([]*url.URL, len(urls)) |
| 852 |
for i, u := range urls { |
| 853 |
cu := &url.URL{} |
| 854 |
*cu = *u |
| 855 |
curls[i] = cu |
| 856 |
} |
| 857 |
return curls |
| 858 |
} |
| 859 |
|
| 860 |
// Configuration file authorization section. |
| 861 |
type authorization struct { |
| 862 |
// Singles |
| 863 |
user string |
| 864 |
pass string |
| 865 |
token string |
| 866 |
nkey string |
| 867 |
acc string |
| 868 |
// If connection must come through proxy |
| 869 |
proxyRequired bool |
| 870 |
// Multiple Nkeys/Users |
| 871 |
nkeys []*NkeyUser |
| 872 |
users []*User |
| 873 |
timeout float64 |
| 874 |
defaultPermissions *Permissions |
| 875 |
// Auth Callouts |
| 876 |
callout *AuthCallout |
| 877 |
} |
| 878 |
|
| 879 |
// TLSConfigOpts holds the parsed tls config information, |
| 880 |
// used with flag parsing |
| 881 |
type TLSConfigOpts struct { |
| 882 |
CertFile string |
| 883 |
KeyFile string |
| 884 |
CaFile string |
| 885 |
Verify bool |
| 886 |
Insecure bool |
| 887 |
Map bool |
| 888 |
TLSCheckKnownURLs bool |
| 889 |
HandshakeFirst bool // Indicate that the TLS handshake should occur first, before sending the INFO protocol. |
| 890 |
FallbackDelay time.Duration // Where supported, indicates how long to wait for the handshake before falling back to sending the INFO protocol first. |
| 891 |
Timeout float64 |
| 892 |
RateLimit int64 |
| 893 |
AllowInsecureCiphers bool |
| 894 |
Ciphers []uint16 |
| 895 |
CurvePreferences []tls.CurveID |
| 896 |
PinnedCerts PinnedCertSet |
| 897 |
CertStore certstore.StoreType |
| 898 |
CertMatchBy certstore.MatchByType |
| 899 |
CertMatch string |
| 900 |
CertMatchSkipInvalid bool |
| 901 |
CaCertsMatch []string |
| 902 |
OCSPPeerConfig *certidp.OCSPPeerConfig |
| 903 |
Certificates []*TLSCertPairOpt |
| 904 |
MinVersion uint16 |
| 905 |
} |
| 906 |
|
| 907 |
// TLSCertPairOpt are the paths to a certificate and private key. |
| 908 |
type TLSCertPairOpt struct { |
| 909 |
CertFile string |
| 910 |
KeyFile string |
| 911 |
} |
| 912 |
|
| 913 |
// OCSPConfig represents the options of OCSP stapling options. |
| 914 |
type OCSPConfig struct { |
| 915 |
// Mode defines the policy for OCSP stapling. |
| 916 |
Mode OCSPMode |
| 917 |
|
| 918 |
// OverrideURLs is the http URL endpoint used to get OCSP staples. |
| 919 |
OverrideURLs []string |
| 920 |
} |
| 921 |
|
| 922 |
// ProxiesConfig represents the options of Proxies. |
| 923 |
type ProxiesConfig struct { |
| 924 |
Trusted []*ProxyConfig |
| 925 |
} |
| 926 |
|
| 927 |
// ProxyConfig represents the options of Proxy. |
| 928 |
type ProxyConfig struct { |
| 929 |
// Public key. |
| 930 |
Key string |
| 931 |
} |
| 932 |
|
| 933 |
var tlsUsage = ` |
| 934 |
TLS configuration is specified in the tls section of a configuration file: |
| 935 |
|
| 936 |
e.g. |
| 937 |
|
| 938 |
tls { |
| 939 |
cert_file: "./certs/server-cert.pem" |
| 940 |
key_file: "./certs/server-key.pem" |
| 941 |
ca_file: "./certs/ca.pem" |
| 942 |
verify: true |
| 943 |
verify_and_map: true |
| 944 |
|
| 945 |
cipher_suites: [ |
| 946 |
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", |
| 947 |
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" |
| 948 |
] |
| 949 |
curve_preferences: [ |
| 950 |
"CurveP256", |
| 951 |
"CurveP384", |
| 952 |
"CurveP521" |
| 953 |
] |
| 954 |
} |
| 955 |
|
| 956 |
Available cipher suites include: |
| 957 |
` |
| 958 |
|
| 959 |
// ProcessConfigFile processes a configuration file. |
| 960 |
// FIXME(dlc): A bit hacky |
| 961 |
func ProcessConfigFile(configFile string) (*Options, error) { |
| 962 |
opts := &Options{} |
| 963 |
if err := opts.ProcessConfigFile(configFile); err != nil { |
| 964 |
// If only warnings then continue and return the options. |
| 965 |
if cerr, ok := err.(*processConfigErr); ok && len(cerr.Errors()) == 0 { |
| 966 |
return opts, nil |
| 967 |
} |
| 968 |
|
| 969 |
return nil, err |
| 970 |
} |
| 971 |
return opts, nil |
| 972 |
} |
| 973 |
|
| 974 |
// token is an item parsed from the configuration. |
| 975 |
type token interface { |
| 976 |
Value() any |
| 977 |
Line() int |
| 978 |
IsUsedVariable() bool |
| 979 |
SourceFile() string |
| 980 |
Position() int |
| 981 |
} |
| 982 |
|
| 983 |
// unwrapValue can be used to get the token and value from an item |
| 984 |
// to be able to report the line number in case of an incorrect |
| 985 |
// configuration. |
| 986 |
// also stores the token in lastToken for use in convertPanicToError |
| 987 |
func unwrapValue(v any, lastToken *token) (token, any) { |
| 988 |
switch tk := v.(type) { |
| 989 |
case token: |
| 990 |
if lastToken != nil { |
| 991 |
*lastToken = tk |
| 992 |
} |
| 993 |
return tk, tk.Value() |
| 994 |
default: |
| 995 |
return nil, v |
| 996 |
} |
| 997 |
} |
| 998 |
|
| 999 |
// use in defer to recover from panic and turn it into an error associated with last token |
| 1000 |
func convertPanicToErrorList(lastToken *token, errors *[]error) { |
| 1001 |
// only recover if an error can be stored |
| 1002 |
if errors == nil { |
| 1003 |
return |
| 1004 |
} else if err := recover(); err == nil { |
| 1005 |
return |
| 1006 |
} else if lastToken != nil && *lastToken != nil { |
| 1007 |
*errors = append(*errors, &configErr{*lastToken, fmt.Sprint(err)}) |
| 1008 |
} else { |
| 1009 |
*errors = append(*errors, fmt.Errorf("encountered panic without a token %v", err)) |
| 1010 |
} |
| 1011 |
} |
| 1012 |
|
| 1013 |
// use in defer to recover from panic and turn it into an error associated with last token |
| 1014 |
func convertPanicToError(lastToken *token, e *error) { |
| 1015 |
// only recover if an error can be stored |
| 1016 |
if e == nil || *e != nil { |
| 1017 |
return |
| 1018 |
} else if err := recover(); err == nil { |
| 1019 |
return |
| 1020 |
} else if lastToken != nil && *lastToken != nil { |
| 1021 |
*e = &configErr{*lastToken, fmt.Sprint(err)} |
| 1022 |
} else { |
| 1023 |
*e = fmt.Errorf("%v", err) |
| 1024 |
} |
| 1025 |
} |
| 1026 |
|
| 1027 |
// configureSystemAccount configures a system account |
| 1028 |
// if present in the configuration. |
| 1029 |
func configureSystemAccount(o *Options, m map[string]any) (retErr error) { |
| 1030 |
var lt token |
| 1031 |
defer convertPanicToError(<, &retErr) |
| 1032 |
configure := func(v any) error { |
| 1033 |
tk, v := unwrapValue(v, <) |
| 1034 |
sa, ok := v.(string) |
| 1035 |
if !ok { |
| 1036 |
return &configErr{tk, "system account name must be a string"} |
| 1037 |
} |
| 1038 |
o.SystemAccount = sa |
| 1039 |
return nil |
| 1040 |
} |
| 1041 |
|
| 1042 |
if v, ok := m["system_account"]; ok { |
| 1043 |
return configure(v) |
| 1044 |
} else if v, ok := m["system"]; ok { |
| 1045 |
return configure(v) |
| 1046 |
} |
| 1047 |
|
| 1048 |
return nil |
| 1049 |
} |
| 1050 |
|
| 1051 |
// ProcessConfigFile updates the Options structure with options |
| 1052 |
// present in the given configuration file. |
| 1053 |
// This version is convenient if one wants to set some default |
| 1054 |
// options and then override them with what is in the config file. |
| 1055 |
// For instance, this version allows you to do something such as: |
| 1056 |
// |
| 1057 |
// opts := &Options{Debug: true} |
| 1058 |
// opts.ProcessConfigFile(myConfigFile) |
| 1059 |
// |
| 1060 |
// If the config file contains "debug: false", after this call, |
| 1061 |
// opts.Debug would really be false. It would be impossible to |
| 1062 |
// achieve that with the non receiver ProcessConfigFile() version, |
| 1063 |
// since one would not know after the call if "debug" was not present |
| 1064 |
// or was present but set to false. |
| 1065 |
func (o *Options) ProcessConfigFile(configFile string) error { |
| 1066 |
o.ConfigFile = configFile |
| 1067 |
if configFile == _EMPTY_ { |
| 1068 |
return nil |
| 1069 |
} |
| 1070 |
m, digest, err := conf.ParseFileWithChecksDigest(configFile) |
| 1071 |
if err != nil { |
| 1072 |
return err |
| 1073 |
} |
| 1074 |
o.configDigest = digest |
| 1075 |
|
| 1076 |
return o.processConfigFile(configFile, m) |
| 1077 |
} |
| 1078 |
|
| 1079 |
// ProcessConfigString is the same as ProcessConfigFile, but expects the |
| 1080 |
// contents of the config file to be passed in rather than the file name. |
| 1081 |
func (o *Options) ProcessConfigString(data string) error { |
| 1082 |
m, err := conf.ParseWithChecks(data) |
| 1083 |
if err != nil { |
| 1084 |
return err |
| 1085 |
} |
| 1086 |
|
| 1087 |
return o.processConfigFile(_EMPTY_, m) |
| 1088 |
} |
| 1089 |
|
| 1090 |
// ConfigDigest returns the digest representing the configuration. |
| 1091 |
func (o *Options) ConfigDigest() string { |
| 1092 |
return o.configDigest |
| 1093 |
} |
| 1094 |
|
| 1095 |
func (o *Options) processConfigFile(configFile string, m map[string]any) error { |
| 1096 |
// Collect all errors and warnings and report them all together. |
| 1097 |
errors := make([]error, 0) |
| 1098 |
warnings := make([]error, 0) |
| 1099 |
if len(m) == 0 { |
| 1100 |
warnings = append(warnings, fmt.Errorf("%s: config has no values or is empty", configFile)) |
| 1101 |
} |
| 1102 |
|
| 1103 |
// First check whether a system account has been defined, |
| 1104 |
// as that is a condition for other features to be enabled. |
| 1105 |
if err := configureSystemAccount(o, m); err != nil { |
| 1106 |
errors = append(errors, err) |
| 1107 |
} |
| 1108 |
|
| 1109 |
for k, v := range m { |
| 1110 |
o.processConfigFileLine(k, v, &errors, &warnings) |
| 1111 |
} |
| 1112 |
|
| 1113 |
// Post-process: check auth callout allowed accounts against configured accounts. |
| 1114 |
if o.AuthCallout != nil { |
| 1115 |
accounts := make(map[string]struct{}) |
| 1116 |
for _, acc := range o.Accounts { |
| 1117 |
accounts[acc.Name] = struct{}{} |
| 1118 |
} |
| 1119 |
|
| 1120 |
for _, acc := range o.AuthCallout.AllowedAccounts { |
| 1121 |
if _, ok := accounts[acc]; !ok { |
| 1122 |
err := &configErr{nil, fmt.Sprintf("auth_callout allowed account %q not found in configured accounts", acc)} |
| 1123 |
errors = append(errors, err) |
| 1124 |
} |
| 1125 |
} |
| 1126 |
} |
| 1127 |
|
| 1128 |
if len(errors) > 0 || len(warnings) > 0 { |
| 1129 |
return &processConfigErr{ |
| 1130 |
errors: errors, |
| 1131 |
warnings: warnings, |
| 1132 |
} |
| 1133 |
} |
| 1134 |
|
| 1135 |
return nil |
| 1136 |
} |
| 1137 |
|
| 1138 |
func (o *Options) processConfigFileLine(k string, v any, errors *[]error, warnings *[]error) { |
| 1139 |
var lt token |
| 1140 |
defer convertPanicToErrorList(<, errors) |
| 1141 |
|
| 1142 |
tk, v := unwrapValue(v, <) |
| 1143 |
switch strings.ToLower(k) { |
| 1144 |
case "listen": |
| 1145 |
hp, err := parseListen(v) |
| 1146 |
if err != nil { |
| 1147 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 1148 |
return |
| 1149 |
} |
| 1150 |
o.Host = hp.host |
| 1151 |
o.Port = hp.port |
| 1152 |
case "client_advertise": |
| 1153 |
o.ClientAdvertise = v.(string) |
| 1154 |
case "port": |
| 1155 |
o.Port = int(v.(int64)) |
| 1156 |
case "server_name": |
| 1157 |
sn := v.(string) |
| 1158 |
if strings.Contains(sn, " ") { |
| 1159 |
err := &configErr{tk, ErrServerNameHasSpaces.Error()} |
| 1160 |
*errors = append(*errors, err) |
| 1161 |
return |
| 1162 |
} |
| 1163 |
o.ServerName = sn |
| 1164 |
case "host", "net": |
| 1165 |
o.Host = v.(string) |
| 1166 |
case "debug": |
| 1167 |
o.Debug = v.(bool) |
| 1168 |
trackExplicitVal(&o.inConfig, "Debug", o.Debug) |
| 1169 |
case "trace": |
| 1170 |
o.Trace = v.(bool) |
| 1171 |
trackExplicitVal(&o.inConfig, "Trace", o.Trace) |
| 1172 |
case "trace_verbose": |
| 1173 |
o.TraceVerbose = v.(bool) |
| 1174 |
o.Trace = v.(bool) |
| 1175 |
trackExplicitVal(&o.inConfig, "TraceVerbose", o.TraceVerbose) |
| 1176 |
trackExplicitVal(&o.inConfig, "Trace", o.Trace) |
| 1177 |
case "trace_headers": |
| 1178 |
o.TraceHeaders = v.(bool) |
| 1179 |
o.Trace = v.(bool) |
| 1180 |
trackExplicitVal(&o.inConfig, "TraceHeaders", o.TraceHeaders) |
| 1181 |
trackExplicitVal(&o.inConfig, "Trace", o.Trace) |
| 1182 |
case "logtime": |
| 1183 |
o.Logtime = v.(bool) |
| 1184 |
trackExplicitVal(&o.inConfig, "Logtime", o.Logtime) |
| 1185 |
case "logtime_utc": |
| 1186 |
o.LogtimeUTC = v.(bool) |
| 1187 |
trackExplicitVal(&o.inConfig, "LogtimeUTC", o.LogtimeUTC) |
| 1188 |
case "mappings", "maps": |
| 1189 |
gacc := NewAccount(globalAccountName) |
| 1190 |
o.Accounts = append(o.Accounts, gacc) |
| 1191 |
err := parseAccountMappings(tk, gacc, errors) |
| 1192 |
if err != nil { |
| 1193 |
*errors = append(*errors, err) |
| 1194 |
return |
| 1195 |
} |
| 1196 |
case "disable_sublist_cache", "no_sublist_cache": |
| 1197 |
o.NoSublistCache = v.(bool) |
| 1198 |
case "accounts": |
| 1199 |
err := parseAccounts(tk, o, errors, warnings) |
| 1200 |
if err != nil { |
| 1201 |
*errors = append(*errors, err) |
| 1202 |
return |
| 1203 |
} |
| 1204 |
case "default_sentinel": |
| 1205 |
o.DefaultSentinel = v.(string) |
| 1206 |
case "authorization": |
| 1207 |
auth, err := parseAuthorization(tk, errors, warnings) |
| 1208 |
if err != nil { |
| 1209 |
*errors = append(*errors, err) |
| 1210 |
return |
| 1211 |
} |
| 1212 |
o.authBlockDefined = true |
| 1213 |
o.Username = auth.user |
| 1214 |
o.Password = auth.pass |
| 1215 |
o.ProxyRequired = auth.proxyRequired |
| 1216 |
o.Authorization = auth.token |
| 1217 |
o.AuthTimeout = auth.timeout |
| 1218 |
o.AuthCallout = auth.callout |
| 1219 |
|
| 1220 |
if (auth.user != _EMPTY_ || auth.pass != _EMPTY_) && auth.token != _EMPTY_ { |
| 1221 |
err := &configErr{tk, "Cannot have a user/pass and token"} |
| 1222 |
*errors = append(*errors, err) |
| 1223 |
return |
| 1224 |
} |
| 1225 |
// In case parseAccounts() was done first, we need to check for duplicates. |
| 1226 |
unames := setupUsersAndNKeysDuplicateCheckMap(o) |
| 1227 |
// Check for multiple users defined. |
| 1228 |
// Note: auth.users will be != nil as long as `users: []` is present |
| 1229 |
// in the authorization block, even if empty, and will also account for |
| 1230 |
// nkey users. We also check for users/nkeys that may have been already |
| 1231 |
// added in parseAccounts() (which means they will be in unames) |
| 1232 |
if auth.users != nil || len(unames) > 0 { |
| 1233 |
if auth.user != _EMPTY_ { |
| 1234 |
err := &configErr{tk, "Can not have a single user/pass and a users array"} |
| 1235 |
*errors = append(*errors, err) |
| 1236 |
return |
| 1237 |
} |
| 1238 |
if auth.token != _EMPTY_ { |
| 1239 |
err := &configErr{tk, "Can not have a token and a users array"} |
| 1240 |
*errors = append(*errors, err) |
| 1241 |
return |
| 1242 |
} |
| 1243 |
// Now check that if we have users, there is no duplicate, including |
| 1244 |
// users that may have been configured in parseAccounts(). |
| 1245 |
if len(auth.users) > 0 { |
| 1246 |
for _, u := range auth.users { |
| 1247 |
if _, ok := unames[u.Username]; ok { |
| 1248 |
err := &configErr{tk, fmt.Sprintf("Duplicate user %q detected", u.Username)} |
| 1249 |
*errors = append(*errors, err) |
| 1250 |
return |
| 1251 |
} |
| 1252 |
unames[u.Username] = struct{}{} |
| 1253 |
} |
| 1254 |
// Users may have been added from Accounts parsing, so do an append here |
| 1255 |
o.Users = append(o.Users, auth.users...) |
| 1256 |
} |
| 1257 |
} |
| 1258 |
// Check for nkeys |
| 1259 |
if len(auth.nkeys) > 0 { |
| 1260 |
for _, u := range auth.nkeys { |
| 1261 |
if _, ok := unames[u.Nkey]; ok { |
| 1262 |
err := &configErr{tk, fmt.Sprintf("Duplicate nkey %q detected", u.Nkey)} |
| 1263 |
*errors = append(*errors, err) |
| 1264 |
return |
| 1265 |
} |
| 1266 |
unames[u.Nkey] = struct{}{} |
| 1267 |
} |
| 1268 |
// NKeys may have been added from Accounts parsing, so do an append here |
| 1269 |
o.Nkeys = append(o.Nkeys, auth.nkeys...) |
| 1270 |
} |
| 1271 |
case "http": |
| 1272 |
hp, err := parseListen(v) |
| 1273 |
if err != nil { |
| 1274 |
err := &configErr{tk, err.Error()} |
| 1275 |
*errors = append(*errors, err) |
| 1276 |
return |
| 1277 |
} |
| 1278 |
o.HTTPHost = hp.host |
| 1279 |
o.HTTPPort = hp.port |
| 1280 |
case "https": |
| 1281 |
hp, err := parseListen(v) |
| 1282 |
if err != nil { |
| 1283 |
err := &configErr{tk, err.Error()} |
| 1284 |
*errors = append(*errors, err) |
| 1285 |
return |
| 1286 |
} |
| 1287 |
o.HTTPHost = hp.host |
| 1288 |
o.HTTPSPort = hp.port |
| 1289 |
case "http_port", "monitor_port": |
| 1290 |
o.HTTPPort = int(v.(int64)) |
| 1291 |
case "https_port": |
| 1292 |
o.HTTPSPort = int(v.(int64)) |
| 1293 |
case "http_base_path": |
| 1294 |
o.HTTPBasePath = v.(string) |
| 1295 |
case "cluster": |
| 1296 |
err := parseCluster(tk, o, errors, warnings) |
| 1297 |
if err != nil { |
| 1298 |
*errors = append(*errors, err) |
| 1299 |
return |
| 1300 |
} |
| 1301 |
case "gateway": |
| 1302 |
if err := parseGateway(tk, o, errors, warnings); err != nil { |
| 1303 |
*errors = append(*errors, err) |
| 1304 |
return |
| 1305 |
} |
| 1306 |
case "leaf", "leafnodes": |
| 1307 |
err := parseLeafNodes(tk, o, errors, warnings) |
| 1308 |
if err != nil { |
| 1309 |
*errors = append(*errors, err) |
| 1310 |
return |
| 1311 |
} |
| 1312 |
case "store_dir", "storedir": |
| 1313 |
// Check if JetStream configuration is also setting the storage directory. |
| 1314 |
if o.StoreDir != _EMPTY_ { |
| 1315 |
*errors = append(*errors, &configErr{tk, "Duplicate 'store_dir' configuration"}) |
| 1316 |
return |
| 1317 |
} |
| 1318 |
o.StoreDir = v.(string) |
| 1319 |
case "jetstream": |
| 1320 |
err := parseJetStream(tk, o, errors, warnings) |
| 1321 |
if err != nil { |
| 1322 |
*errors = append(*errors, err) |
| 1323 |
return |
| 1324 |
} |
| 1325 |
case "logfile", "log_file": |
| 1326 |
o.LogFile = v.(string) |
| 1327 |
case "logfile_size_limit", "log_size_limit": |
| 1328 |
o.LogSizeLimit = v.(int64) |
| 1329 |
case "logfile_max_num", "log_max_num": |
| 1330 |
o.LogMaxFiles = v.(int64) |
| 1331 |
case "syslog": |
| 1332 |
o.Syslog = v.(bool) |
| 1333 |
trackExplicitVal(&o.inConfig, "Syslog", o.Syslog) |
| 1334 |
case "remote_syslog": |
| 1335 |
o.RemoteSyslog = v.(string) |
| 1336 |
case "pidfile", "pid_file": |
| 1337 |
o.PidFile = v.(string) |
| 1338 |
case "ports_file_dir": |
| 1339 |
o.PortsFileDir = v.(string) |
| 1340 |
case "prof_port": |
| 1341 |
o.ProfPort = int(v.(int64)) |
| 1342 |
case "prof_block_rate": |
| 1343 |
o.ProfBlockRate = int(v.(int64)) |
| 1344 |
case "max_control_line": |
| 1345 |
if v.(int64) > 1<<31-1 { |
| 1346 |
err := &configErr{tk, fmt.Sprintf("%s value is too big", k)} |
| 1347 |
*errors = append(*errors, err) |
| 1348 |
return |
| 1349 |
} |
| 1350 |
o.MaxControlLine = int32(v.(int64)) |
| 1351 |
case "max_payload": |
| 1352 |
if v.(int64) > 1<<31-1 { |
| 1353 |
err := &configErr{tk, fmt.Sprintf("%s value is too big", k)} |
| 1354 |
*errors = append(*errors, err) |
| 1355 |
return |
| 1356 |
} |
| 1357 |
o.MaxPayload = int32(v.(int64)) |
| 1358 |
case "max_pending": |
| 1359 |
o.MaxPending = v.(int64) |
| 1360 |
case "proxy_protocol": |
| 1361 |
o.ProxyProtocol = v.(bool) |
| 1362 |
case "max_connections", "max_conn": |
| 1363 |
if o.MaxConn = int(v.(int64)); o.MaxConn == 0 { |
| 1364 |
o.MaxConn = -1 |
| 1365 |
} |
| 1366 |
case "max_traced_msg_len": |
| 1367 |
o.MaxTracedMsgLen = int(v.(int64)) |
| 1368 |
case "max_subscriptions", "max_subs": |
| 1369 |
o.MaxSubs = int(v.(int64)) |
| 1370 |
case "max_sub_tokens", "max_subscription_tokens": |
| 1371 |
if n := v.(int64); n > math.MaxUint8 { |
| 1372 |
err := &configErr{tk, fmt.Sprintf("%s value is too big", k)} |
| 1373 |
*errors = append(*errors, err) |
| 1374 |
return |
| 1375 |
} else if n <= 0 { |
| 1376 |
err := &configErr{tk, fmt.Sprintf("%s value can not be negative", k)} |
| 1377 |
*errors = append(*errors, err) |
| 1378 |
return |
| 1379 |
} else { |
| 1380 |
o.MaxSubTokens = uint8(n) |
| 1381 |
} |
| 1382 |
case "ping_interval": |
| 1383 |
o.PingInterval = parseDuration("ping_interval", tk, v, errors, warnings) |
| 1384 |
case "ping_max": |
| 1385 |
o.MaxPingsOut = int(v.(int64)) |
| 1386 |
case "tls": |
| 1387 |
tc, err := parseTLS(tk, true) |
| 1388 |
if err != nil { |
| 1389 |
*errors = append(*errors, err) |
| 1390 |
return |
| 1391 |
} |
| 1392 |
if o.TLSConfig, err = GenTLSConfig(tc); err != nil { |
| 1393 |
err := &configErr{tk, err.Error()} |
| 1394 |
*errors = append(*errors, err) |
| 1395 |
return |
| 1396 |
} |
| 1397 |
o.TLSTimeout = tc.Timeout |
| 1398 |
o.TLSMap = tc.Map |
| 1399 |
o.TLSPinnedCerts = tc.PinnedCerts |
| 1400 |
o.TLSRateLimit = tc.RateLimit |
| 1401 |
o.TLSHandshakeFirst = tc.HandshakeFirst |
| 1402 |
o.TLSHandshakeFirstFallback = tc.FallbackDelay |
| 1403 |
|
| 1404 |
// Need to keep track of path of the original TLS config |
| 1405 |
// and certs path for OCSP Stapling monitoring. |
| 1406 |
o.tlsConfigOpts = tc |
| 1407 |
case "ocsp": |
| 1408 |
switch vv := v.(type) { |
| 1409 |
case bool: |
| 1410 |
if vv { |
| 1411 |
// Default is Auto which honors Must Staple status request |
| 1412 |
// but does not shutdown the server in case it is revoked, |
| 1413 |
// letting the client choose whether to trust or not the server. |
| 1414 |
o.OCSPConfig = &OCSPConfig{Mode: OCSPModeAuto} |
| 1415 |
} else { |
| 1416 |
o.OCSPConfig = &OCSPConfig{Mode: OCSPModeNever} |
| 1417 |
} |
| 1418 |
case map[string]any: |
| 1419 |
ocsp := &OCSPConfig{Mode: OCSPModeAuto} |
| 1420 |
|
| 1421 |
for kk, kv := range vv { |
| 1422 |
_, v = unwrapValue(kv, &tk) |
| 1423 |
switch kk { |
| 1424 |
case "mode": |
| 1425 |
mode := v.(string) |
| 1426 |
switch { |
| 1427 |
case strings.EqualFold(mode, "always"): |
| 1428 |
ocsp.Mode = OCSPModeAlways |
| 1429 |
case strings.EqualFold(mode, "must"): |
| 1430 |
ocsp.Mode = OCSPModeMust |
| 1431 |
case strings.EqualFold(mode, "never"): |
| 1432 |
ocsp.Mode = OCSPModeNever |
| 1433 |
case strings.EqualFold(mode, "auto"): |
| 1434 |
ocsp.Mode = OCSPModeAuto |
| 1435 |
default: |
| 1436 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("error parsing ocsp config: unsupported ocsp mode %T", mode)}) |
| 1437 |
} |
| 1438 |
case "urls": |
| 1439 |
urls := v.([]string) |
| 1440 |
ocsp.OverrideURLs = urls |
| 1441 |
case "url": |
| 1442 |
url := v.(string) |
| 1443 |
ocsp.OverrideURLs = []string{url} |
| 1444 |
default: |
| 1445 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("error parsing ocsp config: unsupported field %T", kk)}) |
| 1446 |
return |
| 1447 |
} |
| 1448 |
} |
| 1449 |
o.OCSPConfig = ocsp |
| 1450 |
default: |
| 1451 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("error parsing ocsp config: unsupported type %T", v)}) |
| 1452 |
return |
| 1453 |
} |
| 1454 |
case "allow_non_tls": |
| 1455 |
o.AllowNonTLS = v.(bool) |
| 1456 |
case "write_deadline": |
| 1457 |
o.WriteDeadline = parseDuration("write_deadline", tk, v, errors, warnings) |
| 1458 |
case "write_timeout": |
| 1459 |
o.WriteTimeout = parseWriteDeadlinePolicy(tk, v.(string), errors) |
| 1460 |
case "lame_duck_duration": |
| 1461 |
dur, err := time.ParseDuration(v.(string)) |
| 1462 |
if err != nil { |
| 1463 |
err := &configErr{tk, fmt.Sprintf("error parsing lame_duck_duration: %v", err)} |
| 1464 |
*errors = append(*errors, err) |
| 1465 |
return |
| 1466 |
} |
| 1467 |
if dur < 30*time.Second { |
| 1468 |
err := &configErr{tk, fmt.Sprintf("invalid lame_duck_duration of %v, minimum is 30 seconds", dur)} |
| 1469 |
*errors = append(*errors, err) |
| 1470 |
return |
| 1471 |
} |
| 1472 |
o.LameDuckDuration = dur |
| 1473 |
case "lame_duck_grace_period": |
| 1474 |
dur, err := time.ParseDuration(v.(string)) |
| 1475 |
if err != nil { |
| 1476 |
err := &configErr{tk, fmt.Sprintf("error parsing lame_duck_grace_period: %v", err)} |
| 1477 |
*errors = append(*errors, err) |
| 1478 |
return |
| 1479 |
} |
| 1480 |
if dur < 0 { |
| 1481 |
err := &configErr{tk, "invalid lame_duck_grace_period, needs to be positive"} |
| 1482 |
*errors = append(*errors, err) |
| 1483 |
return |
| 1484 |
} |
| 1485 |
o.LameDuckGracePeriod = dur |
| 1486 |
case "operator", "operators", "roots", "root", "root_operators", "root_operator": |
| 1487 |
opFiles := []string{} |
| 1488 |
switch v := v.(type) { |
| 1489 |
case string: |
| 1490 |
opFiles = append(opFiles, v) |
| 1491 |
case []string: |
| 1492 |
opFiles = append(opFiles, v...) |
| 1493 |
case []any: |
| 1494 |
for _, t := range v { |
| 1495 |
if token, ok := t.(token); ok { |
| 1496 |
if v, ok := token.Value().(string); ok { |
| 1497 |
opFiles = append(opFiles, v) |
| 1498 |
} else { |
| 1499 |
err := &configErr{tk, fmt.Sprintf("error parsing operators: unsupported type %T where string is expected", token)} |
| 1500 |
*errors = append(*errors, err) |
| 1501 |
break |
| 1502 |
} |
| 1503 |
} else { |
| 1504 |
err := &configErr{tk, fmt.Sprintf("error parsing operators: unsupported type %T", t)} |
| 1505 |
*errors = append(*errors, err) |
| 1506 |
break |
| 1507 |
} |
| 1508 |
} |
| 1509 |
default: |
| 1510 |
err := &configErr{tk, fmt.Sprintf("error parsing operators: unsupported type %T", v)} |
| 1511 |
*errors = append(*errors, err) |
| 1512 |
} |
| 1513 |
// Assume for now these are file names, but they can also be the JWT itself inline. |
| 1514 |
o.TrustedOperators = make([]*jwt.OperatorClaims, 0, len(opFiles)) |
| 1515 |
for _, fname := range opFiles { |
| 1516 |
theJWT, opc, err := readOperatorJWT(fname) |
| 1517 |
if err != nil { |
| 1518 |
err := &configErr{tk, fmt.Sprintf("error parsing operator JWT: %v", err)} |
| 1519 |
*errors = append(*errors, err) |
| 1520 |
continue |
| 1521 |
} |
| 1522 |
o.operatorJWT = append(o.operatorJWT, theJWT) |
| 1523 |
o.TrustedOperators = append(o.TrustedOperators, opc) |
| 1524 |
} |
| 1525 |
if len(o.TrustedOperators) == 1 { |
| 1526 |
// In case "resolver" is defined as well, it takes precedence |
| 1527 |
if o.AccountResolver == nil { |
| 1528 |
if accUrl, err := parseURL(o.TrustedOperators[0].AccountServerURL, "account resolver"); err == nil { |
| 1529 |
// nsc automatically appends "/accounts" during nsc push |
| 1530 |
o.AccountResolver, _ = NewURLAccResolver(accUrl.String() + "/accounts") |
| 1531 |
} |
| 1532 |
} |
| 1533 |
// In case "system_account" is defined as well, it takes precedence |
| 1534 |
if o.SystemAccount == _EMPTY_ { |
| 1535 |
o.SystemAccount = o.TrustedOperators[0].SystemAccount |
| 1536 |
} |
| 1537 |
} |
| 1538 |
case "resolver", "account_resolver", "accounts_resolver": |
| 1539 |
switch v := v.(type) { |
| 1540 |
case string: |
| 1541 |
// "resolver" takes precedence over value obtained from "operator". |
| 1542 |
// Clear so that parsing errors are not silently ignored. |
| 1543 |
o.AccountResolver = nil |
| 1544 |
memResolverRe := regexp.MustCompile(`(?i)(MEM|MEMORY)\s*`) |
| 1545 |
resolverRe := regexp.MustCompile(`(?i)(?:URL){1}(?:\({1}\s*"?([^\s"]*)"?\s*\){1})?\s*`) |
| 1546 |
if memResolverRe.MatchString(v) { |
| 1547 |
o.AccountResolver = &MemAccResolver{} |
| 1548 |
} else if items := resolverRe.FindStringSubmatch(v); len(items) == 2 { |
| 1549 |
url := items[1] |
| 1550 |
_, err := parseURL(url, "account resolver") |
| 1551 |
if err != nil { |
| 1552 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 1553 |
return |
| 1554 |
} |
| 1555 |
if ur, err := NewURLAccResolver(url); err != nil { |
| 1556 |
err := &configErr{tk, err.Error()} |
| 1557 |
*errors = append(*errors, err) |
| 1558 |
return |
| 1559 |
} else { |
| 1560 |
o.AccountResolver = ur |
| 1561 |
} |
| 1562 |
} |
| 1563 |
case map[string]any: |
| 1564 |
del := false |
| 1565 |
hdel := false |
| 1566 |
hdel_set := false |
| 1567 |
dir := _EMPTY_ |
| 1568 |
dirType := _EMPTY_ |
| 1569 |
limit := int64(0) |
| 1570 |
ttl := time.Duration(0) |
| 1571 |
sync := time.Duration(0) |
| 1572 |
opts := []DirResOption{} |
| 1573 |
var err error |
| 1574 |
if v, ok := v["dir"]; ok { |
| 1575 |
_, v := unwrapValue(v, <) |
| 1576 |
dir = v.(string) |
| 1577 |
} |
| 1578 |
if v, ok := v["type"]; ok { |
| 1579 |
_, v := unwrapValue(v, <) |
| 1580 |
dirType = v.(string) |
| 1581 |
} |
| 1582 |
if v, ok := v["allow_delete"]; ok { |
| 1583 |
_, v := unwrapValue(v, <) |
| 1584 |
del = v.(bool) |
| 1585 |
} |
| 1586 |
if v, ok := v["hard_delete"]; ok { |
| 1587 |
_, v := unwrapValue(v, <) |
| 1588 |
hdel_set = true |
| 1589 |
hdel = v.(bool) |
| 1590 |
} |
| 1591 |
if v, ok := v["limit"]; ok { |
| 1592 |
_, v := unwrapValue(v, <) |
| 1593 |
limit = v.(int64) |
| 1594 |
} |
| 1595 |
if v, ok := v["ttl"]; ok { |
| 1596 |
_, v := unwrapValue(v, <) |
| 1597 |
ttl, err = time.ParseDuration(v.(string)) |
| 1598 |
} |
| 1599 |
if v, ok := v["interval"]; err == nil && ok { |
| 1600 |
_, v := unwrapValue(v, <) |
| 1601 |
sync, err = time.ParseDuration(v.(string)) |
| 1602 |
} |
| 1603 |
if v, ok := v["timeout"]; err == nil && ok { |
| 1604 |
_, v := unwrapValue(v, <) |
| 1605 |
var to time.Duration |
| 1606 |
if to, err = time.ParseDuration(v.(string)); err == nil { |
| 1607 |
opts = append(opts, FetchTimeout(to)) |
| 1608 |
} |
| 1609 |
} |
| 1610 |
if err != nil { |
| 1611 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 1612 |
return |
| 1613 |
} |
| 1614 |
|
| 1615 |
checkDir := func() { |
| 1616 |
if dir == _EMPTY_ { |
| 1617 |
*errors = append(*errors, &configErr{tk, "dir has no value and needs to point to a directory"}) |
| 1618 |
return |
| 1619 |
} |
| 1620 |
if info, _ := os.Stat(dir); info != nil && (!info.IsDir() || info.Mode().Perm()&(1<<(uint(7))) == 0) { |
| 1621 |
*errors = append(*errors, &configErr{tk, "dir needs to point to an accessible directory"}) |
| 1622 |
return |
| 1623 |
} |
| 1624 |
} |
| 1625 |
|
| 1626 |
var res AccountResolver |
| 1627 |
switch strings.ToUpper(dirType) { |
| 1628 |
case "CACHE": |
| 1629 |
checkDir() |
| 1630 |
if sync != 0 { |
| 1631 |
*errors = append(*errors, &configErr{tk, "CACHE does not accept sync"}) |
| 1632 |
} |
| 1633 |
if del { |
| 1634 |
*errors = append(*errors, &configErr{tk, "CACHE does not accept allow_delete"}) |
| 1635 |
} |
| 1636 |
if hdel_set { |
| 1637 |
*errors = append(*errors, &configErr{tk, "CACHE does not accept hard_delete"}) |
| 1638 |
} |
| 1639 |
res, err = NewCacheDirAccResolver(dir, limit, ttl, opts...) |
| 1640 |
case "FULL": |
| 1641 |
checkDir() |
| 1642 |
if ttl != 0 { |
| 1643 |
*errors = append(*errors, &configErr{tk, "FULL does not accept ttl"}) |
| 1644 |
} |
| 1645 |
if hdel_set && !del { |
| 1646 |
*errors = append(*errors, &configErr{tk, "hard_delete has no effect without delete"}) |
| 1647 |
} |
| 1648 |
delete := NoDelete |
| 1649 |
if del { |
| 1650 |
if hdel { |
| 1651 |
delete = HardDelete |
| 1652 |
} else { |
| 1653 |
delete = RenameDeleted |
| 1654 |
} |
| 1655 |
} |
| 1656 |
res, err = NewDirAccResolver(dir, limit, sync, delete, opts...) |
| 1657 |
case "MEM", "MEMORY": |
| 1658 |
res = &MemAccResolver{} |
| 1659 |
} |
| 1660 |
if err != nil { |
| 1661 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 1662 |
return |
| 1663 |
} |
| 1664 |
o.AccountResolver = res |
| 1665 |
default: |
| 1666 |
err := &configErr{tk, fmt.Sprintf("error parsing operator resolver, wrong type %T", v)} |
| 1667 |
*errors = append(*errors, err) |
| 1668 |
return |
| 1669 |
} |
| 1670 |
if o.AccountResolver == nil { |
| 1671 |
err := &configErr{tk, "error parsing account resolver, should be MEM or " + |
| 1672 |
" URL(\"url\") or a map containing dir and type state=[FULL|CACHE])"} |
| 1673 |
*errors = append(*errors, err) |
| 1674 |
} |
| 1675 |
case "resolver_tls": |
| 1676 |
tc, err := parseTLS(tk, true) |
| 1677 |
if err != nil { |
| 1678 |
*errors = append(*errors, err) |
| 1679 |
return |
| 1680 |
} |
| 1681 |
tlsConfig, err := GenTLSConfig(tc) |
| 1682 |
if err != nil { |
| 1683 |
err := &configErr{tk, err.Error()} |
| 1684 |
*errors = append(*errors, err) |
| 1685 |
return |
| 1686 |
} |
| 1687 |
o.AccountResolverTLSConfig = tlsConfig |
| 1688 |
// GenTLSConfig loads the CA file into ClientCAs, but since this will |
| 1689 |
// be used as a client connection, we need to set RootCAs. |
| 1690 |
o.AccountResolverTLSConfig.RootCAs = tlsConfig.ClientCAs |
| 1691 |
case "resolver_preload": |
| 1692 |
mp, ok := v.(map[string]any) |
| 1693 |
if !ok { |
| 1694 |
err := &configErr{tk, "preload should be a map of account_public_key:account_jwt"} |
| 1695 |
*errors = append(*errors, err) |
| 1696 |
return |
| 1697 |
} |
| 1698 |
o.resolverPreloads = make(map[string]string) |
| 1699 |
for key, val := range mp { |
| 1700 |
tk, val = unwrapValue(val, <) |
| 1701 |
if jwtstr, ok := val.(string); !ok { |
| 1702 |
*errors = append(*errors, &configErr{tk, "preload map value should be a string JWT"}) |
| 1703 |
continue |
| 1704 |
} else { |
| 1705 |
// Make sure this is a valid account JWT, that is a config error. |
| 1706 |
// We will warn of expirations, etc later. |
| 1707 |
if _, err := jwt.DecodeAccountClaims(jwtstr); err != nil { |
| 1708 |
err := &configErr{tk, "invalid account JWT"} |
| 1709 |
*errors = append(*errors, err) |
| 1710 |
continue |
| 1711 |
} |
| 1712 |
o.resolverPreloads[key] = jwtstr |
| 1713 |
} |
| 1714 |
} |
| 1715 |
case "resolver_pinned_accounts": |
| 1716 |
switch v := v.(type) { |
| 1717 |
case string: |
| 1718 |
o.resolverPinnedAccounts = map[string]struct{}{v: {}} |
| 1719 |
case []string: |
| 1720 |
o.resolverPinnedAccounts = make(map[string]struct{}) |
| 1721 |
for _, mv := range v { |
| 1722 |
o.resolverPinnedAccounts[mv] = struct{}{} |
| 1723 |
} |
| 1724 |
case []any: |
| 1725 |
o.resolverPinnedAccounts = make(map[string]struct{}) |
| 1726 |
for _, mv := range v { |
| 1727 |
tk, mv = unwrapValue(mv, <) |
| 1728 |
if key, ok := mv.(string); ok { |
| 1729 |
o.resolverPinnedAccounts[key] = struct{}{} |
| 1730 |
} else { |
| 1731 |
err := &configErr{tk, |
| 1732 |
fmt.Sprintf("error parsing resolver_pinned_accounts: unsupported type in array %T", mv)} |
| 1733 |
*errors = append(*errors, err) |
| 1734 |
continue |
| 1735 |
} |
| 1736 |
} |
| 1737 |
default: |
| 1738 |
err := &configErr{tk, fmt.Sprintf("error parsing resolver_pinned_accounts: unsupported type %T", v)} |
| 1739 |
*errors = append(*errors, err) |
| 1740 |
return |
| 1741 |
} |
| 1742 |
case "no_auth_user": |
| 1743 |
o.NoAuthUser = v.(string) |
| 1744 |
case "system_account", "system": |
| 1745 |
// Already processed at the beginning so we just skip them |
| 1746 |
// to not treat them as unknown values. |
| 1747 |
return |
| 1748 |
case "no_system_account", "no_system", "no_sys_acc": |
| 1749 |
o.NoSystemAccount = v.(bool) |
| 1750 |
case "no_header_support": |
| 1751 |
o.NoHeaderSupport = v.(bool) |
| 1752 |
case "trusted", "trusted_keys": |
| 1753 |
switch v := v.(type) { |
| 1754 |
case string: |
| 1755 |
o.TrustedKeys = []string{v} |
| 1756 |
case []string: |
| 1757 |
o.TrustedKeys = v |
| 1758 |
case []any: |
| 1759 |
keys := make([]string, 0, len(v)) |
| 1760 |
for _, mv := range v { |
| 1761 |
tk, mv = unwrapValue(mv, <) |
| 1762 |
if key, ok := mv.(string); ok { |
| 1763 |
keys = append(keys, key) |
| 1764 |
} else { |
| 1765 |
err := &configErr{tk, fmt.Sprintf("error parsing trusted: unsupported type in array %T", mv)} |
| 1766 |
*errors = append(*errors, err) |
| 1767 |
continue |
| 1768 |
} |
| 1769 |
} |
| 1770 |
o.TrustedKeys = keys |
| 1771 |
default: |
| 1772 |
err := &configErr{tk, fmt.Sprintf("error parsing trusted: unsupported type %T", v)} |
| 1773 |
*errors = append(*errors, err) |
| 1774 |
} |
| 1775 |
// Do a quick sanity check on keys |
| 1776 |
for _, key := range o.TrustedKeys { |
| 1777 |
if !nkeys.IsValidPublicOperatorKey(key) { |
| 1778 |
err := &configErr{tk, fmt.Sprintf("trust key %q required to be a valid public operator nkey", key)} |
| 1779 |
*errors = append(*errors, err) |
| 1780 |
} |
| 1781 |
} |
| 1782 |
case "connect_error_reports": |
| 1783 |
o.ConnectErrorReports = int(v.(int64)) |
| 1784 |
case "reconnect_error_reports": |
| 1785 |
o.ReconnectErrorReports = int(v.(int64)) |
| 1786 |
case "websocket", "ws": |
| 1787 |
if err := parseWebsocket(tk, o, errors, warnings); err != nil { |
| 1788 |
*errors = append(*errors, err) |
| 1789 |
return |
| 1790 |
} |
| 1791 |
case "mqtt": |
| 1792 |
if err := parseMQTT(tk, o, errors, warnings); err != nil { |
| 1793 |
*errors = append(*errors, err) |
| 1794 |
return |
| 1795 |
} |
| 1796 |
case "server_tags": |
| 1797 |
var err error |
| 1798 |
switch v := v.(type) { |
| 1799 |
case string: |
| 1800 |
o.Tags.Add(v) |
| 1801 |
case []string: |
| 1802 |
o.Tags.Add(v...) |
| 1803 |
case []any: |
| 1804 |
for _, t := range v { |
| 1805 |
if token, ok := t.(token); ok { |
| 1806 |
if ts, ok := token.Value().(string); ok { |
| 1807 |
o.Tags.Add(ts) |
| 1808 |
continue |
| 1809 |
} else { |
| 1810 |
err = &configErr{tk, fmt.Sprintf("error parsing tags: unsupported type %T where string is expected", token)} |
| 1811 |
} |
| 1812 |
} else { |
| 1813 |
err = &configErr{tk, fmt.Sprintf("error parsing tags: unsupported type %T", t)} |
| 1814 |
} |
| 1815 |
break |
| 1816 |
} |
| 1817 |
default: |
| 1818 |
err = &configErr{tk, fmt.Sprintf("error parsing tags: unsupported type %T", v)} |
| 1819 |
} |
| 1820 |
if err != nil { |
| 1821 |
*errors = append(*errors, err) |
| 1822 |
return |
| 1823 |
} |
| 1824 |
case "server_metadata": |
| 1825 |
var err error |
| 1826 |
switch v := v.(type) { |
| 1827 |
case map[string]any: |
| 1828 |
for mk, mv := range v { |
| 1829 |
tk, mv = unwrapValue(mv, <) |
| 1830 |
if o.Metadata == nil { |
| 1831 |
o.Metadata = make(map[string]string) |
| 1832 |
} |
| 1833 |
o.Metadata[mk] = mv.(string) |
| 1834 |
} |
| 1835 |
default: |
| 1836 |
err = &configErr{tk, fmt.Sprintf("error parsing metadata: unsupported type %T", v)} |
| 1837 |
} |
| 1838 |
if err != nil { |
| 1839 |
*errors = append(*errors, err) |
| 1840 |
return |
| 1841 |
} |
| 1842 |
case "feature_flags": |
| 1843 |
var err error |
| 1844 |
switch v := v.(type) { |
| 1845 |
case map[string]any: |
| 1846 |
for mk, mv := range v { |
| 1847 |
tk, mv = unwrapValue(mv, <) |
| 1848 |
b, ok := mv.(bool) |
| 1849 |
if !ok { |
| 1850 |
err = &configErr{tk, fmt.Sprintf("error parsing feature flag %q: expected bool, got %T", mk, mv)} |
| 1851 |
break |
| 1852 |
} |
| 1853 |
if o.FeatureFlags == nil { |
| 1854 |
o.FeatureFlags = make(map[string]bool) |
| 1855 |
} |
| 1856 |
o.FeatureFlags[mk] = b |
| 1857 |
} |
| 1858 |
default: |
| 1859 |
err = &configErr{tk, fmt.Sprintf("error parsing feature flags: unsupported type %T", v)} |
| 1860 |
} |
| 1861 |
if err != nil { |
| 1862 |
*errors = append(*errors, err) |
| 1863 |
return |
| 1864 |
} |
| 1865 |
case "default_js_domain": |
| 1866 |
vv, ok := v.(map[string]any) |
| 1867 |
if !ok { |
| 1868 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("error default_js_domain config: unsupported type %T", v)}) |
| 1869 |
return |
| 1870 |
} |
| 1871 |
m := make(map[string]string) |
| 1872 |
for kk, kv := range vv { |
| 1873 |
_, v = unwrapValue(kv, &tk) |
| 1874 |
m[kk] = v.(string) |
| 1875 |
} |
| 1876 |
o.JsAccDefaultDomain = m |
| 1877 |
case "ocsp_cache": |
| 1878 |
var err error |
| 1879 |
switch vv := v.(type) { |
| 1880 |
case bool: |
| 1881 |
pc := NewOCSPResponseCacheConfig() |
| 1882 |
if vv { |
| 1883 |
// Set enabled |
| 1884 |
pc.Type = LOCAL |
| 1885 |
o.OCSPCacheConfig = pc |
| 1886 |
} else { |
| 1887 |
// Set disabled (none cache) |
| 1888 |
pc.Type = NONE |
| 1889 |
o.OCSPCacheConfig = pc |
| 1890 |
} |
| 1891 |
case map[string]any: |
| 1892 |
pc, err := parseOCSPResponseCache(v) |
| 1893 |
if err != nil { |
| 1894 |
*errors = append(*errors, err) |
| 1895 |
return |
| 1896 |
} |
| 1897 |
o.OCSPCacheConfig = pc |
| 1898 |
default: |
| 1899 |
err = &configErr{tk, fmt.Sprintf("error parsing tags: unsupported type %T", v)} |
| 1900 |
} |
| 1901 |
if err != nil { |
| 1902 |
*errors = append(*errors, err) |
| 1903 |
return |
| 1904 |
} |
| 1905 |
case "no_fast_producer_stall": |
| 1906 |
o.NoFastProducerStall = v.(bool) |
| 1907 |
case "max_closed_clients": |
| 1908 |
o.MaxClosedClients = int(v.(int64)) |
| 1909 |
case "proxies": |
| 1910 |
proxies, err := parseProxies(tk, errors) |
| 1911 |
if err != nil { |
| 1912 |
*errors = append(*errors, err) |
| 1913 |
return |
| 1914 |
} |
| 1915 |
o.Proxies = proxies |
| 1916 |
default: |
| 1917 |
if au := atomic.LoadInt32(&allowUnknownTopLevelField); au == 0 && !tk.IsUsedVariable() { |
| 1918 |
err := &unknownConfigFieldErr{ |
| 1919 |
field: k, |
| 1920 |
configErr: configErr{ |
| 1921 |
token: tk, |
| 1922 |
}, |
| 1923 |
} |
| 1924 |
*errors = append(*errors, err) |
| 1925 |
} |
| 1926 |
} |
| 1927 |
} |
| 1928 |
|
| 1929 |
func setupUsersAndNKeysDuplicateCheckMap(o *Options) map[string]struct{} { |
| 1930 |
unames := make(map[string]struct{}, len(o.Users)+len(o.Nkeys)) |
| 1931 |
for _, u := range o.Users { |
| 1932 |
unames[u.Username] = struct{}{} |
| 1933 |
} |
| 1934 |
for _, u := range o.Nkeys { |
| 1935 |
unames[u.Nkey] = struct{}{} |
| 1936 |
} |
| 1937 |
return unames |
| 1938 |
} |
| 1939 |
|
| 1940 |
func parseDuration(field string, tk token, v any, errors *[]error, warnings *[]error) time.Duration { |
| 1941 |
if wd, ok := v.(string); ok { |
| 1942 |
if dur, err := time.ParseDuration(wd); err != nil { |
| 1943 |
err := &configErr{tk, fmt.Sprintf("error parsing %s: %v", field, err)} |
| 1944 |
*errors = append(*errors, err) |
| 1945 |
return 0 |
| 1946 |
} else { |
| 1947 |
return dur |
| 1948 |
} |
| 1949 |
} else { |
| 1950 |
// Backward compatible with old type, assume this is the |
| 1951 |
// number of seconds. |
| 1952 |
err := &configWarningErr{ |
| 1953 |
field: field, |
| 1954 |
configErr: configErr{ |
| 1955 |
token: tk, |
| 1956 |
reason: field + " should be converted to a duration", |
| 1957 |
}, |
| 1958 |
} |
| 1959 |
*warnings = append(*warnings, err) |
| 1960 |
return time.Duration(v.(int64)) * time.Second |
| 1961 |
} |
| 1962 |
} |
| 1963 |
|
| 1964 |
func parseWriteDeadlinePolicy(tk token, v string, errors *[]error) WriteTimeoutPolicy { |
| 1965 |
switch v { |
| 1966 |
case "default": |
| 1967 |
return WriteTimeoutPolicyDefault |
| 1968 |
case "close": |
| 1969 |
return WriteTimeoutPolicyClose |
| 1970 |
case "retry": |
| 1971 |
return WriteTimeoutPolicyRetry |
| 1972 |
default: |
| 1973 |
err := &configErr{tk, "write_timeout must be 'default', 'close' or 'retry'"} |
| 1974 |
*errors = append(*errors, err) |
| 1975 |
return WriteTimeoutPolicyDefault |
| 1976 |
} |
| 1977 |
} |
| 1978 |
|
| 1979 |
func trackExplicitVal(pm *map[string]bool, name string, val bool) { |
| 1980 |
m := *pm |
| 1981 |
if m == nil { |
| 1982 |
m = make(map[string]bool) |
| 1983 |
*pm = m |
| 1984 |
} |
| 1985 |
m[name] = val |
| 1986 |
} |
| 1987 |
|
| 1988 |
// hostPort is simple struct to hold parsed listen/addr strings. |
| 1989 |
type hostPort struct { |
| 1990 |
host string |
| 1991 |
port int |
| 1992 |
} |
| 1993 |
|
| 1994 |
// parseListen will parse listen option which is replacing host/net and port |
| 1995 |
func parseListen(v any) (*hostPort, error) { |
| 1996 |
hp := &hostPort{} |
| 1997 |
switch vv := v.(type) { |
| 1998 |
// Only a port |
| 1999 |
case int64: |
| 2000 |
hp.port = int(vv) |
| 2001 |
case string: |
| 2002 |
host, port, err := net.SplitHostPort(vv) |
| 2003 |
if err != nil { |
| 2004 |
return nil, fmt.Errorf("could not parse address string %q", vv) |
| 2005 |
} |
| 2006 |
hp.port, err = strconv.Atoi(port) |
| 2007 |
if err != nil { |
| 2008 |
return nil, fmt.Errorf("could not parse port %q", port) |
| 2009 |
} |
| 2010 |
hp.host = host |
| 2011 |
default: |
| 2012 |
return nil, fmt.Errorf("expected port or host:port, got %T", vv) |
| 2013 |
} |
| 2014 |
return hp, nil |
| 2015 |
} |
| 2016 |
|
| 2017 |
// parseCluster will parse the cluster config. |
| 2018 |
func parseCluster(v any, opts *Options, errors *[]error, warnings *[]error) error { |
| 2019 |
var lt token |
| 2020 |
defer convertPanicToErrorList(<, errors) |
| 2021 |
|
| 2022 |
tk, v := unwrapValue(v, <) |
| 2023 |
cm, ok := v.(map[string]any) |
| 2024 |
if !ok { |
| 2025 |
return &configErr{tk, fmt.Sprintf("Expected map to define cluster, got %T", v)} |
| 2026 |
} |
| 2027 |
|
| 2028 |
for mk, mv := range cm { |
| 2029 |
// Again, unwrap token value if line check is required. |
| 2030 |
tk, mv = unwrapValue(mv, <) |
| 2031 |
switch strings.ToLower(mk) { |
| 2032 |
case "name": |
| 2033 |
cn := mv.(string) |
| 2034 |
if strings.Contains(cn, " ") { |
| 2035 |
err := &configErr{tk, ErrClusterNameHasSpaces.Error()} |
| 2036 |
*errors = append(*errors, err) |
| 2037 |
continue |
| 2038 |
} |
| 2039 |
opts.Cluster.Name = cn |
| 2040 |
case "listen": |
| 2041 |
hp, err := parseListen(mv) |
| 2042 |
if err != nil { |
| 2043 |
err := &configErr{tk, err.Error()} |
| 2044 |
*errors = append(*errors, err) |
| 2045 |
continue |
| 2046 |
} |
| 2047 |
opts.Cluster.Host = hp.host |
| 2048 |
opts.Cluster.Port = hp.port |
| 2049 |
case "port": |
| 2050 |
opts.Cluster.Port = int(mv.(int64)) |
| 2051 |
case "host", "net": |
| 2052 |
opts.Cluster.Host = mv.(string) |
| 2053 |
case "authorization": |
| 2054 |
auth, err := parseAuthorization(tk, errors, warnings) |
| 2055 |
if err != nil { |
| 2056 |
*errors = append(*errors, err) |
| 2057 |
continue |
| 2058 |
} |
| 2059 |
if auth.users != nil { |
| 2060 |
err := &configErr{tk, "Cluster authorization does not allow multiple users"} |
| 2061 |
*errors = append(*errors, err) |
| 2062 |
continue |
| 2063 |
} |
| 2064 |
if auth.token != _EMPTY_ { |
| 2065 |
err := &configErr{tk, "Cluster authorization does not support tokens"} |
| 2066 |
*errors = append(*errors, err) |
| 2067 |
continue |
| 2068 |
} |
| 2069 |
if auth.callout != nil { |
| 2070 |
err := &configErr{tk, "Cluster authorization does not support callouts"} |
| 2071 |
*errors = append(*errors, err) |
| 2072 |
continue |
| 2073 |
} |
| 2074 |
|
| 2075 |
opts.Cluster.Username = auth.user |
| 2076 |
opts.Cluster.Password = auth.pass |
| 2077 |
opts.Cluster.AuthTimeout = auth.timeout |
| 2078 |
|
| 2079 |
if auth.defaultPermissions != nil { |
| 2080 |
if err := checkClusterPermissionSubjects(auth.defaultPermissions); err != nil { |
| 2081 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 2082 |
continue |
| 2083 |
} |
| 2084 |
err := &configWarningErr{ |
| 2085 |
field: mk, |
| 2086 |
configErr: configErr{ |
| 2087 |
token: tk, |
| 2088 |
reason: `setting "permissions" within cluster authorization block is deprecated`, |
| 2089 |
}, |
| 2090 |
} |
| 2091 |
*warnings = append(*warnings, err) |
| 2092 |
|
| 2093 |
// Do not set permissions if they were specified in top-level cluster block. |
| 2094 |
if opts.Cluster.Permissions == nil { |
| 2095 |
setClusterPermissions(&opts.Cluster, auth.defaultPermissions) |
| 2096 |
} |
| 2097 |
} |
| 2098 |
case "routes": |
| 2099 |
ra := mv.([]any) |
| 2100 |
routes, errs := parseURLs(ra, "route", warnings) |
| 2101 |
if errs != nil { |
| 2102 |
*errors = append(*errors, errs...) |
| 2103 |
continue |
| 2104 |
} |
| 2105 |
opts.Routes = routes |
| 2106 |
case "tls": |
| 2107 |
config, tlsopts, err := getTLSConfig(tk) |
| 2108 |
if err != nil { |
| 2109 |
*errors = append(*errors, err) |
| 2110 |
continue |
| 2111 |
} |
| 2112 |
opts.Cluster.TLSConfig = config |
| 2113 |
opts.Cluster.TLSTimeout = tlsopts.Timeout |
| 2114 |
opts.Cluster.TLSMap = tlsopts.Map |
| 2115 |
opts.Cluster.TLSPinnedCerts = tlsopts.PinnedCerts |
| 2116 |
opts.Cluster.TLSCheckKnownURLs = tlsopts.TLSCheckKnownURLs |
| 2117 |
opts.Cluster.tlsConfigOpts = tlsopts |
| 2118 |
case "cluster_advertise", "advertise": |
| 2119 |
opts.Cluster.Advertise = mv.(string) |
| 2120 |
case "no_advertise": |
| 2121 |
opts.Cluster.NoAdvertise = mv.(bool) |
| 2122 |
trackExplicitVal(&opts.inConfig, "Cluster.NoAdvertise", opts.Cluster.NoAdvertise) |
| 2123 |
case "connect_retries": |
| 2124 |
opts.Cluster.ConnectRetries = int(mv.(int64)) |
| 2125 |
case "connect_backoff": |
| 2126 |
opts.Cluster.ConnectBackoff = mv.(bool) |
| 2127 |
case "permissions": |
| 2128 |
perms, err := parseUserPermissions(mv, errors) |
| 2129 |
if err != nil { |
| 2130 |
*errors = append(*errors, err) |
| 2131 |
continue |
| 2132 |
} |
| 2133 |
// Dynamic response permissions do not make sense here. |
| 2134 |
if perms.Response != nil { |
| 2135 |
err := &configErr{tk, "Cluster permissions do not support dynamic responses"} |
| 2136 |
*errors = append(*errors, err) |
| 2137 |
continue |
| 2138 |
} |
| 2139 |
if err := checkClusterPermissionSubjects(perms); err != nil { |
| 2140 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 2141 |
continue |
| 2142 |
} |
| 2143 |
// This will possibly override permissions that were define in auth block |
| 2144 |
setClusterPermissions(&opts.Cluster, perms) |
| 2145 |
case "pool_size": |
| 2146 |
opts.Cluster.PoolSize = int(mv.(int64)) |
| 2147 |
case "accounts": |
| 2148 |
opts.Cluster.PinnedAccounts, _ = parseStringArray("accounts", tk, <, mv, errors) |
| 2149 |
case "compression": |
| 2150 |
if err := parseCompression(&opts.Cluster.Compression, CompressionS2Fast, tk, mk, mv); err != nil { |
| 2151 |
*errors = append(*errors, err) |
| 2152 |
continue |
| 2153 |
} |
| 2154 |
case "ping_interval": |
| 2155 |
opts.Cluster.PingInterval = parseDuration("ping_interval", tk, mv, errors, warnings) |
| 2156 |
if opts.Cluster.PingInterval > routeMaxPingInterval { |
| 2157 |
*warnings = append(*warnings, &configErr{tk, fmt.Sprintf("Cluster 'ping_interval' will reset to %v which is the max for routes", routeMaxPingInterval)}) |
| 2158 |
} |
| 2159 |
case "ping_max": |
| 2160 |
opts.Cluster.MaxPingsOut = int(mv.(int64)) |
| 2161 |
case "write_deadline": |
| 2162 |
opts.Cluster.WriteDeadline = parseDuration("write_deadline", tk, mv, errors, warnings) |
| 2163 |
case "write_timeout": |
| 2164 |
opts.Cluster.WriteTimeout = parseWriteDeadlinePolicy(tk, mv.(string), errors) |
| 2165 |
default: |
| 2166 |
if !tk.IsUsedVariable() { |
| 2167 |
err := &unknownConfigFieldErr{ |
| 2168 |
field: mk, |
| 2169 |
configErr: configErr{ |
| 2170 |
token: tk, |
| 2171 |
}, |
| 2172 |
} |
| 2173 |
*errors = append(*errors, err) |
| 2174 |
continue |
| 2175 |
} |
| 2176 |
} |
| 2177 |
} |
| 2178 |
return nil |
| 2179 |
} |
| 2180 |
|
| 2181 |
// The parameter `chosenModeForOn` indicates which compression mode to use |
| 2182 |
// when the user selects "on" (or enabled, true, etc..). This is because |
| 2183 |
// we may have different defaults depending on where the compression is used. |
| 2184 |
func parseCompression(c *CompressionOpts, chosenModeForOn string, tk token, mk string, mv any) (retErr error) { |
| 2185 |
var lt token |
| 2186 |
defer convertPanicToError(<, &retErr) |
| 2187 |
|
| 2188 |
switch mv := mv.(type) { |
| 2189 |
case string: |
| 2190 |
// Do not validate here, it will be done in NewServer. |
| 2191 |
c.Mode = mv |
| 2192 |
case bool: |
| 2193 |
if mv { |
| 2194 |
c.Mode = chosenModeForOn |
| 2195 |
} else { |
| 2196 |
c.Mode = CompressionOff |
| 2197 |
} |
| 2198 |
case map[string]any: |
| 2199 |
for mk, mv := range mv { |
| 2200 |
tk, mv = unwrapValue(mv, <) |
| 2201 |
switch strings.ToLower(mk) { |
| 2202 |
case "mode": |
| 2203 |
c.Mode = mv.(string) |
| 2204 |
case "rtt_thresholds", "thresholds", "rtts", "rtt": |
| 2205 |
for _, iv := range mv.([]any) { |
| 2206 |
_, mv := unwrapValue(iv, <) |
| 2207 |
dur, err := time.ParseDuration(mv.(string)) |
| 2208 |
if err != nil { |
| 2209 |
return &configErr{tk, err.Error()} |
| 2210 |
} |
| 2211 |
c.RTTThresholds = append(c.RTTThresholds, dur) |
| 2212 |
} |
| 2213 |
default: |
| 2214 |
if !tk.IsUsedVariable() { |
| 2215 |
return &configErr{tk, fmt.Sprintf("unknown field %q", mk)} |
| 2216 |
} |
| 2217 |
} |
| 2218 |
} |
| 2219 |
default: |
| 2220 |
return &configErr{tk, fmt.Sprintf("field %q should be a boolean or a structure, got %T", mk, mv)} |
| 2221 |
} |
| 2222 |
return nil |
| 2223 |
} |
| 2224 |
|
| 2225 |
func parseURLs(a []any, typ string, warnings *[]error) (urls []*url.URL, errors []error) { |
| 2226 |
urls = make([]*url.URL, 0, len(a)) |
| 2227 |
var lt token |
| 2228 |
defer convertPanicToErrorList(<, &errors) |
| 2229 |
|
| 2230 |
dd := make(map[string]bool) |
| 2231 |
|
| 2232 |
for _, u := range a { |
| 2233 |
tk, u := unwrapValue(u, <) |
| 2234 |
sURL := u.(string) |
| 2235 |
if dd[sURL] { |
| 2236 |
err := &configWarningErr{ |
| 2237 |
field: sURL, |
| 2238 |
configErr: configErr{ |
| 2239 |
token: tk, |
| 2240 |
reason: fmt.Sprintf("Duplicate %s entry detected", typ), |
| 2241 |
}, |
| 2242 |
} |
| 2243 |
*warnings = append(*warnings, err) |
| 2244 |
continue |
| 2245 |
} |
| 2246 |
dd[sURL] = true |
| 2247 |
url, err := parseURL(sURL, typ) |
| 2248 |
if err != nil { |
| 2249 |
err := &configErr{tk, err.Error()} |
| 2250 |
errors = append(errors, err) |
| 2251 |
continue |
| 2252 |
} |
| 2253 |
urls = append(urls, url) |
| 2254 |
} |
| 2255 |
return urls, errors |
| 2256 |
} |
| 2257 |
|
| 2258 |
func parseURL(u string, typ string) (*url.URL, error) { |
| 2259 |
urlStr := strings.TrimSpace(u) |
| 2260 |
url, err := url.Parse(urlStr) |
| 2261 |
if err != nil { |
| 2262 |
// Security note: if it's not well-formed but still reached us, then we're going to log as-is which might include password information here. |
| 2263 |
// If the URL parses, we don't log the credentials ever, but if it doesn't even parse we don't have a sane way to redact. |
| 2264 |
return nil, fmt.Errorf("error parsing %s url [%q]", typ, urlStr) |
| 2265 |
} |
| 2266 |
return url, nil |
| 2267 |
} |
| 2268 |
|
| 2269 |
func parseGateway(v any, o *Options, errors *[]error, warnings *[]error) error { |
| 2270 |
var lt token |
| 2271 |
defer convertPanicToErrorList(<, errors) |
| 2272 |
|
| 2273 |
tk, v := unwrapValue(v, <) |
| 2274 |
gm, ok := v.(map[string]any) |
| 2275 |
if !ok { |
| 2276 |
return &configErr{tk, fmt.Sprintf("Expected gateway to be a map, got %T", v)} |
| 2277 |
} |
| 2278 |
for mk, mv := range gm { |
| 2279 |
// Again, unwrap token value if line check is required. |
| 2280 |
tk, mv = unwrapValue(mv, <) |
| 2281 |
switch strings.ToLower(mk) { |
| 2282 |
case "name": |
| 2283 |
gn := mv.(string) |
| 2284 |
if strings.Contains(gn, " ") { |
| 2285 |
err := &configErr{tk, ErrGatewayNameHasSpaces.Error()} |
| 2286 |
*errors = append(*errors, err) |
| 2287 |
continue |
| 2288 |
} |
| 2289 |
o.Gateway.Name = gn |
| 2290 |
case "listen": |
| 2291 |
hp, err := parseListen(mv) |
| 2292 |
if err != nil { |
| 2293 |
err := &configErr{tk, err.Error()} |
| 2294 |
*errors = append(*errors, err) |
| 2295 |
continue |
| 2296 |
} |
| 2297 |
o.Gateway.Host = hp.host |
| 2298 |
o.Gateway.Port = hp.port |
| 2299 |
case "port": |
| 2300 |
o.Gateway.Port = int(mv.(int64)) |
| 2301 |
case "host", "net": |
| 2302 |
o.Gateway.Host = mv.(string) |
| 2303 |
case "authorization": |
| 2304 |
auth, err := parseAuthorization(tk, errors, warnings) |
| 2305 |
if err != nil { |
| 2306 |
*errors = append(*errors, err) |
| 2307 |
continue |
| 2308 |
} |
| 2309 |
if auth.users != nil { |
| 2310 |
*errors = append(*errors, &configErr{tk, "Gateway authorization does not allow multiple users"}) |
| 2311 |
continue |
| 2312 |
} |
| 2313 |
if auth.token != _EMPTY_ { |
| 2314 |
err := &configErr{tk, "Gateway authorization does not support tokens"} |
| 2315 |
*errors = append(*errors, err) |
| 2316 |
continue |
| 2317 |
} |
| 2318 |
if auth.callout != nil { |
| 2319 |
err := &configErr{tk, "Gateway authorization does not support callouts"} |
| 2320 |
*errors = append(*errors, err) |
| 2321 |
continue |
| 2322 |
} |
| 2323 |
|
| 2324 |
o.Gateway.Username = auth.user |
| 2325 |
o.Gateway.Password = auth.pass |
| 2326 |
o.Gateway.AuthTimeout = auth.timeout |
| 2327 |
case "tls": |
| 2328 |
config, tlsopts, err := getTLSConfig(tk) |
| 2329 |
if err != nil { |
| 2330 |
*errors = append(*errors, err) |
| 2331 |
continue |
| 2332 |
} |
| 2333 |
o.Gateway.TLSConfig = config |
| 2334 |
o.Gateway.TLSTimeout = tlsopts.Timeout |
| 2335 |
o.Gateway.TLSMap = tlsopts.Map |
| 2336 |
o.Gateway.TLSCheckKnownURLs = tlsopts.TLSCheckKnownURLs |
| 2337 |
o.Gateway.TLSPinnedCerts = tlsopts.PinnedCerts |
| 2338 |
o.Gateway.tlsConfigOpts = tlsopts |
| 2339 |
case "advertise": |
| 2340 |
o.Gateway.Advertise = mv.(string) |
| 2341 |
case "connect_retries": |
| 2342 |
o.Gateway.ConnectRetries = int(mv.(int64)) |
| 2343 |
case "connect_backoff": |
| 2344 |
o.Gateway.ConnectBackoff = mv.(bool) |
| 2345 |
case "gateways": |
| 2346 |
gateways, err := parseGateways(mv, errors, warnings) |
| 2347 |
if err != nil { |
| 2348 |
return err |
| 2349 |
} |
| 2350 |
o.Gateway.Gateways = gateways |
| 2351 |
case "reject_unknown", "reject_unknown_cluster": |
| 2352 |
o.Gateway.RejectUnknown = mv.(bool) |
| 2353 |
case "write_deadline": |
| 2354 |
o.Gateway.WriteDeadline = parseDuration("write_deadline", tk, mv, errors, warnings) |
| 2355 |
case "write_timeout": |
| 2356 |
o.Gateway.WriteTimeout = parseWriteDeadlinePolicy(tk, mv.(string), errors) |
| 2357 |
default: |
| 2358 |
if !tk.IsUsedVariable() { |
| 2359 |
err := &unknownConfigFieldErr{ |
| 2360 |
field: mk, |
| 2361 |
configErr: configErr{ |
| 2362 |
token: tk, |
| 2363 |
}, |
| 2364 |
} |
| 2365 |
*errors = append(*errors, err) |
| 2366 |
continue |
| 2367 |
} |
| 2368 |
} |
| 2369 |
} |
| 2370 |
return nil |
| 2371 |
} |
| 2372 |
|
| 2373 |
var dynamicJSAccountLimits = JetStreamAccountLimits{-1, -1, -1, -1, -1, -1, -1, false} |
| 2374 |
var defaultJSAccountTiers = map[string]JetStreamAccountLimits{_EMPTY_: dynamicJSAccountLimits} |
| 2375 |
|
| 2376 |
// Parses jetstream account limits for an account. Simple setup with boolen is allowed, and we will |
| 2377 |
// use dynamic account limits. |
| 2378 |
func parseJetStreamForAccount(v any, acc *Account, errors *[]error) error { |
| 2379 |
var lt token |
| 2380 |
|
| 2381 |
tk, v := unwrapValue(v, <) |
| 2382 |
|
| 2383 |
// Value here can be bool, or string "enabled" or a map. |
| 2384 |
switch vv := v.(type) { |
| 2385 |
case bool: |
| 2386 |
if vv { |
| 2387 |
acc.jsLimits = defaultJSAccountTiers |
| 2388 |
} |
| 2389 |
case string: |
| 2390 |
switch strings.ToLower(vv) { |
| 2391 |
case "enabled", "enable": |
| 2392 |
acc.jsLimits = defaultJSAccountTiers |
| 2393 |
case "disabled", "disable": |
| 2394 |
acc.jsLimits = nil |
| 2395 |
default: |
| 2396 |
return &configErr{tk, fmt.Sprintf("Expected 'enabled' or 'disabled' for string value, got '%s'", vv)} |
| 2397 |
} |
| 2398 |
case map[string]any: |
| 2399 |
jsLimits := JetStreamAccountLimits{-1, -1, -1, -1, -1, -1, -1, false} |
| 2400 |
for mk, mv := range vv { |
| 2401 |
tk, mv = unwrapValue(mv, <) |
| 2402 |
switch strings.ToLower(mk) { |
| 2403 |
case "max_memory", "max_mem", "mem", "memory": |
| 2404 |
vv, ok := mv.(int64) |
| 2405 |
if !ok { |
| 2406 |
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)} |
| 2407 |
} |
| 2408 |
jsLimits.MaxMemory = vv |
| 2409 |
case "max_store", "max_file", "max_disk", "store", "disk": |
| 2410 |
vv, ok := mv.(int64) |
| 2411 |
if !ok { |
| 2412 |
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)} |
| 2413 |
} |
| 2414 |
jsLimits.MaxStore = vv |
| 2415 |
case "max_streams", "streams": |
| 2416 |
vv, ok := mv.(int64) |
| 2417 |
if !ok { |
| 2418 |
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)} |
| 2419 |
} |
| 2420 |
jsLimits.MaxStreams = int(vv) |
| 2421 |
case "max_consumers", "consumers": |
| 2422 |
vv, ok := mv.(int64) |
| 2423 |
if !ok { |
| 2424 |
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)} |
| 2425 |
} |
| 2426 |
jsLimits.MaxConsumers = int(vv) |
| 2427 |
case "max_bytes_required", "max_stream_bytes", "max_bytes": |
| 2428 |
vv, ok := mv.(bool) |
| 2429 |
if !ok { |
| 2430 |
return &configErr{tk, fmt.Sprintf("Expected a parseable bool for %q, got %v", mk, mv)} |
| 2431 |
} |
| 2432 |
jsLimits.MaxBytesRequired = vv |
| 2433 |
case "mem_max_stream_bytes", "memory_max_stream_bytes": |
| 2434 |
vv, ok := mv.(int64) |
| 2435 |
if !ok { |
| 2436 |
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)} |
| 2437 |
} |
| 2438 |
jsLimits.MemoryMaxStreamBytes = vv |
| 2439 |
case "disk_max_stream_bytes", "store_max_stream_bytes": |
| 2440 |
vv, ok := mv.(int64) |
| 2441 |
if !ok { |
| 2442 |
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)} |
| 2443 |
} |
| 2444 |
jsLimits.StoreMaxStreamBytes = vv |
| 2445 |
case "max_ack_pending": |
| 2446 |
vv, ok := mv.(int64) |
| 2447 |
if !ok { |
| 2448 |
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)} |
| 2449 |
} |
| 2450 |
jsLimits.MaxAckPending = int(vv) |
| 2451 |
case "cluster_traffic": |
| 2452 |
vv, ok := mv.(string) |
| 2453 |
if !ok { |
| 2454 |
return &configErr{tk, fmt.Sprintf("Expected either 'system' or 'owner' string value for %q, got %v", mk, mv)} |
| 2455 |
} |
| 2456 |
switch vv { |
| 2457 |
case "system", _EMPTY_: |
| 2458 |
acc.nrgAccount = _EMPTY_ |
| 2459 |
case "owner": |
| 2460 |
acc.nrgAccount = acc.Name |
| 2461 |
default: |
| 2462 |
return &configErr{tk, fmt.Sprintf("Expected 'system' or 'owner' string value for %q, got %v", mk, mv)} |
| 2463 |
} |
| 2464 |
default: |
| 2465 |
if !tk.IsUsedVariable() { |
| 2466 |
err := &unknownConfigFieldErr{ |
| 2467 |
field: mk, |
| 2468 |
configErr: configErr{ |
| 2469 |
token: tk, |
| 2470 |
}, |
| 2471 |
} |
| 2472 |
*errors = append(*errors, err) |
| 2473 |
continue |
| 2474 |
} |
| 2475 |
} |
| 2476 |
} |
| 2477 |
acc.jsLimits = map[string]JetStreamAccountLimits{_EMPTY_: jsLimits} |
| 2478 |
default: |
| 2479 |
return &configErr{tk, fmt.Sprintf("Expected map, bool or string to define JetStream, got %T", v)} |
| 2480 |
} |
| 2481 |
return nil |
| 2482 |
} |
| 2483 |
|
| 2484 |
// takes in a storage size as either an int or a string and returns an int64 value based on the input. |
| 2485 |
func getStorageSize(v any) (int64, error) { |
| 2486 |
_, ok := v.(int64) |
| 2487 |
if ok { |
| 2488 |
return v.(int64), nil |
| 2489 |
} |
| 2490 |
|
| 2491 |
s, ok := v.(string) |
| 2492 |
if !ok { |
| 2493 |
return 0, fmt.Errorf("must be int64 or string") |
| 2494 |
} |
| 2495 |
|
| 2496 |
if s == _EMPTY_ { |
| 2497 |
return 0, nil |
| 2498 |
} |
| 2499 |
|
| 2500 |
suffix := s[len(s)-1:] |
| 2501 |
prefix := s[:len(s)-1] |
| 2502 |
num, err := strconv.ParseInt(prefix, 10, 64) |
| 2503 |
if err != nil { |
| 2504 |
return 0, err |
| 2505 |
} |
| 2506 |
|
| 2507 |
suffixMap := map[string]int64{"K": 10, "M": 20, "G": 30, "T": 40} |
| 2508 |
|
| 2509 |
mult, ok := suffixMap[suffix] |
| 2510 |
if !ok { |
| 2511 |
return 0, fmt.Errorf("sizes defined as strings must end in K, M, G, T") |
| 2512 |
} |
| 2513 |
num *= 1 << mult |
| 2514 |
|
| 2515 |
return num, nil |
| 2516 |
} |
| 2517 |
|
| 2518 |
// Parse enablement of jetstream for a server. |
| 2519 |
func parseJetStreamLimits(v any, opts *Options, errors *[]error) error { |
| 2520 |
var lt token |
| 2521 |
tk, v := unwrapValue(v, <) |
| 2522 |
|
| 2523 |
opts.JetStreamLimits = JSLimitOpts{} |
| 2524 |
|
| 2525 |
vv, ok := v.(map[string]any) |
| 2526 |
if !ok { |
| 2527 |
return &configErr{tk, fmt.Sprintf("Expected a map to define JetStreamLimits, got %T", v)} |
| 2528 |
} |
| 2529 |
for mk, mv := range vv { |
| 2530 |
tk, mv = unwrapValue(mv, <) |
| 2531 |
switch strings.ToLower(mk) { |
| 2532 |
case "max_ack_pending": |
| 2533 |
opts.JetStreamLimits.MaxAckPending = int(mv.(int64)) |
| 2534 |
case "max_ha_assets": |
| 2535 |
opts.JetStreamLimits.MaxHAAssets = int(mv.(int64)) |
| 2536 |
case "max_request_batch": |
| 2537 |
opts.JetStreamLimits.MaxRequestBatch = int(mv.(int64)) |
| 2538 |
case "duplicate_window": |
| 2539 |
var err error |
| 2540 |
opts.JetStreamLimits.Duplicates, err = time.ParseDuration(mv.(string)) |
| 2541 |
if err != nil { |
| 2542 |
*errors = append(*errors, err) |
| 2543 |
} |
| 2544 |
case "batch": |
| 2545 |
if err := parseJetStreamLimitsBatch(tk, opts, errors); err != nil { |
| 2546 |
return err |
| 2547 |
} |
| 2548 |
default: |
| 2549 |
if !tk.IsUsedVariable() { |
| 2550 |
err := &unknownConfigFieldErr{ |
| 2551 |
field: mk, |
| 2552 |
configErr: configErr{ |
| 2553 |
token: tk, |
| 2554 |
}, |
| 2555 |
} |
| 2556 |
*errors = append(*errors, err) |
| 2557 |
continue |
| 2558 |
} |
| 2559 |
} |
| 2560 |
} |
| 2561 |
return nil |
| 2562 |
} |
| 2563 |
|
| 2564 |
func parseJetStreamLimitsBatch(v any, opts *Options, errors *[]error) error { |
| 2565 |
var lt token |
| 2566 |
tk, v := unwrapValue(v, <) |
| 2567 |
|
| 2568 |
vv, ok := v.(map[string]any) |
| 2569 |
if !ok { |
| 2570 |
return &configErr{tk, fmt.Sprintf("Expected a map to define batch limits, got %T", v)} |
| 2571 |
} |
| 2572 |
for mk, mv := range vv { |
| 2573 |
tk, mv = unwrapValue(mv, <) |
| 2574 |
switch strings.ToLower(mk) { |
| 2575 |
case "max_inflight_per_stream": |
| 2576 |
opts.JetStreamLimits.MaxBatchInflightPerStream = int(mv.(int64)) |
| 2577 |
case "max_inflight_total": |
| 2578 |
opts.JetStreamLimits.MaxBatchInflightTotal = int(mv.(int64)) |
| 2579 |
case "max_msgs": |
| 2580 |
opts.JetStreamLimits.MaxBatchSize = int(mv.(int64)) |
| 2581 |
case "timeout": |
| 2582 |
var err error |
| 2583 |
opts.JetStreamLimits.MaxBatchTimeout, err = time.ParseDuration(mv.(string)) |
| 2584 |
if err != nil { |
| 2585 |
*errors = append(*errors, err) |
| 2586 |
} |
| 2587 |
default: |
| 2588 |
if !tk.IsUsedVariable() { |
| 2589 |
err := &unknownConfigFieldErr{ |
| 2590 |
field: mk, |
| 2591 |
configErr: configErr{ |
| 2592 |
token: tk, |
| 2593 |
}, |
| 2594 |
} |
| 2595 |
*errors = append(*errors, err) |
| 2596 |
continue |
| 2597 |
} |
| 2598 |
} |
| 2599 |
} |
| 2600 |
return nil |
| 2601 |
} |
| 2602 |
|
| 2603 |
// Parse the JetStream TPM options. |
| 2604 |
func parseJetStreamTPM(v interface{}, opts *Options, errors *[]error) error { |
| 2605 |
var lt token |
| 2606 |
tk, v := unwrapValue(v, <) |
| 2607 |
|
| 2608 |
opts.JetStreamTpm = JSTpmOpts{} |
| 2609 |
|
| 2610 |
vv, ok := v.(map[string]interface{}) |
| 2611 |
if !ok { |
| 2612 |
return &configErr{tk, fmt.Sprintf("Expected a map to define JetStreamLimits, got %T", v)} |
| 2613 |
} |
| 2614 |
for mk, mv := range vv { |
| 2615 |
tk, mv = unwrapValue(mv, <) |
| 2616 |
switch strings.ToLower(mk) { |
| 2617 |
case "keys_file": |
| 2618 |
opts.JetStreamTpm.KeysFile = mv.(string) |
| 2619 |
case "encryption_password": |
| 2620 |
opts.JetStreamTpm.KeyPassword = mv.(string) |
| 2621 |
case "srk_password": |
| 2622 |
opts.JetStreamTpm.SrkPassword = mv.(string) |
| 2623 |
case "pcr": |
| 2624 |
opts.JetStreamTpm.Pcr = int(mv.(int64)) |
| 2625 |
case "cipher": |
| 2626 |
if err := setJetStreamEkCipher(opts, mv, tk); err != nil { |
| 2627 |
return err |
| 2628 |
} |
| 2629 |
default: |
| 2630 |
if !tk.IsUsedVariable() { |
| 2631 |
err := &unknownConfigFieldErr{ |
| 2632 |
field: mk, |
| 2633 |
configErr: configErr{ |
| 2634 |
token: tk, |
| 2635 |
}, |
| 2636 |
} |
| 2637 |
*errors = append(*errors, err) |
| 2638 |
continue |
| 2639 |
} |
| 2640 |
} |
| 2641 |
} |
| 2642 |
return nil |
| 2643 |
} |
| 2644 |
|
| 2645 |
func setJetStreamEkCipher(opts *Options, mv interface{}, tk token) error { |
| 2646 |
switch strings.ToLower(mv.(string)) { |
| 2647 |
case "chacha", "chachapoly": |
| 2648 |
if fips140.Enabled() { |
| 2649 |
return &configErr{tk, fmt.Sprintf("Cipher type %q cannot be used in FIPS-140 mode", mv)} |
| 2650 |
} |
| 2651 |
opts.JetStreamCipher = ChaCha |
| 2652 |
case "aes": |
| 2653 |
opts.JetStreamCipher = AES |
| 2654 |
default: |
| 2655 |
return &configErr{tk, fmt.Sprintf("Unknown cipher type: %q", mv)} |
| 2656 |
} |
| 2657 |
return nil |
| 2658 |
} |
| 2659 |
|
| 2660 |
// Parse enablement of jetstream for a server. |
| 2661 |
func parseJetStream(v any, opts *Options, errors *[]error, warnings *[]error) error { |
| 2662 |
var lt token |
| 2663 |
|
| 2664 |
tk, v := unwrapValue(v, <) |
| 2665 |
|
| 2666 |
// Value here can be bool, or string "enabled" or a map. |
| 2667 |
switch vv := v.(type) { |
| 2668 |
case bool: |
| 2669 |
opts.JetStream = v.(bool) |
| 2670 |
case string: |
| 2671 |
switch strings.ToLower(vv) { |
| 2672 |
case "enabled", "enable": |
| 2673 |
opts.JetStream = true |
| 2674 |
case "disabled", "disable": |
| 2675 |
opts.JetStream = false |
| 2676 |
default: |
| 2677 |
return &configErr{tk, fmt.Sprintf("Expected 'enabled' or 'disabled' for string value, got '%s'", vv)} |
| 2678 |
} |
| 2679 |
case map[string]any: |
| 2680 |
doEnable := true |
| 2681 |
for mk, mv := range vv { |
| 2682 |
tk, mv = unwrapValue(mv, <) |
| 2683 |
switch strings.ToLower(mk) { |
| 2684 |
case "strict": |
| 2685 |
if v, ok := mv.(bool); ok { |
| 2686 |
opts.NoJetStreamStrict = !v |
| 2687 |
} else { |
| 2688 |
return &configErr{tk, fmt.Sprintf("Expected 'true' or 'false' for bool value, got '%s'", mv)} |
| 2689 |
} |
| 2690 |
case "store", "store_dir", "storedir": |
| 2691 |
// StoreDir can be set at the top level as well so have to prevent ambiguous declarations. |
| 2692 |
if opts.StoreDir != _EMPTY_ { |
| 2693 |
return &configErr{tk, "Duplicate 'store_dir' configuration"} |
| 2694 |
} |
| 2695 |
opts.StoreDir = mv.(string) |
| 2696 |
case "sync", "sync_interval": |
| 2697 |
if v, ok := mv.(string); ok && strings.ToLower(v) == "always" { |
| 2698 |
opts.SyncInterval = defaultSyncInterval |
| 2699 |
opts.SyncAlways = true |
| 2700 |
} else { |
| 2701 |
opts.SyncInterval = parseDuration(mk, tk, mv, errors, warnings) |
| 2702 |
} |
| 2703 |
opts.syncSet = true |
| 2704 |
case "max_memory_store", "max_mem_store", "max_mem": |
| 2705 |
s, err := getStorageSize(mv) |
| 2706 |
if err != nil { |
| 2707 |
return &configErr{tk, fmt.Sprintf("max_mem_store %s", err)} |
| 2708 |
} |
| 2709 |
opts.JetStreamMaxMemory = s |
| 2710 |
opts.maxMemSet = true |
| 2711 |
case "max_file_store", "max_file": |
| 2712 |
s, err := getStorageSize(mv) |
| 2713 |
if err != nil { |
| 2714 |
return &configErr{tk, fmt.Sprintf("max_file_store %s", err)} |
| 2715 |
} |
| 2716 |
opts.JetStreamMaxStore = s |
| 2717 |
opts.maxStoreSet = true |
| 2718 |
case "domain": |
| 2719 |
opts.JetStreamDomain = mv.(string) |
| 2720 |
case "enable", "enabled": |
| 2721 |
doEnable = mv.(bool) |
| 2722 |
case "key", "ek", "encryption_key": |
| 2723 |
opts.JetStreamKey = mv.(string) |
| 2724 |
case "prev_key", "prev_ek", "prev_encryption_key": |
| 2725 |
opts.JetStreamOldKey = mv.(string) |
| 2726 |
case "cipher": |
| 2727 |
if err := setJetStreamEkCipher(opts, mv, tk); err != nil { |
| 2728 |
return err |
| 2729 |
} |
| 2730 |
case "extension_hint": |
| 2731 |
opts.JetStreamExtHint = mv.(string) |
| 2732 |
case "limits": |
| 2733 |
if err := parseJetStreamLimits(tk, opts, errors); err != nil { |
| 2734 |
return err |
| 2735 |
} |
| 2736 |
case "tpm": |
| 2737 |
if err := parseJetStreamTPM(tk, opts, errors); err != nil { |
| 2738 |
return err |
| 2739 |
} |
| 2740 |
case "unique_tag": |
| 2741 |
opts.JetStreamUniqueTag = strings.ToLower(strings.TrimSpace(mv.(string))) |
| 2742 |
case "max_outstanding_catchup": |
| 2743 |
s, err := getStorageSize(mv) |
| 2744 |
if err != nil { |
| 2745 |
return &configErr{tk, fmt.Sprintf("%s %s", strings.ToLower(mk), err)} |
| 2746 |
} |
| 2747 |
opts.JetStreamMaxCatchup = s |
| 2748 |
case "max_buffered_size": |
| 2749 |
s, err := getStorageSize(mv) |
| 2750 |
if err != nil { |
| 2751 |
return &configErr{tk, fmt.Sprintf("%s %s", strings.ToLower(mk), err)} |
| 2752 |
} |
| 2753 |
opts.StreamMaxBufferedSize = s |
| 2754 |
case "max_buffered_msgs": |
| 2755 |
mlen, ok := mv.(int64) |
| 2756 |
if !ok { |
| 2757 |
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)} |
| 2758 |
} |
| 2759 |
opts.StreamMaxBufferedMsgs = int(mlen) |
| 2760 |
case "request_queue_limit": |
| 2761 |
lim, ok := mv.(int64) |
| 2762 |
if !ok { |
| 2763 |
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)} |
| 2764 |
} |
| 2765 |
opts.JetStreamRequestQueueLimit = lim |
| 2766 |
case "info_queue_limit": |
| 2767 |
lim, ok := mv.(int64) |
| 2768 |
if !ok { |
| 2769 |
return &configErr{tk, fmt.Sprintf("Expected a parseable size for %q, got %v", mk, mv)} |
| 2770 |
} |
| 2771 |
opts.JetStreamInfoQueueLimit = lim |
| 2772 |
case "meta_compact": |
| 2773 |
thres, ok := mv.(int64) |
| 2774 |
if !ok || thres < 0 { |
| 2775 |
return &configErr{tk, fmt.Sprintf("Expected an absolute size for %q, got %v", mk, mv)} |
| 2776 |
} |
| 2777 |
opts.JetStreamMetaCompact = uint64(thres) |
| 2778 |
case "meta_compact_size": |
| 2779 |
s, err := getStorageSize(mv) |
| 2780 |
if err != nil { |
| 2781 |
return &configErr{tk, fmt.Sprintf("%s %s", strings.ToLower(mk), err)} |
| 2782 |
} |
| 2783 |
if s < 0 { |
| 2784 |
return &configErr{tk, fmt.Sprintf("Expected an absolute size for %q, got %v", mk, mv)} |
| 2785 |
} |
| 2786 |
opts.JetStreamMetaCompactSize = uint64(s) |
| 2787 |
case "meta_compact_sync": |
| 2788 |
opts.JetStreamMetaCompactSync = mv.(bool) |
| 2789 |
case "max_concurrent_io": |
| 2790 |
dios, ok := mv.(int64) |
| 2791 |
if !ok || dios < minConcurrentIOs || dios > maxConcurrentIOs { |
| 2792 |
return &configErr{tk, fmt.Sprintf("Expected an absolute size for %q between 4 and 8192, got %v", mk, mv)} |
| 2793 |
} |
| 2794 |
opts.JetStreamConcurrentIOs = int(dios) |
| 2795 |
default: |
| 2796 |
if !tk.IsUsedVariable() { |
| 2797 |
err := &unknownConfigFieldErr{ |
| 2798 |
field: mk, |
| 2799 |
configErr: configErr{ |
| 2800 |
token: tk, |
| 2801 |
}, |
| 2802 |
} |
| 2803 |
*errors = append(*errors, err) |
| 2804 |
continue |
| 2805 |
} |
| 2806 |
} |
| 2807 |
} |
| 2808 |
opts.JetStream = doEnable |
| 2809 |
default: |
| 2810 |
return &configErr{tk, fmt.Sprintf("Expected map, bool or string to define JetStream, got %T", v)} |
| 2811 |
} |
| 2812 |
|
| 2813 |
return nil |
| 2814 |
} |
| 2815 |
|
| 2816 |
// parseLeafNodes will parse the leaf node config. |
| 2817 |
func parseLeafNodes(v any, opts *Options, errors *[]error, warnings *[]error) error { |
| 2818 |
var lt token |
| 2819 |
defer convertPanicToErrorList(<, errors) |
| 2820 |
|
| 2821 |
tk, v := unwrapValue(v, <) |
| 2822 |
cm, ok := v.(map[string]any) |
| 2823 |
if !ok { |
| 2824 |
return &configErr{tk, fmt.Sprintf("Expected map to define a leafnode, got %T", v)} |
| 2825 |
} |
| 2826 |
|
| 2827 |
for mk, mv := range cm { |
| 2828 |
// Again, unwrap token value if line check is required. |
| 2829 |
tk, mv = unwrapValue(mv, <) |
| 2830 |
switch strings.ToLower(mk) { |
| 2831 |
case "listen": |
| 2832 |
hp, err := parseListen(mv) |
| 2833 |
if err != nil { |
| 2834 |
err := &configErr{tk, err.Error()} |
| 2835 |
*errors = append(*errors, err) |
| 2836 |
continue |
| 2837 |
} |
| 2838 |
opts.LeafNode.Host = hp.host |
| 2839 |
opts.LeafNode.Port = hp.port |
| 2840 |
case "port": |
| 2841 |
opts.LeafNode.Port = int(mv.(int64)) |
| 2842 |
case "host", "net": |
| 2843 |
opts.LeafNode.Host = mv.(string) |
| 2844 |
case "authorization": |
| 2845 |
auth, err := parseLeafAuthorization(tk, errors, warnings) |
| 2846 |
if err != nil { |
| 2847 |
*errors = append(*errors, err) |
| 2848 |
continue |
| 2849 |
} |
| 2850 |
opts.LeafNode.Username = auth.user |
| 2851 |
opts.LeafNode.Password = auth.pass |
| 2852 |
opts.LeafNode.ProxyRequired = auth.proxyRequired |
| 2853 |
opts.LeafNode.AuthTimeout = auth.timeout |
| 2854 |
opts.LeafNode.Account = auth.acc |
| 2855 |
opts.LeafNode.Users = auth.users |
| 2856 |
opts.LeafNode.Nkey = auth.nkey |
| 2857 |
// Validate user info config for leafnode authorization |
| 2858 |
if err := validateLeafNodeAuthOptions(opts); err != nil { |
| 2859 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 2860 |
continue |
| 2861 |
} |
| 2862 |
case "remotes": |
| 2863 |
// Parse the remote options here. |
| 2864 |
remotes, err := parseRemoteLeafNodes(tk, errors, warnings) |
| 2865 |
if err != nil { |
| 2866 |
*errors = append(*errors, err) |
| 2867 |
continue |
| 2868 |
} |
| 2869 |
opts.LeafNode.Remotes = remotes |
| 2870 |
case "reconnect", "reconnect_delay", "reconnect_interval": |
| 2871 |
opts.LeafNode.ReconnectInterval = parseDuration("reconnect", tk, mv, errors, warnings) |
| 2872 |
case "dial_timeout": |
| 2873 |
opts.LeafNode.DialTimeout = parseDuration("dial_timeout", tk, mv, errors, warnings) |
| 2874 |
case "tls": |
| 2875 |
tc, err := parseTLS(tk, true) |
| 2876 |
if err != nil { |
| 2877 |
*errors = append(*errors, err) |
| 2878 |
continue |
| 2879 |
} |
| 2880 |
if opts.LeafNode.TLSConfig, err = GenTLSConfig(tc); err != nil { |
| 2881 |
err := &configErr{tk, err.Error()} |
| 2882 |
*errors = append(*errors, err) |
| 2883 |
continue |
| 2884 |
} |
| 2885 |
opts.LeafNode.TLSTimeout = tc.Timeout |
| 2886 |
opts.LeafNode.TLSMap = tc.Map |
| 2887 |
opts.LeafNode.TLSPinnedCerts = tc.PinnedCerts |
| 2888 |
opts.LeafNode.TLSHandshakeFirst = tc.HandshakeFirst |
| 2889 |
opts.LeafNode.TLSHandshakeFirstFallback = tc.FallbackDelay |
| 2890 |
opts.LeafNode.tlsConfigOpts = tc |
| 2891 |
case "leafnode_advertise", "advertise": |
| 2892 |
opts.LeafNode.Advertise = mv.(string) |
| 2893 |
case "no_advertise": |
| 2894 |
opts.LeafNode.NoAdvertise = mv.(bool) |
| 2895 |
trackExplicitVal(&opts.inConfig, "LeafNode.NoAdvertise", opts.LeafNode.NoAdvertise) |
| 2896 |
case "min_version", "minimum_version": |
| 2897 |
version := mv.(string) |
| 2898 |
if err := checkLeafMinVersionConfig(version); err != nil { |
| 2899 |
err = &configErr{tk, err.Error()} |
| 2900 |
*errors = append(*errors, err) |
| 2901 |
continue |
| 2902 |
} |
| 2903 |
opts.LeafNode.MinVersion = version |
| 2904 |
case "compression": |
| 2905 |
if err := parseCompression(&opts.LeafNode.Compression, CompressionS2Auto, tk, mk, mv); err != nil { |
| 2906 |
*errors = append(*errors, err) |
| 2907 |
continue |
| 2908 |
} |
| 2909 |
case "isolate_leafnode_interest", "isolate": |
| 2910 |
opts.LeafNode.IsolateLeafnodeInterest = mv.(bool) |
| 2911 |
case "write_deadline": |
| 2912 |
opts.LeafNode.WriteDeadline = parseDuration("write_deadline", tk, mv, errors, warnings) |
| 2913 |
case "write_timeout": |
| 2914 |
opts.LeafNode.WriteTimeout = parseWriteDeadlinePolicy(tk, mv.(string), errors) |
| 2915 |
default: |
| 2916 |
if !tk.IsUsedVariable() { |
| 2917 |
err := &unknownConfigFieldErr{ |
| 2918 |
field: mk, |
| 2919 |
configErr: configErr{ |
| 2920 |
token: tk, |
| 2921 |
}, |
| 2922 |
} |
| 2923 |
*errors = append(*errors, err) |
| 2924 |
continue |
| 2925 |
} |
| 2926 |
} |
| 2927 |
} |
| 2928 |
return nil |
| 2929 |
} |
| 2930 |
|
| 2931 |
// This is the authorization parser adapter for the leafnode's |
| 2932 |
// authorization config. |
| 2933 |
func parseLeafAuthorization(v any, errors, warnings *[]error) (*authorization, error) { |
| 2934 |
var ( |
| 2935 |
am map[string]any |
| 2936 |
tk token |
| 2937 |
lt token |
| 2938 |
auth = &authorization{} |
| 2939 |
) |
| 2940 |
defer convertPanicToErrorList(<, errors) |
| 2941 |
|
| 2942 |
_, v = unwrapValue(v, <) |
| 2943 |
am = v.(map[string]any) |
| 2944 |
for mk, mv := range am { |
| 2945 |
tk, mv = unwrapValue(mv, <) |
| 2946 |
switch strings.ToLower(mk) { |
| 2947 |
case "user", "username": |
| 2948 |
auth.user = mv.(string) |
| 2949 |
case "pass", "password": |
| 2950 |
auth.pass = mv.(string) |
| 2951 |
case "nkey": |
| 2952 |
nk := mv.(string) |
| 2953 |
if !nkeys.IsValidPublicUserKey(nk) { |
| 2954 |
*errors = append(*errors, &configErr{tk, "Not a valid public nkey for leafnode authorization"}) |
| 2955 |
} |
| 2956 |
auth.nkey = nk |
| 2957 |
case "timeout": |
| 2958 |
at := float64(0) |
| 2959 |
switch mv := mv.(type) { |
| 2960 |
case int64: |
| 2961 |
at = float64(mv) |
| 2962 |
case float64: |
| 2963 |
at = mv |
| 2964 |
case string: |
| 2965 |
d, err := time.ParseDuration(mv) |
| 2966 |
if err != nil { |
| 2967 |
return nil, &configErr{tk, fmt.Sprintf("error parsing leafnode authorization config, 'timeout' %s", err)} |
| 2968 |
} |
| 2969 |
at = d.Seconds() |
| 2970 |
default: |
| 2971 |
return nil, &configErr{tk, "error parsing leafnode authorization config, 'timeout' wrong type"} |
| 2972 |
} |
| 2973 |
if at > (60 * time.Second).Seconds() { |
| 2974 |
reason := fmt.Sprintf("timeout of %v (%f seconds) is high, consider keeping it under 60 seconds. possibly caused by unquoted duration; use '1m' instead of 1m, for example", mv, at) |
| 2975 |
*warnings = append(*warnings, &configWarningErr{field: mk, configErr: configErr{token: tk, reason: reason}}) |
| 2976 |
} |
| 2977 |
auth.timeout = at |
| 2978 |
case "users": |
| 2979 |
users, err := parseLeafUsers(tk, errors) |
| 2980 |
if err != nil { |
| 2981 |
*errors = append(*errors, err) |
| 2982 |
continue |
| 2983 |
} |
| 2984 |
auth.users = users |
| 2985 |
case "account": |
| 2986 |
auth.acc = mv.(string) |
| 2987 |
case "proxy_required": |
| 2988 |
auth.proxyRequired = mv.(bool) |
| 2989 |
default: |
| 2990 |
if !tk.IsUsedVariable() { |
| 2991 |
err := &unknownConfigFieldErr{ |
| 2992 |
field: mk, |
| 2993 |
configErr: configErr{ |
| 2994 |
token: tk, |
| 2995 |
}, |
| 2996 |
} |
| 2997 |
*errors = append(*errors, err) |
| 2998 |
} |
| 2999 |
continue |
| 3000 |
} |
| 3001 |
} |
| 3002 |
return auth, nil |
| 3003 |
} |
| 3004 |
|
| 3005 |
// This is a trimmed down version of parseUsers that is adapted |
| 3006 |
// for the users possibly defined in the authorization{} section |
| 3007 |
// of leafnodes {}. |
| 3008 |
func parseLeafUsers(mv any, errors *[]error) ([]*User, error) { |
| 3009 |
var ( |
| 3010 |
tk token |
| 3011 |
lt token |
| 3012 |
users = []*User{} |
| 3013 |
) |
| 3014 |
defer convertPanicToErrorList(<, errors) |
| 3015 |
|
| 3016 |
tk, mv = unwrapValue(mv, <) |
| 3017 |
// Make sure we have an array |
| 3018 |
uv, ok := mv.([]any) |
| 3019 |
if !ok { |
| 3020 |
return nil, &configErr{tk, fmt.Sprintf("Expected users field to be an array, got %v", mv)} |
| 3021 |
} |
| 3022 |
for _, u := range uv { |
| 3023 |
tk, u = unwrapValue(u, <) |
| 3024 |
// Check its a map/struct |
| 3025 |
um, ok := u.(map[string]any) |
| 3026 |
if !ok { |
| 3027 |
err := &configErr{tk, fmt.Sprintf("Expected user entry to be a map/struct, got %v", u)} |
| 3028 |
*errors = append(*errors, err) |
| 3029 |
continue |
| 3030 |
} |
| 3031 |
user := &User{} |
| 3032 |
for k, v := range um { |
| 3033 |
tk, v = unwrapValue(v, <) |
| 3034 |
switch strings.ToLower(k) { |
| 3035 |
case "user", "username": |
| 3036 |
user.Username = v.(string) |
| 3037 |
case "pass", "password": |
| 3038 |
user.Password = v.(string) |
| 3039 |
case "account": |
| 3040 |
// We really want to save just the account name here, but |
| 3041 |
// the User object is *Account. So we create an account object |
| 3042 |
// but it won't be registered anywhere. The server will just |
| 3043 |
// use opts.LeafNode.Users[].Account.Name. Alternatively |
| 3044 |
// we need to create internal objects to store u/p and account |
| 3045 |
// name and have a server structure to hold that. |
| 3046 |
user.Account = NewAccount(v.(string)) |
| 3047 |
case "proxy_required": |
| 3048 |
user.ProxyRequired = v.(bool) |
| 3049 |
default: |
| 3050 |
if !tk.IsUsedVariable() { |
| 3051 |
err := &unknownConfigFieldErr{ |
| 3052 |
field: k, |
| 3053 |
configErr: configErr{ |
| 3054 |
token: tk, |
| 3055 |
}, |
| 3056 |
} |
| 3057 |
*errors = append(*errors, err) |
| 3058 |
continue |
| 3059 |
} |
| 3060 |
} |
| 3061 |
} |
| 3062 |
users = append(users, user) |
| 3063 |
} |
| 3064 |
return users, nil |
| 3065 |
} |
| 3066 |
|
| 3067 |
func parseRemoteLeafNodes(v any, errors *[]error, warnings *[]error) ([]*RemoteLeafOpts, error) { |
| 3068 |
var lt token |
| 3069 |
defer convertPanicToErrorList(<, errors) |
| 3070 |
tk, v := unwrapValue(v, <) |
| 3071 |
ra, ok := v.([]any) |
| 3072 |
if !ok { |
| 3073 |
return nil, &configErr{tk, fmt.Sprintf("Expected remotes field to be an array, got %T", v)} |
| 3074 |
} |
| 3075 |
names := make(map[string]struct{}) |
| 3076 |
remotes := make([]*RemoteLeafOpts, 0, len(ra)) |
| 3077 |
for _, r := range ra { |
| 3078 |
tk, r = unwrapValue(r, <) |
| 3079 |
// Check its a map/struct |
| 3080 |
rm, ok := r.(map[string]any) |
| 3081 |
if !ok { |
| 3082 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected remote leafnode entry to be a map/struct, got %v", r)}) |
| 3083 |
continue |
| 3084 |
} |
| 3085 |
remote := &RemoteLeafOpts{} |
| 3086 |
var proxyToken token |
| 3087 |
for k, v := range rm { |
| 3088 |
tk, v = unwrapValue(v, <) |
| 3089 |
switch strings.ToLower(k) { |
| 3090 |
case "no_randomize", "dont_randomize": |
| 3091 |
remote.NoRandomize = v.(bool) |
| 3092 |
case "url", "urls": |
| 3093 |
switch v := v.(type) { |
| 3094 |
case []any, []string: |
| 3095 |
urls, errs := parseURLs(v.([]any), "leafnode", warnings) |
| 3096 |
if errs != nil { |
| 3097 |
*errors = append(*errors, errs...) |
| 3098 |
continue |
| 3099 |
} |
| 3100 |
remote.URLs = urls |
| 3101 |
case string: |
| 3102 |
url, err := parseURL(v, "leafnode") |
| 3103 |
if err != nil { |
| 3104 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 3105 |
continue |
| 3106 |
} |
| 3107 |
remote.URLs = append(remote.URLs, url) |
| 3108 |
default: |
| 3109 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected remote leafnode url to be an array or string, got %v", v)}) |
| 3110 |
continue |
| 3111 |
} |
| 3112 |
case "account", "local": |
| 3113 |
remote.LocalAccount = v.(string) |
| 3114 |
case "creds", "credentials": |
| 3115 |
p, err := expandPath(v.(string)) |
| 3116 |
if err != nil { |
| 3117 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 3118 |
continue |
| 3119 |
} |
| 3120 |
// Can't have both creds and nkey |
| 3121 |
if remote.Nkey != _EMPTY_ { |
| 3122 |
*errors = append(*errors, &configErr{tk, "Remote leafnode can not have both creds and nkey defined"}) |
| 3123 |
continue |
| 3124 |
} |
| 3125 |
remote.Credentials = p |
| 3126 |
case "nkey", "seed": |
| 3127 |
nk := v.(string) |
| 3128 |
if pb, _, err := nkeys.DecodeSeed([]byte(nk)); err != nil || pb != nkeys.PrefixByteUser { |
| 3129 |
err := &configErr{tk, fmt.Sprintf("Remote leafnode nkey is not a valid seed: %q", v)} |
| 3130 |
*errors = append(*errors, err) |
| 3131 |
continue |
| 3132 |
} |
| 3133 |
if remote.Credentials != _EMPTY_ { |
| 3134 |
*errors = append(*errors, &configErr{tk, "Remote leafnode can not have both creds and nkey defined"}) |
| 3135 |
continue |
| 3136 |
} |
| 3137 |
remote.Nkey = nk |
| 3138 |
case "tls": |
| 3139 |
tc, err := parseTLS(tk, true) |
| 3140 |
if err != nil { |
| 3141 |
*errors = append(*errors, err) |
| 3142 |
continue |
| 3143 |
} |
| 3144 |
if remote.TLSConfig, err = GenTLSConfig(tc); err != nil { |
| 3145 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 3146 |
continue |
| 3147 |
} |
| 3148 |
// If ca_file is defined, GenTLSConfig() sets TLSConfig.ClientCAs. |
| 3149 |
// Set RootCAs since this tls.Config is used when soliciting |
| 3150 |
// a connection (therefore behaves as a client). |
| 3151 |
remote.TLSConfig.RootCAs = remote.TLSConfig.ClientCAs |
| 3152 |
if tc.Timeout > 0 { |
| 3153 |
remote.TLSTimeout = tc.Timeout |
| 3154 |
} else { |
| 3155 |
remote.TLSTimeout = float64(DEFAULT_LEAF_TLS_TIMEOUT) / float64(time.Second) |
| 3156 |
} |
| 3157 |
remote.TLSHandshakeFirst = tc.HandshakeFirst |
| 3158 |
remote.tlsConfigOpts = tc |
| 3159 |
case "hub": |
| 3160 |
remote.Hub = v.(bool) |
| 3161 |
case "deny_imports", "deny_import": |
| 3162 |
subjects, err := parsePermSubjects(tk, errors, false) |
| 3163 |
if err != nil { |
| 3164 |
*errors = append(*errors, err) |
| 3165 |
continue |
| 3166 |
} |
| 3167 |
remote.DenyImports = subjects |
| 3168 |
case "deny_exports", "deny_export": |
| 3169 |
subjects, err := parsePermSubjects(tk, errors, false) |
| 3170 |
if err != nil { |
| 3171 |
*errors = append(*errors, err) |
| 3172 |
continue |
| 3173 |
} |
| 3174 |
remote.DenyExports = subjects |
| 3175 |
case "ws_compress", "ws_compression", "websocket_compress", "websocket_compression": |
| 3176 |
remote.Websocket.Compression = v.(bool) |
| 3177 |
case "ws_no_masking", "websocket_no_masking": |
| 3178 |
remote.Websocket.NoMasking = v.(bool) |
| 3179 |
case "jetstream_cluster_migrate", "js_cluster_migrate": |
| 3180 |
var lt token |
| 3181 |
|
| 3182 |
tk, v := unwrapValue(v, <) |
| 3183 |
switch vv := v.(type) { |
| 3184 |
case bool: |
| 3185 |
remote.JetStreamClusterMigrate = vv |
| 3186 |
case map[string]any: |
| 3187 |
remote.JetStreamClusterMigrate = true |
| 3188 |
migrateConfig, ok := v.(map[string]any) |
| 3189 |
if !ok { |
| 3190 |
continue |
| 3191 |
} |
| 3192 |
val, ok := migrateConfig["leader_migrate_delay"] |
| 3193 |
tk, delay := unwrapValue(val, &tk) |
| 3194 |
if ok { |
| 3195 |
remote.JetStreamClusterMigrateDelay = parseDuration("leader_migrate_delay", tk, delay, errors, warnings) |
| 3196 |
} |
| 3197 |
default: |
| 3198 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected boolean or map for jetstream_cluster_migrate, got %T", v)}) |
| 3199 |
} |
| 3200 |
case "isolate_leafnode_interest", "isolate": |
| 3201 |
remote.LocalIsolation = v.(bool) |
| 3202 |
case "request_isolation": |
| 3203 |
remote.RequestIsolation = v.(bool) |
| 3204 |
case "compression": |
| 3205 |
if err := parseCompression(&remote.Compression, CompressionS2Auto, tk, k, v); err != nil { |
| 3206 |
*errors = append(*errors, err) |
| 3207 |
continue |
| 3208 |
} |
| 3209 |
case "first_info_timeout": |
| 3210 |
remote.FirstInfoTimeout = parseDuration(k, tk, v, errors, warnings) |
| 3211 |
case "dial_timeout": |
| 3212 |
remote.DialTimeout = parseDuration(k, tk, v, errors, warnings) |
| 3213 |
case "disabled": |
| 3214 |
remote.Disabled = v.(bool) |
| 3215 |
case "proxy": |
| 3216 |
proxyMap, ok := v.(map[string]any) |
| 3217 |
if !ok { |
| 3218 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected proxy to be a map, got %T", v)}) |
| 3219 |
continue |
| 3220 |
} |
| 3221 |
// Capture the token for the "proxy" field itself, before the map iteration |
| 3222 |
proxyToken = tk |
| 3223 |
for pk, pv := range proxyMap { |
| 3224 |
tk, pv = unwrapValue(pv, <) |
| 3225 |
switch strings.ToLower(pk) { |
| 3226 |
case "url": |
| 3227 |
remote.Proxy.URL = pv.(string) |
| 3228 |
case "username": |
| 3229 |
remote.Proxy.Username = pv.(string) |
| 3230 |
case "password": |
| 3231 |
remote.Proxy.Password = pv.(string) |
| 3232 |
case "timeout": |
| 3233 |
remote.Proxy.Timeout = parseDuration("proxy timeout", tk, pv, errors, warnings) |
| 3234 |
default: |
| 3235 |
if !tk.IsUsedVariable() { |
| 3236 |
err := &unknownConfigFieldErr{ |
| 3237 |
field: pk, |
| 3238 |
configErr: configErr{ |
| 3239 |
token: tk, |
| 3240 |
}, |
| 3241 |
} |
| 3242 |
*errors = append(*errors, err) |
| 3243 |
continue |
| 3244 |
} |
| 3245 |
} |
| 3246 |
} |
| 3247 |
case "ignore_discovered_servers": |
| 3248 |
remote.IgnoreDiscoveredServers = v.(bool) |
| 3249 |
default: |
| 3250 |
if !tk.IsUsedVariable() { |
| 3251 |
err := &unknownConfigFieldErr{ |
| 3252 |
field: k, |
| 3253 |
configErr: configErr{ |
| 3254 |
token: tk, |
| 3255 |
}, |
| 3256 |
} |
| 3257 |
*errors = append(*errors, err) |
| 3258 |
continue |
| 3259 |
} |
| 3260 |
} |
| 3261 |
} |
| 3262 |
// Use the saved proxy token for validation errors, not the last field token |
| 3263 |
if warns, err := validateLeafNodeProxyOptions(remote); err != nil { |
| 3264 |
*errors = append(*errors, &configErr{proxyToken, err.Error()}) |
| 3265 |
continue |
| 3266 |
} else { |
| 3267 |
// Add any warnings about proxy configuration |
| 3268 |
for _, warn := range warns { |
| 3269 |
*warnings = append(*warnings, &configErr{proxyToken, warn}) |
| 3270 |
} |
| 3271 |
} |
| 3272 |
rn := remote.name() |
| 3273 |
if _, dup := names[rn]; dup { |
| 3274 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("duplicate remote %s", remote.safeName())}) |
| 3275 |
continue |
| 3276 |
} |
| 3277 |
names[rn] = struct{}{} |
| 3278 |
remotes = append(remotes, remote) |
| 3279 |
} |
| 3280 |
return remotes, nil |
| 3281 |
} |
| 3282 |
|
| 3283 |
// Parse TLS and returns a TLSConfig and TLSTimeout. |
| 3284 |
// Used by cluster and gateway parsing. |
| 3285 |
func getTLSConfig(tk token) (*tls.Config, *TLSConfigOpts, error) { |
| 3286 |
tc, err := parseTLS(tk, false) |
| 3287 |
if err != nil { |
| 3288 |
return nil, nil, err |
| 3289 |
} |
| 3290 |
config, err := GenTLSConfig(tc) |
| 3291 |
if err != nil { |
| 3292 |
err := &configErr{tk, err.Error()} |
| 3293 |
return nil, nil, err |
| 3294 |
} |
| 3295 |
// For clusters/gateways, we will force strict verification. We also act |
| 3296 |
// as both client and server, so will mirror the rootCA to the |
| 3297 |
// clientCA pool. |
| 3298 |
config.ClientAuth = tls.RequireAndVerifyClientCert |
| 3299 |
config.RootCAs = config.ClientCAs |
| 3300 |
return config, tc, nil |
| 3301 |
} |
| 3302 |
|
| 3303 |
func parseGateways(v any, errors *[]error, warnings *[]error) ([]*RemoteGatewayOpts, error) { |
| 3304 |
var lt token |
| 3305 |
defer convertPanicToErrorList(<, errors) |
| 3306 |
|
| 3307 |
tk, v := unwrapValue(v, <) |
| 3308 |
// Make sure we have an array |
| 3309 |
ga, ok := v.([]any) |
| 3310 |
if !ok { |
| 3311 |
return nil, &configErr{tk, fmt.Sprintf("Expected gateways field to be an array, got %T", v)} |
| 3312 |
} |
| 3313 |
gateways := []*RemoteGatewayOpts{} |
| 3314 |
for _, g := range ga { |
| 3315 |
tk, g = unwrapValue(g, <) |
| 3316 |
// Check its a map/struct |
| 3317 |
gm, ok := g.(map[string]any) |
| 3318 |
if !ok { |
| 3319 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("Expected gateway entry to be a map/struct, got %v", g)}) |
| 3320 |
continue |
| 3321 |
} |
| 3322 |
gateway := &RemoteGatewayOpts{} |
| 3323 |
for k, v := range gm { |
| 3324 |
tk, v = unwrapValue(v, <) |
| 3325 |
switch strings.ToLower(k) { |
| 3326 |
case "name": |
| 3327 |
gateway.Name = v.(string) |
| 3328 |
case "tls": |
| 3329 |
tls, tlsopts, err := getTLSConfig(tk) |
| 3330 |
if err != nil { |
| 3331 |
*errors = append(*errors, err) |
| 3332 |
continue |
| 3333 |
} |
| 3334 |
gateway.TLSConfig = tls |
| 3335 |
gateway.TLSTimeout = tlsopts.Timeout |
| 3336 |
gateway.tlsConfigOpts = tlsopts |
| 3337 |
case "url": |
| 3338 |
url, err := parseURL(v.(string), "gateway") |
| 3339 |
if err != nil { |
| 3340 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 3341 |
continue |
| 3342 |
} |
| 3343 |
gateway.URLs = append(gateway.URLs, url) |
| 3344 |
case "urls": |
| 3345 |
urls, errs := parseURLs(v.([]any), "gateway", warnings) |
| 3346 |
if errs != nil { |
| 3347 |
*errors = append(*errors, errs...) |
| 3348 |
continue |
| 3349 |
} |
| 3350 |
gateway.URLs = urls |
| 3351 |
default: |
| 3352 |
if !tk.IsUsedVariable() { |
| 3353 |
err := &unknownConfigFieldErr{ |
| 3354 |
field: k, |
| 3355 |
configErr: configErr{ |
| 3356 |
token: tk, |
| 3357 |
}, |
| 3358 |
} |
| 3359 |
*errors = append(*errors, err) |
| 3360 |
continue |
| 3361 |
} |
| 3362 |
} |
| 3363 |
} |
| 3364 |
gateways = append(gateways, gateway) |
| 3365 |
} |
| 3366 |
return gateways, nil |
| 3367 |
} |
| 3368 |
|
| 3369 |
// Sets cluster's permissions based on given pub/sub permissions, |
| 3370 |
// doing the appropriate translation. |
| 3371 |
func setClusterPermissions(opts *ClusterOpts, perms *Permissions) { |
| 3372 |
// Import is whether or not we will send a SUB for interest to the other side. |
| 3373 |
// Export is whether or not we will accept a SUB from the remote for a given subject. |
| 3374 |
// Both only effect interest registration. |
| 3375 |
// The parsing sets Import into Publish and Export into Subscribe, convert |
| 3376 |
// accordingly. |
| 3377 |
opts.Permissions = &RoutePermissions{ |
| 3378 |
Import: perms.Publish, |
| 3379 |
Export: perms.Subscribe, |
| 3380 |
} |
| 3381 |
} |
| 3382 |
|
| 3383 |
func checkClusterPermissionSubjects(perms *Permissions) error { |
| 3384 |
if perms == nil { |
| 3385 |
return nil |
| 3386 |
} |
| 3387 |
if perms.Publish != nil { |
| 3388 |
if err := checkPermSubjectArray(perms.Publish.Allow, false); err != nil { |
| 3389 |
return fmt.Errorf("cluster import allow: %w", err) |
| 3390 |
} |
| 3391 |
if err := checkPermSubjectArray(perms.Publish.Deny, false); err != nil { |
| 3392 |
return fmt.Errorf("cluster import deny: %w", err) |
| 3393 |
} |
| 3394 |
} |
| 3395 |
if perms.Subscribe != nil { |
| 3396 |
if err := checkPermSubjectArray(perms.Subscribe.Allow, false); err != nil { |
| 3397 |
return fmt.Errorf("cluster export allow: %w", err) |
| 3398 |
} |
| 3399 |
if err := checkPermSubjectArray(perms.Subscribe.Deny, false); err != nil { |
| 3400 |
return fmt.Errorf("cluster export deny: %w", err) |
| 3401 |
} |
| 3402 |
} |
| 3403 |
return nil |
| 3404 |
} |
| 3405 |
|
| 3406 |
// Temp structures to hold account import and export defintions since they need |
| 3407 |
// to be processed after being parsed. |
| 3408 |
type export struct { |
| 3409 |
acc *Account |
| 3410 |
sub string |
| 3411 |
accs []string |
| 3412 |
rt ServiceRespType |
| 3413 |
lat *serviceLatency |
| 3414 |
rthr time.Duration |
| 3415 |
tPos uint |
| 3416 |
atrc bool // allow_trace |
| 3417 |
} |
| 3418 |
|
| 3419 |
type importStream struct { |
| 3420 |
acc *Account |
| 3421 |
an string |
| 3422 |
sub string |
| 3423 |
to string |
| 3424 |
pre string |
| 3425 |
atrc bool // allow_trace |
| 3426 |
} |
| 3427 |
|
| 3428 |
type importService struct { |
| 3429 |
acc *Account |
| 3430 |
an string |
| 3431 |
sub string |
| 3432 |
to string |
| 3433 |
share bool |
| 3434 |
} |
| 3435 |
|
| 3436 |
// Checks if an account name is reserved. |
| 3437 |
func isReservedAccount(name string) bool { |
| 3438 |
return name == globalAccountName |
| 3439 |
} |
| 3440 |
|
| 3441 |
func parseAccountMapDest(v any, tk token, errors *[]error) (*MapDest, *configErr) { |
| 3442 |
// These should be maps. |
| 3443 |
mv, ok := v.(map[string]any) |
| 3444 |
if !ok { |
| 3445 |
err := &configErr{tk, "Expected an entry for the mapping destination"} |
| 3446 |
*errors = append(*errors, err) |
| 3447 |
return nil, err |
| 3448 |
} |
| 3449 |
|
| 3450 |
mdest := &MapDest{} |
| 3451 |
var lt token |
| 3452 |
var sw bool |
| 3453 |
|
| 3454 |
for k, v := range mv { |
| 3455 |
tk, dmv := unwrapValue(v, <) |
| 3456 |
switch strings.ToLower(k) { |
| 3457 |
case "dest", "destination": |
| 3458 |
mdest.Subject = dmv.(string) |
| 3459 |
case "weight": |
| 3460 |
switch vv := dmv.(type) { |
| 3461 |
case string: |
| 3462 |
ws := vv |
| 3463 |
ws = strings.TrimSuffix(ws, "%") |
| 3464 |
weight, err := strconv.Atoi(ws) |
| 3465 |
if err != nil { |
| 3466 |
err := &configErr{tk, fmt.Sprintf("Invalid weight %q for mapping destination", ws)} |
| 3467 |
*errors = append(*errors, err) |
| 3468 |
return nil, err |
| 3469 |
} |
| 3470 |
if weight > 100 || weight < 0 { |
| 3471 |
err := &configErr{tk, fmt.Sprintf("Invalid weight %d for mapping destination", weight)} |
| 3472 |
*errors = append(*errors, err) |
| 3473 |
return nil, err |
| 3474 |
} |
| 3475 |
mdest.Weight = uint8(weight) |
| 3476 |
sw = true |
| 3477 |
case int64: |
| 3478 |
weight := vv |
| 3479 |
if weight > 100 || weight < 0 { |
| 3480 |
err := &configErr{tk, fmt.Sprintf("Invalid weight %d for mapping destination", weight)} |
| 3481 |
*errors = append(*errors, err) |
| 3482 |
return nil, err |
| 3483 |
} |
| 3484 |
mdest.Weight = uint8(weight) |
| 3485 |
sw = true |
| 3486 |
default: |
| 3487 |
err := &configErr{tk, fmt.Sprintf("Unknown entry type for weight of %v\n", vv)} |
| 3488 |
*errors = append(*errors, err) |
| 3489 |
return nil, err |
| 3490 |
} |
| 3491 |
case "cluster": |
| 3492 |
mdest.Cluster = dmv.(string) |
| 3493 |
default: |
| 3494 |
err := &configErr{tk, fmt.Sprintf("Unknown field %q for mapping destination", k)} |
| 3495 |
*errors = append(*errors, err) |
| 3496 |
return nil, err |
| 3497 |
} |
| 3498 |
} |
| 3499 |
|
| 3500 |
if !sw { |
| 3501 |
err := &configErr{tk, fmt.Sprintf("Missing weight for mapping destination %q", mdest.Subject)} |
| 3502 |
*errors = append(*errors, err) |
| 3503 |
return nil, err |
| 3504 |
} |
| 3505 |
|
| 3506 |
return mdest, nil |
| 3507 |
} |
| 3508 |
|
| 3509 |
// parseAccountMappings is called to parse account mappings. |
| 3510 |
func parseAccountMappings(v any, acc *Account, errors *[]error) error { |
| 3511 |
var lt token |
| 3512 |
defer convertPanicToErrorList(<, errors) |
| 3513 |
|
| 3514 |
tk, v := unwrapValue(v, <) |
| 3515 |
am := v.(map[string]any) |
| 3516 |
for subj, mv := range am { |
| 3517 |
if !IsValidSubject(subj) { |
| 3518 |
err := &configErr{tk, fmt.Sprintf("Subject %q is not a valid subject", subj)} |
| 3519 |
*errors = append(*errors, err) |
| 3520 |
continue |
| 3521 |
} |
| 3522 |
tk, v := unwrapValue(mv, <) |
| 3523 |
|
| 3524 |
switch vv := v.(type) { |
| 3525 |
case string: |
| 3526 |
if err := acc.AddMapping(subj, v.(string)); err != nil { |
| 3527 |
err := &configErr{tk, fmt.Sprintf("Error adding mapping for %q to %q : %v", subj, v.(string), err)} |
| 3528 |
*errors = append(*errors, err) |
| 3529 |
continue |
| 3530 |
} |
| 3531 |
case []any: |
| 3532 |
var mappings []*MapDest |
| 3533 |
for _, mv := range v.([]any) { |
| 3534 |
tk, amv := unwrapValue(mv, <) |
| 3535 |
mdest, err := parseAccountMapDest(amv, tk, errors) |
| 3536 |
if err != nil { |
| 3537 |
continue |
| 3538 |
} |
| 3539 |
mappings = append(mappings, mdest) |
| 3540 |
} |
| 3541 |
|
| 3542 |
// Now add them in.. |
| 3543 |
if err := acc.AddWeightedMappings(subj, mappings...); err != nil { |
| 3544 |
err := &configErr{tk, fmt.Sprintf("Error adding mapping for %q : %v", subj, err)} |
| 3545 |
*errors = append(*errors, err) |
| 3546 |
continue |
| 3547 |
} |
| 3548 |
case any: |
| 3549 |
tk, amv := unwrapValue(mv, <) |
| 3550 |
mdest, err := parseAccountMapDest(amv, tk, errors) |
| 3551 |
if err != nil { |
| 3552 |
continue |
| 3553 |
} |
| 3554 |
// Now add it in.. |
| 3555 |
if err := acc.AddWeightedMappings(subj, mdest); err != nil { |
| 3556 |
err := &configErr{tk, fmt.Sprintf("Error adding mapping for %q : %v", subj, err)} |
| 3557 |
*errors = append(*errors, err) |
| 3558 |
continue |
| 3559 |
} |
| 3560 |
default: |
| 3561 |
err := &configErr{tk, fmt.Sprintf("Unknown type %T for mapping destination", vv)} |
| 3562 |
*errors = append(*errors, err) |
| 3563 |
continue |
| 3564 |
} |
| 3565 |
} |
| 3566 |
|
| 3567 |
return nil |
| 3568 |
} |
| 3569 |
|
| 3570 |
// parseAccountLimits is called to parse account limits in a server config. |
| 3571 |
func parseAccountLimits(mv any, acc *Account, errors *[]error) error { |
| 3572 |
var lt token |
| 3573 |
defer convertPanicToErrorList(<, errors) |
| 3574 |
|
| 3575 |
tk, v := unwrapValue(mv, <) |
| 3576 |
am, ok := v.(map[string]any) |
| 3577 |
if !ok { |
| 3578 |
return &configErr{tk, fmt.Sprintf("Expected account limits to be a map/struct, got %+v", v)} |
| 3579 |
} |
| 3580 |
|
| 3581 |
for k, v := range am { |
| 3582 |
tk, mv = unwrapValue(v, <) |
| 3583 |
switch strings.ToLower(k) { |
| 3584 |
case "max_connections", "max_conn": |
| 3585 |
acc.mconns = int32(mv.(int64)) |
| 3586 |
case "max_subscriptions", "max_subs": |
| 3587 |
acc.msubs = int32(mv.(int64)) |
| 3588 |
case "max_payload", "max_pay": |
| 3589 |
acc.mpay = int32(mv.(int64)) |
| 3590 |
case "max_leafnodes", "max_leafs": |
| 3591 |
acc.mleafs = int32(mv.(int64)) |
| 3592 |
default: |
| 3593 |
if !tk.IsUsedVariable() { |
| 3594 |
err := &configErr{tk, fmt.Sprintf("Unknown field %q parsing account limits", k)} |
| 3595 |
*errors = append(*errors, err) |
| 3596 |
} |
| 3597 |
} |
| 3598 |
} |
| 3599 |
|
| 3600 |
return nil |
| 3601 |
} |
| 3602 |
|
| 3603 |
func parseAccountMsgTrace(mv any, topKey string, acc *Account) error { |
| 3604 |
processDest := func(tk token, k string, v any) error { |
| 3605 |
td, ok := v.(string) |
| 3606 |
if !ok { |
| 3607 |
return &configErr{tk, fmt.Sprintf("Field %q should be a string, got %T", k, v)} |
| 3608 |
} |
| 3609 |
if !IsValidPublishSubject(td) { |
| 3610 |
return &configErr{tk, fmt.Sprintf("Trace destination %q is not valid", td)} |
| 3611 |
} |
| 3612 |
acc.traceDest = td |
| 3613 |
return nil |
| 3614 |
} |
| 3615 |
processSampling := func(tk token, n int) error { |
| 3616 |
if n <= 0 || n > 100 { |
| 3617 |
return &configErr{tk, fmt.Sprintf("Ttrace destination sampling value %d is invalid, needs to be [1..100]", n)} |
| 3618 |
} |
| 3619 |
acc.traceDestSampling = n |
| 3620 |
return nil |
| 3621 |
} |
| 3622 |
|
| 3623 |
var lt token |
| 3624 |
tk, v := unwrapValue(mv, <) |
| 3625 |
switch vv := v.(type) { |
| 3626 |
case string: |
| 3627 |
return processDest(tk, topKey, v) |
| 3628 |
case map[string]any: |
| 3629 |
for k, v := range vv { |
| 3630 |
tk, v := unwrapValue(v, <) |
| 3631 |
switch strings.ToLower(k) { |
| 3632 |
case "dest": |
| 3633 |
if err := processDest(tk, k, v); err != nil { |
| 3634 |
return err |
| 3635 |
} |
| 3636 |
case "sampling": |
| 3637 |
switch vv := v.(type) { |
| 3638 |
case int64: |
| 3639 |
if err := processSampling(tk, int(vv)); err != nil { |
| 3640 |
return err |
| 3641 |
} |
| 3642 |
case string: |
| 3643 |
s := strings.TrimSuffix(vv, "%") |
| 3644 |
n, err := strconv.Atoi(s) |
| 3645 |
if err != nil { |
| 3646 |
return &configErr{tk, fmt.Sprintf("Invalid trace destination sampling value %q", vv)} |
| 3647 |
} |
| 3648 |
if err := processSampling(tk, n); err != nil { |
| 3649 |
return err |
| 3650 |
} |
| 3651 |
default: |
| 3652 |
return &configErr{tk, fmt.Sprintf("Trace destination sampling field %q should be an integer or a percentage, got %T", k, v)} |
| 3653 |
} |
| 3654 |
default: |
| 3655 |
if !tk.IsUsedVariable() { |
| 3656 |
return &configErr{tk, fmt.Sprintf("Unknown field %q parsing account message trace map/struct %q", k, topKey)} |
| 3657 |
} |
| 3658 |
} |
| 3659 |
} |
| 3660 |
default: |
| 3661 |
return &configErr{tk, fmt.Sprintf("Expected account message trace %q to be a string or a map/struct, got %T", topKey, v)} |
| 3662 |
} |
| 3663 |
return nil |
| 3664 |
} |
| 3665 |
|
| 3666 |
// parseAccounts will parse the different accounts syntax. |
| 3667 |
func parseAccounts(v any, opts *Options, errors *[]error, warnings *[]error) error { |
| 3668 |
var ( |
| 3669 |
importStreams []*importStream |
| 3670 |
importServices []*importService |
| 3671 |
exportStreams []*export |
| 3672 |
exportServices []*export |
| 3673 |
lt token |
| 3674 |
) |
| 3675 |
defer convertPanicToErrorList(<, errors) |
| 3676 |
|
| 3677 |
tk, v := unwrapValue(v, <) |
| 3678 |
switch vv := v.(type) { |
| 3679 |
// Simple array of account names. |
| 3680 |
case []any, []string: |
| 3681 |
m := make(map[string]struct{}, len(v.([]any))) |
| 3682 |
for _, n := range v.([]any) { |
| 3683 |
tk, name := unwrapValue(n, <) |
| 3684 |
ns := name.(string) |
| 3685 |
// Check for reserved names. |
| 3686 |
if isReservedAccount(ns) { |
| 3687 |
err := &configErr{tk, fmt.Sprintf("%q is a Reserved Account", ns)} |
| 3688 |
*errors = append(*errors, err) |
| 3689 |
continue |
| 3690 |
} |
| 3691 |
if _, ok := m[ns]; ok { |
| 3692 |
err := &configErr{tk, fmt.Sprintf("Duplicate Account Entry: %s", ns)} |
| 3693 |
*errors = append(*errors, err) |
| 3694 |
continue |
| 3695 |
} |
| 3696 |
opts.Accounts = append(opts.Accounts, NewAccount(ns)) |
| 3697 |
m[ns] = struct{}{} |
| 3698 |
} |
| 3699 |
// More common map entry |
| 3700 |
case map[string]any: |
| 3701 |
// Track users across accounts, must be unique across |
| 3702 |
// accounts and nkeys vs users. |
| 3703 |
// We also want to check for users that may have been added in |
| 3704 |
// parseAuthorization{} if that happened first. |
| 3705 |
uorn := setupUsersAndNKeysDuplicateCheckMap(opts) |
| 3706 |
|
| 3707 |
for aname, mv := range vv { |
| 3708 |
tk, amv := unwrapValue(mv, <) |
| 3709 |
|
| 3710 |
// Skip referenced config vars within the account block. |
| 3711 |
if tk.IsUsedVariable() { |
| 3712 |
continue |
| 3713 |
} |
| 3714 |
|
| 3715 |
// These should be maps. |
| 3716 |
mv, ok := amv.(map[string]any) |
| 3717 |
if !ok { |
| 3718 |
err := &configErr{tk, "Expected map entries for accounts"} |
| 3719 |
*errors = append(*errors, err) |
| 3720 |
continue |
| 3721 |
} |
| 3722 |
if isReservedAccount(aname) { |
| 3723 |
err := &configErr{tk, fmt.Sprintf("%q is a Reserved Account", aname)} |
| 3724 |
*errors = append(*errors, err) |
| 3725 |
continue |
| 3726 |
} |
| 3727 |
var ( |
| 3728 |
users []*User |
| 3729 |
nkeyUsr []*NkeyUser |
| 3730 |
usersTk token |
| 3731 |
) |
| 3732 |
acc := NewAccount(aname) |
| 3733 |
opts.Accounts = append(opts.Accounts, acc) |
| 3734 |
|
| 3735 |
for k, v := range mv { |
| 3736 |
tk, mv := unwrapValue(v, <) |
| 3737 |
switch strings.ToLower(k) { |
| 3738 |
case "nkey": |
| 3739 |
nk, ok := mv.(string) |
| 3740 |
if !ok || !nkeys.IsValidPublicAccountKey(nk) { |
| 3741 |
err := &configErr{tk, fmt.Sprintf("Not a valid public nkey for an account: %q", mv)} |
| 3742 |
*errors = append(*errors, err) |
| 3743 |
continue |
| 3744 |
} |
| 3745 |
acc.Nkey = nk |
| 3746 |
case "imports": |
| 3747 |
streams, services, err := parseAccountImports(tk, acc, errors) |
| 3748 |
if err != nil { |
| 3749 |
*errors = append(*errors, err) |
| 3750 |
continue |
| 3751 |
} |
| 3752 |
importStreams = append(importStreams, streams...) |
| 3753 |
importServices = append(importServices, services...) |
| 3754 |
case "exports": |
| 3755 |
streams, services, err := parseAccountExports(tk, acc, errors) |
| 3756 |
if err != nil { |
| 3757 |
*errors = append(*errors, err) |
| 3758 |
continue |
| 3759 |
} |
| 3760 |
exportStreams = append(exportStreams, streams...) |
| 3761 |
exportServices = append(exportServices, services...) |
| 3762 |
case "jetstream": |
| 3763 |
err := parseJetStreamForAccount(mv, acc, errors) |
| 3764 |
if err != nil { |
| 3765 |
*errors = append(*errors, err) |
| 3766 |
continue |
| 3767 |
} |
| 3768 |
case "users": |
| 3769 |
var err error |
| 3770 |
usersTk = tk |
| 3771 |
nkeyUsr, users, err = parseUsers(mv, errors) |
| 3772 |
if err != nil { |
| 3773 |
*errors = append(*errors, err) |
| 3774 |
continue |
| 3775 |
} |
| 3776 |
case "default_permissions": |
| 3777 |
permissions, err := parseUserPermissions(tk, errors) |
| 3778 |
if err != nil { |
| 3779 |
*errors = append(*errors, err) |
| 3780 |
continue |
| 3781 |
} |
| 3782 |
acc.defaultPerms = permissions |
| 3783 |
case "mappings", "maps": |
| 3784 |
err := parseAccountMappings(tk, acc, errors) |
| 3785 |
if err != nil { |
| 3786 |
*errors = append(*errors, err) |
| 3787 |
continue |
| 3788 |
} |
| 3789 |
case "limits": |
| 3790 |
err := parseAccountLimits(tk, acc, errors) |
| 3791 |
if err != nil { |
| 3792 |
*errors = append(*errors, err) |
| 3793 |
continue |
| 3794 |
} |
| 3795 |
case "msg_trace", "trace_dest": |
| 3796 |
if err := parseAccountMsgTrace(tk, k, acc); err != nil { |
| 3797 |
*errors = append(*errors, err) |
| 3798 |
continue |
| 3799 |
} |
| 3800 |
// If trace destination is set but no sampling, set it to 100%. |
| 3801 |
if acc.traceDest != _EMPTY_ && acc.traceDestSampling == 0 { |
| 3802 |
acc.traceDestSampling = 100 |
| 3803 |
} else if acc.traceDestSampling > 0 && acc.traceDest == _EMPTY_ { |
| 3804 |
// If no trace destination is provided, no trace would be |
| 3805 |
// triggered, so if the user set a sampling value expecting |
| 3806 |
// something to happen, want and set the value to 0 for good |
| 3807 |
// measure. |
| 3808 |
*warnings = append(*warnings, |
| 3809 |
&configErr{tk, "Trace destination sampling ignored since no destination was set"}) |
| 3810 |
acc.traceDestSampling = 0 |
| 3811 |
} |
| 3812 |
default: |
| 3813 |
if !tk.IsUsedVariable() { |
| 3814 |
err := &unknownConfigFieldErr{ |
| 3815 |
field: k, |
| 3816 |
configErr: configErr{ |
| 3817 |
token: tk, |
| 3818 |
}, |
| 3819 |
} |
| 3820 |
*errors = append(*errors, err) |
| 3821 |
} |
| 3822 |
} |
| 3823 |
} |
| 3824 |
// Report error if there is an authorization{} block |
| 3825 |
// with u/p or token and any user defined in accounts{} |
| 3826 |
if len(nkeyUsr) > 0 || len(users) > 0 { |
| 3827 |
if opts.Username != _EMPTY_ { |
| 3828 |
err := &configErr{usersTk, "Can not have a single user/pass and accounts"} |
| 3829 |
*errors = append(*errors, err) |
| 3830 |
continue |
| 3831 |
} |
| 3832 |
if opts.Authorization != _EMPTY_ { |
| 3833 |
err := &configErr{usersTk, "Can not have a token and accounts"} |
| 3834 |
*errors = append(*errors, err) |
| 3835 |
continue |
| 3836 |
} |
| 3837 |
} |
| 3838 |
applyDefaultPermissions(users, nkeyUsr, acc.defaultPerms) |
| 3839 |
for _, u := range nkeyUsr { |
| 3840 |
if _, ok := uorn[u.Nkey]; ok { |
| 3841 |
err := &configErr{usersTk, fmt.Sprintf("Duplicate nkey %q detected", u.Nkey)} |
| 3842 |
*errors = append(*errors, err) |
| 3843 |
continue |
| 3844 |
} |
| 3845 |
uorn[u.Nkey] = struct{}{} |
| 3846 |
u.Account = acc |
| 3847 |
} |
| 3848 |
opts.Nkeys = append(opts.Nkeys, nkeyUsr...) |
| 3849 |
for _, u := range users { |
| 3850 |
if _, ok := uorn[u.Username]; ok { |
| 3851 |
err := &configErr{usersTk, fmt.Sprintf("Duplicate user %q detected", u.Username)} |
| 3852 |
*errors = append(*errors, err) |
| 3853 |
continue |
| 3854 |
} |
| 3855 |
uorn[u.Username] = struct{}{} |
| 3856 |
u.Account = acc |
| 3857 |
} |
| 3858 |
opts.Users = append(opts.Users, users...) |
| 3859 |
} |
| 3860 |
} |
| 3861 |
lt = tk |
| 3862 |
// Bail already if there are previous errors. |
| 3863 |
if len(*errors) > 0 { |
| 3864 |
return nil |
| 3865 |
} |
| 3866 |
|
| 3867 |
// Parse Imports and Exports here after all accounts defined. |
| 3868 |
// Do exports first since they need to be defined for imports to succeed |
| 3869 |
// since we do permissions checks. |
| 3870 |
|
| 3871 |
// Create a lookup map for accounts lookups. |
| 3872 |
am := make(map[string]*Account, len(opts.Accounts)) |
| 3873 |
for _, a := range opts.Accounts { |
| 3874 |
am[a.Name] = a |
| 3875 |
} |
| 3876 |
// Do stream exports |
| 3877 |
for _, stream := range exportStreams { |
| 3878 |
// Make array of accounts if applicable. |
| 3879 |
var accounts []*Account |
| 3880 |
for _, an := range stream.accs { |
| 3881 |
ta := am[an] |
| 3882 |
if ta == nil { |
| 3883 |
msg := fmt.Sprintf("%q account not defined for stream export", an) |
| 3884 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3885 |
continue |
| 3886 |
} |
| 3887 |
accounts = append(accounts, ta) |
| 3888 |
} |
| 3889 |
if err := stream.acc.addStreamExportWithAccountPos(stream.sub, accounts, stream.tPos); err != nil { |
| 3890 |
msg := fmt.Sprintf("Error adding stream export %q: %v", stream.sub, err) |
| 3891 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3892 |
continue |
| 3893 |
} |
| 3894 |
} |
| 3895 |
for _, service := range exportServices { |
| 3896 |
// Make array of accounts if applicable. |
| 3897 |
var accounts []*Account |
| 3898 |
for _, an := range service.accs { |
| 3899 |
ta := am[an] |
| 3900 |
if ta == nil { |
| 3901 |
msg := fmt.Sprintf("%q account not defined for service export", an) |
| 3902 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3903 |
continue |
| 3904 |
} |
| 3905 |
accounts = append(accounts, ta) |
| 3906 |
} |
| 3907 |
if err := service.acc.addServiceExportWithResponseAndAccountPos(service.sub, service.rt, accounts, service.tPos); err != nil { |
| 3908 |
msg := fmt.Sprintf("Error adding service export %q: %v", service.sub, err) |
| 3909 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3910 |
continue |
| 3911 |
} |
| 3912 |
|
| 3913 |
if service.rthr != 0 { |
| 3914 |
// Response threshold was set in options. |
| 3915 |
if err := service.acc.SetServiceExportResponseThreshold(service.sub, service.rthr); err != nil { |
| 3916 |
msg := fmt.Sprintf("Error adding service export response threshold for %q: %v", service.sub, err) |
| 3917 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3918 |
continue |
| 3919 |
} |
| 3920 |
} |
| 3921 |
|
| 3922 |
if service.lat != nil { |
| 3923 |
// System accounts are on be default so just make sure we have not opted out.. |
| 3924 |
if opts.NoSystemAccount { |
| 3925 |
msg := fmt.Sprintf("Error adding service latency sampling for %q: %v", service.sub, ErrNoSysAccount.Error()) |
| 3926 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3927 |
continue |
| 3928 |
} |
| 3929 |
|
| 3930 |
if err := service.acc.TrackServiceExportWithSampling(service.sub, service.lat.subject, int(service.lat.sampling)); err != nil { |
| 3931 |
msg := fmt.Sprintf("Error adding service latency sampling for %q on subject %q: %v", service.sub, service.lat.subject, err) |
| 3932 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3933 |
continue |
| 3934 |
} |
| 3935 |
} |
| 3936 |
|
| 3937 |
if service.atrc { |
| 3938 |
if err := service.acc.SetServiceExportAllowTrace(service.sub, true); err != nil { |
| 3939 |
msg := fmt.Sprintf("Error adding allow_trace for %q: %v", service.sub, err) |
| 3940 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3941 |
continue |
| 3942 |
} |
| 3943 |
} |
| 3944 |
} |
| 3945 |
for _, stream := range importStreams { |
| 3946 |
ta := am[stream.an] |
| 3947 |
if ta == nil { |
| 3948 |
msg := fmt.Sprintf("%q account not defined for stream import", stream.an) |
| 3949 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3950 |
continue |
| 3951 |
} |
| 3952 |
if stream.pre != _EMPTY_ { |
| 3953 |
if err := stream.acc.addStreamImportWithClaim(ta, stream.sub, stream.pre, stream.atrc, nil); err != nil { |
| 3954 |
msg := fmt.Sprintf("Error adding stream import %q: %v", stream.sub, err) |
| 3955 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3956 |
continue |
| 3957 |
} |
| 3958 |
} else { |
| 3959 |
if err := stream.acc.addMappedStreamImportWithClaim(ta, stream.sub, stream.to, stream.atrc, nil); err != nil { |
| 3960 |
msg := fmt.Sprintf("Error adding stream import %q: %v", stream.sub, err) |
| 3961 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3962 |
continue |
| 3963 |
} |
| 3964 |
} |
| 3965 |
} |
| 3966 |
for _, service := range importServices { |
| 3967 |
ta := am[service.an] |
| 3968 |
if ta == nil { |
| 3969 |
msg := fmt.Sprintf("%q account not defined for service import", service.an) |
| 3970 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3971 |
continue |
| 3972 |
} |
| 3973 |
if service.to == _EMPTY_ { |
| 3974 |
service.to = service.sub |
| 3975 |
} |
| 3976 |
if err := service.acc.AddServiceImport(ta, service.to, service.sub); err != nil { |
| 3977 |
msg := fmt.Sprintf("Error adding service import %q: %v", service.sub, err) |
| 3978 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3979 |
continue |
| 3980 |
} |
| 3981 |
if err := service.acc.SetServiceImportSharing(ta, service.sub, service.share); err != nil { |
| 3982 |
msg := fmt.Sprintf("Error setting service import sharing %q: %v", service.sub, err) |
| 3983 |
*errors = append(*errors, &configErr{tk, msg}) |
| 3984 |
continue |
| 3985 |
} |
| 3986 |
} |
| 3987 |
|
| 3988 |
return nil |
| 3989 |
} |
| 3990 |
|
| 3991 |
// Parse the account exports |
| 3992 |
func parseAccountExports(v any, acc *Account, errors *[]error) ([]*export, []*export, error) { |
| 3993 |
var lt token |
| 3994 |
defer convertPanicToErrorList(<, errors) |
| 3995 |
|
| 3996 |
// This should be an array of objects/maps. |
| 3997 |
tk, v := unwrapValue(v, <) |
| 3998 |
ims, ok := v.([]any) |
| 3999 |
if !ok { |
| 4000 |
return nil, nil, &configErr{tk, fmt.Sprintf("Exports should be an array, got %T", v)} |
| 4001 |
} |
| 4002 |
|
| 4003 |
var services []*export |
| 4004 |
var streams []*export |
| 4005 |
|
| 4006 |
for _, v := range ims { |
| 4007 |
// Should have stream or service |
| 4008 |
stream, service, err := parseExportStreamOrService(v, errors) |
| 4009 |
if err != nil { |
| 4010 |
*errors = append(*errors, err) |
| 4011 |
continue |
| 4012 |
} |
| 4013 |
if service != nil { |
| 4014 |
service.acc = acc |
| 4015 |
services = append(services, service) |
| 4016 |
} |
| 4017 |
if stream != nil { |
| 4018 |
stream.acc = acc |
| 4019 |
streams = append(streams, stream) |
| 4020 |
} |
| 4021 |
} |
| 4022 |
return streams, services, nil |
| 4023 |
} |
| 4024 |
|
| 4025 |
// Parse the account imports |
| 4026 |
func parseAccountImports(v any, acc *Account, errors *[]error) ([]*importStream, []*importService, error) { |
| 4027 |
var lt token |
| 4028 |
defer convertPanicToErrorList(<, errors) |
| 4029 |
|
| 4030 |
// This should be an array of objects/maps. |
| 4031 |
tk, v := unwrapValue(v, <) |
| 4032 |
ims, ok := v.([]any) |
| 4033 |
if !ok { |
| 4034 |
return nil, nil, &configErr{tk, fmt.Sprintf("Imports should be an array, got %T", v)} |
| 4035 |
} |
| 4036 |
|
| 4037 |
var services []*importService |
| 4038 |
var streams []*importStream |
| 4039 |
svcSubjects := map[string][]*importService{} |
| 4040 |
|
| 4041 |
IMS_LOOP: |
| 4042 |
for _, v := range ims { |
| 4043 |
// Should have stream or service |
| 4044 |
stream, service, err := parseImportStreamOrService(v, errors) |
| 4045 |
if err != nil { |
| 4046 |
*errors = append(*errors, err) |
| 4047 |
continue |
| 4048 |
} |
| 4049 |
if service != nil { |
| 4050 |
sisPerSubj := svcSubjects[service.to] |
| 4051 |
for _, dup := range sisPerSubj { |
| 4052 |
if dup.an == service.an { |
| 4053 |
tk, _ := unwrapValue(v, <) |
| 4054 |
err := &configErr{tk, |
| 4055 |
fmt.Sprintf("Duplicate service import subject %q, previously used in import for account %q, subject %q", |
| 4056 |
service.to, dup.an, dup.sub)} |
| 4057 |
*errors = append(*errors, err) |
| 4058 |
continue IMS_LOOP |
| 4059 |
} |
| 4060 |
} |
| 4061 |
service.acc = acc |
| 4062 |
sisPerSubj = append(sisPerSubj, service) |
| 4063 |
svcSubjects[service.to] = sisPerSubj |
| 4064 |
services = append(services, service) |
| 4065 |
} |
| 4066 |
if stream != nil { |
| 4067 |
stream.acc = acc |
| 4068 |
streams = append(streams, stream) |
| 4069 |
} |
| 4070 |
} |
| 4071 |
return streams, services, nil |
| 4072 |
} |
| 4073 |
|
| 4074 |
// Helper to parse an embedded account description for imported services or streams. |
| 4075 |
func parseAccount(v map[string]any, errors *[]error) (string, string, error) { |
| 4076 |
var lt token |
| 4077 |
defer convertPanicToErrorList(<, errors) |
| 4078 |
|
| 4079 |
var accountName, subject string |
| 4080 |
for mk, mv := range v { |
| 4081 |
tk, mv := unwrapValue(mv, <) |
| 4082 |
switch strings.ToLower(mk) { |
| 4083 |
case "account": |
| 4084 |
accountName = mv.(string) |
| 4085 |
case "subject": |
| 4086 |
subject = mv.(string) |
| 4087 |
default: |
| 4088 |
if !tk.IsUsedVariable() { |
| 4089 |
err := &unknownConfigFieldErr{ |
| 4090 |
field: mk, |
| 4091 |
configErr: configErr{ |
| 4092 |
token: tk, |
| 4093 |
}, |
| 4094 |
} |
| 4095 |
*errors = append(*errors, err) |
| 4096 |
} |
| 4097 |
} |
| 4098 |
} |
| 4099 |
return accountName, subject, nil |
| 4100 |
} |
| 4101 |
|
| 4102 |
// Parse an export stream or service. |
| 4103 |
// e.g. |
| 4104 |
// {stream: "public.>"} # No accounts means public. |
| 4105 |
// {stream: "synadia.private.>", accounts: [cncf, natsio]} |
| 4106 |
// {service: "pub.request"} # No accounts means public. |
| 4107 |
// {service: "pub.special.request", accounts: [nats.io]} |
| 4108 |
func parseExportStreamOrService(v any, errors *[]error) (*export, *export, error) { |
| 4109 |
var ( |
| 4110 |
curStream *export |
| 4111 |
curService *export |
| 4112 |
accounts []string |
| 4113 |
rt ServiceRespType |
| 4114 |
rtSeen bool |
| 4115 |
rtToken token |
| 4116 |
lat *serviceLatency |
| 4117 |
threshSeen bool |
| 4118 |
thresh time.Duration |
| 4119 |
latToken token |
| 4120 |
lt token |
| 4121 |
accTokPos uint |
| 4122 |
atrc bool |
| 4123 |
atrcSeen bool |
| 4124 |
atrcToken token |
| 4125 |
) |
| 4126 |
defer convertPanicToErrorList(<, errors) |
| 4127 |
|
| 4128 |
tk, v := unwrapValue(v, <) |
| 4129 |
vv, ok := v.(map[string]any) |
| 4130 |
if !ok { |
| 4131 |
return nil, nil, &configErr{tk, fmt.Sprintf("Export Items should be a map with type entry, got %T", v)} |
| 4132 |
} |
| 4133 |
for mk, mv := range vv { |
| 4134 |
tk, mv := unwrapValue(mv, <) |
| 4135 |
switch strings.ToLower(mk) { |
| 4136 |
case "stream": |
| 4137 |
if curService != nil { |
| 4138 |
err := &configErr{tk, fmt.Sprintf("Detected stream %q but already saw a service", mv)} |
| 4139 |
*errors = append(*errors, err) |
| 4140 |
continue |
| 4141 |
} |
| 4142 |
if rtToken != nil { |
| 4143 |
err := &configErr{rtToken, "Detected response directive on non-service"} |
| 4144 |
*errors = append(*errors, err) |
| 4145 |
continue |
| 4146 |
} |
| 4147 |
if latToken != nil { |
| 4148 |
err := &configErr{latToken, "Detected latency directive on non-service"} |
| 4149 |
*errors = append(*errors, err) |
| 4150 |
continue |
| 4151 |
} |
| 4152 |
if atrcToken != nil { |
| 4153 |
err := &configErr{atrcToken, "Detected allow_trace directive on non-service"} |
| 4154 |
*errors = append(*errors, err) |
| 4155 |
continue |
| 4156 |
} |
| 4157 |
mvs, ok := mv.(string) |
| 4158 |
if !ok { |
| 4159 |
err := &configErr{tk, fmt.Sprintf("Expected stream name to be string, got %T", mv)} |
| 4160 |
*errors = append(*errors, err) |
| 4161 |
continue |
| 4162 |
} |
| 4163 |
curStream = &export{sub: mvs} |
| 4164 |
if accounts != nil { |
| 4165 |
curStream.accs = accounts |
| 4166 |
} |
| 4167 |
case "service": |
| 4168 |
if curStream != nil { |
| 4169 |
err := &configErr{tk, fmt.Sprintf("Detected service %q but already saw a stream", mv)} |
| 4170 |
*errors = append(*errors, err) |
| 4171 |
continue |
| 4172 |
} |
| 4173 |
mvs, ok := mv.(string) |
| 4174 |
if !ok { |
| 4175 |
err := &configErr{tk, fmt.Sprintf("Expected service name to be string, got %T", mv)} |
| 4176 |
*errors = append(*errors, err) |
| 4177 |
continue |
| 4178 |
} |
| 4179 |
curService = &export{sub: mvs} |
| 4180 |
if accounts != nil { |
| 4181 |
curService.accs = accounts |
| 4182 |
} |
| 4183 |
if rtSeen { |
| 4184 |
curService.rt = rt |
| 4185 |
} |
| 4186 |
if lat != nil { |
| 4187 |
curService.lat = lat |
| 4188 |
} |
| 4189 |
if threshSeen { |
| 4190 |
curService.rthr = thresh |
| 4191 |
} |
| 4192 |
if atrcSeen { |
| 4193 |
curService.atrc = atrc |
| 4194 |
} |
| 4195 |
case "response", "response_type": |
| 4196 |
if rtSeen { |
| 4197 |
err := &configErr{tk, "Duplicate response type definition"} |
| 4198 |
*errors = append(*errors, err) |
| 4199 |
continue |
| 4200 |
} |
| 4201 |
rtSeen = true |
| 4202 |
rtToken = tk |
| 4203 |
mvs, ok := mv.(string) |
| 4204 |
if !ok { |
| 4205 |
err := &configErr{tk, fmt.Sprintf("Expected response type to be string, got %T", mv)} |
| 4206 |
*errors = append(*errors, err) |
| 4207 |
continue |
| 4208 |
} |
| 4209 |
switch strings.ToLower(mvs) { |
| 4210 |
case "single", "singleton": |
| 4211 |
rt = Singleton |
| 4212 |
case "stream": |
| 4213 |
rt = Streamed |
| 4214 |
case "chunk", "chunked": |
| 4215 |
rt = Chunked |
| 4216 |
default: |
| 4217 |
err := &configErr{tk, fmt.Sprintf("Unknown response type: %q", mvs)} |
| 4218 |
*errors = append(*errors, err) |
| 4219 |
continue |
| 4220 |
} |
| 4221 |
if curService != nil { |
| 4222 |
curService.rt = rt |
| 4223 |
} |
| 4224 |
if curStream != nil { |
| 4225 |
err := &configErr{tk, "Detected response directive on non-service"} |
| 4226 |
*errors = append(*errors, err) |
| 4227 |
} |
| 4228 |
case "threshold", "response_threshold", "response_max_time", "response_time": |
| 4229 |
if threshSeen { |
| 4230 |
err := &configErr{tk, "Duplicate response threshold detected"} |
| 4231 |
*errors = append(*errors, err) |
| 4232 |
continue |
| 4233 |
} |
| 4234 |
threshSeen = true |
| 4235 |
mvs, ok := mv.(string) |
| 4236 |
if !ok { |
| 4237 |
err := &configErr{tk, fmt.Sprintf("Expected response threshold to be a parseable time duration, got %T", mv)} |
| 4238 |
*errors = append(*errors, err) |
| 4239 |
continue |
| 4240 |
} |
| 4241 |
var err error |
| 4242 |
thresh, err = time.ParseDuration(mvs) |
| 4243 |
if err != nil { |
| 4244 |
err := &configErr{tk, fmt.Sprintf("Expected response threshold to be a parseable time duration, got %q", mvs)} |
| 4245 |
*errors = append(*errors, err) |
| 4246 |
continue |
| 4247 |
} |
| 4248 |
if curService != nil { |
| 4249 |
curService.rthr = thresh |
| 4250 |
} |
| 4251 |
if curStream != nil { |
| 4252 |
err := &configErr{tk, "Detected response directive on non-service"} |
| 4253 |
*errors = append(*errors, err) |
| 4254 |
} |
| 4255 |
case "accounts": |
| 4256 |
for _, iv := range mv.([]any) { |
| 4257 |
_, mv := unwrapValue(iv, <) |
| 4258 |
accounts = append(accounts, mv.(string)) |
| 4259 |
} |
| 4260 |
if curStream != nil { |
| 4261 |
curStream.accs = accounts |
| 4262 |
} else if curService != nil { |
| 4263 |
curService.accs = accounts |
| 4264 |
} |
| 4265 |
case "latency": |
| 4266 |
latToken = tk |
| 4267 |
var err error |
| 4268 |
lat, err = parseServiceLatency(tk, mv) |
| 4269 |
if err != nil { |
| 4270 |
*errors = append(*errors, err) |
| 4271 |
continue |
| 4272 |
} |
| 4273 |
if curStream != nil { |
| 4274 |
err = &configErr{tk, "Detected latency directive on non-service"} |
| 4275 |
*errors = append(*errors, err) |
| 4276 |
continue |
| 4277 |
} |
| 4278 |
if curService != nil { |
| 4279 |
curService.lat = lat |
| 4280 |
} |
| 4281 |
case "account_token_position": |
| 4282 |
accTokPos = uint(mv.(int64)) |
| 4283 |
case "allow_trace": |
| 4284 |
atrcSeen = true |
| 4285 |
atrcToken = tk |
| 4286 |
atrc = mv.(bool) |
| 4287 |
if curStream != nil { |
| 4288 |
*errors = append(*errors, |
| 4289 |
&configErr{tk, "Detected allow_trace directive on non-service"}) |
| 4290 |
continue |
| 4291 |
} |
| 4292 |
if curService != nil { |
| 4293 |
curService.atrc = atrc |
| 4294 |
} |
| 4295 |
default: |
| 4296 |
if !tk.IsUsedVariable() { |
| 4297 |
err := &unknownConfigFieldErr{ |
| 4298 |
field: mk, |
| 4299 |
configErr: configErr{ |
| 4300 |
token: tk, |
| 4301 |
}, |
| 4302 |
} |
| 4303 |
*errors = append(*errors, err) |
| 4304 |
} |
| 4305 |
} |
| 4306 |
} |
| 4307 |
if curStream != nil { |
| 4308 |
curStream.tPos = accTokPos |
| 4309 |
} |
| 4310 |
if curService != nil { |
| 4311 |
curService.tPos = accTokPos |
| 4312 |
} |
| 4313 |
return curStream, curService, nil |
| 4314 |
} |
| 4315 |
|
| 4316 |
// parseServiceLatency returns a latency config block. |
| 4317 |
func parseServiceLatency(root token, v any) (l *serviceLatency, retErr error) { |
| 4318 |
var lt token |
| 4319 |
defer convertPanicToError(<, &retErr) |
| 4320 |
|
| 4321 |
if subject, ok := v.(string); ok { |
| 4322 |
return &serviceLatency{ |
| 4323 |
subject: subject, |
| 4324 |
sampling: DEFAULT_SERVICE_LATENCY_SAMPLING, |
| 4325 |
}, nil |
| 4326 |
} |
| 4327 |
|
| 4328 |
latency, ok := v.(map[string]any) |
| 4329 |
if !ok { |
| 4330 |
return nil, &configErr{token: root, |
| 4331 |
reason: fmt.Sprintf("Expected latency entry to be a map/struct or string, got %T", v)} |
| 4332 |
} |
| 4333 |
|
| 4334 |
sl := serviceLatency{ |
| 4335 |
sampling: DEFAULT_SERVICE_LATENCY_SAMPLING, |
| 4336 |
} |
| 4337 |
|
| 4338 |
// Read sampling value. |
| 4339 |
if v, ok := latency["sampling"]; ok { |
| 4340 |
tk, v := unwrapValue(v, <) |
| 4341 |
header := false |
| 4342 |
var sample int64 |
| 4343 |
switch vv := v.(type) { |
| 4344 |
case int64: |
| 4345 |
// Sample is an int, like 50. |
| 4346 |
sample = vv |
| 4347 |
case string: |
| 4348 |
// Sample is a string, like "50%". |
| 4349 |
if strings.ToLower(strings.TrimSpace(vv)) == "headers" { |
| 4350 |
header = true |
| 4351 |
sample = 0 |
| 4352 |
break |
| 4353 |
} |
| 4354 |
s := strings.TrimSuffix(vv, "%") |
| 4355 |
n, err := strconv.Atoi(s) |
| 4356 |
if err != nil { |
| 4357 |
return nil, &configErr{token: tk, |
| 4358 |
reason: fmt.Sprintf("Failed to parse latency sample: %v", err)} |
| 4359 |
} |
| 4360 |
sample = int64(n) |
| 4361 |
default: |
| 4362 |
return nil, &configErr{token: tk, |
| 4363 |
reason: fmt.Sprintf("Expected latency sample to be a string or map/struct, got %T", v)} |
| 4364 |
} |
| 4365 |
if !header { |
| 4366 |
if sample < 1 || sample > 100 { |
| 4367 |
return nil, &configErr{token: tk, |
| 4368 |
reason: ErrBadSampling.Error()} |
| 4369 |
} |
| 4370 |
} |
| 4371 |
|
| 4372 |
sl.sampling = int8(sample) |
| 4373 |
} |
| 4374 |
|
| 4375 |
// Read subject value. |
| 4376 |
v, ok = latency["subject"] |
| 4377 |
if !ok { |
| 4378 |
return nil, &configErr{token: root, |
| 4379 |
reason: "Latency subject required, but missing"} |
| 4380 |
} |
| 4381 |
|
| 4382 |
tk, v := unwrapValue(v, <) |
| 4383 |
subject, ok := v.(string) |
| 4384 |
if !ok { |
| 4385 |
return nil, &configErr{token: tk, |
| 4386 |
reason: fmt.Sprintf("Expected latency subject to be a string, got %T", subject)} |
| 4387 |
} |
| 4388 |
sl.subject = subject |
| 4389 |
|
| 4390 |
return &sl, nil |
| 4391 |
} |
| 4392 |
|
| 4393 |
// Parse an import stream or service. |
| 4394 |
// e.g. |
| 4395 |
// {stream: {account: "synadia", subject:"public.synadia"}, prefix: "imports.synadia"} |
| 4396 |
// {stream: {account: "synadia", subject:"synadia.private.*"}} |
| 4397 |
// {service: {account: "synadia", subject: "pub.special.request"}, to: "synadia.request"} |
| 4398 |
func parseImportStreamOrService(v any, errors *[]error) (*importStream, *importService, error) { |
| 4399 |
var ( |
| 4400 |
curStream *importStream |
| 4401 |
curService *importService |
| 4402 |
pre, to string |
| 4403 |
share bool |
| 4404 |
lt token |
| 4405 |
atrc bool |
| 4406 |
atrcSeen bool |
| 4407 |
atrcToken token |
| 4408 |
) |
| 4409 |
defer convertPanicToErrorList(<, errors) |
| 4410 |
|
| 4411 |
tk, mv := unwrapValue(v, <) |
| 4412 |
vv, ok := mv.(map[string]any) |
| 4413 |
if !ok { |
| 4414 |
return nil, nil, &configErr{tk, fmt.Sprintf("Import Items should be a map with type entry, got %T", mv)} |
| 4415 |
} |
| 4416 |
for mk, mv := range vv { |
| 4417 |
tk, mv := unwrapValue(mv, <) |
| 4418 |
switch strings.ToLower(mk) { |
| 4419 |
case "stream": |
| 4420 |
if curService != nil { |
| 4421 |
err := &configErr{tk, "Detected stream but already saw a service"} |
| 4422 |
*errors = append(*errors, err) |
| 4423 |
continue |
| 4424 |
} |
| 4425 |
ac, ok := mv.(map[string]any) |
| 4426 |
if !ok { |
| 4427 |
err := &configErr{tk, fmt.Sprintf("Stream entry should be an account map, got %T", mv)} |
| 4428 |
*errors = append(*errors, err) |
| 4429 |
continue |
| 4430 |
} |
| 4431 |
// Make sure this is a map with account and subject |
| 4432 |
accountName, subject, err := parseAccount(ac, errors) |
| 4433 |
if err != nil { |
| 4434 |
*errors = append(*errors, err) |
| 4435 |
continue |
| 4436 |
} |
| 4437 |
if accountName == _EMPTY_ || subject == _EMPTY_ { |
| 4438 |
err := &configErr{tk, "Expect an account name and a subject"} |
| 4439 |
*errors = append(*errors, err) |
| 4440 |
continue |
| 4441 |
} |
| 4442 |
curStream = &importStream{an: accountName, sub: subject} |
| 4443 |
if to != _EMPTY_ { |
| 4444 |
curStream.to = to |
| 4445 |
} |
| 4446 |
if pre != _EMPTY_ { |
| 4447 |
curStream.pre = pre |
| 4448 |
} |
| 4449 |
if atrcSeen { |
| 4450 |
curStream.atrc = atrc |
| 4451 |
} |
| 4452 |
case "service": |
| 4453 |
if curStream != nil { |
| 4454 |
err := &configErr{tk, "Detected service but already saw a stream"} |
| 4455 |
*errors = append(*errors, err) |
| 4456 |
continue |
| 4457 |
} |
| 4458 |
if atrcToken != nil { |
| 4459 |
err := &configErr{atrcToken, "Detected allow_trace directive on a non-stream"} |
| 4460 |
*errors = append(*errors, err) |
| 4461 |
continue |
| 4462 |
} |
| 4463 |
ac, ok := mv.(map[string]any) |
| 4464 |
if !ok { |
| 4465 |
err := &configErr{tk, fmt.Sprintf("Service entry should be an account map, got %T", mv)} |
| 4466 |
*errors = append(*errors, err) |
| 4467 |
continue |
| 4468 |
} |
| 4469 |
// Make sure this is a map with account and subject |
| 4470 |
accountName, subject, err := parseAccount(ac, errors) |
| 4471 |
if err != nil { |
| 4472 |
*errors = append(*errors, err) |
| 4473 |
continue |
| 4474 |
} |
| 4475 |
if accountName == _EMPTY_ || subject == _EMPTY_ { |
| 4476 |
err := &configErr{tk, "Expect an account name and a subject"} |
| 4477 |
*errors = append(*errors, err) |
| 4478 |
continue |
| 4479 |
} |
| 4480 |
curService = &importService{an: accountName, sub: subject} |
| 4481 |
if to != _EMPTY_ { |
| 4482 |
curService.to = to |
| 4483 |
} else { |
| 4484 |
curService.to = subject |
| 4485 |
} |
| 4486 |
curService.share = share |
| 4487 |
case "prefix": |
| 4488 |
pre = mv.(string) |
| 4489 |
if curStream != nil { |
| 4490 |
curStream.pre = pre |
| 4491 |
} |
| 4492 |
case "to": |
| 4493 |
to = mv.(string) |
| 4494 |
if curService != nil { |
| 4495 |
curService.to = to |
| 4496 |
} |
| 4497 |
if curStream != nil { |
| 4498 |
curStream.to = to |
| 4499 |
if curStream.pre != _EMPTY_ { |
| 4500 |
err := &configErr{tk, "Stream import can not have a 'prefix' and a 'to' property"} |
| 4501 |
*errors = append(*errors, err) |
| 4502 |
continue |
| 4503 |
} |
| 4504 |
} |
| 4505 |
case "share": |
| 4506 |
share = mv.(bool) |
| 4507 |
if curService != nil { |
| 4508 |
curService.share = share |
| 4509 |
} |
| 4510 |
case "allow_trace": |
| 4511 |
if curService != nil { |
| 4512 |
err := &configErr{tk, "Detected allow_trace directive on a non-stream"} |
| 4513 |
*errors = append(*errors, err) |
| 4514 |
continue |
| 4515 |
} |
| 4516 |
atrcSeen = true |
| 4517 |
atrc = mv.(bool) |
| 4518 |
atrcToken = tk |
| 4519 |
if curStream != nil { |
| 4520 |
curStream.atrc = atrc |
| 4521 |
} |
| 4522 |
default: |
| 4523 |
if !tk.IsUsedVariable() { |
| 4524 |
err := &unknownConfigFieldErr{ |
| 4525 |
field: mk, |
| 4526 |
configErr: configErr{ |
| 4527 |
token: tk, |
| 4528 |
}, |
| 4529 |
} |
| 4530 |
*errors = append(*errors, err) |
| 4531 |
} |
| 4532 |
} |
| 4533 |
|
| 4534 |
} |
| 4535 |
return curStream, curService, nil |
| 4536 |
} |
| 4537 |
|
| 4538 |
// Apply permission defaults to users/nkeyuser that don't have their own. |
| 4539 |
func applyDefaultPermissions(users []*User, nkeys []*NkeyUser, defaultP *Permissions) { |
| 4540 |
if defaultP == nil { |
| 4541 |
return |
| 4542 |
} |
| 4543 |
for _, user := range users { |
| 4544 |
if user.Permissions == nil { |
| 4545 |
user.Permissions = defaultP |
| 4546 |
} |
| 4547 |
} |
| 4548 |
for _, user := range nkeys { |
| 4549 |
if user.Permissions == nil { |
| 4550 |
user.Permissions = defaultP |
| 4551 |
} |
| 4552 |
} |
| 4553 |
} |
| 4554 |
|
| 4555 |
// Helper function to parse Authorization configs. |
| 4556 |
func parseAuthorization(v any, errors, warnings *[]error) (*authorization, error) { |
| 4557 |
var ( |
| 4558 |
am map[string]any |
| 4559 |
tk token |
| 4560 |
lt token |
| 4561 |
auth = &authorization{} |
| 4562 |
) |
| 4563 |
defer convertPanicToErrorList(<, errors) |
| 4564 |
|
| 4565 |
_, v = unwrapValue(v, <) |
| 4566 |
am = v.(map[string]any) |
| 4567 |
for mk, mv := range am { |
| 4568 |
tk, mv = unwrapValue(mv, <) |
| 4569 |
switch strings.ToLower(mk) { |
| 4570 |
case "user", "username": |
| 4571 |
auth.user = mv.(string) |
| 4572 |
case "pass", "password": |
| 4573 |
auth.pass = mv.(string) |
| 4574 |
case "token": |
| 4575 |
auth.token = mv.(string) |
| 4576 |
case "timeout": |
| 4577 |
at := float64(0) |
| 4578 |
switch mv := mv.(type) { |
| 4579 |
case int64: |
| 4580 |
at = float64(mv) |
| 4581 |
case float64: |
| 4582 |
at = mv |
| 4583 |
case string: |
| 4584 |
d, err := time.ParseDuration(mv) |
| 4585 |
if err != nil { |
| 4586 |
return nil, &configErr{tk, fmt.Sprintf("error parsing authorization config, 'timeout' %s", err)} |
| 4587 |
} |
| 4588 |
at = d.Seconds() |
| 4589 |
default: |
| 4590 |
return nil, &configErr{tk, "error parsing authorization config, 'timeout' wrong type"} |
| 4591 |
} |
| 4592 |
if at > (60 * time.Second).Seconds() { |
| 4593 |
reason := fmt.Sprintf("timeout of %v (%f seconds) is high, consider keeping it under 60 seconds. possibly caused by unquoted duration; use '1m' instead of 1m, for example", mv, at) |
| 4594 |
*warnings = append(*warnings, &configWarningErr{field: mk, configErr: configErr{token: tk, reason: reason}}) |
| 4595 |
} |
| 4596 |
auth.timeout = at |
| 4597 |
case "users": |
| 4598 |
nkeys, users, err := parseUsers(tk, errors) |
| 4599 |
if err != nil { |
| 4600 |
*errors = append(*errors, err) |
| 4601 |
continue |
| 4602 |
} |
| 4603 |
auth.users = users |
| 4604 |
auth.nkeys = nkeys |
| 4605 |
case "default_permission", "default_permissions", "permissions": |
| 4606 |
permissions, err := parseUserPermissions(tk, errors) |
| 4607 |
if err != nil { |
| 4608 |
*errors = append(*errors, err) |
| 4609 |
continue |
| 4610 |
} |
| 4611 |
auth.defaultPermissions = permissions |
| 4612 |
case "auth_callout", "auth_hook": |
| 4613 |
if fips140.Enabled() { |
| 4614 |
*errors = append(*errors, fmt.Errorf("'auth_callout' cannot be configured in FIPS-140 mode")) |
| 4615 |
continue |
| 4616 |
} |
| 4617 |
ac, err := parseAuthCallout(tk, errors) |
| 4618 |
if err != nil { |
| 4619 |
*errors = append(*errors, err) |
| 4620 |
continue |
| 4621 |
} |
| 4622 |
auth.callout = ac |
| 4623 |
case "proxy_required": |
| 4624 |
auth.proxyRequired = mv.(bool) |
| 4625 |
default: |
| 4626 |
if !tk.IsUsedVariable() { |
| 4627 |
err := &unknownConfigFieldErr{ |
| 4628 |
field: mk, |
| 4629 |
configErr: configErr{ |
| 4630 |
token: tk, |
| 4631 |
}, |
| 4632 |
} |
| 4633 |
*errors = append(*errors, err) |
| 4634 |
} |
| 4635 |
continue |
| 4636 |
} |
| 4637 |
|
| 4638 |
applyDefaultPermissions(auth.users, auth.nkeys, auth.defaultPermissions) |
| 4639 |
} |
| 4640 |
return auth, nil |
| 4641 |
} |
| 4642 |
|
| 4643 |
// Helper function to parse multiple users array with optional permissions. |
| 4644 |
func parseUsers(mv any, errors *[]error) ([]*NkeyUser, []*User, error) { |
| 4645 |
var ( |
| 4646 |
tk token |
| 4647 |
lt token |
| 4648 |
keys []*NkeyUser |
| 4649 |
users = []*User{} |
| 4650 |
) |
| 4651 |
defer convertPanicToErrorList(<, errors) |
| 4652 |
tk, mv = unwrapValue(mv, <) |
| 4653 |
|
| 4654 |
// Make sure we have an array |
| 4655 |
uv, ok := mv.([]any) |
| 4656 |
if !ok { |
| 4657 |
return nil, nil, &configErr{tk, fmt.Sprintf("Expected users field to be an array, got %v", mv)} |
| 4658 |
} |
| 4659 |
for _, u := range uv { |
| 4660 |
tk, u = unwrapValue(u, <) |
| 4661 |
|
| 4662 |
// Check its a map/struct |
| 4663 |
um, ok := u.(map[string]any) |
| 4664 |
if !ok { |
| 4665 |
err := &configErr{tk, fmt.Sprintf("Expected user entry to be a map/struct, got %v", u)} |
| 4666 |
*errors = append(*errors, err) |
| 4667 |
continue |
| 4668 |
} |
| 4669 |
|
| 4670 |
var ( |
| 4671 |
user = &User{} |
| 4672 |
nkey = &NkeyUser{} |
| 4673 |
perms *Permissions |
| 4674 |
err error |
| 4675 |
) |
| 4676 |
for k, v := range um { |
| 4677 |
// Also needs to unwrap first |
| 4678 |
tk, v = unwrapValue(v, <) |
| 4679 |
|
| 4680 |
switch strings.ToLower(k) { |
| 4681 |
case "nkey": |
| 4682 |
nkey.Nkey = v.(string) |
| 4683 |
case "user", "username": |
| 4684 |
user.Username = v.(string) |
| 4685 |
case "pass", "password": |
| 4686 |
user.Password = v.(string) |
| 4687 |
case "permission", "permissions", "authorization": |
| 4688 |
perms, err = parseUserPermissions(tk, errors) |
| 4689 |
if err != nil { |
| 4690 |
*errors = append(*errors, err) |
| 4691 |
continue |
| 4692 |
} |
| 4693 |
case "allowed_connection_types", "connection_types", "clients": |
| 4694 |
cts := parseAllowedConnectionTypes(tk, <, v, errors) |
| 4695 |
nkey.AllowedConnectionTypes = cts |
| 4696 |
user.AllowedConnectionTypes = cts |
| 4697 |
case "proxy_required": |
| 4698 |
nkey.ProxyRequired = v.(bool) |
| 4699 |
user.ProxyRequired = v.(bool) |
| 4700 |
default: |
| 4701 |
if !tk.IsUsedVariable() { |
| 4702 |
err := &unknownConfigFieldErr{ |
| 4703 |
field: k, |
| 4704 |
configErr: configErr{ |
| 4705 |
token: tk, |
| 4706 |
}, |
| 4707 |
} |
| 4708 |
*errors = append(*errors, err) |
| 4709 |
continue |
| 4710 |
} |
| 4711 |
} |
| 4712 |
} |
| 4713 |
// Place perms if we have them. |
| 4714 |
if perms != nil { |
| 4715 |
// nkey takes precedent. |
| 4716 |
if nkey.Nkey != _EMPTY_ { |
| 4717 |
nkey.Permissions = perms |
| 4718 |
} else { |
| 4719 |
user.Permissions = perms |
| 4720 |
} |
| 4721 |
} |
| 4722 |
|
| 4723 |
// Check to make sure we have at least an nkey or username <password> defined. |
| 4724 |
if nkey.Nkey == _EMPTY_ && user.Username == _EMPTY_ { |
| 4725 |
return nil, nil, &configErr{tk, "User entry requires a user"} |
| 4726 |
} else if nkey.Nkey != _EMPTY_ { |
| 4727 |
// Make sure the nkey a proper public nkey for a user.. |
| 4728 |
if !nkeys.IsValidPublicUserKey(nkey.Nkey) { |
| 4729 |
return nil, nil, &configErr{tk, "Not a valid public nkey for a user"} |
| 4730 |
} |
| 4731 |
// If we have user or password defined here that is an error. |
| 4732 |
if user.Username != _EMPTY_ || user.Password != _EMPTY_ { |
| 4733 |
return nil, nil, &configErr{tk, "Nkey users do not take usernames or passwords"} |
| 4734 |
} |
| 4735 |
keys = append(keys, nkey) |
| 4736 |
} else { |
| 4737 |
users = append(users, user) |
| 4738 |
} |
| 4739 |
} |
| 4740 |
return keys, users, nil |
| 4741 |
} |
| 4742 |
|
| 4743 |
func parseAllowedConnectionTypes(tk token, lt *token, mv any, errors *[]error) map[string]struct{} { |
| 4744 |
cts, err := parseStringArray("allowed connection types", tk, lt, mv, errors) |
| 4745 |
// If error, it has already been added to the `errors` array, simply return |
| 4746 |
if err != nil { |
| 4747 |
return nil |
| 4748 |
} |
| 4749 |
m, err := convertAllowedConnectionTypes(cts) |
| 4750 |
if err != nil { |
| 4751 |
*errors = append(*errors, &configErr{tk, err.Error()}) |
| 4752 |
} |
| 4753 |
return m |
| 4754 |
} |
| 4755 |
|
| 4756 |
// Helper function to parse auth callouts. |
| 4757 |
func parseAuthCallout(mv any, errors *[]error) (*AuthCallout, error) { |
| 4758 |
var ( |
| 4759 |
tk token |
| 4760 |
lt token |
| 4761 |
ac = &AuthCallout{} |
| 4762 |
) |
| 4763 |
defer convertPanicToErrorList(<, errors) |
| 4764 |
|
| 4765 |
tk, mv = unwrapValue(mv, <) |
| 4766 |
pm, ok := mv.(map[string]any) |
| 4767 |
if !ok { |
| 4768 |
return nil, &configErr{tk, fmt.Sprintf("Expected authorization callout to be a map/struct, got %+v", mv)} |
| 4769 |
} |
| 4770 |
for k, v := range pm { |
| 4771 |
tk, mv = unwrapValue(v, <) |
| 4772 |
|
| 4773 |
switch strings.ToLower(k) { |
| 4774 |
case "issuer": |
| 4775 |
ac.Issuer = mv.(string) |
| 4776 |
if !nkeys.IsValidPublicAccountKey(ac.Issuer) { |
| 4777 |
return nil, &configErr{tk, fmt.Sprintf("Expected callout user to be a valid public account nkey, got %q", ac.Issuer)} |
| 4778 |
} |
| 4779 |
case "account", "acc": |
| 4780 |
ac.Account = mv.(string) |
| 4781 |
case "auth_users", "users": |
| 4782 |
aua, ok := mv.([]any) |
| 4783 |
if !ok { |
| 4784 |
return nil, &configErr{tk, fmt.Sprintf("Expected auth_users field to be an array, got %T", v)} |
| 4785 |
} |
| 4786 |
for _, uv := range aua { |
| 4787 |
_, uv = unwrapValue(uv, <) |
| 4788 |
ac.AuthUsers = append(ac.AuthUsers, uv.(string)) |
| 4789 |
} |
| 4790 |
case "xkey", "key": |
| 4791 |
ac.XKey = mv.(string) |
| 4792 |
if !nkeys.IsValidPublicCurveKey(ac.XKey) { |
| 4793 |
return nil, &configErr{tk, fmt.Sprintf("Expected callout xkey to be a valid public xkey, got %q", ac.XKey)} |
| 4794 |
} |
| 4795 |
case "allowed_accounts": |
| 4796 |
aua, ok := mv.([]any) |
| 4797 |
if !ok { |
| 4798 |
return nil, &configErr{tk, fmt.Sprintf("Expected allowed accounts field to be an array, got %T", v)} |
| 4799 |
} |
| 4800 |
for _, uv := range aua { |
| 4801 |
_, uv = unwrapValue(uv, <) |
| 4802 |
ac.AllowedAccounts = append(ac.AllowedAccounts, uv.(string)) |
| 4803 |
} |
| 4804 |
default: |
| 4805 |
if !tk.IsUsedVariable() { |
| 4806 |
err := &configErr{tk, fmt.Sprintf("Unknown field %q parsing authorization callout", k)} |
| 4807 |
*errors = append(*errors, err) |
| 4808 |
} |
| 4809 |
} |
| 4810 |
} |
| 4811 |
// Make sure we have all defined. All fields are required. |
| 4812 |
// If no account specified, selet $G. |
| 4813 |
if ac.Account == _EMPTY_ { |
| 4814 |
ac.Account = globalAccountName |
| 4815 |
} |
| 4816 |
if ac.Issuer == _EMPTY_ { |
| 4817 |
return nil, &configErr{tk, "Authorization callouts require an issuer to be specified"} |
| 4818 |
} |
| 4819 |
if len(ac.AuthUsers) == 0 { |
| 4820 |
return nil, &configErr{tk, "Authorization callouts require authorized users to be specified"} |
| 4821 |
} |
| 4822 |
return ac, nil |
| 4823 |
} |
| 4824 |
|
| 4825 |
// Helper function to parse user/account permissions |
| 4826 |
func parseUserPermissions(mv any, errors *[]error) (*Permissions, error) { |
| 4827 |
var ( |
| 4828 |
tk token |
| 4829 |
lt token |
| 4830 |
p = &Permissions{} |
| 4831 |
) |
| 4832 |
defer convertPanicToErrorList(<, errors) |
| 4833 |
|
| 4834 |
tk, mv = unwrapValue(mv, <) |
| 4835 |
pm, ok := mv.(map[string]any) |
| 4836 |
if !ok { |
| 4837 |
return nil, &configErr{tk, fmt.Sprintf("Expected permissions to be a map/struct, got %+v", mv)} |
| 4838 |
} |
| 4839 |
for k, v := range pm { |
| 4840 |
tk, mv = unwrapValue(v, <) |
| 4841 |
|
| 4842 |
switch strings.ToLower(k) { |
| 4843 |
// For routes: |
| 4844 |
// Import is Publish |
| 4845 |
// Export is Subscribe |
| 4846 |
case "pub", "publish", "import": |
| 4847 |
perms, err := parseVariablePermissions(mv, errors, false) |
| 4848 |
if err != nil { |
| 4849 |
*errors = append(*errors, err) |
| 4850 |
continue |
| 4851 |
} |
| 4852 |
p.Publish = perms |
| 4853 |
case "sub", "subscribe", "export": |
| 4854 |
perms, err := parseVariablePermissions(mv, errors, true) |
| 4855 |
if err != nil { |
| 4856 |
*errors = append(*errors, err) |
| 4857 |
continue |
| 4858 |
} |
| 4859 |
p.Subscribe = perms |
| 4860 |
case "publish_allow_responses", "allow_responses": |
| 4861 |
rp := &ResponsePermission{ |
| 4862 |
MaxMsgs: DEFAULT_ALLOW_RESPONSE_MAX_MSGS, |
| 4863 |
Expires: DEFAULT_ALLOW_RESPONSE_EXPIRATION, |
| 4864 |
} |
| 4865 |
// Try boolean first |
| 4866 |
responses, ok := mv.(bool) |
| 4867 |
if ok { |
| 4868 |
if responses { |
| 4869 |
p.Response = rp |
| 4870 |
} |
| 4871 |
} else { |
| 4872 |
p.Response = parseAllowResponses(v, errors) |
| 4873 |
} |
| 4874 |
if p.Response != nil { |
| 4875 |
if p.Publish == nil { |
| 4876 |
p.Publish = &SubjectPermission{} |
| 4877 |
} |
| 4878 |
if p.Publish.Allow == nil { |
| 4879 |
// We turn off the blanket allow statement. |
| 4880 |
p.Publish.Allow = []string{} |
| 4881 |
} |
| 4882 |
} |
| 4883 |
default: |
| 4884 |
if !tk.IsUsedVariable() { |
| 4885 |
err := &configErr{tk, fmt.Sprintf("Unknown field %q parsing permissions", k)} |
| 4886 |
*errors = append(*errors, err) |
| 4887 |
} |
| 4888 |
} |
| 4889 |
} |
| 4890 |
return p, nil |
| 4891 |
} |
| 4892 |
|
| 4893 |
// Top level parser for authorization configurations. |
| 4894 |
func parseVariablePermissions(v any, errors *[]error, allowQueue bool) (*SubjectPermission, error) { |
| 4895 |
switch vv := v.(type) { |
| 4896 |
case map[string]any: |
| 4897 |
// New style with allow and/or deny properties. |
| 4898 |
return parseSubjectPermission(vv, errors, allowQueue) |
| 4899 |
default: |
| 4900 |
// Old style |
| 4901 |
return parseOldPermissionStyle(v, errors, allowQueue) |
| 4902 |
} |
| 4903 |
} |
| 4904 |
|
| 4905 |
// Helper function to parse subject singletons and/or arrays |
| 4906 |
func parsePermSubjects(v any, errors *[]error, allowQueue bool) ([]string, error) { |
| 4907 |
var lt token |
| 4908 |
defer convertPanicToErrorList(<, errors) |
| 4909 |
|
| 4910 |
tk, v := unwrapValue(v, <) |
| 4911 |
|
| 4912 |
var subjects []string |
| 4913 |
switch vv := v.(type) { |
| 4914 |
case string: |
| 4915 |
subjects = append(subjects, vv) |
| 4916 |
case []string: |
| 4917 |
subjects = vv |
| 4918 |
case []any: |
| 4919 |
for _, i := range vv { |
| 4920 |
tk, i := unwrapValue(i, <) |
| 4921 |
|
| 4922 |
subject, ok := i.(string) |
| 4923 |
if !ok { |
| 4924 |
return nil, &configErr{tk, "Subject in permissions array cannot be cast to string"} |
| 4925 |
} |
| 4926 |
subjects = append(subjects, subject) |
| 4927 |
} |
| 4928 |
default: |
| 4929 |
return nil, &configErr{tk, fmt.Sprintf("Expected subject permissions to be a subject, or array of subjects, got %T", v)} |
| 4930 |
} |
| 4931 |
if err := checkPermSubjectArray(subjects, allowQueue); err != nil { |
| 4932 |
return nil, &configErr{tk, err.Error()} |
| 4933 |
} |
| 4934 |
return subjects, nil |
| 4935 |
} |
| 4936 |
|
| 4937 |
// Helper function to parse a ResponsePermission. |
| 4938 |
func parseAllowResponses(v any, errors *[]error) *ResponsePermission { |
| 4939 |
var lt token |
| 4940 |
defer convertPanicToErrorList(<, errors) |
| 4941 |
|
| 4942 |
tk, v := unwrapValue(v, <) |
| 4943 |
// Check if this is a map. |
| 4944 |
pm, ok := v.(map[string]any) |
| 4945 |
if !ok { |
| 4946 |
err := &configErr{tk, "error parsing response permissions, expected a boolean or a map"} |
| 4947 |
*errors = append(*errors, err) |
| 4948 |
return nil |
| 4949 |
} |
| 4950 |
|
| 4951 |
rp := &ResponsePermission{ |
| 4952 |
MaxMsgs: DEFAULT_ALLOW_RESPONSE_MAX_MSGS, |
| 4953 |
Expires: DEFAULT_ALLOW_RESPONSE_EXPIRATION, |
| 4954 |
} |
| 4955 |
|
| 4956 |
for k, v := range pm { |
| 4957 |
tk, v = unwrapValue(v, <) |
| 4958 |
switch strings.ToLower(k) { |
| 4959 |
case "max", "max_msgs", "max_messages", "max_responses": |
| 4960 |
max := int(v.(int64)) |
| 4961 |
// Negative values are accepted (mean infinite), and 0 |
| 4962 |
// means default value (set above). |
| 4963 |
if max != 0 { |
| 4964 |
rp.MaxMsgs = max |
| 4965 |
} |
| 4966 |
case "expires", "expiration", "ttl": |
| 4967 |
wd, ok := v.(string) |
| 4968 |
if ok { |
| 4969 |
ttl, err := time.ParseDuration(wd) |
| 4970 |
if err != nil { |
| 4971 |
err := &configErr{tk, fmt.Sprintf("error parsing expires: %v", err)} |
| 4972 |
*errors = append(*errors, err) |
| 4973 |
return nil |
| 4974 |
} |
| 4975 |
// Negative values are accepted (mean infinite), and 0 |
| 4976 |
// means default value (set above). |
| 4977 |
if ttl != 0 { |
| 4978 |
rp.Expires = ttl |
| 4979 |
} |
| 4980 |
} else { |
| 4981 |
err := &configErr{tk, "error parsing expires, not a duration string"} |
| 4982 |
*errors = append(*errors, err) |
| 4983 |
return nil |
| 4984 |
} |
| 4985 |
default: |
| 4986 |
if !tk.IsUsedVariable() { |
| 4987 |
err := &configErr{tk, fmt.Sprintf("Unknown field %q parsing permissions", k)} |
| 4988 |
*errors = append(*errors, err) |
| 4989 |
} |
| 4990 |
} |
| 4991 |
} |
| 4992 |
return rp |
| 4993 |
} |
| 4994 |
|
| 4995 |
// Helper function to parse old style authorization configs. |
| 4996 |
func parseOldPermissionStyle(v any, errors *[]error, allowQueue bool) (*SubjectPermission, error) { |
| 4997 |
subjects, err := parsePermSubjects(v, errors, allowQueue) |
| 4998 |
if err != nil { |
| 4999 |
return nil, err |
| 5000 |
} |
| 5001 |
return &SubjectPermission{Allow: subjects}, nil |
| 5002 |
} |
| 5003 |
|
| 5004 |
// Helper function to parse new style authorization into a SubjectPermission with Allow and Deny. |
| 5005 |
func parseSubjectPermission(v any, errors *[]error, allowQueue bool) (*SubjectPermission, error) { |
| 5006 |
var lt token |
| 5007 |
defer convertPanicToErrorList(<, errors) |
| 5008 |
|
| 5009 |
m := v.(map[string]any) |
| 5010 |
if len(m) == 0 { |
| 5011 |
return nil, nil |
| 5012 |
} |
| 5013 |
p := &SubjectPermission{} |
| 5014 |
for k, v := range m { |
| 5015 |
tk, _ := unwrapValue(v, <) |
| 5016 |
switch strings.ToLower(k) { |
| 5017 |
case "allow": |
| 5018 |
subjects, err := parsePermSubjects(tk, errors, allowQueue) |
| 5019 |
if err != nil { |
| 5020 |
*errors = append(*errors, err) |
| 5021 |
continue |
| 5022 |
} |
| 5023 |
p.Allow = subjects |
| 5024 |
case "deny": |
| 5025 |
subjects, err := parsePermSubjects(tk, errors, allowQueue) |
| 5026 |
if err != nil { |
| 5027 |
*errors = append(*errors, err) |
| 5028 |
continue |
| 5029 |
} |
| 5030 |
p.Deny = subjects |
| 5031 |
default: |
| 5032 |
if !tk.IsUsedVariable() { |
| 5033 |
err := &configErr{tk, fmt.Sprintf("Unknown field name %q parsing subject permissions, only 'allow' or 'deny' are permitted", k)} |
| 5034 |
*errors = append(*errors, err) |
| 5035 |
} |
| 5036 |
} |
| 5037 |
} |
| 5038 |
return p, nil |
| 5039 |
} |
| 5040 |
|
| 5041 |
// Helper function to validate permissions subjects. |
| 5042 |
func checkPermSubjectArray(sa []string, allowQueue bool) error { |
| 5043 |
for _, s := range sa { |
| 5044 |
if !IsValidSubject(s) { |
| 5045 |
if !allowQueue { |
| 5046 |
return fmt.Errorf("subject %q is not a valid subject", s) |
| 5047 |
} |
| 5048 |
// Check here if this is a queue group qualified subject. |
| 5049 |
elements := strings.Fields(s) |
| 5050 |
if len(elements) != 2 { |
| 5051 |
return fmt.Errorf("subject %q is not a valid subject", s) |
| 5052 |
} else if !IsValidSubject(elements[0]) { |
| 5053 |
return fmt.Errorf("subject %q is not a valid subject", elements[0]) |
| 5054 |
} else if !IsValidSubject(elements[1]) { |
| 5055 |
return fmt.Errorf("queue %q is not a valid queue", elements[1]) |
| 5056 |
} |
| 5057 |
} |
| 5058 |
} |
| 5059 |
return nil |
| 5060 |
} |
| 5061 |
|
| 5062 |
// PrintTLSHelpAndDie prints TLS usage and exits. |
| 5063 |
func PrintTLSHelpAndDie() { |
| 5064 |
fmt.Printf("%s", tlsUsage) |
| 5065 |
for k := range cipherMap { |
| 5066 |
fmt.Printf(" %s\n", k) |
| 5067 |
} |
| 5068 |
fmt.Printf("\nAvailable curve preferences include:\n") |
| 5069 |
for k := range curvePreferenceMap { |
| 5070 |
fmt.Printf(" %s\n", k) |
| 5071 |
} |
| 5072 |
if runtime.GOOS == "windows" { |
| 5073 |
fmt.Printf("%s\n", certstore.Usage) |
| 5074 |
} |
| 5075 |
fmt.Printf("%s", certidp.OCSPPeerUsage) |
| 5076 |
fmt.Printf("%s", OCSPResponseCacheUsage) |
| 5077 |
os.Exit(0) |
| 5078 |
} |
| 5079 |
|
| 5080 |
func parseCipher(cipherName string) (*tls.CipherSuite, error) { |
| 5081 |
cipher, exists := cipherMap[cipherName] |
| 5082 |
if !exists { |
| 5083 |
return nil, fmt.Errorf("unrecognized cipher %s", cipherName) |
| 5084 |
} |
| 5085 |
return cipher, nil |
| 5086 |
} |
| 5087 |
|
| 5088 |
func parseCurvePreferences(curveName string) (tls.CurveID, error) { |
| 5089 |
curve, exists := curvePreferenceMap[curveName] |
| 5090 |
if !exists { |
| 5091 |
return 0, fmt.Errorf("unrecognized curve preference %s", curveName) |
| 5092 |
} |
| 5093 |
return curve, nil |
| 5094 |
} |
| 5095 |
|
| 5096 |
func parseTLSVersion(v any) (uint16, error) { |
| 5097 |
var tlsVersionNumber uint16 |
| 5098 |
switch v := v.(type) { |
| 5099 |
case string: |
| 5100 |
n, err := tlsVersionFromString(v) |
| 5101 |
if err != nil { |
| 5102 |
return 0, err |
| 5103 |
} |
| 5104 |
tlsVersionNumber = n |
| 5105 |
default: |
| 5106 |
return 0, fmt.Errorf("'min_version' wrong type: %v", v) |
| 5107 |
} |
| 5108 |
if tlsVersionNumber < tls.VersionTLS12 { |
| 5109 |
return 0, fmt.Errorf("unsupported TLS version: %s", tls.VersionName(tlsVersionNumber)) |
| 5110 |
} |
| 5111 |
return tlsVersionNumber, nil |
| 5112 |
} |
| 5113 |
|
| 5114 |
// Helper function to parse TLS configs. |
| 5115 |
func parseTLS(v any, isClientCtx bool) (t *TLSConfigOpts, retErr error) { |
| 5116 |
var ( |
| 5117 |
tlsm map[string]any |
| 5118 |
tc = TLSConfigOpts{} |
| 5119 |
lt token |
| 5120 |
ics []*tls.CipherSuite // Insecure ciphers found |
| 5121 |
) |
| 5122 |
defer convertPanicToError(<, &retErr) |
| 5123 |
|
| 5124 |
tk, v := unwrapValue(v, <) |
| 5125 |
tlsm = v.(map[string]any) |
| 5126 |
for mk, mv := range tlsm { |
| 5127 |
tk, mv := unwrapValue(mv, <) |
| 5128 |
switch strings.ToLower(mk) { |
| 5129 |
case "cert_file": |
| 5130 |
certFile, ok := mv.(string) |
| 5131 |
if !ok { |
| 5132 |
return nil, &configErr{tk, "error parsing tls config, expected 'cert_file' to be filename"} |
| 5133 |
} |
| 5134 |
tc.CertFile = certFile |
| 5135 |
case "key_file": |
| 5136 |
keyFile, ok := mv.(string) |
| 5137 |
if !ok { |
| 5138 |
return nil, &configErr{tk, "error parsing tls config, expected 'key_file' to be filename"} |
| 5139 |
} |
| 5140 |
tc.KeyFile = keyFile |
| 5141 |
case "ca_file": |
| 5142 |
caFile, ok := mv.(string) |
| 5143 |
if !ok { |
| 5144 |
return nil, &configErr{tk, "error parsing tls config, expected 'ca_file' to be filename"} |
| 5145 |
} |
| 5146 |
tc.CaFile = caFile |
| 5147 |
case "insecure": |
| 5148 |
insecure, ok := mv.(bool) |
| 5149 |
if !ok { |
| 5150 |
return nil, &configErr{tk, "error parsing tls config, expected 'insecure' to be a boolean"} |
| 5151 |
} |
| 5152 |
tc.Insecure = insecure |
| 5153 |
case "verify": |
| 5154 |
verify, ok := mv.(bool) |
| 5155 |
if !ok { |
| 5156 |
return nil, &configErr{tk, "error parsing tls config, expected 'verify' to be a boolean"} |
| 5157 |
} |
| 5158 |
tc.Verify = verify |
| 5159 |
case "verify_and_map": |
| 5160 |
verify, ok := mv.(bool) |
| 5161 |
if !ok { |
| 5162 |
return nil, &configErr{tk, "error parsing tls config, expected 'verify_and_map' to be a boolean"} |
| 5163 |
} |
| 5164 |
if verify { |
| 5165 |
tc.Verify = verify |
| 5166 |
} |
| 5167 |
tc.Map = verify |
| 5168 |
case "verify_cert_and_check_known_urls": |
| 5169 |
verify, ok := mv.(bool) |
| 5170 |
if !ok { |
| 5171 |
return nil, &configErr{tk, "error parsing tls config, expected 'verify_cert_and_check_known_urls' to be a boolean"} |
| 5172 |
} |
| 5173 |
if verify && isClientCtx { |
| 5174 |
return nil, &configErr{tk, "verify_cert_and_check_known_urls not supported in this context"} |
| 5175 |
} |
| 5176 |
if verify { |
| 5177 |
tc.Verify = verify |
| 5178 |
} |
| 5179 |
tc.TLSCheckKnownURLs = verify |
| 5180 |
case "allow_insecure_cipher_suites": |
| 5181 |
allow, ok := mv.(bool) |
| 5182 |
if !ok { |
| 5183 |
return nil, &configErr{tk, "error parsing tls config, expected 'allow_insecure_cipher_suites' to be a boolean"} |
| 5184 |
} |
| 5185 |
tc.AllowInsecureCiphers = allow |
| 5186 |
case "cipher_suites": |
| 5187 |
ra := mv.([]any) |
| 5188 |
if len(ra) == 0 { |
| 5189 |
return nil, &configErr{tk, "error parsing tls config, 'cipher_suites' cannot be empty"} |
| 5190 |
} |
| 5191 |
tc.Ciphers = make([]uint16, 0, len(ra)) |
| 5192 |
for _, r := range ra { |
| 5193 |
tk, r := unwrapValue(r, <) |
| 5194 |
cipher, err := parseCipher(r.(string)) |
| 5195 |
if err != nil { |
| 5196 |
return nil, &configErr{tk, err.Error()} |
| 5197 |
} |
| 5198 |
tc.Ciphers = append(tc.Ciphers, cipher.ID) |
| 5199 |
if cipher.Insecure { |
| 5200 |
ics = append(ics, cipher) |
| 5201 |
} |
| 5202 |
} |
| 5203 |
case "curve_preferences": |
| 5204 |
ra := mv.([]any) |
| 5205 |
if len(ra) == 0 { |
| 5206 |
return nil, &configErr{tk, "error parsing tls config, 'curve_preferences' cannot be empty"} |
| 5207 |
} |
| 5208 |
tc.CurvePreferences = make([]tls.CurveID, 0, len(ra)) |
| 5209 |
for _, r := range ra { |
| 5210 |
tk, r := unwrapValue(r, <) |
| 5211 |
cps, err := parseCurvePreferences(r.(string)) |
| 5212 |
if err != nil { |
| 5213 |
return nil, &configErr{tk, err.Error()} |
| 5214 |
} |
| 5215 |
tc.CurvePreferences = append(tc.CurvePreferences, cps) |
| 5216 |
} |
| 5217 |
case "timeout": |
| 5218 |
at := float64(0) |
| 5219 |
switch mv := mv.(type) { |
| 5220 |
case int64: |
| 5221 |
at = float64(mv) |
| 5222 |
case float64: |
| 5223 |
at = mv |
| 5224 |
case string: |
| 5225 |
d, err := time.ParseDuration(mv) |
| 5226 |
if err != nil { |
| 5227 |
return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, 'timeout' %s", err)} |
| 5228 |
} |
| 5229 |
at = d.Seconds() |
| 5230 |
default: |
| 5231 |
return nil, &configErr{tk, "error parsing tls config, 'timeout' wrong type"} |
| 5232 |
} |
| 5233 |
tc.Timeout = at |
| 5234 |
case "connection_rate_limit": |
| 5235 |
at := int64(0) |
| 5236 |
switch mv := mv.(type) { |
| 5237 |
case int64: |
| 5238 |
at = mv |
| 5239 |
default: |
| 5240 |
return nil, &configErr{tk, "error parsing tls config, 'connection_rate_limit' wrong type"} |
| 5241 |
} |
| 5242 |
tc.RateLimit = at |
| 5243 |
case "pinned_certs": |
| 5244 |
ra, ok := mv.([]any) |
| 5245 |
if !ok { |
| 5246 |
return nil, &configErr{tk, "error parsing tls config, expected 'pinned_certs' to be a list of hex-encoded sha256 of DER encoded SubjectPublicKeyInfo"} |
| 5247 |
} |
| 5248 |
if len(ra) != 0 { |
| 5249 |
wl := PinnedCertSet{} |
| 5250 |
re := regexp.MustCompile("^[A-Fa-f0-9]{64}$") |
| 5251 |
for _, r := range ra { |
| 5252 |
tk, r := unwrapValue(r, <) |
| 5253 |
entry := strings.ToLower(r.(string)) |
| 5254 |
if !re.MatchString(entry) { |
| 5255 |
return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, 'pinned_certs' key %s does not look like hex-encoded sha256 of DER encoded SubjectPublicKeyInfo", entry)} |
| 5256 |
} |
| 5257 |
wl[entry] = struct{}{} |
| 5258 |
} |
| 5259 |
tc.PinnedCerts = wl |
| 5260 |
} |
| 5261 |
case "cert_store": |
| 5262 |
certStore, ok := mv.(string) |
| 5263 |
if !ok || certStore == _EMPTY_ { |
| 5264 |
return nil, &configErr{tk, certstore.ErrBadCertStoreField.Error()} |
| 5265 |
} |
| 5266 |
certStoreType, err := certstore.ParseCertStore(certStore) |
| 5267 |
if err != nil { |
| 5268 |
return nil, &configErr{tk, err.Error()} |
| 5269 |
} |
| 5270 |
tc.CertStore = certStoreType |
| 5271 |
case "cert_match_by": |
| 5272 |
certMatchBy, ok := mv.(string) |
| 5273 |
if !ok || certMatchBy == _EMPTY_ { |
| 5274 |
return nil, &configErr{tk, certstore.ErrBadCertMatchByField.Error()} |
| 5275 |
} |
| 5276 |
certMatchByType, err := certstore.ParseCertMatchBy(certMatchBy) |
| 5277 |
if err != nil { |
| 5278 |
return nil, &configErr{tk, err.Error()} |
| 5279 |
} |
| 5280 |
tc.CertMatchBy = certMatchByType |
| 5281 |
case "cert_match": |
| 5282 |
certMatch, ok := mv.(string) |
| 5283 |
if !ok || certMatch == _EMPTY_ { |
| 5284 |
return nil, &configErr{tk, certstore.ErrBadCertMatchField.Error()} |
| 5285 |
} |
| 5286 |
tc.CertMatch = certMatch |
| 5287 |
case "ca_certs_match": |
| 5288 |
rv := []string{} |
| 5289 |
switch mv := mv.(type) { |
| 5290 |
case string: |
| 5291 |
rv = append(rv, mv) |
| 5292 |
case []string: |
| 5293 |
rv = append(rv, mv...) |
| 5294 |
case []any: |
| 5295 |
for _, t := range mv { |
| 5296 |
if token, ok := t.(token); ok { |
| 5297 |
if ts, ok := token.Value().(string); ok { |
| 5298 |
rv = append(rv, ts) |
| 5299 |
continue |
| 5300 |
} else { |
| 5301 |
return nil, &configErr{tk, fmt.Sprintf("error parsing ca_cert_match: unsupported type %T where string is expected", token)} |
| 5302 |
} |
| 5303 |
} else { |
| 5304 |
return nil, &configErr{tk, fmt.Sprintf("error parsing ca_cert_match: unsupported type %T", t)} |
| 5305 |
} |
| 5306 |
} |
| 5307 |
} |
| 5308 |
tc.CaCertsMatch = rv |
| 5309 |
case "handshake_first", "first", "immediate": |
| 5310 |
switch mv := mv.(type) { |
| 5311 |
case bool: |
| 5312 |
tc.HandshakeFirst = mv |
| 5313 |
case string: |
| 5314 |
switch strings.ToLower(mv) { |
| 5315 |
case "true", "on": |
| 5316 |
tc.HandshakeFirst = true |
| 5317 |
case "false", "off": |
| 5318 |
tc.HandshakeFirst = false |
| 5319 |
case "auto", "auto_fallback": |
| 5320 |
tc.HandshakeFirst = true |
| 5321 |
tc.FallbackDelay = DEFAULT_TLS_HANDSHAKE_FIRST_FALLBACK_DELAY |
| 5322 |
default: |
| 5323 |
// Check to see if this is a duration. |
| 5324 |
if dur, err := time.ParseDuration(mv); err == nil { |
| 5325 |
tc.HandshakeFirst = true |
| 5326 |
tc.FallbackDelay = dur |
| 5327 |
break |
| 5328 |
} |
| 5329 |
return nil, &configErr{tk, fmt.Sprintf("field %q's value %q is invalid", mk, mv)} |
| 5330 |
} |
| 5331 |
default: |
| 5332 |
return nil, &configErr{tk, fmt.Sprintf("field %q should be a boolean or a string, got %T", mk, mv)} |
| 5333 |
} |
| 5334 |
case "cert_match_skip_invalid": |
| 5335 |
certMatchSkipInvalid, ok := mv.(bool) |
| 5336 |
if !ok { |
| 5337 |
return nil, &configErr{tk, certstore.ErrBadCertMatchSkipInvalidField.Error()} |
| 5338 |
} |
| 5339 |
tc.CertMatchSkipInvalid = certMatchSkipInvalid |
| 5340 |
case "ocsp_peer": |
| 5341 |
switch vv := mv.(type) { |
| 5342 |
case bool: |
| 5343 |
pc := certidp.NewOCSPPeerConfig() |
| 5344 |
if vv { |
| 5345 |
// Set enabled |
| 5346 |
pc.Verify = true |
| 5347 |
tc.OCSPPeerConfig = pc |
| 5348 |
} else { |
| 5349 |
// Set disabled |
| 5350 |
pc.Verify = false |
| 5351 |
tc.OCSPPeerConfig = pc |
| 5352 |
} |
| 5353 |
case map[string]any: |
| 5354 |
pc, err := parseOCSPPeer(mv) |
| 5355 |
if err != nil { |
| 5356 |
return nil, &configErr{tk, err.Error()} |
| 5357 |
} |
| 5358 |
tc.OCSPPeerConfig = pc |
| 5359 |
default: |
| 5360 |
return nil, &configErr{tk, fmt.Sprintf("error parsing ocsp peer config: unsupported type %T", v)} |
| 5361 |
} |
| 5362 |
case "certs", "certificates": |
| 5363 |
certs, ok := mv.([]any) |
| 5364 |
if !ok { |
| 5365 |
return nil, &configErr{tk, fmt.Sprintf("error parsing certificates config: unsupported type %T", v)} |
| 5366 |
} |
| 5367 |
tc.Certificates = make([]*TLSCertPairOpt, len(certs)) |
| 5368 |
for i, v := range certs { |
| 5369 |
tk, vv := unwrapValue(v, <) |
| 5370 |
pair, ok := vv.(map[string]any) |
| 5371 |
if !ok { |
| 5372 |
return nil, &configErr{tk, fmt.Sprintf("error parsing certificates config: unsupported type %T", vv)} |
| 5373 |
} |
| 5374 |
certPair := &TLSCertPairOpt{} |
| 5375 |
for k, v := range pair { |
| 5376 |
tk, vv = unwrapValue(v, <) |
| 5377 |
file, ok := vv.(string) |
| 5378 |
if !ok { |
| 5379 |
return nil, &configErr{tk, fmt.Sprintf("error parsing certificates config: unsupported type %T", vv)} |
| 5380 |
} |
| 5381 |
switch k { |
| 5382 |
case "cert_file": |
| 5383 |
certPair.CertFile = file |
| 5384 |
case "key_file": |
| 5385 |
certPair.KeyFile = file |
| 5386 |
default: |
| 5387 |
return nil, &configErr{tk, fmt.Sprintf("error parsing tls certs config, unknown field %q", k)} |
| 5388 |
} |
| 5389 |
} |
| 5390 |
if certPair.CertFile == _EMPTY_ || certPair.KeyFile == _EMPTY_ { |
| 5391 |
return nil, &configErr{tk, "error parsing certificates config: both 'cert_file' and 'cert_key' options are required"} |
| 5392 |
} |
| 5393 |
tc.Certificates[i] = certPair |
| 5394 |
} |
| 5395 |
case "min_version": |
| 5396 |
minVersion, err := parseTLSVersion(mv) |
| 5397 |
if err != nil { |
| 5398 |
return nil, &configErr{tk, fmt.Sprintf("error parsing tls config: %v", err)} |
| 5399 |
} |
| 5400 |
tc.MinVersion = minVersion |
| 5401 |
default: |
| 5402 |
return nil, &configErr{tk, fmt.Sprintf("error parsing tls config, unknown field %q", mk)} |
| 5403 |
} |
| 5404 |
} |
| 5405 |
if len(tc.Certificates) > 0 && tc.CertFile != _EMPTY_ { |
| 5406 |
return nil, &configErr{tk, "error parsing tls config, cannot combine 'cert_file' option with 'certs' option"} |
| 5407 |
} |
| 5408 |
|
| 5409 |
// If cipher suites were not specified then use the defaults |
| 5410 |
if tc.Ciphers == nil { |
| 5411 |
tc.Ciphers = defaultCipherSuites() |
| 5412 |
} |
| 5413 |
|
| 5414 |
// If curve preferences were not specified, then use the defaults |
| 5415 |
if tc.CurvePreferences == nil { |
| 5416 |
tc.CurvePreferences = defaultCurvePreferences() |
| 5417 |
} |
| 5418 |
|
| 5419 |
// If we don't allow insecure ciphers, and yet some were configured, then we |
| 5420 |
// should error. |
| 5421 |
if !tc.AllowInsecureCiphers && len(ics) > 0 { |
| 5422 |
names := make([]string, 0, len(ics)) |
| 5423 |
for _, ic := range ics { |
| 5424 |
names = append(names, ic.Name) |
| 5425 |
} |
| 5426 |
return nil, &configErr{tk, fmt.Sprintf("insecure cipher suites configured without 'allow_insecure_cipher_suites' option set: %s", strings.Join(names, ", "))} |
| 5427 |
} |
| 5428 |
|
| 5429 |
return &tc, nil |
| 5430 |
} |
| 5431 |
|
| 5432 |
func parseSimpleAuth(v any, errors *[]error) *authorization { |
| 5433 |
var ( |
| 5434 |
am map[string]any |
| 5435 |
tk token |
| 5436 |
lt token |
| 5437 |
auth = &authorization{} |
| 5438 |
) |
| 5439 |
defer convertPanicToErrorList(<, errors) |
| 5440 |
|
| 5441 |
_, v = unwrapValue(v, <) |
| 5442 |
am = v.(map[string]any) |
| 5443 |
for mk, mv := range am { |
| 5444 |
tk, mv = unwrapValue(mv, <) |
| 5445 |
switch strings.ToLower(mk) { |
| 5446 |
case "user", "username": |
| 5447 |
auth.user = mv.(string) |
| 5448 |
case "pass", "password": |
| 5449 |
auth.pass = mv.(string) |
| 5450 |
case "token": |
| 5451 |
auth.token = mv.(string) |
| 5452 |
case "timeout": |
| 5453 |
at := float64(1) |
| 5454 |
switch mv := mv.(type) { |
| 5455 |
case int64: |
| 5456 |
at = float64(mv) |
| 5457 |
case float64: |
| 5458 |
at = mv |
| 5459 |
} |
| 5460 |
auth.timeout = at |
| 5461 |
default: |
| 5462 |
if !tk.IsUsedVariable() { |
| 5463 |
err := &unknownConfigFieldErr{ |
| 5464 |
field: mk, |
| 5465 |
configErr: configErr{ |
| 5466 |
token: tk, |
| 5467 |
}, |
| 5468 |
} |
| 5469 |
*errors = append(*errors, err) |
| 5470 |
} |
| 5471 |
continue |
| 5472 |
} |
| 5473 |
} |
| 5474 |
return auth |
| 5475 |
} |
| 5476 |
|
| 5477 |
func parseStringArray(fieldName string, tk token, lt *token, mv any, errors *[]error) ([]string, error) { |
| 5478 |
switch mv := mv.(type) { |
| 5479 |
case string: |
| 5480 |
return []string{mv}, nil |
| 5481 |
case []any: |
| 5482 |
strs := make([]string, 0, len(mv)) |
| 5483 |
for _, val := range mv { |
| 5484 |
tk, val = unwrapValue(val, lt) |
| 5485 |
if str, ok := val.(string); ok { |
| 5486 |
strs = append(strs, str) |
| 5487 |
} else { |
| 5488 |
err := &configErr{tk, fmt.Sprintf("error parsing %s: unsupported type in array %T", fieldName, val)} |
| 5489 |
*errors = append(*errors, err) |
| 5490 |
continue |
| 5491 |
} |
| 5492 |
} |
| 5493 |
return strs, nil |
| 5494 |
default: |
| 5495 |
err := &configErr{tk, fmt.Sprintf("error parsing %s: unsupported type %T", fieldName, mv)} |
| 5496 |
*errors = append(*errors, err) |
| 5497 |
return nil, err |
| 5498 |
} |
| 5499 |
} |
| 5500 |
|
| 5501 |
func parseWebsocket(v any, o *Options, errors *[]error, warnings *[]error) error { |
| 5502 |
var lt token |
| 5503 |
defer convertPanicToErrorList(<, errors) |
| 5504 |
|
| 5505 |
tk, v := unwrapValue(v, <) |
| 5506 |
gm, ok := v.(map[string]any) |
| 5507 |
if !ok { |
| 5508 |
return &configErr{tk, fmt.Sprintf("Expected websocket to be a map, got %T", v)} |
| 5509 |
} |
| 5510 |
for mk, mv := range gm { |
| 5511 |
// Again, unwrap token value if line check is required. |
| 5512 |
tk, mv = unwrapValue(mv, <) |
| 5513 |
switch strings.ToLower(mk) { |
| 5514 |
case "listen": |
| 5515 |
hp, err := parseListen(mv) |
| 5516 |
if err != nil { |
| 5517 |
err := &configErr{tk, err.Error()} |
| 5518 |
*errors = append(*errors, err) |
| 5519 |
continue |
| 5520 |
} |
| 5521 |
o.Websocket.Host = hp.host |
| 5522 |
o.Websocket.Port = hp.port |
| 5523 |
case "port": |
| 5524 |
o.Websocket.Port = int(mv.(int64)) |
| 5525 |
case "host", "net": |
| 5526 |
o.Websocket.Host = mv.(string) |
| 5527 |
case "advertise": |
| 5528 |
o.Websocket.Advertise = mv.(string) |
| 5529 |
case "no_tls": |
| 5530 |
o.Websocket.NoTLS = mv.(bool) |
| 5531 |
case "tls": |
| 5532 |
tc, err := parseTLS(tk, true) |
| 5533 |
if err != nil { |
| 5534 |
*errors = append(*errors, err) |
| 5535 |
continue |
| 5536 |
} |
| 5537 |
if o.Websocket.TLSConfig, err = GenTLSConfig(tc); err != nil { |
| 5538 |
err := &configErr{tk, err.Error()} |
| 5539 |
*errors = append(*errors, err) |
| 5540 |
continue |
| 5541 |
} |
| 5542 |
o.Websocket.TLSMap = tc.Map |
| 5543 |
o.Websocket.TLSPinnedCerts = tc.PinnedCerts |
| 5544 |
o.Websocket.tlsConfigOpts = tc |
| 5545 |
case "same_origin": |
| 5546 |
o.Websocket.SameOrigin = mv.(bool) |
| 5547 |
case "allowed_origins", "allowed_origin", "allow_origins", "allow_origin", "origins", "origin": |
| 5548 |
o.Websocket.AllowedOrigins, _ = parseStringArray("allowed origins", tk, <, mv, errors) |
| 5549 |
case "handshake_timeout": |
| 5550 |
ht := time.Duration(0) |
| 5551 |
switch mv := mv.(type) { |
| 5552 |
case int64: |
| 5553 |
ht = time.Duration(mv) * time.Second |
| 5554 |
case string: |
| 5555 |
var err error |
| 5556 |
ht, err = time.ParseDuration(mv) |
| 5557 |
if err != nil { |
| 5558 |
err := &configErr{tk, err.Error()} |
| 5559 |
*errors = append(*errors, err) |
| 5560 |
continue |
| 5561 |
} |
| 5562 |
default: |
| 5563 |
err := &configErr{tk, fmt.Sprintf("error parsing handshake timeout: unsupported type %T", mv)} |
| 5564 |
*errors = append(*errors, err) |
| 5565 |
} |
| 5566 |
o.Websocket.HandshakeTimeout = ht |
| 5567 |
case "compress", "compression": |
| 5568 |
o.Websocket.Compression = mv.(bool) |
| 5569 |
case "authorization", "authentication": |
| 5570 |
auth := parseSimpleAuth(tk, errors) |
| 5571 |
o.Websocket.Username = auth.user |
| 5572 |
o.Websocket.Password = auth.pass |
| 5573 |
o.Websocket.Token = auth.token |
| 5574 |
o.Websocket.AuthTimeout = auth.timeout |
| 5575 |
case "jwt_cookie": |
| 5576 |
o.Websocket.JWTCookie = mv.(string) |
| 5577 |
case "user_cookie": |
| 5578 |
o.Websocket.UsernameCookie = mv.(string) |
| 5579 |
case "pass_cookie": |
| 5580 |
o.Websocket.PasswordCookie = mv.(string) |
| 5581 |
case "token_cookie": |
| 5582 |
o.Websocket.TokenCookie = mv.(string) |
| 5583 |
case "no_auth_user": |
| 5584 |
o.Websocket.NoAuthUser = mv.(string) |
| 5585 |
case "headers": |
| 5586 |
m, ok := mv.(map[string]any) |
| 5587 |
if !ok { |
| 5588 |
err := &configErr{tk, fmt.Sprintf("error parsing headers: unsupported type %T", mv)} |
| 5589 |
*errors = append(*errors, err) |
| 5590 |
continue |
| 5591 |
} |
| 5592 |
o.Websocket.Headers = make(map[string]string) |
| 5593 |
for key, val := range m { |
| 5594 |
tk, val = unwrapValue(val, <) |
| 5595 |
if headerValue, ok := val.(string); !ok { |
| 5596 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("error parsing header key %s: unsupported type %T", key, val)}) |
| 5597 |
continue |
| 5598 |
} else { |
| 5599 |
o.Websocket.Headers[key] = headerValue |
| 5600 |
} |
| 5601 |
} |
| 5602 |
case "ping_interval": |
| 5603 |
o.Websocket.PingInterval = parseDuration("ping_interval", tk, mv, errors, warnings) |
| 5604 |
default: |
| 5605 |
if !tk.IsUsedVariable() { |
| 5606 |
err := &unknownConfigFieldErr{ |
| 5607 |
field: mk, |
| 5608 |
configErr: configErr{ |
| 5609 |
token: tk, |
| 5610 |
}, |
| 5611 |
} |
| 5612 |
*errors = append(*errors, err) |
| 5613 |
continue |
| 5614 |
} |
| 5615 |
} |
| 5616 |
} |
| 5617 |
return nil |
| 5618 |
} |
| 5619 |
|
| 5620 |
func parseMQTT(v any, o *Options, errors *[]error, warnings *[]error) error { |
| 5621 |
var lt token |
| 5622 |
defer convertPanicToErrorList(<, errors) |
| 5623 |
|
| 5624 |
tk, v := unwrapValue(v, <) |
| 5625 |
gm, ok := v.(map[string]any) |
| 5626 |
if !ok { |
| 5627 |
return &configErr{tk, fmt.Sprintf("Expected mqtt to be a map, got %T", v)} |
| 5628 |
} |
| 5629 |
for mk, mv := range gm { |
| 5630 |
// Again, unwrap token value if line check is required. |
| 5631 |
tk, mv = unwrapValue(mv, <) |
| 5632 |
switch strings.ToLower(mk) { |
| 5633 |
case "listen": |
| 5634 |
hp, err := parseListen(mv) |
| 5635 |
if err != nil { |
| 5636 |
err := &configErr{tk, err.Error()} |
| 5637 |
*errors = append(*errors, err) |
| 5638 |
continue |
| 5639 |
} |
| 5640 |
o.MQTT.Host = hp.host |
| 5641 |
o.MQTT.Port = hp.port |
| 5642 |
case "port": |
| 5643 |
o.MQTT.Port = int(mv.(int64)) |
| 5644 |
case "host", "net": |
| 5645 |
o.MQTT.Host = mv.(string) |
| 5646 |
case "tls": |
| 5647 |
tc, err := parseTLS(tk, true) |
| 5648 |
if err != nil { |
| 5649 |
*errors = append(*errors, err) |
| 5650 |
continue |
| 5651 |
} |
| 5652 |
if o.MQTT.TLSConfig, err = GenTLSConfig(tc); err != nil { |
| 5653 |
err := &configErr{tk, err.Error()} |
| 5654 |
*errors = append(*errors, err) |
| 5655 |
continue |
| 5656 |
} |
| 5657 |
o.MQTT.TLSTimeout = tc.Timeout |
| 5658 |
o.MQTT.TLSMap = tc.Map |
| 5659 |
o.MQTT.TLSPinnedCerts = tc.PinnedCerts |
| 5660 |
o.MQTT.tlsConfigOpts = tc |
| 5661 |
case "authorization", "authentication": |
| 5662 |
auth := parseSimpleAuth(tk, errors) |
| 5663 |
o.MQTT.Username = auth.user |
| 5664 |
o.MQTT.Password = auth.pass |
| 5665 |
o.MQTT.Token = auth.token |
| 5666 |
o.MQTT.AuthTimeout = auth.timeout |
| 5667 |
case "no_auth_user": |
| 5668 |
o.MQTT.NoAuthUser = mv.(string) |
| 5669 |
case "ack_wait", "ackwait": |
| 5670 |
o.MQTT.AckWait = parseDuration("ack_wait", tk, mv, errors, warnings) |
| 5671 |
case "js_api_timeout", "api_timeout": |
| 5672 |
o.MQTT.JSAPITimeout = parseDuration("js_api_timeout", tk, mv, errors, warnings) |
| 5673 |
case "max_ack_pending", "max_pending", "max_inflight": |
| 5674 |
tmp := int(mv.(int64)) |
| 5675 |
if tmp < 0 || tmp > 0xFFFF { |
| 5676 |
err := &configErr{tk, fmt.Sprintf("invalid value %v, should in [0..%d] range", tmp, 0xFFFF)} |
| 5677 |
*errors = append(*errors, err) |
| 5678 |
} else { |
| 5679 |
o.MQTT.MaxAckPending = uint16(tmp) |
| 5680 |
} |
| 5681 |
case "js_domain": |
| 5682 |
o.MQTT.JsDomain = mv.(string) |
| 5683 |
case "stream_replicas": |
| 5684 |
o.MQTT.StreamReplicas = int(mv.(int64)) |
| 5685 |
case "consumer_replicas": |
| 5686 |
err := &configWarningErr{ |
| 5687 |
field: mk, |
| 5688 |
configErr: configErr{ |
| 5689 |
token: tk, |
| 5690 |
reason: `consumer replicas setting ignored in this server version`, |
| 5691 |
}, |
| 5692 |
} |
| 5693 |
*warnings = append(*warnings, err) |
| 5694 |
case "consumer_memory_storage": |
| 5695 |
o.MQTT.ConsumerMemoryStorage = mv.(bool) |
| 5696 |
case "consumer_inactive_threshold", "consumer_auto_cleanup": |
| 5697 |
o.MQTT.ConsumerInactiveThreshold = parseDuration("consumer_inactive_threshold", tk, mv, errors, warnings) |
| 5698 |
|
| 5699 |
case "reject_qos2_publish": |
| 5700 |
o.MQTT.rejectQoS2Pub = mv.(bool) |
| 5701 |
case "downgrade_qos2_subscribe": |
| 5702 |
o.MQTT.downgradeQoS2Sub = mv.(bool) |
| 5703 |
|
| 5704 |
default: |
| 5705 |
if !tk.IsUsedVariable() { |
| 5706 |
err := &unknownConfigFieldErr{ |
| 5707 |
field: mk, |
| 5708 |
configErr: configErr{ |
| 5709 |
token: tk, |
| 5710 |
}, |
| 5711 |
} |
| 5712 |
*errors = append(*errors, err) |
| 5713 |
continue |
| 5714 |
} |
| 5715 |
} |
| 5716 |
} |
| 5717 |
return nil |
| 5718 |
} |
| 5719 |
|
| 5720 |
func parseProxies(mv any, errors *[]error) (*ProxiesConfig, error) { |
| 5721 |
var ( |
| 5722 |
tk token |
| 5723 |
lt token |
| 5724 |
proxies = &ProxiesConfig{} |
| 5725 |
) |
| 5726 |
defer convertPanicToErrorList(<, errors) |
| 5727 |
|
| 5728 |
tk, mv = unwrapValue(mv, <) |
| 5729 |
pm, ok := mv.(map[string]any) |
| 5730 |
if !ok { |
| 5731 |
return nil, &configErr{tk, fmt.Sprintf("expected proxies to be a map/struct, got %T", mv)} |
| 5732 |
} |
| 5733 |
for mk, mv := range pm { |
| 5734 |
tk, _ = unwrapValue(mv, <) |
| 5735 |
|
| 5736 |
switch strings.ToLower(mk) { |
| 5737 |
case "trusted": |
| 5738 |
trusted, err := parseProxiesTrusted(tk, errors) |
| 5739 |
if err != nil { |
| 5740 |
*errors = append(*errors, err) |
| 5741 |
continue |
| 5742 |
} |
| 5743 |
proxies.Trusted = trusted |
| 5744 |
default: |
| 5745 |
if !tk.IsUsedVariable() { |
| 5746 |
err := &unknownConfigFieldErr{ |
| 5747 |
field: mk, |
| 5748 |
configErr: configErr{ |
| 5749 |
token: tk, |
| 5750 |
}, |
| 5751 |
} |
| 5752 |
*errors = append(*errors, err) |
| 5753 |
} |
| 5754 |
} |
| 5755 |
} |
| 5756 |
return proxies, nil |
| 5757 |
} |
| 5758 |
|
| 5759 |
func parseProxiesTrusted(mv any, errors *[]error) ([]*ProxyConfig, error) { |
| 5760 |
var ( |
| 5761 |
tk token |
| 5762 |
lt token |
| 5763 |
trusted []*ProxyConfig |
| 5764 |
) |
| 5765 |
defer convertPanicToErrorList(<, errors) |
| 5766 |
|
| 5767 |
tk, mv = unwrapValue(mv, <) |
| 5768 |
ta, ok := mv.([]any) |
| 5769 |
if !ok { |
| 5770 |
return nil, &configErr{tk, fmt.Sprintf("expected proxies' trusted field to be an array, got %T", mv)} |
| 5771 |
} |
| 5772 |
for _, t := range ta { |
| 5773 |
tk, t = unwrapValue(t, <) |
| 5774 |
// Check its a map/struct |
| 5775 |
tm, ok := t.(map[string]any) |
| 5776 |
if !ok { |
| 5777 |
err := &configErr{tk, fmt.Sprintf("expected proxies' trusted entry to be a map/struct, got %T", t)} |
| 5778 |
*errors = append(*errors, err) |
| 5779 |
continue |
| 5780 |
} |
| 5781 |
proxy := &ProxyConfig{} |
| 5782 |
for k, v := range tm { |
| 5783 |
tk, v = unwrapValue(v, <) |
| 5784 |
switch strings.ToLower(k) { |
| 5785 |
case "key", "public_key": |
| 5786 |
proxy.Key = v.(string) |
| 5787 |
if !nkeys.IsValidPublicKey(proxy.Key) { |
| 5788 |
*errors = append(*errors, &configErr{tk, fmt.Sprintf("invalid proxy key %q", proxy.Key)}) |
| 5789 |
continue |
| 5790 |
} |
| 5791 |
default: |
| 5792 |
if !tk.IsUsedVariable() { |
| 5793 |
err := &unknownConfigFieldErr{ |
| 5794 |
field: k, |
| 5795 |
configErr: configErr{ |
| 5796 |
token: tk, |
| 5797 |
}, |
| 5798 |
} |
| 5799 |
*errors = append(*errors, err) |
| 5800 |
continue |
| 5801 |
} |
| 5802 |
} |
| 5803 |
} |
| 5804 |
trusted = append(trusted, proxy) |
| 5805 |
} |
| 5806 |
return trusted, nil |
| 5807 |
} |
| 5808 |
|
| 5809 |
// GenTLSConfig loads TLS related configuration parameters. |
| 5810 |
func GenTLSConfig(tc *TLSConfigOpts) (*tls.Config, error) { |
| 5811 |
// Create the tls.Config from our options before including the certs. |
| 5812 |
// It will determine the cipher suites that we prefer. |
| 5813 |
// FIXME(dlc) change if ARM based. |
| 5814 |
config := tls.Config{ |
| 5815 |
MinVersion: tls.VersionTLS12, |
| 5816 |
CipherSuites: tc.Ciphers, |
| 5817 |
CurvePreferences: tc.CurvePreferences, |
| 5818 |
InsecureSkipVerify: tc.Insecure, |
| 5819 |
} |
| 5820 |
|
| 5821 |
switch { |
| 5822 |
case tc.CertFile != _EMPTY_ && tc.CertStore != certstore.STOREEMPTY: |
| 5823 |
return nil, certstore.ErrConflictCertFileAndStore |
| 5824 |
case tc.CertFile != _EMPTY_ && tc.KeyFile == _EMPTY_: |
| 5825 |
return nil, fmt.Errorf("missing 'key_file' in TLS configuration") |
| 5826 |
case tc.CertFile == _EMPTY_ && tc.KeyFile != _EMPTY_: |
| 5827 |
return nil, fmt.Errorf("missing 'cert_file' in TLS configuration") |
| 5828 |
case tc.CertFile != _EMPTY_ && tc.KeyFile != _EMPTY_: |
| 5829 |
// Now load in cert and private key |
| 5830 |
cert, err := tls.LoadX509KeyPair(tc.CertFile, tc.KeyFile) |
| 5831 |
if err != nil { |
| 5832 |
return nil, fmt.Errorf("error parsing X509 certificate/key pair: %v", err) |
| 5833 |
} |
| 5834 |
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) |
| 5835 |
if err != nil { |
| 5836 |
return nil, fmt.Errorf("error parsing certificate: %v", err) |
| 5837 |
} |
| 5838 |
config.Certificates = []tls.Certificate{cert} |
| 5839 |
case tc.CertStore != certstore.STOREEMPTY: |
| 5840 |
err := certstore.TLSConfig(tc.CertStore, tc.CertMatchBy, tc.CertMatch, tc.CaCertsMatch, tc.CertMatchSkipInvalid, &config) |
| 5841 |
if err != nil { |
| 5842 |
return nil, err |
| 5843 |
} |
| 5844 |
case tc.Certificates != nil: |
| 5845 |
// Multiple certificate support. |
| 5846 |
config.Certificates = make([]tls.Certificate, len(tc.Certificates)) |
| 5847 |
for i, certPair := range tc.Certificates { |
| 5848 |
cert, err := tls.LoadX509KeyPair(certPair.CertFile, certPair.KeyFile) |
| 5849 |
if err != nil { |
| 5850 |
return nil, fmt.Errorf("error parsing X509 certificate/key pair %d/%d: %v", i+1, len(tc.Certificates), err) |
| 5851 |
} |
| 5852 |
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) |
| 5853 |
if err != nil { |
| 5854 |
return nil, fmt.Errorf("error parsing certificate %d/%d: %v", i+1, len(tc.Certificates), err) |
| 5855 |
} |
| 5856 |
config.Certificates[i] = cert |
| 5857 |
} |
| 5858 |
} |
| 5859 |
|
| 5860 |
// Require client certificates as needed |
| 5861 |
if tc.Verify { |
| 5862 |
config.ClientAuth = tls.RequireAndVerifyClientCert |
| 5863 |
} |
| 5864 |
// Add in CAs if applicable. |
| 5865 |
if tc.CaFile != _EMPTY_ { |
| 5866 |
rootPEM, err := os.ReadFile(tc.CaFile) |
| 5867 |
if err != nil || rootPEM == nil { |
| 5868 |
return nil, err |
| 5869 |
} |
| 5870 |
pool := x509.NewCertPool() |
| 5871 |
ok := pool.AppendCertsFromPEM(rootPEM) |
| 5872 |
if !ok { |
| 5873 |
return nil, fmt.Errorf("failed to parse root ca certificate") |
| 5874 |
} |
| 5875 |
config.ClientCAs = pool |
| 5876 |
} |
| 5877 |
// Allow setting TLS minimum version. |
| 5878 |
if tc.MinVersion > 0 { |
| 5879 |
if tc.MinVersion < tls.VersionTLS12 { |
| 5880 |
return nil, fmt.Errorf("unsupported minimum TLS version: %s", tls.VersionName(tc.MinVersion)) |
| 5881 |
} |
| 5882 |
config.MinVersion = tc.MinVersion |
| 5883 |
} |
| 5884 |
|
| 5885 |
return &config, nil |
| 5886 |
} |
| 5887 |
|
| 5888 |
// MergeOptions will merge two options giving preference to the flagOpts |
| 5889 |
// if the item is present. |
| 5890 |
func MergeOptions(fileOpts, flagOpts *Options) *Options { |
| 5891 |
if fileOpts == nil { |
| 5892 |
return flagOpts |
| 5893 |
} |
| 5894 |
if flagOpts == nil { |
| 5895 |
return fileOpts |
| 5896 |
} |
| 5897 |
// Merge the two, flagOpts override |
| 5898 |
opts := *fileOpts |
| 5899 |
|
| 5900 |
if flagOpts.Port != 0 { |
| 5901 |
opts.Port = flagOpts.Port |
| 5902 |
} |
| 5903 |
if flagOpts.Host != _EMPTY_ { |
| 5904 |
opts.Host = flagOpts.Host |
| 5905 |
} |
| 5906 |
if flagOpts.DontListen { |
| 5907 |
opts.DontListen = flagOpts.DontListen |
| 5908 |
} |
| 5909 |
if flagOpts.ClientAdvertise != _EMPTY_ { |
| 5910 |
opts.ClientAdvertise = flagOpts.ClientAdvertise |
| 5911 |
} |
| 5912 |
if flagOpts.Username != _EMPTY_ { |
| 5913 |
opts.Username = flagOpts.Username |
| 5914 |
} |
| 5915 |
if flagOpts.Password != _EMPTY_ { |
| 5916 |
opts.Password = flagOpts.Password |
| 5917 |
} |
| 5918 |
if flagOpts.Authorization != _EMPTY_ { |
| 5919 |
opts.Authorization = flagOpts.Authorization |
| 5920 |
} |
| 5921 |
if flagOpts.HTTPPort != 0 { |
| 5922 |
opts.HTTPPort = flagOpts.HTTPPort |
| 5923 |
} |
| 5924 |
if flagOpts.HTTPBasePath != _EMPTY_ { |
| 5925 |
opts.HTTPBasePath = flagOpts.HTTPBasePath |
| 5926 |
} |
| 5927 |
if flagOpts.Debug { |
| 5928 |
opts.Debug = true |
| 5929 |
} |
| 5930 |
if flagOpts.Trace { |
| 5931 |
opts.Trace = true |
| 5932 |
} |
| 5933 |
if flagOpts.Logtime { |
| 5934 |
opts.Logtime = true |
| 5935 |
} |
| 5936 |
if flagOpts.LogFile != _EMPTY_ { |
| 5937 |
opts.LogFile = flagOpts.LogFile |
| 5938 |
} |
| 5939 |
if flagOpts.PidFile != _EMPTY_ { |
| 5940 |
opts.PidFile = flagOpts.PidFile |
| 5941 |
} |
| 5942 |
if flagOpts.PortsFileDir != _EMPTY_ { |
| 5943 |
opts.PortsFileDir = flagOpts.PortsFileDir |
| 5944 |
} |
| 5945 |
if flagOpts.ProfPort != 0 { |
| 5946 |
opts.ProfPort = flagOpts.ProfPort |
| 5947 |
} |
| 5948 |
if flagOpts.Cluster.ListenStr != _EMPTY_ { |
| 5949 |
opts.Cluster.ListenStr = flagOpts.Cluster.ListenStr |
| 5950 |
} |
| 5951 |
if flagOpts.Cluster.NoAdvertise { |
| 5952 |
opts.Cluster.NoAdvertise = true |
| 5953 |
} |
| 5954 |
if flagOpts.Cluster.ConnectRetries != 0 { |
| 5955 |
opts.Cluster.ConnectRetries = flagOpts.Cluster.ConnectRetries |
| 5956 |
} |
| 5957 |
if flagOpts.Cluster.Advertise != _EMPTY_ { |
| 5958 |
opts.Cluster.Advertise = flagOpts.Cluster.Advertise |
| 5959 |
} |
| 5960 |
if flagOpts.RoutesStr != _EMPTY_ { |
| 5961 |
mergeRoutes(&opts, flagOpts) |
| 5962 |
} |
| 5963 |
if flagOpts.JetStream { |
| 5964 |
opts.JetStream = flagOpts.JetStream |
| 5965 |
} |
| 5966 |
if flagOpts.StoreDir != _EMPTY_ { |
| 5967 |
opts.StoreDir = flagOpts.StoreDir |
| 5968 |
} |
| 5969 |
return &opts |
| 5970 |
} |
| 5971 |
|
| 5972 |
// RoutesFromStr parses route URLs from a string |
| 5973 |
func RoutesFromStr(routesStr string) []*url.URL { |
| 5974 |
routes := strings.Split(routesStr, ",") |
| 5975 |
if len(routes) == 0 { |
| 5976 |
return nil |
| 5977 |
} |
| 5978 |
routeUrls := []*url.URL{} |
| 5979 |
for _, r := range routes { |
| 5980 |
r = strings.TrimSpace(r) |
| 5981 |
u, _ := url.Parse(r) |
| 5982 |
routeUrls = append(routeUrls, u) |
| 5983 |
} |
| 5984 |
return routeUrls |
| 5985 |
} |
| 5986 |
|
| 5987 |
// This will merge the flag routes and override anything that was present. |
| 5988 |
func mergeRoutes(opts, flagOpts *Options) { |
| 5989 |
routeUrls := RoutesFromStr(flagOpts.RoutesStr) |
| 5990 |
if routeUrls == nil { |
| 5991 |
return |
| 5992 |
} |
| 5993 |
opts.Routes = routeUrls |
| 5994 |
opts.RoutesStr = flagOpts.RoutesStr |
| 5995 |
} |
| 5996 |
|
| 5997 |
func setBaselineOptions(opts *Options) { |
| 5998 |
// Setup non-standard Go defaults |
| 5999 |
if opts.Host == _EMPTY_ { |
| 6000 |
opts.Host = DEFAULT_HOST |
| 6001 |
} |
| 6002 |
if opts.HTTPHost == _EMPTY_ { |
| 6003 |
// Default to same bind from server if left undefined |
| 6004 |
opts.HTTPHost = opts.Host |
| 6005 |
} |
| 6006 |
if opts.Port == 0 { |
| 6007 |
opts.Port = DEFAULT_PORT |
| 6008 |
} else if opts.Port == RANDOM_PORT { |
| 6009 |
// Choose randomly inside of net.Listen |
| 6010 |
opts.Port = 0 |
| 6011 |
} |
| 6012 |
if opts.MaxConn == 0 { |
| 6013 |
opts.MaxConn = DEFAULT_MAX_CONNECTIONS |
| 6014 |
} |
| 6015 |
if opts.PingInterval == 0 { |
| 6016 |
opts.PingInterval = DEFAULT_PING_INTERVAL |
| 6017 |
} |
| 6018 |
if opts.MaxPingsOut == 0 { |
| 6019 |
opts.MaxPingsOut = DEFAULT_PING_MAX_OUT |
| 6020 |
} |
| 6021 |
if opts.TLSTimeout == 0 { |
| 6022 |
opts.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second) |
| 6023 |
} |
| 6024 |
if opts.AuthTimeout == 0 { |
| 6025 |
opts.AuthTimeout = getDefaultAuthTimeout(opts.TLSConfig, opts.TLSTimeout) |
| 6026 |
} |
| 6027 |
if opts.Cluster.Port != 0 || opts.Cluster.ListenStr != _EMPTY_ { |
| 6028 |
if opts.Cluster.Host == _EMPTY_ { |
| 6029 |
opts.Cluster.Host = DEFAULT_HOST |
| 6030 |
} |
| 6031 |
if opts.Cluster.TLSTimeout == 0 { |
| 6032 |
opts.Cluster.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second) |
| 6033 |
} |
| 6034 |
if opts.Cluster.AuthTimeout == 0 { |
| 6035 |
opts.Cluster.AuthTimeout = getDefaultAuthTimeout(opts.Cluster.TLSConfig, opts.Cluster.TLSTimeout) |
| 6036 |
} |
| 6037 |
if opts.Cluster.PoolSize == 0 { |
| 6038 |
opts.Cluster.PoolSize = DEFAULT_ROUTE_POOL_SIZE |
| 6039 |
} |
| 6040 |
// Unless pooling/accounts are disabled (by PoolSize being set to -1), |
| 6041 |
// check for Cluster.Accounts. Add the system account if not present and |
| 6042 |
// unless we have a configuration that disabled it. |
| 6043 |
if opts.Cluster.PoolSize > 0 { |
| 6044 |
sysAccName := opts.SystemAccount |
| 6045 |
if sysAccName == _EMPTY_ && !opts.NoSystemAccount { |
| 6046 |
sysAccName = DEFAULT_SYSTEM_ACCOUNT |
| 6047 |
} |
| 6048 |
if sysAccName != _EMPTY_ { |
| 6049 |
var found bool |
| 6050 |
for _, acc := range opts.Cluster.PinnedAccounts { |
| 6051 |
if acc == sysAccName { |
| 6052 |
found = true |
| 6053 |
break |
| 6054 |
} |
| 6055 |
} |
| 6056 |
if !found { |
| 6057 |
opts.Cluster.PinnedAccounts = append(opts.Cluster.PinnedAccounts, sysAccName) |
| 6058 |
} |
| 6059 |
} |
| 6060 |
} |
| 6061 |
// Default to compression "accept", which means that compression is not |
| 6062 |
// initiated, but if the remote selects compression, this server will |
| 6063 |
// use the same. |
| 6064 |
if c := &opts.Cluster.Compression; c.Mode == _EMPTY_ { |
| 6065 |
if testDefaultClusterCompression != _EMPTY_ { |
| 6066 |
c.Mode = testDefaultClusterCompression |
| 6067 |
} else { |
| 6068 |
c.Mode = CompressionAccept |
| 6069 |
} |
| 6070 |
} |
| 6071 |
} |
| 6072 |
if opts.LeafNode.Port != 0 { |
| 6073 |
if opts.LeafNode.Host == _EMPTY_ { |
| 6074 |
opts.LeafNode.Host = DEFAULT_HOST |
| 6075 |
} |
| 6076 |
if opts.LeafNode.TLSTimeout == 0 { |
| 6077 |
opts.LeafNode.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second) |
| 6078 |
} |
| 6079 |
if opts.LeafNode.AuthTimeout == 0 { |
| 6080 |
opts.LeafNode.AuthTimeout = getDefaultAuthTimeout(opts.LeafNode.TLSConfig, opts.LeafNode.TLSTimeout) |
| 6081 |
} |
| 6082 |
// Default to compression "s2_auto". |
| 6083 |
if c := &opts.LeafNode.Compression; c.Mode == _EMPTY_ { |
| 6084 |
if testDefaultLeafNodeCompression != _EMPTY_ { |
| 6085 |
c.Mode = testDefaultLeafNodeCompression |
| 6086 |
} else { |
| 6087 |
c.Mode = CompressionS2Auto |
| 6088 |
} |
| 6089 |
} |
| 6090 |
} |
| 6091 |
// Set baseline connect port for remotes. |
| 6092 |
for _, r := range opts.LeafNode.Remotes { |
| 6093 |
if r != nil { |
| 6094 |
for _, u := range r.URLs { |
| 6095 |
if u.Port() == _EMPTY_ { |
| 6096 |
u.Host = net.JoinHostPort(u.Host, strconv.Itoa(DEFAULT_LEAFNODE_PORT)) |
| 6097 |
} |
| 6098 |
} |
| 6099 |
// Default to compression "s2_auto". |
| 6100 |
if c := &r.Compression; c.Mode == _EMPTY_ { |
| 6101 |
if testDefaultLeafNodeCompression != _EMPTY_ { |
| 6102 |
c.Mode = testDefaultLeafNodeCompression |
| 6103 |
} else { |
| 6104 |
c.Mode = CompressionS2Auto |
| 6105 |
} |
| 6106 |
} |
| 6107 |
// Set default first info timeout value if not set. |
| 6108 |
if r.FirstInfoTimeout <= 0 { |
| 6109 |
r.FirstInfoTimeout = DEFAULT_LEAFNODE_INFO_WAIT |
| 6110 |
} |
| 6111 |
} |
| 6112 |
} |
| 6113 |
|
| 6114 |
// Set this regardless of opts.LeafNode.Port |
| 6115 |
if opts.LeafNode.ReconnectInterval == 0 { |
| 6116 |
opts.LeafNode.ReconnectInterval = DEFAULT_LEAF_NODE_RECONNECT |
| 6117 |
} |
| 6118 |
|
| 6119 |
if opts.MaxControlLine == 0 { |
| 6120 |
opts.MaxControlLine = MAX_CONTROL_LINE_SIZE |
| 6121 |
} |
| 6122 |
if opts.MaxPayload == 0 { |
| 6123 |
opts.MaxPayload = MAX_PAYLOAD_SIZE |
| 6124 |
} |
| 6125 |
if opts.MaxPending == 0 { |
| 6126 |
opts.MaxPending = MAX_PENDING_SIZE |
| 6127 |
} |
| 6128 |
if opts.WriteDeadline == time.Duration(0) { |
| 6129 |
opts.WriteDeadline = DEFAULT_FLUSH_DEADLINE |
| 6130 |
} |
| 6131 |
if opts.MaxClosedClients == 0 { |
| 6132 |
opts.MaxClosedClients = DEFAULT_MAX_CLOSED_CLIENTS |
| 6133 |
} |
| 6134 |
if opts.LameDuckDuration == 0 { |
| 6135 |
opts.LameDuckDuration = DEFAULT_LAME_DUCK_DURATION |
| 6136 |
} |
| 6137 |
if opts.LameDuckGracePeriod == 0 { |
| 6138 |
opts.LameDuckGracePeriod = DEFAULT_LAME_DUCK_GRACE_PERIOD |
| 6139 |
} |
| 6140 |
if opts.Gateway.Port != 0 { |
| 6141 |
if opts.Gateway.Host == _EMPTY_ { |
| 6142 |
opts.Gateway.Host = DEFAULT_HOST |
| 6143 |
} |
| 6144 |
if opts.Gateway.TLSTimeout == 0 { |
| 6145 |
opts.Gateway.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second) |
| 6146 |
} |
| 6147 |
if opts.Gateway.AuthTimeout == 0 { |
| 6148 |
opts.Gateway.AuthTimeout = getDefaultAuthTimeout(opts.Gateway.TLSConfig, opts.Gateway.TLSTimeout) |
| 6149 |
} |
| 6150 |
} |
| 6151 |
if opts.ConnectErrorReports == 0 { |
| 6152 |
opts.ConnectErrorReports = DEFAULT_CONNECT_ERROR_REPORTS |
| 6153 |
} |
| 6154 |
if opts.ReconnectErrorReports == 0 { |
| 6155 |
opts.ReconnectErrorReports = DEFAULT_RECONNECT_ERROR_REPORTS |
| 6156 |
} |
| 6157 |
if opts.Websocket.Port != 0 { |
| 6158 |
if opts.Websocket.Host == _EMPTY_ { |
| 6159 |
opts.Websocket.Host = DEFAULT_HOST |
| 6160 |
} |
| 6161 |
} |
| 6162 |
if opts.MQTT.Port != 0 { |
| 6163 |
if opts.MQTT.Host == _EMPTY_ { |
| 6164 |
opts.MQTT.Host = DEFAULT_HOST |
| 6165 |
} |
| 6166 |
if opts.MQTT.TLSTimeout == 0 { |
| 6167 |
opts.MQTT.TLSTimeout = float64(TLS_TIMEOUT) / float64(time.Second) |
| 6168 |
} |
| 6169 |
} |
| 6170 |
// JetStream |
| 6171 |
if opts.JetStreamMaxMemory == 0 && !opts.maxMemSet { |
| 6172 |
opts.JetStreamMaxMemory = -1 |
| 6173 |
} |
| 6174 |
if opts.JetStreamMaxStore == 0 && !opts.maxStoreSet { |
| 6175 |
opts.JetStreamMaxStore = -1 |
| 6176 |
} |
| 6177 |
if opts.SyncInterval == 0 && !opts.syncSet { |
| 6178 |
opts.SyncInterval = defaultSyncInterval |
| 6179 |
} |
| 6180 |
if opts.JetStreamRequestQueueLimit <= 0 { |
| 6181 |
opts.JetStreamRequestQueueLimit = JSDefaultRequestQueueLimit |
| 6182 |
} |
| 6183 |
if opts.JetStreamInfoQueueLimit <= 0 { |
| 6184 |
opts.JetStreamInfoQueueLimit = opts.JetStreamRequestQueueLimit |
| 6185 |
} |
| 6186 |
if opts.JetStreamConcurrentIOs <= 0 { |
| 6187 |
opts.JetStreamConcurrentIOs = defaultConcurrentIOs |
| 6188 |
} |
| 6189 |
} |
| 6190 |
|
| 6191 |
func getDefaultAuthTimeout(tls *tls.Config, tlsTimeout float64) float64 { |
| 6192 |
var authTimeout float64 |
| 6193 |
if tls != nil { |
| 6194 |
authTimeout = tlsTimeout + 1.0 |
| 6195 |
} else { |
| 6196 |
authTimeout = float64(AUTH_TIMEOUT / time.Second) |
| 6197 |
} |
| 6198 |
return authTimeout |
| 6199 |
} |
| 6200 |
|
| 6201 |
// ConfigureOptions accepts a flag set and augments it with NATS Server |
| 6202 |
// specific flags. On success, an options structure is returned configured |
| 6203 |
// based on the selected flags and/or configuration file. |
| 6204 |
// The command line options take precedence to the ones in the configuration file. |
| 6205 |
func ConfigureOptions(fs *flag.FlagSet, args []string, printVersion, printHelp, printTLSHelp func()) (*Options, error) { |
| 6206 |
opts := &Options{} |
| 6207 |
var ( |
| 6208 |
showVersion bool |
| 6209 |
showHelp bool |
| 6210 |
showTLSHelp bool |
| 6211 |
signal string |
| 6212 |
configFile string |
| 6213 |
dbgAndTrace bool |
| 6214 |
trcAndVerboseTrc bool |
| 6215 |
dbgAndTrcAndVerboseTrc bool |
| 6216 |
err error |
| 6217 |
) |
| 6218 |
|
| 6219 |
fs.BoolVar(&showHelp, "h", false, "Show this message.") |
| 6220 |
fs.BoolVar(&showHelp, "help", false, "Show this message.") |
| 6221 |
fs.IntVar(&opts.Port, "port", 0, "Port to listen on.") |
| 6222 |
fs.IntVar(&opts.Port, "p", 0, "Port to listen on.") |
| 6223 |
fs.StringVar(&opts.ServerName, "n", _EMPTY_, "Server name.") |
| 6224 |
fs.StringVar(&opts.ServerName, "name", _EMPTY_, "Server name.") |
| 6225 |
fs.StringVar(&opts.ServerName, "server_name", _EMPTY_, "Server name.") |
| 6226 |
fs.StringVar(&opts.Host, "addr", _EMPTY_, "Network host to listen on.") |
| 6227 |
fs.StringVar(&opts.Host, "a", _EMPTY_, "Network host to listen on.") |
| 6228 |
fs.StringVar(&opts.Host, "net", _EMPTY_, "Network host to listen on.") |
| 6229 |
fs.StringVar(&opts.ClientAdvertise, "client_advertise", _EMPTY_, "Client URL to advertise to other servers.") |
| 6230 |
fs.BoolVar(&opts.Debug, "D", false, "Enable Debug logging.") |
| 6231 |
fs.BoolVar(&opts.Debug, "debug", false, "Enable Debug logging.") |
| 6232 |
fs.BoolVar(&opts.Trace, "V", false, "Enable Trace logging.") |
| 6233 |
fs.BoolVar(&trcAndVerboseTrc, "VV", false, "Enable Verbose Trace logging. (Traces system account as well)") |
| 6234 |
fs.BoolVar(&opts.Trace, "trace", false, "Enable Trace logging.") |
| 6235 |
fs.BoolVar(&dbgAndTrace, "DV", false, "Enable Debug and Trace logging.") |
| 6236 |
fs.BoolVar(&dbgAndTrcAndVerboseTrc, "DVV", false, "Enable Debug and Verbose Trace logging. (Traces system account as well)") |
| 6237 |
fs.BoolVar(&opts.Logtime, "T", true, "Timestamp log entries.") |
| 6238 |
fs.BoolVar(&opts.Logtime, "logtime", true, "Timestamp log entries.") |
| 6239 |
fs.BoolVar(&opts.LogtimeUTC, "logtime_utc", false, "Timestamps in UTC instead of local timezone.") |
| 6240 |
fs.StringVar(&opts.Username, "user", _EMPTY_, "Username required for connection.") |
| 6241 |
fs.StringVar(&opts.Password, "pass", _EMPTY_, "Password required for connection.") |
| 6242 |
fs.StringVar(&opts.Authorization, "auth", _EMPTY_, "Authorization token required for connection.") |
| 6243 |
fs.IntVar(&opts.HTTPPort, "m", 0, "HTTP Port for /varz, /connz endpoints.") |
| 6244 |
fs.IntVar(&opts.HTTPPort, "http_port", 0, "HTTP Port for /varz, /connz endpoints.") |
| 6245 |
fs.IntVar(&opts.HTTPSPort, "ms", 0, "HTTPS Port for /varz, /connz endpoints.") |
| 6246 |
fs.IntVar(&opts.HTTPSPort, "https_port", 0, "HTTPS Port for /varz, /connz endpoints.") |
| 6247 |
fs.StringVar(&configFile, "c", _EMPTY_, "Configuration file.") |
| 6248 |
fs.StringVar(&configFile, "config", _EMPTY_, "Configuration file.") |
| 6249 |
fs.BoolVar(&opts.CheckConfig, "t", false, "Check configuration and exit.") |
| 6250 |
fs.StringVar(&signal, "sl", "", "Send signal to nats-server process (ldm, stop, quit, term, reopen, reload).") |
| 6251 |
fs.StringVar(&signal, "signal", "", "Send signal to nats-server process (ldm, stop, quit, term, reopen, reload).") |
| 6252 |
fs.StringVar(&opts.PidFile, "P", "", "File to store process pid.") |
| 6253 |
fs.StringVar(&opts.PidFile, "pid", "", "File to store process pid.") |
| 6254 |
fs.StringVar(&opts.PortsFileDir, "ports_file_dir", "", "Creates a ports file in the specified directory (<executable_name>_<pid>.ports).") |
| 6255 |
fs.StringVar(&opts.LogFile, "l", "", "File to store logging output.") |
| 6256 |
fs.StringVar(&opts.LogFile, "log", "", "File to store logging output.") |
| 6257 |
fs.Int64Var(&opts.LogSizeLimit, "log_size_limit", 0, "Logfile size limit being auto-rotated") |
| 6258 |
fs.BoolVar(&opts.Syslog, "s", false, "Enable syslog as log method.") |
| 6259 |
fs.BoolVar(&opts.Syslog, "syslog", false, "Enable syslog as log method.") |
| 6260 |
fs.StringVar(&opts.RemoteSyslog, "r", _EMPTY_, "Syslog server addr (udp://127.0.0.1:514).") |
| 6261 |
fs.StringVar(&opts.RemoteSyslog, "remote_syslog", _EMPTY_, "Syslog server addr (udp://127.0.0.1:514).") |
| 6262 |
fs.BoolVar(&showVersion, "version", false, "Print version information.") |
| 6263 |
fs.BoolVar(&showVersion, "v", false, "Print version information.") |
| 6264 |
fs.IntVar(&opts.ProfPort, "profile", 0, "Profiling HTTP port.") |
| 6265 |
fs.StringVar(&opts.RoutesStr, "routes", _EMPTY_, "Routes to actively solicit a connection.") |
| 6266 |
fs.StringVar(&opts.Cluster.ListenStr, "cluster", _EMPTY_, "Cluster url from which members can solicit routes.") |
| 6267 |
fs.StringVar(&opts.Cluster.ListenStr, "cluster_listen", _EMPTY_, "Cluster url from which members can solicit routes.") |
| 6268 |
fs.StringVar(&opts.Cluster.Advertise, "cluster_advertise", _EMPTY_, "Cluster URL to advertise to other servers.") |
| 6269 |
fs.BoolVar(&opts.Cluster.NoAdvertise, "no_advertise", false, "Advertise known cluster IPs to clients.") |
| 6270 |
fs.IntVar(&opts.Cluster.ConnectRetries, "connect_retries", 0, "For implicit routes, number of connect retries.") |
| 6271 |
fs.StringVar(&opts.Cluster.Name, "cluster_name", _EMPTY_, "Cluster Name, if not set one will be dynamically generated.") |
| 6272 |
fs.BoolVar(&showTLSHelp, "help_tls", false, "TLS help.") |
| 6273 |
fs.BoolVar(&opts.TLS, "tls", false, "Enable TLS.") |
| 6274 |
fs.BoolVar(&opts.TLSVerify, "tlsverify", false, "Enable TLS with client verification.") |
| 6275 |
fs.StringVar(&opts.TLSCert, "tlscert", _EMPTY_, "Server certificate file.") |
| 6276 |
fs.StringVar(&opts.TLSKey, "tlskey", _EMPTY_, "Private key for server certificate.") |
| 6277 |
fs.StringVar(&opts.TLSCaCert, "tlscacert", _EMPTY_, "Client certificate CA for verification.") |
| 6278 |
fs.IntVar(&opts.MaxTracedMsgLen, "max_traced_msg_len", 0, "Maximum printable length for traced messages. 0 for unlimited.") |
| 6279 |
fs.BoolVar(&opts.JetStream, "js", false, "Enable JetStream.") |
| 6280 |
fs.BoolVar(&opts.JetStream, "jetstream", false, "Enable JetStream.") |
| 6281 |
fs.StringVar(&opts.StoreDir, "sd", _EMPTY_, "Storage directory.") |
| 6282 |
fs.StringVar(&opts.StoreDir, "store_dir", _EMPTY_, "Storage directory.") |
| 6283 |
|
| 6284 |
// The flags definition above set "default" values to some of the options. |
| 6285 |
// Calling Parse() here will override the default options with any value |
| 6286 |
// specified from the command line. This is ok. We will then update the |
| 6287 |
// options with the content of the configuration file (if present), and then, |
| 6288 |
// call Parse() again to override the default+config with command line values. |
| 6289 |
// Calling Parse() before processing config file is necessary since configFile |
| 6290 |
// itself is a command line argument, and also Parse() is required in order |
| 6291 |
// to know if user wants simply to show "help" or "version", etc... |
| 6292 |
if err := fs.Parse(args); err != nil { |
| 6293 |
return nil, err |
| 6294 |
} |
| 6295 |
|
| 6296 |
if showVersion { |
| 6297 |
printVersion() |
| 6298 |
return nil, nil |
| 6299 |
} |
| 6300 |
|
| 6301 |
if showHelp { |
| 6302 |
printHelp() |
| 6303 |
return nil, nil |
| 6304 |
} |
| 6305 |
|
| 6306 |
if showTLSHelp { |
| 6307 |
printTLSHelp() |
| 6308 |
return nil, nil |
| 6309 |
} |
| 6310 |
|
| 6311 |
// Process args looking for non-flag options, |
| 6312 |
// 'version' and 'help' only for now |
| 6313 |
showVersion, showHelp, err = ProcessCommandLineArgs(fs) |
| 6314 |
if err != nil { |
| 6315 |
return nil, err |
| 6316 |
} else if showVersion { |
| 6317 |
printVersion() |
| 6318 |
return nil, nil |
| 6319 |
} else if showHelp { |
| 6320 |
printHelp() |
| 6321 |
return nil, nil |
| 6322 |
} |
| 6323 |
|
| 6324 |
// Snapshot flag options. |
| 6325 |
FlagSnapshot = opts.Clone() |
| 6326 |
|
| 6327 |
// Keep track of the boolean flags that were explicitly set with their value. |
| 6328 |
fs.Visit(func(f *flag.Flag) { |
| 6329 |
switch f.Name { |
| 6330 |
case "DVV": |
| 6331 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "Debug", dbgAndTrcAndVerboseTrc) |
| 6332 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", dbgAndTrcAndVerboseTrc) |
| 6333 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "TraceVerbose", dbgAndTrcAndVerboseTrc) |
| 6334 |
case "DV": |
| 6335 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "Debug", dbgAndTrace) |
| 6336 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", dbgAndTrace) |
| 6337 |
case "D": |
| 6338 |
fallthrough |
| 6339 |
case "debug": |
| 6340 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "Debug", FlagSnapshot.Debug) |
| 6341 |
case "VV": |
| 6342 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", trcAndVerboseTrc) |
| 6343 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "TraceVerbose", trcAndVerboseTrc) |
| 6344 |
case "V": |
| 6345 |
fallthrough |
| 6346 |
case "trace": |
| 6347 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "Trace", FlagSnapshot.Trace) |
| 6348 |
case "T": |
| 6349 |
fallthrough |
| 6350 |
case "logtime": |
| 6351 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "Logtime", FlagSnapshot.Logtime) |
| 6352 |
case "s": |
| 6353 |
fallthrough |
| 6354 |
case "syslog": |
| 6355 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "Syslog", FlagSnapshot.Syslog) |
| 6356 |
case "no_advertise": |
| 6357 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "Cluster.NoAdvertise", FlagSnapshot.Cluster.NoAdvertise) |
| 6358 |
case "js": |
| 6359 |
trackExplicitVal(&FlagSnapshot.inCmdLine, "JetStream", FlagSnapshot.JetStream) |
| 6360 |
} |
| 6361 |
}) |
| 6362 |
|
| 6363 |
// Process signal control. |
| 6364 |
if signal != _EMPTY_ { |
| 6365 |
// processSignal always either returns an error or calls os.Exit(0). |
| 6366 |
return nil, processSignal(signal) |
| 6367 |
} |
| 6368 |
|
| 6369 |
// Parse config if given |
| 6370 |
if configFile != _EMPTY_ { |
| 6371 |
// This will update the options with values from the config file. |
| 6372 |
err := opts.ProcessConfigFile(configFile) |
| 6373 |
if err != nil { |
| 6374 |
if opts.CheckConfig { |
| 6375 |
return nil, err |
| 6376 |
} |
| 6377 |
if cerr, ok := err.(*processConfigErr); !ok || len(cerr.Errors()) != 0 { |
| 6378 |
return nil, err |
| 6379 |
} |
| 6380 |
// If we get here we only have warnings and can still continue |
| 6381 |
fmt.Fprint(os.Stderr, err) |
| 6382 |
} else if opts.CheckConfig { |
| 6383 |
// Report configuration file syntax test was successful and exit. |
| 6384 |
return opts, nil |
| 6385 |
} |
| 6386 |
|
| 6387 |
// Call this again to override config file options with options from command line. |
| 6388 |
// Note: We don't need to check error here since if there was an error, it would |
| 6389 |
// have been caught the first time this function was called (after setting up the |
| 6390 |
// flags). |
| 6391 |
fs.Parse(args) |
| 6392 |
} else if opts.CheckConfig { |
| 6393 |
return nil, fmt.Errorf("must specify [-c, --config] option to check configuration file syntax") |
| 6394 |
} |
| 6395 |
|
| 6396 |
// Special handling of some flags |
| 6397 |
var ( |
| 6398 |
flagErr error |
| 6399 |
tlsDisabled bool |
| 6400 |
tlsOverride bool |
| 6401 |
) |
| 6402 |
fs.Visit(func(f *flag.Flag) { |
| 6403 |
// short-circuit if an error was encountered |
| 6404 |
if flagErr != nil { |
| 6405 |
return |
| 6406 |
} |
| 6407 |
if strings.HasPrefix(f.Name, "tls") { |
| 6408 |
if f.Name == "tls" { |
| 6409 |
if !opts.TLS { |
| 6410 |
// User has specified "-tls=false", we need to disable TLS |
| 6411 |
opts.TLSConfig = nil |
| 6412 |
tlsDisabled = true |
| 6413 |
tlsOverride = false |
| 6414 |
return |
| 6415 |
} |
| 6416 |
tlsOverride = true |
| 6417 |
} else if !tlsDisabled { |
| 6418 |
tlsOverride = true |
| 6419 |
} |
| 6420 |
} else { |
| 6421 |
switch f.Name { |
| 6422 |
case "VV": |
| 6423 |
opts.Trace, opts.TraceVerbose = trcAndVerboseTrc, trcAndVerboseTrc |
| 6424 |
case "DVV": |
| 6425 |
opts.Trace, opts.Debug, opts.TraceVerbose = dbgAndTrcAndVerboseTrc, dbgAndTrcAndVerboseTrc, dbgAndTrcAndVerboseTrc |
| 6426 |
case "DV": |
| 6427 |
// Check value to support -DV=false |
| 6428 |
opts.Trace, opts.Debug = dbgAndTrace, dbgAndTrace |
| 6429 |
case "cluster", "cluster_listen": |
| 6430 |
// Override cluster config if explicitly set via flags. |
| 6431 |
flagErr = overrideCluster(opts) |
| 6432 |
case "routes": |
| 6433 |
// Keep in mind that the flag has updated opts.RoutesStr at this point. |
| 6434 |
if opts.RoutesStr == _EMPTY_ { |
| 6435 |
// Set routes array to nil since routes string is empty |
| 6436 |
opts.Routes = nil |
| 6437 |
return |
| 6438 |
} |
| 6439 |
routeUrls := RoutesFromStr(opts.RoutesStr) |
| 6440 |
opts.Routes = routeUrls |
| 6441 |
} |
| 6442 |
} |
| 6443 |
}) |
| 6444 |
if flagErr != nil { |
| 6445 |
return nil, flagErr |
| 6446 |
} |
| 6447 |
|
| 6448 |
// This will be true if some of the `-tls` params have been set and |
| 6449 |
// `-tls=false` has not been set. |
| 6450 |
if tlsOverride { |
| 6451 |
if err := overrideTLS(opts); err != nil { |
| 6452 |
return nil, err |
| 6453 |
} |
| 6454 |
} |
| 6455 |
|
| 6456 |
// If we don't have cluster defined in the configuration |
| 6457 |
// file and no cluster listen string override, but we do |
| 6458 |
// have a routes override, we need to report misconfiguration. |
| 6459 |
if opts.RoutesStr != _EMPTY_ && opts.Cluster.ListenStr == _EMPTY_ && opts.Cluster.Host == _EMPTY_ && opts.Cluster.Port == 0 { |
| 6460 |
return nil, errors.New("solicited routes require cluster capabilities, e.g. --cluster") |
| 6461 |
} |
| 6462 |
|
| 6463 |
return opts, nil |
| 6464 |
} |
| 6465 |
|
| 6466 |
func normalizeBasePath(p string) string { |
| 6467 |
if len(p) == 0 { |
| 6468 |
return "/" |
| 6469 |
} |
| 6470 |
// add leading slash |
| 6471 |
if p[0] != '/' { |
| 6472 |
p = "/" + p |
| 6473 |
} |
| 6474 |
return path.Clean(p) |
| 6475 |
} |
| 6476 |
|
| 6477 |
// overrideTLS is called when at least "-tls=true" has been set. |
| 6478 |
func overrideTLS(opts *Options) error { |
| 6479 |
if opts.TLSCert == _EMPTY_ { |
| 6480 |
return errors.New("TLS Server certificate must be present and valid") |
| 6481 |
} |
| 6482 |
if opts.TLSKey == _EMPTY_ { |
| 6483 |
return errors.New("TLS Server private key must be present and valid") |
| 6484 |
} |
| 6485 |
|
| 6486 |
tc := TLSConfigOpts{} |
| 6487 |
tc.CertFile = opts.TLSCert |
| 6488 |
tc.KeyFile = opts.TLSKey |
| 6489 |
tc.CaFile = opts.TLSCaCert |
| 6490 |
tc.Verify = opts.TLSVerify |
| 6491 |
tc.Ciphers = defaultCipherSuites() |
| 6492 |
|
| 6493 |
var err error |
| 6494 |
opts.TLSConfig, err = GenTLSConfig(&tc) |
| 6495 |
return err |
| 6496 |
} |
| 6497 |
|
| 6498 |
// overrideCluster updates Options.Cluster if that flag "cluster" (or "cluster_listen") |
| 6499 |
// has explicitly be set in the command line. If it is set to empty string, it will |
| 6500 |
// clear the Cluster options. |
| 6501 |
func overrideCluster(opts *Options) error { |
| 6502 |
if opts.Cluster.ListenStr == _EMPTY_ { |
| 6503 |
// This one is enough to disable clustering. |
| 6504 |
opts.Cluster.Port = 0 |
| 6505 |
return nil |
| 6506 |
} |
| 6507 |
// -1 will fail url.Parse, so if we have -1, change it to |
| 6508 |
// 0, and then after parse, replace the port with -1 so we get |
| 6509 |
// automatic port allocation |
| 6510 |
wantsRandom := false |
| 6511 |
if strings.HasSuffix(opts.Cluster.ListenStr, ":-1") { |
| 6512 |
wantsRandom = true |
| 6513 |
cls := fmt.Sprintf("%s:0", opts.Cluster.ListenStr[0:len(opts.Cluster.ListenStr)-3]) |
| 6514 |
opts.Cluster.ListenStr = cls |
| 6515 |
} |
| 6516 |
clusterURL, err := url.Parse(opts.Cluster.ListenStr) |
| 6517 |
if err != nil { |
| 6518 |
return err |
| 6519 |
} |
| 6520 |
h, p, err := net.SplitHostPort(clusterURL.Host) |
| 6521 |
if err != nil { |
| 6522 |
return err |
| 6523 |
} |
| 6524 |
if wantsRandom { |
| 6525 |
p = "-1" |
| 6526 |
} |
| 6527 |
opts.Cluster.Host = h |
| 6528 |
_, err = fmt.Sscan(p, &opts.Cluster.Port) |
| 6529 |
if err != nil { |
| 6530 |
return err |
| 6531 |
} |
| 6532 |
|
| 6533 |
if clusterURL.User != nil { |
| 6534 |
pass, hasPassword := clusterURL.User.Password() |
| 6535 |
if !hasPassword { |
| 6536 |
return errors.New("expected cluster password to be set") |
| 6537 |
} |
| 6538 |
opts.Cluster.Password = pass |
| 6539 |
|
| 6540 |
user := clusterURL.User.Username() |
| 6541 |
opts.Cluster.Username = user |
| 6542 |
} else { |
| 6543 |
// Since we override from flag and there is no user/pwd, make |
| 6544 |
// sure we clear what we may have gotten from config file. |
| 6545 |
opts.Cluster.Username = _EMPTY_ |
| 6546 |
opts.Cluster.Password = _EMPTY_ |
| 6547 |
} |
| 6548 |
|
| 6549 |
return nil |
| 6550 |
} |
| 6551 |
|
| 6552 |
func processSignal(signal string) error { |
| 6553 |
var ( |
| 6554 |
pid string |
| 6555 |
commandAndPid = strings.Split(signal, "=") |
| 6556 |
) |
| 6557 |
if l := len(commandAndPid); l == 2 { |
| 6558 |
pid = maybeReadPidFile(commandAndPid[1]) |
| 6559 |
} else if l > 2 { |
| 6560 |
return fmt.Errorf("invalid signal parameters: %v", commandAndPid[2:]) |
| 6561 |
} |
| 6562 |
if err := ProcessSignal(Command(commandAndPid[0]), pid); err != nil { |
| 6563 |
return err |
| 6564 |
} |
| 6565 |
os.Exit(0) |
| 6566 |
return nil |
| 6567 |
} |
| 6568 |
|
| 6569 |
// maybeReadPidFile returns a PID or Windows service name obtained via the following method: |
| 6570 |
// 1. Try to open a file with path "pidStr" (absolute or relative). |
| 6571 |
// 2. If such a file exists and can be read, return its contents. |
| 6572 |
// 3. Otherwise, return the original "pidStr" string. |
| 6573 |
func maybeReadPidFile(pidStr string) string { |
| 6574 |
if b, err := os.ReadFile(pidStr); err == nil { |
| 6575 |
return string(b) |
| 6576 |
} |
| 6577 |
return pidStr |
| 6578 |
} |
| 6579 |
|
| 6580 |
func homeDir() (string, error) { |
| 6581 |
if runtime.GOOS == "windows" { |
| 6582 |
homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH") |
| 6583 |
userProfile := os.Getenv("USERPROFILE") |
| 6584 |
|
| 6585 |
home := filepath.Join(homeDrive, homePath) |
| 6586 |
if homeDrive == _EMPTY_ || homePath == _EMPTY_ { |
| 6587 |
if userProfile == _EMPTY_ { |
| 6588 |
return _EMPTY_, errors.New("nats: failed to get home dir, require %HOMEDRIVE% and %HOMEPATH% or %USERPROFILE%") |
| 6589 |
} |
| 6590 |
home = userProfile |
| 6591 |
} |
| 6592 |
|
| 6593 |
return home, nil |
| 6594 |
} |
| 6595 |
|
| 6596 |
home := os.Getenv("HOME") |
| 6597 |
if home == _EMPTY_ { |
| 6598 |
return _EMPTY_, errors.New("failed to get home dir, require $HOME") |
| 6599 |
} |
| 6600 |
return home, nil |
| 6601 |
} |
| 6602 |
|
| 6603 |
func expandPath(p string) (string, error) { |
| 6604 |
p = os.ExpandEnv(p) |
| 6605 |
|
| 6606 |
if !strings.HasPrefix(p, "~") { |
| 6607 |
return p, nil |
| 6608 |
} |
| 6609 |
|
| 6610 |
home, err := homeDir() |
| 6611 |
if err != nil { |
| 6612 |
return _EMPTY_, err |
| 6613 |
} |
| 6614 |
|
| 6615 |
return filepath.Join(home, p[1:]), nil |
| 6616 |
} |
| 6617 |
|
| 6618 |
// RedactArgs redacts sensitive arguments from the command line. |
| 6619 |
// For example, turns '--pass=secret' into '--pass=[REDACTED]'. |
| 6620 |
func RedactArgs(args []string) { |
| 6621 |
secretArg := regexp.MustCompile("^-{1,2}(user|pass|auth)(=.*)?$") |
| 6622 |
routeURLArg := regexp.MustCompile("^-{1,2}(routes)(=.*)?$") |
| 6623 |
singleURLArg := regexp.MustCompile("^-{1,2}(cluster|cluster_listen)(=.*)?$") |
| 6624 |
for i, arg := range args { |
| 6625 |
switch { |
| 6626 |
case secretArg.MatchString(arg): |
| 6627 |
redactArgValue(args, i, func(_ string) string { return "[REDACTED]" }) |
| 6628 |
case routeURLArg.MatchString(arg): |
| 6629 |
redactArgValue(args, i, redactURLListUser) |
| 6630 |
case singleURLArg.MatchString(arg): |
| 6631 |
redactArgValue(args, i, redactURLUser) |
| 6632 |
} |
| 6633 |
} |
| 6634 |
} |
| 6635 |
|
| 6636 |
func redactArgValue(args []string, i int, redact func(string) string) { |
| 6637 |
if flag, value, ok := strings.Cut(args[i], "="); ok { |
| 6638 |
args[i] = flag + "=" + redact(value) |
| 6639 |
} else if i+1 < len(args) { |
| 6640 |
args[i+1] = redact(args[i+1]) |
| 6641 |
} |
| 6642 |
} |
| 6643 |
|
| 6644 |
func redactURLUser(raw string) string { |
| 6645 |
if !strings.Contains(raw, "@") { |
| 6646 |
return raw |
| 6647 |
} |
| 6648 |
parseValue := strings.TrimSpace(raw) |
| 6649 |
restoreRandom := false |
| 6650 |
if prefix, ok := strings.CutSuffix(parseValue, ":-1"); ok { |
| 6651 |
parseValue = prefix + ":0" |
| 6652 |
restoreRandom = true |
| 6653 |
} |
| 6654 |
u, err := url.Parse(parseValue) |
| 6655 |
if err != nil || u.User == nil { |
| 6656 |
return raw |
| 6657 |
} |
| 6658 |
// url.String escapes brackets in userinfo, so use |
| 6659 |
// a placeholder here and rewrite it afterward. |
| 6660 |
u.User = url.User("_REDACTED_") |
| 6661 |
if restoreRandom { |
| 6662 |
u.Host = strings.TrimSuffix(u.Host, ":0") + ":-1" |
| 6663 |
} |
| 6664 |
return strings.Replace(u.String(), "_REDACTED_@", "[REDACTED]@", 1) |
| 6665 |
} |
| 6666 |
|
| 6667 |
func redactURLListUser(raw string) string { |
| 6668 |
parts := strings.Split(raw, ",") |
| 6669 |
for i, part := range parts { |
| 6670 |
parts[i] = redactURLUser(part) |
| 6671 |
} |
| 6672 |
return strings.Join(parts, ",") |
| 6673 |
} |