-
Notifications
You must be signed in to change notification settings - Fork 325
/
API.hs
4560 lines (4142 loc) · 194 KB
/
API.hs
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
{-# LANGUAGE OverloadedRecordDot #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
-- This file is part of the Wire Server implementation.
--
-- Copyright (C) 2022 Wire Swiss GmbH <opensource@wire.com>
--
-- This program is free software: you can redistribute it and/or modify it under
-- the terms of the GNU Affero General Public License as published by the Free
-- Software Foundation, either version 3 of the License, or (at your option) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
-- You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see <https://www.gnu.org/licenses/>.
module API
( tests,
)
where
import qualified API.CustomBackend as CustomBackend
import qualified API.Federation as Federation
import API.Federation.Util
import qualified API.MLS
import qualified API.MessageTimer as MessageTimer
import qualified API.Roles as Roles
import API.SQS
import qualified API.Teams as Teams
import qualified API.Teams.Feature as TeamFeature
import qualified API.Teams.LegalHold as Teams.LegalHold
import qualified API.Teams.LegalHold.DisabledByDefault
import API.Util
import qualified API.Util as Util
import API.Util.TeamFeature as TeamFeatures
import qualified API.Util.TeamFeature as Util
import Bilge hiding (head, timeout)
import qualified Bilge
import Bilge.Assert
import Control.Arrow
import qualified Control.Concurrent.Async as Async
import Control.Exception (throw)
import Control.Lens (at, ix, preview, view, (.~), (?~))
import Control.Monad.Trans.Maybe
import Data.Aeson hiding (json)
import qualified Data.ByteString as BS
import Data.ByteString.Conversion
import qualified Data.Code as Code
import Data.Domain
import Data.Either.Extra (eitherToMaybe)
import Data.Id
import Data.Json.Util (toBase64Text, toUTCTimeMillis)
import Data.List.NonEmpty (NonEmpty (..))
import Data.List1 hiding (head)
import qualified Data.List1 as List1
import qualified Data.Map.Strict as Map
import Data.Misc
import Data.Qualified
import Data.Range
import qualified Data.Set as Set
import Data.Singletons
import qualified Data.Text as T
import qualified Data.Text.Ascii as Ascii
import Data.Time.Clock (getCurrentTime)
import Federator.Discovery (DiscoveryFailure (..))
import Federator.MockServer
import Galley.API.Mapping
import Galley.Options (optFederator)
import Galley.Types.Conversations.Members
import Imports
import qualified Network.HTTP.Types.Status as HTTP
import Network.Wai.Utilities.Error
import Test.QuickCheck (arbitrary, generate)
import Test.Tasty
import Test.Tasty.Cannon (TimeoutUnit (..), (#))
import qualified Test.Tasty.Cannon as WS
import Test.Tasty.HUnit
import TestHelpers
import TestSetup
import Util.Options (Endpoint (Endpoint))
import Wire.API.Connection
import Wire.API.Conversation
import Wire.API.Conversation.Action
import Wire.API.Conversation.Code hiding (Value)
import Wire.API.Conversation.Protocol
import Wire.API.Conversation.Role
import Wire.API.Conversation.Typing
import Wire.API.Event.Conversation
import Wire.API.Federation.API
import qualified Wire.API.Federation.API.Brig as F
import Wire.API.Federation.API.Common
import Wire.API.Federation.API.Galley
import qualified Wire.API.Federation.API.Galley as F
import Wire.API.Internal.Notification
import Wire.API.Message
import qualified Wire.API.Message as Message
import Wire.API.Routes.Internal.Galley.ConversationsIntra
import Wire.API.Routes.MultiTablePaging
import Wire.API.Routes.Version
import Wire.API.Routes.Versioned
import qualified Wire.API.Team.Feature as Public
import qualified Wire.API.Team.Member as Teams
import Wire.API.User
import Wire.API.User.Client
import Wire.API.UserMap (UserMap (..))
tests :: IO TestSetup -> TestTree
tests s =
testGroup
"Galley integration tests"
[ Teams.LegalHold.tests s,
API.Teams.LegalHold.DisabledByDefault.tests s,
mainTests,
Teams.tests s,
MessageTimer.tests s,
Roles.tests s,
CustomBackend.tests s,
TeamFeature.tests s,
Federation.tests s,
API.MLS.tests s
]
where
mainTests =
testGroup
"Main Conversations API"
[ test s "status" status,
test s "metrics" metrics,
test s "fetch conversation by qualified ID (v2)" testGetConvQualifiedV2,
test s "create Proteus conversation" postProteusConvOk,
test s "create conversation with remote users" (postConvWithRemoteUsersOk $ Set.fromList [rb1, rb2]),
test s "create conversation with remote users (some unreachable)" (postConvWithRemoteUsersOk $ Set.fromList [rb1, rb2, rb3]),
test s "get empty conversations" getConvsOk,
test s "get conversations by ids" getConvsOk2,
test s "fail to get >500 conversations with v2 API" getConvsFailMaxSizeV2,
test s "get conversation ids with v2 API" testGetConvIdsV2,
test s "list conversation ids" testListConvIds,
test s "paginate through conversation ids with v2 API" paginateConvIds,
test s "paginate through /conversations/list-ids" paginateConvListIds,
test s "paginate through /conversations/list-ids - page ending at locals and remote domain" paginateConvListIdsPageEndingAtLocalsAndDomain,
test s "fail to get >1000 conversation ids" getConvIdsFailMaxSize,
test s "fail to get >1000 conversation ids with v2 API" getConvIdsFailMaxSizeV2,
test s "page through conversations" getConvsPagingOk,
test s "fail to create conversation when not connected" postConvFailNotConnected,
test s "fail to create conversation with qualified users when not connected" postConvQualifiedFailNotConnected,
test s "M:N conversation creation with N - 1 invitees should be allowed" postConvLimitOk,
test s "M:N conversation creation must have <N members" postConvFailNumMembers,
test s "M:N conversation creation must have <N qualified members" postConvQualifiedFailNumMembers,
test s "fail to create conversation when blocked" postConvFailBlocked,
test s "fail to create conversation when blocked by qualified member" postConvQualifiedFailBlocked,
test s "fail to create conversation with remote users when remote user is not connected" postConvQualifiedNoConnection,
test s "fail to create team conversation with remote users when remote user is not connected" postTeamConvQualifiedNoConnection,
test s "create conversation with optional remote users when remote user's domain doesn't exist" postConvQualifiedNonExistentDomain,
test s "fail to create conversation with remote users when federation not configured" postConvQualifiedFederationNotEnabled,
test s "create self conversation" postSelfConvOk,
test s "create 1:1 conversation" postO2OConvOk,
test s "fail to create 1:1 conversation with yourself" postConvO2OFailWithSelf,
test s "create connect conversation" postConnectConvOk,
test s "create connect conversation with email" postConnectConvOk2,
test s "upgrade connect/invite conversation" putConvAcceptOk,
test s "upgrade conversation retries" putConvAcceptRetry,
test s "create mutual connect conversation" postMutualConnectConvOk,
test s "repeat / cancel connect requests" postRepeatConnectConvCancel,
test s "block/unblock a connect/1-1 conversation" putBlockConvOk,
test s "get conversation" getConvOk,
test s "get qualified conversation" getConvQualifiedOk,
test s "conversation meta access" accessConvMeta,
test s "add members" postMembersOk,
test s "add existing members" postMembersOk2,
test s "add past members" postMembersOk3,
test s "add guest forbidden when no guest access role" postMembersFailNoGuestAccess,
test s "generate guest link forbidden when no guest or non-team-member access role" generateGuestLinkFailIfNoNonTeamMemberOrNoGuestAccess,
test s "fail to add members when not connected" postMembersFail,
test s "fail to add too many members" postTooManyMembersFail,
test s "add remote members" testAddRemoteMember,
test s "delete conversation with remote members" testDeleteTeamConversationWithRemoteMembers,
test s "delete conversation with unavailable remote members" testDeleteTeamConversationWithUnavailableRemoteMembers,
test s "get conversations/:domain/:cnv - local" testGetQualifiedLocalConv,
test s "get conversations/:domain/:cnv - local, not found" testGetQualifiedLocalConvNotFound,
test s "get conversations/:domain/:cnv - local, not participating" testGetQualifiedLocalConvNotParticipating,
test s "get conversations/:domain/:cnv - remote" testGetQualifiedRemoteConv,
test s "get conversations/:domain/:cnv - remote, not found" testGetQualifiedRemoteConvNotFound,
test s "get conversations/:domain/:cnv - remote, not found on remote" testGetQualifiedRemoteConvNotFoundOnRemote,
test s "post conversations/list/v2" testBulkGetQualifiedConvs,
test s "add remote members on invalid domain" testAddRemoteMemberInvalidDomain,
test s "add remote members when federation isn't enabled" testAddRemoteMemberFederationDisabled,
test s "add remote members when federator is unavailable" testAddRemoteMemberFederationUnavailable,
test s "delete conversations/:domain/:cnv/members/:domain/:usr - fail, self conv" deleteMembersQualifiedFailSelf,
test s "delete conversations/:domain:/cnv/members/:domain/:usr - fail, 1:1 conv" deleteMembersQualifiedFailO2O,
test s "delete conversations/:domain/:cnv/members/:domain/:usr - local conv with all locals" deleteMembersConvLocalQualifiedOk,
test s "delete conversations/:domain/:cnv/members/:domain/:usr - local conv with locals and remote, delete local" deleteLocalMemberConvLocalQualifiedOk,
test s "delete conversations/:domain/:cnv/members/:domain/:usr - local conv with locals and remote, delete remote" deleteRemoteMemberConvLocalQualifiedOk,
test s "delete conversations/:domain/:cnv/members/:domain/:usr - local conv with locals and remote, delete unavailable remote" deleteUnavailableRemoteMemberConvLocalQualifiedOk,
test s "delete conversations/:domain/:cnv/members/:domain/:usr - remote conv, leave conv" leaveRemoteConvQualifiedOk,
test s "delete conversations/:domain/:cnv/members/:domain/:usr - remote conv, leave conv, non-existent" leaveNonExistentRemoteConv,
test s "delete conversations/:domain/:cnv/members/:domain/:usr - remote conv, leave conv, denied" leaveRemoteConvDenied,
test s "delete conversations/:domain/:cnv/members/:domain/:usr - remote conv, remove local user, fail" removeLocalMemberConvQualifiedFail,
test s "delete conversations/:domain/:cnv/members/:domain/:usr - remote conv, remove remote user, fail" removeRemoteMemberConvQualifiedFail,
test s "rename conversation (deprecated endpoint)" putConvDeprecatedRenameOk,
test s "rename conversation" putConvRenameOk,
test s "rename qualified conversation" putQualifiedConvRenameOk,
test s "rename qualified conversation with remote members" putQualifiedConvRenameWithRemotesOk,
test s "rename qualified conversation with unavailable remote" putQualifiedConvRenameWithRemotesUnavailable,
test s "rename qualified conversation failure" putQualifiedConvRenameFailure,
test s "other member update role" putOtherMemberOk,
test s "qualified other member update role" putQualifiedOtherMemberOk,
test s "member update (otr mute)" putMemberOtrMuteOk,
test s "member update (otr archive)" putMemberOtrArchiveOk,
test s "member update (hidden)" putMemberHiddenOk,
test s "member update (everything b)" putMemberAllOk,
test s "remote conversation member update (otr mute)" putRemoteConvMemberOtrMuteOk,
test s "remote conversation member update (otr archive)" putRemoteConvMemberOtrArchiveOk,
test s "remote conversation member update (otr hidden)" putRemoteConvMemberHiddenOk,
test s "remote conversation member update (everything)" putRemoteConvMemberAllOk,
test s "conversation receipt mode update" putReceiptModeOk,
test s "conversation receipt mode update with remote members" putReceiptModeWithRemotesOk,
test s "conversation receipt mode update with unavailable remote members" putReceiptModeWithRemotesUnavailable,
test s "remote conversation receipt mode update" putRemoteReceiptModeOk,
test s "leave connect conversation" leaveConnectConversation,
test s "post conversations/:cnv/otr/message: message delivery and missing clients" postCryptoMessageVerifyMsgSentAndRejectIfMissingClient,
test s "post conversations/:cnv/otr/message: mismatch and prekey fetching" postCryptoMessageVerifyRejectMissingClientAndRepondMissingPrekeysJson,
test s "post conversations/:cnv/otr/message: mismatch with protobuf" postCryptoMessageVerifyRejectMissingClientAndRepondMissingPrekeysProto,
test s "post conversations/:cnv/otr/message: unknown sender client" postCryptoMessageNotAuthorizeUnknownClient,
test s "post conversations/:cnv/otr/message: ignore_missing and report_missing" postCryptoMessageVerifyCorrectResponseIfIgnoreAndReportMissingQueryParam,
test s "post message qualified - local owning backend - success" postMessageQualifiedLocalOwningBackendSuccess,
test s "post message qualified - local owning backend - missing clients" postMessageQualifiedLocalOwningBackendMissingClients,
test s "post message qualified - local owning backend - redundant and deleted clients" postMessageQualifiedLocalOwningBackendRedundantAndDeletedClients,
test s "post message qualified - local owning backend - ignore missing" postMessageQualifiedLocalOwningBackendIgnoreMissingClients,
test s "post message qualified - local owning backend - failed to send clients" postMessageQualifiedLocalOwningBackendFailedToSendClients,
test s "post message qualified - local owning backend - failed to get clients and failed to send clients" postMessageQualifiedLocalOwningBackendFailedToSendClientsFailingGetUserClients,
test s "post message qualified - remote owning backend - federation failure" postMessageQualifiedRemoteOwningBackendFailure,
test s "post message qualified - remote owning backend - success" postMessageQualifiedRemoteOwningBackendSuccess,
test s "join conversation" postJoinConvOk,
test s "get code-access conversation information" testJoinCodeConv,
test s "join code-access conversation - no password" postJoinCodeConvOk,
test s "join code-access conversation - password" postJoinCodeConvWithPassword,
test s "convert invite to code-access conversation" postConvertCodeConv,
test s "convert code to team-access conversation" postConvertTeamConv,
test s "local and remote guests are removed when access changes" testAccessUpdateGuestRemoved,
test s "local and remote guests are removed when access changes remotes unavailable" testAccessUpdateGuestRemovedRemotesUnavailable,
test s "team member can't join via guest link if access role removed" testTeamMemberCantJoinViaGuestLinkIfAccessRoleRemoved,
test s "cannot join private conversation" postJoinConvFail,
test s "revoke guest links for team conversation" testJoinTeamConvGuestLinksDisabled,
test s "revoke guest links for non-team conversation" testJoinNonTeamConvGuestLinksDisabled,
test s "get code rejected if guest links disabled" testGetCodeRejectedIfGuestLinksDisabled,
test s "post code rejected if guest links disabled" testPostCodeRejectedIfGuestLinksDisabled,
testGroup
"conversation code already exists"
[ test s "existing has no password, requested has no password - 201" postCodeWithoutPasswordExistsWithoutPasswordRequested,
test s "existing has no password, requested has password - 409" postCodeWithoutPasswordExistsWithPasswordRequested,
test s "existing has password, requested has no password - 409" postCodeWithPasswordExistsWithoutPasswordRequested,
test s "existing has password, requested has password - 409" postCodeWithPasswordExistsWithPasswordRequested
],
test s "remove user with only local convs" removeUserNoFederation,
test s "remove user with local and remote convs" removeUser,
test s "iUpsertOne2OneConversation" testAllOne2OneConversationRequests,
test s "post message - reject if missing client" postMessageRejectIfMissingClients,
test s "post message - client that is not in group doesn't receive message" postMessageClientNotInGroupDoesNotReceiveMsg,
test s "get guest links status from foreign team conversation" getGuestLinksStatusFromForeignTeamConv,
testGroup
"Typing indicators"
[ test s "send typing indicators" postTypingIndicators,
test s "send typing indicators without domain" postTypingIndicatorsV2,
test s "send typing indicators with invalid pyaload" postTypingIndicatorsHandlesNonsense
]
]
rb1, rb2, rb3 :: Remote Backend
rb1 =
toRemoteUnsafe
(Domain "c.example.com")
( Backend
{ bReachable = BackendReachable,
bUsers = 2
}
)
rb2 =
toRemoteUnsafe
(Domain "d.example.com")
( Backend
{ bReachable = BackendReachable,
bUsers = 1
}
)
rb3 =
toRemoteUnsafe
(Domain "e.example.com")
( Backend
{ bReachable = BackendUnreachable,
bUsers = 2
}
)
-------------------------------------------------------------------------------
-- API Tests
status :: TestM ()
status = do
g <- viewGalley
get (g . path "/i/status")
!!! const 200 === statusCode
Bilge.head (g . path "/i/status")
!!! const 200 === statusCode
metrics :: TestM ()
metrics = do
g <- viewGalley
get (g . path "/i/metrics") !!! do
const 200 === statusCode
-- Should contain the request duration metric in its output
const (Just "TYPE http_request_duration_seconds histogram") =~= responseBody
testGetConvQualifiedV2 :: TestM ()
testGetConvQualifiedV2 = do
alice <- randomUser
bob <- randomUser
connectUsers alice (list1 bob [])
conv <-
responseJsonError
=<< postConvQualified
alice
Nothing
defNewProteusConv
{ newConvUsers = [bob]
}
<!! const 201 === statusCode
let qcnv = cnvQualifiedId conv
conv' <-
fmap (unVersioned @'V2) . responseJsonError
=<< getConvQualifiedV2 alice qcnv
<!! const 200 === statusCode
liftIO $ conv @=? conv'
postProteusConvOk :: TestM ()
postProteusConvOk = do
c <- view tsCannon
(alice, qalice) <- randomUserTuple
(bob, qbob) <- randomUserTuple
(jane, qjane) <- randomUserTuple
connectUsers alice (list1 bob [jane])
let nameMaxSize = T.replicate 256 "a"
WS.bracketR3 c alice bob jane $ \(wsA, wsB, wsJ) -> do
rsp <-
postConv alice [bob, jane] (Just nameMaxSize) [] Nothing Nothing
<!! const 201 === statusCode
qcid <- assertConv rsp RegularConv alice qalice [qbob, qjane] (Just nameMaxSize) Nothing
let cid = qUnqualified qcid
cvs <- mapM (convView cid) [alice, bob, jane]
liftIO $ mapM_ WS.assertSuccess =<< Async.mapConcurrently (checkWs qalice) (zip cvs [wsA, wsB, wsJ])
where
convView cnv usr = do
r <- getConv usr cnv <!! const 200 === statusCode
unVersioned @'V2 <$> responseJsonError r
checkWs qalice (cnv, ws) = WS.awaitMatch (5 # Second) ws $ \n -> do
ntfTransient n @?= False
let e = List1.head (WS.unpackPayload n)
evtConv e @?= cnvQualifiedId cnv
evtType e @?= ConvCreate
evtFrom e @?= qalice
case evtData e of
EdConversation c' -> assertConvEquals cnv c'
_ -> assertFailure "Unexpected event data"
postConvWithRemoteUsersOk :: Set (Remote Backend) -> TestM ()
postConvWithRemoteUsersOk rbs = do
c <- view tsCannon
(alice, qAlice) <- randomUserTuple
(alex, qAlex) <- randomUserTuple
(amy, qAmy) <- randomUserTuple
connectUsers alice (list1 alex [amy])
(allRemotes, participatingRemotes) <- do
v <- forM (toList rbs) $ \rb -> do
users <- connectBackend alice rb
pure (users, participating rb users)
pure $ foldr (\(a, p) acc -> bimap ((<>) a) ((<>) p) acc) ([], []) v
let nameMaxSize = T.replicate 256 "a"
otherLocals = [qAlex, qAmy]
WS.bracketR3 c alice alex amy $ \(wsAlice, wsAlex, wsAmy) -> do
let joiners = allRemotes <> otherLocals
unreachableBackends =
Set.fromList $
foldMap
( \rb ->
guard (rbReachable rb == BackendUnreachable)
$> tDomain rb
)
rbs
(rsp, federatedRequests) <-
withTempMockFederator' (mockUnreachable unreachableBackends) $
postConvQualified
alice
Nothing
defNewProteusConv
{ newConvName = checked nameMaxSize,
newConvQualifiedUsers = joiners
}
<!! const 201 === statusCode
let shouldBePresent = otherLocals <> participatingRemotes
shouldBePresentSet = Set.fromList (toOtherMember <$> shouldBePresent)
qcid <-
assertConv
rsp
RegularConv
alice
qAlice
shouldBePresent
(Just nameMaxSize)
Nothing
let cid = qUnqualified qcid
cvs <- mapM (convView qcid) [alice, alex, amy]
liftIO $
mapM_ WS.assertSuccess
=<< Async.mapConcurrently (checkWs qAlice) (zip cvs [wsAlice, wsAlex, wsAmy])
liftIO $
-- as many federated requests as remote backends, i.e., one per remote backend
Set.size (Set.fromList $ frTargetDomain <$> federatedRequests) @?= Set.size rbs
let fedReq = head federatedRequests
fedReqBody <- assertRight $ parseFedRequest fedReq
liftIO $ do
length federatedRequests @?= Set.size rbs
F.ccOrigUserId fedReqBody @?= alice
F.ccCnvId fedReqBody @?= cid
F.ccCnvType fedReqBody @?= RegularConv
F.ccCnvAccess fedReqBody @?= [InviteAccess]
F.ccCnvAccessRoles fedReqBody
@?= Set.fromList [TeamMemberAccessRole, NonTeamMemberAccessRole, ServiceAccessRole]
F.ccCnvName fedReqBody @?= Just nameMaxSize
assertBool "Notifying an incorrect set of conversation members" $
shouldBePresentSet `Set.isSubsetOf` F.ccNonCreatorMembers fedReqBody
F.ccMessageTimer fedReqBody @?= Nothing
F.ccReceiptMode fedReqBody @?= Nothing
fedBodies <- forM federatedRequests $ assertRight . parseFedRequest
assertBool "Not all request bodies are equal" (all (fedReqBody ==) fedBodies)
where
mockUnreachable :: Set Domain -> Mock LByteString
mockUnreachable unreachable = do
r <- getRequest
if Set.member (frTargetDomain r) unreachable
then throw (MockErrorResponse HTTP.status503 "Down for maintenance.")
else mockReply ()
connectBackend :: UserId -> Remote Backend -> TestM [Qualified UserId]
connectBackend usr (tDomain &&& bUsers . tUnqualified -> (d, c)) = do
users <- replicateM (fromIntegral c) (randomQualifiedId d)
mapM_ (connectWithRemoteUser usr) users
pure users
participating :: Remote Backend -> [a] -> [a]
participating rb users =
if rbReachable rb == BackendReachable
then users
else []
toOtherMember qid = OtherMember qid Nothing roleNameWireAdmin
convView cnv usr =
responseJsonError =<< getConvQualified usr cnv <!! const 200 === statusCode
checkWs qalice (cnv, ws) = WS.awaitMatch (5 # Second) ws $ \n -> do
ntfTransient n @?= False
let e = List1.head (WS.unpackPayload n)
evtConv e @?= cnvQualifiedId cnv
evtType e @?= ConvCreate
evtFrom e @?= qalice
case evtData e of
EdConversation c' -> assertConvEquals cnv c'
_ -> assertFailure "Unexpected event data"
-- @SF.Separation @TSFI.RESTfulAPI @S2
-- This test verifies whether a message actually gets sent all the way to
-- cannon.
postCryptoMessageVerifyMsgSentAndRejectIfMissingClient :: TestM ()
postCryptoMessageVerifyMsgSentAndRejectIfMissingClient = do
localDomain <- viewFederationDomain
c <- view tsCannon
(alice, ac) <- randomUserWithClient (head someLastPrekeys)
(bob, bc) <- randomUserWithClient (someLastPrekeys !! 1)
(eve, ec) <- randomUserWithClient (someLastPrekeys !! 2)
connectUsers alice (list1 bob [eve])
conv <- decodeConvId <$> postConv alice [bob, eve] (Just "gossip") [] Nothing Nothing
let qalice = Qualified alice localDomain
qconv = Qualified conv localDomain
-- WS receive timeout
let t = 5 # Second
-- Missing eve
let m1 = [(bob, bc, "ciphertext1")]
postOtrMessage id alice ac conv m1 !!! do
const 412 === statusCode
assertMismatch [(eve, Set.singleton ec)] [] []
-- Complete
WS.bracketR2 c bob eve $ \(wsB, wsE) -> do
let m2 = [(bob, bc, toBase64Text "ciphertext2"), (eve, ec, toBase64Text "ciphertext2")]
postOtrMessage id alice ac conv m2 !!! do
const 201 === statusCode
assertMismatch [] [] []
void . liftIO $ WS.assertMatch t wsB (wsAssertOtr qconv qalice ac bc (toBase64Text "ciphertext2"))
void . liftIO $ WS.assertMatch t wsE (wsAssertOtr qconv qalice ac ec (toBase64Text "ciphertext2"))
-- Redundant self
WS.bracketR3 c alice bob eve $ \(wsA, wsB, wsE) -> do
let m3 = [(alice, ac, toBase64Text "ciphertext3"), (bob, bc, toBase64Text "ciphertext3"), (eve, ec, toBase64Text "ciphertext3")]
postOtrMessage id alice ac conv m3 !!! do
const 201 === statusCode
assertMismatch [] [(alice, Set.singleton ac)] []
void . liftIO $ WS.assertMatch t wsB (wsAssertOtr qconv qalice ac bc (toBase64Text "ciphertext3"))
void . liftIO $ WS.assertMatch t wsE (wsAssertOtr qconv qalice ac ec (toBase64Text "ciphertext3"))
-- Alice should not get it
assertNoMsg wsA (wsAssertOtr qconv qalice ac ac (toBase64Text "ciphertext3"))
-- Deleted eve
WS.bracketR2 c bob eve $ \(wsB, wsE) -> do
deleteClient eve ec (Just defPassword) !!! const 200 === statusCode
liftIO $
WS.assertMatch_ (5 # WS.Second) wsE $
wsAssertClientRemoved ec
let m4 = [(bob, bc, toBase64Text "ciphertext4"), (eve, ec, toBase64Text "ciphertext4")]
postOtrMessage id alice ac conv m4 !!! do
const 201 === statusCode
assertMismatch [] [] [(eve, Set.singleton ec)]
void . liftIO $ WS.assertMatch t wsB (wsAssertOtr qconv qalice ac bc (toBase64Text "ciphertext4"))
-- Eve should not get it
assertNoMsg wsE (wsAssertOtr qconv qalice ac ec (toBase64Text "ciphertext4"))
-- Deleted eve & redundant self
WS.bracketR3 c alice bob eve $ \(wsA, wsB, wsE) -> do
let m5 = [(bob, bc, toBase64Text "ciphertext5"), (eve, ec, toBase64Text "ciphertext5"), (alice, ac, toBase64Text "ciphertext5")]
postOtrMessage id alice ac conv m5 !!! do
const 201 === statusCode
assertMismatch [] [(alice, Set.singleton ac)] [(eve, Set.singleton ec)]
void . liftIO $ WS.assertMatch t wsB (wsAssertOtr qconv qalice ac bc (toBase64Text "ciphertext5"))
-- Neither Alice nor Eve should get it
assertNoMsg wsA (wsAssertOtr qconv qalice ac ac (toBase64Text "ciphertext5"))
assertNoMsg wsE (wsAssertOtr qconv qalice ac ec (toBase64Text "ciphertext5"))
-- Missing Bob, deleted eve & redundant self
let m6 = [(eve, ec, toBase64Text "ciphertext6"), (alice, ac, toBase64Text "ciphertext6")]
postOtrMessage id alice ac conv m6 !!! do
const 412 === statusCode
assertMismatch
[(bob, Set.singleton bc)]
[(alice, Set.singleton ac)]
[(eve, Set.singleton ec)]
-- A second client for Bob
bc2 <- randomClient bob (someLastPrekeys !! 3)
-- The first client listens for all messages of Bob
WS.bracketR c bob $ \wsB -> do
let cipher = toBase64Text "ciphertext7"
-- The second client listens only for his own messages
WS.bracketR (c . queryItem "client" (toByteString' bc2)) bob $ \wsB2 -> do
let m7 = [(bob, bc, cipher), (bob, bc2, cipher)]
postOtrMessage id alice ac conv m7 !!! do
const 201 === statusCode
assertMismatch [] [] []
-- Bob's first client gets both messages
void . liftIO $ WS.assertMatch t wsB (wsAssertOtr qconv qalice ac bc cipher)
void . liftIO $ WS.assertMatch t wsB (wsAssertOtr qconv qalice ac bc2 cipher)
-- Bob's second client gets only the message destined for him
void . liftIO $ WS.assertMatch t wsB2 (wsAssertOtr qconv qalice ac bc2 cipher)
liftIO $ assertBool "unexpected equal clients" (bc /= bc2)
assertNoMsg wsB2 (wsAssertOtr qconv qalice ac bc cipher)
-- @END
-- @SF.Separation @TSFI.RESTfulAPI @S2
-- This test verifies basic mismatch behavior of the the JSON endpoint.
postCryptoMessageVerifyRejectMissingClientAndRepondMissingPrekeysJson :: TestM ()
postCryptoMessageVerifyRejectMissingClientAndRepondMissingPrekeysJson = do
(alice, ac) <- randomUserWithClient (head someLastPrekeys)
(bob, bc) <- randomUserWithClient (someLastPrekeys !! 1)
(eve, ec) <- randomUserWithClient (someLastPrekeys !! 2)
connectUsers alice (list1 bob [eve])
conv <- decodeConvId <$> postConv alice [bob, eve] (Just "gossip") [] Nothing Nothing
-- Missing eve
let m = [(bob, bc, toBase64Text "hello bob")]
r1 <-
postOtrMessage id alice ac conv m <!! do
const 412 === statusCode
assertMismatchWithMessage (Just "client mismatch") [(eve, Set.singleton ec)] [] []
let x = responseJsonUnsafeWithMsg "ClientMismatch" r1
-- Fetch all missing clients prekeys
b <- view tsUnversionedBrig
r2 <-
post (b . zUser alice . path "v1/users/prekeys" . json (missingClients x))
<!! const 200 === statusCode
let p = responseJsonUnsafeWithMsg "prekeys" r2 :: UserClientPrekeyMap
liftIO $ do
Map.keys (userClientMap (getUserClientPrekeyMap p)) @=? [eve]
Map.keys <$> Map.lookup eve (userClientMap (getUserClientPrekeyMap p)) @=? Just [ec]
-- @END
-- @SF.Separation @TSFI.RESTfulAPI @S2
-- This test verifies basic mismatch behaviour of the protobuf endpoint.
postCryptoMessageVerifyRejectMissingClientAndRepondMissingPrekeysProto :: TestM ()
postCryptoMessageVerifyRejectMissingClientAndRepondMissingPrekeysProto = do
(alice, ac) <- randomUserWithClient (head someLastPrekeys)
(bob, bc) <- randomUserWithClient (someLastPrekeys !! 1)
(eve, ec) <- randomUserWithClient (someLastPrekeys !! 2)
connectUsers alice (list1 bob [eve])
conv <- decodeConvId <$> postConv alice [bob, eve] (Just "gossip") [] Nothing Nothing
-- Missing eve
let ciphertext = toBase64Text "hello bob"
let m = otrRecipients [(bob, bc, ciphertext)]
r1 <-
postProtoOtrMessage alice ac conv m
<!! const 412 === statusCode
let x = responseJsonUnsafeWithMsg "ClientMismatch" r1
pure r1
!!! assertMismatchWithMessage (Just "client mismatch") [(eve, Set.singleton ec)] [] []
-- Fetch all missing clients prekeys
b <- view tsUnversionedBrig
r2 <-
post (b . zUser alice . path "v1/users/prekeys" . json (missingClients x))
<!! const 200 === statusCode
let p = responseJsonUnsafeWithMsg "prekeys" r2 :: UserClientPrekeyMap
liftIO $ do
Map.keys (userClientMap (getUserClientPrekeyMap p)) @=? [eve]
Map.keys <$> Map.lookup eve (userClientMap (getUserClientPrekeyMap p)) @=? Just [ec]
-- @END
-- | This test verifies behaviour when an unknown client posts the message. Only
-- tests the Protobuf endpoint.
postCryptoMessageNotAuthorizeUnknownClient :: TestM ()
postCryptoMessageNotAuthorizeUnknownClient = do
alice <- randomUser
bob <- randomUser
bc <- randomClient bob (head someLastPrekeys)
connectUsers alice (list1 bob [])
conv <- decodeConvId <$> postConv alice [bob] (Just "gossip") [] Nothing Nothing
-- Unknown client ID => 403
let ciphertext = toBase64Text "hello bob"
let m = otrRecipients [(bob, bc, ciphertext)]
postProtoOtrMessage alice (ClientId "172618352518396") conv m
!!! const 403 === statusCode
-- @SF.Separation @TSFI.RESTfulAPI @S2
-- This test verifies the following scenario.
-- A client sends a message to all clients of a group and one more who is not part of the group.
-- The server must not send this message to client ids not part of the group.
postMessageClientNotInGroupDoesNotReceiveMsg :: TestM ()
postMessageClientNotInGroupDoesNotReceiveMsg = do
localDomain <- viewFederationDomain
cannon <- view tsCannon
(alice, ac) <- randomUserWithClient (head someLastPrekeys)
(bob, bc) <- randomUserWithClient (someLastPrekeys !! 1)
(eve, ec) <- randomUserWithClient (someLastPrekeys !! 2)
(chad, cc) <- randomUserWithClient (someLastPrekeys !! 3)
connectUsers alice (list1 bob [eve, chad])
conversationWithAllButChad <- decodeConvId <$> postConv alice [bob, eve] (Just "gossip") [] Nothing Nothing
let qalice = Qualified alice localDomain
qconv = Qualified conversationWithAllButChad localDomain
WS.bracketR3 cannon bob eve chad $ \(wsBob, wsEve, wsChad) -> do
let msgToAllIncludingChad = [(bob, bc, toBase64Text "ciphertext2"), (eve, ec, toBase64Text "ciphertext2"), (chad, cc, toBase64Text "ciphertext2")]
postOtrMessage id alice ac conversationWithAllButChad msgToAllIncludingChad !!! const 201 === statusCode
let checkBobGetsMsg = void . liftIO $ WS.assertMatch (5 # Second) wsBob (wsAssertOtr qconv qalice ac bc (toBase64Text "ciphertext2"))
let checkEveGetsMsg = void . liftIO $ WS.assertMatch (5 # Second) wsEve (wsAssertOtr qconv qalice ac ec (toBase64Text "ciphertext2"))
let checkChadDoesNotGetMsg = assertNoMsg wsChad (wsAssertOtr qconv qalice ac ac (toBase64Text "ciphertext2"))
checkBobGetsMsg
checkEveGetsMsg
checkChadDoesNotGetMsg
-- @END
-- @SF.Separation @TSFI.RESTfulAPI @S2
-- This test verifies that when a client sends a message not to all clients of a group then the server should reject the message and sent a notification to the sender (412 Missing clients).
-- The test is somewhat redundant because this is already tested as part of other tests already. This is a stand alone test that solely tests the behavior described above.
postMessageRejectIfMissingClients :: TestM ()
postMessageRejectIfMissingClients = do
(sender, senderClient) : allReceivers <- randomUserWithClient `traverse` someLastPrekeys
let (receiver1, receiverClient1) : otherReceivers = allReceivers
connectUsers sender (list1 receiver1 (fst <$> otherReceivers))
conv <- decodeConvId <$> postConv sender (receiver1 : (fst <$> otherReceivers)) (Just "gossip") [] Nothing Nothing
let msgToAllClients = mkMsg "hello!" <$> allReceivers
let msgMissingClients = mkMsg "hello!" <$> drop 1 allReceivers
let checkSendToAllClientShouldBeSuccessful =
postOtrMessage id sender senderClient conv msgToAllClients !!! do
const 201 === statusCode
assertMismatch [] [] []
let checkSendWitMissingClientsShouldFail =
postOtrMessage id sender senderClient conv msgMissingClients !!! do
const 412 === statusCode
assertMismatch [(receiver1, Set.singleton receiverClient1)] [] []
checkSendToAllClientShouldBeSuccessful
checkSendWitMissingClientsShouldFail
where
mkMsg :: ByteString -> (UserId, ClientId) -> (UserId, ClientId, Text)
mkMsg text (userId, clientId) = (userId, clientId, toBase64Text text)
-- @END
-- @SF.Separation @TSFI.RESTfulAPI @S2
-- This test verifies behaviour under various values of ignore_missing and
-- report_missing. Only tests the JSON endpoint.
postCryptoMessageVerifyCorrectResponseIfIgnoreAndReportMissingQueryParam :: TestM ()
postCryptoMessageVerifyCorrectResponseIfIgnoreAndReportMissingQueryParam = do
(alice, ac) <- randomUserWithClient (head someLastPrekeys)
(bob, bc) <- randomUserWithClient (someLastPrekeys !! 1)
(chad, cc) <- randomUserWithClient (someLastPrekeys !! 2)
(eve, ec) <- randomUserWithClient (someLastPrekeys !! 3)
connectUsers alice (list1 bob [chad, eve])
conv <- decodeConvId <$> postConv alice [bob, chad, eve] (Just "gossip") [] Nothing Nothing
-- Missing eve
let msgMissingChadAndEve = [(bob, bc, toBase64Text "hello bob")]
let m' = otrRecipients [(bob, bc, toBase64Text "hello bob")]
-- These three are equivalent (i.e. report all missing clients)
postOtrMessage id alice ac conv msgMissingChadAndEve
!!! const 412 === statusCode
postOtrMessage (queryItem "ignore_missing" "false") alice ac conv msgMissingChadAndEve
!!! const 412 === statusCode
postOtrMessage (queryItem "report_missing" "true") alice ac conv msgMissingChadAndEve
!!! const 412 === statusCode
-- These two are equivalent (i.e. ignore all missing clients)
postOtrMessage (queryItem "ignore_missing" "true") alice ac conv msgMissingChadAndEve
!!! const 201 === statusCode
postOtrMessage (queryItem "report_missing" "false") alice ac conv msgMissingChadAndEve
!!! const 201 === statusCode
-- Report missing clients of a specific user only
postOtrMessage (queryItem "report_missing" (toByteString' bob)) alice ac conv msgMissingChadAndEve
!!! const 201 === statusCode
-- Let's make sure that the same logic using protobuf in the body works too
postProtoOtrMessage' Nothing (queryItem "report_missing" (toByteString' bob)) alice ac conv m'
!!! const 201 === statusCode
-- Body takes precedence
postOtrMessage' (Just [bob]) (queryItem "report_missing" (listToByteString [eve, chad])) alice ac conv msgMissingChadAndEve
!!! const 201 === statusCode
-- Set it only in the body of the message
postOtrMessage' (Just [bob]) id alice ac conv msgMissingChadAndEve
!!! const 201 === statusCode
-- Let's make sure that protobuf works too, when specified in the body only
postProtoOtrMessage' (Just [bob]) id alice ac conv m'
!!! const 201 === statusCode
reportEveAndChad <-
-- send message with no clients
postOtrMessage (queryItem "report_missing" (listToByteString [eve, chad])) alice ac conv []
<!! const 412 === statusCode
pure reportEveAndChad
!!! assertMismatchWithMessage (Just "client mismatch") [(eve, Set.singleton ec), (chad, Set.singleton cc)] [] []
-- Ignore missing clients of a specific user only
postOtrMessage (queryItem "ignore_missing" (listToByteString [chad, eve])) alice ac conv msgMissingChadAndEve
!!! const 201 === statusCode
ignoreEveAndChadButNotBob <-
postOtrMessage (queryItem "ignore_missing" (listToByteString [chad, eve])) alice ac conv []
<!! const 412 === statusCode
pure ignoreEveAndChadButNotBob
!!! assertMismatchWithMessage (Just "client mismatch") [(bob, Set.singleton bc)] [] []
where
listToByteString = BS.intercalate "," . map toByteString'
-- @END
-- | Sets up a conversation on Backend A known as "owning backend". All user's
-- on this backend have names begining with 'A'. The conversation has a couple
-- of users from backend B and one user from backend C.
--
-- One of the users from Backend A will send the message, it is expected that
-- message will be sent successfully.
postMessageQualifiedLocalOwningBackendSuccess :: TestM ()
postMessageQualifiedLocalOwningBackendSuccess = do
-- WS receive timeout
let t = 5 # Second
-- Cannon for local users
cannon <- view tsCannon
-- Domain which owns the converstaion
owningDomain <- viewFederationDomain
(alice, aliceClient) <- randomUserWithClientQualified (head someLastPrekeys)
(alex, alexClient) <- randomUserWithClientQualified (someLastPrekeys !! 1)
alexClient2 <- randomClient (qUnqualified alex) (someLastPrekeys !! 2)
(amy, amyClient) <- randomUserWithClientQualified (someLastPrekeys !! 3)
let bDomain = Domain "b.far-away.example.com"
cDomain = Domain "c.far-away.example.com"
randomQuidAndClients d n = (,) <$> randomQualifiedId d <*> liftIO (replicateM n $ generate arbitrary)
(bob, [bobClient]) <- randomQuidAndClients bDomain 1
(bart, [bartClient1, bartClient2]) <- randomQuidAndClients bDomain 2
(carl, [carlClient]) <- randomQuidAndClients cDomain 1
let aliceU = qUnqualified alice
alexU = qUnqualified alex
amyU = qUnqualified amy
connectLocalQualifiedUsers aliceU (list1 alex [amy])
forM_ [bob, bart, carl] $ connectWithRemoteUser aliceU
resp <-
postConvWithRemoteUsers
aliceU
Nothing
defNewProteusConv {newConvQualifiedUsers = [alex, amy, bob, bart, carl]}
let convId = (`Qualified` owningDomain) . decodeConvId $ resp
WS.bracketAsClientRN cannon [(alexU, alexClient), (alexU, alexClient2), (amyU, amyClient)] $ \[wsAlex1, wsAlex2, wsAmy] -> do
let message =
[ (alex, alexClient, "text-for-alex"),
(alex, alexClient2, "text-for-alex2"),
(amy, amyClient, "text-for-amy"),
(bob, bobClient, "text-for-bob"),
(bart, bartClient1, "text-for-bart1"),
(bart, bartClient2, "text-for-bart2"),
(carl, carlClient, "text-for-carl")
]
let mkPubClient c = PubClient c Nothing
brigMock = do
guardRPC "get-user-clients"
d <- frTargetDomain <$> getRequest
asum
[ do
guard (d == bDomain)
mockReply $
UserMap . Map.fromList $
[ (qUnqualified bob, Set.singleton (mkPubClient bobClient)),
(qUnqualified bart, Set.fromList (map mkPubClient [bartClient1, bartClient2]))
],
do
guard (d == cDomain)
mockReply $
UserMap
( Map.singleton
(qUnqualified carl)
(Set.singleton (PubClient carlClient Nothing))
)
]
galleyMock = "on-message-sent" ~> ()
(resp2, requests) <- postProteusMessageQualifiedWithMockFederator aliceU aliceClient convId message "data" Message.MismatchReportAll (brigMock <|> galleyMock)
pure resp2 !!! do
const 201 === statusCode
assertMismatchQualified mempty mempty mempty mempty
let encodedTextForAlex1 = toBase64Text "text-for-alex"
encodedTextForAlex2 = toBase64Text "text-for-alex2"
encodedTextForAmy = toBase64Text "text-for-amy"
encodedTextForBob = toBase64Text "text-for-bob"
encodedTextForBart1 = toBase64Text "text-for-bart1"
encodedTextForBart2 = toBase64Text "text-for-bart2"
encodedTextForCarl = toBase64Text "text-for-carl"
encodedData = toBase64Text "data"
liftIO $ do
let matchReq domain component r = frTargetDomain r == domain && frComponent r == component
filterReq domain component = filter (matchReq domain component) requests
bBrigReq <- assertOne $ filterReq bDomain Brig
bGalleyReq <- assertOne $ filterReq bDomain Galley
cBrigReq <- assertOne $ filterReq cDomain Brig
cGalleyReq <- assertOne $ filterReq cDomain Galley
frRPC bBrigReq @?= "get-user-clients"
(sort . F.gucUsers <$> parseFedRequest bBrigReq) @?= Right (sort $ qUnqualified <$> [bob, bart])
frRPC cBrigReq @?= "get-user-clients"
parseFedRequest cBrigReq @?= Right (F.GetUserClients [qUnqualified carl])
frRPC bGalleyReq @?= "on-message-sent"
bActualNotif <- assertRight $ parseFedRequest bGalleyReq
let bExpectedNotif =
F.RemoteMessage
{ rmTime = F.rmTime bActualNotif,
rmData = Just $ toBase64Text "data",
rmSender = alice,
rmSenderClient = aliceClient,
rmConversation = qUnqualified convId,
rmPriority = Nothing,
rmPush = True,
rmTransient = False,
rmRecipients =
UserClientMap $
Map.fromList
[ (qUnqualified bob, Map.singleton bobClient encodedTextForBob),
( qUnqualified bart,
Map.fromList
[ (bartClient1, encodedTextForBart1),
(bartClient2, encodedTextForBart2)
]
)
]
}
bActualNotif @?= bExpectedNotif
frRPC cGalleyReq @?= "on-message-sent"
cActualNotif <- assertRight $ parseFedRequest cGalleyReq
let cExpectedNotif =
bExpectedNotif
{ F.rmRecipients =
UserClientMap $ Map.fromList [(qUnqualified carl, Map.singleton carlClient encodedTextForCarl)]
}
cActualNotif @?= cExpectedNotif
WS.assertMatch_ t wsAlex1 (wsAssertOtr' encodedData convId alice aliceClient alexClient encodedTextForAlex1)
WS.assertMatch_ t wsAlex2 (wsAssertOtr' encodedData convId alice aliceClient alexClient2 encodedTextForAlex2)
WS.assertMatch_ t wsAmy (wsAssertOtr' encodedData convId alice aliceClient amyClient encodedTextForAmy)
-- @SF.Separation @TSFI.RESTfulAPI @S2
-- Sets up a conversation on Backend A known as "owning backend". One of the
-- users from Backend A will send the message but have a missing client. It is
-- expected that the message will not be sent.
postMessageQualifiedLocalOwningBackendMissingClients :: TestM ()
postMessageQualifiedLocalOwningBackendMissingClients = do
-- Cannon for local users
cannon <- view tsCannon
-- Domain which owns the converstaion
owningDomain <- viewFederationDomain
(aliceOwningDomain, aliceClient) <- randomUserWithClientQualified (head someLastPrekeys)
(bobOwningDomain, bobClient) <- randomUserWithClientQualified (someLastPrekeys !! 1)
(chadOwningDomain, chadClient) <- randomUserWithClientQualified (someLastPrekeys !! 3)
chadClient2 <- randomClient (qUnqualified chadOwningDomain) (someLastPrekeys !! 2)
deeId <- randomId
deeClient <- liftIO $ generate arbitrary
let remoteDomain = Domain "far-away.example.com"
deeRemote = Qualified deeId remoteDomain
let aliceUnqualified = qUnqualified aliceOwningDomain
bobUnqualified = qUnqualified bobOwningDomain
chadUnqualified = qUnqualified chadOwningDomain
connectLocalQualifiedUsers aliceUnqualified (list1 bobOwningDomain [chadOwningDomain])
connectWithRemoteUser aliceUnqualified deeRemote
-- FUTUREWORK: Do this test with more than one remote domains
resp <-
postConvWithRemoteUsers
aliceUnqualified
Nothing
defNewProteusConv {newConvQualifiedUsers = [bobOwningDomain, chadOwningDomain, deeRemote]}
let convId = (`Qualified` owningDomain) . decodeConvId $ resp
-- Missing Bob, chadClient2 and Dee
let message = [(chadOwningDomain, chadClient, "text-for-chad")]
-- FUTUREWORK: Mock federator and ensure that message is not propagated to remotes
WS.bracketR2 cannon bobUnqualified chadUnqualified $ \(wsBob, wsChad) -> do
let mock = "get-user-clients" ~> UserMap (Map.singleton (qUnqualified deeRemote) (Set.singleton (PubClient deeClient Nothing)))
(resp2, _requests) <- postProteusMessageQualifiedWithMockFederator aliceUnqualified aliceClient convId message "data" Message.MismatchReportAll mock
pure resp2 !!! do
const 412 === statusCode
let expectedMissing =
QualifiedUserClients $
Map.fromList
[ ( owningDomain,
Map.fromList
[ (bobUnqualified, Set.singleton bobClient),
(chadUnqualified, Set.singleton chadClient2)
]
),
( remoteDomain,
Map.singleton (qUnqualified deeRemote) (Set.singleton deeClient)
)
]
assertMismatchQualified mempty expectedMissing mempty mempty
WS.assertNoEvent (1 # Second) [wsBob, wsChad]
-- @END
-- | Sets up a conversation on Backend A known as "owning backend". One of the
-- users from Backend A will send the message, it is expected that message will
-- be sent successfully.
postMessageQualifiedLocalOwningBackendRedundantAndDeletedClients :: TestM ()
postMessageQualifiedLocalOwningBackendRedundantAndDeletedClients = do
-- WS receive timeout
let t = 5 # Second
-- Cannon for local users
cannon <- view tsCannon
-- Domain which owns the converstaion
owningDomain <- viewFederationDomain
let remoteDomain = Domain "far-away.example.com"
(aliceOwningDomain, aliceClient) <- randomUserWithClientQualified (head someLastPrekeys)
(bobOwningDomain, bobClient) <- randomUserWithClientQualified (someLastPrekeys !! 1)
(chadOwningDomain, chadClient) <- randomUserWithClientQualified (someLastPrekeys !! 2)
chadClientNonExistent <- liftIO $ generate arbitrary
deeRemote <- (`Qualified` remoteDomain) <$> randomId
deeClient <- liftIO $ generate arbitrary
(nonMemberOwningDomain, nonMemberOwningDomainClient) <- randomUserWithClientQualified (someLastPrekeys !! 3)
nonMemberRemote <- (`Qualified` remoteDomain) <$> randomId
nonMemberRemoteClient <- liftIO $ generate arbitrary
let aliceUnqualified = qUnqualified aliceOwningDomain
bobUnqualified = qUnqualified bobOwningDomain
chadUnqualified = qUnqualified chadOwningDomain
deeRemoteUnqualified = qUnqualified deeRemote
nonMemberUnqualified = qUnqualified nonMemberOwningDomain
nonMemberRemoteUnqualified = qUnqualified nonMemberRemote
connectLocalQualifiedUsers aliceUnqualified (list1 bobOwningDomain [chadOwningDomain])
connectWithRemoteUser aliceUnqualified deeRemote
-- FUTUREWORK: Do this test with more than one remote domains
resp <-
postConvWithRemoteUsers
aliceUnqualified
Nothing
defNewProteusConv {newConvQualifiedUsers = [bobOwningDomain, chadOwningDomain, deeRemote]}
let convId = (`Qualified` owningDomain) . decodeConvId $ resp
WS.bracketR3 cannon bobUnqualified chadUnqualified nonMemberUnqualified $ \(wsBob, wsChad, wsNonMember) -> do
let message =
[ (bobOwningDomain, bobClient, "text-for-bob"),
(chadOwningDomain, chadClient, "text-for-chad"),
(chadOwningDomain, chadClientNonExistent, "text-for-chad-non-existent"),
(deeRemote, deeClient, "text-for-dee"),