db_seed_test.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package database
  2. import (
  3. "encoding/json"
  4. "path/filepath"
  5. "regexp"
  6. "testing"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. )
  9. func TestInitDB_GeneratesPerPanelSubscriptionPaths(t *testing.T) {
  10. pathPattern := regexp.MustCompile(`^/[0-9a-z]{16}/$`)
  11. loadPaths := func(dbPath string) map[string]string {
  12. t.Helper()
  13. if err := InitDB(dbPath); err != nil {
  14. t.Fatalf("InitDB failed: %v", err)
  15. }
  16. defer func() {
  17. if err := CloseDB(); err != nil {
  18. t.Errorf("CloseDB failed: %v", err)
  19. }
  20. }()
  21. keys := []string{"subPath", "subJsonPath", "subClashPath"}
  22. paths := make(map[string]string, len(keys))
  23. for _, key := range keys {
  24. var setting model.Setting
  25. if err := db.Where("key = ?", key).First(&setting).Error; err != nil {
  26. t.Fatalf("read %s: %v", key, err)
  27. }
  28. if !pathPattern.MatchString(setting.Value) {
  29. t.Fatalf("%s = %q, want /<16 lowercase alphanumeric characters>/", key, setting.Value)
  30. }
  31. paths[key] = setting.Value
  32. }
  33. if paths["subPath"] == paths["subJsonPath"] || paths["subPath"] == paths["subClashPath"] || paths["subJsonPath"] == paths["subClashPath"] {
  34. t.Fatalf("subscription paths must be distinct: %v", paths)
  35. }
  36. return paths
  37. }
  38. firstDB := filepath.Join(t.TempDir(), "x-ui.db")
  39. first := loadPaths(firstDB)
  40. reloaded := loadPaths(firstDB)
  41. for key, firstPath := range first {
  42. if firstPath != reloaded[key] {
  43. t.Fatalf("%s changed after restart: %q, then %q", key, firstPath, reloaded[key])
  44. }
  45. }
  46. second := loadPaths(filepath.Join(t.TempDir(), "x-ui.db"))
  47. for key, firstPath := range first {
  48. if firstPath == second[key] {
  49. t.Fatalf("%s reused across panels: %q", key, firstPath)
  50. }
  51. }
  52. }
  53. func TestSeedClientsFromInboundJSON_IsIdempotentAgainstExistingClients(t *testing.T) {
  54. dbDir := t.TempDir()
  55. t.Setenv("XUI_DB_FOLDER", dbDir)
  56. if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
  57. t.Fatalf("InitDB failed: %v", err)
  58. }
  59. t.Cleanup(func() { _ = CloseDB() })
  60. settings, err := json.Marshal(map[string]any{
  61. "clients": []any{
  62. map[string]any{
  63. "id": "ce8d33df-3a64-4f10-8f9b-91c3a8e0c001",
  64. "email": "[email protected]",
  65. "enable": true,
  66. "flow": "",
  67. "subId": "alice-sub",
  68. "comment": "from-inbound-json",
  69. },
  70. },
  71. })
  72. if err != nil {
  73. t.Fatalf("marshal settings: %v", err)
  74. }
  75. inbound := model.Inbound{
  76. UserId: 1,
  77. Port: 12345,
  78. Protocol: model.VLESS,
  79. Settings: string(settings),
  80. Tag: "test-inbound",
  81. }
  82. if err := db.Create(&inbound).Error; err != nil {
  83. t.Fatalf("seed inbound: %v", err)
  84. }
  85. preExisting := &model.ClientRecord{
  86. Email: "[email protected]",
  87. UUID: "ce8d33df-3a64-4f10-8f9b-91c3a8e0c001",
  88. SubID: "alice-sub",
  89. Enable: true,
  90. Comment: "added-via-api",
  91. }
  92. if err := db.Create(preExisting).Error; err != nil {
  93. t.Fatalf("seed client row: %v", err)
  94. }
  95. if err := db.Where("seeder_name = ?", "ClientsTable").Delete(&model.HistoryOfSeeders{}).Error; err != nil {
  96. t.Fatalf("clear ClientsTable history: %v", err)
  97. }
  98. if err := seedClientsFromInboundJSON(); err != nil {
  99. t.Fatalf("seedClientsFromInboundJSON should be idempotent against existing rows, got: %v", err)
  100. }
  101. var count int64
  102. if err := db.Model(&model.ClientRecord{}).Where("email = ?", "[email protected]").Count(&count).Error; err != nil {
  103. t.Fatalf("count clients: %v", err)
  104. }
  105. if count != 1 {
  106. t.Fatalf("[email protected] should resolve to exactly one row, got %d", count)
  107. }
  108. }
  109. func TestNormalizeInboundClientSubId_FillsMissingAndPreservesExisting(t *testing.T) {
  110. dbDir := t.TempDir()
  111. t.Setenv("XUI_DB_FOLDER", dbDir)
  112. if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
  113. t.Fatalf("InitDB failed: %v", err)
  114. }
  115. t.Cleanup(func() { _ = CloseDB() })
  116. settings, err := json.Marshal(map[string]any{
  117. "clients": []any{
  118. map[string]any{
  119. "id": "00000000-0000-0000-0000-000000000001",
  120. "email": "[email protected]",
  121. "subId": "",
  122. },
  123. map[string]any{
  124. "id": "00000000-0000-0000-0000-000000000002",
  125. "email": "[email protected]",
  126. },
  127. map[string]any{
  128. "id": "00000000-0000-0000-0000-000000000003",
  129. "email": "[email protected]",
  130. "subId": "keep-me-1234",
  131. },
  132. },
  133. })
  134. if err != nil {
  135. t.Fatalf("marshal settings: %v", err)
  136. }
  137. inbound := model.Inbound{
  138. UserId: 1,
  139. Port: 23456,
  140. Protocol: model.VLESS,
  141. Settings: string(settings),
  142. Tag: "subid-fix-inbound",
  143. }
  144. if err := db.Create(&inbound).Error; err != nil {
  145. t.Fatalf("seed inbound: %v", err)
  146. }
  147. if err := db.Where("seeder_name = ?", "InboundClientSubIdFix").Delete(&model.HistoryOfSeeders{}).Error; err != nil {
  148. t.Fatalf("clear seeder history: %v", err)
  149. }
  150. if err := normalizeInboundClientSubId(); err != nil {
  151. t.Fatalf("normalizeInboundClientSubId: %v", err)
  152. }
  153. var reloaded model.Inbound
  154. if err := db.First(&reloaded, inbound.Id).Error; err != nil {
  155. t.Fatalf("reload inbound: %v", err)
  156. }
  157. var parsed map[string]any
  158. if err := json.Unmarshal([]byte(reloaded.Settings), &parsed); err != nil {
  159. t.Fatalf("unmarshal settings: %v", err)
  160. }
  161. clients, ok := parsed["clients"].([]any)
  162. if !ok || len(clients) != 3 {
  163. t.Fatalf("expected 3 clients, got %v", parsed["clients"])
  164. }
  165. subIdPattern := regexp.MustCompile(`^[0-9a-z]{16}$`)
  166. for i := range 2 {
  167. obj := clients[i].(map[string]any)
  168. sub, _ := obj["subId"].(string)
  169. if !subIdPattern.MatchString(sub) {
  170. t.Fatalf("client %d: expected 16-char [0-9a-z] subId, got %q", i, sub)
  171. }
  172. }
  173. preserved := clients[2].(map[string]any)["subId"].(string)
  174. if preserved != "keep-me-1234" {
  175. t.Fatalf("expected existing subId preserved, got %q", preserved)
  176. }
  177. var historyCount int64
  178. if err := db.Model(&model.HistoryOfSeeders{}).Where("seeder_name = ?", "InboundClientSubIdFix").Count(&historyCount).Error; err != nil {
  179. t.Fatalf("count seeder history: %v", err)
  180. }
  181. if historyCount != 1 {
  182. t.Fatalf("expected one InboundClientSubIdFix history row, got %d", historyCount)
  183. }
  184. }
  185. func TestNormalizeSettingPaths_RepairsLegacyValues(t *testing.T) {
  186. dbDir := t.TempDir()
  187. t.Setenv("XUI_DB_FOLDER", dbDir)
  188. if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
  189. t.Fatalf("InitDB failed: %v", err)
  190. }
  191. t.Cleanup(func() { _ = CloseDB() })
  192. seed := []model.Setting{
  193. {Key: "subJsonPath", Value: "YIrCXJOOOL"},
  194. {Key: "subPath", Value: "/sub"},
  195. {Key: "subClashPath", Value: "clash/"},
  196. {Key: "webBasePath", Value: "/panel/"},
  197. }
  198. if err := db.Where("key IN ?", []string{"subPath", "subJsonPath", "subClashPath"}).Delete(&model.Setting{}).Error; err != nil {
  199. t.Fatalf("clear generated subscription paths: %v", err)
  200. }
  201. for i := range seed {
  202. if err := db.Create(&seed[i]).Error; err != nil {
  203. t.Fatalf("seed setting %s: %v", seed[i].Key, err)
  204. }
  205. }
  206. if err := normalizeSettingPaths(); err != nil {
  207. t.Fatalf("normalizeSettingPaths: %v", err)
  208. }
  209. want := map[string]string{
  210. "subJsonPath": "/YIrCXJOOOL/",
  211. "subPath": "/sub/",
  212. "subClashPath": "/clash/",
  213. "webBasePath": "/panel/",
  214. }
  215. for key, expected := range want {
  216. var row model.Setting
  217. if err := db.Where("key = ?", key).First(&row).Error; err != nil {
  218. t.Fatalf("read %s: %v", key, err)
  219. }
  220. if row.Value != expected {
  221. t.Errorf("%s = %q, want %q", key, row.Value, expected)
  222. }
  223. }
  224. }