精简P2: 剥离 xray-core API 客户端: StatsService 改 protowire 线缆级实现(QueryStats/GetUsersStats 字段号按核心 proto 复刻, agent 流量上报与本地流量任务不受影响); Handler/Routing 变更类 RPC 无法脱离核心类型化配置构建, 统一降级 ErrHotApplyUnavailable(调用方既有兜底: 热更新->重启核心, balancer 视图报未运行, 节点桥探测放弃, IP 限连临时断开仅记日志); ValidateOutboundConfig 改纯 JSON 实现, 精确复刻核心 v26.7.11 未加密 vless/trojan 公网禁令(含私有 IP/域名匹配表与原文报错, 且同核心一样只查扁平 address 形式); 删除 buildUserAccount 及 SS/WG/e2e 旧测试, 流量增量测试改线缆级假服务器并新增 stock protobuf 服务器互操作测试
This commit is contained in:
+425
-566
File diff suppressed because it is too large
Load Diff
@@ -1,257 +0,0 @@
|
||||
package xray
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestXrayAPI_E2E exercises the gRPC hot-apply surface (outbounds, inbounds,
|
||||
// routing) against a real xray-core process. It validates the exact error
|
||||
// texts IsMissingHandlerErr/IsExistingTagErr rely on, and that replacing the
|
||||
// routing config keeps the api rule working.
|
||||
//
|
||||
// Skipped unless XRAY_E2E_BINARY points at an xray executable built from the
|
||||
// same xray-core version as go.mod, e.g.:
|
||||
//
|
||||
// go install github.com/xtls/xray-core/main@<version from go.mod>
|
||||
// XRAY_E2E_BINARY=$GOBIN/main go test ./internal/xray -run TestXrayAPI_E2E -v
|
||||
func TestXrayAPI_E2E(t *testing.T) {
|
||||
bin := os.Getenv("XRAY_E2E_BINARY")
|
||||
if bin == "" {
|
||||
t.Skip("set XRAY_E2E_BINARY to an xray binary to run this test")
|
||||
}
|
||||
|
||||
apiPort := freePort(t)
|
||||
cfg := map[string]any{
|
||||
"log": map[string]any{"loglevel": "warning"},
|
||||
"api": map[string]any{
|
||||
"services": []string{"HandlerService", "StatsService", "RoutingService"},
|
||||
"tag": "api",
|
||||
},
|
||||
"inbounds": []any{
|
||||
map[string]any{
|
||||
"listen": "127.0.0.1",
|
||||
"port": apiPort,
|
||||
"protocol": "tunnel",
|
||||
"settings": map[string]any{"rewriteAddress": "127.0.0.1"},
|
||||
"tag": "api",
|
||||
},
|
||||
},
|
||||
"outbounds": []any{
|
||||
map[string]any{"protocol": "freedom", "settings": map[string]any{}, "tag": "direct"},
|
||||
map[string]any{"protocol": "blackhole", "settings": map[string]any{}, "tag": "blocked"},
|
||||
},
|
||||
"routing": map[string]any{
|
||||
"domainStrategy": "AsIs",
|
||||
"rules": []any{
|
||||
map[string]any{"type": "field", "inboundTag": []string{"api"}, "outboundTag": "api"},
|
||||
},
|
||||
},
|
||||
"policy": map[string]any{
|
||||
"levels": map[string]any{
|
||||
"0": map[string]any{"statsUserOnline": true},
|
||||
},
|
||||
},
|
||||
"stats": map[string]any{},
|
||||
}
|
||||
cfgBytes, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfgPath := filepath.Join(t.TempDir(), "config.json")
|
||||
if err := os.WriteFile(cfgPath, cfgBytes, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cmd := exec.Command(bin, "-c", cfgPath)
|
||||
cmd.Stdout = os.Stderr
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("failed to start xray: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = cmd.Process.Kill()
|
||||
_, _ = cmd.Process.Wait()
|
||||
}()
|
||||
|
||||
waitForPort(t, apiPort)
|
||||
|
||||
api := XrayAPI{}
|
||||
if err := api.Init(apiPort); err != nil {
|
||||
t.Fatalf("api init: %v", err)
|
||||
}
|
||||
defer api.Close()
|
||||
|
||||
// --- outbounds ---
|
||||
socksOutbound := []byte(`{"protocol":"socks","settings":{"servers":[{"address":"127.0.0.1","port":10808}]},"tag":"test-out"}`)
|
||||
if err := api.AddOutbound(socksOutbound); err != nil {
|
||||
t.Fatalf("AddOutbound: %v", err)
|
||||
}
|
||||
err = api.AddOutbound(socksOutbound)
|
||||
if err == nil {
|
||||
t.Fatal("duplicate AddOutbound must fail")
|
||||
}
|
||||
if !IsExistingTagErr(err) {
|
||||
t.Fatalf("duplicate AddOutbound error not matched by IsExistingTagErr: %q", err)
|
||||
}
|
||||
if err := api.DelOutbound("test-out"); err != nil {
|
||||
t.Fatalf("DelOutbound: %v", err)
|
||||
}
|
||||
// xray's outbound manager treats removal of an unknown tag as a no-op.
|
||||
if err := api.DelOutbound("test-out"); err != nil && !IsMissingHandlerErr(err) {
|
||||
t.Fatalf("removing a missing outbound: unexpected error %q", err)
|
||||
}
|
||||
|
||||
// --- inbounds ---
|
||||
vlessPort := freePort(t)
|
||||
vlessInbound := fmt.Appendf(nil,
|
||||
`{"listen":"127.0.0.1","port":%d,"protocol":"vless","settings":{"clients":[{"id":"a17e367c-2074-4d3e-aaeb-fbef5dfde7e7","email":"e2e"}],"decryption":"none"},"tag":"test-in"}`,
|
||||
vlessPort)
|
||||
if err := api.AddInbound(vlessInbound); err != nil {
|
||||
t.Fatalf("AddInbound: %v", err)
|
||||
}
|
||||
err = api.AddInbound(vlessInbound)
|
||||
if err == nil {
|
||||
t.Fatal("duplicate AddInbound must fail")
|
||||
}
|
||||
if !IsExistingTagErr(err) {
|
||||
t.Fatalf("duplicate AddInbound error not matched by IsExistingTagErr: %q", err)
|
||||
}
|
||||
if err := api.DelInbound("test-in"); err != nil {
|
||||
t.Fatalf("DelInbound: %v", err)
|
||||
}
|
||||
err = api.DelInbound("test-in")
|
||||
if err == nil {
|
||||
t.Fatal("removing a missing inbound must fail")
|
||||
}
|
||||
if !IsMissingHandlerErr(err) {
|
||||
t.Fatalf("missing inbound error not matched by IsMissingHandlerErr: %q", err)
|
||||
}
|
||||
|
||||
// --- online-stats API ---
|
||||
// statsUserOnline is enabled in the policy above; with no client
|
||||
// connections the call must succeed and return an empty set. This proves
|
||||
// the GetUsersStats plumbing against a real core (an older binary would
|
||||
// return Unimplemented here — see IsUnimplementedErr).
|
||||
online, err := api.GetOnlineUsers()
|
||||
if err != nil {
|
||||
t.Fatalf("GetOnlineUsers: %v", err)
|
||||
}
|
||||
if len(online) != 0 {
|
||||
t.Fatalf("expected no online users on an idle core, got %+v", online)
|
||||
}
|
||||
|
||||
// --- routing (rules + balancers replace) ---
|
||||
newRouting := []byte(`{
|
||||
"domainStrategy": "AsIs",
|
||||
"balancers": [{"tag":"b1","selector":["direct"]}],
|
||||
"rules": [
|
||||
{"type":"field","inboundTag":["api"],"outboundTag":"api"},
|
||||
{"type":"field","port":"6666","outboundTag":"blocked","ruleTag":"e2e-rule"},
|
||||
{"type":"field","port":"7777","balancerTag":"b1","ruleTag":"e2e-balancer-rule"}
|
||||
]
|
||||
}`)
|
||||
if err := api.ApplyRoutingConfig(newRouting); err != nil {
|
||||
t.Fatalf("ApplyRoutingConfig: %v", err)
|
||||
}
|
||||
// The replaced rule set still contains the api rule — the gRPC channel
|
||||
// must keep working after the swap.
|
||||
if err := api.AddOutbound([]byte(`{"protocol":"blackhole","settings":{},"tag":"post-routing"}`)); err != nil {
|
||||
t.Fatalf("api unusable after routing replace (api rule lost?): %v", err)
|
||||
}
|
||||
if err := api.DelOutbound("post-routing"); err != nil {
|
||||
t.Fatalf("DelOutbound after routing replace: %v", err)
|
||||
}
|
||||
|
||||
// --- route testing ---
|
||||
res, err := api.TestRoute(RouteTestRequest{IP: "1.2.3.4", Port: 6666, Network: "tcp"})
|
||||
if err != nil {
|
||||
t.Fatalf("TestRoute(port rule): %v", err)
|
||||
}
|
||||
if !res.Matched || res.OutboundTag != "blocked" {
|
||||
t.Fatalf("TestRoute(port rule) = %+v, want matched blocked", res)
|
||||
}
|
||||
res, err = api.TestRoute(RouteTestRequest{Domain: "example.com", Port: 7777, Network: "tcp"})
|
||||
if err != nil {
|
||||
t.Fatalf("TestRoute(balancer rule): %v", err)
|
||||
}
|
||||
if !res.Matched || res.OutboundTag != "direct" {
|
||||
t.Fatalf("TestRoute(balancer rule) = %+v, want matched direct", res)
|
||||
}
|
||||
// Note: current xray-core never populates OutboundGroupTags in PickRoute,
|
||||
// so GroupTags stays empty even for balancer rules — don't assert on it.
|
||||
res, err = api.TestRoute(RouteTestRequest{Domain: "example.com", Port: 9999, Network: "tcp"})
|
||||
if err != nil {
|
||||
t.Fatalf("TestRoute(no match): %v", err)
|
||||
}
|
||||
if res.Matched {
|
||||
t.Fatalf("TestRoute(no match) = %+v, want unmatched (default outbound)", res)
|
||||
}
|
||||
|
||||
// --- balancer info + override ---
|
||||
info, err := api.GetBalancerInfo("b1")
|
||||
if err != nil {
|
||||
t.Fatalf("GetBalancerInfo: %v", err)
|
||||
}
|
||||
if info.Override != "" {
|
||||
t.Fatalf("fresh balancer must have no override, got %q", info.Override)
|
||||
}
|
||||
if err := api.SetBalancerTarget("b1", "blocked"); err != nil {
|
||||
t.Fatalf("SetBalancerTarget: %v", err)
|
||||
}
|
||||
info, err = api.GetBalancerInfo("b1")
|
||||
if err != nil {
|
||||
t.Fatalf("GetBalancerInfo after override: %v", err)
|
||||
}
|
||||
if info.Override != "blocked" {
|
||||
t.Fatalf("override = %q, want blocked", info.Override)
|
||||
}
|
||||
res, err = api.TestRoute(RouteTestRequest{Domain: "example.com", Port: 7777, Network: "tcp"})
|
||||
if err != nil {
|
||||
t.Fatalf("TestRoute(overridden balancer): %v", err)
|
||||
}
|
||||
if res.OutboundTag != "blocked" {
|
||||
t.Fatalf("overridden balancer must route to blocked, got %+v", res)
|
||||
}
|
||||
if err := api.SetBalancerTarget("b1", ""); err != nil {
|
||||
t.Fatalf("SetBalancerTarget(clear): %v", err)
|
||||
}
|
||||
info, err = api.GetBalancerInfo("b1")
|
||||
if err != nil {
|
||||
t.Fatalf("GetBalancerInfo after clear: %v", err)
|
||||
}
|
||||
if info.Override != "" {
|
||||
t.Fatalf("override after clear = %q, want empty", info.Override)
|
||||
}
|
||||
}
|
||||
|
||||
func freePort(t *testing.T) int {
|
||||
t.Helper()
|
||||
l, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
return l.Addr().(*net.TCPAddr).Port
|
||||
}
|
||||
|
||||
func waitForPort(t *testing.T, port int) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(15 * time.Second)
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", port)
|
||||
for time.Now().Before(deadline) {
|
||||
conn, err := net.DialTimeout("tcp", addr, time.Second)
|
||||
if err == nil {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("xray api port %d did not open in time", port)
|
||||
}
|
||||
@@ -1,149 +0,0 @@
|
||||
package xray
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/xtls/xray-core/proxy/shadowsocks"
|
||||
"github.com/xtls/xray-core/proxy/shadowsocks_2022"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// decodeSSAccount decodes the typed message buildUserAccount produced for a
|
||||
// shadowsocks user. The type URL is what the running inbound casts on, so the
|
||||
// test asserts on it directly.
|
||||
func decodeSSAccount(t *testing.T, user map[string]any) (typeURL string, legacy *shadowsocks.Account, modern *shadowsocks_2022.Account) {
|
||||
t.Helper()
|
||||
tm, err := buildUserAccount("shadowsocks", user)
|
||||
if err != nil {
|
||||
t.Fatalf("buildUserAccount: %v", err)
|
||||
}
|
||||
if tm == nil {
|
||||
t.Fatal("buildUserAccount returned no account for shadowsocks")
|
||||
}
|
||||
typeURL = tm.Type
|
||||
switch {
|
||||
case strings.Contains(typeURL, "shadowsocks_2022"):
|
||||
modern = new(shadowsocks_2022.Account)
|
||||
if err := proto.Unmarshal(tm.Value, modern); err != nil {
|
||||
t.Fatalf("unmarshal shadowsocks_2022 account: %v", err)
|
||||
}
|
||||
case strings.Contains(typeURL, "shadowsocks"):
|
||||
legacy = new(shadowsocks.Account)
|
||||
if err := proto.Unmarshal(tm.Value, legacy); err != nil {
|
||||
t.Fatalf("unmarshal shadowsocks account: %v", err)
|
||||
}
|
||||
default:
|
||||
t.Fatalf("unexpected account type %q", typeURL)
|
||||
}
|
||||
return typeURL, legacy, modern
|
||||
}
|
||||
|
||||
func TestBuildUserAccountShadowsocksLegacyCiphers(t *testing.T) {
|
||||
tests := []struct {
|
||||
cipher string
|
||||
want shadowsocks.CipherType
|
||||
}{
|
||||
{"aes-128-gcm", shadowsocks.CipherType_AES_128_GCM},
|
||||
{"aead_aes_128_gcm", shadowsocks.CipherType_AES_128_GCM},
|
||||
{"aes-256-gcm", shadowsocks.CipherType_AES_256_GCM},
|
||||
{"AES-256-GCM", shadowsocks.CipherType_AES_256_GCM},
|
||||
{"aead_aes_256_gcm", shadowsocks.CipherType_AES_256_GCM},
|
||||
{"chacha20-poly1305", shadowsocks.CipherType_CHACHA20_POLY1305},
|
||||
{"chacha20-ietf-poly1305", shadowsocks.CipherType_CHACHA20_POLY1305},
|
||||
{"aead_chacha20_poly1305", shadowsocks.CipherType_CHACHA20_POLY1305},
|
||||
{"xchacha20-poly1305", shadowsocks.CipherType_XCHACHA20_POLY1305},
|
||||
{"xchacha20-ietf-poly1305", shadowsocks.CipherType_XCHACHA20_POLY1305},
|
||||
{"aead_xchacha20_poly1305", shadowsocks.CipherType_XCHACHA20_POLY1305},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.cipher, func(t *testing.T) {
|
||||
user := map[string]any{"email": "a@example.test", "password": "pw", "cipher": tt.cipher}
|
||||
typeURL, legacy, modern := decodeSSAccount(t, user)
|
||||
if modern != nil {
|
||||
t.Fatalf("cipher %q built a shadowsocks-2022 account (%s); the legacy inbound casts to *shadowsocks.MemoryAccount and panics the core", tt.cipher, typeURL)
|
||||
}
|
||||
if legacy.CipherType != tt.want {
|
||||
t.Fatalf("CipherType = %v, want %v", legacy.CipherType, tt.want)
|
||||
}
|
||||
if legacy.Password != "pw" {
|
||||
t.Fatalf("Password = %q, want %q", legacy.Password, "pw")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUserAccountShadowsocks2022Ciphers(t *testing.T) {
|
||||
for _, cipher := range []string{
|
||||
"2022-blake3-aes-128-gcm",
|
||||
"2022-blake3-aes-256-gcm",
|
||||
"2022-blake3-chacha20-poly1305",
|
||||
} {
|
||||
t.Run(cipher, func(t *testing.T) {
|
||||
user := map[string]any{"email": "a@example.test", "password": b64Key(7), "cipher": cipher}
|
||||
typeURL, _, modern := decodeSSAccount(t, user)
|
||||
if modern == nil {
|
||||
t.Fatalf("cipher %q built a legacy account (%s), want shadowsocks-2022", cipher, typeURL)
|
||||
}
|
||||
if modern.Key != b64Key(7) {
|
||||
t.Fatalf("Key = %q, want the client password", modern.Key)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildUserAccountShadowsocksReadsMethodKey covers the client maps taken
|
||||
// verbatim from an inbound's settings (the auto-renew path): they carry the
|
||||
// inbound's cipher under "method", never "cipher".
|
||||
func TestBuildUserAccountShadowsocksReadsMethodKey(t *testing.T) {
|
||||
user := map[string]any{"email": "a@example.test", "password": "pw", "method": "aes-256-gcm"}
|
||||
_, legacy, modern := decodeSSAccount(t, user)
|
||||
if modern != nil {
|
||||
t.Fatal("a client carrying only \"method\" must still build a legacy account")
|
||||
}
|
||||
if legacy.CipherType != shadowsocks.CipherType_AES_256_GCM {
|
||||
t.Fatalf("CipherType = %v, want AES_256_GCM", legacy.CipherType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUserAccountShadowsocksCipherKeyWins(t *testing.T) {
|
||||
user := map[string]any{
|
||||
"email": "a@example.test",
|
||||
"password": b64Key(3),
|
||||
"cipher": "2022-blake3-aes-128-gcm",
|
||||
"method": "aes-256-gcm",
|
||||
}
|
||||
_, _, modern := decodeSSAccount(t, user)
|
||||
if modern == nil {
|
||||
t.Fatal("the explicit \"cipher\" must win over a stale \"method\"")
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuildUserAccountShadowsocksUnknownCipherErrors is the regression for the
|
||||
// account-type guess that killed the core: an unrecognized cipher used to fall
|
||||
// through to a shadowsocks-2022 account, which xray's legacy inbound casts
|
||||
// without checking, panicking the whole process.
|
||||
func TestBuildUserAccountShadowsocksUnknownCipherErrors(t *testing.T) {
|
||||
for _, cipher := range []string{"", "rc4-md5", "2022-blake3-future-gcm", "none"} {
|
||||
t.Run("cipher="+cipher, func(t *testing.T) {
|
||||
user := map[string]any{"email": "a@example.test", "password": "pw"}
|
||||
if cipher != "" {
|
||||
user["cipher"] = cipher
|
||||
}
|
||||
account, err := buildUserAccount("shadowsocks", user)
|
||||
if err == nil {
|
||||
t.Fatalf("cipher %q built account %v, want an error instead of an account-type guess", cipher, account)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "unknown cipher") {
|
||||
t.Fatalf("error = %q, want it to name the unknown cipher", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUserAccountShadowsocksMissingPassword(t *testing.T) {
|
||||
user := map[string]any{"email": "a@example.test", "cipher": "aes-256-gcm"}
|
||||
if _, err := buildUserAccount("shadowsocks", user); err == nil {
|
||||
t.Fatal("expected an error for a shadowsocks user without a password")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package xray
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/reflect/protodesc"
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
"google.golang.org/protobuf/types/descriptorpb"
|
||||
"google.golang.org/protobuf/types/dynamicpb"
|
||||
)
|
||||
|
||||
// This file proves the wire-level stats client against a STOCK gRPC server:
|
||||
// the server side runs grpc's default protobuf codec with dynamicpb messages
|
||||
// built from the xray.app.stats.command descriptor (rebuilt here from the
|
||||
// .proto field numbers), so what interops is the real wire contract — field
|
||||
// numbers, message shapes, the "proto" content subtype — not just this
|
||||
// package's own codec talking to itself.
|
||||
|
||||
func fieldDesc(name string, num int32, typ descriptorpb.FieldDescriptorProto_Type, label descriptorpb.FieldDescriptorProto_Label, typeName string) *descriptorpb.FieldDescriptorProto {
|
||||
f := &descriptorpb.FieldDescriptorProto{
|
||||
Name: proto.String(name),
|
||||
Number: proto.Int32(num),
|
||||
Type: typ.Enum(),
|
||||
Label: label.Enum(),
|
||||
}
|
||||
if typeName != "" {
|
||||
f.TypeName = proto.String(typeName)
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func statsFileDescriptor(t *testing.T) protoreflect.FileDescriptor {
|
||||
t.Helper()
|
||||
const (
|
||||
strT = descriptorpb.FieldDescriptorProto_TYPE_STRING
|
||||
i64T = descriptorpb.FieldDescriptorProto_TYPE_INT64
|
||||
boolT = descriptorpb.FieldDescriptorProto_TYPE_BOOL
|
||||
msgT = descriptorpb.FieldDescriptorProto_TYPE_MESSAGE
|
||||
opt = descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL
|
||||
rep = descriptorpb.FieldDescriptorProto_LABEL_REPEATED
|
||||
pkg = ".xray.app.stats.command."
|
||||
)
|
||||
msg := func(name string, fields ...*descriptorpb.FieldDescriptorProto) *descriptorpb.DescriptorProto {
|
||||
return &descriptorpb.DescriptorProto{Name: proto.String(name), Field: fields}
|
||||
}
|
||||
fdp := &descriptorpb.FileDescriptorProto{
|
||||
Name: proto.String("stats.proto"),
|
||||
Package: proto.String("xray.app.stats.command"),
|
||||
Syntax: proto.String("proto3"),
|
||||
MessageType: []*descriptorpb.DescriptorProto{
|
||||
msg("Stat",
|
||||
fieldDesc("name", 1, strT, opt, ""),
|
||||
fieldDesc("value", 2, i64T, opt, "")),
|
||||
msg("QueryStatsRequest",
|
||||
fieldDesc("pattern", 1, strT, opt, ""),
|
||||
fieldDesc("reset", 2, boolT, opt, "")),
|
||||
msg("QueryStatsResponse",
|
||||
fieldDesc("stat", 1, msgT, rep, pkg+"Stat")),
|
||||
msg("OnlineIPEntry",
|
||||
fieldDesc("ip", 1, strT, opt, ""),
|
||||
fieldDesc("last_seen", 2, i64T, opt, "")),
|
||||
msg("TrafficUserStat",
|
||||
fieldDesc("uplink", 1, i64T, opt, ""),
|
||||
fieldDesc("downlink", 2, i64T, opt, "")),
|
||||
msg("UserStat",
|
||||
fieldDesc("email", 1, strT, opt, ""),
|
||||
fieldDesc("ips", 2, msgT, rep, pkg+"OnlineIPEntry"),
|
||||
fieldDesc("traffic", 3, msgT, opt, pkg+"TrafficUserStat")),
|
||||
msg("GetUsersStatsRequest",
|
||||
fieldDesc("include_traffic", 1, boolT, opt, ""),
|
||||
fieldDesc("reset", 2, boolT, opt, "")),
|
||||
msg("GetUsersStatsResponse",
|
||||
fieldDesc("users", 1, msgT, rep, pkg+"UserStat")),
|
||||
},
|
||||
Service: []*descriptorpb.ServiceDescriptorProto{
|
||||
{
|
||||
Name: proto.String("StatsService"),
|
||||
Method: []*descriptorpb.MethodDescriptorProto{
|
||||
{Name: proto.String("QueryStats"), InputType: proto.String(pkg + "QueryStatsRequest"), OutputType: proto.String(pkg + "QueryStatsResponse")},
|
||||
{Name: proto.String("GetUsersStats"), InputType: proto.String(pkg + "GetUsersStatsRequest"), OutputType: proto.String(pkg + "GetUsersStatsResponse")},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
fd, err := protodesc.NewFile(fdp, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("build stats descriptor: %v", err)
|
||||
}
|
||||
return fd
|
||||
}
|
||||
|
||||
// stockStats is a StatsService served by grpc's stock codec from dynamicpb
|
||||
// messages, replaying queued responses per method.
|
||||
type stockStats struct {
|
||||
fd protoreflect.FileDescriptor
|
||||
querySeq []*dynamicpb.Message
|
||||
usersSeq []*dynamicpb.Message
|
||||
qCalls int
|
||||
uCalls int
|
||||
}
|
||||
|
||||
func (s *stockStats) newMsg(name protoreflect.Name) *dynamicpb.Message {
|
||||
return dynamicpb.NewMessage(s.fd.Messages().ByName(name))
|
||||
}
|
||||
|
||||
func (s *stockStats) method(name string, reqName protoreflect.Name, pick func() *dynamicpb.Message) grpc.MethodDesc {
|
||||
return grpc.MethodDesc{
|
||||
MethodName: name,
|
||||
Handler: func(_ any, _ context.Context, dec func(any) error, _ grpc.UnaryServerInterceptor) (any, error) {
|
||||
req := s.newMsg(reqName)
|
||||
if err := dec(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return pick(), nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func startStockStats(t *testing.T, st *stockStats) *XrayAPI {
|
||||
t.Helper()
|
||||
st.fd = statsFileDescriptor(t)
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := grpc.NewServer() // stock codec: the real interop surface
|
||||
srv.RegisterService(&grpc.ServiceDesc{
|
||||
ServiceName: "xray.app.stats.command.StatsService",
|
||||
HandlerType: (*statsServiceIface)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
st.method("QueryStats", "QueryStatsRequest", func() *dynamicpb.Message {
|
||||
i := st.qCalls
|
||||
st.qCalls++
|
||||
if i >= len(st.querySeq) {
|
||||
i = len(st.querySeq) - 1
|
||||
}
|
||||
return st.querySeq[i]
|
||||
}),
|
||||
st.method("GetUsersStats", "GetUsersStatsRequest", func() *dynamicpb.Message {
|
||||
i := st.uCalls
|
||||
st.uCalls++
|
||||
if i >= len(st.usersSeq) {
|
||||
i = len(st.usersSeq) - 1
|
||||
}
|
||||
return st.usersSeq[i]
|
||||
}),
|
||||
},
|
||||
}, st)
|
||||
go func() { _ = srv.Serve(lis) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
|
||||
api := &XrayAPI{}
|
||||
if err := api.Init(lis.Addr().(*net.TCPAddr).Port); err != nil {
|
||||
t.Fatalf("api init: %v", err)
|
||||
}
|
||||
t.Cleanup(api.Close)
|
||||
return api
|
||||
}
|
||||
|
||||
func (s *stockStats) statMsg(name string, value int64) *dynamicpb.Message {
|
||||
m := s.newMsg("Stat")
|
||||
d := m.Descriptor()
|
||||
m.Set(d.Fields().ByName("name"), protoreflect.ValueOfString(name))
|
||||
m.Set(d.Fields().ByName("value"), protoreflect.ValueOfInt64(value))
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *stockStats) queryResp(stats ...*dynamicpb.Message) *dynamicpb.Message {
|
||||
m := s.newMsg("QueryStatsResponse")
|
||||
list := m.Mutable(m.Descriptor().Fields().ByName("stat")).List()
|
||||
for _, st := range stats {
|
||||
list.Append(protoreflect.ValueOfMessage(st.ProtoReflect()))
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// TestStatsAgainstStockProtoServer drives GetTraffic and GetOnlineUsers
|
||||
// against the stock-codec server: the same deltas and user shapes the typed
|
||||
// client produced must come out of the wire-level one.
|
||||
func TestStatsAgainstStockProtoServer(t *testing.T) {
|
||||
st := &stockStats{}
|
||||
st.fd = statsFileDescriptor(t)
|
||||
st.querySeq = []*dynamicpb.Message{
|
||||
st.queryResp(st.statMsg("user>>>alice>>>traffic>>>uplink", 100)),
|
||||
st.queryResp(
|
||||
st.statMsg("user>>>alice>>>traffic>>>uplink", 175),
|
||||
st.statMsg("inbound>>>in-443>>>traffic>>>downlink", 2048),
|
||||
),
|
||||
}
|
||||
|
||||
// One online user with two IPs and a traffic block (field 3 — present in
|
||||
// the message, ignored by the panel's OnlineUser shape).
|
||||
user := st.newMsg("UserStat")
|
||||
ud := user.Descriptor()
|
||||
user.Set(ud.Fields().ByName("email"), protoreflect.ValueOfString("alice"))
|
||||
ipList := user.Mutable(ud.Fields().ByName("ips")).List()
|
||||
for _, e := range []struct {
|
||||
ip string
|
||||
seen int64
|
||||
}{{"203.0.113.7", 111}, {"2001:db8::5", 222}} {
|
||||
entry := st.newMsg("OnlineIPEntry")
|
||||
ed := entry.Descriptor()
|
||||
entry.Set(ed.Fields().ByName("ip"), protoreflect.ValueOfString(e.ip))
|
||||
entry.Set(ed.Fields().ByName("last_seen"), protoreflect.ValueOfInt64(e.seen))
|
||||
ipList.Append(protoreflect.ValueOfMessage(entry.ProtoReflect()))
|
||||
}
|
||||
traffic := st.newMsg("TrafficUserStat")
|
||||
td := traffic.Descriptor()
|
||||
traffic.Set(td.Fields().ByName("uplink"), protoreflect.ValueOfInt64(10))
|
||||
traffic.Set(td.Fields().ByName("downlink"), protoreflect.ValueOfInt64(20))
|
||||
user.Set(ud.Fields().ByName("traffic"), protoreflect.ValueOfMessage(traffic.ProtoReflect()))
|
||||
usersResp := st.newMsg("GetUsersStatsResponse")
|
||||
uList := usersResp.Mutable(usersResp.Descriptor().Fields().ByName("users")).List()
|
||||
uList.Append(protoreflect.ValueOfMessage(user.ProtoReflect()))
|
||||
st.usersSeq = []*dynamicpb.Message{usersResp}
|
||||
|
||||
api := startStockStats(t, st)
|
||||
|
||||
if _, _, err := api.GetTraffic(); err != nil {
|
||||
t.Fatalf("GetTraffic (baseline): %v", err)
|
||||
}
|
||||
tags, clients, err := api.GetTraffic()
|
||||
if err != nil {
|
||||
t.Fatalf("GetTraffic: %v", err)
|
||||
}
|
||||
if len(clients) != 1 || clients[0].Email != "alice" || clients[0].Up != 75 {
|
||||
t.Fatalf("clients = %+v, want alice up=75", clients)
|
||||
}
|
||||
if len(tags) != 1 || tags[0].Tag != "in-443" || tags[0].Down != 2048 {
|
||||
t.Fatalf("tags = %+v, want in-443 down=2048", tags)
|
||||
}
|
||||
|
||||
users, err := api.GetOnlineUsers()
|
||||
if err != nil {
|
||||
t.Fatalf("GetOnlineUsers: %v", err)
|
||||
}
|
||||
if len(users) != 1 || users[0].Email != "alice" || len(users[0].IPs) != 2 {
|
||||
t.Fatalf("users = %+v, want alice with 2 IPs", users)
|
||||
}
|
||||
if users[0].IPs[0].IP != "203.0.113.7" || users[0].IPs[0].LastSeen != 111 ||
|
||||
users[0].IPs[1].IP != "2001:db8::5" || users[0].IPs[1].LastSeen != 222 {
|
||||
t.Fatalf("ips = %+v", users[0].IPs)
|
||||
}
|
||||
}
|
||||
+26
-74
@@ -1,89 +1,41 @@
|
||||
package xray
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestRemoveUserGuardsNilHandlerClient pins that mutation calls on an
|
||||
// uninitialized client fail instead of panicking. In this build they fail
|
||||
// unconditionally — hot-apply is unavailable without xray-core — and every
|
||||
// caller treats that as "fall back to a core restart".
|
||||
func TestRemoveUserGuardsNilHandlerClient(t *testing.T) {
|
||||
err := (&XrayAPI{}).RemoveUser("in-443-tcp", "user@example.com")
|
||||
if err == nil {
|
||||
t.Fatal("RemoveUser with an uninitialized HandlerServiceClient must return an error")
|
||||
t.Fatal("RemoveUser with an uninitialized client must return an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRequiredUserString_Present(t *testing.T) {
|
||||
user := map[string]any{"email": "alice@example.com"}
|
||||
got, err := getRequiredUserString(user, "email")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
func TestHotApplyMutationsAreUnavailable(t *testing.T) {
|
||||
api := &XrayAPI{}
|
||||
calls := map[string]func() error{
|
||||
"AddInbound": func() error { return api.AddInbound([]byte("{}")) },
|
||||
"DelInbound": func() error { return api.DelInbound("in-443-tcp") },
|
||||
"AddOutbound": func() error { return api.AddOutbound([]byte("{}")) },
|
||||
"DelOutbound": func() error { return api.DelOutbound("direct") },
|
||||
"ApplyRoutingConfig": func() error { return api.ApplyRoutingConfig([]byte("{}")) },
|
||||
"AddUser": func() error { return api.AddUser("vless", "in-443-tcp", map[string]any{"email": "a@b.c"}) },
|
||||
"RemoveUser": func() error { return api.RemoveUser("in-443-tcp", "a@b.c") },
|
||||
"SetBalancerTarget": func() error { return api.SetBalancerTarget("lb", "direct") },
|
||||
}
|
||||
if got != "alice@example.com" {
|
||||
t.Fatalf("got %q, want %q", got, "alice@example.com")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRequiredUserString_Missing(t *testing.T) {
|
||||
user := map[string]any{}
|
||||
if _, err := getRequiredUserString(user, "email"); err == nil {
|
||||
t.Fatal("expected error for missing key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRequiredUserString_NilValue(t *testing.T) {
|
||||
user := map[string]any{"email": nil}
|
||||
if _, err := getRequiredUserString(user, "email"); err == nil {
|
||||
t.Fatal("expected error for nil value")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRequiredUserString_WrongType(t *testing.T) {
|
||||
user := map[string]any{"email": 42}
|
||||
_, err := getRequiredUserString(user, "email")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for non-string value")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "invalid type") {
|
||||
t.Fatalf("expected %q in error, got: %v", "invalid type", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOptionalUserString_Present(t *testing.T) {
|
||||
user := map[string]any{"flow": "xtls-rprx-vision"}
|
||||
got, err := getOptionalUserString(user, "flow")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != "xtls-rprx-vision" {
|
||||
t.Fatalf("got %q, want %q", got, "xtls-rprx-vision")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOptionalUserString_MissingReturnsEmptyNoError(t *testing.T) {
|
||||
user := map[string]any{}
|
||||
got, err := getOptionalUserString(user, "flow")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error for missing optional field: %v", err)
|
||||
}
|
||||
if got != "" {
|
||||
t.Fatalf("got %q, want empty string", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOptionalUserString_NilReturnsEmptyNoError(t *testing.T) {
|
||||
user := map[string]any{"flow": nil}
|
||||
got, err := getOptionalUserString(user, "flow")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error for nil optional field: %v", err)
|
||||
}
|
||||
if got != "" {
|
||||
t.Fatalf("got %q, want empty string", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetOptionalUserString_WrongTypeErrors(t *testing.T) {
|
||||
user := map[string]any{"flow": []string{"a", "b"}}
|
||||
if _, err := getOptionalUserString(user, "flow"); err == nil {
|
||||
t.Fatal("expected error for non-string optional value")
|
||||
for name, call := range calls {
|
||||
if err := call(); err != ErrHotApplyUnavailable {
|
||||
t.Fatalf("%s = %v, want ErrHotApplyUnavailable", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := api.GetBalancerInfo("lb"); err != ErrHotApplyUnavailable {
|
||||
t.Fatalf("GetBalancerInfo = %v, want ErrHotApplyUnavailable", err)
|
||||
}
|
||||
if _, err := api.TestRoute(RouteTestRequest{}); err != ErrHotApplyUnavailable {
|
||||
t.Fatalf("TestRoute = %v, want ErrHotApplyUnavailable", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,41 +5,78 @@ import (
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
statsService "github.com/xtls/xray-core/app/stats/command"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/protobuf/encoding/protowire"
|
||||
)
|
||||
|
||||
// fakeStatsServer serves a scripted sequence of QueryStats responses, one per
|
||||
// call, so the delta bookkeeping in GetTraffic can be driven exactly.
|
||||
// call, so the delta bookkeeping in GetTraffic can be driven exactly. It
|
||||
// speaks the stats service's wire format directly: this build has no typed
|
||||
// protobuf client, so the fake encodes responses with protowire and the
|
||||
// server runs with the client's raw codec.
|
||||
type fakeStatsServer struct {
|
||||
statsService.UnimplementedStatsServiceServer
|
||||
rounds [][]*statsService.Stat
|
||||
rounds [][]statEntry
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *fakeStatsServer) QueryStats(context.Context, *statsService.QueryStatsRequest) (*statsService.QueryStatsResponse, error) {
|
||||
func (f *fakeStatsServer) queryStats() rawBytes {
|
||||
round := f.calls
|
||||
f.calls++
|
||||
if round >= len(f.rounds) {
|
||||
round = len(f.rounds) - 1
|
||||
}
|
||||
return &statsService.QueryStatsResponse{Stat: f.rounds[round]}, nil
|
||||
return encodeQueryStatsResponse(f.rounds[round])
|
||||
}
|
||||
|
||||
func stat(name string, value int64) *statsService.Stat {
|
||||
return &statsService.Stat{Name: name, Value: value}
|
||||
// encodeQueryStatsResponse builds a QueryStatsResponse message
|
||||
// (stat = 1, repeated Stat{name = 1, value = 2}).
|
||||
func encodeQueryStatsResponse(stats []statEntry) rawBytes {
|
||||
var out []byte
|
||||
for _, st := range stats {
|
||||
var statMsg []byte
|
||||
statMsg = protowire.AppendTag(statMsg, 1, protowire.BytesType)
|
||||
statMsg = protowire.AppendString(statMsg, st.Name)
|
||||
statMsg = protowire.AppendTag(statMsg, 2, protowire.VarintType)
|
||||
statMsg = protowire.AppendVarint(statMsg, uint64(st.Value))
|
||||
out = protowire.AppendTag(out, 1, protowire.BytesType)
|
||||
out = protowire.AppendBytes(out, statMsg)
|
||||
}
|
||||
return rawBytes(out)
|
||||
|
||||
}
|
||||
|
||||
func stat(name string, value int64) statEntry {
|
||||
return statEntry{Name: name, Value: value}
|
||||
}
|
||||
|
||||
type statsServiceIface interface{}
|
||||
|
||||
// startFakeStats runs the scripted stats service and returns an XrayAPI wired
|
||||
// to it.
|
||||
func startFakeStats(t *testing.T, rounds [][]*statsService.Stat) *XrayAPI {
|
||||
func startFakeStats(t *testing.T, rounds [][]statEntry) *XrayAPI {
|
||||
t.Helper()
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := grpc.NewServer()
|
||||
statsService.RegisterStatsServiceServer(srv, &fakeStatsServer{rounds: rounds})
|
||||
fake := &fakeStatsServer{rounds: rounds}
|
||||
srv := grpc.NewServer(grpc.ForceServerCodec(rawCodec{}))
|
||||
srv.RegisterService(&grpc.ServiceDesc{
|
||||
ServiceName: "xray.app.stats.command.StatsService",
|
||||
HandlerType: (*statsServiceIface)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "QueryStats",
|
||||
Handler: func(_ any, _ context.Context, dec func(any) error, _ grpc.UnaryServerInterceptor) (any, error) {
|
||||
var req rawBytes
|
||||
if err := dec(&req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return fake.queryStats(), nil
|
||||
},
|
||||
},
|
||||
},
|
||||
}, fake)
|
||||
go func() { _ = srv.Serve(lis) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
|
||||
@@ -64,7 +101,7 @@ func clientTrafficByEmail(t *testing.T, traffics []*ClientTraffic) map[string]*C
|
||||
// the panel may attach to counters that already hold traffic it cannot
|
||||
// attribute, so the first poll of a client only records baselines.
|
||||
func TestGetTrafficFirstPollIsBaselineOnly(t *testing.T) {
|
||||
api := startFakeStats(t, [][]*statsService.Stat{
|
||||
api := startFakeStats(t, [][]statEntry{
|
||||
{stat("user>>>alice>>>traffic>>>uplink", 5000)},
|
||||
})
|
||||
|
||||
@@ -84,7 +121,7 @@ func TestGetTrafficFirstPollIsBaselineOnly(t *testing.T) {
|
||||
// traffic being dropped: xray creates a counter on first use, so a name that
|
||||
// appears after the baseline poll starts at zero and every byte in it is new.
|
||||
func TestGetTrafficCountsNewStatFromZero(t *testing.T) {
|
||||
api := startFakeStats(t, [][]*statsService.Stat{
|
||||
api := startFakeStats(t, [][]statEntry{
|
||||
{stat("user>>>alice>>>traffic>>>uplink", 100)},
|
||||
{
|
||||
stat("user>>>alice>>>traffic>>>uplink", 180),
|
||||
@@ -122,7 +159,7 @@ func TestGetTrafficCountsNewStatFromZero(t *testing.T) {
|
||||
// start over at zero, so a value below the recorded baseline is all new
|
||||
// traffic rather than something to drop.
|
||||
func TestGetTrafficCountsAfterCounterReset(t *testing.T) {
|
||||
api := startFakeStats(t, [][]*statsService.Stat{
|
||||
api := startFakeStats(t, [][]statEntry{
|
||||
{stat("user>>>alice>>>traffic>>>uplink", 100)},
|
||||
{stat("user>>>alice>>>traffic>>>uplink", 900)},
|
||||
{stat("user>>>alice>>>traffic>>>uplink", 250)},
|
||||
@@ -152,7 +189,7 @@ func TestGetTrafficCountsAfterCounterReset(t *testing.T) {
|
||||
// inbound is the panel's own gRPC channel and is never a user-facing inbound,
|
||||
// and baselines for vanished stats are dropped once they outgrow the live set.
|
||||
func TestGetTrafficSkipsAPIInboundAndPrunes(t *testing.T) {
|
||||
api := startFakeStats(t, [][]*statsService.Stat{
|
||||
api := startFakeStats(t, [][]statEntry{
|
||||
{
|
||||
stat("inbound>>>api>>>traffic>>>uplink", 10),
|
||||
stat("inbound>>>in-443>>>traffic>>>uplink", 10),
|
||||
|
||||
@@ -1,446 +0,0 @@
|
||||
package xray
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// e2eCore is a real xray-core process plus a connected panel API client.
|
||||
type e2eCore struct {
|
||||
api *XrayAPI
|
||||
cmd *exec.Cmd
|
||||
port int
|
||||
}
|
||||
|
||||
// alive reports whether the core is still serving its API port. A gRPC call
|
||||
// that hands the core an account type its inbound does not expect takes the
|
||||
// whole process down, so every user probe checks this.
|
||||
func (c *e2eCore) alive() bool {
|
||||
if c.cmd.ProcessState != nil {
|
||||
return false
|
||||
}
|
||||
conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", c.port), time.Second)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
conn.Close()
|
||||
return true
|
||||
}
|
||||
|
||||
// startE2ECore boots xray-core with the given inbounds plus the api inbound the
|
||||
// panel talks through, and returns a connected client. Skips unless
|
||||
// XRAY_E2E_BINARY points at an xray built from the version go.mod pins.
|
||||
func startE2ECore(t *testing.T, inbounds []any) *e2eCore {
|
||||
t.Helper()
|
||||
bin := os.Getenv("XRAY_E2E_BINARY")
|
||||
if bin == "" {
|
||||
t.Skip("set XRAY_E2E_BINARY to an xray binary to run this test")
|
||||
}
|
||||
|
||||
apiPort := freePort(t)
|
||||
all := []any{
|
||||
map[string]any{
|
||||
"listen": "127.0.0.1",
|
||||
"port": apiPort,
|
||||
"protocol": "tunnel",
|
||||
"settings": map[string]any{"rewriteAddress": "127.0.0.1"},
|
||||
"tag": "api",
|
||||
},
|
||||
}
|
||||
all = append(all, inbounds...)
|
||||
|
||||
cfg := map[string]any{
|
||||
"log": map[string]any{"loglevel": "warning"},
|
||||
"api": map[string]any{
|
||||
"services": []string{"HandlerService", "StatsService", "RoutingService"},
|
||||
"tag": "api",
|
||||
},
|
||||
"inbounds": all,
|
||||
"outbounds": []any{
|
||||
map[string]any{"protocol": "freedom", "settings": map[string]any{}, "tag": "direct"},
|
||||
map[string]any{"protocol": "blackhole", "settings": map[string]any{}, "tag": "blocked"},
|
||||
},
|
||||
"routing": map[string]any{
|
||||
"domainStrategy": "AsIs",
|
||||
"rules": []any{
|
||||
map[string]any{"type": "field", "inboundTag": []string{"api"}, "outboundTag": "api"},
|
||||
},
|
||||
},
|
||||
"policy": map[string]any{
|
||||
"levels": map[string]any{
|
||||
"0": map[string]any{"statsUserUplink": true, "statsUserDownlink": true, "statsUserOnline": true},
|
||||
},
|
||||
"system": map[string]any{"statsInboundUplink": true, "statsInboundDownlink": true},
|
||||
},
|
||||
"stats": map[string]any{},
|
||||
}
|
||||
raw, err := json.MarshalIndent(cfg, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfgPath := filepath.Join(t.TempDir(), "config.json")
|
||||
if err := os.WriteFile(cfgPath, raw, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cmd := exec.Command(bin, "-c", cfgPath)
|
||||
cmd.Stdout = os.Stderr
|
||||
cmd.Stderr = os.Stderr
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("failed to start xray: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = cmd.Process.Kill()
|
||||
_, _ = cmd.Process.Wait()
|
||||
})
|
||||
waitForPort(t, apiPort)
|
||||
|
||||
api := &XrayAPI{}
|
||||
if err := api.Init(apiPort); err != nil {
|
||||
t.Fatalf("api init: %v", err)
|
||||
}
|
||||
t.Cleanup(api.Close)
|
||||
return &e2eCore{api: api, cmd: cmd, port: apiPort}
|
||||
}
|
||||
|
||||
// ssKey builds a base64 shadowsocks-2022 key of the given byte length.
|
||||
func ssKey(n int, seed byte) string {
|
||||
raw := make([]byte, n)
|
||||
for i := range raw {
|
||||
raw[i] = seed + byte(i)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
// panelUser mirrors the map shape the panel's client-apply paths hand to
|
||||
// AddUser: every field is always present, unused ones are empty.
|
||||
func panelUser(email string, fields map[string]any) map[string]any {
|
||||
user := map[string]any{
|
||||
"email": email,
|
||||
"id": "",
|
||||
"auth": "",
|
||||
"security": "",
|
||||
"flow": "",
|
||||
"password": "",
|
||||
"cipher": "",
|
||||
"publicKey": "",
|
||||
"allowedIPs": nil,
|
||||
"preSharedKey": "",
|
||||
"keepAlive": "",
|
||||
}
|
||||
maps.Copy(user, fields)
|
||||
return user
|
||||
}
|
||||
|
||||
// TestXrayAPI_E2E_Users runs the panel's add/remove user surface against a live
|
||||
// core for every protocol it builds accounts for, pinning the error texts
|
||||
// IsUserExistsErr and IsMissingHandlerErr match on.
|
||||
func TestXrayAPI_E2E_Users(t *testing.T) {
|
||||
c := startE2ECore(t, []any{
|
||||
map[string]any{
|
||||
"listen": "127.0.0.1", "port": freePort(t), "protocol": "vmess", "tag": "vmess-in",
|
||||
"settings": map[string]any{"clients": []any{
|
||||
map[string]any{"id": "b831381d-6324-4d53-ad4f-8cda48b30811", "email": "seed-vmess"},
|
||||
}},
|
||||
},
|
||||
map[string]any{
|
||||
"listen": "127.0.0.1", "port": freePort(t), "protocol": "vless", "tag": "vless-in",
|
||||
"settings": map[string]any{"clients": []any{
|
||||
map[string]any{"id": "b831381d-6324-4d53-ad4f-8cda48b30812", "email": "seed-vless"},
|
||||
}, "decryption": "none"},
|
||||
},
|
||||
map[string]any{
|
||||
"listen": "127.0.0.1", "port": freePort(t), "protocol": "trojan", "tag": "trojan-in",
|
||||
"settings": map[string]any{"clients": []any{
|
||||
map[string]any{"password": "seed-pw", "email": "seed-trojan"},
|
||||
}},
|
||||
},
|
||||
map[string]any{
|
||||
"listen": "127.0.0.1", "port": freePort(t), "protocol": "shadowsocks", "tag": "ss-in",
|
||||
"settings": map[string]any{
|
||||
"method": "aes-256-gcm", "network": "tcp,udp",
|
||||
"clients": []any{map[string]any{"method": "aes-256-gcm", "password": "seed-pw", "email": "seed-ss"}},
|
||||
},
|
||||
},
|
||||
map[string]any{
|
||||
"listen": "127.0.0.1", "port": freePort(t), "protocol": "shadowsocks", "tag": "ss2022-in",
|
||||
"settings": map[string]any{
|
||||
"method": "2022-blake3-aes-256-gcm", "password": ssKey(32, 1), "network": "tcp,udp",
|
||||
"clients": []any{map[string]any{"password": ssKey(32, 9), "email": "seed-ss2022"}},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
protocol string
|
||||
tag string
|
||||
user map[string]any
|
||||
// rejectsDuplicateEmail is false for the legacy shadowsocks inbound,
|
||||
// whose validator does not dedupe emails at all.
|
||||
rejectsDuplicateEmail bool
|
||||
}{
|
||||
{
|
||||
name: "vmess", protocol: "vmess", tag: "vmess-in",
|
||||
user: panelUser("e2e-vmess", map[string]any{"id": "b831381d-6324-4d53-ad4f-8cda48b30821", "security": "auto"}),
|
||||
rejectsDuplicateEmail: true,
|
||||
},
|
||||
{
|
||||
name: "vless", protocol: "vless", tag: "vless-in",
|
||||
user: panelUser("e2e-vless", map[string]any{"id": "b831381d-6324-4d53-ad4f-8cda48b30822", "flow": "xtls-rprx-vision"}),
|
||||
rejectsDuplicateEmail: true,
|
||||
},
|
||||
{
|
||||
name: "trojan", protocol: "trojan", tag: "trojan-in",
|
||||
user: panelUser("e2e-trojan", map[string]any{"password": "e2e-pw"}),
|
||||
rejectsDuplicateEmail: true,
|
||||
},
|
||||
{
|
||||
name: "shadowsocks legacy", protocol: "shadowsocks", tag: "ss-in",
|
||||
user: panelUser("e2e-ss", map[string]any{"password": "e2e-pw", "cipher": "aes-256-gcm"}),
|
||||
rejectsDuplicateEmail: false,
|
||||
},
|
||||
{
|
||||
name: "shadowsocks 2022", protocol: "shadowsocks", tag: "ss2022-in",
|
||||
user: panelUser("e2e-ss2022", map[string]any{"password": ssKey(32, 40), "cipher": "2022-blake3-aes-256-gcm"}),
|
||||
rejectsDuplicateEmail: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
email := tt.user["email"].(string)
|
||||
if err := c.api.AddUser(tt.protocol, tt.tag, tt.user); err != nil {
|
||||
t.Fatalf("AddUser: %v", err)
|
||||
}
|
||||
if !c.alive() {
|
||||
t.Fatal("core died on AddUser: the account type does not match the running inbound")
|
||||
}
|
||||
|
||||
if tt.rejectsDuplicateEmail {
|
||||
err := c.api.AddUser(tt.protocol, tt.tag, tt.user)
|
||||
if err == nil {
|
||||
t.Fatal("adding a user whose email is taken must fail")
|
||||
}
|
||||
if !IsUserExistsErr(err) {
|
||||
t.Fatalf("duplicate-email error not matched by IsUserExistsErr: %q", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := c.api.RemoveUser(tt.tag, email); err != nil {
|
||||
t.Fatalf("RemoveUser: %v", err)
|
||||
}
|
||||
err := c.api.RemoveUser(tt.tag, email)
|
||||
if err == nil {
|
||||
t.Fatal("the user is still registered after RemoveUser")
|
||||
}
|
||||
if !IsMissingHandlerErr(err) {
|
||||
t.Fatalf("missing-user error not matched by IsMissingHandlerErr: %q", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("unknown inbound tag", func(t *testing.T) {
|
||||
err := c.api.AddUser("vmess", "no-such-tag", panelUser("e2e-ghost", map[string]any{"id": "b831381d-6324-4d53-ad4f-8cda48b30899"}))
|
||||
if err == nil {
|
||||
t.Fatal("AddUser on an unknown tag must fail")
|
||||
}
|
||||
if !IsMissingHandlerErr(err) {
|
||||
t.Fatalf("unknown-tag error not matched by IsMissingHandlerErr: %q", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestXrayAPI_E2E_ShadowsocksAccountTypeGuess is the regression for the crash
|
||||
// that took the whole core down: a shadowsocks user whose cipher the panel
|
||||
// could not resolve used to be sent as a shadowsocks-2022 account, which the
|
||||
// legacy inbound casts without checking. Every case here must leave the core
|
||||
// running.
|
||||
func TestXrayAPI_E2E_ShadowsocksAccountTypeGuess(t *testing.T) {
|
||||
c := startE2ECore(t, []any{
|
||||
map[string]any{
|
||||
"listen": "127.0.0.1", "port": freePort(t), "protocol": "shadowsocks", "tag": "ss-in",
|
||||
"settings": map[string]any{
|
||||
"method": "aes-256-gcm", "network": "tcp,udp",
|
||||
"clients": []any{map[string]any{"method": "aes-256-gcm", "password": "seed-pw", "email": "seed-ss"}},
|
||||
},
|
||||
},
|
||||
map[string]any{
|
||||
"listen": "127.0.0.1", "port": freePort(t), "protocol": "shadowsocks", "tag": "ss2022-in",
|
||||
"settings": map[string]any{
|
||||
"method": "2022-blake3-aes-256-gcm", "password": ssKey(32, 1), "network": "tcp,udp",
|
||||
"clients": []any{map[string]any{"password": ssKey(32, 9), "email": "seed-ss2022"}},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// The auto-renew path hands over the client object straight out of the
|
||||
// inbound's settings, which carries the cipher under "method".
|
||||
t.Run("client object from settings", func(t *testing.T) {
|
||||
user := map[string]any{"email": "renew-ss", "password": "pw", "method": "aes-256-gcm", "enable": true}
|
||||
if err := c.api.AddUser("shadowsocks", "ss-in", user); err != nil {
|
||||
t.Fatalf("AddUser with the settings-shaped client: %v", err)
|
||||
}
|
||||
if !c.alive() {
|
||||
t.Fatal("core died: a legacy shadowsocks client was sent as a 2022 account")
|
||||
}
|
||||
if err := c.api.RemoveUser("ss-in", "renew-ss"); err != nil {
|
||||
t.Fatalf("RemoveUser: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cipher missing entirely", func(t *testing.T) {
|
||||
err := c.api.AddUser("shadowsocks", "ss-in", map[string]any{"email": "nocipher", "password": "pw"})
|
||||
if err == nil {
|
||||
t.Fatal("a shadowsocks user with no resolvable cipher must be refused, not guessed")
|
||||
}
|
||||
if !c.alive() {
|
||||
t.Fatal("core died on a shadowsocks user with no cipher")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("legacy cipher against a 2022 inbound", func(t *testing.T) {
|
||||
// The reverse mismatch is only reachable when the panel's view of the
|
||||
// inbound has drifted from the running one; the account type is still
|
||||
// the one the cipher names, so the panel never guesses here.
|
||||
user := map[string]any{"email": "drift", "password": ssKey(32, 50), "cipher": "2022-blake3-aes-256-gcm"}
|
||||
if err := c.api.AddUser("shadowsocks", "ss2022-in", user); err != nil {
|
||||
t.Fatalf("AddUser: %v", err)
|
||||
}
|
||||
if !c.alive() {
|
||||
t.Fatal("core died adding a 2022 user to a 2022 inbound")
|
||||
}
|
||||
if err := c.api.RemoveUser("ss2022-in", "drift"); err != nil {
|
||||
t.Fatalf("RemoveUser: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestXrayAPI_E2E_ShadowsocksAddIsIdempotent covers the legacy shadowsocks
|
||||
// inbound accepting a second user under an email it already holds: one removal
|
||||
// then left the client connectable. Adding twice must leave exactly one
|
||||
// registration, so a single removal fully revokes the client.
|
||||
func TestXrayAPI_E2E_ShadowsocksAddIsIdempotent(t *testing.T) {
|
||||
c := startE2ECore(t, []any{
|
||||
map[string]any{
|
||||
"listen": "127.0.0.1", "port": freePort(t), "protocol": "shadowsocks", "tag": "ss-in",
|
||||
"settings": map[string]any{
|
||||
"method": "aes-256-gcm", "network": "tcp,udp",
|
||||
"clients": []any{map[string]any{"method": "aes-256-gcm", "password": "seed-pw", "email": "seed-ss"}},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
user := map[string]any{"email": "dup-ss", "password": "pw", "cipher": "aes-256-gcm"}
|
||||
for i := range 2 {
|
||||
if err := c.api.AddUser("shadowsocks", "ss-in", user); err != nil {
|
||||
t.Fatalf("AddUser #%d: %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := c.api.RemoveUser("ss-in", "dup-ss"); err != nil {
|
||||
t.Fatalf("RemoveUser: %v", err)
|
||||
}
|
||||
err := c.api.RemoveUser("ss-in", "dup-ss")
|
||||
if err == nil {
|
||||
t.Fatal("a second registration survived removal: a disabled client would keep connecting")
|
||||
}
|
||||
if !IsMissingHandlerErr(err) {
|
||||
t.Fatalf("missing-user error not matched by IsMissingHandlerErr: %q", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestXrayAPI_E2E_NewClientTrafficIsCounted proves against a live core that a
|
||||
// counter appearing after the baseline poll is reported in full: xray creates a
|
||||
// user's counter on first use, and dropping that first sample lost a new
|
||||
// client's traffic for a whole polling interval.
|
||||
func TestXrayAPI_E2E_NewClientTrafficIsCounted(t *testing.T) {
|
||||
const payload = 64 * 1024
|
||||
|
||||
backendLn, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
backend := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write(make([]byte, payload))
|
||||
})}
|
||||
go func() { _ = backend.Serve(backendLn) }()
|
||||
t.Cleanup(func() { _ = backend.Close() })
|
||||
|
||||
proxyPort := freePort(t)
|
||||
c := startE2ECore(t, []any{
|
||||
map[string]any{
|
||||
"listen": "127.0.0.1", "port": proxyPort, "protocol": "http", "tag": "http-in",
|
||||
"settings": map[string]any{
|
||||
"accounts": []any{map[string]any{"user": "e2e-fresh", "pass": "e2e-pass"}},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Baseline poll: the client's counter does not exist yet.
|
||||
if _, _, err := c.api.GetTraffic(); err != nil {
|
||||
t.Fatalf("GetTraffic (baseline): %v", err)
|
||||
}
|
||||
|
||||
proxyURL, err := url.Parse(fmt.Sprintf("http://e2e-fresh:e2e-pass@127.0.0.1:%d", proxyPort))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}}
|
||||
resp, err := client.Get(fmt.Sprintf("http://%s/", backendLn.Addr().String()))
|
||||
if err != nil {
|
||||
t.Fatalf("proxied request: %v", err)
|
||||
}
|
||||
n, err := io.Copy(io.Discard, resp.Body)
|
||||
resp.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("reading the proxied response: %v", err)
|
||||
}
|
||||
if n != payload {
|
||||
t.Fatalf("proxied %d bytes, want %d", n, payload)
|
||||
}
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
|
||||
_, clients, err := c.api.GetTraffic()
|
||||
if err != nil {
|
||||
t.Fatalf("GetTraffic: %v", err)
|
||||
}
|
||||
var got *ClientTraffic
|
||||
for _, ct := range clients {
|
||||
if ct.Email == "e2e-fresh" {
|
||||
got = ct
|
||||
}
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatalf("the new client's traffic was dropped; reported clients: %+v", clients)
|
||||
}
|
||||
if got.Down < payload {
|
||||
t.Fatalf("downlink = %d, want at least the %d bytes that were proxied", got.Down, payload)
|
||||
}
|
||||
}
|
||||
|
||||
// TestXrayAPI_E2E_TestRoutePortRange keeps TestRoute from wrapping an
|
||||
// out-of-range port into the uint32 the core is asked about.
|
||||
func TestXrayAPI_E2E_TestRoutePortRange(t *testing.T) {
|
||||
c := startE2ECore(t, nil)
|
||||
|
||||
for _, port := range []int{-1, 65536, 70000} {
|
||||
if _, err := c.api.TestRoute(RouteTestRequest{Domain: "example.com", Port: port}); err == nil {
|
||||
t.Fatalf("TestRoute accepted the out-of-range port %d", port)
|
||||
}
|
||||
}
|
||||
if _, err := c.api.TestRoute(RouteTestRequest{Domain: "example.com", Port: 65535}); err != nil {
|
||||
t.Fatalf("TestRoute rejected the valid port 65535: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,129 +0,0 @@
|
||||
package xray
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
wireguard "github.com/xtls/xray-core/proxy/wireguard"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
func b64Key(seed byte) string {
|
||||
raw := make([]byte, 32)
|
||||
for i := range raw {
|
||||
raw[i] = seed + byte(i)
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func decodeWgAccount(t *testing.T, user map[string]any) *wireguard.PeerConfig {
|
||||
t.Helper()
|
||||
tm, err := buildUserAccount("wireguard", user)
|
||||
if err != nil {
|
||||
t.Fatalf("buildUserAccount: %v", err)
|
||||
}
|
||||
if tm == nil {
|
||||
t.Fatal("buildUserAccount returned nil account for wireguard")
|
||||
}
|
||||
var pc wireguard.PeerConfig
|
||||
if err := proto.Unmarshal(tm.Value, &pc); err != nil {
|
||||
t.Fatalf("unmarshal PeerConfig: %v", err)
|
||||
}
|
||||
return &pc
|
||||
}
|
||||
|
||||
func assertHexKey(t *testing.T, label, value string) {
|
||||
t.Helper()
|
||||
if len(value) != 64 {
|
||||
t.Fatalf("%s = %q, want 64-char hex", label, value)
|
||||
}
|
||||
if raw, err := hex.DecodeString(value); err != nil || len(raw) != 32 {
|
||||
t.Fatalf("%s is not a 32-byte hex key: err=%v len=%d", label, err, len(raw))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUserAccountWireGuardHexConversion(t *testing.T) {
|
||||
pub := b64Key(1)
|
||||
psk := b64Key(100)
|
||||
user := map[string]any{
|
||||
"email": "alice@example.test",
|
||||
"publicKey": pub,
|
||||
"preSharedKey": psk,
|
||||
"allowedIPs": []any{"10.0.0.2/32", "fd00::2/128"},
|
||||
"keepAlive": "25",
|
||||
}
|
||||
|
||||
pc := decodeWgAccount(t, user)
|
||||
assertHexKey(t, "PublicKey", pc.PublicKey)
|
||||
assertHexKey(t, "PreSharedKey", pc.PreSharedKey)
|
||||
|
||||
wantPubHex, _ := hex.DecodeString(pc.PublicKey)
|
||||
gotPub, _ := base64.StdEncoding.DecodeString(pub)
|
||||
if string(wantPubHex) != string(gotPub) {
|
||||
t.Fatal("PublicKey hex does not match the base64 input bytes")
|
||||
}
|
||||
|
||||
if len(pc.AllowedIps) != 2 || pc.AllowedIps[0] != "10.0.0.2/32" || pc.AllowedIps[1] != "fd00::2/128" {
|
||||
t.Fatalf("AllowedIps = %v, want [10.0.0.2/32 fd00::2/128]", pc.AllowedIps)
|
||||
}
|
||||
if pc.KeepAlive != "25" {
|
||||
t.Fatalf("KeepAlive = %q, want %q", pc.KeepAlive, "25")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUserAccountWireGuardNoPSK(t *testing.T) {
|
||||
user := map[string]any{
|
||||
"email": "bob@example.test",
|
||||
"publicKey": b64Key(2),
|
||||
"allowedIPs": []string{"10.0.0.3/32"},
|
||||
}
|
||||
pc := decodeWgAccount(t, user)
|
||||
if pc.PreSharedKey != "" {
|
||||
t.Fatalf("PreSharedKey = %q, want empty", pc.PreSharedKey)
|
||||
}
|
||||
if pc.KeepAlive != "" {
|
||||
t.Fatalf("KeepAlive = %q, want empty", pc.KeepAlive)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUserAccountWireGuardMissingPublicKey(t *testing.T) {
|
||||
user := map[string]any{
|
||||
"email": "c@example.test",
|
||||
"allowedIPs": []any{"10.0.0.4/32"},
|
||||
}
|
||||
if _, err := buildUserAccount("wireguard", user); err == nil {
|
||||
t.Fatal("expected error for missing publicKey")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUserAccountWireGuardMissingAllowedIPs(t *testing.T) {
|
||||
user := map[string]any{
|
||||
"email": "d@example.test",
|
||||
"publicKey": b64Key(3),
|
||||
}
|
||||
if _, err := buildUserAccount("wireguard", user); err == nil {
|
||||
t.Fatal("expected error for missing allowedIPs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUserAccountWireGuardBadKey(t *testing.T) {
|
||||
user := map[string]any{
|
||||
"email": "e@example.test",
|
||||
"publicKey": "not-a-valid-key",
|
||||
"allowedIPs": []any{"10.0.0.5/32"},
|
||||
}
|
||||
if _, err := buildUserAccount("wireguard", user); err == nil {
|
||||
t.Fatal("expected error for invalid publicKey")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildUserAccountUnknownProtocolReturnsNil(t *testing.T) {
|
||||
tm, err := buildUserAccount("mtproto", map[string]any{"email": "x@example.test"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if tm != nil {
|
||||
t.Fatal("expected nil account for unsupported protocol")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user