mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
fix(groups): page client dialogs and submit server-resolved scopes
Keep group client tables and bulk requests bounded with paged queries, frozen selections, and a streamed subscription export. Reuse existing bulk mutations and preserve the explicit-email contracts.
This commit is contained in:
@@ -0,0 +1,292 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/testpg"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
||||
)
|
||||
|
||||
const groupAPI = "/panel/api/clients"
|
||||
|
||||
func groupTestRouter(t *testing.T) *gin.Engine {
|
||||
t.Helper()
|
||||
cleanup, err := testpg.IsolatePackage("group_client_http")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(cleanup)
|
||||
dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
|
||||
router := gin.New()
|
||||
routes := router.Group(groupAPI)
|
||||
NewGroupController(routes)
|
||||
NewClientController(routes)
|
||||
return router
|
||||
}
|
||||
|
||||
func groupAPIRequest(router *gin.Engine, method, route, body string) *httptest.ResponseRecorder {
|
||||
out := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(method, groupAPI+route, strings.NewReader(body))
|
||||
if method == http.MethodPost {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
router.ServeHTTP(out, req)
|
||||
return out
|
||||
}
|
||||
|
||||
func groupPage(t *testing.T, router *gin.Engine, query string) service.GroupClientPage {
|
||||
t.Helper()
|
||||
out := groupAPIRequest(router, http.MethodGet, "/groups/clientPage?"+query, "")
|
||||
var result struct {
|
||||
Success bool
|
||||
Obj service.GroupClientPage
|
||||
}
|
||||
if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success {
|
||||
t.Fatalf("group page %q returned %s (%v)", query, out.Body, err)
|
||||
}
|
||||
return result.Obj
|
||||
}
|
||||
|
||||
func groupMutation(t *testing.T, router *gin.Engine, route string, body any, success bool, field string, want int) {
|
||||
t.Helper()
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := groupAPIRequest(router, http.MethodPost, route, string(payload))
|
||||
var result struct {
|
||||
Success bool
|
||||
Obj map[string]json.RawMessage
|
||||
}
|
||||
if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || result.Success != success {
|
||||
t.Fatalf("%s returned %s (wanted success=%t): %v", route, out.Body, success, err)
|
||||
}
|
||||
if success {
|
||||
var got int
|
||||
if err := json.Unmarshal(result.Obj[field], &got); err != nil || got != want {
|
||||
t.Fatalf("%s returned %s, want %s=%d", route, out.Body, field, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func createTestGroupClients(t *testing.T, size, memberCount int) []model.ClientRecord {
|
||||
t.Helper()
|
||||
db := database.GetDB()
|
||||
if err := db.Create(&model.ClientGroup{Name: "staff"}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows := make([]model.ClientRecord, size)
|
||||
for i := range rows {
|
||||
rows[i] = model.ClientRecord{Email: fmt.Sprintf("client-%06d", i), SubID: fmt.Sprintf("s-%06d", i), Comment: "literal_%", Group: "previous", TotalGB: 1024, Enable: true}
|
||||
if i < memberCount {
|
||||
rows[i].Group = "staff"
|
||||
}
|
||||
}
|
||||
if err := db.CreateInBatches(rows, 300).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
func TestGroupClientPageAndFrozenWriteHTTP(t *testing.T) {
|
||||
router := groupTestRouter(t)
|
||||
rows := createTestGroupClients(t, 230, 110)
|
||||
page := groupPage(t, router, "group=staff&mode=add&page=2")
|
||||
if page.Total != 120 || len(page.Items) != 20 || page.Items[0].ID != rows[210].Id {
|
||||
t.Fatalf("second add page = %d rows out of %d, expected clients 210–229", len(page.Items), page.Total)
|
||||
}
|
||||
search := url.QueryEscape("literal_%")
|
||||
frozen := groupPage(t, router, "group=STAFF&mode=add&freeze=true&search="+search)
|
||||
if frozen.Total != 120 || len(frozen.Items) != 0 || frozen.MaxID != rows[229].Id {
|
||||
t.Fatalf("frozen add scope = %+v", frozen)
|
||||
}
|
||||
db := database.GetDB()
|
||||
newer := model.ClientRecord{Email: "newer", Comment: "literal_%", Group: "previous"}
|
||||
if err := db.Create(&newer).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
alternate := model.ClientRecord{Email: "wildcard-would-match", Comment: "literalXY", Group: "previous"}
|
||||
if err := db.Create(&alternate).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
last := groupPage(t, router, fmt.Sprintf("group=staff&mode=add&page=2&maxId=%d&scopeSearch=%s", frozen.MaxID, search))
|
||||
if len(last.Items) != 22 || last.Items[20].InScope || last.Items[21].InScope || !last.Items[19].InScope {
|
||||
t.Fatalf("new and out-of-filter clients were included in the frozen scope: %+v", last.Items)
|
||||
}
|
||||
selection := service.GroupClientSelection{
|
||||
Mode: "allMatching", ScopeToken: frozen.ScopeToken,
|
||||
Search: "literal_%", ExcludedClientIDs: []int{rows[110].Id},
|
||||
}
|
||||
body := map[string]any{"group": "staff", "selection": selection}
|
||||
if err := db.Model(&rows[111]).UpdateColumn("group_name", "staff").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
groupMutation(t, router, "/groups/bulkAdd", body, false, "", 0)
|
||||
staff := groupPage(t, router, "group=staff&mode=remove")
|
||||
if staff.Total != 111 {
|
||||
t.Fatalf("stale selection changed client groups: staff=%d", staff.Total)
|
||||
}
|
||||
if err := db.Model(&rows[111]).UpdateColumn("group_name", "previous").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
groupMutation(t, router, "/groups/bulkAdd", body, true, "affected", 119)
|
||||
groupMutation(t, router, "/groups/bulkAdd", body, false, "", 0)
|
||||
for _, id := range []int{rows[110].Id, newer.Id, alternate.Id} {
|
||||
var row model.ClientRecord
|
||||
if err := db.First(&row, id).Error; err != nil || row.Group != "previous" {
|
||||
t.Fatalf("client %d left its group: %q, err=%v", id, row.Group, err)
|
||||
}
|
||||
}
|
||||
selection = service.GroupClientSelection{Mode: "explicit", ClientIDs: []int{rows[0].Id, newer.Id}}
|
||||
groupMutation(t, router, "/groups/bulkRemove", map[string]any{"group": "staff", "selection": selection}, false, "", 0)
|
||||
selection.ClientIDs = []int{rows[0].Id, rows[0].Id}
|
||||
groupMutation(t, router, "/groups/bulkRemove", map[string]any{"group": "staff", "selection": selection}, true, "affected", 1)
|
||||
if page := groupPage(t, router, "group=staff&mode=remove&page=3"); page.Total != 228 || len(page.Items) != 28 {
|
||||
t.Fatalf("remove page after mutations = %d out of %d", len(page.Items), page.Total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupBulkOperationsRespectFrozenMembersHTTP(t *testing.T) {
|
||||
router := groupTestRouter(t)
|
||||
rows := createTestGroupClients(t, 6, 2)
|
||||
freeze := groupPage(t, router, "group=staff&mode=remove&freeze=true")
|
||||
db := database.GetDB()
|
||||
if err := db.Model(&rows[0]).UpdateColumn("group_name", "previous").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
groupMutation(t, router, "/bulkDel", map[string]any{"group": "staff", "scopeToken": freeze.ScopeToken}, false, "", 0)
|
||||
|
||||
freeze = groupPage(t, router, "group=staff&mode=remove&freeze=true")
|
||||
body := map[string]any{"group": "staff", "scopeToken": freeze.ScopeToken}
|
||||
newer := model.ClientRecord{Email: "new-member", Group: "staff", TotalGB: 1024}
|
||||
if err := db.Create(&newer).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, record := range []model.ClientRecord{rows[0], rows[1], newer} {
|
||||
if err := db.Create(&xray.ClientTraffic{Email: record.Email, Total: record.TotalGB, Enable: true}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
groupMutation(t, router, "/bulkAdjust", map[string]any{
|
||||
"group": "staff", "scopeToken": freeze.ScopeToken, "addBytes": 256,
|
||||
}, true, "adjusted", 1)
|
||||
for email, want := range map[string]int64{rows[0].Email: 1024, rows[1].Email: 1280, newer.Email: 1024} {
|
||||
var row xray.ClientTraffic
|
||||
if err := db.Where("email = ?", email).First(&row).Error; err != nil || row.Total != want {
|
||||
t.Fatalf("client %s quota = %d, want %d: %v", email, row.Total, want, err)
|
||||
}
|
||||
}
|
||||
groupMutation(t, router, "/bulkDel", body, true, "deleted", 1)
|
||||
groupMutation(t, router, "/bulkDel", body, false, "", 0)
|
||||
groupMutation(t, router, "/bulkDel", map[string]any{"emails": []string{rows[0].Email}}, true, "deleted", 1)
|
||||
if page := groupPage(t, router, "group=staff&mode=remove"); page.Total != 1 || page.Items[0].ID != newer.Id {
|
||||
t.Fatalf("bulk deletion selected clients outside the frozen scope: %+v", page)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupAdjustCapsReportedSkipsWithoutChangingExplicitResponses(t *testing.T) {
|
||||
router := groupTestRouter(t)
|
||||
rows := createTestGroupClients(t, 25, 25)
|
||||
if err := database.GetDB().Model(&model.ClientRecord{}).
|
||||
Where("group_name = ?", "staff").UpdateColumn("total_gb", 0).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
emails := make([]string, len(rows))
|
||||
for i, row := range rows {
|
||||
emails[i] = row.Email
|
||||
}
|
||||
var result struct {
|
||||
Success bool
|
||||
Obj service.BulkAdjustResult
|
||||
}
|
||||
groupResponse := groupAPIRequest(router, http.MethodPost, "/bulkAdjust", `{"group":"staff","addBytes":1}`)
|
||||
if err := json.Unmarshal(groupResponse.Body.Bytes(), &result); err != nil || !result.Success ||
|
||||
result.Obj.Adjusted != 0 || len(result.Obj.Skipped) != 20 || result.Obj.SkippedCount != 25 {
|
||||
t.Fatalf("group adjust response = %s (%v)", groupResponse.Body, err)
|
||||
}
|
||||
body, err := json.Marshal(map[string]any{"emails": emails, "addBytes": 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := groupAPIRequest(router, http.MethodPost, "/bulkAdjust", string(body))
|
||||
result.Obj = service.BulkAdjustResult{}
|
||||
if err := json.Unmarshal(out.Body.Bytes(), &result); err != nil || !result.Success ||
|
||||
result.Obj.Adjusted != 0 || len(result.Obj.Skipped) != 25 || strings.Contains(out.Body.String(), "skippedCount") {
|
||||
t.Fatalf("explicit adjust response = %s (%v)", out.Body, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGroupSubscriptionExportAndPagingHTTP(t *testing.T) {
|
||||
sizes := []int{1000}
|
||||
if os.Getenv("XUI_SCALE_TEST") != "" {
|
||||
sizes = append(sizes, 10000, 50000)
|
||||
}
|
||||
for _, size := range sizes {
|
||||
t.Run(fmt.Sprint(size), func(t *testing.T) {
|
||||
testGroupSubscriptionExportAndPaging(t, size)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testGroupSubscriptionExportAndPaging(t *testing.T, size int) {
|
||||
t.Helper()
|
||||
router := groupTestRouter(t)
|
||||
rows := createTestGroupClients(t, size, min(size, 10000))
|
||||
db := database.GetDB()
|
||||
if err := db.Model(&rows[1]).UpdateColumn("sub_id", "").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for key, val := range map[string]string{
|
||||
"subEnable": "true", "subURI": "https://sub.example.test/plain/", "subJsonEnable": "true", "subJsonURI": "https://sub.example.test/json/",
|
||||
} {
|
||||
var setting model.Setting
|
||||
if err := db.Where("key = ?", key).Assign(model.Setting{Value: val}).FirstOrCreate(&setting, model.Setting{Key: key}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
total := min(size, 10000) - 1
|
||||
page := groupPage(t, router, "group=staff&mode=links")
|
||||
if os.Getenv("XUI_SCALE_TEST") != "" {
|
||||
pageResponse := groupAPIRequest(router, http.MethodGet, "/groups/clientPage?group=staff&mode=links", "")
|
||||
emailResponse := groupAPIRequest(router, http.MethodGet, "/groups/staff/emails", "")
|
||||
t.Logf("%d clients, %d links: page %d bytes, legacy emails %d bytes", size, total, pageResponse.Body.Len(), emailResponse.Body.Len())
|
||||
}
|
||||
if page.Total != int64(total) || len(page.Items) != 100 || page.Items[1].Email != rows[2].Email {
|
||||
t.Fatalf("link page returned %d rows out of %d", len(page.Items), page.Total)
|
||||
}
|
||||
if size == 50000 {
|
||||
add := groupPage(t, router, "group=staff&mode=add&page=400")
|
||||
if add.Total != 40000 || len(add.Items) != 100 || add.Items[99].Email != rows[49999].Email {
|
||||
t.Fatalf("last page of 40,000 candidates returned %d out of %d", len(add.Items), add.Total)
|
||||
}
|
||||
}
|
||||
out := groupAPIRequest(router, http.MethodGet, "/groups/subLinks/export?group=staff", "")
|
||||
lines := strings.Split(out.Body.String(), "\n")
|
||||
if out.Code != http.StatusOK || out.Header().Get("Cache-Control") != "no-store" || len(lines) != total {
|
||||
t.Fatalf("export returned HTTP %d and %d rows, want %d rows", out.Code, len(lines), total)
|
||||
}
|
||||
for index, line := range lines {
|
||||
if index > 0 {
|
||||
index++
|
||||
}
|
||||
row := rows[index]
|
||||
want := row.Email + "\thttps://sub.example.test/plain/" + row.SubID + "\thttps://sub.example.test/json/" + row.SubID
|
||||
if line != want {
|
||||
t.Fatalf("export row %d = %q, want %q", index, line, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user