fix(xray): stop the runtime user API from crashing xray-core

Exercising the whole XrayAPI surface against a real xray-core 26.7.28 (the
version go.mod pins) turned up a way for ordinary panel activity to kill the
core process, plus two smaller mismatches with what the core actually does.

buildUserAccount picked the shadowsocks account type by falling through to a
2022 account whenever the cipher was not one of six hardcoded names. xray's
legacy and 2022 inbounds cast the account they are handed without checking
(proxy/shadowsocks/validator.go, proxy/shadowsocks_2022/inbound_multi.go), so
the wrong type is not an error — it panics the core and drops every connection
on the server. The fallback was reachable without any misconfiguration:
autoRenewClients hands AddUser the client object straight out of the inbound's
settings, where the cipher lives under "method", never "cipher", so every
auto-renewed client on a legacy-cipher shadowsocks inbound took xray down. The
xray-valid aead_* aliases hit it too. The cipher is now read from either key,
matched with the same table (and case-insensitivity) the core's own conf
package uses, and an unrecognized one is an error instead of a guess.

The legacy shadowsocks validator is also the only one that accepts a second
user under an email it already holds, and RemoveUser then drops just one of
them — a disabled or expired client kept connecting. AddUser now drops the
email first on that account type so a single removal fully revokes the client.

GetTraffic skipped every stat the first time it saw it. xray creates a
counter on a user's first use, so that dropped a new client's traffic for a
whole polling interval, as did the counter reset after a core restart. Only
the first poll of a process is a baseline now; later, unseen and rewound
counters both count from zero.

Also fixes three unchecked settings["method"].(string) assertions that panic
the panel on a shadowsocks inbound whose settings carry no method, and bounds
TestRoute's port so an out-of-range value cannot wrap into the uint32 the
core is asked about.

Tests: api_users_e2e_test.go drives add/remove for every protocol against a
real core and asserts it survives each one (skipped unless XRAY_E2E_BINARY is
set); the account-type, traffic-delta and renew paths get unit coverage.
This commit is contained in:
Sanaei
2026-07-28 13:52:10 +02:00
parent 7f7b7e16a4
commit fea6a20f7c
7 changed files with 1019 additions and 29 deletions

View File

@@ -476,7 +476,7 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model
}
cipher := ""
if oldInbound.Protocol == "shadowsocks" {
cipher = oldSettings["method"].(string)
cipher, _ = oldSettings["method"].(string)
}
err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
"email": client.Email,
@@ -858,7 +858,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
if clients[0].Enable {
cipher := ""
if oldInbound.Protocol == "shadowsocks" {
cipher = oldSettings["method"].(string)
cipher, _ = oldSettings["method"].(string)
}
err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{
"email": clients[0].Email,

View File

@@ -0,0 +1,108 @@
package service
import (
"encoding/json"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
// TestAPIUserFromClientCarriesShadowsocksCipher pins what the renew path must
// hand the runtime API. A shadowsocks client object holds no cipher of its own,
// and xray's legacy and 2022 inbounds take different account types that they
// cast without checking — an account built for the wrong one panics the core.
func TestAPIUserFromClientCarriesShadowsocksCipher(t *testing.T) {
client := map[string]any{"email": "a@x", "password": "pw", "method": "aes-256-gcm"}
user := apiUserFromClient(client, "aes-256-gcm")
if got := user["cipher"]; got != "aes-256-gcm" {
t.Fatalf("cipher = %v, want the inbound method", got)
}
if _, polluted := client["cipher"]; polluted {
t.Fatal("the stored client object was mutated; the API-only cipher would be persisted into the inbound settings")
}
user["email"] = "changed@x"
if client["email"] != "a@x" {
t.Fatal("the API user shares storage with the stored client object")
}
}
func TestAPIUserFromClientWithoutCipher(t *testing.T) {
client := map[string]any{"email": "a@x", "id": "11111111-1111-1111-1111-111111111111"}
user := apiUserFromClient(client, "")
if _, ok := user["cipher"]; ok {
t.Fatal("a non-shadowsocks client must not gain a cipher key")
}
if user["id"] != client["id"] {
t.Fatalf("id = %v, want it copied from the client", user["id"])
}
}
// TestAutoRenewShadowsocksKeepsSettingsClean renews a shadowsocks client and
// checks the inbound settings the panel writes back: the cipher the API needs
// must not leak into a stored client object, where it would end up in the
// generated xray config as a per-user key.
func TestAutoRenewShadowsocksKeepsSettingsClean(t *testing.T) {
setupBulkDB(t)
svc := &InboundService{}
db := database.GetDB()
past := time.Now().Add(-48 * time.Hour).UnixMilli()
clients := []model.Client{
{Email: "ss@x", Password: "pw", Enable: false, Reset: 30, ExpiryTime: past},
}
settings := map[string]any{
"method": "aes-256-gcm",
"network": "tcp,udp",
"clients": []map[string]any{
{"email": "ss@x", "password": "pw", "method": "aes-256-gcm", "enable": false, "expiryTime": past, "reset": 30},
},
}
raw, err := json.MarshalIndent(settings, "", " ")
if err != nil {
t.Fatal(err)
}
ib := mkInbound(t, 30011, model.Shadowsocks, string(raw))
if err := svc.clientService.SyncInbound(nil, ib.Id, clients); err != nil {
t.Fatalf("SyncInbound: %v", err)
}
if err := db.Create(&[]xray.ClientTraffic{
{InboundId: ib.Id, Email: "ss@x", Enable: false, Up: 10, Down: 20, Reset: 30, ExpiryTime: past},
}).Error; err != nil {
t.Fatalf("seed client_traffics: %v", err)
}
if _, count, err := svc.autoRenewClients(db); err != nil {
t.Fatalf("autoRenewClients: %v", err)
} else if count != 1 {
t.Fatalf("renewed count = %d, want 1", count)
}
var stored model.Inbound
if err := db.Where("id = ?", ib.Id).First(&stored).Error; err != nil {
t.Fatalf("read inbound: %v", err)
}
var parsed map[string]any
if err := json.Unmarshal([]byte(stored.Settings), &parsed); err != nil {
t.Fatalf("unmarshal stored settings: %v", err)
}
storedClients, _ := parsed["clients"].([]any)
if len(storedClients) != 1 {
t.Fatalf("stored clients = %d, want 1", len(storedClients))
}
client, _ := storedClients[0].(map[string]any)
if _, polluted := client["cipher"]; polluted {
t.Fatalf("the renewed client was persisted with an API-only cipher key: %+v", client)
}
if client["method"] != "aes-256-gcm" {
t.Fatalf("the client's method was lost: %+v", client)
}
if enabled, _ := client["enable"].(bool); !enabled {
t.Fatalf("the renewed client was not re-enabled: %+v", client)
}
}

View File

@@ -287,6 +287,23 @@ func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.Cl
return dbClientTraffics, newExpiryByEmail, nil
}
// apiUserFromClient prepares a stored client object for the runtime AddUser
// call. The copy matters twice over: the stored object keeps being mutated and
// marshalled back into the inbound's settings, which must not gain an API-only
// key, and shadowsocks clients carry no cipher of their own — it lives on the
// inbound, and without it the API cannot tell which of xray's two shadowsocks
// account types the running inbound expects.
func apiUserFromClient(client map[string]any, cipher string) map[string]any {
user := maps.Clone(client)
if user == nil {
user = map[string]any{}
}
if cipher != "" {
user["cipher"] = cipher
}
return user
}
func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
// check for time expired
var traffics []*xray.ClientTraffic
@@ -367,6 +384,10 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
if len(clients) == 0 {
continue
}
cipher := ""
if inbounds[inbound_index].Protocol == model.Shadowsocks {
cipher, _ = settings["method"].(string)
}
for client_index := range clients {
c := clients[client_index].(map[string]any)
email, _ := c["email"].(string)
@@ -393,7 +414,7 @@ func (s *InboundService) autoRenewClients(tx *gorm.DB) (bool, int64, error) {
}{
protocol: string(inbounds[inbound_index].Protocol),
tag: inbounds[inbound_index].Tag,
client: c,
client: apiUserFromClient(c, cipher),
})
}
clients[client_index] = any(c)
@@ -603,7 +624,7 @@ func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (b
if err != nil {
return false, err
}
cipher = oldSettings["method"].(string)
cipher, _ = oldSettings["method"].(string)
}
err1 := rt.AddUser(context.Background(), inbound, map[string]any{
"email": client.Email,

View File

@@ -345,6 +345,10 @@ func (x *XrayAPI) TestRoute(req RouteTestRequest) (*RouteTestResult, error) {
return nil, common.NewError("xray RoutingServiceClient is not initialized")
}
if req.Port < 0 || req.Port > math.MaxUint16 {
return nil, common.NewErrorf("invalid port: %d", req.Port)
}
network := xnet.Network_TCP
if strings.EqualFold(req.Network, "udp") {
network = xnet.Network_UDP
@@ -461,11 +465,71 @@ func collectStringSlice(value any) []string {
}
}
// legacyShadowsocksAccountType is the type URL serial.ToTypedMessage stamps on
// a pre-2022 shadowsocks account, which identifies the one inbound whose user
// list tolerates duplicate emails.
const legacyShadowsocksAccountType = "xray.proxy.shadowsocks.Account"
// shadowsocks2022Ciphers are the methods that select xray's shadowsocks-2022
// inbound (sing's shadowaead_2022 list). They take a different account type
// than the legacy AEAD ciphers, and the running inbound casts the account it
// receives without checking, so a wrong guess takes the whole core down.
var shadowsocks2022Ciphers = map[string]struct{}{
"2022-blake3-aes-128-gcm": {},
"2022-blake3-aes-256-gcm": {},
"2022-blake3-chacha20-poly1305": {},
}
// shadowsocksCipherName resolves the cipher a shadowsocks user's account must
// be built for. Panel-built user maps carry it under "cipher"; client objects
// taken verbatim from an inbound's settings carry the inbound's method under
// "method" instead (HealShadowsocksClientMethods writes it onto every
// legacy-cipher client).
func shadowsocksCipherName(user map[string]any) (string, error) {
cipher, err := getOptionalUserString(user, "cipher")
if err != nil {
return "", err
}
if cipher != "" {
return cipher, nil
}
return getOptionalUserString(user, "method")
}
// shadowsocksCipherType mirrors xray-core's infra/conf cipherFromString,
// aliases and case-insensitivity included, so the account the panel builds for
// a live user matches the one the core built for that inbound from its config.
func shadowsocksCipherType(cipher string) shadowsocks.CipherType {
switch strings.ToLower(cipher) {
case "aes-128-gcm", "aead_aes_128_gcm":
return shadowsocks.CipherType_AES_128_GCM
case "aes-256-gcm", "aead_aes_256_gcm":
return shadowsocks.CipherType_AES_256_GCM
case "chacha20-poly1305", "aead_chacha20_poly1305", "chacha20-ietf-poly1305":
return shadowsocks.CipherType_CHACHA20_POLY1305
case "xchacha20-poly1305", "aead_xchacha20_poly1305", "xchacha20-ietf-poly1305":
return shadowsocks.CipherType_XCHACHA20_POLY1305
default:
return shadowsocks.CipherType_UNKNOWN
}
}
// isShadowsocks2022Cipher reports whether the method selects the
// shadowsocks-2022 inbound rather than the legacy AEAD one.
func isShadowsocks2022Cipher(cipher string) bool {
_, ok := shadowsocks2022Ciphers[strings.ToLower(cipher)]
return ok
}
// buildUserAccount constructs the typed xray account for a user of the given
// protocol. It returns (nil, nil) for protocols that cannot be altered live so
// callers skip the AlterInbound call. WireGuard keys must be converted to the
// hex form xray's wireguard proxy expects (its ParseKey uses hex.DecodeString),
// unlike the file-config path which accepts base64 and converts internally.
// Shadowsocks is resolved strictly from the inbound's cipher: the legacy and
// 2022 inbounds take different account types and cast whatever they receive
// without checking, so an unrecognized cipher is an error rather than a guess
// that would panic the core and kill every connection on the server.
func buildUserAccount(protocolName string, user map[string]any) (*serial.TypedMessage, error) {
switch protocolName {
case "vmess":
@@ -523,7 +587,7 @@ func buildUserAccount(protocolName string, user map[string]any) (*serial.TypedMe
Password: password,
}), nil
case "shadowsocks":
cipher, err := getOptionalUserString(user, "cipher")
cipher, err := shadowsocksCipherName(user)
if err != nil {
return nil, err
}
@@ -533,28 +597,19 @@ func buildUserAccount(protocolName string, user map[string]any) (*serial.TypedMe
return nil, err
}
var ssCipherType shadowsocks.CipherType
switch cipher {
case "aes-128-gcm":
ssCipherType = shadowsocks.CipherType_AES_128_GCM
case "aes-256-gcm":
ssCipherType = shadowsocks.CipherType_AES_256_GCM
case "chacha20-poly1305", "chacha20-ietf-poly1305":
ssCipherType = shadowsocks.CipherType_CHACHA20_POLY1305
case "xchacha20-poly1305", "xchacha20-ietf-poly1305":
ssCipherType = shadowsocks.CipherType_XCHACHA20_POLY1305
default:
ssCipherType = shadowsocks.CipherType_UNKNOWN
}
if ssCipherType != shadowsocks.CipherType_UNKNOWN {
return serial.ToTypedMessage(&shadowsocks.Account{
Password: password,
CipherType: ssCipherType,
if isShadowsocks2022Cipher(cipher) {
return serial.ToTypedMessage(&shadowsocks_2022.Account{
Key: password,
}), nil
}
return serial.ToTypedMessage(&shadowsocks_2022.Account{
Key: password,
ssCipherType := shadowsocksCipherType(cipher)
if ssCipherType == shadowsocks.CipherType_UNKNOWN {
return nil, common.NewErrorf("shadowsocks: unknown cipher %q, cannot build an account for the running inbound", cipher)
}
return serial.ToTypedMessage(&shadowsocks.Account{
Password: password,
CipherType: ssCipherType,
}), nil
case "hysteria":
auth, err := getRequiredUserString(user, "auth")
@@ -605,7 +660,11 @@ func buildUserAccount(protocolName string, user map[string]any) (*serial.TypedMe
}
}
// AddUser adds a user to an inbound in the Xray core using the specified protocol and user data.
// AddUser adds a user to an inbound in the Xray core using the specified
// protocol and user data. On a legacy shadowsocks inbound the add first drops
// any existing holder of the email: that is the one inbound whose validator
// does not reject a duplicate email, and a later removal would then drop just
// one of the two registrations, leaving a disabled client able to connect.
func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]any) error {
userEmail, err := getRequiredUserString(user, "email")
if err != nil {
@@ -625,6 +684,10 @@ func (x *XrayAPI) AddUser(Protocol string, inboundTag string, user map[string]an
}
client := *x.HandlerServiceClient
if account.Type == legacyShadowsocksAccountType {
_ = x.RemoveUser(inboundTag, userEmail)
}
ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout)
defer cancel()
_, err = client.AlterInbound(ctx, &command.AlterInboundRequest{
@@ -663,7 +726,13 @@ func (x *XrayAPI) RemoveUser(inboundTag, email string) error {
return nil
}
// GetTraffic queries traffic statistics from the Xray core, optionally resetting counters.
// GetTraffic queries traffic statistics from the Xray core and reports what
// accrued since the previous call; the counters themselves are never reset.
// The first call of a process only records baselines, since it may be reading
// counters that already hold traffic the panel cannot attribute. After that a
// name the panel has not seen — xray creates a counter on a user's first use —
// and a counter that moved backwards because the core restarted both count
// from zero, so no client's traffic is dropped for a whole polling interval.
func (x *XrayAPI) GetTraffic() ([]*Traffic, []*ClientTraffic, error) {
if x.grpcClient == nil {
return nil, nil, common.NewError("xray api is not initialized")
@@ -685,13 +754,17 @@ func (x *XrayAPI) GetTraffic() ([]*Traffic, []*ClientTraffic, error) {
tagTrafficMap := make(map[string]*Traffic)
emailTrafficMap := make(map[string]*ClientTraffic)
baselinePass := len(x.StatsLastValues) == 0
for _, stat := range resp.GetStat() {
lastValue, ok := x.StatsLastValues[stat.Name]
x.StatsLastValues[stat.Name] = stat.Value
if !ok || stat.Value < lastValue {
// skip first time of seen stat
if baselinePass {
continue
}
if !ok || stat.Value < lastValue {
lastValue = 0
}
value := stat.Value - lastValue
if matches := trafficRegex.FindStringSubmatch(stat.Name); len(matches) == 4 {
processTraffic(matches, value, tagTrafficMap)

View File

@@ -0,0 +1,149 @@
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")
}
}

View File

@@ -0,0 +1,192 @@
package xray
import (
"context"
"net"
"testing"
statsService "github.com/xtls/xray-core/app/stats/command"
"google.golang.org/grpc"
)
// fakeStatsServer serves a scripted sequence of QueryStats responses, one per
// call, so the delta bookkeeping in GetTraffic can be driven exactly.
type fakeStatsServer struct {
statsService.UnimplementedStatsServiceServer
rounds [][]*statsService.Stat
calls int
}
func (f *fakeStatsServer) QueryStats(context.Context, *statsService.QueryStatsRequest) (*statsService.QueryStatsResponse, error) {
round := f.calls
f.calls++
if round >= len(f.rounds) {
round = len(f.rounds) - 1
}
return &statsService.QueryStatsResponse{Stat: f.rounds[round]}, nil
}
func stat(name string, value int64) *statsService.Stat {
return &statsService.Stat{Name: name, Value: value}
}
// startFakeStats runs the scripted stats service and returns an XrayAPI wired
// to it.
func startFakeStats(t *testing.T, rounds [][]*statsService.Stat) *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})
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 clientTrafficByEmail(t *testing.T, traffics []*ClientTraffic) map[string]*ClientTraffic {
t.Helper()
byEmail := make(map[string]*ClientTraffic, len(traffics))
for _, ct := range traffics {
byEmail[ct.Email] = ct
}
return byEmail
}
// TestGetTrafficFirstPollIsBaselineOnly pins the one case the skip protects:
// 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{
{stat("user>>>alice>>>traffic>>>uplink", 5000)},
})
_, clients, err := api.GetTraffic()
if err != nil {
t.Fatalf("GetTraffic: %v", err)
}
if len(clients) != 0 {
t.Fatalf("first poll reported %+v, want no traffic (baseline only)", clients[0])
}
if got := api.StatsLastValues["user>>>alice>>>traffic>>>uplink"]; got != 5000 {
t.Fatalf("baseline = %d, want 5000", got)
}
}
// TestGetTrafficCountsNewStatFromZero is the regression for a new client's
// 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{
{stat("user>>>alice>>>traffic>>>uplink", 100)},
{
stat("user>>>alice>>>traffic>>>uplink", 180),
stat("user>>>bob>>>traffic>>>uplink", 4096),
stat("user>>>bob>>>traffic>>>downlink", 8192),
},
})
if _, _, err := api.GetTraffic(); err != nil {
t.Fatalf("GetTraffic (baseline): %v", err)
}
_, clients, err := api.GetTraffic()
if err != nil {
t.Fatalf("GetTraffic: %v", err)
}
byEmail := clientTrafficByEmail(t, clients)
bob, ok := byEmail["bob"]
if !ok {
t.Fatal("a client whose counter appeared after the baseline poll reported no traffic")
}
if bob.Up != 4096 || bob.Down != 8192 {
t.Fatalf("bob = up %d / down %d, want 4096 / 8192", bob.Up, bob.Down)
}
alice, ok := byEmail["alice"]
if !ok {
t.Fatal("alice reported no traffic")
}
if alice.Up != 80 {
t.Fatalf("alice up = %d, want the delta 80", alice.Up)
}
}
// TestGetTrafficCountsAfterCounterReset covers a core restart: the counters
// 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{
{stat("user>>>alice>>>traffic>>>uplink", 100)},
{stat("user>>>alice>>>traffic>>>uplink", 900)},
{stat("user>>>alice>>>traffic>>>uplink", 250)},
})
if _, _, err := api.GetTraffic(); err != nil {
t.Fatalf("GetTraffic (baseline): %v", err)
}
if _, _, err := api.GetTraffic(); err != nil {
t.Fatalf("GetTraffic (delta): %v", err)
}
_, clients, err := api.GetTraffic()
if err != nil {
t.Fatalf("GetTraffic (after reset): %v", err)
}
alice, ok := clientTrafficByEmail(t, clients)["alice"]
if !ok {
t.Fatal("traffic after a counter reset was dropped entirely")
}
if alice.Up != 250 {
t.Fatalf("alice up = %d, want 250 counted from zero", alice.Up)
}
}
// TestGetTrafficSkipsAPIInboundAndPrunes checks the tag-level parsing: the api
// 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{
{
stat("inbound>>>api>>>traffic>>>uplink", 10),
stat("inbound>>>in-443>>>traffic>>>uplink", 10),
stat("inbound>>>gone-1>>>traffic>>>uplink", 10),
stat("inbound>>>gone-2>>>traffic>>>uplink", 10),
stat("inbound>>>gone-3>>>traffic>>>uplink", 10),
stat("inbound>>>gone-4>>>traffic>>>uplink", 10),
stat("inbound>>>gone-5>>>traffic>>>uplink", 10),
},
{
stat("inbound>>>api>>>traffic>>>uplink", 99),
stat("inbound>>>in-443>>>traffic>>>uplink", 60),
stat("inbound>>>in-443>>>traffic>>>downlink", 70),
},
})
if _, _, err := api.GetTraffic(); err != nil {
t.Fatalf("GetTraffic (baseline): %v", err)
}
tags, _, err := api.GetTraffic()
if err != nil {
t.Fatalf("GetTraffic: %v", err)
}
if len(tags) != 1 {
t.Fatalf("got %d tag traffics, want only the non-api inbound: %+v", len(tags), tags)
}
if tags[0].Tag != "in-443" || !tags[0].IsInbound || tags[0].IsOutbound {
t.Fatalf("tag traffic = %+v, want inbound in-443", tags[0])
}
if tags[0].Up != 50 || tags[0].Down != 70 {
t.Fatalf("in-443 = up %d / down %d, want 50 / 70", tags[0].Up, tags[0].Down)
}
if _, stale := api.StatsLastValues["inbound>>>gone-1>>>traffic>>>uplink"]; stale {
t.Fatal("baselines for stats that no longer exist were not pruned")
}
}

View File

@@ -0,0 +1,447 @@
package xray
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"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": "",
}
for k, v := range fields {
user[k] = v
}
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)
}
}