| 1 |
// Copyright 2012-2026 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 |
"bytes" |
| 18 |
"crypto/tls" |
| 19 |
"encoding/json" |
| 20 |
"flag" |
| 21 |
"fmt" |
| 22 |
"net/url" |
| 23 |
"os" |
| 24 |
"path/filepath" |
| 25 |
"reflect" |
| 26 |
"runtime" |
| 27 |
"strings" |
| 28 |
"sync" |
| 29 |
"sync/atomic" |
| 30 |
"testing" |
| 31 |
"time" |
| 32 |
|
| 33 |
"github.com/nats-io/jwt/v2" |
| 34 |
"github.com/nats-io/nats-server/v2/conf" |
| 35 |
"github.com/nats-io/nats.go" |
| 36 |
"github.com/nats-io/nkeys" |
| 37 |
) |
| 38 |
|
| 39 |
func checkOptionsEqual(t *testing.T, golden, opts *Options) { |
| 40 |
t.Helper() |
| 41 |
// Clone them so we can remove private fields that we don't |
| 42 |
// want to be compared. |
| 43 |
goldenClone := golden.Clone() |
| 44 |
goldenClone.inConfig, goldenClone.inCmdLine = nil, nil |
| 45 |
optsClone := opts.Clone() |
| 46 |
optsClone.inConfig, optsClone.inCmdLine = nil, nil |
| 47 |
if !reflect.DeepEqual(goldenClone, optsClone) { |
| 48 |
t.Fatalf("Options are incorrect.\nexpected: %+v\ngot: %+v", goldenClone, optsClone) |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
func TestDefaultOptions(t *testing.T) { |
| 53 |
golden := &Options{ |
| 54 |
Host: DEFAULT_HOST, |
| 55 |
Port: DEFAULT_PORT, |
| 56 |
MaxConn: DEFAULT_MAX_CONNECTIONS, |
| 57 |
HTTPHost: DEFAULT_HOST, |
| 58 |
PingInterval: DEFAULT_PING_INTERVAL, |
| 59 |
MaxPingsOut: DEFAULT_PING_MAX_OUT, |
| 60 |
TLSTimeout: float64(TLS_TIMEOUT) / float64(time.Second), |
| 61 |
AuthTimeout: float64(AUTH_TIMEOUT) / float64(time.Second), |
| 62 |
MaxControlLine: MAX_CONTROL_LINE_SIZE, |
| 63 |
MaxPayload: MAX_PAYLOAD_SIZE, |
| 64 |
MaxPending: MAX_PENDING_SIZE, |
| 65 |
WriteDeadline: DEFAULT_FLUSH_DEADLINE, |
| 66 |
MaxClosedClients: DEFAULT_MAX_CLOSED_CLIENTS, |
| 67 |
LameDuckDuration: DEFAULT_LAME_DUCK_DURATION, |
| 68 |
LameDuckGracePeriod: DEFAULT_LAME_DUCK_GRACE_PERIOD, |
| 69 |
LeafNode: LeafNodeOpts{ |
| 70 |
ReconnectInterval: DEFAULT_LEAF_NODE_RECONNECT, |
| 71 |
}, |
| 72 |
ConnectErrorReports: DEFAULT_CONNECT_ERROR_REPORTS, |
| 73 |
ReconnectErrorReports: DEFAULT_RECONNECT_ERROR_REPORTS, |
| 74 |
MaxTracedMsgLen: 0, |
| 75 |
JetStreamMaxMemory: -1, |
| 76 |
JetStreamMaxStore: -1, |
| 77 |
SyncInterval: 2 * time.Minute, |
| 78 |
JetStreamRequestQueueLimit: JSDefaultRequestQueueLimit, |
| 79 |
JetStreamInfoQueueLimit: JSDefaultRequestQueueLimit, |
| 80 |
JetStreamConcurrentIOs: defaultConcurrentIOs, |
| 81 |
} |
| 82 |
|
| 83 |
opts := &Options{} |
| 84 |
setBaselineOptions(opts) |
| 85 |
|
| 86 |
checkOptionsEqual(t, golden, opts) |
| 87 |
} |
| 88 |
|
| 89 |
func TestOptions_RandomPort(t *testing.T) { |
| 90 |
opts := &Options{Port: RANDOM_PORT} |
| 91 |
setBaselineOptions(opts) |
| 92 |
|
| 93 |
if opts.Port != 0 { |
| 94 |
t.Fatalf("Process of options should have resolved random port to "+ |
| 95 |
"zero.\nexpected: %d\ngot: %d", 0, opts.Port) |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
func TestConfigFile(t *testing.T) { |
| 100 |
golden := &Options{ |
| 101 |
ConfigFile: "./configs/test.conf", |
| 102 |
ServerName: "testing_server", |
| 103 |
Host: "127.0.0.1", |
| 104 |
Port: 4242, |
| 105 |
Username: "derek", |
| 106 |
Password: "porkchop", |
| 107 |
AuthTimeout: 1.0, |
| 108 |
Debug: false, |
| 109 |
Trace: true, |
| 110 |
Logtime: false, |
| 111 |
HTTPPort: 8222, |
| 112 |
HTTPBasePath: "/nats", |
| 113 |
PidFile: "/tmp/nats-server/nats-server.pid", |
| 114 |
ProfPort: 6543, |
| 115 |
Syslog: true, |
| 116 |
RemoteSyslog: "udp://foo.com:33", |
| 117 |
MaxControlLine: 2048, |
| 118 |
MaxPayload: 65536, |
| 119 |
MaxConn: 100, |
| 120 |
MaxSubs: 1000, |
| 121 |
MaxPending: 10000000, |
| 122 |
PingInterval: 60 * time.Second, |
| 123 |
MaxPingsOut: 3, |
| 124 |
WriteDeadline: 3 * time.Second, |
| 125 |
LameDuckDuration: 4 * time.Minute, |
| 126 |
ConnectErrorReports: 86400, |
| 127 |
ReconnectErrorReports: 5, |
| 128 |
Metadata: map[string]string{"key1": "value1", "key2": "value2"}, |
| 129 |
FeatureFlags: map[string]bool{"feature": false, "fix": true, "revert_fix": true}, |
| 130 |
configDigest: "sha256:f10eacddb9ce83a6bdc79b42c851b9628d49cf8b3c6ba95b1ecf090307504948", |
| 131 |
authBlockDefined: true, |
| 132 |
} |
| 133 |
|
| 134 |
opts, err := ProcessConfigFile("./configs/test.conf") |
| 135 |
if err != nil { |
| 136 |
t.Fatalf("Received an error reading config file: %v", err) |
| 137 |
} |
| 138 |
|
| 139 |
checkOptionsEqual(t, golden, opts) |
| 140 |
} |
| 141 |
|
| 142 |
func TestTLSConfigFile(t *testing.T) { |
| 143 |
golden := &Options{ |
| 144 |
ConfigFile: "./configs/tls.conf", |
| 145 |
Host: "127.0.0.1", |
| 146 |
Port: 4443, |
| 147 |
Username: "derek", |
| 148 |
Password: "foo", |
| 149 |
AuthTimeout: 1.0, |
| 150 |
TLSTimeout: 2.0, |
| 151 |
authBlockDefined: true, |
| 152 |
configDigest: "sha256:cec986d37d7c09c86916d1ba4990cea1b8dadd49c86f9f782b455b47d07c2ac8", |
| 153 |
} |
| 154 |
opts, err := ProcessConfigFile("./configs/tls.conf") |
| 155 |
if err != nil { |
| 156 |
t.Fatalf("Received an error reading config file: %v", err) |
| 157 |
} |
| 158 |
tlsConfig := opts.TLSConfig |
| 159 |
if tlsConfig == nil { |
| 160 |
t.Fatal("Expected opts.TLSConfig to be non-nil") |
| 161 |
} |
| 162 |
opts.TLSConfig = nil |
| 163 |
opts.tlsConfigOpts = nil |
| 164 |
checkOptionsEqual(t, golden, opts) |
| 165 |
|
| 166 |
// Now check TLSConfig a bit more closely |
| 167 |
// CipherSuites |
| 168 |
ciphers := defaultCipherSuites() |
| 169 |
if !reflect.DeepEqual(tlsConfig.CipherSuites, ciphers) { |
| 170 |
t.Fatalf("Got incorrect cipher suite list: [%+v]", tlsConfig.CipherSuites) |
| 171 |
} |
| 172 |
if tlsConfig.MinVersion != tls.VersionTLS12 { |
| 173 |
t.Fatalf("Expected MinVersion of 1.2 [%v], got [%v]", tls.VersionTLS12, tlsConfig.MinVersion) |
| 174 |
} |
| 175 |
// Verify hostname is correct in certificate |
| 176 |
if len(tlsConfig.Certificates) != 1 { |
| 177 |
t.Fatal("Expected 1 certificate") |
| 178 |
} |
| 179 |
cert := tlsConfig.Certificates[0].Leaf |
| 180 |
if err := cert.VerifyHostname("127.0.0.1"); err != nil { |
| 181 |
t.Fatalf("Could not verify hostname in certificate: %v", err) |
| 182 |
} |
| 183 |
|
| 184 |
// First make sure that we can't add insecure cipher suites accidentally. |
| 185 |
_, err = ProcessConfigFile("./configs/tls_insecure_ciphers.conf") |
| 186 |
if err == nil || !strings.Contains(err.Error(), "insecure") { |
| 187 |
t.Fatalf("Expected to receive insecure cipher error reading configuration file but didn't") |
| 188 |
} |
| 189 |
_, err = ProcessConfigFile("./configs/tls_insecure_ciphers_allowed.conf") |
| 190 |
if err != nil { |
| 191 |
t.Fatalf("Received an error reading config file: %v", err) |
| 192 |
} |
| 193 |
|
| 194 |
// Now test adding cipher suites. |
| 195 |
opts, err = ProcessConfigFile("./configs/tls_ciphers.conf") |
| 196 |
if err != nil { |
| 197 |
t.Fatalf("Received an error reading config file: %v", err) |
| 198 |
} |
| 199 |
tlsConfig = opts.TLSConfig |
| 200 |
if tlsConfig == nil { |
| 201 |
t.Fatal("Expected opts.TLSConfig to be non-nil") |
| 202 |
} |
| 203 |
|
| 204 |
// CipherSuites listed in the config - test all of them. |
| 205 |
ciphers = []uint16{ |
| 206 |
tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, |
| 207 |
tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, |
| 208 |
tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, |
| 209 |
tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, |
| 210 |
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, |
| 211 |
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, |
| 212 |
} |
| 213 |
|
| 214 |
if !reflect.DeepEqual(tlsConfig.CipherSuites, ciphers) { |
| 215 |
t.Fatalf("Got incorrect cipher suite list: [%+v]", tlsConfig.CipherSuites) |
| 216 |
} |
| 217 |
|
| 218 |
// Test an unrecognized/bad cipher |
| 219 |
if _, err := ProcessConfigFile("./configs/tls_bad_cipher.conf"); err == nil { |
| 220 |
t.Fatal("Did not receive an error from a unrecognized cipher") |
| 221 |
} |
| 222 |
|
| 223 |
// Test an empty cipher entry in a config file. |
| 224 |
if _, err := ProcessConfigFile("./configs/tls_empty_cipher.conf"); err == nil { |
| 225 |
t.Fatal("Did not receive an error from empty cipher_suites") |
| 226 |
} |
| 227 |
|
| 228 |
// Test a curve preference from the config. |
| 229 |
curves := []tls.CurveID{ |
| 230 |
tls.CurveP256, |
| 231 |
} |
| 232 |
|
| 233 |
// test on a file that will load the curve preference defaults |
| 234 |
opts, err = ProcessConfigFile("./configs/tls_ciphers.conf") |
| 235 |
if err != nil { |
| 236 |
t.Fatalf("Received an error reading config file: %v", err) |
| 237 |
} |
| 238 |
|
| 239 |
if !reflect.DeepEqual(opts.TLSConfig.CurvePreferences, defaultCurvePreferences()) { |
| 240 |
t.Fatalf("Got incorrect curve preference list: [%+v]", tlsConfig.CurvePreferences) |
| 241 |
} |
| 242 |
|
| 243 |
// Test specifying a single curve preference |
| 244 |
opts, err = ProcessConfigFile("./configs/tls_curve_prefs.conf") |
| 245 |
if err != nil { |
| 246 |
t.Fatal("Did not receive an error from a unrecognized cipher.") |
| 247 |
} |
| 248 |
|
| 249 |
if !reflect.DeepEqual(opts.TLSConfig.CurvePreferences, curves) { |
| 250 |
t.Fatalf("Got incorrect cipher suite list: [%+v]", tlsConfig.CurvePreferences) |
| 251 |
} |
| 252 |
|
| 253 |
// Test an unrecognized/bad curve preference |
| 254 |
if _, err := ProcessConfigFile("./configs/tls_bad_curve_prefs.conf"); err == nil { |
| 255 |
t.Fatal("Did not receive an error from a unrecognized curve preference") |
| 256 |
} |
| 257 |
// Test an empty curve preference |
| 258 |
if _, err := ProcessConfigFile("./configs/tls_empty_curve_prefs.conf"); err == nil { |
| 259 |
t.Fatal("Did not receive an error from empty curve preferences") |
| 260 |
} |
| 261 |
} |
| 262 |
|
| 263 |
func TestMergeOverrides(t *testing.T) { |
| 264 |
golden := &Options{ |
| 265 |
ConfigFile: "./configs/test.conf", |
| 266 |
ServerName: "testing_server", |
| 267 |
Host: "127.0.0.1", |
| 268 |
Port: 2222, |
| 269 |
Username: "derek", |
| 270 |
Password: "porkchop", |
| 271 |
AuthTimeout: 1.0, |
| 272 |
Debug: true, |
| 273 |
Trace: true, |
| 274 |
Logtime: false, |
| 275 |
HTTPPort: DEFAULT_HTTP_PORT, |
| 276 |
HTTPBasePath: DEFAULT_HTTP_BASE_PATH, |
| 277 |
PidFile: "/tmp/nats-server/nats-server.pid", |
| 278 |
ProfPort: 6789, |
| 279 |
Syslog: true, |
| 280 |
RemoteSyslog: "udp://foo.com:33", |
| 281 |
MaxControlLine: 2048, |
| 282 |
MaxPayload: 65536, |
| 283 |
MaxConn: 100, |
| 284 |
MaxSubs: 1000, |
| 285 |
MaxPending: 10000000, |
| 286 |
PingInterval: 60 * time.Second, |
| 287 |
MaxPingsOut: 3, |
| 288 |
Cluster: ClusterOpts{ |
| 289 |
NoAdvertise: true, |
| 290 |
ConnectRetries: 2, |
| 291 |
}, |
| 292 |
WriteDeadline: 3 * time.Second, |
| 293 |
LameDuckDuration: 4 * time.Minute, |
| 294 |
ConnectErrorReports: 86400, |
| 295 |
ReconnectErrorReports: 5, |
| 296 |
JetStream: true, |
| 297 |
StoreDir: "/store/dir", |
| 298 |
authBlockDefined: true, |
| 299 |
Metadata: map[string]string{"key1": "value1", "key2": "value2"}, |
| 300 |
FeatureFlags: map[string]bool{"feature": false, "fix": true, "revert_fix": true}, |
| 301 |
configDigest: "sha256:f10eacddb9ce83a6bdc79b42c851b9628d49cf8b3c6ba95b1ecf090307504948", |
| 302 |
} |
| 303 |
fopts, err := ProcessConfigFile("./configs/test.conf") |
| 304 |
if err != nil { |
| 305 |
t.Fatalf("Received an error reading config file: %v", err) |
| 306 |
} |
| 307 |
|
| 308 |
// Overrides via flags |
| 309 |
opts := &Options{ |
| 310 |
Port: 2222, |
| 311 |
Password: "porkchop", |
| 312 |
Debug: true, |
| 313 |
HTTPPort: DEFAULT_HTTP_PORT, |
| 314 |
HTTPBasePath: DEFAULT_HTTP_BASE_PATH, |
| 315 |
ProfPort: 6789, |
| 316 |
Cluster: ClusterOpts{ |
| 317 |
NoAdvertise: true, |
| 318 |
ConnectRetries: 2, |
| 319 |
}, |
| 320 |
JetStream: true, |
| 321 |
StoreDir: "/store/dir", |
| 322 |
} |
| 323 |
merged := MergeOptions(fopts, opts) |
| 324 |
|
| 325 |
checkOptionsEqual(t, golden, merged) |
| 326 |
} |
| 327 |
|
| 328 |
func TestRouteFlagOverride(t *testing.T) { |
| 329 |
routeFlag := "nats-route://ruser:[email protected]:8246" |
| 330 |
rurl, _ := url.Parse(routeFlag) |
| 331 |
|
| 332 |
golden := &Options{ |
| 333 |
ConfigFile: "./configs/srv_a.conf", |
| 334 |
Host: "127.0.0.1", |
| 335 |
Port: 7222, |
| 336 |
Cluster: ClusterOpts{ |
| 337 |
Name: "abc", |
| 338 |
Host: "127.0.0.1", |
| 339 |
Port: 7244, |
| 340 |
Username: "ruser", |
| 341 |
Password: "top_secret", |
| 342 |
AuthTimeout: 0.5, |
| 343 |
}, |
| 344 |
Routes: []*url.URL{rurl}, |
| 345 |
RoutesStr: routeFlag, |
| 346 |
configDigest: "sha256:fe3c13f82637723989a9bbd0ad6d064b95d48971666af440d4196d9c0d3af979", |
| 347 |
} |
| 348 |
|
| 349 |
fopts, err := ProcessConfigFile("./configs/srv_a.conf") |
| 350 |
if err != nil { |
| 351 |
t.Fatalf("Received an error reading config file: %v", err) |
| 352 |
} |
| 353 |
|
| 354 |
// Overrides via flags |
| 355 |
opts := &Options{ |
| 356 |
RoutesStr: routeFlag, |
| 357 |
} |
| 358 |
merged := MergeOptions(fopts, opts) |
| 359 |
|
| 360 |
checkOptionsEqual(t, golden, merged) |
| 361 |
} |
| 362 |
|
| 363 |
func TestClusterFlagsOverride(t *testing.T) { |
| 364 |
routeFlag := "nats-route://ruser:[email protected]:7246" |
| 365 |
rurl, _ := url.Parse(routeFlag) |
| 366 |
|
| 367 |
// In this test, we override the cluster listen string. Note that in |
| 368 |
// the golden options, the cluster other infos correspond to what |
| 369 |
// is recovered from the configuration file, this explains the |
| 370 |
// discrepency between ClusterListenStr and the rest. |
| 371 |
// The server would then process the ClusterListenStr override and |
| 372 |
// correctly override ClusterHost/ClustherPort/etc.. |
| 373 |
golden := &Options{ |
| 374 |
ConfigFile: "./configs/srv_a.conf", |
| 375 |
Host: "127.0.0.1", |
| 376 |
Port: 7222, |
| 377 |
Cluster: ClusterOpts{ |
| 378 |
Name: "abc", |
| 379 |
Host: "127.0.0.1", |
| 380 |
Port: 7244, |
| 381 |
ListenStr: "nats://127.0.0.1:8224", |
| 382 |
Username: "ruser", |
| 383 |
Password: "top_secret", |
| 384 |
AuthTimeout: 0.5, |
| 385 |
}, |
| 386 |
Routes: []*url.URL{rurl}, |
| 387 |
configDigest: "sha256:fe3c13f82637723989a9bbd0ad6d064b95d48971666af440d4196d9c0d3af979", |
| 388 |
} |
| 389 |
|
| 390 |
fopts, err := ProcessConfigFile("./configs/srv_a.conf") |
| 391 |
if err != nil { |
| 392 |
t.Fatalf("Received an error reading config file: %v", err) |
| 393 |
} |
| 394 |
|
| 395 |
// Overrides via flags |
| 396 |
opts := &Options{ |
| 397 |
Cluster: ClusterOpts{ |
| 398 |
ListenStr: "nats://127.0.0.1:8224", |
| 399 |
}, |
| 400 |
} |
| 401 |
merged := MergeOptions(fopts, opts) |
| 402 |
|
| 403 |
checkOptionsEqual(t, golden, merged) |
| 404 |
} |
| 405 |
|
| 406 |
func TestRouteFlagOverrideWithMultiple(t *testing.T) { |
| 407 |
routeFlag := "nats-route://ruser:[email protected]:8246, nats-route://ruser:[email protected]:8266" |
| 408 |
rurls := RoutesFromStr(routeFlag) |
| 409 |
|
| 410 |
golden := &Options{ |
| 411 |
ConfigFile: "./configs/srv_a.conf", |
| 412 |
Host: "127.0.0.1", |
| 413 |
Port: 7222, |
| 414 |
Cluster: ClusterOpts{ |
| 415 |
Host: "127.0.0.1", |
| 416 |
Name: "abc", |
| 417 |
Port: 7244, |
| 418 |
Username: "ruser", |
| 419 |
Password: "top_secret", |
| 420 |
AuthTimeout: 0.5, |
| 421 |
}, |
| 422 |
Routes: rurls, |
| 423 |
RoutesStr: routeFlag, |
| 424 |
configDigest: "sha256:fe3c13f82637723989a9bbd0ad6d064b95d48971666af440d4196d9c0d3af979", |
| 425 |
} |
| 426 |
|
| 427 |
fopts, err := ProcessConfigFile("./configs/srv_a.conf") |
| 428 |
if err != nil { |
| 429 |
t.Fatalf("Received an error reading config file: %v", err) |
| 430 |
} |
| 431 |
|
| 432 |
// Overrides via flags |
| 433 |
opts := &Options{ |
| 434 |
RoutesStr: routeFlag, |
| 435 |
} |
| 436 |
merged := MergeOptions(fopts, opts) |
| 437 |
|
| 438 |
checkOptionsEqual(t, golden, merged) |
| 439 |
} |
| 440 |
|
| 441 |
func TestDynamicPortOnListen(t *testing.T) { |
| 442 |
opts, err := ProcessConfigFile("./configs/listen-1.conf") |
| 443 |
if err != nil { |
| 444 |
t.Fatalf("Received an error reading config file: %v", err) |
| 445 |
} |
| 446 |
if opts.Port != -1 { |
| 447 |
t.Fatalf("Received incorrect port %v, expected -1", opts.Port) |
| 448 |
} |
| 449 |
if opts.HTTPPort != -1 { |
| 450 |
t.Fatalf("Received incorrect monitoring port %v, expected -1", opts.HTTPPort) |
| 451 |
} |
| 452 |
if opts.HTTPSPort != -1 { |
| 453 |
t.Fatalf("Received incorrect secure monitoring port %v, expected -1", opts.HTTPSPort) |
| 454 |
} |
| 455 |
} |
| 456 |
|
| 457 |
func TestListenConfig(t *testing.T) { |
| 458 |
opts, err := ProcessConfigFile("./configs/listen.conf") |
| 459 |
if err != nil { |
| 460 |
t.Fatalf("Received an error reading config file: %v", err) |
| 461 |
} |
| 462 |
setBaselineOptions(opts) |
| 463 |
|
| 464 |
// Normal clients |
| 465 |
host := "10.0.1.22" |
| 466 |
port := 4422 |
| 467 |
monHost := "127.0.0.1" |
| 468 |
if opts.Host != host { |
| 469 |
t.Fatalf("Received incorrect host %q, expected %q", opts.Host, host) |
| 470 |
} |
| 471 |
if opts.HTTPHost != monHost { |
| 472 |
t.Fatalf("Received incorrect host %q, expected %q", opts.HTTPHost, monHost) |
| 473 |
} |
| 474 |
if opts.Port != port { |
| 475 |
t.Fatalf("Received incorrect port %v, expected %v", opts.Port, port) |
| 476 |
} |
| 477 |
|
| 478 |
// Clustering |
| 479 |
clusterHost := "127.0.0.1" |
| 480 |
clusterPort := 4244 |
| 481 |
|
| 482 |
if opts.Cluster.Host != clusterHost { |
| 483 |
t.Fatalf("Received incorrect cluster host %q, expected %q", opts.Cluster.Host, clusterHost) |
| 484 |
} |
| 485 |
if opts.Cluster.Port != clusterPort { |
| 486 |
t.Fatalf("Received incorrect cluster port %v, expected %v", opts.Cluster.Port, clusterPort) |
| 487 |
} |
| 488 |
|
| 489 |
// HTTP |
| 490 |
httpHost := "127.0.0.1" |
| 491 |
httpPort := 8422 |
| 492 |
|
| 493 |
if opts.HTTPHost != httpHost { |
| 494 |
t.Fatalf("Received incorrect http host %q, expected %q", opts.HTTPHost, httpHost) |
| 495 |
} |
| 496 |
if opts.HTTPPort != httpPort { |
| 497 |
t.Fatalf("Received incorrect http port %v, expected %v", opts.HTTPPort, httpPort) |
| 498 |
} |
| 499 |
|
| 500 |
// HTTPS |
| 501 |
httpsPort := 9443 |
| 502 |
if opts.HTTPSPort != httpsPort { |
| 503 |
t.Fatalf("Received incorrect https port %v, expected %v", opts.HTTPSPort, httpsPort) |
| 504 |
} |
| 505 |
} |
| 506 |
|
| 507 |
func TestListenPortOnlyConfig(t *testing.T) { |
| 508 |
opts, err := ProcessConfigFile("./configs/listen_port.conf") |
| 509 |
if err != nil { |
| 510 |
t.Fatalf("Received an error reading config file: %v", err) |
| 511 |
} |
| 512 |
setBaselineOptions(opts) |
| 513 |
|
| 514 |
port := 8922 |
| 515 |
|
| 516 |
if opts.Host != DEFAULT_HOST { |
| 517 |
t.Fatalf("Received incorrect host %q, expected %q", opts.Host, DEFAULT_HOST) |
| 518 |
} |
| 519 |
if opts.HTTPHost != DEFAULT_HOST { |
| 520 |
t.Fatalf("Received incorrect host %q, expected %q", opts.Host, DEFAULT_HOST) |
| 521 |
} |
| 522 |
if opts.Port != port { |
| 523 |
t.Fatalf("Received incorrect port %v, expected %v", opts.Port, port) |
| 524 |
} |
| 525 |
} |
| 526 |
|
| 527 |
func TestListenPortWithColonConfig(t *testing.T) { |
| 528 |
opts, err := ProcessConfigFile("./configs/listen_port_with_colon.conf") |
| 529 |
if err != nil { |
| 530 |
t.Fatalf("Received an error reading config file: %v", err) |
| 531 |
} |
| 532 |
setBaselineOptions(opts) |
| 533 |
|
| 534 |
port := 8922 |
| 535 |
|
| 536 |
if opts.Host != DEFAULT_HOST { |
| 537 |
t.Fatalf("Received incorrect host %q, expected %q", opts.Host, DEFAULT_HOST) |
| 538 |
} |
| 539 |
if opts.HTTPHost != DEFAULT_HOST { |
| 540 |
t.Fatalf("Received incorrect host %q, expected %q", opts.Host, DEFAULT_HOST) |
| 541 |
} |
| 542 |
if opts.Port != port { |
| 543 |
t.Fatalf("Received incorrect port %v, expected %v", opts.Port, port) |
| 544 |
} |
| 545 |
} |
| 546 |
|
| 547 |
func TestListenMonitoringDefault(t *testing.T) { |
| 548 |
opts := &Options{ |
| 549 |
Host: "10.0.1.22", |
| 550 |
} |
| 551 |
setBaselineOptions(opts) |
| 552 |
|
| 553 |
host := "10.0.1.22" |
| 554 |
if opts.Host != host { |
| 555 |
t.Fatalf("Received incorrect host %q, expected %q", opts.Host, host) |
| 556 |
} |
| 557 |
if opts.HTTPHost != host { |
| 558 |
t.Fatalf("Received incorrect host %q, expected %q", opts.Host, host) |
| 559 |
} |
| 560 |
if opts.Port != DEFAULT_PORT { |
| 561 |
t.Fatalf("Received incorrect port %v, expected %v", opts.Port, DEFAULT_PORT) |
| 562 |
} |
| 563 |
} |
| 564 |
|
| 565 |
func TestMultipleUsersConfig(t *testing.T) { |
| 566 |
opts, err := ProcessConfigFile("./configs/multiple_users.conf") |
| 567 |
if err != nil { |
| 568 |
t.Fatalf("Received an error reading config file: %v", err) |
| 569 |
} |
| 570 |
setBaselineOptions(opts) |
| 571 |
} |
| 572 |
|
| 573 |
// Test highly depends on contents of the config file listed below. Any changes to that file |
| 574 |
// may very well break this test. |
| 575 |
func TestAuthorizationConfig(t *testing.T) { |
| 576 |
opts, err := ProcessConfigFile("./configs/authorization.conf") |
| 577 |
if err != nil { |
| 578 |
t.Fatalf("Received an error reading config file: %v", err) |
| 579 |
} |
| 580 |
setBaselineOptions(opts) |
| 581 |
lu := len(opts.Users) |
| 582 |
if lu != 5 { |
| 583 |
t.Fatalf("Expected 5 users, got %d", lu) |
| 584 |
} |
| 585 |
// Build a map |
| 586 |
mu := make(map[string]*User) |
| 587 |
for _, u := range opts.Users { |
| 588 |
mu[u.Username] = u |
| 589 |
} |
| 590 |
|
| 591 |
// Alice |
| 592 |
alice, ok := mu["alice"] |
| 593 |
if !ok { |
| 594 |
t.Fatalf("Expected to see user Alice") |
| 595 |
} |
| 596 |
// Check for permissions details |
| 597 |
if alice.Permissions == nil { |
| 598 |
t.Fatalf("Expected Alice's permissions to be non-nil") |
| 599 |
} |
| 600 |
if alice.Permissions.Publish == nil { |
| 601 |
t.Fatalf("Expected Alice's publish permissions to be non-nil") |
| 602 |
} |
| 603 |
if len(alice.Permissions.Publish.Allow) != 1 { |
| 604 |
t.Fatalf("Expected Alice's publish permissions to have 1 element, got %d", |
| 605 |
len(alice.Permissions.Publish.Allow)) |
| 606 |
} |
| 607 |
pubPerm := alice.Permissions.Publish.Allow[0] |
| 608 |
if pubPerm != "*" { |
| 609 |
t.Fatalf("Expected Alice's publish permissions to be '*', got %q", pubPerm) |
| 610 |
} |
| 611 |
if alice.Permissions.Subscribe == nil { |
| 612 |
t.Fatalf("Expected Alice's subscribe permissions to be non-nil") |
| 613 |
} |
| 614 |
if len(alice.Permissions.Subscribe.Allow) != 1 { |
| 615 |
t.Fatalf("Expected Alice's subscribe permissions to have 1 element, got %d", |
| 616 |
len(alice.Permissions.Subscribe.Allow)) |
| 617 |
} |
| 618 |
subPerm := alice.Permissions.Subscribe.Allow[0] |
| 619 |
if subPerm != ">" { |
| 620 |
t.Fatalf("Expected Alice's subscribe permissions to be '>', got %q", subPerm) |
| 621 |
} |
| 622 |
|
| 623 |
// Bob |
| 624 |
bob, ok := mu["bob"] |
| 625 |
if !ok { |
| 626 |
t.Fatalf("Expected to see user Bob") |
| 627 |
} |
| 628 |
if bob.Permissions == nil { |
| 629 |
t.Fatalf("Expected Bob's permissions to be non-nil") |
| 630 |
} |
| 631 |
|
| 632 |
// Susan |
| 633 |
susan, ok := mu["susan"] |
| 634 |
if !ok { |
| 635 |
t.Fatalf("Expected to see user Susan") |
| 636 |
} |
| 637 |
if susan.Permissions == nil { |
| 638 |
t.Fatalf("Expected Susan's permissions to be non-nil") |
| 639 |
} |
| 640 |
// Check susan closely since she inherited the default permissions. |
| 641 |
if susan.Permissions == nil { |
| 642 |
t.Fatalf("Expected Susan's permissions to be non-nil") |
| 643 |
} |
| 644 |
if susan.Permissions.Publish != nil { |
| 645 |
t.Fatalf("Expected Susan's publish permissions to be nil") |
| 646 |
} |
| 647 |
if susan.Permissions.Subscribe == nil { |
| 648 |
t.Fatalf("Expected Susan's subscribe permissions to be non-nil") |
| 649 |
} |
| 650 |
if len(susan.Permissions.Subscribe.Allow) != 1 { |
| 651 |
t.Fatalf("Expected Susan's subscribe permissions to have 1 element, got %d", |
| 652 |
len(susan.Permissions.Subscribe.Allow)) |
| 653 |
} |
| 654 |
subPerm = susan.Permissions.Subscribe.Allow[0] |
| 655 |
if subPerm != "PUBLIC.>" { |
| 656 |
t.Fatalf("Expected Susan's subscribe permissions to be 'PUBLIC.>', got %q", subPerm) |
| 657 |
} |
| 658 |
|
| 659 |
// Service A |
| 660 |
svca, ok := mu["svca"] |
| 661 |
if !ok { |
| 662 |
t.Fatalf("Expected to see user Service A") |
| 663 |
} |
| 664 |
if svca.Permissions == nil { |
| 665 |
t.Fatalf("Expected Service A's permissions to be non-nil") |
| 666 |
} |
| 667 |
if svca.Permissions.Subscribe == nil { |
| 668 |
t.Fatalf("Expected Service A's subscribe permissions to be non-nil") |
| 669 |
} |
| 670 |
if len(svca.Permissions.Subscribe.Allow) != 1 { |
| 671 |
t.Fatalf("Expected Service A's subscribe permissions to have 1 element, got %d", |
| 672 |
len(svca.Permissions.Subscribe.Allow)) |
| 673 |
} |
| 674 |
subPerm = svca.Permissions.Subscribe.Allow[0] |
| 675 |
if subPerm != "my.service.req" { |
| 676 |
t.Fatalf("Expected Service A's subscribe permissions to be 'my.service.req', got %q", subPerm) |
| 677 |
} |
| 678 |
// We want allow_responses to essentially set deny all, or allow none in this case. |
| 679 |
if svca.Permissions.Publish == nil { |
| 680 |
t.Fatalf("Expected Service A's publish permissions to be non-nil") |
| 681 |
} |
| 682 |
if len(svca.Permissions.Publish.Allow) != 0 { |
| 683 |
t.Fatalf("Expected Service A's publish permissions to have no elements, got %d", |
| 684 |
len(svca.Permissions.Publish.Allow)) |
| 685 |
} |
| 686 |
// We should have a ResponsePermission present with default values. |
| 687 |
if svca.Permissions.Response == nil { |
| 688 |
t.Fatalf("Expected Service A's response permissions to be non-nil") |
| 689 |
} |
| 690 |
if svca.Permissions.Response.MaxMsgs != DEFAULT_ALLOW_RESPONSE_MAX_MSGS { |
| 691 |
t.Fatalf("Expected Service A's response permissions of max msgs to be %d, got %d", |
| 692 |
DEFAULT_ALLOW_RESPONSE_MAX_MSGS, svca.Permissions.Response.MaxMsgs, |
| 693 |
) |
| 694 |
} |
| 695 |
if svca.Permissions.Response.Expires != DEFAULT_ALLOW_RESPONSE_EXPIRATION { |
| 696 |
t.Fatalf("Expected Service A's response permissions of expiration to be %v, got %v", |
| 697 |
DEFAULT_ALLOW_RESPONSE_EXPIRATION, svca.Permissions.Response.Expires, |
| 698 |
) |
| 699 |
} |
| 700 |
|
| 701 |
// Service B |
| 702 |
svcb, ok := mu["svcb"] |
| 703 |
if !ok { |
| 704 |
t.Fatalf("Expected to see user Service B") |
| 705 |
} |
| 706 |
if svcb.Permissions == nil { |
| 707 |
t.Fatalf("Expected Service B's permissions to be non-nil") |
| 708 |
} |
| 709 |
if svcb.Permissions.Subscribe == nil { |
| 710 |
t.Fatalf("Expected Service B's subscribe permissions to be non-nil") |
| 711 |
} |
| 712 |
if len(svcb.Permissions.Subscribe.Allow) != 1 { |
| 713 |
t.Fatalf("Expected Service B's subscribe permissions to have 1 element, got %d", |
| 714 |
len(svcb.Permissions.Subscribe.Allow)) |
| 715 |
} |
| 716 |
subPerm = svcb.Permissions.Subscribe.Allow[0] |
| 717 |
if subPerm != "my.service.req" { |
| 718 |
t.Fatalf("Expected Service B's subscribe permissions to be 'my.service.req', got %q", subPerm) |
| 719 |
} |
| 720 |
// We want allow_responses to essentially set deny all, or allow none in this case. |
| 721 |
if svcb.Permissions.Publish == nil { |
| 722 |
t.Fatalf("Expected Service B's publish permissions to be non-nil") |
| 723 |
} |
| 724 |
if len(svcb.Permissions.Publish.Allow) != 0 { |
| 725 |
t.Fatalf("Expected Service B's publish permissions to have no elements, got %d", |
| 726 |
len(svcb.Permissions.Publish.Allow)) |
| 727 |
} |
| 728 |
// We should have a ResponsePermission present with default values. |
| 729 |
if svcb.Permissions.Response == nil { |
| 730 |
t.Fatalf("Expected Service B's response permissions to be non-nil") |
| 731 |
} |
| 732 |
if svcb.Permissions.Response.MaxMsgs != 10 { |
| 733 |
t.Fatalf("Expected Service B's response permissions of max msgs to be %d, got %d", |
| 734 |
10, svcb.Permissions.Response.MaxMsgs, |
| 735 |
) |
| 736 |
} |
| 737 |
if svcb.Permissions.Response.Expires != time.Minute { |
| 738 |
t.Fatalf("Expected Service B's response permissions of expiration to be %v, got %v", |
| 739 |
time.Minute, svcb.Permissions.Response.Expires, |
| 740 |
) |
| 741 |
} |
| 742 |
} |
| 743 |
|
| 744 |
// Test highly depends on contents of the config file listed below. Any changes to that file |
| 745 |
// may very well break this test. |
| 746 |
func TestNewStyleAuthorizationConfig(t *testing.T) { |
| 747 |
opts, err := ProcessConfigFile("./configs/new_style_authorization.conf") |
| 748 |
if err != nil { |
| 749 |
t.Fatalf("Received an error reading config file: %v", err) |
| 750 |
} |
| 751 |
setBaselineOptions(opts) |
| 752 |
|
| 753 |
lu := len(opts.Users) |
| 754 |
if lu != 2 { |
| 755 |
t.Fatalf("Expected 2 users, got %d", lu) |
| 756 |
} |
| 757 |
// Build a map |
| 758 |
mu := make(map[string]*User) |
| 759 |
for _, u := range opts.Users { |
| 760 |
mu[u.Username] = u |
| 761 |
} |
| 762 |
// Alice |
| 763 |
alice, ok := mu["alice"] |
| 764 |
if !ok { |
| 765 |
t.Fatalf("Expected to see user Alice") |
| 766 |
} |
| 767 |
if alice.Permissions == nil { |
| 768 |
t.Fatalf("Expected Alice's permissions to be non-nil") |
| 769 |
} |
| 770 |
|
| 771 |
if alice.Permissions.Publish == nil { |
| 772 |
t.Fatalf("Expected Alice's publish permissions to be non-nil") |
| 773 |
} |
| 774 |
if len(alice.Permissions.Publish.Allow) != 3 { |
| 775 |
t.Fatalf("Expected Alice's allowed publish permissions to have 3 elements, got %d", |
| 776 |
len(alice.Permissions.Publish.Allow)) |
| 777 |
} |
| 778 |
pubPerm := alice.Permissions.Publish.Allow[0] |
| 779 |
if pubPerm != "foo" { |
| 780 |
t.Fatalf("Expected Alice's first allowed publish permission to be 'foo', got %q", pubPerm) |
| 781 |
} |
| 782 |
pubPerm = alice.Permissions.Publish.Allow[1] |
| 783 |
if pubPerm != "bar" { |
| 784 |
t.Fatalf("Expected Alice's second allowed publish permission to be 'bar', got %q", pubPerm) |
| 785 |
} |
| 786 |
pubPerm = alice.Permissions.Publish.Allow[2] |
| 787 |
if pubPerm != "baz" { |
| 788 |
t.Fatalf("Expected Alice's third allowed publish permission to be 'baz', got %q", pubPerm) |
| 789 |
} |
| 790 |
if len(alice.Permissions.Publish.Deny) != 0 { |
| 791 |
t.Fatalf("Expected Alice's denied publish permissions to have 0 elements, got %d", |
| 792 |
len(alice.Permissions.Publish.Deny)) |
| 793 |
} |
| 794 |
|
| 795 |
if alice.Permissions.Subscribe == nil { |
| 796 |
t.Fatalf("Expected Alice's subscribe permissions to be non-nil") |
| 797 |
} |
| 798 |
if len(alice.Permissions.Subscribe.Allow) != 0 { |
| 799 |
t.Fatalf("Expected Alice's allowed subscribe permissions to have 0 elements, got %d", |
| 800 |
len(alice.Permissions.Subscribe.Allow)) |
| 801 |
} |
| 802 |
if len(alice.Permissions.Subscribe.Deny) != 1 { |
| 803 |
t.Fatalf("Expected Alice's denied subscribe permissions to have 1 element, got %d", |
| 804 |
len(alice.Permissions.Subscribe.Deny)) |
| 805 |
} |
| 806 |
subPerm := alice.Permissions.Subscribe.Deny[0] |
| 807 |
if subPerm != "$SYS.>" { |
| 808 |
t.Fatalf("Expected Alice's only denied subscribe permission to be '$SYS.>', got %q", subPerm) |
| 809 |
} |
| 810 |
|
| 811 |
// Bob |
| 812 |
bob, ok := mu["bob"] |
| 813 |
if !ok { |
| 814 |
t.Fatalf("Expected to see user Bob") |
| 815 |
} |
| 816 |
if bob.Permissions == nil { |
| 817 |
t.Fatalf("Expected Bob's permissions to be non-nil") |
| 818 |
} |
| 819 |
|
| 820 |
if bob.Permissions.Publish == nil { |
| 821 |
t.Fatalf("Expected Bobs's publish permissions to be non-nil") |
| 822 |
} |
| 823 |
if len(bob.Permissions.Publish.Allow) != 1 { |
| 824 |
t.Fatalf("Expected Bob's allowed publish permissions to have 1 element, got %d", |
| 825 |
len(bob.Permissions.Publish.Allow)) |
| 826 |
} |
| 827 |
pubPerm = bob.Permissions.Publish.Allow[0] |
| 828 |
if pubPerm != "$SYS.>" { |
| 829 |
t.Fatalf("Expected Bob's first allowed publish permission to be '$SYS.>', got %q", pubPerm) |
| 830 |
} |
| 831 |
if len(bob.Permissions.Publish.Deny) != 0 { |
| 832 |
t.Fatalf("Expected Bob's denied publish permissions to have 0 elements, got %d", |
| 833 |
len(bob.Permissions.Publish.Deny)) |
| 834 |
} |
| 835 |
|
| 836 |
if bob.Permissions.Subscribe == nil { |
| 837 |
t.Fatalf("Expected Bob's subscribe permissions to be non-nil") |
| 838 |
} |
| 839 |
if len(bob.Permissions.Subscribe.Allow) != 0 { |
| 840 |
t.Fatalf("Expected Bob's allowed subscribe permissions to have 0 elements, got %d", |
| 841 |
len(bob.Permissions.Subscribe.Allow)) |
| 842 |
} |
| 843 |
if len(bob.Permissions.Subscribe.Deny) != 3 { |
| 844 |
t.Fatalf("Expected Bobs's denied subscribe permissions to have 3 elements, got %d", |
| 845 |
len(bob.Permissions.Subscribe.Deny)) |
| 846 |
} |
| 847 |
subPerm = bob.Permissions.Subscribe.Deny[0] |
| 848 |
if subPerm != "foo" { |
| 849 |
t.Fatalf("Expected Bobs's first denied subscribe permission to be 'foo', got %q", subPerm) |
| 850 |
} |
| 851 |
subPerm = bob.Permissions.Subscribe.Deny[1] |
| 852 |
if subPerm != "bar" { |
| 853 |
t.Fatalf("Expected Bobs's second denied subscribe permission to be 'bar', got %q", subPerm) |
| 854 |
} |
| 855 |
subPerm = bob.Permissions.Subscribe.Deny[2] |
| 856 |
if subPerm != "baz" { |
| 857 |
t.Fatalf("Expected Bobs's third denied subscribe permission to be 'baz', got %q", subPerm) |
| 858 |
} |
| 859 |
} |
| 860 |
|
| 861 |
// Test new nkey users |
| 862 |
func TestNkeyUsersConfig(t *testing.T) { |
| 863 |
confFileName := createConfFile(t, []byte(` |
| 864 |
authorization { |
| 865 |
users = [ |
| 866 |
{nkey: "UDKTV7HZVYJFJN64LLMYQBUR6MTNNYCDC3LAZH4VHURW3GZLL3FULBXV"} |
| 867 |
{nkey: "UA3C5TBZYK5GJQJRWPMU6NFY5JNAEVQB2V2TUZFZDHFJFUYVKTTUOFKZ"} |
| 868 |
] |
| 869 |
}`)) |
| 870 |
opts, err := ProcessConfigFile(confFileName) |
| 871 |
if err != nil { |
| 872 |
t.Fatalf("Received an error reading config file: %v", err) |
| 873 |
} |
| 874 |
lu := len(opts.Nkeys) |
| 875 |
if lu != 2 { |
| 876 |
t.Fatalf("Expected 2 nkey users, got %d", lu) |
| 877 |
} |
| 878 |
} |
| 879 |
|
| 880 |
// Test pinned certificates |
| 881 |
func TestTlsPinnedCertificates(t *testing.T) { |
| 882 |
confFileName := createConfFile(t, []byte(` |
| 883 |
tls { |
| 884 |
cert_file: "./configs/certs/server.pem" |
| 885 |
key_file: "./configs/certs/key.pem" |
| 886 |
# Require a client certificate and map user id from certificate |
| 887 |
verify: true |
| 888 |
pinned_certs: ["7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", |
| 889 |
"a8f407340dcc719864214b85ed96f98d16cbffa8f509d9fa4ca237b7bb3f9c32"] |
| 890 |
} |
| 891 |
cluster { |
| 892 |
port -1 |
| 893 |
name cluster-hub |
| 894 |
tls { |
| 895 |
cert_file: "./configs/certs/server.pem" |
| 896 |
key_file: "./configs/certs/key.pem" |
| 897 |
# Require a client certificate and map user id from certificate |
| 898 |
verify: true |
| 899 |
pinned_certs: ["7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", |
| 900 |
"a8f407340dcc719864214b85ed96f98d16cbffa8f509d9fa4ca237b7bb3f9c32"] |
| 901 |
} |
| 902 |
} |
| 903 |
leafnodes { |
| 904 |
port -1 |
| 905 |
tls { |
| 906 |
cert_file: "./configs/certs/server.pem" |
| 907 |
key_file: "./configs/certs/key.pem" |
| 908 |
# Require a client certificate and map user id from certificate |
| 909 |
verify: true |
| 910 |
pinned_certs: ["7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", |
| 911 |
"a8f407340dcc719864214b85ed96f98d16cbffa8f509d9fa4ca237b7bb3f9c32"] |
| 912 |
} |
| 913 |
} |
| 914 |
gateway { |
| 915 |
name: "A" |
| 916 |
port -1 |
| 917 |
tls { |
| 918 |
cert_file: "./configs/certs/server.pem" |
| 919 |
key_file: "./configs/certs/key.pem" |
| 920 |
# Require a client certificate and map user id from certificate |
| 921 |
verify: true |
| 922 |
pinned_certs: ["7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", |
| 923 |
"a8f407340dcc719864214b85ed96f98d16cbffa8f509d9fa4ca237b7bb3f9c32"] |
| 924 |
} |
| 925 |
} |
| 926 |
websocket { |
| 927 |
port -1 |
| 928 |
tls { |
| 929 |
cert_file: "./configs/certs/server.pem" |
| 930 |
key_file: "./configs/certs/key.pem" |
| 931 |
# Require a client certificate and map user id from certificate |
| 932 |
verify: true |
| 933 |
pinned_certs: ["7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", |
| 934 |
"a8f407340dcc719864214b85ed96f98d16cbffa8f509d9fa4ca237b7bb3f9c32"] |
| 935 |
} |
| 936 |
} |
| 937 |
mqtt { |
| 938 |
port -1 |
| 939 |
tls { |
| 940 |
cert_file: "./configs/certs/server.pem" |
| 941 |
key_file: "./configs/certs/key.pem" |
| 942 |
# Require a client certificate and map user id from certificate |
| 943 |
verify: true |
| 944 |
pinned_certs: ["7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069", |
| 945 |
"a8f407340dcc719864214b85ed96f98d16cbffa8f509d9fa4ca237b7bb3f9c32"] |
| 946 |
} |
| 947 |
}`)) |
| 948 |
opts, err := ProcessConfigFile(confFileName) |
| 949 |
if err != nil { |
| 950 |
t.Fatalf("Received an error reading config file: %v", err) |
| 951 |
} |
| 952 |
check := func(set PinnedCertSet) { |
| 953 |
t.Helper() |
| 954 |
if l := len(set); l != 2 { |
| 955 |
t.Fatalf("Expected 2 pinned certificates, got got %d", l) |
| 956 |
} |
| 957 |
} |
| 958 |
|
| 959 |
check(opts.TLSPinnedCerts) |
| 960 |
check(opts.LeafNode.TLSPinnedCerts) |
| 961 |
check(opts.Cluster.TLSPinnedCerts) |
| 962 |
check(opts.MQTT.TLSPinnedCerts) |
| 963 |
check(opts.Gateway.TLSPinnedCerts) |
| 964 |
check(opts.Websocket.TLSPinnedCerts) |
| 965 |
} |
| 966 |
|
| 967 |
func TestNkeyUsersDefaultPermissionsConfig(t *testing.T) { |
| 968 |
confFileName := createConfFile(t, []byte(` |
| 969 |
authorization { |
| 970 |
default_permissions = { |
| 971 |
publish = "foo" |
| 972 |
} |
| 973 |
users = [ |
| 974 |
{ user: "user", password: "pwd"} |
| 975 |
{ user: "other", password: "pwd", |
| 976 |
permissions = { |
| 977 |
subscribe = "bar" |
| 978 |
} |
| 979 |
} |
| 980 |
{ nkey: "UDKTV7HZVYJFJN64LLMYQBUR6MTNNYCDC3LAZH4VHURW3GZLL3FULBXV" } |
| 981 |
{ nkey: "UA3C5TBZYK5GJQJRWPMU6NFY5JNAEVQB2V2TUZFZDHFJFUYVKTTUOFKZ", |
| 982 |
permissions = { |
| 983 |
subscribe = "bar" |
| 984 |
} |
| 985 |
} |
| 986 |
] |
| 987 |
} |
| 988 |
accounts { |
| 989 |
A { |
| 990 |
default_permissions = { |
| 991 |
publish = "foo" |
| 992 |
} |
| 993 |
users = [ |
| 994 |
{ user: "accuser", password: "pwd"} |
| 995 |
{ user: "accother", password: "pwd", |
| 996 |
permissions = { |
| 997 |
subscribe = "bar" |
| 998 |
} |
| 999 |
} |
| 1000 |
{ nkey: "UC4YEYJHYKTU4LHROX7UEKEIO5RP5OUWDYXELHWXZOQHZYXHUD44LCRS" } |
| 1001 |
{ nkey: "UDLSDF4UY3YW7JJQCYE6T2D4KFDCH6RGF3R65KHK247G3POJPI27VMQ3", |
| 1002 |
permissions = { |
| 1003 |
subscribe = "bar" |
| 1004 |
} |
| 1005 |
} |
| 1006 |
] |
| 1007 |
} |
| 1008 |
} |
| 1009 |
`)) |
| 1010 |
checkPerms := func(permsDef *Permissions, permsNonDef *Permissions) { |
| 1011 |
if permsDef.Publish.Allow[0] != "foo" { |
| 1012 |
t.Fatal("Publish allow foo missing") |
| 1013 |
} else if permsDef.Subscribe != nil { |
| 1014 |
t.Fatal("Has unexpected Subscribe permission") |
| 1015 |
} else if permsNonDef.Subscribe.Allow[0] != "bar" { |
| 1016 |
t.Fatal("Subscribe allow bar missing") |
| 1017 |
} else if permsNonDef.Publish != nil { |
| 1018 |
t.Fatal("Has unexpected Publish permission") |
| 1019 |
} |
| 1020 |
} |
| 1021 |
opts, err := ProcessConfigFile(confFileName) |
| 1022 |
if err != nil { |
| 1023 |
t.Fatalf("Received an error reading config file: %v", err) |
| 1024 |
} |
| 1025 |
|
| 1026 |
findUsers := func(u1, u2 string) (found []*User) { |
| 1027 |
find := []string{u1, u2} |
| 1028 |
for _, f := range find { |
| 1029 |
for _, u := range opts.Users { |
| 1030 |
if u.Username == f { |
| 1031 |
found = append(found, u) |
| 1032 |
break |
| 1033 |
} |
| 1034 |
} |
| 1035 |
} |
| 1036 |
return |
| 1037 |
} |
| 1038 |
|
| 1039 |
findNkeyUsers := func(nk1, nk2 string) (found []*NkeyUser) { |
| 1040 |
find := []string{nk1, nk2} |
| 1041 |
for _, f := range find { |
| 1042 |
for _, u := range opts.Nkeys { |
| 1043 |
if strings.HasPrefix(u.Nkey, f) { |
| 1044 |
found = append(found, u) |
| 1045 |
break |
| 1046 |
} |
| 1047 |
} |
| 1048 |
} |
| 1049 |
return |
| 1050 |
} |
| 1051 |
|
| 1052 |
if lu := len(opts.Users); lu != 4 { |
| 1053 |
t.Fatalf("Expected 4 nkey users, got %d", lu) |
| 1054 |
} |
| 1055 |
foundU := findUsers("user", "other") |
| 1056 |
checkPerms(foundU[0].Permissions, foundU[1].Permissions) |
| 1057 |
foundU = findUsers("accuser", "accother") |
| 1058 |
checkPerms(foundU[0].Permissions, foundU[1].Permissions) |
| 1059 |
|
| 1060 |
if lu := len(opts.Nkeys); lu != 4 { |
| 1061 |
t.Fatalf("Expected 4 nkey users, got %d", lu) |
| 1062 |
} |
| 1063 |
foundNk := findNkeyUsers("UDK", "UA3") |
| 1064 |
checkPerms(foundNk[0].Permissions, foundNk[1].Permissions) |
| 1065 |
foundNk = findNkeyUsers("UC4", "UDL") |
| 1066 |
checkPerms(foundNk[0].Permissions, foundNk[1].Permissions) |
| 1067 |
} |
| 1068 |
|
| 1069 |
func TestNkeyUsersWithPermsConfig(t *testing.T) { |
| 1070 |
confFileName := createConfFile(t, []byte(` |
| 1071 |
authorization { |
| 1072 |
users = [ |
| 1073 |
{nkey: "UDKTV7HZVYJFJN64LLMYQBUR6MTNNYCDC3LAZH4VHURW3GZLL3FULBXV", |
| 1074 |
permissions = { |
| 1075 |
publish = "$SYS.>" |
| 1076 |
subscribe = { deny = ["foo", "bar", "baz"] } |
| 1077 |
} |
| 1078 |
} |
| 1079 |
] |
| 1080 |
}`)) |
| 1081 |
opts, err := ProcessConfigFile(confFileName) |
| 1082 |
if err != nil { |
| 1083 |
t.Fatalf("Received an error reading config file: %v", err) |
| 1084 |
} |
| 1085 |
lu := len(opts.Nkeys) |
| 1086 |
if lu != 1 { |
| 1087 |
t.Fatalf("Expected 1 nkey user, got %d", lu) |
| 1088 |
} |
| 1089 |
nk := opts.Nkeys[0] |
| 1090 |
if nk.Permissions == nil { |
| 1091 |
t.Fatal("Expected to have permissions") |
| 1092 |
} |
| 1093 |
if nk.Permissions.Publish == nil { |
| 1094 |
t.Fatal("Expected to have publish permissions") |
| 1095 |
} |
| 1096 |
if nk.Permissions.Publish.Allow[0] != "$SYS.>" { |
| 1097 |
t.Fatalf("Expected publish to allow \"$SYS.>\", but got %v", nk.Permissions.Publish.Allow[0]) |
| 1098 |
} |
| 1099 |
if nk.Permissions.Subscribe == nil { |
| 1100 |
t.Fatal("Expected to have subscribe permissions") |
| 1101 |
} |
| 1102 |
if nk.Permissions.Subscribe.Allow != nil { |
| 1103 |
t.Fatal("Expected to have no subscribe allow permissions") |
| 1104 |
} |
| 1105 |
deny := nk.Permissions.Subscribe.Deny |
| 1106 |
if deny == nil || len(deny) != 3 || |
| 1107 |
deny[0] != "foo" || deny[1] != "bar" || deny[2] != "baz" { |
| 1108 |
t.Fatalf("Expected to have subscribe deny permissions, got %v", deny) |
| 1109 |
} |
| 1110 |
} |
| 1111 |
|
| 1112 |
func TestBadNkeyConfig(t *testing.T) { |
| 1113 |
confFileName := "nkeys_bad.conf" |
| 1114 |
content := ` |
| 1115 |
authorization { |
| 1116 |
users = [ {nkey: "Ufoo"}] |
| 1117 |
}` |
| 1118 |
if err := os.WriteFile(confFileName, []byte(content), 0666); err != nil { |
| 1119 |
t.Fatalf("Error writing config file: %v", err) |
| 1120 |
} |
| 1121 |
defer removeFile(t, confFileName) |
| 1122 |
if _, err := ProcessConfigFile(confFileName); err == nil { |
| 1123 |
t.Fatalf("Expected an error from nkey entry with password") |
| 1124 |
} |
| 1125 |
} |
| 1126 |
|
| 1127 |
func TestNkeyWithPassConfig(t *testing.T) { |
| 1128 |
confFileName := "nkeys_pass.conf" |
| 1129 |
content := ` |
| 1130 |
authorization { |
| 1131 |
users = [ |
| 1132 |
{nkey: "UDKTV7HZVYJFJN64LLMYQBUR6MTNNYCDC3LAZH4VHURW3GZLL3FULBXV", pass: "foo"} |
| 1133 |
] |
| 1134 |
}` |
| 1135 |
if err := os.WriteFile(confFileName, []byte(content), 0666); err != nil { |
| 1136 |
t.Fatalf("Error writing config file: %v", err) |
| 1137 |
} |
| 1138 |
defer removeFile(t, confFileName) |
| 1139 |
if _, err := ProcessConfigFile(confFileName); err == nil { |
| 1140 |
t.Fatalf("Expected an error from bad nkey entry") |
| 1141 |
} |
| 1142 |
} |
| 1143 |
|
| 1144 |
func TestTokenWithUserPass(t *testing.T) { |
| 1145 |
confFileName := "test.conf" |
| 1146 |
content := ` |
| 1147 |
authorization={ |
| 1148 |
user: user |
| 1149 |
pass: password |
| 1150 |
token: $2a$11$whatever |
| 1151 |
}` |
| 1152 |
if err := os.WriteFile(confFileName, []byte(content), 0666); err != nil { |
| 1153 |
t.Fatalf("Error writing config file: %v", err) |
| 1154 |
} |
| 1155 |
defer removeFile(t, confFileName) |
| 1156 |
_, err := ProcessConfigFile(confFileName) |
| 1157 |
if err == nil { |
| 1158 |
t.Fatal("Expected error, got none") |
| 1159 |
} |
| 1160 |
if !strings.Contains(err.Error(), "token") { |
| 1161 |
t.Fatalf("Expected error related to token, got %v", err) |
| 1162 |
} |
| 1163 |
} |
| 1164 |
|
| 1165 |
func TestTokenWithUsers(t *testing.T) { |
| 1166 |
confFileName := "test.conf" |
| 1167 |
content := ` |
| 1168 |
authorization={ |
| 1169 |
token: $2a$11$whatever |
| 1170 |
users: [ |
| 1171 |
{user: test, password: test} |
| 1172 |
] |
| 1173 |
}` |
| 1174 |
if err := os.WriteFile(confFileName, []byte(content), 0666); err != nil { |
| 1175 |
t.Fatalf("Error writing config file: %v", err) |
| 1176 |
} |
| 1177 |
defer removeFile(t, confFileName) |
| 1178 |
_, err := ProcessConfigFile(confFileName) |
| 1179 |
if err == nil { |
| 1180 |
t.Fatal("Expected error, got none") |
| 1181 |
} |
| 1182 |
if !strings.Contains(err.Error(), "token") { |
| 1183 |
t.Fatalf("Expected error related to token, got %v", err) |
| 1184 |
} |
| 1185 |
} |
| 1186 |
|
| 1187 |
func TestParseWriteDeadline(t *testing.T) { |
| 1188 |
confFile := createConfFile(t, []byte("write_deadline: \"1x\"")) |
| 1189 |
_, err := ProcessConfigFile(confFile) |
| 1190 |
if err == nil { |
| 1191 |
t.Fatal("Expected error, got none") |
| 1192 |
} |
| 1193 |
if !strings.Contains(err.Error(), "parsing") { |
| 1194 |
t.Fatalf("Expected error related to parsing, got %v", err) |
| 1195 |
} |
| 1196 |
confFile = createConfFile(t, []byte("write_deadline: \"1s\"")) |
| 1197 |
opts, err := ProcessConfigFile(confFile) |
| 1198 |
if err != nil { |
| 1199 |
t.Fatalf("Unexpected error: %v", err) |
| 1200 |
} |
| 1201 |
if opts.WriteDeadline != time.Second { |
| 1202 |
t.Fatalf("Expected write_deadline to be 1s, got %v", opts.WriteDeadline) |
| 1203 |
} |
| 1204 |
oldStdout := os.Stdout |
| 1205 |
_, w, _ := os.Pipe() |
| 1206 |
defer func() { |
| 1207 |
w.Close() |
| 1208 |
os.Stdout = oldStdout |
| 1209 |
}() |
| 1210 |
os.Stdout = w |
| 1211 |
confFile = createConfFile(t, []byte("write_deadline: 2")) |
| 1212 |
opts, err = ProcessConfigFile(confFile) |
| 1213 |
if err != nil { |
| 1214 |
t.Fatalf("Unexpected error: %v", err) |
| 1215 |
} |
| 1216 |
if opts.WriteDeadline != 2*time.Second { |
| 1217 |
t.Fatalf("Expected write_deadline to be 2s, got %v", opts.WriteDeadline) |
| 1218 |
} |
| 1219 |
} |
| 1220 |
|
| 1221 |
func TestOptionsClone(t *testing.T) { |
| 1222 |
opts := &Options{ |
| 1223 |
ConfigFile: "./configs/test.conf", |
| 1224 |
Host: "127.0.0.1", |
| 1225 |
Port: 2222, |
| 1226 |
Username: "derek", |
| 1227 |
Password: "porkchop", |
| 1228 |
AuthTimeout: 1.0, |
| 1229 |
Debug: true, |
| 1230 |
Trace: true, |
| 1231 |
Logtime: false, |
| 1232 |
HTTPPort: DEFAULT_HTTP_PORT, |
| 1233 |
HTTPBasePath: DEFAULT_HTTP_BASE_PATH, |
| 1234 |
PidFile: "/tmp/nats-server/nats-server.pid", |
| 1235 |
ProfPort: 6789, |
| 1236 |
Syslog: true, |
| 1237 |
RemoteSyslog: "udp://foo.com:33", |
| 1238 |
MaxControlLine: 2048, |
| 1239 |
MaxPayload: 65536, |
| 1240 |
MaxConn: 100, |
| 1241 |
PingInterval: 60 * time.Second, |
| 1242 |
MaxPingsOut: 3, |
| 1243 |
Cluster: ClusterOpts{ |
| 1244 |
NoAdvertise: true, |
| 1245 |
ConnectRetries: 2, |
| 1246 |
WriteDeadline: 3 * time.Second, |
| 1247 |
}, |
| 1248 |
Gateway: GatewayOpts{ |
| 1249 |
Name: "A", |
| 1250 |
Gateways: []*RemoteGatewayOpts{ |
| 1251 |
{Name: "B", URLs: []*url.URL{{Scheme: "nats", Host: "host:5222"}}}, |
| 1252 |
{Name: "C"}, |
| 1253 |
}, |
| 1254 |
}, |
| 1255 |
WriteDeadline: 3 * time.Second, |
| 1256 |
Routes: []*url.URL{{}}, |
| 1257 |
Users: []*User{{Username: "foo", Password: "bar"}}, |
| 1258 |
} |
| 1259 |
|
| 1260 |
clone := opts.Clone() |
| 1261 |
|
| 1262 |
if !reflect.DeepEqual(opts, clone) { |
| 1263 |
t.Fatalf("Cloned Options are incorrect.\nexpected: %+v\ngot: %+v", |
| 1264 |
clone, opts) |
| 1265 |
} |
| 1266 |
|
| 1267 |
clone.Users[0].Password = "baz" |
| 1268 |
if reflect.DeepEqual(opts, clone) { |
| 1269 |
t.Fatal("Expected Options to be different") |
| 1270 |
} |
| 1271 |
|
| 1272 |
opts.Gateway.Gateways[0].URLs[0] = nil |
| 1273 |
if reflect.DeepEqual(opts.Gateway.Gateways[0], clone.Gateway.Gateways[0]) { |
| 1274 |
t.Fatal("Expected Options to be different") |
| 1275 |
} |
| 1276 |
if clone.Gateway.Gateways[0].URLs[0].Host != "host:5222" { |
| 1277 |
t.Fatalf("Unexpected URL: %v", clone.Gateway.Gateways[0].URLs[0]) |
| 1278 |
} |
| 1279 |
} |
| 1280 |
|
| 1281 |
func TestOptionsCloneNilLists(t *testing.T) { |
| 1282 |
opts := &Options{} |
| 1283 |
|
| 1284 |
clone := opts.Clone() |
| 1285 |
|
| 1286 |
if clone.Routes != nil { |
| 1287 |
t.Fatalf("Expected Routes to be nil, got: %v", clone.Routes) |
| 1288 |
} |
| 1289 |
if clone.Users != nil { |
| 1290 |
t.Fatalf("Expected Users to be nil, got: %v", clone.Users) |
| 1291 |
} |
| 1292 |
} |
| 1293 |
|
| 1294 |
func TestOptionsCloneNil(t *testing.T) { |
| 1295 |
opts := (*Options)(nil) |
| 1296 |
clone := opts.Clone() |
| 1297 |
if clone != nil { |
| 1298 |
t.Fatalf("Expected nil, got: %+v", clone) |
| 1299 |
} |
| 1300 |
} |
| 1301 |
|
| 1302 |
func TestEmptyConfig(t *testing.T) { |
| 1303 |
opts, err := ProcessConfigFile("") |
| 1304 |
|
| 1305 |
if err != nil { |
| 1306 |
t.Fatalf("Expected no error from empty config, got: %+v", err) |
| 1307 |
} |
| 1308 |
|
| 1309 |
if opts.ConfigFile != "" { |
| 1310 |
t.Fatalf("Expected empty config, got: %+v", opts) |
| 1311 |
} |
| 1312 |
} |
| 1313 |
|
| 1314 |
func TestMalformedListenAddress(t *testing.T) { |
| 1315 |
opts, err := ProcessConfigFile("./configs/malformed_listen_address.conf") |
| 1316 |
if err == nil { |
| 1317 |
t.Fatalf("Expected an error reading config file: got %+v", opts) |
| 1318 |
} |
| 1319 |
} |
| 1320 |
|
| 1321 |
func TestMalformedClusterAddress(t *testing.T) { |
| 1322 |
opts, err := ProcessConfigFile("./configs/malformed_cluster_address.conf") |
| 1323 |
if err == nil { |
| 1324 |
t.Fatalf("Expected an error reading config file: got %+v", opts) |
| 1325 |
} |
| 1326 |
} |
| 1327 |
|
| 1328 |
func TestPanic(t *testing.T) { |
| 1329 |
conf := createConfFile(t, []byte(`port: "this_string_trips_a_panic"`)) |
| 1330 |
opts, err := ProcessConfigFile(conf) |
| 1331 |
if err == nil { |
| 1332 |
t.Fatalf("Expected an error reading config file: got %+v", opts) |
| 1333 |
} else { |
| 1334 |
if !strings.Contains(err.Error(), ":1:0: interface conversion:") { |
| 1335 |
t.Fatalf("This was supposed to trip a panic on interface conversion right at the beginning") |
| 1336 |
} |
| 1337 |
} |
| 1338 |
} |
| 1339 |
|
| 1340 |
func TestMaxClosedClients(t *testing.T) { |
| 1341 |
conf := createConfFile(t, []byte(`max_closed_clients: 5`)) |
| 1342 |
opts, err := ProcessConfigFile(conf) |
| 1343 |
require_NoError(t, err) |
| 1344 |
require_Equal(t, opts.MaxClosedClients, 5) |
| 1345 |
} |
| 1346 |
|
| 1347 |
func TestPingIntervalOld(t *testing.T) { |
| 1348 |
conf := createConfFile(t, []byte(`ping_interval: 5`)) |
| 1349 |
opts := &Options{} |
| 1350 |
err := opts.ProcessConfigFile(conf) |
| 1351 |
if err == nil { |
| 1352 |
t.Fatalf("expected an error") |
| 1353 |
} |
| 1354 |
errTyped, ok := err.(*processConfigErr) |
| 1355 |
if !ok { |
| 1356 |
t.Fatalf("expected an error of type processConfigErr") |
| 1357 |
} |
| 1358 |
if len(errTyped.warnings) != 1 { |
| 1359 |
t.Fatalf("expected processConfigErr to have one warning") |
| 1360 |
} |
| 1361 |
if len(errTyped.errors) != 0 { |
| 1362 |
t.Fatalf("expected processConfigErr to have no error") |
| 1363 |
} |
| 1364 |
if opts.PingInterval != 5*time.Second { |
| 1365 |
t.Fatalf("expected ping interval to be 5 seconds") |
| 1366 |
} |
| 1367 |
} |
| 1368 |
|
| 1369 |
func TestPingIntervalNew(t *testing.T) { |
| 1370 |
conf := createConfFile(t, []byte(`ping_interval: "5m"`)) |
| 1371 |
opts := &Options{} |
| 1372 |
if err := opts.ProcessConfigFile(conf); err != nil { |
| 1373 |
t.Fatalf("expected no error") |
| 1374 |
} |
| 1375 |
if opts.PingInterval != 5*time.Minute { |
| 1376 |
t.Fatalf("expected ping interval to be 5 minutes") |
| 1377 |
} |
| 1378 |
} |
| 1379 |
|
| 1380 |
func TestOptionsProcessConfigFile(t *testing.T) { |
| 1381 |
// Create options with default values of Debug and Trace |
| 1382 |
// that are the opposite of what is in the config file. |
| 1383 |
// Set another option that is not present in the config file. |
| 1384 |
logFileName := "test.log" |
| 1385 |
opts := &Options{ |
| 1386 |
Debug: true, |
| 1387 |
Trace: false, |
| 1388 |
LogFile: logFileName, |
| 1389 |
} |
| 1390 |
configFileName := "./configs/test.conf" |
| 1391 |
if err := opts.ProcessConfigFile(configFileName); err != nil { |
| 1392 |
t.Fatalf("Error processing config file: %v", err) |
| 1393 |
} |
| 1394 |
// Verify that values are as expected |
| 1395 |
if opts.ConfigFile != configFileName { |
| 1396 |
t.Fatalf("Expected ConfigFile to be set to %q, got %v", configFileName, opts.ConfigFile) |
| 1397 |
} |
| 1398 |
if opts.Debug { |
| 1399 |
t.Fatal("Debug option should have been set to false from config file") |
| 1400 |
} |
| 1401 |
if !opts.Trace { |
| 1402 |
t.Fatal("Trace option should have been set to true from config file") |
| 1403 |
} |
| 1404 |
if opts.LogFile != logFileName { |
| 1405 |
t.Fatalf("Expected LogFile to be %q, got %q", logFileName, opts.LogFile) |
| 1406 |
} |
| 1407 |
} |
| 1408 |
|
| 1409 |
func TestConfigureOptions(t *testing.T) { |
| 1410 |
// Options.Configure() will snapshot the flags. This is used by the reload code. |
| 1411 |
// We need to set it back to nil otherwise it will impact reload tests. |
| 1412 |
defer func() { FlagSnapshot = nil }() |
| 1413 |
|
| 1414 |
ch := make(chan bool, 1) |
| 1415 |
checkPrintInvoked := func() { |
| 1416 |
ch <- true |
| 1417 |
} |
| 1418 |
usage := func() { panic("should not get there") } |
| 1419 |
var fs *flag.FlagSet |
| 1420 |
type testPrint struct { |
| 1421 |
args []string |
| 1422 |
version, help, tlsHelp func() |
| 1423 |
} |
| 1424 |
testFuncs := []testPrint{ |
| 1425 |
{[]string{"-v"}, checkPrintInvoked, usage, PrintTLSHelpAndDie}, |
| 1426 |
{[]string{"version"}, checkPrintInvoked, usage, PrintTLSHelpAndDie}, |
| 1427 |
{[]string{"-h"}, PrintServerAndExit, checkPrintInvoked, PrintTLSHelpAndDie}, |
| 1428 |
{[]string{"help"}, PrintServerAndExit, checkPrintInvoked, PrintTLSHelpAndDie}, |
| 1429 |
{[]string{"-help_tls"}, PrintServerAndExit, usage, checkPrintInvoked}, |
| 1430 |
} |
| 1431 |
for _, tf := range testFuncs { |
| 1432 |
fs = flag.NewFlagSet("test", flag.ContinueOnError) |
| 1433 |
opts, err := ConfigureOptions(fs, tf.args, tf.version, tf.help, tf.tlsHelp) |
| 1434 |
if err != nil { |
| 1435 |
t.Fatalf("Error on configure: %v", err) |
| 1436 |
} |
| 1437 |
if opts != nil { |
| 1438 |
t.Fatalf("Expected options to be nil, got %v", opts) |
| 1439 |
} |
| 1440 |
select { |
| 1441 |
case <-ch: |
| 1442 |
case <-time.After(time.Second): |
| 1443 |
t.Fatalf("Should have invoked print function for args=%v", tf.args) |
| 1444 |
} |
| 1445 |
} |
| 1446 |
|
| 1447 |
// Helper function that expect parsing with given args to not produce an error. |
| 1448 |
mustNotFail := func(args []string) *Options { |
| 1449 |
fs := flag.NewFlagSet("test", flag.ContinueOnError) |
| 1450 |
opts, err := ConfigureOptions(fs, args, PrintServerAndExit, fs.Usage, PrintTLSHelpAndDie) |
| 1451 |
if err != nil { |
| 1452 |
stackFatalf(t, "Error on configure: %v", err) |
| 1453 |
} |
| 1454 |
return opts |
| 1455 |
} |
| 1456 |
|
| 1457 |
// Helper function that expect configuration to fail. |
| 1458 |
expectToFail := func(args []string, errContent ...string) { |
| 1459 |
fs := flag.NewFlagSet("test", flag.ContinueOnError) |
| 1460 |
// Silence the flagSet so that on failure nothing is printed. |
| 1461 |
// (flagSet would print error message about unknown flags, etc..) |
| 1462 |
silenceOuput := &bytes.Buffer{} |
| 1463 |
fs.SetOutput(silenceOuput) |
| 1464 |
opts, err := ConfigureOptions(fs, args, PrintServerAndExit, fs.Usage, PrintTLSHelpAndDie) |
| 1465 |
if opts != nil || err == nil { |
| 1466 |
stackFatalf(t, "Expected no option and an error, got opts=%v and err=%v", opts, err) |
| 1467 |
} |
| 1468 |
for _, testErr := range errContent { |
| 1469 |
if strings.Contains(err.Error(), testErr) { |
| 1470 |
// We got the error we wanted. |
| 1471 |
return |
| 1472 |
} |
| 1473 |
} |
| 1474 |
stackFatalf(t, "Expected errors containing any of those %v, got %v", errContent, err) |
| 1475 |
} |
| 1476 |
|
| 1477 |
// Basic test with port number |
| 1478 |
opts := mustNotFail([]string{"-p", "1234"}) |
| 1479 |
if opts.Port != 1234 { |
| 1480 |
t.Fatalf("Expected port to be 1234, got %v", opts.Port) |
| 1481 |
} |
| 1482 |
|
| 1483 |
// Should fail because of unknown parameter |
| 1484 |
expectToFail([]string{"foo"}, "command") |
| 1485 |
|
| 1486 |
// Should fail because unknown flag |
| 1487 |
expectToFail([]string{"-xxx", "foo"}, "flag") |
| 1488 |
|
| 1489 |
// Should fail because of config file missing |
| 1490 |
expectToFail([]string{"-c", "xxx.cfg"}, "file") |
| 1491 |
|
| 1492 |
// Should fail because of too many args for signal command |
| 1493 |
expectToFail([]string{"-sl", "quit=pid=foo"}, "signal") |
| 1494 |
|
| 1495 |
// Should fail because of invalid pid |
| 1496 |
// On windows, if not running with admin privileges, you would get access denied. |
| 1497 |
expectToFail([]string{"-sl", "quit=pid"}, "pid", "denied") |
| 1498 |
|
| 1499 |
// The config file set Trace to true. |
| 1500 |
opts = mustNotFail([]string{"-c", "./configs/test.conf"}) |
| 1501 |
if !opts.Trace { |
| 1502 |
t.Fatal("Trace should have been set to true") |
| 1503 |
} |
| 1504 |
|
| 1505 |
// The config file set Trace to true, but was overridden by param -V=false |
| 1506 |
opts = mustNotFail([]string{"-c", "./configs/test.conf", "-V=false"}) |
| 1507 |
if opts.Trace { |
| 1508 |
t.Fatal("Trace should have been set to false") |
| 1509 |
} |
| 1510 |
|
| 1511 |
// The config file set Trace to true, but was overridden by param -DV=false |
| 1512 |
opts = mustNotFail([]string{"-c", "./configs/test.conf", "-DV=false"}) |
| 1513 |
if opts.Debug || opts.Trace { |
| 1514 |
t.Fatal("Debug and Trace should have been set to false") |
| 1515 |
} |
| 1516 |
|
| 1517 |
// The config file set Trace to true, but was overridden by param -DV |
| 1518 |
opts = mustNotFail([]string{"-c", "./configs/test.conf", "-DV"}) |
| 1519 |
if !opts.Debug || !opts.Trace { |
| 1520 |
t.Fatal("Debug and Trace should have been set to true") |
| 1521 |
} |
| 1522 |
|
| 1523 |
// This should fail since -cluster is missing |
| 1524 |
expectedURL, _ := url.Parse("nats://127.0.0.1:6223") |
| 1525 |
expectToFail([]string{"-routes", expectedURL.String()}, "solicited routes") |
| 1526 |
|
| 1527 |
// Ensure that we can set cluster and routes from command line |
| 1528 |
opts = mustNotFail([]string{"-cluster", "nats://127.0.0.1:6222", "-routes", expectedURL.String()}) |
| 1529 |
if opts.Cluster.ListenStr != "nats://127.0.0.1:6222" { |
| 1530 |
t.Fatalf("Unexpected Cluster.ListenStr=%q", opts.Cluster.ListenStr) |
| 1531 |
} |
| 1532 |
if opts.RoutesStr != "nats://127.0.0.1:6223" || len(opts.Routes) != 1 || opts.Routes[0].String() != expectedURL.String() { |
| 1533 |
t.Fatalf("Unexpected RoutesStr: %q and Routes: %v", opts.RoutesStr, opts.Routes) |
| 1534 |
} |
| 1535 |
|
| 1536 |
// Use a config with cluster configuration and explicit route defined. |
| 1537 |
// Override with empty routes string. |
| 1538 |
opts = mustNotFail([]string{"-c", "./configs/srv_a.conf", "-routes", ""}) |
| 1539 |
if opts.RoutesStr != "" || len(opts.Routes) != 0 { |
| 1540 |
t.Fatalf("Unexpected RoutesStr: %q and Routes: %v", opts.RoutesStr, opts.Routes) |
| 1541 |
} |
| 1542 |
|
| 1543 |
// Use a config with cluster configuration and override cluster listen string |
| 1544 |
expectedURL, _ = url.Parse("nats-route://ruser:[email protected]:7246") |
| 1545 |
opts = mustNotFail([]string{"-c", "./configs/srv_a.conf", "-cluster", "nats://ivan:[email protected]:6222"}) |
| 1546 |
if opts.Cluster.Username != "ivan" || opts.Cluster.Password != "pwd" || opts.Cluster.Port != 6222 || |
| 1547 |
len(opts.Routes) != 1 || opts.Routes[0].String() != expectedURL.String() { |
| 1548 |
t.Fatalf("Unexpected Cluster and/or Routes: %#v - %v", opts.Cluster, opts.Routes) |
| 1549 |
} |
| 1550 |
|
| 1551 |
// Disable clustering from command line |
| 1552 |
opts = mustNotFail([]string{"-c", "./configs/srv_a.conf", "-cluster", ""}) |
| 1553 |
if opts.Cluster.Port != 0 { |
| 1554 |
t.Fatalf("Unexpected Cluster: %v", opts.Cluster) |
| 1555 |
} |
| 1556 |
|
| 1557 |
// Various erros due to malformed cluster listen string. |
| 1558 |
// (adding -routes to have more than 1 set flag to check |
| 1559 |
// that Visit() stops when an error is found). |
| 1560 |
expectToFail([]string{"-cluster", ":", "-routes", ""}, "protocol") |
| 1561 |
expectToFail([]string{"-cluster", "nats://127.0.0.1", "-routes", ""}, "port") |
| 1562 |
expectToFail([]string{"-cluster", "nats://127.0.0.1:xxx", "-routes", ""}, "invalid port") |
| 1563 |
expectToFail([]string{"-cluster", "nats://ivan:127.0.0.1:6222", "-routes", ""}, "colons") |
| 1564 |
expectToFail([]string{"-cluster", "nats://[email protected]:6222", "-routes", ""}, "password") |
| 1565 |
|
| 1566 |
// Override config file's TLS configuration from command line, and completely disable TLS |
| 1567 |
opts = mustNotFail([]string{"-c", "./configs/tls.conf", "-tls=false"}) |
| 1568 |
if opts.TLSConfig != nil || opts.TLS { |
| 1569 |
t.Fatal("Expected TLS to be disabled") |
| 1570 |
} |
| 1571 |
// Override config file's TLS configuration from command line, and force TLS verification. |
| 1572 |
// However, since TLS config has to be regenerated, user need to provide -tlscert and -tlskey too. |
| 1573 |
// So this should fail. |
| 1574 |
expectToFail([]string{"-c", "./configs/tls.conf", "-tlsverify"}, "valid") |
| 1575 |
|
| 1576 |
// Now same than above, but with all valid params. |
| 1577 |
opts = mustNotFail([]string{"-c", "./configs/tls.conf", "-tlsverify", "-tlscert", "./configs/certs/server.pem", "-tlskey", "./configs/certs/key.pem"}) |
| 1578 |
if opts.TLSConfig == nil || !opts.TLSVerify { |
| 1579 |
t.Fatal("Expected TLS to be configured and force verification") |
| 1580 |
} |
| 1581 |
|
| 1582 |
// Configure TLS, but some TLS params missing |
| 1583 |
expectToFail([]string{"-tls"}, "valid") |
| 1584 |
expectToFail([]string{"-tls", "-tlscert", "./configs/certs/server.pem"}, "valid") |
| 1585 |
// One of the file does not exist |
| 1586 |
expectToFail([]string{"-tls", "-tlscert", "./configs/certs/server.pem", "-tlskey", "./configs/certs/notfound.pem"}, "file") |
| 1587 |
|
| 1588 |
// Configure TLS and check that this results in a TLSConfig option. |
| 1589 |
opts = mustNotFail([]string{"-tls", "-tlscert", "./configs/certs/server.pem", "-tlskey", "./configs/certs/key.pem"}) |
| 1590 |
if opts.TLSConfig == nil || !opts.TLS { |
| 1591 |
t.Fatal("Expected TLSConfig to be set") |
| 1592 |
} |
| 1593 |
// Check that we use default TLS ciphers |
| 1594 |
if !reflect.DeepEqual(opts.TLSConfig.CipherSuites, defaultCipherSuites()) { |
| 1595 |
t.Fatalf("Default ciphers not set, expected %v, got %v", defaultCipherSuites(), opts.TLSConfig.CipherSuites) |
| 1596 |
} |
| 1597 |
} |
| 1598 |
|
| 1599 |
func TestClusterPermissionsConfig(t *testing.T) { |
| 1600 |
template := ` |
| 1601 |
cluster { |
| 1602 |
port: 1234 |
| 1603 |
%s |
| 1604 |
authorization { |
| 1605 |
user: ivan |
| 1606 |
password: pwd |
| 1607 |
permissions { |
| 1608 |
import { |
| 1609 |
allow: "foo" |
| 1610 |
} |
| 1611 |
export { |
| 1612 |
allow: "bar" |
| 1613 |
} |
| 1614 |
} |
| 1615 |
} |
| 1616 |
} |
| 1617 |
` |
| 1618 |
conf := createConfFile(t, []byte(fmt.Sprintf(template, ""))) |
| 1619 |
opts, err := ProcessConfigFile(conf) |
| 1620 |
if err != nil { |
| 1621 |
if cerr, ok := err.(*processConfigErr); ok && len(cerr.Errors()) > 0 { |
| 1622 |
t.Fatalf("Error processing config file: %v", err) |
| 1623 |
} |
| 1624 |
} |
| 1625 |
if opts.Cluster.Permissions == nil { |
| 1626 |
t.Fatal("Expected cluster permissions to be set") |
| 1627 |
} |
| 1628 |
if opts.Cluster.Permissions.Import == nil { |
| 1629 |
t.Fatal("Expected cluster import permissions to be set") |
| 1630 |
} |
| 1631 |
if len(opts.Cluster.Permissions.Import.Allow) != 1 || opts.Cluster.Permissions.Import.Allow[0] != "foo" { |
| 1632 |
t.Fatalf("Expected cluster import permissions to have %q, got %v", "foo", opts.Cluster.Permissions.Import.Allow) |
| 1633 |
} |
| 1634 |
if opts.Cluster.Permissions.Export == nil { |
| 1635 |
t.Fatal("Expected cluster export permissions to be set") |
| 1636 |
} |
| 1637 |
if len(opts.Cluster.Permissions.Export.Allow) != 1 || opts.Cluster.Permissions.Export.Allow[0] != "bar" { |
| 1638 |
t.Fatalf("Expected cluster export permissions to have %q, got %v", "bar", opts.Cluster.Permissions.Export.Allow) |
| 1639 |
} |
| 1640 |
|
| 1641 |
// Now add permissions in top level cluster and check |
| 1642 |
// that this is the one that is being used. |
| 1643 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, ` |
| 1644 |
permissions { |
| 1645 |
import { |
| 1646 |
allow: "baz" |
| 1647 |
} |
| 1648 |
export { |
| 1649 |
allow: "bat" |
| 1650 |
} |
| 1651 |
} |
| 1652 |
`))) |
| 1653 |
opts, err = ProcessConfigFile(conf) |
| 1654 |
if err != nil { |
| 1655 |
t.Fatalf("Error processing config file: %v", err) |
| 1656 |
} |
| 1657 |
if opts.Cluster.Permissions == nil { |
| 1658 |
t.Fatal("Expected cluster permissions to be set") |
| 1659 |
} |
| 1660 |
if opts.Cluster.Permissions.Import == nil { |
| 1661 |
t.Fatal("Expected cluster import permissions to be set") |
| 1662 |
} |
| 1663 |
if len(opts.Cluster.Permissions.Import.Allow) != 1 || opts.Cluster.Permissions.Import.Allow[0] != "baz" { |
| 1664 |
t.Fatalf("Expected cluster import permissions to have %q, got %v", "baz", opts.Cluster.Permissions.Import.Allow) |
| 1665 |
} |
| 1666 |
if opts.Cluster.Permissions.Export == nil { |
| 1667 |
t.Fatal("Expected cluster export permissions to be set") |
| 1668 |
} |
| 1669 |
if len(opts.Cluster.Permissions.Export.Allow) != 1 || opts.Cluster.Permissions.Export.Allow[0] != "bat" { |
| 1670 |
t.Fatalf("Expected cluster export permissions to have %q, got %v", "bat", opts.Cluster.Permissions.Export.Allow) |
| 1671 |
} |
| 1672 |
|
| 1673 |
// Tests with invalid permissions |
| 1674 |
invalidPerms := []string{ |
| 1675 |
`permissions: foo`, |
| 1676 |
`permissions { |
| 1677 |
unknown_field: "foo" |
| 1678 |
}`, |
| 1679 |
`permissions { |
| 1680 |
import: [1, 2, 3] |
| 1681 |
}`, |
| 1682 |
`permissions { |
| 1683 |
import { |
| 1684 |
unknown_field: "foo" |
| 1685 |
} |
| 1686 |
}`, |
| 1687 |
`permissions { |
| 1688 |
import { |
| 1689 |
allow { |
| 1690 |
x: y |
| 1691 |
} |
| 1692 |
} |
| 1693 |
}`, |
| 1694 |
`permissions { |
| 1695 |
import { |
| 1696 |
deny { |
| 1697 |
x: y |
| 1698 |
} |
| 1699 |
} |
| 1700 |
}`, |
| 1701 |
`permissions { |
| 1702 |
export: [1, 2, 3] |
| 1703 |
}`, |
| 1704 |
`permissions { |
| 1705 |
export { |
| 1706 |
unknown_field: "foo" |
| 1707 |
} |
| 1708 |
}`, |
| 1709 |
`permissions { |
| 1710 |
export { |
| 1711 |
allow { |
| 1712 |
x: y |
| 1713 |
} |
| 1714 |
} |
| 1715 |
}`, |
| 1716 |
`permissions { |
| 1717 |
export { |
| 1718 |
deny { |
| 1719 |
x: y |
| 1720 |
} |
| 1721 |
} |
| 1722 |
}`, |
| 1723 |
} |
| 1724 |
for _, perms := range invalidPerms { |
| 1725 |
conf = createConfFile(t, []byte(fmt.Sprintf(` |
| 1726 |
cluster { |
| 1727 |
port: 1234 |
| 1728 |
%s |
| 1729 |
} |
| 1730 |
`, perms))) |
| 1731 |
_, err := ProcessConfigFile(conf) |
| 1732 |
if err == nil { |
| 1733 |
t.Fatalf("Expected failure for permissions %s", perms) |
| 1734 |
} |
| 1735 |
} |
| 1736 |
|
| 1737 |
for _, perms := range invalidPerms { |
| 1738 |
conf = createConfFile(t, []byte(fmt.Sprintf(` |
| 1739 |
cluster { |
| 1740 |
port: 1234 |
| 1741 |
authorization { |
| 1742 |
user: ivan |
| 1743 |
password: pwd |
| 1744 |
%s |
| 1745 |
} |
| 1746 |
} |
| 1747 |
`, perms))) |
| 1748 |
_, err := ProcessConfigFile(conf) |
| 1749 |
if err == nil { |
| 1750 |
t.Fatalf("Expected failure for permissions %s", perms) |
| 1751 |
} |
| 1752 |
} |
| 1753 |
} |
| 1754 |
|
| 1755 |
func TestParseServiceLatency(t *testing.T) { |
| 1756 |
cases := []struct { |
| 1757 |
name string |
| 1758 |
conf string |
| 1759 |
want *serviceLatency |
| 1760 |
wantErr bool |
| 1761 |
}{ |
| 1762 |
{ |
| 1763 |
name: "block with percent sample default value", |
| 1764 |
conf: `system_account = nats.io |
| 1765 |
accounts { |
| 1766 |
nats.io { |
| 1767 |
exports [{ |
| 1768 |
service: nats.add |
| 1769 |
latency: { |
| 1770 |
sampling: 100% |
| 1771 |
subject: latency.tracking.add |
| 1772 |
} |
| 1773 |
}] |
| 1774 |
} |
| 1775 |
}`, |
| 1776 |
want: &serviceLatency{ |
| 1777 |
subject: "latency.tracking.add", |
| 1778 |
sampling: 100, |
| 1779 |
}, |
| 1780 |
}, |
| 1781 |
{ |
| 1782 |
name: "block with percent sample nondefault value", |
| 1783 |
conf: `system_account = nats.io |
| 1784 |
accounts { |
| 1785 |
nats.io { |
| 1786 |
exports [{ |
| 1787 |
service: nats.add |
| 1788 |
latency: { |
| 1789 |
sampling: 33% |
| 1790 |
subject: latency.tracking.add |
| 1791 |
} |
| 1792 |
}] |
| 1793 |
} |
| 1794 |
}`, |
| 1795 |
want: &serviceLatency{ |
| 1796 |
subject: "latency.tracking.add", |
| 1797 |
sampling: 33, |
| 1798 |
}, |
| 1799 |
}, |
| 1800 |
{ |
| 1801 |
name: "block with number sample nondefault value", |
| 1802 |
conf: `system_account = nats.io |
| 1803 |
accounts { |
| 1804 |
nats.io { |
| 1805 |
exports [{ |
| 1806 |
service: nats.add |
| 1807 |
latency: { |
| 1808 |
sampling: 87 |
| 1809 |
subject: latency.tracking.add |
| 1810 |
} |
| 1811 |
}] |
| 1812 |
} |
| 1813 |
}`, |
| 1814 |
want: &serviceLatency{ |
| 1815 |
subject: "latency.tracking.add", |
| 1816 |
sampling: 87, |
| 1817 |
}, |
| 1818 |
}, |
| 1819 |
{ |
| 1820 |
name: "field with subject", |
| 1821 |
conf: `system_account = nats.io |
| 1822 |
accounts { |
| 1823 |
nats.io { |
| 1824 |
exports [{ |
| 1825 |
service: nats.add |
| 1826 |
latency: latency.tracking.add |
| 1827 |
}] |
| 1828 |
} |
| 1829 |
}`, |
| 1830 |
want: &serviceLatency{ |
| 1831 |
subject: "latency.tracking.add", |
| 1832 |
sampling: 100, |
| 1833 |
}, |
| 1834 |
}, |
| 1835 |
{ |
| 1836 |
name: "block with missing subject", |
| 1837 |
conf: `system_account = nats.io |
| 1838 |
accounts { |
| 1839 |
nats.io { |
| 1840 |
exports [{ |
| 1841 |
service: nats.add |
| 1842 |
latency: { |
| 1843 |
sampling: 87 |
| 1844 |
} |
| 1845 |
}] |
| 1846 |
} |
| 1847 |
}`, |
| 1848 |
wantErr: true, |
| 1849 |
}, |
| 1850 |
} |
| 1851 |
|
| 1852 |
for _, c := range cases { |
| 1853 |
t.Run(c.name, func(t *testing.T) { |
| 1854 |
f := createConfFile(t, []byte(c.conf)) |
| 1855 |
opts, err := ProcessConfigFile(f) |
| 1856 |
switch { |
| 1857 |
case c.wantErr && err == nil: |
| 1858 |
t.Fatalf("Expected ProcessConfigFile to fail, but didn't") |
| 1859 |
case c.wantErr && err != nil: |
| 1860 |
// We wanted an error and got one, test passed. |
| 1861 |
return |
| 1862 |
case !c.wantErr && err == nil: |
| 1863 |
// We didn't want an error and didn't get one, keep going. |
| 1864 |
break |
| 1865 |
case !c.wantErr && err != nil: |
| 1866 |
t.Fatalf("Failed to process config: %v", err) |
| 1867 |
} |
| 1868 |
|
| 1869 |
if len(opts.Accounts) != 1 { |
| 1870 |
t.Fatalf("Expected accounts to have len %d, got %d", 1, len(opts.Accounts)) |
| 1871 |
} |
| 1872 |
if len(opts.Accounts[0].exports.services) != 1 { |
| 1873 |
t.Fatalf("Expected export services to have len %d, got %d", 1, len(opts.Accounts[0].exports.services)) |
| 1874 |
} |
| 1875 |
s, ok := opts.Accounts[0].exports.services["nats.add"] |
| 1876 |
if !ok { |
| 1877 |
t.Fatalf("Expected export service nats.add, missing") |
| 1878 |
} |
| 1879 |
|
| 1880 |
if !reflect.DeepEqual(s.latency, c.want) { |
| 1881 |
t.Fatalf("Expected latency to be %#v, got %#v", c.want, s.latency) |
| 1882 |
} |
| 1883 |
}) |
| 1884 |
} |
| 1885 |
} |
| 1886 |
|
| 1887 |
func TestParseExport(t *testing.T) { |
| 1888 |
conf := ` |
| 1889 |
port: -1 |
| 1890 |
system_account: sys |
| 1891 |
accounts { |
| 1892 |
sys { |
| 1893 |
exports [{ |
| 1894 |
stream "$SYS.SERVER.ACCOUNT.*.CONNS" |
| 1895 |
account_token_position 4 |
| 1896 |
}] |
| 1897 |
} |
| 1898 |
accE { |
| 1899 |
exports [{ |
| 1900 |
service foo.* |
| 1901 |
account_token_position 2 |
| 1902 |
}] |
| 1903 |
users [{ |
| 1904 |
user ue |
| 1905 |
password pwd |
| 1906 |
}], |
| 1907 |
} |
| 1908 |
accI1 { |
| 1909 |
imports [{ |
| 1910 |
service { |
| 1911 |
account accE |
| 1912 |
subject foo.accI1 |
| 1913 |
} |
| 1914 |
to foo |
| 1915 |
},{ |
| 1916 |
stream { |
| 1917 |
account sys |
| 1918 |
subject "$SYS.SERVER.ACCOUNT.accI1.CONNS" |
| 1919 |
} |
| 1920 |
}], |
| 1921 |
users [{ |
| 1922 |
user u1 |
| 1923 |
password pwd |
| 1924 |
}], |
| 1925 |
} |
| 1926 |
accI2 { |
| 1927 |
imports [{ |
| 1928 |
service { |
| 1929 |
account accE |
| 1930 |
subject foo.accI2 |
| 1931 |
} |
| 1932 |
to foo |
| 1933 |
},{ |
| 1934 |
stream { |
| 1935 |
account sys |
| 1936 |
subject "$SYS.SERVER.ACCOUNT.accI2.CONNS" |
| 1937 |
} |
| 1938 |
}], |
| 1939 |
users [{ |
| 1940 |
user u2 |
| 1941 |
password pwd |
| 1942 |
}], |
| 1943 |
} |
| 1944 |
}` |
| 1945 |
f := createConfFile(t, []byte(conf)) |
| 1946 |
s, o := RunServerWithConfig(f) |
| 1947 |
if s == nil { |
| 1948 |
t.Fatal("Failed startup") |
| 1949 |
} |
| 1950 |
defer s.Shutdown() |
| 1951 |
connect := func(user string) *nats.Conn { |
| 1952 |
nc, err := nats.Connect(fmt.Sprintf("nats://%s:pwd@%s:%d", user, o.Host, o.Port)) |
| 1953 |
require_NoError(t, err) |
| 1954 |
return nc |
| 1955 |
} |
| 1956 |
nc1 := connect("u1") |
| 1957 |
defer nc1.Close() |
| 1958 |
nc2 := connect("u2") |
| 1959 |
defer nc2.Close() |
| 1960 |
|
| 1961 |
// Due to the fact that above CONNECT events are generated and sent from |
| 1962 |
// a system go routine, it is possible that by the time we create the |
| 1963 |
// subscriptions below, the interest would exist and messages be sent, |
| 1964 |
// which was causing issues since wg.Done() was called too many times. |
| 1965 |
// Add a little delay to minimize risk, but also use counter to decide |
| 1966 |
// when to call wg.Done() to avoid panic due to negative number. |
| 1967 |
time.Sleep(100 * time.Millisecond) |
| 1968 |
|
| 1969 |
wg := sync.WaitGroup{} |
| 1970 |
wg.Add(1) |
| 1971 |
count := int32(0) |
| 1972 |
// We expect a total of 6 messages |
| 1973 |
expected := int32(6) |
| 1974 |
subscribe := func(nc *nats.Conn, subj string) { |
| 1975 |
t.Helper() |
| 1976 |
_, err := nc.Subscribe(subj, func(msg *nats.Msg) { |
| 1977 |
if msg.Reply != _EMPTY_ { |
| 1978 |
msg.Respond(msg.Data) |
| 1979 |
} |
| 1980 |
if atomic.AddInt32(&count, 1) == expected { |
| 1981 |
wg.Done() |
| 1982 |
} |
| 1983 |
}) |
| 1984 |
require_NoError(t, err) |
| 1985 |
nc.Flush() |
| 1986 |
} |
| 1987 |
//Subscribe to CONNS events |
| 1988 |
subscribe(nc1, "$SYS.SERVER.ACCOUNT.accI1.CONNS") |
| 1989 |
subscribe(nc2, "$SYS.SERVER.ACCOUNT.accI2.CONNS") |
| 1990 |
// Trigger 2 CONNS event |
| 1991 |
nc3 := connect("u1") |
| 1992 |
nc3.Close() |
| 1993 |
nc4 := connect("u2") |
| 1994 |
nc4.Close() |
| 1995 |
// test service |
| 1996 |
ncE := connect("ue") |
| 1997 |
defer ncE.Close() |
| 1998 |
subscribe(ncE, "foo.*") |
| 1999 |
request := func(nc *nats.Conn, msg string) { |
| 2000 |
if m, err := nc.Request("foo", []byte(msg), time.Second); err != nil { |
| 2001 |
t.Fatal("Failed request ", msg, err) |
| 2002 |
} else if m == nil { |
| 2003 |
t.Fatal("No response msg") |
| 2004 |
} else if string(m.Data) != msg { |
| 2005 |
t.Fatal("Wrong response msg", string(m.Data)) |
| 2006 |
} |
| 2007 |
} |
| 2008 |
request(nc1, "1") |
| 2009 |
request(nc2, "1") |
| 2010 |
wg.Wait() |
| 2011 |
} |
| 2012 |
|
| 2013 |
func TestAccountUsersLoadedProperly(t *testing.T) { |
| 2014 |
conf := createConfFile(t, []byte(` |
| 2015 |
listen: "127.0.0.1:-1" |
| 2016 |
authorization { |
| 2017 |
users [ |
| 2018 |
{user: ivan, password: bar} |
| 2019 |
{nkey : UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX} |
| 2020 |
] |
| 2021 |
} |
| 2022 |
accounts { |
| 2023 |
synadia { |
| 2024 |
users [ |
| 2025 |
{user: derek, password: foo} |
| 2026 |
{nkey : UBAAQWTW6CG2G6ANGNKB5U2B7HRWHSGMZEZX3AQSAJOQDAUGJD46LD2E} |
| 2027 |
] |
| 2028 |
} |
| 2029 |
} |
| 2030 |
`)) |
| 2031 |
check := func(t *testing.T) { |
| 2032 |
t.Helper() |
| 2033 |
s, _ := RunServerWithConfig(conf) |
| 2034 |
defer s.Shutdown() |
| 2035 |
opts := s.getOpts() |
| 2036 |
if n := len(opts.Users); n != 2 { |
| 2037 |
t.Fatalf("Should have 2 users, got %v", n) |
| 2038 |
} |
| 2039 |
if n := len(opts.Nkeys); n != 2 { |
| 2040 |
t.Fatalf("Should have 2 nkeys, got %v", n) |
| 2041 |
} |
| 2042 |
} |
| 2043 |
// Repeat test since issue was with ordering of processing |
| 2044 |
// of authorization vs accounts that depends on range of a map (after actual parsing) |
| 2045 |
for i := 0; i < 20; i++ { |
| 2046 |
check(t) |
| 2047 |
} |
| 2048 |
} |
| 2049 |
|
| 2050 |
func TestParsingGateways(t *testing.T) { |
| 2051 |
content := ` |
| 2052 |
gateway { |
| 2053 |
name: "A" |
| 2054 |
listen: "127.0.0.1:4444" |
| 2055 |
host: "127.0.0.1" |
| 2056 |
port: 4444 |
| 2057 |
reject_unknown_cluster: true |
| 2058 |
authorization { |
| 2059 |
user: "ivan" |
| 2060 |
password: "pwd" |
| 2061 |
timeout: 2.0 |
| 2062 |
} |
| 2063 |
tls { |
| 2064 |
cert_file: "./configs/certs/server.pem" |
| 2065 |
key_file: "./configs/certs/key.pem" |
| 2066 |
timeout: 3.0 |
| 2067 |
} |
| 2068 |
advertise: "me:1" |
| 2069 |
connect_retries: 10 |
| 2070 |
connect_backoff: true |
| 2071 |
gateways: [ |
| 2072 |
{ |
| 2073 |
name: "B" |
| 2074 |
urls: ["nats://user1:pwd1@host2:5222", "nats://user1:pwd1@host3:6222"] |
| 2075 |
} |
| 2076 |
{ |
| 2077 |
name: "C" |
| 2078 |
url: "nats://host4:7222" |
| 2079 |
} |
| 2080 |
] |
| 2081 |
} |
| 2082 |
` |
| 2083 |
file := "server_config_gateways.conf" |
| 2084 |
if err := os.WriteFile(file, []byte(content), 0600); err != nil { |
| 2085 |
t.Fatalf("Error writing config file: %v", err) |
| 2086 |
} |
| 2087 |
defer removeFile(t, file) |
| 2088 |
opts, err := ProcessConfigFile(file) |
| 2089 |
if err != nil { |
| 2090 |
t.Fatalf("Error processing file: %v", err) |
| 2091 |
} |
| 2092 |
|
| 2093 |
expected := &GatewayOpts{ |
| 2094 |
Name: "A", |
| 2095 |
Host: "127.0.0.1", |
| 2096 |
Port: 4444, |
| 2097 |
Username: "ivan", |
| 2098 |
Password: "pwd", |
| 2099 |
AuthTimeout: 2.0, |
| 2100 |
Advertise: "me:1", |
| 2101 |
ConnectRetries: 10, |
| 2102 |
ConnectBackoff: true, |
| 2103 |
TLSTimeout: 3.0, |
| 2104 |
RejectUnknown: true, |
| 2105 |
} |
| 2106 |
u1, _ := url.Parse("nats://user1:pwd1@host2:5222") |
| 2107 |
u2, _ := url.Parse("nats://user1:pwd1@host3:6222") |
| 2108 |
urls := []*url.URL{u1, u2} |
| 2109 |
gw := &RemoteGatewayOpts{ |
| 2110 |
Name: "B", |
| 2111 |
URLs: urls, |
| 2112 |
} |
| 2113 |
expected.Gateways = append(expected.Gateways, gw) |
| 2114 |
|
| 2115 |
u1, _ = url.Parse("nats://host4:7222") |
| 2116 |
urls = []*url.URL{u1} |
| 2117 |
gw = &RemoteGatewayOpts{ |
| 2118 |
Name: "C", |
| 2119 |
URLs: urls, |
| 2120 |
} |
| 2121 |
expected.Gateways = append(expected.Gateways, gw) |
| 2122 |
|
| 2123 |
// Just make sure that TLSConfig is set.. we have aother test |
| 2124 |
// to check proper generating TLSConfig from config file... |
| 2125 |
if opts.Gateway.TLSConfig == nil { |
| 2126 |
t.Fatalf("Expected TLSConfig, got none") |
| 2127 |
} |
| 2128 |
opts.Gateway.TLSConfig = nil |
| 2129 |
opts.Gateway.tlsConfigOpts = nil |
| 2130 |
if !reflect.DeepEqual(&opts.Gateway, expected) { |
| 2131 |
t.Fatalf("Expected %v, got %v", expected, opts.Gateway) |
| 2132 |
} |
| 2133 |
} |
| 2134 |
|
| 2135 |
func TestParsingGatewaysErrors(t *testing.T) { |
| 2136 |
for _, test := range []struct { |
| 2137 |
name string |
| 2138 |
content string |
| 2139 |
expectedErr string |
| 2140 |
}{ |
| 2141 |
{ |
| 2142 |
"bad_type", |
| 2143 |
`gateway: "bad_type"`, |
| 2144 |
"Expected gateway to be a map", |
| 2145 |
}, |
| 2146 |
{ |
| 2147 |
"bad_listen", |
| 2148 |
`gateway { |
| 2149 |
name: "A" |
| 2150 |
port: -1 |
| 2151 |
listen: "bad::address" |
| 2152 |
}`, |
| 2153 |
"parse address", |
| 2154 |
}, |
| 2155 |
{ |
| 2156 |
"bad_auth", |
| 2157 |
`gateway { |
| 2158 |
name: "A" |
| 2159 |
port: -1 |
| 2160 |
authorization { |
| 2161 |
users { |
| 2162 |
} |
| 2163 |
} |
| 2164 |
}`, |
| 2165 |
"be an array", |
| 2166 |
}, |
| 2167 |
{ |
| 2168 |
"unknown_field", |
| 2169 |
`gateway { |
| 2170 |
name: "A" |
| 2171 |
port: -1 |
| 2172 |
reject_unknown_cluster: true |
| 2173 |
unknown_field: 1 |
| 2174 |
}`, |
| 2175 |
"unknown field", |
| 2176 |
}, |
| 2177 |
{ |
| 2178 |
"users_not_supported", |
| 2179 |
`gateway { |
| 2180 |
name: "A" |
| 2181 |
port: -1 |
| 2182 |
authorization { |
| 2183 |
users [ |
| 2184 |
{user: alice, password: foo} |
| 2185 |
{user: bob, password: bar} |
| 2186 |
] |
| 2187 |
} |
| 2188 |
}`, |
| 2189 |
"does not allow multiple users", |
| 2190 |
}, |
| 2191 |
{ |
| 2192 |
"tls_error", |
| 2193 |
`gateway { |
| 2194 |
name: "A" |
| 2195 |
port: -1 |
| 2196 |
tls { |
| 2197 |
cert_file: 123 |
| 2198 |
} |
| 2199 |
}`, |
| 2200 |
"to be filename", |
| 2201 |
}, |
| 2202 |
{ |
| 2203 |
"tls_gen_error_cert_file_not_found", |
| 2204 |
`gateway { |
| 2205 |
name: "A" |
| 2206 |
port: -1 |
| 2207 |
tls { |
| 2208 |
cert_file: "./configs/certs/missing.pem" |
| 2209 |
key_file: "./configs/certs/server-key.pem" |
| 2210 |
} |
| 2211 |
}`, |
| 2212 |
"certificate/key pair", |
| 2213 |
}, |
| 2214 |
{ |
| 2215 |
"tls_gen_error_key_file_not_found", |
| 2216 |
`gateway { |
| 2217 |
name: "A" |
| 2218 |
port: -1 |
| 2219 |
tls { |
| 2220 |
cert_file: "./configs/certs/server.pem" |
| 2221 |
key_file: "./configs/certs/missing.pem" |
| 2222 |
} |
| 2223 |
}`, |
| 2224 |
"certificate/key pair", |
| 2225 |
}, |
| 2226 |
{ |
| 2227 |
"tls_gen_error_key_file_missing", |
| 2228 |
`gateway { |
| 2229 |
name: "A" |
| 2230 |
port: -1 |
| 2231 |
tls { |
| 2232 |
cert_file: "./configs/certs/server.pem" |
| 2233 |
} |
| 2234 |
}`, |
| 2235 |
`missing 'key_file' in TLS configuration`, |
| 2236 |
}, |
| 2237 |
{ |
| 2238 |
"tls_gen_error_cert_file_missing", |
| 2239 |
`gateway { |
| 2240 |
name: "A" |
| 2241 |
port: -1 |
| 2242 |
tls { |
| 2243 |
key_file: "./configs/certs/server-key.pem" |
| 2244 |
} |
| 2245 |
}`, |
| 2246 |
`missing 'cert_file' in TLS configuration`, |
| 2247 |
}, |
| 2248 |
{ |
| 2249 |
"tls_gen_error_key_file_not_found", |
| 2250 |
`gateway { |
| 2251 |
name: "A" |
| 2252 |
port: -1 |
| 2253 |
tls { |
| 2254 |
cert_file: "./configs/certs/server.pem" |
| 2255 |
key_file: "./configs/certs/missing.pem" |
| 2256 |
} |
| 2257 |
}`, |
| 2258 |
"certificate/key pair", |
| 2259 |
}, |
| 2260 |
{ |
| 2261 |
"gateways_needs_to_be_an_array", |
| 2262 |
`gateway { |
| 2263 |
name: "A" |
| 2264 |
gateways { |
| 2265 |
name: "B" |
| 2266 |
} |
| 2267 |
}`, |
| 2268 |
"Expected gateways field to be an array", |
| 2269 |
}, |
| 2270 |
{ |
| 2271 |
"gateways_entry_needs_to_be_a_map", |
| 2272 |
`gateway { |
| 2273 |
name: "A" |
| 2274 |
gateways [ |
| 2275 |
"g1", "g2" |
| 2276 |
] |
| 2277 |
}`, |
| 2278 |
"Expected gateway entry to be a map", |
| 2279 |
}, |
| 2280 |
{ |
| 2281 |
"bad_url", |
| 2282 |
`gateway { |
| 2283 |
name: "A" |
| 2284 |
gateways [ |
| 2285 |
{ |
| 2286 |
name: "B" |
| 2287 |
url: "nats://wrong url" |
| 2288 |
} |
| 2289 |
] |
| 2290 |
}`, |
| 2291 |
"error parsing gateway url", |
| 2292 |
}, |
| 2293 |
{ |
| 2294 |
"bad_urls", |
| 2295 |
`gateway { |
| 2296 |
name: "A" |
| 2297 |
gateways [ |
| 2298 |
{ |
| 2299 |
name: "B" |
| 2300 |
urls: ["nats://wrong url", "nats://host:5222"] |
| 2301 |
} |
| 2302 |
] |
| 2303 |
}`, |
| 2304 |
"error parsing gateway url", |
| 2305 |
}, |
| 2306 |
{ |
| 2307 |
"gateway_tls_error", |
| 2308 |
`gateway { |
| 2309 |
name: "A" |
| 2310 |
port: -1 |
| 2311 |
gateways [ |
| 2312 |
{ |
| 2313 |
name: "B" |
| 2314 |
tls { |
| 2315 |
cert_file: 123 |
| 2316 |
} |
| 2317 |
} |
| 2318 |
] |
| 2319 |
}`, |
| 2320 |
"to be filename", |
| 2321 |
}, |
| 2322 |
{ |
| 2323 |
"gateway_unknown_field", |
| 2324 |
`gateway { |
| 2325 |
name: "A" |
| 2326 |
port: -1 |
| 2327 |
gateways [ |
| 2328 |
{ |
| 2329 |
name: "B" |
| 2330 |
unknown_field: 1 |
| 2331 |
} |
| 2332 |
] |
| 2333 |
}`, |
| 2334 |
"unknown field", |
| 2335 |
}, |
| 2336 |
} { |
| 2337 |
t.Run(test.name, func(t *testing.T) { |
| 2338 |
file := fmt.Sprintf("server_config_gateways_%s.conf", test.name) |
| 2339 |
if err := os.WriteFile(file, []byte(test.content), 0600); err != nil { |
| 2340 |
t.Fatalf("Error writing config file: %v", err) |
| 2341 |
} |
| 2342 |
defer removeFile(t, file) |
| 2343 |
_, err := ProcessConfigFile(file) |
| 2344 |
if err == nil { |
| 2345 |
t.Fatalf("Expected to fail, did not. Content:\n%s", test.content) |
| 2346 |
} else if !strings.Contains(err.Error(), test.expectedErr) { |
| 2347 |
t.Fatalf("Expected error containing %q, got %q, for content:\n%s", test.expectedErr, err, test.content) |
| 2348 |
} |
| 2349 |
}) |
| 2350 |
} |
| 2351 |
} |
| 2352 |
|
| 2353 |
func TestParsingLeafNodesListener(t *testing.T) { |
| 2354 |
content := ` |
| 2355 |
leafnodes { |
| 2356 |
listen: "127.0.0.1:3333" |
| 2357 |
host: "127.0.0.1" |
| 2358 |
port: 3333 |
| 2359 |
advertise: "me:22" |
| 2360 |
authorization { |
| 2361 |
user: "derek" |
| 2362 |
password: "s3cr3t!" |
| 2363 |
timeout: 2.2 |
| 2364 |
} |
| 2365 |
tls { |
| 2366 |
cert_file: "./configs/certs/server.pem" |
| 2367 |
key_file: "./configs/certs/key.pem" |
| 2368 |
timeout: 3.3 |
| 2369 |
} |
| 2370 |
} |
| 2371 |
` |
| 2372 |
conf := createConfFile(t, []byte(content)) |
| 2373 |
opts, err := ProcessConfigFile(conf) |
| 2374 |
if err != nil { |
| 2375 |
t.Fatalf("Error processing file: %v", err) |
| 2376 |
} |
| 2377 |
|
| 2378 |
expected := &LeafNodeOpts{ |
| 2379 |
Host: "127.0.0.1", |
| 2380 |
Port: 3333, |
| 2381 |
Username: "derek", |
| 2382 |
Password: "s3cr3t!", |
| 2383 |
AuthTimeout: 2.2, |
| 2384 |
Advertise: "me:22", |
| 2385 |
TLSTimeout: 3.3, |
| 2386 |
} |
| 2387 |
if opts.LeafNode.TLSConfig == nil { |
| 2388 |
t.Fatalf("Expected TLSConfig, got none") |
| 2389 |
} |
| 2390 |
if opts.LeafNode.tlsConfigOpts == nil { |
| 2391 |
t.Fatalf("Expected TLSConfig snapshot, got none") |
| 2392 |
} |
| 2393 |
opts.LeafNode.TLSConfig = nil |
| 2394 |
opts.LeafNode.tlsConfigOpts = nil |
| 2395 |
if !reflect.DeepEqual(&opts.LeafNode, expected) { |
| 2396 |
t.Fatalf("Expected %v, got %v", expected, opts.LeafNode) |
| 2397 |
} |
| 2398 |
} |
| 2399 |
|
| 2400 |
func TestParsingLeafNodeRemotes(t *testing.T) { |
| 2401 |
t.Run("parse config file with relative path", func(t *testing.T) { |
| 2402 |
content := ` |
| 2403 |
leafnodes { |
| 2404 |
remotes = [ |
| 2405 |
{ |
| 2406 |
url: nats-leaf://127.0.0.1:2222 |
| 2407 |
account: foobar // Local Account to bind to.. |
| 2408 |
credentials: "./my.creds" |
| 2409 |
} |
| 2410 |
] |
| 2411 |
} |
| 2412 |
` |
| 2413 |
conf := createConfFile(t, []byte(content)) |
| 2414 |
opts, err := ProcessConfigFile(conf) |
| 2415 |
if err != nil { |
| 2416 |
t.Fatalf("Error processing file: %v", err) |
| 2417 |
} |
| 2418 |
if len(opts.LeafNode.Remotes) != 1 { |
| 2419 |
t.Fatalf("Expected 1 remote, got %d", len(opts.LeafNode.Remotes)) |
| 2420 |
} |
| 2421 |
expected := &RemoteLeafOpts{ |
| 2422 |
LocalAccount: "foobar", |
| 2423 |
Credentials: "./my.creds", |
| 2424 |
} |
| 2425 |
u, _ := url.Parse("nats-leaf://127.0.0.1:2222") |
| 2426 |
expected.URLs = append(expected.URLs, u) |
| 2427 |
if !reflect.DeepEqual(opts.LeafNode.Remotes[0], expected) { |
| 2428 |
t.Fatalf("Expected %v, got %v", expected, opts.LeafNode.Remotes[0]) |
| 2429 |
} |
| 2430 |
}) |
| 2431 |
|
| 2432 |
t.Run("parse config file with tilde path", func(t *testing.T) { |
| 2433 |
if runtime.GOOS == "windows" { |
| 2434 |
t.SkipNow() |
| 2435 |
} |
| 2436 |
|
| 2437 |
origHome := os.Getenv("HOME") |
| 2438 |
defer os.Setenv("HOME", origHome) |
| 2439 |
os.Setenv("HOME", "/home/foo") |
| 2440 |
|
| 2441 |
content := ` |
| 2442 |
leafnodes { |
| 2443 |
remotes = [ |
| 2444 |
{ |
| 2445 |
url: nats-leaf://127.0.0.1:2222 |
| 2446 |
account: foobar // Local Account to bind to.. |
| 2447 |
credentials: "~/my.creds" |
| 2448 |
} |
| 2449 |
] |
| 2450 |
} |
| 2451 |
` |
| 2452 |
conf := createConfFile(t, []byte(content)) |
| 2453 |
opts, err := ProcessConfigFile(conf) |
| 2454 |
if err != nil { |
| 2455 |
t.Fatalf("Error processing file: %v", err) |
| 2456 |
} |
| 2457 |
expected := &RemoteLeafOpts{ |
| 2458 |
LocalAccount: "foobar", |
| 2459 |
Credentials: "/home/foo/my.creds", |
| 2460 |
} |
| 2461 |
u, _ := url.Parse("nats-leaf://127.0.0.1:2222") |
| 2462 |
expected.URLs = append(expected.URLs, u) |
| 2463 |
if !reflect.DeepEqual(opts.LeafNode.Remotes[0], expected) { |
| 2464 |
t.Fatalf("Expected %v, got %v", expected, opts.LeafNode.Remotes[0]) |
| 2465 |
} |
| 2466 |
}) |
| 2467 |
|
| 2468 |
t.Run("url ordering", func(t *testing.T) { |
| 2469 |
// 16! possible permutations. |
| 2470 |
orderedURLs := make([]string, 0, 16) |
| 2471 |
for i := 0; i < cap(orderedURLs); i++ { |
| 2472 |
orderedURLs = append(orderedURLs, fmt.Sprintf("nats-leaf://host%d:7422", i)) |
| 2473 |
} |
| 2474 |
confURLs, err := json.Marshal(orderedURLs) |
| 2475 |
if err != nil { |
| 2476 |
t.Fatal(err) |
| 2477 |
} |
| 2478 |
|
| 2479 |
content := ` |
| 2480 |
port: -1 |
| 2481 |
accounts: { |
| 2482 |
A { users [ {user: a, password: a} ]} |
| 2483 |
B { users [ {user: b, password: b} ]} |
| 2484 |
} |
| 2485 |
leafnodes { |
| 2486 |
remotes = [ |
| 2487 |
{ |
| 2488 |
dont_randomize: true |
| 2489 |
urls: %[1]s |
| 2490 |
account: "A" |
| 2491 |
} |
| 2492 |
{ |
| 2493 |
urls: %[1]s |
| 2494 |
account: "B" |
| 2495 |
} |
| 2496 |
] |
| 2497 |
} |
| 2498 |
` |
| 2499 |
conf := createConfFile(t, []byte(fmt.Sprintf(content, confURLs))) |
| 2500 |
|
| 2501 |
s, _ := RunServerWithConfig(conf) |
| 2502 |
defer s.Shutdown() |
| 2503 |
|
| 2504 |
var r1, r2 *leafNodeCfg |
| 2505 |
s.mu.RLock() |
| 2506 |
for r := range s.leafRemoteCfgs { |
| 2507 |
if r.NoRandomize { |
| 2508 |
r1 = r |
| 2509 |
} else { |
| 2510 |
r2 = r |
| 2511 |
} |
| 2512 |
} |
| 2513 |
s.mu.RUnlock() |
| 2514 |
|
| 2515 |
r1.RLock() |
| 2516 |
gotOrdered := r1.urls |
| 2517 |
r1.RUnlock() |
| 2518 |
if got, want := len(gotOrdered), len(orderedURLs); got != want { |
| 2519 |
t.Fatalf("Unexpected rem0 len URLs, got %d, want %d", got, want) |
| 2520 |
} |
| 2521 |
|
| 2522 |
// These should be IN order. |
| 2523 |
for i := range orderedURLs { |
| 2524 |
if got, want := gotOrdered[i].String(), orderedURLs[i]; got != want { |
| 2525 |
t.Fatalf("Unexpected ordered url, got %s, want %s", got, want) |
| 2526 |
} |
| 2527 |
} |
| 2528 |
|
| 2529 |
r2.RLock() |
| 2530 |
gotRandom := r2.urls |
| 2531 |
r2.RUnlock() |
| 2532 |
if got, want := len(gotRandom), len(orderedURLs); got != want { |
| 2533 |
t.Fatalf("Unexpected rem1 len URLs, got %d, want %d", got, want) |
| 2534 |
} |
| 2535 |
|
| 2536 |
// These should be OUT of order. |
| 2537 |
var random bool |
| 2538 |
for i := range orderedURLs { |
| 2539 |
if gotRandom[i].String() != orderedURLs[i] { |
| 2540 |
random = true |
| 2541 |
break |
| 2542 |
} |
| 2543 |
} |
| 2544 |
if !random { |
| 2545 |
t.Fatal("Expected urls to be random") |
| 2546 |
} |
| 2547 |
}) |
| 2548 |
|
| 2549 |
t.Run("parse config file js_cluster_migrate", func(t *testing.T) { |
| 2550 |
content := ` |
| 2551 |
leafnodes { |
| 2552 |
remotes = [ |
| 2553 |
{ |
| 2554 |
url: nats-leaf://127.0.0.1:2222 |
| 2555 |
account: foo // Local Account to bind to.. |
| 2556 |
credentials: "./my.creds" |
| 2557 |
js_cluster_migrate: true |
| 2558 |
}, |
| 2559 |
{ |
| 2560 |
url: nats-leaf://127.0.0.1:2222 |
| 2561 |
account: bar // Local Account to bind to.. |
| 2562 |
credentials: "./my.creds" |
| 2563 |
js_cluster_migrate: { |
| 2564 |
leader_migrate_delay: 30s |
| 2565 |
} |
| 2566 |
}, |
| 2567 |
{ |
| 2568 |
url: nats-leaf://127.0.0.1:2222 |
| 2569 |
account: baz // Local Account to bind to.. |
| 2570 |
credentials: "./my.creds" |
| 2571 |
js_cluster_migrate: false |
| 2572 |
} |
| 2573 |
] |
| 2574 |
} |
| 2575 |
` |
| 2576 |
conf := createConfFile(t, []byte(content)) |
| 2577 |
opts, err := ProcessConfigFile(conf) |
| 2578 |
if err != nil { |
| 2579 |
t.Fatalf("Error processing file: %v", err) |
| 2580 |
} |
| 2581 |
if len(opts.LeafNode.Remotes) != 3 { |
| 2582 |
t.Fatalf("Expected 2 remote, got %d", len(opts.LeafNode.Remotes)) |
| 2583 |
} |
| 2584 |
u, _ := url.Parse("nats-leaf://127.0.0.1:2222") |
| 2585 |
expected := []*RemoteLeafOpts{ |
| 2586 |
{ |
| 2587 |
URLs: []*url.URL{u}, |
| 2588 |
LocalAccount: "foo", |
| 2589 |
Credentials: "./my.creds", |
| 2590 |
JetStreamClusterMigrate: true, |
| 2591 |
}, |
| 2592 |
{ |
| 2593 |
URLs: []*url.URL{u}, |
| 2594 |
LocalAccount: "bar", |
| 2595 |
Credentials: "./my.creds", |
| 2596 |
JetStreamClusterMigrate: true, |
| 2597 |
JetStreamClusterMigrateDelay: 30 * time.Second, |
| 2598 |
}, |
| 2599 |
{ |
| 2600 |
URLs: []*url.URL{u}, |
| 2601 |
LocalAccount: "baz", |
| 2602 |
Credentials: "./my.creds", |
| 2603 |
JetStreamClusterMigrate: false, |
| 2604 |
}, |
| 2605 |
} |
| 2606 |
if !reflect.DeepEqual(opts.LeafNode.Remotes, expected) { |
| 2607 |
t.Fatalf("Expected %v, got %v", expected, opts.LeafNode.Remotes) |
| 2608 |
} |
| 2609 |
}) |
| 2610 |
|
| 2611 |
} |
| 2612 |
|
| 2613 |
func TestLargeMaxControlLine(t *testing.T) { |
| 2614 |
confFileName := createConfFile(t, []byte(` |
| 2615 |
max_control_line = 3000000000 |
| 2616 |
`)) |
| 2617 |
if _, err := ProcessConfigFile(confFileName); err == nil { |
| 2618 |
t.Fatalf("Expected an error from too large of a max_control_line entry") |
| 2619 |
} |
| 2620 |
} |
| 2621 |
|
| 2622 |
func TestLargeMaxPayload(t *testing.T) { |
| 2623 |
confFileName := createConfFile(t, []byte(` |
| 2624 |
max_payload = 3000000000 |
| 2625 |
`)) |
| 2626 |
if _, err := ProcessConfigFile(confFileName); err == nil { |
| 2627 |
t.Fatalf("Expected an error from too large of a max_payload entry") |
| 2628 |
} |
| 2629 |
|
| 2630 |
confFileName = createConfFile(t, []byte(` |
| 2631 |
max_payload = 100000 |
| 2632 |
max_pending = 50000 |
| 2633 |
`)) |
| 2634 |
o := LoadConfig(confFileName) |
| 2635 |
s, err := NewServer(o) |
| 2636 |
if err == nil || !strings.Contains(err.Error(), "cannot be higher") { |
| 2637 |
if s != nil { |
| 2638 |
s.Shutdown() |
| 2639 |
} |
| 2640 |
t.Fatalf("Unexpected error: %v", err) |
| 2641 |
} |
| 2642 |
} |
| 2643 |
|
| 2644 |
func TestHandleUnknownTopLevelConfigurationField(t *testing.T) { |
| 2645 |
conf := createConfFile(t, []byte(` |
| 2646 |
port: 1234 |
| 2647 |
streaming { |
| 2648 |
id: "me" |
| 2649 |
} |
| 2650 |
`)) |
| 2651 |
|
| 2652 |
// Verify that we get an error because of unknown "streaming" field. |
| 2653 |
opts := &Options{} |
| 2654 |
if err := opts.ProcessConfigFile(conf); err == nil || !strings.Contains(err.Error(), "streaming") { |
| 2655 |
t.Fatal("Expected error, got none") |
| 2656 |
} |
| 2657 |
|
| 2658 |
// Verify that if that is set, we get no error |
| 2659 |
NoErrOnUnknownFields(true) |
| 2660 |
defer NoErrOnUnknownFields(false) |
| 2661 |
|
| 2662 |
if err := opts.ProcessConfigFile(conf); err != nil { |
| 2663 |
t.Fatalf("Unexpected error: %v", err) |
| 2664 |
} |
| 2665 |
if opts.Port != 1234 { |
| 2666 |
t.Fatalf("Port was not parsed correctly: %v", opts.Port) |
| 2667 |
} |
| 2668 |
|
| 2669 |
// Verify that ignore works only on top level fields. |
| 2670 |
changeCurrentConfigContentWithNewContent(t, conf, []byte(` |
| 2671 |
port: 1234 |
| 2672 |
cluster { |
| 2673 |
non_top_level_unknown_field: 123 |
| 2674 |
} |
| 2675 |
streaming { |
| 2676 |
id: "me" |
| 2677 |
} |
| 2678 |
`)) |
| 2679 |
if err := opts.ProcessConfigFile(conf); err == nil || !strings.Contains(err.Error(), "non_top_level") { |
| 2680 |
t.Fatal("Expected error, got none") |
| 2681 |
} |
| 2682 |
} |
| 2683 |
|
| 2684 |
func TestSublistNoCacheConfig(t *testing.T) { |
| 2685 |
confFileName := createConfFile(t, []byte(` |
| 2686 |
disable_sublist_cache: true |
| 2687 |
`)) |
| 2688 |
opts, err := ProcessConfigFile(confFileName) |
| 2689 |
if err != nil { |
| 2690 |
t.Fatalf("Received an error reading config file: %v", err) |
| 2691 |
} |
| 2692 |
if !opts.NoSublistCache { |
| 2693 |
t.Fatalf("Expected sublist cache to be disabled") |
| 2694 |
} |
| 2695 |
} |
| 2696 |
|
| 2697 |
func TestSublistNoCacheConfigOnAccounts(t *testing.T) { |
| 2698 |
confFileName := createConfFile(t, []byte(` |
| 2699 |
listen: "127.0.0.1:-1" |
| 2700 |
disable_sublist_cache: true |
| 2701 |
|
| 2702 |
accounts { |
| 2703 |
synadia { |
| 2704 |
users [ {nkey : UBAAQWTW6CG2G6ANGNKB5U2B7HRWHSGMZEZX3AQSAJOQDAUGJD46LD2E} ] |
| 2705 |
} |
| 2706 |
nats.io { |
| 2707 |
users [ {nkey : UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX} ] |
| 2708 |
} |
| 2709 |
} |
| 2710 |
no_sys_acc = true |
| 2711 |
`)) |
| 2712 |
|
| 2713 |
s, _ := RunServerWithConfig(confFileName) |
| 2714 |
defer s.Shutdown() |
| 2715 |
|
| 2716 |
// Check that all account sublists do not have caching enabled. |
| 2717 |
ta := s.numReservedAccounts() + 2 |
| 2718 |
if la := s.numAccounts(); la != ta { |
| 2719 |
t.Fatalf("Expected to have a server with %d active accounts, got %v", ta, la) |
| 2720 |
} |
| 2721 |
|
| 2722 |
s.accounts.Range(func(k, v any) bool { |
| 2723 |
acc := v.(*Account) |
| 2724 |
if acc == nil { |
| 2725 |
t.Fatalf("Expected non-nil sublist for account") |
| 2726 |
} |
| 2727 |
if acc.sl.CacheEnabled() { |
| 2728 |
t.Fatalf("Expected the account sublist to not have caching enabled") |
| 2729 |
} |
| 2730 |
return true |
| 2731 |
}) |
| 2732 |
} |
| 2733 |
|
| 2734 |
func TestParsingResponsePermissions(t *testing.T) { |
| 2735 |
template := ` |
| 2736 |
listen: "127.0.0.1:-1" |
| 2737 |
authorization { |
| 2738 |
users [ |
| 2739 |
{ |
| 2740 |
user: ivan |
| 2741 |
password: pwd |
| 2742 |
permissions { |
| 2743 |
allow_responses { |
| 2744 |
%s |
| 2745 |
%s |
| 2746 |
} |
| 2747 |
} |
| 2748 |
} |
| 2749 |
] |
| 2750 |
} |
| 2751 |
` |
| 2752 |
|
| 2753 |
check := func(t *testing.T, conf string, expectedError string, expectedMaxMsgs int, expectedTTL time.Duration) { |
| 2754 |
t.Helper() |
| 2755 |
opts, err := ProcessConfigFile(conf) |
| 2756 |
if expectedError != "" { |
| 2757 |
if err == nil || !strings.Contains(err.Error(), expectedError) { |
| 2758 |
t.Fatalf("Expected error about %q, got %q", expectedError, err) |
| 2759 |
} |
| 2760 |
// OK! |
| 2761 |
return |
| 2762 |
} |
| 2763 |
if err != nil { |
| 2764 |
t.Fatalf("Error on process: %v", err) |
| 2765 |
} |
| 2766 |
u := opts.Users[0] |
| 2767 |
p := u.Permissions.Response |
| 2768 |
if p == nil { |
| 2769 |
t.Fatalf("Expected response permissions to be set, it was not") |
| 2770 |
} |
| 2771 |
if n := p.MaxMsgs; n != expectedMaxMsgs { |
| 2772 |
t.Fatalf("Expected response max msgs to be %v, got %v", expectedMaxMsgs, n) |
| 2773 |
} |
| 2774 |
if ttl := p.Expires; ttl != expectedTTL { |
| 2775 |
t.Fatalf("Expected response ttl to be %v, got %v", expectedTTL, ttl) |
| 2776 |
} |
| 2777 |
} |
| 2778 |
|
| 2779 |
// Check defaults |
| 2780 |
conf := createConfFile(t, []byte(fmt.Sprintf(template, "", ""))) |
| 2781 |
check(t, conf, "", DEFAULT_ALLOW_RESPONSE_MAX_MSGS, DEFAULT_ALLOW_RESPONSE_EXPIRATION) |
| 2782 |
|
| 2783 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, "max: 10", ""))) |
| 2784 |
check(t, conf, "", 10, DEFAULT_ALLOW_RESPONSE_EXPIRATION) |
| 2785 |
|
| 2786 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, "", "ttl: 5s"))) |
| 2787 |
check(t, conf, "", DEFAULT_ALLOW_RESPONSE_MAX_MSGS, 5*time.Second) |
| 2788 |
|
| 2789 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, "max: 0", ""))) |
| 2790 |
check(t, conf, "", DEFAULT_ALLOW_RESPONSE_MAX_MSGS, DEFAULT_ALLOW_RESPONSE_EXPIRATION) |
| 2791 |
|
| 2792 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, "", `ttl: "0s"`))) |
| 2793 |
check(t, conf, "", DEFAULT_ALLOW_RESPONSE_MAX_MSGS, DEFAULT_ALLOW_RESPONSE_EXPIRATION) |
| 2794 |
|
| 2795 |
// Check normal values |
| 2796 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, "max: 10", `ttl: "5s"`))) |
| 2797 |
check(t, conf, "", 10, 5*time.Second) |
| 2798 |
|
| 2799 |
// Check negative values ok |
| 2800 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, "max: -1", `ttl: "5s"`))) |
| 2801 |
check(t, conf, "", -1, 5*time.Second) |
| 2802 |
|
| 2803 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, "max: 10", `ttl: "-1s"`))) |
| 2804 |
check(t, conf, "", 10, -1*time.Second) |
| 2805 |
|
| 2806 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, "max: -1", `ttl: "-1s"`))) |
| 2807 |
check(t, conf, "", -1, -1*time.Second) |
| 2808 |
|
| 2809 |
// Check parsing errors |
| 2810 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, "unknown_field: 123", ""))) |
| 2811 |
check(t, conf, "Unknown field", 0, 0) |
| 2812 |
|
| 2813 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, "max: 10", "ttl: 123"))) |
| 2814 |
check(t, conf, "not a duration string", 0, 0) |
| 2815 |
|
| 2816 |
conf = createConfFile(t, []byte(fmt.Sprintf(template, "max: 10", "ttl: xyz"))) |
| 2817 |
check(t, conf, "error parsing expires", 0, 0) |
| 2818 |
} |
| 2819 |
|
| 2820 |
func TestExpandPath(t *testing.T) { |
| 2821 |
if runtime.GOOS == "windows" { |
| 2822 |
origUserProfile := os.Getenv("USERPROFILE") |
| 2823 |
origHomeDrive, origHomePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH") |
| 2824 |
defer func() { |
| 2825 |
os.Setenv("USERPROFILE", origUserProfile) |
| 2826 |
os.Setenv("HOMEDRIVE", origHomeDrive) |
| 2827 |
os.Setenv("HOMEPATH", origHomePath) |
| 2828 |
}() |
| 2829 |
|
| 2830 |
cases := []struct { |
| 2831 |
path string |
| 2832 |
userProfile string |
| 2833 |
homeDrive string |
| 2834 |
homePath string |
| 2835 |
|
| 2836 |
wantPath string |
| 2837 |
wantErr bool |
| 2838 |
}{ |
| 2839 |
// Missing HOMEDRIVE and HOMEPATH. |
| 2840 |
{path: "/Foo/Bar", userProfile: `C:\Foo\Bar`, wantPath: "/Foo/Bar"}, |
| 2841 |
{path: "Foo/Bar", userProfile: `C:\Foo\Bar`, wantPath: "Foo/Bar"}, |
| 2842 |
{path: "~/Fizz", userProfile: `C:\Foo\Bar`, wantPath: `C:\Foo\Bar\Fizz`}, |
| 2843 |
{path: `${HOMEDRIVE}${HOMEPATH}\Fizz`, homeDrive: `C:`, homePath: `\Foo\Bar`, wantPath: `C:\Foo\Bar\Fizz`}, |
| 2844 |
|
| 2845 |
// Missing USERPROFILE. |
| 2846 |
{path: "~/Fizz", homeDrive: "X:", homePath: `\Foo\Bar`, wantPath: `X:\Foo\Bar\Fizz`}, |
| 2847 |
|
| 2848 |
// Set all environment variables. HOMEDRIVE and HOMEPATH take |
| 2849 |
// precedence. |
| 2850 |
{path: "~/Fizz", userProfile: `C:\Foo\Bar`, |
| 2851 |
homeDrive: "X:", homePath: `\Foo\Bar`, wantPath: `X:\Foo\Bar\Fizz`}, |
| 2852 |
|
| 2853 |
// Missing all environment variables. |
| 2854 |
{path: "~/Fizz", wantErr: true}, |
| 2855 |
} |
| 2856 |
for i, c := range cases { |
| 2857 |
t.Run(fmt.Sprintf("windows case %d", i), func(t *testing.T) { |
| 2858 |
os.Setenv("USERPROFILE", c.userProfile) |
| 2859 |
os.Setenv("HOMEDRIVE", c.homeDrive) |
| 2860 |
os.Setenv("HOMEPATH", c.homePath) |
| 2861 |
|
| 2862 |
gotPath, err := expandPath(c.path) |
| 2863 |
if !c.wantErr && err != nil { |
| 2864 |
t.Fatalf("unexpected error: got=%v; want=%v", err, nil) |
| 2865 |
} else if c.wantErr && err == nil { |
| 2866 |
t.Fatalf("unexpected success: got=%v; want=%v", nil, "err") |
| 2867 |
} |
| 2868 |
|
| 2869 |
if gotPath != c.wantPath { |
| 2870 |
t.Fatalf("unexpected path: got=%v; want=%v", gotPath, c.wantPath) |
| 2871 |
} |
| 2872 |
}) |
| 2873 |
} |
| 2874 |
|
| 2875 |
return |
| 2876 |
} |
| 2877 |
|
| 2878 |
// Unix tests |
| 2879 |
|
| 2880 |
origHome := os.Getenv("HOME") |
| 2881 |
defer os.Setenv("HOME", origHome) |
| 2882 |
|
| 2883 |
cases := []struct { |
| 2884 |
path string |
| 2885 |
home string |
| 2886 |
wantPath string |
| 2887 |
wantErr bool |
| 2888 |
}{ |
| 2889 |
{path: "/foo/bar", home: "/fizz/buzz", wantPath: "/foo/bar"}, |
| 2890 |
{path: "foo/bar", home: "/fizz/buzz", wantPath: "foo/bar"}, |
| 2891 |
{path: "~/fizz", home: "/foo/bar", wantPath: "/foo/bar/fizz"}, |
| 2892 |
{path: "$HOME/fizz", home: "/foo/bar", wantPath: "/foo/bar/fizz"}, |
| 2893 |
|
| 2894 |
// missing HOME env var |
| 2895 |
{path: "~/fizz", wantErr: true}, |
| 2896 |
} |
| 2897 |
for i, c := range cases { |
| 2898 |
t.Run(fmt.Sprintf("unix case %d", i), func(t *testing.T) { |
| 2899 |
os.Setenv("HOME", c.home) |
| 2900 |
|
| 2901 |
gotPath, err := expandPath(c.path) |
| 2902 |
if !c.wantErr && err != nil { |
| 2903 |
t.Fatalf("unexpected error: got=%v; want=%v", err, nil) |
| 2904 |
} else if c.wantErr && err == nil { |
| 2905 |
t.Fatalf("unexpected success: got=%v; want=%v", nil, "err") |
| 2906 |
} |
| 2907 |
|
| 2908 |
if gotPath != c.wantPath { |
| 2909 |
t.Fatalf("unexpected path: got=%v; want=%v", gotPath, c.wantPath) |
| 2910 |
} |
| 2911 |
}) |
| 2912 |
} |
| 2913 |
} |
| 2914 |
|
| 2915 |
func TestNoAuthUserCode(t *testing.T) { |
| 2916 |
confFileName := createConfFile(t, []byte(` |
| 2917 |
listen: "127.0.0.1:-1" |
| 2918 |
no_auth_user: $NO_AUTH_USER |
| 2919 |
|
| 2920 |
accounts { |
| 2921 |
synadia { |
| 2922 |
users [ |
| 2923 |
{user: "a", password: "a"}, |
| 2924 |
{nkey : UBAAQWTW6CG2G6ANGNKB5U2B7HRWHSGMZEZX3AQSAJOQDAUGJD46LD2E}, |
| 2925 |
] |
| 2926 |
} |
| 2927 |
acc { |
| 2928 |
users [ |
| 2929 |
{user: "c", password: "c"} |
| 2930 |
] |
| 2931 |
} |
| 2932 |
} |
| 2933 |
# config for $G |
| 2934 |
authorization { |
| 2935 |
users [ |
| 2936 |
{user: "b", password: "b"} |
| 2937 |
] |
| 2938 |
} |
| 2939 |
`)) |
| 2940 |
defer os.Unsetenv("NO_AUTH_USER") |
| 2941 |
|
| 2942 |
for _, user := range []string{"a", "b", "b"} { |
| 2943 |
t.Run(user, func(t *testing.T) { |
| 2944 |
os.Setenv("NO_AUTH_USER", user) |
| 2945 |
opts, err := ProcessConfigFile(confFileName) |
| 2946 |
if err != nil { |
| 2947 |
t.Fatalf("Received unexpected error %s", err) |
| 2948 |
} else { |
| 2949 |
opts.NoLog = true |
| 2950 |
srv := RunServer(opts) |
| 2951 |
nc, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", opts.Port)) |
| 2952 |
if err != nil { |
| 2953 |
t.Fatalf("couldn't connect %s", err) |
| 2954 |
} |
| 2955 |
nc.Close() |
| 2956 |
srv.Shutdown() |
| 2957 |
} |
| 2958 |
}) |
| 2959 |
} |
| 2960 |
|
| 2961 |
for _, badUser := range []string{"notthere", "UBAAQWTW6CG2G6ANGNKB5U2B7HRWHSGMZEZX3AQSAJOQDAUGJD46LD2F"} { |
| 2962 |
t.Run(badUser, func(t *testing.T) { |
| 2963 |
os.Setenv("NO_AUTH_USER", badUser) |
| 2964 |
opts, err := ProcessConfigFile(confFileName) |
| 2965 |
if err != nil { |
| 2966 |
t.Fatalf("Received unexpected error %s", err) |
| 2967 |
} |
| 2968 |
s, err := NewServer(opts) |
| 2969 |
if err != nil { |
| 2970 |
if !strings.HasPrefix(err.Error(), "no_auth_user") { |
| 2971 |
t.Fatalf("Received unexpected error %s", err) |
| 2972 |
} |
| 2973 |
return // error looks as expected |
| 2974 |
} |
| 2975 |
s.Shutdown() |
| 2976 |
t.Fatalf("Received no error, where no_auth_user error was expected") |
| 2977 |
}) |
| 2978 |
} |
| 2979 |
|
| 2980 |
} |
| 2981 |
|
| 2982 |
const operatorJwtWithSysAccAndUrlResolver = ` |
| 2983 |
listen: "127.0.0.1:-1" |
| 2984 |
operator: eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJJVEdJNjNCUUszM1VNN1pBSzZWT1RXNUZEU01ESlNQU1pRQ0RMNUlLUzZQTVhBU0ROQ01RIiwiaWF0IjoxNTg5ODM5MjA1LCJpc3MiOiJPQ1k2REUyRVRTTjNVT0RGVFlFWEJaTFFMSTdYNEdTWFI1NE5aQzRCQkxJNlFDVFpVVDY1T0lWTiIsIm5hbWUiOiJPUCIsInN1YiI6Ik9DWTZERTJFVFNOM1VPREZUWUVYQlpMUUxJN1g0R1NYUjU0TlpDNEJCTEk2UUNUWlVUNjVPSVZOIiwidHlwZSI6Im9wZXJhdG9yIiwibmF0cyI6eyJhY2NvdW50X3NlcnZlcl91cmwiOiJodHRwOi8vbG9jYWxob3N0OjgwMDAvand0L3YxIiwib3BlcmF0b3Jfc2VydmljZV91cmxzIjpbIm5hdHM6Ly9sb2NhbGhvc3Q6NDIyMiJdLCJzeXN0ZW1fYWNjb3VudCI6IkFEWjU0N0IyNFdIUExXT0s3VE1MTkJTQTdGUUZYUjZVTTJOWjRISE5JQjdSREZWWlFGT1o0R1FRIn19.3u710KqMLwgXwsMvhxfEp9xzK84XyAZ-4dd6QY0T6hGj8Bw9mS-HcQ7HbvDDNU01S61tNFfpma_JR6LtB3ixBg |
| 2985 |
` |
| 2986 |
|
| 2987 |
func TestReadOperatorJWT(t *testing.T) { |
| 2988 |
confFileName := createConfFile(t, []byte(operatorJwtWithSysAccAndUrlResolver)) |
| 2989 |
opts, err := ProcessConfigFile(confFileName) |
| 2990 |
if err != nil { |
| 2991 |
t.Fatalf("Received unexpected error %s", err) |
| 2992 |
} |
| 2993 |
if opts.SystemAccount != "ADZ547B24WHPLWOK7TMLNBSA7FQFXR6UM2NZ4HHNIB7RDFVZQFOZ4GQQ" { |
| 2994 |
t.Fatalf("Expected different SystemAccount: %s", opts.SystemAccount) |
| 2995 |
} |
| 2996 |
if r, ok := opts.AccountResolver.(*URLAccResolver); !ok { |
| 2997 |
t.Fatalf("Expected different SystemAccount: %s", opts.SystemAccount) |
| 2998 |
} else if r.url != "http://localhost:8000/jwt/v1/accounts/" { |
| 2999 |
t.Fatalf("Expected different SystemAccount: %s", r.url) |
| 3000 |
} |
| 3001 |
} |
| 3002 |
|
| 3003 |
const operatorJwtList = ` |
| 3004 |
listen: "127.0.0.1:-1" |
| 3005 |
system_account = SYSACC |
| 3006 |
operator: [ |
| 3007 |
eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJJVEdJNjNCUUszM1VNN1pBSzZWT1RXNUZEU01ESlNQU1pRQ0RMNUlLUzZQTVhBU0ROQ01RIiwiaWF0IjoxNTg5ODM5MjA1LCJpc3MiOiJPQ1k2REUyRVRTTjNVT0RGVFlFWEJaTFFMSTdYNEdTWFI1NE5aQzRCQkxJNlFDVFpVVDY1T0lWTiIsIm5hbWUiOiJPUCIsInN1YiI6Ik9DWTZERTJFVFNOM1VPREZUWUVYQlpMUUxJN1g0R1NYUjU0TlpDNEJCTEk2UUNUWlVUNjVPSVZOIiwidHlwZSI6Im9wZXJhdG9yIiwibmF0cyI6eyJhY2NvdW50X3NlcnZlcl91cmwiOiJodHRwOi8vbG9jYWxob3N0OjgwMDAvand0L3YxIiwib3BlcmF0b3Jfc2VydmljZV91cmxzIjpbIm5hdHM6Ly9sb2NhbGhvc3Q6NDIyMiJdLCJzeXN0ZW1fYWNjb3VudCI6IkFEWjU0N0IyNFdIUExXT0s3VE1MTkJTQTdGUUZYUjZVTTJOWjRISE5JQjdSREZWWlFGT1o0R1FRIn19.3u710KqMLwgXwsMvhxfEp9xzK84XyAZ-4dd6QY0T6hGj8Bw9mS-HcQ7HbvDDNU01S61tNFfpma_JR6LtB3ixBg, |
| 3008 |
eyJ0eXAiOiJKV1QiLCJhbGciOiJlZDI1NTE5LW5rZXkifQ.eyJqdGkiOiIzTVJCS1BRTU1IUjdOQVFQU080NUlWTlkyMzVMRlQyTEs0WkZFVU1KWU9EWUJXU0RXWlRBIiwiaWF0IjoxNzI2NTYwMjAwLCJpc3MiOiJPQkxPR1VCSVVQSkhGVE00RjRaTE9CR1BMSlBJRjRTR0JDWUVERUtFUVNNWVVaTVFTMkRGTUUyWCIsIm5hbWUiOiJvcDIiLCJzdWIiOiJPQkxPR1VCSVVQSkhGVE00RjRaTE9CR1BMSlBJRjRTR0JDWUVERUtFUVNNWVVaTVFTMkRGTUUyWCIsIm5hdHMiOnsic2lnbmluZ19rZXlzIjpbIk9ES0xMSTZWWldWNk03V1RaV0I3MjVITE9MVFFRVERLNE5RR1ZFR0Q0Q083SjJMMlVJWk81U0dXIl0sInN5c3RlbV9hY2NvdW50IjoiQUNRVFdWR1NHSFlWWTNSNkQyV01PM1Y2TFYyTUdLNUI3RzQ3RTQzQkhKQjZGUVZZN0VITlRNTUciLCJ0eXBlIjoib3BlcmF0b3IiLCJ2ZXJzaW9uIjoyfX0.8kUmC6CwGLTJSs1zj_blsMpP5b6n2jZhZFNvMPXvJlRyyR5ZbCsxJ442BimaxaiosS8T-IFcZAIphtiOcqhRCg |
| 3009 |
] |
| 3010 |
` |
| 3011 |
|
| 3012 |
func TestReadMultipleOperatorJWT(t *testing.T) { |
| 3013 |
confFileName := createConfFile(t, []byte(operatorJwtList)) |
| 3014 |
opts, err := ProcessConfigFile(confFileName) |
| 3015 |
if err != nil { |
| 3016 |
t.Fatalf("Received unexpected error %s", err) |
| 3017 |
} |
| 3018 |
|
| 3019 |
require_Equal(t, len(opts.TrustedOperators), 2) |
| 3020 |
require_Equal(t, opts.TrustedOperators[0].Name, "OP") |
| 3021 |
require_Equal(t, opts.TrustedOperators[1].Name, "op2") |
| 3022 |
require_Equal(t, opts.TrustedOperators[0].SystemAccount, "ADZ547B24WHPLWOK7TMLNBSA7FQFXR6UM2NZ4HHNIB7RDFVZQFOZ4GQQ") |
| 3023 |
require_Equal(t, opts.TrustedOperators[1].SystemAccount, "ACQTWVGSGHYVY3R6D2WMO3V6LV2MGK5B7G47E43BHJB6FQVY7EHNTMMG") |
| 3024 |
// check if system account precedence is correct |
| 3025 |
require_Equal(t, opts.SystemAccount, "SYSACC") |
| 3026 |
|
| 3027 |
} |
| 3028 |
|
| 3029 |
// using memory resolver so this test does not have to start the memory resolver |
| 3030 |
const operatorJwtWithSysAccAndMemResolver = ` |
| 3031 |
listen: "127.0.0.1:-1" |
| 3032 |
// Operator "TESTOP" |
| 3033 |
operator: eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiJLRTZRU0tWTU1VWFFKNFZCTDNSNDdGRFlIWElaTDRZSE1INjVIT0k1UjZCNUpPUkxVQlZBIiwiaWF0IjoxNTg5OTE2MzgyLCJpc3MiOiJPQVRUVkJYTElVTVRRT1FXVUEySU0zRkdUQlFRSEFHUEZaQTVET05NTlFSUlRQUjYzTERBTDM1WiIsIm5hbWUiOiJURVNUT1AiLCJzdWIiOiJPQVRUVkJYTElVTVRRT1FXVUEySU0zRkdUQlFRSEFHUEZaQTVET05NTlFSUlRQUjYzTERBTDM1WiIsInR5cGUiOiJvcGVyYXRvciIsIm5hdHMiOnsic3lzdGVtX2FjY291bnQiOiJBRFNQT1lNSFhKTjZKVllRQ0xSWjVYUTVJVU42QTNTMzNYQTROVjRWSDc0NDIzVTdVN1lSNFlWVyJ9fQ.HiyUtlk8kectKHeQHtuqFcjFt0RbYZE_WAqPCcoWlV2IFVdXuOTzShYEMgDmtgvsFG_zxNQOj08Gr6a06ovwBA |
| 3034 |
resolver: MEMORY |
| 3035 |
resolver_preload: { |
| 3036 |
// Account "TESTSYS" |
| 3037 |
ADSPOYMHXJN6JVYQCLRZ5XQ5IUN6A3S33XA4NV4VH74423U7U7YR4YVW: eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5In0.eyJqdGkiOiI2WEtYUFZNTjdEVFlBSUE0R1JDWUxXUElSM1ZEM1Q2UVk2RFg3NURHTVFVWkdVWTJSRFNRIiwiaWF0IjoxNTg5OTE2MzIzLCJpc3MiOiJPQVRUVkJYTElVTVRRT1FXVUEySU0zRkdUQlFRSEFHUEZaQTVET05NTlFSUlRQUjYzTERBTDM1WiIsIm5hbWUiOiJURVNUU1lTIiwic3ViIjoiQURTUE9ZTUhYSk42SlZZUUNMUlo1WFE1SVVONkEzUzMzWEE0TlY0Vkg3NDQyM1U3VTdZUjRZVlciLCJ0eXBlIjoiYWNjb3VudCIsIm5hdHMiOnsibGltaXRzIjp7InN1YnMiOi0xLCJjb25uIjotMSwibGVhZiI6LTEsImltcG9ydHMiOi0xLCJleHBvcnRzIjotMSwiZGF0YSI6LTEsInBheWxvYWQiOi0xLCJ3aWxkY2FyZHMiOnRydWV9fX0.vhtWanIrOncdNfg-yO-7L61ccc-yRacvVtEsaIgWBEmW4czlEPhsiF1MkUKG91rtgcbwUf73ZIFEfja5MgFBAQ |
| 3038 |
} |
| 3039 |
` |
| 3040 |
|
| 3041 |
func TestReadOperatorJWTSystemAccountMatch(t *testing.T) { |
| 3042 |
confFileName := createConfFile(t, []byte(operatorJwtWithSysAccAndMemResolver+` |
| 3043 |
system_account: ADSPOYMHXJN6JVYQCLRZ5XQ5IUN6A3S33XA4NV4VH74423U7U7YR4YVW |
| 3044 |
`)) |
| 3045 |
opts, err := ProcessConfigFile(confFileName) |
| 3046 |
if err != nil { |
| 3047 |
t.Fatalf("Received unexpected error %s", err) |
| 3048 |
} |
| 3049 |
s, err := NewServer(opts) |
| 3050 |
if err != nil { |
| 3051 |
t.Fatalf("Received unexpected error %s", err) |
| 3052 |
} |
| 3053 |
s.Shutdown() |
| 3054 |
} |
| 3055 |
|
| 3056 |
func TestReadOperatorJWTSystemAccountMismatch(t *testing.T) { |
| 3057 |
confFileName := createConfFile(t, []byte(operatorJwtWithSysAccAndMemResolver+` |
| 3058 |
system_account: ADXJJCDCSRSMCOV25FXQW7R4QOG7R763TVEXBNWJHLBMBGWOJYG5XZBG |
| 3059 |
`)) |
| 3060 |
opts, err := ProcessConfigFile(confFileName) |
| 3061 |
if err != nil { |
| 3062 |
t.Fatalf("Received unexpected error %s", err) |
| 3063 |
} |
| 3064 |
s, err := NewServer(opts) |
| 3065 |
if err == nil { |
| 3066 |
s.Shutdown() |
| 3067 |
t.Fatalf("Received no error") |
| 3068 |
} else if !strings.Contains(err.Error(), "system_account in config and operator JWT must be identical") { |
| 3069 |
t.Fatalf("Received unexpected error %s", err) |
| 3070 |
} |
| 3071 |
} |
| 3072 |
|
| 3073 |
func TestReadOperatorAssertVersion(t *testing.T) { |
| 3074 |
kp, _ := nkeys.CreateOperator() |
| 3075 |
pk, _ := kp.PublicKey() |
| 3076 |
op := jwt.NewOperatorClaims(pk) |
| 3077 |
op.AssertServerVersion = "1.2.3" |
| 3078 |
jwt, err := op.Encode(kp) |
| 3079 |
if err != nil { |
| 3080 |
t.Fatalf("Received unexpected error %s", err) |
| 3081 |
} |
| 3082 |
confFileName := createConfFile(t, []byte(fmt.Sprintf(` |
| 3083 |
operator: %s |
| 3084 |
resolver: MEM |
| 3085 |
`, jwt))) |
| 3086 |
opts, err := ProcessConfigFile(confFileName) |
| 3087 |
if err != nil { |
| 3088 |
t.Fatalf("Received unexpected error %s", err) |
| 3089 |
} |
| 3090 |
s, err := NewServer(opts) |
| 3091 |
if err != nil { |
| 3092 |
t.Fatalf("Received unexpected error %s", err) |
| 3093 |
} |
| 3094 |
s.Shutdown() |
| 3095 |
} |
| 3096 |
|
| 3097 |
func TestReadOperatorAssertVersionFail(t *testing.T) { |
| 3098 |
kp, _ := nkeys.CreateOperator() |
| 3099 |
pk, _ := kp.PublicKey() |
| 3100 |
op := jwt.NewOperatorClaims(pk) |
| 3101 |
op.AssertServerVersion = "10.20.30" |
| 3102 |
jwt, err := op.Encode(kp) |
| 3103 |
if err != nil { |
| 3104 |
t.Fatalf("Received unexpected error %s", err) |
| 3105 |
} |
| 3106 |
confFileName := createConfFile(t, []byte(fmt.Sprintf(` |
| 3107 |
operator: %s |
| 3108 |
resolver: MEM |
| 3109 |
`, jwt))) |
| 3110 |
opts, err := ProcessConfigFile(confFileName) |
| 3111 |
if err != nil { |
| 3112 |
t.Fatalf("Received unexpected error %s", err) |
| 3113 |
} |
| 3114 |
s, err := NewServer(opts) |
| 3115 |
if err == nil { |
| 3116 |
s.Shutdown() |
| 3117 |
t.Fatalf("Received no error") |
| 3118 |
} else if !strings.Contains(err.Error(), "expected major version 10 > server major version") { |
| 3119 |
t.Fatal("expected different error got: ", err) |
| 3120 |
} |
| 3121 |
} |
| 3122 |
|
| 3123 |
func TestClusterNameAndGatewayNameConflict(t *testing.T) { |
| 3124 |
conf := createConfFile(t, []byte(` |
| 3125 |
listen: 127.0.0.1:-1 |
| 3126 |
cluster { |
| 3127 |
name: A |
| 3128 |
listen: 127.0.0.1:-1 |
| 3129 |
} |
| 3130 |
gateway { |
| 3131 |
name: B |
| 3132 |
listen: 127.0.0.1:-1 |
| 3133 |
} |
| 3134 |
`)) |
| 3135 |
|
| 3136 |
opts, err := ProcessConfigFile(conf) |
| 3137 |
if err != nil { |
| 3138 |
t.Fatalf("Unexpected error: %v", err) |
| 3139 |
} |
| 3140 |
|
| 3141 |
if err := validateOptions(opts); err != ErrClusterNameConfigConflict { |
| 3142 |
t.Fatalf("Expected ErrClusterNameConfigConflict got %v", err) |
| 3143 |
} |
| 3144 |
} |
| 3145 |
|
| 3146 |
func TestDefaultAuthTimeout(t *testing.T) { |
| 3147 |
opts := DefaultOptions() |
| 3148 |
opts.AuthTimeout = 0 |
| 3149 |
s := RunServer(opts) |
| 3150 |
defer s.Shutdown() |
| 3151 |
|
| 3152 |
sopts := s.getOpts() |
| 3153 |
if at := time.Duration(sopts.AuthTimeout * float64(time.Second)); at != AUTH_TIMEOUT { |
| 3154 |
t.Fatalf("Expected auth timeout to be %v, got %v", AUTH_TIMEOUT, at) |
| 3155 |
} |
| 3156 |
s.Shutdown() |
| 3157 |
|
| 3158 |
opts = DefaultOptions() |
| 3159 |
tc := &TLSConfigOpts{ |
| 3160 |
CertFile: "../test/configs/certs/server-cert.pem", |
| 3161 |
KeyFile: "../test/configs/certs/server-key.pem", |
| 3162 |
CaFile: "../test/configs/certs/ca.pem", |
| 3163 |
Timeout: 4.0, |
| 3164 |
} |
| 3165 |
tlsConfig, err := GenTLSConfig(tc) |
| 3166 |
if err != nil { |
| 3167 |
t.Fatalf("Error generating tls config: %v", err) |
| 3168 |
} |
| 3169 |
opts.TLSConfig = tlsConfig |
| 3170 |
opts.TLSTimeout = tc.Timeout |
| 3171 |
s = RunServer(opts) |
| 3172 |
defer s.Shutdown() |
| 3173 |
|
| 3174 |
sopts = s.getOpts() |
| 3175 |
if sopts.AuthTimeout != 5 { |
| 3176 |
t.Fatalf("Expected auth timeout to be %v, got %v", 5, sopts.AuthTimeout) |
| 3177 |
} |
| 3178 |
} |
| 3179 |
|
| 3180 |
func TestQueuePermissions(t *testing.T) { |
| 3181 |
cfgFmt := ` |
| 3182 |
listen: 127.0.0.1:-1 |
| 3183 |
no_auth_user: u |
| 3184 |
authorization { |
| 3185 |
users [{ |
| 3186 |
user: u, password: pwd, permissions: { sub: { %s: ["foo.> *.dev"] } } |
| 3187 |
}] |
| 3188 |
}` |
| 3189 |
errChan := make(chan error, 1) |
| 3190 |
defer close(errChan) |
| 3191 |
for _, test := range []struct { |
| 3192 |
permType string |
| 3193 |
queue string |
| 3194 |
errExpected bool |
| 3195 |
}{ |
| 3196 |
{"allow", "queue.dev", false}, |
| 3197 |
{"allow", "", true}, |
| 3198 |
{"allow", "bad", true}, |
| 3199 |
{"deny", "", false}, |
| 3200 |
{"deny", "queue.dev", true}, |
| 3201 |
} { |
| 3202 |
t.Run(test.permType+test.queue, func(t *testing.T) { |
| 3203 |
confFileName := createConfFile(t, []byte(fmt.Sprintf(cfgFmt, test.permType))) |
| 3204 |
opts, err := ProcessConfigFile(confFileName) |
| 3205 |
if err != nil { |
| 3206 |
t.Fatalf("Received unexpected error %s", err) |
| 3207 |
} |
| 3208 |
opts.NoLog, opts.NoSigs = true, true |
| 3209 |
s := RunServer(opts) |
| 3210 |
defer s.Shutdown() |
| 3211 |
nc, err := nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", opts.Port), |
| 3212 |
nats.ErrorHandler(func(conn *nats.Conn, s *nats.Subscription, err error) { |
| 3213 |
errChan <- err |
| 3214 |
})) |
| 3215 |
if err != nil { |
| 3216 |
t.Fatalf("No error expected: %v", err) |
| 3217 |
} |
| 3218 |
defer nc.Close() |
| 3219 |
if test.queue == "" { |
| 3220 |
if _, err := nc.Subscribe("foo.bar", func(msg *nats.Msg) {}); err != nil { |
| 3221 |
t.Fatalf("no error expected: %v", err) |
| 3222 |
} |
| 3223 |
} else { |
| 3224 |
if _, err := nc.QueueSubscribe("foo.bar", test.queue, func(msg *nats.Msg) {}); err != nil { |
| 3225 |
t.Fatalf("no error expected: %v", err) |
| 3226 |
} |
| 3227 |
} |
| 3228 |
nc.Flush() |
| 3229 |
select { |
| 3230 |
case err := <-errChan: |
| 3231 |
if !test.errExpected { |
| 3232 |
t.Fatalf("Expected no error, got %v", err) |
| 3233 |
} |
| 3234 |
if !strings.Contains(err.Error(), `Permissions Violation for Subscription to "foo.bar"`) { |
| 3235 |
t.Fatalf("error %v", err) |
| 3236 |
} |
| 3237 |
case <-time.After(150 * time.Millisecond): |
| 3238 |
if test.errExpected { |
| 3239 |
t.Fatal("Expected an error") |
| 3240 |
} |
| 3241 |
} |
| 3242 |
}) |
| 3243 |
|
| 3244 |
} |
| 3245 |
} |
| 3246 |
|
| 3247 |
func TestQueueQualifierOnlyAllowedForSubscribePermissions(t *testing.T) { |
| 3248 |
for _, tc := range []struct { |
| 3249 |
name string |
| 3250 |
config string |
| 3251 |
shouldErr bool |
| 3252 |
}{ |
| 3253 |
{ |
| 3254 |
name: "subscribe deny", |
| 3255 |
config: ` |
| 3256 |
authorization { |
| 3257 |
users: [{ |
| 3258 |
user: u |
| 3259 |
password: p |
| 3260 |
permissions: { subscribe: { deny: ["admin.secret workers"] } } |
| 3261 |
}] |
| 3262 |
} |
| 3263 |
`, |
| 3264 |
}, |
| 3265 |
{ |
| 3266 |
name: "publish deny", |
| 3267 |
config: ` |
| 3268 |
authorization { |
| 3269 |
users: [{ |
| 3270 |
user: u |
| 3271 |
password: p |
| 3272 |
permissions: { publish: { deny: ["admin.secret workers"] } } |
| 3273 |
}] |
| 3274 |
} |
| 3275 |
`, |
| 3276 |
shouldErr: true, |
| 3277 |
}, |
| 3278 |
{ |
| 3279 |
name: "leaf deny imports", |
| 3280 |
config: ` |
| 3281 |
leafnodes { |
| 3282 |
remotes: [{ |
| 3283 |
url: "nats://127.0.0.1:7422" |
| 3284 |
deny_imports: ["admin.secret workers"] |
| 3285 |
}] |
| 3286 |
} |
| 3287 |
`, |
| 3288 |
shouldErr: true, |
| 3289 |
}, |
| 3290 |
{ |
| 3291 |
name: "leaf deny exports", |
| 3292 |
config: ` |
| 3293 |
leafnodes { |
| 3294 |
remotes: [{ |
| 3295 |
url: "nats://127.0.0.1:7422" |
| 3296 |
deny_exports: ["admin.secret workers"] |
| 3297 |
}] |
| 3298 |
} |
| 3299 |
`, |
| 3300 |
shouldErr: true, |
| 3301 |
}, |
| 3302 |
{ |
| 3303 |
name: "cluster export deny", |
| 3304 |
config: ` |
| 3305 |
cluster { |
| 3306 |
name: "C" |
| 3307 |
permissions { |
| 3308 |
export { deny: ["admin.secret workers"] } |
| 3309 |
} |
| 3310 |
} |
| 3311 |
`, |
| 3312 |
shouldErr: true, |
| 3313 |
}, |
| 3314 |
} { |
| 3315 |
t.Run(tc.name, func(t *testing.T) { |
| 3316 |
conf := createConfFile(t, []byte(tc.config)) |
| 3317 |
_, err := ProcessConfigFile(conf) |
| 3318 |
if tc.shouldErr && err == nil { |
| 3319 |
t.Fatal("Expected queue-qualified permission to be rejected") |
| 3320 |
} |
| 3321 |
if !tc.shouldErr && err != nil { |
| 3322 |
t.Fatalf("Expected queue-qualified subscribe permission to be accepted, got %v", err) |
| 3323 |
} |
| 3324 |
}) |
| 3325 |
} |
| 3326 |
|
| 3327 |
opts := DefaultOptions() |
| 3328 |
opts.Cluster.Permissions = &RoutePermissions{ |
| 3329 |
Export: &SubjectPermission{Deny: []string{"admin.secret workers"}}, |
| 3330 |
} |
| 3331 |
if _, err := NewServer(opts); err == nil { |
| 3332 |
t.Fatal("Expected programmatic queue-qualified cluster export permission to be rejected") |
| 3333 |
} |
| 3334 |
} |
| 3335 |
|
| 3336 |
func TestResolverPinnedAccountsFail(t *testing.T) { |
| 3337 |
cfgFmt := ` |
| 3338 |
operator: %s |
| 3339 |
resolver: URL(foo.bar) |
| 3340 |
resolver_pinned_accounts: [%s] |
| 3341 |
` |
| 3342 |
|
| 3343 |
conf := createConfFile(t, []byte(fmt.Sprintf(cfgFmt, ojwt, "f"))) |
| 3344 |
srv, err := NewServer(LoadConfig(conf)) |
| 3345 |
defer srv.Shutdown() |
| 3346 |
require_Error(t, err) |
| 3347 |
require_Contains(t, err.Error(), " is not a valid public account nkey") |
| 3348 |
|
| 3349 |
conf = createConfFile(t, []byte(fmt.Sprintf(cfgFmt, ojwt, "1, x"))) |
| 3350 |
_, err = ProcessConfigFile(conf) |
| 3351 |
require_Error(t, err) |
| 3352 |
require_Contains(t, "parsing resolver_pinned_accounts: unsupported type") |
| 3353 |
} |
| 3354 |
|
| 3355 |
func TestMaxSubTokens(t *testing.T) { |
| 3356 |
conf := createConfFile(t, []byte(` |
| 3357 |
listen: 127.0.0.1:-1 |
| 3358 |
max_sub_tokens: 4 |
| 3359 |
`)) |
| 3360 |
|
| 3361 |
s, _ := RunServerWithConfig(conf) |
| 3362 |
defer s.Shutdown() |
| 3363 |
|
| 3364 |
nc, err := nats.Connect(s.ClientURL()) |
| 3365 |
require_NoError(t, err) |
| 3366 |
defer nc.Close() |
| 3367 |
|
| 3368 |
errs := make(chan error, 1) |
| 3369 |
|
| 3370 |
nc.SetErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, err error) { |
| 3371 |
errs <- err |
| 3372 |
}) |
| 3373 |
|
| 3374 |
bad := "a.b.c.d.e" |
| 3375 |
_, err = nc.SubscribeSync(bad) |
| 3376 |
require_NoError(t, err) |
| 3377 |
|
| 3378 |
select { |
| 3379 |
case e := <-errs: |
| 3380 |
if !strings.Contains(e.Error(), "too many tokens") { |
| 3381 |
t.Fatalf("Got wrong error: %v", err) |
| 3382 |
} |
| 3383 |
case <-time.After(2 * time.Second): |
| 3384 |
t.Fatal("Did not get the permissions error") |
| 3385 |
} |
| 3386 |
} |
| 3387 |
|
| 3388 |
func TestGetStorageSize(t *testing.T) { |
| 3389 |
tt := []struct { |
| 3390 |
input string |
| 3391 |
want int64 |
| 3392 |
err bool |
| 3393 |
}{ |
| 3394 |
{"1K", 1024, false}, |
| 3395 |
{"1M", 1048576, false}, |
| 3396 |
{"1G", 1073741824, false}, |
| 3397 |
{"1T", 1099511627776, false}, |
| 3398 |
{"1L", 0, true}, |
| 3399 |
{"TT", 0, true}, |
| 3400 |
{"", 0, false}, |
| 3401 |
} |
| 3402 |
|
| 3403 |
for _, v := range tt { |
| 3404 |
var testErr bool |
| 3405 |
got, err := getStorageSize(v.input) |
| 3406 |
if err != nil { |
| 3407 |
testErr = true |
| 3408 |
} |
| 3409 |
|
| 3410 |
if got != v.want || v.err != testErr { |
| 3411 |
t.Errorf("Got: %v, want %v with error: %v", got, v.want, testErr) |
| 3412 |
} |
| 3413 |
} |
| 3414 |
|
| 3415 |
} |
| 3416 |
|
| 3417 |
func TestAuthorizationAndAccountsMisconfigurations(t *testing.T) { |
| 3418 |
// There is a test called TestConfigCheck but we can't use it |
| 3419 |
// because the place where the error will be reported will depend |
| 3420 |
// if the error is found while parsing authorization{} or |
| 3421 |
// accounts{}, but we can't control the internal parsing of those |
| 3422 |
// (due to lexer giving back a map and iteration over map is random) |
| 3423 |
// regardless of the ordering in the configuration file. |
| 3424 |
// The test is also repeated |
| 3425 |
for _, test := range []struct { |
| 3426 |
name string |
| 3427 |
config string |
| 3428 |
err string |
| 3429 |
}{ |
| 3430 |
{ |
| 3431 |
"duplicate users", |
| 3432 |
` |
| 3433 |
authorization = {users = [ {user: "user1", pass: "pwd"} ] } |
| 3434 |
accounts { ACC { users = [ {user: "user1"} ] } } |
| 3435 |
`, |
| 3436 |
fmt.Sprintf("Duplicate user %q detected", "user1"), |
| 3437 |
}, |
| 3438 |
{ |
| 3439 |
"duplicate nkey", |
| 3440 |
` |
| 3441 |
authorization = {users = [ {nkey: UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX} ] } |
| 3442 |
accounts { ACC { users = [ {nkey: UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX} ] } } |
| 3443 |
`, |
| 3444 |
fmt.Sprintf("Duplicate nkey %q detected", "UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX"), |
| 3445 |
}, |
| 3446 |
{ |
| 3447 |
"auth single user and password and accounts users", |
| 3448 |
` |
| 3449 |
authorization = {user: "user1", password: "pwd"} |
| 3450 |
accounts = { ACC { users = [ {user: "user2", pass: "pwd"} ] } } |
| 3451 |
`, |
| 3452 |
"Can not have a single user/pass", |
| 3453 |
}, |
| 3454 |
{ |
| 3455 |
"auth single user and password and accounts nkeys", |
| 3456 |
` |
| 3457 |
authorization = {user: "user1", password: "pwd"} |
| 3458 |
accounts = { ACC { users = [ {nkey: UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX} ] } } |
| 3459 |
`, |
| 3460 |
"Can not have a single user/pass", |
| 3461 |
}, |
| 3462 |
{ |
| 3463 |
"auth token and accounts users", |
| 3464 |
` |
| 3465 |
authorization = {token: "my_token"} |
| 3466 |
accounts = { ACC { users = [ {user: "user2", pass: "pwd"} ] } } |
| 3467 |
`, |
| 3468 |
"Can not have a token", |
| 3469 |
}, |
| 3470 |
{ |
| 3471 |
"auth token and accounts nkeys", |
| 3472 |
` |
| 3473 |
authorization = {token: "my_token"} |
| 3474 |
accounts = { ACC { users = [ {nkey: UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX} ] } } |
| 3475 |
`, |
| 3476 |
"Can not have a token", |
| 3477 |
}, |
| 3478 |
{ |
| 3479 |
"auth callout allowed accounts", |
| 3480 |
` |
| 3481 |
accounts { |
| 3482 |
AUTH { users = [ {user: "auth", password: "auth"} ] } |
| 3483 |
FOO {} |
| 3484 |
} |
| 3485 |
authorization { |
| 3486 |
auth_callout { |
| 3487 |
issuer: "ABJHLOVMPA4CI6R5KLNGOB4GSLNIY7IOUPAJC4YFNDLQVIOBYQGUWVLA" |
| 3488 |
account: AUTH |
| 3489 |
auth_users: [ auth ] |
| 3490 |
allowed_accounts: [ BAR ] |
| 3491 |
} |
| 3492 |
} |
| 3493 |
`, |
| 3494 |
"auth_callout allowed account \"BAR\" not found in configured accounts", |
| 3495 |
}, |
| 3496 |
} { |
| 3497 |
t.Run(test.name, func(t *testing.T) { |
| 3498 |
conf := createConfFile(t, []byte(test.config)) |
| 3499 |
if _, err := ProcessConfigFile(conf); err == nil || !strings.Contains(err.Error(), test.err) { |
| 3500 |
t.Fatalf("Expected error %q, got %q", test.err, err.Error()) |
| 3501 |
} |
| 3502 |
}) |
| 3503 |
} |
| 3504 |
} |
| 3505 |
|
| 3506 |
// TestProcessConfigString duplicates the previous test, but uses the (*Options).ProcessConfigString |
| 3507 |
// instead of the ProcessConfigFile function. |
| 3508 |
func TestProcessConfigString(t *testing.T) { |
| 3509 |
for _, test := range []struct { |
| 3510 |
name string |
| 3511 |
config string |
| 3512 |
err string |
| 3513 |
}{ |
| 3514 |
{ |
| 3515 |
"duplicate users", |
| 3516 |
` |
| 3517 |
authorization = {users = [ {user: "user1", pass: "pwd"} ] } |
| 3518 |
accounts { ACC { users = [ {user: "user1"} ] } } |
| 3519 |
`, |
| 3520 |
fmt.Sprintf("Duplicate user %q detected", "user1"), |
| 3521 |
}, |
| 3522 |
{ |
| 3523 |
"duplicate nkey", |
| 3524 |
` |
| 3525 |
authorization = {users = [ {nkey: UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX} ] } |
| 3526 |
accounts { ACC { users = [ {nkey: UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX} ] } } |
| 3527 |
`, |
| 3528 |
fmt.Sprintf("Duplicate nkey %q detected", "UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX"), |
| 3529 |
}, |
| 3530 |
{ |
| 3531 |
"auth single user and password and accounts users", |
| 3532 |
` |
| 3533 |
authorization = {user: "user1", password: "pwd"} |
| 3534 |
accounts = { ACC { users = [ {user: "user2", pass: "pwd"} ] } } |
| 3535 |
`, |
| 3536 |
"Can not have a single user/pass", |
| 3537 |
}, |
| 3538 |
{ |
| 3539 |
"auth single user and password and accounts nkeys", |
| 3540 |
` |
| 3541 |
authorization = {user: "user1", password: "pwd"} |
| 3542 |
accounts = { ACC { users = [ {nkey: UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX} ] } } |
| 3543 |
`, |
| 3544 |
"Can not have a single user/pass", |
| 3545 |
}, |
| 3546 |
{ |
| 3547 |
"auth token and accounts users", |
| 3548 |
` |
| 3549 |
authorization = {token: "my_token"} |
| 3550 |
accounts = { ACC { users = [ {user: "user2", pass: "pwd"} ] } } |
| 3551 |
`, |
| 3552 |
"Can not have a token", |
| 3553 |
}, |
| 3554 |
{ |
| 3555 |
"auth token and accounts nkeys", |
| 3556 |
` |
| 3557 |
authorization = {token: "my_token"} |
| 3558 |
accounts = { ACC { users = [ {nkey: UC6NLCN7AS34YOJVCYD4PJ3QB7QGLYG5B5IMBT25VW5K4TNUJODM7BOX} ] } } |
| 3559 |
`, |
| 3560 |
"Can not have a token", |
| 3561 |
}, |
| 3562 |
{ |
| 3563 |
"auth callout allowed accounts", |
| 3564 |
` |
| 3565 |
accounts { |
| 3566 |
AUTH { users = [ {user: "auth", password: "auth"} ] } |
| 3567 |
FOO {} |
| 3568 |
} |
| 3569 |
authorization { |
| 3570 |
auth_callout { |
| 3571 |
issuer: "ABJHLOVMPA4CI6R5KLNGOB4GSLNIY7IOUPAJC4YFNDLQVIOBYQGUWVLA" |
| 3572 |
account: AUTH |
| 3573 |
auth_users: [ auth ] |
| 3574 |
allowed_accounts: [ BAR ] |
| 3575 |
} |
| 3576 |
} |
| 3577 |
`, |
| 3578 |
"auth_callout allowed account \"BAR\" not found in configured accounts", |
| 3579 |
}, |
| 3580 |
} { |
| 3581 |
t.Run(test.name, func(t *testing.T) { |
| 3582 |
opts := &Options{} |
| 3583 |
if err := opts.ProcessConfigString(test.config); err == nil || !strings.Contains(err.Error(), test.err) { |
| 3584 |
t.Fatalf("Expected error %q, got %q", test.err, err.Error()) |
| 3585 |
} |
| 3586 |
}) |
| 3587 |
} |
| 3588 |
} |
| 3589 |
|
| 3590 |
func TestDefaultSentinel(t *testing.T) { |
| 3591 |
d := ` |
| 3592 |
default_sentinel: "hello" |
| 3593 |
` |
| 3594 |
conf := createConfFile(t, []byte(d)) |
| 3595 |
opts := LoadConfig(conf) |
| 3596 |
require_Equal(t, "hello", opts.DefaultSentinel) |
| 3597 |
|
| 3598 |
// if we validate, it will fail, we need an operator |
| 3599 |
// tests verifying run of configured, elsewhere |
| 3600 |
err := validateOptions(opts) |
| 3601 |
require_Error(t, err) |
| 3602 |
require_Equal(t, "default sentinel requires operators and accounts", err.Error()) |
| 3603 |
} |
| 3604 |
|
| 3605 |
func TestAuthorizationTimeoutConfigParsing(t *testing.T) { |
| 3606 |
type testCase struct { |
| 3607 |
name string |
| 3608 |
config string |
| 3609 |
expectParsed float64 |
| 3610 |
expectRunning float64 |
| 3611 |
expectErrorContains string |
| 3612 |
} |
| 3613 |
|
| 3614 |
for _, tc := range []testCase{{ |
| 3615 |
name: "defaults", |
| 3616 |
config: "authorization {}", |
| 3617 |
expectParsed: 0, |
| 3618 |
expectRunning: 2, |
| 3619 |
}, { |
| 3620 |
name: "explicit zero", |
| 3621 |
config: ` |
| 3622 |
authorization { |
| 3623 |
timeout: 0 |
| 3624 |
}`, |
| 3625 |
expectParsed: 0, |
| 3626 |
expectRunning: 2, |
| 3627 |
}, { |
| 3628 |
name: "explicit one", |
| 3629 |
config: ` |
| 3630 |
authorization { |
| 3631 |
timeout: 1 |
| 3632 |
}`, |
| 3633 |
expectParsed: 1, |
| 3634 |
expectRunning: 1, |
| 3635 |
}, { |
| 3636 |
name: "garbage", |
| 3637 |
config: ` |
| 3638 |
authorization { |
| 3639 |
timeout: random_garbage |
| 3640 |
}`, |
| 3641 |
expectErrorContains: `invalid duration "random_garbage"`, |
| 3642 |
}, { |
| 3643 |
name: "human readable", |
| 3644 |
config: ` |
| 3645 |
authorization { |
| 3646 |
timeout: 10s |
| 3647 |
}`, |
| 3648 |
expectParsed: 10, |
| 3649 |
expectRunning: 10, |
| 3650 |
}, { |
| 3651 |
name: "bare values could be parsed as integers", |
| 3652 |
config: ` |
| 3653 |
authorization { |
| 3654 |
timeout: 1m |
| 3655 |
}`, |
| 3656 |
expectParsed: 1000000, |
| 3657 |
expectRunning: 1000000, |
| 3658 |
}, { |
| 3659 |
name: "but quoted values will be parsed as durations", |
| 3660 |
config: ` |
| 3661 |
authorization { |
| 3662 |
timeout: "1m" |
| 3663 |
}`, |
| 3664 |
expectParsed: 60, |
| 3665 |
expectRunning: 60, |
| 3666 |
}, { |
| 3667 |
name: "human readable minutes quoted", |
| 3668 |
config: ` |
| 3669 |
authorization { |
| 3670 |
timeout: "10m5s30ms" |
| 3671 |
}`, |
| 3672 |
expectParsed: 605.03, |
| 3673 |
expectRunning: 605.03, |
| 3674 |
}, { |
| 3675 |
name: "floats work", |
| 3676 |
config: ` |
| 3677 |
authorization { |
| 3678 |
timeout: 0.091 |
| 3679 |
}`, |
| 3680 |
expectParsed: .091, |
| 3681 |
expectRunning: .091, |
| 3682 |
}, { |
| 3683 |
name: "but no leading digit fails", |
| 3684 |
config: ` |
| 3685 |
authorization { |
| 3686 |
timeout: .091 |
| 3687 |
}`, |
| 3688 |
expectErrorContains: "Floats must start with a digit", |
| 3689 |
}} { |
| 3690 |
t.Run(tc.name, func(t *testing.T) { |
| 3691 |
opts, err := parseConfigTolerantly(t, tc.config) |
| 3692 |
if tc.expectErrorContains != "" { |
| 3693 |
if !strings.Contains(err.Error(), tc.expectErrorContains) { |
| 3694 |
t.Errorf("Expected error like %q, got %v", tc.expectErrorContains, err) |
| 3695 |
} |
| 3696 |
return |
| 3697 |
} else { |
| 3698 |
if err != nil { |
| 3699 |
t.Errorf("Error processing config: %v", err) |
| 3700 |
} |
| 3701 |
} |
| 3702 |
|
| 3703 |
if opts.AuthTimeout != tc.expectParsed { |
| 3704 |
t.Errorf("Expected Parsed AuthTimeout to be %f, got %f", tc.expectParsed, opts.AuthTimeout) |
| 3705 |
} |
| 3706 |
|
| 3707 |
s := RunServer(opts) |
| 3708 |
defer s.Shutdown() |
| 3709 |
|
| 3710 |
sopts := s.getOpts() |
| 3711 |
if sopts.AuthTimeout != tc.expectRunning { |
| 3712 |
t.Errorf("Expected Running AuthTimeout to be %f, got %f", tc.expectRunning, sopts.AuthTimeout) |
| 3713 |
} |
| 3714 |
}) |
| 3715 |
} |
| 3716 |
} |
| 3717 |
|
| 3718 |
func TestLeafnodeAuthorizationTimeoutConfigParsing(t *testing.T) { |
| 3719 |
type testCase struct { |
| 3720 |
name string |
| 3721 |
config string |
| 3722 |
expect float64 |
| 3723 |
expectErrorContains string |
| 3724 |
} |
| 3725 |
|
| 3726 |
for _, tc := range []testCase{{ |
| 3727 |
name: "defaults", |
| 3728 |
config: "leafnodes { authorization {} }", |
| 3729 |
expect: 0, |
| 3730 |
}, { |
| 3731 |
name: "explicit zero", |
| 3732 |
config: ` |
| 3733 |
leafnodes { |
| 3734 |
authorization { |
| 3735 |
timeout: 0 |
| 3736 |
} |
| 3737 |
}`, |
| 3738 |
expect: 0, |
| 3739 |
}, { |
| 3740 |
name: "explicit one", |
| 3741 |
config: ` |
| 3742 |
leafnodes { |
| 3743 |
authorization { |
| 3744 |
timeout: 1 |
| 3745 |
} |
| 3746 |
}`, |
| 3747 |
expect: 1, |
| 3748 |
}, { |
| 3749 |
name: "garbage", |
| 3750 |
config: ` |
| 3751 |
leafnodes { |
| 3752 |
authorization { |
| 3753 |
timeout: random_garbage |
| 3754 |
} |
| 3755 |
}`, |
| 3756 |
expectErrorContains: `invalid duration "random_garbage"`, |
| 3757 |
}, { |
| 3758 |
name: "human readable", |
| 3759 |
config: ` |
| 3760 |
leafnodes { |
| 3761 |
authorization { |
| 3762 |
timeout: 10s |
| 3763 |
} |
| 3764 |
}`, |
| 3765 |
expect: 10, |
| 3766 |
}, { |
| 3767 |
name: "bare values could be parsed as integers", |
| 3768 |
config: ` |
| 3769 |
leafnodes { |
| 3770 |
authorization { |
| 3771 |
timeout: 1m |
| 3772 |
} |
| 3773 |
}`, |
| 3774 |
expect: 1000000, |
| 3775 |
}, { |
| 3776 |
name: "but quoted values will be parsed as durations", |
| 3777 |
config: ` |
| 3778 |
leafnodes { |
| 3779 |
authorization { |
| 3780 |
timeout: "1m" |
| 3781 |
} |
| 3782 |
}`, |
| 3783 |
expect: 60, |
| 3784 |
}, { |
| 3785 |
name: "human readable minutes quoted", |
| 3786 |
config: ` |
| 3787 |
leafnodes { |
| 3788 |
authorization { |
| 3789 |
timeout: "10m5s30ms" |
| 3790 |
} |
| 3791 |
}`, |
| 3792 |
expect: 605.03, |
| 3793 |
}, { |
| 3794 |
name: "floats work", |
| 3795 |
config: ` |
| 3796 |
leafnodes { |
| 3797 |
authorization { |
| 3798 |
timeout: 0.091 |
| 3799 |
} |
| 3800 |
}`, |
| 3801 |
expect: .091, |
| 3802 |
}, { |
| 3803 |
name: "but no leading digit fails", |
| 3804 |
config: ` |
| 3805 |
leafnodes { |
| 3806 |
authorization { |
| 3807 |
timeout: .091 |
| 3808 |
} |
| 3809 |
}`, |
| 3810 |
expectErrorContains: "Floats must start with a digit", |
| 3811 |
}} { |
| 3812 |
t.Run(tc.name, func(t *testing.T) { |
| 3813 |
opts, err := parseConfigTolerantly(t, tc.config) |
| 3814 |
if tc.expectErrorContains != "" { |
| 3815 |
if !strings.Contains(err.Error(), tc.expectErrorContains) { |
| 3816 |
t.Errorf("Expected error like %q, got %v", tc.expectErrorContains, err) |
| 3817 |
} |
| 3818 |
return |
| 3819 |
} else { |
| 3820 |
if err != nil { |
| 3821 |
t.Errorf("Error processing config: %v", err) |
| 3822 |
} |
| 3823 |
} |
| 3824 |
|
| 3825 |
if opts.LeafNode.AuthTimeout != tc.expect { |
| 3826 |
t.Errorf("Expected Parsed LeafNode AuthTimeout to be %f, got %f", tc.expect, opts.LeafNode.AuthTimeout) |
| 3827 |
} |
| 3828 |
}) |
| 3829 |
} |
| 3830 |
} |
| 3831 |
|
| 3832 |
func parseConfigTolerantly(t *testing.T, data string) (*Options, error) { |
| 3833 |
t.Helper() |
| 3834 |
|
| 3835 |
m, err := conf.ParseWithChecks(data) |
| 3836 |
if err != nil { |
| 3837 |
return nil, err |
| 3838 |
} |
| 3839 |
|
| 3840 |
o := new(Options) |
| 3841 |
if err = o.processConfigFile(_EMPTY_, m); err != nil { |
| 3842 |
switch v := err.(type) { |
| 3843 |
case *processConfigErr: |
| 3844 |
if len(v.errors) > 0 { |
| 3845 |
return o, err |
| 3846 |
} |
| 3847 |
for _, w := range v.warnings { |
| 3848 |
t.Logf("WARNING: %v", w) |
| 3849 |
} |
| 3850 |
return o, nil |
| 3851 |
default: |
| 3852 |
t.Logf("Unexpected error type %T", v) |
| 3853 |
return o, err |
| 3854 |
} |
| 3855 |
} |
| 3856 |
|
| 3857 |
return o, nil |
| 3858 |
} |
| 3859 |
|
| 3860 |
func TestOptionsProxyTrustedKeys(t *testing.T) { |
| 3861 |
o := DefaultOptions() |
| 3862 |
o.Proxies = &ProxiesConfig{ |
| 3863 |
Trusted: []*ProxyConfig{ |
| 3864 |
{Key: "UCARKS2E3KVB7YORL2DG34XLT7PUCOL2SVM7YXV6ETHLW6Z46UUJ2VZ3"}, |
| 3865 |
{Key: "bad1"}, |
| 3866 |
{Key: "UD6AYQSOIN2IN5OGC6VQZCR4H3UFMIOXSW6NNS6N53CLJA4PB56CEJJI"}, |
| 3867 |
{Key: "bad2"}, |
| 3868 |
}, |
| 3869 |
} |
| 3870 |
err := validateOptions(o) |
| 3871 |
require_Error(t, err) |
| 3872 |
require_Equal(t, "proxy trusted key \"bad1\" is invalid", err.Error()) |
| 3873 |
|
| 3874 |
o.Proxies = &ProxiesConfig{ |
| 3875 |
Trusted: []*ProxyConfig{ |
| 3876 |
{Key: "UCARKS2E3KVB7YORL2DG34XLT7PUCOL2SVM7YXV6ETHLW6Z46UUJ2VZ3"}, |
| 3877 |
{Key: "UD6AYQSOIN2IN5OGC6VQZCR4H3UFMIOXSW6NNS6N53CLJA4PB56CEJJI"}, |
| 3878 |
}, |
| 3879 |
} |
| 3880 |
s := RunServer(o) |
| 3881 |
defer s.Shutdown() |
| 3882 |
|
| 3883 |
s.mu.RLock() |
| 3884 |
defer s.mu.RUnlock() |
| 3885 |
opts := s.getOpts() |
| 3886 |
for i, kp := range s.proxiesKeyPairs { |
| 3887 |
pub, err := kp.PublicKey() |
| 3888 |
require_NoError(t, err) |
| 3889 |
require_Equal(t, opts.Proxies.Trusted[i].Key, pub) |
| 3890 |
} |
| 3891 |
} |
| 3892 |
|
| 3893 |
func TestOptionsProxyRequired(t *testing.T) { |
| 3894 |
conf := createConfFile(t, []byte(` |
| 3895 |
port: -1 |
| 3896 |
authorization { |
| 3897 |
user: user |
| 3898 |
password: pwd |
| 3899 |
proxy_required: true |
| 3900 |
} |
| 3901 |
`)) |
| 3902 |
o, err := ProcessConfigFile(conf) |
| 3903 |
require_NoError(t, err) |
| 3904 |
require_Equal(t, o.Username, "user") |
| 3905 |
require_Equal(t, o.Password, "pwd") |
| 3906 |
require_True(t, o.ProxyRequired) |
| 3907 |
|
| 3908 |
conf = createConfFile(t, []byte(` |
| 3909 |
port: -1 |
| 3910 |
authorization { |
| 3911 |
users: [ |
| 3912 |
{user: user1, password: pwd1} |
| 3913 |
{user: user2, password: pwd2, proxy_required: true} |
| 3914 |
{user: user3, password: pwd3, proxy_required: false} |
| 3915 |
{nkey: "UCARKS2E3KVB7YORL2DG34XLT7PUCOL2SVM7YXV6ETHLW6Z46UUJ2VZ3", proxy_required: true} |
| 3916 |
{nkey: "UD6AYQSOIN2IN5OGC6VQZCR4H3UFMIOXSW6NNS6N53CLJA4PB56CEJJI", proxy_required: false} |
| 3917 |
] |
| 3918 |
} |
| 3919 |
`)) |
| 3920 |
o, err = ProcessConfigFile(conf) |
| 3921 |
require_NoError(t, err) |
| 3922 |
|
| 3923 |
checkUsersAndNkeys := func(users []*User, hasNkeys bool, nkeys []*NkeyUser) { |
| 3924 |
t.Helper() |
| 3925 |
var found bool |
| 3926 |
|
| 3927 |
require_Len(t, len(users), 3) |
| 3928 |
for _, u := range users { |
| 3929 |
switch u.Username { |
| 3930 |
case "user1", "user3": |
| 3931 |
require_False(t, u.ProxyRequired) |
| 3932 |
case "user2": |
| 3933 |
require_True(t, u.ProxyRequired) |
| 3934 |
found = true |
| 3935 |
} |
| 3936 |
} |
| 3937 |
require_True(t, found) |
| 3938 |
|
| 3939 |
if !hasNkeys { |
| 3940 |
return |
| 3941 |
} |
| 3942 |
|
| 3943 |
found = false |
| 3944 |
require_Len(t, len(nkeys), 2) |
| 3945 |
for _, u := range nkeys { |
| 3946 |
switch u.Nkey { |
| 3947 |
case "UCARKS2E3KVB7YORL2DG34XLT7PUCOL2SVM7YXV6ETHLW6Z46UUJ2VZ3": |
| 3948 |
require_True(t, u.ProxyRequired) |
| 3949 |
found = true |
| 3950 |
case "UD6AYQSOIN2IN5OGC6VQZCR4H3UFMIOXSW6NNS6N53CLJA4PB56CEJJI": |
| 3951 |
require_False(t, u.ProxyRequired) |
| 3952 |
} |
| 3953 |
} |
| 3954 |
require_True(t, found) |
| 3955 |
} |
| 3956 |
checkUsersAndNkeys(o.Users, true, o.Nkeys) |
| 3957 |
|
| 3958 |
conf = createConfFile(t, []byte(` |
| 3959 |
port: -1 |
| 3960 |
accounts { |
| 3961 |
A { |
| 3962 |
users: [ |
| 3963 |
{user: user1, password: pwd1} |
| 3964 |
{user: user2, password: pwd2, proxy_required: true} |
| 3965 |
{user: user3, password: pwd3, proxy_required: false} |
| 3966 |
{nkey: "UCARKS2E3KVB7YORL2DG34XLT7PUCOL2SVM7YXV6ETHLW6Z46UUJ2VZ3", proxy_required: true} |
| 3967 |
{nkey: "UD6AYQSOIN2IN5OGC6VQZCR4H3UFMIOXSW6NNS6N53CLJA4PB56CEJJI", proxy_required: false} |
| 3968 |
] |
| 3969 |
} |
| 3970 |
} |
| 3971 |
`)) |
| 3972 |
o, err = ProcessConfigFile(conf) |
| 3973 |
require_NoError(t, err) |
| 3974 |
require_Len(t, len(o.Accounts), 1) |
| 3975 |
require_Equal(t, o.Accounts[0].Name, "A") |
| 3976 |
checkUsersAndNkeys(o.Users, true, o.Nkeys) |
| 3977 |
|
| 3978 |
conf = createConfFile(t, []byte(` |
| 3979 |
port: -1 |
| 3980 |
leafnodes { |
| 3981 |
port: -1 |
| 3982 |
authorization { |
| 3983 |
user: user |
| 3984 |
password: pwd |
| 3985 |
proxy_required: true |
| 3986 |
} |
| 3987 |
} |
| 3988 |
`)) |
| 3989 |
o, err = ProcessConfigFile(conf) |
| 3990 |
require_NoError(t, err) |
| 3991 |
require_Equal(t, o.LeafNode.Username, "user") |
| 3992 |
require_Equal(t, o.LeafNode.Password, "pwd") |
| 3993 |
require_True(t, o.LeafNode.ProxyRequired) |
| 3994 |
|
| 3995 |
conf = createConfFile(t, []byte(` |
| 3996 |
port: -1 |
| 3997 |
leafnodes { |
| 3998 |
port: -1 |
| 3999 |
authorization { |
| 4000 |
nkey: "UCARKS2E3KVB7YORL2DG34XLT7PUCOL2SVM7YXV6ETHLW6Z46UUJ2VZ3" |
| 4001 |
proxy_required: true |
| 4002 |
} |
| 4003 |
} |
| 4004 |
`)) |
| 4005 |
o, err = ProcessConfigFile(conf) |
| 4006 |
require_NoError(t, err) |
| 4007 |
require_Equal(t, o.LeafNode.Nkey, "UCARKS2E3KVB7YORL2DG34XLT7PUCOL2SVM7YXV6ETHLW6Z46UUJ2VZ3") |
| 4008 |
require_True(t, o.LeafNode.ProxyRequired) |
| 4009 |
|
| 4010 |
conf = createConfFile(t, []byte(` |
| 4011 |
port: -1 |
| 4012 |
leafnodes: { |
| 4013 |
port: -1 |
| 4014 |
authorization { |
| 4015 |
users: [ |
| 4016 |
{user: user1, password: pwd1} |
| 4017 |
{user: user2, password: pwd2, proxy_required: true} |
| 4018 |
{user: user3, password: pwd3, proxy_required: false} |
| 4019 |
] |
| 4020 |
} |
| 4021 |
} |
| 4022 |
`)) |
| 4023 |
o, err = ProcessConfigFile(conf) |
| 4024 |
require_NoError(t, err) |
| 4025 |
checkUsersAndNkeys(o.LeafNode.Users, false, nil) |
| 4026 |
} |
| 4027 |
|
| 4028 |
// TestNewServerFromConfigFunctionality tests the NewServerFromConfig() function |
| 4029 |
// to ensure it properly processes config files and creates servers correctly. |
| 4030 |
func TestNewServerFromConfigFunctionality(t *testing.T) { |
| 4031 |
// Test 1: Error handling - invalid configuration |
| 4032 |
confFileName := createConfFile(t, []byte(` |
| 4033 |
max_payload = 3000000000 |
| 4034 |
`)) |
| 4035 |
|
| 4036 |
opts1 := &Options{ |
| 4037 |
ConfigFile: confFileName, |
| 4038 |
} |
| 4039 |
|
| 4040 |
// Should fail due to oversized max_payload (same as TestLargeMaxPayload) |
| 4041 |
if _, err := NewServerFromConfig(opts1); err == nil { |
| 4042 |
t.Fatalf("Expected an error from too large of a max_payload entry") |
| 4043 |
} |
| 4044 |
|
| 4045 |
// Test 2: Config validation error - max_pending > max_payload |
| 4046 |
confFileName = createConfFile(t, []byte(` |
| 4047 |
max_payload = 100000 |
| 4048 |
max_pending = 50000 |
| 4049 |
`)) |
| 4050 |
|
| 4051 |
opts2 := &Options{ |
| 4052 |
ConfigFile: confFileName, |
| 4053 |
} |
| 4054 |
|
| 4055 |
// This should trigger validation error (same as TestLargeMaxPayload) |
| 4056 |
server, err := NewServerFromConfig(opts2) |
| 4057 |
if err == nil || !strings.Contains(err.Error(), "cannot be higher") { |
| 4058 |
if server != nil { |
| 4059 |
server.Shutdown() |
| 4060 |
} |
| 4061 |
t.Fatalf("Expected validation error, got: %v", err) |
| 4062 |
} |
| 4063 |
} |
| 4064 |
|
| 4065 |
// TestNewServerFromConfigVsLoadConfig tests that NewServerFromConfig produces |
| 4066 |
// equivalent results to the traditional LoadConfig approach. |
| 4067 |
func TestNewServerFromConfigVsLoadConfig(t *testing.T) { |
| 4068 |
confFileName := createConfFile(t, []byte(` |
| 4069 |
port = 4224 |
| 4070 |
max_payload = 4194304 |
| 4071 |
max_connections = 200 |
| 4072 |
ping_interval = "30s" |
| 4073 |
`)) |
| 4074 |
|
| 4075 |
// Method 1: Using LoadConfig (traditional approach) |
| 4076 |
opts1 := LoadConfig(confFileName) |
| 4077 |
|
| 4078 |
// Method 2: Using NewServerFromConfig (new approach for embedded servers) |
| 4079 |
opts2 := &Options{ConfigFile: confFileName} |
| 4080 |
|
| 4081 |
// Test 1: Both should be able to create servers successfully |
| 4082 |
server1, err := NewServer(opts1) |
| 4083 |
if err != nil { |
| 4084 |
t.Fatalf("Failed to create server with LoadConfig options: %v", err) |
| 4085 |
} |
| 4086 |
server1.Shutdown() |
| 4087 |
|
| 4088 |
server2, err := NewServerFromConfig(opts2) |
| 4089 |
if err != nil { |
| 4090 |
t.Fatalf("Failed to create server with NewServerFromConfig: %v", err) |
| 4091 |
} |
| 4092 |
server2.Shutdown() |
| 4093 |
|
| 4094 |
// Test 2: Both methods should produce equivalent results - normalize test environment fields |
| 4095 |
// LoadConfig sets these fields for testing, so we need to match them for fair comparison |
| 4096 |
opts2.NoSigs, opts2.NoLog = true, opts2.LogFile == _EMPTY_ |
| 4097 |
|
| 4098 |
checkOptionsEqual(t, opts1, opts2) |
| 4099 |
} |
| 4100 |
|
| 4101 |
func TestWriteDeadlineConfigParsing(t *testing.T) { |
| 4102 |
type testCase struct { |
| 4103 |
name string |
| 4104 |
config string |
| 4105 |
expect func(t *testing.T, opts *Options) |
| 4106 |
} |
| 4107 |
|
| 4108 |
for _, tc := range []testCase{ |
| 4109 |
{ |
| 4110 |
name: "LeafNode", |
| 4111 |
config: ` |
| 4112 |
leafnodes { |
| 4113 |
write_deadline: 5s |
| 4114 |
} |
| 4115 |
`, |
| 4116 |
expect: func(t *testing.T, opts *Options) { |
| 4117 |
require_Equal(t, opts.LeafNode.WriteDeadline, 5*time.Second) |
| 4118 |
}, |
| 4119 |
}, |
| 4120 |
{ |
| 4121 |
name: "Gateway", |
| 4122 |
config: ` |
| 4123 |
gateway { |
| 4124 |
write_deadline: 6s |
| 4125 |
} |
| 4126 |
`, |
| 4127 |
expect: func(t *testing.T, opts *Options) { |
| 4128 |
require_Equal(t, opts.Gateway.WriteDeadline, 6*time.Second) |
| 4129 |
}, |
| 4130 |
}, |
| 4131 |
{ |
| 4132 |
name: "Cluster", |
| 4133 |
config: ` |
| 4134 |
cluster { |
| 4135 |
write_deadline: 7s |
| 4136 |
} |
| 4137 |
`, |
| 4138 |
expect: func(t *testing.T, opts *Options) { |
| 4139 |
require_Equal(t, opts.Cluster.WriteDeadline, 7*time.Second) |
| 4140 |
}, |
| 4141 |
}, |
| 4142 |
{ |
| 4143 |
name: "Global", |
| 4144 |
config: ` |
| 4145 |
write_deadline: 8s |
| 4146 |
`, |
| 4147 |
expect: func(t *testing.T, opts *Options) { |
| 4148 |
require_Equal(t, opts.WriteDeadline, 8*time.Second) |
| 4149 |
}, |
| 4150 |
}, |
| 4151 |
} { |
| 4152 |
t.Run(tc.name, func(t *testing.T) { |
| 4153 |
opts, err := parseConfigTolerantly(t, tc.config) |
| 4154 |
require_NoError(t, err) |
| 4155 |
tc.expect(t, opts) |
| 4156 |
}) |
| 4157 |
} |
| 4158 |
} |
| 4159 |
|
| 4160 |
func TestWriteTimeoutConfigParsing(t *testing.T) { |
| 4161 |
type testCase struct { |
| 4162 |
name string |
| 4163 |
config string |
| 4164 |
expect func(t *testing.T, opts *Options) |
| 4165 |
} |
| 4166 |
|
| 4167 |
for str, pol := range map[string]WriteTimeoutPolicy{ |
| 4168 |
"default": WriteTimeoutPolicyDefault, |
| 4169 |
"retry": WriteTimeoutPolicyRetry, |
| 4170 |
"close": WriteTimeoutPolicyClose, |
| 4171 |
} { |
| 4172 |
for _, tc := range []testCase{ |
| 4173 |
{ |
| 4174 |
name: "LeafNode", |
| 4175 |
config: fmt.Sprintf(` |
| 4176 |
leafnodes { |
| 4177 |
write_timeout: %s |
| 4178 |
} |
| 4179 |
`, str), |
| 4180 |
expect: func(t *testing.T, opts *Options) { |
| 4181 |
require_Equal(t, opts.LeafNode.WriteTimeout, pol) |
| 4182 |
}, |
| 4183 |
}, |
| 4184 |
{ |
| 4185 |
name: "Gateway", |
| 4186 |
config: fmt.Sprintf(` |
| 4187 |
gateway { |
| 4188 |
write_timeout: %s |
| 4189 |
} |
| 4190 |
`, str), |
| 4191 |
expect: func(t *testing.T, opts *Options) { |
| 4192 |
require_Equal(t, opts.Gateway.WriteTimeout, pol) |
| 4193 |
}, |
| 4194 |
}, |
| 4195 |
{ |
| 4196 |
name: "Cluster", |
| 4197 |
config: fmt.Sprintf(` |
| 4198 |
cluster { |
| 4199 |
write_timeout: %s |
| 4200 |
} |
| 4201 |
`, str), |
| 4202 |
expect: func(t *testing.T, opts *Options) { |
| 4203 |
require_Equal(t, opts.Cluster.WriteTimeout, pol) |
| 4204 |
}, |
| 4205 |
}, |
| 4206 |
{ |
| 4207 |
name: "Global", |
| 4208 |
config: fmt.Sprintf(` |
| 4209 |
write_timeout: %s |
| 4210 |
`, str), |
| 4211 |
expect: func(t *testing.T, opts *Options) { |
| 4212 |
require_Equal(t, opts.WriteTimeout, pol) |
| 4213 |
}, |
| 4214 |
}, |
| 4215 |
} { |
| 4216 |
t.Run(fmt.Sprintf("%s/%s", tc.name, str), func(t *testing.T) { |
| 4217 |
opts, err := parseConfigTolerantly(t, tc.config) |
| 4218 |
require_NoError(t, err) |
| 4219 |
tc.expect(t, opts) |
| 4220 |
}) |
| 4221 |
} |
| 4222 |
} |
| 4223 |
} |
| 4224 |
|
| 4225 |
func TestWebsocketPingIntervalConfig(t *testing.T) { |
| 4226 |
// Test with string format (duration string) |
| 4227 |
confFile := createConfFile(t, []byte(` |
| 4228 |
websocket { |
| 4229 |
port: 8080 |
| 4230 |
ping_interval: "30s" |
| 4231 |
} |
| 4232 |
`)) |
| 4233 |
opts, err := ProcessConfigFile(confFile) |
| 4234 |
if err != nil { |
| 4235 |
t.Fatalf("Unexpected error: %v", err) |
| 4236 |
} |
| 4237 |
if opts.Websocket.PingInterval != 30*time.Second { |
| 4238 |
t.Fatalf("Expected websocket ping_interval to be 30s, got %v", opts.Websocket.PingInterval) |
| 4239 |
} |
| 4240 |
|
| 4241 |
// Test with integer format (seconds) |
| 4242 |
confFile = createConfFile(t, []byte(` |
| 4243 |
websocket { |
| 4244 |
port: 8080 |
| 4245 |
ping_interval: 45 |
| 4246 |
} |
| 4247 |
`)) |
| 4248 |
opts, err = ProcessConfigFile(confFile) |
| 4249 |
if err != nil { |
| 4250 |
t.Fatalf("Unexpected error: %v", err) |
| 4251 |
} |
| 4252 |
if opts.Websocket.PingInterval != 45*time.Second { |
| 4253 |
t.Fatalf("Expected websocket ping_interval to be 45s, got %v", opts.Websocket.PingInterval) |
| 4254 |
} |
| 4255 |
|
| 4256 |
// Test with different duration format |
| 4257 |
confFile = createConfFile(t, []byte(` |
| 4258 |
websocket { |
| 4259 |
port: 8080 |
| 4260 |
ping_interval: "2m" |
| 4261 |
} |
| 4262 |
`)) |
| 4263 |
opts, err = ProcessConfigFile(confFile) |
| 4264 |
if err != nil { |
| 4265 |
t.Fatalf("Unexpected error: %v", err) |
| 4266 |
} |
| 4267 |
if opts.Websocket.PingInterval != 2*time.Minute { |
| 4268 |
t.Fatalf("Expected websocket ping_interval to be 2m, got %v", opts.Websocket.PingInterval) |
| 4269 |
} |
| 4270 |
|
| 4271 |
// Test without ping_interval (should be zero/unset) |
| 4272 |
confFile = createConfFile(t, []byte(` |
| 4273 |
websocket { |
| 4274 |
port: 8080 |
| 4275 |
} |
| 4276 |
`)) |
| 4277 |
opts, err = ProcessConfigFile(confFile) |
| 4278 |
if err != nil { |
| 4279 |
t.Fatalf("Unexpected error: %v", err) |
| 4280 |
} |
| 4281 |
if opts.Websocket.PingInterval != 0 { |
| 4282 |
t.Fatalf("Expected websocket ping_interval to be 0 (unset), got %v", opts.Websocket.PingInterval) |
| 4283 |
} |
| 4284 |
} |
| 4285 |
|
| 4286 |
// Test variables that reference other variables |
| 4287 |
func TestVarReferencesVar(t *testing.T) { |
| 4288 |
confFileName := createConfFile(t, []byte(` |
| 4289 |
A: 7890 |
| 4290 |
B: $A |
| 4291 |
C: $B |
| 4292 |
port: $C |
| 4293 |
`)) |
| 4294 |
opts, err := ProcessConfigFile(confFileName) |
| 4295 |
if err != nil { |
| 4296 |
t.Fatalf("Unexpected error: %v", err) |
| 4297 |
} |
| 4298 |
if opts.Port != 7890 { |
| 4299 |
t.Fatalf("Expected port 7890, found %d", opts.Port) |
| 4300 |
} |
| 4301 |
} |
| 4302 |
|
| 4303 |
// A variables that reference an environment variable |
| 4304 |
func TestVarReferencesEnvVar(t *testing.T) { |
| 4305 |
confFileName := createConfFile(t, []byte(` |
| 4306 |
A: $_TEST_ENV_NATS_PORT_ |
| 4307 |
B: $A |
| 4308 |
C: $B |
| 4309 |
port: $C |
| 4310 |
`)) |
| 4311 |
|
| 4312 |
defer os.Unsetenv("_TEST_ENV_NATS_PORT_") |
| 4313 |
os.Setenv("_TEST_ENV_NATS_PORT_", "7890") |
| 4314 |
opts, err := ProcessConfigFile(confFileName) |
| 4315 |
if err != nil { |
| 4316 |
t.Fatalf("Unexpected error: %v", err) |
| 4317 |
} |
| 4318 |
if opts.Port != 7890 { |
| 4319 |
t.Fatalf("Expected port 7890, found %d", opts.Port) |
| 4320 |
} |
| 4321 |
} |
| 4322 |
|
| 4323 |
// Test a variable that references itself |
| 4324 |
func TestVarReferencesSelf(t *testing.T) { |
| 4325 |
confFileName := createConfFile(t, []byte(`A: $A`)) |
| 4326 |
_, err := ProcessConfigFile(confFileName) |
| 4327 |
if err == nil { |
| 4328 |
t.Fatalf("Expected var not found error") |
| 4329 |
} |
| 4330 |
require_Contains(t, err.Error(), |
| 4331 |
"variable reference for 'A' on line 1 can not be found") |
| 4332 |
} |
| 4333 |
|
| 4334 |
// An environment variable can't reference a variable |
| 4335 |
func TestEnvVarReferencesVar(t *testing.T) { |
| 4336 |
confFileName := createConfFile(t, []byte(` |
| 4337 |
P: 8080 |
| 4338 |
port: $_TEST_ENV_NATS_PORT_ |
| 4339 |
`)) |
| 4340 |
|
| 4341 |
defer os.Unsetenv("_TEST_ENV_NATS_PORT_") |
| 4342 |
os.Setenv("_TEST_ENV_NATS_PORT_", "$P") |
| 4343 |
|
| 4344 |
_, err := ProcessConfigFile(confFileName) |
| 4345 |
if err == nil { |
| 4346 |
t.Fatalf("Expected var not found error") |
| 4347 |
} |
| 4348 |
require_Contains(t, err.Error(), |
| 4349 |
"variable reference for 'P' on line 1 can not be found") |
| 4350 |
} |
| 4351 |
|
| 4352 |
// Environment variables can reference other environment variables |
| 4353 |
func TestEnvVarReferencesEnvVar(t *testing.T) { |
| 4354 |
confFileName := createConfFile(t, []byte(` |
| 4355 |
port: $_TEST_ENV_A_ |
| 4356 |
`)) |
| 4357 |
|
| 4358 |
defer os.Unsetenv("_TEST_ENV_A_") |
| 4359 |
defer os.Unsetenv("_TEST_ENV_B_") |
| 4360 |
defer os.Unsetenv("_TEST_ENV_C_") |
| 4361 |
|
| 4362 |
os.Setenv("_TEST_ENV_A_", "$_TEST_ENV_B_") |
| 4363 |
os.Setenv("_TEST_ENV_B_", "$_TEST_ENV_C_") |
| 4364 |
os.Setenv("_TEST_ENV_C_", "7890") |
| 4365 |
|
| 4366 |
opts, err := ProcessConfigFile(confFileName) |
| 4367 |
if err != nil { |
| 4368 |
t.Fatalf("Unexpected error: %v", err) |
| 4369 |
} |
| 4370 |
if opts.Port != 7890 { |
| 4371 |
t.Fatalf("Expected port 7890, found %d", opts.Port) |
| 4372 |
} |
| 4373 |
} |
| 4374 |
|
| 4375 |
// Test an environment variable that references itself |
| 4376 |
func TestEnvVarReferencesSelf(t *testing.T) { |
| 4377 |
confFileName := createConfFile(t, []byte(` |
| 4378 |
TEST: $_TEST_ENV_ |
| 4379 |
`)) |
| 4380 |
|
| 4381 |
defer os.Unsetenv("_TEST_ENV_") |
| 4382 |
|
| 4383 |
os.Setenv("_TEST_ENV_", "$_TEST_ENV_") |
| 4384 |
|
| 4385 |
_, err := ProcessConfigFile(confFileName) |
| 4386 |
if err == nil { |
| 4387 |
t.Fatalf("Expected an error") |
| 4388 |
} |
| 4389 |
require_Contains(t, err.Error(), "variable reference cycle") |
| 4390 |
} |
| 4391 |
|
| 4392 |
// Test an environment variable that references itself through a cycle |
| 4393 |
func TestEnvVarReferencesSelfCycle(t *testing.T) { |
| 4394 |
confFileName := createConfFile(t, []byte(` |
| 4395 |
TEST: $_TEST_ENV_A_ |
| 4396 |
`)) |
| 4397 |
|
| 4398 |
defer os.Unsetenv("_TEST_ENV_A_") |
| 4399 |
defer os.Unsetenv("_TEST_ENV_B_") |
| 4400 |
defer os.Unsetenv("_TEST_ENV_C_") |
| 4401 |
|
| 4402 |
os.Setenv("_TEST_ENV_A_", "$_TEST_ENV_B_") |
| 4403 |
os.Setenv("_TEST_ENV_B_", "$_TEST_ENV_C_") |
| 4404 |
os.Setenv("_TEST_ENV_C_", "$_TEST_ENV_A_") |
| 4405 |
|
| 4406 |
_, err := ProcessConfigFile(confFileName) |
| 4407 |
if err == nil { |
| 4408 |
t.Fatalf("Expected an error") |
| 4409 |
} |
| 4410 |
require_Contains(t, err.Error(), "variable reference cycle") |
| 4411 |
} |
| 4412 |
|
| 4413 |
// Test can't include from environment variable |
| 4414 |
func TestEnvVarInclude(t *testing.T) { |
| 4415 |
confFileName := createConfFile(t, []byte(` |
| 4416 |
TEST: $_TEST_ENV_A_ |
| 4417 |
`)) |
| 4418 |
|
| 4419 |
defer os.Unsetenv("_TEST_ENV_A_") |
| 4420 |
|
| 4421 |
os.Setenv("_TEST_ENV_A_", "include x") |
| 4422 |
|
| 4423 |
_, err := ProcessConfigFile(confFileName) |
| 4424 |
if err == nil { |
| 4425 |
t.Fatal("Expected an error") |
| 4426 |
} |
| 4427 |
require_Contains(t, err.Error(), "Expected a top-level value to end with a new line, comment or EOF") |
| 4428 |
} |
| 4429 |
|
| 4430 |
func TestEnvVarFromIncludedFile(t *testing.T) { |
| 4431 |
includeFileName := createConfFile(t, []byte(` |
| 4432 |
TEST_PORT: $_TEST_ENV_PORT_A_ |
| 4433 |
`)) |
| 4434 |
|
| 4435 |
confFileContent := fmt.Sprintf(` |
| 4436 |
include "./%s" |
| 4437 |
port: $TEST_PORT |
| 4438 |
`, filepath.Base(includeFileName)) |
| 4439 |
|
| 4440 |
dir := filepath.Dir(includeFileName) |
| 4441 |
conf, err := os.CreateTemp(dir, "conf-") |
| 4442 |
require_NoError(t, err) |
| 4443 |
if err := os.WriteFile(conf.Name(), []byte(confFileContent), 0666); err != nil { |
| 4444 |
t.Fatalf("Error writing conf file: %v", err) |
| 4445 |
} |
| 4446 |
|
| 4447 |
defer os.Unsetenv("_TEST_ENV_PORT_A_") |
| 4448 |
defer os.Unsetenv("_TEST_ENV_PORT_B_") |
| 4449 |
|
| 4450 |
os.Setenv("_TEST_ENV_PORT_A_", "$_TEST_ENV_PORT_B_") |
| 4451 |
os.Setenv("_TEST_ENV_PORT_B_", "7890") |
| 4452 |
|
| 4453 |
opts, err := ProcessConfigFile(conf.Name()) |
| 4454 |
if err != nil { |
| 4455 |
t.Fatalf("Unexpected error: %v", err) |
| 4456 |
} |
| 4457 |
if opts.Port != 7890 { |
| 4458 |
t.Fatalf("Expected port 7890, found %d", opts.Port) |
| 4459 |
} |
| 4460 |
} |
| 4461 |
|
| 4462 |
func TestRedactArgs(t *testing.T) { |
| 4463 |
var tests []struct { |
| 4464 |
name string |
| 4465 |
input []string |
| 4466 |
expected []string |
| 4467 |
} |
| 4468 |
|
| 4469 |
for _, dash := range []string{"-", "--"} { |
| 4470 |
for _, tag := range []string{"user", "pass", "auth"} { |
| 4471 |
for _, value := range []string{"hello", "hello world"} { |
| 4472 |
flag := dash + tag |
| 4473 |
tests = append(tests, struct { |
| 4474 |
name string |
| 4475 |
input []string |
| 4476 |
expected []string |
| 4477 |
}{ |
| 4478 |
name: fmt.Sprintf("%s%s-space-%q", dash, tag, value), |
| 4479 |
input: []string{flag, value}, |
| 4480 |
expected: []string{flag, "[REDACTED]"}, |
| 4481 |
}) |
| 4482 |
tests = append(tests, struct { |
| 4483 |
name string |
| 4484 |
input []string |
| 4485 |
expected []string |
| 4486 |
}{ |
| 4487 |
name: fmt.Sprintf("%s%s-equals-%q", dash, tag, value), |
| 4488 |
input: []string{flag + "=" + value}, |
| 4489 |
expected: []string{flag + "=[REDACTED]"}, |
| 4490 |
}) |
| 4491 |
} |
| 4492 |
} |
| 4493 |
} |
| 4494 |
|
| 4495 |
for _, dash := range []string{"-", "--"} { |
| 4496 |
for _, test := range []struct { |
| 4497 |
name string |
| 4498 |
tag string |
| 4499 |
input string |
| 4500 |
expected string |
| 4501 |
}{ |
| 4502 |
{ |
| 4503 |
name: "routes-single", |
| 4504 |
tag: "routes", |
| 4505 |
input: "nats://ruser:[email protected]:6222", |
| 4506 |
expected: "nats://[REDACTED]@127.0.0.1:6222", |
| 4507 |
}, |
| 4508 |
{ |
| 4509 |
name: "routes-no-creds", |
| 4510 |
tag: "routes", |
| 4511 |
input: "nats://127.0.0.1:6222", |
| 4512 |
expected: "nats://127.0.0.1:6222", |
| 4513 |
}, |
| 4514 |
{ |
| 4515 |
name: "routes-multi", |
| 4516 |
tag: "routes", |
| 4517 |
input: "nats://ruser:[email protected]:6222, nats://ruser2:[email protected]:6223", |
| 4518 |
expected: "nats://[REDACTED]@127.0.0.1:6222,nats://[REDACTED]@127.0.0.1:6223", |
| 4519 |
}, |
| 4520 |
{ |
| 4521 |
name: "cluster", |
| 4522 |
tag: "cluster", |
| 4523 |
input: "nats://cuser:[email protected]:6224", |
| 4524 |
expected: "nats://[REDACTED]@127.0.0.1:6224", |
| 4525 |
}, |
| 4526 |
{ |
| 4527 |
name: "cluster-no-creds", |
| 4528 |
tag: "cluster", |
| 4529 |
input: "nats://127.0.0.1:6224", |
| 4530 |
expected: "nats://127.0.0.1:6224", |
| 4531 |
}, |
| 4532 |
{ |
| 4533 |
name: "cluster-comma-user", |
| 4534 |
tag: "cluster", |
| 4535 |
input: "nats://cuser,extra:[email protected]:6224", |
| 4536 |
expected: "nats://[REDACTED]@127.0.0.1:6224", |
| 4537 |
}, |
| 4538 |
{ |
| 4539 |
name: "cluster-random-port", |
| 4540 |
tag: "cluster", |
| 4541 |
input: "nats://cuser:[email protected]:-1", |
| 4542 |
expected: "nats://[REDACTED]@127.0.0.1:-1", |
| 4543 |
}, |
| 4544 |
{ |
| 4545 |
name: "cluster-listen", |
| 4546 |
tag: "cluster_listen", |
| 4547 |
input: "nats://luser:[email protected]:6225", |
| 4548 |
expected: "nats://[REDACTED]@127.0.0.1:6225", |
| 4549 |
}, |
| 4550 |
{ |
| 4551 |
name: "cluster-listen-comma-user", |
| 4552 |
tag: "cluster_listen", |
| 4553 |
input: "nats://luser,extra:[email protected]:6225", |
| 4554 |
expected: "nats://[REDACTED]@127.0.0.1:6225", |
| 4555 |
}, |
| 4556 |
{ |
| 4557 |
name: "cluster-listen-random-port", |
| 4558 |
tag: "cluster_listen", |
| 4559 |
input: "nats://luser:[email protected]:-1", |
| 4560 |
expected: "nats://[REDACTED]@127.0.0.1:-1", |
| 4561 |
}, |
| 4562 |
} { |
| 4563 |
tests = append(tests, struct { |
| 4564 |
name string |
| 4565 |
input []string |
| 4566 |
expected []string |
| 4567 |
}{ |
| 4568 |
name: fmt.Sprintf("%s%s-space", dash, test.name), |
| 4569 |
input: []string{dash + test.tag, test.input}, |
| 4570 |
expected: []string{dash + test.tag, test.expected}, |
| 4571 |
}) |
| 4572 |
tests = append(tests, struct { |
| 4573 |
name string |
| 4574 |
input []string |
| 4575 |
expected []string |
| 4576 |
}{ |
| 4577 |
name: fmt.Sprintf("%s%s-equals", dash, test.name), |
| 4578 |
input: []string{dash + test.tag + "=" + test.input}, |
| 4579 |
expected: []string{dash + test.tag + "=" + test.expected}, |
| 4580 |
}) |
| 4581 |
} |
| 4582 |
} |
| 4583 |
|
| 4584 |
for _, test := range tests { |
| 4585 |
t.Run(test.name, func(t *testing.T) { |
| 4586 |
input := append([]string(nil), test.input...) |
| 4587 |
RedactArgs(input) |
| 4588 |
if !reflect.DeepEqual(input, test.expected) { |
| 4589 |
t.Fatalf("A %v\nB %v", test.expected, input) |
| 4590 |
} |
| 4591 |
}) |
| 4592 |
} |
| 4593 |
} |
| 4594 |
|
| 4595 |
func TestOptionsCompressionEqual(t *testing.T) { |
| 4596 |
for _, test := range []struct { |
| 4597 |
name string |
| 4598 |
genOpts func() (*CompressionOpts, *CompressionOpts) |
| 4599 |
equal bool |
| 4600 |
}{ |
| 4601 |
{"same pointer", func() (*CompressionOpts, *CompressionOpts) { |
| 4602 |
c := &CompressionOpts{} |
| 4603 |
return c, c |
| 4604 |
}, true}, |
| 4605 |
{"first nil", func() (*CompressionOpts, *CompressionOpts) { |
| 4606 |
return &CompressionOpts{}, nil |
| 4607 |
}, false}, |
| 4608 |
{"second nil", func() (*CompressionOpts, *CompressionOpts) { |
| 4609 |
return nil, &CompressionOpts{} |
| 4610 |
}, false}, |
| 4611 |
{"both nil", func() (*CompressionOpts, *CompressionOpts) { |
| 4612 |
return nil, nil |
| 4613 |
}, true}, |
| 4614 |
{"different mode", func() (*CompressionOpts, *CompressionOpts) { |
| 4615 |
return &CompressionOpts{Mode: CompressionS2Fast}, |
| 4616 |
&CompressionOpts{Mode: CompressionS2Best} |
| 4617 |
}, false}, |
| 4618 |
{"same mode", func() (*CompressionOpts, *CompressionOpts) { |
| 4619 |
return &CompressionOpts{Mode: CompressionS2Best}, |
| 4620 |
&CompressionOpts{Mode: CompressionS2Best} |
| 4621 |
}, true}, |
| 4622 |
{"s2 auto c1 default rtt thresholds", func() (*CompressionOpts, *CompressionOpts) { |
| 4623 |
return &CompressionOpts{ |
| 4624 |
Mode: CompressionS2Auto, |
| 4625 |
RTTThresholds: defaultCompressionS2AutoRTTThresholds, |
| 4626 |
}, &CompressionOpts{ |
| 4627 |
Mode: CompressionS2Auto, |
| 4628 |
} |
| 4629 |
}, true}, |
| 4630 |
{"s2 auto c2 default rtt thresholds", func() (*CompressionOpts, *CompressionOpts) { |
| 4631 |
return &CompressionOpts{ |
| 4632 |
Mode: CompressionS2Auto, |
| 4633 |
}, &CompressionOpts{ |
| 4634 |
Mode: CompressionS2Auto, |
| 4635 |
RTTThresholds: defaultCompressionS2AutoRTTThresholds, |
| 4636 |
} |
| 4637 |
}, true}, |
| 4638 |
{"s2 auto same rtt thresholds", func() (*CompressionOpts, *CompressionOpts) { |
| 4639 |
return &CompressionOpts{ |
| 4640 |
Mode: CompressionS2Auto, |
| 4641 |
RTTThresholds: []time.Duration{5 * time.Millisecond, 10 * time.Millisecond}, |
| 4642 |
}, &CompressionOpts{ |
| 4643 |
Mode: CompressionS2Auto, |
| 4644 |
RTTThresholds: []time.Duration{5 * time.Millisecond, 10 * time.Millisecond}, |
| 4645 |
} |
| 4646 |
}, true}, |
| 4647 |
{"s2 auto different rtt thresholds", func() (*CompressionOpts, *CompressionOpts) { |
| 4648 |
return &CompressionOpts{ |
| 4649 |
Mode: CompressionS2Auto, |
| 4650 |
RTTThresholds: []time.Duration{5 * time.Millisecond, 10 * time.Millisecond}, |
| 4651 |
}, &CompressionOpts{ |
| 4652 |
Mode: CompressionS2Auto, |
| 4653 |
RTTThresholds: []time.Duration{15 * time.Millisecond, 30 * time.Millisecond}, |
| 4654 |
} |
| 4655 |
}, false}, |
| 4656 |
{"s2 auto different rtt thresholds c1 not set", func() (*CompressionOpts, *CompressionOpts) { |
| 4657 |
return &CompressionOpts{ |
| 4658 |
Mode: CompressionS2Auto, |
| 4659 |
}, &CompressionOpts{ |
| 4660 |
Mode: CompressionS2Auto, |
| 4661 |
RTTThresholds: []time.Duration{15 * time.Millisecond, 30 * time.Millisecond}, |
| 4662 |
} |
| 4663 |
}, false}, |
| 4664 |
{"s2 auto different rtt thresholds c2 not set", func() (*CompressionOpts, *CompressionOpts) { |
| 4665 |
return &CompressionOpts{ |
| 4666 |
Mode: CompressionS2Auto, |
| 4667 |
RTTThresholds: []time.Duration{15 * time.Millisecond, 30 * time.Millisecond}, |
| 4668 |
}, &CompressionOpts{ |
| 4669 |
Mode: CompressionS2Auto, |
| 4670 |
} |
| 4671 |
}, false}, |
| 4672 |
{"s2 auto both rtt thresholds empty", func() (*CompressionOpts, *CompressionOpts) { |
| 4673 |
return &CompressionOpts{ |
| 4674 |
Mode: CompressionS2Auto, |
| 4675 |
RTTThresholds: []time.Duration{}, |
| 4676 |
}, &CompressionOpts{ |
| 4677 |
Mode: CompressionS2Auto, |
| 4678 |
RTTThresholds: []time.Duration{}, |
| 4679 |
} |
| 4680 |
}, true}, |
| 4681 |
{"s2 auto both rtt thresholds nil", func() (*CompressionOpts, *CompressionOpts) { |
| 4682 |
return &CompressionOpts{ |
| 4683 |
Mode: CompressionS2Auto, |
| 4684 |
}, &CompressionOpts{ |
| 4685 |
Mode: CompressionS2Auto, |
| 4686 |
} |
| 4687 |
}, true}, |
| 4688 |
} { |
| 4689 |
t.Run(test.name, func(t *testing.T) { |
| 4690 |
c1, c2 := test.genOpts() |
| 4691 |
res := c1.equals(c2) |
| 4692 |
require_Equal(t, test.equal, res) |
| 4693 |
}) |
| 4694 |
} |
| 4695 |
} |
| 4696 |
|
| 4697 |
func TestOptionsRemoteLeafNodeName(t *testing.T) { |
| 4698 |
u1, err := url.Parse("nats://user1:[email protected]:7222") |
| 4699 |
require_NoError(t, err) |
| 4700 |
u2, err := url.Parse("nats://user2:[email protected]:7222") |
| 4701 |
require_NoError(t, err) |
| 4702 |
// With unredacted versions of the URLs |
| 4703 |
urls := []*url.URL{u1, u2} |
| 4704 |
safeURLs := redactURLList(urls) |
| 4705 |
// Some Nkey |
| 4706 |
nkey := "SUACJN3OSKWWPQXME4JUNFJ3PARXPO657GGNWNU7PK7G3AUQQYHLW26XH4" |
| 4707 |
for _, test := range []struct { |
| 4708 |
name string |
| 4709 |
input *RemoteLeafOpts |
| 4710 |
output string |
| 4711 |
safeOutput string |
| 4712 |
}{ |
| 4713 |
{ |
| 4714 |
"url only", &RemoteLeafOpts{ |
| 4715 |
URLs: []*url.URL{u1, u2}, |
| 4716 |
}, |
| 4717 |
fmt.Sprintf("urls=%q, account=%q", urls, globalAccountName), |
| 4718 |
fmt.Sprintf("urls=%q, account=%q", safeURLs, globalAccountName), |
| 4719 |
}, |
| 4720 |
{ |
| 4721 |
"url with account", &RemoteLeafOpts{ |
| 4722 |
URLs: []*url.URL{u1, u2}, |
| 4723 |
LocalAccount: "A", |
| 4724 |
}, |
| 4725 |
fmt.Sprintf("urls=%q, account=%q", urls, "A"), |
| 4726 |
fmt.Sprintf("urls=%q, account=%q", safeURLs, "A"), |
| 4727 |
}, |
| 4728 |
{ |
| 4729 |
"url with credentials", &RemoteLeafOpts{ |
| 4730 |
URLs: []*url.URL{u1, u2}, |
| 4731 |
Credentials: "credsfile", |
| 4732 |
}, |
| 4733 |
fmt.Sprintf("urls=%q, account=%q, credentials=%q", urls, globalAccountName, "credsfile"), |
| 4734 |
fmt.Sprintf("urls=%q, account=%q, credentials=%q", safeURLs, globalAccountName, "credsfile"), |
| 4735 |
}, |
| 4736 |
{ |
| 4737 |
"url with nkey", &RemoteLeafOpts{ |
| 4738 |
URLs: []*url.URL{u1, u2}, |
| 4739 |
Nkey: nkey, |
| 4740 |
}, |
| 4741 |
fmt.Sprintf("urls=%q, account=%q, nkey=%q", urls, globalAccountName, nkey), |
| 4742 |
fmt.Sprintf("urls=%q, account=%q, nkey=%q", safeURLs, globalAccountName, "[REDACTED]"), |
| 4743 |
}, |
| 4744 |
{ |
| 4745 |
"url with account and credentials", &RemoteLeafOpts{ |
| 4746 |
URLs: []*url.URL{u1, u2}, |
| 4747 |
LocalAccount: "A", |
| 4748 |
Credentials: "credsfile", |
| 4749 |
}, |
| 4750 |
fmt.Sprintf("urls=%q, account=%q, credentials=%q", urls, "A", "credsfile"), |
| 4751 |
fmt.Sprintf("urls=%q, account=%q, credentials=%q", safeURLs, "A", "credsfile"), |
| 4752 |
}, |
| 4753 |
{ |
| 4754 |
"url with account and nkey", &RemoteLeafOpts{ |
| 4755 |
URLs: []*url.URL{u1, u2}, |
| 4756 |
LocalAccount: "A", |
| 4757 |
Nkey: nkey, |
| 4758 |
}, |
| 4759 |
fmt.Sprintf("urls=%q, account=%q, nkey=%q", urls, "A", nkey), |
| 4760 |
fmt.Sprintf("urls=%q, account=%q, nkey=%q", safeURLs, "A", "[REDACTED]"), |
| 4761 |
}, |
| 4762 |
} { |
| 4763 |
t.Run(test.name, func(t *testing.T) { |
| 4764 |
name := test.input.name() |
| 4765 |
require_Equal(t, name, test.output) |
| 4766 |
name = test.input.safeName() |
| 4767 |
require_Equal(t, name, test.safeOutput) |
| 4768 |
}) |
| 4769 |
} |
| 4770 |
|
| 4771 |
// Because we use `%q` when building the name, those two will have different |
| 4772 |
// names: |
| 4773 |
// r1=urls=["nats://user1:[email protected]:7222"], account="A", credentials="creds" |
| 4774 |
// r2=urls=["nats://user1:[email protected]:7222"], account="A\", credentials=\"creds" |
| 4775 |
r1 := &RemoteLeafOpts{URLs: []*url.URL{u1}, LocalAccount: "A", Credentials: "creds"} |
| 4776 |
r2 := &RemoteLeafOpts{URLs: []*url.URL{u1}, LocalAccount: `A", credentials="creds`} |
| 4777 |
require_False(t, r1.name() == r2.name()) |
| 4778 |
} |