inbound_migration_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package service
  2. import (
  3. "errors"
  4. "path/filepath"
  5. "strings"
  6. "testing"
  7. "gorm.io/gorm"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database"
  9. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  10. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  11. )
  12. // TestMigrationRequirements_BackfillsClientTrafficsWithMultiDomainInbound guards the
  13. // PostgreSQL fix where the externalProxy detection query (executed via .Scan) errored on
  14. // json_extract and rolled back the whole transaction — including the client_traffics
  15. // backfill at inbound.go:3093-3106, leaving clients with no traffic rows. A MultiDomain
  16. // inbound is present so that query returns rows and the function runs to completion; both
  17. // the backfill and the MultiDomain→ExternalProxy migration must then commit.
  18. func TestMigrationRequirements_BackfillsClientTrafficsWithMultiDomainInbound(t *testing.T) {
  19. dbDir := t.TempDir()
  20. t.Setenv("XUI_DB_FOLDER", dbDir)
  21. if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
  22. t.Fatalf("InitDB: %v", err)
  23. }
  24. t.Cleanup(func() { _ = database.CloseDB() })
  25. db := database.GetDB()
  26. const backfillEmail = "[email protected]"
  27. const uid = "ce8d33df-3a64-4f10-8f9b-91c3a8e0c010"
  28. // Inbound A: a client present only in settings.clients, with no client_traffics row.
  29. clientInbound := &model.Inbound{
  30. UserId: 1,
  31. Tag: "a-tag",
  32. Enable: true,
  33. Port: 30001,
  34. Protocol: model.VLESS,
  35. Settings: `{"clients":[{"email":"` + backfillEmail + `","id":"` + uid + `","enable":true}]}`,
  36. StreamSettings: `{"network":"tcp","security":"none"}`,
  37. }
  38. if err := db.Create(clientInbound).Error; err != nil {
  39. t.Fatalf("create client inbound: %v", err)
  40. }
  41. // Inbound B: a legacy MultiDomain inbound whose tag carries the 0.0.0.0: prefix.
  42. // Its presence makes the externalProxy query return rows, so the function does not
  43. // early-return and reaches the tag-cleanup statement.
  44. multiDomainInbound := &model.Inbound{
  45. UserId: 1,
  46. Tag: "inbound-0.0.0.0:30002",
  47. Enable: true,
  48. Port: 30002,
  49. Protocol: model.VLESS,
  50. Settings: `{"clients":[]}`,
  51. StreamSettings: `{"security":"tls","tlsSettings":{"settings":{"domains":[{"domain":"example.com"}]}}}`,
  52. }
  53. if err := db.Create(multiDomainInbound).Error; err != nil {
  54. t.Fatalf("create multidomain inbound: %v", err)
  55. }
  56. var before int64
  57. if err := db.Model(xray.ClientTraffic{}).Count(&before).Error; err != nil {
  58. t.Fatalf("count client_traffics before: %v", err)
  59. }
  60. if before != 0 {
  61. t.Fatalf("expected no client_traffics before migration, got %d", before)
  62. }
  63. svc := InboundService{}
  64. svc.MigrationRequirements()
  65. // The backfill must have committed: the settings-only client now owns a row.
  66. // Before the fix this was rolled back whenever the externalProxy detection query
  67. // errored (it does on Postgres via json_extract), so the MultiDomain inbound below
  68. // is deliberately present to make that query return rows and run to completion.
  69. var ct xray.ClientTraffic
  70. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", backfillEmail).First(&ct).Error; err != nil {
  71. t.Fatalf("client_traffics row not backfilled for %s: %v", backfillEmail, err)
  72. }
  73. // The MultiDomain→ExternalProxy migration must have committed too: the detection
  74. // query ran (.Scan executes it) and the loop rewrote the inbound's streamSettings.
  75. var refreshed model.Inbound
  76. if err := db.First(&refreshed, multiDomainInbound.Id).Error; err != nil {
  77. t.Fatalf("reload multidomain inbound: %v", err)
  78. }
  79. if !strings.Contains(refreshed.StreamSettings, "externalProxy") {
  80. t.Errorf("MultiDomain migration did not commit; streamSettings = %q", refreshed.StreamSettings)
  81. }
  82. }
  83. func TestMigrationRequirementsReturnsAddClientStatFailure(t *testing.T) {
  84. dbDir := t.TempDir()
  85. t.Setenv("XUI_DB_FOLDER", dbDir)
  86. if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
  87. t.Fatalf("InitDB: %v", err)
  88. }
  89. t.Cleanup(func() { _ = database.CloseDB() })
  90. db := database.GetDB()
  91. first := &model.Inbound{UserId: 1, Tag: "first", Port: 31001, Protocol: model.VLESS, Settings: `{"clients":[{"email":"[email protected]","id":"id-1"}]}`, StreamSettings: `{}`}
  92. if err := db.Create(first).Error; err != nil {
  93. t.Fatalf("create first: %v", err)
  94. }
  95. const injected = "injected AddClientStat failure"
  96. failSave := func(tx *gorm.DB) {
  97. tx.AddError(errors.New(injected))
  98. }
  99. if err := db.Callback().Update().Before("gorm:update").Register("test:fail-migration-inbound-save", failSave); err != nil {
  100. t.Fatalf("register update callback: %v", err)
  101. }
  102. if err := db.Callback().Create().Before("gorm:create").Register("test:fail-migration-inbound-save", failSave); err != nil {
  103. t.Fatalf("register create callback: %v", err)
  104. }
  105. err := (&InboundService{}).MigrationRequirements()
  106. if err == nil || err.Error() != injected {
  107. t.Fatalf("MigrationRequirements error = %v, want %q", err, injected)
  108. }
  109. var count int64
  110. if err := db.Model(&xray.ClientTraffic{}).Where("email = ?", "[email protected]").Count(&count).Error; err != nil {
  111. t.Fatalf("count rolled-back traffic: %v", err)
  112. }
  113. if count != 0 {
  114. t.Fatalf("earlier traffic write committed after save failure: count=%d", count)
  115. }
  116. }
  117. // TestMigrationRequirements_CleansLegacyZeroAddrTag guards the legacy tag cleanup that
  118. // strips the auto-generated "0.0.0.0:" prefix. The inbound is MultiDomain TLS so the
  119. // externalProxy detection query returns rows and the cleanup is reached (it early-returns
  120. // at len(externalProxy)==0 otherwise). The cleanup must use tx.Exec, not tx.Raw, which
  121. // only builds a non-SELECT statement without running it.
  122. func TestMigrationRequirements_CleansLegacyZeroAddrTag(t *testing.T) {
  123. dbDir := t.TempDir()
  124. t.Setenv("XUI_DB_FOLDER", dbDir)
  125. if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
  126. t.Fatalf("InitDB: %v", err)
  127. }
  128. t.Cleanup(func() { _ = database.CloseDB() })
  129. db := database.GetDB()
  130. legacy := &model.Inbound{
  131. UserId: 1,
  132. Tag: "inbound-0.0.0.0:30002",
  133. Enable: true,
  134. Port: 30002,
  135. Protocol: model.VLESS,
  136. Settings: `{"clients":[]}`,
  137. StreamSettings: `{"security":"tls","tlsSettings":{"settings":{"domains":[{"domain":"example.com"}]}}}`,
  138. }
  139. if err := db.Create(legacy).Error; err != nil {
  140. t.Fatalf("create legacy inbound: %v", err)
  141. }
  142. svc := InboundService{}
  143. svc.MigrationRequirements()
  144. var got model.Inbound
  145. if err := db.First(&got, legacy.Id).Error; err != nil {
  146. t.Fatalf("reload inbound: %v", err)
  147. }
  148. if got.Tag != "inbound-30002" {
  149. t.Fatalf("legacy 0.0.0.0: tag not stripped: got %q, want %q", got.Tag, "inbound-30002")
  150. }
  151. }
  152. func TestMigrationRemoveOrphanedTraffics(t *testing.T) {
  153. setupConflictDB(t)
  154. db := database.GetDB()
  155. clientSvc := &ClientService{}
  156. inboundSvc := &InboundService{}
  157. const attachedEmail = "[email protected]"
  158. attachedClient := model.Client{Email: attachedEmail, ID: "11111111-1111-1111-1111-111111111111", SubID: attachedEmail, Enable: true}
  159. attachedIb := mkInbound(t, 30003, model.VLESS, clientsSettings(t, []model.Client{attachedClient}))
  160. if err := clientSvc.SyncInbound(nil, attachedIb.Id, []model.Client{attachedClient}); err != nil {
  161. t.Fatalf("seed attached client: %v", err)
  162. }
  163. mkTraffic(t, attachedIb.Id, attachedEmail, 0, 0, 0, 0, true)
  164. const detachedEmail = "[email protected]"
  165. detachedClient := model.Client{Email: detachedEmail, ID: "22222222-2222-2222-2222-222222222222", SubID: detachedEmail, Enable: true}
  166. detachedIb := mkInbound(t, 30004, model.VLESS, clientsSettings(t, []model.Client{detachedClient}))
  167. if err := clientSvc.SyncInbound(nil, detachedIb.Id, []model.Client{detachedClient}); err != nil {
  168. t.Fatalf("seed detached client: %v", err)
  169. }
  170. mkTraffic(t, detachedIb.Id, detachedEmail, 123, 456, 0, 0, true)
  171. detachedRec := lookupClientRecord(t, detachedEmail)
  172. if _, err := clientSvc.Detach(inboundSvc, detachedRec.Id, []int{detachedIb.Id}); err != nil {
  173. t.Fatalf("Detach: %v", err)
  174. }
  175. const jsonOnlyEmail = "[email protected]"
  176. jsonOnlyClient := model.Client{Email: jsonOnlyEmail, ID: "33333333-3333-3333-3333-333333333333", SubID: jsonOnlyEmail, Enable: true}
  177. jsonOnlyIb := mkInbound(t, 30005, model.VLESS, clientsSettings(t, []model.Client{jsonOnlyClient}))
  178. mkTraffic(t, jsonOnlyIb.Id, jsonOnlyEmail, 0, 0, 0, 0, true)
  179. const trulyOrphanedEmail = "[email protected]"
  180. mkTraffic(t, attachedIb.Id, trulyOrphanedEmail, 0, 0, 0, 0, true)
  181. inboundSvc.MigrationRemoveOrphanedTraffics()
  182. cases := []struct {
  183. name string
  184. email string
  185. want int64
  186. }{
  187. {"attached, in clients table and JSON", attachedEmail, 1},
  188. {"detached-but-alive, in clients table only", detachedEmail, 1},
  189. {"seeder-skipped-but-live, in JSON only", jsonOnlyEmail, 1},
  190. {"truly orphaned, in neither", trulyOrphanedEmail, 0},
  191. }
  192. for _, c := range cases {
  193. t.Run(c.name, func(t *testing.T) {
  194. var got int64
  195. if err := db.Model(xray.ClientTraffic{}).Where("email = ?", c.email).Count(&got).Error; err != nil {
  196. t.Fatalf("count client_traffics for %s: %v", c.email, err)
  197. }
  198. if got != c.want {
  199. t.Errorf("client_traffics count for %s: got %d, want %d", c.email, got, c.want)
  200. }
  201. })
  202. }
  203. }
  204. func TestMigrationRequirements_NormalizesShareAddressFields(t *testing.T) {
  205. setupConflictDB(t)
  206. db := database.GetDB()
  207. invalidStrategy := &model.Inbound{
  208. UserId: 1,
  209. Tag: "invalid-share-strategy",
  210. Enable: true,
  211. Port: 31001,
  212. Protocol: model.VLESS,
  213. Settings: `{"clients":[]}`,
  214. StreamSettings: `{"network":"tcp","security":"none"}`,
  215. }
  216. paddedStrategy := &model.Inbound{
  217. UserId: 1,
  218. Tag: "padded-share-strategy",
  219. Enable: true,
  220. Port: 31002,
  221. Protocol: model.VLESS,
  222. Settings: `{"clients":[]}`,
  223. StreamSettings: `{"network":"tcp","security":"none"}`,
  224. }
  225. invalidAddress := &model.Inbound{
  226. UserId: 1,
  227. Tag: "invalid-share-address",
  228. Enable: true,
  229. Port: 31003,
  230. Protocol: model.VLESS,
  231. Settings: `{"clients":[]}`,
  232. StreamSettings: `{"network":"tcp","security":"none"}`,
  233. }
  234. if err := db.Create(invalidStrategy).Error; err != nil {
  235. t.Fatalf("create invalid strategy inbound: %v", err)
  236. }
  237. if err := db.Create(paddedStrategy).Error; err != nil {
  238. t.Fatalf("create padded strategy inbound: %v", err)
  239. }
  240. if err := db.Create(invalidAddress).Error; err != nil {
  241. t.Fatalf("create invalid address inbound: %v", err)
  242. }
  243. if err := db.Model(&model.Inbound{}).Where("id = ?", invalidStrategy.Id).Updates(map[string]any{
  244. "share_addr_strategy": " auto ",
  245. "share_addr": " edge.example.com ",
  246. }).Error; err != nil {
  247. t.Fatalf("seed invalid share fields: %v", err)
  248. }
  249. if err := db.Model(&model.Inbound{}).Where("id = ?", paddedStrategy.Id).Updates(map[string]any{
  250. "share_addr_strategy": " listen ",
  251. "share_addr": " 10.0.0.1 ",
  252. }).Error; err != nil {
  253. t.Fatalf("seed padded share fields: %v", err)
  254. }
  255. if err := db.Model(&model.Inbound{}).Where("id = ?", invalidAddress.Id).Updates(map[string]any{
  256. "share_addr_strategy": "custom",
  257. "share_addr": "edge.example.com:8443",
  258. }).Error; err != nil {
  259. t.Fatalf("seed invalid address share fields: %v", err)
  260. }
  261. svc := InboundService{}
  262. svc.MigrationRequirements()
  263. var gotInvalid model.Inbound
  264. if err := db.First(&gotInvalid, invalidStrategy.Id).Error; err != nil {
  265. t.Fatalf("reload invalid strategy inbound: %v", err)
  266. }
  267. if gotInvalid.ShareAddrStrategy != "node" || gotInvalid.ShareAddr != "edge.example.com" {
  268. t.Fatalf("invalid share fields = (%q, %q), want (node, edge.example.com)", gotInvalid.ShareAddrStrategy, gotInvalid.ShareAddr)
  269. }
  270. var gotPadded model.Inbound
  271. if err := db.First(&gotPadded, paddedStrategy.Id).Error; err != nil {
  272. t.Fatalf("reload padded strategy inbound: %v", err)
  273. }
  274. if gotPadded.ShareAddrStrategy != "listen" || gotPadded.ShareAddr != "10.0.0.1" {
  275. t.Fatalf("padded share fields = (%q, %q), want (listen, 10.0.0.1)", gotPadded.ShareAddrStrategy, gotPadded.ShareAddr)
  276. }
  277. var gotInvalidAddress model.Inbound
  278. if err := db.First(&gotInvalidAddress, invalidAddress.Id).Error; err != nil {
  279. t.Fatalf("reload invalid address inbound: %v", err)
  280. }
  281. if gotInvalidAddress.ShareAddrStrategy != "node" || gotInvalidAddress.ShareAddr != "" {
  282. t.Fatalf("invalid address share fields = (%q, %q), want (node, empty)", gotInvalidAddress.ShareAddrStrategy, gotInvalidAddress.ShareAddr)
  283. }
  284. }