Repository navigation
Expand file tree
/
Copy pathinvoke_test.go
More file actions
860 lines (804 loc) · 24.7 KB
/
Copy pathinvoke_test.go
File metadata and controls
860 lines (804 loc) · 24.7 KB
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
package libXray
import (
"bytes"
"encoding/base64"
"encoding/json"
"io"
"os"
"path/filepath"
"strings"
"testing"
"github.com/metacubex/age"
"github.com/metacubex/age/armor"
"github.com/xtls/libxray/nodep"
"github.com/xtls/xray-core/common/geodata"
"github.com/xtls/xray-core/infra/conf"
"google.golang.org/protobuf/proto"
)
type testResponse struct {
Success bool `json:"success"`
Data json.RawMessage `json:"data,omitempty"`
Err string `json:"error,omitempty"`
}
func invokeForTest(t *testing.T, method LibXrayMethod, payload any) testResponse {
t.Helper()
rawPayload, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
rawRequest, err := json.Marshal(&LibXrayInvokeRequest{
APIVersion: LibXrayAPIVersion,
Method: method,
Payload: rawPayload,
})
if err != nil {
t.Fatal(err)
}
var response testResponse
if err := json.Unmarshal([]byte(Invoke(string(rawRequest))), &response); err != nil {
t.Fatal(err)
}
return response
}
func invokeRawForTest(t *testing.T, requestJSON string) testResponse {
t.Helper()
var response testResponse
if err := json.Unmarshal([]byte(Invoke(requestJSON)), &response); err != nil {
t.Fatal(err)
}
return response
}
func requireNoDataObject(t *testing.T, response testResponse) {
t.Helper()
if got := string(response.Data); got != "{}" {
t.Fatalf("data = %s, want {}", got)
}
}
func decodeDataObject[T any](t *testing.T, response testResponse) T {
t.Helper()
if !json.Valid(response.Data) {
t.Fatalf("data is not valid JSON: %s", response.Data)
}
var object map[string]json.RawMessage
if err := json.Unmarshal(response.Data, &object); err != nil {
t.Fatalf("data is not an object: %s", response.Data)
}
var value T
if err := json.Unmarshal(response.Data, &value); err != nil {
t.Fatal(err)
}
return value
}
func decodeShareConfig(t *testing.T, response testResponse) conf.Config {
t.Helper()
return decodeDataObject[conf.Config](t, response)
}
func writeGeoSiteDatForTest(t *testing.T, path string) {
t.Helper()
data, err := proto.Marshal(&geodata.GeoSiteList{
Entry: []*geodata.GeoSite{
{
Code: "TEST",
Domain: []*geodata.Domain{
{
Type: geodata.Domain_Domain,
Value: "example.com",
Attribute: []*geodata.Domain_Attribute{
{
Key: "ads",
TypedValue: &geodata.Domain_Attribute_BoolValue{
BoolValue: true,
},
},
},
},
},
},
},
})
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, data, 0o644); err != nil {
t.Fatal(err)
}
}
func testVmessPayloadBase64() string {
const vmessJSON = `{"add":"127.0.0.1","port":1080,"id":"00000000-0000-0000-0000-000000000000","aid":0,"scy":"auto"}`
return base64.StdEncoding.EncodeToString([]byte(vmessJSON))
}
func testXrayConfig(t *testing.T) any {
t.Helper()
decoded, err := base64.StdEncoding.DecodeString(testVmessPayloadBase64())
if err != nil {
t.Fatal(err)
}
var vmessConfig struct {
Add string `json:"add"`
Port int `json:"port"`
ID string `json:"id"`
AID int `json:"aid"`
Scy string `json:"scy"`
}
if err := json.Unmarshal(decoded, &vmessConfig); err != nil {
t.Fatal(err)
}
return struct {
Log any `json:"log"`
Inbounds []any `json:"inbounds"`
Outbounds []any `json:"outbounds"`
}{
Log: struct {
Loglevel string `json:"loglevel"`
}{Loglevel: "debug"},
Inbounds: []any{
struct {
Port int `json:"port"`
Protocol string `json:"protocol"`
Settings any `json:"settings"`
}{
Port: 1080,
Protocol: "socks",
Settings: struct {
Auth string `json:"auth"`
}{Auth: "noauth"},
},
},
Outbounds: []any{
struct {
Protocol string `json:"protocol"`
Settings any `json:"settings"`
}{
Protocol: "vmess",
Settings: struct {
Vnext []any `json:"vnext"`
}{
Vnext: []any{
struct {
Address string `json:"address"`
Port int `json:"port"`
Users []any `json:"users"`
}{
Address: vmessConfig.Add,
Port: vmessConfig.Port,
Users: []any{
struct {
ID string `json:"id"`
AlterID int `json:"alterId"`
Security string `json:"security"`
}{
ID: vmessConfig.ID,
AlterID: vmessConfig.AID,
Security: vmessConfig.Scy,
},
},
},
},
},
},
},
}
}
func TestInvokeTestXray(t *testing.T) {
xrayJSON, err := json.Marshal(testXrayConfig(t))
if err != nil {
t.Fatal(err)
}
response := invokeForTest(
t,
LibXrayMethodTestXray,
TestXrayRequest{XrayJson: string(xrayJSON)},
)
if !response.Success {
t.Fatalf("TestXray failed: %s", response.Err)
}
requireNoDataObject(t, response)
}
func TestInvokeTestXrayConstructsWithoutStarting(t *testing.T) {
logPath := filepath.Join(t.TempDir(), "error.log")
config, err := json.Marshal(map[string]any{
"log": map[string]any{"error": logPath, "loglevel": "debug"},
"inbounds": []any{
map[string]any{"tag": "tunIn", "protocol": "tun", "settings": map[string]any{"name": "TestXrayMustNotCreate", "mtu": 1500}},
},
"outbounds": []any{
map[string]any{"protocol": "freedom", "tag": "direct"},
},
})
if err != nil {
t.Fatal(err)
}
response := invokeForTest(t, LibXrayMethodTestXray, TestXrayRequest{XrayJson: string(config)})
if !response.Success {
t.Fatalf("testXray must construct handlers without starting the TUN: %s", response.Err)
}
requireNoDataObject(t, response)
if _, err := os.Stat(logPath); err != nil {
t.Fatalf("testXray did not construct the configured file logger: %v", err)
}
response = invokeForTest(t, LibXrayMethodTestXray, TestXrayRequest{XrayJson: `{"outbounds":[{"protocol":"unknown"}]}`})
if response.Success || string(response.Data) != "null" {
t.Fatalf("testXray must still reject invalid core configuration: %+v", response)
}
}
func TestInvokeTestXrayReturnsConstructionError(t *testing.T) {
response := invokeForTest(t, LibXrayMethodTestXray, TestXrayRequest{XrayJson: `{
"log":{"loglevel":"none"},
"outbounds":[{"protocol":"freedom","tag":"direct"}],
"routing":{"rules":[{"domain":["example.com"],"balancerTag":"missing"}]}
}`})
if response.Success || string(response.Data) != "null" || !strings.Contains(response.Err, "balancer missing not found") {
t.Fatalf("testXray must expose the core construction error: %+v", response)
}
}
func TestInvokeTestXrayDoesNotReadConfigPath(t *testing.T) {
configPath := filepath.Join(t.TempDir(), "xray.json")
configJSON, err := json.Marshal(testXrayConfig(t))
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(configPath, configJSON, 0o600); err != nil {
t.Fatal(err)
}
response := invokeForTest(
t,
LibXrayMethodTestXray,
TestXrayRequest{XrayJson: configPath},
)
if response.Success {
t.Fatal("testXray should parse xrayJson instead of reading a path")
}
}
func TestInvokeRunXray(t *testing.T) {
xrayJSON, err := json.Marshal(testXrayConfig(t))
if err != nil {
t.Fatal(err)
}
response := invokeForTest(
t,
LibXrayMethodRunXray,
RunXrayRequest{XrayJson: string(xrayJSON)},
)
defer xrayStopForTest(t)
if !response.Success {
t.Fatalf("RunXray failed: %s", response.Err)
}
requireNoDataObject(t, response)
}
func TestInvokeRunXrayAppliesConfigEnv(t *testing.T) {
const key = "XRAY_LIBXRAY_CONFIG_ENV_TEST"
t.Setenv(key, "")
rawConfig, err := json.Marshal(testXrayConfig(t))
if err != nil {
t.Fatal(err)
}
var config map[string]any
if err := json.Unmarshal(rawConfig, &config); err != nil {
t.Fatal(err)
}
config["env"] = map[string]string{key: "configured"}
xrayJSON, err := json.Marshal(config)
if err != nil {
t.Fatal(err)
}
response := invokeForTest(
t,
LibXrayMethodRunXray,
RunXrayRequest{XrayJson: string(xrayJSON)},
)
defer xrayStopForTest(t)
if !response.Success {
t.Fatalf("RunXray failed: %s", response.Err)
}
if got := os.Getenv(key); got != "configured" {
t.Fatalf("config env = %q, want configured", got)
}
}
func TestInvokeXrayVersion(t *testing.T) {
response := invokeForTest(t, LibXrayMethodXrayVersion, nil)
if !response.Success {
t.Fatalf("XrayVersion failed: %s", response.Err)
}
version := decodeDataObject[XrayVersionResponse](t, response)
if version.Version == "" {
t.Fatal("Xray version should not be empty")
}
}
func TestInvokeGetFreePortsExclusions(t *testing.T) {
response := invokeRawForTest(t, `{"apiVersion":3,"method":"getFreePorts","payload":{"count":2,"excludePorts":[18587,9000,18587]}}`)
if !response.Success {
t.Fatalf("GetFreePorts failed: %s", response.Err)
}
ports := decodeDataObject[GetFreePortsResponse](t, response).Ports
if len(ports) != 2 || ports[0] == ports[1] {
t.Fatalf("ports = %v, want two distinct ports", ports)
}
for _, port := range ports {
if port == 18587 || port == 9000 {
t.Fatalf("excluded port returned: %d", port)
}
}
response = invokeForTest(t, LibXrayMethodGetFreePorts, GetFreePortsRequest{
Count: 1, ExcludePorts: []int{0},
})
if response.Success || !strings.Contains(response.Err, "excluded port") {
t.Fatalf("invalid exclusion response = %+v", response)
}
response = invokeRawForTest(t, `{"apiVersion":3,"method":"getFreePorts","payload":{"count":1,"excludePorts":["18587"]}}`)
if response.Success {
t.Fatal("string exclusion should fail JSON decoding")
}
}
func TestInvokeMapResponseShape(t *testing.T) {
response := invokeForTest(t, LibXrayMethodGetFreePorts, GetFreePortsRequest{Count: 1})
if !response.Success {
t.Fatalf("GetFreePorts failed: %s", response.Err)
}
ports := decodeDataObject[GetFreePortsResponse](t, response)
if len(ports.Ports) != 1 {
t.Fatalf("ports = %v", ports.Ports)
}
response = invokeForTest(t, LibXrayMethodGetXrayState, nil)
if !response.Success {
t.Fatalf("GetXrayState failed: %s", response.Err)
}
_ = decodeDataObject[GetXrayStateResponse](t, response)
rawConfig, err := json.Marshal(testXrayConfig(t))
if err != nil {
t.Fatal(err)
}
response = invokeForTest(
t,
LibXrayMethodConvertXrayJsonToShareLinks,
ConvertXrayJsonToShareLinksRequest{XrayJson: string(rawConfig)},
)
if !response.Success {
t.Fatalf("ConvertXrayJsonToShareLinks failed: %s", response.Err)
}
links := decodeDataObject[ConvertXrayJsonToShareLinksResponse](t, response)
if links.Links == "" {
t.Fatal("links should not be empty")
}
}
func TestInvokeConvertShareLinksFiltersBuildInvalidOutbounds(t *testing.T) {
const validName = "Valid"
links := "vless://2418d087-648k-4990-86e8-19dca1d006d3@invalid.example:443?encryption=none&security=tls&sni=invalid.example&fp=chrome\n" +
"vless://12345678-abcd-abcd-abcd-123456789abc@valid.example:443?encryption=none&security=tls&sni=valid.example&fp=chrome#" + validName
response := invokeForTest(
t,
LibXrayMethodConvertShareLinksToXrayJson,
ConvertShareLinksToXrayJsonRequest{Text: links},
)
if !response.Success {
t.Fatalf("ConvertShareLinksToXrayJson failed: %s", response.Err)
}
config := decodeShareConfig(t, response)
if len(config.OutboundConfigs) != 1 {
t.Fatalf("outbounds = %d, want 1", len(config.OutboundConfigs))
}
if config.OutboundConfigs[0].Tag != validName {
t.Fatalf("tag = %q, want %q", config.OutboundConfigs[0].Tag, validName)
}
if config.OutboundConfigs[0].SendThrough != nil {
t.Fatalf("sendThrough = %v, want nil", config.OutboundConfigs[0].SendThrough)
}
}
func TestInvokeHysteria2ShareRoundTrip(t *testing.T) {
for _, scheme := range []string{"hysteria2", "hy2"} {
t.Run(scheme, func(t *testing.T) {
response := invokeForTest(t, LibXrayMethodConvertShareLinksToXrayJson,
ConvertShareLinksToXrayJsonRequest{Text: scheme + "://password@example.com:443?obfs=salamander&obfs-password=secret#Test"})
if !response.Success {
t.Fatal(response.Err)
}
config := decodeShareConfig(t, response)
if len(config.OutboundConfigs) != 1 || config.OutboundConfigs[0].Protocol != "hysteria" || config.OutboundConfigs[0].Tag != "Test" {
t.Fatalf("unexpected Hysteria2 projection: %s", response.Data)
}
if result := invokeForTest(t, LibXrayMethodTestXray, TestXrayRequest{XrayJson: string(response.Data)}); !result.Success {
t.Fatal(result.Err)
}
result := invokeForTest(t, LibXrayMethodConvertXrayJsonToShareLinks,
ConvertXrayJsonToShareLinksRequest{XrayJson: string(response.Data)})
if !result.Success {
t.Fatal(result.Err)
}
links := decodeDataObject[ConvertXrayJsonToShareLinksResponse](t, result)
if !strings.HasPrefix(links.Links, "hysteria2://") || !strings.HasSuffix(links.Links, "#Test") {
t.Fatalf("unexpected Hysteria2 link: %s", links.Links)
}
})
}
}
func TestInvokeConvertShareLinksRejectsRemovedFormats(t *testing.T) {
for _, test := range []struct {
name, text string
}{
{"Clash", "proxies:\n - {type: vless, server: example.com, port: 443, uuid: 12345678-abcd-abcd-abcd-123456789abc}"},
{"HysteriaRealm", "hysteria2+realm://token@example.com/realm?auth=password"},
} {
t.Run(test.name, func(t *testing.T) {
response := invokeForTest(t, LibXrayMethodConvertShareLinksToXrayJson,
ConvertShareLinksToXrayJsonRequest{Text: test.text})
if response.Success || response.Err != "unsupported share format" {
t.Fatalf("success = %v, error = %q", response.Success, response.Err)
}
if string(response.Data) != "null" {
t.Fatalf("data = %s, want null", response.Data)
}
})
}
}
func TestInvokeConvertShareLinksReturnsProjectedObject(t *testing.T) {
const publicKey = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
link := "vless://12345678-abcd-abcd-abcd-123456789abc@example.com:443" +
"?encryption=none&type=xhttp&host=cdn.example.com&path=%2Fx&mode=stream-up" +
"&security=reality&sni=example.com&fp=chrome&pbk=" + publicKey + "&sid=abcd"
response := invokeForTest(
t,
LibXrayMethodConvertShareLinksToXrayJson,
ConvertShareLinksToXrayJsonRequest{Text: link},
)
if !response.Success {
t.Fatalf("ConvertShareLinksToXrayJson failed: %s", response.Err)
}
config := decodeShareConfig(t, response)
var root map[string]json.RawMessage
if err := json.Unmarshal(response.Data, &root); err != nil {
t.Fatalf("config is not an object: %s", response.Data)
}
if len(root) != 1 || root["outbounds"] == nil {
t.Fatalf("config root = %s, want only outbounds", response.Data)
}
for _, field := range []string{"publicKey", "target", "dest", "proxySettings", "sockopt"} {
if bytes.Contains(response.Data, []byte(`"`+field+`"`)) {
t.Fatalf("config contains unsupported field %q: %s", field, response.Data)
}
}
if !bytes.Contains(response.Data, []byte(`"password":"`+publicKey+`"`)) {
t.Fatalf("config did not canonicalize REALITY password: %s", response.Data)
}
if len(config.OutboundConfigs) != 1 {
t.Fatalf("outbounds = %d, want 1", len(config.OutboundConfigs))
}
if _, err := config.OutboundConfigs[0].Build(); err != nil {
t.Fatalf("projected outbound does not build: %v", err)
}
}
func TestInvokeConvertShareLinksPreservesKCPParameters(t *testing.T) {
response := invokeForTest(t, LibXrayMethodConvertShareLinksToXrayJson,
ConvertShareLinksToXrayJsonRequest{Text: "vless://12345678-abcd-abcd-abcd-123456789abc@127.0.0.1:443?type=kcp&mtu=1350&tti=30"})
if !response.Success {
t.Fatalf("ConvertShareLinksToXrayJson failed: %s", response.Err)
}
config := decodeShareConfig(t, response)
if len(config.OutboundConfigs) != 1 {
t.Fatalf("outbounds = %d, want 1", len(config.OutboundConfigs))
}
stream := config.OutboundConfigs[0].StreamSetting
if stream == nil || stream.KCPSettings == nil {
t.Fatal("KCP settings missing from Invoke response")
}
kcp := stream.KCPSettings
if kcp.Mtu == nil || *kcp.Mtu != 1350 || kcp.Tti == nil || *kcp.Tti != 30 {
t.Fatalf("unexpected KCP parameters: %s", response.Data)
}
}
func TestInvokeAgeKeyGenerationAndConversion(t *testing.T) {
generated := invokeForTest(
t,
LibXrayMethodGenerateAgeKeyPair,
GenerateAgeKeyPairRequest{KeyType: AgeKeyTypeX25519},
)
if !generated.Success {
t.Fatalf("GenerateAgeKeyPair failed: %s", generated.Err)
}
pair := decodeDataObject[GenerateAgeKeyPairResponse](t, generated)
if pair.SecretKey == "" || pair.PublicKey == "" {
t.Fatalf("generated pair is incomplete: %+v", pair)
}
recipient, err := age.ParseX25519Recipient(pair.PublicKey)
if err != nil {
t.Fatal(err)
}
var encrypted bytes.Buffer
armored := armor.NewWriter(&encrypted)
writer, err := age.Encrypt(armored, recipient)
if err != nil {
t.Fatal(err)
}
const link = "vless://12345678-abcd-abcd-abcd-123456789abc@example.com:443?encryption=none&security=tls&sni=example.com#AgeInvoke"
if _, err := io.WriteString(writer, link); err != nil {
t.Fatal(err)
}
if err := writer.Close(); err != nil {
t.Fatal(err)
}
if err := armored.Close(); err != nil {
t.Fatal(err)
}
converted := invokeForTest(
t,
LibXrayMethodConvertShareLinksToXrayJson,
ConvertShareLinksToXrayJsonRequest{
Text: encrypted.String(),
Age: &AgeDecryptConfig{SecretKey: pair.SecretKey},
},
)
if !converted.Success {
t.Fatalf("ConvertShareLinksToXrayJson failed: %s", converted.Err)
}
config := decodeShareConfig(t, converted)
if len(config.OutboundConfigs) != 1 {
t.Fatalf("outbounds = %d, want 1", len(config.OutboundConfigs))
}
}
func TestInvokeAgeFailuresHaveNullData(t *testing.T) {
for _, test := range []struct {
method LibXrayMethod
payload any
}{
{
method: LibXrayMethodGenerateAgeKeyPair,
payload: GenerateAgeKeyPairRequest{KeyType: AgeKeyType("invalid")},
},
{
method: LibXrayMethodConvertShareLinksToXrayJson,
payload: ConvertShareLinksToXrayJsonRequest{
Text: "-----BEGIN AGE ENCRYPTED FILE-----\ninvalid",
},
},
} {
response := invokeForTest(t, test.method, test.payload)
if response.Success {
t.Fatalf("method %q unexpectedly succeeded", test.method)
}
if got := string(response.Data); got != "null" {
t.Fatalf("method %q data = %s, want null", test.method, got)
}
if response.Err == "" {
t.Fatalf("method %q returned no error", test.method)
}
}
}
func TestInvokeConvertShareLinksFailsWhenAllOutboundsAreBuildInvalid(t *testing.T) {
response := invokeForTest(
t,
LibXrayMethodConvertShareLinksToXrayJson,
ConvertShareLinksToXrayJsonRequest{
Text: "vless://2418d087-648k-4990-86e8-19dca1d006d3@invalid.example:443?encryption=none&security=tls&sni=invalid.example&fp=chrome",
},
)
if response.Success {
t.Fatal("ConvertShareLinksToXrayJson should fail when all outbounds are invalid")
}
if !strings.Contains(response.Err, "no valid outbound found") {
t.Fatalf("error = %q", response.Err)
}
if string(response.Data) != "null" {
t.Fatalf("data = %s, want null", response.Data)
}
}
func TestInvokePingBatchReturnsPerItemFailures(t *testing.T) {
response := invokeForTest(
t,
LibXrayMethodPingBatch,
PingBatchRequest{
Configs: []PingBatchItemRequest{
{
XrayJson: "not JSON",
},
},
Timeout: 1,
URL: "https://example.com",
},
)
if !response.Success {
t.Fatalf("PingBatch failed: %s", response.Err)
}
batch := decodeDataObject[PingBatchResponse](t, response)
if len(batch.Results) != 1 {
t.Fatalf("results = %d, want 1", len(batch.Results))
}
result := batch.Results[0]
if result.Success {
t.Fatal("missing config unexpectedly succeeded")
}
if result.Delay != nodep.PingDelayError {
t.Fatalf("delay = %d, want %d", result.Delay, nodep.PingDelayError)
}
if result.Error == "" {
t.Fatal("missing config has no error")
}
}
func TestInvokePingBatchRejectsInvalidRequest(t *testing.T) {
response := invokeForTest(
t,
LibXrayMethodPingBatch,
PingBatchRequest{
Timeout: 1,
URL: "https://example.com",
},
)
if response.Success {
t.Fatal("PingBatch should reject an empty config list")
}
if !strings.Contains(response.Err, "configs are empty") {
t.Fatalf("error = %q", response.Err)
}
if got := string(response.Data); got != "null" {
t.Fatalf("data = %s, want null", got)
}
}
func TestInvokePingBatchRejectsMoreThanFiveConfigs(t *testing.T) {
configs := make([]PingBatchItemRequest, 6)
for i := range configs {
configs[i] = PingBatchItemRequest{
XrayJson: `{"outbounds":[{"protocol":"freedom"}]}`,
}
}
response := invokeForTest(
t,
LibXrayMethodPingBatch,
PingBatchRequest{
Configs: configs,
Timeout: 1,
URL: "https://example.com",
},
)
if response.Success {
t.Fatal("PingBatch should reject more than five configs")
}
if !strings.Contains(response.Err, "more than 5 configs") {
t.Fatalf("error = %q", response.Err)
}
if got := string(response.Data); got != "null" {
t.Fatalf("data = %s, want null", got)
}
}
func TestInvokeCountGeoDataUsesPayloadDatDir(t *testing.T) {
datDir := t.TempDir()
writeGeoSiteDatForTest(t, filepath.Join(datDir, "geosite.dat"))
response := invokeForTest(
t,
LibXrayMethodCountGeoData,
CountGeoDataRequest{
Name: "geosite",
GeoType: "domain",
DatDir: datDir,
},
)
if !response.Success {
t.Fatalf("CountGeoData failed: %s", response.Err)
}
requireNoDataObject(t, response)
output, err := os.ReadFile(filepath.Join(datDir, "geosite.json"))
if err != nil {
t.Fatal(err)
}
if !json.Valid(output) {
t.Fatalf("geosite.json is not valid JSON: %s", output)
}
var list struct {
CategoryCount int `json:"categoryCount,omitempty"`
RuleCount int `json:"ruleCount,omitempty"`
}
if err := json.Unmarshal(output, &list); err != nil {
t.Fatal(err)
}
if list.CategoryCount != 1 || list.RuleCount != 1 {
t.Fatalf("unexpected geosite counts: %+v", list)
}
}
func TestInvokeUnknownMethod(t *testing.T) {
response := invokeForTest(t, LibXrayMethod("unknown"), nil)
if response.Success {
t.Fatal("unknown method should fail")
}
}
func TestInvokeRemovedMethods(t *testing.T) {
for _, method := range []string{"ping", "runXrayFromJson", "deriveAgePublicKey", "checkRoute"} {
response := invokeRawForTest(
t,
`{"apiVersion":3,"method":"`+method+`","payload":{}}`,
)
if response.Success {
t.Fatalf("removed method %q should fail", method)
}
if response.Err != "unknown method" {
t.Fatalf("method %q error = %q, want unknown method", method, response.Err)
}
}
}
func TestInvokeRejectsOversizedRequest(t *testing.T) {
response := invokeRawForTest(t, strings.Repeat(" ", maxInvokeJSONBytes+1))
if response.Success {
t.Fatal("oversized request should fail")
}
if response.Err != "invoke request exceeds the 16 MiB size limit" {
t.Fatalf("error = %q", response.Err)
}
if got := string(response.Data); got != "null" {
t.Fatalf("data = %s, want null", got)
}
}
func TestInvokeRejectsOversizedResponse(t *testing.T) {
responseText := encodeInvokeResponse(
struct {
Text string `json:"text"`
}{Text: strings.Repeat("x", maxInvokeJSONBytes)},
nil,
)
var response testResponse
if err := json.Unmarshal([]byte(responseText), &response); err != nil {
t.Fatal(err)
}
if response.Success {
t.Fatal("oversized response should fail")
}
if response.Err != "invoke response exceeds the 16 MiB size limit" {
t.Fatalf("error = %q", response.Err)
}
if got := string(response.Data); got != "null" {
t.Fatalf("data = %s, want null", got)
}
}
func TestInvokeAPIVersion(t *testing.T) {
response := invokeRawForTest(t, `{"method":"xrayVersion"}`)
if response.Success {
t.Fatal("omitted apiVersion should fail")
}
for _, version := range []string{"2", "4", "5"} {
response = invokeRawForTest(t, `{"apiVersion":`+version+`,"method":"xrayVersion"}`)
if response.Success {
t.Fatalf("v%s apiVersion should fail", version)
}
if got := string(response.Data); got != "null" {
t.Fatalf("data = %s, want null", got)
}
}
response = invokeRawForTest(t, `{"apiVersion":3,"method":"xrayVersion"}`)
if !response.Success {
t.Fatalf("v3 apiVersion should succeed: %s", response.Err)
}
}
func TestInvokeNoDataResponseShape(t *testing.T) {
response := invokeForTest(t, LibXrayMethodStopXray, nil)
if !response.Success {
t.Fatalf("StopXray failed: %s", response.Err)
}
requireNoDataObject(t, response)
response = invokeRawForTest(t, `{"apiVersion":3,"method":"runXray","payload":"invalid"}`)
if response.Success {
t.Fatal("invalid runXray payload should fail")
}
if got := string(response.Data); got != "null" {
t.Fatalf("data = %s, want null", got)
}
}
func TestInvokeIgnoresTopLevelEnv(t *testing.T) {
const key = "XRAY_LIBXRAY_UNKNOWN_ENV_TEST"
_ = os.Unsetenv(key)
t.Cleanup(func() { _ = os.Unsetenv(key) })
requestJSON := `{"apiVersion":3,"method":"xrayVersion","env":{"` + key + `":"/tmp"}}`
var response testResponse
if err := json.Unmarshal([]byte(Invoke(requestJSON)), &response); err != nil {
t.Fatal(err)
}
if !response.Success {
t.Fatalf("top-level env should be ignored: %s", response.Err)
}
if _, found := os.LookupEnv(key); found {
t.Fatal("top-level env should not be set")
}
}
func xrayStopForTest(t *testing.T) {
t.Helper()
response := invokeForTest(t, LibXrayMethodStopXray, nil)
if !response.Success {
t.Fatalf("StopXray failed: %s", response.Err)
}
}