Debian Codegraph @

server/mqtt_test.go

raw
1 // Copyright 2020-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 //go:build !skip_mqtt_tests
15
16 package server
17
18 import (
19 "bufio"
20 "bytes"
21 "crypto/tls"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "io"
26 "math/rand"
27 "net"
28 "os"
29 "path/filepath"
30 "reflect"
31 "strings"
32 "sync"
33 "testing"
34 "time"
35
36 "github.com/nats-io/jwt/v2"
37 "github.com/nats-io/nats.go"
38 "github.com/nats-io/nkeys"
39 "github.com/nats-io/nuid"
40 )
41
42 var testMQTTTimeout = 10 * time.Second
43
44 var jsClusterTemplWithLeafAndMQTT = `
45 listen: 127.0.0.1:-1
46 server_name: %s
47 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
48
49 {{leaf}}
50
51 cluster {
52 name: %s
53 listen: 127.0.0.1:%d
54 routes = [%s]
55 }
56
57 mqtt {
58 listen: 127.0.0.1:-1
59 }
60
61 # For access to system account.
62 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } }
63 `
64
65 type mqttWrapAsWs struct {
66 net.Conn
67 t testing.TB
68 br *bufio.Reader
69 tmp []byte
70 }
71
72 func (c *mqttWrapAsWs) Write(p []byte) (int, error) {
73 proto := testWSCreateClientMsg(wsBinaryMessage, 1, true, false, p)
74 return c.Conn.Write(proto)
75 }
76
77 func (c *mqttWrapAsWs) Read(p []byte) (int, error) {
78 for {
79 if n := len(c.tmp); n > 0 {
80 if len(p) < n {
81 n = len(p)
82 }
83 copy(p, c.tmp[:n])
84 c.tmp = c.tmp[n:]
85 return n, nil
86 }
87 c.tmp = testWSReadFrame(c.t, c.br)
88 }
89 }
90
91 func testMQTTReadPacket(t testing.TB, r *mqttReader) (byte, int) {
92 t.Helper()
93
94 var b byte
95 var pl int
96 var err error
97
98 rd := r.reader
99
100 fill := func() []byte {
101 t.Helper()
102 var buf [512]byte
103
104 n, err := rd.Read(buf[:])
105 if err != nil {
106 t.Fatalf("Error reading data: %v", err)
107 }
108 return copyBytes(buf[:n])
109 }
110
111 rd.SetReadDeadline(time.Now().Add(testMQTTTimeout))
112 for {
113 r.pstart = r.pos
114 if !r.hasMore() {
115 r.reset(fill())
116 continue
117 }
118 b, err = r.readByte("packet type")
119 if err != nil {
120 t.Fatalf("Error reading packet: %v", err)
121 }
122 var complete bool
123 pl, complete, err = r.readPacketLen(MAX_PAYLOAD_SIZE)
124 if err != nil {
125 t.Fatalf("Error reading packet: %v", err)
126 }
127 if !complete {
128 r.reset(fill())
129 continue
130 }
131 break
132 }
133 rd.SetReadDeadline(time.Time{})
134 return b, pl
135 }
136
137 func testMQTTReadPIPacket(expectedType byte, t testing.TB, r *mqttReader, expectedPI uint16) {
138 t.Helper()
139 b, _ := testMQTTReadPacket(t, r)
140 if pt := b & mqttPacketMask; pt != expectedType {
141 t.Fatalf("Expected packet %x, got %x", expectedType, pt)
142 }
143 rpi, err := r.readUint16("packet identifier")
144 if err != nil || rpi != expectedPI {
145 t.Fatalf("Expected PI %v got: %v, err=%v", expectedPI, rpi, err)
146 }
147 }
148
149 func TestMQTTReader(t *testing.T) {
150 r := &mqttReader{}
151 r.reset([]byte{0, 2, 'a', 'b'})
152 bs, err := r.readBytes("", false)
153 if err != nil {
154 t.Fatal(err)
155 }
156 sbs := string(bs)
157 if sbs != "ab" {
158 t.Fatalf(`expected "ab", got %q`, sbs)
159 }
160
161 r.reset([]byte{0, 2, 'a', 'b'})
162 bs, err = r.readBytes("", true)
163 if err != nil {
164 t.Fatal(err)
165 }
166 bs[0], bs[1] = 'c', 'd'
167 if bytes.Equal(bs, r.buf[2:]) {
168 t.Fatal("readBytes should have returned a copy")
169 }
170
171 r.reset([]byte{'a', 'b'})
172 if b, err := r.readByte(""); err != nil || b != 'a' {
173 t.Fatalf("Error reading byte: b=%v err=%v", b, err)
174 }
175 if !r.hasMore() {
176 t.Fatal("expected to have more, did not")
177 }
178 if b, err := r.readByte(""); err != nil || b != 'b' {
179 t.Fatalf("Error reading byte: b=%v err=%v", b, err)
180 }
181 if r.hasMore() {
182 t.Fatal("expected to not have more")
183 }
184 if _, err := r.readByte("test"); err == nil || !strings.Contains(err.Error(), "error reading test") {
185 t.Fatalf("unexpected error: %v", err)
186 }
187
188 r.reset([]byte{0, 2, 'a', 'b'})
189 if s, err := r.readString(""); err != nil || s != "ab" {
190 t.Fatalf("Error reading string: s=%q err=%v", s, err)
191 }
192
193 r.reset([]byte{10})
194 if _, err := r.readUint16("uint16"); err == nil || !strings.Contains(err.Error(), "error reading uint16") {
195 t.Fatalf("unexpected error: %v", err)
196 }
197
198 r.reset([]byte{0x82, 0xff, 0x3})
199 l, _, err := r.readVarInt()
200 if err != nil {
201 t.Fatal("error getting packet len")
202 }
203 if l != 0xff82 {
204 t.Fatalf("expected length 0xff82 got 0x%x", l)
205 }
206 r.reset([]byte{0xff, 0xff, 0xff, 0xff, 0xff})
207 if _, _, err := r.readVarInt(); err == nil || !strings.Contains(err.Error(), "malformed") {
208 t.Fatalf("unexpected error: %v", err)
209 }
210
211 r.reset([]byte{0, 2, 'a', 'b', mqttPacketPub, 0x82, 0xff, 0x3})
212 r.readString("")
213 for i := 0; i < 2; i++ {
214 r.pstart = r.pos
215 b, err := r.readByte("")
216 if err != nil {
217 t.Fatalf("Error reading byte: %v", err)
218 }
219 if pt := b & mqttPacketMask; pt != mqttPacketPub {
220 t.Fatalf("Unexpected byte: %v", b)
221 }
222 pl, complete, err := r.readPacketLen(MAX_PAYLOAD_SIZE)
223 if err != nil {
224 t.Fatalf("Unexpected error: %v", err)
225 }
226 if complete {
227 t.Fatal("Expected to be incomplete")
228 }
229 if pl != 0 {
230 t.Fatalf("Expected pl to be 0, got %v", pl)
231 }
232 if i > 0 {
233 break
234 }
235 if !bytes.Equal(r.pbuf, []byte{mqttPacketPub, 0x82, 0xff, 0x3}) {
236 t.Fatalf("Invalid recorded partial: %v", r.pbuf)
237 }
238 r.reset([]byte{'a', 'b', 'c'})
239 if !bytes.Equal(r.buf, []byte{mqttPacketPub, 0x82, 0xff, 0x3, 'a', 'b', 'c'}) {
240 t.Fatalf("Invalid buffer: %v", r.buf)
241 }
242 if r.pbuf != nil {
243 t.Fatalf("Partial buffer should have been reset, got %v", r.pbuf)
244 }
245 if r.pos != 0 {
246 t.Fatalf("Pos should have been reset, got %v", r.pos)
247 }
248 if r.pstart != 0 {
249 t.Fatalf("Pstart should have been reset, got %v", r.pstart)
250 }
251 }
252 // On second pass, the pbuf should have been extended with 'abc'
253 if !bytes.Equal(r.pbuf, []byte{mqttPacketPub, 0x82, 0xff, 0x3, 'a', 'b', 'c'}) {
254 t.Fatalf("Invalid recorded partial: %v", r.pbuf)
255 }
256 }
257
258 func TestMQTTWriter(t *testing.T) {
259 w := newMQTTWriter(0)
260 w.WriteUint16(1234)
261
262 r := &mqttReader{}
263 r.reset(w.Bytes())
264 if v, err := r.readUint16(""); err != nil || v != 1234 {
265 t.Fatalf("unexpected value: v=%v err=%v", v, err)
266 }
267
268 w.Reset()
269 w.WriteString("test")
270 r.reset(w.Bytes())
271 if len(r.buf) != 6 {
272 t.Fatalf("Expected 2 bytes size before string, got %v", r.buf)
273 }
274
275 w.Reset()
276 w.WriteBytes([]byte("test"))
277 r.reset(w.Bytes())
278 if len(r.buf) != 6 {
279 t.Fatalf("Expected 2 bytes size before bytes, got %v", r.buf)
280 }
281
282 ints := []int{
283 0, 1, 127, 128, 16383, 16384, 2097151, 2097152, 268435455,
284 }
285 lens := []int{
286 1, 1, 1, 2, 2, 3, 3, 4, 4,
287 }
288
289 tl := 0
290 w.Reset()
291 for i, v := range ints {
292 w.WriteVarInt(v)
293 tl += lens[i]
294 if tl != w.Len() {
295 t.Fatalf("expected len %d, got %d", tl, w.Len())
296 }
297 }
298
299 r.reset(w.Bytes())
300 for _, v := range ints {
301 x, _, _ := r.readVarInt()
302 if v != x {
303 t.Fatalf("expected %d, got %d", v, x)
304 }
305 }
306 }
307
308 func TestMQTTIncompleteConnectMaxPayloadViolationDisconnects(t *testing.T) {
309 const maxPayload = 1024
310 const remainingLength = maxPayload + 1
311
312 o := testMQTTDefaultOptions()
313 o.MaxPayload = maxPayload
314 s := testMQTTRunServer(t, o)
315 defer testMQTTShutdownServer(s)
316
317 c, err := net.Dial("tcp", net.JoinHostPort(o.MQTT.Host, fmt.Sprintf("%d", o.MQTT.Port)))
318 require_NoError(t, err)
319 defer c.Close()
320
321 w := newMQTTWriter(0)
322 w.WriteByte(mqttPacketConnect)
323 w.WriteVarInt(remainingLength)
324 w.Write(bytes.Repeat([]byte{'A'}, maxPayload))
325
326 _, err = testMQTTWrite(c, w.Bytes())
327 require_NoError(t, err)
328
329 testMQTTExpectDisconnect(t, c)
330 }
331
332 func TestMQTTPacketLenMaxPayloadViolation(t *testing.T) {
333 const maxPayload = 1024
334
335 w := newMQTTWriter(0)
336 w.WriteByte(mqttPacketConnect)
337 w.WriteVarInt(maxPayload)
338 w.Write(bytes.Repeat([]byte{'A'}, maxPayload))
339
340 r := &mqttReader{}
341 r.reset(w.Bytes())
342 r.pstart = r.pos
343
344 _, err := r.readByte("packet type")
345 require_NoError(t, err)
346
347 packetLen, complete, err := r.readPacketLen(maxPayload)
348 require_Error(t, err, ErrMaxPayload)
349 require_False(t, complete)
350 require_Equal(t, packetLen, w.Len())
351 require_Equal(t, len(r.pbuf), 0)
352 }
353
354 func testMQTTDefaultOptions() *Options {
355 o := DefaultOptions()
356 o.ServerName = nuid.Next()
357 o.Cluster.Port = 0
358 o.Gateway.Name = ""
359 o.Gateway.Port = 0
360 o.LeafNode.Port = 0
361 o.Websocket.Port = 0
362 o.MQTT.Host = "127.0.0.1"
363 o.MQTT.Port = -1
364 o.JetStream = true
365 return o
366 }
367
368 func testMQTTRunServer(t testing.TB, o *Options) *Server {
369 t.Helper()
370 o.NoLog = false
371 if o.StoreDir == _EMPTY_ {
372 o.StoreDir = t.TempDir()
373 }
374 s, err := NewServer(o)
375 if err != nil {
376 t.Fatalf("Error creating server: %v", err)
377 }
378 l := &DummyLogger{}
379 s.SetLogger(l, true, true)
380 s.Start()
381 if err := s.readyForConnections(3 * time.Second); err != nil {
382 testMQTTShutdownServer(s)
383 t.Fatal(err)
384 }
385 return s
386 }
387
388 func testMQTTShutdownRestartedServer(s **Server) {
389 srv := *s
390 testMQTTShutdownServer(srv)
391 *s = nil
392 }
393
394 func testMQTTShutdownServer(s *Server) {
395 if c := s.JetStreamConfig(); c != nil {
396 dir := strings.TrimSuffix(c.StoreDir, JetStreamStoreDir)
397 defer os.RemoveAll(dir)
398 }
399 s.Shutdown()
400 }
401
402 func testMQTTDefaultTLSOptions(t *testing.T, verify bool) *Options {
403 t.Helper()
404 o := testMQTTDefaultOptions()
405 tc := &TLSConfigOpts{
406 CertFile: "../test/configs/certs/server-cert.pem",
407 KeyFile: "../test/configs/certs/server-key.pem",
408 CaFile: "../test/configs/certs/ca.pem",
409 Verify: verify,
410 }
411 var err error
412 o.MQTT.TLSConfig, err = GenTLSConfig(tc)
413 o.MQTT.TLSTimeout = 2.0
414 if err != nil {
415 t.Fatalf("Error creating tls config: %v", err)
416 }
417 return o
418 }
419
420 func TestMQTTServerNameRequired(t *testing.T) {
421 conf := createConfFile(t, []byte(`
422 cluster {
423 port: -1
424 }
425 mqtt {
426 port: -1
427 }
428 `))
429 o, err := ProcessConfigFile(conf)
430 if err != nil {
431 t.Fatalf("Error processing config file: %v", err)
432 }
433 if _, err := NewServer(o); err == nil || err.Error() != errMQTTServerNameMustBeSet.Error() {
434 t.Fatalf("Expected error about requiring server name to be set, got %v", err)
435 }
436
437 conf = createConfFile(t, []byte(`
438 mqtt {
439 port: -1
440 }
441 `))
442 o, err = ProcessConfigFile(conf)
443 if err != nil {
444 t.Fatalf("Error processing config file: %v", err)
445 }
446 if _, err := NewServer(o); err == nil || err.Error() != errMQTTStandaloneNeedsJetStream.Error() {
447 t.Fatalf(`Expected errMQTTStandaloneNeedsJetStream ("next in line"), got %v`, err)
448 }
449 }
450
451 func TestMQTTStandaloneRequiresJetStream(t *testing.T) {
452 conf := createConfFile(t, []byte(`
453 server_name: mqtt
454 mqtt {
455 port: -1
456 tls {
457 cert_file: "./configs/certs/server.pem"
458 key_file: "./configs/certs/key.pem"
459 }
460 }
461 `))
462 o, err := ProcessConfigFile(conf)
463 if err != nil {
464 t.Fatalf("Error processing config file: %v", err)
465 }
466 if _, err := NewServer(o); err == nil || err.Error() != errMQTTStandaloneNeedsJetStream.Error() {
467 t.Fatalf("Expected error about requiring JetStream in standalone mode, got %v", err)
468 }
469 }
470
471 func TestMQTTConfig(t *testing.T) {
472 conf := createConfFile(t, []byte(fmt.Sprintf(`
473 jetstream {
474 store_dir = %q
475 }
476 server_name: mqtt
477 mqtt {
478 port: -1
479 tls {
480 cert_file: "./configs/certs/server.pem"
481 key_file: "./configs/certs/key.pem"
482 }
483 }
484 `, t.TempDir())))
485 s, o := RunServerWithConfig(conf)
486 defer testMQTTShutdownServer(s)
487 if o.MQTT.TLSConfig == nil {
488 t.Fatal("expected TLS config to be set")
489 }
490 }
491
492 func TestMQTTValidateOptions(t *testing.T) {
493 nmqtto := DefaultOptions()
494 mqtto := testMQTTDefaultOptions()
495 for _, test := range []struct {
496 name string
497 getOpts func() *Options
498 err error
499 }{
500 {"mqtt disabled", func() *Options { return nmqtto.Clone() }, nil},
501 {"mqtt username not allowed if users specified", func() *Options {
502 o := mqtto.Clone()
503 o.Users = []*User{{Username: "abc", Password: "pwd"}}
504 o.MQTT.Username = "b"
505 o.MQTT.Password = "pwd"
506 return o
507 }, errMQTTUserMixWithUsersNKeys},
508 {"mqtt token not allowed if users specified", func() *Options {
509 o := mqtto.Clone()
510 o.Nkeys = []*NkeyUser{{Nkey: "abc"}}
511 o.MQTT.Token = "mytoken"
512 return o
513 }, errMQTTTokenMixWIthUsersNKeys},
514 {"ack wait should be >=0", func() *Options {
515 o := mqtto.Clone()
516 o.MQTT.AckWait = -10 * time.Second
517 return o
518 }, errMQTTAckWaitMustBePositive},
519 {"js api timeout should be >=0", func() *Options {
520 o := mqtto.Clone()
521 o.MQTT.JSAPITimeout = -10 * time.Second
522 return o
523 }, errMQTTJSAPITimeoutMustBePositive},
524 } {
525 t.Run(test.name, func(t *testing.T) {
526 err := validateMQTTOptions(test.getOpts())
527 if test.err == nil && err != nil {
528 t.Fatalf("Unexpected error: %v", err)
529 } else if test.err != nil && (err == nil || err.Error() != test.err.Error()) {
530 t.Fatalf("Expected error to contain %q, got %v", test.err, err)
531 }
532 })
533 }
534 }
535
536 func TestMQTTParseOptions(t *testing.T) {
537 for _, test := range []struct {
538 name string
539 content string
540 checkOpt func(*MQTTOpts) error
541 err string
542 }{
543 // Negative tests
544 {"bad type", "mqtt: []", nil, "to be a map"},
545 {"bad listen", "mqtt: { listen: [] }", nil, "port or host:port"},
546 {"bad port", `mqtt: { port: "abc" }`, nil, "not int64"},
547 {"bad host", `mqtt: { host: 123 }`, nil, "not string"},
548 {"bad tls", `mqtt: { tls: 123 }`, nil, "not map[string]interface {}"},
549 {"unknown field", `mqtt: { this_does_not_exist: 123 }`, nil, "unknown"},
550 {"ack wait", `mqtt: {ack_wait: abc}`, nil, "invalid duration"},
551 {"max ack pending", `mqtt: {max_ack_pending: abc}`, nil, "not int64"},
552 {"max ack pending too high", `mqtt: {max_ack_pending: 12345678}`, nil, "invalid value"},
553 {"js_api_timeout bad duration", `mqtt: {js_api_timeout: abc}`, nil, "invalid duration"},
554 // Positive tests
555 {"tls gen fails", `
556 mqtt {
557 tls {
558 cert_file: "./configs/certs/server.pem"
559 }
560 }`, nil, "missing 'key_file'"},
561 {"listen port only", `mqtt { listen: 1234 }`, func(o *MQTTOpts) error {
562 if o.Port != 1234 {
563 return fmt.Errorf("expected 1234, got %v", o.Port)
564 }
565 return nil
566 }, ""},
567 {"listen host and port", `mqtt { listen: "localhost:1234" }`, func(o *MQTTOpts) error {
568 if o.Host != "localhost" || o.Port != 1234 {
569 return fmt.Errorf("expected localhost:1234, got %v:%v", o.Host, o.Port)
570 }
571 return nil
572 }, ""},
573 {"host", `mqtt { host: "localhost" }`, func(o *MQTTOpts) error {
574 if o.Host != "localhost" {
575 return fmt.Errorf("expected localhost, got %v", o.Host)
576 }
577 return nil
578 }, ""},
579 {"port", `mqtt { port: 1234 }`, func(o *MQTTOpts) error {
580 if o.Port != 1234 {
581 return fmt.Errorf("expected 1234, got %v", o.Port)
582 }
583 return nil
584 }, ""},
585 {"tls config",
586 `
587 mqtt {
588 tls {
589 cert_file: "./configs/certs/server.pem"
590 key_file: "./configs/certs/key.pem"
591 }
592 }
593 `, func(o *MQTTOpts) error {
594 if o.TLSConfig == nil {
595 return fmt.Errorf("TLSConfig should have been set")
596 }
597 return nil
598 }, ""},
599 {"no auth user",
600 `
601 mqtt {
602 no_auth_user: "noauthuser"
603 }
604 `, func(o *MQTTOpts) error {
605 if o.NoAuthUser != "noauthuser" {
606 return fmt.Errorf("Invalid NoAuthUser value: %q", o.NoAuthUser)
607 }
608 return nil
609 }, ""},
610 {"auth block",
611 `
612 mqtt {
613 authorization {
614 user: "mqttuser"
615 password: "pwd"
616 token: "token"
617 timeout: 2.0
618 }
619 }
620 `, func(o *MQTTOpts) error {
621 if o.Username != "mqttuser" || o.Password != "pwd" || o.Token != "token" || o.AuthTimeout != 2.0 {
622 return fmt.Errorf("Invalid auth block: %+v", o)
623 }
624 return nil
625 }, ""},
626 {"auth timeout as int",
627 `
628 mqtt {
629 authorization {
630 timeout: 2
631 }
632 }
633 `, func(o *MQTTOpts) error {
634 if o.AuthTimeout != 2.0 {
635 return fmt.Errorf("Invalid auth timeout: %v", o.AuthTimeout)
636 }
637 return nil
638 }, ""},
639 {"ack wait",
640 `
641 mqtt {
642 ack_wait: "10s"
643 }
644 `, func(o *MQTTOpts) error {
645 if o.AckWait != 10*time.Second {
646 return fmt.Errorf("Invalid ack wait: %v", o.AckWait)
647 }
648 return nil
649 }, ""},
650 {"max ack pending",
651 `
652 mqtt {
653 max_ack_pending: 123
654 }
655 `, func(o *MQTTOpts) error {
656 if o.MaxAckPending != 123 {
657 return fmt.Errorf("Invalid max ack pending: %v", o.MaxAckPending)
658 }
659 return nil
660 }, ""},
661 {"reject_qos2_publish",
662 `
663 mqtt {
664 reject_qos2_publish: true
665 }
666 `, func(o *MQTTOpts) error {
667 if !o.rejectQoS2Pub {
668 return fmt.Errorf("Invalid: expected rejectQoS2Pub to be set")
669 }
670 return nil
671 }, ""},
672 {"downgrade_qos2_subscribe",
673 `
674 mqtt {
675 downgrade_qos2_subscribe: true
676 }
677 `, func(o *MQTTOpts) error {
678 if !o.downgradeQoS2Sub {
679 return fmt.Errorf("Invalid: expected downgradeQoS2Sub to be set")
680 }
681 return nil
682 }, ""},
683 {"js_api_timeout",
684 `
685 mqtt {
686 js_api_timeout: "60s"
687 }
688 `, func(o *MQTTOpts) error {
689 if o.JSAPITimeout != 60*time.Second {
690 return fmt.Errorf("Invalid JS API timeout: %v", o.JSAPITimeout)
691 }
692 return nil
693 }, ""},
694 } {
695 t.Run(test.name, func(t *testing.T) {
696 conf := createConfFile(t, []byte(test.content))
697 o, err := ProcessConfigFile(conf)
698 if test.err != _EMPTY_ {
699 if err == nil || !strings.Contains(err.Error(), test.err) {
700 t.Fatalf("For content: %q, expected error about %q, got %v", test.content, test.err, err)
701 }
702 return
703 } else if err != nil {
704 t.Fatalf("Unexpected error for content %q: %v", test.content, err)
705 }
706 if err := test.checkOpt(&o.MQTT); err != nil {
707 t.Fatalf("Incorrect option for content %q: %v", test.content, err.Error())
708 }
709 })
710 }
711 }
712
713 func TestMQTTStart(t *testing.T) {
714 o := testMQTTDefaultOptions()
715 s := testMQTTRunServer(t, o)
716 defer testMQTTShutdownServer(s)
717
718 nc, err := net.Dial("tcp", net.JoinHostPort(o.MQTT.Host, fmt.Sprintf("%d", o.MQTT.Port)))
719 if err != nil {
720 t.Fatalf("Unable to create tcp connection to mqtt port: %v", err)
721 }
722 nc.Close()
723
724 // Check failure to start due to port in use
725 o2 := testMQTTDefaultOptions()
726 o2.MQTT.Port = o.MQTT.Port
727 s2, err := NewServer(o2)
728 if err != nil {
729 t.Fatalf("Error creating server: %v", err)
730 }
731 defer s2.Shutdown()
732 l := &captureFatalLogger{fatalCh: make(chan string, 1)}
733 s2.SetLogger(l, false, false)
734 s2.Start()
735
736 select {
737 case e := <-l.fatalCh:
738 if !strings.Contains(e, "Unable to listen for MQTT connections") {
739 t.Fatalf("Unexpected error: %q", e)
740 }
741 case <-time.After(time.Second):
742 t.Fatal("Should have gotten a fatal error")
743 }
744 }
745
746 func TestMQTTTLS(t *testing.T) {
747 o := testMQTTDefaultTLSOptions(t, false)
748 s := testMQTTRunServer(t, o)
749 defer testMQTTShutdownServer(s)
750
751 c, _, err := testMQTTConnectRetryWithError(t, &mqttConnInfo{tls: true}, o.MQTT.Host, o.MQTT.Port, 0)
752 if err != nil {
753 t.Fatal(err)
754 }
755 c.Close()
756 c = nil
757 testMQTTShutdownServer(s)
758
759 // Force client cert verification
760 o = testMQTTDefaultTLSOptions(t, true)
761 s = testMQTTRunServer(t, o)
762 defer testMQTTShutdownServer(s)
763
764 c, _, err = testMQTTConnectRetryWithError(t, &mqttConnInfo{tls: true}, o.MQTT.Host, o.MQTT.Port, 0)
765 if err == nil || c != nil {
766 if c != nil {
767 c.Close()
768 }
769 t.Fatal("Handshake expected to fail since client did not provide cert")
770 }
771
772 // Add client cert.
773 tc := &TLSConfigOpts{
774 CertFile: "../test/configs/certs/client-cert.pem",
775 KeyFile: "../test/configs/certs/client-key.pem",
776 }
777 tlsc, err := GenTLSConfig(tc)
778 if err != nil {
779 t.Fatalf("Error generating tls config: %v", err)
780 }
781 tlsc.InsecureSkipVerify = true
782 c, _, err = testMQTTConnectRetryWithError(t, &mqttConnInfo{
783 tls: true,
784 tlsc: tlsc,
785 }, o.MQTT.Host, o.MQTT.Port, 0)
786 if err != nil {
787 t.Fatal(err)
788 }
789 c.Close()
790 c = nil
791 testMQTTShutdownServer(s)
792
793 // Lower TLS timeout so low that we should fail
794 o.MQTT.TLSTimeout = 0.001
795 s = testMQTTRunServer(t, o)
796 defer testMQTTShutdownServer(s)
797
798 nc, err := net.Dial("tcp", net.JoinHostPort(o.MQTT.Host, fmt.Sprintf("%d", o.MQTT.Port)))
799 if err != nil {
800 t.Fatalf("Unable to create tcp connection to mqtt port: %v", err)
801 }
802 defer nc.Close()
803 time.Sleep(100 * time.Millisecond)
804 tlsConn := tls.Client(nc, tlsc)
805 tlsConn.SetDeadline(time.Now().Add(time.Second))
806 if err := tlsConn.Handshake(); err == nil {
807 t.Fatal("Expected failure, did not get one")
808 }
809 }
810
811 type mqttConnInfo struct {
812 clientID string
813 cleanSess bool
814 keepAlive uint16
815 will *mqttWill
816 user string
817 pass string
818 ws bool
819 tls bool
820 tlsc *tls.Config
821 }
822
823 func testMQTTGetClient(t testing.TB, s *Server, clientID string) *client {
824 t.Helper()
825 var mc *client
826 s.mu.Lock()
827 for _, c := range s.clients {
828 c.mu.Lock()
829 if c.isMqtt() && c.mqtt.cid == clientID {
830 mc = c
831 }
832 c.mu.Unlock()
833 if mc != nil {
834 break
835 }
836 }
837 s.mu.Unlock()
838 if mc == nil {
839 t.Fatalf("Did not find client %q", clientID)
840 }
841 return mc
842 }
843
844 func testMQTTGetAccountSessionManager(t *testing.T, s *Server, cid string) *mqttAccountSessionManager {
845 t.Helper()
846 c := testMQTTGetClient(t, s, cid)
847 require_NotNil(t, c)
848 asm := c.mqtt.asm
849 require_NotNil(t, asm)
850 return asm
851 }
852
853 func testMQTTRead(c net.Conn) ([]byte, error) {
854 var buf [512]byte
855 // Make sure that test does not block
856 c.SetReadDeadline(time.Now().Add(testMQTTTimeout))
857 n, err := c.Read(buf[:])
858 if err != nil {
859 return nil, err
860 }
861 c.SetReadDeadline(time.Time{})
862 return copyBytes(buf[:n]), nil
863 }
864
865 func testMQTTWrite(c net.Conn, buf []byte) (int, error) {
866 c.SetWriteDeadline(time.Now().Add(testMQTTTimeout))
867 n, err := c.Write(buf)
868 c.SetWriteDeadline(time.Time{})
869 return n, err
870 }
871
872 func testMQTTConnect(t testing.TB, ci *mqttConnInfo, host string, port int) (net.Conn, *mqttReader) {
873 t.Helper()
874 return testMQTTConnectRetry(t, ci, host, port, 0)
875 }
876
877 func testMQTTConnectRetry(t testing.TB, ci *mqttConnInfo, host string, port int, retryCount int) (net.Conn, *mqttReader) {
878 t.Helper()
879 c, r, err := testMQTTConnectRetryWithError(t, ci, host, port, retryCount)
880 if err != nil {
881 t.Fatal(err)
882 }
883 return c, r
884 }
885
886 func testMQTTConnectRetryWithError(t testing.TB, ci *mqttConnInfo, host string, port int, retryCount int) (net.Conn, *mqttReader, error) {
887 retry := func(c net.Conn) bool {
888 if c != nil {
889 c.Close()
890 }
891 if retryCount == 0 {
892 return false
893 }
894 time.Sleep(time.Second)
895 retryCount--
896 return true
897 }
898
899 addr := net.JoinHostPort(host, fmt.Sprintf("%d", port))
900 var c net.Conn
901 var err error
902 RETRY:
903 if ci.ws {
904 var br *bufio.Reader
905 c, br, _, err = testNewWSClientWithError(t, testWSClientOptions{
906 host: host,
907 port: port,
908 noTLS: !ci.tls,
909 path: mqttWSPath,
910 })
911 if err == nil {
912 c = &mqttWrapAsWs{Conn: c, t: t, br: br}
913 }
914 } else {
915 c, err = net.Dial("tcp", addr)
916 if err == nil && ci.tls {
917 tc := ci.tlsc
918 if tc == nil {
919 tc = &tls.Config{InsecureSkipVerify: true}
920 }
921 c = tls.Client(c, tc)
922 c.SetDeadline(time.Now().Add(time.Second))
923 err = c.(*tls.Conn).Handshake()
924 c.SetDeadline(time.Time{})
925 }
926 }
927 if err != nil {
928 if retry(c) {
929 goto RETRY
930 }
931 return nil, nil, fmt.Errorf("Error creating mqtt connection: %v", err)
932 }
933
934 proto := mqttCreateConnectProto(ci)
935 if _, err := testMQTTWrite(c, proto); err != nil {
936 if retry(c) {
937 goto RETRY
938 }
939 return nil, nil, fmt.Errorf("Error writing connect: %v", err)
940 }
941
942 buf, err := testMQTTRead(c)
943 if err != nil {
944 if retry(c) {
945 goto RETRY
946 }
947 return nil, nil, fmt.Errorf("Error reading: %v", err)
948 }
949 mr := &mqttReader{reader: c}
950 mr.reset(buf)
951
952 return c, mr, nil
953 }
954
955 func mqttCreateConnectProto(ci *mqttConnInfo) []byte {
956 flags := byte(0)
957 if ci.cleanSess {
958 flags |= mqttConnFlagCleanSession
959 }
960 if ci.will != nil {
961 flags |= mqttConnFlagWillFlag | (ci.will.qos << 3)
962 if ci.will.retain {
963 flags |= mqttConnFlagWillRetain
964 }
965 }
966 if ci.user != _EMPTY_ {
967 flags |= mqttConnFlagUsernameFlag
968 }
969 if ci.pass != _EMPTY_ {
970 flags |= mqttConnFlagPasswordFlag
971 }
972
973 pkLen := 2 + len(mqttProtoName) +
974 1 + // proto level
975 1 + // flags
976 2 + // keepAlive
977 2 + len(ci.clientID)
978
979 if ci.will != nil {
980 pkLen += 2 + len(ci.will.topic)
981 pkLen += 2 + len(ci.will.message)
982 }
983 if ci.user != _EMPTY_ {
984 pkLen += 2 + len(ci.user)
985 }
986 if ci.pass != _EMPTY_ {
987 pkLen += 2 + len(ci.pass)
988 }
989
990 w := newMQTTWriter(0)
991 w.WriteByte(mqttPacketConnect)
992 w.WriteVarInt(pkLen)
993 w.WriteString(string(mqttProtoName))
994 w.WriteByte(0x4)
995 w.WriteByte(flags)
996 w.WriteUint16(ci.keepAlive)
997 w.WriteString(ci.clientID)
998 if ci.will != nil {
999 w.WriteBytes(ci.will.topic)
1000 w.WriteBytes(ci.will.message)
1001 }
1002 if ci.user != _EMPTY_ {
1003 w.WriteString(ci.user)
1004 }
1005 if ci.pass != _EMPTY_ {
1006 w.WriteBytes([]byte(ci.pass))
1007 }
1008 return w.Bytes()
1009 }
1010
1011 func testMQTTCheckConnAck(t testing.TB, r *mqttReader, rc byte, sessionPresent bool) {
1012 t.Helper()
1013 b, pl := testMQTTReadPacket(t, r)
1014 pt := b & mqttPacketMask
1015 if pt != mqttPacketConnectAck {
1016 t.Fatalf("Expected ConnAck (%x), got %x", mqttPacketConnectAck, pt)
1017 }
1018 if pl != 2 {
1019 t.Fatalf("ConnAck packet length should be 2, got %v", pl)
1020 }
1021 caf, err := r.readByte("connack flags")
1022 if err != nil {
1023 t.Fatalf("Error reading packet length: %v", err)
1024 }
1025 if caf&0xfe != 0 {
1026 t.Fatalf("ConnAck flag bits 7-1 should all be 0, got %x", caf>>1)
1027 }
1028 if sp := caf == 1; sp != sessionPresent {
1029 t.Fatalf("Expected session present flag=%v got %v", sessionPresent, sp)
1030 }
1031 carc, err := r.readByte("connack return code")
1032 if err != nil {
1033 t.Fatalf("Error reading returned code: %v", err)
1034 }
1035 if carc != rc {
1036 t.Fatalf("Expected return code to be %v, got %v", rc, carc)
1037 }
1038 }
1039
1040 func testMQTTCheckPubAck(t testing.TB, r *mqttReader, packetType byte) {
1041 t.Helper()
1042 b, pl := testMQTTReadPacket(t, r)
1043 pt := b & mqttPacketMask
1044 if pt != packetType {
1045 t.Fatalf("Expected %x, got %x", packetType, pt)
1046 }
1047 r.pos += pl
1048 }
1049
1050 func TestMQTTRequiresJSEnabled(t *testing.T) {
1051 o := testMQTTDefaultOptions()
1052 acc := NewAccount("mqtt")
1053 o.Accounts = []*Account{acc}
1054 o.Users = []*User{{Username: "mqtt", Account: acc}}
1055 s := testMQTTRunServer(t, o)
1056 defer testMQTTShutdownServer(s)
1057
1058 addr := net.JoinHostPort(o.MQTT.Host, fmt.Sprintf("%d", o.MQTT.Port))
1059 c, err := net.Dial("tcp", addr)
1060 if err != nil {
1061 t.Fatalf("Error creating mqtt connection: %v", err)
1062 }
1063 defer c.Close()
1064
1065 proto := mqttCreateConnectProto(&mqttConnInfo{cleanSess: true, user: "mqtt"})
1066 if _, err := testMQTTWrite(c, proto); err != nil {
1067 t.Fatalf("Error writing connect: %v", err)
1068 }
1069 if _, err := testMQTTRead(c); err == nil {
1070 t.Fatal("Expected failure, did not get one")
1071 }
1072 }
1073
1074 func testMQTTEnableJSForAccount(t *testing.T, s *Server, accName string) {
1075 t.Helper()
1076 acc, err := s.LookupAccount(accName)
1077 if err != nil {
1078 t.Fatalf("Error looking up account: %v", err)
1079 }
1080 limits := map[string]JetStreamAccountLimits{
1081 _EMPTY_: {
1082 MaxConsumers: -1,
1083 MaxStreams: -1,
1084 MaxMemory: 1024 * 1024,
1085 MaxStore: 1024 * 1024,
1086 },
1087 }
1088 if err := acc.EnableJetStream(limits, nil); err != nil {
1089 t.Fatalf("Error enabling JS: %v", err)
1090 }
1091 }
1092
1093 func TestMQTTTLSVerifyAndMap(t *testing.T) {
1094 accName := "MyAccount"
1095 acc := NewAccount(accName)
1096 certUserName := "CN=example.com,OU=NATS.io"
1097 users := []*User{{Username: certUserName, Account: acc}}
1098
1099 for _, test := range []struct {
1100 name string
1101 filtering bool
1102 provideCert bool
1103 }{
1104 {"no filtering, client provides cert", false, true},
1105 {"no filtering, client does not provide cert", false, false},
1106 {"filtering, client provides cert", true, true},
1107 {"filtering, client does not provide cert", true, false},
1108 } {
1109 t.Run(test.name, func(t *testing.T) {
1110 o := testMQTTDefaultOptions()
1111 o.Host = "localhost"
1112 o.Accounts = []*Account{acc}
1113 o.Users = users
1114 if test.filtering {
1115 o.Users[0].AllowedConnectionTypes = testCreateAllowedConnectionTypes([]string{jwt.ConnectionTypeStandard, jwt.ConnectionTypeMqtt})
1116 }
1117 tc := &TLSConfigOpts{
1118 CertFile: "../test/configs/certs/tlsauth/server.pem",
1119 KeyFile: "../test/configs/certs/tlsauth/server-key.pem",
1120 CaFile: "../test/configs/certs/tlsauth/ca.pem",
1121 Verify: true,
1122 }
1123 tlsc, err := GenTLSConfig(tc)
1124 if err != nil {
1125 t.Fatalf("Error creating tls config: %v", err)
1126 }
1127 o.MQTT.TLSConfig = tlsc
1128 o.MQTT.TLSTimeout = 2.0
1129 o.MQTT.TLSMap = true
1130 s := testMQTTRunServer(t, o)
1131 defer testMQTTShutdownServer(s)
1132
1133 testMQTTEnableJSForAccount(t, s, accName)
1134
1135 tlscc := &tls.Config{}
1136 if test.provideCert {
1137 tc := &TLSConfigOpts{
1138 CertFile: "../test/configs/certs/tlsauth/client.pem",
1139 KeyFile: "../test/configs/certs/tlsauth/client-key.pem",
1140 }
1141 var err error
1142 tlscc, err = GenTLSConfig(tc)
1143 if err != nil {
1144 t.Fatalf("Error generating tls config: %v", err)
1145 }
1146 }
1147 tlscc.InsecureSkipVerify = true
1148 if test.provideCert {
1149 tlscc.MinVersion = tls.VersionTLS13
1150 }
1151 mc, r, err := testMQTTConnectRetryWithError(t, &mqttConnInfo{
1152 cleanSess: true,
1153 tls: true,
1154 tlsc: tlscc,
1155 }, o.MQTT.Host, o.MQTT.Port, 0)
1156 if !test.provideCert {
1157 if err == nil {
1158 t.Fatal("Expected error, did not get one")
1159 } else if !strings.Contains(err.Error(), "bad certificate") && !strings.Contains(err.Error(), "certificate required") {
1160 t.Fatalf("Unexpected error: %v", err)
1161 }
1162 return
1163 }
1164 if err != nil {
1165 t.Fatalf("Error reading: %v", err)
1166 }
1167 defer mc.Close()
1168 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1169
1170 var c *client
1171 s.mu.Lock()
1172 for _, sc := range s.clients {
1173 sc.mu.Lock()
1174 if sc.isMqtt() {
1175 c = sc
1176 }
1177 sc.mu.Unlock()
1178 if c != nil {
1179 break
1180 }
1181 }
1182 s.mu.Unlock()
1183 if c == nil {
1184 t.Fatal("Client not found")
1185 }
1186
1187 var uname string
1188 var accname string
1189 c.mu.Lock()
1190 uname = c.opts.Username
1191 if c.acc != nil {
1192 accname = c.acc.GetName()
1193 }
1194 c.mu.Unlock()
1195 if uname != certUserName {
1196 t.Fatalf("Expected username %q, got %q", certUserName, uname)
1197 }
1198 if accname != accName {
1199 t.Fatalf("Expected account %q, got %v", accName, accname)
1200 }
1201 })
1202 }
1203 }
1204
1205 func TestMQTTBasicAuth(t *testing.T) {
1206 for _, test := range []struct {
1207 name string
1208 opts func() *Options
1209 user string
1210 pass string
1211 rc byte
1212 }{
1213 {
1214 "top level auth, no override, wrong u/p",
1215 func() *Options {
1216 o := testMQTTDefaultOptions()
1217 o.Username = "normal"
1218 o.Password = "client"
1219 return o
1220 },
1221 "mqtt", "client", mqttConnAckRCNotAuthorized,
1222 },
1223 {
1224 "top level auth, no override, correct u/p",
1225 func() *Options {
1226 o := testMQTTDefaultOptions()
1227 o.Username = "normal"
1228 o.Password = "client"
1229 return o
1230 },
1231 "normal", "client", mqttConnAckRCConnectionAccepted,
1232 },
1233 {
1234 "no top level auth, mqtt auth, wrong u/p",
1235 func() *Options {
1236 o := testMQTTDefaultOptions()
1237 o.MQTT.Username = "mqtt"
1238 o.MQTT.Password = "client"
1239 return o
1240 },
1241 "normal", "client", mqttConnAckRCNotAuthorized,
1242 },
1243 {
1244 "no top level auth, mqtt auth, correct u/p",
1245 func() *Options {
1246 o := testMQTTDefaultOptions()
1247 o.MQTT.Username = "mqtt"
1248 o.MQTT.Password = "client"
1249 return o
1250 },
1251 "mqtt", "client", mqttConnAckRCConnectionAccepted,
1252 },
1253 {
1254 "top level auth, mqtt override, wrong u/p",
1255 func() *Options {
1256 o := testMQTTDefaultOptions()
1257 o.Username = "normal"
1258 o.Password = "client"
1259 o.MQTT.Username = "mqtt"
1260 o.MQTT.Password = "client"
1261 return o
1262 },
1263 "normal", "client", mqttConnAckRCNotAuthorized,
1264 },
1265 {
1266 "top level auth, mqtt override, correct u/p",
1267 func() *Options {
1268 o := testMQTTDefaultOptions()
1269 o.Username = "normal"
1270 o.Password = "client"
1271 o.MQTT.Username = "mqtt"
1272 o.MQTT.Password = "client"
1273 return o
1274 },
1275 "mqtt", "client", mqttConnAckRCConnectionAccepted,
1276 },
1277 } {
1278 t.Run(test.name, func(t *testing.T) {
1279 o := test.opts()
1280 s := testMQTTRunServer(t, o)
1281 defer testMQTTShutdownServer(s)
1282
1283 ci := &mqttConnInfo{
1284 cleanSess: true,
1285 user: test.user,
1286 pass: test.pass,
1287 }
1288 mc, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
1289 defer mc.Close()
1290 testMQTTCheckConnAck(t, r, test.rc, false)
1291 })
1292 }
1293 }
1294
1295 func TestMQTTAuthTimeout(t *testing.T) {
1296 for _, test := range []struct {
1297 name string
1298 at float64
1299 mat float64
1300 ok bool
1301 }{
1302 {"use top-level auth timeout", 0.5, 0.0, true},
1303 {"use mqtt auth timeout", 0.5, 0.05, false},
1304 } {
1305 t.Run(test.name, func(t *testing.T) {
1306 o := testMQTTDefaultOptions()
1307 o.AuthTimeout = test.at
1308 o.MQTT.Username = "mqtt"
1309 o.MQTT.Password = "client"
1310 o.MQTT.AuthTimeout = test.mat
1311 s := testMQTTRunServer(t, o)
1312 defer testMQTTShutdownServer(s)
1313
1314 mc, err := net.Dial("tcp", net.JoinHostPort(o.MQTT.Host, fmt.Sprintf("%d", o.MQTT.Port)))
1315 if err != nil {
1316 t.Fatalf("Error connecting: %v", err)
1317 }
1318 defer mc.Close()
1319
1320 time.Sleep(100 * time.Millisecond)
1321
1322 ci := &mqttConnInfo{
1323 cleanSess: true,
1324 user: "mqtt",
1325 pass: "client",
1326 }
1327 proto := mqttCreateConnectProto(ci)
1328 if _, err := testMQTTWrite(mc, proto); err != nil {
1329 if test.ok {
1330 t.Fatalf("Error sending connect: %v", err)
1331 }
1332 // else it is ok since we got disconnected due to auth timeout
1333 return
1334 }
1335 buf, err := testMQTTRead(mc)
1336 if err != nil {
1337 if test.ok {
1338 t.Fatalf("Error reading: %v", err)
1339 }
1340 // else it is ok since we got disconnected due to auth timeout
1341 return
1342 }
1343 r := &mqttReader{reader: mc}
1344 r.reset(buf)
1345 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1346
1347 time.Sleep(500 * time.Millisecond)
1348 testMQTTPublish(t, mc, r, 1, false, false, "foo", 1, []byte("msg"))
1349 })
1350 }
1351 }
1352
1353 func TestMQTTTokenAuth(t *testing.T) {
1354 for _, test := range []struct {
1355 name string
1356 opts func() *Options
1357 token string
1358 rc byte
1359 }{
1360 {
1361 "top level auth, no override, wrong token",
1362 func() *Options {
1363 o := testMQTTDefaultOptions()
1364 o.Authorization = "goodtoken"
1365 return o
1366 },
1367 "badtoken", mqttConnAckRCNotAuthorized,
1368 },
1369 {
1370 "top level auth, no override, correct token",
1371 func() *Options {
1372 o := testMQTTDefaultOptions()
1373 o.Authorization = "goodtoken"
1374 return o
1375 },
1376 "goodtoken", mqttConnAckRCConnectionAccepted,
1377 },
1378 {
1379 "no top level auth, mqtt auth, wrong token",
1380 func() *Options {
1381 o := testMQTTDefaultOptions()
1382 o.MQTT.Token = "goodtoken"
1383 return o
1384 },
1385 "badtoken", mqttConnAckRCNotAuthorized,
1386 },
1387 {
1388 "no top level auth, mqtt auth, correct token",
1389 func() *Options {
1390 o := testMQTTDefaultOptions()
1391 o.MQTT.Token = "goodtoken"
1392 return o
1393 },
1394 "goodtoken", mqttConnAckRCConnectionAccepted,
1395 },
1396 {
1397 "top level auth, mqtt override, wrong token",
1398 func() *Options {
1399 o := testMQTTDefaultOptions()
1400 o.Authorization = "clienttoken"
1401 o.MQTT.Token = "mqtttoken"
1402 return o
1403 },
1404 "clienttoken", mqttConnAckRCNotAuthorized,
1405 },
1406 {
1407 "top level auth, mqtt override, correct token",
1408 func() *Options {
1409 o := testMQTTDefaultOptions()
1410 o.Authorization = "clienttoken"
1411 o.MQTT.Token = "mqtttoken"
1412 return o
1413 },
1414 "mqtttoken", mqttConnAckRCConnectionAccepted,
1415 },
1416 } {
1417 t.Run(test.name, func(t *testing.T) {
1418 o := test.opts()
1419 s := testMQTTRunServer(t, o)
1420 defer testMQTTShutdownServer(s)
1421
1422 ci := &mqttConnInfo{
1423 cleanSess: true,
1424 user: "ignore_use_token",
1425 pass: test.token,
1426 }
1427 mc, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
1428 defer mc.Close()
1429 testMQTTCheckConnAck(t, r, test.rc, false)
1430 })
1431 }
1432 }
1433
1434 func TestMQTTJWTWithAllowedConnectionTypes(t *testing.T) {
1435 o := testMQTTDefaultOptions()
1436 // Create System Account
1437 syskp, _ := nkeys.CreateAccount()
1438 syspub, _ := syskp.PublicKey()
1439 sysAc := jwt.NewAccountClaims(syspub)
1440 sysjwt, err := sysAc.Encode(oKp)
1441 if err != nil {
1442 t.Fatalf("Error generating account JWT: %v", err)
1443 }
1444 // Create memory resolver and store system account
1445 mr := &MemAccResolver{}
1446 mr.Store(syspub, sysjwt)
1447 if err != nil {
1448 t.Fatalf("Error saving system account JWT to memory resolver: %v", err)
1449 }
1450 // Add system account and memory resolver to server options
1451 o.SystemAccount = syspub
1452 o.AccountResolver = mr
1453 setupAddTrusted(o)
1454
1455 s := testMQTTRunServer(t, o)
1456 defer testMQTTShutdownServer(s)
1457
1458 for _, test := range []struct {
1459 name string
1460 connectionTypes []string
1461 rc byte
1462 }{
1463 {"not allowed", []string{jwt.ConnectionTypeStandard}, mqttConnAckRCNotAuthorized},
1464 {"allowed", []string{jwt.ConnectionTypeStandard, strings.ToLower(jwt.ConnectionTypeMqtt)}, mqttConnAckRCConnectionAccepted},
1465 {"allowed with unknown", []string{jwt.ConnectionTypeMqtt, "SomeNewType"}, mqttConnAckRCConnectionAccepted},
1466 {"not allowed with unknown", []string{"SomeNewType"}, mqttConnAckRCNotAuthorized},
1467 } {
1468 t.Run(test.name, func(t *testing.T) {
1469
1470 nuc := newJWTTestUserClaims()
1471 nuc.AllowedConnectionTypes = test.connectionTypes
1472 nuc.BearerToken = true
1473
1474 okp, _ := nkeys.FromSeed(oSeed)
1475
1476 akp, _ := nkeys.CreateAccount()
1477 apub, _ := akp.PublicKey()
1478 nac := jwt.NewAccountClaims(apub)
1479 // Enable Jetstream on account with lax limitations
1480 nac.Limits.JetStreamLimits.Consumer = -1
1481 nac.Limits.JetStreamLimits.Streams = -1
1482 nac.Limits.JetStreamLimits.MemoryStorage = 1024 * 1024
1483 nac.Limits.JetStreamLimits.DiskStorage = 1024 * 1024
1484 ajwt, err := nac.Encode(okp)
1485 if err != nil {
1486 t.Fatalf("Error generating account JWT: %v", err)
1487 }
1488
1489 nkp, _ := nkeys.CreateUser()
1490 pub, _ := nkp.PublicKey()
1491 nuc.Subject = pub
1492 jwt, err := nuc.Encode(akp)
1493 if err != nil {
1494 t.Fatalf("Error generating user JWT: %v", err)
1495 }
1496
1497 addAccountToMemResolver(s, apub, ajwt)
1498
1499 ci := &mqttConnInfo{
1500 cleanSess: true,
1501 user: "ignore_use_token",
1502 pass: jwt,
1503 }
1504
1505 mc, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
1506 defer mc.Close()
1507 testMQTTCheckConnAck(t, r, test.rc, false)
1508 })
1509 }
1510 }
1511
1512 func TestMQTTUsersAuth(t *testing.T) {
1513 users := []*User{{Username: "user", Password: "pwd"}}
1514 for _, test := range []struct {
1515 name string
1516 opts func() *Options
1517 user string
1518 pass string
1519 rc byte
1520 }{
1521 {
1522 "no filtering, wrong user",
1523 func() *Options {
1524 o := testMQTTDefaultOptions()
1525 o.Users = users
1526 return o
1527 },
1528 "wronguser", "pwd", mqttConnAckRCNotAuthorized,
1529 },
1530 {
1531 "no filtering, correct user",
1532 func() *Options {
1533 o := testMQTTDefaultOptions()
1534 o.Users = users
1535 return o
1536 },
1537 "user", "pwd", mqttConnAckRCConnectionAccepted,
1538 },
1539 {
1540 "filtering, user not allowed",
1541 func() *Options {
1542 o := testMQTTDefaultOptions()
1543 o.Users = users
1544 // Only allowed for regular clients
1545 o.Users[0].AllowedConnectionTypes = testCreateAllowedConnectionTypes([]string{jwt.ConnectionTypeStandard})
1546 return o
1547 },
1548 "user", "pwd", mqttConnAckRCNotAuthorized,
1549 },
1550 {
1551 "filtering, user allowed",
1552 func() *Options {
1553 o := testMQTTDefaultOptions()
1554 o.Users = users
1555 o.Users[0].AllowedConnectionTypes = testCreateAllowedConnectionTypes([]string{jwt.ConnectionTypeStandard, jwt.ConnectionTypeMqtt})
1556 return o
1557 },
1558 "user", "pwd", mqttConnAckRCConnectionAccepted,
1559 },
1560 {
1561 "filtering, wrong password",
1562 func() *Options {
1563 o := testMQTTDefaultOptions()
1564 o.Users = users
1565 o.Users[0].AllowedConnectionTypes = testCreateAllowedConnectionTypes([]string{jwt.ConnectionTypeStandard, jwt.ConnectionTypeMqtt})
1566 return o
1567 },
1568 "user", "badpassword", mqttConnAckRCNotAuthorized,
1569 },
1570 } {
1571 t.Run(test.name, func(t *testing.T) {
1572 o := test.opts()
1573 s := testMQTTRunServer(t, o)
1574 defer testMQTTShutdownServer(s)
1575
1576 ci := &mqttConnInfo{
1577 cleanSess: true,
1578 user: test.user,
1579 pass: test.pass,
1580 }
1581 mc, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
1582 defer mc.Close()
1583 testMQTTCheckConnAck(t, r, test.rc, false)
1584 })
1585 }
1586 }
1587
1588 func TestMQTTNoAuthUserValidation(t *testing.T) {
1589 o := testMQTTDefaultOptions()
1590 o.Users = []*User{{Username: "user", Password: "pwd"}}
1591 // Should fail because it is not part of o.Users.
1592 o.MQTT.NoAuthUser = "notfound"
1593 if _, err := NewServer(o); err == nil || !strings.Contains(err.Error(), "not present as user") {
1594 t.Fatalf("Expected error saying not present as user, got %v", err)
1595 }
1596
1597 // Set a valid no auth user for global options, but still should fail because
1598 // of o.MQTT.NoAuthUser
1599 o.NoAuthUser = "user"
1600 o.MQTT.NoAuthUser = "notfound"
1601 if _, err := NewServer(o); err == nil || !strings.Contains(err.Error(), "not present as user") {
1602 t.Fatalf("Expected error saying not present as user, got %v", err)
1603 }
1604 }
1605
1606 func TestMQTTNoAuthUser(t *testing.T) {
1607 for _, test := range []struct {
1608 name string
1609 override bool
1610 useAuth bool
1611 expectedUser string
1612 expectedAcc string
1613 }{
1614 {"no override, no user provided", false, false, "noauth", "normal"},
1615 {"no override, user povided", false, true, "user", "normal"},
1616 {"override, no user provided", true, false, "mqttnoauth", "mqtt"},
1617 {"override, user provided", true, true, "mqttuser", "mqtt"},
1618 } {
1619 t.Run(test.name, func(t *testing.T) {
1620 o := testMQTTDefaultOptions()
1621 normalAcc := NewAccount("normal")
1622 mqttAcc := NewAccount("mqtt")
1623 o.Accounts = []*Account{normalAcc, mqttAcc}
1624 o.Users = []*User{
1625 {Username: "noauth", Password: "pwd", Account: normalAcc},
1626 {Username: "user", Password: "pwd", Account: normalAcc},
1627 {Username: "mqttnoauth", Password: "pwd", Account: mqttAcc},
1628 {Username: "mqttuser", Password: "pwd", Account: mqttAcc},
1629 }
1630 o.NoAuthUser = "noauth"
1631 if test.override {
1632 o.MQTT.NoAuthUser = "mqttnoauth"
1633 }
1634 s := testMQTTRunServer(t, o)
1635 defer testMQTTShutdownServer(s)
1636
1637 testMQTTEnableJSForAccount(t, s, "normal")
1638 testMQTTEnableJSForAccount(t, s, "mqtt")
1639
1640 ci := &mqttConnInfo{clientID: "mqtt", cleanSess: true}
1641 if test.useAuth {
1642 ci.user = test.expectedUser
1643 ci.pass = "pwd"
1644 }
1645 mc, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
1646 defer mc.Close()
1647 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1648
1649 c := testMQTTGetClient(t, s, "mqtt")
1650 c.mu.Lock()
1651 uname := c.opts.Username
1652 aname := c.acc.GetName()
1653 c.mu.Unlock()
1654 if uname != test.expectedUser {
1655 t.Fatalf("Expected selected user to be %q, got %q", test.expectedUser, uname)
1656 }
1657 if aname != test.expectedAcc {
1658 t.Fatalf("Expected selected account to be %q, got %q", test.expectedAcc, aname)
1659 }
1660 })
1661 }
1662 }
1663
1664 func TestMQTTConnectNotFirstPacket(t *testing.T) {
1665 o := testMQTTDefaultOptions()
1666 s := testMQTTRunServer(t, o)
1667 defer testMQTTShutdownServer(s)
1668
1669 l := &captureErrorLogger{errCh: make(chan string, 10)}
1670 s.SetLogger(l, false, false)
1671
1672 c, err := net.Dial("tcp", net.JoinHostPort(o.MQTT.Host, fmt.Sprintf("%d", o.MQTT.Port)))
1673 if err != nil {
1674 t.Fatalf("Error on dial: %v", err)
1675 }
1676 defer c.Close()
1677
1678 testMQTTSendPublishPacket(t, c, 0, false, false, "foo", 0, []byte("hello"))
1679 testMQTTExpectDisconnect(t, c)
1680
1681 select {
1682 case err := <-l.errCh:
1683 if !strings.Contains(err, "should be a CONNECT") {
1684 t.Fatalf("Expected error about first packet being a CONNECT, got %v", err)
1685 }
1686 case <-time.After(time.Second):
1687 t.Fatal("Did not log any error")
1688 }
1689 }
1690
1691 func TestMQTTSecondConnect(t *testing.T) {
1692 o := testMQTTDefaultOptions()
1693 s := testMQTTRunServer(t, o)
1694 defer testMQTTShutdownServer(s)
1695
1696 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1697 defer mc.Close()
1698 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1699
1700 proto := mqttCreateConnectProto(&mqttConnInfo{cleanSess: true})
1701 if _, err := testMQTTWrite(mc, proto); err != nil {
1702 t.Fatalf("Error writing connect: %v", err)
1703 }
1704 testMQTTExpectDisconnect(t, mc)
1705 }
1706
1707 func TestMQTTParseConnect(t *testing.T) {
1708 for _, test := range []struct {
1709 name string
1710 proto []byte
1711 err string
1712 wantErr bool
1713 }{
1714 {"packet in buffer error", []byte{0}, io.ErrUnexpectedEOF.Error(), false},
1715 {"bad proto name", []byte{0, 4, 'B', 'A', 'D'}, "protocol name", false},
1716 {"invalid proto name", []byte{0, 3, 'B', 'A', 'D'}, "expected connect packet with protocol name", false},
1717 {"old proto not supported", []byte{0, 6, 'M', 'Q', 'I', 's', 'd', 'p'}, "older protocol", false},
1718 {"error on protocol level", []byte{0, 4, 'M', 'Q', 'T', 'T'}, "protocol level", false},
1719 {"unacceptable protocol version", []byte{0, 4, 'M', 'Q', 'T', 'T', 10}, "unacceptable protocol version", false},
1720 {"error on flags", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel}, "flags", false},
1721 {"reserved flag", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 1}, errMQTTConnFlagReserved.Error(), false},
1722 {"will qos without will flag", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 1 << 3}, "if Will flag is set to 0, Will QoS must be 0 too", false},
1723 {"will retain without will flag", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 1 << 5}, errMQTTWillAndRetainFlag.Error(), false},
1724 {"will qos", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 3<<3 | 1<<2}, "if Will flag is set to 1, Will QoS can be 0, 1 or 2", false},
1725 {"no user but password", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagPasswordFlag}, errMQTTPasswordFlagAndNoUser.Error(), false},
1726 {"missing keep alive", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0}, "keep alive", false},
1727 {"missing client ID", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0, 0, 1}, "client ID", false},
1728 {"empty client ID", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0, 0, 1, 0, 0}, errMQTTCIDEmptyNeedsCleanFlag.Error(), false},
1729 {"invalid utf8 client ID", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0, 0, 1, 0, 1, 241}, "invalid utf8 for client ID", false},
1730 {"client ID with null byte", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0, 0, 1, 0, 3, 'a', 0, 'b'}, "", true},
1731 {"client ID with invalid character", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, 0, 0, 1, 0, 1, '.'}, "", true},
1732 {"missing will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0}, "Will topic", false},
1733 {"empty will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 0}, errMQTTEmptyWillTopic.Error(), false},
1734 {"invalid utf8 will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 241}, "invalid utf8 for Will topic", false},
1735 {"invalid wildcard will topic", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, '#'}, "wildcards not allowed", false},
1736 {"error on will message", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagWillFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 'a', 0, 3}, "Will message", false},
1737 {"error on username", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagCleanSession, 0, 0, 0, 0}, "user name", false},
1738 {"empty username", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 0}, errMQTTEmptyUsername.Error(), false},
1739 {"invalid utf8 username", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 241}, "invalid utf8 for user name", false},
1740 {"username with null byte", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 3, 'a', 0, 'b'}, "", true},
1741 {"error on password", []byte{0, 4, 'M', 'Q', 'T', 'T', mqttProtoLevel, mqttConnFlagUsernameFlag | mqttConnFlagPasswordFlag | mqttConnFlagCleanSession, 0, 0, 0, 0, 0, 1, 'a'}, "password", false},
1742 } {
1743 t.Run(test.name, func(t *testing.T) {
1744 r := &mqttReader{}
1745 r.reset(test.proto)
1746 mqtt := &mqtt{r: r}
1747 c := &client{mqtt: mqtt}
1748 _, _, err := c.mqttParseConnect(r, false)
1749 if test.wantErr {
1750 if err == nil {
1751 t.Fatal("Expected an error, got none")
1752 }
1753 return
1754 }
1755 if err == nil || !strings.Contains(err.Error(), test.err) {
1756 t.Fatalf("Expected error %q, got %v", test.err, err)
1757 }
1758 })
1759 }
1760 }
1761
1762 func TestMQTTConnectFailsOnParse(t *testing.T) {
1763 o := testMQTTDefaultOptions()
1764 s := testMQTTRunServer(t, o)
1765 defer testMQTTShutdownServer(s)
1766
1767 addr := net.JoinHostPort(o.MQTT.Host, fmt.Sprintf("%d", o.MQTT.Port))
1768 c, err := net.Dial("tcp", addr)
1769 if err != nil {
1770 t.Fatalf("Error creating mqtt connection: %v", err)
1771 }
1772
1773 pkLen := 2 + len(mqttProtoName) +
1774 1 + // proto level
1775 1 + // flags
1776 2 + // keepAlive
1777 2 + len("mqtt")
1778
1779 w := newMQTTWriter(0)
1780 w.WriteByte(mqttPacketConnect)
1781 w.WriteVarInt(pkLen)
1782 w.WriteString(string(mqttProtoName))
1783 w.WriteByte(0x7)
1784 w.WriteByte(mqttConnFlagCleanSession)
1785 w.WriteUint16(0)
1786 w.WriteString("mqtt")
1787 c.Write(w.Bytes())
1788
1789 buf, err := testMQTTRead(c)
1790 if err != nil {
1791 t.Fatalf("Error reading: %v", err)
1792 }
1793 r := &mqttReader{reader: c}
1794 r.reset(buf)
1795 testMQTTCheckConnAck(t, r, mqttConnAckRCUnacceptableProtocolVersion, false)
1796 }
1797
1798 func TestMQTTConnKeepAlive(t *testing.T) {
1799 o := testMQTTDefaultOptions()
1800 s := testMQTTRunServer(t, o)
1801 defer testMQTTShutdownServer(s)
1802
1803 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true, keepAlive: 1}, o.MQTT.Host, o.MQTT.Port)
1804 defer mc.Close()
1805 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1806
1807 testMQTTPublish(t, mc, r, 0, false, false, "foo", 0, []byte("msg"))
1808
1809 time.Sleep(2 * time.Second)
1810 testMQTTExpectDisconnect(t, mc)
1811 }
1812
1813 func TestMQTTMalformedFixedHeaderFlagsCauseDisconnect(t *testing.T) {
1814 o := testMQTTDefaultOptions()
1815 s := testMQTTRunServer(t, o)
1816 defer testMQTTShutdownServer(s)
1817
1818 for _, test := range []struct {
1819 name string
1820 packet func(t *testing.T) (net.Conn, []byte)
1821 }{
1822 {
1823 name: "connect",
1824 packet: func(t *testing.T) (net.Conn, []byte) {
1825 addr := net.JoinHostPort(o.MQTT.Host, fmt.Sprintf("%d", o.MQTT.Port))
1826 c, err := net.Dial("tcp", addr)
1827 if err != nil {
1828 t.Fatalf("Error creating mqtt connection: %v", err)
1829 }
1830 proto := mqttCreateConnectProto(&mqttConnInfo{cleanSess: true})
1831 proto[0] |= 0x1
1832 return c, proto
1833 },
1834 },
1835 {
1836 name: "pingreq",
1837 packet: func(t *testing.T) (net.Conn, []byte) {
1838 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1839 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1840 return mc, []byte{mqttPacketPing | 0x1, 0}
1841 },
1842 },
1843 {
1844 name: "puback",
1845 packet: func(t *testing.T) (net.Conn, []byte) {
1846 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1847 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1848 return mc, []byte{mqttPacketPubAck | 0x1, 2, 0, 1}
1849 },
1850 },
1851 {
1852 name: "pubrec",
1853 packet: func(t *testing.T) (net.Conn, []byte) {
1854 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1855 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1856 return mc, []byte{mqttPacketPubRec | 0x1, 2, 0, 1}
1857 },
1858 },
1859 {
1860 name: "pubrel",
1861 packet: func(t *testing.T) (net.Conn, []byte) {
1862 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1863 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1864 return mc, []byte{mqttPacketPubRel | 0x1, 2, 0, 1}
1865 },
1866 },
1867 {
1868 name: "pubcomp",
1869 packet: func(t *testing.T) (net.Conn, []byte) {
1870 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1871 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1872 return mc, []byte{mqttPacketPubComp | 0x1, 2, 0, 1}
1873 },
1874 },
1875 } {
1876 t.Run(test.name, func(t *testing.T) {
1877 c, packet := test.packet(t)
1878 defer c.Close()
1879
1880 if _, err := testMQTTWrite(c, packet); err != nil {
1881 t.Fatalf("Error writing malformed %s packet: %v", test.name, err)
1882 }
1883 testMQTTExpectDisconnect(t, c)
1884 })
1885 }
1886 }
1887
1888 func TestMQTTMalformedRemainingLengthCausesDisconnect(t *testing.T) {
1889 o := testMQTTDefaultOptions()
1890 s := testMQTTRunServer(t, o)
1891 defer testMQTTShutdownServer(s)
1892
1893 for _, test := range []struct {
1894 name string
1895 packet func(t *testing.T) (net.Conn, []byte)
1896 }{
1897 {
1898 name: "pingreq",
1899 packet: func(t *testing.T) (net.Conn, []byte) {
1900 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1901 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1902 return mc, []byte{mqttPacketPing, 1, 0}
1903 },
1904 },
1905 {
1906 name: "puback",
1907 packet: func(t *testing.T) (net.Conn, []byte) {
1908 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1909 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1910 return mc, []byte{mqttPacketPubAck, 3, 0, 1, 0}
1911 },
1912 },
1913 {
1914 name: "pubrec",
1915 packet: func(t *testing.T) (net.Conn, []byte) {
1916 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1917 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1918 return mc, []byte{mqttPacketPubRec, 3, 0, 1, 0}
1919 },
1920 },
1921 {
1922 name: "pubrel",
1923 packet: func(t *testing.T) (net.Conn, []byte) {
1924 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1925 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1926 return mc, []byte{mqttPacketPubRel | 0x2, 3, 0, 1, 0}
1927 },
1928 },
1929 {
1930 name: "pubcomp",
1931 packet: func(t *testing.T) (net.Conn, []byte) {
1932 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1933 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1934 return mc, []byte{mqttPacketPubComp, 3, 0, 1, 0}
1935 },
1936 },
1937 {
1938 name: "publish",
1939 packet: func(t *testing.T) (net.Conn, []byte) {
1940 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1941 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1942
1943 // Declare a remaining length that only covers the topic length field,
1944 // then write a much larger topic.
1945 w := newMQTTWriter(0)
1946 w.WriteByte(mqttPacketPub)
1947 w.WriteVarInt(2)
1948 w.WriteBytes(bytes.Repeat([]byte("a"), 64))
1949 return mc, w.Bytes()
1950 },
1951 },
1952 } {
1953 t.Run(test.name, func(t *testing.T) {
1954 c, packet := test.packet(t)
1955 defer c.Close()
1956
1957 if _, err := testMQTTWrite(c, packet); err != nil {
1958 t.Fatalf("Error writing malformed %s packet: %v", test.name, err)
1959 }
1960 testMQTTExpectDisconnect(t, c)
1961 })
1962 }
1963 }
1964
1965 func TestMQTTDontSetPinger(t *testing.T) {
1966 o := testMQTTDefaultOptions()
1967 o.PingInterval = 15 * time.Millisecond
1968 s := testMQTTRunServer(t, o)
1969 defer testMQTTShutdownServer(s)
1970
1971 mc, r := testMQTTConnect(t, &mqttConnInfo{clientID: "mqtt", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
1972 defer mc.Close()
1973 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
1974
1975 c := testMQTTGetClient(t, s, "mqtt")
1976 c.mu.Lock()
1977 timerSet := c.ping.tmr != nil
1978 c.mu.Unlock()
1979 if timerSet {
1980 t.Fatalf("Ping timer should not be set for MQTT clients")
1981 }
1982
1983 // Wait a bit and expect nothing (and connection should still be valid)
1984 testMQTTExpectNothing(t, r)
1985 testMQTTPublish(t, mc, r, 0, false, false, "foo", 0, []byte("msg"))
1986 }
1987
1988 func TestMQTTTopicAndSubjectConversion(t *testing.T) {
1989 for _, test := range []struct {
1990 name string
1991 mqttTopic string
1992 natsSubject string
1993 err string
1994 }{
1995 {"/", "/", "/./", ""},
1996 {"//", "//", "/././", ""},
1997 {"///", "///", "/./././", ""},
1998 {"////", "////", "/././././", ""},
1999 {"foo", "foo", "foo", ""},
2000 {"/foo", "/foo", "/.foo", ""},
2001 {"//foo", "//foo", "/./.foo", ""},
2002 {"///foo", "///foo", "/././.foo", ""},
2003 {"///foo/", "///foo/", "/././.foo./", ""},
2004 {"///foo//", "///foo//", "/././.foo././", ""},
2005 {"///foo///", "///foo///", "/././.foo./././", ""},
2006 {"//.foo.//", "//.foo.//", "/././/foo//././", ""},
2007 {"foo/bar", "foo/bar", "foo.bar", ""},
2008 {"/foo/bar", "/foo/bar", "/.foo.bar", ""},
2009 {"/foo/bar/", "/foo/bar/", "/.foo.bar./", ""},
2010 {"foo/bar/baz", "foo/bar/baz", "foo.bar.baz", ""},
2011 {"/foo/bar/baz", "/foo/bar/baz", "/.foo.bar.baz", ""},
2012 {"/foo/bar/baz/", "/foo/bar/baz/", "/.foo.bar.baz./", ""},
2013 {"bar", "bar/", "bar./", ""},
2014 {"bar//", "bar//", "bar././", ""},
2015 {"bar///", "bar///", "bar./././", ""},
2016 {"foo//bar", "foo//bar", "foo./.bar", ""},
2017 {"foo///bar", "foo///bar", "foo././.bar", ""},
2018 {"foo////bar", "foo////bar", "foo./././.bar", ""},
2019 {".", ".", "//", ""},
2020 {"..", "..", "////", ""},
2021 {"...", "...", "//////", ""},
2022 {"./", "./", "//./", ""},
2023 {".//.", ".//.", "//././/", ""},
2024 {"././.", "././.", "//.//.//", ""},
2025 {"././/.", "././/.", "//.//././/", ""},
2026 {".foo", ".foo", "//foo", ""},
2027 {"foo.", "foo.", "foo//", ""},
2028 {".foo.", ".foo.", "//foo//", ""},
2029 {"foo../bar/", "foo../bar/", "foo////.bar./", ""},
2030 {"foo../bar/.", "foo../bar/.", "foo////.bar.//", ""},
2031 {"/foo/", "/foo/", "/.foo./", ""},
2032 {"./foo/.", "./foo/.", "//.foo.//", ""},
2033 {"foo.bar/baz", "foo.bar/baz", "foo//bar.baz", ""},
2034 // These should produce errors
2035 {"foo/+", "foo/+", "", "wildcards not allowed in publish"},
2036 {"foo/#", "foo/#", "", "wildcards not allowed in publish"},
2037 {"foo bar", "foo bar", "", "not supported"},
2038 {"foo\x7fbar", "foo\x7fbar", "", "not supported"},
2039 } {
2040 t.Run(test.name, func(t *testing.T) {
2041 res, err := mqttTopicToNATSPubSubject([]byte(test.mqttTopic))
2042 if test.err != _EMPTY_ {
2043 if err == nil || !strings.Contains(err.Error(), test.err) {
2044 t.Fatalf("Expected error %q, got %v", test.err, err)
2045 }
2046 return
2047 }
2048 toNATS := string(res)
2049 if toNATS != test.natsSubject {
2050 t.Fatalf("Expected subject %q got %q", test.natsSubject, toNATS)
2051 }
2052
2053 res = natsSubjectToMQTTTopic(res)
2054 backToMQTT := string(res)
2055 if backToMQTT != test.mqttTopic {
2056 t.Fatalf("Expected topic %q got %q (NATS conversion was %q)", test.mqttTopic, backToMQTT, toNATS)
2057 }
2058 })
2059 }
2060 }
2061
2062 func TestMQTTFilterConversion(t *testing.T) {
2063 // Similar to TopicConversion test except that wildcards are OK here.
2064 // So testing only those.
2065 for _, test := range []struct {
2066 name string
2067 mqttTopic string
2068 natsSubject string
2069 }{
2070 {"single level wildcard", "+", "*"},
2071 {"single level wildcard", "/+", "/.*"},
2072 {"single level wildcard", "+/", "*./"},
2073 {"single level wildcard", "/+/", "/.*./"},
2074 {"single level wildcard", "foo/+", "foo.*"},
2075 {"single level wildcard", "foo/+/", "foo.*./"},
2076 {"single level wildcard", "foo/+/bar", "foo.*.bar"},
2077 {"single level wildcard", "foo/+/+", "foo.*.*"},
2078 {"single level wildcard", "foo/+/+/", "foo.*.*./"},
2079 {"single level wildcard", "foo/+/+/bar", "foo.*.*.bar"},
2080 {"single level wildcard", "foo//+", "foo./.*"},
2081 {"single level wildcard", "foo//+/", "foo./.*./"},
2082 {"single level wildcard", "foo//+//", "foo./.*././"},
2083 {"single level wildcard", "foo//+//bar", "foo./.*./.bar"},
2084 {"single level wildcard", "foo///+///bar", "foo././.*././.bar"},
2085 {"single level wildcard", "foo.bar///+///baz", "foo//bar././.*././.baz"},
2086
2087 {"multi level wildcard", "#", ">"},
2088 {"multi level wildcard", "/#", "/.>"},
2089 {"multi level wildcard", "/foo/#", "/.foo.>"},
2090 {"multi level wildcard", "foo/#", "foo.>"},
2091 {"multi level wildcard", "foo//#", "foo./.>"},
2092 {"multi level wildcard", "foo///#", "foo././.>"},
2093 {"multi level wildcard", "foo/bar/#", "foo.bar.>"},
2094 {"multi level wildcard", "foo/bar.baz/#", "foo.bar//baz.>"},
2095
2096 // NATS wildcards in MQTT filters are generally
2097 // not escaped, and get interpreted as wildcards
2098 // when converted to NATS subjects
2099 {"* literal", "foo*/bar", "foo*.bar"},
2100 {"> literal", "foo>/bar", "foo>.bar"},
2101 {"* wildcard middle", "foo/*/bar", "foo.*.bar"},
2102 {"* wildcard end", "foo/*/bar/*", "foo.*.bar.*"},
2103 {"> wildcard", "foo/>", "foo.>"},
2104 {"wildcard mix", "foo/*/bar/>", "foo.*.bar.>"},
2105 } {
2106 t.Run(test.name, func(t *testing.T) {
2107 res, err := mqttFilterToNATSSubject([]byte(test.mqttTopic))
2108 if err != nil {
2109 t.Fatalf("Error: %v", err)
2110 }
2111 if string(res) != test.natsSubject {
2112 t.Fatalf("Expected subject %q got %q", test.natsSubject, res)
2113 }
2114 })
2115 }
2116 }
2117
2118 func TestMQTTParseSub(t *testing.T) {
2119 for _, test := range []struct {
2120 name string
2121 proto []byte
2122 b byte
2123 pl int
2124 err string
2125 wantErr bool
2126 }{
2127 {"reserved flag", nil, 3, 0, "wrong subscribe reserved flags", false},
2128 {"ensure packet loaded", []byte{1, 2}, mqttSubscribeFlags, 10, io.ErrUnexpectedEOF.Error(), false},
2129 {"error reading packet id", []byte{1}, mqttSubscribeFlags, 1, "reading packet identifier", false},
2130 {"packet id cannot be zero", []byte{0, 0}, mqttSubscribeFlags, 2, errMQTTPacketIdentifierIsZero.Error(), false},
2131 {"missing filters", []byte{0, 1}, mqttSubscribeFlags, 2, "subscribe protocol must contain at least 1 topic filter", false},
2132 {"error reading topic", []byte{0, 1, 0, 2, 'a'}, mqttSubscribeFlags, 5, "topic filter", false},
2133 {"empty topic", []byte{0, 1, 0, 0}, mqttSubscribeFlags, 4, errMQTTTopicFilterCannotBeEmpty.Error(), false},
2134 {"invalid utf8 topic", []byte{0, 1, 0, 1, 241}, mqttSubscribeFlags, 5, "invalid utf8 for topic filter", false},
2135 {"topic with null byte", []byte{0, 1, 0, 3, 'a', 0, 'b', 0}, mqttSubscribeFlags, 8, "", true},
2136 {"missing qos", []byte{0, 1, 0, 1, 'a'}, mqttSubscribeFlags, 5, "QoS", false},
2137 {"invalid qos", []byte{0, 1, 0, 1, 'a', 3}, mqttSubscribeFlags, 6, "subscribe QoS value must be 0, 1 or 2", false},
2138 } {
2139 t.Run(test.name, func(t *testing.T) {
2140 r := &mqttReader{}
2141 r.reset(test.proto)
2142 mqtt := &mqtt{r: r}
2143 c := &client{mqtt: mqtt}
2144 _, _, err := c.mqttParseSubsOrUnsubs(r, test.b, test.pl, true)
2145 if test.wantErr {
2146 if err == nil {
2147 t.Fatal("Expected an error, got none")
2148 }
2149 return
2150 }
2151 if err == nil || !strings.Contains(err.Error(), test.err) {
2152 t.Fatalf("Expected error %q, got %v", test.err, err)
2153 }
2154 })
2155 }
2156 }
2157
2158 func testMQTTSub(t testing.TB, pi uint16, c net.Conn, r *mqttReader, filters []*mqttFilter, expected []byte) {
2159 t.Helper()
2160 w := newMQTTWriter(0)
2161 pkLen := 2 // for pi
2162 for i := 0; i < len(filters); i++ {
2163 f := filters[i]
2164 pkLen += 2 + len(f.filter) + 1
2165 }
2166 w.WriteByte(mqttPacketSub | mqttSubscribeFlags)
2167 w.WriteVarInt(pkLen)
2168 w.WriteUint16(pi)
2169 for i := 0; i < len(filters); i++ {
2170 f := filters[i]
2171 w.WriteBytes([]byte(f.filter))
2172 w.WriteByte(f.qos)
2173 }
2174 if _, err := testMQTTWrite(c, w.Bytes()); err != nil {
2175 t.Fatalf("Error writing SUBSCRIBE protocol: %v", err)
2176 }
2177 b, pl := testMQTTReadPacket(t, r)
2178 if pt := b & mqttPacketMask; pt != mqttPacketSubAck {
2179 t.Fatalf("Expected SUBACK packet %x, got %x", mqttPacketSubAck, pt)
2180 }
2181 rpi, err := r.readUint16("packet identifier")
2182 if err != nil || rpi != pi {
2183 t.Fatalf("Error with packet identifier expected=%v got: %v err=%v", pi, rpi, err)
2184 }
2185 for i, rem := 0, pl-2; rem > 0; rem-- {
2186 qos, err := r.readByte("filter qos")
2187 if err != nil {
2188 t.Fatal(err)
2189 }
2190 if expected != nil && qos != expected[i] {
2191 t.Fatalf("For topic filter %q expected qos of %v, got %v",
2192 filters[i].filter, expected[i], qos)
2193 }
2194 i++
2195 }
2196 }
2197
2198 func TestMQTTSubAck(t *testing.T) {
2199 o := testMQTTDefaultOptions()
2200 o.Users = []*User{
2201 {
2202 Username: "user",
2203 Password: "pass",
2204 Permissions: &Permissions{
2205 Subscribe: &SubjectPermission{Allow: []string{"foo", "bar", "baz", "foo.>"}},
2206 },
2207 },
2208 }
2209 s := testMQTTRunServer(t, o)
2210 defer testMQTTShutdownServer(s)
2211
2212 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true, user: "user", pass: "pass"}, o.MQTT.Host, o.MQTT.Port)
2213 defer mc.Close()
2214 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
2215
2216 subs := []*mqttFilter{
2217 {filter: "foo", qos: 0},
2218 {filter: "bar", qos: 1},
2219 {filter: "baz", qos: 2},
2220 {filter: "foo/#/bar", qos: 0}, // Invalid sub, so we should receive a result of mqttSubAckFailure
2221 }
2222 expected := []byte{
2223 0,
2224 1,
2225 2,
2226 mqttSubAckFailure,
2227 }
2228 testMQTTSub(t, 1, mc, r, subs, expected)
2229 }
2230
2231 func TestMQTTQoS2SubDowngrade(t *testing.T) {
2232 o := testMQTTDefaultOptions()
2233 o.MQTT.downgradeQoS2Sub = true
2234 s := testMQTTRunServer(t, o)
2235 defer testMQTTShutdownServer(s)
2236
2237 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2238 defer mc.Close()
2239 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
2240
2241 subs := []*mqttFilter{
2242 {filter: "bar", qos: 1},
2243 {filter: "baz", qos: 2},
2244 }
2245 expected := []byte{
2246 1,
2247 1,
2248 }
2249 testMQTTSub(t, 1, mc, r, subs, expected)
2250 }
2251
2252 func testMQTTFlush(t testing.TB, c net.Conn, bw *bufio.Writer, r *mqttReader) {
2253 t.Helper()
2254 w := newMQTTWriter(0)
2255 w.WriteByte(mqttPacketPing)
2256 w.WriteByte(0)
2257 if bw != nil {
2258 bw.Write(w.Bytes())
2259 bw.Flush()
2260 } else {
2261 c.Write(w.Bytes())
2262 }
2263 ab, l := testMQTTReadPacket(t, r)
2264 if pt := ab & mqttPacketMask; pt != mqttPacketPingResp {
2265 t.Fatalf("Expected ping response got %x", pt)
2266 }
2267 if l != 0 {
2268 t.Fatalf("Expected PINGRESP length to be 0, got %v", l)
2269 }
2270 }
2271
2272 func testMQTTExpectNothing(t testing.TB, r *mqttReader) {
2273 t.Helper()
2274 // First, check that we don't have buffered data.
2275 if r.hasMore() {
2276 t.Fatalf("Expected nothing, got %v", r.buf[r.pos:])
2277 }
2278 // Then, try to read from the reader with some timeout.
2279 var buf [128]byte
2280 r.reader.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
2281 if n, err := r.reader.Read(buf[:]); err == nil {
2282 t.Fatalf("Expected nothing, got %v", buf[:n])
2283 }
2284 r.reader.SetReadDeadline(time.Time{})
2285 }
2286
2287 func testMQTTCheckPubMsg(t testing.TB, c net.Conn, r *mqttReader, topic string, expectedFlags byte, payload []byte) uint16 {
2288 t.Helper()
2289 pi := testMQTTCheckPubMsgNoAck(t, c, r, topic, expectedFlags, payload)
2290 if pi == 0 {
2291 return 0
2292 }
2293 qos := mqttGetQoS(expectedFlags)
2294 switch qos {
2295 case 1:
2296 testMQTTSendPIPacket(mqttPacketPubAck, t, c, pi)
2297 case 2:
2298 testMQTTSendPIPacket(mqttPacketPubRec, t, c, pi)
2299 }
2300 return pi
2301 }
2302
2303 func testMQTTCheckPubMsgNoAck(t testing.TB, c net.Conn, r *mqttReader, topic string, expectedFlags byte, payload []byte) uint16 {
2304 t.Helper()
2305 pflags, pi := testMQTTGetPubMsg(t, c, r, topic, payload)
2306 if pflags != expectedFlags {
2307 t.Fatalf("Expected flags to be %x, got %x", expectedFlags, pflags)
2308 }
2309 return pi
2310 }
2311
2312 func testMQTTGetPubMsg(t testing.TB, c net.Conn, r *mqttReader, topic string, payload []byte) (byte, uint16) {
2313 t.Helper()
2314 flags, pi, _, _ := testMQTTGetPubMsgEx(t, c, r, topic, payload)
2315 return flags, pi
2316 }
2317
2318 func testMQTTGetPubMsgEx(t testing.TB, _ net.Conn, r *mqttReader, topic string, payload []byte) (byte, uint16, string, []byte) {
2319 t.Helper()
2320 b, pl := testMQTTReadPacket(t, r)
2321 if pt := b & mqttPacketMask; pt != mqttPacketPub {
2322 t.Fatalf("Expected PUBLISH packet %x, got %x", mqttPacketPub, pt)
2323 }
2324 return testMQTTGetPubMsgExEx(t, nil, r, b, pl, topic, payload)
2325 }
2326
2327 func testMQTTGetPubMsgExEx(t testing.TB, _ net.Conn, r *mqttReader, b byte, pl int, topic string, payload []byte) (byte, uint16, string, []byte) {
2328 t.Helper()
2329 pflags := b & mqttPacketFlagMask
2330 qos := (pflags & mqttPubFlagQoS) >> 1
2331 start := r.pos
2332 ptopic, err := r.readString("topic name")
2333 if err != nil {
2334 t.Fatal(err)
2335 }
2336 if topic != _EMPTY_ && ptopic != topic {
2337 t.Fatalf("Expected topic %q, got %q", topic, ptopic)
2338 }
2339 var pi uint16
2340 if qos > 0 {
2341 pi, err = r.readUint16("packet identifier")
2342 if err != nil {
2343 t.Fatal(err)
2344 }
2345 }
2346 msgLen := pl - (r.pos - start)
2347 if r.pos+msgLen > len(r.buf) {
2348 t.Fatalf("computed message length goes beyond buffer: ml=%v pos=%v lenBuf=%v",
2349 msgLen, r.pos, len(r.buf))
2350 }
2351 ppayload := r.buf[r.pos : r.pos+msgLen]
2352 if payload != nil && !bytes.Equal(payload, ppayload) {
2353 t.Fatalf("Expected payload %q, got %q", payload, ppayload)
2354 }
2355 r.pos += msgLen
2356 return pflags, pi, ptopic, ppayload
2357 }
2358
2359 func testMQTTReadPubPacket(t testing.TB, r *mqttReader) (flags byte, pi uint16, topic string, payload []byte) {
2360 t.Helper()
2361 b, pl := testMQTTReadPacket(t, r)
2362 if pt := b & mqttPacketMask; pt != mqttPacketPub {
2363 t.Fatalf("Expected PUBLISH packet %x, got %x", mqttPacketPub, pt)
2364 }
2365 flags = b & mqttPacketFlagMask
2366 start := r.pos
2367 topic, err := r.readString("topic name")
2368 if err != nil {
2369 t.Fatal(err)
2370 }
2371 qos := (flags & mqttPubFlagQoS) >> 1
2372 if qos > 0 {
2373 pi, err = r.readUint16("packet identifier")
2374 if err != nil {
2375 t.Fatal(err)
2376 }
2377 }
2378 msgLen := pl - (r.pos - start)
2379 if r.pos+msgLen > len(r.buf) {
2380 t.Fatalf("computed message length goes beyond buffer: ml=%v pos=%v lenBuf=%v",
2381 msgLen, r.pos, len(r.buf))
2382 }
2383 payload = r.buf[r.pos : r.pos+msgLen]
2384 r.pos += msgLen
2385 return flags, pi, topic, payload
2386 }
2387
2388 func testMQTTSendPIPacket(packetType byte, t testing.TB, c net.Conn, pi uint16) {
2389 t.Helper()
2390 w := newMQTTWriter(0)
2391 w.WriteByte(packetType)
2392 w.WriteVarInt(2)
2393 w.WriteUint16(pi)
2394 if _, err := testMQTTWrite(c, w.Bytes()); err != nil {
2395 t.Fatalf("Error writing packet type %v: %v", packetType, err)
2396 }
2397 }
2398
2399 func testMQTTWritePublishPacket(t testing.TB, w *mqttWriter, qos byte, dup, retain bool, topic string, pi uint16, payload []byte) {
2400 t.Helper()
2401 w.WritePublishHeader(pi, qos, dup, retain, []byte(topic), len(payload))
2402 if _, err := w.Write(payload); err != nil {
2403 t.Fatalf("Error writing PUBLISH proto: %v", err)
2404 }
2405 }
2406
2407 func testMQTTSendPublishPacket(t testing.TB, c net.Conn, qos byte, dup, retain bool, topic string, pi uint16, payload []byte) {
2408 t.Helper()
2409 c.SetWriteDeadline(time.Now().Add(testMQTTTimeout))
2410 _, header := mqttMakePublishHeader(pi, qos, dup, retain, []byte(topic), len(payload))
2411 if _, err := c.Write(header); err != nil {
2412 t.Fatalf("Error writing PUBLISH header: %v", err)
2413 }
2414 if _, err := c.Write(payload); err != nil {
2415 t.Fatalf("Error writing PUBLISH payload: %v", err)
2416 }
2417 c.SetWriteDeadline(time.Time{})
2418 }
2419
2420 func testMQTTPublish(t testing.TB, c net.Conn, r *mqttReader, qos byte, dup, retain bool, topic string, pi uint16, payload []byte) {
2421 t.Helper()
2422 testMQTTSendPublishPacket(t, c, qos, dup, retain, topic, pi, payload)
2423 switch qos {
2424 case 1:
2425 b, _ := testMQTTReadPacket(t, r)
2426 if pt := b & mqttPacketMask; pt != mqttPacketPubAck {
2427 t.Fatalf("Expected PUBACK packet %x, got %x", mqttPacketPubAck, pt)
2428 }
2429 rpi, err := r.readUint16("packet identifier")
2430 if err != nil || rpi != pi {
2431 t.Fatalf("Error with packet identifier expected=%v got: %v err=%v", pi, rpi, err)
2432 }
2433
2434 case 2:
2435 b, _ := testMQTTReadPacket(t, r)
2436 if pt := b & mqttPacketMask; pt != mqttPacketPubRec {
2437 t.Fatalf("Expected PUBREC packet %x, got %x", mqttPacketPubRec, pt)
2438 }
2439 rpi, err := r.readUint16("packet identifier")
2440 if err != nil || rpi != pi {
2441 t.Fatalf("Error with packet identifier expected=%v got: %v err=%v", pi, rpi, err)
2442 }
2443
2444 testMQTTSendPIPacket(mqttPacketPubRel|0x2, t, c, pi)
2445
2446 b, _ = testMQTTReadPacket(t, r)
2447 if pt := b & mqttPacketMask; pt != mqttPacketPubComp {
2448 t.Fatalf("Expected PUBCOMP packet %x, got %x", mqttPacketPubComp, pt)
2449 }
2450 rpi, err = r.readUint16("packet identifier")
2451 if err != nil || rpi != pi {
2452 t.Fatalf("Error with packet identifier expected=%v got: %v err=%v", pi, rpi, err)
2453 }
2454
2455 testMQTTFlush(t, c, nil, r)
2456 }
2457 }
2458
2459 func TestMQTTParsePub(t *testing.T) {
2460 for _, test := range []struct {
2461 name string
2462 flags byte
2463 proto []byte
2464 pl int
2465 err string
2466 wantErr bool
2467 }{
2468 {"qos not supported", (3 << 1), nil, 0, "QoS=3 is invalid in MQTT", false},
2469 {"packet in buffer error", 0, nil, 10, io.ErrUnexpectedEOF.Error(), false},
2470 {"error on topic", 0, []byte{0, 3, 'f', 'o'}, 4, "topic", false},
2471 {"empty topic", 0, []byte{0, 0}, 2, errMQTTTopicIsEmpty.Error(), false},
2472 {"wildcards topic", 0, []byte{0, 1, '#'}, 3, "wildcards not allowed", false},
2473 {"invalid utf8 topic", 0, []byte{0, 1, 241}, 3, "", true},
2474 {"topic with null byte", 0, []byte{0, 3, 'f', 0, 'o'}, 5, "", true},
2475 {"error on packet identifier", mqttPubQos1, []byte{0, 3, 'f', 'o', 'o'}, 5, "packet identifier", false},
2476 {"invalid packet identifier", mqttPubQos1, []byte{0, 3, 'f', 'o', 'o', 0, 0}, 7, errMQTTPacketIdentifierIsZero.Error(), false},
2477 } {
2478 t.Run(test.name, func(t *testing.T) {
2479 r := &mqttReader{}
2480 r.reset(test.proto)
2481 mqtt := &mqtt{r: r}
2482 c := &client{mqtt: mqtt}
2483 pp := &mqttPublish{flags: test.flags}
2484 err := c.mqttParsePub(r, test.pl, pp, false)
2485 if test.wantErr {
2486 if err == nil {
2487 t.Fatal("Expected an error, got none")
2488 }
2489 return
2490 }
2491 if err == nil || !strings.Contains(err.Error(), test.err) {
2492 t.Fatalf("Expected error %q, got %v", test.err, err)
2493 }
2494 })
2495 }
2496 }
2497
2498 func TestMQTTNatsHeaderFlags(t *testing.T) {
2499 // Round-trip every MQTT flags nibble through the header byte.
2500 for flags := byte(0); flags <= mqttPubFlags; flags++ {
2501 enc := mqttNatsHeaderEncodeFlags(flags)
2502 if enc < '0' || (enc > '9' && enc < 'a') || enc > 'f' {
2503 t.Fatalf("flags 0x%x encoded to non-hex byte %q", flags, enc)
2504 }
2505 // Decode reads value[1]; value[0] is the (irrelevant here) QoS char.
2506 if got := mqttNatsHeaderDecodeFlags([]byte{'0', enc}); got != flags {
2507 t.Fatalf("flags 0x%x: round-trip got 0x%x", flags, got)
2508 }
2509 }
2510
2511 // Bits above the nibble (e.g. a stray high bit) are not encoded.
2512 if enc := mqttNatsHeaderEncodeFlags(0xf0 | mqttPubFlagRetain); enc != '1' {
2513 t.Fatalf("high bits leaked into flags byte: %q", enc)
2514 }
2515
2516 // Named examples, including the "25" from the header contract comment.
2517 for _, test := range []struct {
2518 flags byte
2519 enc byte
2520 }{
2521 {0, '0'},
2522 {mqttPubFlagRetain, '1'},
2523 {mqttPubQoS2 | mqttPubFlagRetain, '5'},
2524 {mqttPubFlags, 'f'},
2525 } {
2526 if enc := mqttNatsHeaderEncodeFlags(test.flags); enc != test.enc {
2527 t.Fatalf("flags 0x%x encoded to %q, want %q", test.flags, enc, test.enc)
2528 }
2529 }
2530
2531 // Cross-version contract: a value with no flags byte (older sender) reads
2532 // as no flags set, never a panic.
2533 for _, value := range [][]byte{nil, {}, {'2'}} {
2534 if got := mqttNatsHeaderDecodeFlags(value); got != 0 {
2535 t.Fatalf("value %q: want no flags, got 0x%x", value, got)
2536 }
2537 }
2538 }
2539
2540 func TestMQTTParsePIMsg(t *testing.T) {
2541 for _, test := range []struct {
2542 name string
2543 proto []byte
2544 err string
2545 }{
2546 {"packet in buffer error", nil, io.ErrUnexpectedEOF.Error()},
2547 {"error reading packet identifier", []byte{0}, "packet identifier"},
2548 {"invalid packet identifier", []byte{0, 0}, errMQTTPacketIdentifierIsZero.Error()},
2549 } {
2550 t.Run(test.name, func(t *testing.T) {
2551 r := &mqttReader{}
2552 r.reset(test.proto)
2553 if _, err := mqttParsePIPacket(r); err == nil || !strings.Contains(err.Error(), test.err) {
2554 t.Fatalf("Expected error %q, got %v", test.err, err)
2555 }
2556 })
2557 }
2558 }
2559
2560 func TestMQTTPublish(t *testing.T) {
2561 o := testMQTTDefaultOptions()
2562 s := testMQTTRunServer(t, o)
2563 defer testMQTTShutdownServer(s)
2564
2565 nc := natsConnect(t, s.ClientURL())
2566 defer nc.Close()
2567
2568 mcp, mpr := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2569 defer mcp.Close()
2570 testMQTTCheckConnAck(t, mpr, mqttConnAckRCConnectionAccepted, false)
2571
2572 testMQTTPublish(t, mcp, mpr, 0, false, false, "foo", 0, []byte("msg"))
2573 testMQTTPublish(t, mcp, mpr, 1, false, false, "foo", 1, []byte("msg"))
2574 testMQTTPublish(t, mcp, mpr, 2, false, false, "foo", 2, []byte("msg"))
2575 }
2576
2577 func TestMQTTQoS2PubReject(t *testing.T) {
2578 o := testMQTTDefaultOptions()
2579 o.MQTT.rejectQoS2Pub = true
2580 s := testMQTTRunServer(t, o)
2581 defer testMQTTShutdownServer(s)
2582
2583 nc := natsConnect(t, s.ClientURL())
2584 defer nc.Close()
2585
2586 mcp, mpr := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2587 defer mcp.Close()
2588 testMQTTCheckConnAck(t, mpr, mqttConnAckRCConnectionAccepted, false)
2589
2590 testMQTTPublish(t, mcp, mpr, 1, false, false, "foo", 1, []byte("msg"))
2591
2592 testMQTTSendPublishPacket(t, mcp, 2, false, false, "foo", 2, []byte("msg"))
2593 testMQTTExpectDisconnect(t, mcp)
2594 }
2595
2596 func TestMQTTSub(t *testing.T) {
2597 o := testMQTTDefaultOptions()
2598 s := testMQTTRunServer(t, o)
2599 defer testMQTTShutdownServer(s)
2600
2601 nc := natsConnect(t, s.ClientURL())
2602 defer nc.Close()
2603
2604 mcp, mpr := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2605 defer mcp.Close()
2606 testMQTTCheckConnAck(t, mpr, mqttConnAckRCConnectionAccepted, false)
2607
2608 for _, test := range []struct {
2609 name string
2610 mqttSubTopic string
2611 natsPubSubject string
2612 mqttPubTopic string
2613 ok bool
2614 }{
2615 {"1 level match", "foo", "foo", "foo", true},
2616 {"1 level no match", "foo", "bar", "bar", false},
2617 {"2 levels match", "foo/bar", "foo.bar", "foo/bar", true},
2618 {"2 levels no match", "foo/bar", "foo.baz", "foo/baz", false},
2619 {"3 levels match", "/foo/bar", "/.foo.bar", "/foo/bar", true},
2620 {"3 levels no match", "/foo/bar", "/.foo.baz", "/foo/baz", false},
2621
2622 {"single level wc", "foo/+", "foo.bar.baz", "foo/bar/baz", false},
2623 {"single level wc", "foo/+", "foo.bar./", "foo/bar/", false},
2624 {"single level wc", "foo/+", "foo.bar", "foo/bar", true},
2625 {"single level wc", "foo/+", "foo./", "foo/", true},
2626 {"single level wc", "foo/+", "foo", "foo", false},
2627 {"single level wc", "foo/+", "/.foo", "/foo", false},
2628
2629 {"multiple level wc", "foo/#", "foo.bar.baz./", "foo/bar/baz/", true},
2630 {"multiple level wc", "foo/#", "foo.bar.baz", "foo/bar/baz", true},
2631 {"multiple level wc", "foo/#", "foo.bar./", "foo/bar/", true},
2632 {"multiple level wc", "foo/#", "foo.bar", "foo/bar", true},
2633 {"multiple level wc", "foo/#", "foo./", "foo/", true},
2634 {"multiple level wc", "foo/#", "foo", "foo", true},
2635 {"multiple level wc", "foo/#", "/.foo", "/foo", false},
2636 } {
2637 t.Run(test.name, func(t *testing.T) {
2638 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2639 defer mc.Close()
2640 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
2641
2642 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: test.mqttSubTopic, qos: 0}}, []byte{0})
2643 testMQTTFlush(t, mc, nil, r)
2644
2645 natsPub(t, nc, test.natsPubSubject, []byte("msg"))
2646 if test.ok {
2647 testMQTTCheckPubMsg(t, mc, r, test.mqttPubTopic, 0, []byte("msg"))
2648 } else {
2649 testMQTTExpectNothing(t, r)
2650 }
2651
2652 testMQTTPublish(t, mcp, mpr, 0, false, false, test.mqttPubTopic, 0, []byte("msg"))
2653 if test.ok {
2654 testMQTTCheckPubMsg(t, mc, r, test.mqttPubTopic, 0, []byte("msg"))
2655 } else {
2656 testMQTTExpectNothing(t, r)
2657 }
2658 })
2659 }
2660 }
2661
2662 func TestMQTTSubQoS2(t *testing.T) {
2663 o := testMQTTDefaultOptions()
2664 s := testMQTTRunServer(t, o)
2665 defer testMQTTShutdownServer(s)
2666
2667 nc := natsConnect(t, s.ClientURL())
2668 defer nc.Close()
2669
2670 mcp, mpr := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2671 defer mcp.Close()
2672 testMQTTCheckConnAck(t, mpr, mqttConnAckRCConnectionAccepted, false)
2673
2674 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2675 defer mc.Close()
2676 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
2677
2678 topic := "foo/bar/baz"
2679 mqttTopic0 := "foo/#"
2680 mqttTopic1 := "foo/bar/#"
2681 mqttTopic2 := topic
2682 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: mqttTopic0, qos: 0}}, []byte{0})
2683 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: mqttTopic1, qos: 1}}, []byte{1})
2684 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: mqttTopic2, qos: 2}}, []byte{2})
2685 testMQTTFlush(t, mc, nil, r)
2686
2687 for pubQoS, expectedCounts := range map[byte]map[byte]int{
2688 0: {0: 3},
2689 1: {0: 1, 1: 2},
2690 2: {0: 1, 1: 1, 2: 1},
2691 } {
2692 t.Run(fmt.Sprintf("pubQoS %v", pubQoS), func(t *testing.T) {
2693 pubPI := uint16(456)
2694
2695 testMQTTPublish(t, mcp, mpr, pubQoS, false, false, topic, pubPI, []byte("msg"))
2696
2697 qosCounts := map[byte]int{}
2698 delivered := map[uint16]byte{}
2699
2700 // We have 3 subscriptions, each should receive the message, with the
2701 // QoS that maybe "trimmed" to that of the subscription.
2702 for i := 0; i < 3; i++ {
2703 flags, pi := testMQTTGetPubMsg(t, mc, r, topic, []byte("msg"))
2704 delivered[pi] = flags
2705 qosCounts[mqttGetQoS(flags)]++
2706 }
2707
2708 for pi, flags := range delivered {
2709 switch mqttGetQoS(flags) {
2710 case 1:
2711 testMQTTSendPIPacket(mqttPacketPubAck, t, mc, pi)
2712
2713 case 2:
2714 testMQTTSendPIPacket(mqttPacketPubRec, t, mc, pi)
2715 testMQTTReadPIPacket(mqttPacketPubRel, t, r, pi)
2716 testMQTTSendPIPacket(mqttPacketPubComp, t, mc, pi)
2717 }
2718 }
2719
2720 if !reflect.DeepEqual(qosCounts, expectedCounts) {
2721 t.Fatalf("Expected QoS %#v, got %#v", expectedCounts, qosCounts)
2722 }
2723 })
2724 }
2725 }
2726
2727 func TestMQTTSubQoS2Restart(t *testing.T) {
2728 o := testMQTTDefaultOptions()
2729 s := testMQTTRunServer(t, o)
2730 defer testMQTTShutdownServer(s)
2731
2732 pubTopic := "foo/bar"
2733
2734 publish := func(msg string) {
2735 t.Helper()
2736 mcp, mpr := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2737 defer mcp.Close()
2738 testMQTTCheckConnAck(t, mpr, mqttConnAckRCConnectionAccepted, false)
2739 testMQTTPublish(t, mcp, mpr, 2, false, false, pubTopic, 1, []byte(msg))
2740 testMQTTFlush(t, mcp, nil, mpr)
2741 }
2742
2743 createSub := func(present bool) (net.Conn, *mqttReader) {
2744 t.Helper()
2745 c, r := testMQTTConnect(t, &mqttConnInfo{clientID: "sub", cleanSess: false}, o.MQTT.Host, o.MQTT.Port)
2746 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, present)
2747 if !present {
2748 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo/bar", qos: 2}}, []byte{2})
2749 testMQTTSub(t, 2, c, r, []*mqttFilter{{filter: "foo/+", qos: 2}}, []byte{2})
2750 testMQTTFlush(t, c, nil, r)
2751 }
2752 return c, r
2753 }
2754
2755 c, r := createSub(false)
2756 defer c.Close()
2757
2758 nc, js := jsClientConnect(t, s)
2759 defer nc.Close()
2760 checkSub := func(count int) {
2761 t.Helper()
2762 checkFor(t, time.Second, 15*time.Millisecond, func() error {
2763 for c := range js.Consumers(mqttOutStreamName) {
2764 acc := s.GlobalAccount()
2765 res := acc.sl.Match(c.Config.DeliverSubject)
2766 if n := len(res.psubs); n != count {
2767 return fmt.Errorf("Expected %v subscription on %q, got %v",
2768 count, c.Config.DeliverSubject, n)
2769 } else {
2770 // We got the JS consumer and verified that it has the
2771 // expected number of subscription, so we are done.
2772 return nil
2773 }
2774 }
2775 // No JS consumer was found.
2776 return fmt.Errorf("Did not find a JS consumer for %q", mqttOutStreamName)
2777 })
2778 }
2779 checkSub(1)
2780
2781 publish("msg1")
2782
2783 consume := func(msg string) {
2784 t.Helper()
2785 var pis []uint16
2786 for range 2 {
2787 b, pl := testMQTTReadPacket(t, r)
2788 if pt := b & mqttPacketMask; pt != mqttPacketPub {
2789 t.Fatalf("Expected PUBLISH packet %x, got %x", mqttPacketPub, pt)
2790 }
2791 flags, pi, _, _ := testMQTTGetPubMsgExEx(t, c, r, b, pl, pubTopic, []byte(msg))
2792 require_Equal(t, flags, byte(mqttPubQoS2))
2793 pis = append(pis, pi)
2794 }
2795 for _, pi := range pis {
2796 testMQTTSendPIPacket(mqttPacketPubRec, t, c, pi)
2797 testMQTTReadPIPacket(mqttPacketPubRel, t, r, pi)
2798 testMQTTSendPIPacket(mqttPacketPubComp, t, c, pi)
2799 }
2800 testMQTTExpectNothing(t, r)
2801 }
2802
2803 consume("msg1")
2804 testMQTTDisconnect(t, c, nil)
2805 c.Close()
2806 checkSub(0)
2807
2808 publish("msg2")
2809
2810 c, r = createSub(true)
2811 defer c.Close()
2812 checkSub(1)
2813 consume("msg2")
2814
2815 publish("msg3")
2816 consume("msg3")
2817 }
2818
2819 func TestMQTTSubQoS1(t *testing.T) {
2820 o := testMQTTDefaultOptions()
2821 s := testMQTTRunServer(t, o)
2822 defer testMQTTShutdownServer(s)
2823
2824 nc := natsConnect(t, s.ClientURL())
2825 defer nc.Close()
2826
2827 mcp, mpr := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2828 defer mcp.Close()
2829 testMQTTCheckConnAck(t, mpr, mqttConnAckRCConnectionAccepted, false)
2830
2831 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2832 defer mc.Close()
2833 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
2834
2835 mqttTopic := "foo/bar"
2836
2837 // Subscribe with QoS 1
2838 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo/#", qos: 1}}, []byte{1})
2839 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: mqttTopic, qos: 1}}, []byte{1})
2840 testMQTTFlush(t, mc, nil, r)
2841
2842 // Publish from NATS, which means QoS 0
2843 natsPub(t, nc, "foo.bar", []byte("NATS"))
2844 // Will receive as QoS 0
2845 testMQTTCheckPubMsg(t, mc, r, mqttTopic, 0, []byte("NATS"))
2846 testMQTTCheckPubMsg(t, mc, r, mqttTopic, 0, []byte("NATS"))
2847
2848 // Publish from MQTT with QoS 0
2849 testMQTTPublish(t, mcp, mpr, 0, false, false, mqttTopic, 0, []byte("msg"))
2850 // Will receive as QoS 0
2851 testMQTTCheckPubMsg(t, mc, r, mqttTopic, 0, []byte("msg"))
2852 testMQTTCheckPubMsg(t, mc, r, mqttTopic, 0, []byte("msg"))
2853
2854 // Publish from MQTT with QoS 1
2855 testMQTTPublish(t, mcp, mpr, 1, false, false, mqttTopic, 1, []byte("msg"))
2856 pflags1, pi1 := testMQTTGetPubMsg(t, mc, r, mqttTopic, []byte("msg"))
2857 if pflags1 != 0x2 {
2858 t.Fatalf("Expected flags to be 0x2, got %v", pflags1)
2859 }
2860 pflags2, pi2 := testMQTTGetPubMsg(t, mc, r, mqttTopic, []byte("msg"))
2861 if pflags2 != 0x2 {
2862 t.Fatalf("Expected flags to be 0x2, got %v", pflags2)
2863 }
2864 if pi1 == pi2 {
2865 t.Fatalf("packet identifier for message 1: %v should be different from message 2", pi1)
2866 }
2867 testMQTTSendPIPacket(mqttPacketPubAck, t, mc, pi1)
2868 testMQTTSendPIPacket(mqttPacketPubAck, t, mc, pi2)
2869 }
2870
2871 func getSubQoS(sub *subscription) int {
2872 if sub.mqtt != nil {
2873 return int(sub.mqtt.qos)
2874 }
2875 return -1
2876 }
2877
2878 func TestMQTTSubDups(t *testing.T) {
2879 o := testMQTTDefaultOptions()
2880 s := testMQTTRunServer(t, o)
2881 defer testMQTTShutdownServer(s)
2882
2883 mcp, mpr := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2884 defer mcp.Close()
2885 testMQTTCheckConnAck(t, mpr, mqttConnAckRCConnectionAccepted, false)
2886
2887 mc, r := testMQTTConnect(t, &mqttConnInfo{clientID: "sub", user: "sub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
2888 defer mc.Close()
2889 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
2890
2891 // Test with single SUBSCRIBE protocol but multiple filters
2892 filters := []*mqttFilter{
2893 {filter: "foo", qos: 1},
2894 {filter: "foo", qos: 0},
2895 }
2896 testMQTTSub(t, 1, mc, r, filters, []byte{1, 0})
2897 testMQTTFlush(t, mc, nil, r)
2898
2899 // And also with separate SUBSCRIBE protocols
2900 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "bar", qos: 0}}, []byte{0})
2901 // Ask for QoS 1 but server will downgrade to 1
2902 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
2903 testMQTTFlush(t, mc, nil, r)
2904
2905 // Publish and test msg received only once
2906 testMQTTPublish(t, mcp, r, 0, false, false, "foo", 0, []byte("msg"))
2907 testMQTTCheckPubMsg(t, mc, r, "foo", 0, []byte("msg"))
2908 testMQTTExpectNothing(t, r)
2909
2910 testMQTTPublish(t, mcp, r, 0, false, false, "bar", 0, []byte("msg"))
2911 testMQTTCheckPubMsg(t, mc, r, "bar", 0, []byte("msg"))
2912 testMQTTExpectNothing(t, r)
2913
2914 // Check that the QoS for subscriptions have been updated to the latest received filter
2915 var err error
2916 subc := testMQTTGetClient(t, s, "sub")
2917 subc.mu.Lock()
2918 if subc.opts.Username != "sub" {
2919 err = fmt.Errorf("wrong user name")
2920 }
2921 if err == nil {
2922 if sub := subc.subs["foo"]; sub == nil || getSubQoS(sub) != 0 {
2923 err = fmt.Errorf("subscription foo QoS should be 0, got %v", getSubQoS(sub))
2924 }
2925 }
2926 if err == nil {
2927 if sub := subc.subs["bar"]; sub == nil || getSubQoS(sub) != 1 {
2928 err = fmt.Errorf("subscription bar QoS should be 1, got %v", getSubQoS(sub))
2929 }
2930 }
2931 subc.mu.Unlock()
2932 if err != nil {
2933 t.Fatal(err)
2934 }
2935
2936 // Now subscribe on "foo/#" which means that a PUBLISH on "foo" will be received
2937 // by this subscription and also the one on "foo".
2938 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo/#", qos: 1}}, []byte{1})
2939 testMQTTFlush(t, mc, nil, r)
2940
2941 // Publish and test msg received twice
2942 testMQTTPublish(t, mcp, r, 0, false, false, "foo", 0, []byte("msg"))
2943 testMQTTCheckPubMsg(t, mc, r, "foo", 0, []byte("msg"))
2944 testMQTTCheckPubMsg(t, mc, r, "foo", 0, []byte("msg"))
2945
2946 checkWCSub := func(expectedQoS int) {
2947 t.Helper()
2948
2949 subc.mu.Lock()
2950 defer subc.mu.Unlock()
2951
2952 // When invoked with expectedQoS==1, we have the following subs:
2953 // foo (QoS-0), bar (QoS-1), foo.> (QoS-1)
2954 // which means (since QoS-1 have a JS consumer + sub for delivery
2955 // and foo.> causes a "foo fwc") that we should have the following
2956 // number of NATS subs: foo (1), bar (2), foo.> (2) and "foo fwc" (2),
2957 // so total=7.
2958 // When invoked with expectedQoS==0, it means that we have replaced
2959 // foo/# QoS-1 to QoS-0, so we should have 2 less NATS subs,
2960 // so total=5
2961 expected := 7
2962 if expectedQoS == 0 {
2963 expected = 5
2964 }
2965 if lenmap := len(subc.subs); lenmap != expected {
2966 t.Fatalf("Subs map should have %v entries, got %v", expected, lenmap)
2967 }
2968 if sub, ok := subc.subs["foo.>"]; !ok {
2969 t.Fatal("Expected sub foo.> to be present but was not")
2970 } else if getSubQoS(sub) != expectedQoS {
2971 t.Fatalf("Expected sub foo.> QoS to be %v, got %v", expectedQoS, getSubQoS(sub))
2972 }
2973 if sub, ok := subc.subs["foo fwc"]; !ok {
2974 t.Fatal("Expected sub foo fwc to be present but was not")
2975 } else if getSubQoS(sub) != expectedQoS {
2976 t.Fatalf("Expected sub foo fwc QoS to be %v, got %v", expectedQoS, getSubQoS(sub))
2977 }
2978 // Make sure existing sub on "foo" qos was not changed.
2979 if sub, ok := subc.subs["foo"]; !ok {
2980 t.Fatal("Expected sub foo to be present but was not")
2981 } else if getSubQoS(sub) != 0 {
2982 t.Fatalf("Expected sub foo QoS to be 0, got %v", getSubQoS(sub))
2983 }
2984 }
2985 checkWCSub(1)
2986
2987 // Sub again on same subject with lower QoS
2988 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo/#", qos: 0}}, []byte{0})
2989 testMQTTFlush(t, mc, nil, r)
2990
2991 // Publish and test msg received twice
2992 testMQTTPublish(t, mcp, r, 0, false, false, "foo", 0, []byte("msg"))
2993 testMQTTCheckPubMsg(t, mc, r, "foo", 0, []byte("msg"))
2994 testMQTTCheckPubMsg(t, mc, r, "foo", 0, []byte("msg"))
2995 checkWCSub(0)
2996 }
2997
2998 func TestMQTTSubWithSpaces(t *testing.T) {
2999 o := testMQTTDefaultOptions()
3000 s := testMQTTRunServer(t, o)
3001 defer testMQTTShutdownServer(s)
3002
3003 mcp, mpr := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3004 defer mcp.Close()
3005 testMQTTCheckConnAck(t, mpr, mqttConnAckRCConnectionAccepted, false)
3006
3007 mc, r := testMQTTConnect(t, &mqttConnInfo{user: "sub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3008 defer mc.Close()
3009 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
3010
3011 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo bar", qos: 0}}, []byte{mqttSubAckFailure})
3012 }
3013
3014 // Filters containing characters that would corrupt the NATS wire protocol
3015 // (\t, \n, \r, \f) must result in a per-filter SUBACK failure, not a
3016 // connection drop. mqttFilterToNATSSubject rejects them; the SUBSCRIBE
3017 // parser logs and continues so the failure surfaces as mqttSubAckFailure.
3018 func TestMQTTSubWithControlChars(t *testing.T) {
3019 o := testMQTTDefaultOptions()
3020 s := testMQTTRunServer(t, o)
3021 defer testMQTTShutdownServer(s)
3022
3023 for _, test := range []struct {
3024 name string
3025 filter string
3026 }{
3027 {"tab", "foo\tbar"},
3028 {"line feed", "foo\nbar"},
3029 {"carriage return", "foo\rbar"},
3030 {"form feed", "foo\fbar"},
3031 } {
3032 t.Run(test.name, func(t *testing.T) {
3033 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3034 defer mc.Close()
3035 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
3036
3037 // Mix a bad filter with a good one to prove the good one still
3038 // succeeds (the connection is not torn down by the bad filter).
3039 testMQTTSub(t, 1, mc, r,
3040 []*mqttFilter{{filter: test.filter, qos: 0}, {filter: "good/topic", qos: 0}},
3041 []byte{mqttSubAckFailure, 0})
3042 })
3043 }
3044 }
3045
3046 func TestMQTTSubCaseSensitive(t *testing.T) {
3047 o := testMQTTDefaultOptions()
3048 s := testMQTTRunServer(t, o)
3049 defer testMQTTShutdownServer(s)
3050
3051 mcp, mpr := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3052 defer mcp.Close()
3053 testMQTTCheckConnAck(t, mpr, mqttConnAckRCConnectionAccepted, false)
3054
3055 mc, r := testMQTTConnect(t, &mqttConnInfo{user: "sub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3056 defer mc.Close()
3057 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
3058
3059 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "Foo/Bar", qos: 0}}, []byte{0})
3060 testMQTTFlush(t, mc, nil, r)
3061
3062 testMQTTPublish(t, mcp, r, 0, false, false, "Foo/Bar", 0, []byte("msg"))
3063 testMQTTCheckPubMsg(t, mc, r, "Foo/Bar", 0, []byte("msg"))
3064
3065 testMQTTPublish(t, mcp, r, 0, false, false, "foo/bar", 0, []byte("msg"))
3066 testMQTTExpectNothing(t, r)
3067
3068 nc := natsConnect(t, s.ClientURL())
3069 defer nc.Close()
3070
3071 natsPub(t, nc, "Foo.Bar", []byte("nats"))
3072 testMQTTCheckPubMsg(t, mc, r, "Foo/Bar", 0, []byte("nats"))
3073
3074 natsPub(t, nc, "foo.bar", []byte("nats"))
3075 testMQTTExpectNothing(t, r)
3076 }
3077
3078 func TestMQTTPubSubMatrix(t *testing.T) {
3079 for _, test := range []struct {
3080 name string
3081 natsPub bool
3082 mqttPub bool
3083 mqttPubQoS byte
3084 natsSub bool
3085 mqttSubQoS0 bool
3086 mqttSubQoS1 bool
3087 }{
3088 {"NATS to MQTT sub QoS-0", true, false, 0, false, true, false},
3089 {"NATS to MQTT sub QoS-1", true, false, 0, false, false, true},
3090 {"NATS to MQTT sub QoS-0 and QoS-1", true, false, 0, false, true, true},
3091
3092 {"MQTT QoS-0 to NATS sub", false, true, 0, true, false, false},
3093 {"MQTT QoS-0 to MQTT sub QoS-0", false, true, 0, false, true, false},
3094 {"MQTT QoS-0 to MQTT sub QoS-1", false, true, 0, false, false, true},
3095 {"MQTT QoS-0 to NATS sub and MQTT sub QoS-0", false, true, 0, true, true, false},
3096 {"MQTT QoS-0 to NATS sub and MQTT sub QoS-1", false, true, 0, true, false, true},
3097 {"MQTT QoS-0 to all subs", false, true, 0, true, true, true},
3098
3099 {"MQTT QoS-1 to NATS sub", false, true, 1, true, false, false},
3100 {"MQTT QoS-1 to MQTT sub QoS-0", false, true, 1, false, true, false},
3101 {"MQTT QoS-1 to MQTT sub QoS-1", false, true, 1, false, false, true},
3102 {"MQTT QoS-1 to NATS sub and MQTT sub QoS-0", false, true, 1, true, true, false},
3103 {"MQTT QoS-1 to NATS sub and MQTT sub QoS-1", false, true, 1, true, false, true},
3104 {"MQTT QoS-1 to all subs", false, true, 1, true, true, true},
3105 } {
3106 t.Run(test.name, func(t *testing.T) {
3107 o := testMQTTDefaultOptions()
3108 s := testMQTTRunServer(t, o)
3109 defer testMQTTShutdownServer(s)
3110
3111 nc := natsConnect(t, s.ClientURL())
3112 defer nc.Close()
3113
3114 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3115 defer mc.Close()
3116 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
3117
3118 mc1, r1 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3119 defer mc1.Close()
3120 testMQTTCheckConnAck(t, r1, mqttConnAckRCConnectionAccepted, false)
3121
3122 mc2, r2 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3123 defer mc2.Close()
3124 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, false)
3125
3126 // First setup subscriptions based on test options.
3127 var ns *nats.Subscription
3128 if test.natsSub {
3129 ns = natsSubSync(t, nc, "foo")
3130 }
3131 if test.mqttSubQoS0 {
3132 testMQTTSub(t, 1, mc1, r1, []*mqttFilter{{filter: "foo", qos: 0}}, []byte{0})
3133 testMQTTFlush(t, mc1, nil, r1)
3134 }
3135 if test.mqttSubQoS1 {
3136 testMQTTSub(t, 1, mc2, r2, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
3137 testMQTTFlush(t, mc2, nil, r2)
3138 }
3139
3140 // Just as a barrier
3141 natsFlush(t, nc)
3142
3143 // Now publish
3144 if test.natsPub {
3145 natsPub(t, nc, "foo", []byte("msg"))
3146 } else {
3147 testMQTTPublish(t, mc, r, test.mqttPubQoS, false, false, "foo", 1, []byte("msg"))
3148 }
3149
3150 // Check message received
3151 if test.natsSub {
3152 natsNexMsg(t, ns, time.Second)
3153 // Make sure no other is received
3154 if msg, err := ns.NextMsg(50 * time.Millisecond); err == nil {
3155 t.Fatalf("Should not have gotten a second message, got %v", msg)
3156 }
3157 }
3158 if test.mqttSubQoS0 {
3159 testMQTTCheckPubMsg(t, mc1, r1, "foo", 0, []byte("msg"))
3160 testMQTTExpectNothing(t, r1)
3161 }
3162 if test.mqttSubQoS1 {
3163 var expectedFlag byte
3164 if test.mqttPubQoS > 0 {
3165 expectedFlag = test.mqttPubQoS << 1
3166 }
3167 testMQTTCheckPubMsg(t, mc2, r2, "foo", expectedFlag, []byte("msg"))
3168 testMQTTExpectNothing(t, r2)
3169 }
3170 })
3171 }
3172 }
3173
3174 func TestMQTTPreventSubWithMQTTSubPrefix(t *testing.T) {
3175 o := testMQTTDefaultOptions()
3176 s := testMQTTRunServer(t, o)
3177 defer testMQTTShutdownServer(s)
3178
3179 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3180 defer mc.Close()
3181 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
3182 testMQTTSub(t, 1, mc, r,
3183 []*mqttFilter{{filter: strings.ReplaceAll(mqttSubPrefix, ".", "/") + "foo/bar", qos: 1}},
3184 []byte{mqttSubAckFailure})
3185 }
3186
3187 func TestMQTTSubWithNATSStream(t *testing.T) {
3188 o := testMQTTDefaultOptions()
3189 s := testMQTTRunServer(t, o)
3190 defer testMQTTShutdownServer(s)
3191
3192 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3193 defer mc.Close()
3194 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
3195 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo/bar", qos: 1}}, []byte{1})
3196 testMQTTFlush(t, mc, nil, r)
3197
3198 mcp, rp := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3199 defer mcp.Close()
3200 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
3201 testMQTTFlush(t, mcp, nil, rp)
3202
3203 nc := natsConnect(t, s.ClientURL())
3204 defer nc.Close()
3205
3206 sc := &StreamConfig{
3207 Name: "test",
3208 Storage: FileStorage,
3209 Retention: InterestPolicy,
3210 Subjects: []string{"foo.>"},
3211 }
3212 mset, err := s.GlobalAccount().addStream(sc)
3213 if err != nil {
3214 t.Fatalf("Unable to create stream: %v", err)
3215 }
3216
3217 sub := natsSubSync(t, nc, "bar")
3218 cc := &ConsumerConfig{
3219 Durable: "dur",
3220 AckPolicy: AckExplicit,
3221 DeliverSubject: "bar",
3222 }
3223 if _, err := mset.addConsumer(cc); err != nil {
3224 t.Fatalf("Unable to add consumer: %v", err)
3225 }
3226
3227 // Now send message from NATS
3228 resp, err := nc.Request("foo.bar", []byte("nats"), time.Second)
3229 if err != nil {
3230 t.Fatalf("Error publishing: %v", err)
3231 }
3232 ar := &ApiResponse{}
3233 if err := json.Unmarshal(resp.Data, ar); err != nil || ar.Error != nil {
3234 t.Fatalf("Unexpected response: err=%v resp=%+v", err, ar.Error)
3235 }
3236
3237 // Check that message is received by both
3238 checkRecv := func(content string, flags byte) {
3239 t.Helper()
3240 if msg := natsNexMsg(t, sub, time.Second); string(msg.Data) != content {
3241 t.Fatalf("Expected %q, got %q", content, msg.Data)
3242 }
3243 testMQTTCheckPubMsg(t, mc, r, "foo/bar", flags, []byte(content))
3244 }
3245 checkRecv("nats", 0)
3246
3247 // Send from MQTT as a QoS0
3248 testMQTTPublish(t, mcp, rp, 0, false, false, "foo/bar", 0, []byte("qos0"))
3249 checkRecv("qos0", 0)
3250
3251 // Send from MQTT as a QoS1
3252 testMQTTPublish(t, mcp, rp, 1, false, false, "foo/bar", 1, []byte("qos1"))
3253 checkRecv("qos1", mqttPubQos1)
3254 }
3255
3256 func TestMQTTTrackPendingOverrun(t *testing.T) {
3257 sess := mqttSession{}
3258
3259 sess.last_pi = 0xFFFF
3260 pi := sess.trackPublishRetained("foo")
3261 if pi != 1 {
3262 t.Fatalf("Expected 1, got %v", pi)
3263 }
3264
3265 p := &mqttPending{}
3266 for i := 1; i <= 0xFFFF; i++ {
3267 sess.pendingPublish[uint16(i)] = p
3268 }
3269 pi, _ = sess.trackPublish("test", "test")
3270 if pi != 0 {
3271 t.Fatalf("Expected 0, got %v", pi)
3272 }
3273
3274 delete(sess.pendingPublish, 1234)
3275 pi = sess.trackPublishRetained("foo")
3276 if pi != 1234 {
3277 t.Fatalf("Expected 1234, got %v", pi)
3278 }
3279 }
3280
3281 func TestMQTTSubRestart(t *testing.T) {
3282 o := testMQTTDefaultOptions()
3283 s := testMQTTRunServer(t, o)
3284 defer testMQTTShutdownServer(s)
3285
3286 nc := natsConnect(t, s.ClientURL())
3287 defer nc.Close()
3288
3289 mc, r := testMQTTConnect(t, &mqttConnInfo{clientID: "sub", cleanSess: false}, o.MQTT.Host, o.MQTT.Port)
3290 defer mc.Close()
3291 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
3292
3293 // Start an MQTT subscription QoS=1 on "foo"
3294 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
3295 testMQTTFlush(t, mc, nil, r)
3296
3297 // Now start a NATS subscription on ">" (anything that would match the JS consumer delivery subject)
3298 natsSubSync(t, nc, ">")
3299 natsFlush(t, nc)
3300
3301 // Restart the MQTT client
3302 testMQTTDisconnect(t, mc, nil)
3303 mc.Close()
3304
3305 mc, r = testMQTTConnect(t, &mqttConnInfo{clientID: "sub", cleanSess: false}, o.MQTT.Host, o.MQTT.Port)
3306 defer mc.Close()
3307 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
3308
3309 // Restart an MQTT subscription QoS=1 on "foo"
3310 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
3311 testMQTTFlush(t, mc, nil, r)
3312
3313 pc, pr := testMQTTConnect(t, &mqttConnInfo{clientID: "pub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3314 defer pc.Close()
3315 testMQTTCheckConnAck(t, pr, mqttConnAckRCConnectionAccepted, false)
3316
3317 // Publish a message QoS1
3318 testMQTTPublish(t, pc, pr, 1, false, false, "foo", 1, []byte("msg1"))
3319 // Make sure we receive it
3320 testMQTTCheckPubMsg(t, mc, r, "foo", mqttPubQos1, []byte("msg1"))
3321
3322 // Now "restart" the subscription but as a Qos0
3323 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo", qos: 0}}, []byte{0})
3324 testMQTTFlush(t, mc, nil, r)
3325
3326 // Publish a message QoS
3327 testMQTTPublish(t, pc, pr, 1, false, false, "foo", 1, []byte("msg2"))
3328 // Make sure we receive but as a QoS0
3329 testMQTTCheckPubMsg(t, mc, r, "foo", 0, []byte("msg2"))
3330 }
3331
3332 func testMQTTGetClusterTemplaceNoLeaf() string {
3333 return strings.Replace(jsClusterTemplWithLeafAndMQTT, "{{leaf}}", "", 1)
3334 }
3335
3336 func TestMQTTSubPropagation(t *testing.T) {
3337 cl := createJetStreamClusterWithTemplate(t, testMQTTGetClusterTemplaceNoLeaf(), "MQTT", 2)
3338 defer cl.shutdown()
3339
3340 o := cl.opts[0]
3341 s2 := cl.servers[1]
3342 nc := natsConnect(t, s2.ClientURL())
3343 defer nc.Close()
3344
3345 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3346 defer mc.Close()
3347 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
3348
3349 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo/#", qos: 0}}, []byte{0})
3350 testMQTTFlush(t, mc, nil, r)
3351
3352 // Because in MQTT foo/# means foo.> but also foo, check that this is propagated
3353 checkSubInterest(t, s2, globalAccountName, "foo", time.Second)
3354
3355 // Publish on foo.bar, foo./ and foo and we should receive them
3356 natsPub(t, nc, "foo.bar", []byte("hello"))
3357 testMQTTCheckPubMsg(t, mc, r, "foo/bar", 0, []byte("hello"))
3358
3359 natsPub(t, nc, "foo./", []byte("from"))
3360 testMQTTCheckPubMsg(t, mc, r, "foo/", 0, []byte("from"))
3361
3362 natsPub(t, nc, "foo", []byte("NATS"))
3363 testMQTTCheckPubMsg(t, mc, r, "foo", 0, []byte("NATS"))
3364 }
3365
3366 func TestMQTTCluster(t *testing.T) {
3367 cl := createJetStreamClusterWithTemplate(t, testMQTTGetClusterTemplaceNoLeaf(), "MQTT", 2)
3368 defer cl.shutdown()
3369
3370 for _, topTest := range []struct {
3371 name string
3372 restart bool
3373 }{
3374 {"first_start", true},
3375 {"restart", false},
3376 } {
3377 t.Run(topTest.name, func(t *testing.T) {
3378 for _, test := range []struct {
3379 name string
3380 subQos byte
3381 }{
3382 {"qos_0", 0},
3383 {"qos_1", 1},
3384 } {
3385 t.Run(test.name, func(t *testing.T) {
3386 clientID := nuid.Next()
3387
3388 o := cl.opts[0]
3389 mc, r := testMQTTConnectRetry(t, &mqttConnInfo{clientID: clientID, cleanSess: false}, o.MQTT.Host, o.MQTT.Port, 5)
3390 defer mc.Close()
3391 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
3392
3393 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo/#", qos: test.subQos}}, []byte{test.subQos})
3394 testMQTTFlush(t, mc, nil, r)
3395
3396 check := func(mc net.Conn, r *mqttReader, o *Options, s *Server) {
3397 t.Helper()
3398
3399 nc := natsConnect(t, s.ClientURL())
3400 defer nc.Close()
3401
3402 natsPub(t, nc, "foo.bar", []byte("fromNats"))
3403 testMQTTCheckPubMsg(t, mc, r, "foo/bar", 0, []byte("fromNats"))
3404
3405 mpc, pr := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3406 defer mpc.Close()
3407 testMQTTCheckConnAck(t, pr, mqttConnAckRCConnectionAccepted, false)
3408
3409 testMQTTPublish(t, mpc, pr, 0, false, false, "foo/baz", 0, []byte("mqtt_qos0"))
3410 testMQTTCheckPubMsg(t, mc, r, "foo/baz", 0, []byte("mqtt_qos0"))
3411
3412 testMQTTPublish(t, mpc, pr, 1, false, false, "foo/bat", 1, []byte("mqtt_qos1"))
3413 expectedQoS := byte(0)
3414 if test.subQos == 1 {
3415 expectedQoS = mqttPubQos1
3416 }
3417 testMQTTCheckPubMsg(t, mc, r, "foo/bat", expectedQoS, []byte("mqtt_qos1"))
3418 testMQTTDisconnect(t, mpc, nil)
3419 }
3420 check(mc, r, cl.opts[0], cl.servers[0])
3421 check(mc, r, cl.opts[1], cl.servers[1])
3422
3423 // Start the same subscription from the other server. It should disconnect
3424 // the one connected in the first server.
3425 o = cl.opts[1]
3426
3427 mc2, r2 := testMQTTConnect(t, &mqttConnInfo{clientID: clientID, cleanSess: false}, o.MQTT.Host, o.MQTT.Port)
3428 defer mc2.Close()
3429 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, true)
3430
3431 // Expect first connection to be closed.
3432 testMQTTExpectDisconnect(t, mc)
3433
3434 // Now re-run the checks
3435 check(mc2, r2, cl.opts[0], cl.servers[0])
3436 check(mc2, r2, cl.opts[1], cl.servers[1])
3437
3438 // Disconnect our sub and restart with clean session then disconnect again to clear the state.
3439 testMQTTDisconnect(t, mc2, nil)
3440 mc2.Close()
3441 mc2, r2 = testMQTTConnect(t, &mqttConnInfo{clientID: clientID, cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3442 defer mc2.Close()
3443 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, false)
3444 testMQTTFlush(t, mc2, nil, r2)
3445 testMQTTDisconnect(t, mc2, nil)
3446
3447 // Remove the session from the flappers so we can restart the test
3448 // without failure and have to wait for 1sec before being able to reconnect.
3449 s := cl.servers[0]
3450 sm := &s.mqtt.sessmgr
3451 sm.mu.Lock()
3452 asm := sm.sessions[globalAccountName]
3453 sm.mu.Unlock()
3454 if asm != nil {
3455 asm.mu.Lock()
3456 delete(asm.flappers, clientID)
3457 asm.mu.Unlock()
3458 }
3459 })
3460 }
3461 if !t.Failed() && topTest.restart {
3462 cl.stopAll()
3463 cl.restartAll()
3464
3465 streams := []string{mqttStreamName, mqttRetainedMsgsStreamName, mqttSessStreamName}
3466 for _, sn := range streams {
3467 cl.waitOnStreamLeader(globalAccountName, sn)
3468 }
3469
3470 mset, err := cl.randomServer().GlobalAccount().lookupStream(mqttRetainedMsgsStreamName)
3471 if err != nil {
3472 t.Fatalf("Expected to find a stream for %q", mqttRetainedMsgsStreamName)
3473 }
3474
3475 rmConsumerNames := []string{}
3476 mset.mu.RLock()
3477 for _, o := range mset.consumers {
3478 rmConsumerNames = append(rmConsumerNames, o.name)
3479 }
3480 mset.mu.RUnlock()
3481
3482 for _, consumerName := range rmConsumerNames {
3483 cl.waitOnConsumerLeader(globalAccountName, mqttRetainedMsgsStreamName, consumerName)
3484 }
3485 }
3486 })
3487 }
3488 }
3489
3490 func testMQTTConnectDisconnect(t *testing.T, o *Options, clientID string, clean bool, found bool) {
3491 t.Helper()
3492 mc, r := testMQTTConnect(t, &mqttConnInfo{clientID: clientID, cleanSess: clean}, o.MQTT.Host, o.MQTT.Port)
3493 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, found)
3494 testMQTTDisconnectEx(t, mc, nil, false)
3495 mc.Close()
3496 }
3497
3498 func TestMQTTClusterConnectDisconnectClean(t *testing.T) {
3499 // The purpose of this test was to illustrate and verify
3500 // https://github.com/nats-io/nats-server/pull/4734. Due to its timing
3501 // sensitivity it has never been 100% reliable, prone to flaking on an
3502 // occasional MQTT Connect failure (API timeout?). Skip for now, to reduce
3503 // the flaky noise.
3504 t.Skip()
3505
3506 nServers := 3
3507 cl := createJetStreamClusterWithTemplate(t, testMQTTGetClusterTemplaceNoLeaf(), "MQTT", nServers)
3508 defer cl.shutdown()
3509
3510 clientID := nuid.Next()
3511
3512 // test runs a connect/disconnect against a random server in the cluster, as
3513 // specified.
3514 N := 100
3515 for n := 0; n < N; n++ {
3516 testMQTTConnectDisconnect(t, cl.opts[rand.Intn(nServers)], clientID, true, false)
3517 }
3518 }
3519
3520 func TestMQTTClusterConnectDisconnectPersist(t *testing.T) {
3521 // The purpose of this test was to illustrate and verify
3522 // https://github.com/nats-io/nats-server/pull/4734. Due to its timing
3523 // sensitivity it has never been 100% reliable, prone to flaking on an
3524 // occasional MQTT Connect failure (API timeout?). Skip for now, to reduce
3525 // the flaky noise.
3526 t.Skip()
3527
3528 nServers := 3
3529 cl := createJetStreamClusterWithTemplate(t, testMQTTGetClusterTemplaceNoLeaf(), "MQTT", nServers)
3530 defer cl.shutdown()
3531
3532 clientID := nuid.Next()
3533
3534 // test runs a connect/disconnect against a random server in the cluster, as
3535 // specified.
3536 N := 20
3537 for n := 0; n < N; n++ {
3538 // First clean sessions on all servers
3539 for i := 0; i < nServers; i++ {
3540 testMQTTConnectDisconnect(t, cl.opts[i], clientID, true, false)
3541 }
3542
3543 testMQTTConnectDisconnect(t, cl.opts[0], clientID, false, false)
3544 testMQTTConnectDisconnect(t, cl.opts[1], clientID, false, true)
3545 testMQTTConnectDisconnect(t, cl.opts[2], clientID, false, true)
3546 testMQTTConnectDisconnect(t, cl.opts[0], clientID, false, true)
3547 }
3548 }
3549
3550 func TestMQTTClusterRetainedMsg(t *testing.T) {
3551 cl := createJetStreamClusterWithTemplate(t, testMQTTGetClusterTemplaceNoLeaf(), "MQTT", 2)
3552 defer cl.shutdown()
3553
3554 srv1Opts := cl.opts[0]
3555 srv2Opts := cl.opts[1]
3556
3557 // Connect subscription on server 1.
3558 mc, rc := testMQTTConnectRetry(t, &mqttConnInfo{clientID: "sub", cleanSess: false}, srv1Opts.MQTT.Host, srv1Opts.MQTT.Port, 5)
3559 defer mc.Close()
3560 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
3561
3562 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/#", qos: 1}}, []byte{1})
3563 testMQTTFlush(t, mc, nil, rc)
3564
3565 // Create a publisher from server 2.
3566 mp, rp := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, srv2Opts.MQTT.Host, srv2Opts.MQTT.Port)
3567 defer mp.Close()
3568 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
3569
3570 // Send retained message.
3571 testMQTTPublish(t, mp, rp, 1, false, true, "foo/bar", 1, []byte("retained"))
3572 // Check it is received.
3573 testMQTTCheckPubMsg(t, mc, rc, "foo/bar", mqttPubQos1, []byte("retained"))
3574
3575 // Start a new subscription on server 1 and make sure we receive the retained message
3576 mc2, rc2 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, srv1Opts.MQTT.Host, srv1Opts.MQTT.Port)
3577 defer mc2.Close()
3578 testMQTTCheckConnAck(t, rc2, mqttConnAckRCConnectionAccepted, false)
3579 testMQTTSub(t, 1, mc2, rc2, []*mqttFilter{{filter: "foo/#", qos: 1}}, []byte{1})
3580 testMQTTCheckPubMsg(t, mc2, rc2, "foo/bar", mqttPubQos1|mqttPubFlagRetain, []byte("retained"))
3581 testMQTTDisconnect(t, mc2, nil)
3582 mc2.Close()
3583
3584 // Send an empty retained message which should remove it from storage, but still be delivered.
3585 testMQTTPublish(t, mp, rp, 1, false, true, "foo/bar", 1, []byte(""))
3586 testMQTTCheckPubMsg(t, mc, rc, "foo/bar", mqttPubQos1, []byte(""))
3587
3588 // Now shutdown the consumer connection
3589 testMQTTDisconnect(t, mc, nil)
3590 mc.Close()
3591
3592 // Reconnect to server where the retained message was published (server 2)
3593 mc, rc = testMQTTConnect(t, &mqttConnInfo{clientID: "sub", cleanSess: false}, srv2Opts.MQTT.Host, srv2Opts.MQTT.Port)
3594 defer mc.Close()
3595 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, true)
3596 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/#", qos: 1}}, []byte{1})
3597 // The retained message should not be delivered.
3598 testMQTTExpectNothing(t, rc)
3599 // Now disconnect and reconnect back to first server
3600 testMQTTDisconnect(t, mc, nil)
3601 mc.Close()
3602
3603 // Now reconnect to the server 1, which is not where the messages were published, and check
3604 // that we don't receive the message.
3605 mc, rc = testMQTTConnect(t, &mqttConnInfo{clientID: "sub", cleanSess: false}, srv1Opts.MQTT.Host, srv1Opts.MQTT.Port)
3606 defer mc.Close()
3607 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, true)
3608 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/#", qos: 1}}, []byte{1})
3609 testMQTTExpectNothing(t, rc)
3610 testMQTTDisconnect(t, mc, nil)
3611 mc.Close()
3612
3613 // Will now test network deletes
3614
3615 // Create a subscription on server 1 and server 2
3616 mc, rc = testMQTTConnect(t, &mqttConnInfo{clientID: "sub_one", cleanSess: false}, srv1Opts.MQTT.Host, srv1Opts.MQTT.Port)
3617 defer mc.Close()
3618 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
3619 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
3620 testMQTTFlush(t, mc, nil, rc)
3621
3622 mc2, rc2 = testMQTTConnect(t, &mqttConnInfo{clientID: "sub_two", cleanSess: false}, srv2Opts.MQTT.Host, srv2Opts.MQTT.Port)
3623 defer mc2.Close()
3624 testMQTTCheckConnAck(t, rc2, mqttConnAckRCConnectionAccepted, false)
3625 testMQTTSub(t, 1, mc2, rc2, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
3626 testMQTTFlush(t, mc2, nil, rc2)
3627
3628 // Publish 1 retained message (producer is connected to server 2)
3629 testMQTTPublish(t, mp, rp, 1, false, true, "bar", 1, []byte("msg1"))
3630
3631 // Make sure messages are received by both
3632 testMQTTCheckPubMsg(t, mc, rc, "bar", mqttPubQos1, []byte("msg1"))
3633 testMQTTCheckPubMsg(t, mc2, rc2, "bar", mqttPubQos1, []byte("msg1"))
3634
3635 // Now send an empty retained message that should delete it. For the one on server 1,
3636 // this will be a network delete.
3637 testMQTTPublish(t, mp, rp, 1, false, true, "bar", 1, []byte(""))
3638 testMQTTCheckPubMsg(t, mc, rc, "bar", mqttPubQos1, []byte(""))
3639 testMQTTCheckPubMsg(t, mc2, rc2, "bar", mqttPubQos1, []byte(""))
3640
3641 // Now send a new retained message
3642 testMQTTPublish(t, mp, rp, 1, false, true, "bar", 1, []byte("msg2"))
3643
3644 // Again, verify that they all receive it.
3645 testMQTTCheckPubMsg(t, mc, rc, "bar", mqttPubQos1, []byte("msg2"))
3646 testMQTTCheckPubMsg(t, mc2, rc2, "bar", mqttPubQos1, []byte("msg2"))
3647
3648 // But now, restart the consumer that was in the server that processed the
3649 // original network delete.
3650 testMQTTDisconnect(t, mc, nil)
3651 mc.Close()
3652
3653 mc, rc = testMQTTConnect(t, &mqttConnInfo{clientID: "sub_one", cleanSess: false}, srv1Opts.MQTT.Host, srv1Opts.MQTT.Port)
3654 defer mc.Close()
3655 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, true)
3656 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
3657 // Expect the message to be delivered as retained
3658 testMQTTCheckPubMsg(t, mc, rc, "bar", mqttPubQos1|mqttPubFlagRetain, []byte("msg2"))
3659 }
3660
3661 func TestMQTTRetainedMsgMigration(t *testing.T) {
3662 o := testMQTTDefaultOptions()
3663 s := testMQTTRunServer(t, o)
3664 defer testMQTTShutdownServer(s)
3665
3666 nc, js := jsClientConnect(t, s)
3667 defer nc.Close()
3668
3669 // Create the retained messages stream to listen on the old subject first.
3670 // The server will correct this when the migration takes place.
3671 _, err := js.AddStream(&nats.StreamConfig{
3672 Name: mqttRetainedMsgsStreamName,
3673 Subjects: []string{`$MQTT.rmsgs`},
3674 Storage: nats.FileStorage,
3675 Retention: nats.LimitsPolicy,
3676 Replicas: 1,
3677 })
3678 require_NoError(t, err)
3679
3680 // Publish some retained messages on the old "$MQTT.rmsgs" subject.
3681 const N = 100
3682 for i := 0; i < N; i++ {
3683 msg := fmt.Sprintf(
3684 `{"origin":"b5IQZNtG","subject":"test%d","topic":"test%d","msg":"YmFy","flags":1}`, i, i,
3685 )
3686 _, err := js.Publish(`$MQTT.rmsgs`, []byte(msg))
3687 require_NoError(t, err)
3688 }
3689
3690 // Check that the old subject looks right.
3691 si, err := js.StreamInfo(mqttRetainedMsgsStreamName, &nats.StreamInfoRequest{
3692 SubjectsFilter: `$MQTT.>`,
3693 })
3694 require_NoError(t, err)
3695 if si.State.NumSubjects != 1 {
3696 t.Fatalf("expected 1 subject, got %d", si.State.NumSubjects)
3697 }
3698 if n := si.State.Subjects[`$MQTT.rmsgs`]; n != N {
3699 t.Fatalf("expected to find %d messages on the original subject but found %d", N, n)
3700 }
3701
3702 // Create an MQTT client, this will cause a migration to take place.
3703 mc, rc := testMQTTConnect(t, &mqttConnInfo{clientID: "sub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3704 defer mc.Close()
3705 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
3706
3707 as := testMQTTGetAccountSessionManager(t, s, "sub")
3708 checkFor(t, time.Second, 10*time.Millisecond, func() error {
3709 as.mu.RLock()
3710 defer as.mu.RUnlock()
3711 if n := as.retmsgs.Size(); n != N {
3712 return fmt.Errorf("Got only %v retained messages", n)
3713 }
3714 return nil
3715 })
3716
3717 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "+", qos: 0}}, []byte{0})
3718 topics := map[string]struct{}{}
3719 for i := 0; i < N; i++ {
3720 _, _, topic, _ := testMQTTGetPubMsgEx(t, mc, rc, _EMPTY_, []byte("bar"))
3721 topics[topic] = struct{}{}
3722 }
3723 if len(topics) != N {
3724 t.Fatalf("Unexpected topics: %v", topics)
3725 }
3726
3727 // Now look at the stream, there should be N messages on the new
3728 // divided subjects and none on the old undivided subject.
3729 si, err = js.StreamInfo(mqttRetainedMsgsStreamName, &nats.StreamInfoRequest{
3730 SubjectsFilter: `$MQTT.>`,
3731 })
3732 require_NoError(t, err)
3733 if si.State.NumSubjects != N {
3734 t.Fatalf("expected %d subjects, got %d", N, si.State.NumSubjects)
3735 }
3736 if n := si.State.Subjects[`$MQTT.rmsgs`]; n > 0 {
3737 t.Fatalf("expected to find no messages on the original subject but found %d", n)
3738 }
3739
3740 // Check that the message counts look right. There should be one
3741 // retained message per key.
3742 for i := 0; i < N; i++ {
3743 expected := fmt.Sprintf(`$MQTT.rmsgs.test%d`, i)
3744 n, ok := si.State.Subjects[expected]
3745 if !ok {
3746 t.Fatalf("expected to find %q but didn't", expected)
3747 }
3748 if n != 1 {
3749 t.Fatalf("expected %q to have 1 message but had %d", expected, n)
3750 }
3751 }
3752 }
3753
3754 func TestMQTTRetainedNoMsgBodyCorruption(t *testing.T) {
3755 f := func() {
3756 o := testMQTTDefaultOptions()
3757 s := testMQTTRunServer(t, o)
3758 defer testMQTTShutdownServer(s)
3759
3760 // Send a retained message.
3761 c, r := testMQTTConnect(t, &mqttConnInfo{clientID: "pub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3762 defer c.Close()
3763 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
3764 testMQTTPublish(t, c, r, 0, false, true, "foo/bar", 0, []byte("retained 1"))
3765 testMQTTFlush(t, c, nil, r)
3766
3767 checkRetained := func(msg string) {
3768 t.Helper()
3769 c, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
3770 defer c.Close()
3771 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
3772 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo/#", qos: 0}}, []byte{0})
3773 testMQTTCheckPubMsg(t, c, r, "foo/bar", mqttPubFlagRetain, []byte(msg))
3774 }
3775 // Subscribe to make it load into the cache.
3776 checkRetained("retained 1")
3777
3778 // Now send another one.
3779 testMQTTPublish(t, c, r, 0, false, true, "foo/bar", 0, []byte("retained 2"))
3780 testMQTTFlush(t, c, nil, r)
3781
3782 // Check it is updated
3783 checkRetained("retained 2")
3784
3785 // Now we will simulate an update coming from another server
3786 // if we were in cluster mode.
3787 nc := natsConnect(t, s.ClientURL())
3788 defer nc.Close()
3789
3790 msg := nats.NewMsg("$MQTT.rmsgs.foo.bar")
3791 msg.Header.Set(mqttNatsRetainedMessageOrigin, "XXXXXXXX")
3792 msg.Header.Set(mqttNatsRetainedMessageTopic, "foo/bar")
3793 msg.Header.Set(mqttNatsRetainedMessageFlags, "1")
3794 msg.Data = []byte("retained 3")
3795 nc.PublishMsg(msg)
3796 natsFlush(t, nc)
3797
3798 // Have a continuous flow of updates coming in
3799 wg := sync.WaitGroup{}
3800 wg.Add(1)
3801 ch := make(chan struct{})
3802 go func() {
3803 defer wg.Done()
3804 for {
3805 nc.PublishMsg(msg)
3806 select {
3807 case <-ch:
3808 return
3809 default:
3810 }
3811 }
3812 }()
3813
3814 // Retrieve the account session manager using the "pub" client we have.
3815 as := testMQTTGetAccountSessionManager(t, s, "pub")
3816 as.mu.RLock()
3817 cache := as.rmsCache
3818 as.mu.RUnlock()
3819
3820 // Wait to make sure at least the first update occurs
3821 checkFor(t, 5*time.Second, 10*time.Millisecond, func() error {
3822 v, ok := cache.Load("foo.bar")
3823 if !ok {
3824 return errors.New("not in the cache")
3825 }
3826 rm := v.(*mqttRetainedMsg)
3827 if !bytes.Equal(rm.Msg, []byte("retained 3")) {
3828 return fmt.Errorf("Retained message not updated, got %q", rm.Msg)
3829 }
3830 return nil
3831 })
3832 // Repeat starting a subscription to check the retained message and
3833 // make sure it is not corrupted. With the bug, the payload will at
3834 // the very least contain trailing "\r\n" and possibly be corrupted
3835 // (and the race detector would report a race).
3836 for range 50 {
3837 checkRetained("retained 3")
3838 }
3839 close(ch)
3840 wg.Wait()
3841 }
3842 for range 5 {
3843 f()
3844 }
3845 }
3846
3847 func TestMQTTClusterReplicasCount(t *testing.T) {
3848 for _, test := range []struct {
3849 size int
3850 replicas int
3851 }{
3852 {1, 1},
3853 {2, 2},
3854 {3, 3},
3855 {5, 3},
3856 } {
3857 t.Run(fmt.Sprintf("size %v", test.size), func(t *testing.T) {
3858 var s *Server
3859 var o *Options
3860 if test.size == 1 {
3861 o = testMQTTDefaultOptions()
3862 s = testMQTTRunServer(t, o)
3863 defer testMQTTShutdownServer(s)
3864 } else {
3865 cl := createJetStreamClusterWithTemplate(t, testMQTTGetClusterTemplaceNoLeaf(), "MQTT", test.size)
3866 defer cl.shutdown()
3867 o = cl.opts[0]
3868 s = cl.randomServer()
3869 }
3870
3871 mc, rc := testMQTTConnectRetry(t, &mqttConnInfo{clientID: "sub", cleanSess: false}, o.MQTT.Host, o.MQTT.Port, 5)
3872 defer mc.Close()
3873 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
3874 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/#", qos: 1}}, []byte{1})
3875 testMQTTFlush(t, mc, nil, rc)
3876
3877 nc := natsConnect(t, s.ClientURL())
3878 defer nc.Close()
3879
3880 // Check the replicas of all MQTT streams
3881 js, err := nc.JetStream()
3882 if err != nil {
3883 t.Fatalf("Error getting js: %v", err)
3884 }
3885 for _, sname := range []string{
3886 mqttStreamName,
3887 mqttRetainedMsgsStreamName,
3888 mqttSessStreamName,
3889 } {
3890 t.Run(sname, func(t *testing.T) {
3891 si, err := js.StreamInfo(sname)
3892 if err != nil {
3893 t.Fatalf("Error getting stream info: %v", err)
3894 }
3895 if si.Config.Replicas != test.replicas {
3896 t.Fatalf("Expected %v replicas, got %v", test.replicas, si.Config.Replicas)
3897 }
3898 })
3899 }
3900 })
3901 }
3902 }
3903
3904 func TestMQTTClusterCanCreateSessionWithOnServerDown(t *testing.T) {
3905 cl := createJetStreamClusterWithTemplate(t, testMQTTGetClusterTemplaceNoLeaf(), "MQTT", 3)
3906 defer cl.shutdown()
3907 o := cl.opts[0]
3908
3909 mc, rc := testMQTTConnectRetry(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 5)
3910 defer mc.Close()
3911 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
3912 mc.Close()
3913
3914 // Shutdown one of the server.
3915 sd := cl.servers[1].StoreDir()
3916 defer os.RemoveAll(strings.TrimSuffix(sd, JetStreamStoreDir))
3917 cl.servers[1].Shutdown()
3918
3919 // Make sure there is a meta leader
3920 cl.waitOnPeerCount(2)
3921 cl.waitOnLeader()
3922
3923 // Now try to create a new session. Since we use a single stream now for all sessions,
3924 // this should succeed.
3925 o = cl.opts[2]
3926 // We may still get failures because of some JS APIs may timeout while things
3927 // settle, so try again for a certain amount of times.
3928 mc, rc = testMQTTConnectRetry(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 5)
3929 defer mc.Close()
3930 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
3931 }
3932
3933 func TestMQTTClusterPlacement(t *testing.T) {
3934 sc := createJetStreamSuperCluster(t, 3, 2)
3935 defer sc.shutdown()
3936
3937 c := sc.randomCluster()
3938 lnc := c.createLeafNodesWithTemplateAndStartPort(jsClusterTemplWithLeafAndMQTT, "SPOKE", 3, 22111)
3939 defer lnc.shutdown()
3940
3941 sc.waitOnPeerCount(9)
3942 sc.waitOnLeader()
3943
3944 for i := 0; i < 10; i++ {
3945 mc, rc := testMQTTConnectRetry(t, &mqttConnInfo{cleanSess: true}, lnc.opts[i%3].MQTT.Host, lnc.opts[i%3].MQTT.Port, 5)
3946 defer mc.Close()
3947 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
3948 }
3949
3950 // Now check that MQTT assets have been created in the LEAF node's side, not the Hub.
3951 nc := natsConnect(t, lnc.servers[0].ClientURL())
3952 defer nc.Close()
3953 js, err := nc.JetStream()
3954 if err != nil {
3955 t.Fatalf("Unable to get JetStream: %v", err)
3956 }
3957 count := 0
3958 for si := range js.StreamsInfo() {
3959 if si.Cluster == nil || si.Cluster.Name != "SPOKE" {
3960 t.Fatalf("Expected asset %q to be placed on spoke cluster, was placed on %+v", si.Config.Name, si.Cluster)
3961 }
3962 for _, repl := range si.Cluster.Replicas {
3963 if !strings.HasPrefix(repl.Name, "SPOKE-") {
3964 t.Fatalf("Replica on the wrong cluster: %+v", repl)
3965 }
3966 }
3967 if si.State.Consumers > 0 {
3968 for ci := range js.ConsumersInfo(si.Config.Name) {
3969 if ci.Cluster == nil || ci.Cluster.Name != "SPOKE" {
3970 t.Fatalf("Expected asset %q to be placed on spoke cluster, was placed on %+v", ci.Name, si.Cluster)
3971 }
3972 for _, repl := range ci.Cluster.Replicas {
3973 if !strings.HasPrefix(repl.Name, "SPOKE-") {
3974 t.Fatalf("Replica on the wrong cluster: %+v", repl)
3975 }
3976 }
3977 }
3978 }
3979 count++
3980 }
3981 if count == 0 {
3982 t.Fatal("No stream found!")
3983 }
3984 }
3985
3986 func TestMQTTLeafnodeWithoutJSToClusterWithJSNoSharedSysAcc(t *testing.T) {
3987 test := func(t *testing.T, resolution int) {
3988 getClusterOpts := func(name string, i int) *Options {
3989 o := testMQTTDefaultOptions()
3990 o.ServerName = name
3991 o.Cluster.Name = "hub"
3992 // first two test cases rely on domain not being set in hub
3993 if resolution > 1 {
3994 o.JetStreamDomain = "DOMAIN"
3995 }
3996 o.Cluster.Host = "127.0.0.1"
3997 o.Cluster.Port = 2790 + i
3998 o.Routes = RoutesFromStr("nats://127.0.0.1:2791,nats://127.0.0.1:2792,nats://127.0.0.1:2793")
3999 o.LeafNode.Host = "127.0.0.1"
4000 o.LeafNode.Port = -1
4001 return o
4002 }
4003 o1 := getClusterOpts("S1", 1)
4004 s1 := testMQTTRunServer(t, o1)
4005 defer testMQTTShutdownServer(s1)
4006
4007 o2 := getClusterOpts("S2", 2)
4008 s2 := testMQTTRunServer(t, o2)
4009 defer testMQTTShutdownServer(s2)
4010
4011 o3 := getClusterOpts("S3", 3)
4012 s3 := testMQTTRunServer(t, o3)
4013 defer testMQTTShutdownServer(s3)
4014
4015 cluster := []*Server{s1, s2, s3}
4016 checkClusterFormed(t, cluster...)
4017 checkFor(t, 10*time.Second, 50*time.Millisecond, func() error {
4018 for _, s := range cluster {
4019 if s.JetStreamIsLeader() {
4020 // Need to wait for usage updates now to propagate to meta leader.
4021 if len(s.JetStreamClusterPeers()) == len(cluster) {
4022 time.Sleep(100 * time.Millisecond)
4023 return nil
4024 }
4025 }
4026 }
4027 return fmt.Errorf("no leader yet")
4028 })
4029
4030 // Now define a leafnode that has mqtt enabled, but no JS. This should still work.
4031 lno := testMQTTDefaultOptions()
4032 // Make sure jetstream is not explicitly defined here.
4033 lno.JetStream = false
4034 switch resolution {
4035 case 0:
4036 // turn off jetstream in $G by adding another account and set mqtt domain option and set account default
4037 lno.Accounts = append(lno.Accounts, NewAccount("unused-account"))
4038 fallthrough
4039 case 1:
4040 lno.JsAccDefaultDomain = map[string]string{"$G": ""}
4041 case 2:
4042 lno.JsAccDefaultDomain = map[string]string{"$G": o1.JetStreamDomain}
4043 case 3:
4044 // turn off jetstream in $G by adding another account and set mqtt domain option
4045 lno.Accounts = append(lno.Accounts, NewAccount("unused-account"))
4046 fallthrough
4047 case 4:
4048 // actual solution
4049 lno.MQTT.JsDomain = o1.JetStreamDomain
4050 case 5:
4051 // set per account overwrite and disable js in $G
4052 lno.Accounts = append(lno.Accounts, NewAccount("unused-account"))
4053 lno.JsAccDefaultDomain = map[string]string{
4054 "$G": o1.JetStreamDomain,
4055 }
4056 }
4057 // Whenever an account was added to disable JS in $G, enable it in the server
4058 if len(lno.Accounts) > 0 {
4059 lno.JetStream = true
4060 lno.JetStreamDomain = "OTHER"
4061 lno.StoreDir = t.TempDir()
4062 }
4063
4064 // Use RoutesFromStr() to make an array of urls
4065 urls := RoutesFromStr(fmt.Sprintf("nats://127.0.0.1:%d,nats://127.0.0.1:%d,nats://127.0.0.1:%d",
4066 o1.LeafNode.Port, o2.LeafNode.Port, o3.LeafNode.Port))
4067 lno.LeafNode.Remotes = []*RemoteLeafOpts{{URLs: urls}}
4068
4069 ln := RunServer(lno)
4070 defer testMQTTShutdownServer(ln)
4071
4072 checkLeafNodeConnected(t, ln)
4073
4074 // Now connect to leafnode and subscribe
4075 mc, rc := testMQTTConnectRetry(t, &mqttConnInfo{clientID: "sub", cleanSess: true}, lno.MQTT.Host, lno.MQTT.Port, 5)
4076 defer mc.Close()
4077 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
4078 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
4079 testMQTTFlush(t, mc, nil, rc)
4080
4081 connectAndPublish := func(o *Options) {
4082 mp, rp := testMQTTConnectRetry(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 5)
4083 defer mp.Close()
4084 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
4085
4086 testMQTTPublish(t, mp, rp, 1, false, false, "foo", 1, []byte("msg"))
4087 }
4088 // Connect a publisher from leafnode and publish, verify message is received.
4089 connectAndPublish(lno)
4090 testMQTTCheckPubMsg(t, mc, rc, "foo", mqttPubQos1, []byte("msg"))
4091
4092 // Connect from one server in the cluster check it works from there too.
4093 connectAndPublish(o3)
4094 testMQTTCheckPubMsg(t, mc, rc, "foo", mqttPubQos1, []byte("msg"))
4095
4096 // Connect from a server in the hub and subscribe
4097 mc2, rc2 := testMQTTConnectRetry(t, &mqttConnInfo{clientID: "sub2", cleanSess: true}, o2.MQTT.Host, o2.MQTT.Port, 5)
4098 defer mc2.Close()
4099 testMQTTCheckConnAck(t, rc2, mqttConnAckRCConnectionAccepted, false)
4100 testMQTTSub(t, 1, mc2, rc2, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
4101 testMQTTFlush(t, mc2, nil, rc2)
4102
4103 // Connect a publisher from leafnode and publish, verify message is received.
4104 connectAndPublish(lno)
4105 testMQTTCheckPubMsg(t, mc2, rc2, "foo", mqttPubQos1, []byte("msg"))
4106
4107 // Connect from one server in the cluster check it works from there too.
4108 connectAndPublish(o1)
4109 testMQTTCheckPubMsg(t, mc2, rc2, "foo", mqttPubQos1, []byte("msg"))
4110 }
4111 t.Run("backwards-compatibility-default-js-enabled-in-leaf", func(t *testing.T) {
4112 test(t, 0) // test with JsAccDefaultDomain set to default (pointing at hub) but jetstream enabled in leaf node too
4113 })
4114 t.Run("backwards-compatibility-default-js-disabled-in-leaf", func(t *testing.T) {
4115 // test with JsAccDefaultDomain set. Checks if it works with backwards compatibility code for empty domain
4116 test(t, 1)
4117 })
4118 t.Run("backwards-compatibility-domain-js-disabled-in-leaf", func(t *testing.T) {
4119 // test with JsAccDefaultDomain set. Checks if it works with backwards compatibility code for domain set
4120 test(t, 2) // test with domain set in mqtt client
4121 })
4122 t.Run("mqtt-explicit-js-enabled-in-leaf", func(t *testing.T) {
4123 test(t, 3) // test with domain set in mqtt client (pointing at hub) but jetstream enabled in leaf node too
4124 })
4125 t.Run("mqtt-explicit-js-disabled-in-leaf", func(t *testing.T) {
4126 test(t, 4) // test with domain set in mqtt client
4127 })
4128 t.Run("backwards-compatibility-domain-js-enabled-in-leaf", func(t *testing.T) {
4129 test(t, 5) // test with JsAccDefaultDomain set to domain (pointing at hub) but jetstream enabled in leaf node too
4130 })
4131 }
4132
4133 func TestMQTTImportExport(t *testing.T) {
4134 conf := createConfFile(t, []byte(fmt.Sprintf(`
4135 listen: "127.0.0.1:-1"
4136 server_name: "mqtt"
4137 jetstream {
4138 store_dir = %q
4139 }
4140 accounts {
4141 org {
4142 jetstream: enabled
4143 users: [{user: org, password: pwd}]
4144 imports = [{stream: {account: "device", subject: "foo"}, prefix: "org"}]
4145 }
4146 device {
4147 users: [{user: device, password: pwd}]
4148 exports = [{stream: "foo"}]
4149 }
4150 }
4151 mqtt {
4152 listen: "127.0.0.1:-1"
4153 }
4154 no_auth_user: device
4155 `, t.TempDir())))
4156 defer os.Remove(conf)
4157
4158 s, o := RunServerWithConfig(conf)
4159 defer s.Shutdown()
4160
4161 mc1, rc1 := testMQTTConnect(t, &mqttConnInfo{clientID: "sub1", user: "org", pass: "pwd", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4162 defer mc1.Close()
4163 testMQTTCheckConnAck(t, rc1, mqttConnAckRCConnectionAccepted, false)
4164 testMQTTSub(t, 1, mc1, rc1, []*mqttFilter{{filter: "org/foo", qos: 0}}, []byte{0})
4165 testMQTTFlush(t, mc1, nil, rc1)
4166
4167 mc2, rc2 := testMQTTConnect(t, &mqttConnInfo{clientID: "sub2", user: "org", pass: "pwd", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4168 defer mc2.Close()
4169 testMQTTCheckConnAck(t, rc2, mqttConnAckRCConnectionAccepted, false)
4170 testMQTTSub(t, 1, mc2, rc2, []*mqttFilter{{filter: "org/foo", qos: 1}}, []byte{1})
4171 testMQTTFlush(t, mc2, nil, rc2)
4172
4173 nc := natsConnect(t, s.ClientURL())
4174 defer nc.Close()
4175 natsPub(t, nc, "foo", []byte("msg"))
4176
4177 // Verify message is received on receiver side.
4178 testMQTTCheckPubMsg(t, mc1, rc1, "org/foo", 0, []byte("msg"))
4179 testMQTTCheckPubMsg(t, mc2, rc2, "org/foo", 0, []byte("msg"))
4180 }
4181
4182 func TestMQTTSessionMovingDomains(t *testing.T) {
4183 tmpl := strings.Replace(jsClusterTemplWithLeafAndMQTT, "{{leaf}}", `leafnodes { listen: 127.0.0.1:-1 }`, 1)
4184 tmpl = strings.Replace(tmpl, "store_dir:", "domain: HUB, store_dir:", 1)
4185 c := createJetStreamCluster(t, tmpl, "HUB", _EMPTY_, 3, 22020, true)
4186 defer c.shutdown()
4187 c.waitOnLeader()
4188
4189 tmpl = strings.Replace(jsClusterTemplWithLeafAndMQTT, "store_dir:", "domain: SPOKE, store_dir:", 1)
4190 lnc := c.createLeafNodesWithTemplateAndStartPort(tmpl, "SPOKE", 3, 22111)
4191 defer lnc.shutdown()
4192 lnc.waitOnPeerCount(3)
4193
4194 connectSubAndDisconnect := func(host string, port int, present bool) {
4195 t.Helper()
4196 mc, rc := testMQTTConnectRetry(t, &mqttConnInfo{clientID: "sub", cleanSess: false}, host, port, 5)
4197 defer mc.Close()
4198 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, present)
4199 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
4200 testMQTTFlush(t, mc, nil, rc)
4201 testMQTTDisconnect(t, mc, nil)
4202 }
4203
4204 // Create a session on the HUB. Make sure we don't use "clean" session so that
4205 // it is not removed when the client connection closes.
4206 for i := 0; i < 7; i++ {
4207 var present bool
4208 if i > 0 {
4209 present = true
4210 }
4211 connectSubAndDisconnect(c.opts[0].MQTT.Host, c.opts[0].MQTT.Port, present)
4212 }
4213
4214 // Now move to the SPOKE cluster, this is a brand new session there, so should not be present.
4215 connectSubAndDisconnect(lnc.opts[1].MQTT.Host, lnc.opts[1].MQTT.Port, false)
4216
4217 // Move back to HUB cluster. Make it interesting by connecting to a different
4218 // server in that cluster. This should work, and present flag should be true.
4219 connectSubAndDisconnect(c.opts[2].MQTT.Host, c.opts[2].MQTT.Port, true)
4220 }
4221
4222 type remoteConnSameClientIDLogger struct {
4223 DummyLogger
4224 warn chan string
4225 }
4226
4227 func (l *remoteConnSameClientIDLogger) Warnf(format string, args ...any) {
4228 msg := fmt.Sprintf(format, args...)
4229 if strings.Contains(msg, "remote connection has started with the same client ID") {
4230 l.warn <- msg
4231 }
4232 }
4233
4234 func TestMQTTSessionsDifferentDomains(t *testing.T) {
4235 tmpl := strings.Replace(jsClusterTemplWithLeafAndMQTT, "{{leaf}}", `leafnodes { listen: 127.0.0.1:-1 }`, 1)
4236 c := createJetStreamCluster(t, tmpl, "HUB", _EMPTY_, 3, 22020, true)
4237 defer c.shutdown()
4238 c.waitOnLeader()
4239
4240 tmpl = strings.Replace(jsClusterTemplWithLeafAndMQTT, "store_dir:", "domain: LEAF1, store_dir:", 1)
4241 lnc1 := c.createLeafNodesWithTemplateAndStartPort(tmpl, "LEAF1", 2, 22111)
4242 defer lnc1.shutdown()
4243 lnc1.waitOnPeerCount(2)
4244
4245 l := &remoteConnSameClientIDLogger{warn: make(chan string, 10)}
4246 lnc1.servers[0].SetLogger(l, false, false)
4247
4248 tmpl = strings.Replace(jsClusterTemplWithLeafAndMQTT, "store_dir:", "domain: LEAF2, store_dir:", 1)
4249 lnc2 := c.createLeafNodesWithTemplateAndStartPort(tmpl, "LEAF2", 2, 23111)
4250 defer lnc2.shutdown()
4251 lnc2.waitOnPeerCount(2)
4252
4253 o := &(lnc1.opts[0].MQTT)
4254 mc1, rc1 := testMQTTConnectRetry(t, &mqttConnInfo{clientID: "sub", cleanSess: false}, o.Host, o.Port, 5)
4255 defer mc1.Close()
4256 testMQTTCheckConnAck(t, rc1, mqttConnAckRCConnectionAccepted, false)
4257 testMQTTSub(t, 1, mc1, rc1, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
4258 testMQTTFlush(t, mc1, nil, rc1)
4259
4260 o = &(lnc2.opts[0].MQTT)
4261 connectSubAndDisconnect := func(host string, port int, present bool) {
4262 t.Helper()
4263 mc, rc := testMQTTConnectRetry(t, &mqttConnInfo{clientID: "sub", cleanSess: false}, host, port, 5)
4264 defer mc.Close()
4265 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, present)
4266 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
4267 testMQTTFlush(t, mc, nil, rc)
4268 testMQTTDisconnect(t, mc, nil)
4269 }
4270
4271 for i := 0; i < 2; i++ {
4272 connectSubAndDisconnect(o.Host, o.Port, i > 0)
4273 }
4274
4275 select {
4276 case w := <-l.warn:
4277 t.Fatalf("Got a warning: %v", w)
4278 case <-time.After(500 * time.Millisecond):
4279 // OK
4280 }
4281 }
4282
4283 func TestMQTTParseUnsub(t *testing.T) {
4284 for _, test := range []struct {
4285 name string
4286 proto []byte
4287 b byte
4288 pl int
4289 err string
4290 wantErr bool
4291 }{
4292 {"reserved flag", nil, 3, 0, "wrong unsubscribe reserved flags", false},
4293 {"ensure packet loaded", []byte{1, 2}, mqttUnsubscribeFlags, 10, io.ErrUnexpectedEOF.Error(), false},
4294 {"error reading packet id", []byte{1}, mqttUnsubscribeFlags, 1, "reading packet identifier", false},
4295 {"packet id cannot be zero", []byte{0, 0}, mqttUnsubscribeFlags, 2, errMQTTPacketIdentifierIsZero.Error(), false},
4296 {"missing filters", []byte{0, 1}, mqttUnsubscribeFlags, 2, "subscribe protocol must contain at least 1 topic filter", false},
4297 {"error reading topic", []byte{0, 1, 0, 2, 'a'}, mqttUnsubscribeFlags, 5, "topic filter", false},
4298 {"empty topic", []byte{0, 1, 0, 0}, mqttUnsubscribeFlags, 4, errMQTTTopicFilterCannotBeEmpty.Error(), false},
4299 {"invalid utf8 topic", []byte{0, 1, 0, 1, 241}, mqttUnsubscribeFlags, 5, "invalid utf8 for topic filter", false},
4300 {"topic with null byte", []byte{0, 1, 0, 3, 'a', 0, 'b'}, mqttUnsubscribeFlags, 7, "", true},
4301 } {
4302 t.Run(test.name, func(t *testing.T) {
4303 r := &mqttReader{}
4304 r.reset(test.proto)
4305 mqtt := &mqtt{r: r}
4306 c := &client{mqtt: mqtt}
4307 _, _, err := c.mqttParseSubsOrUnsubs(r, test.b, test.pl, false)
4308 if test.wantErr {
4309 if err == nil {
4310 t.Fatal("Expected an error, got none")
4311 }
4312 return
4313 }
4314 if err == nil || !strings.Contains(err.Error(), test.err) {
4315 t.Fatalf("Expected error %q, got %v", test.err, err)
4316 }
4317 })
4318 }
4319 }
4320
4321 func testMQTTUnsub(t *testing.T, pi uint16, c net.Conn, r *mqttReader, filters []*mqttFilter) {
4322 t.Helper()
4323 w := newMQTTWriter(0)
4324 pkLen := 2 // for pi
4325 for i := 0; i < len(filters); i++ {
4326 f := filters[i]
4327 pkLen += 2 + len(f.filter)
4328 }
4329 w.WriteByte(mqttPacketUnsub | mqttUnsubscribeFlags)
4330 w.WriteVarInt(pkLen)
4331 w.WriteUint16(pi)
4332 for i := 0; i < len(filters); i++ {
4333 f := filters[i]
4334 w.WriteBytes([]byte(f.filter))
4335 }
4336 if _, err := testMQTTWrite(c, w.Bytes()); err != nil {
4337 t.Fatalf("Error writing UNSUBSCRIBE protocol: %v", err)
4338 }
4339 b, _ := testMQTTReadPacket(t, r)
4340 if pt := b & mqttPacketMask; pt != mqttPacketUnsubAck {
4341 t.Fatalf("Expected UNSUBACK packet %x, got %x", mqttPacketUnsubAck, pt)
4342 }
4343 rpi, err := r.readUint16("packet identifier")
4344 if err != nil || rpi != pi {
4345 t.Fatalf("Error with packet identifier expected=%v got: %v err=%v", pi, rpi, err)
4346 }
4347 }
4348
4349 func TestMQTTUnsub(t *testing.T) {
4350 o := testMQTTDefaultOptions()
4351 s := testMQTTRunServer(t, o)
4352 defer testMQTTShutdownServer(s)
4353
4354 mcp, mpr := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4355 defer mcp.Close()
4356 testMQTTCheckConnAck(t, mpr, mqttConnAckRCConnectionAccepted, false)
4357
4358 mc, r := testMQTTConnect(t, &mqttConnInfo{user: "sub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4359 defer mc.Close()
4360 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
4361
4362 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo", qos: 0}}, []byte{0})
4363 testMQTTFlush(t, mc, nil, r)
4364
4365 // Publish and test msg received
4366 testMQTTPublish(t, mcp, r, 0, false, false, "foo", 0, []byte("msg"))
4367 testMQTTCheckPubMsg(t, mc, r, "foo", 0, []byte("msg"))
4368
4369 // Unsubscribe
4370 testMQTTUnsub(t, 1, mc, r, []*mqttFilter{{filter: "foo"}})
4371
4372 // Publish and test msg not received
4373 testMQTTPublish(t, mcp, r, 0, false, false, "foo", 0, []byte("msg"))
4374 testMQTTExpectNothing(t, r)
4375
4376 // Use of wildcards subs
4377 filters := []*mqttFilter{
4378 {filter: "foo/bar", qos: 0},
4379 {filter: "foo/#", qos: 0},
4380 }
4381 testMQTTSub(t, 1, mc, r, filters, []byte{0, 0})
4382 testMQTTFlush(t, mc, nil, r)
4383
4384 // Publish and check that message received twice
4385 testMQTTPublish(t, mcp, r, 0, false, false, "foo/bar", 0, []byte("msg"))
4386 testMQTTCheckPubMsg(t, mc, r, "foo/bar", 0, []byte("msg"))
4387 testMQTTCheckPubMsg(t, mc, r, "foo/bar", 0, []byte("msg"))
4388
4389 // Unsub the wildcard one
4390 testMQTTUnsub(t, 1, mc, r, []*mqttFilter{{filter: "foo/#"}})
4391 // Publish and check that message received once
4392 testMQTTPublish(t, mcp, r, 0, false, false, "foo/bar", 0, []byte("msg"))
4393 testMQTTCheckPubMsg(t, mc, r, "foo/bar", 0, []byte("msg"))
4394 testMQTTExpectNothing(t, r)
4395
4396 // Unsub last
4397 testMQTTUnsub(t, 1, mc, r, []*mqttFilter{{filter: "foo/bar"}})
4398 // Publish and test msg not received
4399 testMQTTPublish(t, mcp, r, 0, false, false, "foo/bar", 0, []byte("msg"))
4400 testMQTTExpectNothing(t, r)
4401 }
4402
4403 func testMQTTExpectDisconnect(t testing.TB, c net.Conn) {
4404 t.Helper()
4405 buf, err := testMQTTRead(c)
4406 if err == nil {
4407 t.Fatalf("Expected connection to be disconnected, got %s", buf)
4408 }
4409 // Distinguish real disconnection (EOF, connection reset) from timeout
4410 if ne, ok := err.(net.Error); ok && ne.Timeout() {
4411 t.Fatal("Expected a disconnect but got a timeout error")
4412 }
4413 }
4414
4415 func TestMQTTPublishTopicErrors(t *testing.T) {
4416 o := testMQTTDefaultOptions()
4417 s := testMQTTRunServer(t, o)
4418 defer testMQTTShutdownServer(s)
4419
4420 for _, test := range []struct {
4421 name string
4422 topic string
4423 }{
4424 {"empty", ""},
4425 {"with single level wildcard", "foo/+"},
4426 {"with multiple level wildcard", "foo/#"},
4427 {"with tab", "foo\tbar"},
4428 {"with line feed", "foo\nbar"},
4429 {"with carriage return", "foo\rbar"},
4430 {"with form feed", "foo\fbar"},
4431 } {
4432 t.Run(test.name, func(t *testing.T) {
4433 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4434 defer mc.Close()
4435 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
4436
4437 testMQTTPublish(t, mc, r, 0, false, false, test.topic, 0, []byte("msg"))
4438 testMQTTExpectDisconnect(t, mc)
4439 })
4440 }
4441 }
4442
4443 func testMQTTDisconnect(t testing.TB, c net.Conn, bw *bufio.Writer) {
4444 t.Helper()
4445 testMQTTDisconnectEx(t, c, bw, true)
4446 }
4447
4448 func testMQTTDisconnectEx(t testing.TB, c net.Conn, bw *bufio.Writer, wait bool) {
4449 t.Helper()
4450 w := newMQTTWriter(0)
4451 w.WriteByte(mqttPacketDisconnect)
4452 w.WriteByte(0)
4453 if bw != nil {
4454 bw.Write(w.Bytes())
4455 bw.Flush()
4456 } else {
4457 c.Write(w.Bytes())
4458 }
4459 if wait {
4460 testMQTTExpectDisconnect(t, c)
4461 }
4462 }
4463
4464 func TestMQTTWill(t *testing.T) {
4465 o := testMQTTDefaultOptions()
4466 s := testMQTTRunServer(t, o)
4467 defer testMQTTShutdownServer(s)
4468
4469 nc := natsConnect(t, s.ClientURL())
4470 defer nc.Close()
4471
4472 sub := natsSubSync(t, nc, "will.topic")
4473 natsFlush(t, nc)
4474
4475 willMsg := []byte("bye")
4476
4477 for _, test := range []struct {
4478 name string
4479 willExpected bool
4480 willQoS byte
4481 }{
4482 {"will qos 0", true, 0},
4483 {"will qos 1", true, 1},
4484 {"will qos 2", true, 2},
4485 {"proper disconnect no will", false, 0},
4486 } {
4487 t.Run(test.name, func(t *testing.T) {
4488 mcs, rs := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4489 defer mcs.Close()
4490 testMQTTCheckConnAck(t, rs, mqttConnAckRCConnectionAccepted, false)
4491
4492 testMQTTSub(t, 1, mcs, rs, []*mqttFilter{{filter: "will/#", qos: 2}}, []byte{2})
4493 testMQTTFlush(t, mcs, nil, rs)
4494
4495 mc, r := testMQTTConnect(t,
4496 &mqttConnInfo{
4497 cleanSess: true,
4498 will: &mqttWill{
4499 topic: []byte("will/topic"),
4500 message: willMsg,
4501 qos: test.willQoS,
4502 },
4503 }, o.MQTT.Host, o.MQTT.Port)
4504 defer mc.Close()
4505 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
4506
4507 if test.willExpected {
4508 mc.Close()
4509 testMQTTCheckPubMsg(t, mcs, rs, "will/topic", test.willQoS<<1, willMsg)
4510 wm := natsNexMsg(t, sub, time.Second)
4511 if !bytes.Equal(wm.Data, willMsg) {
4512 t.Fatalf("Expected will message to be %q, got %q", willMsg, wm.Data)
4513 }
4514 } else {
4515 testMQTTDisconnect(t, mc, nil)
4516 testMQTTExpectNothing(t, rs)
4517 if wm, err := sub.NextMsg(100 * time.Millisecond); err == nil {
4518 t.Fatalf("Should not have receive a message, got subj=%q data=%q",
4519 wm.Subject, wm.Data)
4520 }
4521 }
4522 })
4523 }
4524 }
4525
4526 func TestMQTTQoS2WillReject(t *testing.T) {
4527 o := testMQTTDefaultOptions()
4528 o.MQTT.rejectQoS2Pub = true
4529 s := testMQTTRunServer(t, o)
4530 defer testMQTTShutdownServer(s)
4531
4532 mcs, rs := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4533 defer mcs.Close()
4534 testMQTTCheckConnAck(t, rs, mqttConnAckRCConnectionAccepted, false)
4535
4536 testMQTTSub(t, 1, mcs, rs, []*mqttFilter{{filter: "will/#", qos: 2}}, []byte{2})
4537 testMQTTFlush(t, mcs, nil, rs)
4538
4539 mc, r := testMQTTConnect(t,
4540 &mqttConnInfo{
4541 cleanSess: true,
4542 will: &mqttWill{
4543 topic: []byte("will/topic"),
4544 message: []byte("bye"),
4545 qos: 2,
4546 },
4547 }, o.MQTT.Host, o.MQTT.Port)
4548 defer mc.Close()
4549 testMQTTCheckConnAck(t, r, mqttConnAckRCQoS2WillRejected, false)
4550 }
4551
4552 func TestMQTTWillRetain(t *testing.T) {
4553 for _, test := range []struct {
4554 name string
4555 pubQoS byte
4556 subQoS byte
4557 }{
4558 {"pub QoS0 sub QoS0", 0, 0},
4559 {"pub QoS0 sub QoS1", 0, 1},
4560 {"pub QoS1 sub QoS0", 1, 0},
4561 {"pub QoS1 sub QoS1", 1, 1},
4562 } {
4563 t.Run(test.name, func(t *testing.T) {
4564 o := testMQTTDefaultOptions()
4565 s := testMQTTRunServer(t, o)
4566 defer testMQTTShutdownServer(s)
4567
4568 mces, res := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4569 defer mces.Close()
4570 testMQTTCheckConnAck(t, res, mqttConnAckRCConnectionAccepted, false)
4571 testMQTTSub(t, 1, mces, res, []*mqttFilter{{filter: "will/#", qos: test.subQoS}}, []byte{test.subQoS})
4572
4573 willTopic := []byte("will/topic")
4574 willMsg := []byte("bye")
4575
4576 mc, r := testMQTTConnect(t,
4577 &mqttConnInfo{
4578 cleanSess: true,
4579 will: &mqttWill{
4580 topic: willTopic,
4581 message: willMsg,
4582 qos: test.pubQoS,
4583 retain: true,
4584 },
4585 }, o.MQTT.Host, o.MQTT.Port)
4586 defer mc.Close()
4587 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
4588
4589 // Disconnect the client
4590 mc.Close()
4591
4592 // Wait for the server to process the connection close, which will
4593 // cause the "will" message to be published (and retained).
4594 checkClientsCount(t, s, 1)
4595
4596 // Create subscription on will topic and expect will message.
4597 mcs, rs := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4598 defer mcs.Close()
4599 testMQTTCheckConnAck(t, rs, mqttConnAckRCConnectionAccepted, false)
4600
4601 testMQTTSub(t, 1, mcs, rs, []*mqttFilter{{filter: "will/#", qos: test.subQoS}}, []byte{test.subQoS})
4602 pflags, _ := testMQTTGetPubMsg(t, mcs, rs, "will/topic", willMsg)
4603 if !mqttIsRetained(pflags) {
4604 t.Fatalf("expected retain flag to be set, it was not: %v", pflags)
4605 }
4606 // Expected QoS will be the lesser of the pub/sub QoS.
4607 expectedQoS := test.pubQoS
4608 if test.subQoS == 0 {
4609 expectedQoS = 0
4610 }
4611 if qos := mqttGetQoS(pflags); qos != expectedQoS {
4612 t.Fatalf("expected qos to be %v, got %v", expectedQoS, qos)
4613 }
4614
4615 // The existing subscription (prior to sending the will) should receive
4616 // the will but the retain flag should not be set.
4617 pflags, _ = testMQTTGetPubMsg(t, mces, res, "will/topic", willMsg)
4618 if mqttIsRetained(pflags) {
4619 t.Fatalf("expected retain flag to not be set, it was: %v", pflags)
4620 }
4621 // Expected QoS will be the lesser of the pub/sub QoS.
4622 if qos := mqttGetQoS(pflags); qos != expectedQoS {
4623 t.Fatalf("expected qos to be %v, got %v", expectedQoS, qos)
4624 }
4625 })
4626 }
4627 }
4628
4629 func TestMQTTWillRetainPermViolation(t *testing.T) {
4630 template := `
4631 port: -1
4632 jetstream {
4633 store_dir = %q
4634 }
4635 server_name: mqtt
4636 authorization {
4637 mqtt_perms = {
4638 publish = ["%s"]
4639 subscribe = ["foo", "bar"]
4640 }
4641 users = [
4642 {user: mqtt, password: pass, permissions: $mqtt_perms}
4643 ]
4644 }
4645 mqtt {
4646 port: -1
4647 }
4648 `
4649 tdir := t.TempDir()
4650 conf := createConfFile(t, fmt.Appendf(nil, template, tdir, "foo"))
4651
4652 s, o := RunServerWithConfig(conf)
4653 defer testMQTTShutdownServer(s)
4654
4655 ci := &mqttConnInfo{
4656 cleanSess: true,
4657 user: "mqtt",
4658 pass: "pass",
4659 }
4660
4661 // We create first a connection with the Will topic that the publisher
4662 // is allowed to publish to.
4663 ci.will = &mqttWill{
4664 topic: []byte("foo"),
4665 message: []byte("bye"),
4666 qos: 1,
4667 retain: true,
4668 }
4669 mc, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
4670 defer mc.Close()
4671 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
4672
4673 // Disconnect, which will cause the Will to be sent with retain flag.
4674 mc.Close()
4675
4676 // Wait for the server to process the connection close, which will
4677 // cause the "will" message to be published (and retained).
4678 checkClientsCount(t, s, 0)
4679
4680 // Create a subscription on the Will subject and we should receive it.
4681 ci.will = nil
4682 mcs, rs := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
4683 defer mcs.Close()
4684 testMQTTCheckConnAck(t, rs, mqttConnAckRCConnectionAccepted, false)
4685
4686 testMQTTSub(t, 1, mcs, rs, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
4687 pflags, _ := testMQTTGetPubMsg(t, mcs, rs, "foo", []byte("bye"))
4688 if !mqttIsRetained(pflags) {
4689 t.Fatalf("expected retain flag to be set, it was not: %v", pflags)
4690 }
4691 if qos := mqttGetQoS(pflags); qos != 1 {
4692 t.Fatalf("expected qos to be 1, got %v", qos)
4693 }
4694 testMQTTDisconnect(t, mcs, nil)
4695 mcs.Close()
4696
4697 // Now create another connection with a Will that client is not allowed to publish to.
4698 ci.will = &mqttWill{
4699 topic: []byte("bar"),
4700 message: []byte("bye"),
4701 qos: 1,
4702 retain: true,
4703 }
4704 mc, r = testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
4705 defer mc.Close()
4706 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
4707
4708 // Disconnect, to cause Will to be produced, but in that case should not be stored
4709 // since user not allowed to publish on "bar".
4710 mc.Close()
4711
4712 // Wait for the server to process the connection close, which will
4713 // cause the "will" message to be published (and retained).
4714 checkClientsCount(t, s, 0)
4715
4716 // Create sub on "bar" which user is allowed to subscribe to.
4717 ci.will = nil
4718 mcs, rs = testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
4719 defer mcs.Close()
4720 testMQTTCheckConnAck(t, rs, mqttConnAckRCConnectionAccepted, false)
4721
4722 testMQTTSub(t, 1, mcs, rs, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
4723 // No Will should be published since it should not have been stored in the first place.
4724 testMQTTExpectNothing(t, rs)
4725 testMQTTDisconnect(t, mcs, nil)
4726 mcs.Close()
4727
4728 // Now remove permission to publish on "foo" and check that a new subscription
4729 // on "foo" is now not getting the will message because the original user no
4730 // longer has permission to do so.
4731 reloadUpdateConfig(t, s, conf, fmt.Sprintf(template, tdir, "baz"))
4732
4733 mcs, rs = testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
4734 defer mcs.Close()
4735 testMQTTCheckConnAck(t, rs, mqttConnAckRCConnectionAccepted, false)
4736
4737 testMQTTSub(t, 1, mcs, rs, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
4738 testMQTTExpectNothing(t, rs)
4739 testMQTTDisconnect(t, mcs, nil)
4740 }
4741
4742 func TestMQTTPublishRetain(t *testing.T) {
4743 o := testMQTTDefaultOptions()
4744 s := testMQTTRunServer(t, o)
4745 defer testMQTTShutdownServer(s)
4746
4747 buf := strings.Builder{}
4748 for i := 0; i < 128; i++ { // 128Kb
4749 for j := 0; j < 64; j++ { // 16 * 64 = 1Kb
4750 buf.Write([]byte("0123456789abcdef"))
4751 }
4752 }
4753 large := buf.String()
4754
4755 for _, test := range []struct {
4756 name string
4757 retained bool
4758 sentValue string
4759 expectedValue string
4760 subGetsIt bool
4761 }{
4762 {"publish large retained", true, large, large, true},
4763 {"publish retained", true, "retained", "retained", true},
4764 {"publish not retained", false, "not retained", "retained", true},
4765 {"remove retained", true, "", "", false},
4766 } {
4767 t.Run(test.name, func(t *testing.T) {
4768 mc1, rs1 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4769 defer mc1.Close()
4770 testMQTTCheckConnAck(t, rs1, mqttConnAckRCConnectionAccepted, false)
4771 testMQTTPublish(t, mc1, rs1, 0, false, test.retained, "foo", 0, []byte(test.sentValue))
4772 testMQTTFlush(t, mc1, nil, rs1)
4773
4774 mc2, rs2 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4775 defer mc2.Close()
4776 testMQTTCheckConnAck(t, rs2, mqttConnAckRCConnectionAccepted, false)
4777
4778 testMQTTSub(t, 1, mc2, rs2, []*mqttFilter{{filter: "foo/#", qos: 1}}, []byte{1})
4779
4780 if test.subGetsIt {
4781 pflags, _ := testMQTTGetPubMsg(t, mc2, rs2, "foo", []byte(test.expectedValue))
4782 if !mqttIsRetained(pflags) {
4783 t.Fatalf("retain flag should have been set, it was not: flags=%v", pflags)
4784 }
4785 } else {
4786 testMQTTExpectNothing(t, rs2)
4787 }
4788
4789 testMQTTDisconnect(t, mc1, nil)
4790 testMQTTDisconnect(t, mc2, nil)
4791 })
4792 }
4793 }
4794
4795 func TestMQTTQoS2RetainedReject(t *testing.T) {
4796 // Start the server with QOS2 enabled, and submit retained messages with QoS
4797 // 1 and 2.
4798 o := testMQTTDefaultOptions()
4799 s := testMQTTRunServer(t, o)
4800 mc1, rs1 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4801 testMQTTCheckConnAck(t, rs1, mqttConnAckRCConnectionAccepted, false)
4802 testMQTTPublish(t, mc1, rs1, 2, false, true, "foo", 1, []byte("qos2 failed"))
4803 testMQTTPublish(t, mc1, rs1, 1, false, true, "bar", 2, []byte("qos1 retained"))
4804 testMQTTFlush(t, mc1, nil, rs1)
4805 testMQTTDisconnect(t, mc1, nil)
4806 mc1.Close()
4807 s.Shutdown()
4808
4809 // Restart the server with QOS2 disabled; we should be using the same
4810 // JetStream store, so the retained message should still be there.
4811 o.MQTT.rejectQoS2Pub = true
4812 s = testMQTTRunServer(t, o)
4813 defer testMQTTShutdownServer(s)
4814
4815 mc2, rs2 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4816 defer mc2.Close()
4817 testMQTTCheckConnAck(t, rs2, mqttConnAckRCConnectionAccepted, false)
4818
4819 testMQTTSub(t, 1, mc2, rs2, []*mqttFilter{{filter: "bar/#", qos: 2}}, []byte{2})
4820 pflags, _ := testMQTTGetPubMsg(t, mc2, rs2, "bar", []byte("qos1 retained"))
4821 if !mqttIsRetained(pflags) {
4822 t.Fatalf("retain flag should have been set, it was not: flags=%v", pflags)
4823 }
4824
4825 testMQTTSub(t, 1, mc2, rs2, []*mqttFilter{{filter: "foo/#", qos: 2}}, []byte{2})
4826 testMQTTExpectNothing(t, rs2)
4827 testMQTTDisconnect(t, mc2, nil)
4828 }
4829
4830 func TestMQTTRetainFlag(t *testing.T) {
4831 o := testMQTTDefaultOptions()
4832 s := testMQTTRunServer(t, o)
4833 defer testMQTTShutdownServer(s)
4834
4835 mc1, rs1 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4836 defer mc1.Close()
4837 testMQTTCheckConnAck(t, rs1, mqttConnAckRCConnectionAccepted, false)
4838 testMQTTPublish(t, mc1, rs1, 0, false, true, "foo/0", 0, []byte("flag set"))
4839 testMQTTPublish(t, mc1, rs1, 0, false, true, "foo/1", 0, []byte("flag set"))
4840 testMQTTFlush(t, mc1, nil, rs1)
4841
4842 mc2, rs2 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
4843 defer mc2.Close()
4844 testMQTTCheckConnAck(t, rs2, mqttConnAckRCConnectionAccepted, false)
4845
4846 testMQTTSub(t, 1, mc2, rs2, []*mqttFilter{{filter: "foo/0", qos: 0}}, []byte{0})
4847 pflags, _ := testMQTTGetPubMsg(t, mc2, rs2, "foo/0", []byte("flag set"))
4848 if !mqttIsRetained(pflags) {
4849 t.Fatalf("retain flag should have been set, it was not: flags=%v", pflags)
4850 }
4851
4852 testMQTTSub(t, 1, mc2, rs2, []*mqttFilter{{filter: "foo/1", qos: 1}}, []byte{1})
4853 pflags, _ = testMQTTGetPubMsg(t, mc2, rs2, "foo/1", []byte("flag set"))
4854 if !mqttIsRetained(pflags) {
4855 t.Fatalf("retain flag should have been set, it was not: flags=%v", pflags)
4856 }
4857
4858 // For existing subscriptions, RETAIN flag should not be set: [MQTT-3.3.1-9].
4859 testMQTTPublish(t, mc1, rs1, 0, false, true, "foo/0", 0, []byte("flag not set"))
4860 testMQTTFlush(t, mc1, nil, rs1)
4861
4862 pflags, _ = testMQTTGetPubMsg(t, mc2, rs2, "foo/0", []byte("flag not set"))
4863 if mqttIsRetained(pflags) {
4864 t.Fatalf("retain flag should not have been set, it was: flags=%v", pflags)
4865 }
4866
4867 testMQTTPublish(t, mc1, rs1, 0, false, true, "foo/1", 0, []byte("flag not set"))
4868 testMQTTFlush(t, mc1, nil, rs1)
4869
4870 pflags, _ = testMQTTGetPubMsg(t, mc2, rs2, "foo/1", []byte("flag not set"))
4871 if mqttIsRetained(pflags) {
4872 t.Fatalf("retain flag should not have been set, it was: flags=%v", pflags)
4873 }
4874 }
4875
4876 func TestMQTTPublishRetainPermViolation(t *testing.T) {
4877 o := testMQTTDefaultOptions()
4878 o.Users = []*User{
4879 {
4880 Username: "mqtt1",
4881 Password: "pass",
4882 Permissions: &Permissions{
4883 Publish: &SubjectPermission{Allow: []string{"foo"}},
4884 Subscribe: &SubjectPermission{Allow: []string{"bar"}},
4885 },
4886 },
4887 {
4888 Username: "mqtt2",
4889 Password: "pass",
4890 Permissions: &Permissions{
4891 Publish: &SubjectPermission{Allow: []string{"foo", "bar"}},
4892 Subscribe: &SubjectPermission{Allow: []string{">"}},
4893 },
4894 },
4895 {
4896 Username: "mqtt3",
4897 Password: "pass",
4898 Permissions: &Permissions{
4899 Publish: &SubjectPermission{Allow: []string{"foo.bar", "baz", "barbaz"}},
4900 Subscribe: &SubjectPermission{Allow: []string{">"}},
4901 },
4902 },
4903 {
4904 Username: "mqtt4",
4905 Password: "pass",
4906 },
4907 }
4908 s := testMQTTRunServer(t, o)
4909 defer testMQTTShutdownServer(s)
4910
4911 var asm *mqttAccountSessionManager
4912
4913 pubRetained := func(user, subject string) {
4914 t.Helper()
4915 mc, rs := testMQTTConnect(t, &mqttConnInfo{
4916 cleanSess: true,
4917 clientID: "pub",
4918 user: user,
4919 pass: "pass",
4920 }, o.MQTT.Host, o.MQTT.Port)
4921 defer mc.Close()
4922 testMQTTCheckConnAck(t, rs, mqttConnAckRCConnectionAccepted, false)
4923 testMQTTPublish(t, mc, rs, 0, false, true, subject, 0, []byte("retained"))
4924 testMQTTFlush(t, mc, nil, rs)
4925 if asm == nil {
4926 asm = testMQTTGetAccountSessionManager(t, s, "pub")
4927 }
4928 testMQTTDisconnect(t, mc, nil)
4929 }
4930 consumeRetained := func(user, subject string, expected bool) {
4931 t.Helper()
4932 mc, rs := testMQTTConnect(t, &mqttConnInfo{
4933 cleanSess: true,
4934 user: user,
4935 pass: "pass",
4936 }, o.MQTT.Host, o.MQTT.Port)
4937 defer mc.Close()
4938 testMQTTCheckConnAck(t, rs, mqttConnAckRCConnectionAccepted, false)
4939 testMQTTSub(t, 1, mc, rs, []*mqttFilter{{filter: subject, qos: 0}}, []byte{0})
4940 if expected {
4941 testMQTTCheckPubMsg(t, mc, rs, subject, mqttPubFlagRetain, []byte("retained"))
4942 } else {
4943 testMQTTExpectNothing(t, rs)
4944 }
4945 testMQTTDisconnect(t, mc, nil)
4946 }
4947
4948 // With user "mqtt", publish a retained message on "bar".
4949 // Since this user has no permission, the server should not have stored it.
4950 pubRetained("mqtt1", "bar")
4951
4952 // Verify that we can't get it with a new subscription.
4953 consumeRetained("mqtt1", "bar", false)
4954
4955 // Use the user "mqtt2" that has permissions to publish on foo and bar.
4956 // Publish on "foo" and check retained message can be received.
4957 pubRetained("mqtt2", "foo")
4958 consumeRetained("mqtt2", "foo", true)
4959
4960 // For user "mqtt3", we will publish on "foo/bar" and check retained
4961 // message is properly received.
4962 pubRetained("mqtt3", "foo/bar")
4963 consumeRetained("mqtt3", "foo/bar", true)
4964
4965 // Simulate a message that would have been produced in a different server
4966 // on subject "barbaz". We will use user "mqtt4" that has no pub permissions
4967 // since we need to send to low-level "$MQTT.rmsgs.barbaz" subject...
4968 nc := natsConnect(t, s.ClientURL(), nats.UserInfo("mqtt4", "pass"))
4969 defer nc.Close()
4970 msg := nats.NewMsg("$MQTT.rmsgs.barbaz")
4971 msg.Header.Set(mqttNatsRetainedMessageOrigin, "SomeOtherServer")
4972 msg.Header.Set(mqttNatsRetainedMessageTopic, "barbaz")
4973 msg.Header.Set(mqttNatsRetainedMessageFlags, "1")
4974 msg.Data = []byte("retained")
4975 nc.PublishMsg(msg)
4976 natsFlush(t, nc)
4977
4978 // Wait a bit to make sure it is processed.
4979 time.Sleep(250 * time.Millisecond)
4980
4981 // Then check that it can be received
4982 consumeRetained("mqtt3", "barbaz", true)
4983
4984 // Same with user "mqtt4" that does not have permissions defined, which
4985 // means allowed to pub/sub on everything.
4986 pubRetained("mqtt4", "bat")
4987 consumeRetained("mqtt4", "bat", true)
4988
4989 // Do a config reload and make sure that the server does not panic
4990 // and we can still get the retained messages.
4991 no := *o
4992 // Remove the "bar" publish permission from "mqtt2"
4993 no.Users[1].Permissions.Publish = &SubjectPermission{Allow: []string{"foo"}}
4994 // And the "foo.bar" and "barbaz" publish permissions from "mqtt3"
4995 no.Users[2].Permissions.Publish = &SubjectPermission{Allow: []string{"baz"}}
4996 err := s.ReloadOptions(&no)
4997 require_NoError(t, err)
4998
4999 checkFor(t, time.Second, 10*time.Millisecond, func() error {
5000 asm.mu.RLock()
5001 defer asm.mu.RUnlock()
5002 if _, ok := asm.retmsgs.Find([]byte("foo.bar")); ok {
5003 return errors.New("foo.bar subject still in map")
5004 }
5005 return nil
5006 })
5007
5008 // Still message on "bar" should not exist
5009 consumeRetained("mqtt1", "bar", false)
5010 // This one should still be able to be received
5011 consumeRetained("mqtt2", "foo", true)
5012 // Retained message on "foo.bar" should have been removed.
5013 consumeRetained("mqtt3", "foo/bar", false)
5014 // However, message on "barbaz" should have been left alone since it
5015 // was produced on a different server.
5016 consumeRetained("mqtt3", "barbaz", true)
5017 // And finally, this user that had no permission should still be able
5018 // to get the retained message on "bat".
5019 consumeRetained("mqtt4", "bat", true)
5020 }
5021
5022 func TestMQTTPermissionsViolation(t *testing.T) {
5023 o := testMQTTDefaultOptions()
5024 o.Users = []*User{
5025 {
5026 Username: "mqtt",
5027 Password: "pass",
5028 Permissions: &Permissions{
5029 Publish: &SubjectPermission{Allow: []string{"foo.bar"}},
5030 Subscribe: &SubjectPermission{Allow: []string{"foo.*"}, Deny: []string{"foo.baz"}},
5031 },
5032 },
5033 {
5034 Username: "mqtt2",
5035 Password: "pass",
5036 Permissions: &Permissions{
5037 Publish: &SubjectPermission{Allow: []string{"foo"}},
5038 // We use to require explicit allow permission on "$MQTT.sub.>" when any
5039 // subscribe permission were provided. We now implicitly allow it, but
5040 // we want to make sure that, if needs arise, one can block the server
5041 // to subscribe on "$MQTT.sub".
5042 Subscribe: &SubjectPermission{Allow: []string{"foo"}, Deny: []string{"$MQTT.sub.>"}},
5043 },
5044 },
5045 {
5046 Username: "observer",
5047 Password: "pass",
5048 },
5049 }
5050 s := testMQTTRunServer(t, o)
5051 defer testMQTTShutdownServer(s)
5052
5053 ci := &mqttConnInfo{
5054 user: "mqtt",
5055 pass: "pass",
5056 }
5057 ci.clientID = "sub"
5058 mc, rc := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5059 defer mc.Close()
5060 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
5061 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/+", qos: 1}}, []byte{1})
5062 // Should not be allowed to subscribe on specifically on "foo/baz"
5063 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/baz", qos: 1}}, []byte{mqttSubAckFailure})
5064 // MQTT literals "*" and ">" are converted and interpreted as NATS wildcards
5065 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/*", qos: 1}}, []byte{1})
5066 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/*/*", qos: 1}}, []byte{mqttSubAckFailure})
5067 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/>", qos: 1}}, []byte{mqttSubAckFailure})
5068 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/*/>", qos: 1}}, []byte{mqttSubAckFailure})
5069 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/>/*", qos: 1}}, []byte{mqttSubAckFailure})
5070 testMQTTFlush(t, mc, nil, rc)
5071
5072 ci.clientID = "pub"
5073 ci.cleanSess = true
5074 mp, rp := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5075 defer mp.Close()
5076 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
5077
5078 // These should be received since publisher has the right to publish on foo.bar
5079 testMQTTPublish(t, mp, rp, 0, false, false, "foo/bar", 0, []byte("msg1"))
5080 testMQTTCheckPubMsg(t, mc, rc, "foo/bar", 0, []byte("msg1"))
5081 testMQTTPublish(t, mp, rp, 1, false, false, "foo/bar", 1, []byte("msg2"))
5082 testMQTTCheckPubMsg(t, mc, rc, "foo/bar", mqttPubQos1, []byte("msg2"))
5083
5084 // MQTT clients should not be able to access internal "$MQTT.msgs.*" subjects
5085 // unless explicitly granted by allow permissions.
5086 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "$MQTT/msgs/#", qos: 1}}, []byte{mqttSubAckFailure})
5087
5088 // MQTT clients should not be able to subscribe to the internal
5089 // "$MQTT.deliver.pubrel.*" subjects either. Unlike "$MQTT.msgs.*",
5090 // canSubscribe bypasses the allow-list for this prefix (so internal
5091 // subscriptions work), so processSubs is the only guard that rejects it.
5092 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: strings.ReplaceAll(mqttPubRelDeliverySubjectPrefix, ".", "/") + "+", qos: 1}}, []byte{mqttSubAckFailure})
5093
5094 onc := natsConnect(t, s.ClientURL(), nats.UserInfo("observer", "pass"))
5095 defer onc.Close()
5096 osub := natsSubSync(t, onc, "$MQTT.msgs.>")
5097 natsFlush(t, onc)
5098 testMQTTPublish(t, mp, rp, 0, false, false, "$MQTT/msgs/injected", 0, []byte("internal"))
5099 if m, err := osub.NextMsg(250 * time.Millisecond); err == nil {
5100 t.Fatalf("Expected no internal MQTT message to be published, got subject=%q", m.Subject)
5101 }
5102
5103 // But these should not be cause pub has no permission to publish on foo.baz
5104 testMQTTPublish(t, mp, rp, 0, false, false, "foo/baz", 0, []byte("msg3"))
5105 testMQTTExpectNothing(t, rc)
5106 testMQTTPublish(t, mp, rp, 1, false, false, "foo/baz", 1, []byte("msg4"))
5107 testMQTTExpectNothing(t, rc)
5108
5109 // Disconnect publisher
5110 testMQTTDisconnect(t, mp, nil)
5111 mp.Close()
5112 // Disconnect subscriber and restart it to make sure that it does not receive msg3/msg4
5113 testMQTTDisconnect(t, mc, nil)
5114 mc.Close()
5115
5116 ci.cleanSess = false
5117 ci.clientID = "sub"
5118 mc, rc = testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5119 defer mc.Close()
5120 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, true)
5121 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/+", qos: 1}}, []byte{1})
5122 testMQTTExpectNothing(t, rc)
5123 mc.Close()
5124
5125 ci.cleanSess = true
5126 ci.user = "mqtt2"
5127 ci.clientID = "sub"
5128 mc, rc = testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5129 defer mc.Close()
5130 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
5131 // This should fail because although this user is allowed to subscribe on "foo"
5132 // we deny permission to subscribe on "$MQTT.sub.>", so the server won't be
5133 // able to create the internal NATS subscription for the JS consumer.
5134 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "foo/baz", qos: 1}}, []byte{mqttSubAckFailure})
5135 }
5136
5137 func TestMQTTSubscribeDenyInternalMessageSubject(t *testing.T) {
5138 o := testMQTTDefaultOptions()
5139 o.Users = []*User{
5140 {
5141 Username: "victim",
5142 Password: "pass",
5143 Permissions: &Permissions{
5144 Publish: &SubjectPermission{Allow: []string{"secret.>"}},
5145 },
5146 },
5147 {
5148 Username: "attacker",
5149 Password: "pass",
5150 Permissions: &Permissions{
5151 Subscribe: &SubjectPermission{Deny: []string{"secret.>"}},
5152 },
5153 },
5154 }
5155 s := testMQTTRunServer(t, o)
5156 defer testMQTTShutdownServer(s)
5157
5158 attacker := &mqttConnInfo{clientID: "attacker", user: "attacker", pass: "pass", cleanSess: true}
5159 ac, ar := testMQTTConnect(t, attacker, o.MQTT.Host, o.MQTT.Port)
5160 defer ac.Close()
5161 testMQTTCheckConnAck(t, ar, mqttConnAckRCConnectionAccepted, false)
5162
5163 // The deny permission rejects the user topic directly. Neither the internal
5164 // namespace nor the "msgs" stream subject may be used to bypass it.
5165 testMQTTSub(t, 1, ac, ar, []*mqttFilter{{filter: "secret/#", qos: 0}}, []byte{mqttSubAckFailure})
5166 testMQTTSub(t, 2, ac, ar, []*mqttFilter{{filter: "$MQTT/#", qos: 0}}, []byte{mqttSubAckFailure})
5167 testMQTTSub(t, 3, ac, ar, []*mqttFilter{{filter: "$MQTT/msgs/secret/#", qos: 0}}, []byte{mqttSubAckFailure})
5168
5169 victim := &mqttConnInfo{clientID: "victim", user: "victim", pass: "pass", cleanSess: true}
5170 vc, vr := testMQTTConnect(t, victim, o.MQTT.Host, o.MQTT.Port)
5171 defer vc.Close()
5172 testMQTTCheckConnAck(t, vr, mqttConnAckRCConnectionAccepted, false)
5173 testMQTTPublish(t, vc, vr, 1, false, false, "secret/x", 1, []byte("secret payload"))
5174 testMQTTExpectNothing(t, ar)
5175 }
5176
5177 func TestMQTTSubscribeDenyRetainedAndQoSReplay(t *testing.T) {
5178 // A subscriber can be allowed to subscribe to a broad wildcard while being
5179 // denied delivery of more specific subjects. Normal live delivery applies
5180 // the deny filter (deliverMsg -> checkDenySub), but retained-message
5181 // serialization and QoS1+ durable replay must apply it too.
5182 o := testMQTTDefaultOptions()
5183 o.Users = []*User{
5184 {
5185 Username: "pub",
5186 Password: "pass",
5187 Permissions: &Permissions{
5188 Publish: &SubjectPermission{Allow: []string{"secret.>", "foo.>"}},
5189 Subscribe: &SubjectPermission{Allow: []string{"_INBOX.>"}},
5190 },
5191 },
5192 {
5193 Username: "sub",
5194 Password: "pass",
5195 Permissions: &Permissions{
5196 Subscribe: &SubjectPermission{Allow: []string{">"}, Deny: []string{"secret.>"}},
5197 },
5198 },
5199 }
5200 s := testMQTTRunServer(t, o)
5201 defer testMQTTShutdownServer(s)
5202
5203 pub := &mqttConnInfo{clientID: "pub", user: "pub", pass: "pass", cleanSess: true}
5204 mp, rp := testMQTTConnect(t, pub, o.MQTT.Host, o.MQTT.Port)
5205 defer mp.Close()
5206 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
5207
5208 // 1) Live delivery: the denied subject must not be delivered, but an allowed
5209 // subject on the same broad wildcard subscription must.
5210 subLive := &mqttConnInfo{clientID: "sub-live", user: "sub", pass: "pass", cleanSess: true}
5211 mc, rc := testMQTTConnect(t, subLive, o.MQTT.Host, o.MQTT.Port)
5212 defer mc.Close()
5213 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
5214 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "#", qos: 0}}, []byte{0})
5215 testMQTTPublish(t, mp, rp, 0, false, false, "secret/one", 0, []byte("live-denied"))
5216 testMQTTExpectNothing(t, rc)
5217 testMQTTPublish(t, mp, rp, 0, false, false, "foo/live", 0, []byte("live-allowed"))
5218 testMQTTCheckPubMsg(t, mc, rc, "foo/live", 0, []byte("live-allowed"))
5219 testMQTTDisconnect(t, mc, nil)
5220 mc.Close()
5221
5222 // 2) QoS1 durable replay: subscribe with a persistent session, disconnect,
5223 // publish a denied and an allowed QoS1 message while offline, then reconnect.
5224 // The denied subject must not be replayed; the allowed one must.
5225 persist := &mqttConnInfo{clientID: "persist-sub", user: "sub", pass: "pass", cleanSess: false}
5226 mc, rc = testMQTTConnect(t, persist, o.MQTT.Host, o.MQTT.Port)
5227 defer mc.Close()
5228 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
5229 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "#", qos: 1}}, []byte{1})
5230 testMQTTDisconnect(t, mc, nil)
5231 mc.Close()
5232
5233 // secret.one is published first so that, without the deny check, it would be
5234 // the first message replayed (i.e. the bypass would be observed here).
5235 testMQTTPublish(t, mp, rp, 1, false, false, "secret/one", 1, []byte("qos1-denied"))
5236 testMQTTPublish(t, mp, rp, 1, false, false, "foo/replay", 2, []byte("qos1-allowed"))
5237
5238 mc, rc = testMQTTConnect(t, persist, o.MQTT.Host, o.MQTT.Port)
5239 defer mc.Close()
5240 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, true)
5241 // Only the allowed message is replayed; the denied one is filtered out (and
5242 // acked so JetStream does not keep redelivering it) before delivery.
5243 testMQTTCheckPubMsg(t, mc, rc, "foo/replay", mqttPubQos1, []byte("qos1-allowed"))
5244 testMQTTExpectNothing(t, rc)
5245 testMQTTDisconnect(t, mc, nil)
5246 mc.Close()
5247
5248 // 3) Retained delivery: a retained denied subject must not be serialized to a
5249 // new subscriber, but a retained allowed subject must.
5250 testMQTTPublish(t, mp, rp, 0, false, true, "secret/one", 0, []byte("retained-denied"))
5251 testMQTTPublish(t, mp, rp, 0, false, true, "foo/ret", 0, []byte("retained-allowed"))
5252 testMQTTFlush(t, mp, nil, rp)
5253
5254 subRet := &mqttConnInfo{clientID: "sub-retained", user: "sub", pass: "pass", cleanSess: true}
5255 mc, rc = testMQTTConnect(t, subRet, o.MQTT.Host, o.MQTT.Port)
5256 defer mc.Close()
5257 testMQTTCheckConnAck(t, rc, mqttConnAckRCConnectionAccepted, false)
5258 testMQTTSub(t, 1, mc, rc, []*mqttFilter{{filter: "#", qos: 0}}, []byte{0})
5259 // Only the allowed retained message is delivered (with the RETAIN flag set).
5260 testMQTTCheckPubMsg(t, mc, rc, "foo/ret", mqttPubFlagRetain, []byte("retained-allowed"))
5261 testMQTTExpectNothing(t, rc)
5262 }
5263
5264 func TestMQTTCleanSession(t *testing.T) {
5265 o := testMQTTDefaultOptions()
5266 s := testMQTTRunServer(t, o)
5267 defer testMQTTShutdownServer(s)
5268
5269 ci := &mqttConnInfo{
5270 clientID: "me",
5271 cleanSess: false,
5272 }
5273 c, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5274 defer c.Close()
5275 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5276 testMQTTDisconnect(t, c, nil)
5277 c.Close()
5278
5279 c, r = testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5280 defer c.Close()
5281 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
5282 testMQTTDisconnect(t, c, nil)
5283 c.Close()
5284
5285 ci.cleanSess = true
5286 c, r = testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5287 defer c.Close()
5288 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5289 testMQTTDisconnect(t, c, nil)
5290 }
5291
5292 func TestMQTTDuplicateClientID(t *testing.T) {
5293 o := testMQTTDefaultOptions()
5294 s := testMQTTRunServer(t, o)
5295 defer testMQTTShutdownServer(s)
5296
5297 ci := &mqttConnInfo{
5298 clientID: "me",
5299 cleanSess: false,
5300 }
5301 c1, r1 := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5302 defer c1.Close()
5303 testMQTTCheckConnAck(t, r1, mqttConnAckRCConnectionAccepted, false)
5304
5305 c2, r2 := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5306 defer c2.Close()
5307 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, true)
5308
5309 // The old client should be disconnected.
5310 testMQTTExpectDisconnect(t, c1)
5311 }
5312
5313 func TestMQTTPersistedSession(t *testing.T) {
5314 o := testMQTTDefaultOptions()
5315 s := testMQTTRunServer(t, o)
5316 defer testMQTTShutdownRestartedServer(&s)
5317
5318 cisub := &mqttConnInfo{clientID: "sub", cleanSess: false}
5319 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
5320
5321 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
5322 defer c.Close()
5323 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5324
5325 testMQTTSub(t, 1, c, r,
5326 []*mqttFilter{
5327 {filter: "foo/#", qos: 1},
5328 {filter: "bar", qos: 1},
5329 {filter: "baz", qos: 0},
5330 },
5331 []byte{1, 1, 0})
5332 testMQTTFlush(t, c, nil, r)
5333
5334 // Shutdown server, close connection and restart server. It should
5335 // have restored the session and consumers.
5336 dir := strings.TrimSuffix(s.JetStreamConfig().StoreDir, JetStreamStoreDir)
5337 s.Shutdown()
5338 c.Close()
5339
5340 o.Port = -1
5341 o.MQTT.Port = -1
5342 o.StoreDir = dir
5343 s = testMQTTRunServer(t, o)
5344 // There is already the defer for shutdown at top of function
5345
5346 // Create a publisher that will send qos1 so we verify that messages
5347 // are stored for the persisted sessions.
5348 c, r = testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
5349 defer c.Close()
5350 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5351
5352 testMQTTPublish(t, c, r, 1, false, false, "foo/bar", 1, []byte("msg0"))
5353 testMQTTFlush(t, c, nil, r)
5354 testMQTTDisconnect(t, c, nil)
5355 c.Close()
5356
5357 // Recreate session
5358 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
5359 defer c.Close()
5360 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
5361
5362 // Since consumers have been recovered, messages should be received
5363 // (MQTT does not need client to recreate consumers for a recovered
5364 // session)
5365
5366 // Check that qos1 publish message is received.
5367 testMQTTCheckPubMsg(t, c, r, "foo/bar", mqttPubQos1, []byte("msg0"))
5368
5369 // Flush to prevent publishes to be done too soon since we are
5370 // receiving the CONNACK before the subscriptions are restored.
5371 testMQTTFlush(t, c, nil, r)
5372
5373 // Now publish some messages to all subscriptions.
5374 nc := natsConnect(t, s.ClientURL())
5375 defer nc.Close()
5376
5377 natsPub(t, nc, "foo.bar", []byte("msg1"))
5378 testMQTTCheckPubMsg(t, c, r, "foo/bar", 0, []byte("msg1"))
5379
5380 natsPub(t, nc, "foo", []byte("msg2"))
5381 testMQTTCheckPubMsg(t, c, r, "foo", 0, []byte("msg2"))
5382
5383 natsPub(t, nc, "bar", []byte("msg3"))
5384 testMQTTCheckPubMsg(t, c, r, "bar", 0, []byte("msg3"))
5385
5386 natsPub(t, nc, "baz", []byte("msg4"))
5387 testMQTTCheckPubMsg(t, c, r, "baz", 0, []byte("msg4"))
5388
5389 // Now unsub "bar" and verify that message published on this topic
5390 // is not received.
5391 testMQTTUnsub(t, 1, c, r, []*mqttFilter{{filter: "bar"}})
5392 natsPub(t, nc, "bar", []byte("msg5"))
5393 testMQTTExpectNothing(t, r)
5394
5395 nc.Close()
5396 s.Shutdown()
5397 c.Close()
5398
5399 o.Port = -1
5400 o.MQTT.Port = -1
5401 o.StoreDir = dir
5402 s = testMQTTRunServer(t, o)
5403 // There is already the defer for shutdown at top of function
5404
5405 // Recreate a client
5406 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
5407 defer c.Close()
5408 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
5409
5410 nc = natsConnect(t, s.ClientURL())
5411 defer nc.Close()
5412
5413 natsPub(t, nc, "foo.bar", []byte("msg6"))
5414 testMQTTCheckPubMsg(t, c, r, "foo/bar", 0, []byte("msg6"))
5415
5416 natsPub(t, nc, "foo", []byte("msg7"))
5417 testMQTTCheckPubMsg(t, c, r, "foo", 0, []byte("msg7"))
5418
5419 // Make sure that we did not recover bar.
5420 natsPub(t, nc, "bar", []byte("msg8"))
5421 testMQTTExpectNothing(t, r)
5422
5423 natsPub(t, nc, "baz", []byte("msg9"))
5424 testMQTTCheckPubMsg(t, c, r, "baz", 0, []byte("msg9"))
5425
5426 // Have the sub client send a subscription downgrading the qos1 subscription.
5427 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo/#", qos: 0}}, []byte{0})
5428 testMQTTFlush(t, c, nil, r)
5429
5430 nc.Close()
5431 s.Shutdown()
5432 c.Close()
5433
5434 o.Port = -1
5435 o.MQTT.Port = -1
5436 o.StoreDir = dir
5437 s = testMQTTRunServer(t, o)
5438 // There is already the defer for shutdown at top of function
5439
5440 // Recreate the sub client
5441 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
5442 defer c.Close()
5443 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
5444
5445 // Publish as a qos1
5446 c2, r2 := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
5447 defer c2.Close()
5448 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, false)
5449 testMQTTPublish(t, c2, r2, 1, false, false, "foo/bar", 1, []byte("msg10"))
5450
5451 // Verify that it is received as qos0 which is the qos of the subscription.
5452 testMQTTCheckPubMsg(t, c, r, "foo/bar", 0, []byte("msg10"))
5453
5454 testMQTTDisconnect(t, c, nil)
5455 c.Close()
5456 testMQTTDisconnect(t, c2, nil)
5457 c2.Close()
5458
5459 // Finally, recreate the sub with clean session and ensure that all is gone
5460 cisub.cleanSess = true
5461 for i := 0; i < 2; i++ {
5462 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
5463 defer c.Close()
5464 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5465
5466 nc = natsConnect(t, s.ClientURL())
5467 defer nc.Close()
5468
5469 natsPub(t, nc, "foo.bar", []byte("msg11"))
5470 testMQTTExpectNothing(t, r)
5471
5472 natsPub(t, nc, "foo", []byte("msg12"))
5473 testMQTTExpectNothing(t, r)
5474
5475 // Make sure that we did not recover bar.
5476 natsPub(t, nc, "bar", []byte("msg13"))
5477 testMQTTExpectNothing(t, r)
5478
5479 natsPub(t, nc, "baz", []byte("msg14"))
5480 testMQTTExpectNothing(t, r)
5481
5482 testMQTTDisconnect(t, c, nil)
5483 c.Close()
5484 nc.Close()
5485
5486 s.Shutdown()
5487 o.Port = -1
5488 o.MQTT.Port = -1
5489 o.StoreDir = dir
5490 s = testMQTTRunServer(t, o)
5491 // There is already the defer for shutdown at top of function
5492 }
5493 }
5494
5495 func TestMQTTRejectsHashCollidingClientID(t *testing.T) {
5496 o := testMQTTDefaultOptions()
5497 s := testMQTTRunServer(t, o)
5498 defer testMQTTShutdownServer(s)
5499
5500 // These IDs were found to collide under getHash()
5501 victimID := "cid-03579431"
5502 attackerID := "cid-09191235"
5503 require_True(t, getHash(victimID) == getHash(attackerID))
5504
5505 c, r := testMQTTConnect(t, &mqttConnInfo{clientID: victimID, cleanSess: false}, o.MQTT.Host, o.MQTT.Port)
5506 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5507 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
5508 testMQTTFlush(t, c, nil, r)
5509 testMQTTDisconnect(t, c, nil)
5510 c.Close()
5511
5512 attacker, r := testMQTTConnect(t, &mqttConnInfo{clientID: attackerID, cleanSess: false}, o.MQTT.Host, o.MQTT.Port)
5513 defer attacker.Close()
5514 testMQTTCheckConnAck(t, r, mqttConnAckRCIdentifierRejected, false)
5515 testMQTTExpectDisconnect(t, attacker)
5516 attacker.Close()
5517
5518 c, r = testMQTTConnect(t, &mqttConnInfo{clientID: victimID, cleanSess: false}, o.MQTT.Host, o.MQTT.Port)
5519 defer c.Close()
5520 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
5521 testMQTTFlush(t, c, nil, r)
5522
5523 nc := natsConnect(t, s.ClientURL())
5524 defer nc.Close()
5525
5526 natsPub(t, nc, "foo", []byte("msg"))
5527 testMQTTCheckPubMsg(t, c, r, "foo", 0, []byte("msg"))
5528 }
5529
5530 func TestMQTTRecoverSessionAndAddNewSub(t *testing.T) {
5531 o := testMQTTDefaultOptions()
5532 s := testMQTTRunServer(t, o)
5533 defer testMQTTShutdownRestartedServer(&s)
5534
5535 cisub := &mqttConnInfo{clientID: "sub1", cleanSess: false}
5536 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
5537 defer c.Close()
5538 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5539 testMQTTDisconnect(t, c, nil)
5540 c.Close()
5541
5542 // Shutdown server, close connection and restart server. It should
5543 // have restored the session and consumers.
5544 dir := strings.TrimSuffix(s.JetStreamConfig().StoreDir, JetStreamStoreDir)
5545 s.Shutdown()
5546 c.Close()
5547
5548 o.Port = -1
5549 o.MQTT.Port = -1
5550 o.StoreDir = dir
5551 s = testMQTTRunServer(t, o)
5552 // No need for defer since it is done top of function
5553
5554 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
5555 defer c.Close()
5556 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
5557 // Now add sub and make sure it does not crash
5558 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
5559 testMQTTFlush(t, c, nil, r)
5560
5561 // Now repeat with a new client but without server restart.
5562 cisub2 := &mqttConnInfo{clientID: "sub2", cleanSess: false}
5563 c2, r2 := testMQTTConnect(t, cisub2, o.MQTT.Host, o.MQTT.Port)
5564 defer c2.Close()
5565 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, false)
5566 testMQTTDisconnect(t, c2, nil)
5567 c2.Close()
5568
5569 c2, r2 = testMQTTConnect(t, cisub2, o.MQTT.Host, o.MQTT.Port)
5570 defer c2.Close()
5571 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, true)
5572 testMQTTSub(t, 1, c2, r2, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
5573 testMQTTFlush(t, c2, nil, r2)
5574 }
5575
5576 func TestMQTTRecoverSessionWithSubAndClientResendSub(t *testing.T) {
5577 o := testMQTTDefaultOptions()
5578 s := testMQTTRunServer(t, o)
5579 defer testMQTTShutdownRestartedServer(&s)
5580
5581 cisub1 := &mqttConnInfo{clientID: "sub1", cleanSess: false}
5582 c, r := testMQTTConnect(t, cisub1, o.MQTT.Host, o.MQTT.Port)
5583 defer c.Close()
5584 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5585
5586 // Have a client send a SUBSCRIBE protocol for foo, QoS1
5587 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
5588 testMQTTDisconnect(t, c, nil)
5589 c.Close()
5590
5591 // Restart the server now.
5592 dir := strings.TrimSuffix(s.JetStreamConfig().StoreDir, JetStreamStoreDir)
5593 s.Shutdown()
5594
5595 o.Port = -1
5596 o.MQTT.Port = -1
5597 o.StoreDir = dir
5598 s = testMQTTRunServer(t, o)
5599 // No need for defer since it is done top of function
5600
5601 // Now restart the client. Since the client was created with cleanSess==false,
5602 // the server will have recorded the subscriptions for this client.
5603 c, r = testMQTTConnect(t, cisub1, o.MQTT.Host, o.MQTT.Port)
5604 defer c.Close()
5605 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
5606 // At this point, the server has recreated the subscription on foo, QoS1.
5607
5608 // For applications that restart, it is possible (likely) that they
5609 // will resend their SUBSCRIBE protocols, so do so now:
5610 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
5611 testMQTTFlush(t, c, nil, r)
5612
5613 checkNumSub := func(clientID string) {
5614 t.Helper()
5615
5616 // Find the MQTT client...
5617 mc := testMQTTGetClient(t, s, clientID)
5618
5619 // Check how many NATS subscriptions are registered.
5620 var fooSub int
5621 var otherSub int
5622 mc.mu.Lock()
5623 for _, sub := range mc.subs {
5624 switch string(sub.subject) {
5625 case "foo":
5626 fooSub++
5627 default:
5628 otherSub++
5629 }
5630 }
5631 mc.mu.Unlock()
5632
5633 // We should have 2 subscriptions, one on "foo", and one for the JS durable
5634 // consumer's delivery subject.
5635 if fooSub != 1 {
5636 t.Fatalf("Expected 1 sub on 'foo', got %v", fooSub)
5637 }
5638 if otherSub != 1 {
5639 t.Fatalf("Expected 1 subscription for JS durable, got %v", otherSub)
5640 }
5641 }
5642 checkNumSub("sub1")
5643
5644 c.Close()
5645
5646 // Now same but without the server restart in-between.
5647 cisub2 := &mqttConnInfo{clientID: "sub2", cleanSess: false}
5648 c, r = testMQTTConnect(t, cisub2, o.MQTT.Host, o.MQTT.Port)
5649 defer c.Close()
5650 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5651 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
5652 testMQTTDisconnect(t, c, nil)
5653 c.Close()
5654 // Restart client
5655 c, r = testMQTTConnect(t, cisub2, o.MQTT.Host, o.MQTT.Port)
5656 defer c.Close()
5657 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
5658 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
5659 testMQTTFlush(t, c, nil, r)
5660 // Check client subs
5661 checkNumSub("sub2")
5662 }
5663
5664 func TestMQTTFlappingSession(t *testing.T) {
5665 mqttSessJailDur = 250 * time.Millisecond
5666 mqttFlapCleanItvl = 350 * time.Millisecond
5667 defer func() {
5668 mqttSessJailDur = mqttSessFlappingJailDur
5669 mqttFlapCleanItvl = mqttSessFlappingCleanupInterval
5670 }()
5671
5672 o := testMQTTDefaultOptions()
5673 s := testMQTTRunServer(t, o)
5674 defer testMQTTShutdownServer(s)
5675
5676 ci := &mqttConnInfo{clientID: "flapper", cleanSess: false}
5677 c, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5678 defer c.Close()
5679 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5680
5681 // Let's get a handle on the asm to check things later.
5682 asm := testMQTTGetAccountSessionManager(t, s, "flapper")
5683
5684 // Start a new connection with the same clientID, which should replace
5685 // the old one and put it in the flappers map.
5686 c2, r2 := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5687 defer c2.Close()
5688 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, true)
5689
5690 // Should be disconnected...
5691 testMQTTExpectDisconnect(t, c)
5692
5693 // Now try to reconnect "c" and we should fail. We have to do this manually,
5694 // since we expect it to fail.
5695 addr := net.JoinHostPort(o.MQTT.Host, fmt.Sprintf("%d", o.MQTT.Port))
5696 c, err := net.Dial("tcp", addr)
5697 if err != nil {
5698 t.Fatalf("Error creating mqtt connection: %v", err)
5699 }
5700 defer c.Close()
5701 proto := mqttCreateConnectProto(ci)
5702 if _, err := testMQTTWrite(c, proto); err != nil {
5703 t.Fatalf("Error writing protocols: %v", err)
5704 }
5705 // Misbehave and send a SUB protocol without waiting for the CONNACK
5706 w := newMQTTWriter(0)
5707 pkLen := 2 // for pi
5708 // Topic "foo"
5709 pkLen += 2 + 3 + 1
5710 w.WriteByte(mqttPacketSub | mqttSubscribeFlags)
5711 w.WriteVarInt(pkLen)
5712 w.WriteUint16(1)
5713 w.WriteBytes([]byte("foo"))
5714 w.WriteByte(1)
5715 if _, err := testMQTTWrite(c, w.Bytes()); err != nil {
5716 t.Fatalf("Error writing protocols: %v", err)
5717 }
5718 // Now read the CONNACK and we should have been disconnected.
5719 if _, err := testMQTTRead(c); err == nil {
5720 t.Fatal("Expected connection to fail")
5721 }
5722
5723 // This should be in the flappers map, but after 250ms should be cleared.
5724 for i := 0; i < 2; i++ {
5725 asm.mu.RLock()
5726 _, present := asm.flappers["flapper"]
5727 asm.mu.RUnlock()
5728 if i == 0 {
5729 if !present {
5730 t.Fatal("Did not find the client ID in the flappers map")
5731 }
5732 // Wait for more than the cleanup interval
5733 time.Sleep(mqttFlapCleanItvl + 100*time.Millisecond)
5734 } else if present {
5735 t.Fatal("The client ID should have been cleared from the map")
5736 }
5737 }
5738 }
5739
5740 func TestMQTTLockedSession(t *testing.T) {
5741 o := testMQTTDefaultOptions()
5742 s := testMQTTRunServer(t, o)
5743 defer testMQTTShutdownServer(s)
5744
5745 subClientID := "sub"
5746 ci := &mqttConnInfo{clientID: subClientID, cleanSess: false}
5747 c, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5748 defer c.Close()
5749 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5750
5751 sm := &s.mqtt.sessmgr
5752 sm.mu.Lock()
5753 asm := sm.sessions[globalAccountName]
5754 sm.mu.Unlock()
5755 if asm == nil {
5756 t.Fatalf("account session manager not found")
5757 }
5758
5759 // It is possible, however unlikely, to have received CONNACK while
5760 // mqttProcessConnect is still running, and the session remains locked. Wait
5761 // for it to finish.
5762 checkFor(t, 250*time.Millisecond, 10*time.Millisecond, func() error {
5763 asm.mu.RLock()
5764 defer asm.mu.RUnlock()
5765 if _, stillLocked := asm.sessLocked[subClientID]; stillLocked {
5766 return fmt.Errorf("session still locked")
5767 }
5768 return nil
5769 })
5770
5771 // Get the session for "sub"
5772 cli := testMQTTGetClient(t, s, subClientID)
5773 sess := cli.mqtt.sess
5774
5775 // Pretend that the session above is locked.
5776 if err := asm.lockSession(sess, cli); err != nil {
5777 t.Fatalf("Unable to lock session: %v", err)
5778 }
5779 defer asm.unlockSession(sess)
5780
5781 // Now try to connect another client that wants to use "sub".
5782 // We can't use testMQTTConnect() because it is going to fail.
5783 addr := net.JoinHostPort(o.MQTT.Host, fmt.Sprintf("%d", o.MQTT.Port))
5784 c2, err := net.Dial("tcp", addr)
5785 if err != nil {
5786 t.Fatalf("Error creating mqtt connection: %v", err)
5787 }
5788 defer c2.Close()
5789 proto := mqttCreateConnectProto(ci)
5790 if _, err := testMQTTWrite(c2, proto); err != nil {
5791 t.Fatalf("Error writing connect: %v", err)
5792 }
5793 if _, err := testMQTTRead(c2); err == nil {
5794 t.Fatal("Expected connection to fail")
5795 }
5796
5797 // Now try again, but this time release the session while waiting
5798 // to connect and it should succeed.
5799 time.AfterFunc(250*time.Millisecond, func() { asm.unlockSession(sess) })
5800 c3, r3 := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5801 defer c3.Close()
5802 testMQTTCheckConnAck(t, r3, mqttConnAckRCConnectionAccepted, true)
5803 }
5804
5805 func TestMQTTPersistRetainedMsg(t *testing.T) {
5806 o := testMQTTDefaultOptions()
5807 s := testMQTTRunServer(t, o)
5808 defer testMQTTShutdownRestartedServer(&s)
5809
5810 dir := strings.TrimSuffix(s.JetStreamConfig().StoreDir, JetStreamStoreDir)
5811
5812 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
5813 c, r := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
5814 defer c.Close()
5815 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5816
5817 testMQTTPublish(t, c, r, 1, false, true, "moo/foo", 1, []byte("foo1"))
5818 testMQTTPublish(t, c, r, 1, false, true, "moo/foo", 1, []byte("foo2"))
5819 testMQTTPublish(t, c, r, 1, false, true, "moo/bar", 1, []byte("bar1"))
5820 testMQTTPublish(t, c, r, 0, false, true, "moo/baz", 1, []byte("baz1"))
5821 // Remove bar
5822 testMQTTPublish(t, c, r, 1, false, true, "moo/bar", 1, nil)
5823 testMQTTFlush(t, c, nil, r)
5824 testMQTTDisconnect(t, c, nil)
5825 c.Close()
5826
5827 s.Shutdown()
5828
5829 o.Port = -1
5830 o.MQTT.Port = -1
5831 o.StoreDir = dir
5832 s = testMQTTRunServer(t, o)
5833
5834 cisub := &mqttConnInfo{clientID: "sub", cleanSess: false}
5835 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
5836 defer c.Close()
5837 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5838
5839 t.Run("many subs one topic", func(t *testing.T) {
5840 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "moo/foo", qos: 1}}, []byte{1})
5841 testMQTTCheckPubMsg(t, c, r, "moo/foo", mqttPubFlagRetain|mqttPubQos1, []byte("foo2"))
5842
5843 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "moo/baz", qos: 1}}, []byte{1})
5844 testMQTTCheckPubMsg(t, c, r, "moo/baz", mqttPubFlagRetain, []byte("baz1"))
5845
5846 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "moo/bar", qos: 1}}, []byte{1})
5847 testMQTTExpectNothing(t, r)
5848 })
5849
5850 runSingleSubscribe := func(filters []*mqttFilter) func(t *testing.T) {
5851 return func(t *testing.T) {
5852 testMQTTSub(t, 1, c, r, filters, nil)
5853
5854 for i := 0; i < 2; i++ {
5855 flags, pi, topic, payload := testMQTTReadPubPacket(t, r)
5856 if (flags & mqttPubFlagRetain) == 0 {
5857 t.Fatalf("Expected flags to have retain set, got %v", flags)
5858 }
5859 if (flags & mqttPubFlagDup) != 0 {
5860 t.Fatalf("Expected flags to not have Dup set, got %v", flags)
5861 }
5862 var expQOS byte
5863 var expPayload []byte
5864 switch topic {
5865 case "moo/foo":
5866 expQOS = mqttPubQos1
5867 expPayload = []byte("foo2")
5868 testMQTTSendPIPacket(mqttPacketPubAck, t, c, pi)
5869 case "moo/baz":
5870 expQOS = 0
5871 expPayload = []byte("baz1")
5872 default:
5873 t.Fatalf("Unexpected topic: %v", topic)
5874 }
5875 if (flags & mqttPubFlagQoS) != expQOS {
5876 t.Fatalf("Expected flags to have QOS %x set, got %x", expQOS, flags)
5877 }
5878 if string(payload) != string(expPayload) {
5879 t.Fatalf("Expected payload to be %q, got %v", expPayload, string(payload))
5880 }
5881 }
5882 testMQTTExpectNothing(t, r)
5883 }
5884 }
5885
5886 t.Run("one sub many topics", runSingleSubscribe([]*mqttFilter{
5887 {filter: "moo/foo", qos: 1},
5888 {filter: "moo/baz", qos: 1},
5889 {filter: "moo/bar", qos: 1},
5890 }))
5891
5892 t.Run("one sub wildcard plus", runSingleSubscribe([]*mqttFilter{
5893 {filter: "moo/+", qos: 1},
5894 }))
5895
5896 t.Run("one sub wildcard hash", runSingleSubscribe([]*mqttFilter{
5897 {filter: "moo/#", qos: 1},
5898 }))
5899
5900 testMQTTDisconnect(t, c, nil)
5901 c.Close()
5902 }
5903
5904 func TestMQTTRetainedMsgCleanup(t *testing.T) {
5905 mqttRetainedCacheTTL = 250 * time.Millisecond
5906 defer func() { mqttRetainedCacheTTL = mqttDefaultRetainedCacheTTL }()
5907
5908 o := testMQTTDefaultOptions()
5909 s := testMQTTRunServer(t, o)
5910 defer testMQTTShutdownServer(s)
5911
5912 ci := &mqttConnInfo{clientID: "cache", cleanSess: true}
5913 c, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5914 defer c.Close()
5915 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5916
5917 // Send a retained message.
5918 testMQTTPublish(t, c, r, 1, false, true, "foo", 1, []byte("msg"))
5919 testMQTTFlush(t, c, nil, r)
5920
5921 // Start a subscription.
5922 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
5923 testMQTTCheckPubMsg(t, c, r, "foo", mqttPubQos1|mqttPubFlagRetain, []byte("msg"))
5924
5925 time.Sleep(2 * mqttRetainedCacheTTL)
5926
5927 // Make sure not in cache anymore
5928 asm := testMQTTGetAccountSessionManager(t, s, "cache")
5929 if v, ok := asm.rmsCache.Load("foo"); ok {
5930 t.Fatalf("Should not be in cache, got %+v", v)
5931 }
5932 }
5933
5934 func TestMQTTRestoreRetainedMsgs(t *testing.T) {
5935 o := testMQTTDefaultOptions()
5936 s := testMQTTRunServer(t, o)
5937 defer testMQTTShutdownServer(s)
5938
5939 ci := &mqttConnInfo{clientID: "retain", cleanSess: true}
5940 c, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5941 defer c.Close()
5942 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5943
5944 // Send several retained messages on different topic
5945 testMQTTPublish(t, c, r, 1, false, true, "foo", 1, []byte("msg1"))
5946 testMQTTPublish(t, c, r, 1, false, true, "bar", 1, []byte("msg2"))
5947 testMQTTPublish(t, c, r, 1, false, true, "baz", 1, []byte("msg3"))
5948
5949 // Remove the two last ones (by sending empty body)
5950 testMQTTPublish(t, c, r, 1, false, true, "bar", 1, []byte(""))
5951 testMQTTPublish(t, c, r, 1, false, true, "baz", 1, []byte(""))
5952 testMQTTFlush(t, c, nil, r)
5953 testMQTTDisconnect(t, c, nil)
5954 c.Close()
5955
5956 // Now restart the server. We had a bug where we would wait to restore retained
5957 // messages based on stream last sequence, which was wrong.
5958 s.Shutdown()
5959 s, err := NewServer(o)
5960 require_NoError(t, err)
5961 l := &captureWarnLogger{warn: make(chan string, 10)}
5962 s.SetLogger(l, false, false)
5963 s.Start()
5964 defer testMQTTShutdownServer(s)
5965
5966 time.Sleep(500 * time.Millisecond)
5967 start := time.Now()
5968 c, r = testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
5969 defer c.Close()
5970 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5971 dur := time.Since(start)
5972 if dur > 2*time.Second {
5973 var warnMsg string
5974 select {
5975 case warnMsg = <-l.warn:
5976 default:
5977 }
5978 t.Fatalf("Likely timing out restoring retained messages (%s)", warnMsg)
5979 }
5980 }
5981
5982 func TestMQTTConnAckFirstPacket(t *testing.T) {
5983 o := testMQTTDefaultOptions()
5984 o.NoLog, o.Debug, o.Trace = true, false, false
5985 s := RunServer(o)
5986 defer testMQTTShutdownServer(s)
5987
5988 cisub := &mqttConnInfo{clientID: "sub", cleanSess: false}
5989 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
5990 defer c.Close()
5991 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
5992 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 0}}, []byte{0})
5993 testMQTTDisconnect(t, c, nil)
5994 c.Close()
5995
5996 nc := natsConnect(t, s.ClientURL())
5997 defer nc.Close()
5998
5999 wg := sync.WaitGroup{}
6000 wg.Add(1)
6001 ch := make(chan struct{}, 1)
6002 ready := make(chan struct{})
6003 go func() {
6004 defer wg.Done()
6005
6006 close(ready)
6007 for {
6008 nc.Publish("foo", []byte("msg"))
6009 select {
6010 case <-ch:
6011 return
6012 default:
6013 }
6014 }
6015 }()
6016
6017 <-ready
6018 for i := 0; i < 100; i++ {
6019 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6020 defer c.Close()
6021 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
6022 w := newMQTTWriter(0)
6023 w.WriteByte(mqttPacketDisconnect)
6024 w.WriteByte(0)
6025 c.Write(w.Bytes())
6026 // Wait to be disconnected, we can't use testMQTTDisconnect() because
6027 // it would fail because we may still receive some NATS messages.
6028 var b [10]byte
6029 for {
6030 if _, err := c.Read(b[:]); err != nil {
6031 break
6032 }
6033 }
6034 c.Close()
6035 }
6036 close(ch)
6037 wg.Wait()
6038 }
6039
6040 func TestMQTTRedeliveryAckWait(t *testing.T) {
6041 o := testMQTTDefaultOptions()
6042 o.MQTT.AckWait = 250 * time.Millisecond
6043 s := testMQTTRunServer(t, o)
6044 defer testMQTTShutdownServer(s)
6045
6046 cisub := &mqttConnInfo{clientID: "sub", cleanSess: false}
6047 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6048 defer c.Close()
6049 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6050 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
6051
6052 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6053 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6054 defer cp.Close()
6055 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6056
6057 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("foo1"))
6058 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 2, []byte("foo2"))
6059 testMQTTDisconnect(t, cp, nil)
6060 cp.Close()
6061
6062 for i := 0; i < 2; i++ {
6063 flags := mqttPubQos1
6064 if i > 0 {
6065 flags |= mqttPubFlagDup
6066 }
6067 pi1 := testMQTTCheckPubMsgNoAck(t, c, r, "foo", flags, []byte("foo1"))
6068 pi2 := testMQTTCheckPubMsgNoAck(t, c, r, "foo", flags, []byte("foo2"))
6069
6070 if pi1 != 1 || pi2 != 2 {
6071 t.Fatalf("Unexpected pi values: %v, %v", pi1, pi2)
6072 }
6073 }
6074 // Ack first message
6075 testMQTTSendPIPacket(mqttPacketPubAck, t, c, 1)
6076 // Redelivery should only be for second message now
6077 for i := 0; i < 2; i++ {
6078 flags := mqttPubQos1 | mqttPubFlagDup
6079 pi := testMQTTCheckPubMsgNoAck(t, c, r, "foo", flags, []byte("foo2"))
6080 if pi != 2 {
6081 t.Fatalf("Unexpected pi to be 2, got %v", pi)
6082 }
6083 }
6084
6085 // Restart client, should receive second message with pi==2
6086 c.Close()
6087 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6088 defer c.Close()
6089 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
6090 // Check that message is received with proper pi
6091 pi := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1|mqttPubFlagDup, []byte("foo2"))
6092 if pi != 2 {
6093 t.Fatalf("Unexpected pi to be 2, got %v", pi)
6094 }
6095 // Now ack second message
6096 testMQTTSendPIPacket(mqttPacketPubAck, t, c, 2)
6097 // Flush to make sure it is processed before checking client's maps
6098 testMQTTFlush(t, c, nil, r)
6099
6100 // Look for the sub client
6101 mc := testMQTTGetClient(t, s, "sub")
6102 mc.mu.Lock()
6103 sess := mc.mqtt.sess
6104 sess.mu.Lock()
6105 lpi := len(sess.pendingPublish)
6106 var lsseq int
6107 for _, sseqToPi := range sess.cpending {
6108 lsseq += len(sseqToPi)
6109 }
6110 sess.mu.Unlock()
6111 mc.mu.Unlock()
6112 if lpi != 0 || lsseq != 0 {
6113 t.Fatalf("Maps should be empty, got %v, %v", lpi, lsseq)
6114 }
6115 }
6116
6117 // [MQTT-2.3.1-4] A QoS 1/2 packet identifier must not be reused while it (or an
6118 // earlier one) is still in flight, and clients treat a just-freed identifier
6119 // re-appearing within a delivery burst as a duplicate. Deliver-and-ack one
6120 // message so pendingPublish momentarily empties, then deliver a second: its
6121 // packet identifier must advance rather than reset to the first one.
6122 func TestMQTTPacketIdentifierMonotonicAfterAck(t *testing.T) {
6123 o := testMQTTDefaultOptions()
6124 s := testMQTTRunServer(t, o)
6125 defer testMQTTShutdownServer(s)
6126
6127 cisub := &mqttConnInfo{clientID: "sub", cleanSess: true}
6128 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6129 defer c.Close()
6130 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6131 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
6132
6133 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6134 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6135 defer cp.Close()
6136 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6137
6138 // First message: receive it, then PUBACK so pendingPublish drains back to
6139 // empty before the next delivery is assigned an identifier.
6140 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg1"))
6141 pi1 := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1, []byte("msg1"))
6142 testMQTTSendPIPacket(mqttPacketPubAck, t, c, pi1)
6143 testMQTTFlush(t, c, nil, r)
6144
6145 // Second message: its identifier must not reuse the freed one.
6146 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg2"))
6147 pi2 := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1, []byte("msg2"))
6148 if pi2 == pi1 {
6149 t.Fatalf("Packet identifier was reset and reused after ack: pi1=%v pi2=%v", pi1, pi2)
6150 }
6151 testMQTTSendPIPacket(mqttPacketPubAck, t, c, pi2)
6152 }
6153
6154 // Re-subscribing a QoS 1/2 filter at QoS 0 deletes its JS consumer; the
6155 // consumer's pending (unacknowledged) deliveries must be purged too, otherwise
6156 // their packet identifiers leak and permanently count against the in-flight cap
6157 // for the life of the session (as mqttProcessUnsubs already does). Same for
6158 // in-flight retained deliveries, which have no JS consumer at all.
6159 func TestMQTTQoS0DowngradePurgesPending(t *testing.T) {
6160 o := testMQTTDefaultOptions()
6161 s := testMQTTRunServer(t, o)
6162 defer testMQTTShutdownServer(s)
6163
6164 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6165 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6166 defer cp.Close()
6167 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6168
6169 // Store a retained QoS 1 message before the subscriber connects.
6170 testMQTTPublish(t, cp, rp, 1, false, true, "foo", 1, []byte("retained"))
6171
6172 ci := &mqttConnInfo{clientID: "sub", cleanSess: true}
6173 c, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
6174 defer c.Close()
6175 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6176
6177 // Subscribing at QoS 1 delivers the retained message; receive it without
6178 // acking: tracked as pending under the sid's retained pseudo-durable.
6179 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
6180 testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1|mqttPubFlagRetain, []byte("retained"))
6181
6182 // Deliver a QoS 1 message and receive it without acking: it is now tracked
6183 // as pending against the "foo" consumer.
6184 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 2, []byte("msg"))
6185 testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1, []byte("msg"))
6186
6187 countPending := func() (int, int) {
6188 mc := testMQTTGetClient(t, s, "sub")
6189 mc.mu.Lock()
6190 sess := mc.mqtt.sess
6191 mc.mu.Unlock()
6192 sess.mu.Lock()
6193 defer sess.mu.Unlock()
6194 var np, nc int
6195 np = len(sess.pendingPublish)
6196 for _, m := range sess.cpending {
6197 nc += len(m)
6198 }
6199 return np, nc
6200 }
6201
6202 if np, nc := countPending(); np != 2 || nc != 2 {
6203 t.Fatalf("Expected 2 pending publish/cpending before downgrade, got %v/%v", np, nc)
6204 }
6205
6206 // Re-subscribe the same filter at QoS 0: deletes the JS consumer and must
6207 // purge its pending deliveries, consumer-based and retained alike.
6208 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 0}}, []byte{0})
6209 // The new subscription re-delivers the retained message, now at QoS 0
6210 // (no packet identifier, so nothing new is tracked).
6211 testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubFlagRetain, []byte("retained"))
6212 testMQTTFlush(t, c, nil, r)
6213
6214 if np, nc := countPending(); np != 0 || nc != 0 {
6215 t.Fatalf("Expected pending maps purged after QoS 0 downgrade, got pendingPublish=%v cpending=%v", np, nc)
6216 }
6217 }
6218
6219 // - [MQTT-3.10.4-3] If a Server deletes a Subscription It MUST complete the
6220 // delivery of any QoS 1 or QoS 2 messages which it has started to send to the
6221 // Client.
6222 //
6223 // Test flow:
6224 // - Subscribe to foo, publish 3 QoS2 messages.
6225 // - After one is PUBCOMP-ed, and one is PUBREC-ed, Unsubscribe.
6226 // - See that the remaining 2 are fully delivered.
6227 func TestMQTTQoS2InflightMsgsDeliveredAfterUnsubscribe(t *testing.T) {
6228 // This test has proven flaky on Travis, so skip for now. Line 4926, the 3rd
6229 // testMQTTCheckPubMsgNoAck sometimes returns `data1`, instead of `data3`
6230 // that we are expecting. It must be a retry since we did not acknowledge
6231 // `data1` until later.
6232 t.Skip()
6233
6234 o := testMQTTDefaultOptions()
6235 o.MQTT.AckWait = 10 * time.Millisecond
6236 s := testMQTTRunServer(t, o)
6237 defer testMQTTShutdownServer(s)
6238
6239 var qos2 byte = 2
6240 cisub := &mqttConnInfo{clientID: "sub", cleanSess: true}
6241 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6242 defer c.Close()
6243 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6244 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: qos2}}, []byte{qos2})
6245
6246 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6247 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6248 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6249
6250 // send 3 messages
6251 testMQTTPublish(t, cp, rp, qos2, false, false, "foo", 441, []byte("data1"))
6252 testMQTTPublish(t, cp, rp, qos2, false, false, "foo", 442, []byte("data2"))
6253 testMQTTPublish(t, cp, rp, qos2, false, false, "foo", 443, []byte("data3"))
6254
6255 testMQTTDisconnect(t, cp, nil)
6256 cp.Close()
6257
6258 subPI1 := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQoS2, []byte("data1"))
6259 subPI2 := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQoS2, []byte("data2"))
6260 // subPI3 := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQoS2, []byte("data3"))
6261 _ = testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQoS2, []byte("data3"))
6262
6263 // fully receive first message
6264 testMQTTSendPIPacket(mqttPacketPubRec, t, c, subPI1)
6265 testMQTTReadPIPacket(mqttPacketPubRel, t, r, subPI1)
6266 testMQTTSendPIPacket(mqttPacketPubComp, t, c, subPI1)
6267
6268 // Do not PUBCOMP the 2nd message yet.
6269 testMQTTSendPIPacket(mqttPacketPubRec, t, c, subPI2)
6270 testMQTTReadPIPacket(mqttPacketPubRel, t, r, subPI2)
6271
6272 // Unsubscribe
6273 testMQTTUnsub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: qos2}})
6274
6275 // We expect that PI2 and PI3 will continue to be delivered, from their
6276 // respective states.
6277 gotPI2PubRel := false
6278
6279 // TODO: Currently, we do not get the unacknowledged PUBLISH re-delivered
6280 // after an UNSUBSCRIBE. Ongoing discussion if we should/must.
6281 // gotPI3Publish := false
6282 // gotPI3PubRel := false
6283 for !gotPI2PubRel /* || !gotPI3Publish || !gotPI3PubRel */ {
6284 b, _ /* len */ := testMQTTReadPacket(t, r)
6285 switch b & mqttPacketMask {
6286 case mqttPacketPubRel:
6287 pi, err := r.readUint16("packet identifier")
6288 if err != nil {
6289 t.Fatalf("got unexpected error: %v", err)
6290 }
6291 switch pi {
6292 case subPI2:
6293 testMQTTSendPIPacket(mqttPacketPubComp, t, c, pi)
6294 gotPI2PubRel = true
6295 // case subPI3:
6296 // testMQTTSendPIPacket(mqttPacketPubComp, t, c, pi)
6297 // gotPI3PubRel = true
6298 default:
6299 t.Fatalf("Expected PI %v got: %v", subPI2, pi)
6300 }
6301
6302 // case mqttPacketPub:
6303 // _, pi, _ := testMQTTGetPubMsgExEx(t, c, r, b, len, "foo", []byte("data3"))
6304 // if pi != subPI3 {
6305 // t.Fatalf("Expected PI %v got: %v", subPI3, pi)
6306 // }
6307 // gotPI3Publish = true
6308 // testMQTTSendPIPacket(mqttPacketPubRec, t, c, subPI3)
6309
6310 default:
6311 t.Fatalf("Unexpected packet type: %v", b&mqttPacketMask)
6312 }
6313 }
6314
6315 testMQTTExpectNothing(t, r)
6316 }
6317
6318 func TestMQTTQoS2RejectPublishDuplicates(t *testing.T) {
6319 o := testMQTTDefaultOptions()
6320 s := testMQTTRunServer(t, o)
6321 defer testMQTTShutdownServer(s)
6322
6323 var qos2 byte = 2
6324 cisub := &mqttConnInfo{clientID: "sub", cleanSess: true}
6325 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6326 defer c.Close()
6327 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6328 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: qos2}}, []byte{qos2})
6329
6330 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6331 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6332 defer cp.Close()
6333 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6334
6335 // Publish 3 different with same PI before we get any PUBREC back, then
6336 // complete the PUBREL/PUBCOMP flow as needed. Only one message (first
6337 // payload) should be delivered. PUBRECs,
6338 var pubPI uint16 = 444
6339 testMQTTSendPublishPacket(t, cp, qos2, false, false, "foo", pubPI, []byte("data1"))
6340 testMQTTSendPublishPacket(t, cp, qos2, true, false, "foo", pubPI, []byte("data2"))
6341 testMQTTSendPublishPacket(t, cp, qos2, false, false, "foo", pubPI, []byte("data3"))
6342
6343 for i := 0; i < 3; i++ {
6344 // [MQTT-4.3.3-1] The receiver
6345 //
6346 // - MUST respond with a PUBREC containing the Packet Identifier from
6347 // the incoming PUBLISH Packet, having accepted ownership of the
6348 // Application Message.
6349 //
6350 // - Until it has received the corresponding PUBREL packet, the Receiver
6351 // MUST acknowledge any subsequent PUBLISH packet with the same Packet
6352 // Identifier by sending a PUBREC. It MUST NOT cause duplicate messages
6353 // to be delivered to any onward recipients in this case.
6354 testMQTTReadPIPacket(mqttPacketPubRec, t, rp, pubPI)
6355 }
6356 for i := 0; i < 3; i++ {
6357 testMQTTSendPIPacket(mqttPacketPubRel|0x2, t, cp, pubPI)
6358 }
6359 for i := 0; i < 3; i++ {
6360 // [MQTT-4.3.3-1] MUST respond to a PUBREL packet by sending a PUBCOMP
6361 // packet containing the same Packet Identifier as the PUBREL.
6362 testMQTTReadPIPacket(mqttPacketPubComp, t, rp, pubPI)
6363 }
6364
6365 // [MQTT-4.3.3-1] After it has sent a PUBCOMP, the receiver MUST treat any
6366 // subsequent PUBLISH packet that contains that Packet Identifier as being a
6367 // new publication.
6368 //
6369 // Publish another message, identical to the first one. Since the server
6370 // already sent us a PUBCOMP, it will deliver this message, for a total of 2
6371 // delivered.
6372 testMQTTPublish(t, cp, rp, qos2, false, false, "foo", pubPI, []byte("data5"))
6373
6374 testMQTTDisconnect(t, cp, nil)
6375 cp.Close()
6376
6377 // Verify we got a total of 2 messages.
6378 subPI1 := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQoS2, []byte("data1"))
6379 subPI2 := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQoS2, []byte("data5"))
6380 for _, pi := range []uint16{subPI1, subPI2} {
6381 testMQTTSendPIPacket(mqttPacketPubRec, t, c, pi)
6382 testMQTTReadPIPacket(mqttPacketPubRel, t, r, pi)
6383 testMQTTSendPIPacket(mqttPacketPubComp, t, c, pi)
6384 }
6385 testMQTTExpectNothing(t, r)
6386 }
6387
6388 func TestMQTTQoS2RetriesPublish(t *testing.T) {
6389 o := testMQTTDefaultOptions()
6390 o.MQTT.AckWait = 100 * time.Millisecond
6391 s := testMQTTRunServer(t, o)
6392 defer testMQTTShutdownServer(s)
6393
6394 var qos2 byte = 2
6395 cisub := &mqttConnInfo{clientID: "sub", cleanSess: true}
6396 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6397 defer c.Close()
6398 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6399 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: qos2}}, []byte{qos2})
6400
6401 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6402 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6403 defer cp.Close()
6404 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6405
6406 // Publish a message and close the pub connection.
6407 var pubPI uint16 = 444
6408 testMQTTPublish(t, cp, rp, qos2, false, false, "foo", pubPI, []byte("data1"))
6409 testMQTTDisconnect(t, cp, nil)
6410 cp.Close()
6411
6412 // See that we got the message delivered to the sub, but don't PUBREC it
6413 // yet.
6414 subPI := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQoS2, []byte("data1"))
6415
6416 // See that the message is redelivered again 2 times, with the DUP on, before we PUBREC it.
6417 for i := 0; i < 2; i++ {
6418 expectedFlags := mqttPubQoS2 | mqttPubFlagDup
6419 pi := testMQTTCheckPubMsgNoAck(t, c, r, "foo", expectedFlags, []byte("data1"))
6420 if pi != subPI {
6421 t.Fatalf("Expected pi to be %v, got %v", subPI, pi)
6422 }
6423 }
6424
6425 // Finish the exchange and make sure there are no more attempts.
6426 testMQTTSendPIPacket(mqttPacketPubRec, t, c, subPI)
6427 testMQTTReadPIPacket(mqttPacketPubRel, t, r, subPI)
6428 testMQTTSendPIPacket(mqttPacketPubComp, t, c, subPI)
6429 testMQTTExpectNothing(t, r)
6430 }
6431
6432 func TestMQTTQoS2RetriesPubRel(t *testing.T) {
6433 o := testMQTTDefaultOptions()
6434 o.MQTT.AckWait = 50 * time.Millisecond
6435 s := testMQTTRunServer(t, o)
6436 defer testMQTTShutdownServer(s)
6437
6438 var qos2 byte = 2
6439 cisub := &mqttConnInfo{clientID: "sub", cleanSess: true}
6440 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6441 defer c.Close()
6442 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6443 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: qos2}}, []byte{qos2})
6444
6445 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6446 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6447 defer cp.Close()
6448 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6449
6450 // Publish a message and close the pub connection.
6451 var pubPI uint16 = 444
6452 testMQTTPublish(t, cp, rp, qos2, false, false, "foo", pubPI, []byte("data1"))
6453 testMQTTDisconnect(t, cp, nil)
6454 cp.Close()
6455
6456 // See that we got the message delivered to the sub, PUBREC it and expect a
6457 // PUBREL from the server.
6458 subPI := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQoS2, []byte("data1"))
6459 testMQTTSendPIPacket(mqttPacketPubRec, t, c, subPI)
6460
6461 // See that we get PUBREL redelivered several times, there's no DUP flag to
6462 // check.
6463 testMQTTReadPIPacket(mqttPacketPubRel, t, r, subPI)
6464 testMQTTReadPIPacket(mqttPacketPubRel, t, r, subPI)
6465 testMQTTReadPIPacket(mqttPacketPubRel, t, r, subPI)
6466
6467 // Finish the exchange and make sure there are no more attempts.
6468 testMQTTSendPIPacket(mqttPacketPubComp, t, c, subPI)
6469 testMQTTExpectNothing(t, r)
6470 }
6471
6472 func TestMQTTAckWaitConfigChange(t *testing.T) {
6473 o := testMQTTDefaultOptions()
6474 o.MQTT.AckWait = 250 * time.Millisecond
6475 s := testMQTTRunServer(t, o)
6476 defer testMQTTShutdownRestartedServer(&s)
6477
6478 dir := strings.TrimSuffix(s.JetStreamConfig().StoreDir, JetStreamStoreDir)
6479
6480 cisub := &mqttConnInfo{clientID: "sub", cleanSess: false}
6481 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6482 defer c.Close()
6483 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6484 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
6485
6486 sendMsg := func(topic, payload string) {
6487 t.Helper()
6488 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6489 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6490 defer cp.Close()
6491 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6492
6493 testMQTTPublish(t, cp, rp, 1, false, false, topic, 1, []byte(payload))
6494 testMQTTDisconnect(t, cp, nil)
6495 cp.Close()
6496 }
6497 sendMsg("foo", "msg1")
6498
6499 for i := 0; i < 2; i++ {
6500 flags := mqttPubQos1
6501 if i > 0 {
6502 flags |= mqttPubFlagDup
6503 }
6504 testMQTTCheckPubMsgNoAck(t, c, r, "foo", flags, []byte("msg1"))
6505 }
6506
6507 // Restart the server with a different AckWait option value.
6508 // Verify that MQTT sub restart succeeds. It will keep the
6509 // original value.
6510 c.Close()
6511 s.Shutdown()
6512
6513 o.Port = -1
6514 o.MQTT.Port = -1
6515 o.MQTT.AckWait = 10 * time.Millisecond
6516 o.StoreDir = dir
6517 s = testMQTTRunServer(t, o)
6518 // There is already the defer for shutdown at top of function
6519
6520 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6521 defer c.Close()
6522 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
6523 testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1|mqttPubFlagDup, []byte("msg1"))
6524 start := time.Now()
6525 testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1|mqttPubFlagDup, []byte("msg1"))
6526 if dur := time.Since(start); dur < 200*time.Millisecond {
6527 t.Fatalf("AckWait seem to have changed for existing subscription: %v", dur)
6528 }
6529
6530 // Create new subscription
6531 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
6532 sendMsg("bar", "msg2")
6533 testMQTTCheckPubMsgNoAck(t, c, r, "bar", mqttPubQos1, []byte("msg2"))
6534 start = time.Now()
6535 testMQTTCheckPubMsgNoAck(t, c, r, "bar", mqttPubQos1|mqttPubFlagDup, []byte("msg2"))
6536 if dur := time.Since(start); dur > 50*time.Millisecond {
6537 t.Fatalf("AckWait new value not used by new sub: %v", dur)
6538 }
6539 c.Close()
6540 }
6541
6542 func TestMQTTUnsubscribeWithPendingAcks(t *testing.T) {
6543 o := testMQTTDefaultOptions()
6544 o.MQTT.AckWait = 250 * time.Millisecond
6545 s := testMQTTRunServer(t, o)
6546 defer testMQTTShutdownServer(s)
6547
6548 cisub := &mqttConnInfo{clientID: "sub", cleanSess: false}
6549 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6550 defer c.Close()
6551 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6552 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
6553
6554 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6555 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6556 defer cp.Close()
6557 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6558
6559 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg"))
6560 testMQTTDisconnect(t, cp, nil)
6561 cp.Close()
6562
6563 for i := 0; i < 2; i++ {
6564 flags := mqttPubQos1
6565 if i > 0 {
6566 flags |= mqttPubFlagDup
6567 }
6568 testMQTTCheckPubMsgNoAck(t, c, r, "foo", flags, []byte("msg"))
6569 }
6570
6571 testMQTTUnsub(t, 1, c, r, []*mqttFilter{{filter: "foo"}})
6572 testMQTTFlush(t, c, nil, r)
6573
6574 mc := testMQTTGetClient(t, s, "sub")
6575 mc.mu.Lock()
6576 sess := mc.mqtt.sess
6577 sess.mu.Lock()
6578 pal := len(sess.pendingPublish)
6579 sess.mu.Unlock()
6580 mc.mu.Unlock()
6581 if pal != 0 {
6582 t.Fatalf("Expected pending ack map to be empty, got %v", pal)
6583 }
6584 }
6585
6586 func TestMQTTMaxAckPending(t *testing.T) {
6587 o := testMQTTDefaultOptions()
6588 o.MQTT.MaxAckPending = 1
6589 s := testMQTTRunServer(t, o)
6590 defer testMQTTShutdownRestartedServer(&s)
6591
6592 nc, js := jsClientConnect(t, s)
6593 defer nc.Close()
6594
6595 dir := strings.TrimSuffix(s.JetStreamConfig().StoreDir, JetStreamStoreDir)
6596
6597 cisub := &mqttConnInfo{clientID: "sub", cleanSess: false}
6598 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6599 defer c.Close()
6600 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6601 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
6602
6603 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6604 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6605 defer cp.Close()
6606 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6607
6608 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg1"))
6609 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg2"))
6610
6611 pi := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1, []byte("msg1"))
6612 // Check that we don't receive the second one due to max ack pending
6613 testMQTTExpectNothing(t, r)
6614
6615 // Now ack first message
6616 testMQTTSendPIPacket(mqttPacketPubAck, t, c, pi)
6617 // Now we should receive message 2
6618 testMQTTCheckPubMsg(t, c, r, "foo", mqttPubQos1, []byte("msg2"))
6619 testMQTTDisconnect(t, c, nil)
6620 c.Close()
6621
6622 // Give a chance to the server to "close" the consumer
6623 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
6624 for ci := range js.ConsumersInfo("$MQTT_msgs") {
6625 if ci.PushBound {
6626 return fmt.Errorf("Consumer still connected")
6627 }
6628 }
6629 return nil
6630 })
6631
6632 // Send 2 messages while sub is offline
6633 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg3"))
6634 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg4"))
6635
6636 // Restart consumer
6637 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6638 defer c.Close()
6639 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
6640
6641 // Should receive only message 3
6642 pi = testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1, []byte("msg3"))
6643 testMQTTExpectNothing(t, r)
6644
6645 // Ack and get the next
6646 testMQTTSendPIPacket(mqttPacketPubAck, t, c, pi)
6647 testMQTTCheckPubMsg(t, c, r, "foo", mqttPubQos1, []byte("msg4"))
6648
6649 // Make sure this message gets ack'ed
6650 mcli := testMQTTGetClient(t, s, cisub.clientID)
6651 checkFor(t, time.Second, 15*time.Millisecond, func() error {
6652 mcli.mu.Lock()
6653 sess := mcli.mqtt.sess
6654 sess.mu.Lock()
6655 np := len(sess.pendingPublish)
6656 sess.mu.Unlock()
6657 mcli.mu.Unlock()
6658 if np != 0 {
6659 return fmt.Errorf("Still %v pending messages", np)
6660 }
6661 return nil
6662 })
6663
6664 // Check that change to config does not prevent restart of sub.
6665 cp.Close()
6666 c.Close()
6667 s.Shutdown()
6668
6669 o.Port = -1
6670 o.MQTT.Port = -1
6671 o.MQTT.MaxAckPending = 2
6672 o.StoreDir = dir
6673 s = testMQTTRunServer(t, o)
6674 // There is already the defer for shutdown at top of function
6675
6676 cp, rp = testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6677 defer cp.Close()
6678 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6679
6680 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg5"))
6681 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg6"))
6682
6683 // Restart consumer
6684 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6685 defer c.Close()
6686 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, true)
6687
6688 // Should receive only message 5
6689 pi = testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1, []byte("msg5"))
6690 testMQTTExpectNothing(t, r)
6691
6692 // Ack and get the next
6693 testMQTTSendPIPacket(mqttPacketPubAck, t, c, pi)
6694 testMQTTCheckPubMsg(t, c, r, "foo", mqttPubQos1, []byte("msg6"))
6695 }
6696
6697 func TestMQTTMaxAckPendingForMultipleSubs(t *testing.T) {
6698 o := testMQTTDefaultOptions()
6699 o.MQTT.AckWait = time.Second
6700 o.MQTT.MaxAckPending = 1
6701 s := testMQTTRunServer(t, o)
6702 defer testMQTTShutdownServer(s)
6703
6704 cisub := &mqttConnInfo{clientID: "sub", cleanSess: true}
6705 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6706 defer c.Close()
6707 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6708 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
6709 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
6710
6711 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6712 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6713 defer cp.Close()
6714 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6715
6716 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg1"))
6717 pi := testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1, []byte("msg1"))
6718
6719 // Now send a second message but on topic bar
6720 testMQTTPublish(t, cp, rp, 1, false, false, "bar", 1, []byte("msg2"))
6721
6722 // JS allows us to limit per consumer, but we apply the limit to the
6723 // session, so although JS will attempt to delivery this message,
6724 // the MQTT code will suppress it.
6725 testMQTTExpectNothing(t, r)
6726
6727 // Ack the first message.
6728 testMQTTSendPIPacket(mqttPacketPubAck, t, c, pi)
6729
6730 // Now we should get the second message
6731 testMQTTCheckPubMsg(t, c, r, "bar", mqttPubQos1|mqttPubFlagDup, []byte("msg2"))
6732 }
6733
6734 func TestMQTTMaxAckPendingOverLimit(t *testing.T) {
6735 o := testMQTTDefaultOptions()
6736 o.MQTT.MaxAckPending = 20000
6737 s := testMQTTRunServer(t, o)
6738 defer testMQTTShutdownServer(s)
6739
6740 checkTMax := func(sess *mqttSession, expected int) {
6741 t.Helper()
6742 sess.mu.Lock()
6743 tmax := sess.tmaxack
6744 sess.mu.Unlock()
6745 if tmax != expected {
6746 t.Fatalf("Expected current tmax to be %v, got %v", expected, tmax)
6747 }
6748 }
6749
6750 cisub := &mqttConnInfo{clientID: "sub", cleanSess: false}
6751 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6752 defer c.Close()
6753 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6754
6755 mc := testMQTTGetClient(t, s, "sub")
6756 mc.mu.Lock()
6757 sess := mc.mqtt.sess
6758 mc.mu.Unlock()
6759
6760 // After this one, total would be 20000
6761 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
6762 checkTMax(sess, 20000)
6763 // This one will count for 2, so total will be 60000
6764 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "bar/#", qos: 1}}, []byte{1})
6765 checkTMax(sess, 60000)
6766
6767 // This should fail
6768 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{mqttSubAckFailure})
6769 checkTMax(sess, 60000)
6770
6771 // Remove the one with wildcard
6772 testMQTTUnsub(t, 1, c, r, []*mqttFilter{{filter: "bar/#"}})
6773 checkTMax(sess, 20000)
6774
6775 // Now we could add 2 more without wildcards
6776 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
6777 checkTMax(sess, 40000)
6778 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "baz", qos: 1}}, []byte{1})
6779 checkTMax(sess, 60000)
6780
6781 // Again, this one should fail
6782 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "bat", qos: 1}}, []byte{mqttSubAckFailure})
6783 checkTMax(sess, 60000)
6784
6785 // Now remove all and check that we are at 0
6786 testMQTTUnsub(t, 1, c, r, []*mqttFilter{{filter: "foo"}})
6787 checkTMax(sess, 40000)
6788 testMQTTUnsub(t, 1, c, r, []*mqttFilter{{filter: "bar"}})
6789 checkTMax(sess, 20000)
6790 testMQTTUnsub(t, 1, c, r, []*mqttFilter{{filter: "baz"}})
6791 checkTMax(sess, 0)
6792 }
6793
6794 func TestMQTTConfigReload(t *testing.T) {
6795 template := `
6796 jetstream: true
6797 server_name: mqtt
6798 mqtt {
6799 port: -1
6800 ack_wait: %s
6801 max_ack_pending: %s
6802 }
6803 `
6804 conf := createConfFile(t, []byte(fmt.Sprintf(template, `"5s"`, `10000`)))
6805
6806 s, o := RunServerWithConfig(conf)
6807 defer testMQTTShutdownServer(s)
6808
6809 if val := o.MQTT.AckWait; val != 5*time.Second {
6810 t.Fatalf("Invalid ackwait: %v", val)
6811 }
6812 if val := o.MQTT.MaxAckPending; val != 10000 {
6813 t.Fatalf("Invalid ackwait: %v", val)
6814 }
6815
6816 changeCurrentConfigContentWithNewContent(t, conf, []byte(fmt.Sprintf(template, `"250ms"`, `1`)))
6817 if err := s.Reload(); err != nil {
6818 t.Fatalf("Error on reload: %v", err)
6819 }
6820
6821 cisub := &mqttConnInfo{clientID: "sub", cleanSess: false}
6822 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6823 defer c.Close()
6824 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6825 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
6826
6827 cipub := &mqttConnInfo{clientID: "pub", cleanSess: true}
6828 cp, rp := testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6829 defer cp.Close()
6830 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6831
6832 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg1"))
6833 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg2"))
6834
6835 testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1, []byte("msg1"))
6836 start := time.Now()
6837 testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1|mqttPubFlagDup, []byte("msg1"))
6838 if dur := time.Since(start); dur > 500*time.Millisecond {
6839 t.Fatalf("AckWait not applied? dur=%v", dur)
6840 }
6841 c.Close()
6842 cp.Close()
6843 testMQTTShutdownServer(s)
6844
6845 changeCurrentConfigContentWithNewContent(t, conf, []byte(fmt.Sprintf(template, `"30s"`, `1`)))
6846 s, o = RunServerWithConfig(conf)
6847 defer testMQTTShutdownServer(s)
6848
6849 cisub.cleanSess = true
6850 c, r = testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6851 defer c.Close()
6852 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6853 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
6854
6855 cipub = &mqttConnInfo{clientID: "pub", cleanSess: true}
6856 cp, rp = testMQTTConnect(t, cipub, o.MQTT.Host, o.MQTT.Port)
6857 defer cp.Close()
6858 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
6859
6860 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg1"))
6861 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg2"))
6862
6863 testMQTTCheckPubMsgNoAck(t, c, r, "foo", mqttPubQos1, []byte("msg1"))
6864 testMQTTExpectNothing(t, r)
6865
6866 // Increase the max ack pending
6867 changeCurrentConfigContentWithNewContent(t, conf, []byte(fmt.Sprintf(template, `"30s"`, `10`)))
6868 // Reload now
6869 if err := s.Reload(); err != nil {
6870 t.Fatalf("Error on reload: %v", err)
6871 }
6872
6873 // Reload will have effect only on new subscriptions.
6874 // Create a new subscription, and we should not be able to get the 2 messages.
6875 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
6876
6877 testMQTTPublish(t, cp, rp, 1, false, false, "bar", 1, []byte("msg3"))
6878 testMQTTPublish(t, cp, rp, 1, false, false, "bar", 1, []byte("msg4"))
6879
6880 testMQTTCheckPubMsg(t, c, r, "bar", mqttPubQos1, []byte("msg3"))
6881 testMQTTCheckPubMsg(t, c, r, "bar", mqttPubQos1, []byte("msg4"))
6882 }
6883
6884 func TestMQTTStreamInfoReturnsNonEmptySubject(t *testing.T) {
6885 o := testMQTTDefaultOptions()
6886 s := testMQTTRunServer(t, o)
6887 defer testMQTTShutdownServer(s)
6888
6889 cisub := &mqttConnInfo{clientID: "sub", cleanSess: false}
6890 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
6891 defer c.Close()
6892 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6893
6894 nc := natsConnect(t, s.ClientURL())
6895 defer nc.Close()
6896
6897 // Check that we can query all MQTT streams. MQTT streams are
6898 // created without subject filter, however, if we return them like this,
6899 // the 'nats' utility will fail to display them due to some xml validation.
6900 for _, sname := range []string{
6901 mqttStreamName,
6902 mqttRetainedMsgsStreamName,
6903 } {
6904 t.Run(sname, func(t *testing.T) {
6905 resp, err := nc.Request(fmt.Sprintf(JSApiStreamInfoT, sname), nil, time.Second)
6906 if err != nil {
6907 t.Fatalf("Unexpected error: %v", err)
6908 }
6909 var bResp JSApiStreamInfoResponse
6910 if err = json.Unmarshal(resp.Data, &bResp); err != nil {
6911 t.Fatalf("Unexpected error: %v", err)
6912 }
6913 if len(bResp.Config.Subjects) == 0 {
6914 t.Fatalf("No subject returned, which will cause nats tooling to fail: %+v", bResp.Config)
6915 }
6916 })
6917 }
6918 }
6919
6920 func TestMQTTWebsocketToMQTTPort(t *testing.T) {
6921 conf := createConfFile(t, []byte(fmt.Sprintf(`
6922 listen: "127.0.0.1:-1"
6923 http: "127.0.0.1:-1"
6924 server_name: "mqtt"
6925 jetstream {
6926 store_dir = %q
6927 }
6928 mqtt {
6929 listen: "127.0.0.1:-1"
6930 }
6931 websocket {
6932 listen: "127.0.0.1:-1"
6933 no_tls: true
6934 }
6935 `, t.TempDir())))
6936 s, o := RunServerWithConfig(conf)
6937 defer testMQTTShutdownServer(s)
6938
6939 l := &captureErrorLogger{errCh: make(chan string, 10)}
6940 s.SetLogger(l, false, false)
6941
6942 ci := &mqttConnInfo{cleanSess: true, ws: true}
6943 if _, _, err := testMQTTConnectRetryWithError(t, ci, o.MQTT.Host, o.MQTT.Port, 0); err == nil {
6944 t.Fatal("Expected error during connect")
6945 }
6946 select {
6947 case e := <-l.errCh:
6948 if !strings.Contains(e, errMQTTNotWebsocketPort.Error()) {
6949 t.Fatalf("Unexpected error: %v", e)
6950 }
6951 case <-time.After(time.Second):
6952 t.Fatal("No error regarding wrong port")
6953 }
6954 }
6955
6956 func TestMQTTWebsocket(t *testing.T) {
6957 tdir := t.TempDir()
6958 template := `
6959 listen: "127.0.0.1:-1"
6960 http: "127.0.0.1:-1"
6961 server_name: "mqtt"
6962 jetstream {
6963 store_dir = %q
6964 }
6965 accounts {
6966 MQTT {
6967 jetstream: enabled
6968 users [
6969 {user: "mqtt", pass: "pwd", connection_types: ["%s"%s]}
6970 ]
6971 }
6972 }
6973 mqtt {
6974 listen: "127.0.0.1:-1"
6975 }
6976 websocket {
6977 listen: "127.0.0.1:-1"
6978 no_tls: true
6979 }
6980 `
6981 s, o, conf := runReloadServerWithContent(t, []byte(fmt.Sprintf(template, tdir, jwt.ConnectionTypeMqtt, "")))
6982 defer testMQTTShutdownServer(s)
6983
6984 cisub := &mqttConnInfo{clientID: "sub", user: "mqtt", pass: "pwd", ws: true}
6985 c, r := testMQTTConnect(t, cisub, o.Websocket.Host, o.Websocket.Port)
6986 defer c.Close()
6987 testMQTTCheckConnAck(t, r, mqttConnAckRCNotAuthorized, false)
6988 c.Close()
6989
6990 ws := fmt.Sprintf(`, "%s"`, jwt.ConnectionTypeMqttWS)
6991 reloadUpdateConfig(t, s, conf, fmt.Sprintf(template, tdir, jwt.ConnectionTypeMqtt, ws))
6992
6993 cisub = &mqttConnInfo{clientID: "sub", user: "mqtt", pass: "pwd", ws: true}
6994 c, r = testMQTTConnect(t, cisub, o.Websocket.Host, o.Websocket.Port)
6995 defer c.Close()
6996 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
6997
6998 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
6999 testMQTTFlush(t, c, nil, r)
7000
7001 cipub := &mqttConnInfo{clientID: "pub", user: "mqtt", pass: "pwd", ws: true}
7002 cp, rp := testMQTTConnect(t, cipub, o.Websocket.Host, o.Websocket.Port)
7003 defer cp.Close()
7004 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
7005
7006 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg1"))
7007 testMQTTCheckPubMsg(t, c, r, "foo", mqttPubQos1, []byte("msg1"))
7008 }
7009
7010 type chunkWriteConn struct {
7011 net.Conn
7012 }
7013
7014 func (cwc *chunkWriteConn) Write(p []byte) (int, error) {
7015 max := len(p)
7016 cs := rand.Intn(max) + 1
7017 if cs < max {
7018 if pn, perr := cwc.Conn.Write(p[:cs]); perr != nil {
7019 return pn, perr
7020 }
7021 time.Sleep(10 * time.Millisecond)
7022 if pn, perr := cwc.Conn.Write(p[cs:]); perr != nil {
7023 return pn, perr
7024 }
7025 return len(p), nil
7026 }
7027 return cwc.Conn.Write(p)
7028 }
7029
7030 func TestMQTTPartial(t *testing.T) {
7031 conf := createConfFile(t, []byte(fmt.Sprintf(`
7032 listen: "127.0.0.1:-1"
7033 http: "127.0.0.1:-1"
7034 server_name: "mqtt"
7035 jetstream {
7036 store_dir = %q
7037 }
7038 mqtt {
7039 listen: "127.0.0.1:-1"
7040 }
7041 websocket {
7042 listen: "127.0.0.1:-1"
7043 no_tls: true
7044 }
7045 `, t.TempDir())))
7046 s, o := RunServerWithConfig(conf)
7047 defer testMQTTShutdownServer(s)
7048
7049 for _, test := range []struct {
7050 name string
7051 ws bool
7052 }{
7053 {"standard", false},
7054 {"websocket", true},
7055 } {
7056 t.Run(test.name, func(t *testing.T) {
7057 ci := &mqttConnInfo{cleanSess: true, ws: test.ws}
7058 host, port := o.MQTT.Host, o.MQTT.Port
7059 if test.ws {
7060 host, port = o.Websocket.Host, o.Websocket.Port
7061 }
7062 c, r := testMQTTConnect(t, ci, host, port)
7063 defer c.Close()
7064 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
7065 c = &chunkWriteConn{Conn: c}
7066
7067 cp, rp := testMQTTConnect(t, ci, host, port)
7068 defer cp.Close()
7069 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
7070 cp = &chunkWriteConn{Conn: cp}
7071
7072 subj := nuid.Next()
7073 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: subj, qos: 1}}, []byte{1})
7074 testMQTTFlush(t, c, nil, r)
7075 for i := 0; i < 10; i++ {
7076 testMQTTPublish(t, cp, rp, 1, false, false, subj, 1, []byte("msg"))
7077 testMQTTCheckPubMsg(t, c, r, subj, mqttPubQos1, []byte("msg"))
7078 }
7079 })
7080 }
7081 }
7082
7083 func TestMQTTWebsocketTLS(t *testing.T) {
7084 conf := createConfFile(t, []byte(fmt.Sprintf(`
7085 listen: "127.0.0.1:-1"
7086 http: "127.0.0.1:-1"
7087 server_name: "mqtt"
7088 jetstream {
7089 store_dir = %q
7090 }
7091 mqtt {
7092 listen: "127.0.0.1:-1"
7093 }
7094 websocket {
7095 listen: "127.0.0.1:-1"
7096 tls {
7097 cert_file: '../test/configs/certs/server-cert.pem'
7098 key_file: '../test/configs/certs/server-key.pem'
7099 ca_file: '../test/configs/certs/ca.pem'
7100 }
7101 }
7102 `, t.TempDir())))
7103 s, o := RunServerWithConfig(conf)
7104 defer testMQTTShutdownServer(s)
7105
7106 c, r := testMQTTConnect(t, &mqttConnInfo{clientID: "sub", ws: true, tls: true}, o.Websocket.Host, o.Websocket.Port)
7107 defer c.Close()
7108 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
7109 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
7110 testMQTTFlush(t, c, nil, r)
7111
7112 cp, rp := testMQTTConnect(t, &mqttConnInfo{clientID: "pub", ws: true, tls: true}, o.Websocket.Host, o.Websocket.Port)
7113 defer cp.Close()
7114 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
7115
7116 testMQTTPublish(t, cp, rp, 1, false, false, "foo", 1, []byte("msg1"))
7117 testMQTTCheckPubMsg(t, c, r, "foo", mqttPubQos1, []byte("msg1"))
7118 }
7119
7120 func TestMQTTTransferSessionStreamsToMuxed(t *testing.T) {
7121 cl := createJetStreamClusterWithTemplate(t, testMQTTGetClusterTemplaceNoLeaf(), "MQTT", 3)
7122 defer cl.shutdown()
7123
7124 nc, js := jsClientConnect(t, cl.randomServer())
7125 defer nc.Close()
7126
7127 // Create 2 streams that start with "$MQTT_sess_" to check for transfer to new
7128 // mux'ed unique "$MQTT_sess" stream. One of this stream will not contain a
7129 // proper session record, and we will check that the stream does not get deleted.
7130 sessStreamName1 := mqttSessionsStreamNamePrefix + getHash("sub")
7131 if _, err := js.AddStream(&nats.StreamConfig{
7132 Name: sessStreamName1,
7133 Subjects: []string{sessStreamName1},
7134 Replicas: 3,
7135 MaxMsgs: 1,
7136 }); err != nil {
7137 t.Fatalf("Unable to add stream: %v", err)
7138 }
7139 // Then add the session record
7140 ps := mqttPersistedSession{
7141 ID: "sub",
7142 Subs: map[string]byte{"foo": 1},
7143 Cons: map[string]*ConsumerConfig{"foo": {
7144 Durable: "d6INCtp3_cK39H5WHEtOSU7sLy2oQv3",
7145 DeliverSubject: "$MQTT.sub.cK39H5WHEtOSU7sLy2oQrR",
7146 DeliverPolicy: DeliverNew,
7147 AckPolicy: AckExplicit,
7148 FilterSubject: "$MQTT.msgs.foo",
7149 MaxAckPending: 1024,
7150 }},
7151 }
7152 b, _ := json.Marshal(&ps)
7153 if _, err := js.Publish(sessStreamName1, b); err != nil {
7154 t.Fatalf("Error on publish: %v", err)
7155 }
7156
7157 // Create the stream that has "$MQTT_sess_" prefix, but that is not really a MQTT session stream
7158 sessStreamName2 := mqttSessionsStreamNamePrefix + "ivan"
7159 if _, err := js.AddStream(&nats.StreamConfig{
7160 Name: sessStreamName2,
7161 Subjects: []string{sessStreamName2},
7162 Replicas: 3,
7163 MaxMsgs: 1,
7164 }); err != nil {
7165 t.Fatalf("Unable to add stream: %v", err)
7166 }
7167 if _, err := js.Publish(sessStreamName2, []byte("some content")); err != nil {
7168 t.Fatalf("Error on publish: %v", err)
7169 }
7170
7171 cl.waitOnStreamLeader(globalAccountName, sessStreamName1)
7172 cl.waitOnStreamLeader(globalAccountName, sessStreamName2)
7173
7174 // Now create a real MQTT connection
7175 o := cl.opts[0]
7176 sc, sr := testMQTTConnectRetry(t, &mqttConnInfo{clientID: "sub"}, o.MQTT.Host, o.MQTT.Port, 10)
7177 defer sc.Close()
7178 testMQTTCheckConnAck(t, sr, mqttConnAckRCConnectionAccepted, true)
7179
7180 // Check that old session stream is gone, but the non session stream is still present.
7181 var gotIt = false
7182 for info := range js.StreamsInfo() {
7183 if strings.HasPrefix(info.Config.Name, mqttSessionsStreamNamePrefix) {
7184 if strings.HasSuffix(info.Config.Name, "_ivan") {
7185 gotIt = true
7186 } else {
7187 t.Fatalf("The stream %q should have been deleted", info.Config.Name)
7188 }
7189 }
7190 }
7191 if !gotIt {
7192 t.Fatalf("The stream %q should not have been deleted", mqttSessionsStreamNamePrefix+"ivan")
7193 }
7194
7195 // We want to check that the record was properly transferred.
7196 rmsg, err := js.GetMsg(mqttSessStreamName, 2)
7197 if err != nil {
7198 t.Fatalf("Unable to get session message: %v", err)
7199 }
7200 ps2 := &mqttPersistedSession{}
7201 if err := json.Unmarshal(rmsg.Data, ps2); err != nil {
7202 t.Fatalf("Error unpacking session record: %v", err)
7203 }
7204 if ps2.ID != "sub" {
7205 t.Fatalf("Unexpected session record, %+v vs %+v", ps2, ps)
7206 }
7207 if qos, ok := ps2.Subs["foo"]; !ok || qos != 1 {
7208 t.Fatalf("Unexpected session record, %+v vs %+v", ps2, ps)
7209 }
7210 if cons, ok := ps2.Cons["foo"]; !ok || !reflect.DeepEqual(cons, ps.Cons["foo"]) {
7211 t.Fatalf("Unexpected session record, %+v vs %+v", ps2, ps)
7212 }
7213
7214 // Make sure we don't attempt to transfer again by creating a subscription
7215 // on the "stream names" API, which is used to get the list of streams to transfer
7216 sub := natsSubSync(t, nc, JSApiStreams)
7217
7218 // Make sure to connect an MQTT client from a different node so that this node
7219 // gets a connection for the account for the first time and tries to create
7220 // all MQTT streams, etc..
7221 o = cl.opts[1]
7222 sc, sr = testMQTTConnectRetry(t, &mqttConnInfo{clientID: "sub2"}, o.MQTT.Host, o.MQTT.Port, 10)
7223 defer sc.Close()
7224 testMQTTCheckConnAck(t, sr, mqttConnAckRCConnectionAccepted, false)
7225
7226 if _, err := sub.NextMsg(200 * time.Millisecond); err == nil {
7227 t.Fatal("Looks like attempt to transfer was done again")
7228 }
7229 }
7230
7231 func TestMQTTConnectAndDisconnectEvent(t *testing.T) {
7232 conf := createConfFile(t, []byte(fmt.Sprintf(`
7233 listen: "127.0.0.1:-1"
7234 http: "127.0.0.1:-1"
7235 server_name: "mqtt"
7236 jetstream {
7237 store_dir = %q
7238 }
7239 accounts {
7240 MQTT {
7241 jetstream: enabled
7242 users: [{user: "mqtt", password: "pwd"}]
7243 }
7244 SYS {
7245 users: [{user: "sys", password: "pwd"}]
7246 }
7247 }
7248 mqtt {
7249 listen: "127.0.0.1:-1"
7250 }
7251 system_account: "SYS"
7252 `, t.TempDir())))
7253 defer os.Remove(conf)
7254 s, o := RunServerWithConfig(conf)
7255 defer testMQTTShutdownServer(s)
7256
7257 nc := natsConnect(t, s.ClientURL(), nats.UserInfo("sys", "pwd"))
7258 defer nc.Close()
7259
7260 accConn := natsSubSync(t, nc, fmt.Sprintf(connectEventSubj, "MQTT"))
7261 accDisc := natsSubSync(t, nc, fmt.Sprintf(disconnectEventSubj, "MQTT"))
7262 accAuth := natsSubSync(t, nc, fmt.Sprintf(authErrorEventSubj, s.ID()))
7263 natsFlush(t, nc)
7264
7265 checkConnEvent := func(data []byte, expected string) {
7266 t.Helper()
7267 var ce ConnectEventMsg
7268 json.Unmarshal(data, &ce)
7269 if ce.Client.MQTTClient != expected {
7270 t.Fatalf("Expected client ID %q, got this connect event: %+v", expected, ce)
7271 }
7272 }
7273 checkDiscEvent := func(data []byte, expected string) {
7274 t.Helper()
7275 var de DisconnectEventMsg
7276 json.Unmarshal(data, &de)
7277 if de.Client.MQTTClient != expected {
7278 t.Fatalf("Expected client ID %q, got this disconnect event: %+v", expected, de)
7279 }
7280 }
7281
7282 c1, r1 := testMQTTConnect(t, &mqttConnInfo{user: "mqtt", pass: "pwd", clientID: "conn1", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7283 defer c1.Close()
7284 testMQTTCheckConnAck(t, r1, mqttConnAckRCConnectionAccepted, false)
7285
7286 cm := natsNexMsg(t, accConn, time.Second)
7287 checkConnEvent(cm.Data, "conn1")
7288
7289 c2, r2 := testMQTTConnect(t, &mqttConnInfo{user: "mqtt", pass: "pwd", clientID: "conn2", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7290 defer c2.Close()
7291 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, false)
7292
7293 cm = natsNexMsg(t, accConn, time.Second)
7294 checkConnEvent(cm.Data, "conn2")
7295
7296 c3, r3 := testMQTTConnect(t, &mqttConnInfo{user: "mqtt", pass: "pwd", clientID: "conn3", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7297 defer c3.Close()
7298 testMQTTCheckConnAck(t, r3, mqttConnAckRCConnectionAccepted, false)
7299
7300 cm = natsNexMsg(t, accConn, time.Second)
7301 checkConnEvent(cm.Data, "conn3")
7302
7303 testMQTTDisconnect(t, c3, nil)
7304 c3.Close()
7305 cm = natsNexMsg(t, accDisc, time.Second)
7306 checkDiscEvent(cm.Data, "conn3")
7307
7308 // Now try a bad auth
7309 c4, r4 := testMQTTConnect(t, &mqttConnInfo{clientID: "conn4", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7310 defer c4.Close()
7311 testMQTTCheckConnAck(t, r4, mqttConnAckRCNotAuthorized, false)
7312 // This will generate an auth error, which is a disconnect event
7313 cm = natsNexMsg(t, accAuth, time.Second)
7314 checkDiscEvent(cm.Data, "conn4")
7315
7316 url := fmt.Sprintf("http://127.0.0.1:%d/", s.MonitorAddr().Port)
7317 for mode := 0; mode < 2; mode++ {
7318 c := pollConnz(t, s, mode, url+"connz", nil)
7319 if c.Conns == nil || len(c.Conns) != 3 {
7320 t.Fatalf("Expected 3 connections in array, got %v", len(c.Conns))
7321 }
7322
7323 // Check that client ID is present
7324 for _, conn := range c.Conns {
7325 if conn.Type == clientTypeStringMap[MQTT] && conn.MQTTClient == _EMPTY_ {
7326 t.Fatalf("Expected a client ID to be set, got %+v", conn)
7327 }
7328 }
7329
7330 // Check that we can select based on client ID:
7331 c = pollConnz(t, s, mode, url+"connz?mqtt_client=conn2", &ConnzOptions{MQTTClient: "conn2"})
7332 if c.Conns == nil || len(c.Conns) != 1 {
7333 t.Fatalf("Expected 1 connection in array, got %v", len(c.Conns))
7334 }
7335 if c.Conns[0].MQTTClient != "conn2" {
7336 t.Fatalf("Unexpected client ID: %+v", c.Conns[0])
7337 }
7338
7339 // Check that we have the closed ones
7340 c = pollConnz(t, s, mode, url+"connz?state=closed", &ConnzOptions{State: ConnClosed})
7341 if c.Conns == nil || len(c.Conns) != 2 {
7342 t.Fatalf("Expected 2 connections in array, got %v", len(c.Conns))
7343 }
7344 for _, conn := range c.Conns {
7345 if conn.MQTTClient == _EMPTY_ {
7346 t.Fatalf("Expected a client ID, got %+v", conn)
7347 }
7348 }
7349
7350 // Check that we can select with client ID for closed state
7351 c = pollConnz(t, s, mode, url+"connz?state=closed&mqtt_client=conn3", &ConnzOptions{State: ConnClosed, MQTTClient: "conn3"})
7352 if c.Conns == nil || len(c.Conns) != 1 {
7353 t.Fatalf("Expected 1 connection in array, got %v", len(c.Conns))
7354 }
7355 if c.Conns[0].MQTTClient != "conn3" {
7356 t.Fatalf("Unexpected client ID: %+v", c.Conns[0])
7357 }
7358 // Check that we can select with client ID for closed state (but in this case not found)
7359 c = pollConnz(t, s, mode, url+"connz?state=closed&mqtt_client=conn5", &ConnzOptions{State: ConnClosed, MQTTClient: "conn5"})
7360 if len(c.Conns) != 0 {
7361 t.Fatalf("Expected 0 connection in array, got %v", len(c.Conns))
7362 }
7363 }
7364
7365 reply := nc.NewRespInbox()
7366 replySub := natsSubSync(t, nc, reply)
7367
7368 // Test system events now
7369 for _, test := range []struct {
7370 opt any
7371 cid string
7372 }{
7373 {&ConnzOptions{MQTTClient: "conn1"}, "conn1"},
7374 {&ConnzOptions{MQTTClient: "conn3", State: ConnClosed}, "conn3"},
7375 {&ConnzOptions{MQTTClient: "conn4", State: ConnClosed}, "conn4"},
7376 {&ConnzOptions{MQTTClient: "conn5"}, _EMPTY_},
7377 {json.RawMessage(`{"mqtt_client":"conn1"}`), "conn1"},
7378 {json.RawMessage(fmt.Sprintf(`{"mqtt_client":"conn3", "state":%v}`, ConnClosed)), "conn3"},
7379 {json.RawMessage(fmt.Sprintf(`{"mqtt_client":"conn4", "state":%v}`, ConnClosed)), "conn4"},
7380 {json.RawMessage(`{"mqtt_client":"conn5"}`), _EMPTY_},
7381 } {
7382 t.Run("sys connz", func(t *testing.T) {
7383 b, _ := json.Marshal(test.opt)
7384
7385 // set a header to make sure request parsing knows to ignore them
7386 nc.PublishMsg(&nats.Msg{
7387 Subject: fmt.Sprintf("%s.CONNZ", serverStatsPingReqSubj),
7388 Reply: reply,
7389 Data: b,
7390 })
7391
7392 msg := natsNexMsg(t, replySub, time.Second)
7393 var response ServerAPIResponse
7394 if err := json.Unmarshal(msg.Data, &response); err != nil {
7395 t.Fatalf("Error unmarshalling response json: %v", err)
7396 }
7397 tmp, _ := json.Marshal(response.Data)
7398 cz := &Connz{}
7399 if err := json.Unmarshal(tmp, cz); err != nil {
7400 t.Fatalf("Error unmarshalling connz: %v", err)
7401 }
7402 if test.cid == _EMPTY_ {
7403 if len(cz.Conns) != 0 {
7404 t.Fatalf("Expected no connections, got %v", len(cz.Conns))
7405 }
7406 return
7407 }
7408 if len(cz.Conns) != 1 {
7409 t.Fatalf("Expected single connection, got %v", len(cz.Conns))
7410 }
7411 conn := cz.Conns[0]
7412 if conn.MQTTClient != test.cid {
7413 t.Fatalf("Expected client ID %q, got %q", test.cid, conn.MQTTClient)
7414 }
7415 })
7416 }
7417 }
7418
7419 func TestMQTTClientIDInLogStatements(t *testing.T) {
7420 o := testMQTTDefaultOptions()
7421 s := testMQTTRunServer(t, o)
7422 defer testMQTTShutdownServer(s)
7423
7424 l := &captureDebugLogger{dbgCh: make(chan string, 10)}
7425 s.SetLogger(l, true, false)
7426
7427 cisub := &mqttConnInfo{clientID: "my_client_id", cleanSess: false}
7428 c, r := testMQTTConnect(t, cisub, o.MQTT.Host, o.MQTT.Port)
7429 defer c.Close()
7430 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
7431 testMQTTDisconnect(t, c, nil)
7432 c.Close()
7433
7434 tm := time.NewTimer(2 * time.Second)
7435 var connected bool
7436 var disconnected bool
7437 for {
7438 select {
7439 case dl := <-l.dbgCh:
7440 if strings.Contains(dl, "my_client_id") {
7441 if strings.Contains(dl, "Client connected") {
7442 connected = true
7443 } else if strings.Contains(dl, "Client connection closed") {
7444 disconnected = true
7445 }
7446 if connected && disconnected {
7447 // OK!
7448 return
7449 }
7450 }
7451 case <-tm.C:
7452 t.Fatal("Did not get the debug statements or client_id in them")
7453 }
7454 }
7455 }
7456
7457 func TestMQTTStreamReplicasOverride(t *testing.T) {
7458 conf := `
7459 listen: 127.0.0.1:-1
7460 server_name: %s
7461 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
7462
7463 cluster {
7464 name: %s
7465 listen: 127.0.0.1:%d
7466 routes = [%s]
7467 }
7468
7469 mqtt {
7470 listen: 127.0.0.1:-1
7471 stream_replicas: 3
7472 }
7473
7474 # For access to system account.
7475 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } }
7476 `
7477 cl := createJetStreamClusterWithTemplate(t, conf, "MQTT", 3)
7478 defer cl.shutdown()
7479
7480 connectAndCheck := func(restarted bool) {
7481 t.Helper()
7482
7483 o := cl.opts[0]
7484 mc, r := testMQTTConnectRetry(t, &mqttConnInfo{clientID: "test", cleanSess: false}, o.MQTT.Host, o.MQTT.Port, 5)
7485 defer mc.Close()
7486 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, restarted)
7487
7488 nc, js := jsClientConnect(t, cl.servers[2])
7489 defer nc.Close()
7490
7491 streams := []string{mqttStreamName, mqttRetainedMsgsStreamName, mqttSessStreamName}
7492 for _, sn := range streams {
7493 si, err := js.StreamInfo(sn)
7494 require_NoError(t, err)
7495 if n := len(si.Cluster.Replicas); n != 2 {
7496 t.Fatalf("Expected stream %q to have 2 replicas, got %v", sn, n)
7497 }
7498 }
7499 }
7500 connectAndCheck(false)
7501
7502 cl.stopAll()
7503 for _, o := range cl.opts {
7504 o.MQTT.StreamReplicas = 2
7505 }
7506 cl.restartAllSamePorts()
7507 cl.waitOnStreamLeader(globalAccountName, mqttStreamName)
7508 cl.waitOnStreamLeader(globalAccountName, mqttRetainedMsgsStreamName)
7509 cl.waitOnStreamLeader(globalAccountName, mqttSessStreamName)
7510
7511 l := &captureWarnLogger{warn: make(chan string, 10)}
7512 cl.servers[0].SetLogger(l, false, false)
7513
7514 connectAndCheck(true)
7515
7516 select {
7517 case w := <-l.warn:
7518 if !strings.Contains(w, "current is 3 but configuration is 2") {
7519 t.Fatalf("Unexpected warning: %q", w)
7520 }
7521 case <-time.After(2 * time.Second):
7522 t.Fatal("Should have warned against replicas mismatch")
7523 }
7524 }
7525
7526 func TestMQTTStreamReplicasConfigReload(t *testing.T) {
7527 tdir := t.TempDir()
7528 tmpl := `
7529 jetstream {
7530 store_dir = %q
7531 }
7532 server_name: mqtt
7533 mqtt {
7534 port: -1
7535 stream_replicas: %v
7536 }
7537 `
7538 conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, tdir, 3)))
7539 s, o := RunServerWithConfig(conf)
7540 defer testMQTTShutdownServer(s)
7541
7542 l := &captureErrorLogger{errCh: make(chan string, 10)}
7543 s.SetLogger(l, false, false)
7544
7545 _, _, err := testMQTTConnectRetryWithError(t, &mqttConnInfo{clientID: "mqtt", cleanSess: false}, o.MQTT.Host, o.MQTT.Port, 0)
7546 if err == nil {
7547 t.Fatal("Expected to fail, did not")
7548 }
7549
7550 select {
7551 case e := <-l.errCh:
7552 if !strings.Contains(e, NewJSStreamReplicasNotSupportedError().Description) {
7553 t.Fatalf("Expected error regarding replicas, got %v", e)
7554 }
7555 case <-time.After(2 * time.Second):
7556 t.Fatalf("Did not get the error regarding replicas count")
7557 }
7558
7559 reloadUpdateConfig(t, s, conf, fmt.Sprintf(tmpl, tdir, 1))
7560
7561 mc, r := testMQTTConnect(t, &mqttConnInfo{clientID: "mqtt", cleanSess: false}, o.MQTT.Host, o.MQTT.Port)
7562 defer mc.Close()
7563 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
7564 }
7565
7566 func TestMQTTStreamReplicasInsufficientResources(t *testing.T) {
7567 conf := `
7568 listen: 127.0.0.1:-1
7569 server_name: %s
7570 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
7571
7572 cluster {
7573 name: %s
7574 listen: 127.0.0.1:%d
7575 routes = [%s]
7576 }
7577
7578 mqtt {
7579 listen: 127.0.0.1:-1
7580 stream_replicas: 5
7581 }
7582
7583 # For access to system account.
7584 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } }
7585 `
7586 cl := createJetStreamClusterWithTemplate(t, conf, "MQTT", 3)
7587 defer cl.shutdown()
7588
7589 l := &captureErrorLogger{errCh: make(chan string, 10)}
7590 for _, s := range cl.servers {
7591 s.SetLogger(l, false, false)
7592 }
7593
7594 o := cl.opts[1]
7595 _, _, err := testMQTTConnectRetryWithError(t, &mqttConnInfo{clientID: "mqtt", cleanSess: false}, o.MQTT.Host, o.MQTT.Port, 0)
7596 if err == nil {
7597 t.Fatal("Expected to fail, did not")
7598 }
7599
7600 select {
7601 case e := <-l.errCh:
7602 if !strings.Contains(e, fmt.Sprintf("%d", NewJSClusterNoPeersError(errors.New("")).ErrCode)) {
7603 t.Fatalf("Expected error regarding no peers error, got %v", e)
7604 }
7605 case <-time.After(2 * time.Second):
7606 t.Fatalf("Did not get the error regarding replicas count")
7607 }
7608 }
7609
7610 func TestMQTTConsumerReplicasValidate(t *testing.T) {
7611 o := testMQTTDefaultOptions()
7612 for _, test := range []struct {
7613 name string
7614 sr int
7615 cr int
7616 err bool
7617 }{
7618 {"stream replicas neg", -1, 3, false},
7619 {"stream replicas 0", 0, 3, false},
7620 {"consumer replicas neg", 0, -1, false},
7621 {"consumer replicas 0", -1, 0, false},
7622 {"consumer replicas too high", 1, 2, true},
7623 } {
7624 t.Run(test.name, func(t *testing.T) {
7625 o.MQTT.StreamReplicas = test.sr
7626 o.MQTT.ConsumerReplicas = test.cr
7627 err := validateMQTTOptions(o)
7628 if test.err {
7629 if err == nil {
7630 t.Fatal("Expected error, did not get one")
7631 }
7632 if !strings.Contains(err.Error(), "cannot be higher") {
7633 t.Fatalf("Unexpected error: %v", err)
7634 }
7635 // OK
7636 return
7637 } else if err != nil {
7638 t.Fatalf("Unexpected error: %v", err)
7639 }
7640 })
7641 }
7642 }
7643
7644 // This was ill-advised since the messages stream is currently interest policy.
7645 // Interest policy streams require consumers match the replica count.
7646 // Will leave her for now to make sure we do not override.
7647 func TestMQTTConsumerReplicasOverride(t *testing.T) {
7648 conf := `
7649 listen: 127.0.0.1:-1
7650 server_name: %s
7651 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, store_dir: '%s'}
7652
7653 cluster {
7654 name: %s
7655 listen: 127.0.0.1:%d
7656 routes = [%s]
7657 }
7658
7659 mqtt {
7660 listen: 127.0.0.1:-1
7661 stream_replicas: 5
7662 consumer_replicas: 1
7663 consumer_memory_storage: true
7664 }
7665
7666 # For access to system account.
7667 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } }
7668 `
7669 cl := createJetStreamClusterWithTemplate(t, conf, "MQTT", 5)
7670 defer cl.shutdown()
7671
7672 connectAndCheck := func(subject string, restarted bool) {
7673 t.Helper()
7674
7675 o := cl.opts[0]
7676 mc, r := testMQTTConnectRetry(t, &mqttConnInfo{clientID: "test", cleanSess: false}, o.MQTT.Host, o.MQTT.Port, 5)
7677 defer mc.Close()
7678 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, restarted)
7679 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: subject, qos: 1}}, []byte{1})
7680
7681 nc, js := jsClientConnect(t, cl.servers[2])
7682 defer nc.Close()
7683
7684 for ci := range js.ConsumersInfo(mqttStreamName) {
7685 if ci.Config.FilterSubject == mqttStreamSubjectPrefix+subject {
7686 if rf := len(ci.Cluster.Replicas) + 1; rf != 5 {
7687 t.Fatalf("Expected consumer to be R5, got: %d", rf)
7688 }
7689 }
7690 }
7691 }
7692 connectAndCheck("foo", false)
7693
7694 cl.stopAll()
7695 for _, o := range cl.opts {
7696 o.MQTT.ConsumerReplicas = 2
7697 o.MQTT.ConsumerMemoryStorage = false
7698 }
7699 cl.restartAllSamePorts()
7700 cl.waitOnStreamLeader(globalAccountName, mqttStreamName)
7701 cl.waitOnStreamLeader(globalAccountName, mqttRetainedMsgsStreamName)
7702 cl.waitOnStreamLeader(globalAccountName, mqttSessStreamName)
7703
7704 connectAndCheck("bar", true)
7705 }
7706
7707 func TestMQTTConsumerMemStorageReload(t *testing.T) {
7708 tdir := t.TempDir()
7709 tmpl := `
7710 jetstream {
7711 store_dir = %q
7712 }
7713 server_name: mqtt
7714 mqtt {
7715 port: -1
7716 consumer_memory_storage: %s
7717 }
7718 `
7719 conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, tdir, "false")))
7720 s, o := RunServerWithConfig(conf)
7721 defer testMQTTShutdownServer(s)
7722
7723 l := &captureErrorLogger{errCh: make(chan string, 10)}
7724 s.SetLogger(l, false, false)
7725
7726 c, r := testMQTTConnect(t, &mqttConnInfo{clientID: "sub", cleanSess: false}, o.MQTT.Host, o.MQTT.Port)
7727 defer c.Close()
7728 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
7729
7730 reloadUpdateConfig(t, s, conf, fmt.Sprintf(tmpl, tdir, "true"))
7731
7732 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
7733
7734 mset, err := s.GlobalAccount().lookupStream(mqttStreamName)
7735 if err != nil {
7736 t.Fatalf("Error looking up stream: %v", err)
7737 }
7738 var cons *consumer
7739 mset.mu.RLock()
7740 for _, c := range mset.consumers {
7741 cons = c
7742 break
7743 }
7744 mset.mu.RUnlock()
7745 cons.mu.RLock()
7746 st := cons.store.Type()
7747 cons.mu.RUnlock()
7748 if st != MemoryStorage {
7749 t.Fatalf("Expected storage %v, got %v", MemoryStorage, st)
7750 }
7751 }
7752
7753 // Test for auto-cleanup of consumers.
7754 func TestMQTTConsumerInactiveThreshold(t *testing.T) {
7755 tdir := t.TempDir()
7756 tmpl := `
7757 listen: 127.0.0.1:-1
7758 server_name: mqtt
7759 jetstream {
7760 store_dir = %q
7761 }
7762
7763 mqtt {
7764 listen: 127.0.0.1:-1
7765 consumer_inactive_threshold: %q
7766 }
7767
7768 # For access to system account.
7769 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } }
7770 `
7771 conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, tdir, "0.2s")))
7772 s, o := RunServerWithConfig(conf)
7773 defer testMQTTShutdownServer(s)
7774
7775 mc, r := testMQTTConnectRetry(t, &mqttConnInfo{clientID: "test", cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 5)
7776 defer mc.Close()
7777 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
7778 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
7779
7780 nc, js := jsClientConnect(t, s)
7781 defer nc.Close()
7782
7783 ci := <-js.ConsumersInfo("$MQTT_msgs")
7784
7785 // Make sure we clean up this consumer.
7786 mc.Close()
7787 checkFor(t, 2*time.Second, 50*time.Millisecond, func() error {
7788 _, err := js.ConsumerInfo(ci.Stream, ci.Name)
7789 if err == nil {
7790 return fmt.Errorf("Consumer still present")
7791 }
7792 return nil
7793 })
7794
7795 // Check reload.
7796 // We will not redo existing consumers however.
7797 reloadUpdateConfig(t, s, conf, fmt.Sprintf(tmpl, tdir, "22s"))
7798 if opts := s.getOpts(); opts.MQTT.ConsumerInactiveThreshold != 22*time.Second {
7799 t.Fatalf("Expected reloaded value of %v but got %v", 22*time.Second, opts.MQTT.ConsumerInactiveThreshold)
7800 }
7801 }
7802
7803 func TestMQTTSubjectMapping(t *testing.T) {
7804 conf := createConfFile(t, []byte(fmt.Sprintf(`
7805 listen: 127.0.0.1:-1
7806 server_name: mqtt
7807 jetstream {
7808 store_dir = %q
7809 }
7810
7811 mappings = {
7812 foo0: bar0
7813 foo1: bar1
7814 }
7815
7816 mqtt {
7817 listen: 127.0.0.1:-1
7818 }
7819 `, t.TempDir())))
7820 s, o := RunServerWithConfig(conf)
7821 defer testMQTTShutdownServer(s)
7822
7823 nc, js := jsClientConnect(t, s)
7824 defer nc.Close()
7825
7826 for _, qos := range []byte{0, 1} {
7827 t.Run(fmt.Sprintf("qos%d", qos), func(t *testing.T) {
7828 mc, r := testMQTTConnect(t, &mqttConnInfo{clientID: "sub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7829 defer mc.Close()
7830
7831 bar := fmt.Sprintf("bar%v", qos)
7832 foo := fmt.Sprintf("foo%v", qos)
7833
7834 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
7835 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: bar, qos: qos}}, []byte{qos})
7836 testMQTTFlush(t, mc, nil, r)
7837
7838 mcp, rp := testMQTTConnect(t, &mqttConnInfo{clientID: "pub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7839 defer mcp.Close()
7840 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
7841
7842 natsPub(t, nc, foo, []byte("msg0"))
7843 testMQTTCheckPubMsgNoAck(t, mc, r, bar, 0, []byte("msg0"))
7844
7845 testMQTTPublish(t, mcp, rp, 0, false, false, foo, 0, []byte("msg1"))
7846 testMQTTCheckPubMsgNoAck(t, mc, r, bar, 0, []byte("msg1"))
7847
7848 testMQTTPublish(t, mcp, rp, 0, false, true, foo, 0, []byte("msg1_retained"))
7849 testMQTTCheckPubMsgNoAck(t, mc, r, bar, 0, []byte("msg1_retained"))
7850
7851 testMQTTPublish(t, mcp, rp, 1, false, false, foo, 1, []byte("msg2"))
7852 // For the receiving side, the expected QoS is based on the subscription's QoS,
7853 // not the publisher.
7854 expected := byte(0)
7855 if qos == 1 {
7856 expected = mqttPubQos1
7857 }
7858 testMQTTCheckPubMsgNoAck(t, mc, r, bar, expected, []byte("msg2"))
7859
7860 testMQTTPublish(t, mcp, rp, 1, false, true, foo, 1, []byte("msg2_retained"))
7861 testMQTTCheckPubMsgNoAck(t, mc, r, bar, expected, []byte("msg2_retained"))
7862
7863 testMQTTDisconnect(t, mcp, nil)
7864 mcp.Close()
7865
7866 // Try the with the "will" with QoS0 first
7867 mcp, rp = testMQTTConnect(t, &mqttConnInfo{
7868 clientID: "pub",
7869 cleanSess: true,
7870 will: &mqttWill{topic: []byte(foo), qos: 0, message: []byte("willmsg1")}},
7871 o.MQTT.Host, o.MQTT.Port)
7872 defer mcp.Close()
7873 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
7874 testMQTTFlush(t, mcp, nil, rp)
7875
7876 // Close the connection without proper disconnect for will to be sent
7877 mcp.Close()
7878 testMQTTCheckPubMsgNoAck(t, mc, r, bar, 0, []byte("willmsg1"))
7879
7880 // Try the with the "will" with QoS1 now
7881 mcp, rp = testMQTTConnect(t, &mqttConnInfo{
7882 clientID: "pub",
7883 cleanSess: true,
7884 will: &mqttWill{topic: []byte(foo), qos: 1, message: []byte("willmsg2")}},
7885 o.MQTT.Host, o.MQTT.Port)
7886 defer mcp.Close()
7887 testMQTTCheckConnAck(t, rp, mqttConnAckRCConnectionAccepted, false)
7888 testMQTTFlush(t, mcp, nil, rp)
7889
7890 // Close the connection without proper disconnect for will to be sent
7891 mcp.Close()
7892 testMQTTCheckPubMsgNoAck(t, mc, r, bar, expected, []byte("willmsg2"))
7893
7894 si, err := js.StreamInfo("$MQTT_msgs")
7895 require_NoError(t, err)
7896 if qos == 0 {
7897 require_True(t, si.State.Msgs == 0)
7898 require_True(t, si.State.NumSubjects == 0)
7899 } else {
7900 // Number of QoS1 messages: 1 regular, 1 retained, 1 from will.
7901 require_True(t, si.State.Msgs == 3)
7902 require_True(t, si.State.NumSubjects == 1)
7903 }
7904 testMQTTDisconnect(t, mc, nil)
7905 })
7906 }
7907 }
7908
7909 func TestMQTTSubjectMappingWithImportExport(t *testing.T) {
7910 conf := createConfFile(t, []byte(fmt.Sprintf(`
7911 listen: 127.0.0.1:-1
7912 server_name: mqtt
7913 jetstream {
7914 store_dir = %q
7915 }
7916
7917 accounts {
7918 A {
7919 users = [{user: "a", password: "pwd"}]
7920 mappings = {
7921 bar: foo
7922 }
7923 exports = [{service: "bar"}]
7924 jetstream: enabled
7925 }
7926 B {
7927 users = [{user: "b", password: "pwd"}]
7928 mappings = {
7929 foo: bar
7930 }
7931 imports = [{service: {account: "A", subject: "bar"}}]
7932 jetstream: enabled
7933 }
7934 $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
7935 }
7936
7937 mqtt {
7938 listen: 127.0.0.1:-1
7939 }
7940 `, t.TempDir())))
7941 s, o := RunServerWithConfig(conf)
7942 defer testMQTTShutdownServer(s)
7943
7944 c1, r1 := testMQTTConnect(t, &mqttConnInfo{user: "a", pass: "pwd", clientID: "a1", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7945 defer c1.Close()
7946 testMQTTCheckConnAck(t, r1, mqttConnAckRCConnectionAccepted, false)
7947 testMQTTSub(t, 1, c1, r1, []*mqttFilter{{filter: "foo", qos: 0}}, []byte{0})
7948 testMQTTFlush(t, c1, nil, r1)
7949
7950 c2, r2 := testMQTTConnect(t, &mqttConnInfo{user: "a", pass: "pwd", clientID: "a2", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7951 defer c2.Close()
7952 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, false)
7953 testMQTTSub(t, 1, c2, r2, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
7954 testMQTTFlush(t, c2, nil, r2)
7955
7956 c3, r3 := testMQTTConnect(t, &mqttConnInfo{user: "a", pass: "pwd", clientID: "a3", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7957 defer c3.Close()
7958 testMQTTCheckConnAck(t, r3, mqttConnAckRCConnectionAccepted, false)
7959 testMQTTSub(t, 1, c3, r3, []*mqttFilter{{filter: "bar", qos: 0}}, []byte{0})
7960 testMQTTFlush(t, c3, nil, r3)
7961
7962 c4, r4 := testMQTTConnect(t, &mqttConnInfo{user: "a", pass: "pwd", clientID: "a4", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7963 defer c4.Close()
7964 testMQTTCheckConnAck(t, r4, mqttConnAckRCConnectionAccepted, false)
7965 testMQTTSub(t, 1, c4, r4, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
7966 testMQTTFlush(t, c4, nil, r4)
7967
7968 bc, br := testMQTTConnect(t, &mqttConnInfo{user: "b", pass: "pwd", clientID: "b0", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7969 defer bc.Close()
7970 testMQTTCheckConnAck(t, br, mqttConnAckRCConnectionAccepted, false)
7971
7972 bc1, br1 := testMQTTConnect(t, &mqttConnInfo{user: "b", pass: "pwd", clientID: "b1", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7973 defer bc1.Close()
7974 testMQTTCheckConnAck(t, br1, mqttConnAckRCConnectionAccepted, false)
7975 testMQTTSub(t, 1, bc1, br1, []*mqttFilter{{filter: "foo", qos: 0}}, []byte{0})
7976 testMQTTFlush(t, bc1, nil, br1)
7977
7978 bc2, br2 := testMQTTConnect(t, &mqttConnInfo{user: "b", pass: "pwd", clientID: "b2", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7979 defer bc2.Close()
7980 testMQTTCheckConnAck(t, br2, mqttConnAckRCConnectionAccepted, false)
7981 testMQTTSub(t, 1, bc2, br2, []*mqttFilter{{filter: "b", qos: 1}}, []byte{1})
7982 testMQTTFlush(t, bc2, nil, br2)
7983
7984 bc3, br3 := testMQTTConnect(t, &mqttConnInfo{user: "b", pass: "pwd", clientID: "b3", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7985 defer bc3.Close()
7986 testMQTTCheckConnAck(t, br3, mqttConnAckRCConnectionAccepted, false)
7987 testMQTTSub(t, 1, bc3, br3, []*mqttFilter{{filter: "bar", qos: 0}}, []byte{0})
7988 testMQTTFlush(t, bc3, nil, br3)
7989
7990 bc4, br4 := testMQTTConnect(t, &mqttConnInfo{user: "b", pass: "pwd", clientID: "b4", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
7991 defer bc4.Close()
7992 testMQTTCheckConnAck(t, br4, mqttConnAckRCConnectionAccepted, false)
7993 testMQTTSub(t, 1, bc4, br4, []*mqttFilter{{filter: "bar", qos: 1}}, []byte{1})
7994 testMQTTFlush(t, bc4, nil, br4)
7995
7996 nc := natsConnect(t, fmt.Sprintf("nats://b:pwd@%s:%d", o.Host, o.Port))
7997 defer nc.Close()
7998
7999 natsPub(t, nc, "foo", []byte("msg0"))
8000 testMQTTCheckPubMsgNoAck(t, c1, r1, "foo", 0, []byte("msg0"))
8001 testMQTTCheckPubMsgNoAck(t, c2, r2, "foo", 0, []byte("msg0"))
8002 testMQTTExpectNothing(t, r3)
8003 testMQTTExpectNothing(t, r4)
8004 testMQTTExpectNothing(t, br1)
8005 testMQTTExpectNothing(t, br2)
8006 testMQTTCheckPubMsgNoAck(t, bc3, br3, "bar", 0, []byte("msg0"))
8007 testMQTTCheckPubMsgNoAck(t, bc4, br4, "bar", 0, []byte("msg0"))
8008
8009 testMQTTPublish(t, bc, br, 0, false, false, "foo", 0, []byte("msg1"))
8010 testMQTTCheckPubMsgNoAck(t, c1, r1, "foo", 0, []byte("msg1"))
8011 testMQTTCheckPubMsgNoAck(t, c2, r2, "foo", 0, []byte("msg1"))
8012 testMQTTExpectNothing(t, r3)
8013 testMQTTExpectNothing(t, r4)
8014 testMQTTExpectNothing(t, br1)
8015 testMQTTExpectNothing(t, br2)
8016 testMQTTCheckPubMsgNoAck(t, bc3, br3, "bar", 0, []byte("msg1"))
8017 testMQTTCheckPubMsgNoAck(t, bc4, br4, "bar", 0, []byte("msg1"))
8018
8019 testMQTTPublish(t, bc, br, 1, false, false, "foo", 1, []byte("msg2"))
8020 testMQTTCheckPubMsgNoAck(t, c1, r1, "foo", 0, []byte("msg2"))
8021 testMQTTCheckPubMsgNoAck(t, c2, r2, "foo", mqttPubQos1, []byte("msg2"))
8022 testMQTTExpectNothing(t, r3)
8023 testMQTTExpectNothing(t, r4)
8024 testMQTTExpectNothing(t, br1)
8025 testMQTTExpectNothing(t, br2)
8026 testMQTTCheckPubMsgNoAck(t, bc3, br3, "bar", 0, []byte("msg2"))
8027 testMQTTCheckPubMsgNoAck(t, bc4, br4, "bar", mqttPubQos1, []byte("msg2"))
8028
8029 // Connection nc is for account B
8030 check := func(nc *nats.Conn, subj string) {
8031 t.Helper()
8032 req, err := json.Marshal(&JSApiStreamInfoRequest{SubjectsFilter: ">"})
8033 require_NoError(t, err)
8034 resp, err := nc.Request(fmt.Sprintf(JSApiStreamInfoT, "$MQTT_msgs"), req, time.Second)
8035 require_NoError(t, err)
8036 var si StreamInfo
8037 err = json.Unmarshal(resp.Data, &si)
8038 require_NoError(t, err)
8039 require_True(t, si.State.Msgs == 1)
8040 require_True(t, si.State.NumSubjects == 1)
8041 require_True(t, si.State.Subjects[subj] == 1)
8042 }
8043 // Currently, nc is for account B
8044 check(nc, "$MQTT.msgs.bar")
8045
8046 nc.Close()
8047 nc = natsConnect(t, fmt.Sprintf("nats://a:pwd@%s:%d", o.Host, o.Port))
8048 defer nc.Close()
8049 check(nc, "$MQTT.msgs.foo")
8050 }
8051
8052 func TestMQTTSubRetainedRace(t *testing.T) {
8053 o := testMQTTDefaultOptions()
8054
8055 useCases := []struct {
8056 name string
8057 f func(t *testing.T, s *Server, o *Options, subTopic, pubTopic string, QOS byte)
8058 }{
8059 {"new top level", testMQTTNewSubRetainedRace},
8060 {"existing top level", testMQTTNewSubWithExistingTopLevelRetainedRace},
8061 }
8062 pubTopic := "/bar"
8063 subTopics := []string{"#", "/bar", "/+", "/#"}
8064 QOS := []byte{0, 1, 2}
8065 for _, tc := range useCases {
8066 t.Run(tc.name, func(t *testing.T) {
8067 for _, subTopic := range subTopics {
8068 t.Run(subTopic, func(t *testing.T) {
8069 for _, qos := range QOS {
8070 t.Run(fmt.Sprintf("QOS%d", qos), func(t *testing.T) {
8071 s := testMQTTRunServer(t, o)
8072 defer testMQTTShutdownServer(s)
8073
8074 tc.f(t, s, o, subTopic, pubTopic, qos)
8075 })
8076 }
8077 })
8078 }
8079 })
8080 }
8081 }
8082
8083 func testMQTTNewSubRetainedRace(t *testing.T, s *Server, o *Options, subTopic, pubTopic string, QOS byte) {
8084 expectedFlags := (QOS << 1) | mqttPubFlagRetain
8085 payload := []byte("testmsg")
8086
8087 pubID := nuid.Next()
8088 pubc, pubr := testMQTTConnectRetry(t, &mqttConnInfo{clientID: pubID, cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 3)
8089 testMQTTCheckConnAck(t, pubr, mqttConnAckRCConnectionAccepted, false)
8090 defer testMQTTDisconnectEx(t, pubc, nil, true)
8091 defer pubc.Close()
8092 testMQTTPublish(t, pubc, pubr, QOS, false, true, pubTopic, 1, payload)
8093
8094 // Wait for retained messages stream to be populated.
8095 checkFor(t, time.Second, 10*time.Millisecond, func() error {
8096 acc, err := s.lookupAccount(globalAccountName)
8097 if err != nil {
8098 return err
8099 }
8100 mset, err := acc.lookupStream(mqttRetainedMsgsStreamName)
8101 if err != nil {
8102 return err
8103 }
8104 if mset.state().Msgs != 1 {
8105 return errors.New("retained message not populated yet")
8106 }
8107 return nil
8108 })
8109
8110 subID := nuid.Next()
8111 subc, subr := testMQTTConnect(t, &mqttConnInfo{clientID: subID, cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8112 testMQTTCheckConnAck(t, subr, mqttConnAckRCConnectionAccepted, false)
8113 testMQTTSub(t, 1, subc, subr, []*mqttFilter{{filter: subTopic, qos: QOS}}, []byte{QOS})
8114
8115 testMQTTCheckPubMsg(t, subc, subr, pubTopic, expectedFlags, payload)
8116 if QOS == 2 {
8117 testMQTTCheckPubAck(t, subr, mqttPacketPubRel)
8118 testMQTTSendPIPacket(mqttPacketPubComp, t, subc, 1)
8119 }
8120
8121 testMQTTDisconnectEx(t, subc, nil, true)
8122 subc.Close()
8123 }
8124
8125 func testMQTTNewSubWithExistingTopLevelRetainedRace(t *testing.T, s *Server, o *Options, subTopic, pubTopic string, QOS byte) {
8126 expectedFlags := (QOS << 1) | mqttPubFlagRetain
8127 payload := []byte("testmsg")
8128
8129 pubID := nuid.Next()
8130 pubc, pubr := testMQTTConnectRetry(t, &mqttConnInfo{clientID: pubID, cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 3)
8131 testMQTTCheckConnAck(t, pubr, mqttConnAckRCConnectionAccepted, false)
8132 defer testMQTTDisconnectEx(t, pubc, nil, true)
8133 defer pubc.Close()
8134
8135 subID := nuid.Next()
8136 subc, subr := testMQTTConnect(t, &mqttConnInfo{clientID: subID, cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8137 testMQTTCheckConnAck(t, subr, mqttConnAckRCConnectionAccepted, false)
8138
8139 // Subscribe to `#` first.
8140 testMQTTSub(t, 1, subc, subr, []*mqttFilter{{filter: `#`, qos: 0}}, []byte{0})
8141 testMQTTExpectNothing(t, subr)
8142
8143 // Publish the retained message with QOS2, see that the `#` subscriber gets it.
8144 testMQTTPublish(t, pubc, pubr, 2, false, true, pubTopic, 1, payload)
8145 testMQTTCheckPubMsg(t, subc, subr, pubTopic, 0, payload)
8146 testMQTTExpectNothing(t, subr)
8147
8148 // Wait for retained messages stream to be populated.
8149 checkFor(t, time.Second, 10*time.Millisecond, func() error {
8150 acc, err := s.lookupAccount(globalAccountName)
8151 if err != nil {
8152 return err
8153 }
8154 mset, err := acc.lookupStream(mqttRetainedMsgsStreamName)
8155 if err != nil {
8156 return err
8157 }
8158 if mset.state().Msgs != 1 {
8159 return errors.New("retained message not populated yet")
8160 }
8161 return nil
8162 })
8163
8164 // Now subscribe to the topic we want to test. We should get the retained
8165 // message there.
8166 testMQTTSub(t, 1, subc, subr, []*mqttFilter{{filter: subTopic, qos: QOS}}, []byte{QOS})
8167 testMQTTCheckPubMsg(t, subc, subr, pubTopic, expectedFlags, payload)
8168 if QOS == 2 {
8169 testMQTTCheckPubAck(t, subr, mqttPacketPubRel)
8170 testMQTTSendPIPacket(mqttPacketPubComp, t, subc, 1)
8171 }
8172
8173 testMQTTDisconnectEx(t, subc, nil, true)
8174 subc.Close()
8175 }
8176
8177 // Issue https://github.com/nats-io/nats-server/issues/3924
8178 // The MQTT Server MUST NOT match Topic Filters starting with a wildcard character (# or +),
8179 // with Topic Names beginning with a $ character [MQTT-4.7.2-1]
8180 func TestMQTTSubjectWildcardStart(t *testing.T) {
8181 conf := createConfFile(t, []byte(fmt.Sprintf(`
8182 listen: 127.0.0.1:-1
8183 server_name: mqtt
8184 jetstream {
8185 store_dir = %q
8186 }
8187 mqtt {
8188 listen: 127.0.0.1:-1
8189 }
8190 `, t.TempDir())))
8191 s, o := RunServerWithConfig(conf)
8192 defer testMQTTShutdownServer(s)
8193
8194 nc := natsConnect(t, s.ClientURL())
8195 defer nc.Close()
8196
8197 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8198 defer mc.Close()
8199 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8200
8201 mc1, r1 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8202 defer mc1.Close()
8203 testMQTTCheckConnAck(t, r1, mqttConnAckRCConnectionAccepted, false)
8204
8205 mc2, r2 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8206 defer mc2.Close()
8207 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, false)
8208
8209 mc3, r3 := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8210 defer mc3.Close()
8211 testMQTTCheckConnAck(t, r3, mqttConnAckRCConnectionAccepted, false)
8212
8213 // These will fail already with the bug due to messages already being queue up before the subAck.
8214 testMQTTSub(t, 1, mc1, r1, []*mqttFilter{{filter: "*", qos: 0}}, []byte{0})
8215 testMQTTFlush(t, mc1, nil, r1)
8216
8217 testMQTTSub(t, 1, mc2, r2, []*mqttFilter{{filter: "#", qos: 1}}, []byte{1})
8218 testMQTTFlush(t, mc2, nil, r2)
8219
8220 testMQTTSub(t, 1, mc3, r3, []*mqttFilter{{filter: "*/foo", qos: 1}}, []byte{1})
8221 testMQTTFlush(t, mc2, nil, r2)
8222
8223 // Just as a barrier
8224 natsFlush(t, nc)
8225
8226 // Now publish
8227
8228 // NATS Publish
8229 msg := []byte("HELLO WORLD")
8230 natsPub(t, nc, "foo", msg)
8231
8232 // Check messages received
8233 testMQTTCheckPubMsg(t, mc1, r1, "foo", 0, msg)
8234 testMQTTExpectNothing(t, r1)
8235
8236 testMQTTCheckPubMsg(t, mc2, r2, "foo", 0, msg)
8237 testMQTTExpectNothing(t, r2)
8238
8239 testMQTTExpectNothing(t, r3)
8240
8241 // Anything that starts with $ is reserved against wildcard subjects like above.
8242 natsPub(t, nc, "$JS.foo", msg)
8243 testMQTTExpectNothing(t, r1)
8244 testMQTTExpectNothing(t, r2)
8245 testMQTTExpectNothing(t, r3)
8246
8247 // Now do MQTT QoS-0
8248 testMQTTPublish(t, mc, r, 0, false, false, "foo", 0, msg)
8249
8250 testMQTTCheckPubMsg(t, mc1, r1, "foo", 0, msg)
8251 testMQTTExpectNothing(t, r1)
8252
8253 testMQTTCheckPubMsg(t, mc2, r2, "foo", 0, msg)
8254 testMQTTExpectNothing(t, r2)
8255
8256 testMQTTExpectNothing(t, r3)
8257
8258 testMQTTPublish(t, mc, r, 0, false, false, "$JS/foo", 1, msg)
8259
8260 testMQTTExpectNothing(t, r1)
8261 testMQTTExpectNothing(t, r2)
8262 testMQTTExpectNothing(t, r3)
8263
8264 // Now do MQTT QoS-1
8265 msg = []byte("HELLO WORLD - RETAINED")
8266 testMQTTPublish(t, mc, r, 1, false, false, "$JS/foo", 4, msg)
8267
8268 testMQTTExpectNothing(t, r1)
8269 testMQTTExpectNothing(t, r2)
8270 testMQTTExpectNothing(t, r3)
8271
8272 testMQTTPublish(t, mc, r, 1, false, false, "foo", 2, msg)
8273
8274 testMQTTCheckPubMsg(t, mc1, r1, "foo", 0, msg)
8275 testMQTTExpectNothing(t, r1)
8276
8277 testMQTTCheckPubMsg(t, mc2, r2, "foo", 2, msg)
8278 testMQTTExpectNothing(t, r2)
8279
8280 testMQTTExpectNothing(t, r3)
8281
8282 testMQTTPublish(t, mc, r, 1, false, false, "foo/foo", 3, msg)
8283
8284 testMQTTExpectNothing(t, r1)
8285
8286 testMQTTCheckPubMsg(t, mc2, r2, "foo/foo", 2, msg)
8287 testMQTTExpectNothing(t, r2)
8288
8289 testMQTTCheckPubMsg(t, mc3, r3, "foo/foo", 2, msg)
8290 testMQTTExpectNothing(t, r3)
8291
8292 // Make sure we did not retain the messages prefixed with $.
8293 nc, js := jsClientConnect(t, s)
8294 defer nc.Close()
8295
8296 si, err := js.StreamInfo(mqttStreamName)
8297 require_NoError(t, err)
8298
8299 require_True(t, si.State.Msgs == 0)
8300 }
8301
8302 func TestMQTTTopicWithDot(t *testing.T) {
8303 o := testMQTTDefaultOptions()
8304 s := testMQTTRunServer(t, o)
8305 defer testMQTTShutdownServer(s)
8306
8307 nc := natsConnect(t, s.ClientURL(), nats.UserInfo("mqtt", "pwd"))
8308 defer nc.Close()
8309
8310 sub := natsSubSync(t, nc, "*.*")
8311
8312 c1, r1 := testMQTTConnect(t, &mqttConnInfo{user: "mqtt", pass: "pwd", clientID: "conn1", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8313 defer c1.Close()
8314 testMQTTCheckConnAck(t, r1, mqttConnAckRCConnectionAccepted, false)
8315 testMQTTSub(t, 1, c1, r1, []*mqttFilter{{filter: "spBv1.0/plant1", qos: 0}}, []byte{0})
8316 testMQTTSub(t, 1, c1, r1, []*mqttFilter{{filter: "spBv1.0/plant2", qos: 1}}, []byte{1})
8317
8318 c2, r2 := testMQTTConnect(t, &mqttConnInfo{user: "mqtt", pass: "pwd", clientID: "conn2", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8319 defer c2.Close()
8320 testMQTTCheckConnAck(t, r2, mqttConnAckRCConnectionAccepted, false)
8321
8322 testMQTTPublish(t, c2, r2, 0, false, false, "spBv1.0/plant1", 0, []byte("msg1"))
8323 testMQTTCheckPubMsg(t, c1, r1, "spBv1.0/plant1", 0, []byte("msg1"))
8324 msg := natsNexMsg(t, sub, time.Second)
8325 require_Equal(t, msg.Subject, "spBv1//0.plant1")
8326
8327 testMQTTPublish(t, c2, r2, 1, false, false, "spBv1.0/plant2", 1, []byte("msg2"))
8328 testMQTTCheckPubMsg(t, c1, r1, "spBv1.0/plant2", mqttPubQos1, []byte("msg2"))
8329 msg = natsNexMsg(t, sub, time.Second)
8330 require_Equal(t, msg.Subject, "spBv1//0.plant2")
8331
8332 natsPub(t, nc, "spBv1//0.plant1", []byte("msg3"))
8333 testMQTTCheckPubMsg(t, c1, r1, "spBv1.0/plant1", 0, []byte("msg3"))
8334 msg = natsNexMsg(t, sub, time.Second)
8335 require_Equal(t, msg.Subject, "spBv1//0.plant1")
8336
8337 natsPub(t, nc, "spBv1//0.plant2", []byte("msg4"))
8338 testMQTTCheckPubMsg(t, c1, r1, "spBv1.0/plant2", 0, []byte("msg4"))
8339 msg = natsNexMsg(t, sub, time.Second)
8340 require_Equal(t, msg.Subject, "spBv1//0.plant2")
8341 }
8342
8343 // Issue https://github.com/nats-io/nats-server/issues/4291
8344 func TestMQTTJetStreamRepublishAndQoS0Subscribers(t *testing.T) {
8345 conf := createConfFile(t, []byte(fmt.Sprintf(`
8346 listen: 127.0.0.1:-1
8347 server_name: mqtt
8348 jetstream {
8349 store_dir = %q
8350 }
8351 mqtt {
8352 listen: 127.0.0.1:-1
8353 }
8354 `, t.TempDir())))
8355 s, o := RunServerWithConfig(conf)
8356 defer testMQTTShutdownServer(s)
8357
8358 nc, js := jsClientConnect(t, s)
8359 defer nc.Close()
8360
8361 // Setup stream with republish on it.
8362 _, err := js.AddStream(&nats.StreamConfig{
8363 Name: "TEST",
8364 Subjects: []string{"foo"},
8365 RePublish: &nats.RePublish{
8366 Source: "foo",
8367 Destination: "mqtt.foo",
8368 },
8369 })
8370 require_NoError(t, err)
8371
8372 // Create QoS0 subscriber to catch re-publishes.
8373 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8374 defer mc.Close()
8375 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8376
8377 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "mqtt/foo", qos: 0}}, []byte{0})
8378 testMQTTFlush(t, mc, nil, r)
8379
8380 msg := []byte("HELLO WORLD")
8381 _, err = js.Publish("foo", msg)
8382 require_NoError(t, err)
8383
8384 testMQTTCheckPubMsg(t, mc, r, "mqtt/foo", 0, msg)
8385 testMQTTExpectNothing(t, r)
8386 }
8387
8388 func TestMQTTDecodeRetainedMessage(t *testing.T) {
8389 tdir := t.TempDir()
8390 tmpl := `
8391 listen: 127.0.0.1:-1
8392 server_name: mqtt
8393 jetstream {
8394 store_dir = %q
8395 }
8396
8397 mqtt {
8398 listen: 127.0.0.1:-1
8399 consumer_inactive_threshold: %q
8400 }
8401
8402 # For access to system account.
8403 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } }
8404 `
8405 conf := createConfFile(t, []byte(fmt.Sprintf(tmpl, tdir, "0.2s")))
8406 s, o := RunServerWithConfig(conf)
8407 defer testMQTTShutdownServer(s)
8408
8409 // Connect and publish a retained message, this will be in the "newer" form,
8410 // with the metadata in the header.
8411 mc, r := testMQTTConnectRetry(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 5)
8412 defer mc.Close()
8413 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8414 testMQTTPublish(t, mc, r, 0, false, true, "foo/1", 0, []byte("msg1"))
8415 mc.Close()
8416
8417 // Store a "legacy", JSON-encoded payload directly into the stream.
8418 nc, js := jsClientConnect(t, s)
8419 defer nc.Close()
8420
8421 rm := mqttRetainedMsg{
8422 Origin: "test",
8423 Subject: "foo.2",
8424 Topic: "foo/2",
8425 Flags: mqttPubFlagRetain,
8426 Msg: []byte("msg2"),
8427 }
8428 jsonData, _ := json.Marshal(rm)
8429 _, err := js.PublishMsg(&nats.Msg{
8430 Subject: mqttRetainedMsgsStreamSubject + rm.Subject,
8431 Data: jsonData,
8432 })
8433 if err != nil {
8434 t.Fatalf("Error publishing retained message to JS directly: %v", err)
8435 }
8436
8437 // Restart the server to see that it picks up both retained messages on restart.
8438 s.Shutdown()
8439 s = RunServer(o)
8440 defer testMQTTShutdownServer(s)
8441
8442 // Connect again, subscribe, and check that we get both messages.
8443 mc, r = testMQTTConnectRetry(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 5)
8444 defer mc.Close()
8445 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8446 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo/+", qos: 0}}, []byte{0})
8447 for i := 0; i < 2; i++ {
8448 b, pl := testMQTTReadPacket(t, r)
8449 if pt := b & mqttPacketMask; pt != mqttPacketPub {
8450 t.Fatalf("Expected PUBLISH packet %x, got %x", mqttPacketPub, pt)
8451 }
8452 _, _, topic, _ := testMQTTGetPubMsgExEx(t, mc, r, mqttPubFlagRetain, pl, "", nil)
8453 if string(topic) != "foo/1" && string(topic) != "foo/2" {
8454 t.Fatalf("Expected foo/1 or foo/2, got %q", topic)
8455 }
8456 }
8457 testMQTTExpectNothing(t, r)
8458 mc.Close()
8459
8460 // Clear both retained messages.
8461 mc, r = testMQTTConnectRetry(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 5)
8462 defer mc.Close()
8463 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8464 testMQTTPublish(t, mc, r, 0, false, true, "foo/1", 0, []byte{})
8465 testMQTTPublish(t, mc, r, 0, false, true, "foo/2", 0, []byte{})
8466 testMQTTFlush(t, mc, nil, r)
8467 testMQTTDisconnect(t, mc, nil)
8468 mc.Close()
8469
8470 // Connect again, subscribe, and check that we get nothing.
8471 mc, r = testMQTTConnectRetry(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 5)
8472 defer mc.Close()
8473 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8474 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo/+", qos: 0}}, []byte{0})
8475 testMQTTExpectNothing(t, r)
8476 }
8477
8478 func TestMQTTSparkbDeathHandling(t *testing.T) {
8479 o := testMQTTDefaultOptions()
8480 s := testMQTTRunServer(t, o)
8481 defer testMQTTShutdownServer(s)
8482
8483 // protoMetrics is protobuf-encoded test data, with no timestamp.
8484 //
8485 // p := &sproto.Payload{
8486 // Metrics: []*sproto.Payload_Metric{
8487 // newSparkbMetric_Uint64(sparkbBDSeqMetric, uint64(sparkbBDSeq)),
8488 // newSparkbMetric(sparkbDeviceMetric1, "value-at-death-1"),
8489 // newSparkbMetric(sparkbDeviceMetric2, "value-at-death-2"),
8490 // },
8491 // Timestamp: nil,
8492 // }
8493 protoMetrics := []byte{0x12, 0x0b, 0x0a, 0x05, 0x62, 0x64, 0x53, 0x65, 0x71, 0x20, 0x04, 0x58, 0x02, 0x12, 0x24, 0x0a, 0x0e, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x2d, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x31, 0x20, 0x0c, 0x7a, 0x10, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x2d, 0x61, 0x74, 0x2d, 0x64, 0x65, 0x61, 0x74, 0x68, 0x2d, 0x31, 0x12, 0x24, 0x0a, 0x0e, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x2d, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x32, 0x20, 0x0c, 0x7a, 0x10, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x2d, 0x61, 0x74, 0x2d, 0x64, 0x65, 0x61, 0x74, 0x68, 0x2d, 0x32}
8494
8495 proto0Timestamp := []byte{0x08, 0x00}
8496
8497 protoDeadbeefTimestamp := []byte{0x08, 0xef, 0xfd, 0xb6, 0xf5, 0xfd, 0xde, 0xef, 0xd6, 0xde, 0x01}
8498
8499 mcPub, rPub := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8500 defer mcPub.Close()
8501 testMQTTCheckConnAck(t, rPub, mqttConnAckRCConnectionAccepted, false)
8502
8503 mcSub, rSub := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8504 defer mcSub.Close()
8505 testMQTTCheckConnAck(t, rSub, mqttConnAckRCConnectionAccepted, false)
8506 testMQTTSub(t, 1, mcSub, rSub, []*mqttFilter{{filter: "spBv1.0/ggg/#", qos: 0}}, []byte{0})
8507
8508 for _, test := range []*struct {
8509 name string
8510 payload []byte
8511 expectTimestampOffset int
8512 expectUnchanged bool
8513 }{
8514 {"append", protoMetrics, len(protoMetrics), false},
8515 {"replace at the end", append(protoMetrics, proto0Timestamp...), len(protoMetrics), false},
8516 {"replace at the start", append(protoDeadbeefTimestamp, protoMetrics...), 0, false},
8517 {"invalid", []byte{0xde, 0xad, 0xbe, 0xef}, 0, true}, // invalid payload
8518 {"invalid fixed32", []byte{0x0d, 0x01}, 0, true},
8519 {"invalid fixed64", []byte{0x09, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}, 0, true},
8520 } {
8521 var sendPI uint16
8522 for _, topic := range []string{"NDEATH/nnn", "DDEATH/nnn/ddd"} {
8523 sendPI++
8524 t.Run(test.name+" "+topic, func(t *testing.T) {
8525 testMQTTPublish(t, mcPub, rPub, 1, false, false, "spBv1.0/ggg/"+topic, sendPI, test.payload)
8526
8527 flags, pi, _, received := testMQTTGetPubMsgEx(t, mcSub, rSub, "", nil)
8528 if mqttGetQoS(flags) == 1 {
8529 testMQTTSendPIPacket(mqttPacketPubAck, t, mcSub, pi)
8530 }
8531
8532 if test.expectUnchanged {
8533 if !bytes.Equal(test.payload, received) {
8534 t.Fatalf("Expected payload to be unchanged, got %q", received)
8535 }
8536 return
8537 }
8538
8539 if test.expectTimestampOffset > len(received) {
8540 t.Fatalf("Expected timestamp offset %v to be less than %v", test.expectTimestampOffset, len(received))
8541 }
8542 if test.expectTimestampOffset > 0 {
8543 if !bytes.Equal(protoMetrics, received[:test.expectTimestampOffset]) {
8544 t.Fatalf("Expected payload to be unchanged up to %v, got %q", test.expectTimestampOffset, received)
8545 }
8546 }
8547
8548 tsBytes := received[test.expectTimestampOffset:]
8549 if tsBytes[0] != 0x08 {
8550 t.Fatalf("Expected timestamp to start with 0x08, got %x", tsBytes)
8551 }
8552 v, _, err := protoScanVarint(tsBytes[1:])
8553 if err != nil {
8554 t.Fatalf("Error scanning varint: %v", err)
8555 }
8556
8557 ts := time.UnixMilli(int64(v))
8558 if time.Now().Before(ts) {
8559 t.Fatalf("Expected timestamp to be in the past, got %v", ts)
8560 }
8561 if time.Since(ts) > time.Second {
8562 t.Fatalf("Expected timestamp to be within a second, got %v", time.Since(ts))
8563 }
8564 })
8565 }
8566 }
8567 }
8568
8569 func TestMQTTSparkbBirthHandling(t *testing.T) {
8570 o := testMQTTDefaultOptions()
8571 s := testMQTTRunServer(t, o)
8572 defer testMQTTShutdownServer(s)
8573
8574 // Publish an NBIRTH message. Make sure it is received as both the original
8575 // subject, and as a $sparkplug/certificates one.
8576
8577 const NBORN = "NODE BORN FAKE MESSAGE"
8578 const DBORN = "DEVICE BORN FAKE MESSAGE"
8579
8580 tests := []*struct {
8581 topic string
8582 payload string
8583 flags byte
8584 mc net.Conn
8585 r *mqttReader
8586 }{
8587 {
8588 topic: "spBv1.0/ggg/NBIRTH/nnn",
8589 payload: NBORN,
8590 flags: 0,
8591 },
8592 {
8593 topic: "spBv1.0/ggg/DBIRTH/nnn/ddd",
8594 payload: DBORN,
8595 flags: 0,
8596 },
8597 {
8598 topic: "$sparkplug/certificates/spBv1.0/ggg/NBIRTH/nnn",
8599 payload: NBORN,
8600 flags: mqttPubFlagRetain,
8601 },
8602 {
8603 topic: "$sparkplug/certificates/spBv1.0/ggg/DBIRTH/nnn/ddd",
8604 payload: DBORN,
8605 flags: mqttPubFlagRetain,
8606 },
8607 }
8608
8609 t.Run("$sparkplug messages delivered", func(t *testing.T) {
8610 // Connect the subscribers, unique for each topic we monitor.
8611 for i, test := range tests {
8612 test.mc, test.r = testMQTTConnect(t, &mqttConnInfo{cleanSess: true, clientID: fmt.Sprintf("sub-%v", i)}, o.MQTT.Host, o.MQTT.Port)
8613 defer test.mc.Close()
8614 testMQTTCheckConnAck(t, test.r, mqttConnAckRCConnectionAccepted, false)
8615
8616 // Subscribne at QoS2 to make sure the messages are posted at QoS0 and
8617 // not truncated to sub QoS.
8618 testMQTTSub(t, 1, test.mc, test.r, []*mqttFilter{{filter: test.topic, qos: 2}}, []byte{2})
8619 }
8620
8621 // connect the publisher
8622 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true, clientID: "pub"}, o.MQTT.Host, o.MQTT.Port)
8623 defer mc.Close()
8624 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8625
8626 // {Publish} [ND]BIRTH messages. Note that IRL these are protobuf payloads.
8627 testMQTTPublish(t, mc, r, 0, false, false, "spBv1.0/ggg/NBIRTH/nnn", 0, []byte("NODE BORN FAKE MESSAGE"))
8628 testMQTTPublish(t, mc, r, 0, false, false, "spBv1.0/ggg/DBIRTH/nnn/ddd", 0, []byte("DEVICE BORN FAKE MESSAGE"))
8629
8630 // Check that the subscribers got the messages.
8631 for _, test := range tests {
8632 testMQTTCheckPubMsg(t, test.mc, test.r, test.topic, test.flags, []byte(test.payload))
8633 }
8634 })
8635
8636 t.Run("$sparkplug messages retained", func(t *testing.T) {
8637 // Connect/subscribe again, and make sure that only retained messages are there.
8638 for i, test := range tests {
8639 mc, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true, clientID: fmt.Sprintf("sub-%v", i+100)}, o.MQTT.Host, o.MQTT.Port)
8640 defer mc.Close()
8641 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8642 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: test.topic, qos: 2}}, []byte{2})
8643 if test.flags&mqttPubFlagRetain != 0 {
8644 testMQTTCheckPubMsg(t, mc, r, test.topic, test.flags, []byte(test.payload))
8645 } else {
8646 testMQTTExpectNothing(t, r)
8647 }
8648 }
8649 })
8650 }
8651
8652 func TestMQTTMaxPayloadEnforced(t *testing.T) {
8653 conf := createConfFile(t, []byte(`
8654 server_name: test_mqtt_max_payload
8655 port: -1
8656 max_payload: 1024
8657 mqtt { listen: "127.0.0.1:-1" }
8658 jetstream: { domain: "TEST", max_mem_store: 8MB, max_file_store: 8MB, store_dir: "`+t.TempDir()+`" }
8659 `))
8660 s, o := RunServerWithConfig(conf)
8661 defer s.Shutdown()
8662
8663 mp := o.MQTT.Port
8664 host := o.MQTT.Host
8665 mc, _ := testMQTTConnect(t, &mqttConnInfo{clientID: "cid", cleanSess: true}, host, mp)
8666 defer mc.Close()
8667
8668 oversized := bytes.Repeat([]byte{'A'}, 1500)
8669 testMQTTSendPublishPacket(t, mc, 0, false, false, "foo", 0, oversized)
8670
8671 testMQTTExpectDisconnect(t, mc)
8672 }
8673
8674 func TestMQTTMaxPayloadDoesNotCapPublishTopic(t *testing.T) {
8675 conf := createConfFile(t, []byte(`
8676 server_name: test_mqtt_max_payload_topic
8677 port: -1
8678 max_payload: 1024
8679 mqtt { listen: "127.0.0.1:-1" }
8680 jetstream: { domain: "TEST", max_mem_store: 8MB, max_file_store: 8MB, store_dir: "`+t.TempDir()+`" }
8681 `))
8682 s, o := RunServerWithConfig(conf)
8683 defer s.Shutdown()
8684
8685 mc, r := testMQTTConnect(t, &mqttConnInfo{clientID: "cid", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
8686 defer mc.Close()
8687 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8688
8689 testMQTTSendPublishPacket(t, mc, 0, false, false, strings.Repeat("a", 1100), 0, nil)
8690 testMQTTFlush(t, mc, nil, r)
8691 }
8692
8693 func TestMQTTJSApiMapping(t *testing.T) {
8694 td := t.TempDir()
8695 hubDir := filepath.Join(td, "hub")
8696 hubConf := createConfFile(t, fmt.Appendf(nil, `
8697 server_name: hub
8698 listen: "127.0.0.1:-1"
8699 jetstream {
8700 domain: "HUB"
8701 store_dir: "%s"
8702 }
8703 mqtt {
8704 listen: "127.0.0.1:-1"
8705 }
8706 leafnodes {
8707 listen: "127.0.0.1:-1"
8708 isolate: true
8709 }
8710 accounts: {
8711 SYS: { users: [ { user:s, password:x } ] }
8712 HUB: {
8713 jetstream: true
8714 users: [
8715 {
8716 user:h
8717 password:x
8718 permissions: {
8719 subscribe: {allow: ["foo", "bar", "_INBOX.>"], deny: ["baz"] }
8720 }
8721 }
8722 ]
8723 }
8724 }
8725 system_account: SYS
8726 `, hubDir))
8727 hub, ohub := RunServerWithConfig(hubConf)
8728 defer hub.Shutdown()
8729
8730 leafDir := filepath.Join(td, "leaf")
8731 leafTmpl := `
8732 server_name: leaf
8733 listen: "127.0.0.1:-1"
8734 jetstream {
8735 domain: "LEAF"
8736 store_dir: "%s"
8737 }
8738 mqtt {
8739 listen: "127.0.0.1:-1"
8740 js_api_timeout: "500ms"
8741 }
8742 leafnodes {
8743 remotes [
8744 { urls: [ nats-leaf://s:[email protected]:%d ], account: SYS }
8745 { urls: [ nats-leaf://h:[email protected]:%d ], account: HUB }
8746 ]
8747 }
8748 accounts: {
8749 SYS: { users: [ { user:s, password:x } ] }
8750 HUB: {
8751 jetstream: false
8752 users: [ { user:h, password:x } ]
8753 mappings: {
8754 "$JS.API.>" : "$JS.HUB.API.>"
8755 %s
8756 }
8757 }
8758 LEAF: {
8759 jetstream: true
8760 users: [ { user:l, password:x } ]
8761 }
8762 }
8763 system_account: SYS
8764 `
8765 leafConf := createConfFile(t, fmt.Appendf(nil, leafTmpl, leafDir, ohub.LeafNode.Port, ohub.LeafNode.Port, ""))
8766 leaf, oleaf := RunServerWithConfig(leafConf)
8767 defer leaf.Shutdown()
8768
8769 checkLeafNodeConnectedCount(t, leaf, 2)
8770
8771 testRetained := func(user string, port int, msg string) {
8772 t.Helper()
8773 // Create a producer
8774 c, r := testMQTTConnect(t, &mqttConnInfo{
8775 cleanSess: true,
8776 user: user,
8777 pass: "x",
8778 }, "127.0.0.1", port)
8779 defer c.Close()
8780 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8781 testMQTTPublish(t, c, r, 0, false, true, "foo", 0, []byte(msg))
8782 testMQTTFlush(t, c, nil, r)
8783 testMQTTDisconnect(t, c, nil)
8784 c.Close()
8785
8786 // Create a consumer
8787 c, r = testMQTTConnect(t, &mqttConnInfo{
8788 cleanSess: true,
8789 user: user,
8790 pass: "x",
8791 }, "127.0.0.1", port)
8792 defer c.Close()
8793 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8794 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 0}}, []byte{0})
8795 testMQTTCheckPubMsg(t, c, r, "foo", mqttPubFlagRetain, []byte(msg))
8796 }
8797
8798 // Connect to leaf
8799 testRetained("l", oleaf.MQTT.Port, "hi leaf")
8800
8801 // Now same test in the hub
8802 testRetained("h", ohub.MQTT.Port, "hi hub")
8803
8804 // Now test the hub account in the leaf node. We expect it to fail
8805 // because we don't have the mapping for the sessions to be persisted
8806 // in the hub.
8807 _, _, err := testMQTTConnectRetryWithError(t, &mqttConnInfo{
8808 cleanSess: true,
8809 user: "h",
8810 pass: "x",
8811 }, oleaf.MQTT.Host, oleaf.MQTT.Port, 0)
8812 if err == nil {
8813 t.Fatal("Expected failure to connect, but did connect")
8814 }
8815
8816 // Config reload the leaf server to add the missing mapping.
8817 reloadUpdateConfig(t, leaf, leafConf, fmt.Sprintf(leafTmpl,
8818 leafDir, ohub.LeafNode.Port, ohub.LeafNode.Port, `"$MQTT.sess.LEAF.>" : "$MQTT.sess.HUB.>"`))
8819
8820 c, r := testMQTTConnect(t, &mqttConnInfo{
8821 cleanSess: true,
8822 user: "h",
8823 pass: "x",
8824 }, "127.0.0.1", oleaf.MQTT.Port)
8825 defer c.Close()
8826 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8827 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 0}}, []byte{0})
8828 testMQTTCheckPubMsg(t, c, r, "foo", mqttPubFlagRetain, []byte("hi hub"))
8829 }
8830
8831 func TestMQTTMappingsQoS0(t *testing.T) {
8832 td := t.TempDir()
8833 dir := filepath.Join(td, "js")
8834 conf := createConfFile(t, fmt.Appendf(nil, `
8835 server_name: server
8836 jetstream {
8837 domain: "A"
8838 store_dir: "%s"
8839 }
8840 mqtt {
8841 listen: "127.0.0.1:-1"
8842 }
8843 accounts: {
8844 A: {
8845 jetstream: true
8846 users: [ { user:a, password:x }]
8847 exports: [ { stream: "foo.>" }]
8848 mappings: { "baz.>" : "bazz.>" }
8849 }
8850 B: {
8851 jetstream: true
8852 users: [ { user:b, password:x }]
8853 imports: [ { stream: { account: A, subject: "foo.>" }, to: "bar.>" } ]
8854 }
8855 C: {
8856 jetstream: true
8857 users: [ { user:c, password:x }]
8858 imports: [ { stream: { account: A, subject: "foo.>" }, to: "baz.>" } ]
8859 }
8860 D: {
8861 jetstream: true
8862 users: [ { user:d, password:x }]
8863 # Same imports than for account C
8864 imports: [ { stream: { account: A, subject: "foo.>" }, to: "baz.>" } ]
8865 }
8866 }
8867 `, dir))
8868 s, o := RunServerWithConfig(conf)
8869 defer s.Shutdown()
8870
8871 // First, we check for mapping inside the same account A.
8872 aSubConn, aSubReader := testMQTTConnect(t, &mqttConnInfo{
8873 cleanSess: true,
8874 clientID: "sub",
8875 user: "a",
8876 pass: "x",
8877 }, "127.0.0.1", o.MQTT.Port)
8878 defer aSubConn.Close()
8879 testMQTTCheckConnAck(t, aSubReader, mqttConnAckRCConnectionAccepted, false)
8880 testMQTTSub(t, 1, aSubConn, aSubReader, []*mqttFilter{{filter: "#", qos: 0}}, []byte{0})
8881 testMQTTFlush(t, aSubConn, nil, aSubReader)
8882
8883 aPubConn, aPubReader := testMQTTConnect(t, &mqttConnInfo{
8884 cleanSess: true,
8885 clientID: "pub",
8886 user: "a",
8887 pass: "x",
8888 }, "127.0.0.1", o.MQTT.Port)
8889 defer aPubConn.Close()
8890 testMQTTCheckConnAck(t, aPubReader, mqttConnAckRCConnectionAccepted, false)
8891 testMQTTPublish(t, aPubConn, aPubReader, 0, false, true, "baz/x", 0, []byte("msg1"))
8892 // Because of mapping, the subscription should receive the message on "bazz/x"
8893 testMQTTCheckPubMsg(t, aSubConn, aSubReader, "bazz/x", 0, []byte("msg1"))
8894
8895 // Helper to create a connection and sub for a given user on given topic
8896 createSub := func(user, topic string) (net.Conn, *mqttReader) {
8897 t.Helper()
8898 c, r := testMQTTConnect(t, &mqttConnInfo{
8899 cleanSess: true,
8900 clientID: nuid.Next(),
8901 user: user,
8902 pass: "x",
8903 }, "127.0.0.1", o.MQTT.Port)
8904 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
8905 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: topic, qos: 0}}, []byte{0})
8906 testMQTTFlush(t, c, nil, r)
8907 return c, r
8908 }
8909 bConn1, bReader1 := createSub("b", "bar/#")
8910 defer bConn1.Close()
8911 bConn2, bReader2 := createSub("b", "bar/+")
8912 defer bConn2.Close()
8913 cConn1, cReader1 := createSub("c", "baz/#")
8914 defer cConn1.Close()
8915 cConn2, cReader2 := createSub("c", "baz/+")
8916 defer cConn2.Close()
8917 dConn1, dReader1 := createSub("d", "baz/#")
8918 defer dConn1.Close()
8919 dConn2, dReader2 := createSub("d", "baz/+")
8920 defer dConn2.Close()
8921
8922 // Now from "A" publisher, publishes on "foo/x", and with mapping across
8923 // accounts, we should get the expected results. We send 2 messages in
8924 // a row and verify that we get those, and no more than that.
8925 testMQTTPublish(t, aPubConn, aPubReader, 0, false, true, "foo/x", 0, []byte("msg2"))
8926 testMQTTPublish(t, aPubConn, aPubReader, 0, false, true, "foo/x", 0, []byte("msg3"))
8927
8928 // "B" consumers should receive on "bar/x"
8929 conns := []net.Conn{bConn1, bConn2}
8930 readers := []*mqttReader{bReader1, bReader2}
8931 for i := range len(conns) {
8932 testMQTTCheckPubMsg(t, conns[i], readers[i], "bar/x", 0, []byte("msg2"))
8933 testMQTTCheckPubMsg(t, conns[i], readers[i], "bar/x", 0, []byte("msg3"))
8934 testMQTTExpectNothing(t, readers[i])
8935 }
8936 // For "C" and "D" consumers, it should be "baz/x"
8937 conns = []net.Conn{cConn1, cConn2, dConn1, dConn2}
8938 readers = []*mqttReader{cReader1, cReader2, dReader1, dReader2}
8939 for i := range len(conns) {
8940 testMQTTCheckPubMsg(t, conns[i], readers[i], "baz/x", 0, []byte("msg2"))
8941 testMQTTCheckPubMsg(t, conns[i], readers[i], "baz/x", 0, []byte("msg3"))
8942 testMQTTExpectNothing(t, readers[i])
8943 }
8944 }
8945
8946 func TestMQTTSliceHeadersAndDecodeRetainedMessage(t *testing.T) {
8947 // First check low level mqttSliceHeaders
8948 for _, test := range []struct {
8949 name string
8950 hdr string
8951 expected []string
8952 }{
8953 // Valid cases
8954 {"one key and some random", hdrLine + "key1:val1\r\nsomeotherkey:someval\r\n", []string{"val1", _EMPTY_, _EMPTY_}},
8955 {"two keys", hdrLine + "key2:val2\r\nthisisnotkey1:someval\r\nkey1:val1\r\n", []string{"val1", "val2", _EMPTY_}},
8956 {"three keys", hdrLine + "key2:val2\r\nkey3:val3\r\nkey1:val1\r\n", []string{"val1", "val2", "val3"}},
8957 {"space before value", hdrLine + "somekey:someval\r\nkey2: val2withspacebefore\r\n", []string{_EMPTY_, "val2withspacebefore", _EMPTY_}},
8958 {"space between key and colon sign", hdrLine + "key1:val1\r\nkey2 :val2\r\nkey3 : val3\r\n", []string{"val1", "val2", "val3"}},
8959 // Error cases
8960 {"no hdr line", "key1:val1\r\n", []string{_EMPTY_, _EMPTY_, _EMPTY_}},
8961 {"key length 0", hdrLine + "key1:val1\r\n:val2\r\nkey3:val3\r\n", []string{"val1", _EMPTY_, _EMPTY_}},
8962 {"key is only spaces", hdrLine + "key1:val1\r\nkey2:val2\r\n :val3\r\n", []string{"val1", "val2", _EMPTY_}},
8963 {"value no crlf", hdrLine + "key1:val1\r\nkey2:val2", []string{"val1", _EMPTY_, _EMPTY_}},
8964 } {
8965 t.Run(test.name, func(t *testing.T) {
8966 headers := map[string][]byte{
8967 "key1": nil,
8968 "key2": nil,
8969 "key3": nil,
8970 }
8971 mqttSliceHeaders(headers, []byte(test.hdr))
8972 for i := range len(headers) {
8973 key := fmt.Sprintf("key%d", i+1)
8974 val := string(headers[key])
8975 if ev := test.expected[i]; ev != val {
8976 t.Fatalf("For key %q, expected value to be %q, got %q", key, ev, val)
8977 }
8978 }
8979 })
8980 }
8981
8982 // Now test mqttDecodeRetainedMessage() itself.
8983 t.Run("flag with delete marker", func(t *testing.T) {
8984 hdr := fmt.Appendf(nil, "%sNmqtt-RFlags:%c1\r\n\r\n", hdrLine, mqttRetainedFlagDelMarker)
8985 rm, err := mqttDecodeRetainedMessage("$MQTT.rmsgs.bar.x", hdr, nil)
8986 require_NoError(t, err)
8987 require_Equal(t, rm.Flags, 1)
8988 })
8989 t.Run("flag not a number", func(t *testing.T) {
8990 hdr := fmt.Appendf(nil, "%sNmqtt-RFlags:bad\r\n\r\n", hdrLine)
8991 _, err := mqttDecodeRetainedMessage("$MQTT.rmsgs.bar.x", hdr, []byte("msg"))
8992 require_Error(t, err, errMQTTInvalidRetainFlags)
8993 })
8994 t.Run("flag not a number with delete marker", func(t *testing.T) {
8995 hdr := fmt.Appendf(nil, "%sNmqtt-RFlags:%cad\r\n\r\n", hdrLine, mqttRetainedFlagDelMarker)
8996 _, err := mqttDecodeRetainedMessage("$MQTT.rmsgs.bar.x", hdr, []byte("msg"))
8997 require_Error(t, err, errMQTTInvalidRetainFlags)
8998 })
8999 t.Run("flag too big", func(t *testing.T) {
9000 hdr := fmt.Appendf(nil, "%sNmqtt-RFlags:%c15\r\n\r\n", hdrLine, mqttRetainedFlagDelMarker)
9001 _, err := mqttDecodeRetainedMessage("$MQTT.rmsgs.bar.x", hdr, []byte("msg"))
9002 require_Error(t, err, errMQTTInvalidRetainFlags)
9003 })
9004 t.Run("flag invalid qos", func(t *testing.T) {
9005 hdr := fmt.Appendf(nil, "%sNmqtt-RFlags:%c7\r\n\r\n", hdrLine, mqttRetainedFlagDelMarker)
9006 _, err := mqttDecodeRetainedMessage("$MQTT.rmsgs.bar.x", hdr, []byte("msg"))
9007 require_Error(t, err, errMQTTInvalidRetainFlags)
9008 })
9009 t.Run("decode retained msg with space before header value", func(t *testing.T) {
9010 msg, hdrLen := mqttEncodeRetainedMessage(&mqttRetainedMsg{
9011 Topic: "foo/x",
9012 Origin: " Origin", // Add spaces in front on purpose
9013 Source: "Source",
9014 Flags: 1,
9015 Msg: []byte("msg1"),
9016 })
9017 hdr := msg[:hdrLen]
9018 msg = msg[hdrLen:]
9019 rm, err := mqttDecodeRetainedMessage("$MQTT.rmsgs.foo.x", hdr, msg)
9020 require_NoError(t, err)
9021 require_Equal(t, rm.Topic, "foo/x")
9022 require_Equal(t, rm.Subject, "foo.x")
9023 require_Equal(t, rm.Origin, "Origin")
9024 require_Equal(t, rm.Source, "Source")
9025 require_Equal(t, rm.Flags, 1)
9026 require_Equal(t, string(rm.Msg), "msg1")
9027 })
9028 t.Run("decode retained msg with subject transformed", func(t *testing.T) {
9029 msg, hdrLen := mqttEncodeRetainedMessage(&mqttRetainedMsg{
9030 Topic: "foo/x",
9031 Origin: "Origin",
9032 Source: "Source",
9033 Flags: 1,
9034 Msg: []byte("msg2"),
9035 })
9036 hdr := msg[:hdrLen]
9037 msg = msg[hdrLen:]
9038 // Use different subject when calling the function. Make sure the
9039 // topic is properly reflecting the subject.
9040 rm, err := mqttDecodeRetainedMessage("$MQTT.rmsgs.bar.x", hdr, msg)
9041 require_NoError(t, err)
9042 require_Equal(t, rm.Topic, "bar/x")
9043 require_Equal(t, rm.Subject, "bar.x")
9044 require_Equal(t, rm.Origin, "Origin")
9045 require_Equal(t, rm.Source, "Source")
9046 require_Equal(t, rm.Flags, 1)
9047 require_Equal(t, string(rm.Msg), "msg2")
9048 })
9049 t.Run("decode deleted retained message", func(t *testing.T) {
9050 msg, hdrLen := mqttEncodeRetainedMessage(&mqttRetainedMsg{
9051 Topic: "foo/x",
9052 Origin: "Origin",
9053 Source: "Source",
9054 Flags: 1,
9055 Msg: nil,
9056 })
9057 hdr := msg[:hdrLen]
9058 msg = msg[hdrLen:]
9059 // Use different subject too
9060 rm, err := mqttDecodeRetainedMessage("$MQTT.rmsgs.bar.x", hdr, msg)
9061 require_NoError(t, err)
9062 require_Equal(t, rm.Topic, "bar/x")
9063 require_Equal(t, rm.Subject, "bar.x")
9064 require_Equal(t, rm.Origin, "Origin")
9065 require_Equal(t, rm.Source, "Source")
9066 require_Equal(t, rm.Flags, 1)
9067 require_Len(t, len(rm.Msg), 0)
9068 })
9069 t.Run("decode retained message as JSON with bad flags", func(t *testing.T) {
9070 rmo := &mqttRetainedMsg{Flags: 15}
9071 msg, err := json.Marshal(rmo)
9072 require_NoError(t, err)
9073 _, err = mqttDecodeRetainedMessage("$MQTT.rmsgs.foo.x", nil, msg)
9074 require_Error(t, err, errMQTTInvalidRetainFlags)
9075 })
9076 t.Run("decode retained message as JSON null", func(t *testing.T) {
9077 // A JSON `null` decodes into a nil pointer without an error, which
9078 // used to be dereferenced when checking the flags.
9079 _, err := mqttDecodeRetainedMessage("$MQTT.rmsgs.foo.x", nil, []byte("null"))
9080 require_Error(t, err, errMQTTInvalidRetainedMessage)
9081 })
9082 t.Run("decode retained message as JSON subject transform", func(t *testing.T) {
9083 rmo := &mqttRetainedMsg{
9084 Topic: "foo/x",
9085 Origin: "Origin",
9086 Source: "Source",
9087 Flags: 1,
9088 Msg: []byte("hello"),
9089 }
9090 msg, err := json.Marshal(rmo)
9091 require_NoError(t, err)
9092 rm, err := mqttDecodeRetainedMessage("$MQTT.rmsgs.bar.x", nil, msg)
9093 require_NoError(t, err)
9094 require_Equal(t, rm.Topic, "bar/x")
9095 require_Equal(t, rm.Subject, "bar.x")
9096 require_Equal(t, rm.Origin, "Origin")
9097 require_Equal(t, rm.Source, "Source")
9098 require_Equal(t, rm.Flags, 1)
9099 require_Equal(t, string(rm.Msg), "hello")
9100 })
9101 }
9102
9103 func TestMQTTPoisonedJSONRecordsDoNotCrashServer(t *testing.T) {
9104 o := testMQTTDefaultOptions()
9105 s := testMQTTRunServer(t, o)
9106 defer testMQTTShutdownServer(s)
9107
9108 // A first connection creates the account session manager, which is what
9109 // installs the internal subscriptions that process the records below.
9110 mc, mr := testMQTTConnect(t, &mqttConnInfo{clientID: "first", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
9111 defer mc.Close()
9112 testMQTTCheckConnAck(t, mr, mqttConnAckRCConnectionAccepted, false)
9113
9114 nc := natsConnect(t, s.ClientURL())
9115 defer nc.Close()
9116
9117 // A retained message stored as the JSON literal `null` decodes into a nil
9118 // *mqttRetainedMsg with no error. Processed on the stream's internal loop.
9119 if _, err := nc.Request(mqttRetainedMsgsStreamSubject+"x", []byte("null"), time.Second); err != nil {
9120 t.Fatalf("Error storing retained message: %v", err)
9121 }
9122
9123 // A session persist reply that carries none of the PubAck fields leaves the
9124 // embedded *PubAck nil. The JS id token has to differ from this server's for
9125 // the record not to be ignored as our own.
9126 natsPub(t, nc, mqttJSARepliesPrefix+nuid.Next()+"."+mqttJSASessPersist+"."+getHash("first")+"."+nuid.Next(), []byte("{}"))
9127 natsFlush(t, nc)
9128
9129 // A session record with a `null` consumer decodes into a present key with a
9130 // nil *ConsumerConfig, which is dereferenced when the session is cleared.
9131 poisonCID := "poison"
9132 sessSubj := mqttSessStreamSubjectPrefix + getHash(poisonCID)
9133 sessRec := fmt.Appendf(nil, `{"id":%q,"cons":{"sub1":null}}`, poisonCID)
9134 if _, err := nc.Request(sessSubj, sessRec, time.Second); err != nil {
9135 t.Fatalf("Error storing session record: %v", err)
9136 }
9137
9138 // Connecting with a clean session recovers that record and then clears it.
9139 pc, pr := testMQTTConnect(t, &mqttConnInfo{clientID: poisonCID, cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
9140 defer pc.Close()
9141 testMQTTCheckConnAck(t, pr, mqttConnAckRCConnectionAccepted, false)
9142
9143 // The server must still be running, and the retained message machinery
9144 // still functional, which means the internal loop did not go away.
9145 testMQTTPublish(t, mc, mr, 0, false, true, "foo/bar", 0, []byte("msg"))
9146
9147 sc, sr := testMQTTConnect(t, &mqttConnInfo{clientID: "sub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
9148 defer sc.Close()
9149 testMQTTCheckConnAck(t, sr, mqttConnAckRCConnectionAccepted, false)
9150 testMQTTSub(t, 1, sc, sr, []*mqttFilter{{filter: "foo/bar", qos: 0}}, []byte{0})
9151 testMQTTCheckPubMsg(t, sc, sr, "foo/bar", mqttPubFlagRetain, []byte("msg"))
9152 }
9153
9154 // mqttNewPoisonASM returns an isolated account session manager whose JS API send
9155 // queue is never drained, so no real JetStream ever answers a request made
9156 // through it. Requests block until a forged reply is injected.
9157 func mqttNewPoisonASM(s *Server) *mqttAccountSessionManager {
9158 id := "POISONID"
9159 return &mqttAccountSessionManager{
9160 sessions: make(map[string]*mqttSession),
9161 sessByHash: make(map[string]*mqttSession),
9162 sessLocked: make(map[string]struct{}),
9163 flappers: make(map[string]time.Time),
9164 jsa: mqttJSA{
9165 id: id,
9166 rplyr: mqttJSARepliesPrefix + id + ".",
9167 sendq: newIPQueue[*mqttJSPubMsg](s, "test-poison-send-"+nuid.Next()),
9168 nuid: nuid.New(),
9169 quitCh: make(chan struct{}),
9170 timeout: 10 * time.Second,
9171 },
9172 rmsCache: &sync.Map{},
9173 }
9174 }
9175
9176 // mqttRunWithPoisonedReply runs fn, which must issue a JS API request through
9177 // as.jsa and block waiting for the reply. Once the request is in flight, `reply`
9178 // is injected as the forged reply body on the exact subject the request
9179 // registered. Fails the test if fn panics (the pre-fix crash) or never returns.
9180 // Any value fn assigns is safe to read after this returns.
9181 func mqttRunWithPoisonedReply(t *testing.T, as *mqttAccountSessionManager, reply []byte, fn func()) {
9182 t.Helper()
9183 donec := make(chan any, 1)
9184 go func() {
9185 defer func() { donec <- recover() }()
9186 fn()
9187 }()
9188
9189 // Wait for the request to register its reply channel, then inject the
9190 // forged reply on that exact subject.
9191 var replySubj string
9192 for i := 0; i < 400 && replySubj == _EMPTY_; i++ {
9193 as.jsa.replies.Range(func(k, _ any) bool {
9194 replySubj = k.(string)
9195 return false
9196 })
9197 if replySubj == _EMPTY_ {
9198 time.Sleep(5 * time.Millisecond)
9199 }
9200 }
9201 require_True(t, replySubj != _EMPTY_)
9202 as.processJSAPIReplies(nil, nil, nil, replySubj, _EMPTY_, reply)
9203
9204 select {
9205 case p := <-donec:
9206 if p != nil {
9207 t.Fatalf("panicked on poisoned reply %q: %v", reply, p)
9208 }
9209 case <-time.After(15 * time.Second):
9210 t.Fatalf("did not return after injecting poisoned reply %q", reply)
9211 }
9212 }
9213
9214 func TestMQTTJSAPIPoisonedRepliesDoNotCrash(t *testing.T) {
9215 o := testMQTTDefaultOptions()
9216 s := testMQTTRunServer(t, o)
9217 defer testMQTTShutdownServer(s)
9218
9219 for _, tc := range []struct {
9220 name string
9221 reply []byte
9222 wantErr bool
9223 fn func(jsa *mqttJSA) error
9224 }{
9225 // `null` exercises the &resp double-pointer decode sites (findings F, J, C).
9226 {"stream_lookup_null", []byte("null"), true, func(jsa *mqttJSA) error {
9227 _, err := jsa.lookupStream("foo")
9228 return err
9229 }},
9230 {"stream_delete_null", []byte("null"), false, func(jsa *mqttJSA) error {
9231 _, err := jsa.deleteStream("foo")
9232 return err
9233 }},
9234 {"msg_load_null", []byte("null"), true, func(jsa *mqttJSA) error {
9235 _, err := jsa.loadMsg("foo", 1)
9236 return err
9237 }},
9238 // `{}` exercises the inner nil-pointer sites that survive the decode
9239 // (findings G, H1, I, D, H2).
9240 {"stream_lookup_empty", []byte("{}"), true, func(jsa *mqttJSA) error {
9241 _, err := jsa.lookupStream("foo")
9242 return err
9243 }},
9244 {"stream_create_empty", []byte("{}"), true, func(jsa *mqttJSA) error {
9245 _, _, err := jsa.createStream(&StreamConfig{Name: "foo", Storage: FileStorage})
9246 return err
9247 }},
9248 {"stream_update_empty", []byte("{}"), true, func(jsa *mqttJSA) error {
9249 _, err := jsa.updateStream(&StreamConfig{Name: "foo", Storage: FileStorage})
9250 return err
9251 }},
9252 {"msg_load_empty", []byte("{}"), true, func(jsa *mqttJSA) error {
9253 _, err := jsa.loadMsg("foo", 1)
9254 return err
9255 }},
9256 // The same inner *StoredMsg guard is replicated in the other two message
9257 // load accessors, so cover them too. A `null` case is not repeated here:
9258 // all three accessors share the mqttJSAMsgLoad decode site, so
9259 // msg_load_null above already covers that regression for them.
9260 {"msg_load_last_for_empty", []byte("{}"), true, func(jsa *mqttJSA) error {
9261 _, err := jsa.loadLastMsgFor("foo", "bar")
9262 return err
9263 }},
9264 {"msg_load_next_for_empty", []byte("{}"), true, func(jsa *mqttJSA) error {
9265 _, err := jsa.loadNextMsgFor("foo", "bar")
9266 return err
9267 }},
9268 {"pub_ack_empty", []byte("{}"), true, func(jsa *mqttJSA) error {
9269 sess := mqttSessionCreate(jsa, "cid", getHash("cid"), 0, o)
9270 return sess.save()
9271 }},
9272 } {
9273 t.Run(tc.name, func(t *testing.T) {
9274 as := mqttNewPoisonASM(s)
9275 var err error
9276 mqttRunWithPoisonedReply(t, as, tc.reply, func() { err = tc.fn(&as.jsa) })
9277 if tc.wantErr {
9278 require_Error(t, err)
9279 } else {
9280 require_NoError(t, err)
9281 }
9282 })
9283 }
9284 }
9285
9286 func TestMQTTLoadRetainedMessagesPoisonedReplyDoesNotCrash(t *testing.T) {
9287 o := testMQTTDefaultOptions()
9288 s := testMQTTRunServer(t, o)
9289 defer testMQTTShutdownServer(s)
9290
9291 as := mqttNewPoisonASM(s)
9292 var rms map[string]*mqttRetainedMsg
9293 // A `{}` body decodes into a non-nil JSApiMsgGetResponse with a nil Message.
9294 mqttRunWithPoisonedReply(t, as, []byte("{}"), func() {
9295 rms = as.loadRetainedMessages(map[string]uint64{"foo": 1}, s)
9296 })
9297 // The poisoned message is skipped, so nothing is returned.
9298 require_True(t, len(rms) == 0)
9299 }
9300
9301 func TestMQTTRetainedMessageWithDelSubjectIsNotRestored(t *testing.T) {
9302 tdir := t.TempDir()
9303 tmpl := `
9304 listen: 127.0.0.1:-1
9305 server_name: mqtt
9306 jetstream {
9307 store_dir = %q
9308 }
9309
9310 mqtt {
9311 listen: 127.0.0.1:-1
9312 consumer_inactive_threshold: %q
9313 }
9314
9315 # For access to system account.
9316 accounts { $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] } }
9317 `
9318 conf := createConfFile(t, fmt.Appendf(nil, tmpl, tdir, "0.2s"))
9319 s, o := RunServerWithConfig(conf)
9320 defer testMQTTShutdownServer(s)
9321
9322 // Publish one normal retained message through MQTT.
9323 mc, r := testMQTTConnectRetry(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 5)
9324 defer mc.Close()
9325 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
9326 testMQTTPublish(t, mc, r, 0, false, true, "foo/ok", 0, []byte("ok"))
9327 mc.Close()
9328
9329 // Store a legacy retained message directly into JetStream using a subject
9330 // that contains DEL. That subject can no longer be indexed after restore.
9331 nc, js := jsClientConnect(t, s)
9332 defer nc.Close()
9333 rm := mqttRetainedMsg{
9334 Origin: "test",
9335 Subject: "foo.\x7fbad",
9336 Topic: "foo/\x7fbad",
9337 Flags: mqttPubFlagRetain,
9338 Msg: []byte("bad"),
9339 }
9340 jsonData, _ := json.Marshal(rm)
9341 _, err := js.PublishMsg(&nats.Msg{
9342 Subject: mqttRetainedMsgsStreamSubject + rm.Subject,
9343 Data: jsonData,
9344 })
9345 require_NoError(t, err)
9346
9347 // Restart the server so retained-message recovery runs through
9348 // processRetainedMsg().
9349 s.Shutdown()
9350 s = RunServer(o)
9351 defer testMQTTShutdownServer(s)
9352
9353 mc, r = testMQTTConnectRetry(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port, 5)
9354 defer mc.Close()
9355 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
9356 testMQTTSub(t, 1, mc, r, []*mqttFilter{{filter: "foo/+", qos: 0}}, []byte{0})
9357 testMQTTCheckPubMsg(t, mc, r, "foo/ok", mqttPubFlagRetain, []byte("ok"))
9358 testMQTTExpectNothing(t, r)
9359 }
9360
9361 func TestMQTTRetainedMsgRemovedFromMapIfNotInStream(t *testing.T) {
9362 mqttRetainedCacheTTL = 250 * time.Millisecond
9363 defer func() { mqttRetainedCacheTTL = mqttDefaultRetainedCacheTTL }()
9364
9365 o := testMQTTDefaultOptions()
9366 s := testMQTTRunServer(t, o)
9367 defer testMQTTShutdownServer(s)
9368
9369 c, r := testMQTTConnect(t, &mqttConnInfo{clientID: "pub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
9370 defer c.Close()
9371 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
9372 testMQTTPublish(t, c, r, 0, false, true, "foo", 0, []byte("msg1"))
9373 testMQTTFlush(t, c, nil, r)
9374
9375 checkRetained := func(expected string) {
9376 t.Helper()
9377 c, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
9378 defer c.Close()
9379 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
9380 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: "foo", qos: 0}}, []byte{0})
9381 if expected == _EMPTY_ {
9382 testMQTTExpectNothing(t, r)
9383 } else {
9384 testMQTTCheckPubMsg(t, c, r, "foo", mqttPubFlagRetain, []byte(expected))
9385 }
9386 }
9387 checkRetained("msg1")
9388
9389 testMQTTPublish(t, c, r, 0, false, true, "foo", 0, []byte("msg2"))
9390 testMQTTFlush(t, c, nil, r)
9391
9392 checkRetained("msg2")
9393
9394 // Now we will get the current sequence for the retained message and
9395 // remove it from the stream. We expect to get a warning that indicates
9396 // that the load failed. Restarting the subscription should not longer
9397 // cause this warning and the retained message should have been removed
9398 // from the map/cache.
9399 l := &captureWarnLogger{warn: make(chan string, 10)}
9400 s.SetLogger(l, false, false)
9401
9402 asm := testMQTTGetAccountSessionManager(t, s, "pub")
9403 // Make sure it is in the cache
9404 rm := asm.getCachedRetainedMsg("foo")
9405 require_NotNil(t, rm)
9406 // Get the retained message sequence from the tree.
9407 asm.mu.RLock()
9408 rf, ok := asm.retmsgs.Find([]byte("foo"))
9409 asm.mu.RUnlock()
9410 require_True(t, ok)
9411 nc, js := jsClientConnect(t, s)
9412 defer nc.Close()
9413 err := js.DeleteMsg(mqttRetainedMsgsStreamName, rf.sseq)
9414 require_NoError(t, err)
9415
9416 // Wait for more than the cache TTL
9417 time.Sleep(2 * mqttRetainedCacheTTL)
9418
9419 checkRetained(_EMPTY_)
9420
9421 // We should have got a warning.
9422 select {
9423 case w := <-l.warn:
9424 if !strings.Contains(w, ApiErrors[JSNoMessageFoundErr].Description) {
9425 t.Fatalf("Unexpected warning: %q", w)
9426 }
9427 case <-time.After(time.Second):
9428 t.Fatalf("Test timed out")
9429 }
9430
9431 // But restarting it should not cause the server to try to load the retained
9432 // message again. So we should not have a warning.
9433 checkRetained(_EMPTY_)
9434
9435 select {
9436 case w := <-l.warn:
9437 if strings.Contains(w, ApiErrors[JSNoMessageFoundErr].Description) {
9438 t.Fatalf("Got the warning: %q", w)
9439 }
9440 case <-time.After(250 * time.Millisecond):
9441 // OK
9442 }
9443
9444 // Finally, check that the retmsgs map is empty.
9445 asm.mu.RLock()
9446 ok = asm.retmsgs.Size() == 0
9447 asm.mu.RUnlock()
9448 require_True(t, ok)
9449 }
9450
9451 func TestMQTTCrossAccountRetain(t *testing.T) {
9452 for _, test := range []struct {
9453 name string
9454 importTransform string
9455 sourceDest string
9456 bDest string
9457 getLastMsgSubj string
9458 }{
9459 {"without transform", "", "", "foo/x", "$MQTT.rmsgs.foo.x"},
9460 {"with transform", `, to: "foobar.>"`, "$MQTT.rmsgs.foobar.>", "foobar/x", "$MQTT.rmsgs.foobar.x"},
9461 } {
9462 t.Run(test.name, func(t *testing.T) {
9463 td := t.TempDir()
9464 dir := filepath.Join(td, "js")
9465 conf := createConfFile(t, fmt.Appendf(nil, `
9466 server_name: server
9467 listen: "127.0.0.1:-1"
9468 jetstream {
9469 domain: "MYDOMAIN"
9470 store_dir: "%s"
9471 }
9472 mqtt {
9473 listen: "127.0.0.1:-1"
9474 }
9475 accounts: {
9476 A: {
9477 jetstream: true
9478 users: [ { user:a, password:x }]
9479 exports: [
9480 { stream: "foo.>" }
9481 { service: "$JS.API.>", response_type: stream }
9482 { stream: "a2b.>" }
9483 ]
9484 }
9485 B: {
9486 jetstream: true
9487 users: [ { user:b, password:x }]
9488 imports: [
9489 { stream: { account: A, subject: "foo.>" }%s }
9490 { service: { account: A, subject: "$JS.API.>"}, to: "A.$JS.API.>" }
9491 { stream: { account: A, subject: "a2b.>" } }
9492 ]
9493 }
9494 }
9495 `, dir, test.importTransform))
9496 s, o := RunServerWithConfig(conf)
9497 defer s.Shutdown()
9498
9499 // Connect a user on "B" to create the MQTT assets.
9500 c, r := testMQTTConnect(t, &mqttConnInfo{cleanSess: true, user: "b", pass: "x"}, "127.0.0.1", o.MQTT.Port)
9501 defer c.Close()
9502 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
9503 testMQTTDisconnect(t, c, nil)
9504 c.Close()
9505
9506 pubRetained := func(user, dest, msg string) {
9507 t.Helper()
9508 c, r := testMQTTConnect(t, &mqttConnInfo{
9509 cleanSess: true,
9510 user: user,
9511 pass: "x",
9512 }, "127.0.0.1", o.MQTT.Port)
9513 defer c.Close()
9514 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
9515 testMQTTPublish(t, c, r, 0, false, true, dest, 0, []byte(msg))
9516 testMQTTFlush(t, c, nil, r)
9517 }
9518
9519 // Publish a retained message from account "A".
9520 retainInAMsg := "Retain in A"
9521 pubRetained("a", "foo/x", retainInAMsg)
9522
9523 // Now we are going to do something unusual, which is to update
9524 // the MQTT retain stream in "B" to source from "A".
9525 nc, js := jsClientConnect(t, s, nats.UserInfo("b", "x"))
9526 defer nc.Close()
9527
9528 si, err := js.StreamInfo(mqttRetainedMsgsStreamName)
9529 require_NoError(t, err)
9530 src := &nats.StreamSource{
9531 Name: mqttRetainedMsgsStreamName,
9532 External: &nats.ExternalStream{
9533 APIPrefix: "A.$JS.API",
9534 DeliverPrefix: "a2b",
9535 },
9536 SubjectTransforms: []nats.SubjectTransformConfig{
9537 {
9538 Source: mqttRetainedMsgsStreamSubject + "foo.>",
9539 Destination: test.sourceDest,
9540 },
9541 },
9542 }
9543 si.Config.Sources = []*nats.StreamSource{src}
9544 _, err = js.UpdateStream(&si.Config)
9545 require_NoError(t, err)
9546
9547 // Now wait to make sure that the "B" retained messages stream
9548 // contains the message with body "Retain in A"
9549 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
9550 msg, err := js.GetLastMsg(mqttRetainedMsgsStreamName, test.getLastMsgSubj)
9551 if err != nil {
9552 return err
9553 }
9554 if !bytes.Contains(msg.Data, []byte(retainInAMsg)) {
9555 return fmt.Errorf("Message is not from A: %q", msg.Data)
9556 }
9557 return nil
9558 })
9559
9560 getRetained := func(user, dest, msg string) {
9561 t.Helper()
9562 c, r := testMQTTConnect(t, &mqttConnInfo{
9563 cleanSess: true,
9564 user: user,
9565 pass: "x",
9566 }, "127.0.0.1", o.MQTT.Port)
9567 testMQTTCheckConnAck(t, r, mqttConnAckRCConnectionAccepted, false)
9568 testMQTTSub(t, 1, c, r, []*mqttFilter{{filter: dest, qos: 0}}, []byte{0})
9569 if msg == _EMPTY_ {
9570 testMQTTExpectNothing(t, r)
9571 } else {
9572 testMQTTCheckPubMsg(t, c, r, dest, mqttPubFlagRetain, []byte(msg))
9573 }
9574 }
9575
9576 // The retained message in account A should of course be "Retain in A"
9577 getRetained("a", "foo/x", retainInAMsg)
9578 // But because of the sourcing, the retained message in "B" should be
9579 // the retained message from the "A" account.
9580 getRetained("b", test.bDest, retainInAMsg)
9581
9582 // Now publish a retained message from "B" account and make sure that
9583 // it is correctly replacing "Retain in A".
9584 retainInBMsg := "Retain in B"
9585 pubRetained("b", test.bDest, retainInBMsg)
9586 // Check that we can receive it.
9587 getRetained("b", test.bDest, retainInBMsg)
9588 // And "A" still has the "Retain in A" message.
9589 getRetained("a", "foo/x", retainInAMsg)
9590
9591 // Publish from "A" a new message:
9592 retainInAMsg = "Retain in A2"
9593 pubRetained("a", "foo/x", retainInAMsg)
9594 // Make sure that this retained appears on "A" and "B".
9595 getRetained("a", "foo/x", retainInAMsg)
9596 getRetained("b", test.bDest, retainInAMsg)
9597
9598 // Now publish an empty body retained message from "A". This
9599 // should remove the retained message from both "A" and "B".
9600 pubRetained("a", "foo/x", _EMPTY_)
9601
9602 // We will check that the message gets removed from the stream.
9603 checkFor(t, 2*time.Second, 15*time.Millisecond, func() error {
9604 _, err := js.GetLastMsg(mqttRetainedMsgsStreamName, test.getLastMsgSubj)
9605 if err == nats.ErrMsgNotFound {
9606 return nil
9607 }
9608 return fmt.Errorf("Message still present or unexpected error %v", err)
9609 })
9610 // The helper will use "expect nothing" if the given string is empty.
9611 getRetained("a", "foo/x", _EMPTY_)
9612 getRetained("b", test.bDest, _EMPTY_)
9613 })
9614 }
9615 }
9616
9617 // TestMQTTSessionPersistSpoofPrevented verifies that an MQTT client cannot
9618 // publish to internal $MQTT.JSA.* subjects to spoof session-persist messages
9619 // and evict other sessions.
9620 func TestMQTTSessionPersistSpoofPrevented(t *testing.T) {
9621 o := testMQTTDefaultOptions()
9622 o.Users = []*User{
9623 {
9624 Username: "victim",
9625 Password: "pass",
9626 Permissions: &Permissions{
9627 Publish: &SubjectPermission{Allow: []string{"foo.>"}},
9628 Subscribe: &SubjectPermission{Allow: []string{"foo.>"}},
9629 },
9630 },
9631 {
9632 Username: "attacker",
9633 Password: "pass",
9634 Permissions: &Permissions{
9635 Publish: &SubjectPermission{Allow: []string{"foo.>"}},
9636 Subscribe: &SubjectPermission{Allow: []string{"foo.>"}},
9637 },
9638 },
9639 }
9640 s := testMQTTRunServer(t, o)
9641 defer testMQTTShutdownServer(s)
9642
9643 // Connect the victim MQTT client with a persistent session.
9644 vc, vr := testMQTTConnect(t, &mqttConnInfo{
9645 clientID: "victim",
9646 user: "victim",
9647 pass: "pass",
9648 cleanSess: true,
9649 }, o.MQTT.Host, o.MQTT.Port)
9650 defer vc.Close()
9651 testMQTTCheckConnAck(t, vr, mqttConnAckRCConnectionAccepted, false)
9652 testMQTTSub(t, 1, vc, vr, []*mqttFilter{{filter: "foo/+", qos: 1}}, []byte{1})
9653 testMQTTFlush(t, vc, nil, vr)
9654
9655 // Connect the attacker MQTT client.
9656 ac, ar := testMQTTConnect(t, &mqttConnInfo{
9657 clientID: "attacker",
9658 user: "attacker",
9659 pass: "pass",
9660 cleanSess: true,
9661 }, o.MQTT.Host, o.MQTT.Port)
9662 defer ac.Close()
9663 testMQTTCheckConnAck(t, ar, mqttConnAckRCConnectionAccepted, false)
9664
9665 // Craft a forged session-persist message targeting the victim's session.
9666 // MQTT topic "/" maps to NATS ".", so this becomes:
9667 // $MQTT.JSA.fakenode.SP.<victimHash>.fakeuuid
9668 victimHash := getHash("victim")
9669 spoofTopic := fmt.Sprintf("$MQTT/JSA/fakenode/%s/%s/fakeuuid", mqttJSASessPersist, victimHash)
9670 forgedPayload := []byte(`{"stream":"` + mqttSessStreamName + `","seq":999}`)
9671
9672 // Attempt the spoofed publish. With the fix, the implicit allow bypass
9673 // for MQTT clients on $MQTT.* subjects is removed, so this publish is
9674 // denied by the permission check (attacker only has "foo.>" allow).
9675 testMQTTPublish(t, ac, ar, 0, false, false, spoofTopic, 0, forgedPayload)
9676 testMQTTFlush(t, ac, nil, ar)
9677
9678 // Give the server time to process if the message leaked through.
9679 time.Sleep(250 * time.Millisecond)
9680
9681 // Verify the victim session was NOT evicted by round-tripping a message.
9682 testMQTTPublish(t, ac, ar, 0, false, false, "foo/bar", 0, []byte("still-alive"))
9683 testMQTTCheckPubMsg(t, vc, vr, "foo/bar", 0, []byte("still-alive"))
9684 }
9685
9686 func TestMQTTPublishSubjectLeafNodeParserFailures(t *testing.T) {
9687 const (
9688 hdrLen = 25
9689 leafControlLimit = MAX_CONTROL_LINE_SIZE * 16
9690 )
9691
9692 hdr := []byte("NATS/1.0\r\nNmqtt-Pub:0\r\n\r\n")
9693 require_Equal(t, len(hdr), hdrLen)
9694
9695 convertMQTTTopic := func(t *testing.T, topic []byte) []byte {
9696 t.Helper()
9697 require_NoError(t, mqttValidateTopic(topic, "topic"))
9698 subject, err := mqttTopicToNATSPubSubject(topic)
9699 require_NoError(t, err)
9700 return subject
9701 }
9702
9703 parseLeafHMSG := func(subject []byte) error {
9704 c := dummyClient()
9705 c.kind = LEAF
9706 c.leaf = &leaf{}
9707 c.flags.set(connectReceived)
9708 proto := fmt.Appendf(nil, "HMSG %s %d %d\r\n", subject, hdrLen, hdrLen)
9709 proto = append(proto, hdr...)
9710 proto = append(proto, _CRLF_...)
9711 return c.parse(proto)
9712 }
9713
9714 leafHMSGArgLen := func(subject []byte) int {
9715 return len(subject) + len(" 25 25")
9716 }
9717
9718 makeRepeatedLevelTopic := func(levels int) []byte {
9719 topic := bytes.Repeat([]byte("a."), levels)
9720 return topic[:len(topic)-1]
9721 }
9722
9723 makeSlashExpansionTopic := func(t *testing.T) []byte {
9724 t.Helper()
9725 var topic []byte
9726 for {
9727 if len(topic) > 0 {
9728 topic = append(topic, '/', '/')
9729 }
9730 topic = append(topic, 'a')
9731 subject := convertMQTTTopic(t, topic)
9732 if len(subject) > leafControlLimit-len(" 25 25") {
9733 return topic
9734 }
9735 }
9736 }
9737
9738 for _, test := range []struct {
9739 name string
9740 topic []byte
9741 wantErr bool
9742 wantExpansion bool
9743 wantArgLen int
9744 }{
9745 {
9746 name: "converted subject at leaf control line limit is accepted",
9747 topic: bytes.Repeat([]byte{'a'}, leafControlLimit-len(" 25 25")),
9748 wantErr: false,
9749 wantArgLen: leafControlLimit,
9750 },
9751 {
9752 name: "literal topic exceeds leaf control line limit",
9753 topic: bytes.Repeat([]byte{'a'}, leafControlLimit-len(" 25 25")+1),
9754 wantErr: true,
9755 wantArgLen: leafControlLimit + 1,
9756 },
9757 {
9758 name: "dot expansion can make a shorter topic exceed leaf control line limit",
9759 topic: makeRepeatedLevelTopic(21845),
9760 wantErr: true,
9761 wantExpansion: true,
9762 },
9763 {
9764 name: "slash escaping can make a shorter topic exceed leaf control line limit",
9765 topic: makeSlashExpansionTopic(t),
9766 wantErr: true,
9767 wantExpansion: true,
9768 },
9769 } {
9770 t.Run(test.name, func(t *testing.T) {
9771 subject := convertMQTTTopic(t, test.topic)
9772 if test.wantArgLen > 0 {
9773 require_Equal(t, leafHMSGArgLen(subject), test.wantArgLen)
9774 }
9775 if test.wantExpansion {
9776 require_True(t, len(test.topic) <= len(subject))
9777 }
9778 if err := parseLeafHMSG(subject); test.wantErr {
9779 require_Error(t, err, ErrMaxControlLine)
9780 } else {
9781 require_NoError(t, err)
9782 }
9783 })
9784 }
9785
9786 for _, test := range []struct {
9787 name string
9788 topic []byte
9789 }{
9790 {name: "space", topic: []byte("foo bar")},
9791 {name: "tab", topic: []byte("foo\tbar")},
9792 {name: "carriage return", topic: []byte("foo\rbar")},
9793 {name: "line feed", topic: []byte("foo\nbar")},
9794 {name: "carriage return line feed", topic: []byte("foo\r\nbar")},
9795 {name: "null", topic: []byte("foo\x00bar")},
9796 {name: "invalid utf8", topic: []byte{0xff}},
9797 {name: "single level wildcard", topic: []byte("foo/+")},
9798 {name: "multi level wildcard", topic: []byte("foo/#")},
9799 } {
9800 t.Run("rejected before leaf forwarding/"+test.name, func(t *testing.T) {
9801 if err := mqttValidateTopic(test.topic, "topic"); err == nil {
9802 _, err = mqttTopicToNATSPubSubject(test.topic)
9803 require_Error(t, err)
9804 }
9805 })
9806 }
9807 }
9808
9809 //////////////////////////////////////////////////////////////////////////
9810 //
9811 // Benchmarks
9812 //
9813 //////////////////////////////////////////////////////////////////////////
9814
9815 const (
9816 mqttPubSubj = "a"
9817 mqttBenchBufLen = 32768
9818 )
9819
9820 func mqttBenchPubQoS0(b *testing.B, subject, payload string, numSubs int) {
9821 b.StopTimer()
9822 b.ReportAllocs()
9823 o := testMQTTDefaultOptions()
9824 s := RunServer(o)
9825 defer testMQTTShutdownServer(s)
9826
9827 ci := &mqttConnInfo{clientID: "pub", cleanSess: true}
9828 c, br := testMQTTConnect(b, ci, o.MQTT.Host, o.MQTT.Port)
9829 testMQTTCheckConnAck(b, br, mqttConnAckRCConnectionAccepted, false)
9830 w := newMQTTWriter(0)
9831 testMQTTWritePublishPacket(b, w, 0, false, false, subject, 0, []byte(payload))
9832 sendOp := w.Bytes()
9833
9834 dch := make(chan error, 1)
9835 totalSize := int64(len(sendOp))
9836 cdch := 0
9837
9838 createSub := func(i int) {
9839 ci := &mqttConnInfo{clientID: fmt.Sprintf("sub%d", i), cleanSess: true}
9840 cs, brs := testMQTTConnect(b, ci, o.MQTT.Host, o.MQTT.Port)
9841 testMQTTCheckConnAck(b, brs, mqttConnAckRCConnectionAccepted, false)
9842
9843 testMQTTSub(b, 1, cs, brs, []*mqttFilter{{filter: subject, qos: 0}}, []byte{0})
9844 testMQTTFlush(b, cs, nil, brs)
9845
9846 w := newMQTTWriter(0)
9847 varHeaderAndPayload := 2 + len(subject) + len(payload)
9848 w.WriteVarInt(varHeaderAndPayload)
9849 size := 1 + w.Len() + varHeaderAndPayload
9850 totalSize += int64(size)
9851
9852 go func() {
9853 mqttBenchConsumeMsgQoS0(cs, int64(b.N)*int64(size), dch)
9854 cs.Close()
9855 }()
9856 }
9857 for i := 0; i < numSubs; i++ {
9858 createSub(i + 1)
9859 cdch++
9860 }
9861
9862 bw := bufio.NewWriterSize(c, mqttBenchBufLen)
9863 b.SetBytes(totalSize)
9864 b.StartTimer()
9865 for i := 0; i < b.N; i++ {
9866 bw.Write(sendOp)
9867 }
9868 testMQTTFlush(b, c, bw, br)
9869 for i := 0; i < cdch; i++ {
9870 if e := <-dch; e != nil {
9871 b.Fatal(e.Error())
9872 }
9873 }
9874 b.StopTimer()
9875 c.Close()
9876 s.Shutdown()
9877 }
9878
9879 func mqttBenchConsumeMsgQoS0(c net.Conn, total int64, dch chan<- error) {
9880 var buf [mqttBenchBufLen]byte
9881 var err error
9882 var n int
9883 for size := int64(0); size < total; {
9884 n, err = c.Read(buf[:])
9885 if err != nil {
9886 break
9887 }
9888 size += int64(n)
9889 }
9890 dch <- err
9891 }
9892
9893 func mqttBenchPubQoS1(b *testing.B, subject, payload string, numSubs int) {
9894 b.StopTimer()
9895 o := testMQTTDefaultOptions()
9896 o.MQTT.MaxAckPending = 0xFFFF
9897 s := RunServer(o)
9898 defer testMQTTShutdownServer(s)
9899
9900 ci := &mqttConnInfo{cleanSess: true}
9901 c, br := testMQTTConnect(b, ci, o.MQTT.Host, o.MQTT.Port)
9902 testMQTTCheckConnAck(b, br, mqttConnAckRCConnectionAccepted, false)
9903
9904 w := newMQTTWriter(0)
9905 testMQTTWritePublishPacket(b, w, 1, false, false, subject, 1, []byte(payload))
9906 // For reported bytes we will count the PUBLISH + PUBACK (4 bytes)
9907 totalSize := int64(w.Len() + 4)
9908 w.Reset()
9909
9910 pi := uint16(1)
9911 maxpi := uint16(60000)
9912 ppich := make(chan error, 10)
9913 dch := make(chan error, 1+numSubs)
9914 cdch := 1
9915 // Start go routine to consume PUBACK for published QoS 1 messages.
9916 go mqttBenchConsumePubAck(c, b.N, dch, ppich)
9917
9918 createSub := func(i int) {
9919 ci := &mqttConnInfo{clientID: fmt.Sprintf("sub%d", i), cleanSess: true}
9920 cs, brs := testMQTTConnect(b, ci, o.MQTT.Host, o.MQTT.Port)
9921 testMQTTCheckConnAck(b, brs, mqttConnAckRCConnectionAccepted, false)
9922
9923 testMQTTSub(b, 1, cs, brs, []*mqttFilter{{filter: subject, qos: 1}}, []byte{1})
9924 testMQTTFlush(b, cs, nil, brs)
9925
9926 w := newMQTTWriter(0)
9927 varHeaderAndPayload := 2 + len(subject) + 2 + len(payload)
9928 w.WriteVarInt(varHeaderAndPayload)
9929 size := 1 + w.Len() + varHeaderAndPayload
9930 // Add to the bytes reported the size of message sent to subscriber + PUBACK (4 bytes)
9931 totalSize += int64(size + 4)
9932
9933 go func() {
9934 mqttBenchConsumeMsgQos1(cs, b.N, size, dch)
9935 cs.Close()
9936 }()
9937 }
9938 for i := 0; i < numSubs; i++ {
9939 createSub(i + 1)
9940 cdch++
9941 }
9942
9943 flush := func() {
9944 b.Helper()
9945 if _, err := c.Write(w.Bytes()); err != nil {
9946 b.Fatalf("Error on write: %v", err)
9947 }
9948 w.Reset()
9949 }
9950
9951 b.SetBytes(totalSize)
9952 b.StartTimer()
9953 for i := 0; i < b.N; i++ {
9954 if pi <= maxpi {
9955 testMQTTWritePublishPacket(b, w, 1, false, false, subject, pi, []byte(payload))
9956 pi++
9957 if w.Len() >= mqttBenchBufLen {
9958 flush()
9959 }
9960 } else {
9961 if w.Len() > 0 {
9962 flush()
9963 }
9964 if pi > 60000 {
9965 pi = 1
9966 maxpi = 0
9967 }
9968 if e := <-ppich; e != nil {
9969 b.Fatal(e.Error())
9970 }
9971 maxpi += 10000
9972 i--
9973 }
9974 }
9975 if w.Len() > 0 {
9976 flush()
9977 }
9978 for i := 0; i < cdch; i++ {
9979 if e := <-dch; e != nil {
9980 b.Fatal(e.Error())
9981 }
9982 }
9983 b.StopTimer()
9984 c.Close()
9985 s.Shutdown()
9986 }
9987
9988 func mqttBenchConsumeMsgQos1(c net.Conn, total, size int, dch chan<- error) {
9989 var buf [mqttBenchBufLen]byte
9990 pubAck := [4]byte{mqttPacketPubAck, 0x2, 0, 0}
9991 var err error
9992 var n int
9993 var pi uint16
9994 var prev int
9995 for i := 0; i < total; {
9996 n, err = c.Read(buf[:])
9997 if err != nil {
9998 break
9999 }
10000 n += prev
10001 for ; n >= size; n -= size {
10002 i++
10003 pi++
10004 pubAck[2] = byte(pi >> 8)
10005 pubAck[3] = byte(pi)
10006 if _, err = c.Write(pubAck[:4]); err != nil {
10007 dch <- err
10008 return
10009 }
10010 if pi == 60000 {
10011 pi = 0
10012 }
10013 }
10014 prev = n
10015 }
10016 dch <- err
10017 }
10018
10019 func mqttBenchConsumePubAck(c net.Conn, total int, dch, ppich chan<- error) {
10020 var buf [mqttBenchBufLen]byte
10021 var err error
10022 var n int
10023 var pi uint16
10024 var prev int
10025 for i := 0; i < total; {
10026 n, err = c.Read(buf[:])
10027 if err != nil {
10028 break
10029 }
10030 n += prev
10031 for ; n >= 4; n -= 4 {
10032 i++
10033 pi++
10034 if pi%10000 == 0 {
10035 ppich <- nil
10036 }
10037 if pi == 60001 {
10038 pi = 0
10039 }
10040 }
10041 prev = n
10042 }
10043 ppich <- err
10044 dch <- err
10045 }
10046
10047 func BenchmarkMQTT_QoS0_Pub_______0b_Payload(b *testing.B) {
10048 mqttBenchPubQoS0(b, mqttPubSubj, "", 0)
10049 }
10050
10051 func BenchmarkMQTT_QoS0_Pub_______8b_Payload(b *testing.B) {
10052 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(8), 0)
10053 }
10054
10055 func BenchmarkMQTT_QoS0_Pub______32b_Payload(b *testing.B) {
10056 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(32), 0)
10057 }
10058
10059 func BenchmarkMQTT_QoS0_Pub_____128b_Payload(b *testing.B) {
10060 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(128), 0)
10061 }
10062
10063 func BenchmarkMQTT_QoS0_Pub_____256b_Payload(b *testing.B) {
10064 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(256), 0)
10065 }
10066
10067 func BenchmarkMQTT_QoS0_Pub_______1K_Payload(b *testing.B) {
10068 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(1024), 0)
10069 }
10070
10071 func BenchmarkMQTT_QoS0_PubSub1___0b_Payload(b *testing.B) {
10072 mqttBenchPubQoS0(b, mqttPubSubj, "", 1)
10073 }
10074
10075 func BenchmarkMQTT_QoS0_PubSub1___8b_Payload(b *testing.B) {
10076 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(8), 1)
10077 }
10078
10079 func BenchmarkMQTT_QoS0_PubSub1__32b_Payload(b *testing.B) {
10080 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(32), 1)
10081 }
10082
10083 func BenchmarkMQTT_QoS0_PubSub1_128b_Payload(b *testing.B) {
10084 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(128), 1)
10085 }
10086
10087 func BenchmarkMQTT_QoS0_PubSub1_256b_Payload(b *testing.B) {
10088 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(256), 1)
10089 }
10090
10091 func BenchmarkMQTT_QoS0_PubSub1___1K_Payload(b *testing.B) {
10092 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(1024), 1)
10093 }
10094
10095 func BenchmarkMQTT_QoS0_PubSub2___0b_Payload(b *testing.B) {
10096 mqttBenchPubQoS0(b, mqttPubSubj, "", 2)
10097 }
10098
10099 func BenchmarkMQTT_QoS0_PubSub2___8b_Payload(b *testing.B) {
10100 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(8), 2)
10101 }
10102
10103 func BenchmarkMQTT_QoS0_PubSub2__32b_Payload(b *testing.B) {
10104 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(32), 2)
10105 }
10106
10107 func BenchmarkMQTT_QoS0_PubSub2_128b_Payload(b *testing.B) {
10108 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(128), 2)
10109 }
10110
10111 func BenchmarkMQTT_QoS0_PubSub2_256b_Payload(b *testing.B) {
10112 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(256), 2)
10113 }
10114
10115 func BenchmarkMQTT_QoS0_PubSub2___1K_Payload(b *testing.B) {
10116 mqttBenchPubQoS0(b, mqttPubSubj, sizedString(1024), 2)
10117 }
10118
10119 func BenchmarkMQTT_QoS1_Pub_______0b_Payload(b *testing.B) {
10120 mqttBenchPubQoS1(b, mqttPubSubj, "", 0)
10121 }
10122
10123 func BenchmarkMQTT_QoS1_Pub_______8b_Payload(b *testing.B) {
10124 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(8), 0)
10125 }
10126
10127 func BenchmarkMQTT_QoS1_Pub______32b_Payload(b *testing.B) {
10128 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(32), 0)
10129 }
10130
10131 func BenchmarkMQTT_QoS1_Pub_____128b_Payload(b *testing.B) {
10132 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(128), 0)
10133 }
10134
10135 func BenchmarkMQTT_QoS1_Pub_____256b_Payload(b *testing.B) {
10136 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(256), 0)
10137 }
10138
10139 func BenchmarkMQTT_QoS1_Pub_______1K_Payload(b *testing.B) {
10140 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(1024), 0)
10141 }
10142
10143 func BenchmarkMQTT_QoS1_PubSub1___0b_Payload(b *testing.B) {
10144 mqttBenchPubQoS1(b, mqttPubSubj, "", 1)
10145 }
10146
10147 func BenchmarkMQTT_QoS1_PubSub1___8b_Payload(b *testing.B) {
10148 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(8), 1)
10149 }
10150
10151 func BenchmarkMQTT_QoS1_PubSub1__32b_Payload(b *testing.B) {
10152 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(32), 1)
10153 }
10154
10155 func BenchmarkMQTT_QoS1_PubSub1_128b_Payload(b *testing.B) {
10156 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(128), 1)
10157 }
10158
10159 func BenchmarkMQTT_QoS1_PubSub1_256b_Payload(b *testing.B) {
10160 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(256), 1)
10161 }
10162
10163 func BenchmarkMQTT_QoS1_PubSub1___1K_Payload(b *testing.B) {
10164 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(1024), 1)
10165 }
10166
10167 func BenchmarkMQTT_QoS1_PubSub2___0b_Payload(b *testing.B) {
10168 mqttBenchPubQoS1(b, mqttPubSubj, "", 2)
10169 }
10170
10171 func BenchmarkMQTT_QoS1_PubSub2___8b_Payload(b *testing.B) {
10172 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(8), 2)
10173 }
10174
10175 func BenchmarkMQTT_QoS1_PubSub2__32b_Payload(b *testing.B) {
10176 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(32), 2)
10177 }
10178
10179 func BenchmarkMQTT_QoS1_PubSub2_128b_Payload(b *testing.B) {
10180 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(128), 2)
10181 }
10182
10183 func BenchmarkMQTT_QoS1_PubSub2_256b_Payload(b *testing.B) {
10184 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(256), 2)
10185 }
10186
10187 func BenchmarkMQTT_QoS1_PubSub2___1K_Payload(b *testing.B) {
10188 mqttBenchPubQoS1(b, mqttPubSubj, sizedString(1024), 2)
10189 }
10190
10191 // A PUBREL arriving on a different connection than its PUBLISH (session
10192 // resumed after a reconnect) has no staged in-memory copy and must fall
10193 // back to loading the message from JetStream, still delivering it exactly
10194 // once and completing the exchange.
10195 func TestMQTTQoS2PubRelResumedSessionDelivery(t *testing.T) {
10196 o := testMQTTDefaultOptions()
10197 s := testMQTTRunServer(t, o)
10198 defer testMQTTShutdownServer(s)
10199
10200 mcs, msr := testMQTTConnect(t, &mqttConnInfo{clientID: "sub", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
10201 defer mcs.Close()
10202 testMQTTCheckConnAck(t, msr, mqttConnAckRCConnectionAccepted, false)
10203 testMQTTSub(t, 1, mcs, msr, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
10204 testMQTTFlush(t, mcs, nil, msr)
10205
10206 // Publish QoS2 retained and PUBREC it, then drop before the PUBREL.
10207 const pubPI = 7
10208 ci := &mqttConnInfo{clientID: "pub", cleanSess: false}
10209 mcp, mpr := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
10210 testMQTTCheckConnAck(t, mpr, mqttConnAckRCConnectionAccepted, false)
10211 testMQTTSendPublishPacket(t, mcp, 2, false, true, "foo", pubPI, []byte("m"))
10212 testMQTTReadPIPacket(mqttPacketPubRec, t, mpr, pubPI)
10213 testMQTTDisconnect(t, mcp, nil)
10214 mcp.Close()
10215 testMQTTExpectNothing(t, msr)
10216
10217 // Resume the session; the PUBREL now delivers the message, at the sub's QoS.
10218 mcp2, mpr2 := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
10219 defer mcp2.Close()
10220 testMQTTCheckConnAck(t, mpr2, mqttConnAckRCConnectionAccepted, true)
10221 testMQTTSendPIPacket(mqttPacketPubRel|0x2, t, mcp2, pubPI)
10222 testMQTTReadPIPacket(mqttPacketPubComp, t, mpr2, pubPI)
10223 testMQTTCheckPubMsgNoAck(t, mcs, msr, "foo", mqttPubQos1, []byte("m"))
10224 testMQTTExpectNothing(t, msr)
10225
10226 // A repeated PUBREL is acked without redelivering.
10227 testMQTTSendPIPacket(mqttPacketPubRel|0x2, t, mcp2, pubPI)
10228 testMQTTReadPIPacket(mqttPacketPubComp, t, mpr2, pubPI)
10229 testMQTTExpectNothing(t, msr)
10230
10231 // The retain flag must survive the staging round-trip: a new
10232 // subscriber gets the message as retained.
10233 checkFor(t, time.Second, 10*time.Millisecond, func() error {
10234 acc, err := s.lookupAccount(globalAccountName)
10235 if err != nil {
10236 return err
10237 }
10238 mset, err := acc.lookupStream(mqttRetainedMsgsStreamName)
10239 if err != nil {
10240 return err
10241 }
10242 if mset.state().Msgs != 1 {
10243 return errors.New("retained message not stored")
10244 }
10245 return nil
10246 })
10247 mcs2, msr2 := testMQTTConnect(t, &mqttConnInfo{clientID: "sub2", cleanSess: true}, o.MQTT.Host, o.MQTT.Port)
10248 defer mcs2.Close()
10249 testMQTTCheckConnAck(t, msr2, mqttConnAckRCConnectionAccepted, false)
10250 testMQTTSub(t, 1, mcs2, msr2, []*mqttFilter{{filter: "foo", qos: 1}}, []byte{1})
10251 testMQTTCheckPubMsgNoAck(t, mcs2, msr2, "foo", mqttPubQos1|mqttPubFlagRetain, []byte("m"))
10252 }
10253
10254 func TestMQTTCertMappedUserNotPasswordAuthenticatable(t *testing.T) {
10255 const certUser = "CN=example.com,OU=NATS.io"
10256
10257 // The mqtt listener does not map, so a certificate identity must not be
10258 // authenticatable by username there. The leafnode and websocket listeners
10259 // are covered by TestAuthCertMappedUserNotPasswordAuthenticatable.
10260 conf := createConfFile(t, []byte(fmt.Sprintf(`
10261 listen: "127.0.0.1:-1"
10262 server_name: "S1"
10263 jetstream { store_dir: %q }
10264 tls {
10265 cert_file: "../test/configs/certs/tlsauth/server.pem"
10266 key_file: "../test/configs/certs/tlsauth/server-key.pem"
10267 ca_file: "../test/configs/certs/tlsauth/ca.pem"
10268 verify_and_map: true
10269 }
10270 mqtt { listen: "127.0.0.1:-1" }
10271 authorization {
10272 users [
10273 { user = "CN=other.example.com,OU=NATS.io" }
10274 { user = "%s" }
10275 ]
10276 }
10277 `, t.TempDir(), certUser)))
10278 s, o := RunServerWithConfig(conf)
10279 defer testMQTTShutdownServer(s)
10280
10281 for _, test := range []struct {
10282 name string
10283 user string
10284 pass string
10285 }{
10286 {"empty password", certUser, _EMPTY_},
10287 {"wrong password", certUser, "wrongpassword"},
10288 {"unknown user", "CN=attacker.com,OU=NATS.io", _EMPTY_},
10289 {"anonymous", _EMPTY_, _EMPTY_},
10290 } {
10291 t.Run(test.name, func(t *testing.T) {
10292 ci := &mqttConnInfo{clientID: "mqtt", cleanSess: true, user: test.user, pass: test.pass}
10293 mc, r := testMQTTConnect(t, ci, o.MQTT.Host, o.MQTT.Port)
10294 defer mc.Close()
10295 testMQTTCheckConnAck(t, r, mqttConnAckRCNotAuthorized, false)
10296 })
10297 }
10298 }