diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index 80dba5f38..db89e3d36 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -1649,9 +1649,10 @@ func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []strin successEmails = append(successEmails, email) } + var trafficErr error if len(successEmails) > 0 { now := time.Now().UnixMilli() - if err := runSerializedTx(func(tx *gorm.DB) error { + trafficErr = runSerializedTx(func(tx *gorm.DB) error { for _, batch := range chunkStrings(successEmails, sqlInChunk) { if e := tx.Model(xray.ClientTraffic{}).Where("email IN ?", batch).Update("enable", enable).Error; e != nil { return e @@ -1662,10 +1663,18 @@ func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []strin } } return nil - }); err != nil { - return result, needRestart, err + }) + } + // Sidecars serve by the traffic rows, so push them only after the rows flip; + // a push before it left a bulk-enabled client off until the reconcile job. + for i, ibRes := range enableResults { + if enablePanics[i] == nil && ibRes.sidecar != "" { + applyBulkSidecar(inboundSvc, enableIds[i], ibRes.sidecar) } } + if trafficErr != nil { + return result, needRestart, trafficErr + } result.Changed = len(successEmails) for email, reason := range skippedReasons { @@ -1677,6 +1686,19 @@ func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []strin type bulkSetEnableInboundResult struct { perEmailSkipped map[string]string needRestart bool + sidecar model.Protocol // local sidecar inbound to push after the traffic rows +} + +func applyBulkSidecar(inboundSvc *InboundService, inboundId int, protocol model.Protocol) { + defer lockInbound(inboundId).Unlock() + switch protocol { + case model.MTProto: + inboundSvc.applyLocalMtproto(inboundId) + case model.AmneziaWG: + inboundSvc.applyLocalAmneziaWG(inboundId) + case model.TUIC: + inboundSvc.applyLocalTuic(inboundId) + } } func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, inboundId int, emails []string, enable bool) bulkSetEnableInboundResult { @@ -1807,19 +1829,12 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, if oldInbound.NodeID == nil { if !push { res.needRestart = true + } else if servedOutsideXray(oldInbound.Protocol) { + res.sidecar = oldInbound.Protocol } else { for _, ch := range changed { if enable { - err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{ - "email": ch.client.Email, - "id": ch.client.ID, - "security": ch.client.Security, - "flow": ch.client.Flow, - "auth": ch.client.Auth, - "password": ch.client.Password, - "cipher": cipher, - "reverse": ch.client.Reverse, - }) + err1 := rt.AddUser(context.Background(), oldInbound, coreUserFromClient(&ch.client, cipher)) if err1 != nil { logger.Debug("Error in adding client on", rt.Name(), ":", err1) res.needRestart = true diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 89f9a5614..08ff8ba56 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -46,6 +46,18 @@ func validateClientEmail(email string) error { return nil } +func validateClientsNames(clients []model.Client) error { + for _, client := range clients { + if err := validateClientEmail(client.Email); err != nil { + return err + } + if err := validateClientSubID(client.SubID); err != nil { + return err + } + } + return nil +} + func validateClientSubID(subID string) error { if hasForbiddenClientChar(subID) { return common.NewError("client subId contains an invalid character:", subID) diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index f0c9c1882..28be1a1d0 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -691,20 +691,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model if oldInbound.Protocol == "shadowsocks" { cipher, _ = oldSettings["method"].(string) } - err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{ - "email": client.Email, - "id": client.ID, - "auth": client.Auth, - "security": client.Security, - "flow": client.Flow, - "password": client.Password, - "cipher": cipher, - "publicKey": client.PublicKey, - "allowedIPs": client.AllowedIPs, - "preSharedKey": client.PreSharedKey, - "keepAlive": keepAliveStr(client.KeepAliveSeconds()), - "reverse": client.Reverse, - }) + err1 := rt.AddUser(context.Background(), oldInbound, coreUserFromClient(&client, cipher)) if err1 == nil { logger.Debug("Client added on", rt.Name(), ":", client.Email) } else { @@ -1154,20 +1141,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if oldInbound.Protocol == "shadowsocks" { cipher, _ = oldSettings["method"].(string) } - err1 := rt.AddUser(context.Background(), oldInbound, map[string]any{ - "email": clients[0].Email, - "id": clients[0].ID, - "security": clients[0].Security, - "flow": clients[0].Flow, - "auth": clients[0].Auth, - "password": clients[0].Password, - "cipher": cipher, - "publicKey": clients[0].PublicKey, - "allowedIPs": clients[0].AllowedIPs, - "preSharedKey": clients[0].PreSharedKey, - "keepAlive": keepAliveStr(clients[0].KeepAliveSeconds()), - "reverse": clients[0].Reverse, - }) + err1 := rt.AddUser(context.Background(), oldInbound, coreUserFromClient(&clients[0], cipher)) if err1 == nil { logger.Debug("Client edited on", rt.Name(), ":", clients[0].Email) } else { diff --git a/internal/web/service/client_reset_core_readd_test.go b/internal/web/service/client_reset_core_readd_test.go new file mode 100644 index 000000000..7026345d5 --- /dev/null +++ b/internal/web/service/client_reset_core_readd_test.go @@ -0,0 +1,262 @@ +package service + +import ( + "context" + "encoding/json" + "sync" + "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" + + "github.com/xtls/xray-core/app/proxyman/command" + "google.golang.org/grpc" +) + +// acceptingHandler is a core HandlerService that takes every user operation. +type acceptingHandler struct{ command.HandlerServiceClient } + +func (acceptingHandler) AlterInbound(context.Context, *command.AlterInboundRequest, ...grpc.CallOption) (*command.AlterInboundResponse, error) { + return &command.AlterInboundResponse{}, nil +} + +// coreReAddProbe behaves like runtime.Local: Xray protocols go through the real +// account builder, sidecar protocols only change through UpdateInbound. +type coreReAddProbe struct { + fakeNodeRuntime + mu sync.Mutex + addUsers []map[string]any + addErrs []error + updated []model.Inbound +} + +func (p *coreReAddProbe) AddUser(_ context.Context, ib *model.Inbound, user map[string]any) error { + if servedOutsideXray(ib.Protocol) { + return nil + } + var core command.HandlerServiceClient = acceptingHandler{} + err := (&xray.XrayAPI{HandlerServiceClient: &core}).AddUser(string(ib.Protocol), ib.Tag, user) + p.mu.Lock() + defer p.mu.Unlock() + p.addUsers = append(p.addUsers, user) + p.addErrs = append(p.addErrs, err) + return err +} + +func (p *coreReAddProbe) UpdateInbound(_ context.Context, _, newIb *model.Inbound) error { + p.mu.Lock() + defer p.mu.Unlock() + p.updated = append(p.updated, *newIb) + return nil +} + +// seedQuotaDisabledClient leaves c the way the quota job does: off in the +// inbound JSON, in its traffic row and in its record, with the quota used up. +func seedQuotaDisabledClient(t *testing.T, port int, proto model.Protocol, c model.Client) (*model.Inbound, *coreReAddProbe) { + t.Helper() + setupBulkDB(t) + probe := &coreReAddProbe{} + useTestRuntimeManager(t).SetLocalRuntimeOverride(probe) + svc := &ClientService{} + c.Enable = false + c.TotalGB = 1000 + ib := mkInbound(t, port, proto, clientsSettings(t, []model.Client{c})) + if err := svc.SyncInbound(nil, ib.Id, []model.Client{c}); err != nil { + t.Fatalf("SyncInbound: %v", err) + } + mkTraffic(t, ib.Id, c.Email, 600, 500, 1000, 0, false) + forceRecordDisabled(t, svc, c.Email) + return ib, probe +} + +const resetProbePeerKey = "AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=" + +// The reset re-added a WireGuard peer without publicKey/allowedIPs, the core +// rejected it, and the reset restarted Xray for every connected user. +func TestResetTrafficOfQuotaDisabledWireGuardPeerNeedsNoRestart(t *testing.T) { + const email = "wg-reset@x" + ib, probe := seedQuotaDisabledClient(t, 51840, model.WireGuard, model.Client{ + Email: email, SubID: "sub-" + email, PublicKey: resetProbePeerKey, + AllowedIPs: []string{"10.0.0.7/32"}, KeepAlive: model.KeepAlivePtr(25), + }) + + needRestart, err := (&ClientService{}).ResetTrafficByEmail(&InboundService{}, email) + if err != nil { + t.Fatalf("ResetTrafficByEmail: %v", err) + } + probe.mu.Lock() + users, errs := probe.addUsers, probe.addErrs + probe.mu.Unlock() + if len(users) != 1 { + t.Fatalf("core re-adds = %d, want exactly one for %s", len(users), email) + } + if errs[0] != nil { + t.Fatalf("the core rejected the re-added peer: %v", errs[0]) + } + if got, _ := users[0]["publicKey"].(string); got != resetProbePeerKey { + t.Fatalf("re-added peer publicKey = %q, want %q", got, resetProbePeerKey) + } + if needRestart { + t.Fatal("resetting a quota-disabled WireGuard peer asked for an Xray restart") + } + assertEnableEverywhere(t, &ClientService{}, &InboundService{}, ib.Id, email, true) +} + +// An AmneziaWG peer reaches the device only through the inbound reconcile; +// the reset's AddUser is a no-op there and left the peer off the device. +func TestResetTrafficOfQuotaDisabledAmneziaWGPeerReachesTheDevice(t *testing.T) { + const email = "awg-reset@x" + ib, probe := seedQuotaDisabledClient(t, 51841, model.AmneziaWG, model.Client{ + Email: email, SubID: "sub-" + email, PublicKey: resetProbePeerKey, + AllowedIPs: []string{"10.8.1.7/32"}, + }) + + needRestart, err := (&ClientService{}).ResetTrafficByEmail(&InboundService{}, email) + if err != nil { + t.Fatalf("ResetTrafficByEmail: %v", err) + } + if needRestart { + t.Fatal("resetting a quota-disabled AmneziaWG peer asked for an Xray restart") + } + probe.mu.Lock() + updated := probe.updated + probe.mu.Unlock() + for _, pushed := range updated { + if pushed.Id == ib.Id && settingsClientEnabled(t, pushed.Settings, email) { + return + } + } + t.Fatalf("no inbound reconcile carried %s back enabled; pushed %d updates", email, len(updated)) +} + +func settingsClientEnabled(t *testing.T, settings, email string) bool { + t.Helper() + var parsed struct { + Clients []model.Client `json:"clients"` + } + if err := json.Unmarshal([]byte(settings), &parsed); err != nil { + t.Fatalf("parse pushed settings: %v", err) + } + for _, c := range parsed.Clients { + if c.Email == email { + return c.Enable + } + } + return false +} + +// The stored JSON keeps keepAlive as a number, which the core's account builder +// rejects; every auto-renew of such a WireGuard peer restarted Xray. +func TestAutoRenewOfWireGuardPeerWithKeepAliveNeedsNoRestart(t *testing.T) { + const email = "wg-renew@x" + ib, probe := seedQuotaDisabledClient(t, 51842, model.WireGuard, model.Client{ + Email: email, SubID: "sub-" + email, PublicKey: resetProbePeerKey, + AllowedIPs: []string{"10.0.0.8/32"}, KeepAlive: model.KeepAlivePtr(25), + Reset: 30, ExpiryTime: time.Now().Add(-48 * time.Hour).UnixMilli(), + }) + db := database.GetDB() + if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", email). + Updates(map[string]any{"reset": 30, "expiry_time": time.Now().Add(-48 * time.Hour).UnixMilli()}).Error; err != nil { + t.Fatalf("make the traffic row renewable: %v", err) + } + svc := &InboundService{} + batch := newTrafficMutationBatch() + if _, count, err := svc.autoRenewClients(db, batch); err != nil || count != 1 { + t.Fatalf("autoRenewClients: renewed %d, err %v; want 1 renewal", count, err) + } + + needRestart := svc.applyTrafficMutationBatch(batch) + probe.mu.Lock() + errs := probe.addErrs + probe.mu.Unlock() + if len(errs) != 1 || errs[0] != nil { + t.Fatalf("core re-adds of %s on inbound %d: %v, want one accepted add", email, ib.Id, errs) + } + if needRestart { + t.Fatal("auto-renewing a WireGuard peer asked for an Xray restart") + } +} + +// Bulk enable built its own account map without the WireGuard keys, so +// enabling a peer restarted Xray for every user. +func TestBulkEnableOfWireGuardPeerNeedsNoRestart(t *testing.T) { + const email = "wg-bulk@x" + _, probe := seedQuotaDisabledClient(t, 51843, model.WireGuard, model.Client{ + Email: email, SubID: "sub-" + email, PublicKey: resetProbePeerKey, + AllowedIPs: []string{"10.0.0.9/32"}, + }) + liftQuota(t, email) + + _, needRestart, err := (&ClientService{}).BulkSetEnable(&InboundService{}, []string{email}, true) + if err != nil { + t.Fatalf("BulkSetEnable: %v", err) + } + probe.mu.Lock() + errs := probe.addErrs + probe.mu.Unlock() + if len(errs) != 1 || errs[0] != nil { + t.Fatalf("core adds of %s: %v, want one accepted add", email, errs) + } + if needRestart { + t.Fatal("bulk-enabling a WireGuard peer asked for an Xray restart") + } +} + +// Sidecar AddUser/RemoveUser are no-ops, so a bulk toggle must reach the device +// through the inbound reconcile, in both directions, from a hand-disabled client. +func TestBulkSetEnableOfSidecarClientReachesTheDevice(t *testing.T) { + cases := []struct { + proto model.Protocol + port int + client model.Client + }{ + {model.AmneziaWG, 51844, model.Client{PublicKey: resetProbePeerKey, AllowedIPs: []string{"10.8.1.9/32"}}}, + {model.MTProto, 51845, model.Client{Secret: "ee1234567890abcdef1234567890abcd7777772e636c6f7564666c6172652e636f6d"}}, + {model.TUIC, 51846, model.Client{ID: "11111111-1111-1111-1111-111111111146", Password: "tuic-pass"}}, + } + for _, tc := range cases { + t.Run(string(tc.proto), func(t *testing.T) { + email := string(tc.proto) + "-bulk@x" + c := tc.client + c.Email, c.SubID, c.Enable, c.TotalGB = email, "sub-"+email, true, 1000 + setupBulkDB(t) + probe := &coreReAddProbe{} + useTestRuntimeManager(t).SetLocalRuntimeOverride(probe) + ib := mkInbound(t, tc.port, tc.proto, clientsSettings(t, []model.Client{c})) + if err := (&ClientService{}).SyncInbound(nil, ib.Id, []model.Client{c}); err != nil { + t.Fatalf("SyncInbound: %v", err) + } + mkTraffic(t, ib.Id, email, 0, 0, 1000, 0, true) + for _, enable := range []bool{false, true} { + if _, _, err := (&ClientService{}).BulkSetEnable(&InboundService{}, []string{email}, enable); err != nil { + t.Fatalf("BulkSetEnable(%v): %v", enable, err) + } + probe.mu.Lock() + updated := probe.updated + probe.updated = nil + probe.mu.Unlock() + reached := false + for _, pushed := range updated { + if pushed.Id == ib.Id && settingsClientEnabled(t, pushed.Settings, email) == enable { + reached = true + } + } + if !reached { + t.Fatalf("bulk enable=%v never reached the %s sidecar; pushed %d updates", enable, tc.proto, len(updated)) + } + } + }) + } +} + +// liftQuota leaves the client switched off by hand only, the state bulk enable +// turns back on; a depleted one stays off the runtime whatever its flag says. +func liftQuota(t *testing.T, email string) { + t.Helper() + if err := database.GetDB().Model(&xray.ClientTraffic{}).Where("email = ?", email). + Updates(map[string]any{"enable": true, "up": 0, "down": 0}).Error; err != nil { + t.Fatalf("lift quota of %s: %v", email, err) + } +} diff --git a/internal/web/service/inbound.go b/internal/web/service/inbound.go index 3089c40db..c038e3097 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -1375,6 +1375,12 @@ func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound, boo if err := validateClientsKeepAlive(inbound.Protocol, clients); err != nil { return inbound, false, err } + // The names the client API refuses; a master's push may carry a legacy one. + if !s.FromNodeSync { + if err := validateClientsNames(clients); err != nil { + return inbound, false, err + } + } for _, traffic := range inbound.ClientStats { if err := validateClientRenewal(model.Client{Reset: traffic.Reset, ResetDay: traffic.ResetDay, ResetWeekday: traffic.ResetWeekday}); err != nil { return inbound, false, err diff --git a/internal/web/service/inbound_add_client_email_test.go b/internal/web/service/inbound_add_client_email_test.go new file mode 100644 index 000000000..e4faeee65 --- /dev/null +++ b/internal/web/service/inbound_add_client_email_test.go @@ -0,0 +1,42 @@ +package service + +import ( + "testing" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +// /clients/add refuses these emails and subIds, while /inbounds/add still +// created exactly those records from the inbound's settings. +func TestAddInboundRefusesClientNamesTheClientAPIRefuses(t *testing.T) { + for i, tc := range []struct{ email, subID, want string }{ + {".", "", "client email must not be '.' or '..'\n"}, + {"..", "", "client email must not be '.' or '..'\n"}, + {"a/b", "", "client email contains an invalid character: a/b\n"}, + {"ok@x", "sub one", "client subId contains an invalid character: sub one\n"}, + } { + t.Run(tc.email+"|"+tc.subID, func(t *testing.T) { + setupConflictDB(t) + ib := makeInboundWithSubSortIndex("in-reserved-email", 7101+i, 0) + ib.Settings = clientsSettings(t, []model.Client{{Email: tc.email, SubID: tc.subID, ID: "11111111-1111-1111-1111-111111111111", Enable: true}}) + _, _, err := (&InboundService{}).AddInbound(ib) + if err == nil || err.Error() != tc.want { + t.Fatalf("AddInbound with client %q subId %q: err = %v, want %q", tc.email, tc.subID, err, tc.want) + } + }) + } +} + +// A node takes what its master already holds, legacy names included; refusing +// the push would only leave the node out of sync. +func TestAddInboundFromMasterPushKeepsALegacyDotName(t *testing.T) { + setupConflictDB(t) + ib := makeInboundWithSubSortIndex("in-legacy-dot", 7111, 0) + ib.Settings = clientsSettings(t, []model.Client{{Email: ".", ID: "11111111-1111-1111-1111-111111111111", Enable: true}}) + if _, _, err := (&InboundService{FromNodeSync: true}).AddInbound(ib); err != nil { + t.Fatalf("master push with a legacy '.' client: %v", err) + } + if rec := lookupClientRecord(t, "."); rec.Email != "." { + t.Fatalf("stored record email = %q, want the pushed '.'", rec.Email) + } +} diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go index 7de298b98..0eaad0110 100644 --- a/internal/web/service/inbound_traffic.go +++ b/internal/web/service/inbound_traffic.go @@ -360,6 +360,25 @@ func (s *InboundService) adjustTraffics(tx *gorm.DB, dbClientTraffics []*xray.Cl return dbClientTraffics, newExpiryByEmail, nil } +// coreUserFromClient is the account map the runtime AddUser expects; WireGuard +// peers fail it without publicKey/allowedIPs, and a failed add restarts Xray. +func coreUserFromClient(c *model.Client, cipher string) map[string]any { + return map[string]any{ + "email": c.Email, + "id": c.ID, + "auth": c.Auth, + "security": c.Security, + "flow": c.Flow, + "password": c.Password, + "cipher": cipher, + "publicKey": c.PublicKey, + "allowedIPs": c.AllowedIPs, + "preSharedKey": c.PreSharedKey, + "keepAlive": keepAliveStr(c.KeepAliveSeconds()), + "reverse": c.Reverse, + } +} + // 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 @@ -374,6 +393,10 @@ func apiUserFromClient(client map[string]any, cipher string) map[string]any { if cipher != "" { user["cipher"] = cipher } + // Stored JSON holds keepAlive as a number; the core's builder takes a string. + if seconds, ok := user["keepAlive"].(float64); ok { + user["keepAlive"] = keepAliveStr(int(seconds)) + } return user } @@ -763,20 +786,10 @@ func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (b } cipher, _ = oldSettings["method"].(string) } - clientMap := map[string]any{ - "email": entry.Email, - "id": entry.ID, - "auth": entry.Auth, - "security": entry.Security, - "flow": entry.Flow, - "password": entry.Password, - "cipher": cipher, - "reverse": entry.Reverse, - } if inbound.NodeID != nil { reenableNodeID = inbound.NodeID } else { - reenablePlan = &trafficLocalApplyPlan{action: trafficAddUser, inbound: *inbound, client: clientMap} + reenablePlan = &trafficLocalApplyPlan{action: trafficAddUser, inbound: *inbound, client: coreUserFromClient(entry, cipher)} } } @@ -835,15 +848,9 @@ func (s *InboundService) resetClientTrafficLocked(id int, clientEmail string) (b } if reenablePlan != nil { - rt, err := s.runtimeFor(&reenablePlan.inbound) - if err != nil { - needRestart = true - } else if err := rt.AddUser(context.Background(), &reenablePlan.inbound, reenablePlan.client); err != nil { - logger.Debug("Error in enabling client on", rt.Name(), ":", err) - needRestart = true - } else { - logger.Debug("Client enabled on", rt.Name(), "due to reset traffic:", clientEmail) - } + // The batch routes MTProto/AmneziaWG/TUIC to their own reconcilers; their + // AddUser is a no-op, so a quota-disabled peer would never come back. + needRestart = s.applyTrafficMutationBatch(&trafficMutationBatch{localPlans: []trafficLocalApplyPlan{*reenablePlan}}) } return needRestart, inbound.NodeID, nil