mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
c483882e56
Replace the unbounded Detach Clients modal with server-paged candidate loading, debounced search and a virtualized list. Preserve explicit-ID selection and add frozen all-matching scopes with exclusions so selection remains stable across pages and searches without sending an N-sized client list from the browser. Execute large detach requests as idempotent background jobs. Revalidate source-inbound membership in bounded batches, atomically apply membership deltas, preserve ClientRecords and traffic, and queue reconciliation for remote nodes. Keep the legacy email-based bulkDetach API compatible. Add PostgreSQL/SQLite regression coverage for concurrent membership changes, stale scopes, exclusions, retries, rollback and legacy callers, plus real master/node coverage for offline-node reconciliation. Regenerate and validate the API contract and OpenAPI artifacts.
141 lines
5.2 KiB
Go
141 lines
5.2 KiB
Go
package controller
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/testpg"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web/locale"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
|
|
)
|
|
|
|
func TestScopedDetachAPIAndIdempotency(t *testing.T) {
|
|
cleanup, err := testpg.IsolatePackage("scoped_detach_api")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(cleanup)
|
|
engine, auth := newAPIAuthTestEngine(t)
|
|
clients := engine.Group("/panel/api/clients", auth.checkAPIAuth, auth.enforceTokenScope)
|
|
clients.Use(func(c *gin.Context) {
|
|
c.Set("I18n", func(_ locale.I18nType, key string, _ ...string) string { return key })
|
|
c.Next()
|
|
})
|
|
controller := &ClientController{}
|
|
clients.GET("/detachCandidates", controller.detachCandidates)
|
|
clients.POST("/detachCandidates/freeze", controller.freezeDetachCandidates)
|
|
clients.POST("/bulkDetach", controller.bulkDetach)
|
|
clients.GET("/bulkDetach/:id", controller.detachStatus)
|
|
db := database.GetDB()
|
|
for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeNodeSync} {
|
|
if err := db.Create(&model.ApiToken{Name: scope, Token: crypto.HashTokenSHA256(scope), Scope: scope, Enabled: true}).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
inbound := model.Inbound{Tag: "detach-api", Protocol: model.VLESS, Settings: `{"clients":[{"email":"detach-api@test","enable":false}]}`}
|
|
record := model.ClientRecord{Email: "detach-api@test"}
|
|
if err := db.Create(&inbound).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := db.Create(&record).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := db.Create(&model.ClientInbound{ClientId: record.Id, InboundId: inbound.Id}).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
request := func(method, path, scope string, body any) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
raw, err := json.Marshal(body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
req := httptest.NewRequest(method, "/panel/api/clients"+path, bytes.NewReader(raw))
|
|
req.Header.Set("Authorization", "Bearer "+scope)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
out := httptest.NewRecorder()
|
|
engine.ServeHTTP(out, req)
|
|
return out
|
|
}
|
|
type envelope struct {
|
|
Success bool `json:"success"`
|
|
Obj json.RawMessage `json:"obj"`
|
|
Msg string `json:"msg"`
|
|
}
|
|
admin := model.ApiScopeAdmin
|
|
candidatePath := fmt.Sprintf("/detachCandidates?inboundId=%d", inbound.Id)
|
|
if response := request(http.MethodGet, candidatePath, model.ApiScopeNodeSync, nil); response.Code != http.StatusForbidden {
|
|
t.Fatalf("node-sync got %d: %s", response.Code, response.Body)
|
|
}
|
|
read := func(out *httptest.ResponseRecorder) envelope {
|
|
t.Helper()
|
|
var res envelope
|
|
if err := json.Unmarshal(out.Body.Bytes(), &res); err != nil {
|
|
t.Fatalf("read response: %v (%s)", err, out.Body)
|
|
}
|
|
return res
|
|
}
|
|
page := read(request(http.MethodGet, candidatePath, admin, nil))
|
|
var candidates service.DetachCandidatePage
|
|
if err := json.Unmarshal(page.Obj, &candidates); err != nil || !page.Success || len(candidates.Items) != 1 ||
|
|
candidates.Items[0].ID != record.Id || candidates.Attached != 1 {
|
|
t.Fatalf("candidate response = %+v (%s), error %v", candidates, page.Msg, err)
|
|
}
|
|
freeze := read(request(http.MethodPost, "/detachCandidates/freeze", admin, gin.H{"inboundId": inbound.Id}))
|
|
var scoped service.DetachScopeSummary
|
|
if err := json.Unmarshal(freeze.Obj, &scoped); err != nil || !freeze.Success || scoped.Total != 1 || scoped.ScopeToken == "" {
|
|
t.Fatalf("freeze response = %+v (%s), error %v", scoped, freeze.Msg, err)
|
|
}
|
|
jobID := uuid.NewString()
|
|
body := bulkDetachRequest{
|
|
InboundIds: []int{inbound.Id},
|
|
RequestID: jobID,
|
|
Selection: &service.DetachSelection{Mode: "allMatching", ScopeToken: scoped.ScopeToken},
|
|
}
|
|
start := func(req bulkDetachRequest) envelope {
|
|
return read(request(http.MethodPost, "/bulkDetach", admin, req))
|
|
}
|
|
if res := start(body); !res.Success || !bytes.Contains(res.Obj, []byte(jobID)) {
|
|
t.Fatalf("job submission: %+v", res)
|
|
}
|
|
if res := start(body); !res.Success || !bytes.Contains(res.Obj, []byte(jobID)) {
|
|
t.Fatalf("duplicate submission: %+v", res)
|
|
}
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for {
|
|
res := read(request(http.MethodGet, "/bulkDetach/"+jobID, admin, nil))
|
|
var status DetachJobStatus
|
|
if err := json.Unmarshal(res.Obj, &status); err != nil || !res.Success {
|
|
t.Fatalf("job status: %+v, error %v", res, err)
|
|
}
|
|
if !status.Running {
|
|
if status.Error != "" || status.Processed != 1 || status.Result == nil || status.Result.Detached != 1 {
|
|
t.Fatalf("unexpected terminal status %+v", status)
|
|
}
|
|
break
|
|
}
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("detachment job did not finish")
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
if res := start(body); !res.Success || !bytes.Contains(res.Obj, []byte(jobID)) {
|
|
t.Fatalf("identical retry did not return the same job: %+v", res)
|
|
}
|
|
changed := body
|
|
changed.Selection = &service.DetachSelection{Mode: "explicit", ClientIDs: []int{record.Id}}
|
|
if res := start(changed); res.Success {
|
|
t.Fatal("changed payload reused a request ID")
|
|
}
|
|
}
|