| 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 |
"bufio" |
| 18 |
"bytes" |
| 19 |
"crypto/tls" |
| 20 |
"encoding/base64" |
| 21 |
"encoding/json" |
| 22 |
"fmt" |
| 23 |
"io" |
| 24 |
"math" |
| 25 |
"net" |
| 26 |
"net/url" |
| 27 |
"reflect" |
| 28 |
"regexp" |
| 29 |
"runtime" |
| 30 |
"slices" |
| 31 |
"strings" |
| 32 |
"sync" |
| 33 |
"sync/atomic" |
| 34 |
"testing" |
| 35 |
"time" |
| 36 |
|
| 37 |
"github.com/klauspost/compress/s2" |
| 38 |
"github.com/nats-io/jwt/v2" |
| 39 |
"github.com/nats-io/nats.go" |
| 40 |
"github.com/nats-io/nkeys" |
| 41 |
) |
| 42 |
|
| 43 |
type serverInfo struct { |
| 44 |
ID string `json:"server_id"` |
| 45 |
Host string `json:"host"` |
| 46 |
Port uint `json:"port"` |
| 47 |
Version string `json:"version"` |
| 48 |
AuthRequired bool `json:"auth_required"` |
| 49 |
TLSRequired bool `json:"tls_required"` |
| 50 |
MaxPayload int64 `json:"max_payload"` |
| 51 |
Headers bool `json:"headers"` |
| 52 |
ConnectURLs []string `json:"connect_urls,omitempty"` |
| 53 |
LameDuckMode bool `json:"ldm,omitempty"` |
| 54 |
CID uint64 `json:"client_id,omitempty"` |
| 55 |
} |
| 56 |
|
| 57 |
type testAsyncClient struct { |
| 58 |
*client |
| 59 |
parseAsync func(string) |
| 60 |
quitCh chan bool |
| 61 |
} |
| 62 |
|
| 63 |
func (c *testAsyncClient) close() { |
| 64 |
c.client.closeConnection(ClientClosed) |
| 65 |
c.quitCh <- true |
| 66 |
} |
| 67 |
|
| 68 |
func (c *testAsyncClient) parse(proto []byte) error { |
| 69 |
err := c.client.parse(proto) |
| 70 |
c.client.flushClients(0) |
| 71 |
return err |
| 72 |
} |
| 73 |
|
| 74 |
func (c *testAsyncClient) parseAndClose(proto []byte) { |
| 75 |
c.client.parse(proto) |
| 76 |
c.client.flushClients(0) |
| 77 |
c.closeConnection(ClientClosed) |
| 78 |
} |
| 79 |
|
| 80 |
func createClientAsync(ch chan *client, s *Server, cli net.Conn) { |
| 81 |
// Normally, those type of clients are used against non running servers. |
| 82 |
// However, some don't, which would then cause the writeLoop to be |
| 83 |
// started twice for the same client (since createClient() start both |
| 84 |
// read and write loop if it is detected as running). |
| 85 |
startWriteLoop := !s.isRunning() |
| 86 |
if startWriteLoop { |
| 87 |
s.grWG.Add(1) |
| 88 |
} |
| 89 |
go func() { |
| 90 |
c := s.createClient(cli) |
| 91 |
// Must be here to suppress +OK |
| 92 |
c.opts.Verbose = false |
| 93 |
if startWriteLoop { |
| 94 |
go c.writeLoop() |
| 95 |
} |
| 96 |
ch <- c |
| 97 |
}() |
| 98 |
} |
| 99 |
|
| 100 |
func newClientForServer(s *Server) (*testAsyncClient, *bufio.Reader, string) { |
| 101 |
cli, srv := net.Pipe() |
| 102 |
cr := bufio.NewReaderSize(cli, maxBufSize) |
| 103 |
ch := make(chan *client) |
| 104 |
createClientAsync(ch, s, srv) |
| 105 |
// So failing tests don't just hang. |
| 106 |
cli.SetReadDeadline(time.Now().Add(10 * time.Second)) |
| 107 |
l, _ := cr.ReadString('\n') |
| 108 |
// Grab client |
| 109 |
c := <-ch |
| 110 |
parse, quitCh := genAsyncParser(c) |
| 111 |
asyncClient := &testAsyncClient{ |
| 112 |
client: c, |
| 113 |
parseAsync: parse, |
| 114 |
quitCh: quitCh, |
| 115 |
} |
| 116 |
return asyncClient, cr, l |
| 117 |
} |
| 118 |
|
| 119 |
func genAsyncParser(c *client) (func(string), chan bool) { |
| 120 |
pab := make(chan []byte, 16) |
| 121 |
pas := func(cs string) { pab <- []byte(cs) } |
| 122 |
quit := make(chan bool) |
| 123 |
go func() { |
| 124 |
for { |
| 125 |
select { |
| 126 |
case cs := <-pab: |
| 127 |
c.parse(cs) |
| 128 |
c.flushClients(0) |
| 129 |
case <-quit: |
| 130 |
return |
| 131 |
} |
| 132 |
} |
| 133 |
}() |
| 134 |
return pas, quit |
| 135 |
} |
| 136 |
|
| 137 |
var defaultServerOptions = Options{ |
| 138 |
Host: "127.0.0.1", |
| 139 |
Port: -1, |
| 140 |
Trace: true, |
| 141 |
Debug: true, |
| 142 |
DisableShortFirstPing: true, |
| 143 |
NoLog: true, |
| 144 |
NoSigs: true, |
| 145 |
} |
| 146 |
|
| 147 |
func rawSetup(serverOptions Options) (*Server, *testAsyncClient, *bufio.Reader, string) { |
| 148 |
s := New(&serverOptions) |
| 149 |
c, cr, l := newClientForServer(s) |
| 150 |
return s, c, cr, l |
| 151 |
} |
| 152 |
|
| 153 |
func setUpClientWithResponse() (*testAsyncClient, string) { |
| 154 |
_, c, _, l := rawSetup(defaultServerOptions) |
| 155 |
return c, l |
| 156 |
} |
| 157 |
|
| 158 |
func setupClient() (*Server, *testAsyncClient, *bufio.Reader) { |
| 159 |
s, c, cr, _ := rawSetup(defaultServerOptions) |
| 160 |
return s, c, cr |
| 161 |
} |
| 162 |
|
| 163 |
func checkClientsCount(t *testing.T, s *Server, expected int) { |
| 164 |
t.Helper() |
| 165 |
checkFor(t, 2*time.Second, 15*time.Millisecond, func() error { |
| 166 |
if nc := s.NumClients(); nc != expected { |
| 167 |
return fmt.Errorf("The number of expected connections was %v, got %v", expected, nc) |
| 168 |
} |
| 169 |
return nil |
| 170 |
}) |
| 171 |
} |
| 172 |
|
| 173 |
func checkAccClientsCount(t *testing.T, acc *Account, expected int) { |
| 174 |
t.Helper() |
| 175 |
checkFor(t, 4*time.Second, 10*time.Millisecond, func() error { |
| 176 |
if nc := acc.NumConnections(); nc != expected { |
| 177 |
return fmt.Errorf("Expected account %q to have %v clients, got %v", |
| 178 |
acc.Name, expected, nc) |
| 179 |
} |
| 180 |
return nil |
| 181 |
}) |
| 182 |
} |
| 183 |
|
| 184 |
func TestAsyncClientWithRunningServer(t *testing.T) { |
| 185 |
o := DefaultOptions() |
| 186 |
s := RunServer(o) |
| 187 |
defer s.Shutdown() |
| 188 |
|
| 189 |
c, _, _ := newClientForServer(s) |
| 190 |
defer c.close() |
| 191 |
|
| 192 |
buf := make([]byte, 1000000) |
| 193 |
writeLoopTxt := fmt.Sprintf("writeLoop(%p)", c.client) |
| 194 |
checkFor(t, time.Second, 15*time.Millisecond, func() error { |
| 195 |
n := runtime.Stack(buf, true) |
| 196 |
if count := strings.Count(string(buf[:n]), writeLoopTxt); count != 1 { |
| 197 |
return fmt.Errorf("writeLoop for client should have been started only once: %v", count) |
| 198 |
} |
| 199 |
return nil |
| 200 |
}) |
| 201 |
} |
| 202 |
|
| 203 |
func TestClientCreateAndInfo(t *testing.T) { |
| 204 |
s, c, _, l := rawSetup(defaultServerOptions) |
| 205 |
defer c.close() |
| 206 |
|
| 207 |
if c.cid != 1 { |
| 208 |
t.Fatalf("Expected cid of 1 vs %d\n", c.cid) |
| 209 |
} |
| 210 |
if c.state != OP_START { |
| 211 |
t.Fatal("Expected state to be OP_START") |
| 212 |
} |
| 213 |
|
| 214 |
if !strings.HasPrefix(l, "INFO ") { |
| 215 |
t.Fatalf("INFO response incorrect: %s\n", l) |
| 216 |
} |
| 217 |
// Make sure payload is proper json |
| 218 |
var info serverInfo |
| 219 |
err := json.Unmarshal([]byte(l[5:]), &info) |
| 220 |
if err != nil { |
| 221 |
t.Fatalf("Could not parse INFO json: %v\n", err) |
| 222 |
} |
| 223 |
// Sanity checks |
| 224 |
if info.MaxPayload != MAX_PAYLOAD_SIZE || |
| 225 |
info.AuthRequired || info.TLSRequired || |
| 226 |
int(info.Port) != s.opts.Port { |
| 227 |
t.Fatalf("INFO inconsistent: %+v\n", info) |
| 228 |
} |
| 229 |
} |
| 230 |
|
| 231 |
func TestClientNoResponderSupport(t *testing.T) { |
| 232 |
opts := defaultServerOptions |
| 233 |
s := New(&opts) |
| 234 |
|
| 235 |
c, _, _ := newClientForServer(s) |
| 236 |
defer c.close() |
| 237 |
|
| 238 |
// Force header support if you want to do no_responders. Make sure headers are set. |
| 239 |
if err := c.parse([]byte("CONNECT {\"no_responders\":true}\r\n")); err == nil { |
| 240 |
t.Fatalf("Expected error") |
| 241 |
} |
| 242 |
|
| 243 |
c, cr, _ := newClientForServer(s) |
| 244 |
defer c.close() |
| 245 |
|
| 246 |
c.parseAsync("CONNECT {\"headers\":true, \"no_responders\":true}\r\nSUB reply 1\r\nPUB foo reply 2\r\nok\r\n") |
| 247 |
|
| 248 |
l, err := cr.ReadString('\n') |
| 249 |
if err != nil { |
| 250 |
t.Fatalf("Error receiving msg from server: %v\n", err) |
| 251 |
} |
| 252 |
|
| 253 |
am := hmsgPat.FindAllStringSubmatch(l, -1) |
| 254 |
if len(am) == 0 { |
| 255 |
t.Fatalf("Did not get a match for %q", l) |
| 256 |
} |
| 257 |
checkPayload(cr, []byte("NATS/1.0 503\r\nNats-Subject: foo\r\n\r\n\r\n"), t) |
| 258 |
} |
| 259 |
|
| 260 |
func TestServerHeaderSupport(t *testing.T) { |
| 261 |
opts := defaultServerOptions |
| 262 |
s := New(&opts) |
| 263 |
|
| 264 |
c, _, l := newClientForServer(s) |
| 265 |
defer c.close() |
| 266 |
|
| 267 |
if !strings.HasPrefix(l, "INFO ") { |
| 268 |
t.Fatalf("INFO response incorrect: %s\n", l) |
| 269 |
} |
| 270 |
var info serverInfo |
| 271 |
if err := json.Unmarshal([]byte(l[5:]), &info); err != nil { |
| 272 |
t.Fatalf("Could not parse INFO json: %v\n", err) |
| 273 |
} |
| 274 |
if !info.Headers { |
| 275 |
t.Fatalf("Expected by default for header support to be enabled") |
| 276 |
} |
| 277 |
|
| 278 |
opts.NoHeaderSupport = true |
| 279 |
opts.Port = -1 |
| 280 |
s = New(&opts) |
| 281 |
|
| 282 |
c, _, l = newClientForServer(s) |
| 283 |
defer c.close() |
| 284 |
|
| 285 |
if err := json.Unmarshal([]byte(l[5:]), &info); err != nil { |
| 286 |
t.Fatalf("Could not parse INFO json: %v\n", err) |
| 287 |
} |
| 288 |
if info.Headers { |
| 289 |
t.Fatalf("Expected header support to be disabled") |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
// This test specifically is not testing how headers are encoded in a raw msg. |
| 294 |
// It wants to make sure the serve and clients agreement on when to use headers |
| 295 |
// is bi-directional and functions properly. |
| 296 |
func TestClientHeaderSupport(t *testing.T) { |
| 297 |
opts := defaultServerOptions |
| 298 |
s := New(&opts) |
| 299 |
|
| 300 |
c, _, _ := newClientForServer(s) |
| 301 |
defer c.close() |
| 302 |
|
| 303 |
// Even though the server supports headers we need to explicitly say we do in the |
| 304 |
// CONNECT. If we do not we should get an error. |
| 305 |
if err := c.parse([]byte("CONNECT {}\r\nHPUB foo 0 2\r\nok\r\n")); err != ErrMsgHeadersNotSupported { |
| 306 |
t.Fatalf("Expected to receive an error, got %v", err) |
| 307 |
} |
| 308 |
|
| 309 |
// This should succeed. |
| 310 |
c, _, _ = newClientForServer(s) |
| 311 |
defer c.close() |
| 312 |
|
| 313 |
if err := c.parse([]byte("CONNECT {\"headers\":true}\r\nHPUB foo 0 2\r\nok\r\n")); err != nil { |
| 314 |
t.Fatalf("Unexpected error %v", err) |
| 315 |
} |
| 316 |
|
| 317 |
// Now start a server without support. |
| 318 |
opts.NoHeaderSupport = true |
| 319 |
opts.Port = -1 |
| 320 |
s = New(&opts) |
| 321 |
|
| 322 |
c, _, _ = newClientForServer(s) |
| 323 |
defer c.close() |
| 324 |
if err := c.parse([]byte("CONNECT {\"headers\":true}\r\nHPUB foo 0 2\r\nok\r\n")); err != ErrMsgHeadersNotSupported { |
| 325 |
t.Fatalf("Expected to receive an error, got %v", err) |
| 326 |
} |
| 327 |
} |
| 328 |
|
| 329 |
var hmsgPat = regexp.MustCompile(`HMSG\s+([^\s]+)\s+([^\s]+)\s+(([^\s]+)[^\S\r\n]+)?(\d+)[^\S\r\n]+(\d+)\r\n`) |
| 330 |
|
| 331 |
func TestClientHeaderDeliverMsg(t *testing.T) { |
| 332 |
opts := defaultServerOptions |
| 333 |
s := New(&opts) |
| 334 |
|
| 335 |
c, cr, _ := newClientForServer(s) |
| 336 |
defer c.close() |
| 337 |
|
| 338 |
connect := "CONNECT {\"headers\":true}" |
| 339 |
subOp := "SUB foo 1" |
| 340 |
pubOp := "HPUB foo 12 14\r\nName:Derek\r\nOK\r\n" |
| 341 |
cmd := strings.Join([]string{connect, subOp, pubOp}, "\r\n") |
| 342 |
|
| 343 |
c.parseAsync(cmd) |
| 344 |
l, err := cr.ReadString('\n') |
| 345 |
if err != nil { |
| 346 |
t.Fatalf("Error receiving msg from server: %v\n", err) |
| 347 |
} |
| 348 |
|
| 349 |
am := hmsgPat.FindAllStringSubmatch(l, -1) |
| 350 |
if len(am) == 0 { |
| 351 |
t.Fatalf("Did not get a match for %q", l) |
| 352 |
} |
| 353 |
matches := am[0] |
| 354 |
if len(matches) != 7 { |
| 355 |
t.Fatalf("Did not get correct # matches: %d vs %d\n", len(matches), 7) |
| 356 |
} |
| 357 |
if matches[SUB_INDEX] != "foo" { |
| 358 |
t.Fatalf("Did not get correct subject: '%s'\n", matches[SUB_INDEX]) |
| 359 |
} |
| 360 |
if matches[SID_INDEX] != "1" { |
| 361 |
t.Fatalf("Did not get correct sid: '%s'\n", matches[SID_INDEX]) |
| 362 |
} |
| 363 |
if matches[HDR_INDEX] != "12" { |
| 364 |
t.Fatalf("Did not get correct msg length: '%s'\n", matches[HDR_INDEX]) |
| 365 |
} |
| 366 |
if matches[TLEN_INDEX] != "14" { |
| 367 |
t.Fatalf("Did not get correct msg length: '%s'\n", matches[TLEN_INDEX]) |
| 368 |
} |
| 369 |
checkPayload(cr, []byte("Name:Derek\r\nOK\r\n"), t) |
| 370 |
} |
| 371 |
|
| 372 |
var smsgPat = regexp.MustCompile(`^MSG\s+([^\s]+)\s+([^\s]+)\s+(([^\s]+)[^\S\r\n]+)?(\d+)\r\n`) |
| 373 |
|
| 374 |
func TestClientHeaderDeliverStrippedMsg(t *testing.T) { |
| 375 |
opts := defaultServerOptions |
| 376 |
s := New(&opts) |
| 377 |
|
| 378 |
c, _, _ := newClientForServer(s) |
| 379 |
defer c.close() |
| 380 |
|
| 381 |
b, br, _ := newClientForServer(s) |
| 382 |
defer b.close() |
| 383 |
|
| 384 |
// Does not support headers |
| 385 |
b.parseAsync("SUB foo 1\r\nPING\r\n") |
| 386 |
if _, err := br.ReadString('\n'); err != nil { |
| 387 |
t.Fatalf("Error receiving msg from server: %v\n", err) |
| 388 |
} |
| 389 |
|
| 390 |
connect := "CONNECT {\"headers\":true}" |
| 391 |
pubOp := "HPUB foo 12 14\r\nName:Derek\r\nOK\r\n" |
| 392 |
cmd := strings.Join([]string{connect, pubOp}, "\r\n") |
| 393 |
c.parseAsync(cmd) |
| 394 |
// Read from 'b' client. |
| 395 |
l, err := br.ReadString('\n') |
| 396 |
if err != nil { |
| 397 |
t.Fatalf("Error receiving msg from server: %v\n", err) |
| 398 |
} |
| 399 |
am := smsgPat.FindAllStringSubmatch(l, -1) |
| 400 |
if len(am) == 0 { |
| 401 |
t.Fatalf("Did not get a correct match for %q", l) |
| 402 |
} |
| 403 |
matches := am[0] |
| 404 |
if len(matches) != 6 { |
| 405 |
t.Fatalf("Did not get correct # matches: %d vs %d\n", len(matches), 6) |
| 406 |
} |
| 407 |
if matches[SUB_INDEX] != "foo" { |
| 408 |
t.Fatalf("Did not get correct subject: '%s'\n", matches[SUB_INDEX]) |
| 409 |
} |
| 410 |
if matches[SID_INDEX] != "1" { |
| 411 |
t.Fatalf("Did not get correct sid: '%s'\n", matches[SID_INDEX]) |
| 412 |
} |
| 413 |
if matches[LEN_INDEX] != "2" { |
| 414 |
t.Fatalf("Did not get correct msg length: '%s'\n", matches[LEN_INDEX]) |
| 415 |
} |
| 416 |
checkPayload(br, []byte("OK\r\n"), t) |
| 417 |
if br.Buffered() != 0 { |
| 418 |
t.Fatalf("Expected no extra bytes to be buffered, got %d", br.Buffered()) |
| 419 |
} |
| 420 |
} |
| 421 |
|
| 422 |
func TestClientHeaderDeliverQueueSubStrippedMsg(t *testing.T) { |
| 423 |
opts := defaultServerOptions |
| 424 |
s := New(&opts) |
| 425 |
|
| 426 |
c, _, _ := newClientForServer(s) |
| 427 |
defer c.close() |
| 428 |
|
| 429 |
b, br, _ := newClientForServer(s) |
| 430 |
defer b.close() |
| 431 |
|
| 432 |
// Does not support headers |
| 433 |
b.parseAsync("SUB foo bar 1\r\nPING\r\n") |
| 434 |
if _, err := br.ReadString('\n'); err != nil { |
| 435 |
t.Fatalf("Error receiving msg from server: %v\n", err) |
| 436 |
} |
| 437 |
|
| 438 |
connect := "CONNECT {\"headers\":true}" |
| 439 |
pubOp := "HPUB foo 12 14\r\nName:Derek\r\nOK\r\n" |
| 440 |
cmd := strings.Join([]string{connect, pubOp}, "\r\n") |
| 441 |
c.parseAsync(cmd) |
| 442 |
// Read from 'b' client. |
| 443 |
l, err := br.ReadString('\n') |
| 444 |
if err != nil { |
| 445 |
t.Fatalf("Error receiving msg from server: %v\n", err) |
| 446 |
} |
| 447 |
am := smsgPat.FindAllStringSubmatch(l, -1) |
| 448 |
if len(am) == 0 { |
| 449 |
t.Fatalf("Did not get a correct match for %q", l) |
| 450 |
} |
| 451 |
matches := am[0] |
| 452 |
if len(matches) != 6 { |
| 453 |
t.Fatalf("Did not get correct # matches: %d vs %d\n", len(matches), 6) |
| 454 |
} |
| 455 |
if matches[SUB_INDEX] != "foo" { |
| 456 |
t.Fatalf("Did not get correct subject: '%s'\n", matches[SUB_INDEX]) |
| 457 |
} |
| 458 |
if matches[SID_INDEX] != "1" { |
| 459 |
t.Fatalf("Did not get correct sid: '%s'\n", matches[SID_INDEX]) |
| 460 |
} |
| 461 |
if matches[LEN_INDEX] != "2" { |
| 462 |
t.Fatalf("Did not get correct msg length: '%s'\n", matches[LEN_INDEX]) |
| 463 |
} |
| 464 |
checkPayload(br, []byte("OK\r\n"), t) |
| 465 |
} |
| 466 |
|
| 467 |
func TestNonTLSConnectionState(t *testing.T) { |
| 468 |
_, c, _ := setupClient() |
| 469 |
defer c.close() |
| 470 |
state := c.GetTLSConnectionState() |
| 471 |
if state != nil { |
| 472 |
t.Error("GetTLSConnectionState() returned non-nil") |
| 473 |
} |
| 474 |
} |
| 475 |
|
| 476 |
func TestClientConnect(t *testing.T) { |
| 477 |
_, c, _ := setupClient() |
| 478 |
defer c.close() |
| 479 |
|
| 480 |
// Basic Connect setting flags |
| 481 |
connectOp := []byte("CONNECT {\"verbose\":true,\"pedantic\":true,\"tls_required\":false,\"echo\":false}\r\n") |
| 482 |
err := c.parse(connectOp) |
| 483 |
if err != nil { |
| 484 |
t.Fatalf("Received error: %v\n", err) |
| 485 |
} |
| 486 |
if c.state != OP_START { |
| 487 |
t.Fatalf("Expected state of OP_START vs %d\n", c.state) |
| 488 |
} |
| 489 |
if !reflect.DeepEqual(c.opts, ClientOpts{Verbose: true, Pedantic: true, Echo: false}) { |
| 490 |
t.Fatalf("Did not parse connect options correctly: %+v\n", c.opts) |
| 491 |
} |
| 492 |
|
| 493 |
// Test that we can capture user/pass |
| 494 |
connectOp = []byte("CONNECT {\"user\":\"derek\",\"pass\":\"foo\"}\r\n") |
| 495 |
c.opts = defaultOpts |
| 496 |
err = c.parse(connectOp) |
| 497 |
if err != nil { |
| 498 |
t.Fatalf("Received error: %v\n", err) |
| 499 |
} |
| 500 |
if c.state != OP_START { |
| 501 |
t.Fatalf("Expected state of OP_START vs %d\n", c.state) |
| 502 |
} |
| 503 |
if !reflect.DeepEqual(c.opts, ClientOpts{Echo: true, Verbose: true, Pedantic: true, Username: "derek", Password: "foo"}) { |
| 504 |
t.Fatalf("Did not parse connect options correctly: %+v\n", c.opts) |
| 505 |
} |
| 506 |
|
| 507 |
// Test that we can capture client name |
| 508 |
connectOp = []byte("CONNECT {\"user\":\"derek\",\"pass\":\"foo\",\"name\":\"router\"}\r\n") |
| 509 |
c.opts = defaultOpts |
| 510 |
err = c.parse(connectOp) |
| 511 |
if err != nil { |
| 512 |
t.Fatalf("Received error: %v\n", err) |
| 513 |
} |
| 514 |
if c.state != OP_START { |
| 515 |
t.Fatalf("Expected state of OP_START vs %d\n", c.state) |
| 516 |
} |
| 517 |
|
| 518 |
if !reflect.DeepEqual(c.opts, ClientOpts{Echo: true, Verbose: true, Pedantic: true, Username: "derek", Password: "foo", Name: "router"}) { |
| 519 |
t.Fatalf("Did not parse connect options correctly: %+v\n", c.opts) |
| 520 |
} |
| 521 |
|
| 522 |
// Test that we correctly capture auth tokens |
| 523 |
connectOp = []byte("CONNECT {\"auth_token\":\"YZZ222\",\"name\":\"router\"}\r\n") |
| 524 |
c.opts = defaultOpts |
| 525 |
err = c.parse(connectOp) |
| 526 |
if err != nil { |
| 527 |
t.Fatalf("Received error: %v\n", err) |
| 528 |
} |
| 529 |
if c.state != OP_START { |
| 530 |
t.Fatalf("Expected state of OP_START vs %d\n", c.state) |
| 531 |
} |
| 532 |
|
| 533 |
if !reflect.DeepEqual(c.opts, ClientOpts{Echo: true, Verbose: true, Pedantic: true, Token: "YZZ222", Name: "router"}) { |
| 534 |
t.Fatalf("Did not parse connect options correctly: %+v\n", c.opts) |
| 535 |
} |
| 536 |
} |
| 537 |
|
| 538 |
func TestClientConnectProto(t *testing.T) { |
| 539 |
_, c, r := setupClient() |
| 540 |
defer c.close() |
| 541 |
|
| 542 |
// Basic Connect setting flags, proto should be zero (original proto) |
| 543 |
connectOp := []byte("CONNECT {\"verbose\":true,\"pedantic\":true,\"tls_required\":false}\r\n") |
| 544 |
err := c.parse(connectOp) |
| 545 |
if err != nil { |
| 546 |
t.Fatalf("Received error: %v\n", err) |
| 547 |
} |
| 548 |
if c.state != OP_START { |
| 549 |
t.Fatalf("Expected state of OP_START vs %d\n", c.state) |
| 550 |
} |
| 551 |
if !reflect.DeepEqual(c.opts, ClientOpts{Echo: true, Verbose: true, Pedantic: true, Protocol: ClientProtoZero}) { |
| 552 |
t.Fatalf("Did not parse connect options correctly: %+v\n", c.opts) |
| 553 |
} |
| 554 |
|
| 555 |
// ProtoInfo |
| 556 |
connectOp = []byte(fmt.Sprintf("CONNECT {\"verbose\":true,\"pedantic\":true,\"tls_required\":false,\"protocol\":%d}\r\n", ClientProtoInfo)) |
| 557 |
err = c.parse(connectOp) |
| 558 |
if err != nil { |
| 559 |
t.Fatalf("Received error: %v\n", err) |
| 560 |
} |
| 561 |
if c.state != OP_START { |
| 562 |
t.Fatalf("Expected state of OP_START vs %d\n", c.state) |
| 563 |
} |
| 564 |
if !reflect.DeepEqual(c.opts, ClientOpts{Echo: true, Verbose: true, Pedantic: true, Protocol: ClientProtoInfo}) { |
| 565 |
t.Fatalf("Did not parse connect options correctly: %+v\n", c.opts) |
| 566 |
} |
| 567 |
if c.opts.Protocol != ClientProtoInfo { |
| 568 |
t.Fatalf("Protocol should have been set to %v, but is set to %v", ClientProtoInfo, c.opts.Protocol) |
| 569 |
} |
| 570 |
|
| 571 |
// Illegal Option |
| 572 |
connectOp = []byte("CONNECT {\"protocol\":22}\r\n") |
| 573 |
wg := sync.WaitGroup{} |
| 574 |
wg.Add(1) |
| 575 |
// The client here is using a pipe, we need to be dequeuing |
| 576 |
// data otherwise the server would be blocked trying to send |
| 577 |
// the error back to it. |
| 578 |
go func() { |
| 579 |
defer wg.Done() |
| 580 |
for { |
| 581 |
if _, _, err := r.ReadLine(); err != nil { |
| 582 |
return |
| 583 |
} |
| 584 |
} |
| 585 |
}() |
| 586 |
err = c.parse(connectOp) |
| 587 |
if err == nil { |
| 588 |
t.Fatalf("Expected to receive an error\n") |
| 589 |
} |
| 590 |
if err != ErrBadClientProtocol { |
| 591 |
t.Fatalf("Expected err of %q, got %q\n", ErrBadClientProtocol, err) |
| 592 |
} |
| 593 |
wg.Wait() |
| 594 |
} |
| 595 |
|
| 596 |
func TestRemoteAddress(t *testing.T) { |
| 597 |
rc := &client{} |
| 598 |
|
| 599 |
// though in reality this will panic if it does not, adding coverage anyway |
| 600 |
if rc.RemoteAddress() != nil { |
| 601 |
t.Errorf("RemoteAddress() did not handle nil connection correctly") |
| 602 |
} |
| 603 |
|
| 604 |
_, c, _ := setupClient() |
| 605 |
defer c.close() |
| 606 |
addr := c.RemoteAddress() |
| 607 |
|
| 608 |
if addr.Network() != "pipe" { |
| 609 |
t.Errorf("RemoteAddress() returned invalid network: %s", addr.Network()) |
| 610 |
} |
| 611 |
|
| 612 |
if addr.String() != "pipe" { |
| 613 |
t.Errorf("RemoteAddress() returned invalid string: %s", addr.String()) |
| 614 |
} |
| 615 |
} |
| 616 |
|
| 617 |
func TestClientPing(t *testing.T) { |
| 618 |
_, c, cr := setupClient() |
| 619 |
defer c.close() |
| 620 |
|
| 621 |
// PING |
| 622 |
pingOp := "PING\r\n" |
| 623 |
c.parseAsync(pingOp) |
| 624 |
l, err := cr.ReadString('\n') |
| 625 |
if err != nil { |
| 626 |
t.Fatalf("Error receiving info from server: %v\n", err) |
| 627 |
} |
| 628 |
if !strings.HasPrefix(l, "PONG\r\n") { |
| 629 |
t.Fatalf("PONG response incorrect: %s\n", l) |
| 630 |
} |
| 631 |
} |
| 632 |
|
| 633 |
var msgPat = regexp.MustCompile(`MSG\s+([^\s]+)\s+([^\s]+)\s+(([^\s]+)[^\S\r\n]+)?(\d+)\r\n`) |
| 634 |
|
| 635 |
const ( |
| 636 |
SUB_INDEX = 1 |
| 637 |
SID_INDEX = 2 |
| 638 |
REPLY_INDEX = 4 |
| 639 |
LEN_INDEX = 5 |
| 640 |
HDR_INDEX = 5 |
| 641 |
TLEN_INDEX = 6 |
| 642 |
) |
| 643 |
|
| 644 |
func grabPayload(cr *bufio.Reader, expected int) []byte { |
| 645 |
d := make([]byte, expected) |
| 646 |
n, _ := cr.Read(d) |
| 647 |
cr.ReadString('\n') |
| 648 |
return d[:n] |
| 649 |
} |
| 650 |
|
| 651 |
func checkPayload(cr *bufio.Reader, expected []byte, t *testing.T) { |
| 652 |
t.Helper() |
| 653 |
// Read in payload |
| 654 |
d := make([]byte, len(expected)) |
| 655 |
n, err := cr.Read(d) |
| 656 |
if err != nil { |
| 657 |
t.Fatalf("Error receiving msg payload from server: %v\n", err) |
| 658 |
} |
| 659 |
if n != len(expected) { |
| 660 |
t.Fatalf("Did not read correct amount of bytes: %d vs %d\n", n, len(expected)) |
| 661 |
} |
| 662 |
if !bytes.Equal(d, expected) { |
| 663 |
t.Fatalf("Did not read correct payload:: <%s>\n", d) |
| 664 |
} |
| 665 |
} |
| 666 |
|
| 667 |
func TestClientSimplePubSub(t *testing.T) { |
| 668 |
_, c, cr := setupClient() |
| 669 |
defer c.close() |
| 670 |
// SUB/PUB |
| 671 |
c.parseAsync("SUB foo 1\r\nPUB foo 5\r\nhello\r\nPING\r\n") |
| 672 |
l, err := cr.ReadString('\n') |
| 673 |
if err != nil { |
| 674 |
t.Fatalf("Error receiving msg from server: %v\n", err) |
| 675 |
} |
| 676 |
matches := msgPat.FindAllStringSubmatch(l, -1)[0] |
| 677 |
if len(matches) != 6 { |
| 678 |
t.Fatalf("Did not get correct # matches: %d vs %d\n", len(matches), 6) |
| 679 |
} |
| 680 |
if matches[SUB_INDEX] != "foo" { |
| 681 |
t.Fatalf("Did not get correct subject: '%s'\n", matches[SUB_INDEX]) |
| 682 |
} |
| 683 |
if matches[SID_INDEX] != "1" { |
| 684 |
t.Fatalf("Did not get correct sid: '%s'\n", matches[SID_INDEX]) |
| 685 |
} |
| 686 |
if matches[LEN_INDEX] != "5" { |
| 687 |
t.Fatalf("Did not get correct msg length: '%s'\n", matches[LEN_INDEX]) |
| 688 |
} |
| 689 |
checkPayload(cr, []byte("hello\r\n"), t) |
| 690 |
} |
| 691 |
|
| 692 |
func TestClientPubSubNoEcho(t *testing.T) { |
| 693 |
_, c, cr := setupClient() |
| 694 |
defer c.close() |
| 695 |
// Specify no echo |
| 696 |
connectOp := []byte("CONNECT {\"echo\":false}\r\n") |
| 697 |
err := c.parse(connectOp) |
| 698 |
if err != nil { |
| 699 |
t.Fatalf("Received error: %v\n", err) |
| 700 |
} |
| 701 |
// SUB/PUB |
| 702 |
c.parseAsync("SUB foo 1\r\nPUB foo 5\r\nhello\r\nPING\r\n") |
| 703 |
l, err := cr.ReadString('\n') |
| 704 |
if err != nil { |
| 705 |
t.Fatalf("Error receiving msg from server: %v\n", err) |
| 706 |
} |
| 707 |
// We should not receive anything but a PONG since we specified no echo. |
| 708 |
if !strings.HasPrefix(l, "PONG\r\n") { |
| 709 |
t.Fatalf("PONG response incorrect: %q\n", l) |
| 710 |
} |
| 711 |
} |
| 712 |
|
| 713 |
func TestClientSimplePubSubWithReply(t *testing.T) { |
| 714 |
_, c, cr := setupClient() |
| 715 |
defer c.close() |
| 716 |
|
| 717 |
// SUB/PUB |
| 718 |
c.parseAsync("SUB foo 1\r\nPUB foo bar 5\r\nhello\r\nPING\r\n") |
| 719 |
l, err := cr.ReadString('\n') |
| 720 |
if err != nil { |
| 721 |
t.Fatalf("Error receiving msg from server: %v\n", err) |
| 722 |
} |
| 723 |
matches := msgPat.FindAllStringSubmatch(l, -1)[0] |
| 724 |
if len(matches) != 6 { |
| 725 |
t.Fatalf("Did not get correct # matches: %d vs %d\n", len(matches), 6) |
| 726 |
} |
| 727 |
if matches[SUB_INDEX] != "foo" { |
| 728 |
t.Fatalf("Did not get correct subject: '%s'\n", matches[SUB_INDEX]) |
| 729 |
} |
| 730 |
if matches[SID_INDEX] != "1" { |
| 731 |
t.Fatalf("Did not get correct sid: '%s'\n", matches[SID_INDEX]) |
| 732 |
} |
| 733 |
if matches[REPLY_INDEX] != "bar" { |
| 734 |
t.Fatalf("Did not get correct reply subject: '%s'\n", matches[REPLY_INDEX]) |
| 735 |
} |
| 736 |
if matches[LEN_INDEX] != "5" { |
| 737 |
t.Fatalf("Did not get correct msg length: '%s'\n", matches[LEN_INDEX]) |
| 738 |
} |
| 739 |
} |
| 740 |
|
| 741 |
func TestClientNoBodyPubSubWithReply(t *testing.T) { |
| 742 |
_, c, cr := setupClient() |
| 743 |
defer c.close() |
| 744 |
|
| 745 |
// SUB/PUB |
| 746 |
c.parseAsync("SUB foo 1\r\nPUB foo bar 0\r\n\r\nPING\r\n") |
| 747 |
l, err := cr.ReadString('\n') |
| 748 |
if err != nil { |
| 749 |
t.Fatalf("Error receiving msg from server: %v\n", err) |
| 750 |
} |
| 751 |
matches := msgPat.FindAllStringSubmatch(l, -1)[0] |
| 752 |
if len(matches) != 6 { |
| 753 |
t.Fatalf("Did not get correct # matches: %d vs %d\n", len(matches), 6) |
| 754 |
} |
| 755 |
if matches[SUB_INDEX] != "foo" { |
| 756 |
t.Fatalf("Did not get correct subject: '%s'\n", matches[SUB_INDEX]) |
| 757 |
} |
| 758 |
if matches[SID_INDEX] != "1" { |
| 759 |
t.Fatalf("Did not get correct sid: '%s'\n", matches[SID_INDEX]) |
| 760 |
} |
| 761 |
if matches[REPLY_INDEX] != "bar" { |
| 762 |
t.Fatalf("Did not get correct reply subject: '%s'\n", matches[REPLY_INDEX]) |
| 763 |
} |
| 764 |
if matches[LEN_INDEX] != "0" { |
| 765 |
t.Fatalf("Did not get correct msg length: '%s'\n", matches[LEN_INDEX]) |
| 766 |
} |
| 767 |
} |
| 768 |
|
| 769 |
func TestClientPubWithQueueSub(t *testing.T) { |
| 770 |
_, c, cr := setupClient() |
| 771 |
defer c.close() |
| 772 |
|
| 773 |
num := 100 |
| 774 |
|
| 775 |
// Queue SUB/PUB |
| 776 |
subs := []byte("SUB foo g1 1\r\nSUB foo g1 2\r\n") |
| 777 |
pubs := []byte("PUB foo bar 5\r\nhello\r\n") |
| 778 |
op := []byte{} |
| 779 |
op = append(op, subs...) |
| 780 |
for i := 0; i < num; i++ { |
| 781 |
op = append(op, pubs...) |
| 782 |
} |
| 783 |
|
| 784 |
go c.parseAndClose(op) |
| 785 |
|
| 786 |
var n1, n2, received int |
| 787 |
for ; ; received++ { |
| 788 |
l, err := cr.ReadString('\n') |
| 789 |
if err != nil { |
| 790 |
break |
| 791 |
} |
| 792 |
matches := msgPat.FindAllStringSubmatch(l, -1)[0] |
| 793 |
|
| 794 |
// Count which sub |
| 795 |
switch matches[SID_INDEX] { |
| 796 |
case "1": |
| 797 |
n1++ |
| 798 |
case "2": |
| 799 |
n2++ |
| 800 |
} |
| 801 |
checkPayload(cr, []byte("hello\r\n"), t) |
| 802 |
} |
| 803 |
if received != num { |
| 804 |
t.Fatalf("Received wrong # of msgs: %d vs %d\n", received, num) |
| 805 |
} |
| 806 |
// Threshold for randomness for now |
| 807 |
if n1 < 20 || n2 < 20 { |
| 808 |
t.Fatalf("Received wrong # of msgs per subscriber: %d - %d\n", n1, n2) |
| 809 |
} |
| 810 |
} |
| 811 |
|
| 812 |
func TestSplitSubjectQueue(t *testing.T) { |
| 813 |
cases := []struct { |
| 814 |
name string |
| 815 |
sq string |
| 816 |
wantSubject []byte |
| 817 |
wantQueue []byte |
| 818 |
wantErr bool |
| 819 |
}{ |
| 820 |
{name: "single subject", |
| 821 |
sq: "foo", wantSubject: []byte("foo"), wantQueue: nil}, |
| 822 |
{name: "subject and queue", |
| 823 |
sq: "foo bar", wantSubject: []byte("foo"), wantQueue: []byte("bar")}, |
| 824 |
{name: "subject and queue with surrounding spaces", |
| 825 |
sq: " foo bar ", wantSubject: []byte("foo"), wantQueue: []byte("bar")}, |
| 826 |
{name: "subject and queue with extra spaces in the middle", |
| 827 |
sq: "foo bar", wantSubject: []byte("foo"), wantQueue: []byte("bar")}, |
| 828 |
{name: "subject, queue, and extra token", |
| 829 |
sq: "foo bar fizz", wantSubject: []byte(nil), wantQueue: []byte(nil), wantErr: true}, |
| 830 |
{name: "empty", |
| 831 |
sq: "", wantSubject: []byte(nil), wantQueue: []byte(nil), wantErr: true}, |
| 832 |
{name: "tab only", |
| 833 |
sq: "\t", wantSubject: []byte(nil), wantQueue: []byte(nil), wantErr: true}, |
| 834 |
{name: "newline only", |
| 835 |
sq: "\n", wantSubject: []byte(nil), wantQueue: []byte(nil), wantErr: true}, |
| 836 |
{name: "mixed whitespace", |
| 837 |
sq: " \t\r\n", wantSubject: []byte(nil), wantQueue: []byte(nil), wantErr: true}, |
| 838 |
} |
| 839 |
|
| 840 |
for _, c := range cases { |
| 841 |
t.Run(c.name, func(t *testing.T) { |
| 842 |
sub, que, err := splitSubjectQueue(c.sq) |
| 843 |
if err == nil && c.wantErr { |
| 844 |
t.Fatal("Expected error, but got nil") |
| 845 |
} |
| 846 |
if err != nil && !c.wantErr { |
| 847 |
t.Fatalf("Expected nil error, but got %v", err) |
| 848 |
} |
| 849 |
|
| 850 |
if !reflect.DeepEqual(sub, c.wantSubject) { |
| 851 |
t.Fatalf("Expected to get subject %#v, but instead got %#v", c.wantSubject, sub) |
| 852 |
} |
| 853 |
if !reflect.DeepEqual(que, c.wantQueue) { |
| 854 |
t.Fatalf("Expected to get queue %#v, but instead got %#v", c.wantQueue, que) |
| 855 |
} |
| 856 |
}) |
| 857 |
} |
| 858 |
} |
| 859 |
|
| 860 |
func TestTypeString(t *testing.T) { |
| 861 |
cases := []struct { |
| 862 |
intType int |
| 863 |
stringType string |
| 864 |
}{ |
| 865 |
{ |
| 866 |
intType: CLIENT, |
| 867 |
stringType: "Client", |
| 868 |
}, |
| 869 |
{ |
| 870 |
intType: ROUTER, |
| 871 |
stringType: "Router", |
| 872 |
}, |
| 873 |
{ |
| 874 |
intType: GATEWAY, |
| 875 |
stringType: "Gateway", |
| 876 |
}, |
| 877 |
{ |
| 878 |
intType: LEAF, |
| 879 |
stringType: "Leafnode", |
| 880 |
}, |
| 881 |
{ |
| 882 |
intType: JETSTREAM, |
| 883 |
stringType: "JetStream", |
| 884 |
}, |
| 885 |
{ |
| 886 |
intType: ACCOUNT, |
| 887 |
stringType: "Account", |
| 888 |
}, |
| 889 |
{ |
| 890 |
intType: SYSTEM, |
| 891 |
stringType: "System", |
| 892 |
}, |
| 893 |
{ |
| 894 |
intType: -1, |
| 895 |
stringType: "Unknown Type", |
| 896 |
}, |
| 897 |
} |
| 898 |
for _, cs := range cases { |
| 899 |
c := &client{kind: cs.intType} |
| 900 |
typeStringVal := c.kindString() |
| 901 |
|
| 902 |
if typeStringVal != cs.stringType { |
| 903 |
t.Fatalf("Expected typeString value %q, but instead received %q", cs.stringType, typeStringVal) |
| 904 |
} |
| 905 |
} |
| 906 |
} |
| 907 |
|
| 908 |
func TestQueueSubscribePermissions(t *testing.T) { |
| 909 |
cases := []struct { |
| 910 |
name string |
| 911 |
perms *SubjectPermission |
| 912 |
subject string |
| 913 |
queue string |
| 914 |
want string |
| 915 |
}{ |
| 916 |
{ |
| 917 |
name: "plain subscription on foo", |
| 918 |
perms: &SubjectPermission{Allow: []string{"foo"}}, |
| 919 |
subject: "foo", |
| 920 |
want: "+OK\r\n", |
| 921 |
}, |
| 922 |
{ |
| 923 |
name: "queue subscribe with allowed group", |
| 924 |
perms: &SubjectPermission{Allow: []string{"foo bar"}}, |
| 925 |
subject: "foo", |
| 926 |
queue: "bar", |
| 927 |
want: "+OK\r\n", |
| 928 |
}, |
| 929 |
{ |
| 930 |
name: "queue subscribe with wildcard allowed group", |
| 931 |
perms: &SubjectPermission{Allow: []string{"foo bar.*"}}, |
| 932 |
subject: "foo", |
| 933 |
queue: "bar.fizz", |
| 934 |
want: "+OK\r\n", |
| 935 |
}, |
| 936 |
{ |
| 937 |
name: "queue subscribe with full wildcard subject and subgroup", |
| 938 |
perms: &SubjectPermission{Allow: []string{"> bar.>"}}, |
| 939 |
subject: "whizz", |
| 940 |
queue: "bar.bang", |
| 941 |
want: "+OK\r\n", |
| 942 |
}, |
| 943 |
{ |
| 944 |
name: "plain subscribe with full wildcard subject and subgroup", |
| 945 |
perms: &SubjectPermission{Allow: []string{"> bar.>"}}, |
| 946 |
subject: "whizz", |
| 947 |
want: "-ERR 'Permissions Violation for Subscription to \"whizz\"'\r\n", |
| 948 |
}, |
| 949 |
{ |
| 950 |
name: "deny plain subscription on foo", |
| 951 |
perms: &SubjectPermission{Allow: []string{">"}, Deny: []string{"foo"}}, |
| 952 |
subject: "foo", |
| 953 |
queue: "bar", |
| 954 |
want: "-ERR 'Permissions Violation for Subscription to \"foo\" using queue \"bar\"'\r\n", |
| 955 |
}, |
| 956 |
{ |
| 957 |
name: "allow plain subscription, except foo", |
| 958 |
perms: &SubjectPermission{Allow: []string{">"}, Deny: []string{"foo"}}, |
| 959 |
subject: "bar", |
| 960 |
want: "+OK\r\n", |
| 961 |
}, |
| 962 |
{ |
| 963 |
name: "deny everything", |
| 964 |
perms: &SubjectPermission{Allow: []string{">"}, Deny: []string{">"}}, |
| 965 |
subject: "foo", |
| 966 |
queue: "bar", |
| 967 |
want: "-ERR 'Permissions Violation for Subscription to \"foo\" using queue \"bar\"'\r\n", |
| 968 |
}, |
| 969 |
{ |
| 970 |
name: "can only subscribe to queues v1", |
| 971 |
perms: &SubjectPermission{Allow: []string{"> v1.>"}}, |
| 972 |
subject: "foo", |
| 973 |
queue: "v1.prod", |
| 974 |
want: "+OK\r\n", |
| 975 |
}, |
| 976 |
{ |
| 977 |
name: "cannot subscribe to queues, plain subscribe ok", |
| 978 |
perms: &SubjectPermission{Allow: []string{">"}, Deny: []string{"> >"}}, |
| 979 |
subject: "foo", |
| 980 |
want: "+OK\r\n", |
| 981 |
}, |
| 982 |
{ |
| 983 |
name: "cannot subscribe to queues, queue subscribe not ok", |
| 984 |
perms: &SubjectPermission{Deny: []string{"> >"}}, |
| 985 |
subject: "foo", |
| 986 |
queue: "bar", |
| 987 |
want: "-ERR 'Permissions Violation for Subscription to \"foo\" using queue \"bar\"'\r\n", |
| 988 |
}, |
| 989 |
{ |
| 990 |
name: "deny all queue subscriptions on dev or stg only", |
| 991 |
perms: &SubjectPermission{Deny: []string{"> *.dev", "> *.stg"}}, |
| 992 |
subject: "foo", |
| 993 |
queue: "bar", |
| 994 |
want: "+OK\r\n", |
| 995 |
}, |
| 996 |
{ |
| 997 |
name: "allow only queue subscription on dev or stg", |
| 998 |
perms: &SubjectPermission{Allow: []string{"> *.dev", "> *.stg"}}, |
| 999 |
subject: "foo", |
| 1000 |
queue: "bar", |
| 1001 |
want: "-ERR 'Permissions Violation for Subscription to \"foo\" using queue \"bar\"'\r\n", |
| 1002 |
}, |
| 1003 |
{ |
| 1004 |
name: "deny queue subscriptions with subject foo", |
| 1005 |
perms: &SubjectPermission{Deny: []string{"foo >"}}, |
| 1006 |
subject: "foo", |
| 1007 |
queue: "bar", |
| 1008 |
want: "-ERR 'Permissions Violation for Subscription to \"foo\" using queue \"bar\"'\r\n", |
| 1009 |
}, |
| 1010 |
{ |
| 1011 |
name: "plain sub is allowed, but queue subscribe with queue not in list", |
| 1012 |
perms: &SubjectPermission{Allow: []string{"foo bar"}}, |
| 1013 |
subject: "foo", |
| 1014 |
queue: "fizz", |
| 1015 |
want: "-ERR 'Permissions Violation for Subscription to \"foo\" using queue \"fizz\"'\r\n", |
| 1016 |
}, |
| 1017 |
{ |
| 1018 |
name: "allow plain sub, but do queue subscribe", |
| 1019 |
perms: &SubjectPermission{Allow: []string{"foo"}}, |
| 1020 |
subject: "foo", |
| 1021 |
queue: "bar", |
| 1022 |
want: "+OK\r\n", |
| 1023 |
}, |
| 1024 |
{ |
| 1025 |
name: "plain sub deny bypassed by queue deny rules", |
| 1026 |
perms: &SubjectPermission{Allow: []string{">"}, Deny: []string{"admin.>", "> restricted"}}, |
| 1027 |
subject: "admin.secret", |
| 1028 |
queue: "workers", |
| 1029 |
want: "-ERR 'Permissions Violation for Subscription to \"admin.secret\" using queue \"workers\"'\r\n", |
| 1030 |
}, |
| 1031 |
} |
| 1032 |
for _, c := range cases { |
| 1033 |
t.Run(c.name, func(t *testing.T) { |
| 1034 |
_, client, r := setupClient() |
| 1035 |
defer client.close() |
| 1036 |
|
| 1037 |
client.RegisterUser(&User{ |
| 1038 |
Permissions: &Permissions{Subscribe: c.perms}, |
| 1039 |
}) |
| 1040 |
connect := []byte("CONNECT {\"verbose\":true}\r\n") |
| 1041 |
qsub := []byte(fmt.Sprintf("SUB %s %s 1\r\n", c.subject, c.queue)) |
| 1042 |
|
| 1043 |
go client.parseAndClose(append(connect, qsub...)) |
| 1044 |
|
| 1045 |
var buf bytes.Buffer |
| 1046 |
if _, err := io.Copy(&buf, r); err != nil { |
| 1047 |
t.Fatal(err) |
| 1048 |
} |
| 1049 |
|
| 1050 |
// Extra OK is from the successful CONNECT. |
| 1051 |
want := "+OK\r\n" + c.want |
| 1052 |
if got := buf.String(); got != want { |
| 1053 |
t.Fatalf("Expected to receive %q, but instead received %q", want, got) |
| 1054 |
} |
| 1055 |
}) |
| 1056 |
} |
| 1057 |
} |
| 1058 |
|
| 1059 |
func TestClientSubscribeDenyWildcardOverlapBlocksDelivery(t *testing.T) { |
| 1060 |
for _, tc := range []struct { |
| 1061 |
name string |
| 1062 |
deny string |
| 1063 |
sub string |
| 1064 |
blocked string |
| 1065 |
allowed string |
| 1066 |
}{ |
| 1067 |
{name: "suffix overlap", deny: "*.secret", sub: "foo.*", blocked: "foo.secret", allowed: "foo.public"}, |
| 1068 |
{name: "middle overlap", deny: "foo.*.bar", sub: "foo.baz.*", blocked: "foo.baz.bar", allowed: "foo.baz.qux"}, |
| 1069 |
{name: "nested wildcard overlap", deny: "*.*.bar", sub: "foo.*.*", blocked: "foo.baz.bar", allowed: "foo.baz.qux"}, |
| 1070 |
{name: "full wildcard overlap", deny: "a.>", sub: "*.b", blocked: "a.b", allowed: "z.b"}, |
| 1071 |
} { |
| 1072 |
t.Run(tc.name, func(t *testing.T) { |
| 1073 |
require_True(t, SubjectsCollide(tc.deny, tc.sub)) |
| 1074 |
|
| 1075 |
opts := DefaultOptions() |
| 1076 |
opts.Users = []*User{ |
| 1077 |
{ |
| 1078 |
Username: "attacker", |
| 1079 |
Password: "pass", |
| 1080 |
Permissions: &Permissions{ |
| 1081 |
Subscribe: &SubjectPermission{ |
| 1082 |
Allow: []string{">"}, |
| 1083 |
Deny: []string{tc.deny}, |
| 1084 |
}, |
| 1085 |
}, |
| 1086 |
}, |
| 1087 |
{Username: "publisher", Password: "pass"}, |
| 1088 |
} |
| 1089 |
|
| 1090 |
s := RunServer(opts) |
| 1091 |
defer s.Shutdown() |
| 1092 |
|
| 1093 |
attacker, err := nats.Connect(s.ClientURL(), nats.UserInfo("attacker", "pass")) |
| 1094 |
require_NoError(t, err) |
| 1095 |
defer attacker.Close() |
| 1096 |
|
| 1097 |
publisher, err := nats.Connect(s.ClientURL(), nats.UserInfo("publisher", "pass")) |
| 1098 |
require_NoError(t, err) |
| 1099 |
defer publisher.Close() |
| 1100 |
|
| 1101 |
sub, err := attacker.QueueSubscribeSync(tc.sub, "workers") |
| 1102 |
require_NoError(t, err) |
| 1103 |
require_NoError(t, attacker.Flush()) |
| 1104 |
|
| 1105 |
require_NoError(t, publisher.Publish(tc.blocked, []byte("blocked"))) |
| 1106 |
require_NoError(t, publisher.Publish(tc.allowed, []byte("ok"))) |
| 1107 |
require_NoError(t, publisher.Flush()) |
| 1108 |
|
| 1109 |
msg, err := sub.NextMsg(time.Second) |
| 1110 |
require_NoError(t, err) |
| 1111 |
require_Equal(t, msg.Subject, tc.allowed) |
| 1112 |
require_Equal(t, string(msg.Data), "ok") |
| 1113 |
}) |
| 1114 |
} |
| 1115 |
} |
| 1116 |
|
| 1117 |
func TestClientQueueScopedSubscribeDenyBlocksOnlyMatchingQueue(t *testing.T) { |
| 1118 |
for _, tc := range []struct { |
| 1119 |
name string |
| 1120 |
deny string |
| 1121 |
deniedQ string |
| 1122 |
allowedQ string |
| 1123 |
subject string |
| 1124 |
subscribe string |
| 1125 |
}{ |
| 1126 |
{ |
| 1127 |
name: "literal queue", |
| 1128 |
deny: "admin.secret workers", |
| 1129 |
deniedQ: "workers", |
| 1130 |
allowedQ: "auditors", |
| 1131 |
subject: "admin.secret", |
| 1132 |
subscribe: "admin.*", |
| 1133 |
}, |
| 1134 |
{ |
| 1135 |
name: "wildcard queue", |
| 1136 |
deny: "admin.secret work.*", |
| 1137 |
deniedQ: "work.prod", |
| 1138 |
allowedQ: "audit.prod", |
| 1139 |
subject: "admin.secret", |
| 1140 |
subscribe: "admin.*", |
| 1141 |
}, |
| 1142 |
} { |
| 1143 |
t.Run(tc.name, func(t *testing.T) { |
| 1144 |
opts := DefaultOptions() |
| 1145 |
opts.Users = []*User{ |
| 1146 |
{ |
| 1147 |
Username: "attacker", |
| 1148 |
Password: "pass", |
| 1149 |
Permissions: &Permissions{ |
| 1150 |
Subscribe: &SubjectPermission{ |
| 1151 |
Allow: []string{">"}, |
| 1152 |
Deny: []string{tc.deny}, |
| 1153 |
}, |
| 1154 |
}, |
| 1155 |
}, |
| 1156 |
{Username: "publisher", Password: "pass"}, |
| 1157 |
} |
| 1158 |
|
| 1159 |
s := RunServer(opts) |
| 1160 |
defer s.Shutdown() |
| 1161 |
|
| 1162 |
attacker := natsConnect(t, s.ClientURL(), nats.UserInfo("attacker", "pass")) |
| 1163 |
defer attacker.Close() |
| 1164 |
publisher := natsConnect(t, s.ClientURL(), nats.UserInfo("publisher", "pass")) |
| 1165 |
defer publisher.Close() |
| 1166 |
|
| 1167 |
denied := natsQueueSubSync(t, attacker, tc.subscribe, tc.deniedQ) |
| 1168 |
allowed := natsQueueSubSync(t, attacker, tc.subscribe, tc.allowedQ) |
| 1169 |
plain := natsSubSync(t, attacker, tc.subscribe) |
| 1170 |
natsFlush(t, attacker) |
| 1171 |
|
| 1172 |
natsPub(t, publisher, tc.subject, []byte("secret")) |
| 1173 |
natsFlush(t, publisher) |
| 1174 |
|
| 1175 |
if _, err := denied.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout { |
| 1176 |
t.Fatalf("Expected matching queue subscription to be denied, got %v", err) |
| 1177 |
} |
| 1178 |
require_Equal(t, "secret", string(natsNexMsg(t, allowed, time.Second).Data)) |
| 1179 |
require_Equal(t, "secret", string(natsNexMsg(t, plain, time.Second).Data)) |
| 1180 |
}) |
| 1181 |
} |
| 1182 |
} |
| 1183 |
|
| 1184 |
func TestClientSetPermissionsClearsStaleMsgDenyState(t *testing.T) { |
| 1185 |
c := &client{} |
| 1186 |
c.setPermissions(&Permissions{ |
| 1187 |
Subscribe: &SubjectPermission{Deny: []string{"foo.secret"}}, |
| 1188 |
}) |
| 1189 |
require_True(t, c.canSubscribe("foo.*")) |
| 1190 |
require_True(t, c.mperms != nil) |
| 1191 |
require_Len(t, len(c.darray), 1) |
| 1192 |
|
| 1193 |
c.setPermissions(&Permissions{}) |
| 1194 |
require_True(t, c.mperms == nil) |
| 1195 |
require_Len(t, len(c.darray), 0) |
| 1196 |
|
| 1197 |
require_True(t, c.canSubscribe("foo.*")) |
| 1198 |
require_True(t, c.mperms == nil) |
| 1199 |
} |
| 1200 |
|
| 1201 |
func TestClientSetPermissionsPublishDenyQueueQualifierFailsClosed(t *testing.T) { |
| 1202 |
c := &client{srv: New(&Options{})} |
| 1203 |
c.setPermissions(&Permissions{ |
| 1204 |
Publish: &SubjectPermission{Deny: []string{"admin.secret workers"}}, |
| 1205 |
}) |
| 1206 |
np, _ := c.perms.pub.deny.NumInterest("admin.secret") |
| 1207 |
require_Equal(t, 1, np) |
| 1208 |
} |
| 1209 |
|
| 1210 |
func TestClientPublicPermissionsPreservesQueueQualifier(t *testing.T) { |
| 1211 |
c := &client{} |
| 1212 |
c.setPermissions(&Permissions{ |
| 1213 |
Subscribe: &SubjectPermission{ |
| 1214 |
Allow: []string{"events.* readers"}, |
| 1215 |
Deny: []string{"admin.secret workers"}, |
| 1216 |
}, |
| 1217 |
}) |
| 1218 |
perms := c.publicPermissions() |
| 1219 |
require_Equal(t, "events.* readers", perms.Subscribe.Allow[0]) |
| 1220 |
require_Equal(t, "admin.secret workers", perms.Subscribe.Deny[0]) |
| 1221 |
} |
| 1222 |
|
| 1223 |
func TestClientPubWithQueueSubNoEcho(t *testing.T) { |
| 1224 |
opts := DefaultOptions() |
| 1225 |
s := RunServer(opts) |
| 1226 |
defer s.Shutdown() |
| 1227 |
|
| 1228 |
nc1, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) |
| 1229 |
if err != nil { |
| 1230 |
t.Fatalf("Error on connect: %v", err) |
| 1231 |
} |
| 1232 |
defer nc1.Close() |
| 1233 |
|
| 1234 |
// Grab the client from server and set no echo by hand. |
| 1235 |
s.mu.Lock() |
| 1236 |
lc := len(s.clients) |
| 1237 |
c := s.clients[s.gcid] |
| 1238 |
s.mu.Unlock() |
| 1239 |
|
| 1240 |
if lc != 1 { |
| 1241 |
t.Fatalf("Expected only 1 client but got %d\n", lc) |
| 1242 |
} |
| 1243 |
if c == nil { |
| 1244 |
t.Fatal("Expected to retrieve client\n") |
| 1245 |
} |
| 1246 |
c.mu.Lock() |
| 1247 |
c.echo = false |
| 1248 |
c.mu.Unlock() |
| 1249 |
|
| 1250 |
// Queue sub on nc1. |
| 1251 |
_, err = nc1.QueueSubscribe("foo", "bar", func(*nats.Msg) {}) |
| 1252 |
if err != nil { |
| 1253 |
t.Fatalf("Error on subscribe: %v", err) |
| 1254 |
} |
| 1255 |
nc1.Flush() |
| 1256 |
|
| 1257 |
nc2, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) |
| 1258 |
if err != nil { |
| 1259 |
t.Fatalf("Error on connect: %v", err) |
| 1260 |
} |
| 1261 |
defer nc2.Close() |
| 1262 |
|
| 1263 |
n := int32(0) |
| 1264 |
cb := func(m *nats.Msg) { |
| 1265 |
atomic.AddInt32(&n, 1) |
| 1266 |
} |
| 1267 |
|
| 1268 |
_, err = nc2.QueueSubscribe("foo", "bar", cb) |
| 1269 |
if err != nil { |
| 1270 |
t.Fatalf("Error on subscribe: %v", err) |
| 1271 |
} |
| 1272 |
nc2.Flush() |
| 1273 |
|
| 1274 |
// Now publish 100 messages on nc1 which does not allow echo. |
| 1275 |
for i := 0; i < 100; i++ { |
| 1276 |
nc1.Publish("foo", []byte("Hello")) |
| 1277 |
} |
| 1278 |
nc1.Flush() |
| 1279 |
nc2.Flush() |
| 1280 |
|
| 1281 |
checkFor(t, 5*time.Second, 10*time.Millisecond, func() error { |
| 1282 |
num := atomic.LoadInt32(&n) |
| 1283 |
if num != int32(100) { |
| 1284 |
return fmt.Errorf("Expected all the msgs to be received by nc2, got %d\n", num) |
| 1285 |
} |
| 1286 |
return nil |
| 1287 |
}) |
| 1288 |
} |
| 1289 |
|
| 1290 |
func TestClientUnSub(t *testing.T) { |
| 1291 |
_, c, cr := setupClient() |
| 1292 |
defer c.close() |
| 1293 |
|
| 1294 |
num := 1 |
| 1295 |
|
| 1296 |
// SUB/PUB |
| 1297 |
subs := []byte("SUB foo 1\r\nSUB foo 2\r\n") |
| 1298 |
unsub := []byte("UNSUB 1\r\n") |
| 1299 |
pub := []byte("PUB foo bar 5\r\nhello\r\n") |
| 1300 |
|
| 1301 |
op := []byte{} |
| 1302 |
op = append(op, subs...) |
| 1303 |
op = append(op, unsub...) |
| 1304 |
op = append(op, pub...) |
| 1305 |
|
| 1306 |
go c.parseAndClose(op) |
| 1307 |
|
| 1308 |
var received int |
| 1309 |
for ; ; received++ { |
| 1310 |
l, err := cr.ReadString('\n') |
| 1311 |
if err != nil { |
| 1312 |
break |
| 1313 |
} |
| 1314 |
matches := msgPat.FindAllStringSubmatch(l, -1)[0] |
| 1315 |
if matches[SID_INDEX] != "2" { |
| 1316 |
t.Fatalf("Received msg on unsubscribed subscription!\n") |
| 1317 |
} |
| 1318 |
checkPayload(cr, []byte("hello\r\n"), t) |
| 1319 |
} |
| 1320 |
if received != num { |
| 1321 |
t.Fatalf("Received wrong # of msgs: %d vs %d\n", received, num) |
| 1322 |
} |
| 1323 |
} |
| 1324 |
|
| 1325 |
func TestClientUnSubMax(t *testing.T) { |
| 1326 |
_, c, cr := setupClient() |
| 1327 |
defer c.close() |
| 1328 |
|
| 1329 |
num := 10 |
| 1330 |
exp := 5 |
| 1331 |
|
| 1332 |
// SUB/PUB |
| 1333 |
subs := []byte("SUB foo 1\r\n") |
| 1334 |
unsub := []byte("UNSUB 1 5\r\n") |
| 1335 |
pub := []byte("PUB foo bar 5\r\nhello\r\n") |
| 1336 |
|
| 1337 |
op := []byte{} |
| 1338 |
op = append(op, subs...) |
| 1339 |
op = append(op, unsub...) |
| 1340 |
for i := 0; i < num; i++ { |
| 1341 |
op = append(op, pub...) |
| 1342 |
} |
| 1343 |
|
| 1344 |
go c.parseAndClose(op) |
| 1345 |
|
| 1346 |
var received int |
| 1347 |
for ; ; received++ { |
| 1348 |
l, err := cr.ReadString('\n') |
| 1349 |
if err != nil { |
| 1350 |
break |
| 1351 |
} |
| 1352 |
matches := msgPat.FindAllStringSubmatch(l, -1)[0] |
| 1353 |
if matches[SID_INDEX] != "1" { |
| 1354 |
t.Fatalf("Received msg on unsubscribed subscription!\n") |
| 1355 |
} |
| 1356 |
checkPayload(cr, []byte("hello\r\n"), t) |
| 1357 |
} |
| 1358 |
if received != exp { |
| 1359 |
t.Fatalf("Received wrong # of msgs: %d vs %d\n", received, exp) |
| 1360 |
} |
| 1361 |
} |
| 1362 |
|
| 1363 |
func TestClientAutoUnsubExactReceived(t *testing.T) { |
| 1364 |
_, c, _ := setupClient() |
| 1365 |
defer c.close() |
| 1366 |
|
| 1367 |
// SUB/PUB |
| 1368 |
subs := []byte("SUB foo 1\r\n") |
| 1369 |
unsub := []byte("UNSUB 1 1\r\n") |
| 1370 |
pub := []byte("PUB foo bar 2\r\nok\r\n") |
| 1371 |
|
| 1372 |
op := []byte{} |
| 1373 |
op = append(op, subs...) |
| 1374 |
op = append(op, unsub...) |
| 1375 |
op = append(op, pub...) |
| 1376 |
|
| 1377 |
c.parse(op) |
| 1378 |
|
| 1379 |
// We should not have any subscriptions in place here. |
| 1380 |
if len(c.subs) != 0 { |
| 1381 |
t.Fatalf("Wrong number of subscriptions: expected 0, got %d\n", len(c.subs)) |
| 1382 |
} |
| 1383 |
} |
| 1384 |
|
| 1385 |
func TestClientUnsubAfterAutoUnsub(t *testing.T) { |
| 1386 |
_, c, _ := setupClient() |
| 1387 |
defer c.close() |
| 1388 |
|
| 1389 |
// SUB/UNSUB/UNSUB |
| 1390 |
subs := []byte("SUB foo 1\r\n") |
| 1391 |
asub := []byte("UNSUB 1 1\r\n") |
| 1392 |
unsub := []byte("UNSUB 1\r\n") |
| 1393 |
|
| 1394 |
op := []byte{} |
| 1395 |
op = append(op, subs...) |
| 1396 |
op = append(op, asub...) |
| 1397 |
op = append(op, unsub...) |
| 1398 |
|
| 1399 |
c.parse(op) |
| 1400 |
|
| 1401 |
// We should not have any subscriptions in place here. |
| 1402 |
if len(c.subs) != 0 { |
| 1403 |
t.Fatalf("Wrong number of subscriptions: expected 0, got %d\n", len(c.subs)) |
| 1404 |
} |
| 1405 |
} |
| 1406 |
|
| 1407 |
func TestClientRemoveSubsOnDisconnect(t *testing.T) { |
| 1408 |
s, c, _ := setupClient() |
| 1409 |
defer c.close() |
| 1410 |
subs := []byte("SUB foo 1\r\nSUB bar 2\r\n") |
| 1411 |
|
| 1412 |
c.parse(subs) |
| 1413 |
|
| 1414 |
if s.NumSubscriptions() != 2 { |
| 1415 |
t.Fatalf("Should have 2 subscriptions, got %d\n", s.NumSubscriptions()) |
| 1416 |
} |
| 1417 |
c.closeConnection(ClientClosed) |
| 1418 |
checkExpectedSubs(t, 0, s) |
| 1419 |
} |
| 1420 |
|
| 1421 |
func TestClientDoesNotAddSubscriptionsWhenConnectionClosed(t *testing.T) { |
| 1422 |
_, c, _ := setupClient() |
| 1423 |
c.close() |
| 1424 |
subs := []byte("SUB foo 1\r\nSUB bar 2\r\n") |
| 1425 |
|
| 1426 |
c.parse(subs) |
| 1427 |
|
| 1428 |
if c.acc.sl.Count() != 0 { |
| 1429 |
t.Fatalf("Should have no subscriptions after close, got %d\n", c.acc.sl.Count()) |
| 1430 |
} |
| 1431 |
} |
| 1432 |
|
| 1433 |
func TestClientMapRemoval(t *testing.T) { |
| 1434 |
s, c, _ := setupClient() |
| 1435 |
c.close() |
| 1436 |
|
| 1437 |
checkClientsCount(t, s, 0) |
| 1438 |
} |
| 1439 |
|
| 1440 |
func TestAuthorizationTimeout(t *testing.T) { |
| 1441 |
serverOptions := DefaultOptions() |
| 1442 |
serverOptions.Authorization = "my_token" |
| 1443 |
serverOptions.AuthTimeout = 0.4 |
| 1444 |
s := RunServer(serverOptions) |
| 1445 |
defer s.Shutdown() |
| 1446 |
|
| 1447 |
conn, err := net.Dial("tcp", net.JoinHostPort(serverOptions.Host, fmt.Sprintf("%d", serverOptions.Port))) |
| 1448 |
if err != nil { |
| 1449 |
t.Fatalf("Error dialing server: %v\n", err) |
| 1450 |
} |
| 1451 |
defer conn.Close() |
| 1452 |
client := bufio.NewReaderSize(conn, maxBufSize) |
| 1453 |
if _, err := client.ReadString('\n'); err != nil { |
| 1454 |
t.Fatalf("Error receiving info from server: %v\n", err) |
| 1455 |
} |
| 1456 |
time.Sleep(3 * secondsToDuration(serverOptions.AuthTimeout)) |
| 1457 |
l, err := client.ReadString('\n') |
| 1458 |
if err != nil { |
| 1459 |
t.Fatalf("Error receiving info from server: %v\n", err) |
| 1460 |
} |
| 1461 |
if !strings.Contains(l, "Authentication Timeout") { |
| 1462 |
t.Fatalf("Authentication Timeout response incorrect: %q\n", l) |
| 1463 |
} |
| 1464 |
} |
| 1465 |
|
| 1466 |
// This is from bug report #18 |
| 1467 |
func TestTwoTokenPubMatchSingleTokenSub(t *testing.T) { |
| 1468 |
_, c, cr := setupClient() |
| 1469 |
defer c.close() |
| 1470 |
test := "PUB foo.bar 5\r\nhello\r\nSUB foo 1\r\nPING\r\nPUB foo.bar 5\r\nhello\r\nPING\r\n" |
| 1471 |
c.parseAsync(test) |
| 1472 |
l, err := cr.ReadString('\n') |
| 1473 |
if err != nil { |
| 1474 |
t.Fatalf("Error receiving info from server: %v\n", err) |
| 1475 |
} |
| 1476 |
if !strings.HasPrefix(l, "PONG\r\n") { |
| 1477 |
t.Fatalf("PONG response incorrect: %q\n", l) |
| 1478 |
} |
| 1479 |
// Expect just a pong, no match should exist here.. |
| 1480 |
l, _ = cr.ReadString('\n') |
| 1481 |
if !strings.HasPrefix(l, "PONG\r\n") { |
| 1482 |
t.Fatalf("PONG response was expected, got: %q\n", l) |
| 1483 |
} |
| 1484 |
} |
| 1485 |
|
| 1486 |
func TestUnsubRace(t *testing.T) { |
| 1487 |
opts := DefaultOptions() |
| 1488 |
s := RunServer(opts) |
| 1489 |
defer s.Shutdown() |
| 1490 |
|
| 1491 |
url := fmt.Sprintf("nats://%s:%d", |
| 1492 |
s.getOpts().Host, |
| 1493 |
s.Addr().(*net.TCPAddr).Port, |
| 1494 |
) |
| 1495 |
nc, err := nats.Connect(url) |
| 1496 |
if err != nil { |
| 1497 |
t.Fatalf("Error creating client to %s: %v\n", url, err) |
| 1498 |
} |
| 1499 |
defer nc.Close() |
| 1500 |
|
| 1501 |
ncp, err := nats.Connect(url) |
| 1502 |
if err != nil { |
| 1503 |
t.Fatalf("Error creating client: %v\n", err) |
| 1504 |
} |
| 1505 |
defer ncp.Close() |
| 1506 |
|
| 1507 |
sub, _ := nc.Subscribe("foo", func(m *nats.Msg) { |
| 1508 |
// Just eat it.. |
| 1509 |
}) |
| 1510 |
nc.Flush() |
| 1511 |
|
| 1512 |
var wg sync.WaitGroup |
| 1513 |
|
| 1514 |
wg.Add(1) |
| 1515 |
|
| 1516 |
go func() { |
| 1517 |
for i := 0; i < 10000; i++ { |
| 1518 |
ncp.Publish("foo", []byte("hello")) |
| 1519 |
} |
| 1520 |
wg.Done() |
| 1521 |
}() |
| 1522 |
|
| 1523 |
time.Sleep(5 * time.Millisecond) |
| 1524 |
|
| 1525 |
sub.Unsubscribe() |
| 1526 |
|
| 1527 |
wg.Wait() |
| 1528 |
} |
| 1529 |
|
| 1530 |
func TestClientCloseTLSConnection(t *testing.T) { |
| 1531 |
opts, err := ProcessConfigFile("./configs/tls.conf") |
| 1532 |
if err != nil { |
| 1533 |
t.Fatalf("Error processing config file: %v", err) |
| 1534 |
} |
| 1535 |
opts.TLSTimeout = 100 |
| 1536 |
opts.NoLog = true |
| 1537 |
opts.NoSigs = true |
| 1538 |
s := RunServer(opts) |
| 1539 |
defer s.Shutdown() |
| 1540 |
|
| 1541 |
endpoint := net.JoinHostPort(opts.Host, fmt.Sprintf("%d", opts.Port)) |
| 1542 |
conn, err := net.DialTimeout("tcp", endpoint, 2*time.Second) |
| 1543 |
if err != nil { |
| 1544 |
t.Fatalf("Unexpected error on dial: %v", err) |
| 1545 |
} |
| 1546 |
defer conn.Close() |
| 1547 |
br := bufio.NewReaderSize(conn, 100) |
| 1548 |
if _, err := br.ReadString('\n'); err != nil { |
| 1549 |
t.Fatalf("Unexpected error reading INFO: %v", err) |
| 1550 |
} |
| 1551 |
|
| 1552 |
tlsConn := tls.Client(conn, &tls.Config{InsecureSkipVerify: true}) |
| 1553 |
defer tlsConn.Close() |
| 1554 |
if err := tlsConn.Handshake(); err != nil { |
| 1555 |
t.Fatalf("Unexpected error during handshake: %v", err) |
| 1556 |
} |
| 1557 |
br = bufio.NewReaderSize(tlsConn, 100) |
| 1558 |
connectOp := []byte("CONNECT {\"user\":\"derek\",\"pass\":\"foo\",\"verbose\":false,\"pedantic\":false,\"tls_required\":true}\r\n") |
| 1559 |
if _, err := tlsConn.Write(connectOp); err != nil { |
| 1560 |
t.Fatalf("Unexpected error writing CONNECT: %v", err) |
| 1561 |
} |
| 1562 |
if _, err := tlsConn.Write([]byte("PING\r\n")); err != nil { |
| 1563 |
t.Fatalf("Unexpected error writing PING: %v", err) |
| 1564 |
} |
| 1565 |
if _, err := br.ReadString('\n'); err != nil { |
| 1566 |
t.Fatalf("Unexpected error reading PONG: %v", err) |
| 1567 |
} |
| 1568 |
|
| 1569 |
// Check that client is registered. |
| 1570 |
checkClientsCount(t, s, 1) |
| 1571 |
var cli *client |
| 1572 |
s.mu.Lock() |
| 1573 |
for _, c := range s.clients { |
| 1574 |
cli = c |
| 1575 |
break |
| 1576 |
} |
| 1577 |
s.mu.Unlock() |
| 1578 |
if cli == nil { |
| 1579 |
t.Fatal("Did not register client on time") |
| 1580 |
} |
| 1581 |
// Test GetTLSConnectionState |
| 1582 |
state := cli.GetTLSConnectionState() |
| 1583 |
if state == nil { |
| 1584 |
t.Error("GetTLSConnectionState() returned nil") |
| 1585 |
} |
| 1586 |
|
| 1587 |
// Test RemoteAddress |
| 1588 |
addr := cli.RemoteAddress() |
| 1589 |
if addr == nil { |
| 1590 |
t.Error("RemoteAddress() returned nil") |
| 1591 |
} |
| 1592 |
|
| 1593 |
if addr.(*net.TCPAddr).IP.String() != "127.0.0.1" { |
| 1594 |
t.Error("RemoteAddress() returned incorrect ip " + addr.String()) |
| 1595 |
} |
| 1596 |
|
| 1597 |
// Fill the buffer. We want to timeout on write so that nc.Close() |
| 1598 |
// would block due to a write that cannot complete. |
| 1599 |
buf := make([]byte, 64*1024) |
| 1600 |
done := false |
| 1601 |
for !done { |
| 1602 |
cli.nc.SetWriteDeadline(time.Now().Add(time.Second)) |
| 1603 |
if _, err := cli.nc.Write(buf); err != nil { |
| 1604 |
done = true |
| 1605 |
} |
| 1606 |
cli.nc.SetWriteDeadline(time.Time{}) |
| 1607 |
} |
| 1608 |
ch := make(chan bool) |
| 1609 |
go func() { |
| 1610 |
select { |
| 1611 |
case <-ch: |
| 1612 |
return |
| 1613 |
case <-time.After(3 * time.Second): |
| 1614 |
fmt.Println("!!!! closeConnection is blocked, test will hang !!!") |
| 1615 |
return |
| 1616 |
} |
| 1617 |
}() |
| 1618 |
// Close the client |
| 1619 |
cli.closeConnection(ClientClosed) |
| 1620 |
ch <- true |
| 1621 |
} |
| 1622 |
|
| 1623 |
// This tests issue #558 |
| 1624 |
func TestWildcardCharsInLiteralSubjectWorks(t *testing.T) { |
| 1625 |
opts := DefaultOptions() |
| 1626 |
s := RunServer(opts) |
| 1627 |
defer s.Shutdown() |
| 1628 |
|
| 1629 |
nc, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) |
| 1630 |
if err != nil { |
| 1631 |
t.Fatalf("Error on connect: %v", err) |
| 1632 |
} |
| 1633 |
defer nc.Close() |
| 1634 |
|
| 1635 |
ch := make(chan bool, 1) |
| 1636 |
// This subject is a literal even though it contains `*` and `>`, |
| 1637 |
// they are not treated as wildcards. |
| 1638 |
subj := "foo.bar,*,>,baz" |
| 1639 |
cb := func(_ *nats.Msg) { |
| 1640 |
ch <- true |
| 1641 |
} |
| 1642 |
for i := 0; i < 2; i++ { |
| 1643 |
sub, err := nc.Subscribe(subj, cb) |
| 1644 |
if err != nil { |
| 1645 |
t.Fatalf("Error on subscribe: %v", err) |
| 1646 |
} |
| 1647 |
if err := nc.Flush(); err != nil { |
| 1648 |
t.Fatalf("Error on flush: %v", err) |
| 1649 |
} |
| 1650 |
if err := nc.LastError(); err != nil { |
| 1651 |
t.Fatalf("Server reported error: %v", err) |
| 1652 |
} |
| 1653 |
if err := nc.Publish(subj, []byte("msg")); err != nil { |
| 1654 |
t.Fatalf("Error on publish: %v", err) |
| 1655 |
} |
| 1656 |
select { |
| 1657 |
case <-ch: |
| 1658 |
case <-time.After(time.Second): |
| 1659 |
t.Fatalf("Should have received the message") |
| 1660 |
} |
| 1661 |
if err := sub.Unsubscribe(); err != nil { |
| 1662 |
t.Fatalf("Error on unsubscribe: %v", err) |
| 1663 |
} |
| 1664 |
} |
| 1665 |
} |
| 1666 |
|
| 1667 |
// This test ensures that coalescing into the fixed-size output |
| 1668 |
// queues works as expected. When bytes are queued up, they should |
| 1669 |
// not overflow a buffer until the capacity is exceeded, at which |
| 1670 |
// point a new buffer should be added. |
| 1671 |
func TestClientOutboundQueueCoalesce(t *testing.T) { |
| 1672 |
opts := DefaultOptions() |
| 1673 |
s := RunServer(opts) |
| 1674 |
defer s.Shutdown() |
| 1675 |
|
| 1676 |
nc, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) |
| 1677 |
if err != nil { |
| 1678 |
t.Fatalf("Error on connect: %v", err) |
| 1679 |
} |
| 1680 |
defer nc.Close() |
| 1681 |
|
| 1682 |
clients := s.GlobalAccount().getClients() |
| 1683 |
if len(clients) != 1 { |
| 1684 |
t.Fatal("Expecting a client to exist") |
| 1685 |
} |
| 1686 |
client := clients[0] |
| 1687 |
client.mu.Lock() |
| 1688 |
defer client.mu.Unlock() |
| 1689 |
|
| 1690 |
// First up, queue something small into the queue. |
| 1691 |
client.queueOutbound([]byte{1, 2, 3, 4, 5}) |
| 1692 |
|
| 1693 |
if len(client.out.nb) != 1 { |
| 1694 |
t.Fatal("Expecting a single queued buffer") |
| 1695 |
} |
| 1696 |
if l := len(client.out.nb[0]); l != 5 { |
| 1697 |
t.Fatalf("Expecting only 5 bytes in the first queued buffer, found %d instead", l) |
| 1698 |
} |
| 1699 |
|
| 1700 |
// Then queue up a few more bytes, but not enough |
| 1701 |
// to overflow into the next buffer. |
| 1702 |
client.queueOutbound([]byte{6, 7, 8, 9, 10}) |
| 1703 |
|
| 1704 |
if len(client.out.nb) != 1 { |
| 1705 |
t.Fatal("Expecting a single queued buffer") |
| 1706 |
} |
| 1707 |
if l := len(client.out.nb[0]); l != 10 { |
| 1708 |
t.Fatalf("Expecting 10 bytes in the first queued buffer, found %d instead", l) |
| 1709 |
} |
| 1710 |
|
| 1711 |
// Finally, queue up something that is guaranteed |
| 1712 |
// to overflow. |
| 1713 |
b := nbPoolSmall.Get().(*[nbPoolSizeSmall]byte)[:] |
| 1714 |
b = b[:cap(b)] |
| 1715 |
client.queueOutbound(b) |
| 1716 |
if len(client.out.nb) != 2 { |
| 1717 |
t.Fatal("Expecting buffer to have overflowed") |
| 1718 |
} |
| 1719 |
if l := len(client.out.nb[0]); l != cap(b) { |
| 1720 |
t.Fatalf("Expecting %d bytes in the first queued buffer, found %d instead", cap(b), l) |
| 1721 |
} |
| 1722 |
if l := len(client.out.nb[1]); l != 10 { |
| 1723 |
t.Fatalf("Expecting 10 bytes in the second queued buffer, found %d instead", l) |
| 1724 |
} |
| 1725 |
} |
| 1726 |
|
| 1727 |
func TestClientTraceRace(t *testing.T) { |
| 1728 |
opts := DefaultOptions() |
| 1729 |
s := RunServer(opts) |
| 1730 |
defer s.Shutdown() |
| 1731 |
|
| 1732 |
// Activate trace logging |
| 1733 |
s.SetLogger(&DummyLogger{}, false, true) |
| 1734 |
|
| 1735 |
nc1, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) |
| 1736 |
if err != nil { |
| 1737 |
t.Fatalf("Error on connect: %v", err) |
| 1738 |
} |
| 1739 |
defer nc1.Close() |
| 1740 |
total := 10000 |
| 1741 |
count := 0 |
| 1742 |
ch := make(chan bool, 1) |
| 1743 |
if _, err := nc1.Subscribe("foo", func(_ *nats.Msg) { |
| 1744 |
count++ |
| 1745 |
if count == total { |
| 1746 |
ch <- true |
| 1747 |
} |
| 1748 |
}); err != nil { |
| 1749 |
t.Fatalf("Error on subscribe: %v", err) |
| 1750 |
} |
| 1751 |
nc2, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) |
| 1752 |
if err != nil { |
| 1753 |
t.Fatalf("Error on connect: %v", err) |
| 1754 |
} |
| 1755 |
defer nc2.Close() |
| 1756 |
|
| 1757 |
wg := sync.WaitGroup{} |
| 1758 |
wg.Add(1) |
| 1759 |
go func() { |
| 1760 |
defer wg.Done() |
| 1761 |
for i := 0; i < total; i++ { |
| 1762 |
nc1.Publish("bar", []byte("hello")) |
| 1763 |
} |
| 1764 |
}() |
| 1765 |
for i := 0; i < total; i++ { |
| 1766 |
nc2.Publish("foo", []byte("hello")) |
| 1767 |
} |
| 1768 |
if err := wait(ch); err != nil { |
| 1769 |
t.Fatal("Did not get all our messages") |
| 1770 |
} |
| 1771 |
wg.Wait() |
| 1772 |
} |
| 1773 |
|
| 1774 |
func TestClientUserInfo(t *testing.T) { |
| 1775 |
pnkey := "UD6AYQSOIN2IN5OGC6VQZCR4H3UFMIOXSW6NNS6N53CLJA4PB56CEJJI" |
| 1776 |
c := &client{ |
| 1777 |
cid: 1024, |
| 1778 |
opts: ClientOpts{ |
| 1779 |
Nkey: pnkey, |
| 1780 |
}, |
| 1781 |
} |
| 1782 |
got := c.getAuthUser() |
| 1783 |
expected := `Nkey "UD6AYQSOIN2IN5OGC6VQZCR4H3UFMIOXSW6NNS6N53CLJA4PB56CEJJI"` |
| 1784 |
if got != expected { |
| 1785 |
t.Errorf("Expected %q, got %q", expected, got) |
| 1786 |
} |
| 1787 |
|
| 1788 |
c = &client{ |
| 1789 |
cid: 1024, |
| 1790 |
opts: ClientOpts{ |
| 1791 |
Username: "foo", |
| 1792 |
}, |
| 1793 |
} |
| 1794 |
got = c.getAuthUser() |
| 1795 |
expected = `User "foo"` |
| 1796 |
if got != expected { |
| 1797 |
t.Errorf("Expected %q, got %q", expected, got) |
| 1798 |
} |
| 1799 |
|
| 1800 |
c = &client{ |
| 1801 |
cid: 1024, |
| 1802 |
opts: ClientOpts{}, |
| 1803 |
} |
| 1804 |
got = c.getAuthUser() |
| 1805 |
expected = `User "N/A"` |
| 1806 |
if got != expected { |
| 1807 |
t.Errorf("Expected %q, got %q", expected, got) |
| 1808 |
} |
| 1809 |
|
| 1810 |
c = &client{ |
| 1811 |
cid: 1024, |
| 1812 |
opts: ClientOpts{ |
| 1813 |
Token: "s3cr3t!", |
| 1814 |
}, |
| 1815 |
} |
| 1816 |
got = c.getAuthUser() |
| 1817 |
expected = `Token "[REDACTED]"` |
| 1818 |
if got != expected { |
| 1819 |
t.Errorf("Expected %q, got %q", expected, got) |
| 1820 |
} |
| 1821 |
} |
| 1822 |
|
| 1823 |
type captureWarnLogger struct { |
| 1824 |
DummyLogger |
| 1825 |
warn chan string |
| 1826 |
} |
| 1827 |
|
| 1828 |
func (l *captureWarnLogger) Warnf(format string, v ...any) { |
| 1829 |
select { |
| 1830 |
case l.warn <- fmt.Sprintf(format, v...): |
| 1831 |
default: |
| 1832 |
} |
| 1833 |
} |
| 1834 |
|
| 1835 |
func TestReadloopWarning(t *testing.T) { |
| 1836 |
readLoopReportThreshold = 100 * time.Millisecond |
| 1837 |
defer func() { readLoopReportThreshold = readLoopReport }() |
| 1838 |
|
| 1839 |
opts := DefaultOptions() |
| 1840 |
s := RunServer(opts) |
| 1841 |
defer s.Shutdown() |
| 1842 |
|
| 1843 |
l := &captureWarnLogger{warn: make(chan string, 1)} |
| 1844 |
s.SetLogger(l, false, false) |
| 1845 |
|
| 1846 |
url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port) |
| 1847 |
nc := natsConnect(t, url) |
| 1848 |
defer nc.Close() |
| 1849 |
natsSubSync(t, nc, "foo") |
| 1850 |
natsFlush(t, nc) |
| 1851 |
cid, _ := nc.GetClientID() |
| 1852 |
|
| 1853 |
sender := natsConnect(t, url) |
| 1854 |
defer sender.Close() |
| 1855 |
|
| 1856 |
wg := sync.WaitGroup{} |
| 1857 |
wg.Add(1) |
| 1858 |
c := s.getClient(cid) |
| 1859 |
c.mu.Lock() |
| 1860 |
go func() { |
| 1861 |
defer wg.Done() |
| 1862 |
time.Sleep(250 * time.Millisecond) |
| 1863 |
c.mu.Unlock() |
| 1864 |
}() |
| 1865 |
|
| 1866 |
natsPub(t, sender, "foo", make([]byte, 100)) |
| 1867 |
natsFlush(t, sender) |
| 1868 |
|
| 1869 |
select { |
| 1870 |
case warn := <-l.warn: |
| 1871 |
if !strings.Contains(warn, "Readloop") { |
| 1872 |
t.Fatalf("unexpected warning: %v", warn) |
| 1873 |
} |
| 1874 |
case <-time.After(2 * time.Second): |
| 1875 |
t.Fatalf("No warning printed") |
| 1876 |
} |
| 1877 |
wg.Wait() |
| 1878 |
} |
| 1879 |
|
| 1880 |
func TestTraceMsg(t *testing.T) { |
| 1881 |
c := &client{} |
| 1882 |
|
| 1883 |
// Enable message trace |
| 1884 |
c.trace = true |
| 1885 |
|
| 1886 |
cases := []struct { |
| 1887 |
Desc string |
| 1888 |
Msg []byte |
| 1889 |
Wanted string |
| 1890 |
MaxTracedMsgLen int |
| 1891 |
}{ |
| 1892 |
{ |
| 1893 |
Desc: "normal length", |
| 1894 |
Msg: []byte(fmt.Sprintf("normal%s", CR_LF)), |
| 1895 |
Wanted: "<<- MSG_PAYLOAD: [\"normal\"]", |
| 1896 |
MaxTracedMsgLen: 10, |
| 1897 |
}, |
| 1898 |
{ |
| 1899 |
Desc: "over length", |
| 1900 |
Msg: []byte(fmt.Sprintf("over length%s", CR_LF)), |
| 1901 |
Wanted: "<<- MSG_PAYLOAD: [\"over lengt...\"]", |
| 1902 |
MaxTracedMsgLen: 10, |
| 1903 |
}, |
| 1904 |
{ |
| 1905 |
Desc: "unlimited length", |
| 1906 |
Msg: []byte(fmt.Sprintf("unlimited length%s", CR_LF)), |
| 1907 |
Wanted: "<<- MSG_PAYLOAD: [\"unlimited length\"]", |
| 1908 |
MaxTracedMsgLen: 0, |
| 1909 |
}, |
| 1910 |
{ |
| 1911 |
Desc: "negative max traced msg len", |
| 1912 |
Msg: []byte(fmt.Sprintf("negative max traced msg len%s", CR_LF)), |
| 1913 |
Wanted: "<<- MSG_PAYLOAD: [\"negative max traced msg len\"]", |
| 1914 |
MaxTracedMsgLen: -1, |
| 1915 |
}, |
| 1916 |
} |
| 1917 |
|
| 1918 |
for _, ut := range cases { |
| 1919 |
c.srv = &Server{ |
| 1920 |
opts: &Options{MaxTracedMsgLen: ut.MaxTracedMsgLen}, |
| 1921 |
} |
| 1922 |
c.srv.SetLogger(&DummyLogger{}, true, true) |
| 1923 |
|
| 1924 |
c.traceMsg(ut.Msg) |
| 1925 |
|
| 1926 |
got := c.srv.logging.logger.(*DummyLogger).Msg |
| 1927 |
if !reflect.DeepEqual(ut.Wanted, got) { |
| 1928 |
t.Errorf("Desc: %s. Msg %q. Traced msg want: %s, got: %s", ut.Desc, ut.Msg, ut.Wanted, got) |
| 1929 |
} |
| 1930 |
} |
| 1931 |
} |
| 1932 |
|
| 1933 |
func TestTraceMsgHeadersOnly(t *testing.T) { |
| 1934 |
c := &client{} |
| 1935 |
// Enable message trace |
| 1936 |
c.trace = true |
| 1937 |
|
| 1938 |
hdr := fmt.Sprintf(`NATS/1.0%sFoo: 1%s%s`, CR_LF, CR_LF, CR_LF) |
| 1939 |
hdr2 := fmt.Sprintf(`NATS/1.0%sFoo: 1%sBar: 2%s%s`, CR_LF, CR_LF, CR_LF, CR_LF) |
| 1940 |
|
| 1941 |
cases := []struct { |
| 1942 |
Desc string |
| 1943 |
Msg []byte |
| 1944 |
Hdr int |
| 1945 |
Wanted string |
| 1946 |
MaxTracedMsgLen int |
| 1947 |
}{ |
| 1948 |
{ |
| 1949 |
Desc: "payload only", |
| 1950 |
Msg: []byte(`test\r\n`), |
| 1951 |
Hdr: 0, |
| 1952 |
Wanted: _EMPTY_, |
| 1953 |
MaxTracedMsgLen: 0, |
| 1954 |
}, |
| 1955 |
{ |
| 1956 |
Desc: "header only", |
| 1957 |
Msg: []byte(hdr), |
| 1958 |
Hdr: len(hdr), |
| 1959 |
Wanted: `<<- MSG_PAYLOAD: ["NATS/1.0\r\nFoo: 1"]`, |
| 1960 |
MaxTracedMsgLen: 0, |
| 1961 |
}, |
| 1962 |
{ |
| 1963 |
Desc: "with header and payload", |
| 1964 |
Msg: []byte(fmt.Sprintf("%stest%s", hdr, CR_LF)), |
| 1965 |
Hdr: len(hdr), |
| 1966 |
Wanted: `<<- MSG_PAYLOAD: ["NATS/1.0\r\nFoo: 1"]`, |
| 1967 |
MaxTracedMsgLen: 0, |
| 1968 |
}, |
| 1969 |
{ |
| 1970 |
Desc: "max length", |
| 1971 |
Msg: []byte(hdr), |
| 1972 |
Hdr: len(hdr), |
| 1973 |
Wanted: `<<- MSG_PAYLOAD: ["NATS/1..."]`, |
| 1974 |
MaxTracedMsgLen: 6, |
| 1975 |
}, |
| 1976 |
{ |
| 1977 |
Desc: "two headers max length", |
| 1978 |
Msg: []byte(hdr2), |
| 1979 |
Hdr: len(hdr2), |
| 1980 |
Wanted: `<<- MSG_PAYLOAD: ["NATS/1.0\r\nFoo: 1\r\nBar..."]`, |
| 1981 |
MaxTracedMsgLen: 21, |
| 1982 |
}, |
| 1983 |
} |
| 1984 |
|
| 1985 |
for _, ut := range cases { |
| 1986 |
t.Run(ut.Desc, func(t *testing.T) { |
| 1987 |
c.srv = &Server{ |
| 1988 |
opts: &Options{MaxTracedMsgLen: ut.MaxTracedMsgLen, TraceHeaders: true}, |
| 1989 |
} |
| 1990 |
c.srv.SetLogger(&DummyLogger{}, true, true) |
| 1991 |
c.pa.hdr = ut.Hdr |
| 1992 |
|
| 1993 |
c.traceMsg(ut.Msg) |
| 1994 |
|
| 1995 |
got := c.srv.logging.logger.(*DummyLogger).Msg |
| 1996 |
require_Equal(t, string(ut.Wanted), got) |
| 1997 |
}) |
| 1998 |
} |
| 1999 |
} |
| 2000 |
|
| 2001 |
func TestTraceMsgDelivery(t *testing.T) { |
| 2002 |
logger := &DummyLogger{} |
| 2003 |
|
| 2004 |
opts := DefaultOptions() |
| 2005 |
opts.Trace = true |
| 2006 |
s := RunServer(opts) |
| 2007 |
s.SetLogger(logger, true, true) |
| 2008 |
defer s.Shutdown() |
| 2009 |
|
| 2010 |
nc, err := nats.Connect(s.ClientURL()) |
| 2011 |
require_NoError(t, err) |
| 2012 |
defer nc.Close() |
| 2013 |
|
| 2014 |
ncp, err := nats.Connect(s.ClientURL()) |
| 2015 |
require_NoError(t, err) |
| 2016 |
defer ncp.Close() |
| 2017 |
|
| 2018 |
_, err = nc.Subscribe("foo", func(msg *nats.Msg) { |
| 2019 |
m := nats.NewMsg(msg.Reply) |
| 2020 |
m.Header["A"] = []string{"1"} |
| 2021 |
m.Header["B"] = []string{"2"} |
| 2022 |
m.Data = []byte("Hi Traced") |
| 2023 |
msg.RespondMsg(m) |
| 2024 |
}) |
| 2025 |
require_NoError(t, err) |
| 2026 |
nc.Flush() |
| 2027 |
|
| 2028 |
msg := nats.NewMsg("foo") |
| 2029 |
msg.Header = nats.Header{} |
| 2030 |
msg.Header["A"] = []string{"A:1"} |
| 2031 |
msg.Header["B"] = []string{"B:2"} |
| 2032 |
msg.Data = []byte("Hello Traced") |
| 2033 |
_, err = ncp.RequestMsg(msg, 100*time.Millisecond) |
| 2034 |
require_NoError(t, err) |
| 2035 |
|
| 2036 |
// Wait for logging to settle and safely read the message. |
| 2037 |
time.Sleep(50 * time.Millisecond) |
| 2038 |
logger.Lock() |
| 2039 |
m := logger.Msg |
| 2040 |
logger.Unlock() |
| 2041 |
require_Contains(t, m, "->> MSG_PAYLOAD:") |
| 2042 |
require_Contains(t, m, "NATS/1.0") |
| 2043 |
require_Contains(t, m, "Hi Traced") |
| 2044 |
|
| 2045 |
_, err = nc.Subscribe("bar", func(msg *nats.Msg) { |
| 2046 |
m := nats.NewMsg(msg.Reply) |
| 2047 |
m.Data = []byte("Plain Response") |
| 2048 |
msg.RespondMsg(m) |
| 2049 |
}) |
| 2050 |
require_NoError(t, err) |
| 2051 |
nc.Flush() |
| 2052 |
|
| 2053 |
msg = nats.NewMsg("bar") |
| 2054 |
_, err = ncp.RequestMsg(msg, 100*time.Millisecond) |
| 2055 |
require_NoError(t, err) |
| 2056 |
|
| 2057 |
// Wait and safely read again. |
| 2058 |
time.Sleep(50 * time.Millisecond) |
| 2059 |
logger.Lock() |
| 2060 |
m = logger.Msg |
| 2061 |
logger.Unlock() |
| 2062 |
require_Contains(t, m, "->> MSG_PAYLOAD:") |
| 2063 |
require_Contains(t, m, "Plain Response") |
| 2064 |
} |
| 2065 |
|
| 2066 |
func TestTraceMsgDeliveryWithHeaders(t *testing.T) { |
| 2067 |
c := &client{} |
| 2068 |
c.trace = true |
| 2069 |
hdr := fmt.Sprintf(`NATS/1.0%sFoo: 1%s%s`, CR_LF, CR_LF, CR_LF) |
| 2070 |
hdr2 := fmt.Sprintf(`NATS/1.0%sFoo: bar%sBar: baz%s%s`, CR_LF, CR_LF, CR_LF, CR_LF) |
| 2071 |
|
| 2072 |
cases := []struct { |
| 2073 |
name string |
| 2074 |
msg []byte |
| 2075 |
hdr int |
| 2076 |
traceDeliver bool |
| 2077 |
traceHeaders bool |
| 2078 |
expected string |
| 2079 |
}{ |
| 2080 |
{ |
| 2081 |
name: "delivery with headers enabled", |
| 2082 |
msg: []byte(hdr), |
| 2083 |
hdr: len(hdr), |
| 2084 |
traceHeaders: true, |
| 2085 |
expected: `->> MSG_PAYLOAD: ["NATS/1.0\r\nFoo: 1"]`, |
| 2086 |
}, |
| 2087 |
{ |
| 2088 |
name: "delivery with full message", |
| 2089 |
msg: []byte(fmt.Sprintf("%stest%s", hdr, CR_LF)), |
| 2090 |
hdr: len(hdr), |
| 2091 |
traceHeaders: false, |
| 2092 |
expected: `->> MSG_PAYLOAD: ["NATS/1.0\r\nFoo: 1\r\n\r\ntest"]`, |
| 2093 |
}, |
| 2094 |
{ |
| 2095 |
name: "delivery with headers only", |
| 2096 |
msg: []byte(fmt.Sprintf("%stest%s", hdr, CR_LF)), |
| 2097 |
hdr: len(hdr), |
| 2098 |
traceHeaders: true, |
| 2099 |
expected: `->> MSG_PAYLOAD: ["NATS/1.0\r\nFoo: 1"]`, |
| 2100 |
}, |
| 2101 |
{ |
| 2102 |
name: "delivery multiple headers", |
| 2103 |
msg: []byte(hdr2), |
| 2104 |
hdr: len(hdr2), |
| 2105 |
traceHeaders: true, |
| 2106 |
expected: `->> MSG_PAYLOAD: ["NATS/1.0\r\nFoo: bar\r\nBar: baz"]`, |
| 2107 |
}, |
| 2108 |
{ |
| 2109 |
name: "delivery with payload but headers only tracing", |
| 2110 |
msg: []byte(fmt.Sprintf("%spayload data%s", hdr2, CR_LF)), |
| 2111 |
hdr: len(hdr2), |
| 2112 |
traceHeaders: true, |
| 2113 |
expected: `->> MSG_PAYLOAD: ["NATS/1.0\r\nFoo: bar\r\nBar: baz"]`, |
| 2114 |
}, |
| 2115 |
{ |
| 2116 |
name: "delivery no headers but tracing enabled", |
| 2117 |
msg: []byte(fmt.Sprintf("plain message%s", CR_LF)), |
| 2118 |
hdr: 0, |
| 2119 |
traceHeaders: false, |
| 2120 |
expected: `->> MSG_PAYLOAD: ["plain message"]`, |
| 2121 |
}, |
| 2122 |
{ |
| 2123 |
name: "delivery headers disabled but deliver enabled", |
| 2124 |
msg: []byte(fmt.Sprintf("%spayload%s", hdr, CR_LF)), |
| 2125 |
hdr: len(hdr), |
| 2126 |
traceHeaders: false, |
| 2127 |
expected: `->> MSG_PAYLOAD: ["NATS/1.0\r\nFoo: 1\r\n\r\npayload"]`, |
| 2128 |
}, |
| 2129 |
} |
| 2130 |
|
| 2131 |
for _, tc := range cases { |
| 2132 |
t.Run(tc.name, func(t *testing.T) { |
| 2133 |
logger := &DummyLogger{} |
| 2134 |
|
| 2135 |
c.srv = &Server{ |
| 2136 |
opts: &Options{ |
| 2137 |
Trace: true, |
| 2138 |
TraceHeaders: tc.traceHeaders, |
| 2139 |
}, |
| 2140 |
} |
| 2141 |
c.srv.SetLogger(logger, true, true) |
| 2142 |
c.pa.hdr = tc.hdr |
| 2143 |
c.traceMsgDelivery(tc.msg, tc.hdr) |
| 2144 |
got := logger.Msg |
| 2145 |
if tc.expected == "" { |
| 2146 |
// Disabled |
| 2147 |
require_Equal(t, tc.expected, got) |
| 2148 |
} else { |
| 2149 |
require_True(t, strings.Contains(got, "->> MSG_PAYLOAD:")) |
| 2150 |
require_Equal(t, tc.expected, got) |
| 2151 |
} |
| 2152 |
}) |
| 2153 |
} |
| 2154 |
} |
| 2155 |
|
| 2156 |
func TestClientMaxPending(t *testing.T) { |
| 2157 |
opts := DefaultOptions() |
| 2158 |
opts.MaxPending = math.MaxInt32 + 1 |
| 2159 |
s := RunServer(opts) |
| 2160 |
defer s.Shutdown() |
| 2161 |
|
| 2162 |
nc := natsConnect(t, fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) |
| 2163 |
defer nc.Close() |
| 2164 |
|
| 2165 |
sub := natsSubSync(t, nc, "foo") |
| 2166 |
natsPub(t, nc, "foo", []byte("msg")) |
| 2167 |
natsNexMsg(t, sub, 100*time.Millisecond) |
| 2168 |
} |
| 2169 |
|
| 2170 |
func TestResponsePermissions(t *testing.T) { |
| 2171 |
for i, test := range []struct { |
| 2172 |
name string |
| 2173 |
perms *ResponsePermission |
| 2174 |
}{ |
| 2175 |
{"max_msgs", &ResponsePermission{MaxMsgs: 2, Expires: time.Hour}}, |
| 2176 |
{"no_expire_limit", &ResponsePermission{MaxMsgs: 3, Expires: -1 * time.Millisecond}}, |
| 2177 |
{"expire", &ResponsePermission{MaxMsgs: 1000, Expires: 100 * time.Millisecond}}, |
| 2178 |
{"no_msgs_limit", &ResponsePermission{MaxMsgs: -1, Expires: 100 * time.Millisecond}}, |
| 2179 |
} { |
| 2180 |
t.Run(test.name, func(t *testing.T) { |
| 2181 |
opts := DefaultOptions() |
| 2182 |
u1 := &User{ |
| 2183 |
Username: "service", |
| 2184 |
Password: "pwd", |
| 2185 |
Permissions: &Permissions{Response: test.perms}, |
| 2186 |
} |
| 2187 |
u2 := &User{Username: "ivan", Password: "pwd"} |
| 2188 |
opts.Users = []*User{u1, u2} |
| 2189 |
s := RunServer(opts) |
| 2190 |
defer s.Shutdown() |
| 2191 |
|
| 2192 |
svcNC := natsConnect(t, fmt.Sprintf("nats://service:pwd@%s:%d", opts.Host, opts.Port)) |
| 2193 |
defer svcNC.Close() |
| 2194 |
reqSub := natsSubSync(t, svcNC, "request") |
| 2195 |
natsFlush(t, svcNC) |
| 2196 |
|
| 2197 |
nc := natsConnect(t, fmt.Sprintf("nats://ivan:pwd@%s:%d", opts.Host, opts.Port)) |
| 2198 |
defer nc.Close() |
| 2199 |
|
| 2200 |
replySub := natsSubSync(t, nc, "reply") |
| 2201 |
|
| 2202 |
natsPubReq(t, nc, "request", "reply", []byte("req1")) |
| 2203 |
|
| 2204 |
req1 := natsNexMsg(t, reqSub, 100*time.Millisecond) |
| 2205 |
|
| 2206 |
checkFailed := func(t *testing.T) { |
| 2207 |
t.Helper() |
| 2208 |
if reply, err := replySub.NextMsg(100 * time.Millisecond); err != nats.ErrTimeout { |
| 2209 |
if reply != nil { |
| 2210 |
t.Fatalf("Expected to receive timeout, got reply=%q", reply.Data) |
| 2211 |
} else { |
| 2212 |
t.Fatalf("Unexpected error: %v", err) |
| 2213 |
} |
| 2214 |
} |
| 2215 |
} |
| 2216 |
|
| 2217 |
switch i { |
| 2218 |
case 0: |
| 2219 |
// Should allow only 2 replies... |
| 2220 |
for i := 0; i < 10; i++ { |
| 2221 |
natsPub(t, svcNC, req1.Reply, []byte("reply")) |
| 2222 |
} |
| 2223 |
natsNexMsg(t, replySub, 100*time.Millisecond) |
| 2224 |
natsNexMsg(t, replySub, 100*time.Millisecond) |
| 2225 |
// The next should fail... |
| 2226 |
checkFailed(t) |
| 2227 |
case 1: |
| 2228 |
// Expiration is set to -1ms, which should count as infinite... |
| 2229 |
natsPub(t, svcNC, req1.Reply, []byte("reply")) |
| 2230 |
// Sleep a bit before next send |
| 2231 |
time.Sleep(50 * time.Millisecond) |
| 2232 |
natsPub(t, svcNC, req1.Reply, []byte("reply")) |
| 2233 |
// Make sure we receive both |
| 2234 |
natsNexMsg(t, replySub, 100*time.Millisecond) |
| 2235 |
natsNexMsg(t, replySub, 100*time.Millisecond) |
| 2236 |
case 2: |
| 2237 |
fallthrough |
| 2238 |
case 3: |
| 2239 |
// Expire set to 100ms so make sure we wait more between |
| 2240 |
// next publish |
| 2241 |
natsPub(t, svcNC, req1.Reply, []byte("reply")) |
| 2242 |
time.Sleep(200 * time.Millisecond) |
| 2243 |
natsPub(t, svcNC, req1.Reply, []byte("reply")) |
| 2244 |
// Should receive one, and fail on the other |
| 2245 |
natsNexMsg(t, replySub, 100*time.Millisecond) |
| 2246 |
checkFailed(t) |
| 2247 |
} |
| 2248 |
// When testing expiration, sleep before sending next reply |
| 2249 |
if i >= 2 { |
| 2250 |
time.Sleep(400 * time.Millisecond) |
| 2251 |
} |
| 2252 |
}) |
| 2253 |
} |
| 2254 |
} |
| 2255 |
|
| 2256 |
func TestPingNotSentTooSoon(t *testing.T) { |
| 2257 |
opts := DefaultOptions() |
| 2258 |
s := RunServer(opts) |
| 2259 |
defer s.Shutdown() |
| 2260 |
|
| 2261 |
doneCh := make(chan bool, 1) |
| 2262 |
wg := sync.WaitGroup{} |
| 2263 |
wg.Add(1) |
| 2264 |
go func() { |
| 2265 |
defer wg.Done() |
| 2266 |
for { |
| 2267 |
s.Connz(nil) |
| 2268 |
select { |
| 2269 |
case <-doneCh: |
| 2270 |
return |
| 2271 |
case <-time.After(time.Millisecond): |
| 2272 |
} |
| 2273 |
} |
| 2274 |
}() |
| 2275 |
|
| 2276 |
for i := 0; i < 100; i++ { |
| 2277 |
nc, err := nats.Connect(s.ClientURL()) |
| 2278 |
if err != nil { |
| 2279 |
t.Fatalf("Error on connect: %v", err) |
| 2280 |
} |
| 2281 |
nc.Close() |
| 2282 |
} |
| 2283 |
close(doneCh) |
| 2284 |
wg.Wait() |
| 2285 |
|
| 2286 |
c, br, _ := newClientForServer(s) |
| 2287 |
defer c.close() |
| 2288 |
connectOp := []byte("CONNECT {\"user\":\"ivan\",\"pass\":\"bar\"}\r\n") |
| 2289 |
c.parse(connectOp) |
| 2290 |
|
| 2291 |
// Since client has not send PING, having server try to send RTT ping |
| 2292 |
// to client should not do anything |
| 2293 |
if c.sendRTTPing() { |
| 2294 |
t.Fatalf("RTT ping should not have been sent") |
| 2295 |
} |
| 2296 |
// Used to move c.start here but it is often causing race conditions, |
| 2297 |
// so we'll just wait instead. |
| 2298 |
time.Sleep(maxNoRTTPingBeforeFirstPong) |
| 2299 |
|
| 2300 |
errCh := make(chan error, 1) |
| 2301 |
go func() { |
| 2302 |
l, _ := br.ReadString('\n') |
| 2303 |
if l != "PING\r\n" { |
| 2304 |
errCh <- fmt.Errorf("expected to get PING, got %s", l) |
| 2305 |
return |
| 2306 |
} |
| 2307 |
errCh <- nil |
| 2308 |
}() |
| 2309 |
if !c.sendRTTPing() { |
| 2310 |
t.Fatalf("RTT ping should have been sent") |
| 2311 |
} |
| 2312 |
wg.Wait() |
| 2313 |
if e := <-errCh; e != nil { |
| 2314 |
t.Fatal(e.Error()) |
| 2315 |
} |
| 2316 |
} |
| 2317 |
|
| 2318 |
func TestClientCheckUseOfGWReplyPrefix(t *testing.T) { |
| 2319 |
opts := DefaultOptions() |
| 2320 |
s := RunServer(opts) |
| 2321 |
defer s.Shutdown() |
| 2322 |
|
| 2323 |
ech := make(chan error, 1) |
| 2324 |
nc, err := nats.Connect(s.ClientURL(), |
| 2325 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, e error) { |
| 2326 |
ech <- e |
| 2327 |
})) |
| 2328 |
if err != nil { |
| 2329 |
t.Fatalf("Error on connect: %v", err) |
| 2330 |
} |
| 2331 |
defer nc.Close() |
| 2332 |
|
| 2333 |
// Expect to fail if publish on gateway reply prefix |
| 2334 |
nc.Publish(gwReplyPrefix+"anything", []byte("should fail")) |
| 2335 |
|
| 2336 |
// Wait for publish violation error |
| 2337 |
select { |
| 2338 |
case e := <-ech: |
| 2339 |
if e == nil || !strings.Contains(strings.ToLower(e.Error()), "violation for publish") { |
| 2340 |
t.Fatalf("Expected violation error, got %v", e) |
| 2341 |
} |
| 2342 |
case <-time.After(time.Second): |
| 2343 |
t.Fatalf("Did not receive permissions violation error") |
| 2344 |
} |
| 2345 |
|
| 2346 |
// Now publish a message with a reply set to the prefix, |
| 2347 |
// it should be rejected too. |
| 2348 |
nc.PublishRequest("foo", gwReplyPrefix+"anything", []byte("should fail")) |
| 2349 |
|
| 2350 |
// Wait for publish violation error with reply |
| 2351 |
select { |
| 2352 |
case e := <-ech: |
| 2353 |
if e == nil || !strings.Contains(strings.ToLower(e.Error()), "violation for publish with reply") { |
| 2354 |
t.Fatalf("Expected violation error, got %v", e) |
| 2355 |
} |
| 2356 |
case <-time.After(time.Second): |
| 2357 |
t.Fatalf("Did not receive permissions violation error") |
| 2358 |
} |
| 2359 |
} |
| 2360 |
|
| 2361 |
func TestNoClientLeakOnSlowConsumer(t *testing.T) { |
| 2362 |
opts := DefaultOptions() |
| 2363 |
s := RunServer(opts) |
| 2364 |
defer s.Shutdown() |
| 2365 |
|
| 2366 |
c, err := net.Dial("tcp", net.JoinHostPort(opts.Host, fmt.Sprintf("%d", opts.Port))) |
| 2367 |
if err != nil { |
| 2368 |
t.Fatalf("Error connecting: %v", err) |
| 2369 |
} |
| 2370 |
defer c.Close() |
| 2371 |
|
| 2372 |
cr := bufio.NewReader(c) |
| 2373 |
|
| 2374 |
// Wait for INFO... |
| 2375 |
line, _, _ := cr.ReadLine() |
| 2376 |
var info serverInfo |
| 2377 |
if err = json.Unmarshal(line[5:], &info); err != nil { |
| 2378 |
t.Fatalf("Could not parse INFO json: %v\n", err) |
| 2379 |
} |
| 2380 |
|
| 2381 |
// Send our connect |
| 2382 |
if _, err := c.Write([]byte("CONNECT {\"verbose\": false}\r\nSUB foo 1\r\nPING\r\n")); err != nil { |
| 2383 |
t.Fatalf("Error sending CONNECT and SUB: %v", err) |
| 2384 |
} |
| 2385 |
// Wait for PONG |
| 2386 |
line, _, _ = cr.ReadLine() |
| 2387 |
if string(line) != "PONG" { |
| 2388 |
t.Fatalf("Expected 'PONG' but got %q", line) |
| 2389 |
} |
| 2390 |
|
| 2391 |
// Get the client from server map |
| 2392 |
cli := s.GetClient(info.CID) |
| 2393 |
if cli == nil { |
| 2394 |
t.Fatalf("No client registered") |
| 2395 |
} |
| 2396 |
// Change the write deadline to very low value |
| 2397 |
cli.mu.Lock() |
| 2398 |
cli.out.wdl = time.Nanosecond |
| 2399 |
cli.mu.Unlock() |
| 2400 |
|
| 2401 |
nc := natsConnect(t, s.ClientURL()) |
| 2402 |
defer nc.Close() |
| 2403 |
|
| 2404 |
// Send some messages to cause write deadline error on "cli" |
| 2405 |
payload := make([]byte, 1000) |
| 2406 |
for i := 0; i < 100; i++ { |
| 2407 |
natsPub(t, nc, "foo", payload) |
| 2408 |
} |
| 2409 |
natsFlush(t, nc) |
| 2410 |
nc.Close() |
| 2411 |
|
| 2412 |
// Now make sure that the number of clients goes to 0. |
| 2413 |
checkClientsCount(t, s, 0) |
| 2414 |
} |
| 2415 |
|
| 2416 |
func TestClientSlowConsumerWithoutConnect(t *testing.T) { |
| 2417 |
opts := DefaultOptions() |
| 2418 |
opts.WriteDeadline = 100 * time.Millisecond |
| 2419 |
s := RunServer(opts) |
| 2420 |
defer s.Shutdown() |
| 2421 |
|
| 2422 |
url := fmt.Sprintf("127.0.0.1:%d", opts.Port) |
| 2423 |
c, err := net.Dial("tcp", url) |
| 2424 |
if err != nil { |
| 2425 |
t.Fatalf("Error on dial: %v", err) |
| 2426 |
} |
| 2427 |
defer c.Close() |
| 2428 |
c.Write([]byte("SUB foo 1\r\n")) |
| 2429 |
|
| 2430 |
payload := make([]byte, 10000) |
| 2431 |
nc, err := nats.Connect(url) |
| 2432 |
if err != nil { |
| 2433 |
t.Fatalf("Error on connect: %v", err) |
| 2434 |
} |
| 2435 |
defer nc.Close() |
| 2436 |
for i := 0; i < 10000; i++ { |
| 2437 |
nc.Publish("foo", payload) |
| 2438 |
} |
| 2439 |
nc.Flush() |
| 2440 |
checkFor(t, time.Second, 15*time.Millisecond, func() error { |
| 2441 |
// Expect slow consumer.. |
| 2442 |
if n := atomic.LoadInt64(&s.slowConsumers); n != 1 { |
| 2443 |
return fmt.Errorf("Expected 1 slow consumer, got: %v", n) |
| 2444 |
} |
| 2445 |
if n := s.scStats.clients.Load(); n != 1 { |
| 2446 |
return fmt.Errorf("Expected 1 slow consumer, got: %v", n) |
| 2447 |
} |
| 2448 |
return nil |
| 2449 |
}) |
| 2450 |
varz, err := s.Varz(nil) |
| 2451 |
if err != nil { |
| 2452 |
t.Fatal(err) |
| 2453 |
} |
| 2454 |
if varz.SlowConsumersStats.Clients != 1 { |
| 2455 |
t.Error("Expected a slow consumer client in varz") |
| 2456 |
} |
| 2457 |
} |
| 2458 |
|
| 2459 |
func TestClientNoSlowConsumerIfConnectExpected(t *testing.T) { |
| 2460 |
opts := DefaultOptions() |
| 2461 |
opts.Username = "ivan" |
| 2462 |
opts.Password = "pass" |
| 2463 |
// Make it very slow so that the INFO sent to client fails... |
| 2464 |
opts.WriteDeadline = time.Nanosecond |
| 2465 |
s := RunServer(opts) |
| 2466 |
defer s.Shutdown() |
| 2467 |
|
| 2468 |
// Expect server to close the connection, but will bump the slow |
| 2469 |
// consumer count. |
| 2470 |
nc, err := nats.Connect(fmt.Sprintf("nats://ivan:pass@%s:%d", opts.Host, opts.Port)) |
| 2471 |
if err == nil { |
| 2472 |
nc.Close() |
| 2473 |
t.Fatal("Expected connect error") |
| 2474 |
} |
| 2475 |
if n := atomic.LoadInt64(&s.slowConsumers); n != 0 { |
| 2476 |
t.Fatalf("Expected 0 slow consumer, got: %v", n) |
| 2477 |
} |
| 2478 |
} |
| 2479 |
|
| 2480 |
func TestClientIPv6Address(t *testing.T) { |
| 2481 |
opts := DefaultOptions() |
| 2482 |
opts.Host = "0.0.0.0" |
| 2483 |
s := RunServer(opts) |
| 2484 |
defer s.Shutdown() |
| 2485 |
|
| 2486 |
nc, err := nats.Connect(fmt.Sprintf("nats://[::1]:%v", opts.Port)) |
| 2487 |
// Travis may not accept IPv6, in that case, skip the test. |
| 2488 |
if err != nil { |
| 2489 |
t.Skipf("Skipping test because could not connect: %v", err) |
| 2490 |
} |
| 2491 |
defer nc.Close() |
| 2492 |
|
| 2493 |
cid, _ := nc.GetClientID() |
| 2494 |
c := s.GetClient(cid) |
| 2495 |
c.mu.Lock() |
| 2496 |
ncs := c.String() |
| 2497 |
c.mu.Unlock() |
| 2498 |
if !strings.HasPrefix(ncs, "[::1]") { |
| 2499 |
t.Fatalf("Wrong string representation of an IPv6 address: %q", ncs) |
| 2500 |
} |
| 2501 |
} |
| 2502 |
|
| 2503 |
func TestPBNotIncreasedOnMaxPending(t *testing.T) { |
| 2504 |
opts := DefaultOptions() |
| 2505 |
opts.MaxPending = 100 |
| 2506 |
s := &Server{opts: opts} |
| 2507 |
c := &client{srv: s} |
| 2508 |
c.initClient() |
| 2509 |
|
| 2510 |
c.mu.Lock() |
| 2511 |
c.queueOutbound(make([]byte, 200)) |
| 2512 |
pb := c.out.pb |
| 2513 |
c.mu.Unlock() |
| 2514 |
|
| 2515 |
if pb != 0 { |
| 2516 |
t.Fatalf("c.out.pb should be 0, got %v", pb) |
| 2517 |
} |
| 2518 |
} |
| 2519 |
|
| 2520 |
type testConnWritePartial struct { |
| 2521 |
net.Conn |
| 2522 |
partial bool |
| 2523 |
buf bytes.Buffer |
| 2524 |
} |
| 2525 |
|
| 2526 |
func (c *testConnWritePartial) Write(p []byte) (int, error) { |
| 2527 |
n := len(p) |
| 2528 |
if c.partial { |
| 2529 |
n = n/2 + 1 |
| 2530 |
} |
| 2531 |
return c.buf.Write(p[:n]) |
| 2532 |
} |
| 2533 |
|
| 2534 |
func (c *testConnWritePartial) RemoteAddr() net.Addr { |
| 2535 |
return nil |
| 2536 |
} |
| 2537 |
|
| 2538 |
func (c *testConnWritePartial) SetWriteDeadline(_ time.Time) error { |
| 2539 |
return nil |
| 2540 |
} |
| 2541 |
|
| 2542 |
func TestFlushOutboundNoSliceReuseIfPartial(t *testing.T) { |
| 2543 |
opts := DefaultOptions() |
| 2544 |
opts.MaxPending = 1024 |
| 2545 |
s := &Server{opts: opts} |
| 2546 |
|
| 2547 |
fakeConn := &testConnWritePartial{partial: true} |
| 2548 |
c := &client{srv: s, nc: fakeConn} |
| 2549 |
c.initClient() |
| 2550 |
|
| 2551 |
bufs := [][]byte{ |
| 2552 |
[]byte("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), |
| 2553 |
[]byte("------"), |
| 2554 |
[]byte("0123456789"), |
| 2555 |
} |
| 2556 |
expected := bytes.Buffer{} |
| 2557 |
for _, buf := range bufs { |
| 2558 |
expected.Write(buf) |
| 2559 |
c.mu.Lock() |
| 2560 |
c.queueOutbound(buf) |
| 2561 |
c.flushOutbound() |
| 2562 |
fakeConn.partial = false |
| 2563 |
c.mu.Unlock() |
| 2564 |
} |
| 2565 |
// Ensure everything is flushed. |
| 2566 |
for done := false; !done; { |
| 2567 |
c.mu.Lock() |
| 2568 |
if c.out.pb > 0 { |
| 2569 |
c.flushOutbound() |
| 2570 |
} else { |
| 2571 |
done = true |
| 2572 |
} |
| 2573 |
c.mu.Unlock() |
| 2574 |
} |
| 2575 |
if !bytes.Equal(expected.Bytes(), fakeConn.buf.Bytes()) { |
| 2576 |
t.Fatalf("Expected\n%q\ngot\n%q", expected.String(), fakeConn.buf.String()) |
| 2577 |
} |
| 2578 |
} |
| 2579 |
|
| 2580 |
func TestFlushOutboundFreesExcessiveWorkingBuffer(t *testing.T) { |
| 2581 |
opts := DefaultOptions() |
| 2582 |
opts.MaxPending = MAX_PENDING_SIZE |
| 2583 |
s := &Server{opts: opts} |
| 2584 |
|
| 2585 |
fakeConn := &testConnWritePartial{} |
| 2586 |
c := &client{srv: s, nc: fakeConn} |
| 2587 |
c.initClient() |
| 2588 |
|
| 2589 |
// Helper that queues n separate chunks, each filling a small pool |
| 2590 |
// buffer exactly, so that "nb" ends up with n entries, and then |
| 2591 |
// flushes until everything has been written out. |
| 2592 |
queueAndFlush := func(n int) { |
| 2593 |
t.Helper() |
| 2594 |
payload := make([]byte, nbPoolSizeSmall) |
| 2595 |
c.mu.Lock() |
| 2596 |
defer c.mu.Unlock() |
| 2597 |
for i := 0; i < n; i++ { |
| 2598 |
c.queueOutbound(payload) |
| 2599 |
} |
| 2600 |
if len(c.out.nb) != n { |
| 2601 |
t.Fatalf("Expected %d queued buffers, got %d", n, len(c.out.nb)) |
| 2602 |
} |
| 2603 |
for c.out.pb > 0 { |
| 2604 |
c.flushOutbound() |
| 2605 |
} |
| 2606 |
} |
| 2607 |
|
| 2608 |
// A modest flush should retain the working buffer for reuse. |
| 2609 |
queueAndFlush(10) |
| 2610 |
c.mu.Lock() |
| 2611 |
retained := c.out.wnb != nil |
| 2612 |
c.mu.Unlock() |
| 2613 |
if !retained { |
| 2614 |
t.Fatalf("Expected the working buffer to be retained for reuse") |
| 2615 |
} |
| 2616 |
|
| 2617 |
// Growing the working buffer beyond a full writev batch of entries |
| 2618 |
// should cause it to be freed once everything has been written. |
| 2619 |
queueAndFlush(nbMaxVectorSize + 100) |
| 2620 |
c.mu.Lock() |
| 2621 |
freed := c.out.wnb == nil |
| 2622 |
c.mu.Unlock() |
| 2623 |
if !freed { |
| 2624 |
t.Fatalf("Expected the excessively grown working buffer to be freed") |
| 2625 |
} |
| 2626 |
} |
| 2627 |
|
| 2628 |
type captureNoticeLogger struct { |
| 2629 |
DummyLogger |
| 2630 |
notices []string |
| 2631 |
} |
| 2632 |
|
| 2633 |
func (l *captureNoticeLogger) Noticef(format string, v ...any) { |
| 2634 |
l.Lock() |
| 2635 |
l.notices = append(l.notices, fmt.Sprintf(format, v...)) |
| 2636 |
l.Unlock() |
| 2637 |
} |
| 2638 |
|
| 2639 |
func TestCloseConnectionLogsReason(t *testing.T) { |
| 2640 |
o1 := DefaultOptions() |
| 2641 |
s1 := RunServer(o1) |
| 2642 |
defer s1.Shutdown() |
| 2643 |
|
| 2644 |
l := &captureNoticeLogger{} |
| 2645 |
s1.SetLogger(l, true, true) |
| 2646 |
|
| 2647 |
o2 := DefaultOptions() |
| 2648 |
o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port)) |
| 2649 |
s2 := RunServer(o2) |
| 2650 |
defer s2.Shutdown() |
| 2651 |
|
| 2652 |
checkClusterFormed(t, s1, s2) |
| 2653 |
s2.Shutdown() |
| 2654 |
|
| 2655 |
checkFor(t, time.Second, 15*time.Millisecond, func() error { |
| 2656 |
if s1.NumRoutes() != 0 { |
| 2657 |
return fmt.Errorf("route still connected") |
| 2658 |
} |
| 2659 |
return nil |
| 2660 |
}) |
| 2661 |
// Now check that s1 has logged that the connection is closed and that the reason is included. |
| 2662 |
ok := false |
| 2663 |
l.Lock() |
| 2664 |
for _, n := range l.notices { |
| 2665 |
if strings.Contains(n, "connection closed: "+ClientClosed.String()) { |
| 2666 |
ok = true |
| 2667 |
break |
| 2668 |
} |
| 2669 |
} |
| 2670 |
l.Unlock() |
| 2671 |
if !ok { |
| 2672 |
t.Fatal("Log does not contain closed reason") |
| 2673 |
} |
| 2674 |
} |
| 2675 |
|
| 2676 |
func TestCloseConnectionVeryEarly(t *testing.T) { |
| 2677 |
for _, test := range []struct { |
| 2678 |
name string |
| 2679 |
useTLS bool |
| 2680 |
}{ |
| 2681 |
{"no_tls", false}, |
| 2682 |
{"tls", true}, |
| 2683 |
} { |
| 2684 |
t.Run(test.name, func(t *testing.T) { |
| 2685 |
o := DefaultOptions() |
| 2686 |
if test.useTLS { |
| 2687 |
tc := &TLSConfigOpts{ |
| 2688 |
CertFile: "../test/configs/certs/server-cert.pem", |
| 2689 |
KeyFile: "../test/configs/certs/server-key.pem", |
| 2690 |
CaFile: "../test/configs/certs/ca.pem", |
| 2691 |
} |
| 2692 |
tlsConfig, err := GenTLSConfig(tc) |
| 2693 |
if err != nil { |
| 2694 |
t.Fatalf("Error generating tls config: %v", err) |
| 2695 |
} |
| 2696 |
o.TLSConfig = tlsConfig |
| 2697 |
} |
| 2698 |
s := RunServer(o) |
| 2699 |
defer s.Shutdown() |
| 2700 |
|
| 2701 |
// The issue was with a connection that would break right when |
| 2702 |
// server was sending the INFO. Creating a bare TCP connection |
| 2703 |
// and closing it right away won't help reproduce the problem. |
| 2704 |
// So testing in 2 steps. |
| 2705 |
|
| 2706 |
// Get a normal TCP connection to the server. |
| 2707 |
c, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", o.Port)) |
| 2708 |
if err != nil { |
| 2709 |
t.Fatalf("Unable to create tcp connection") |
| 2710 |
} |
| 2711 |
// Now close it. |
| 2712 |
c.Close() |
| 2713 |
|
| 2714 |
// Wait that num clients falls to 0. |
| 2715 |
checkClientsCount(t, s, 0) |
| 2716 |
|
| 2717 |
// Call again with this closed connection. Alternatively, we |
| 2718 |
// would have to call with a fake connection that implements |
| 2719 |
// net.Conn but returns an error on Write. |
| 2720 |
s.createClient(c) |
| 2721 |
|
| 2722 |
// This connection should not have been added to the server. |
| 2723 |
checkClientsCount(t, s, 0) |
| 2724 |
}) |
| 2725 |
} |
| 2726 |
} |
| 2727 |
|
| 2728 |
type connAddrString struct { |
| 2729 |
net.Addr |
| 2730 |
} |
| 2731 |
|
| 2732 |
func (a *connAddrString) String() string { |
| 2733 |
return "[fe80::abc:def:ghi:123%utun0]:4222" |
| 2734 |
} |
| 2735 |
|
| 2736 |
type connString struct { |
| 2737 |
net.Conn |
| 2738 |
} |
| 2739 |
|
| 2740 |
func (c *connString) RemoteAddr() net.Addr { |
| 2741 |
return &connAddrString{} |
| 2742 |
} |
| 2743 |
|
| 2744 |
func TestClientConnectionName(t *testing.T) { |
| 2745 |
s, err := NewServer(DefaultOptions()) |
| 2746 |
if err != nil { |
| 2747 |
t.Fatalf("Error creating server: %v", err) |
| 2748 |
} |
| 2749 |
l := &DummyLogger{} |
| 2750 |
s.SetLogger(l, true, true) |
| 2751 |
|
| 2752 |
for _, test := range []struct { |
| 2753 |
name string |
| 2754 |
kind int |
| 2755 |
kindStr string |
| 2756 |
ws bool |
| 2757 |
mqtt bool |
| 2758 |
}{ |
| 2759 |
{"client", CLIENT, "cid:", false, false}, |
| 2760 |
{"ws client", CLIENT, "wid:", true, false}, |
| 2761 |
{"mqtt client", CLIENT, "mid:", false, true}, |
| 2762 |
{"route", ROUTER, "rid:", false, false}, |
| 2763 |
{"gateway", GATEWAY, "gid:", false, false}, |
| 2764 |
{"leafnode", LEAF, "lid:", false, false}, |
| 2765 |
} { |
| 2766 |
t.Run(test.name, func(t *testing.T) { |
| 2767 |
c := &client{srv: s, nc: &connString{}, kind: test.kind} |
| 2768 |
if test.ws { |
| 2769 |
c.ws = &websocket{} |
| 2770 |
} |
| 2771 |
if test.mqtt { |
| 2772 |
c.mqtt = &mqtt{} |
| 2773 |
} |
| 2774 |
c.initClient() |
| 2775 |
|
| 2776 |
if host := "fe80::abc:def:ghi:123%utun0"; host != c.host { |
| 2777 |
t.Fatalf("expected host to be %q, got %q", host, c.host) |
| 2778 |
} |
| 2779 |
if port := uint16(4222); port != c.port { |
| 2780 |
t.Fatalf("expected port to be %v, got %v", port, c.port) |
| 2781 |
} |
| 2782 |
|
| 2783 |
checkLog := func(suffix string) { |
| 2784 |
t.Helper() |
| 2785 |
l.Lock() |
| 2786 |
msg := l.Msg |
| 2787 |
l.Unlock() |
| 2788 |
if strings.Contains(msg, "(MISSING)") { |
| 2789 |
t.Fatalf("conn name was not escaped properly, got MISSING: %s", msg) |
| 2790 |
} |
| 2791 |
if !strings.Contains(l.Msg, test.kindStr) { |
| 2792 |
t.Fatalf("expected kind to be %q, got: %s", test.kindStr, msg) |
| 2793 |
} |
| 2794 |
if !strings.HasSuffix(l.Msg, suffix) { |
| 2795 |
t.Fatalf("expected statement to end with %q, got %s", suffix, msg) |
| 2796 |
} |
| 2797 |
} |
| 2798 |
|
| 2799 |
c.Debugf("debug: %v", 1) |
| 2800 |
checkLog(" 1") |
| 2801 |
c.Tracef("trace: %s", "2") |
| 2802 |
checkLog(" 2") |
| 2803 |
c.Warnf("warn: %s %d", "3", 4) |
| 2804 |
checkLog(" 3 4") |
| 2805 |
c.Errorf("error: %v %s", 5, "6") |
| 2806 |
checkLog(" 5 6") |
| 2807 |
}) |
| 2808 |
} |
| 2809 |
} |
| 2810 |
|
| 2811 |
func TestClientLimits(t *testing.T) { |
| 2812 |
accKp, err := nkeys.CreateAccount() |
| 2813 |
if err != nil { |
| 2814 |
t.Fatalf("Error creating account key: %v", err) |
| 2815 |
} |
| 2816 |
uKp, err := nkeys.CreateUser() |
| 2817 |
if err != nil { |
| 2818 |
t.Fatalf("Error creating user key: %v", err) |
| 2819 |
} |
| 2820 |
uPub, err := uKp.PublicKey() |
| 2821 |
if err != nil { |
| 2822 |
t.Fatalf("Error obtaining publicKey: %v", err) |
| 2823 |
} |
| 2824 |
s, err := NewServer(DefaultOptions()) |
| 2825 |
if err != nil { |
| 2826 |
t.Fatalf("Error creating server: %v", err) |
| 2827 |
} |
| 2828 |
for _, test := range []struct { |
| 2829 |
client int32 |
| 2830 |
acc int32 |
| 2831 |
srv int32 |
| 2832 |
expect int32 |
| 2833 |
}{ |
| 2834 |
// all identical |
| 2835 |
{1, 1, 1, 1}, |
| 2836 |
{-1, -1, 0, -1}, |
| 2837 |
// only one value unlimited |
| 2838 |
{1, -1, 0, 1}, |
| 2839 |
{-1, 1, 0, 1}, |
| 2840 |
{-1, -1, 1, 1}, |
| 2841 |
// all combinations of distinct values |
| 2842 |
{1, 2, 3, 1}, |
| 2843 |
{1, 3, 2, 1}, |
| 2844 |
{2, 1, 3, 1}, |
| 2845 |
{2, 3, 1, 1}, |
| 2846 |
{3, 1, 2, 1}, |
| 2847 |
{3, 2, 1, 1}, |
| 2848 |
} { |
| 2849 |
t.Run("", func(t *testing.T) { |
| 2850 |
s.opts.MaxPayload = test.srv |
| 2851 |
s.opts.MaxSubs = int(test.srv) |
| 2852 |
c := &client{srv: s, acc: &Account{ |
| 2853 |
limits: limits{mpay: test.acc, msubs: test.acc}, |
| 2854 |
}} |
| 2855 |
uc := jwt.NewUserClaims(uPub) |
| 2856 |
uc.Limits.Subs = int64(test.client) |
| 2857 |
uc.Limits.Payload = int64(test.client) |
| 2858 |
c.opts.JWT, err = uc.Encode(accKp) |
| 2859 |
if err != nil { |
| 2860 |
t.Fatalf("Error encoding jwt: %v", err) |
| 2861 |
} |
| 2862 |
c.applyAccountLimits() |
| 2863 |
if c.mpay != test.expect { |
| 2864 |
t.Fatalf("payload %d not as expected %d", c.mpay, test.expect) |
| 2865 |
} |
| 2866 |
if c.msubs != test.expect { |
| 2867 |
t.Fatalf("subscriber %d not as expected %d", c.msubs, test.expect) |
| 2868 |
} |
| 2869 |
}) |
| 2870 |
} |
| 2871 |
} |
| 2872 |
|
| 2873 |
// Must be run with -race. |
| 2874 |
func TestClientApplyAccountLimitsSigningKeysRace(t *testing.T) { |
| 2875 |
akp, _ := nkeys.CreateAccount() |
| 2876 |
apub, _ := akp.PublicKey() |
| 2877 |
skp, _ := nkeys.CreateAccount() |
| 2878 |
spub, _ := skp.PublicKey() |
| 2879 |
|
| 2880 |
// Build a user JWT issued by the signing key on behalf of the account. |
| 2881 |
nkp, _ := nkeys.CreateUser() |
| 2882 |
upub, _ := nkp.PublicKey() |
| 2883 |
nuc := jwt.NewUserClaims(upub) |
| 2884 |
nuc.IssuerAccount = apub // != Issuer (spub) so the signingKeys lookup runs |
| 2885 |
nuc.Limits.Payload = jwt.NoLimit |
| 2886 |
nuc.Limits.Subs = jwt.NoLimit |
| 2887 |
ujwt, err := nuc.Encode(skp) |
| 2888 |
require_NoError(t, err) |
| 2889 |
|
| 2890 |
// The scope stored in the account's signing keys map. |
| 2891 |
scope := jwt.NewUserScope() |
| 2892 |
scope.Key = spub |
| 2893 |
scope.Template.Limits.Payload = jwt.NoLimit |
| 2894 |
scope.Template.Limits.Subs = jwt.NoLimit |
| 2895 |
|
| 2896 |
acc := &Account{Name: apub, Issuer: apub} |
| 2897 |
acc.mpay = jwt.NoLimit |
| 2898 |
acc.msubs = jwt.NoLimit |
| 2899 |
acc.signingKeys = map[string]jwt.Scope{spub: scope} |
| 2900 |
|
| 2901 |
srv := &Server{opts: &Options{}} |
| 2902 |
c := &client{srv: srv, acc: acc, kind: CLIENT} |
| 2903 |
c.opts.JWT = ujwt |
| 2904 |
|
| 2905 |
const iters = 1000 |
| 2906 |
var wg sync.WaitGroup |
| 2907 |
wg.Add(2) |
| 2908 |
|
| 2909 |
// Reader: repeatedly applies account limits, reading acc.signingKeys. |
| 2910 |
go func() { |
| 2911 |
defer wg.Done() |
| 2912 |
for range iters { |
| 2913 |
c.applyAccountLimits() |
| 2914 |
} |
| 2915 |
}() |
| 2916 |
|
| 2917 |
// Writer: mimics updateAccountClaimsWithRefresh rebuilding signingKeys. |
| 2918 |
go func() { |
| 2919 |
defer wg.Done() |
| 2920 |
for range iters { |
| 2921 |
acc.mu.Lock() |
| 2922 |
acc.signingKeys = make(map[string]jwt.Scope) |
| 2923 |
acc.signingKeys[spub] = scope |
| 2924 |
acc.signingKeys[acc.Name] = nil |
| 2925 |
acc.mu.Unlock() |
| 2926 |
} |
| 2927 |
}() |
| 2928 |
|
| 2929 |
wg.Wait() |
| 2930 |
} |
| 2931 |
|
| 2932 |
// Must be run with -race. |
| 2933 |
func TestClientApplyAccountLimitsMpayAtomicRace(t *testing.T) { |
| 2934 |
akp, _ := nkeys.CreateAccount() |
| 2935 |
apub, _ := akp.PublicKey() |
| 2936 |
skp, _ := nkeys.CreateAccount() |
| 2937 |
spub, _ := skp.PublicKey() |
| 2938 |
|
| 2939 |
// Build a user JWT issued by the signing key on behalf of the account. |
| 2940 |
nkp, _ := nkeys.CreateUser() |
| 2941 |
upub, _ := nkp.PublicKey() |
| 2942 |
nuc := jwt.NewUserClaims(upub) |
| 2943 |
nuc.IssuerAccount = apub // != Issuer (spub) so the scoped signingKeys branch runs |
| 2944 |
nuc.Limits.Payload = 2048 |
| 2945 |
nuc.Limits.Subs = 20 |
| 2946 |
ujwt, err := nuc.Encode(skp) |
| 2947 |
require_NoError(t, err) |
| 2948 |
|
| 2949 |
// The scope stored in the account's signing keys map, carrying a Payload |
| 2950 |
// template so applyAccountLimits writes c.mpay on every call. |
| 2951 |
scope := jwt.NewUserScope() |
| 2952 |
scope.Key = spub |
| 2953 |
scope.Template.Limits.Payload = 1024 |
| 2954 |
scope.Template.Limits.Subs = 10 |
| 2955 |
|
| 2956 |
acc := &Account{Name: apub, Issuer: apub} |
| 2957 |
acc.mpay = jwt.NoLimit |
| 2958 |
acc.msubs = jwt.NoLimit |
| 2959 |
acc.signingKeys = map[string]jwt.Scope{spub: scope} |
| 2960 |
|
| 2961 |
srv := &Server{opts: &Options{}} |
| 2962 |
c := &client{srv: srv, acc: acc, kind: CLIENT} |
| 2963 |
c.opts.JWT = ujwt |
| 2964 |
|
| 2965 |
// Sanity: ensure we actually hit the scoped-signing-key branch. |
| 2966 |
c.applyAccountLimits() |
| 2967 |
if got := atomic.LoadInt32(&c.mpay); got != 1024 { |
| 2968 |
t.Fatalf("expected scoped template payload 1024, got %d", got) |
| 2969 |
} |
| 2970 |
|
| 2971 |
const iters = 1000 |
| 2972 |
var wg sync.WaitGroup |
| 2973 |
wg.Add(2) |
| 2974 |
|
| 2975 |
// Writer: repeatedly applies account limits, writing c.mpay. |
| 2976 |
go func() { |
| 2977 |
defer wg.Done() |
| 2978 |
for range iters { |
| 2979 |
c.applyAccountLimits() |
| 2980 |
} |
| 2981 |
}() |
| 2982 |
|
| 2983 |
// Reader: mimics processPub's atomic read of c.mpay. |
| 2984 |
go func() { |
| 2985 |
defer wg.Done() |
| 2986 |
for range iters { |
| 2987 |
_ = atomic.LoadInt32(&c.mpay) |
| 2988 |
} |
| 2989 |
}() |
| 2990 |
|
| 2991 |
wg.Wait() |
| 2992 |
} |
| 2993 |
|
| 2994 |
// Must be run with -race. |
| 2995 |
func TestClientGenerateClientInfoJSONMpayAtomicRace(t *testing.T) { |
| 2996 |
c := &client{} |
| 2997 |
c.mpay = 1024 |
| 2998 |
|
| 2999 |
const iters = 1000 |
| 3000 |
var wg sync.WaitGroup |
| 3001 |
wg.Add(2) |
| 3002 |
|
| 3003 |
// Reader: generates the client INFO, reading c.mpay. |
| 3004 |
go func() { |
| 3005 |
defer wg.Done() |
| 3006 |
for range iters { |
| 3007 |
_ = c.generateClientInfoJSON(Info{}, false) |
| 3008 |
} |
| 3009 |
}() |
| 3010 |
|
| 3011 |
// Writer: mimics maxPayloadOption.Apply on config reload, which stores |
| 3012 |
// c.mpay atomically while holding only the server lock. |
| 3013 |
go func() { |
| 3014 |
defer wg.Done() |
| 3015 |
for range iters { |
| 3016 |
atomic.StoreInt32(&c.mpay, 2048) |
| 3017 |
} |
| 3018 |
}() |
| 3019 |
|
| 3020 |
wg.Wait() |
| 3021 |
} |
| 3022 |
|
| 3023 |
func TestClientClampMaxSubsErrReport(t *testing.T) { |
| 3024 |
maxSubLimitReportThreshold = int64(100 * time.Millisecond) |
| 3025 |
defer func() { maxSubLimitReportThreshold = defaultMaxSubLimitReportThreshold }() |
| 3026 |
|
| 3027 |
o1 := DefaultOptions() |
| 3028 |
o1.MaxSubs = 1 |
| 3029 |
o1.LeafNode.Host = "127.0.0.1" |
| 3030 |
o1.LeafNode.Port = -1 |
| 3031 |
s1 := RunServer(o1) |
| 3032 |
defer s1.Shutdown() |
| 3033 |
|
| 3034 |
l := &captureErrorLogger{errCh: make(chan string, 10)} |
| 3035 |
s1.SetLogger(l, false, false) |
| 3036 |
|
| 3037 |
o2 := DefaultOptions() |
| 3038 |
o2.Cluster.Name = "xyz" |
| 3039 |
u, _ := url.Parse(fmt.Sprintf("nats://127.0.0.1:%d", o1.LeafNode.Port)) |
| 3040 |
o2.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: []*url.URL{u}}} |
| 3041 |
s2 := RunServer(o2) |
| 3042 |
defer s2.Shutdown() |
| 3043 |
|
| 3044 |
checkLeafNodeConnected(t, s1) |
| 3045 |
checkLeafNodeConnected(t, s2) |
| 3046 |
|
| 3047 |
nc := natsConnect(t, s2.ClientURL()) |
| 3048 |
defer nc.Close() |
| 3049 |
natsSubSync(t, nc, "foo") |
| 3050 |
natsSubSync(t, nc, "bar") |
| 3051 |
|
| 3052 |
// Make sure we receive only 1 |
| 3053 |
check := func() { |
| 3054 |
t.Helper() |
| 3055 |
for i := 0; i < 2; i++ { |
| 3056 |
select { |
| 3057 |
case errStr := <-l.errCh: |
| 3058 |
if i > 0 { |
| 3059 |
t.Fatalf("Should not have logged a second time: %s", errStr) |
| 3060 |
} |
| 3061 |
if !strings.Contains(errStr, "maximum subscriptions") { |
| 3062 |
t.Fatalf("Unexpected error: %s", errStr) |
| 3063 |
} |
| 3064 |
case <-time.After(300 * time.Millisecond): |
| 3065 |
if i == 0 { |
| 3066 |
t.Fatal("Error should have been logged") |
| 3067 |
} |
| 3068 |
} |
| 3069 |
} |
| 3070 |
} |
| 3071 |
check() |
| 3072 |
|
| 3073 |
// The above will have waited long enough to clear the report threshold. |
| 3074 |
// So create two new subs and check again that we get only 1 report. |
| 3075 |
natsSubSync(t, nc, "baz") |
| 3076 |
natsSubSync(t, nc, "bat") |
| 3077 |
check() |
| 3078 |
} |
| 3079 |
|
| 3080 |
func TestClientDenySysGroupSub(t *testing.T) { |
| 3081 |
s := RunServer(DefaultOptions()) |
| 3082 |
defer s.Shutdown() |
| 3083 |
|
| 3084 |
nc, err := nats.Connect(s.ClientURL(), nats.ErrorHandler(func(*nats.Conn, *nats.Subscription, error) {})) |
| 3085 |
require_NoError(t, err) |
| 3086 |
defer nc.Close() |
| 3087 |
|
| 3088 |
_, err = nc.QueueSubscribeSync("foo", sysGroup) |
| 3089 |
require_NoError(t, err) |
| 3090 |
nc.Flush() |
| 3091 |
err = nc.LastError() |
| 3092 |
require_Error(t, err) |
| 3093 |
require_Contains(t, err.Error(), "Permissions Violation") |
| 3094 |
} |
| 3095 |
|
| 3096 |
func TestClientAuthRequiredNoAuthUser(t *testing.T) { |
| 3097 |
conf := createConfFile(t, []byte(` |
| 3098 |
listen: 127.0.0.1:-1 |
| 3099 |
accounts: { |
| 3100 |
A: { users: [ { user: user, password: pass } ] } |
| 3101 |
} |
| 3102 |
no_auth_user: user |
| 3103 |
`)) |
| 3104 |
|
| 3105 |
s, _ := RunServerWithConfig(conf) |
| 3106 |
defer s.Shutdown() |
| 3107 |
|
| 3108 |
nc, err := nats.Connect(s.ClientURL()) |
| 3109 |
require_NoError(t, err) |
| 3110 |
defer nc.Close() |
| 3111 |
|
| 3112 |
if nc.AuthRequired() { |
| 3113 |
t.Fatalf("Expected AuthRequired to be false due to 'no_auth_user'") |
| 3114 |
} |
| 3115 |
} |
| 3116 |
|
| 3117 |
func TestClientUserInfoReq(t *testing.T) { |
| 3118 |
conf := createConfFile(t, []byte(` |
| 3119 |
listen: 127.0.0.1:-1 |
| 3120 |
PERMS = { |
| 3121 |
publish = { allow: "$SYS.REQ.>", deny: "$SYS.REQ.ACCOUNT.>" } |
| 3122 |
subscribe = "_INBOX.>" |
| 3123 |
allow_responses: true |
| 3124 |
} |
| 3125 |
accounts: { |
| 3126 |
A: { users: [ { user: dlc, password: pass, permissions: $PERMS } ] } |
| 3127 |
$SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } |
| 3128 |
} |
| 3129 |
no_auth_user: dlc |
| 3130 |
`)) |
| 3131 |
defer removeFile(t, conf) |
| 3132 |
|
| 3133 |
s, _ := RunServerWithConfig(conf) |
| 3134 |
defer s.Shutdown() |
| 3135 |
|
| 3136 |
nc, err := nats.Connect(s.ClientURL()) |
| 3137 |
require_NoError(t, err) |
| 3138 |
defer nc.Close() |
| 3139 |
|
| 3140 |
resp, err := nc.Request("$SYS.REQ.USER.INFO", nil, time.Second) |
| 3141 |
require_NoError(t, err) |
| 3142 |
|
| 3143 |
response := ServerAPIResponse{Data: &UserInfo{}} |
| 3144 |
err = json.Unmarshal(resp.Data, &response) |
| 3145 |
require_NoError(t, err) |
| 3146 |
|
| 3147 |
userInfo := response.Data.(*UserInfo) |
| 3148 |
|
| 3149 |
dlc := &UserInfo{ |
| 3150 |
UserID: "dlc", |
| 3151 |
Account: "A", |
| 3152 |
AccountName: "A", |
| 3153 |
Permissions: &Permissions{ |
| 3154 |
Publish: &SubjectPermission{ |
| 3155 |
Allow: []string{"$SYS.REQ.>"}, |
| 3156 |
Deny: []string{"$SYS.REQ.ACCOUNT.>"}, |
| 3157 |
}, |
| 3158 |
Subscribe: &SubjectPermission{ |
| 3159 |
Allow: []string{"_INBOX.>"}, |
| 3160 |
}, |
| 3161 |
Response: &ResponsePermission{ |
| 3162 |
MaxMsgs: DEFAULT_ALLOW_RESPONSE_MAX_MSGS, |
| 3163 |
Expires: DEFAULT_ALLOW_RESPONSE_EXPIRATION, |
| 3164 |
}, |
| 3165 |
}, |
| 3166 |
} |
| 3167 |
if !reflect.DeepEqual(dlc, userInfo) { |
| 3168 |
t.Fatalf("User info for %q did not match", "dlc") |
| 3169 |
} |
| 3170 |
|
| 3171 |
// Make sure system users work ok too. |
| 3172 |
nc, err = nats.Connect(s.ClientURL(), nats.UserInfo("admin", "s3cr3t!")) |
| 3173 |
require_NoError(t, err) |
| 3174 |
defer nc.Close() |
| 3175 |
|
| 3176 |
resp, err = nc.Request("$SYS.REQ.USER.INFO", nil, time.Second) |
| 3177 |
require_NoError(t, err) |
| 3178 |
|
| 3179 |
response = ServerAPIResponse{Data: &UserInfo{}} |
| 3180 |
err = json.Unmarshal(resp.Data, &response) |
| 3181 |
require_NoError(t, err) |
| 3182 |
|
| 3183 |
userInfo = response.Data.(*UserInfo) |
| 3184 |
|
| 3185 |
admin := &UserInfo{ |
| 3186 |
UserID: "admin", |
| 3187 |
Account: "$SYS", |
| 3188 |
AccountName: "$SYS", |
| 3189 |
} |
| 3190 |
if !reflect.DeepEqual(admin, userInfo) { |
| 3191 |
t.Fatalf("User info for %q did not match", "admin") |
| 3192 |
} |
| 3193 |
} |
| 3194 |
|
| 3195 |
func TestTLSClientHandshakeFirst(t *testing.T) { |
| 3196 |
tmpl := ` |
| 3197 |
listen: "127.0.0.1:-1" |
| 3198 |
tls { |
| 3199 |
cert_file: "../test/configs/certs/server-cert.pem" |
| 3200 |
key_file: "../test/configs/certs/server-key.pem" |
| 3201 |
timeout: 1 |
| 3202 |
first: %s |
| 3203 |
} |
| 3204 |
` |
| 3205 |
conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, "true"))) |
| 3206 |
s, o := RunServerWithConfig(conf) |
| 3207 |
defer s.Shutdown() |
| 3208 |
|
| 3209 |
connect := func(tlsfirst, expectedOk bool) { |
| 3210 |
opts := []nats.Option{nats.RootCAs("../test/configs/certs/ca.pem")} |
| 3211 |
if tlsfirst { |
| 3212 |
opts = append(opts, nats.TLSHandshakeFirst()) |
| 3213 |
} |
| 3214 |
nc, err := nats.Connect(fmt.Sprintf("tls://localhost:%d", o.Port), opts...) |
| 3215 |
if expectedOk { |
| 3216 |
defer nc.Close() |
| 3217 |
if err != nil { |
| 3218 |
t.Fatalf("Unexpected error: %v", err) |
| 3219 |
} |
| 3220 |
if tlsfirst { |
| 3221 |
cz, err := s.Connz(nil) |
| 3222 |
if err != nil { |
| 3223 |
t.Fatalf("Error getting connz: %v", err) |
| 3224 |
} |
| 3225 |
if !cz.Conns[0].TLSFirst { |
| 3226 |
t.Fatal("Expected TLSFirst boolean to be set, it was not") |
| 3227 |
} |
| 3228 |
} |
| 3229 |
} else if !expectedOk && err == nil { |
| 3230 |
nc.Close() |
| 3231 |
t.Fatal("Expected error, got none") |
| 3232 |
} |
| 3233 |
} |
| 3234 |
|
| 3235 |
// Server is TLS first, but client is not, so should fail. |
| 3236 |
connect(false, false) |
| 3237 |
|
| 3238 |
// Now client is TLS first too, so should work. |
| 3239 |
connect(true, true) |
| 3240 |
|
| 3241 |
// Config reload the server and disable tls first |
| 3242 |
reloadUpdateConfig(t, s, conf, fmt.Sprintf(tmpl, "false")) |
| 3243 |
|
| 3244 |
// Now if client wants TLS first, connection should fail. |
| 3245 |
connect(true, false) |
| 3246 |
|
| 3247 |
// But if it does not, should be ok. |
| 3248 |
connect(false, true) |
| 3249 |
|
| 3250 |
// Config reload the server again and enable tls first |
| 3251 |
reloadUpdateConfig(t, s, conf, fmt.Sprintf(tmpl, "true")) |
| 3252 |
|
| 3253 |
// If both client and server are TLS first, this should work. |
| 3254 |
connect(true, true) |
| 3255 |
} |
| 3256 |
|
| 3257 |
func TestTLSClientHandshakeFirstFallbackDelayConfigValues(t *testing.T) { |
| 3258 |
tmpl := ` |
| 3259 |
listen: "127.0.0.1:-1" |
| 3260 |
tls { |
| 3261 |
cert_file: "../test/configs/certs/server-cert.pem" |
| 3262 |
key_file: "../test/configs/certs/server-key.pem" |
| 3263 |
timeout: 1 |
| 3264 |
first: %s |
| 3265 |
} |
| 3266 |
` |
| 3267 |
for _, test := range []struct { |
| 3268 |
name string |
| 3269 |
val string |
| 3270 |
first bool |
| 3271 |
delay time.Duration |
| 3272 |
}{ |
| 3273 |
{"first as boolean true", "true", true, 0}, |
| 3274 |
{"first as boolean false", "false", false, 0}, |
| 3275 |
{"first as string true", "\"true\"", true, 0}, |
| 3276 |
{"first as string false", "\"false\"", false, 0}, |
| 3277 |
{"first as string on", "on", true, 0}, |
| 3278 |
{"first as string off", "off", false, 0}, |
| 3279 |
{"first as string auto", "auto", true, DEFAULT_TLS_HANDSHAKE_FIRST_FALLBACK_DELAY}, |
| 3280 |
{"first as string auto_fallback", "auto_fallback", true, DEFAULT_TLS_HANDSHAKE_FIRST_FALLBACK_DELAY}, |
| 3281 |
{"first as fallback duration", "300ms", true, 300 * time.Millisecond}, |
| 3282 |
} { |
| 3283 |
t.Run(test.name, func(t *testing.T) { |
| 3284 |
conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, test.val))) |
| 3285 |
s, o := RunServerWithConfig(conf) |
| 3286 |
defer s.Shutdown() |
| 3287 |
|
| 3288 |
if test.first { |
| 3289 |
if !o.TLSHandshakeFirst { |
| 3290 |
t.Fatal("Expected tls first to be true, was not") |
| 3291 |
} |
| 3292 |
if test.delay != o.TLSHandshakeFirstFallback { |
| 3293 |
t.Fatalf("Expected fallback delay to be %v, got %v", test.delay, o.TLSHandshakeFirstFallback) |
| 3294 |
} |
| 3295 |
} else { |
| 3296 |
if o.TLSHandshakeFirst { |
| 3297 |
t.Fatal("Expected tls first to be false, was not") |
| 3298 |
} |
| 3299 |
if o.TLSHandshakeFirstFallback != 0 { |
| 3300 |
t.Fatalf("Expected fallback delay to be 0, got %v", o.TLSHandshakeFirstFallback) |
| 3301 |
} |
| 3302 |
} |
| 3303 |
}) |
| 3304 |
} |
| 3305 |
} |
| 3306 |
|
| 3307 |
type pauseAfterDial struct { |
| 3308 |
delay time.Duration |
| 3309 |
} |
| 3310 |
|
| 3311 |
func (d *pauseAfterDial) Dial(network, address string) (net.Conn, error) { |
| 3312 |
c, err := net.Dial(network, address) |
| 3313 |
if err != nil { |
| 3314 |
return nil, err |
| 3315 |
} |
| 3316 |
time.Sleep(d.delay) |
| 3317 |
return c, nil |
| 3318 |
} |
| 3319 |
|
| 3320 |
func TestTLSClientHandshakeFirstFallbackDelay(t *testing.T) { |
| 3321 |
// Using certificates with RSA 4K to make sure that the fallback does |
| 3322 |
// not prevent a client with TLS first to successfully connect. |
| 3323 |
tmpl := ` |
| 3324 |
listen: "127.0.0.1:-1" |
| 3325 |
tls { |
| 3326 |
cert_file: "./configs/certs/tls/benchmark-server-cert-rsa-4096.pem" |
| 3327 |
key_file: "./configs/certs/tls/benchmark-server-key-rsa-4096.pem" |
| 3328 |
timeout: 1 |
| 3329 |
first: %s |
| 3330 |
} |
| 3331 |
` |
| 3332 |
conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, "auto"))) |
| 3333 |
s, o := RunServerWithConfig(conf) |
| 3334 |
defer s.Shutdown() |
| 3335 |
|
| 3336 |
url := fmt.Sprintf("tls://localhost:%d", o.Port) |
| 3337 |
d := &pauseAfterDial{delay: DEFAULT_TLS_HANDSHAKE_FIRST_FALLBACK_DELAY + 100*time.Millisecond} |
| 3338 |
|
| 3339 |
// Connect a client without "TLS first" and it should be accepted. |
| 3340 |
nc, err := nats.Connect(url, |
| 3341 |
nats.SetCustomDialer(d), |
| 3342 |
nats.Secure(&tls.Config{ |
| 3343 |
ServerName: "reuben.nats.io", |
| 3344 |
MinVersion: tls.VersionTLS12, |
| 3345 |
}), |
| 3346 |
nats.RootCAs("./configs/certs/tls/benchmark-ca-cert.pem")) |
| 3347 |
require_NoError(t, err) |
| 3348 |
defer nc.Close() |
| 3349 |
// Check that the TLS first in monitoring is set to false |
| 3350 |
cs, err := s.Connz(nil) |
| 3351 |
require_NoError(t, err) |
| 3352 |
if cs.Conns[0].TLSFirst { |
| 3353 |
t.Fatal("Expected monitoring ConnInfo.TLSFirst to be false, it was not") |
| 3354 |
} |
| 3355 |
nc.Close() |
| 3356 |
|
| 3357 |
// Wait for the client to be removed |
| 3358 |
checkClientsCount(t, s, 0) |
| 3359 |
|
| 3360 |
// Increase the fallback delay with config reload. |
| 3361 |
reloadUpdateConfig(t, s, conf, fmt.Sprintf(tmpl, "\"1s\"")) |
| 3362 |
|
| 3363 |
// This time, start the client with "TLS first". |
| 3364 |
// We will also make sure that we did not wait for the fallback delay |
| 3365 |
// in order to connect. |
| 3366 |
start := time.Now() |
| 3367 |
nc, err = nats.Connect(url, |
| 3368 |
nats.SetCustomDialer(d), |
| 3369 |
nats.Secure(&tls.Config{ |
| 3370 |
ServerName: "reuben.nats.io", |
| 3371 |
MinVersion: tls.VersionTLS12, |
| 3372 |
}), |
| 3373 |
nats.RootCAs("./configs/certs/tls/benchmark-ca-cert.pem"), |
| 3374 |
nats.TLSHandshakeFirst()) |
| 3375 |
require_NoError(t, err) |
| 3376 |
require_True(t, time.Since(start) < 500*time.Millisecond) |
| 3377 |
defer nc.Close() |
| 3378 |
|
| 3379 |
// Check that the TLS first in monitoring is set to true. |
| 3380 |
cs, err = s.Connz(nil) |
| 3381 |
require_NoError(t, err) |
| 3382 |
if !cs.Conns[0].TLSFirst { |
| 3383 |
t.Fatal("Expected monitoring ConnInfo.TLSFirst to be true, it was not") |
| 3384 |
} |
| 3385 |
nc.Close() |
| 3386 |
} |
| 3387 |
|
| 3388 |
func TestTLSClientHandshakeFirstFallbackDelayAndAllowNonTLS(t *testing.T) { |
| 3389 |
tmpl := ` |
| 3390 |
listen: "127.0.0.1:-1" |
| 3391 |
tls { |
| 3392 |
cert_file: "../test/configs/certs/server-cert.pem" |
| 3393 |
key_file: "../test/configs/certs/server-key.pem" |
| 3394 |
timeout: 1 |
| 3395 |
first: %s |
| 3396 |
} |
| 3397 |
allow_non_tls: true |
| 3398 |
` |
| 3399 |
conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, "true"))) |
| 3400 |
s, o := RunServerWithConfig(conf) |
| 3401 |
defer s.Shutdown() |
| 3402 |
|
| 3403 |
// We first start with a server that has handshake first set to true |
| 3404 |
// and allow_non_tls. In that case, only "TLS first" clients should be |
| 3405 |
// accepted. |
| 3406 |
url := fmt.Sprintf("tls://localhost:%d", o.Port) |
| 3407 |
nc, err := nats.Connect(url, |
| 3408 |
nats.RootCAs("../test/configs/certs/ca.pem"), |
| 3409 |
nats.TLSHandshakeFirst()) |
| 3410 |
require_NoError(t, err) |
| 3411 |
defer nc.Close() |
| 3412 |
// Check that the TLS first in monitoring is set to true |
| 3413 |
cs, err := s.Connz(nil) |
| 3414 |
require_NoError(t, err) |
| 3415 |
if !cs.Conns[0].TLSFirst { |
| 3416 |
t.Fatal("Expected monitoring ConnInfo.TLSFirst to be true, it was not") |
| 3417 |
} |
| 3418 |
nc.Close() |
| 3419 |
|
| 3420 |
// Client not using "TLS First" should fail. |
| 3421 |
nc, err = nats.Connect(url, nats.RootCAs("../test/configs/certs/ca.pem")) |
| 3422 |
if err == nil { |
| 3423 |
nc.Close() |
| 3424 |
t.Fatal("Expected connection to fail, it did not") |
| 3425 |
} |
| 3426 |
|
| 3427 |
// And non TLS clients should also fail to connect. |
| 3428 |
nc, err = nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", o.Port)) |
| 3429 |
if err == nil { |
| 3430 |
nc.Close() |
| 3431 |
t.Fatal("Expected connection to fail, it did not") |
| 3432 |
} |
| 3433 |
|
| 3434 |
// Now we will replace TLS first in server with a fallback delay. |
| 3435 |
reloadUpdateConfig(t, s, conf, fmt.Sprintf(tmpl, "\"25ms\"")) |
| 3436 |
|
| 3437 |
// Clients with "TLS first" should still be able to connect |
| 3438 |
nc, err = nats.Connect(url, |
| 3439 |
nats.RootCAs("../test/configs/certs/ca.pem"), |
| 3440 |
nats.TLSHandshakeFirst()) |
| 3441 |
require_NoError(t, err) |
| 3442 |
defer nc.Close() |
| 3443 |
|
| 3444 |
checkConnInfo := func(isTLS, isTLSFirst bool) { |
| 3445 |
t.Helper() |
| 3446 |
cs, err = s.Connz(nil) |
| 3447 |
require_NoError(t, err) |
| 3448 |
conn := cs.Conns[0] |
| 3449 |
if !isTLS { |
| 3450 |
if conn.TLSVersion != _EMPTY_ { |
| 3451 |
t.Fatalf("Being a non TLS client, there should not be TLSVersion set, got %v", conn.TLSVersion) |
| 3452 |
} |
| 3453 |
if conn.TLSFirst { |
| 3454 |
t.Fatal("Being a non TLS client, TLSFirst should not be set, but it was") |
| 3455 |
} |
| 3456 |
return |
| 3457 |
} |
| 3458 |
if isTLSFirst && !conn.TLSFirst { |
| 3459 |
t.Fatal("Expected monitoring ConnInfo.TLSFirst to be true, it was not") |
| 3460 |
} else if !isTLSFirst && conn.TLSFirst { |
| 3461 |
t.Fatal("Expected monitoring ConnInfo.TLSFirst to be false, it was not") |
| 3462 |
} |
| 3463 |
nc.Close() |
| 3464 |
|
| 3465 |
checkClientsCount(t, s, 0) |
| 3466 |
} |
| 3467 |
checkConnInfo(true, true) |
| 3468 |
|
| 3469 |
// Clients with TLS but not "TLS first" should also be able to connect. |
| 3470 |
nc, err = nats.Connect(url, nats.RootCAs("../test/configs/certs/ca.pem")) |
| 3471 |
require_NoError(t, err) |
| 3472 |
defer nc.Close() |
| 3473 |
checkConnInfo(true, false) |
| 3474 |
|
| 3475 |
// And non TLS clients should also be able to connect. |
| 3476 |
nc, err = nats.Connect(fmt.Sprintf("nats://127.0.0.1:%d", o.Port)) |
| 3477 |
require_NoError(t, err) |
| 3478 |
defer nc.Close() |
| 3479 |
checkConnInfo(false, false) |
| 3480 |
} |
| 3481 |
|
| 3482 |
func TestTLSClientNoticeWithAllowNonTLS(t *testing.T) { |
| 3483 |
tc := &TLSConfigOpts{ |
| 3484 |
CertFile: "../test/configs/certs/server-cert.pem", |
| 3485 |
KeyFile: "../test/configs/certs/server-key.pem", |
| 3486 |
CaFile: "../test/configs/certs/ca.pem", |
| 3487 |
} |
| 3488 |
tlsConfig, err := GenTLSConfig(tc) |
| 3489 |
require_NoError(t, err) |
| 3490 |
|
| 3491 |
const ( |
| 3492 |
tlsRequired = "TLS required for client connections" |
| 3493 |
tlsAvailable = "TLS available for client connections" |
| 3494 |
) |
| 3495 |
for _, test := range []struct { |
| 3496 |
name string |
| 3497 |
allowNonTLS bool |
| 3498 |
first bool |
| 3499 |
fallback time.Duration |
| 3500 |
expected string |
| 3501 |
}{ |
| 3502 |
{"tls only", false, false, 0, tlsRequired}, |
| 3503 |
{"allow non tls", true, false, 0, tlsAvailable}, |
| 3504 |
// With "TLS first" and no fallback delay, non TLS clients are rejected |
| 3505 |
// even with allow_non_tls, so TLS is really required. |
| 3506 |
{"allow non tls and tls first", true, true, 0, tlsRequired}, |
| 3507 |
// But with a fallback delay, they are accepted once it has expired. |
| 3508 |
{"allow non tls and tls first with fallback", true, true, 25 * time.Millisecond, tlsAvailable}, |
| 3509 |
} { |
| 3510 |
t.Run(test.name, func(t *testing.T) { |
| 3511 |
o := DefaultOptions() |
| 3512 |
o.TLSConfig = tlsConfig.Clone() |
| 3513 |
o.AllowNonTLS = test.allowNonTLS |
| 3514 |
o.TLSHandshakeFirst = test.first |
| 3515 |
o.TLSHandshakeFirstFallback = test.fallback |
| 3516 |
|
| 3517 |
s, err := NewServer(o) |
| 3518 |
require_NoError(t, err) |
| 3519 |
defer s.Shutdown() |
| 3520 |
|
| 3521 |
// Set the logger before starting the server so that the notices |
| 3522 |
// emitted by the client accept loop are captured. |
| 3523 |
l := &captureNoticeLogger{} |
| 3524 |
s.SetLogger(l, false, false) |
| 3525 |
go s.Start() |
| 3526 |
require_NoError(t, s.readyForConnections(time.Second)) |
| 3527 |
|
| 3528 |
var notices []string |
| 3529 |
l.Lock() |
| 3530 |
for _, n := range l.notices { |
| 3531 |
if strings.HasPrefix(n, "TLS ") && strings.HasSuffix(n, " for client connections") { |
| 3532 |
notices = append(notices, n) |
| 3533 |
} |
| 3534 |
} |
| 3535 |
l.Unlock() |
| 3536 |
if len(notices) != 1 || notices[0] != test.expected { |
| 3537 |
t.Fatalf("Expected notice %q, got %q", test.expected, notices) |
| 3538 |
} |
| 3539 |
}) |
| 3540 |
} |
| 3541 |
} |
| 3542 |
|
| 3543 |
func TestTLSClientHandshakeFirstAndInProcessConnection(t *testing.T) { |
| 3544 |
conf := createConfFile(t, []byte(` |
| 3545 |
listen: "127.0.0.1:-1" |
| 3546 |
tls { |
| 3547 |
cert_file: "../test/configs/certs/server-cert.pem" |
| 3548 |
key_file: "../test/configs/certs/server-key.pem" |
| 3549 |
timeout: 1 |
| 3550 |
first: true |
| 3551 |
} |
| 3552 |
`)) |
| 3553 |
s, _ := RunServerWithConfig(conf) |
| 3554 |
defer s.Shutdown() |
| 3555 |
|
| 3556 |
// Check that we can create an in process connection that does not use TLS |
| 3557 |
nc, err := nats.Connect(_EMPTY_, nats.InProcessServer(s)) |
| 3558 |
require_NoError(t, err) |
| 3559 |
defer nc.Close() |
| 3560 |
if nc.TLSRequired() { |
| 3561 |
t.Fatalf("Shouldn't have required TLS for in-process connection") |
| 3562 |
} |
| 3563 |
if _, err = nc.TLSConnectionState(); err == nil { |
| 3564 |
t.Fatal("Should have got an error retrieving TLS connection state") |
| 3565 |
} |
| 3566 |
nc.Close() |
| 3567 |
|
| 3568 |
// If the client wants TLS, it should get a TLS connection. |
| 3569 |
nc, err = nats.Connect(_EMPTY_, |
| 3570 |
nats.InProcessServer(s), |
| 3571 |
nats.RootCAs("../test/configs/certs/ca.pem")) |
| 3572 |
require_NoError(t, err) |
| 3573 |
defer nc.Close() |
| 3574 |
if _, err = nc.TLSConnectionState(); err != nil { |
| 3575 |
t.Fatal("Should have not got an error retrieving TLS connection state") |
| 3576 |
} |
| 3577 |
// However, the server would not have sent that TLS was required, |
| 3578 |
// but instead it is available. |
| 3579 |
if nc.TLSRequired() { |
| 3580 |
t.Fatalf("Shouldn't have required TLS for in-process connection") |
| 3581 |
} |
| 3582 |
nc.Close() |
| 3583 |
|
| 3584 |
// The in-process connection with TLS and "TLS first" should also be working. |
| 3585 |
nc, err = nats.Connect(_EMPTY_, |
| 3586 |
nats.InProcessServer(s), |
| 3587 |
nats.RootCAs("../test/configs/certs/ca.pem"), |
| 3588 |
nats.TLSHandshakeFirst()) |
| 3589 |
require_NoError(t, err) |
| 3590 |
defer nc.Close() |
| 3591 |
if !nc.TLSRequired() { |
| 3592 |
t.Fatalf("The server should have sent that TLS is required") |
| 3593 |
} |
| 3594 |
if _, err = nc.TLSConnectionState(); err != nil { |
| 3595 |
t.Fatal("Should have not got an error retrieving TLS connection state") |
| 3596 |
} |
| 3597 |
} |
| 3598 |
|
| 3599 |
type captureTLSHandshakeLogger struct { |
| 3600 |
DummyLogger |
| 3601 |
debugCh chan string |
| 3602 |
errCh chan string |
| 3603 |
} |
| 3604 |
|
| 3605 |
func (l *captureTLSHandshakeLogger) Debugf(format string, v ...any) { |
| 3606 |
select { |
| 3607 |
case l.debugCh <- fmt.Sprintf(format, v...): |
| 3608 |
default: |
| 3609 |
} |
| 3610 |
} |
| 3611 |
|
| 3612 |
func (l *captureTLSHandshakeLogger) Errorf(format string, v ...any) { |
| 3613 |
select { |
| 3614 |
case l.errCh <- fmt.Sprintf(format, v...): |
| 3615 |
default: |
| 3616 |
} |
| 3617 |
} |
| 3618 |
|
| 3619 |
func TestTLSClientHandshakeProbeErrorsLogAsDebug(t *testing.T) { |
| 3620 |
tc := &TLSConfigOpts{ |
| 3621 |
CertFile: "../test/configs/certs/server-cert.pem", |
| 3622 |
KeyFile: "../test/configs/certs/server-key.pem", |
| 3623 |
} |
| 3624 |
tlsConfig, err := GenTLSConfig(tc) |
| 3625 |
require_NoError(t, err) |
| 3626 |
|
| 3627 |
for _, test := range []struct { |
| 3628 |
name string |
| 3629 |
timeout float64 |
| 3630 |
peer string |
| 3631 |
pCerts PinnedCertSet |
| 3632 |
wantDebug bool |
| 3633 |
wantErrLog bool |
| 3634 |
}{ |
| 3635 |
{"timeout", 0.01, _EMPTY_, nil, true, false}, |
| 3636 |
{"not_tls_first_record", 1, "plain", nil, true, false}, |
| 3637 |
{"pinned_cert_failure", 1, "tls", PinnedCertSet{"bad": struct{}{}}, false, true}, |
| 3638 |
} { |
| 3639 |
t.Run(test.name, func(t *testing.T) { |
| 3640 |
s, err := NewServer(DefaultOptions()) |
| 3641 |
require_NoError(t, err) |
| 3642 |
l := &captureTLSHandshakeLogger{ |
| 3643 |
debugCh: make(chan string, 4), |
| 3644 |
errCh: make(chan string, 4), |
| 3645 |
} |
| 3646 |
s.SetLogger(l, true, false) |
| 3647 |
|
| 3648 |
serverConn, clientConn := net.Pipe() |
| 3649 |
defer clientConn.Close() |
| 3650 |
|
| 3651 |
c := &client{srv: s, nc: serverConn, kind: CLIENT} |
| 3652 |
c.initClient() |
| 3653 |
|
| 3654 |
switch test.peer { |
| 3655 |
case "plain": |
| 3656 |
go clientConn.Write([]byte("not tls\r\n")) |
| 3657 |
case "tls": |
| 3658 |
go func() { |
| 3659 |
tlsClient := tls.Client(clientConn, &tls.Config{InsecureSkipVerify: true}) |
| 3660 |
tlsClient.Handshake() |
| 3661 |
tlsClient.Close() |
| 3662 |
}() |
| 3663 |
} |
| 3664 |
|
| 3665 |
c.mu.Lock() |
| 3666 |
err = c.doTLSServerHandshake(_EMPTY_, tlsConfig, test.timeout, test.pCerts) |
| 3667 |
c.mu.Unlock() |
| 3668 |
require_Error(t, err) |
| 3669 |
|
| 3670 |
var gotDebug, gotErrLog bool |
| 3671 |
deadline := time.After(100 * time.Millisecond) |
| 3672 |
for done := false; !done; { |
| 3673 |
select { |
| 3674 |
case msg := <-l.errCh: |
| 3675 |
if strings.Contains(msg, "TLS handshake error") { |
| 3676 |
gotErrLog = true |
| 3677 |
} |
| 3678 |
case msg := <-l.debugCh: |
| 3679 |
if strings.Contains(msg, "TLS handshake error") { |
| 3680 |
gotDebug = true |
| 3681 |
} |
| 3682 |
case <-deadline: |
| 3683 |
done = true |
| 3684 |
} |
| 3685 |
} |
| 3686 |
if gotDebug != test.wantDebug { |
| 3687 |
t.Fatalf("Expected debug TLS handshake error log: %v, got: %v", test.wantDebug, gotDebug) |
| 3688 |
} |
| 3689 |
if gotErrLog != test.wantErrLog { |
| 3690 |
t.Fatalf("Expected error TLS handshake error log: %v, got: %v", test.wantErrLog, gotErrLog) |
| 3691 |
} |
| 3692 |
}) |
| 3693 |
} |
| 3694 |
} |
| 3695 |
|
| 3696 |
func TestTLSHandshakeTimerTimeoutLogLevel(t *testing.T) { |
| 3697 |
tc := &TLSConfigOpts{ |
| 3698 |
CertFile: "../test/configs/certs/server-cert.pem", |
| 3699 |
KeyFile: "../test/configs/certs/server-key.pem", |
| 3700 |
} |
| 3701 |
tlsConfig, err := GenTLSConfig(tc) |
| 3702 |
require_NoError(t, err) |
| 3703 |
|
| 3704 |
for _, test := range []struct { |
| 3705 |
kind int |
| 3706 |
wantDebug bool |
| 3707 |
wantErrLog bool |
| 3708 |
}{ |
| 3709 |
{CLIENT, true, false}, |
| 3710 |
{LEAF, true, false}, |
| 3711 |
{ROUTER, false, true}, |
| 3712 |
{GATEWAY, false, true}, |
| 3713 |
} { |
| 3714 |
t.Run(kindStringMap[test.kind], func(t *testing.T) { |
| 3715 |
s, err := NewServer(DefaultOptions()) |
| 3716 |
require_NoError(t, err) |
| 3717 |
l := &captureTLSHandshakeLogger{ |
| 3718 |
debugCh: make(chan string, 4), |
| 3719 |
errCh: make(chan string, 4), |
| 3720 |
} |
| 3721 |
s.SetLogger(l, true, false) |
| 3722 |
|
| 3723 |
serverConn, clientConn := net.Pipe() |
| 3724 |
defer clientConn.Close() |
| 3725 |
|
| 3726 |
tlsConn := tls.Server(serverConn, tlsConfig) |
| 3727 |
c := &client{srv: s, nc: tlsConn, kind: test.kind} |
| 3728 |
if test.kind == ROUTER { |
| 3729 |
c.route = &route{} |
| 3730 |
} else if test.kind == GATEWAY { |
| 3731 |
c.gw = &gateway{} |
| 3732 |
} |
| 3733 |
c.initClient() |
| 3734 |
c.flags.set(noReconnect) |
| 3735 |
|
| 3736 |
tlsTimeout(c, tlsConn) |
| 3737 |
|
| 3738 |
var gotDebug, gotErrLog bool |
| 3739 |
deadline := time.After(100 * time.Millisecond) |
| 3740 |
for done := false; !done; { |
| 3741 |
select { |
| 3742 |
case msg := <-l.errCh: |
| 3743 |
if strings.Contains(msg, "TLS handshake timeout") { |
| 3744 |
gotErrLog = true |
| 3745 |
} |
| 3746 |
case msg := <-l.debugCh: |
| 3747 |
if strings.Contains(msg, "TLS handshake timeout") { |
| 3748 |
gotDebug = true |
| 3749 |
} |
| 3750 |
case <-deadline: |
| 3751 |
done = true |
| 3752 |
} |
| 3753 |
} |
| 3754 |
if gotDebug != test.wantDebug { |
| 3755 |
t.Fatalf("Expected debug TLS handshake timeout log: %v, got: %v", test.wantDebug, gotDebug) |
| 3756 |
} |
| 3757 |
if gotErrLog != test.wantErrLog { |
| 3758 |
t.Fatalf("Expected error TLS handshake timeout log: %v, got: %v", test.wantErrLog, gotErrLog) |
| 3759 |
} |
| 3760 |
}) |
| 3761 |
} |
| 3762 |
} |
| 3763 |
|
| 3764 |
func TestRemoveHeaderIfPrefixPresent(t *testing.T) { |
| 3765 |
hdr := []byte("NATS/1.0\r\n\r\n") |
| 3766 |
|
| 3767 |
hdr = genHeader(hdr, "a", "1") |
| 3768 |
hdr = genHeader(hdr, JSExpectedStream, "my-stream") |
| 3769 |
hdr = genHeader(hdr, JSExpectedLastSeq, "22") |
| 3770 |
hdr = genHeader(hdr, "b", "2") |
| 3771 |
hdr = genHeader(hdr, JSExpectedLastSubjSeq, "24") |
| 3772 |
hdr = genHeader(hdr, JSExpectedLastMsgId, "1") |
| 3773 |
hdr = genHeader(hdr, "c", "3") |
| 3774 |
|
| 3775 |
hdr = removeHeaderIfPrefixPresent(hdr, "Nats-Expected-") |
| 3776 |
|
| 3777 |
if !bytes.Equal(hdr, []byte("NATS/1.0\r\na: 1\r\nb: 2\r\nc: 3\r\n\r\n")) { |
| 3778 |
t.Fatalf("Expected headers to be stripped, got %q", hdr) |
| 3779 |
} |
| 3780 |
} |
| 3781 |
|
| 3782 |
func TestRemoveHeaderIfPrefixPresentSkipsValueMatches(t *testing.T) { |
| 3783 |
hdr := []byte("NATS/1.0\r\n\r\n") |
| 3784 |
|
| 3785 |
// "Nats-Expected-Stream" embedded in another header's value must not |
| 3786 |
// short-circuit the scan: the real Nats-Expected-* headers below it |
| 3787 |
// still need to be removed. |
| 3788 |
hdr = genHeader(hdr, "X-Note", "see Nats-Expected-Stream below") |
| 3789 |
hdr = genHeader(hdr, JSExpectedStream, "my-stream") |
| 3790 |
hdr = genHeader(hdr, JSExpectedLastSeq, "22") |
| 3791 |
hdr = genHeader(hdr, "c", "3") |
| 3792 |
|
| 3793 |
hdr = removeHeaderIfPrefixPresent(hdr, "Nats-Expected-") |
| 3794 |
expected := []byte("NATS/1.0\r\nX-Note: see Nats-Expected-Stream below\r\nc: 3\r\n\r\n") |
| 3795 |
if !bytes.Equal(hdr, expected) { |
| 3796 |
t.Fatalf("Expected %q, got %q", expected, hdr) |
| 3797 |
} |
| 3798 |
} |
| 3799 |
|
| 3800 |
func TestRemoveHeaderIfPresentSkipsValueMatches(t *testing.T) { |
| 3801 |
hdr := []byte("NATS/1.0\r\n\r\n") |
| 3802 |
|
| 3803 |
// "Nats-Msg-Id" appearing inside another header's value must not stop |
| 3804 |
// the scan: the real Nats-Msg-Id header below it still needs to be |
| 3805 |
// removed, and the header containing the substring must be left intact. |
| 3806 |
hdr = genHeader(hdr, "X-Note", "Nats-Msg-Id is set below") |
| 3807 |
hdr = genHeader(hdr, "Nats-Msg-Id", "real-id") |
| 3808 |
hdr = genHeader(hdr, "c", "3") |
| 3809 |
|
| 3810 |
hdr = removeHeaderIfPresent(hdr, "Nats-Msg-Id") |
| 3811 |
expected := []byte("NATS/1.0\r\nX-Note: Nats-Msg-Id is set below\r\nc: 3\r\n\r\n") |
| 3812 |
if !bytes.Equal(hdr, expected) { |
| 3813 |
t.Fatalf("Expected %q, got %q", expected, hdr) |
| 3814 |
} |
| 3815 |
} |
| 3816 |
|
| 3817 |
func TestRemoveHeaderIfPresentDuplicates(t *testing.T) { |
| 3818 |
hdr := []byte("NATS/1.0\r\n\r\n") |
| 3819 |
|
| 3820 |
hdr = genHeader(hdr, "a", "1") |
| 3821 |
hdr = genHeader(hdr, "a", "2") |
| 3822 |
hdr = genHeader(hdr, "c", "3") |
| 3823 |
hdr = genHeader(hdr, "a", "4") |
| 3824 |
hdr = genHeader(hdr, "a", "5") |
| 3825 |
|
| 3826 |
hdr = removeHeaderIfPresent(hdr, "a") |
| 3827 |
|
| 3828 |
if !bytes.Equal(hdr, []byte("NATS/1.0\r\nc: 3\r\n\r\n")) { |
| 3829 |
t.Fatalf("Expected headers to be stripped, got %q", hdr) |
| 3830 |
} |
| 3831 |
} |
| 3832 |
|
| 3833 |
func TestSliceHeader(t *testing.T) { |
| 3834 |
hdr := []byte("NATS/1.0\r\n\r\n") |
| 3835 |
|
| 3836 |
hdr = genHeader(hdr, "a", "1") |
| 3837 |
hdr = genHeader(hdr, JSExpectedStream, "my-stream") |
| 3838 |
hdr = genHeader(hdr, JSExpectedLastSeq, "22") |
| 3839 |
hdr = genHeader(hdr, "b", "2") |
| 3840 |
hdr = genHeader(hdr, JSExpectedLastSubjSeq, "24") |
| 3841 |
hdr = genHeader(hdr, JSExpectedLastMsgId, "1") |
| 3842 |
hdr = genHeader(hdr, "c", "3") |
| 3843 |
|
| 3844 |
sliced := sliceHeader(JSExpectedLastSubjSeq, hdr) |
| 3845 |
copied := getHeader(JSExpectedLastSubjSeq, hdr) |
| 3846 |
|
| 3847 |
require_NotNil(t, sliced) |
| 3848 |
require_Equal(t, cap(sliced), 2) |
| 3849 |
|
| 3850 |
require_NotNil(t, copied) |
| 3851 |
require_Equal(t, cap(copied), len(copied)) |
| 3852 |
|
| 3853 |
require_True(t, bytes.Equal(sliced, copied)) |
| 3854 |
} |
| 3855 |
|
| 3856 |
func TestSliceHeaderOrderingPrefix(t *testing.T) { |
| 3857 |
hdr := []byte("NATS/1.0\r\n\r\n") |
| 3858 |
|
| 3859 |
// These headers share the same prefix, the longer subject |
| 3860 |
// must not invalidate the existence of the shorter one. |
| 3861 |
hdr = genHeader(hdr, JSExpectedLastSubjSeqSubj, "foo") |
| 3862 |
hdr = genHeader(hdr, JSExpectedLastSubjSeq, "24") |
| 3863 |
|
| 3864 |
sliced := sliceHeader(JSExpectedLastSubjSeq, hdr) |
| 3865 |
copied := getHeader(JSExpectedLastSubjSeq, hdr) |
| 3866 |
|
| 3867 |
require_NotNil(t, sliced) |
| 3868 |
require_Equal(t, cap(sliced), 2) |
| 3869 |
|
| 3870 |
require_NotNil(t, copied) |
| 3871 |
require_Equal(t, cap(copied), len(copied)) |
| 3872 |
|
| 3873 |
require_True(t, bytes.Equal(sliced, copied)) |
| 3874 |
} |
| 3875 |
|
| 3876 |
func TestReplyHasJSAckSuffix(t *testing.T) { |
| 3877 |
for _, test := range []struct { |
| 3878 |
name string |
| 3879 |
reply string |
| 3880 |
want bool |
| 3881 |
}{ |
| 3882 |
{"plain JSAck no suffix", "$JS.ACK.STREAM.CONS.1.2.3.4.5", false}, |
| 3883 |
{"single @ encoded", "[email protected]", true}, |
| 3884 |
{"double @ encoded (already corrupted)", "$JS.ACK.STREAM.CONS.1.2.3.4.5@inner@outer", true}, |
| 3885 |
{"non-JSAck reply with @", "_INBOX.abc@xyz", false}, |
| 3886 |
{"@ before 8 dots", "[email protected]", false}, |
| 3887 |
{"empty", "", false}, |
| 3888 |
{"JSAck prefix only no fields", "$JS.ACK.", false}, |
| 3889 |
// Cross-domain v2 token has more dots, but still 8+ before the @. |
| 3890 |
{"v2 token encoded", "$JS.ACK.dom.acct.STREAM.CONS.1.2.3.4.5@deliver", true}, |
| 3891 |
} { |
| 3892 |
t.Run(test.name, func(t *testing.T) { |
| 3893 |
got := replyHasJSAckSuffix([]byte(test.reply)) |
| 3894 |
require_Equal(t, got, test.want) |
| 3895 |
}) |
| 3896 |
} |
| 3897 |
} |
| 3898 |
|
| 3899 |
func TestSliceHeaderOrderingSuffix(t *testing.T) { |
| 3900 |
hdr := []byte("NATS/1.0\r\n\r\n") |
| 3901 |
|
| 3902 |
// These headers share the same suffix, the longer subject |
| 3903 |
// must not invalidate the existence of the shorter one. |
| 3904 |
hdr = genHeader(hdr, "Previous-Nats-Msg-Id", "user") |
| 3905 |
hdr = genHeader(hdr, "Nats-Msg-Id", "control") |
| 3906 |
|
| 3907 |
sliced := sliceHeader("Nats-Msg-Id", hdr) |
| 3908 |
copied := getHeader("Nats-Msg-Id", hdr) |
| 3909 |
|
| 3910 |
require_NotNil(t, sliced) |
| 3911 |
require_NotNil(t, copied) |
| 3912 |
require_True(t, bytes.Equal(sliced, copied)) |
| 3913 |
require_Equal(t, string(copied), "control") |
| 3914 |
} |
| 3915 |
|
| 3916 |
func TestRemoveHeaderIfPresentOrderingPrefix(t *testing.T) { |
| 3917 |
hdr := []byte("NATS/1.0\r\n\r\n") |
| 3918 |
|
| 3919 |
// These headers share the same prefix, the longer subject |
| 3920 |
// must not invalidate the existence of the shorter one. |
| 3921 |
hdr = genHeader(hdr, JSExpectedLastSubjSeqSubj, "foo") |
| 3922 |
hdr = genHeader(hdr, JSExpectedLastSubjSeq, "24") |
| 3923 |
|
| 3924 |
hdr = removeHeaderIfPresent(hdr, JSExpectedLastSubjSeq) |
| 3925 |
ehdr := genHeader(nil, JSExpectedLastSubjSeqSubj, "foo") |
| 3926 |
require_True(t, bytes.Equal(hdr, ehdr)) |
| 3927 |
} |
| 3928 |
|
| 3929 |
func TestRemoveHeaderIfPresentOrderingSuffix(t *testing.T) { |
| 3930 |
hdr := []byte("NATS/1.0\r\n\r\n") |
| 3931 |
|
| 3932 |
// These headers share the same suffix, the longer subject |
| 3933 |
// must not invalidate the existence of the shorter one. |
| 3934 |
hdr = genHeader(hdr, "Previous-Nats-Msg-Id", "user") |
| 3935 |
hdr = genHeader(hdr, "Nats-Msg-Id", "control") |
| 3936 |
|
| 3937 |
hdr = removeHeaderIfPresent(hdr, "Nats-Msg-Id") |
| 3938 |
ehdr := genHeader(nil, "Previous-Nats-Msg-Id", "user") |
| 3939 |
require_True(t, bytes.Equal(hdr, ehdr)) |
| 3940 |
} |
| 3941 |
|
| 3942 |
func TestMsgPartsCapsHdrSlice(t *testing.T) { |
| 3943 |
c := &client{} |
| 3944 |
hdrContent := hdrLine + "Key1: Val1\r\nKey2: Val2\r\n\r\n" |
| 3945 |
msgBody := "hello\r\n" |
| 3946 |
buf := slices.Clone([]byte(hdrContent + msgBody)) |
| 3947 |
c.pa.hdr = len(hdrContent) |
| 3948 |
|
| 3949 |
hdr, msg := c.msgParts(buf) |
| 3950 |
// Make sure "hdr" and "msg" are as expected. |
| 3951 |
require_Equal(t, string(hdr), hdrContent) |
| 3952 |
require_Equal(t, string(msg), msgBody) |
| 3953 |
// Previously, cap(hdr) would have been the same than the one of "buf", |
| 3954 |
// but now this is not the case. |
| 3955 |
require_True(t, cap(hdr) < cap(buf)) |
| 3956 |
// Just to make sure, try to add something (smaller than "hello\r\n") |
| 3957 |
// to "hdr" and make sure the "msg" content is not modified. |
| 3958 |
hdr = append(hdr, "test"...) |
| 3959 |
require_Equal(t, string(hdr), hdrContent+"test") |
| 3960 |
require_Equal(t, string(msg), "hello\r\n") |
| 3961 |
} |
| 3962 |
|
| 3963 |
func TestSetHeaderDoesNotOverwriteUnderlyingBuffer(t *testing.T) { |
| 3964 |
initialHdrContent := "NATS/1.0\r\nKey1: Val1\r\nKey2: Val2\r\n\r\n" |
| 3965 |
msgBody := "this is the message body\r\n" |
| 3966 |
for _, test := range []struct { |
| 3967 |
name string |
| 3968 |
key string |
| 3969 |
val string |
| 3970 |
expectedHdr string |
| 3971 |
newBuf bool |
| 3972 |
}{ |
| 3973 |
{"existing key new value larger", "Key1", "Val1Updated", "NATS/1.0\r\nKey1: Val1Updated\r\nKey2: Val2\r\n\r\n", true}, |
| 3974 |
{"existing key new value smaller", "Key1", "v1", "NATS/1.0\r\nKey1: v1\r\nKey2: Val2\r\n\r\n", false}, |
| 3975 |
{"new key", "Key3", "Val3", "NATS/1.0\r\nKey1: Val1\r\nKey2: Val2\r\nKey3: Val3\r\n\r\n", true}, |
| 3976 |
} { |
| 3977 |
t.Run(test.name, func(t *testing.T) { |
| 3978 |
buf := make([]byte, 0, len(initialHdrContent)+len(msgBody)) |
| 3979 |
buf = append(buf, initialHdrContent...) |
| 3980 |
msgStart := len(buf) |
| 3981 |
buf = append(buf, msgBody...) |
| 3982 |
|
| 3983 |
// Simulate that we create slices out of the underlying buffer, |
| 3984 |
// separating the header and body parts. |
| 3985 |
hdr, msg := buf[:msgStart], buf[msgStart:] |
| 3986 |
hdr = setHeader(test.key, test.val, hdr) |
| 3987 |
require_Equal(t, string(hdr), test.expectedHdr) |
| 3988 |
require_Equal(t, string(msg), msgBody) |
| 3989 |
if test.newBuf { |
| 3990 |
// The "hdr" part of the underlying buffer should not have |
| 3991 |
// been changed. |
| 3992 |
require_Equal(t, string(buf[:len(initialHdrContent)]), initialHdrContent) |
| 3993 |
} else { |
| 3994 |
// The "hdr" part of the underlying buffer has been changed. |
| 3995 |
require_Equal(t, string(buf[:len(test.expectedHdr)]), test.expectedHdr) |
| 3996 |
} |
| 3997 |
}) |
| 3998 |
} |
| 3999 |
} |
| 4000 |
|
| 4001 |
func TestClientSetHeaderDoesNotMutateInputMsg(t *testing.T) { |
| 4002 |
hdr := "NATS/1.0\r\nClientInfo: {old}\r\nKey2: Val2\r\n\r\n" |
| 4003 |
msg := "this is the message body\r\n" |
| 4004 |
|
| 4005 |
buf := make([]byte, 0, len(hdr)+len(msg)) |
| 4006 |
buf = append(buf, hdr...) |
| 4007 |
buf = append(buf, msg...) |
| 4008 |
|
| 4009 |
c := &client{} |
| 4010 |
c.pa.hdr = len(hdr) |
| 4011 |
c.pa.size = len(buf) |
| 4012 |
|
| 4013 |
// setHeader should copy to not corrupt the input message. |
| 4014 |
original := slices.Clone(buf) |
| 4015 |
out := c.setHeader("ClientInfo", "{newvalue}", buf) |
| 4016 |
require_Equal(t, string(buf), string(original)) |
| 4017 |
|
| 4018 |
expected := "NATS/1.0\r\nKey2: Val2\r\nClientInfo: {newvalue}\r\n\r\n" + msg |
| 4019 |
require_Equal(t, string(out), expected) |
| 4020 |
} |
| 4021 |
|
| 4022 |
func TestSetHeaderOrderingPrefix(t *testing.T) { |
| 4023 |
for _, space := range []bool{true, false} { |
| 4024 |
title := "Normal" |
| 4025 |
if !space { |
| 4026 |
title = "Trimmed" |
| 4027 |
} |
| 4028 |
t.Run(title, func(t *testing.T) { |
| 4029 |
hdr := []byte("NATS/1.0\r\n\r\n") |
| 4030 |
|
| 4031 |
// These headers share the same prefix, the longer subject |
| 4032 |
// must not invalidate the existence of the shorter one. |
| 4033 |
hdr = genHeader(hdr, JSExpectedLastSubjSeqSubj, "foo") |
| 4034 |
hdr = genHeader(hdr, JSExpectedLastSubjSeq, "24") |
| 4035 |
if !space { |
| 4036 |
hdr = bytes.ReplaceAll(hdr, []byte(" "), nil) |
| 4037 |
} |
| 4038 |
|
| 4039 |
hdr = setHeader(JSExpectedLastSubjSeq, "12", hdr) |
| 4040 |
ehdr := genHeader(nil, JSExpectedLastSubjSeqSubj, "foo") |
| 4041 |
ehdr = genHeader(ehdr, JSExpectedLastSubjSeq, "12") |
| 4042 |
if !space { |
| 4043 |
ehdr = bytes.ReplaceAll(ehdr, []byte(" "), nil) |
| 4044 |
} |
| 4045 |
require_True(t, bytes.Equal(hdr, ehdr)) |
| 4046 |
}) |
| 4047 |
} |
| 4048 |
} |
| 4049 |
|
| 4050 |
func TestSetHeaderOrderingSuffix(t *testing.T) { |
| 4051 |
for _, space := range []bool{true, false} { |
| 4052 |
title := "Normal" |
| 4053 |
if !space { |
| 4054 |
title = "Trimmed" |
| 4055 |
} |
| 4056 |
t.Run(title, func(t *testing.T) { |
| 4057 |
hdr := []byte("NATS/1.0\r\n\r\n") |
| 4058 |
|
| 4059 |
// These headers share the same suffix, the longer subject |
| 4060 |
// must not invalidate the existence of the shorter one. |
| 4061 |
hdr = genHeader(hdr, "Previous-Nats-Msg-Id", "user") |
| 4062 |
hdr = genHeader(hdr, "Nats-Msg-Id", "control") |
| 4063 |
if !space { |
| 4064 |
hdr = bytes.ReplaceAll(hdr, []byte(" "), nil) |
| 4065 |
} |
| 4066 |
|
| 4067 |
hdr = setHeader("Nats-Msg-Id", "other", hdr) |
| 4068 |
ehdr := genHeader(nil, "Previous-Nats-Msg-Id", "user") |
| 4069 |
ehdr = genHeader(ehdr, "Nats-Msg-Id", "other") |
| 4070 |
if !space { |
| 4071 |
ehdr = bytes.ReplaceAll(ehdr, []byte(" "), nil) |
| 4072 |
} |
| 4073 |
require_True(t, bytes.Equal(hdr, ehdr)) |
| 4074 |
}) |
| 4075 |
} |
| 4076 |
} |
| 4077 |
|
| 4078 |
func TestInProcessAllowedConnectionType(t *testing.T) { |
| 4079 |
tmpl := ` |
| 4080 |
listen: "127.0.0.1:-1" |
| 4081 |
accounts { |
| 4082 |
A { users: [{user: "test", password: "pwd", allowed_connection_types: ["%s"]}] } |
| 4083 |
} |
| 4084 |
write_deadline: "500ms" |
| 4085 |
` |
| 4086 |
for _, test := range []struct { |
| 4087 |
name string |
| 4088 |
ct string |
| 4089 |
inProcessOnly bool |
| 4090 |
}{ |
| 4091 |
{"conf inprocess", jwt.ConnectionTypeInProcess, true}, |
| 4092 |
{"conf standard", jwt.ConnectionTypeStandard, false}, |
| 4093 |
} { |
| 4094 |
t.Run(test.name, func(t *testing.T) { |
| 4095 |
conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, test.ct))) |
| 4096 |
s, _ := RunServerWithConfig(conf) |
| 4097 |
defer s.Shutdown() |
| 4098 |
|
| 4099 |
// Create standard connection |
| 4100 |
nc, err := nats.Connect(s.ClientURL(), nats.UserInfo("test", "pwd")) |
| 4101 |
if test.inProcessOnly && err == nil { |
| 4102 |
nc.Close() |
| 4103 |
t.Fatal("Expected standard connection to fail, it did not") |
| 4104 |
} |
| 4105 |
// Works if nc is nil (which it will if only in-process are allowed) |
| 4106 |
nc.Close() |
| 4107 |
|
| 4108 |
// Create inProcess connection |
| 4109 |
nc, err = nats.Connect(_EMPTY_, nats.UserInfo("test", "pwd"), nats.InProcessServer(s)) |
| 4110 |
if !test.inProcessOnly && err == nil { |
| 4111 |
nc.Close() |
| 4112 |
t.Fatal("Expected in-process connection to fail, it did not") |
| 4113 |
} |
| 4114 |
// Works if nc is nil (which it will if only standard are allowed) |
| 4115 |
nc.Close() |
| 4116 |
}) |
| 4117 |
} |
| 4118 |
for _, test := range []struct { |
| 4119 |
name string |
| 4120 |
ct string |
| 4121 |
inProcessOnly bool |
| 4122 |
}{ |
| 4123 |
{"jwt inprocess", jwt.ConnectionTypeInProcess, true}, |
| 4124 |
{"jwt standard", jwt.ConnectionTypeStandard, false}, |
| 4125 |
} { |
| 4126 |
t.Run(test.name, func(t *testing.T) { |
| 4127 |
skp, _ := nkeys.FromSeed(oSeed) |
| 4128 |
spub, _ := skp.PublicKey() |
| 4129 |
|
| 4130 |
o := defaultServerOptions |
| 4131 |
o.TrustedKeys = []string{spub} |
| 4132 |
o.WriteDeadline = 500 * time.Millisecond |
| 4133 |
s := RunServer(&o) |
| 4134 |
defer s.Shutdown() |
| 4135 |
|
| 4136 |
buildMemAccResolver(s) |
| 4137 |
|
| 4138 |
kp, _ := nkeys.CreateAccount() |
| 4139 |
aPub, _ := kp.PublicKey() |
| 4140 |
claim := jwt.NewAccountClaims(aPub) |
| 4141 |
aJwt, err := claim.Encode(oKp) |
| 4142 |
require_NoError(t, err) |
| 4143 |
|
| 4144 |
addAccountToMemResolver(s, aPub, aJwt) |
| 4145 |
|
| 4146 |
creds := createUserWithLimit(t, kp, time.Time{}, |
| 4147 |
func(j *jwt.UserPermissionLimits) { |
| 4148 |
j.AllowedConnectionTypes.Add(test.ct) |
| 4149 |
}) |
| 4150 |
// Create standard connection |
| 4151 |
nc, err := nats.Connect(s.ClientURL(), nats.UserCredentials(creds)) |
| 4152 |
if test.inProcessOnly && err == nil { |
| 4153 |
nc.Close() |
| 4154 |
t.Fatal("Expected standard connection to fail, it did not") |
| 4155 |
} |
| 4156 |
// Works if nc is nil (which it will if only in-process are allowed) |
| 4157 |
nc.Close() |
| 4158 |
|
| 4159 |
// Create inProcess connection |
| 4160 |
nc, err = nats.Connect(_EMPTY_, nats.UserCredentials(creds), nats.InProcessServer(s)) |
| 4161 |
if !test.inProcessOnly && err == nil { |
| 4162 |
nc.Close() |
| 4163 |
t.Fatal("Expected in-process connection to fail, it did not") |
| 4164 |
} |
| 4165 |
// Works if nc is nil (which it will if only standard are allowed) |
| 4166 |
nc.Close() |
| 4167 |
}) |
| 4168 |
} |
| 4169 |
} |
| 4170 |
|
| 4171 |
func TestClientFlushOutboundNoSlowConsumer(t *testing.T) { |
| 4172 |
opts := DefaultOptions() |
| 4173 |
opts.MaxPending = 1024 * 1024 * 140 // 140MB |
| 4174 |
opts.MaxPayload = 1024 * 1024 * 16 // 16MB |
| 4175 |
opts.WriteDeadline = time.Second * 30 |
| 4176 |
s := RunServer(opts) |
| 4177 |
defer s.Shutdown() |
| 4178 |
|
| 4179 |
nc := natsConnect(t, fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) |
| 4180 |
defer nc.Close() |
| 4181 |
|
| 4182 |
proxy := newNetProxy(0, 1024*1024*8, 1024*1024*8, s.ClientURL()) // 8MB/s |
| 4183 |
defer proxy.stop() |
| 4184 |
|
| 4185 |
wait := make(chan error) |
| 4186 |
|
| 4187 |
nca, err := nats.Connect(proxy.clientURL(), nats.NoCallbacksAfterClientClose()) |
| 4188 |
require_NoError(t, err) |
| 4189 |
defer nca.Close() |
| 4190 |
nca.SetDisconnectErrHandler(func(c *nats.Conn, err error) { |
| 4191 |
wait <- err |
| 4192 |
close(wait) |
| 4193 |
}) |
| 4194 |
|
| 4195 |
ncb, err := nats.Connect(s.ClientURL()) |
| 4196 |
require_NoError(t, err) |
| 4197 |
defer ncb.Close() |
| 4198 |
|
| 4199 |
_, err = nca.Subscribe("test", func(msg *nats.Msg) { |
| 4200 |
wait <- nil |
| 4201 |
}) |
| 4202 |
require_NoError(t, err) |
| 4203 |
|
| 4204 |
// Publish 128MB of data onto the test subject. This will |
| 4205 |
// mean that the outbound queue for nca has more than 64MB, |
| 4206 |
// which is the max we will send into a single writev call. |
| 4207 |
payload := make([]byte, 1024*1024*16) // 16MB |
| 4208 |
for i := 0; i < 8; i++ { |
| 4209 |
require_NoError(t, ncb.Publish("test", payload)) |
| 4210 |
} |
| 4211 |
|
| 4212 |
// Get the client ID for nca. |
| 4213 |
cid, err := nca.GetClientID() |
| 4214 |
require_NoError(t, err) |
| 4215 |
|
| 4216 |
// Check that the client queue has more than 64MB queued |
| 4217 |
// up in it. |
| 4218 |
s.mu.RLock() |
| 4219 |
ca := s.clients[cid] |
| 4220 |
s.mu.RUnlock() |
| 4221 |
ca.mu.Lock() |
| 4222 |
pba := ca.out.pb |
| 4223 |
ca.mu.Unlock() |
| 4224 |
require_True(t, pba > 1024*1024*64) |
| 4225 |
|
| 4226 |
// Wait for our messages to be delivered. This will take |
| 4227 |
// a few seconds as the client is limited to 8MB/s, so it |
| 4228 |
// can't deliver messages to us as quickly as the other |
| 4229 |
// client can publish them. |
| 4230 |
var msgs int |
| 4231 |
for err := range wait { |
| 4232 |
require_NoError(t, err) |
| 4233 |
msgs++ |
| 4234 |
if msgs == 8 { |
| 4235 |
break |
| 4236 |
} |
| 4237 |
} |
| 4238 |
require_Equal(t, msgs, 8) |
| 4239 |
} |
| 4240 |
|
| 4241 |
func TestClientRejectsNRGSubjects(t *testing.T) { |
| 4242 |
conf := createConfFile(t, []byte(` |
| 4243 |
listen: 127.0.0.1:-1 |
| 4244 |
accounts: { |
| 4245 |
A: { users: [ { user: nat, password: pass } ] } |
| 4246 |
$SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } |
| 4247 |
} |
| 4248 |
no_auth_user: nat |
| 4249 |
`)) |
| 4250 |
defer removeFile(t, conf) |
| 4251 |
|
| 4252 |
s, _ := RunServerWithConfig(conf) |
| 4253 |
defer s.Shutdown() |
| 4254 |
|
| 4255 |
t.Run("System", func(t *testing.T) { |
| 4256 |
ech := make(chan error, 1) |
| 4257 |
nc, err := nats.Connect(s.ClientURL(), nats.UserInfo("admin", "s3cr3t!"), |
| 4258 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, e error) { |
| 4259 |
ech <- e |
| 4260 |
}), |
| 4261 |
) |
| 4262 |
require_NoError(t, err) |
| 4263 |
defer nc.Close() |
| 4264 |
|
| 4265 |
// System account clients are allowed to publish to these subjects. |
| 4266 |
require_NoError(t, nc.Publish("$NRG.foo", nil)) |
| 4267 |
require_NoChanRead(t, ech, time.Second) |
| 4268 |
}) |
| 4269 |
|
| 4270 |
t.Run("Normal", func(t *testing.T) { |
| 4271 |
ech := make(chan error, 1) |
| 4272 |
nc, err := nats.Connect(s.ClientURL(), |
| 4273 |
nats.ErrorHandler(func(_ *nats.Conn, _ *nats.Subscription, e error) { |
| 4274 |
ech <- e |
| 4275 |
}), |
| 4276 |
) |
| 4277 |
require_NoError(t, err) |
| 4278 |
defer nc.Close() |
| 4279 |
|
| 4280 |
// Non-system clients should receive a pub permission error. |
| 4281 |
require_NoError(t, nc.Publish("$NRG.foo", nil)) |
| 4282 |
err = require_ChanRead(t, ech, time.Second) |
| 4283 |
require_Error(t, err) |
| 4284 |
require_True(t, strings.HasPrefix(err.Error(), "nats: permissions violation")) |
| 4285 |
}) |
| 4286 |
} |
| 4287 |
|
| 4288 |
func TestConnectionStringWithLogConnectionInfo(t *testing.T) { |
| 4289 |
opts := DefaultOptions() |
| 4290 |
s, c, _, _ := rawSetup(*opts) |
| 4291 |
defer c.close() |
| 4292 |
defer s.Shutdown() |
| 4293 |
|
| 4294 |
c.kind = CLIENT |
| 4295 |
connectArg := []byte("{\"verbose\":false,\"pedantic\":false,\"version\":\"1.0.0\",\"lang\":\"go\",\"name\":\"test-client\"}") |
| 4296 |
|
| 4297 |
err := c.processConnect(connectArg) |
| 4298 |
if err != nil { |
| 4299 |
t.Fatalf("Received error on first processConnect: %v", err) |
| 4300 |
} |
| 4301 |
|
| 4302 |
// Get the connection string after first processConnect. |
| 4303 |
firstConnStr := c.ncs.Load() |
| 4304 |
if firstConnStr == nil { |
| 4305 |
return |
| 4306 |
} |
| 4307 |
firstStr := firstConnStr.(string) |
| 4308 |
firstLen := len(firstStr) |
| 4309 |
require_Equal(t, firstStr, `pipe - cid:1 - "v1.0.0:go:test-client"`) |
| 4310 |
|
| 4311 |
// Process connect multiple times. |
| 4312 |
for i := 0; i < 3; i++ { |
| 4313 |
err = c.processConnect(connectArg) |
| 4314 |
if err != nil { |
| 4315 |
t.Fatalf("Received error on processConnect attempt %d: %v", i+2, err) |
| 4316 |
} |
| 4317 |
} |
| 4318 |
|
| 4319 |
// Get the connection string after multiple calls. |
| 4320 |
finalConnStr := c.ncs.Load() |
| 4321 |
require_NotNil(t, finalConnStr) |
| 4322 |
|
| 4323 |
finalStr := finalConnStr.(string) |
| 4324 |
require_Equal(t, firstStr, finalStr) |
| 4325 |
|
| 4326 |
// Now send a different connect over the same connection. |
| 4327 |
connectArg2 := []byte("{\"verbose\":false,\"pedantic\":false,\"version\":\"1.0.0\",\"lang\":\"go\",\"name\":\"test-client:new\"}") |
| 4328 |
|
| 4329 |
err = c.processConnect(connectArg2) |
| 4330 |
if err != nil { |
| 4331 |
t.Fatalf("Received error on processConnect: %v", err) |
| 4332 |
} |
| 4333 |
finalConnStr = c.ncs.Load() |
| 4334 |
require_NotNil(t, finalConnStr) |
| 4335 |
|
| 4336 |
// Check that it remains the same size after a different connect. |
| 4337 |
finalStr = finalConnStr.(string) |
| 4338 |
finalLen := len(finalStr) |
| 4339 |
if finalLen > firstLen { |
| 4340 |
t.Fatalf("Connection string grew from %d to %d characters", firstLen, finalLen) |
| 4341 |
} |
| 4342 |
} |
| 4343 |
|
| 4344 |
func TestLogConnectionAuthInfo(t *testing.T) { |
| 4345 |
t.Run("username_password", func(t *testing.T) { |
| 4346 |
opts := DefaultOptions() |
| 4347 |
opts.Username = "testuser" |
| 4348 |
opts.Password = "testpass" |
| 4349 |
s, c, _, _ := rawSetup(*opts) |
| 4350 |
defer c.close() |
| 4351 |
defer s.Shutdown() |
| 4352 |
|
| 4353 |
c.kind = CLIENT |
| 4354 |
connectArg := []byte(`{"verbose":false,"pedantic":false,"user":"testuser","pass":"testpass"}`) |
| 4355 |
|
| 4356 |
err := c.processConnect(connectArg) |
| 4357 |
require_NoError(t, err) |
| 4358 |
|
| 4359 |
connStr := c.ncs.Load() |
| 4360 |
require_NotNil(t, connStr) |
| 4361 |
str := connStr.(string) |
| 4362 |
require_Contains(t, str, `"$G/user:testuser"`) |
| 4363 |
}) |
| 4364 |
t.Run("token", func(t *testing.T) { |
| 4365 |
opts := DefaultOptions() |
| 4366 |
opts.Authorization = "secret-token" |
| 4367 |
s, c, _, _ := rawSetup(*opts) |
| 4368 |
defer c.close() |
| 4369 |
defer s.Shutdown() |
| 4370 |
|
| 4371 |
c.kind = CLIENT |
| 4372 |
connectArg := []byte(`{"verbose":false,"pedantic":false,"auth_token":"secret-token"}`) |
| 4373 |
|
| 4374 |
err := c.processConnect(connectArg) |
| 4375 |
require_NoError(t, err) |
| 4376 |
|
| 4377 |
connStr := c.ncs.Load() |
| 4378 |
require_NotNil(t, connStr) |
| 4379 |
str := connStr.(string) |
| 4380 |
require_Contains(t, str, `"$G/token"`) |
| 4381 |
}) |
| 4382 |
t.Run("nkey", func(t *testing.T) { |
| 4383 |
kp, _ := nkeys.CreateUser() |
| 4384 |
pub, _ := kp.PublicKey() |
| 4385 |
nkey := string(pub) |
| 4386 |
|
| 4387 |
opts := DefaultOptions() |
| 4388 |
opts.Nkeys = []*NkeyUser{{Nkey: nkey}} |
| 4389 |
s, c, _, _ := rawSetup(*opts) |
| 4390 |
defer c.close() |
| 4391 |
defer s.Shutdown() |
| 4392 |
|
| 4393 |
c.kind = CLIENT |
| 4394 |
nonce := make([]byte, 32) |
| 4395 |
c.nonce = nonce |
| 4396 |
sig, _ := kp.Sign(nonce) |
| 4397 |
sigEncoded := base64.RawURLEncoding.EncodeToString(sig) |
| 4398 |
|
| 4399 |
connectArg := fmt.Sprintf(`{"verbose":false,"pedantic":false,"nkey":"%s","sig":"%s"}`, nkey, sigEncoded) |
| 4400 |
|
| 4401 |
err := c.processConnect([]byte(connectArg)) |
| 4402 |
require_NoError(t, err) |
| 4403 |
|
| 4404 |
connStr := c.ncs.Load() |
| 4405 |
require_NotNil(t, connStr) |
| 4406 |
str := connStr.(string) |
| 4407 |
require_Contains(t, str, fmt.Sprintf(`"$G/nkey:%s"`, nkey)) |
| 4408 |
}) |
| 4409 |
t.Run("combined_info_and_auth", func(t *testing.T) { |
| 4410 |
opts := DefaultOptions() |
| 4411 |
opts.Username = "testuser" |
| 4412 |
opts.Password = "testpass" |
| 4413 |
s, c, _, _ := rawSetup(*opts) |
| 4414 |
defer c.close() |
| 4415 |
defer s.Shutdown() |
| 4416 |
|
| 4417 |
c.kind = CLIENT |
| 4418 |
connectArg := []byte(`{"verbose":false,"pedantic":false,"user":"testuser","pass":"testpass","version":"1.0.0","lang":"go","name":"test-client"}`) |
| 4419 |
|
| 4420 |
err := c.processConnect(connectArg) |
| 4421 |
require_NoError(t, err) |
| 4422 |
|
| 4423 |
connStr := c.ncs.Load() |
| 4424 |
require_NotNil(t, connStr) |
| 4425 |
str := connStr.(string) |
| 4426 |
require_Contains(t, str, `"v1.0.0:go:test-client"`) |
| 4427 |
require_Contains(t, str, `"$G/user:testuser"`) |
| 4428 |
}) |
| 4429 |
t.Run("no_auth", func(t *testing.T) { |
| 4430 |
opts := DefaultOptions() |
| 4431 |
s, c, _, _ := rawSetup(*opts) |
| 4432 |
defer c.close() |
| 4433 |
defer s.Shutdown() |
| 4434 |
|
| 4435 |
c.kind = CLIENT |
| 4436 |
connectArg := []byte(`{"verbose":false,"pedantic":false}`) |
| 4437 |
|
| 4438 |
err := c.processConnect(connectArg) |
| 4439 |
require_NoError(t, err) |
| 4440 |
|
| 4441 |
connStr := c.ncs.Load() |
| 4442 |
if connStr != nil { |
| 4443 |
str := connStr.(string) |
| 4444 |
if strings.Contains(str, "$G/") { |
| 4445 |
t.Fatalf("Expected no auth info when no authentication provided, got: %s", str) |
| 4446 |
} |
| 4447 |
} |
| 4448 |
}) |
| 4449 |
} |
| 4450 |
|
| 4451 |
func TestClientConfigureWriteTimeoutPolicy(t *testing.T) { |
| 4452 |
for name, policy := range map[string]WriteTimeoutPolicy{ |
| 4453 |
"Default": WriteTimeoutPolicyDefault, |
| 4454 |
"Retry": WriteTimeoutPolicyRetry, |
| 4455 |
"Close": WriteTimeoutPolicyClose, |
| 4456 |
} { |
| 4457 |
t.Run(name, func(t *testing.T) { |
| 4458 |
opts := DefaultOptions() |
| 4459 |
opts.WriteTimeout = policy |
| 4460 |
s := RunServer(opts) |
| 4461 |
defer s.Shutdown() |
| 4462 |
|
| 4463 |
nc := natsConnect(t, fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) |
| 4464 |
defer nc.Close() |
| 4465 |
|
| 4466 |
s.mu.RLock() |
| 4467 |
defer s.mu.RUnlock() |
| 4468 |
|
| 4469 |
for _, r := range s.clients { |
| 4470 |
if policy == WriteTimeoutPolicyDefault { |
| 4471 |
require_Equal(t, r.out.wtp, WriteTimeoutPolicyClose) |
| 4472 |
} else { |
| 4473 |
require_Equal(t, r.out.wtp, policy) |
| 4474 |
} |
| 4475 |
} |
| 4476 |
}) |
| 4477 |
} |
| 4478 |
} |
| 4479 |
|
| 4480 |
// TestClientFlushOutboundWriteTimeoutPolicy relies on specifically having |
| 4481 |
// written at least one byte in order to not trip the "written == 0" close |
| 4482 |
// condition, so just setting an unrealistically low write deadline won't |
| 4483 |
// work. Instead what we'll do is write the first byte very quickly and then |
| 4484 |
// slow down, so that we can trip a more honest slow consumer condition. |
| 4485 |
type writeTimeoutPolicyWriter struct { |
| 4486 |
net.Conn |
| 4487 |
deadline time.Time |
| 4488 |
written int |
| 4489 |
} |
| 4490 |
|
| 4491 |
func (w *writeTimeoutPolicyWriter) SetWriteDeadline(deadline time.Time) error { |
| 4492 |
w.deadline = deadline |
| 4493 |
return w.Conn.SetWriteDeadline(deadline) |
| 4494 |
} |
| 4495 |
|
| 4496 |
func (w *writeTimeoutPolicyWriter) Write(b []byte) (int, error) { |
| 4497 |
if w.written == 0 { |
| 4498 |
w.written++ |
| 4499 |
return w.Conn.Write(b[:1]) |
| 4500 |
} |
| 4501 |
time.Sleep(time.Until(w.deadline) + 10*time.Millisecond) |
| 4502 |
return w.Conn.Write(b) |
| 4503 |
} |
| 4504 |
|
| 4505 |
func TestClientFlushOutboundWriteTimeoutPolicy(t *testing.T) { |
| 4506 |
for name, policy := range map[string]WriteTimeoutPolicy{ |
| 4507 |
"Retry": WriteTimeoutPolicyRetry, |
| 4508 |
"Close": WriteTimeoutPolicyClose, |
| 4509 |
} { |
| 4510 |
t.Run(name, func(t *testing.T) { |
| 4511 |
opts := DefaultOptions() |
| 4512 |
opts.PingInterval = 250 * time.Millisecond |
| 4513 |
opts.WriteDeadline = 100 * time.Millisecond |
| 4514 |
opts.WriteTimeout = policy |
| 4515 |
s := RunServer(opts) |
| 4516 |
defer s.Shutdown() |
| 4517 |
|
| 4518 |
nc1 := natsConnect(t, fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) |
| 4519 |
defer nc1.Close() |
| 4520 |
|
| 4521 |
_, err := nc1.Subscribe("test", func(_ *nats.Msg) {}) |
| 4522 |
require_NoError(t, err) |
| 4523 |
|
| 4524 |
nc2 := natsConnect(t, fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) |
| 4525 |
defer nc2.Close() |
| 4526 |
|
| 4527 |
cid, err := nc1.GetClientID() |
| 4528 |
require_NoError(t, err) |
| 4529 |
|
| 4530 |
client := s.getClient(cid) |
| 4531 |
client.mu.Lock() |
| 4532 |
client.out.wdl = 100 * time.Millisecond |
| 4533 |
client.nc = &writeTimeoutPolicyWriter{Conn: client.nc} |
| 4534 |
client.mu.Unlock() |
| 4535 |
|
| 4536 |
require_NoError(t, nc2.Publish("test", make([]byte, 1024*1024))) |
| 4537 |
|
| 4538 |
checkFor(t, 5*time.Second, 10*time.Millisecond, func() error { |
| 4539 |
client.mu.Lock() |
| 4540 |
defer client.mu.Unlock() |
| 4541 |
switch { |
| 4542 |
case !client.flags.isSet(connMarkedClosed): |
| 4543 |
return fmt.Errorf("connection not closed yet") |
| 4544 |
case policy == WriteTimeoutPolicyRetry && client.flags.isSet(isSlowConsumer): |
| 4545 |
// Retry policy should have marked the client as a slow consumer and |
| 4546 |
// continued to retry flushes. |
| 4547 |
return nil |
| 4548 |
case policy == WriteTimeoutPolicyClose && !client.flags.isSet(isSlowConsumer): |
| 4549 |
// Close policy shouldn't have marked the client as a slow consumer, |
| 4550 |
// it will just close it instead. |
| 4551 |
return nil |
| 4552 |
default: |
| 4553 |
return fmt.Errorf("client not in correct state yet") |
| 4554 |
} |
| 4555 |
}) |
| 4556 |
}) |
| 4557 |
} |
| 4558 |
} |
| 4559 |
|
| 4560 |
func TestFlushOutboundS2CompressionPoolBufferRecycling(t *testing.T) { |
| 4561 |
opts := DefaultOptions() |
| 4562 |
s := &Server{opts: opts} |
| 4563 |
|
| 4564 |
fakeConn := &testConnWritePartial{} |
| 4565 |
c := &client{srv: s, nc: fakeConn, kind: ROUTER} |
| 4566 |
c.initClient() |
| 4567 |
c.out.cw = s2.NewWriter(nil, s2.WriterConcurrency(1)) |
| 4568 |
|
| 4569 |
payload := make([]byte, 256) |
| 4570 |
for i := range payload { |
| 4571 |
payload[i] = byte(i) |
| 4572 |
} |
| 4573 |
|
| 4574 |
// Queue multiple buffers per iteration so each leaked pool |
| 4575 |
// buffer adds one extra allocation, making the leak obvious. |
| 4576 |
const numBuffers = 10 |
| 4577 |
|
| 4578 |
// Warm up: run a few iterations to populate the pool. |
| 4579 |
for i := 0; i < 5; i++ { |
| 4580 |
c.mu.Lock() |
| 4581 |
for j := 0; j < numBuffers; j++ { |
| 4582 |
c.queueOutbound(payload) |
| 4583 |
} |
| 4584 |
c.flushOutbound() |
| 4585 |
c.mu.Unlock() |
| 4586 |
} |
| 4587 |
|
| 4588 |
allocs := testing.AllocsPerRun(100, func() { |
| 4589 |
c.mu.Lock() |
| 4590 |
for j := 0; j < numBuffers; j++ { |
| 4591 |
c.queueOutbound(payload) |
| 4592 |
} |
| 4593 |
c.flushOutbound() |
| 4594 |
c.mu.Unlock() |
| 4595 |
}) |
| 4596 |
if allocs > 15 { |
| 4597 |
t.Fatalf("Too many allocs per iteration (%.1f); pool buffers are likely being leaked", allocs) |
| 4598 |
} |
| 4599 |
} |
| 4600 |
|
| 4601 |
func TestClientPingNoAuthUserExceptionsAndRestrictions(t *testing.T) { |
| 4602 |
conf := createConfFile(t, []byte(` |
| 4603 |
listen: "127.0.0.1:-1" |
| 4604 |
accounts { |
| 4605 |
A { users [{user: "foo", password: "pwd"}] } |
| 4606 |
} |
| 4607 |
no_auth_user: "foo" |
| 4608 |
cluster { |
| 4609 |
listen: "127.0.0.1:-1" |
| 4610 |
authorization { |
| 4611 |
user: "route_user" |
| 4612 |
password: "route_pwd" |
| 4613 |
timeout: 1 |
| 4614 |
} |
| 4615 |
} |
| 4616 |
leafnodes { |
| 4617 |
listen: "127.0.0.1:-1" |
| 4618 |
compression: off |
| 4619 |
authorization { |
| 4620 |
user: "leaf_user" |
| 4621 |
password: "leaf_pwd" |
| 4622 |
timeout: 1 |
| 4623 |
} |
| 4624 |
} |
| 4625 |
`)) |
| 4626 |
s, _ := RunServerWithConfig(conf) |
| 4627 |
defer s.Shutdown() |
| 4628 |
|
| 4629 |
opts := s.getOpts() |
| 4630 |
acc, err := s.LookupAccount("A") |
| 4631 |
require_NoError(t, err) |
| 4632 |
|
| 4633 |
readInfoLine := func(t *testing.T, conn net.Conn) { |
| 4634 |
t.Helper() |
| 4635 |
br := bufio.NewReader(conn) |
| 4636 |
line, _, err := br.ReadLine() |
| 4637 |
require_NoError(t, err) |
| 4638 |
require_True(t, len(line) >= 5) |
| 4639 |
require_Equal(t, string(line[:5]), "INFO ") |
| 4640 |
} |
| 4641 |
|
| 4642 |
t.Run("RouteNotAllowed", func(t *testing.T) { |
| 4643 |
conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", opts.Cluster.Port)) |
| 4644 |
require_NoError(t, err) |
| 4645 |
defer conn.Close() |
| 4646 |
readInfoLine(t, conn) |
| 4647 |
|
| 4648 |
// Send PING as the first command (not CONNECT). This should NOT |
| 4649 |
// trigger the NoAuthUser fast-path on a route connection. |
| 4650 |
_, err = conn.Write([]byte("PING\r\n")) |
| 4651 |
require_NoError(t, err) |
| 4652 |
|
| 4653 |
// The server should reject this connection. |
| 4654 |
require_NoError(t, conn.SetReadDeadline(time.Now().Add(2*time.Second))) |
| 4655 |
br := bufio.NewReader(conn) |
| 4656 |
line, _, err := br.ReadLine() |
| 4657 |
require_NoError(t, err) |
| 4658 |
require_NotEqual(t, string(line), "PONG") |
| 4659 |
require_Equal(t, s.NumRoutes(), 0) |
| 4660 |
checkAccClientsCount(t, acc, 0) |
| 4661 |
}) |
| 4662 |
|
| 4663 |
t.Run("RouteInjectionNotAllowed", func(t *testing.T) { |
| 4664 |
conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", opts.Cluster.Port)) |
| 4665 |
require_NoError(t, err) |
| 4666 |
defer conn.Close() |
| 4667 |
readInfoLine(t, conn) |
| 4668 |
|
| 4669 |
// Attempt to inject an RMSG directly without CONNECT. |
| 4670 |
// This simulates cross-account message injection via the route protocol. |
| 4671 |
_, err = conn.Write([]byte("RMSG $G foo 2\r\nok\r\n")) |
| 4672 |
require_NoError(t, err) |
| 4673 |
|
| 4674 |
// The server must reject this — either close the connection or |
| 4675 |
// return an error. It must NOT process the RMSG. |
| 4676 |
conn.SetReadDeadline(time.Now().Add(2 * time.Second)) |
| 4677 |
br := bufio.NewReader(conn) |
| 4678 |
_, _, _ = br.ReadLine() |
| 4679 |
// We expect either an -ERR or a closed connection (io.EOF / read error). |
| 4680 |
// Either way, no routes should be registered. |
| 4681 |
require_Equal(t, s.NumRoutes(), 0) |
| 4682 |
checkAccClientsCount(t, acc, 0) |
| 4683 |
}) |
| 4684 |
|
| 4685 |
t.Run("LeafNotAllowed", func(t *testing.T) { |
| 4686 |
conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", opts.LeafNode.Port)) |
| 4687 |
require_NoError(t, err) |
| 4688 |
defer conn.Close() |
| 4689 |
readInfoLine(t, conn) |
| 4690 |
|
| 4691 |
// Send PING as the first command (not CONNECT). This should NOT |
| 4692 |
// trigger the NoAuthUser fast-path on a leaf connection. |
| 4693 |
_, err = conn.Write([]byte("PING\r\n")) |
| 4694 |
require_NoError(t, err) |
| 4695 |
|
| 4696 |
// The server should reject this connection. |
| 4697 |
require_NoError(t, conn.SetReadDeadline(time.Now().Add(2*time.Second))) |
| 4698 |
br := bufio.NewReader(conn) |
| 4699 |
line, _, err := br.ReadLine() |
| 4700 |
require_NoError(t, err) |
| 4701 |
require_NotEqual(t, string(line), "PONG") |
| 4702 |
require_Equal(t, s.NumLeafNodes(), 0) |
| 4703 |
checkAccClientsCount(t, acc, 0) |
| 4704 |
}) |
| 4705 |
|
| 4706 |
t.Run("ClientAllowed", func(t *testing.T) { |
| 4707 |
// Verify that the NoAuthUser fast-path still works correctly on the |
| 4708 |
// client port — this is the intended use case. |
| 4709 |
conn, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", opts.Port)) |
| 4710 |
require_NoError(t, err) |
| 4711 |
readInfoLine(t, conn) |
| 4712 |
|
| 4713 |
// Send PING without CONNECT — this should succeed on the client port |
| 4714 |
// because NoAuthUser is configured. |
| 4715 |
_, err = conn.Write([]byte("PING\r\n")) |
| 4716 |
require_NoError(t, err) |
| 4717 |
|
| 4718 |
// Should get a PONG as expected as we expect to be dropped into the |
| 4719 |
// no auth user. |
| 4720 |
conn.SetReadDeadline(time.Now().Add(2 * time.Second)) |
| 4721 |
br := bufio.NewReader(conn) |
| 4722 |
line, _, err := br.ReadLine() |
| 4723 |
require_NoError(t, err) |
| 4724 |
require_Equal(t, string(line), "PONG") |
| 4725 |
checkAccClientsCount(t, acc, 1) |
| 4726 |
require_NoError(t, conn.Close()) |
| 4727 |
checkAccClientsCount(t, acc, 0) |
| 4728 |
}) |
| 4729 |
} |
| 4730 |
|
| 4731 |
func TestClientRepeatConnectSwitchesAccountAndCleansOldSubs(t *testing.T) { |
| 4732 |
for _, diffAcc := range []bool{true, false} { |
| 4733 |
title := "ToDifferentAccount" |
| 4734 |
if !diffAcc { |
| 4735 |
title = "SameAccount" |
| 4736 |
} |
| 4737 |
t.Run(title, func(t *testing.T) { |
| 4738 |
conf := createConfFile(t, []byte(` |
| 4739 |
listen: 127.0.0.1:-1 |
| 4740 |
accounts: { |
| 4741 |
A: { users: [ { user: ua, password: pa } ] } |
| 4742 |
B: { users: [ { user: ub, password: pb } ] } |
| 4743 |
} |
| 4744 |
`)) |
| 4745 |
|
| 4746 |
s, opts := RunServerWithConfig(conf) |
| 4747 |
defer s.Shutdown() |
| 4748 |
|
| 4749 |
accA, err := s.LookupAccount("A") |
| 4750 |
require_NoError(t, err) |
| 4751 |
accB, err := s.LookupAccount("B") |
| 4752 |
require_NoError(t, err) |
| 4753 |
|
| 4754 |
c, err := net.Dial("tcp", net.JoinHostPort(opts.Host, fmt.Sprintf("%d", opts.Port))) |
| 4755 |
require_NoError(t, err) |
| 4756 |
defer c.Close() |
| 4757 |
|
| 4758 |
// Consume INFO. |
| 4759 |
cr := bufio.NewReader(c) |
| 4760 |
line, _, err := cr.ReadLine() |
| 4761 |
require_NoError(t, err) |
| 4762 |
require_Contains(t, string(line), "INFO {") |
| 4763 |
|
| 4764 |
// First CONNECT into account A plus a subscription. |
| 4765 |
_, err = c.Write([]byte("CONNECT {\"verbose\":false,\"user\":\"ua\",\"pass\":\"pa\"}\r\nSUB foo 1\r\nPING\r\n")) |
| 4766 |
require_NoError(t, err) |
| 4767 |
line, _, err = cr.ReadLine() |
| 4768 |
require_NoError(t, err) |
| 4769 |
require_Equal(t, string(line), "PONG") |
| 4770 |
|
| 4771 |
// Confirm the sub landed in account A. |
| 4772 |
checkFor(t, time.Second, 15*time.Millisecond, func() error { |
| 4773 |
r := accA.sl.Match("foo") |
| 4774 |
if n := len(r.psubs); n != 1 { |
| 4775 |
return fmt.Errorf("expected 1 psub on foo in account A, got %d", n) |
| 4776 |
} |
| 4777 |
if n := accA.NumLocalConnections(); n != 1 { |
| 4778 |
return fmt.Errorf("expected 1 client in account A, got %d", n) |
| 4779 |
} |
| 4780 |
return nil |
| 4781 |
}) |
| 4782 |
|
| 4783 |
// Second CONNECT, re-authenticating... |
| 4784 |
if diffAcc { |
| 4785 |
// ..., into account B. |
| 4786 |
_, err = c.Write([]byte("CONNECT {\"verbose\":false,\"user\":\"ub\",\"pass\":\"pb\"}\r\nPING\r\n")) |
| 4787 |
} else { |
| 4788 |
// ..., into the same account A. |
| 4789 |
_, err = c.Write([]byte("CONNECT {\"verbose\":false,\"user\":\"ua\",\"pass\":\"pa\"}\r\nPING\r\n")) |
| 4790 |
} |
| 4791 |
require_NoError(t, err) |
| 4792 |
line, _, err = cr.ReadLine() |
| 4793 |
require_NoError(t, err) |
| 4794 |
require_Equal(t, string(line), "PONG") |
| 4795 |
|
| 4796 |
// Account A must no longer have the old sub (or the client if connected to B). |
| 4797 |
checkFor(t, time.Second, 15*time.Millisecond, func() error { |
| 4798 |
r := accA.sl.Match("foo") |
| 4799 |
if n := len(r.psubs); n != 0 { |
| 4800 |
return fmt.Errorf("expected 0 psubs on foo in account A after re-CONNECT, got %d", n) |
| 4801 |
} |
| 4802 |
var ea, eb int |
| 4803 |
if diffAcc { |
| 4804 |
eb = 1 |
| 4805 |
} else { |
| 4806 |
ea = 1 |
| 4807 |
} |
| 4808 |
if n := accA.NumLocalConnections(); n != ea { |
| 4809 |
return fmt.Errorf("expected %d clients in account A after re-CONNECT, got %d", ea, n) |
| 4810 |
} |
| 4811 |
if n := accB.NumLocalConnections(); n != eb { |
| 4812 |
return fmt.Errorf("expected %d client in account B after re-CONNECT, got %d", eb, n) |
| 4813 |
} |
| 4814 |
return nil |
| 4815 |
}) |
| 4816 |
|
| 4817 |
// Publishing foo on account A must not be delivered to this client. |
| 4818 |
ncA := natsConnect(t, s.ClientURL(), nats.UserInfo("ua", "pa")) |
| 4819 |
defer ncA.Close() |
| 4820 |
natsPub(t, ncA, "foo", []byte("should-not-arrive")) |
| 4821 |
natsFlush(t, ncA) |
| 4822 |
|
| 4823 |
require_NoError(t, c.SetReadDeadline(time.Now().Add(150*time.Millisecond))) |
| 4824 |
if line, _, err = cr.ReadLine(); err == nil { |
| 4825 |
t.Fatalf("Did not expect to read anything from stale sub, got %q", line) |
| 4826 |
} |
| 4827 |
}) |
| 4828 |
} |
| 4829 |
} |
| 4830 |
|
| 4831 |
func TestClientMsgsMetric(t *testing.T) { |
| 4832 |
o1 := DefaultOptions() |
| 4833 |
o1.ServerName = "S1" |
| 4834 |
s1 := RunServer(o1) |
| 4835 |
defer s1.Shutdown() |
| 4836 |
|
| 4837 |
o2 := DefaultOptions() |
| 4838 |
o2.ServerName = "S2" |
| 4839 |
o2.Routes = RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d", o1.Cluster.Port)) |
| 4840 |
s2 := RunServer(o2) |
| 4841 |
defer s2.Shutdown() |
| 4842 |
|
| 4843 |
checkClusterFormed(t, s1, s2) |
| 4844 |
|
| 4845 |
ncS1 := natsConnect(t, s1.ClientURL(), nats.IgnoreDiscoveredServers()) |
| 4846 |
defer ncS1.Close() |
| 4847 |
|
| 4848 |
ncS2 := natsConnect(t, s2.ClientURL(), nats.IgnoreDiscoveredServers()) |
| 4849 |
defer ncS2.Close() |
| 4850 |
|
| 4851 |
// Echo the message back |
| 4852 |
natsSub(t, ncS1, "foo", func(m *nats.Msg) { m.Respond(m.Data) }) |
| 4853 |
natsSub(t, ncS2, "bar", func(m *nats.Msg) { m.Respond(m.Data) }) |
| 4854 |
ncS1.Flush() |
| 4855 |
ncS2.Flush() |
| 4856 |
|
| 4857 |
checkSubInterest(t, s1, globalAccountName, "bar", 5*time.Second) |
| 4858 |
checkSubInterest(t, s2, globalAccountName, "foo", 5*time.Second) |
| 4859 |
|
| 4860 |
// Request foo and bar from non-local servers, |
| 4861 |
// to make sure client messages are counted correctly. |
| 4862 |
fooMsg := "6bytes" |
| 4863 |
_, err := ncS2.Request("foo", []byte(fooMsg), 5*time.Second) |
| 4864 |
if err != nil { |
| 4865 |
t.Fatalf("Error on receiving: %v", err) |
| 4866 |
} |
| 4867 |
barMsg := "ninebytes" |
| 4868 |
_, err = ncS1.Request("bar", []byte(barMsg), 5*time.Second) |
| 4869 |
if err != nil { |
| 4870 |
t.Fatalf("Error on receiving: %v", err) |
| 4871 |
} |
| 4872 |
err = ncS1.Flush() |
| 4873 |
if err != nil { |
| 4874 |
t.Fatalf("Error on flushing connection: %v", err) |
| 4875 |
} |
| 4876 |
err = ncS2.Flush() |
| 4877 |
if err != nil { |
| 4878 |
t.Fatalf("Error on flushing connection: %v", err) |
| 4879 |
} |
| 4880 |
|
| 4881 |
// In/out Msgs/Bytes include routed messages, including STATSZ heartbeats too. |
| 4882 |
// So there should be at least 2 foo and 2 bar messages received and sent by each server, |
| 4883 |
// but depending on the test timing, we may also catch some STATSZ messages. |
| 4884 |
require_True(t, atomic.LoadInt64(&s1.inMsgs) >= 4) |
| 4885 |
require_True(t, atomic.LoadInt64(&s1.inBytes) >= int64(len(fooMsg)*2+len(barMsg)*2)) |
| 4886 |
require_True(t, atomic.LoadInt64(&s2.inMsgs) >= 4) |
| 4887 |
require_True(t, atomic.LoadInt64(&s2.inBytes) >= int64(len(fooMsg)*2+len(barMsg)*2)) |
| 4888 |
|
| 4889 |
require_True(t, atomic.LoadInt64(&s1.outMsgs) >= 4) |
| 4890 |
require_True(t, atomic.LoadInt64(&s1.outBytes) >= int64(len(fooMsg)*2+len(barMsg)*2)) |
| 4891 |
require_True(t, atomic.LoadInt64(&s2.outMsgs) >= 4) |
| 4892 |
require_True(t, atomic.LoadInt64(&s2.outBytes) >= int64(len(fooMsg)*2+len(barMsg)*2)) |
| 4893 |
|
| 4894 |
// In/out ClientMsgs/Bytes only count client messages. |
| 4895 |
require_Equal(t, atomic.LoadInt64(&s1.inClientMsgs), 2) |
| 4896 |
require_Equal(t, atomic.LoadInt64(&s1.inClientBytes), int64(len(fooMsg)+len(barMsg))) |
| 4897 |
require_Equal(t, atomic.LoadInt64(&s2.inClientMsgs), 2) |
| 4898 |
require_Equal(t, atomic.LoadInt64(&s2.inClientBytes), int64(len(fooMsg)+len(barMsg))) |
| 4899 |
|
| 4900 |
require_Equal(t, atomic.LoadInt64(&s1.outClientMsgs), 2) |
| 4901 |
require_Equal(t, atomic.LoadInt64(&s1.outClientBytes), int64(len(fooMsg)+len(barMsg))) |
| 4902 |
require_Equal(t, atomic.LoadInt64(&s2.outClientMsgs), 2) |
| 4903 |
require_Equal(t, atomic.LoadInt64(&s2.outClientBytes), int64(len(fooMsg)+len(barMsg))) |
| 4904 |
|
| 4905 |
// Now test that messages delivered as part of queue subscriptions are counted correctly |
| 4906 |
natsQueueSub(t, ncS1, "orders.new", "workers", func(m *nats.Msg) { m.Respond(m.Data) }) |
| 4907 |
natsQueueSub(t, ncS2, "orders.new", "workers", func(m *nats.Msg) { m.Respond(m.Data) }) |
| 4908 |
ncS1.Flush() |
| 4909 |
ncS2.Flush() |
| 4910 |
|
| 4911 |
orderMsg := "order" |
| 4912 |
_, err = ncS1.Request("orders.new", []byte(orderMsg), 5*time.Second) |
| 4913 |
if err != nil { |
| 4914 |
t.Fatalf("Error on receiving: %v", err) |
| 4915 |
} |
| 4916 |
err = ncS1.Flush() |
| 4917 |
if err != nil { |
| 4918 |
t.Fatalf("Error on flushing connection: %v", err) |
| 4919 |
} |
| 4920 |
err = ncS2.Flush() |
| 4921 |
if err != nil { |
| 4922 |
t.Fatalf("Error on flushing connection: %v", err) |
| 4923 |
} |
| 4924 |
|
| 4925 |
// We do not know which client the message will be routed to, so check both cases. |
| 4926 |
// If the queue subscriber on S1 receives the message, S1 will send total 4 client messages: |
| 4927 |
// 2 messages from previous step, qsub message, and echo reply. |
| 4928 |
if atomic.LoadInt64(&s1.outClientMsgs) == 4 { |
| 4929 |
require_Equal(t, atomic.LoadInt64(&s2.outClientMsgs), 2) |
| 4930 |
|
| 4931 |
require_Equal(t, atomic.LoadInt64(&s1.outClientBytes), |
| 4932 |
int64(len(fooMsg)+len(barMsg)+len(orderMsg)*2)) |
| 4933 |
|
| 4934 |
require_Equal(t, atomic.LoadInt64(&s2.outClientBytes), |
| 4935 |
int64(len(fooMsg)+len(barMsg))) |
| 4936 |
|
| 4937 |
// If message received by S2, both servers will have 3 messages total. |
| 4938 |
} else if atomic.LoadInt64(&s1.outClientMsgs) == 3 { |
| 4939 |
require_Equal(t, atomic.LoadInt64(&s2.outClientMsgs), 3) |
| 4940 |
|
| 4941 |
require_Equal(t, atomic.LoadInt64(&s1.outClientBytes), |
| 4942 |
int64(len(fooMsg)+len(barMsg)+len(orderMsg))) |
| 4943 |
|
| 4944 |
require_Equal(t, atomic.LoadInt64(&s2.outClientBytes), |
| 4945 |
int64(len(fooMsg)+len(barMsg)+len(orderMsg))) |
| 4946 |
|
| 4947 |
} else { |
| 4948 |
t.Fatalf("Did not get expected outClientMsg/Bytes for message sent on qsub") |
| 4949 |
} |
| 4950 |
} |