-
Notifications
You must be signed in to change notification settings - Fork 265
/
tactics_test.go
1228 lines (1005 loc) · 28.8 KB
/
tactics_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 (c) 2018, Psiphon Inc.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package tactics
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/parameters"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/stacktrace"
)
func TestTactics(t *testing.T) {
// Server tactics configuration
// Long and short region lists test both map and slice lookups.
//
// Repeated median aggregation tests aggregation memoization.
//
// The test-packetman-spec tests a reference between a filter tactics
// and default tactics.
tacticsConfigTemplate := `
{
"RequestPublicKey" : "%s",
"RequestPrivateKey" : "%s",
"RequestObfuscatedKey" : "%s",
"DefaultTactics" : {
"TTL" : "1s",
"Parameters" : {
"NetworkLatencyMultiplier" : %0.1f,
"ServerPacketManipulationSpecs" : [{"Name": "test-packetman-spec", "PacketSpecs": [["TCP-flags S"]]}]
}
},
"FilteredTactics" : [
{
"Filter" : {
"Regions": ["R1", "R2", "R3", "R4", "R5", "R6"],
"APIParameters" : {"client_platform" : ["P1"]},
"SpeedTestRTTMilliseconds" : {
"Aggregation" : "Median",
"AtLeast" : 1
}
},
"Tactics" : {
"Parameters" : {
"ConnectionWorkerPoolSize" : %d
}
}
},
{
"Filter" : {
"Regions": ["R1"],
"ASNs": ["1"],
"APIParameters" : {"client_platform" : ["P1"], "client_version": ["V1"]},
"SpeedTestRTTMilliseconds" : {
"Aggregation" : "Median",
"AtLeast" : 1
}
},
"Tactics" : {
"Parameters" : {
%s
}
}
},
{
"Filter" : {
"APIParameters" : {"client_platform" : ["P2"], "client_version": ["V2"]}
},
"Tactics" : {
"Parameters" : {
"ConnectionWorkerPoolSize" : 1
}
}
},
{
"Filter" : {
"Regions": ["R2"]
},
"Tactics" : {
"Parameters" : {
"ConnectionWorkerPoolSize" : %d
}
}
},
{
"Filter" : {
"Regions": ["R7"]
},
"Tactics" : {
"Parameters" : {
"ServerProtocolPacketManipulations": {"All" : ["test-packetman-spec"]}
}
}
}
]
}
`
if stringLookupThreshold != 5 {
t.Fatalf("unexpected stringLookupThreshold")
}
encodedRequestPublicKey, encodedRequestPrivateKey, encodedObfuscatedKey, err := GenerateKeys()
if err != nil {
t.Fatalf("GenerateKeys failed: %s", err)
}
tacticsNetworkLatencyMultiplier := 2.0
tacticsConnectionWorkerPoolSize := 5
tacticsLimitTunnelProtocols := protocol.TunnelProtocols{"OSSH", "SSH"}
jsonTacticsLimitTunnelProtocols := `"LimitTunnelProtocols" : ["OSSH", "SSH"]`
expectedApplyCount := 3
tacticsConfig := fmt.Sprintf(
tacticsConfigTemplate,
encodedRequestPublicKey,
encodedRequestPrivateKey,
encodedObfuscatedKey,
tacticsNetworkLatencyMultiplier,
tacticsConnectionWorkerPoolSize,
jsonTacticsLimitTunnelProtocols,
tacticsConnectionWorkerPoolSize+1)
file, err := ioutil.TempFile("", "tactics.config")
if err != nil {
t.Fatalf("TempFile create failed: %s", err)
}
_, err = file.Write([]byte(tacticsConfig))
if err != nil {
t.Fatalf("TempFile write failed: %s", err)
}
file.Close()
configFileName := file.Name()
defer os.Remove(configFileName)
// Configure and run server
// Mock server uses an insecure HTTP transport that exposes endpoint names
clientGeoIPData := common.GeoIPData{Country: "R1", ASN: "1"}
logger := newTestLogger()
validator := func(
apiParams common.APIParameters) error {
expectedParams := []string{"client_platform", "client_version"}
for _, name := range expectedParams {
value, ok := apiParams[name]
if !ok {
return fmt.Errorf("missing param: %s", name)
}
_, ok = value.(string)
if !ok {
return fmt.Errorf("invalid param type: %s", name)
}
}
return nil
}
formatter := func(
geoIPData common.GeoIPData,
apiParams common.APIParameters) common.LogFields {
return common.LogFields(apiParams)
}
server, err := NewServer(
logger,
formatter,
validator,
configFileName)
if err != nil {
t.Fatalf("NewServer failed: %s", err)
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("Listen failed: %s", err)
}
serverAddress := listener.Addr().String()
go func() {
serveMux := http.NewServeMux()
serveMux.HandleFunc(
"/",
func(w http.ResponseWriter, r *http.Request) {
// Ensure RTT takes at least 1 millisecond for speed test
time.Sleep(1 * time.Millisecond)
endPoint := strings.Trim(r.URL.Path, "/")
if !server.HandleEndPoint(endPoint, clientGeoIPData, w, r) {
http.NotFound(w, r)
}
})
httpServer := &http.Server{
Addr: serverAddress,
Handler: serveMux,
}
httpServer.Serve(listener)
}()
// Configure client
params, err := parameters.NewParameters(
func(err error) {
t.Fatalf("Parameters getValue failed: %s", err)
})
if err != nil {
t.Fatalf("NewParameters failed: %s", err)
}
networkID := "NETWORK1"
getNetworkID := func() string { return networkID }
apiParams := common.APIParameters{
"client_platform": "P1",
"client_version": "V1"}
storer := newTestStorer()
endPointRegion := "R0"
endPointProtocol := "OSSH"
differentEndPointProtocol := "SSH"
obfuscatedRoundTripper := func(
ctx context.Context,
endPoint string,
requestBody []byte) ([]byte, error) {
// This mock ObfuscatedRoundTripper does not actually obfuscate the endpoint
// value.
request, err := http.NewRequest(
"POST",
fmt.Sprintf("http://%s/%s", serverAddress, endPoint),
bytes.NewReader(requestBody))
if err != nil {
return nil, err
}
request = request.WithContext(ctx)
response, err := http.DefaultClient.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP request failed: %d", response.StatusCode)
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
return body, nil
}
// There should be no local tactics
tacticsRecord, err := UseStoredTactics(storer, networkID)
if err != nil {
t.Fatalf("UseStoredTactics failed: %s", err)
}
if tacticsRecord != nil {
t.Fatalf("unexpected tactics record")
}
// Helper to check that expected tactics parameters are returned
checkParameters := func(r *Record) {
p, err := parameters.NewParameters(nil)
if err != nil {
t.Fatalf("NewParameters failed: %s", err)
}
// ValidationSkipOnError is set for Psiphon clients
counts, err := p.Set(r.Tag, parameters.ValidationSkipOnError, r.Tactics.Parameters)
if err != nil {
t.Fatalf("Apply failed: %s", err)
}
if counts[0] != expectedApplyCount {
t.Fatalf("Unexpected apply count: %d", counts[0])
}
multipler := p.Get().Float(parameters.NetworkLatencyMultiplier)
if multipler != tacticsNetworkLatencyMultiplier {
t.Fatalf("Unexpected NetworkLatencyMultiplier: %v", multipler)
}
connectionWorkerPoolSize := p.Get().Int(parameters.ConnectionWorkerPoolSize)
if connectionWorkerPoolSize != tacticsConnectionWorkerPoolSize {
t.Fatalf("Unexpected ConnectionWorkerPoolSize: %v", connectionWorkerPoolSize)
}
limitTunnelProtocols := p.Get().TunnelProtocols(parameters.LimitTunnelProtocols)
if !reflect.DeepEqual(limitTunnelProtocols, tacticsLimitTunnelProtocols) {
t.Fatalf("Unexpected LimitTunnelProtocols: %v", limitTunnelProtocols)
}
}
// Helper to check server-side cachedTacticsData state
checkServerCache := func(cacheEntryFilterMatches ...[]bool) {
cacheItems := server.cachedTacticsData.Items()
if len(cacheItems) != len(cacheEntryFilterMatches) {
t.Fatalf("Unexpected cachedTacticsData size: %v", len(cacheItems))
}
for _, filterMatches := range cacheEntryFilterMatches {
includeServerSizeOnly := false
hasFilterMatches := true
cacheKey := getCacheKey(includeServerSizeOnly, hasFilterMatches, filterMatches)
_, ok := server.cachedTacticsData.Get(cacheKey)
if !ok {
t.Fatalf("Unexpected missing cachedTacticsData entry: %v", filterMatches)
}
}
}
// Initial tactics request; will also run a speed test
// Request should complete in < 1 second
ctx, cancelFunc := context.WithTimeout(context.Background(), 1*time.Second)
initialFetchTacticsRecord, err := FetchTactics(
ctx,
params,
storer,
getNetworkID,
apiParams,
endPointProtocol,
endPointRegion,
encodedRequestPublicKey,
encodedObfuscatedKey,
obfuscatedRoundTripper)
cancelFunc()
if err != nil {
t.Fatalf("FetchTactics failed: %s", err)
}
if initialFetchTacticsRecord == nil {
t.Fatalf("expected tactics record")
}
checkParameters(initialFetchTacticsRecord)
// Server should be caching tactics data for tactics matching first two
// filters.
checkServerCache([]bool{true, true, false, false, false})
// There should now be cached local tactics
storedTacticsRecord, err := UseStoredTactics(storer, networkID)
if err != nil {
t.Fatalf("UseStoredTactics failed: %s", err)
}
if storedTacticsRecord == nil {
t.Fatalf("expected stored tactics record")
}
// Strip monotonic component so comparisons will work
initialFetchTacticsRecord.Expiry = initialFetchTacticsRecord.Expiry.Round(0)
if !reflect.DeepEqual(initialFetchTacticsRecord, storedTacticsRecord) {
t.Fatalf("tactics records are not identical:\n\n%#v\n\n%#v\n\n",
initialFetchTacticsRecord, storedTacticsRecord)
}
checkParameters(storedTacticsRecord)
// There should now be a speed test sample
speedTestSamples, err := getSpeedTestSamples(storer, networkID)
if err != nil {
t.Fatalf("getSpeedTestSamples failed: %s", err)
}
if len(speedTestSamples) != 1 {
t.Fatalf("unexpected speed test samples count")
}
// Wait for tactics to expire
time.Sleep(1 * time.Second)
storedTacticsRecord, err = UseStoredTactics(storer, networkID)
if err != nil {
t.Fatalf("UseStoredTactics failed: %s", err)
}
if storedTacticsRecord != nil {
t.Fatalf("unexpected stored tactics record")
}
// Next fetch should merge empty payload as tag matches
// TODO: inspect tactics response payload
fetchTacticsRecord, err := FetchTactics(
context.Background(),
params,
storer,
getNetworkID,
apiParams,
endPointProtocol,
endPointRegion,
encodedRequestPublicKey,
encodedObfuscatedKey,
obfuscatedRoundTripper)
if err != nil {
t.Fatalf("FetchTactics failed: %s", err)
}
if fetchTacticsRecord == nil {
t.Fatalf("expected tactics record")
}
if initialFetchTacticsRecord.Tag != fetchTacticsRecord.Tag {
t.Fatalf("tags are not identical")
}
if initialFetchTacticsRecord.Expiry.Equal(fetchTacticsRecord.Expiry) {
t.Fatalf("expiries unexpectedly identical")
}
if !reflect.DeepEqual(initialFetchTacticsRecord.Tactics, fetchTacticsRecord.Tactics) {
t.Fatalf("tactics are not identical:\n\n%#v\n\n%#v\n\n",
initialFetchTacticsRecord.Tactics, fetchTacticsRecord.Tactics)
}
checkParameters(fetchTacticsRecord)
// Server cache should be the same
checkServerCache([]bool{true, true, false, false, false})
// Modify tactics configuration to change payload
tacticsConnectionWorkerPoolSize = 6
tacticsLimitTunnelProtocols = protocol.TunnelProtocols{}
jsonTacticsLimitTunnelProtocols = ``
expectedApplyCount = 2
// Omitting LimitTunnelProtocols entirely tests this bug fix: When a new
// tactics payload is obtained, all previous parameters should be cleared.
//
// In the bug, any previous parameters not in the new tactics were
// incorrectly retained. In this test case, LimitTunnelProtocols is
// omitted in the new tactics; if FetchTactics fails to clear the old
// LimitTunnelProtocols then the test will fail.
tacticsConfig = fmt.Sprintf(
tacticsConfigTemplate,
encodedRequestPublicKey,
encodedRequestPrivateKey,
encodedObfuscatedKey,
tacticsNetworkLatencyMultiplier,
tacticsConnectionWorkerPoolSize,
jsonTacticsLimitTunnelProtocols,
tacticsConnectionWorkerPoolSize+1)
err = ioutil.WriteFile(configFileName, []byte(tacticsConfig), 0600)
if err != nil {
t.Fatalf("WriteFile failed: %s", err)
}
reloaded, err := server.Reload()
if err != nil {
t.Fatalf("Reload failed: %s", err)
}
if !reloaded {
t.Fatalf("Server config failed to reload")
}
// Server cache should be flushed
checkServerCache()
// Next fetch should return a different payload
fetchTacticsRecord, err = FetchTactics(
context.Background(),
params,
storer,
getNetworkID,
apiParams,
endPointProtocol,
endPointRegion,
encodedRequestPublicKey,
encodedObfuscatedKey,
obfuscatedRoundTripper)
if err != nil {
t.Fatalf("FetchTactics failed: %s", err)
}
if fetchTacticsRecord == nil {
t.Fatalf("expected tactics record")
}
if initialFetchTacticsRecord.Tag == fetchTacticsRecord.Tag {
t.Fatalf("tags unexpectedly identical")
}
if initialFetchTacticsRecord.Expiry.Equal(fetchTacticsRecord.Expiry) {
t.Fatalf("expires unexpectedly identical")
}
if reflect.DeepEqual(initialFetchTacticsRecord.Tactics, fetchTacticsRecord.Tactics) {
t.Fatalf("tactics unexpectedly identical")
}
checkParameters(fetchTacticsRecord)
checkServerCache([]bool{true, true, false, false, false})
// Exercise handshake transport of tactics
// Wait for tactics to expire; handshake should renew
time.Sleep(1 * time.Second)
handshakeParams := common.APIParameters{
"client_platform": "P1",
"client_version": "V1"}
err = SetTacticsAPIParameters(storer, networkID, handshakeParams)
if err != nil {
t.Fatalf("SetTacticsAPIParameters failed: %s", err)
}
tacticsPayload, err := server.GetTacticsPayload(clientGeoIPData, handshakeParams)
if err != nil {
t.Fatalf("GetTacticsPayload failed: %s", err)
}
handshakeTacticsRecord, err := HandleTacticsPayload(storer, networkID, tacticsPayload)
if err != nil {
t.Fatalf("HandleTacticsPayload failed: %s", err)
}
// When tactic parameters are unchanged, HandleTacticsPayload returns nil,
// so that callers do not apply tactics unnecessarily.
//
// Check that nil is returned, but then directly load the record stored by
// HandleTacticsPayload in order to check metadata including the updated
// TTL.
if handshakeTacticsRecord != nil {
t.Fatalf("unexpected tactics record")
}
handshakeTacticsRecord, err = getStoredTacticsRecord(storer, networkID)
if err != nil {
t.Fatalf("getStoredTacticsRecord failed: %s", err)
}
if fetchTacticsRecord.Tag != handshakeTacticsRecord.Tag {
t.Fatalf("tags are not identical")
}
if fetchTacticsRecord.Expiry.Equal(handshakeTacticsRecord.Expiry) {
t.Fatalf("expiries unexpectedly identical")
}
if !reflect.DeepEqual(fetchTacticsRecord.Tactics, handshakeTacticsRecord.Tactics) {
t.Fatalf("tactics are not identical:\n\n%#v\n\n%#v\n\n",
fetchTacticsRecord.Tactics, handshakeTacticsRecord.Tactics)
}
checkParameters(handshakeTacticsRecord)
checkServerCache([]bool{true, true, false, false, false})
// Now there should be stored tactics
storedTacticsRecord, err = UseStoredTactics(storer, networkID)
if err != nil {
t.Fatalf("UseStoredTactics failed: %s", err)
}
if storedTacticsRecord == nil {
t.Fatalf("expected stored tactics record")
}
handshakeTacticsRecord.Expiry = handshakeTacticsRecord.Expiry.Round(0)
if !reflect.DeepEqual(handshakeTacticsRecord, storedTacticsRecord) {
t.Fatalf("tactics records are not identical:\n\n%#v\n\n%#v\n\n",
handshakeTacticsRecord, storedTacticsRecord)
}
checkParameters(storedTacticsRecord)
// Change network ID, should be no stored tactics
networkID = "NETWORK2"
storedTacticsRecord, err = UseStoredTactics(storer, networkID)
if err != nil {
t.Fatalf("UseStoredTactics failed: %s", err)
}
if storedTacticsRecord != nil {
t.Fatalf("unexpected stored tactics record")
}
// Server should cache a new entry for different filter matches
apiParams2 := common.APIParameters{
"client_platform": "P2",
"client_version": "V2"}
fetchTacticsRecord, err = FetchTactics(
context.Background(),
params,
storer,
getNetworkID,
apiParams2,
endPointProtocol,
endPointRegion,
encodedRequestPublicKey,
encodedObfuscatedKey,
obfuscatedRoundTripper)
if err != nil {
t.Fatalf("FetchTactics failed: %s", err)
}
if fetchTacticsRecord == nil {
t.Fatalf("expected tactics record")
}
checkServerCache(
[]bool{true, true, false, false, false},
[]bool{false, false, true, false, false})
// Exercise speed test sample truncation
maxSamples := params.Get().Int(parameters.SpeedTestMaxSampleCount)
for i := 0; i < maxSamples*2; i++ {
response, err := MakeSpeedTestResponse(0, 0)
if err != nil {
t.Fatalf("MakeSpeedTestResponse failed: %s", err)
}
err = AddSpeedTestSample(
params,
storer,
networkID,
"",
differentEndPointProtocol,
100*time.Millisecond,
nil,
response)
if err != nil {
t.Fatalf("AddSpeedTestSample failed: %s", err)
}
}
speedTestSamples, err = getSpeedTestSamples(storer, networkID)
if err != nil {
t.Fatalf("getSpeedTestSamples failed: %s", err)
}
if len(speedTestSamples) != maxSamples {
t.Fatalf("unexpected speed test samples count")
}
for _, sample := range speedTestSamples {
if sample.EndPointProtocol == endPointProtocol {
t.Fatalf("unexpected old speed test sample")
}
}
// Fetch should fail when using incorrect keys
encodedIncorrectRequestPublicKey, _, encodedIncorrectObfuscatedKey, err := GenerateKeys()
if err != nil {
t.Fatalf("GenerateKeys failed: %s", err)
}
_, err = FetchTactics(
context.Background(),
params,
storer,
getNetworkID,
apiParams,
endPointProtocol,
endPointRegion,
encodedIncorrectRequestPublicKey,
encodedObfuscatedKey,
obfuscatedRoundTripper)
if err == nil {
t.Fatalf("FetchTactics succeeded unexpectedly with incorrect request key")
}
_, err = FetchTactics(
context.Background(),
params,
storer,
getNetworkID,
apiParams,
endPointProtocol,
endPointRegion,
encodedRequestPublicKey,
encodedIncorrectObfuscatedKey,
obfuscatedRoundTripper)
if err == nil {
t.Fatalf("FetchTactics succeeded unexpectedly with incorrect obfuscated key")
}
// When no keys are supplied, untunneled tactics requests are not supported, but
// handshake tactics (GetTacticsPayload) should still work.
tacticsConfig = fmt.Sprintf(
tacticsConfigTemplate,
"",
"",
"",
tacticsNetworkLatencyMultiplier,
tacticsConnectionWorkerPoolSize,
jsonTacticsLimitTunnelProtocols,
tacticsConnectionWorkerPoolSize+1)
err = ioutil.WriteFile(configFileName, []byte(tacticsConfig), 0600)
if err != nil {
t.Fatalf("WriteFile failed: %s", err)
}
reloaded, err = server.Reload()
if err != nil {
t.Fatalf("Reload failed: %s", err)
}
if !reloaded {
t.Fatalf("Server config failed to reload")
}
_, err = server.GetTacticsPayload(clientGeoIPData, handshakeParams)
if err != nil {
t.Fatalf("GetTacticsPayload failed: %s", err)
}
handled := server.HandleEndPoint(TACTICS_END_POINT, clientGeoIPData, nil, nil)
if handled {
t.Fatalf("HandleEndPoint unexpectedly handled request")
}
handled = server.HandleEndPoint(SPEED_TEST_END_POINT, clientGeoIPData, nil, nil)
if handled {
t.Fatalf("HandleEndPoint unexpectedly handled request")
}
// TODO: test replay attack defence
// TODO: test Server.Validate with invalid tactics configurations
}
func TestTacticsFilterGeoIPScope(t *testing.T) {
encodedRequestPublicKey, encodedRequestPrivateKey, encodedObfuscatedKey, err := GenerateKeys()
if err != nil {
t.Fatalf("GenerateKeys failed: %s", err)
}
tacticsConfigTemplate := fmt.Sprintf(`
{
"RequestPublicKey" : "%s",
"RequestPrivateKey" : "%s",
"RequestObfuscatedKey" : "%s",
"DefaultTactics" : {
"TTL" : "60s"
},
%%s
}
`, encodedRequestPublicKey, encodedRequestPrivateKey, encodedObfuscatedKey)
// Test: region-only scope
filteredTactics := `
"FilteredTactics" : [
{
"Filter" : {
"Regions": ["R1", "R2", "R3"]
}
},
{
"Filter" : {
"Regions": ["R4", "R5", "R6"]
}
}
]
`
tacticsConfig := fmt.Sprintf(tacticsConfigTemplate, filteredTactics)
file, err := ioutil.TempFile("", "tactics.config")
if err != nil {
t.Fatalf("TempFile create failed: %s", err)
}
_, err = file.Write([]byte(tacticsConfig))
if err != nil {
t.Fatalf("TempFile write failed: %s", err)
}
file.Close()
configFileName := file.Name()
defer os.Remove(configFileName)
server, err := NewServer(
nil,
nil,
nil,
configFileName)
if err != nil {
t.Fatalf("NewServer failed: %s", err)
}
reload := func() {
tacticsConfig = fmt.Sprintf(tacticsConfigTemplate, filteredTactics)
err = ioutil.WriteFile(configFileName, []byte(tacticsConfig), 0600)
if err != nil {
t.Fatalf("WriteFile failed: %s", err)
}
reloaded, err := server.Reload()
if err != nil {
t.Fatalf("Reload failed: %s", err)
}
if !reloaded {
t.Fatalf("Server config failed to reload")
}
}
geoIPData := common.GeoIPData{
Country: "R0",
ISP: "I0",
ASN: "0",
City: "C0",
}
scope := server.GetFilterGeoIPScope(geoIPData)
if scope != GeoIPScopeRegion {
t.Fatalf("unexpected scope: %b", scope)
}
// Test: ISP-only scope
filteredTactics = `
"FilteredTactics" : [
{
"Filter" : {
"ISPs": ["I1", "I2", "I3"]
}
},
{
"Filter" : {
"ISPs": ["I4", "I5", "I6"]
}
}
]
`
reload()
scope = server.GetFilterGeoIPScope(geoIPData)
if scope != GeoIPScopeISP {
t.Fatalf("unexpected scope: %b", scope)
}
// Test: ASN-only scope
filteredTactics = `
"FilteredTactics" : [
{
"Filter" : {
"ASNs": ["1", "2", "3"]
}
},
{
"Filter" : {
"ASNs": ["4", "5", "6"]
}
}
]
`
reload()
scope = server.GetFilterGeoIPScope(geoIPData)
if scope != GeoIPScopeASN {
t.Fatalf("unexpected scope: %b", scope)
}
// Test: City-only scope
filteredTactics = `
"FilteredTactics" : [
{
"Filter" : {
"Cities": ["C1", "C2", "C3"]
}
},
{
"Filter" : {
"Cities": ["C4", "C5", "C6"]
}
}
]
`
reload()
scope = server.GetFilterGeoIPScope(geoIPData)
if scope != GeoIPScopeCity {
t.Fatalf("unexpected scope: %b", scope)
}
// Test: full scope
filteredTactics = `
"FilteredTactics" : [
{
"Filter" : {
"Regions": ["R1", "R2", "R3"]
}
},
{
"Filter" : {
"ISPs": ["I1", "I2", "I3"]
}
},
{
"Filter" : {
"ASNs": ["1", "2", "3"]
}
},
{
"Filter" : {
"Cities": ["C4", "C5", "C6"]
}
}
]
`
reload()
scope = server.GetFilterGeoIPScope(geoIPData)
if scope != GeoIPScopeRegion|GeoIPScopeISP|GeoIPScopeASN|GeoIPScopeCity {
t.Fatalf("unexpected scope: %b", scope)
}
// Test: conditional scopes
filteredTactics = `
"FilteredTactics" : [
{