mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 16:34:52 +03:00
45f6596663
Fixes the Bulk Add regression where a manually entered subscription ID was copied to every generated client, causing all but the first client to be rejected as duplicates. For multi-client batches, treat the entered value as a readable prefix and append an independent cryptographically random suffix; preserve the exact value for a single client and independent random IDs when the field is empty. Remove the process-wide allocation lock to avoid blocking unrelated requests during remote-node dispatch, and cover concurrent BulkCreate/Create, deleted-ID reuse, and uniqueness regressions. Document subIdPrefix in the API contract and regenerate the OpenAPI/API reference artifacts. Validation: CI 12/12 and Docs CI passed on the reviewed head.
213 lines
6.6 KiB
Go
213 lines
6.6 KiB
Go
package service
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
|
)
|
|
|
|
func TestBulkCreateAllocatesIndependentSubscriptionIDsAlongsideCreate(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
db := database.GetDB()
|
|
const prefix = "test_%!"
|
|
for i, suffix := range []int{1, 3} {
|
|
row := model.ClientRecord{Email: fmt.Sprintf("existing-%d@example.test", i), SubID: fmt.Sprintf("%s-%d", prefix, suffix)}
|
|
if err := db.Create(&row).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
inbounds := []*model.Inbound{
|
|
mkInbound(t, 27601, model.VLESS, `{"clients":[]}`),
|
|
mkInbound(t, 27602, model.VLESS, `{"clients":[]}`),
|
|
}
|
|
single := mkInbound(t, 27603, model.VLESS, `{"clients":[]}`)
|
|
start := make(chan struct{})
|
|
done := make(chan error, len(inbounds)+1)
|
|
go func() {
|
|
<-start
|
|
_, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{
|
|
Client: model.Client{Email: "single@example.test", SubID: prefix + "-2", Enable: true},
|
|
InboundIds: []int{single.Id},
|
|
})
|
|
done <- err
|
|
}()
|
|
for i, inbound := range inbounds {
|
|
go func() {
|
|
items := make([]ClientCreatePayload, 2)
|
|
for j := range items {
|
|
items[j] = ClientCreatePayload{
|
|
Client: model.Client{Email: fmt.Sprintf("batch-%d-%d@example.test", i, j), Enable: true},
|
|
InboundIds: []int{inbound.Id},
|
|
SubIDPrefix: prefix,
|
|
}
|
|
}
|
|
<-start
|
|
result, _, err := (&ClientService{}).BulkCreate(&InboundService{}, items)
|
|
if err == nil && (result.Created != len(items) || len(result.Skipped) != 0) {
|
|
err = fmt.Errorf("created %d, skipped %v", result.Created, result.Skipped)
|
|
}
|
|
done <- err
|
|
}()
|
|
}
|
|
close(start)
|
|
for range len(inbounds) + 1 {
|
|
if err := <-done; err != nil {
|
|
t.Error(err)
|
|
}
|
|
}
|
|
if t.Failed() {
|
|
return
|
|
}
|
|
var got []string
|
|
if err := db.Model(&model.ClientRecord{}).Where("email LIKE ?", "batch-%").Pluck("sub_id", &got).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
seen := make(map[string]bool)
|
|
for _, id := range got {
|
|
suffix, ok := strings.CutPrefix(id, prefix+"-")
|
|
if !ok || len(suffix) < 26 || seen[id] {
|
|
t.Fatal("bulk allocation did not create an independent random subscription ID")
|
|
}
|
|
seen[id] = true
|
|
}
|
|
if len(seen) != 4 || lookupClientRecord(t, "single@example.test").SubID != prefix+"-2" {
|
|
t.Fatal("concurrent BulkCreate and Create did not retain distinct IDs")
|
|
}
|
|
}
|
|
|
|
func TestBulkCreateSubscriptionPrefixRequest(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
inbound := mkInbound(t, 27604, model.VLESS, `{"clients":[]}`)
|
|
var request []ClientCreatePayload
|
|
err := json.Unmarshal([]byte(`[
|
|
{"client":{"email":"allocated@example.test"},"subIdPrefix":"label","inboundIds":[1]},
|
|
{"client":{"email":"explicit@example.test","subId":"label-1"},"inboundIds":[1]}
|
|
]`), &request)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for i := range request {
|
|
request[i].InboundIds = []int{inbound.Id}
|
|
}
|
|
svc := &ClientService{}
|
|
result, _, err := svc.BulkCreate(&InboundService{}, request)
|
|
if err != nil || result.Created != 2 || request[0].Client.SubID != "" {
|
|
t.Fatalf("bulk create: created=%d, error=%v", result.Created, err)
|
|
}
|
|
if lookupClientRecord(t, "explicit@example.test").SubID != "label-1" {
|
|
t.Fatal("explicit subscription ID changed")
|
|
}
|
|
request[0].Client.SubID = "conflicting"
|
|
if _, _, err := svc.BulkCreate(&InboundService{}, request); err == nil {
|
|
t.Fatal("expected a request with both an explicit ID and a prefix to be rejected")
|
|
}
|
|
}
|
|
|
|
func TestBulkCreateDoesNotReissueDeletedSubscriptionID(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
inbound := mkInbound(t, 27605, model.VLESS, `{"clients":[]}`)
|
|
svc, inboundSvc := &ClientService{}, &InboundService{}
|
|
create := func(email string) string {
|
|
t.Helper()
|
|
result, _, err := svc.BulkCreate(inboundSvc, []ClientCreatePayload{{
|
|
Client: model.Client{Email: email, Enable: true},
|
|
InboundIds: []int{inbound.Id},
|
|
SubIDPrefix: "label",
|
|
}})
|
|
if err != nil || result.Created != 1 {
|
|
t.Fatalf("bulk create: created=%d, error=%v", result.Created, err)
|
|
}
|
|
return lookupClientRecord(t, email).SubID
|
|
}
|
|
deleted := create("deleted@example.test")
|
|
if _, err := svc.DeleteByEmail(inboundSvc, "deleted@example.test", false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if next := create("replacement@example.test"); next == deleted {
|
|
t.Fatal("the deleted subscription ID was issued to a different client")
|
|
}
|
|
var owners int64
|
|
if err := database.GetDB().Model(&model.ClientRecord{}).Where("sub_id = ?", deleted).Count(&owners).Error; err != nil || owners != 0 {
|
|
t.Fatalf("deleted subscription still has an owner: %d, %v", owners, err)
|
|
}
|
|
}
|
|
|
|
func TestBulkCreatePrefixedBatchDoesNotWaitForUnrelatedNode(t *testing.T) {
|
|
setupClientNodeOrderDB(t)
|
|
useTestRuntimeManager(t)
|
|
peer := &groupedCreatePeer{tags: map[string]int{}, settings: map[int]string{}}
|
|
entered, release := make(chan struct{}, 1), make(chan struct{})
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodPost {
|
|
select {
|
|
case entered <- struct{}{}:
|
|
default:
|
|
}
|
|
select {
|
|
case <-release:
|
|
_, _ = w.Write([]byte(`{"success":true}`))
|
|
case <-r.Context().Done():
|
|
}
|
|
return
|
|
}
|
|
peer.serve(w, r)
|
|
}))
|
|
defer server.Close()
|
|
slow := realNodeInbound(t, &fakeNodeHTTP{srv: server, tags: peer.tags}, 27606, nil)
|
|
local := mkInbound(t, 27607, model.VLESS, `{"clients":[]}`)
|
|
bulk := func(email, prefix string, inbound int) error {
|
|
result, _, err := (&ClientService{}).BulkCreate(&InboundService{}, []ClientCreatePayload{{
|
|
Client: model.Client{Email: email, Enable: true}, InboundIds: []int{inbound}, SubIDPrefix: prefix,
|
|
}})
|
|
if err == nil && result.Created != 1 {
|
|
err = fmt.Errorf("created %d clients", result.Created)
|
|
}
|
|
return err
|
|
}
|
|
slowDone := make(chan struct{})
|
|
var localDone chan struct{}
|
|
var slowErr error
|
|
go func() {
|
|
defer close(slowDone)
|
|
slowErr = bulk("slow@example.test", "slow", slow.Id)
|
|
}()
|
|
defer func() {
|
|
close(release)
|
|
<-slowDone
|
|
if localDone != nil {
|
|
<-localDone
|
|
}
|
|
if slowErr != nil {
|
|
t.Error(slowErr)
|
|
}
|
|
}()
|
|
select {
|
|
case <-entered:
|
|
case <-slowDone:
|
|
t.Fatalf("bulk create finished before the remote apply: %v", slowErr)
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("bulk create did not reach the remote apply")
|
|
}
|
|
localDone = make(chan struct{})
|
|
var localErr error
|
|
go func() {
|
|
defer close(localDone)
|
|
localErr = bulk("local@example.test", "local", local.Id)
|
|
}()
|
|
select {
|
|
case <-localDone:
|
|
if localErr != nil {
|
|
t.Fatal(localErr)
|
|
}
|
|
case <-time.After(3 * time.Second):
|
|
t.Fatal("the local prefixed batch waited for the unrelated remote apply")
|
|
}
|
|
}
|