From eccf2e71bdc6f1a98f95eca47397c76b0220d962 Mon Sep 17 00:00:00 2001 From: Sanaei Date: Tue, 24 Nov 2026 23:52:09 +0330 Subject: [PATCH] fix(wireguard): change one peer without disturbing the others A client's devices all carry the client's email, and the core removes a WireGuard user by email, one peer at a time. The hot diff therefore removed every peer of the email and added the survivors back, and a client that left for good counted as a user whose sessions had to be dropped. Measured on a running panel (Xray 26.11.9, kernel WireGuard clients): - disabling or deleting one device cut the client's other devices for about 15 s, the time a client waits before it handshakes again with a peer the server forgot; - disabling or deleting a connected WireGuard client restarted the whole core with the default restartXrayOnClientDisable, taking every inbound down. The diff is now per public key: a peer that stays is never touched, a changed peer is updated in place, and a removed one goes through RemoveWireguardPeer, which relabels that single peer and removes the label. A WireGuard session ends with its peer, so its removal no longer asks for the restart. After the change the other devices and other clients of the inbound keep their tunnels with no gap, and the core keeps its pid. --- internal/web/service/inbound.go | 3 - .../web/service/wireguard_hot_apply_test.go | 20 ++- internal/web/service/xray.go | 4 +- internal/xray/api.go | 46 ++++++ internal/xray/api_users_e2e_test.go | 148 ++++++++++++++++++ internal/xray/hot-diff-wireguard.go | 24 +-- internal/xray/hot_diff.go | 7 +- internal/xray/hot_diff_drops_users_test.go | 24 +++ 8 files changed, 253 insertions(+), 23 deletions(-) diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 5a1faec16..159fe8881 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -2432,9 +2432,6 @@ func applyInboundUserOps(rt runtime.Runtime, running, next *model.Inbound) bool return false } if next.Protocol == model.WireGuard { - if diff.DropsUsers() { - return false - } if !diff.Empty() { // Reconcile peers and the Xray config snapshot together. (&XrayService{}).SetToNeedReconcile() diff --git a/internal/web/service/wireguard_hot_apply_test.go b/internal/web/service/wireguard_hot_apply_test.go index c07f3c738..6f02bbf79 100644 --- a/internal/web/service/wireguard_hot_apply_test.go +++ b/internal/web/service/wireguard_hot_apply_test.go @@ -69,14 +69,20 @@ func TestWireguardDeviceChangesKeepOtherCorePeers(t *testing.T) { next.InboundConfigs = slices.Clone(previous.InboundConfigs) next.InboundConfigs[len(next.InboundConfigs)-1] = *render() diff, ok := xray.ComputeHotDiff(previous, &next) - if !ok || diff.DropsUsers() || len(diff.RemovedInboundTags)+len(diff.AddedInbounds) != 0 || - len(diff.AddedUsers) != 1 || diff.AddedUsers[0].Email != "owner" || - diff.AddedUsers[0].User["keepAlive"] != "25" { - t.Fatalf("%s: expected only owner peer changes, got %+v", step.name, diff) + if !ok || diff.DropsUsers() || len(diff.RemovedInboundTags)+len(diff.AddedInbounds) != 0 { + t.Fatalf("%s: expected an in-place peer change, got %+v", step.name, diff) } - if step.active && len(diff.RemovedUsers) != 0 || - !step.active && (len(diff.RemovedUsers) != 1 || diff.RemovedUsers[0].Email != "owner") { - t.Fatalf("%s: unexpected removals: %+v", step.name, diff.RemovedUsers) + // Only the phone's own peer may be touched: removing or re-adding the owner's + // primary peer resets the tunnel of a device nobody changed. + touched, untouched := diff.AddedUsers, diff.RemovedUsers + if !step.active { + touched, untouched = diff.RemovedUsers, diff.AddedUsers + } + if len(touched) != 1 || len(untouched) != 0 || touched[0].Email != "owner" || touched[0].User["publicKey"] != phone { + t.Fatalf("%s: added=%+v removed=%+v, want one op on the phone's peer only", step.name, diff.AddedUsers, diff.RemovedUsers) + } + if step.active && touched[0].User["keepAlive"] != "25" { + t.Fatalf("%s: device peer lost the client's keepalive: %+v", step.name, touched[0].User) } if !applyXrayHotDiff(api, diff) { t.Fatalf("%s: peer update failed", step.name) diff --git a/internal/web/service/xray.go b/internal/web/service/xray.go index 779d66cfd..7327679e3 100644 --- a/internal/web/service/xray.go +++ b/internal/web/service/xray.go @@ -1708,7 +1708,9 @@ func applyXrayHotDiff(hotAPI *xray.XrayAPI, diff *xray.HotDiff) bool { // the additions that follow. for _, u := range diff.RemovedUsers { var err error - if u.Protocol == string(model.WireGuard) { + if key, _ := u.User["publicKey"].(string); u.Protocol == string(model.WireGuard) && key != "" { + err = hotAPI.RemoveWireguardPeer(u.Tag, key) + } else if u.Protocol == string(model.WireGuard) { err = hotAPI.RemoveWireguardUsers(u.Tag, u.Email) } else { err = hotAPI.RemoveUser(u.Tag, u.Email) diff --git a/internal/xray/api.go b/internal/xray/api.go index ba56492f2..99d2d9211 100644 --- a/internal/xray/api.go +++ b/internal/xray/api.go @@ -1025,6 +1025,52 @@ func (x *XrayAPI) RemoveWireguardUsers(inboundTag, email string) error { return nil } +// wireguardRemovalEmail labels the one peer about to go: the core removes by email +// only, and all of a client's devices share theirs. +const wireguardRemovalEmail = "3x-ui-wireguard-peer-removal" + +// RemoveWireguardPeer removes one peer by public key and leaves every other peer and +// its session alone: it relabels the peer in place, then removes that label. +func (x *XrayAPI) RemoveWireguardPeer(inboundTag, publicKey string) error { + if x.HandlerServiceClient == nil { + return common.NewError("xray HandlerServiceClient is not initialized") + } + wanted, err := wgutil.KeyToHex(publicKey) + if err != nil || wanted == "" { + return fmt.Errorf("wireguard publicKey: %w", err) + } + ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout) + defer cancel() + response, err := (*x.HandlerServiceClient).GetInboundUsers(ctx, &command.GetInboundUserRequest{Tag: inboundTag}) + if err != nil { + return fmt.Errorf("list wireguard peers: %w", err) + } + for _, user := range response.GetUsers() { + account, err := user.GetAccount().GetInstance() + if err != nil { + continue + } + peer, ok := account.(*wireguard.PeerConfig) + if !ok || !strings.EqualFold(peer.GetPublicKey(), wanted) { + continue + } + if user.GetEmail() != wireguardRemovalEmail { + _, err = (*x.HandlerServiceClient).AlterInbound(ctx, &command.AlterInboundRequest{ + Tag: inboundTag, + Operation: serial.ToTypedMessage(&command.AddUserOperation{ + User: &protocol.User{Email: wireguardRemovalEmail, Account: user.GetAccount()}, + }), + }) + if err != nil { + return fmt.Errorf("relabel wireguard peer: %w", err) + } + } + break + } + // Also clears a label an interrupted earlier removal left behind. + return x.RemoveWireguardUsers(inboundTag, wireguardRemovalEmail) +} + // RemoveUser removes a user from an inbound in the Xray core by email. func (x *XrayAPI) RemoveUser(inboundTag, email string) error { if x.HandlerServiceClient == nil { diff --git a/internal/xray/api_users_e2e_test.go b/internal/xray/api_users_e2e_test.go index a0881daad..25bf25928 100644 --- a/internal/xray/api_users_e2e_test.go +++ b/internal/xray/api_users_e2e_test.go @@ -1,6 +1,7 @@ package xray import ( + "context" "encoding/base64" "encoding/json" "fmt" @@ -12,8 +13,14 @@ import ( "os" "os/exec" "path/filepath" + "slices" "testing" "time" + + "github.com/xtls/xray-core/app/proxyman/command" + wireguard "github.com/xtls/xray-core/proxy/wireguard" + + wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard" ) // e2eCore is a real xray-core process plus a connected panel API client. @@ -455,3 +462,144 @@ func TestXrayAPI_E2E_TestRoutePortRange(t *testing.T) { t.Fatalf("TestRoute rejected the valid port 65535: %v", err) } } + +func e2eInboundEmails(t *testing.T, c *e2eCore, tag string) []string { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout) + defer cancel() + resp, err := (*c.api.HandlerServiceClient).GetInboundUsers(ctx, &command.GetInboundUserRequest{Tag: tag}) + if err != nil { + t.Fatalf("list users of %s: %v", tag, err) + } + emails := make([]string, 0, len(resp.GetUsers())) + for _, u := range resp.GetUsers() { + emails = append(emails, u.GetEmail()) + } + slices.Sort(emails) + return emails +} + +// A client's WireGuard devices are peers sharing its email. The core must keep each +// one, and removing the client must drop all of them and nobody else's. +func TestXrayAPI_E2E_WireguardDevicesShareAnEmail(t *testing.T) { + serverKey, _, err := wgutil.GenerateWireguardKeypair() + if err != nil { + t.Fatal(err) + } + _, otherPub, err := wgutil.GenerateWireguardKeypair() + if err != nil { + t.Fatal(err) + } + c := startE2ECore(t, []any{map[string]any{ + "listen": "127.0.0.1", "port": freePort(t), "protocol": "wireguard", "tag": "wg-in", + "settings": map[string]any{ + "secretKey": serverKey, "mtu": 1420, + "peers": []any{map[string]any{"publicKey": otherPub, "allowedIPs": []string{"10.0.0.2/32"}, "email": "other"}}, + }, + }}) + + devices := make([]map[string]any, 3) + for i := range devices { + _, pub, err := wgutil.GenerateWireguardKeypair() + if err != nil { + t.Fatal(err) + } + devices[i] = map[string]any{ + "email": "multi", "publicKey": pub, "keepAlive": "25", + "allowedIPs": []string{fmt.Sprintf("10.0.0.%d/32", 10+i)}, + } + if err := c.api.AddUser("wireguard", "wg-in", devices[i]); err != nil || !c.alive() { + t.Fatalf("add device %d: err=%v alive=%v", i+1, err, c.alive()) + } + } + if got, want := e2eInboundEmails(t, c, "wg-in"), []string{"multi", "multi", "multi", "other"}; !slices.Equal(got, want) { + t.Fatalf("peers after adding three devices = %v, want %v", got, want) + } + + if err := c.api.RemoveWireguardUsers("wg-in", "multi"); err != nil || !c.alive() { + t.Fatalf("remove the client's peers: err=%v alive=%v", err, c.alive()) + } + if got, want := e2eInboundEmails(t, c, "wg-in"), []string{"other"}; !slices.Equal(got, want) { + t.Fatalf("peers after removing the client = %v, want %v", got, want) + } + + // Re-enabling a device re-adds the peer it had before. + if err := c.api.AddUser("wireguard", "wg-in", devices[1]); err != nil || !c.alive() { + t.Fatalf("re-add a removed device: err=%v alive=%v", err, c.alive()) + } + if got, want := e2eInboundEmails(t, c, "wg-in"), []string{"multi", "other"}; !slices.Equal(got, want) { + t.Fatalf("peers after re-adding one device = %v, want %v", got, want) + } +} + +func e2eWireguardPeers(t *testing.T, c *e2eCore, tag string) map[string]string { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), handlerRPCTimeout) + defer cancel() + resp, err := (*c.api.HandlerServiceClient).GetInboundUsers(ctx, &command.GetInboundUserRequest{Tag: tag}) + if err != nil { + t.Fatalf("list peers of %s: %v", tag, err) + } + peers := make(map[string]string, len(resp.GetUsers())) + for _, u := range resp.GetUsers() { + account, err := u.GetAccount().GetInstance() + if err != nil { + t.Fatal(err) + } + peers[account.(*wireguard.PeerConfig).GetPublicKey()] = u.GetEmail() + } + return peers +} + +// Disabling one device must take exactly its peer out of the core. The core removes +// by email, which the client's other devices share, so the removal goes by key. +func TestXrayAPI_E2E_WireguardPeerRemovedByKey(t *testing.T) { + serverKey, _, err := wgutil.GenerateWireguardKeypair() + if err != nil { + t.Fatal(err) + } + c := startE2ECore(t, []any{map[string]any{ + "listen": "127.0.0.1", "port": freePort(t), "protocol": "wireguard", "tag": "wg-in", + "settings": map[string]any{"secretKey": serverKey, "mtu": 1420, "peers": []any{}}, + }}) + + keys := make([]string, 4) + want := make(map[string]string, len(keys)) + for i := range keys { + _, pub, err := wgutil.GenerateWireguardKeypair() + if err != nil { + t.Fatal(err) + } + keys[i] = pub + email := "multi" + if i == 3 { + email = "other" + } + user := map[string]any{"email": email, "publicKey": pub, "allowedIPs": []string{fmt.Sprintf("10.0.0.%d/32", 10+i)}} + if err := c.api.AddUser("wireguard", "wg-in", user); err != nil { + t.Fatalf("add peer %d: %v", i, err) + } + hexKey, err := wgutil.KeyToHex(pub) + if err != nil { + t.Fatal(err) + } + want[hexKey] = email + } + + if err := c.api.RemoveWireguardPeer("wg-in", keys[1]); err != nil || !c.alive() { + t.Fatalf("remove one device: err=%v alive=%v", err, c.alive()) + } + gone, _ := wgutil.KeyToHex(keys[1]) + delete(want, gone) + if got := e2eWireguardPeers(t, c, "wg-in"); !maps.Equal(got, want) { + t.Fatalf("peers after removing one device = %v, want %v", got, want) + } + + // The reconcile repeats the removal once the peer is already gone. + if err := c.api.RemoveWireguardPeer("wg-in", keys[1]); err != nil || !c.alive() { + t.Fatalf("repeat the removal: err=%v alive=%v", err, c.alive()) + } + if got := e2eWireguardPeers(t, c, "wg-in"); !maps.Equal(got, want) { + t.Fatalf("peers after repeating the removal = %v, want %v", got, want) + } +} diff --git a/internal/xray/hot-diff-wireguard.go b/internal/xray/hot-diff-wireguard.go index 3f0ff4ee6..9cf91a6d9 100644 --- a/internal/xray/hot-diff-wireguard.go +++ b/internal/xray/hot-diff-wireguard.go @@ -3,6 +3,8 @@ package xray import ( "bytes" "encoding/json" + "maps" + "slices" "github.com/mhsanaei/3x-ui/v3/internal/util/json_util" wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard" @@ -55,25 +57,25 @@ func splitWireguardPeers(raw json_util.RawMessage) (map[string]clientEntry, []by return byKey, rest, err == nil } +// diffWireguardPeers emits one op per changed peer, keyed by public key. A peer that +// stays is never removed: re-adding it would reset a tunnel nobody changed. func diffWireguardPeers(oldIb, newIb *InboundConfig, diff *HotDiff) bool { oldPeers, oldRest, oldOK := splitWireguardPeers(oldIb.Settings) newPeers, newRest, newOK := splitWireguardPeers(newIb.Settings) if !oldOK || !newOK || !bytes.Equal(oldRest, newRest) { return false } - replaced := make(map[string]bool) - for key, peer := range oldPeers { - email := peer.user["email"].(string) - if !replaced[email] && !bytes.Equal(peer.norm, newPeers[key].norm) { - diff.RemovedUsers = append(diff.RemovedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: email}) - replaced[email] = true + for _, key := range slices.Sorted(maps.Keys(oldPeers)) { + if _, kept := newPeers[key]; !kept { + peer := oldPeers[key] + diff.RemovedUsers = append(diff.RemovedUsers, UserOp{Tag: oldIb.Tag, Protocol: oldIb.Protocol, Email: peer.user["email"].(string), User: peer.user}) } } - // Xray removes by email, so restore the surviving peers of this client. - for key, peer := range newPeers { - email := peer.user["email"].(string) - if replaced[email] || !bytes.Equal(peer.norm, oldPeers[key].norm) { - diff.AddedUsers = append(diff.AddedUsers, UserOp{Tag: newIb.Tag, Protocol: newIb.Protocol, Email: email, User: peer.user}) + // The core updates a peer it already knows in place, so a changed peer is only added. + for _, key := range slices.Sorted(maps.Keys(newPeers)) { + peer := newPeers[key] + if !bytes.Equal(peer.norm, oldPeers[key].norm) { + diff.AddedUsers = append(diff.AddedUsers, UserOp{Tag: newIb.Tag, Protocol: newIb.Protocol, Email: peer.user["email"].(string), User: peer.user}) } } return true diff --git a/internal/xray/hot_diff.go b/internal/xray/hot_diff.go index ce2184767..0e6ddcbdc 100644 --- a/internal/xray/hot_diff.go +++ b/internal/xray/hot_diff.go @@ -33,7 +33,8 @@ type InboundReplacement struct { Next *InboundConfig } -// UserOp is a per-user AlterInbound operation; User is nil for removals. +// UserOp is a per-user AlterInbound operation; User is nil for removals, except a +// WireGuard peer's, which is removed by its public key. type UserOp struct { Tag string Protocol string @@ -55,6 +56,10 @@ func (d *HotDiff) DropsUsers() bool { readded[u.Tag+"\x00"+u.Email] = struct{}{} } for _, u := range d.RemovedUsers { + // A WireGuard session ends with its peer; nothing is left running to drop. + if u.Protocol == "wireguard" { + continue + } if _, ok := readded[u.Tag+"\x00"+u.Email]; !ok { return true } diff --git a/internal/xray/hot_diff_drops_users_test.go b/internal/xray/hot_diff_drops_users_test.go index 283421853..a39b2cf03 100644 --- a/internal/xray/hot_diff_drops_users_test.go +++ b/internal/xray/hot_diff_drops_users_test.go @@ -111,3 +111,27 @@ func TestHotDiffDropsUsers(t *testing.T) { }) } } + +// Removing a WireGuard peer ends its session in the core, so a dropped device or client +// must not ask for the restart that strands other protocols' live connections need. +func TestHotDiffWireguardPeerRemovalDropsNoLiveSession(t *testing.T) { + const kept = `{"publicKey":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=","allowedIPs":["10.0.0.2/32"],"email":"owner"}` + const gone = `{"publicKey":"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=","allowedIPs":["10.0.0.3/32"],"email":"owner"}` + withPeers := func(peers string) *Config { + cfg := makeHotConfig() + ib := &cfg.InboundConfigs[1] + ib.Protocol = "wireguard" + ib.Settings = json_util.RawMessage(`{"secretKey":"s","peers":[` + peers + `]}`) + return cfg + } + diff, ok := ComputeHotDiff(withPeers(kept+","+gone), withPeers(kept)) + if !ok { + t.Fatal("a removed peer must stay API-applicable") + } + if len(diff.RemovedUsers) != 1 || diff.RemovedUsers[0].User["publicKey"] != "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=" || len(diff.AddedUsers) != 0 { + t.Fatalf("removed=%+v added=%+v, want the one removed peer and nothing re-added", diff.RemovedUsers, diff.AddedUsers) + } + if diff.DropsUsers() { + t.Fatal("DropsUsers = true for a removed WireGuard peer: the core would be restarted for nothing") + } +}