From d4ce11954d7460372d54275e619542e532d17f05 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Sun, 29 Nov 2026 21:48:57 +0330 Subject: [PATCH] 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. --- internal/web/service/client_bulk.go | 5 +- .../service/client_disable_restart_test.go | 145 ++++++++++++++++++ internal/web/service/client_inbound_apply.go | 15 +- internal/web/service/inbound_disable.go | 2 +- internal/web/service/inbound_traffic_apply.go | 2 +- internal/web/service/xray.go | 4 +- .../web/service/xray_depletion_restart.go | 14 +- .../service/xray_depletion_restart_test.go | 8 +- .../service/xray_lifecycle_telemetry_test.go | 4 +- 9 files changed, 177 insertions(+), 22 deletions(-) diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index b996d31a6..ea249ba19 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -1226,6 +1226,9 @@ func (s *ClientService) bulkDelInboundClients( err1 := rt.RemoveUser(context.Background(), oldInbound, email) if err1 == nil { logger.Debug("Client deleted on", rt.Name(), ":", email) + if endDroppedClientSessions(oldInbound) { + res.needRestart = true + } } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) { logger.Debug("User is already deleted. Nothing to do more...") } else { @@ -1851,7 +1854,7 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, if err1 != nil && !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", ch.email)) { logger.Debug("Error in removing client on", rt.Name(), ":", err1) res.needRestart = true - } else if err1 == nil && droppedClientNeedsRestart() { + } else if err1 == nil && endDroppedClientSessions(oldInbound) { // A removed credential does not end the session it was serving. res.needRestart = true } diff --git a/internal/web/service/client_disable_restart_test.go b/internal/web/service/client_disable_restart_test.go index aede9f81d..ae6cdc1d4 100644 --- a/internal/web/service/client_disable_restart_test.go +++ b/internal/web/service/client_disable_restart_test.go @@ -1,6 +1,8 @@ package service import ( + "os" + goruntime "runtime" "testing" "github.com/mhsanaei/3x-ui/v3/internal/database" @@ -62,3 +64,146 @@ func TestManualClientDisableHonoursRestartSetting(t *testing.T) { }) } } + +// 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) + } + }) + } +} diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index 8f4e8879d..6a1c4842c 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -22,13 +22,16 @@ import ( "gorm.io/gorm" ) -// droppedClientNeedsRestart is what restartXrayOnClientDisable asks for: the core -// API drops the credential only, so a live session needs the process replaced. -func droppedClientNeedsRestart() bool { +// endDroppedClientSessions is what restartXrayOnClientDisable asks for once the API removed a +// client: it drops the credential only, so the restart is queued here, not left to a config diff. +func endDroppedClientSessions(inbound *model.Inbound) bool { on, err := (&SettingService{}).GetRestartXrayOnClientDisable() if err != nil { logger.Warning("get RestartXrayOnClientDisable failed:", err) } + if on && removalLeavesXraySessions(inbound) { + pendingXraySessionDrop.Store(true) + } return on } @@ -312,6 +315,8 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId if !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.email)) { needRestart = true } + } else if endDroppedClientSessions(oldInbound) { + needRestart = true } } } else if nodePush && !nodePushFailed { @@ -1186,7 +1191,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo logger.Debug("Old client deleted on", rt.Name(), ":", oldEmail) // The API removal is enough only while the client is re-added; a // dropped one ends its session only through a restart. - if !clients[0].Enable && droppedClientNeedsRestart() { + if !clients[0].Enable && endDroppedClientSessions(oldInbound) { needRestart = true } } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", oldEmail)) { @@ -1366,7 +1371,7 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo needRestart = true } else if err1 := rt.RemoveUser(context.Background(), oldInbound, email); err1 == nil { logger.Debug("Client deleted on", rt.Name(), ":", email) - needRestart = droppedClientNeedsRestart() + needRestart = endDroppedClientSessions(oldInbound) } else if strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", email)) { logger.Debug("User is already deleted. Nothing to do more...") } else { diff --git a/internal/web/service/inbound_disable.go b/internal/web/service/inbound_disable.go index 24bd80111..a3b502b5e 100644 --- a/internal/web/service/inbound_disable.go +++ b/internal/web/service/inbound_disable.go @@ -177,7 +177,7 @@ func (s *InboundService) disableInvalidClients(tx *gorm.DB, mutationBatch *traff oldInbound: *oldInbound, newInbound: *inbound, }) mutationBatch.addNode(*inbound.NodeID) - if depletionNeedsXrayRestart(oldInbound) { + if removalLeavesXraySessions(oldInbound) { disabledNodeIDs[*inbound.NodeID] = struct{}{} } continue diff --git a/internal/web/service/inbound_traffic_apply.go b/internal/web/service/inbound_traffic_apply.go index 80b7fb48b..d2d65afd5 100644 --- a/internal/web/service/inbound_traffic_apply.go +++ b/internal/web/service/inbound_traffic_apply.go @@ -136,7 +136,7 @@ func (s *InboundService) applyTrafficMutationBatch(b *trafficMutationBatch) bool if err != nil && strings.Contains(err.Error(), "not found") { err = nil } - if err == nil && original != nil && depletionNeedsXrayRestart(&plan.inbound) { + if err == nil && original != nil && removalLeavesXraySessions(&plan.inbound) { if removed == nil { removed = make(map[string]map[string]struct{}) } diff --git a/internal/web/service/xray.go b/internal/web/service/xray.go index 9d1143f62..1e1aa7800 100644 --- a/internal/web/service/xray.go +++ b/internal/web/service/xray.go @@ -1981,7 +1981,7 @@ func (s *XrayService) IsNeedRestartAndSetFalse() bool { func (s *XrayService) ApplyPendingRestart() { reconcile := isNeedXrayReconcile.Swap(false) pending := pendingXrayRestart.Swap(nil) - depleted := pendingXrayDepletionRestart.Swap(false) && s.IsXrayRunning() + depleted := pendingXraySessionDrop.Swap(false) && s.IsXrayRunning() if pending == nil && !reconcile && !depleted { return } @@ -1996,7 +1996,7 @@ func (s *XrayService) ApplyPendingRestart() { if err := s.restartXrayFrom(false, origin, trigger, depleted); err != nil { logger.Error("reconcile xray failed:", err) if depleted { - pendingXrayDepletionRestart.Store(true) + pendingXraySessionDrop.Store(true) } if pending != nil { pendingXrayRestart.CompareAndSwap(nil, pending) diff --git a/internal/web/service/xray_depletion_restart.go b/internal/web/service/xray_depletion_restart.go index bea3faa02..c2509b4d4 100644 --- a/internal/web/service/xray_depletion_restart.go +++ b/internal/web/service/xray_depletion_restart.go @@ -7,9 +7,11 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/logger" ) -var pendingXrayDepletionRestart atomic.Bool +// pendingXraySessionDrop asks the next tick to replace the core: the API removed a client's +// credential, and only a new process ends the sessions that client still has open. +var pendingXraySessionDrop atomic.Bool -func depletionNeedsXrayRestart(inbound *model.Inbound) bool { +func removalLeavesXraySessions(inbound *model.Inbound) bool { if !inbound.Enable { return false } @@ -23,14 +25,14 @@ func depletionNeedsXrayRestart(inbound *model.Inbound) bool { func queueLocalDepletionRestart(batch *trafficMutationBatch) { for _, plan := range batch.localPlans { - if plan.action != trafficRemoveUser || !depletionNeedsXrayRestart(&plan.inbound) { + if plan.action != trafficRemoveUser || !removalLeavesXraySessions(&plan.inbound) { continue } enabled, err := (&SettingService{}).GetRestartXrayOnClientDepleted() if err != nil { logger.Warning("get restartXrayOnClientDepleted failed:", err) } else if enabled { - pendingXrayDepletionRestart.Store(true) + pendingXraySessionDrop.Store(true) } return } @@ -38,11 +40,11 @@ func queueLocalDepletionRestart(batch *trafficMutationBatch) { // ApplyPendingDepletionRestart drops sessions for a committed local depletion batch. func (s *XrayService) ApplyPendingDepletionRestart() { - if !pendingXrayDepletionRestart.Swap(false) || !s.IsXrayRunning() { + if !pendingXraySessionDrop.Swap(false) || !s.IsXrayRunning() { return } if err := s.restartXrayFrom(false, XrayOriginClientDepletion, "", true); err != nil { logger.Error("restart xray after client depletion failed:", err) - pendingXrayDepletionRestart.Store(true) + pendingXraySessionDrop.Store(true) } } diff --git a/internal/web/service/xray_depletion_restart_test.go b/internal/web/service/xray_depletion_restart_test.go index 22a314fac..5edcb23ed 100644 --- a/internal/web/service/xray_depletion_restart_test.go +++ b/internal/web/service/xray_depletion_restart_test.go @@ -44,8 +44,8 @@ func TestDepletionSettingsAreIndependentAndSurviveLegacySaves(t *testing.T) { if err != nil || !depletion { t.Fatalf("depletion = %t, error %v", depletion, err) } - if droppedClientNeedsRestart() { - t.Fatal("enabling depletion restarts also enabled ordinary disable restarts") + if ordinary, err := settings.GetRestartXrayOnClientDisable(); err != nil || ordinary { + t.Fatalf("enabling depletion restarts also enabled ordinary disable restarts: %t, error %v", ordinary, err) } timeout, err := settings.GetNodeTrafficFetchTimeout() if err != nil || timeout != 15*time.Second { @@ -70,11 +70,11 @@ func checkCommittedLocalDepletion(t *testing.T, restart bool) { } wasStopped := isManuallyStopped.Swap(false) - wasPending := pendingXrayDepletionRestart.Swap(false) + wasPending := pendingXraySessionDrop.Swap(false) ordinaryPending := pendingXrayRestart.Swap(nil) t.Cleanup(func() { isManuallyStopped.Store(wasStopped) - pendingXrayDepletionRestart.Store(wasPending) + pendingXraySessionDrop.Store(wasPending) pendingXrayRestart.Store(ordinaryPending) }) t.Setenv("XUI_BIN_FOLDER", t.TempDir()) diff --git a/internal/web/service/xray_lifecycle_telemetry_test.go b/internal/web/service/xray_lifecycle_telemetry_test.go index 8e4a053f3..323254643 100644 --- a/internal/web/service/xray_lifecycle_telemetry_test.go +++ b/internal/web/service/xray_lifecycle_telemetry_test.go @@ -35,11 +35,11 @@ func TestXrayLifecycleReportsActualReplacement(t *testing.T) { first := startFakeCore(t) stopped := isManuallyStopped.Swap(false) pending := pendingXrayRestart.Swap(nil) - depletion := pendingXrayDepletionRestart.Swap(false) + depletion := pendingXraySessionDrop.Swap(false) t.Cleanup(func() { isManuallyStopped.Store(stopped) pendingXrayRestart.Store(pending) - pendingXrayDepletionRestart.Store(depletion) + pendingXraySessionDrop.Store(depletion) }) svc := new(XrayService)