-
Notifications
You must be signed in to change notification settings - Fork 7
/
websocket_push_session_test.go
1073 lines (816 loc) · 29.2 KB
/
websocket_push_session_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 Aporeto Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bahamut
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net/http"
"net/url"
"testing"
"time"
"github.com/gorilla/websocket"
"github.com/opentracing/opentracing-go"
// nolint:revive // Allow dot imports for readability in tests
. "github.com/smartystreets/goconvey/convey"
"go.aporeto.io/elemental"
testmodel "go.aporeto.io/elemental/test/model"
"go.aporeto.io/wsc"
)
func TestWSPushSession_newPushSession(t *testing.T) {
Convey("Given call newWSPushSession", t, func() {
u, _ := url.Parse("http://toto.com?a=b")
conf := config{}
req := &http.Request{
Header: http.Header{"Authorization": {"a"}},
URL: u,
TLS: &tls.ConnectionState{},
RemoteAddr: "1.2.3.4",
}
unregister := func(i *wsPushSession) {}
s := newWSPushSession(req, conf, unregister, elemental.EncodingTypeMSGPACK, elemental.EncodingTypeMSGPACK)
Convey("Then it should be correctly initialized", func() {
So(s.dataCh, ShouldHaveSameTypeAs, make(chan []byte))
So(s.Claims(), ShouldResemble, []string{})
So(s.claimsMap, ShouldResemble, map[string]string{})
So(s.cfg, ShouldResemble, conf)
So(s.headers, ShouldResemble, http.Header{"Authorization": {"a"}})
So(s.Header("Authorization"), ShouldEqual, "a")
So(s.id, ShouldNotBeEmpty)
So(s.parameters, ShouldResemble, url.Values{"a": {"b"}})
So(s.Parameter("a"), ShouldEqual, "b")
So(s.closeCh, ShouldHaveSameTypeAs, make(chan struct{}))
So(s.unregister, ShouldEqual, unregister)
So(s.Context(), ShouldNotBeNil)
So(s.cancel, ShouldNotBeNil)
So(s.TLSConnectionState(), ShouldEqual, req.TLS)
So(s.ClientIP(), ShouldEqual, req.RemoteAddr)
})
})
}
func TestWSPushSession_DirectPush(t *testing.T) {
Convey("Given I have a session and an event", t, func() {
req, _ := http.NewRequest("GET", "bla", nil)
cfg := config{}
s := newWSPushSession(req, cfg, nil, elemental.EncodingTypeMSGPACK, elemental.EncodingTypeMSGPACK)
evt := elemental.NewEvent(elemental.EventCreate, testmodel.NewList())
msgpack, _, err := prepareEventData(evt)
if err != nil {
panic(err)
}
Convey("When I call directPush", func() {
go s.DirectPush(evt, evt)
data1 := <-s.dataCh
data2 := <-s.dataCh
Convey("Then data1 should be correct", func() {
So(string(data1), ShouldEqual, string(msgpack))
})
Convey("Then data2 should be correct", func() {
So(string(data2), ShouldEqual, string(msgpack))
})
})
Convey("When I call directPush but event is filtered", func() {
f := elemental.NewPushConfig()
f.FilterIdentity("not-list")
s.setCurrentPushConfig(f)
go s.DirectPush(evt)
var data []byte
select {
case data = <-s.dataCh:
case <-time.After(1 * time.Second):
}
Convey("Then data should be correct", func() {
So(data, ShouldBeNil)
})
})
Convey("When I call directPush but event is before session", func() {
s.startTime = time.Now().Add(1 * time.Second)
go s.DirectPush(evt)
var data []byte
select {
case data = <-s.dataCh:
case <-time.After(1 * time.Second):
}
Convey("Then data should be correct", func() {
So(data, ShouldBeNil)
})
})
Convey("When I call directPush with a bad event", func() {
evt.Encoding = elemental.EncodingTypeJSON
evt.RawData = []byte("{brodken")
go s.DirectPush(evt)
var data []byte
select {
case data = <-s.dataCh:
case <-time.After(1 * time.Second):
}
Convey("Then data should be correct", func() {
So(data, ShouldBeNil)
})
})
})
}
func TestWSPushSession_send(t *testing.T) {
Convey("Given I have a session and an event", t, func() {
req, _ := http.NewRequest("GET", "bla", nil)
cfg := config{}
s := newWSPushSession(req, cfg, nil, elemental.EncodingTypeMSGPACK, elemental.EncodingTypeMSGPACK)
Convey("When I call directPush and pull from the event channel", func() {
s.send([]byte("hello"))
data := <-s.dataCh
Convey("Then data should be correct", func() {
So(string(data), ShouldEqual, "hello")
})
})
Convey("When I call directPush and overflow it", func() {
for i := 0; i < 2000; i++ {
s.send([]byte("hello"))
}
var total int
for i := 0; i < 2000; i++ {
select {
case <-s.dataCh:
total++
default:
}
}
Convey("Then we should get 64 data", func() {
So(total, ShouldEqual, 64)
})
})
})
}
func TestWSPushSession_String(t *testing.T) {
Convey("Given I have a session", t, func() {
req, _ := http.NewRequest("GET", "bla", nil)
cfg := config{}
s := newWSPushSession(req, cfg, nil, elemental.EncodingTypeMSGPACK, elemental.EncodingTypeMSGPACK)
Convey("When I call String", func() {
str := s.String()
Convey("Then the string representation should be correct", func() {
So(str, ShouldEqual, fmt.Sprintf("<pushsession id:%s>", s.Identifier()))
})
})
})
}
func TestWSPushSession_Filtering(t *testing.T) {
Convey("Given I call setCurrentPushConfig", t, func() {
req, _ := http.NewRequest("GET", "bla", nil)
cfg := config{}
s := newWSPushSession(req, cfg, nil, elemental.EncodingTypeMSGPACK, elemental.EncodingTypeMSGPACK)
pc := elemental.NewPushConfig()
pc.SetParameter("hello", "world")
s.setCurrentPushConfig(pc)
Convey("Then the filter should be installed", func() {
So(s.currentPushConfig(), ShouldNotEqual, pc)
So(s.currentPushConfig(), ShouldResemble, pc)
})
Convey("Then the parameters have benn installed", func() {
So(s.Parameter("hello"), ShouldEqual, "world")
})
Convey("When I reset the filter to nil", func() {
s.setCurrentPushConfig(nil)
Convey("Then the filter should be uninstalled", func() {
So(s.currentPushConfig(), ShouldBeNil)
})
})
})
}
func TestWSPushSession_accessors(t *testing.T) {
Convey("Given create a push session", t, func() {
u, _ := url.Parse("http://toto.com?a=b&token=token")
conf := config{}
req := &http.Request{
Header: http.Header{"h1": {"a"}},
URL: u,
TLS: &tls.ConnectionState{},
RemoteAddr: "1.2.3.4",
}
span := opentracing.StartSpan("test")
ctx := opentracing.ContextWithSpan(context.Background(), span)
req = req.WithContext(ctx)
unregister := func(i *wsPushSession) {}
s := newWSPushSession(req, conf, unregister, elemental.EncodingTypeMSGPACK, elemental.EncodingTypeMSGPACK)
Convey("When I call Identifier()", func() {
id := s.Identifier()
Convey("Then id should be correct", func() {
So(id, ShouldNotBeEmpty)
})
})
Convey("When I call SetClaims()", func() {
s.SetClaims([]string{"a=a", "b=b"})
Convey("Then Claims() should return the correct claims ", func() {
So(s.Claims(), ShouldResemble, []string{"a=a", "b=b"})
})
Convey("Then ClaimsMap() should return the correct claims ", func() {
m := s.ClaimsMap()
So(len(m), ShouldEqual, 2)
So(m["a"], ShouldEqual, "a")
So(m["b"], ShouldEqual, "b")
})
})
Convey("When I call Token()", func() {
token := s.Token()
Convey("Then token should be correct", func() {
So(token, ShouldEqual, "token")
})
})
Convey("When I call TLSConnectionState()", func() {
s := s.TLSConnectionState()
Convey("Then TLSConnectionState should be correct", func() {
So(s, ShouldEqual, req.TLS)
})
})
Convey("When I call SetMetadata()", func() {
s.SetMetadata("hi")
Convey("Then Metadata() should return the correct metadata ", func() {
So(s.Metadata(), ShouldResemble, "hi")
})
})
Convey("When I call Context()", func() {
c := s.Context()
Convey("Then Context() should return the correct context ", func() {
So(opentracing.SpanFromContext(c), ShouldResemble, span)
})
})
Convey("When I call Parameter()", func() {
p := s.Parameter("a")
Convey("Then parameter should be correct", func() {
So(p, ShouldEqual, "b")
})
})
Convey("When I call setRemoteAddress()", func() {
s.setRemoteAddress("a.b.c.d")
Convey("Then address should be correct", func() {
So(s.remoteAddr, ShouldEqual, "a.b.c.d")
})
})
Convey("When I call setTLSConnectionState()", func() {
tcs := &tls.ConnectionState{}
s.setTLSConnectionState(tcs)
Convey("Then address should be correct", func() {
So(s.tlsConnectionState, ShouldEqual, tcs)
})
})
Convey("When I call setSocket()", func() {
ws := wsc.NewMockWebsocket(context.TODO())
s.setConn(ws)
Convey("Then ws should be correct", func() {
So(s.conn, ShouldEqual, ws)
})
})
Convey("When I call Cookie()", func() {
s.cookies = []*http.Cookie{
{
Name: "toto",
Value: "hey",
},
}
Convey("Then Cookie on existing key should be correct", func() {
v, err := s.Cookie("toto")
So(v.Value, ShouldEqual, "hey")
So(err, ShouldBeNil)
})
Convey("Then Cookie on existing non existing should be correct", func() {
v, err := s.Cookie("titi")
So(v, ShouldBeNil)
So(err, ShouldEqual, http.ErrNoCookie)
})
})
})
}
func TestWSPushSession_listen(t *testing.T) {
Convey("Given I have a push session", t, FailureHalts, func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
unregistered := make(chan bool, 10)
s := newWSPushSession(
(&http.Request{URL: &url.URL{}}).WithContext(ctx),
config{},
func(i *wsPushSession) {
unregistered <- true
},
elemental.EncodingTypeMSGPACK,
elemental.EncodingTypeMSGPACK,
)
conn := wsc.NewMockWebsocket(ctx)
s.setConn(conn)
testEvent := elemental.NewEvent(elemental.EventUpdate, testmodel.NewList())
Convey("When I simulate an incoming event that is not filtered out", func() {
go s.listen()
s.DirectPush(testEvent)
var data []byte
select {
case data = <-conn.LastWrite():
case <-ctx.Done():
panic("test: did not receive data in time")
}
Convey("Then the websocket should send the event", func() {
r, _ := elemental.Encode(elemental.EncodingTypeMSGPACK, testEvent)
So(data, ShouldResemble, r)
})
})
Convey("Verify error event - when the client sends a push config which declares a filter on an undeclared identity", func() {
// TL;DR
//
// This test ensures that the server does NOT the socket connection in the event that the:
// • client connects to the push server with 'enableErrors' query param to indicate it can handle error events
// • client sends an invalid push config message - in this case, they declare an identity filter on an
// undeclared identity.
//
// In such a scenario, the push server should emit an error event with a clear description of the error.
// IMPORTANT: adjust the test session to make it look like the client connected to the server w/ the special query param
// to indicate to the server that it can handle error events.
s.parameters.Add(enableErrorsQueryParam, "true")
go s.listen()
testIdentity := "identity-one"
pc := elemental.NewPushConfig()
pc.FilterIdentity(testIdentity)
pc.IdentityFilters = map[string]string{
// notice how identity-two has NOT been declared
"identity-two": elemental.NewFilterComposer().
WithKey("someAttr").
Exists().
Done().
String(),
}
rawPushConfig, err := elemental.Encode(elemental.EncodingTypeMSGPACK, pc)
So(err, ShouldBeNil)
conn.NextRead(rawPushConfig)
// When the client is connected to the push server w/ error event support mode, in the event of an error the server
// should NOT close the socket. Let's verify that the socket was not closed...
var closeErr error
select {
case closeErr = <-conn.Done():
case <-time.After(500 * time.Millisecond):
}
var unregisterWasCalled bool
select {
case unregisterWasCalled = <-unregistered:
default:
}
So(closeErr, ShouldBeNil)
So(unregisterWasCalled, ShouldBeFalse)
So(s.inErrorState(), ShouldBeTrue)
// An error event should be sent to the client notifying them what was wrong with their push config message
var rawEvent []byte
select {
case rawEvent = <-conn.LastWrite():
case <-time.After(500 * time.Millisecond):
}
var event elemental.Event
So(elemental.Decode(s.encodingWrite, rawEvent, &event), ShouldBeNil)
So(event.Type, ShouldEqual, elemental.EventError)
So(event.Identity, ShouldEqual, "")
var eventData []byte
switch event.Encoding {
case elemental.EncodingTypeMSGPACK:
eventData = event.RawData
So(event.JSONData, ShouldBeNil)
case elemental.EncodingTypeJSON:
eventData = event.JSONData
So(event.RawData, ShouldBeNil)
}
var elemErr elemental.Error
So(elemental.Decode(event.Encoding, eventData, &elemErr), ShouldBeNil)
So(elemErr.Title, ShouldEqual, "Bad request")
So(elemErr.Description, ShouldContainSubstring, "elemental: cannot declare an identity filter on \"identity-two\" as that was not declared in 'Identities'")
So(elemErr.Data, ShouldResemble, map[string]any{
"pushconfig": "filters",
})
})
Convey("Verify error event - when the client sends a push config with a filter that cannot be parsed", func() {
// IMPORTANT: adjust the test session to make it look like the client connected to the server w/ the special query param
// to indicate to the server that it can handle error events.
s.parameters.Add(enableErrorsQueryParam, "true")
go s.listen()
testIdentity := "identity-one"
pc := elemental.NewPushConfig()
pc.FilterIdentity(testIdentity)
pc.IdentityFilters = map[string]string{
testIdentity: "this-will-not-parse",
}
rawPushConfig, err := elemental.Encode(elemental.EncodingTypeMSGPACK, pc)
So(err, ShouldBeNil)
conn.NextRead(rawPushConfig)
// When the client is connected to the push server w/ error event support mode, in the event of an error the server
// should NOT close the socket. Let's verify that the socket was not closed...
var closeErr error
select {
case closeErr = <-conn.Done():
case <-time.After(500 * time.Millisecond):
}
var unregisterWasCalled bool
select {
case unregisterWasCalled = <-unregistered:
default:
}
So(closeErr, ShouldBeNil)
So(unregisterWasCalled, ShouldBeFalse)
So(s.inErrorState(), ShouldBeTrue)
// An error event should be sent to the client notifying them what was wrong with their push config message
var rawEvent []byte
select {
case rawEvent = <-conn.LastWrite():
case <-time.After(500 * time.Millisecond):
}
var event elemental.Event
So(elemental.Decode(s.encodingWrite, rawEvent, &event), ShouldBeNil)
So(event.Type, ShouldEqual, elemental.EventError)
So(event.Identity, ShouldEqual, "")
var eventData []byte
switch event.Encoding {
case elemental.EncodingTypeMSGPACK:
eventData = event.RawData
So(event.JSONData, ShouldBeNil)
case elemental.EncodingTypeJSON:
eventData = event.JSONData
So(event.RawData, ShouldBeNil)
}
var elemErr elemental.Error
So(elemental.Decode(event.Encoding, eventData, &elemErr), ShouldBeNil)
So(elemErr.Title, ShouldEqual, "Bad request")
So(elemErr.Description, ShouldContainSubstring, "elemental: unable to parse filter \"this-will-not-parse\": invalid operator")
So(elemErr.Data, ShouldResemble, map[string]any{
"pushconfig": "filters",
})
})
Convey("Verify error event - when the client sends a push config with a filter utilizing an unsupported comparator", func() {
// IMPORTANT: adjust the test session to make it look like the client connected to the server w/ the special query param
// to indicate to the server that it can handle error events.
s.parameters.Add(enableErrorsQueryParam, "true")
go s.listen()
testIdentity := "identity-one"
pc := elemental.NewPushConfig()
pc.FilterIdentity(testIdentity)
pc.IdentityFilters = map[string]string{
testIdentity: elemental.NewFilterComposer().
WithKey("someAttr").
Contains(1, 2, 3).
Done().
String(),
}
rawPushConfig, err := elemental.Encode(elemental.EncodingTypeMSGPACK, pc)
So(err, ShouldBeNil)
conn.NextRead(rawPushConfig)
// When the client is connected to the push server w/ error event support mode, in the event of an error the server
// should NOT close the socket. Let's verify that the socket was not closed...
var closeErr error
select {
case closeErr = <-conn.Done():
case <-time.After(500 * time.Millisecond):
}
So(closeErr, ShouldBeNil)
var unregisterWasCalled bool
select {
case unregisterWasCalled = <-unregistered:
default:
}
So(unregisterWasCalled, ShouldBeFalse)
So(s.inErrorState(), ShouldBeTrue)
// An error event should be sent to the client notifying them what was wrong with their push config message
var rawEvent []byte
select {
case rawEvent = <-conn.LastWrite():
case <-time.After(500 * time.Millisecond):
}
var event elemental.Event
So(elemental.Decode(s.encodingWrite, rawEvent, &event), ShouldBeNil)
So(event.Type, ShouldEqual, elemental.EventError)
So(event.Identity, ShouldEqual, "")
var eventData []byte
switch event.Encoding {
case elemental.EncodingTypeMSGPACK:
eventData = event.RawData
So(event.JSONData, ShouldBeNil)
case elemental.EncodingTypeJSON:
eventData = event.JSONData
So(event.RawData, ShouldBeNil)
}
var elemErr elemental.Error
So(elemental.Decode(event.Encoding, eventData, &elemErr), ShouldBeNil)
So(elemErr.Title, ShouldEqual, "Bad request")
So(elemErr.Description, ShouldContainSubstring, "unsupported comparator: CONTAINS")
So(elemErr.Data, ShouldResemble, map[string]any{
"pushconfig": "filters",
})
})
Convey("Verify error event - when the client sends a message that cannot be de-serialized into an elemental.PushConfig", func() {
// IMPORTANT: adjust the test session to make it look like the client connected to the server w/ the special query param
// to indicate to the server that it can handle error events.
s.parameters.Add(enableErrorsQueryParam, "true")
go s.listen()
conn.NextRead([]byte("THIS WON'T DE-SERIALIZE INTO AN PUSH CONFIG MESSAGE"))
// When the client is connected to the push server w/ error event support mode, in the event of an error the server
// should NOT close the socket. Let's verify that the socket was not closed...
var closeErr error
select {
case closeErr = <-conn.Done():
case <-time.After(500 * time.Millisecond):
}
So(closeErr, ShouldBeNil)
var unregisterWasCalled bool
select {
case unregisterWasCalled = <-unregistered:
default:
}
So(unregisterWasCalled, ShouldBeFalse)
So(s.inErrorState(), ShouldBeTrue)
// An error event should be sent to the client notifying them what was wrong with their message
var rawEvent []byte
select {
case rawEvent = <-conn.LastWrite():
case <-time.After(500 * time.Millisecond):
}
var event elemental.Event
So(elemental.Decode(s.encodingWrite, rawEvent, &event), ShouldBeNil)
So(event.Type, ShouldEqual, elemental.EventError)
So(event.Identity, ShouldEqual, "")
var eventData []byte
switch event.Encoding {
case elemental.EncodingTypeMSGPACK:
eventData = event.RawData
So(event.JSONData, ShouldBeNil)
case elemental.EncodingTypeJSON:
eventData = event.JSONData
So(event.RawData, ShouldBeNil)
}
var err elemental.Error
So(elemental.Decode(event.Encoding, eventData, &err), ShouldBeNil)
So(err.Title, ShouldEqual, "Bad request")
So(err.Description, ShouldContainSubstring, "could not decode message into *elemental.PushConfig")
So(err.Data, ShouldBeNil)
})
Convey("Verify client can get out of error state if they pass in another valid (push config) message", func() {
// IMPORTANT: adjust the test session to make it look like the client connected to the server w/ the special query param
// to indicate to the server that it can handle error events.
s.parameters.Add(enableErrorsQueryParam, "true")
go s.listen()
// STEP 1: let's get the client into an error state first
conn.NextRead([]byte("THIS WON'T DE-SERIALIZE INTO AN PUSH CONFIG MESSAGE"))
// When the client is connected to the push server w/ error event support mode, in the event of an error the server
// should NOT close the socket. Let's verify that the socket was not closed...
var closeErr error
select {
case closeErr = <-conn.Done():
case <-time.After(500 * time.Millisecond):
}
So(closeErr, ShouldBeNil)
var unregisterWasCalled bool
select {
case unregisterWasCalled = <-unregistered:
default:
}
So(unregisterWasCalled, ShouldBeFalse)
So(s.inErrorState(), ShouldBeTrue)
// An error event should be sent to the client notifying them what was wrong with their message
var rawEvent []byte
select {
case rawEvent = <-conn.LastWrite():
case <-time.After(500 * time.Millisecond):
}
var event elemental.Event
So(elemental.Decode(s.encodingWrite, rawEvent, &event), ShouldBeNil)
So(event.Type, ShouldEqual, elemental.EventError)
// STEP 2: now let's send another message to the push server that is valid
testIdentity := "identity-one"
pc := elemental.NewPushConfig()
pc.FilterIdentity(testIdentity)
rawPushConfig, err := elemental.Encode(elemental.EncodingTypeMSGPACK, pc)
So(err, ShouldBeNil)
conn.NextRead(rawPushConfig)
select {
case closeErr = <-conn.Done():
case <-time.After(500 * time.Millisecond):
}
// STEP 3: the session should be happy again \o/ yay
So(closeErr, ShouldBeNil)
So(s.inErrorState(), ShouldBeFalse)
})
Convey("When the client sends a push config with a filter that cannot be parsed", func() {
go s.listen()
testIdentity := "identity-one"
pc := elemental.NewPushConfig()
pc.FilterIdentity(testIdentity)
pc.IdentityFilters = map[string]string{
testIdentity: "this-will-not-parse",
}
rawPushConfig, err := elemental.Encode(elemental.EncodingTypeMSGPACK, pc)
Convey("should be able to encode a semantically invalid push config", func() {
So(err, ShouldBeNil)
})
conn.NextRead(rawPushConfig)
var closeErr error
select {
case closeErr = <-conn.Done():
case <-time.After(500 * time.Millisecond):
}
Convey("Then an error should be received from the channel returned from the connection's Done() method", func() {
So(closeErr, ShouldNotBeNil)
Convey("error copy should include the close code indicating why the socket was closed", func() {
So(closeErr.Error(), ShouldContainSubstring, fmt.Sprintf("%d", websocket.CloseUnsupportedData))
})
Convey("the current push config should be nil", func() {
So(s.currentPushConfig(), ShouldBeNil)
})
})
Convey("The unregister func should have been called", func() {
var ok bool
select {
case ok = <-unregistered:
case <-time.After(500 * time.Millisecond):
}
So(ok, ShouldBeTrue)
})
})
Convey("When the client sends a push config with a filter on an identity that is NOT declared", func() {
go s.listen()
testIdentity := "identity-one"
identityFilter := elemental.NewFilterComposer().
WithKey("environment").
Equals("production").
Done()
pc := elemental.NewPushConfig()
pc.FilterIdentity(testIdentity)
pc.IdentityFilters = map[string]string{
// notice how the identity filter below is on an identity that is not declared in the PushConfig's 'Identities'
// attribute - it only contains "identity-one"
"undeclared-identity": identityFilter.String(),
}
rawPushConfig, err := elemental.Encode(elemental.EncodingTypeMSGPACK, pc)
Convey("should be able to encode the push config", func() {
So(err, ShouldBeNil)
})
conn.NextRead(rawPushConfig)
var closeErr error
select {
case closeErr = <-conn.Done():
case <-time.After(500 * time.Millisecond):
}
Convey("Then an error should be received from the channel returned from the connection's Done() method", func() {
So(closeErr, ShouldNotBeNil)
Convey("error copy should include the close code indicating why the socket was closed", func() {
So(closeErr.Error(), ShouldContainSubstring, fmt.Sprintf("%d", websocket.CloseUnsupportedData))
})
Convey("the current push config should be nil", func() {
So(s.currentPushConfig(), ShouldBeNil)
})
})
Convey("The unregister func should have been called", func() {
var ok bool
select {
case ok = <-unregistered:
case <-time.After(500 * time.Millisecond):
}
So(ok, ShouldBeTrue)
})
})
Convey("When the client sends a push config with a valid identity filter", func() {
go s.listen()
testIdentity := "identity-one"
identityFilter := elemental.NewFilterComposer().
WithKey("environment").
Equals("production").
Done()
pc := elemental.NewPushConfig()
pc.FilterIdentity(testIdentity)
pc.IdentityFilters = map[string]string{
testIdentity: identityFilter.String(),
}
rawPushConfig, err := elemental.Encode(elemental.EncodingTypeMSGPACK, pc)
Convey("should be able to encode the push config used in the test", func() {
So(err, ShouldBeNil)
})
conn.NextRead(rawPushConfig)
var closeErr error
select {
case closeErr = <-conn.Done():
case <-time.After(500 * time.Millisecond):
}
Convey("Then no error should be returned from the channel returned by calling the connection's Done() method", func() {
So(closeErr, ShouldBeNil)
Convey("the current push config should not be nil", func() {
pc := s.currentPushConfig()
So(pc, ShouldNotBeNil)
So(pc.String(), ShouldEqual, `<pushconfig identities:map[identity-one:[]] identityfilters:map[identity-one:environment == "production"]>`)
Convey("the push config should contain the parsed identity filter", func() {
filter, found := pc.FilterForIdentity(testIdentity)
So(found, ShouldBeTrue)
So(filter.String(), ShouldEqual, identityFilter.String())
})
})
})
})
Convey("When I simulate an incoming event that is manually filtered out", func() {
go s.listen()
f := elemental.NewPushConfig()
f.FilterIdentity("not-list")
s.setCurrentPushConfig(f)
s.DirectPush(testEvent)
var data []byte
select {
case data = <-conn.LastWrite():
case <-time.After(800 * time.Millisecond):
}
Convey("Then the websocket should not send the event", func() {
So(data, ShouldBeNil)
})
})
Convey("When I simulate an incoming event that is older than the session", func() {
go s.listen()
testEvent.Timestamp = time.Now().Add(-1 * time.Hour)
s.DirectPush(testEvent)
var data []byte
select {
case data = <-conn.LastWrite():
case <-time.After(800 * time.Millisecond):
}
Convey("Then the websocket should not send the event", func() {
So(data, ShouldBeNil)
})
})
Convey("When I simulate an incoming event with broken json", func() {
go s.listen()
s.DirectPush(testEvent)
var data []byte
select {
case data = <-conn.LastWrite():
case <-ctx.Done():
panic("test: did not receive data in time")
}
Convey("Then the websocket should send the event", func() {
r, _ := elemental.Encode(elemental.EncodingTypeMSGPACK, testEvent)
So(data, ShouldResemble, r)
})
})
Convey("When I send a valid filter in the websocket", func() {
go s.listen()
s.encodingRead = elemental.EncodingTypeJSON
s.encodingWrite = elemental.EncodingTypeJSON
conn.NextRead([]byte(`{"identities":{"not-list": null}}`))
<-time.After(300 * time.Millisecond)