From 45f65966633006148c87cbe6bb4913b99ba9a039 Mon Sep 17 00:00:00 2001 From: Benjamin Mitchell <352241654+BenjaminMitchell-D0FB@users.noreply.github.com> Date: Thu, 3 Dec 2026 02:27:47 -0800 Subject: [PATCH] fix(clients): generate unique subIds in Bulk Add (#7360) 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. --- .../content/docs/en/reference/api/clients.mdx | 24 +- docs/public/openapi.json | 63 +++++- frontend/public/openapi.json | 63 +++++- frontend/src/pages/api-docs/endpoints.ts | 45 +++- .../src/pages/clients/ClientBulkAddModal.tsx | 12 +- .../src/test/client-bulk-add-subid.test.tsx | 122 ++++++++++ internal/web/service/client.go | 31 +-- internal/web/service/client_bulk.go | 42 ++++ .../web/service/client_bulk_subid_test.go | 212 ++++++++++++++++++ 9 files changed, 563 insertions(+), 51 deletions(-) create mode 100644 frontend/src/test/client-bulk-add-subid.test.tsx create mode 100644 internal/web/service/client_bulk_subid_test.go diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index 996aebdaa..9ee16d78a 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -190,12 +190,11 @@ _openapi: keepTraffic to retain client counters. url: '#delete-clients-identified-by-emails-or-by-a-server-resolved-group-set-keeptraffic-to-retain-client-counters' - depth: 2 - title: Create many clients in one call. Body is a JSON array of {client, - inboundIds} payloads — the same shape /add accepts. Items are processed - sequentially; per-email skip reasons are returned for items that fail - (e.g., duplicate email). Triggers a single Xray restart at the end if - any inbound was running. - url: '#create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running' + title: Create many clients in one call. Use subIdPrefix to generate a + subscription ID with an independent cryptographically random suffix. + Omit client.subId or leave it empty on that item. The result includes + per-email skip reasons. + url: '#create-many-clients-in-one-call-use-subidprefix-to-generate-a-subscription-id-with-an-independent-cryptographically-random-suffix-omit-clientsubid-or-leave-it-empty-on-that-item-the-result-includes-per-email-skip-reasons' - depth: 2 title: Move clients into a group and update every owning inbound's settings in the same transaction. @@ -558,12 +557,11 @@ _openapi: - content: Delete clients identified by emails or by a server-resolved group. Set keepTraffic to retain client counters. id: delete-clients-identified-by-emails-or-by-a-server-resolved-group-set-keeptraffic-to-retain-client-counters - - content: Create many clients in one call. Body is a JSON array of {client, - inboundIds} payloads — the same shape /add accepts. Items are - processed sequentially; per-email skip reasons are returned for items - that fail (e.g., duplicate email). Triggers a single Xray restart at - the end if any inbound was running. - id: create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running + - content: Create many clients in one call. Use subIdPrefix to generate a + subscription ID with an independent cryptographically random suffix. + Omit client.subId or leave it empty on that item. The result includes + per-email skip reasons. + id: create-many-clients-in-one-call-use-subidprefix-to-generate-a-subscription-id-with-an-independent-cryptographically-random-suffix-omit-clientsubid-or-leave-it-empty-on-that-item-the-result-includes-per-email-skip-reasons - content: Move clients into a group and update every owning inbound's settings in the same transaction. id: move-clients-into-a-group-and-update-every-owning-inbounds-settings-in-the-same-transaction @@ -1024,7 +1022,7 @@ _openapi: obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue. - heading: create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running + heading: create-many-clients-in-one-call-use-subidprefix-to-generate-a-subscription-id-with-an-independent-cryptographically-random-suffix-omit-clientsubid-or-leave-it-empty-on-that-item-the-result-includes-per-email-skip-reasons - content: Send one of emails, inboundId, or selection with the target group. Emails and inboundId can create the group. A picker selection targets an existing group and excludes current members. Explicit selections diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 027fa94fd..8b68fdee1 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -13246,7 +13246,7 @@ "tags": [ "Clients" ], - "summary": "Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed sequentially; per-email skip reasons are returned for items that fail (e.g., duplicate email). Triggers a single Xray restart at the end if any inbound was running.", + "summary": "Create many clients in one call. Use subIdPrefix to generate a subscription ID with an independent cryptographically random suffix. Omit client.subId or leave it empty on that item. The result includes per-email skip reasons.", "operationId": "post_panel_api_clients_bulkCreate", "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { @@ -13254,33 +13254,76 @@ "content": { "application/json": { "schema": { - "type": "object" + "type": "array", + "items": { + "type": "object", + "required": [ + "client", + "inboundIds" + ], + "properties": { + "client": { + "type": "object", + "required": [ + "email" + ], + "properties": { + "email": { + "type": "string" + }, + "subId": { + "type": "string" + }, + "totalGB": { + "type": "integer" + }, + "expiryTime": { + "type": "integer" + }, + "limitHwid": { + "type": "integer" + }, + "enable": { + "type": "boolean" + } + } + }, + "inboundIds": { + "type": "array", + "items": { + "type": "integer" + } + }, + "subIdPrefix": { + "type": "string", + "description": "Optional readable prefix. The panel adds a random suffix." + } + } + } }, "example": [ { "client": { "email": "alice@example.com", "totalGB": 53687091200, - "expiryTime": 0, - "limitHwid": 2, - "enable": true + "limitHwid": 2 }, "inboundIds": [ 7 - ] + ], + "subIdPrefix": "team" }, { "client": { "email": "bob@example.com", "totalGB": 53687091200, - "expiryTime": 0, - "limitHwid": 0, - "enable": true + "limitHwid": 0 }, "inboundIds": [ 7, 9 - ] + ], + "subIdPrefix": "team" } ] } diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 027fa94fd..8b68fdee1 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -13246,7 +13246,7 @@ "tags": [ "Clients" ], - "summary": "Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed sequentially; per-email skip reasons are returned for items that fail (e.g., duplicate email). Triggers a single Xray restart at the end if any inbound was running.", + "summary": "Create many clients in one call. Use subIdPrefix to generate a subscription ID with an independent cryptographically random suffix. Omit client.subId or leave it empty on that item. The result includes per-email skip reasons.", "operationId": "post_panel_api_clients_bulkCreate", "description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue.", "requestBody": { @@ -13254,33 +13254,76 @@ "content": { "application/json": { "schema": { - "type": "object" + "type": "array", + "items": { + "type": "object", + "required": [ + "client", + "inboundIds" + ], + "properties": { + "client": { + "type": "object", + "required": [ + "email" + ], + "properties": { + "email": { + "type": "string" + }, + "subId": { + "type": "string" + }, + "totalGB": { + "type": "integer" + }, + "expiryTime": { + "type": "integer" + }, + "limitHwid": { + "type": "integer" + }, + "enable": { + "type": "boolean" + } + } + }, + "inboundIds": { + "type": "array", + "items": { + "type": "integer" + } + }, + "subIdPrefix": { + "type": "string", + "description": "Optional readable prefix. The panel adds a random suffix." + } + } + } }, "example": [ { "client": { "email": "alice@example.com", "totalGB": 53687091200, - "expiryTime": 0, - "limitHwid": 2, - "enable": true + "limitHwid": 2 }, "inboundIds": [ 7 - ] + ], + "subIdPrefix": "team" }, { "client": { "email": "bob@example.com", "totalGB": 53687091200, - "expiryTime": 0, - "limitHwid": 0, - "enable": true + "limitHwid": 0 }, "inboundIds": [ 7, 9 - ] + ], + "subIdPrefix": "team" } ] } diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 4e8852846..cc420f88a 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -1796,8 +1796,49 @@ export const sections: readonly Section[] = [ path: '/panel/api/clients/bulkCreate', description: bulkClientNodeApplyDescription, summary: - 'Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed sequentially; per-email skip reasons are returned for items that fail (e.g., duplicate email). Triggers a single Xray restart at the end if any inbound was running.', - body: '[\n {\n "client": {\n "email": "alice@example.com",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "limitHwid": 2,\n "enable": true\n },\n "inboundIds": [7]\n },\n {\n "client": {\n "email": "bob@example.com",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "limitHwid": 0,\n "enable": true\n },\n "inboundIds": [7, 9]\n }\n]', + 'Create many clients in one call. Use subIdPrefix to generate a subscription ID with an independent cryptographically random suffix. Omit client.subId or leave it empty on that item. The result includes per-email skip reasons.', + requestSchema: { + type: 'array', + items: { + type: 'object', + required: ['client', 'inboundIds'], + properties: { + client: { + type: 'object', + required: ['email'], + properties: { + email: { type: 'string' }, + subId: { type: 'string' }, + totalGB: { type: 'integer' }, + expiryTime: { type: 'integer' }, + limitHwid: { type: 'integer' }, + enable: { type: 'boolean' }, + }, + }, + inboundIds: { type: 'array', items: { type: 'integer' } }, + subIdPrefix: { + type: 'string', + description: 'Optional readable prefix. The panel adds a random suffix.', + }, + }, + }, + }, + body: JSON.stringify( + [ + { + client: { email: 'alice@example.com', totalGB: 53687091200, limitHwid: 2 }, + inboundIds: [7], + subIdPrefix: 'team', + }, + { + client: { email: 'bob@example.com', totalGB: 53687091200, limitHwid: 0 }, + inboundIds: [7, 9], + subIdPrefix: 'team', + }, + ], + null, + 2, + ), responseSchema: 'BulkCreateResult', }, { diff --git a/frontend/src/pages/clients/ClientBulkAddModal.tsx b/frontend/src/pages/clients/ClientBulkAddModal.tsx index 79aef46a6..2c6df7ec7 100644 --- a/frontend/src/pages/clients/ClientBulkAddModal.tsx +++ b/frontend/src/pages/clients/ClientBulkAddModal.tsx @@ -192,10 +192,12 @@ export default function ClientBulkAddModal({ setSaving(true); try { + const subIdPrefix = emails.length > 1 ? current.subId : ''; const payloads = emails.map((email) => ({ + subIdPrefix: subIdPrefix || undefined, client: { email, - subId: current.subId || RandomUtil.randomLowerAndNum(16), + subId: subIdPrefix ? '' : current.subId || RandomUtil.randomLowerAndNum(16), id: RandomUtil.randomUUID(), password: ss2022Method ? RandomUtil.randomShadowsocksPassword(ss2022Method) @@ -219,11 +221,15 @@ export default function ClientBulkAddModal({ inboundIds: current.inboundIds, })); const msg = await bulkCreate(payloads); + if (!msg?.success) { + messageApi.error(msg?.msg || t('somethingWentWrong')); + return; + } const ok = msg?.obj?.created ?? 0; const skipped = msg?.obj?.skipped ?? []; const failed = skipped.length; - const firstError = skipped[0]?.reason ?? msg?.msg ?? ''; - if (failed === 0 && msg?.success) { + const firstError = skipped[0]?.reason ?? ''; + if (failed === 0) { messageApi.success(t('pages.clients.toasts.bulkCreated', { count: ok })); } else { messageApi.warning( diff --git a/frontend/src/test/client-bulk-add-subid.test.tsx b/frontend/src/test/client-bulk-add-subid.test.tsx new file mode 100644 index 000000000..460dad161 --- /dev/null +++ b/frontend/src/test/client-bulk-add-subid.test.tsx @@ -0,0 +1,122 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, screen, waitFor } from '@testing-library/react'; + +import ClientBulkAddModal from '@/pages/clients/ClientBulkAddModal'; +import { HttpUtil, Msg } from '@/utils'; +import { renderWithProviders } from './test-utils'; + +const { bulkCreate } = vi.hoisted(() => ({ bulkCreate: vi.fn() })); +vi.mock('@/hooks/useClients', () => ({ useClients: () => ({ bulkCreate }) })); + +function mockHttp() { + vi.spyOn(HttpUtil, 'get').mockImplementation(async (url) => { + if (typeof url === 'string' && url.includes('fail2banStatus')) + return new Msg(true, '', { enabled: true, installed: true, usable: true, windows: false }); + return new Msg(true, '', {}); + }); + vi.spyOn(HttpUtil, 'post').mockImplementation(async (url) => { + if (url !== '/panel/api/clients/renewalPreview') + return new Msg(true, '', { datepicker: 'gregorian' }); + return new Msg(true, '', { + timeZone: 'Asia/Taipei', + renewAt: '', + validThrough: '', + nextExpiry: '', + suggestedExpiryTime: 1893427200000, + suggestedExpiry: '2030-01-01T00:00:00+08:00', + renewals: 0, + canRenew: false, + delayedStart: false, + }); + }); +} + +function renderModal(onOpenChange = vi.fn()) { + renderWithProviders( + , + ); + return onOpenChange; +} + +function fillBatch(quantity: string, subId: string) { + fireEvent.click(screen.getByRole('button', { name: 'Select all' })); + fireEvent.change(screen.getByLabelText('Number of Clients'), { target: { value: quantity } }); + fireEvent.change(screen.getByLabelText('Subscription ID'), { target: { value: subId } }); +} + +async function submit() { + const button = document.querySelector('.ant-modal-footer .ant-btn-primary'); + if (!button) throw new Error('Create button missing'); + await waitFor(() => expect(button.classList.contains('ant-btn-loading')).toBe(false)); + fireEvent.click(button); +} + +function subIdsOf(call: unknown[]): string[] { + const payloads = call[0] as { client: { subId: string } }[]; + return payloads.map((p) => p.client.subId); +} + +describe('ClientBulkAddModal subscription IDs', () => { + beforeEach(() => { + bulkCreate.mockClear(); + bulkCreate.mockResolvedValue(new Msg(true, '', { created: 3, skipped: [] })); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('sends the typed prefix for server allocation without fetching all clients', async () => { + mockHttp(); + renderModal(); + fillBatch('3', 'test123'); + await submit(); + await waitFor(() => expect(bulkCreate).toHaveBeenCalledTimes(1)); + expect(subIdsOf(bulkCreate.mock.calls[0])).toEqual(['', '', '']); + expect(bulkCreate.mock.calls[0][0]).toEqual( + Array.from({ length: 3 }, () => expect.objectContaining({ subIdPrefix: 'test123' })), + ); + expect( + vi.mocked(HttpUtil.get).mock.calls.some(([url]) => url === '/panel/api/clients/list'), + ).toBe(false); + }); + + it('keeps a typed ID exact for a single client', async () => { + mockHttp(); + renderModal(); + fillBatch('1', 'test123'); + await submit(); + await waitFor(() => expect(bulkCreate).toHaveBeenCalledTimes(1)); + expect(subIdsOf(bulkCreate.mock.calls[0])).toEqual(['test123']); + expect(bulkCreate.mock.calls[0][0][0].subIdPrefix).toBeUndefined(); + }); + + it('leaves the form open for retry when server allocation fails', async () => { + mockHttp(); + bulkCreate.mockResolvedValueOnce(new Msg(false, 'Could not allocate subscription IDs', null)); + const onOpenChange = renderModal(); + fillBatch('3', 'test123'); + await submit(); + await screen.findByText('Could not allocate subscription IDs'); + expect(onOpenChange).not.toHaveBeenCalled(); + expect((screen.getByLabelText('Subscription ID') as HTMLInputElement).value).toBe('test123'); + await submit(); + await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false)); + }); + + it('gives each client a different random ID when Subscription ID is empty', async () => { + mockHttp(); + renderModal(); + fillBatch('3', ''); + await submit(); + await waitFor(() => expect(bulkCreate).toHaveBeenCalledTimes(1)); + const subIds = subIdsOf(bulkCreate.mock.calls[0]); + expect(subIds).toHaveLength(3); + expect(new Set(subIds).size).toBe(3); + for (const subId of subIds) expect(subId).toMatch(/^[a-z0-9]{16}$/); + }); +}); diff --git a/internal/web/service/client.go b/internal/web/service/client.go index 4fd2625e1..64fb9b072 100644 --- a/internal/web/service/client.go +++ b/internal/web/service/client.go @@ -68,10 +68,11 @@ type ClientService struct { var ErrClientNotInInbound = errors.New("client not found in inbound") type ClientCreatePayload struct { - Client model.Client `json:"client"` - InboundIds []int `json:"inboundIds"` - LimitHwid int `json:"-"` - Traffic *ClientPortableTraffic `json:"traffic,omitempty"` + Client model.Client `json:"client"` + InboundIds []int `json:"inboundIds"` + LimitHwid int `json:"-"` + Traffic *ClientPortableTraffic `json:"traffic,omitempty"` + SubIDPrefix string `json:"subIdPrefix,omitempty"` } const sqlInChunk = 400 @@ -83,9 +84,10 @@ type clientPayloadWithHwid struct { func (p *ClientCreatePayload) UnmarshalJSON(data []byte) error { var raw struct { - Client json.RawMessage `json:"client"` - InboundIds []int `json:"inboundIds"` - Traffic *ClientPortableTraffic `json:"traffic"` + Client json.RawMessage `json:"client"` + InboundIds []int `json:"inboundIds"` + Traffic *ClientPortableTraffic `json:"traffic"` + SubIDPrefix string `json:"subIdPrefix"` } if err := json.Unmarshal(data, &raw); err != nil { return err @@ -100,6 +102,7 @@ func (p *ClientCreatePayload) UnmarshalJSON(data []byte) error { p.InboundIds = raw.InboundIds p.LimitHwid = withHwid.LimitHwid p.Traffic = raw.Traffic + p.SubIDPrefix = raw.SubIDPrefix // Omit enable → true (legacy API); explicit false is preserved (#6478). var keys map[string]json.RawMessage if len(raw.Client) > 0 && json.Unmarshal(raw.Client, &keys) == nil { @@ -112,12 +115,14 @@ func (p *ClientCreatePayload) UnmarshalJSON(data []byte) error { func (p ClientCreatePayload) MarshalJSON() ([]byte, error) { return json.Marshal(struct { - Client clientPayloadWithHwid `json:"client"` - InboundIds []int `json:"inboundIds"` - Traffic *ClientPortableTraffic `json:"traffic,omitempty"` + Client clientPayloadWithHwid `json:"client"` + InboundIds []int `json:"inboundIds"` + Traffic *ClientPortableTraffic `json:"traffic,omitempty"` + SubIDPrefix string `json:"subIdPrefix,omitempty"` }{ - Client: clientPayloadWithHwid{Client: p.Client, LimitHwid: p.LimitHwid}, - InboundIds: p.InboundIds, - Traffic: p.Traffic, + Client: clientPayloadWithHwid{Client: p.Client, LimitHwid: p.LimitHwid}, + InboundIds: p.InboundIds, + Traffic: p.Traffic, + SubIDPrefix: p.SubIDPrefix, }) } diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index 3bd167783..98be6dd81 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -3,6 +3,7 @@ package service import ( "cmp" "context" + "crypto/rand" "encoding/json" "errors" "fmt" @@ -1479,10 +1480,51 @@ type BulkCreateReport struct { } func (s *ClientService) BulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, bool, error) { + if slices.ContainsFunc(payloads, func(payload ClientCreatePayload) bool { + return payload.SubIDPrefix != "" + }) { + var err error + payloads, err = allocateBulkSubIDs(payloads) + if err != nil { + return BulkCreateResult{}, false, err + } + } result, _, needRestart, err := s.bulkCreate(inboundSvc, payloads) return result, needRestart, err } +func allocateBulkSubIDs(payloads []ClientCreatePayload) ([]ClientCreatePayload, error) { + payloads = slices.Clone(payloads) + taken := make(map[string]bool, len(payloads)) + for _, item := range payloads { + if item.Client.SubID != "" { + if item.SubIDPrefix != "" { + return nil, common.NewError("subId and subIdPrefix cannot both be set") + } + taken[item.Client.SubID] = true + } + } + for i := range payloads { + prefix := payloads[i].SubIDPrefix + if prefix == "" { + continue + } + if err := validateClientSubID(prefix); err != nil { + return nil, err + } + for { + // The prefix is public. Each subscription gets independent secret entropy. + subID := prefix + "-" + rand.Text() + if !taken[subID] { + payloads[i].Client.SubID = subID + taken[subID] = true + break + } + } + } + return payloads, nil +} + // bulkCreate also returns the payload indexes that inserted a new client record; // a Created payload whose email already existed only reused that client. func (s *ClientService) bulkCreate(inboundSvc *InboundService, payloads []ClientCreatePayload) (BulkCreateResult, []int, bool, error) { diff --git a/internal/web/service/client_bulk_subid_test.go b/internal/web/service/client_bulk_subid_test.go new file mode 100644 index 000000000..7b711677c --- /dev/null +++ b/internal/web/service/client_bulk_subid_test.go @@ -0,0 +1,212 @@ +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") + } +}