feat(groups): assign host rules from client groups (#7064)

Host rules could only be given to clients one by one, so giving a set of customers their own endpoints meant editing every client. A client group can now carry host rules, chosen when the group is created, from its edit dialog or from a quick-assign action on the Groups page.

A subscription resolves a client's hosts in this order: the client's own host rules, then the host rules of its group, then the inbound's default pool. A group whose bound rules are all disabled or excluded from the requested format renders nothing for that inbound instead of falling back to the default pool. Binding a rule to a group narrows what its members get; other clients still see that rule in the default pool.

Group names are now matched case-insensitively. On upgrade, labels that differ only in case (VIP and vip) are merged into one group, the first by name order.

Adds POST /panel/api/clients/groups/:name/hosts and an optional hostGroupIds on group create and rename.
This commit is contained in:
Nethmina Yasas
2026-11-25 17:51:43 +05:30
committed by GitHub
parent 4013219698
commit e95d17a7db
46 changed files with 2222 additions and 285 deletions
+91
View File
@@ -0,0 +1,91 @@
package database
import (
"errors"
"sort"
"strings"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"gorm.io/gorm"
)
// EnsureClientGroup returns the canonical group row for name, creating it if
// absent. Matching is case-insensitive so casing cannot create a second group.
func EnsureClientGroup(tx *gorm.DB, name string) (*model.ClientGroup, error) {
name = strings.TrimSpace(name)
if name == "" {
return nil, nil
}
if tx == nil {
tx = db
}
var group model.ClientGroup
err := tx.Where("LOWER(name) = LOWER(?)", name).Order("id ASC").First(&group).Error
if err == nil {
return &group, nil
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
group = model.ClientGroup{Name: name}
if err := tx.Create(&group).Error; err != nil {
// A concurrent writer may have created it between the lookup and insert.
var existing model.ClientGroup
if e := tx.Where("LOWER(name) = LOWER(?)", name).Order("id ASC").First(&existing).Error; e == nil {
return &existing, nil
}
return nil, err
}
return &group, nil
}
// PruneHostGroupClientGroups drops bindings whose host group no longer has any
// hosts row (e.g. the inbound was deleted). Idempotent; runs on every start.
func PruneHostGroupClientGroups() error {
return PruneHostGroupClientGroupsTx(db)
}
// PruneHostGroupClientGroupsTx drops bindings to rules whose hosts are gone, so
// deleting an inbound cannot leave a group bound to a rule nobody can select.
func PruneHostGroupClientGroupsTx(tx *gorm.DB) error {
return tx.Exec(`DELETE FROM host_group_client_groups
WHERE host_group_id NOT IN (SELECT DISTINCT group_id FROM hosts)
OR client_group_id NOT IN (SELECT id FROM client_groups)`).Error
}
// EnsureClientGroupRows repairs group labels that have no client_groups row and
// rewrites case variants to the canonical row's spelling. Idempotent.
func EnsureClientGroupRows() error {
var names []string
if err := db.Model(&model.ClientRecord{}).
Where("TRIM(COALESCE(group_name, '')) <> ''").
Distinct().Pluck("group_name", &names).Error; err != nil {
return err
}
if len(names) == 0 {
return nil
}
sort.Strings(names)
return db.Transaction(func(tx *gorm.DB) error {
for _, raw := range names {
name := strings.TrimSpace(raw)
if name == "" {
continue
}
group, err := EnsureClientGroup(tx, name)
if err != nil {
return err
}
if group == nil || group.Name == raw {
continue
}
if err := tx.Model(&model.ClientRecord{}).
Where("group_name = ?", raw).
UpdateColumn("group_name", group.Name).Error; err != nil {
return err
}
}
return nil
})
}
+123
View File
@@ -0,0 +1,123 @@
package database
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func TestEnsureClientGroupRows_CreatesMissingAndCanonicalizes(t *testing.T) {
initMigrateDB(t)
db := GetDB()
if err := db.Create(&model.ClientRecord{Email: "a@x", Group: "VIP", Enable: true}).Error; err != nil {
t.Fatalf("create client a: %v", err)
}
if err := db.Create(&model.ClientRecord{Email: "b@x", Group: "vip", Enable: true}).Error; err != nil {
t.Fatalf("create client b: %v", err)
}
if err := EnsureClientGroupRows(); err != nil {
t.Fatalf("EnsureClientGroupRows: %v", err)
}
var groups []model.ClientGroup
if err := db.Order("id ASC").Find(&groups).Error; err != nil {
t.Fatalf("load groups: %v", err)
}
if len(groups) != 1 || groups[0].Name != "VIP" {
t.Fatalf("groups = %+v, want one canonical VIP", groups)
}
var clients []model.ClientRecord
if err := db.Order("email ASC").Find(&clients).Error; err != nil {
t.Fatalf("load clients: %v", err)
}
for _, client := range clients {
if client.Group != "VIP" {
t.Fatalf("client %s group = %q, want VIP", client.Email, client.Group)
}
}
if err := EnsureClientGroupRows(); err != nil {
t.Fatalf("second EnsureClientGroupRows: %v", err)
}
var count int64
if err := db.Model(&model.ClientGroup{}).Count(&count).Error; err != nil {
t.Fatalf("count groups: %v", err)
}
if count != 1 {
t.Fatalf("second run created a duplicate: %d", count)
}
}
func TestEnsureClientGroupRows_UpgradeExistingDB(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "x-ui.db")
if err := InitDB(dbPath); err != nil {
t.Fatalf("InitDB: %v", err)
}
if err := GetDB().Create(&model.ClientRecord{Email: "legacy@x", Group: "Legacy", Enable: true}).Error; err != nil {
t.Fatalf("create client: %v", err)
}
if err := CloseDB(); err != nil {
t.Fatalf("CloseDB: %v", err)
}
if err := InitDB(dbPath); err != nil {
t.Fatalf("reopen InitDB: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
var group model.ClientGroup
if err := GetDB().Where("name = ?", "Legacy").First(&group).Error; err != nil {
t.Fatalf("reopen did not create the missing group row: %v", err)
}
}
func TestPruneHostGroupClientGroups(t *testing.T) {
initMigrateDB(t)
db := GetDB()
inbound := seedInboundWithStream(t, "prune", 4599, `{"network":"tcp","security":"none"}`)
if err := db.Create(&model.Host{GroupId: "live", InboundId: inbound.Id, Remark: "L", Address: "live.example.com"}).Error; err != nil {
t.Fatalf("create host: %v", err)
}
group := &model.ClientGroup{Name: "VIP"}
if err := db.Create(group).Error; err != nil {
t.Fatalf("create group: %v", err)
}
for _, hostGroup := range []string{"live", "gone"} {
if err := db.Create(&model.HostGroupClientGroup{HostGroupId: hostGroup, ClientGroupId: group.Id}).Error; err != nil {
t.Fatalf("create binding %s: %v", hostGroup, err)
}
}
if err := PruneHostGroupClientGroups(); err != nil {
t.Fatalf("PruneHostGroupClientGroups: %v", err)
}
var ids []string
if err := db.Model(&model.HostGroupClientGroup{}).Pluck("host_group_id", &ids).Error; err != nil {
t.Fatalf("load bindings: %v", err)
}
if len(ids) != 1 || ids[0] != "live" {
t.Fatalf("bindings = %v, want only live", ids)
}
}
func TestEnsureClientGroupRows_Postgres(t *testing.T) {
if strings.TrimSpace(os.Getenv("XUI_DB_DSN")) == "" || os.Getenv("XUI_DB_TYPE") != "postgres" {
t.Skip("set XUI_DB_TYPE=postgres and XUI_DB_DSN to run the postgres test")
}
if err := InitDB(""); err != nil {
t.Fatalf("InitDB: %v", err)
}
t.Cleanup(func() { _ = CloseDB() })
GetDB().Exec("TRUNCATE TABLE clients, client_groups RESTART IDENTITY CASCADE")
if err := GetDB().Create(&model.ClientRecord{Email: "pg@x", Group: "PgGroup", Enable: true}).Error; err != nil {
t.Fatalf("create client: %v", err)
}
if err := EnsureClientGroupRows(); err != nil {
t.Fatalf("EnsureClientGroupRows: %v", err)
}
var group model.ClientGroup
if err := GetDB().Where("name = ?", "PgGroup").First(&group).Error; err != nil {
t.Fatalf("group not created: %v", err)
}
}
+8
View File
@@ -77,6 +77,7 @@ func allModels() []any {
&model.ClientHwid{},
&model.ClientExternalLink{},
&model.ClientGroup{},
&model.HostGroupClientGroup{},
&model.InboundFallback{},
&model.Host{},
&model.HostTombstone{},
@@ -1770,6 +1771,13 @@ func runSeeders(isUsersEmpty bool) error {
return err
}
if err := EnsureClientGroupRows(); err != nil {
return err
}
if err := PruneHostGroupClientGroups(); err != nil {
return err
}
// Self-gated on the "MtprotoSecretsToClients" row.
if err := seedMtprotoSecretsToClients(); err != nil {
return err
+1
View File
@@ -51,6 +51,7 @@ func migrationModels() []any {
&model.ClientHwid{},
&model.ClientExternalLink{},
&model.ClientGroup{},
&model.HostGroupClientGroup{},
&model.InboundFallback{},
&model.Host{},
&model.HostTombstone{},
+9
View File
@@ -1129,6 +1129,15 @@ type ClientGroup struct {
func (ClientGroup) TableName() string { return "client_groups" }
// HostGroupClientGroup binds a host group (hosts.group_id) to a client group.
// Rows added later to the host group inherit the binding; no FK cascade.
type HostGroupClientGroup struct {
HostGroupId string `json:"hostGroupId" gorm:"column:host_group_id;primaryKey"`
ClientGroupId int `json:"clientGroupId" gorm:"column:client_group_id;primaryKey;index"`
}
func (HostGroupClientGroup) TableName() string { return "host_group_client_groups" }
// MarshalJSON emits the reverse column as a nested JSON object rather than an
// escaped JSON-text string, matching the same convention Inbound uses for its
// JSON-text columns. Empty storage renders as null.