-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathURLEndpointListenerTest.cs
1408 lines (1162 loc) · 51.1 KB
/
URLEndpointListenerTest.cs
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
//
// URLEndpointListenerTest.cs
//
// Copyright (c) 2020 Couchbase, Inc All rights reserved.
//
// 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.
//
#if COUCHBASE_ENTERPRISE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net;
using System.Reflection;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using Couchbase.Lite;
using Couchbase.Lite.P2P;
using Couchbase.Lite.Sync;
using FluentAssertions;
using LiteCore.Interop;
using System.Runtime.InteropServices;
#if !WINDOWS_UWP
using Xunit;
using Xunit.Abstractions;
#else
using Fact = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute;
#endif
namespace Test
{
internal static class URLEndpointListenerExtensions
{
#region Public Methods
public static URLEndpoint LocalEndpoint(this URLEndpointListener listener)
=> new URLEndpoint(LocalUrl(listener));
public static Uri LocalUrl(this URLEndpointListener listener)
{
Debug.Assert(listener.Port > 0);
var builder = new UriBuilder(
listener.Config.DisableTLS ? "ws" : "wss",
"localhost",
listener.Port,
$"/{listener.Config.Database.Name}"
);
return builder.Uri;
}
#endregion
}
#if WINDOWS_UWP
[Microsoft.VisualStudio.TestTools.UnitTesting.TestClass]
#endif
public sealed class URLEndpointListenerTest : ReplicatorTestBase
{
#region Constants
private const ushort WsPort = 4984;
private const ushort WssPort = 4985;
private const string ServerCertLabel = "CBL-Server-Cert";
private const string ClientCertLabel = "CBL-Client-Cert";
#endregion
#region Variables
private URLEndpointListener _listener;
private X509Store _store;
#endregion
#region Constructors
#if !WINDOWS_UWP
public URLEndpointListenerTest(ITestOutputHelper output) : base(output)
#else
public URLEndpointListenerTest()
#endif
{
_store = new X509Store(StoreName.My);
}
#endregion
#region Public Methods
[Fact]
public void TestPort()
{
//init and start a listener
_listener = CreateListener(false);
//In order to get the test to pass on Linux, temp modify to this:
_listener.Port.Should().BeGreaterThan(0);
//_listener.Port.Should().Be(WsPort);
//stop the listener
_listener.Stop();
_listener.Port.Should().Be(0, "Listener's port should be 0 because the listener is stopped.");
}
[Fact]
public void TestEmptyPort()
{
//init and start a listener
var config = CreateListenerConfig(false);
_listener = Listen(config, 0, 0);
_listener.Port.Should().NotBe(0, "Because the port is dynamically assigned.");
//stop the listener
_listener.Stop();
_listener.Port.Should().Be(0, "Listener's port should be 0 because the listener is stopped.");
}
[Fact]
public void TestBusyPort()
{
_listener = CreateListener(false, false);
_listener.Start();
//listener1 uses the same port as listener
var config = CreateListenerConfig(false, false, stopListener: false);
var listener1 = Listen(config, GetEADDRINUSECode(), CouchbaseLiteErrorType.POSIX, stopListener: false);
listener1.Dispose();
}
[Fact]
public void TestTLSIdentity()
{
// TLS is disabled
_listener = CreateListener(false);
_listener.TlsIdentity.Should().BeNull();
_listener.Stop();
_listener.TlsIdentity.Should().BeNull();
// Anonymous Identity
_listener = CreateListener(true);
_listener.TlsIdentity.Should().NotBeNull();
_listener.Stop();
_listener.TlsIdentity.Should().BeNull();
// User Identity
TLSIdentity.DeleteIdentity(_store, ServerCertLabel, null);
var id = TLSIdentity.CreateIdentity(false,
new Dictionary<string, string>() { { Certificate.CommonNameAttribute, "CBL-Server" } },
null,
_store,
ServerCertLabel,
null);
var config = CreateListenerConfig(true, true, null, id);
_listener = new URLEndpointListener(config);
_listener.TlsIdentity.Should().BeNull();
_listener.Start();
_listener.TlsIdentity.Should().NotBeNull();
_listener.TlsIdentity.Should().BeEquivalentTo(config.TlsIdentity);
_listener.Stop();
_listener.TlsIdentity.Should().BeNull();
}
[Fact]
public void TestUrls()
{
_listener = CreateListener(false);
_listener.Urls.Count.Should().NotBe(0);
_listener.Stop();
_listener.Urls.Count.Should().Be(0);
}
[Fact]
public void TestStatus()
{
ulong maxConnectionCount = 0UL;
ulong maxActiveCount = 0UL;
//init and start a listener
_listener = CreateListener(false);
//listener is started at this point
_listener.Status.ConnectionCount.Should().Be(0, "Listener's connection count should be 0 because no client connection has been established.");
_listener.Status.ActiveConnectionCount.Should().Be(0, "Listener's active connection count should be 0 because no client connection has been established.");
using (var doc1 = new MutableDocument())
using (var doc2 = new MutableDocument()) {
doc1.SetString("name", "Sam");
Db.Save(doc1);
doc2.SetString("name", "Mary");
OtherDb.Save(doc2);
}
var targetEndpoint = _listener.LocalEndpoint();
var config = new ReplicatorConfiguration(Db, targetEndpoint);
using (var repl = new Replicator(config)) {
var waitAssert = new WaitAssert();
var token = repl.AddChangeListener((sender, args) =>
{
WriteLine($"Yeehaw {_listener.Status.ConnectionCount} / {_listener.Status.ActiveConnectionCount}");
maxConnectionCount = Math.Max(maxConnectionCount, _listener.Status.ConnectionCount);
maxActiveCount = Math.Max(maxActiveCount, _listener.Status.ActiveConnectionCount);
waitAssert.RunConditionalAssert(() =>
{
return args.Status.Activity == ReplicatorActivityLevel.Stopped;
});
});
repl.Start();
while(repl.Status.Activity != ReplicatorActivityLevel.Busy) {
Thread.Sleep(100);
}
// For some reason running on mac throws off the timing enough so that the active connection count
// of 1 is never seen. So record the value right after it becomes busy.
maxConnectionCount = Math.Max(maxConnectionCount, _listener.Status.ConnectionCount);
maxActiveCount = Math.Max(maxActiveCount, _listener.Status.ActiveConnectionCount);
try {
waitAssert.WaitForResult(TimeSpan.FromSeconds(100));
} finally {
token.Remove();
}
}
maxConnectionCount.Should().Be(1);
maxActiveCount.Should().Be(1);
//stop the listener
_listener.Stop();
_listener.Status.ConnectionCount.Should().Be(0, "Listener's connection count should be 0 because the connection is stopped.");
_listener.Status.ActiveConnectionCount.Should().Be(0, "Listener's active connection count should be 0 because the connection is stopped.");
}
[Fact]
public void TestPasswordAuthenticator()
{
var auth = new ListenerPasswordAuthenticator((sender, username, password) =>
{
return username == "daniel" && new NetworkCredential(string.Empty, password).Password == "123";
});
_listener = CreateListener(false, true, auth);
// Replicator - No authenticator
var targetEndpoint = _listener.LocalEndpoint();
var config = new ReplicatorConfiguration(Db, targetEndpoint);
RunReplication(config, (int) CouchbaseLiteError.HTTPAuthRequired, CouchbaseLiteErrorType.CouchbaseLite);
var pw = "123";
var wrongPw = "456";
SecureString pwSecureString = null;
SecureString wrongPwSecureString = null;
unsafe {
fixed (char* pw_ = pw)
fixed (char* wrongPw_ = wrongPw) {
pwSecureString = new SecureString(pw_, pw.Length);
wrongPwSecureString = new SecureString(wrongPw_, wrongPw.Length);
}
}
// Replicator - Wrong Credentials
config.Authenticator = new BasicAuthenticator("daniel", wrongPwSecureString);
RunReplication(config, (int) CouchbaseLiteError.HTTPAuthRequired, CouchbaseLiteErrorType.CouchbaseLite);
// Replicator - Success
config.Authenticator = new BasicAuthenticator("daniel", pwSecureString);
RunReplication(config, 0, 0);
_listener.Stop();
pwSecureString.Dispose();
wrongPwSecureString.Dispose();
}
#if !NET6_0_ANDROID
[Fact]
public void TestClientCertAuthWithCallback()
{
var auth = new ListenerCertificateAuthenticator((sender, cert) =>
{
if (cert.Count != 1) {
return false;
}
return cert[0].SubjectName.Name?.Replace("CN=", "") == "daniel";
});
var badAuth = new ListenerCertificateAuthenticator((sender, cert) =>
{
return cert.Count == 100; // Obviously fail
});
_listener = CreateListener(true, true, auth);
// User Identity
TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
var id = TLSIdentity.CreateIdentity(false,
new Dictionary<string, string>() { { Certificate.CommonNameAttribute, "daniel" } },
null,
_store,
ClientCertLabel,
null);
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
new ClientCertificateAuthenticator(id),
false,
_listener.TlsIdentity.Certs[0],
0,
0
);
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
null, // Don't send client cert
false,
_listener.TlsIdentity.Certs[0],
(int)CouchbaseLiteError.TLSHandshakeFailed,
CouchbaseLiteErrorType.CouchbaseLite
);
_listener.Stop();
_listener = CreateListener(true, true, badAuth);
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
new ClientCertificateAuthenticator(id), // send wrong client cert
false,
_listener.TlsIdentity.Certs[0],
(int)CouchbaseLiteError.TLSHandshakeFailed,
CouchbaseLiteErrorType.CouchbaseLite
);
TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
}
#endif
[Fact]
public void TestClientCertAuthRootCertsError()
{
byte[] caData = GetFileByteArray("client-ca.der", typeof(URLEndpointListenerTest));
var rootCert = new X509Certificate2(caData);
var auth = new ListenerCertificateAuthenticator(new X509Certificate2Collection(rootCert));
_listener = CreateListener(true, true, auth);
TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
// Create wrong client identity
var id = TLSIdentity.CreateIdentity(false,
new Dictionary<string, string>() { { Certificate.CommonNameAttribute, "daniel" } },
null,
_store,
ClientCertLabel,
null);
id.Should().NotBeNull();
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
new ClientCertificateAuthenticator(id),
true,
_listener.TlsIdentity.Certs[0],
(int) CouchbaseLiteError.TLSHandshakeFailed, //not TLSClientCertRejected as mac has..
CouchbaseLiteErrorType.CouchbaseLite
);
TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
_listener.Stop();
}
#if !NET6_0_ANDROID
[Fact]
public void TestClientCertAuthenticatorRootCerts()
{
byte[] caData = GetFileByteArray("client-ca.der", typeof(URLEndpointListenerTest));
#if NET6_0_ANDROID
byte[] clientData = GetFileByteArray("client.pfx", typeof(URLEndpointListenerTest));
#else
byte[] clientData = GetFileByteArray("client.p12", typeof(URLEndpointListenerTest));
#endif
var rootCert = new X509Certificate2(caData);
var auth = new ListenerCertificateAuthenticator(new X509Certificate2Collection(rootCert));
_listener = CreateListener(true, true, auth);
var serverCert = _listener.TlsIdentity.Certs[0];
// Cleanup
TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
// Create client identity
var id = TLSIdentity.ImportIdentity(_store, clientData, "123", ClientCertLabel, null);
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
new ClientCertificateAuthenticator(id),
true,
serverCert,
0,
0
);
TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
_listener.Stop();
}
#endif
#if !NET6_0_ANDROID
[Fact]
public void TestListenerWithImportIdentity()
{
#if NET6_0_ANDROID
byte[] serverData = GetFileByteArray("client.pfx", typeof(URLEndpointListenerTest));
#else
byte[] serverData = GetFileByteArray("client.p12", typeof(URLEndpointListenerTest));
#endif
// Cleanup
TLSIdentity.DeleteIdentity(_store, ClientCertLabel, null);
// Import identity
var id = TLSIdentity.ImportIdentity(_store, serverData, "123", ServerCertLabel, null);
// Create listener and start
var config = CreateListenerConfig(true, true, null, id);
_listener = Listen(config);
_listener.TlsIdentity.Should().NotBeNull();
using (var doc1 = new MutableDocument("doc1")) {
doc1.SetString("name", "Sam");
Db.Save(doc1);
}
OtherDb.Count.Should().Be(0);
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
null, //authenticator
false, //accept only self signed server cert
_listener.TlsIdentity.Certs[0], //server cert
0,
0
);
OtherDb.Count.Should().Be(1);
_listener.Stop();
}
[Fact]
public void TestAcceptSelfSignedCertWithPinnedCertificate()
{
_listener = CreateListener();
_listener.TlsIdentity.Should()
.NotBeNull("because otherwise the TLS identity was not created for the listener");
_listener.TlsIdentity.Certs.Count.Should().Be(1,
"because otherwise bogus certs were used");
// listener = cert1; replicator.pin = cert2; acceptSelfSigned = true => fail
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
null, //authenticator
true, //accept only self signed server cert
DefaultServerCert, //server cert
(int) CouchbaseLiteError.TLSCertUntrusted,
CouchbaseLiteErrorType.CouchbaseLite
);
// listener = cert1; replicator.pin = cert1; acceptSelfSigned = false => pass
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
null,
false, //accept only self signed server cert
_listener.TlsIdentity.Certs[0], //server cert
0,
0
);
_listener.Stop();
}
[Fact]
public void TestAcceptOnlySelfSignedCertMode()
{
_listener = CreateListener();
_listener.TlsIdentity.Should()
.NotBeNull("because otherwise the TLS identity was not created for the listener");
_listener.TlsIdentity.Certs.Count.Should().Be(1,
"because otherwise bogus certs were used");
DisableDefaultServerCertPinning = true;
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
null,
false,//accept only self signed server cert
null,
//TODO: Need to handle Linux throwing different error TLSCertUntrusted (5008)
(int)CouchbaseLiteError.TLSCertUnknownRoot,
CouchbaseLiteErrorType.CouchbaseLite
);
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
null,
true, //accept only self signed server cert
null,
0,
0
);
_listener.Stop();
}
[Fact]
public void TestDoNotAcceptSelfSignedMode() //aka testPinnedServerCertificate in iOS
{
_listener = CreateListener();
_listener.TlsIdentity.Should()
.NotBeNull("because otherwise the TLS identity was not created for the listener");
_listener.TlsIdentity.Certs.Count.Should().Be(1,
"because otherwise bogus certs were used");
DisableDefaultServerCertPinning = true;
// Replicator - TLS Error
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
null,
false, //accept only self signed server cert
null,
(int) CouchbaseLiteError.TLSCertUnknownRoot, //maui android 5006
CouchbaseLiteErrorType.CouchbaseLite
);
// Replicator - Success
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
null,
false, //accept only self signed server cert
_listener.TlsIdentity.Certs[0],
0,
0
);
_listener.Stop();
}
#endif
[Fact]
public void TestEmptyNetworkInterface()
{
var config = CreateListenerConfig(false);
config.NetworkInterface = "0.0.0.0";
_listener = Listen(config, 0, 0);
_listener.Stop();
}
[Fact]
public void TestUnavailableNetworkInterface()
{
var config = CreateListenerConfig(false);
config.NetworkInterface = "1.1.1.256";
Listen(config, (int) CouchbaseLiteError.UnknownHost, CouchbaseLiteErrorType.CouchbaseLite);
config.NetworkInterface = "blah";
Listen(config, (int) CouchbaseLiteError.UnknownHost, CouchbaseLiteErrorType.CouchbaseLite);
}
//[Fact] //CouchbaseLiteException (POSIXDomain / 101): The requested address is not valid in its context.
public void TestNetworkInterfaceName()
{
var config = CreateListenerConfig(false);
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) {
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211
|| ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses) {
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
config.NetworkInterface = ip.Address.ToString();
_listener = Listen(config, 0, 0);
_listener.Stop();
}
}
}
}
}
#if !NET6_0_ANDROID
[Fact]
public void TestMultipleListenersOnSameDatabase()
{
_listener = CreateListener();
var listener2 = CreateNewListener();
using (var doc1 = new MutableDocument("doc1"))
using (var doc2 = new MutableDocument("doc2")) {
doc1.SetString("name", "Sam");
Db.Save(doc1);
doc2.SetString("name", "Mary");
OtherDb.Save(doc2);
}
RunReplication(
_listener.LocalEndpoint(),
ReplicatorType.PushAndPull,
false,
null,
false, //accept only self signed server cert
_listener.TlsIdentity.Certs[0],
0,
0
);
listener2.Stop();
OtherDb.Count.Should().Be(2);
}
// A three way replication with one database acting as both a listener
// and a replicator
[Fact]
public void TestReplicatorAndListenerOnSameDatabase()
{
using (var doc = new MutableDocument()) {
OtherDb.Save(doc);
}
CreateListener();
using (var doc1 = new MutableDocument()) {
Db.Save(doc1);
}
var target = new DatabaseEndpoint(Db);
var config1 = CreateConfig(target, ReplicatorType.PushAndPull, true, sourceDb:OtherDb);
var repl1 = new Replicator(config1);
Database.Delete("urlepTestDb", Directory);
var urlepTestDb = OpenDB("urlepTestDb");
using (var doc2 = new MutableDocument()) {
urlepTestDb.Save(doc2);
}
var config2 = CreateConfig(_listener.LocalEndpoint(), ReplicatorType.PushAndPull, true,
serverCert: _listener.TlsIdentity.Certs[0], sourceDb: urlepTestDb);
var repl2 = new Replicator(config2);
var wait1 = new ManualResetEventSlim();
var wait2 = new ManualResetEventSlim();
EventHandler<ReplicatorStatusChangedEventArgs> changeListener = (sender, args) =>
{
if (args.Status.Activity == ReplicatorActivityLevel.Idle && args.Status.Progress.Completed ==
args.Status.Progress.Total) {
if (OtherDb.Count == 3 && Db.Count == 3 && urlepTestDb.Count == 3) {
((Replicator) sender).Stop();
}
} else if (args.Status.Activity == ReplicatorActivityLevel.Stopped) {
if (sender == repl1) {
wait1.Set();
} else {
wait2.Set();
}
}
};
var token1 = repl1.AddChangeListener(changeListener);
var token2 = repl2.AddChangeListener(changeListener);
repl1.Start();
repl2.Start();
WaitHandle.WaitAll(new[] {wait1.WaitHandle, wait2.WaitHandle}, TimeSpan.FromSeconds(20))
.Should().BeTrue();
token1.Remove();
token2.Remove();
Db.Count.Should().Be(3, "because otherwise not all docs were received into Db");
OtherDb.Count.Should().Be(3, "because otherwise not all docs were received into OtherDb");
urlepTestDb.Count.Should().Be(3, "because otherwise not all docs were received into urlepTestDb");
repl1.Dispose();
repl2.Dispose();
wait1.Dispose();
wait2.Dispose();
urlepTestDb.Close();
Thread.Sleep(500); // wait for everything to stop
}
#endif
[Fact]
public void TestReadOnlyListener()
{
using (var doc1 = new MutableDocument()) {
Db.Save(doc1);
}
var config = new URLEndpointListenerConfiguration(OtherDb)
{
DisableTLS = true,
ReadOnly = true
};
Listen(config);
RunReplication(_listener.LocalEndpoint(), ReplicatorType.PushAndPull,
false, null, null,
(int)CouchbaseLiteError.HTTPForbidden,
CouchbaseLiteErrorType.CouchbaseLite);
_listener.Stop();
}
[Fact]
public void TestCloseWithActiveListener()
{
Listen(CreateListenerConfig(false));
OtherDb.Close();
_listener.Port.Should().Be(0);
_listener.Urls.Should().BeEmpty();
}
[Fact]
public void TestReplicatorServerCertNoTLS() => CheckReplicatorServerCert(false, false);
#if !NET6_0_ANDROID
[Fact]
public void TestReplicatorServerCertWithTLS() => CheckReplicatorServerCert(true, true);
[Fact]
public void TestReplicatorServerCertWithTLSError() => CheckReplicatorServerCert(true, false);
[Fact] //hang maui android
public void TestMultipleReplicatorsToListener()
{
_listener = Listen(CreateListenerConfig()); // writable listener
// save a doc on listenerDB
using (var doc = new MutableDocument()) {
OtherDb.Save(doc);
}
ValidateMultipleReplicationsTo(ReplicatorType.PushAndPull);
}
#if NET6_0_OR_GREATER
[Fact] // Looks like MSBuild doesn't understand RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ?
public void TestMultipleReplicatorsOnReadOnlyListener()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) //Mac OS 8-23-21 hang with LiteCore Commit: 5d9539fae43e9282787c2b68772bb85ecbc00b5c [5d9539f]
{
var config = CreateListenerConfig();
config.ReadOnly = true;
_listener = Listen(config);
// save a doc on listener DB
using (var doc = new MutableDocument()) {
OtherDb.Save(doc);
}
ValidateMultipleReplicationsTo(ReplicatorType.Pull);
}
}
#endif
[Fact] //hang maui android
public void TestCloseWithActiveReplicationsAndURLEndpointListener() => WithActiveReplicationsAndURLEndpointListener(true);
[Fact]//hang maui android
public void TestDeleteWithActiveReplicationsAndURLEndpointListener() => WithActiveReplicationsAndURLEndpointListener(false);
[Fact]
public void TestCloseWithActiveReplicatorAndURLEndpointListeners() => WithActiveReplicatorAndURLEndpointListeners(true);
[Fact]
public void TestDeleteWithActiveReplicatorAndURLEndpointListeners() => WithActiveReplicatorAndURLEndpointListeners(false);
#endif
[Fact]
public void TestStopListener()
{
ManualResetEventSlim waitIdleAssert = new ManualResetEventSlim();
ManualResetEventSlim waitStoppedAssert = new ManualResetEventSlim();
var config = CreateListenerConfig(false);
_listener = Listen(config);
var target = _listener.LocalEndpoint();
var config1 = CreateConfig(target, ReplicatorType.PushAndPull, true,
serverCert: null);
using (var repl = new Replicator(config1)) {
var token = repl.AddChangeListener((sender, args) =>
{
if (args.Status.Activity == ReplicatorActivityLevel.Idle) {
waitIdleAssert.Set();
// Stop listener aka server
_listener.Stop();
} else if (args.Status.Activity == ReplicatorActivityLevel.Stopped) {
waitStoppedAssert.Set();
}
});
repl.Start();
// Wait until idle then stop the listener
waitIdleAssert.Wait(TimeSpan.FromSeconds(15)).Should().BeTrue();
// Wait for the replicator to be stopped
waitStoppedAssert.Wait(TimeSpan.FromSeconds(20)).Should().BeTrue();
// Check error
var error = repl.Status.Error.As<CouchbaseWebsocketException>();
((int)error.Error).Should().Be((int)CouchbaseLiteError.WebSocketGoingAway);
}
}
#endregion
#region 8.15 Collections replication in URLEndpointListener
[Fact]
public void TestCollectionsSingleShotPushPullReplication() => CollectionsPushPullReplication(continuous: false);
[Fact]
public void TestCollectionsContinuousPushPullReplication() => CollectionsPushPullReplication(continuous: true);
[Fact]
public void TestMismatchedCollectionReplication()
{
using (var colAOtherDb = OtherDb.CreateCollection("colA", "scopeA"))
using (var colADb = Db.CreateCollection("colB", "scopeA")) {
var collsOtherDb = new List<Collection>();
collsOtherDb.Add(colAOtherDb);
var config = new URLEndpointListenerConfiguration(collsOtherDb)
{
Port = 0,
DisableTLS = true
};
var listener = new URLEndpointListener(config);
listener.Start();
var targetEndpoint = listener.LocalEndpoint();
var replConfig = new ReplicatorConfiguration(targetEndpoint)
{
ReplicatorType = ReplicatorType.PushAndPull,
Continuous = false
};
replConfig.AddCollection(colADb);
RunReplication(replConfig, (int)CouchbaseLiteError.HTTPNotFound, CouchbaseLiteErrorType.CouchbaseLite);
listener.Stop();
}
}
[Fact]
public void TestCreateListenerConfigWithEmptyCollection()
{
var collsOtherDb = new List<Collection>();
Action badAct = () => new URLEndpointListenerConfiguration(collsOtherDb)
{
Port = 0,
DisableTLS = true
};
badAct.Should().Throw<CouchbaseLiteException>().WithMessage("The given collections must not be null or empty.");
}
#endregion
#region Private Methods
private void CollectionsPushPullReplication(bool continuous)
{
using (var colAOtherDb = OtherDb.CreateCollection("colA", "scopeA"))
using (var colADb = Db.CreateCollection("colA", "scopeA")) {
using (var doc = new MutableDocument("doc"))
using (var doc1 = new MutableDocument("doc1")) {
doc.SetString("str", "string");
doc1.SetString("str1", "string1");
colADb.Save(doc);
colADb.Save(doc1);
}
using (var doc = new MutableDocument("doc2"))
using (var doc1 = new MutableDocument("doc3")) {
doc.SetString("str2", "string2");
doc1.SetString("str3", "string3");
colAOtherDb.Save(doc);
colAOtherDb.Save(doc1);
}
var collsOtherDb = new List<Collection>() { colAOtherDb };
var config = new URLEndpointListenerConfiguration(collsOtherDb)
{
Port = 0,
DisableTLS = true
};
var listener = new URLEndpointListener(config);
listener.Start();
var targetEndpoint = listener.LocalEndpoint();
var replConfig = new ReplicatorConfiguration(targetEndpoint)
{
ReplicatorType = ReplicatorType.PushAndPull,
Continuous = continuous
};
replConfig.AddCollection(colADb);
RunReplication(replConfig, 0, 0);
// Check docs are replicated between collections colADb & colAOtherDb
colAOtherDb.GetDocument("doc").GetString("str").Should().Be("string");
colAOtherDb.GetDocument("doc1").GetString("str1").Should().Be("string1");
colADb.GetDocument("doc2").GetString("str2").Should().Be("string2");
colADb.GetDocument("doc3").GetString("str3").Should().Be("string3");
listener.Stop();
}
}
private int GetEADDRINUSECode()
{
#if NET6_0_OR_GREATER
if (OperatingSystem.IsAndroid() || OperatingSystem.IsLinux())
{
return 98;
}
if (OperatingSystem.IsIOS() || OperatingSystem.IsMacCatalyst() || OperatingSystem.IsMacOS())
{
return 48;
}
if (OperatingSystem.IsWindows())
{
return 100;
}
throw new PlatformNotSupportedException();
#elif __MOBILE__
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return 100;
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return 48;
}
else
{