Files
mirror-3x-ui/internal/web/service/client_disable_restart_test.go
T
Sanaei d4ce11954d fix(clients): end a removed client's sessions without waiting on a config diff
With restart-on-client-disable on, a client the API removes from a running
inbound must be followed by a core restart: the removal drops the credential
only. The apply layer asked for that restart by setting the generic
need-restart flag, and the tick then restarted only when the generated config
differed from the running-config snapshot. A client added over the API is not
in that snapshot, so disabling or deleting it before any reconcile diffed as
"no change" and its live session kept passing traffic.

The removal now queues the session-drop restart itself, through the request
the depletion path already uses, so the tick replaces the core whatever the
snapshot holds. Detaching a client and bulk delete removed clients the same
way without asking for anything; they queue it too. WireGuard is left out: its
session ends with the peer.

The pending flag and the protocol predicate lose "depletion" from their names
now that manual removals share them.

Run on a panel with the real core: a client added after the core started,
holding a stream open, was cut and the core replaced within one tick of its
disable; before the change the stream ran on and the core kept its PID.
2026-11-29 21:48:57 +03:30

210 lines
7.9 KiB
Go

package service
import (
"os"
goruntime "runtime"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
"github.com/mhsanaei/3x-ui/v3/internal/xray"
)
// The manual switch applies through the runtime, and the core's API removal
// drops the credential only: whether the live session ends is what the setting
// asks for, exactly as on the auto-disable path #6533 reports from.
func TestManualClientDisableHonoursRestartSetting(t *testing.T) {
const email = "manual-disable@example.com"
for _, tc := range []struct {
name string
setting bool
want bool
}{
{"setting on", true, true},
{"setting off", false, false},
} {
t.Run(tc.name, func(t *testing.T) {
setupConflictDB(t)
setRestartOnClientDisable(t, tc.setting)
mgr := runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }})
mgr.SetLocalRuntimeOverride(&fakeNodeRuntime{})
runtime.SetManager(mgr)
t.Cleanup(func() { runtime.SetManager(nil) })
seedInboundConflict(t, "manual-disable", "0.0.0.0", 50055, model.VLESS, `{"network":"tcp"}`,
`{"clients":[{"email":"`+email+`","id":"5f2eb9d6-3a2f-4a55-9812-6ea1e2f7a333","enable":true}]}`)
inbound := loadInboundByTag(t, "manual-disable")
inboundSvc := InboundService{}
clientSvc := ClientService{}
clients, err := inboundSvc.GetClients(inbound)
if err != nil {
t.Fatalf("GetClients: %v", err)
}
if err := clientSvc.SyncInbound(nil, inbound.Id, clients); err != nil {
t.Fatalf("SyncInbound: %v", err)
}
if err := database.GetDB().Create(&xray.ClientTraffic{InboundId: inbound.Id, Email: email, Enable: true}).Error; err != nil {
t.Fatalf("seed traffic: %v", err)
}
changed, needRestart, err := clientSvc.SetClientEnableByEmail(&inboundSvc, email, false)
if err != nil {
t.Fatalf("SetClientEnableByEmail: %v", err)
}
if !changed {
t.Fatal("the disable must be recorded")
}
if needRestart != tc.want {
t.Fatalf("needRestart = %v, want %v", needRestart, tc.want)
}
})
}
}
// A client the core learned over the API is not in the config snapshot a reconcile diffs
// against, so its disable must reach the restart without that diff (#6550's promise).
func TestManualDisableRestartsACoreThatLearnedTheClientOverTheAPI(t *testing.T) {
if goruntime.GOOS == "windows" {
t.Skip("the fake core is a shell script")
}
const email = "added-live@example.com"
setupConflictDB(t)
setRestartOnClientDisable(t, true)
stopped := isManuallyStopped.Swap(false)
pending := pendingXrayRestart.Swap(nil)
t.Cleanup(func() {
isManuallyStopped.Store(stopped)
pendingXrayRestart.Store(pending)
})
t.Setenv("XUI_BIN_FOLDER", t.TempDir())
t.Setenv("XUI_LOG_FOLDER", t.TempDir())
if err := os.WriteFile(xray.GetBinaryPath(), []byte(fakeXrayCore("26.10.21", true)), 0o755); err != nil {
t.Fatal(err)
}
mgr := runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }})
mgr.SetLocalRuntimeOverride(&fakeNodeRuntime{})
runtime.SetManager(mgr)
t.Cleanup(func() { runtime.SetManager(nil) })
seedInboundConflict(t, "added-live", "127.0.0.1", freeLoopbackPort(t), model.VLESS, `{"network":"tcp"}`, `{"clients":[]}`)
inbound := loadInboundByTag(t, "added-live")
before := startFakeCore(t)
inboundSvc, clientSvc, xraySvc := InboundService{}, ClientService{}, XrayService{}
created := model.Client{Email: email, ID: "5f2eb9d6-3a2f-4a55-9812-6ea1e2f7a444", Enable: true}
if _, err := clientSvc.Create(&inboundSvc, &ClientCreatePayload{Client: created, InboundIds: []int{inbound.Id}}); err != nil {
t.Fatalf("Create: %v", err)
}
_, needRestart, err := clientSvc.SetClientEnableByEmail(&inboundSvc, email, false)
if err != nil {
t.Fatalf("SetClientEnableByEmail: %v", err)
}
// What the controller does with the flag, then the 30s tick.
if needRestart {
xraySvc.SetToNeedRestart()
}
xraySvc.ApplyPendingRestart()
after := XrayProcess()
if after == before || after == nil || !after.IsRunning() || before.IsRunning() {
t.Fatal("the core that served the disabled client was not replaced: its live session keeps running")
}
}
// Every way a client leaves a running local inbound asks for the same restart: the tick
// honours the request itself, so no path may rely on a later config diff to notice.
func TestClientLeavingARunningInboundQueuesTheSessionDrop(t *testing.T) {
const email = "leaving@example.com"
const vlessClient = `{"email":"` + email + `","id":"5f2eb9d6-3a2f-4a55-9812-6ea1e2f7a555","enable":true}`
const wireguardClient = `{"email":"` + email + `","publicKey":"cHVibGljLWtleS1mb3ItdGhlLXRlc3QtcGVlci0wMDAwMDA=","allowedIPs":["10.9.0.2/32"],"enable":true}`
for _, tc := range []struct {
name string
protocol model.Protocol
settings string
setting bool
leave func(*testing.T, *InboundService, *ClientService, *model.Inbound) error
want bool
}{
{
"delete", model.VLESS, `{"clients":[` + vlessClient + `]}`, true,
func(_ *testing.T, inboundSvc *InboundService, clientSvc *ClientService, ib *model.Inbound) error {
_, err := clientSvc.DelInboundClientByEmail(inboundSvc, ib.Id, email, false, true)
return err
}, true,
},
{
"bulk disable", model.VLESS, `{"clients":[` + vlessClient + `]}`, true,
func(_ *testing.T, inboundSvc *InboundService, clientSvc *ClientService, _ *model.Inbound) error {
_, _, err := clientSvc.BulkSetEnable(inboundSvc, []string{email}, false)
return err
}, true,
},
{
"detach", model.VLESS, `{"clients":[` + vlessClient + `]}`, true,
func(_ *testing.T, inboundSvc *InboundService, clientSvc *ClientService, ib *model.Inbound) error {
_, err := clientSvc.DetachByEmail(inboundSvc, ib.Id, email)
return err
}, true,
},
{
"bulk delete", model.VLESS, `{"clients":[` + vlessClient + `]}`, true,
func(_ *testing.T, inboundSvc *InboundService, clientSvc *ClientService, _ *model.Inbound) error {
_, _, err := clientSvc.BulkDelete(inboundSvc, []string{email}, false)
return err
}, true,
},
{
"setting off", model.VLESS, `{"clients":[` + vlessClient + `]}`, false,
func(_ *testing.T, inboundSvc *InboundService, clientSvc *ClientService, _ *model.Inbound) error {
_, _, err := clientSvc.SetClientEnableByEmail(inboundSvc, email, false)
return err
}, false,
},
// A WireGuard session ends with its peer: there is nothing left to restart for.
{
"wireguard peer", model.WireGuard, `{"secretKey":"server","clients":[` + wireguardClient + `]}`, true,
func(_ *testing.T, inboundSvc *InboundService, clientSvc *ClientService, _ *model.Inbound) error {
_, _, err := clientSvc.SetClientEnableByEmail(inboundSvc, email, false)
return err
}, false,
},
} {
t.Run(tc.name, func(t *testing.T) {
setupConflictDB(t)
setRestartOnClientDisable(t, tc.setting)
wasQueued := pendingXraySessionDrop.Swap(false)
t.Cleanup(func() { pendingXraySessionDrop.Store(wasQueued) })
mgr := runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }})
mgr.SetLocalRuntimeOverride(&fakeNodeRuntime{})
runtime.SetManager(mgr)
t.Cleanup(func() { runtime.SetManager(nil) })
seedInboundConflict(t, "leaving", "127.0.0.1", 50056, tc.protocol, `{"network":"tcp"}`, tc.settings)
inbound := loadInboundByTag(t, "leaving")
inboundSvc, clientSvc := InboundService{}, ClientService{}
clients, err := inboundSvc.GetClients(inbound)
if err != nil {
t.Fatalf("GetClients: %v", err)
}
if err := clientSvc.SyncInbound(nil, inbound.Id, clients); err != nil {
t.Fatalf("SyncInbound: %v", err)
}
if err := database.GetDB().Create(&xray.ClientTraffic{InboundId: inbound.Id, Email: email, Enable: true}).Error; err != nil {
t.Fatalf("seed traffic: %v", err)
}
if err := tc.leave(t, &inboundSvc, &clientSvc, inbound); err != nil {
t.Fatalf("%s: %v", tc.name, err)
}
if got := pendingXraySessionDrop.Load(); got != tc.want {
t.Fatalf("session drop queued = %v, want %v", got, tc.want)
}
})
}
}