client_hwid_test.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. package service
  2. import (
  3. "path/filepath"
  4. "testing"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  7. )
  8. func initClientHwidTestDB(t *testing.T) {
  9. t.Helper()
  10. dbDir := t.TempDir()
  11. t.Setenv("XUI_DB_FOLDER", dbDir)
  12. if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
  13. t.Fatalf("InitDB: %v", err)
  14. }
  15. t.Cleanup(func() { _ = database.CloseDB() })
  16. }
  17. func seedHwidClient(t *testing.T, limit int) *model.ClientRecord {
  18. t.Helper()
  19. rec := &model.ClientRecord{
  20. Email: "[email protected]",
  21. SubID: "sub-hwid",
  22. UUID: "11111111-2222-4333-8444-555555555555",
  23. Enable: true,
  24. LimitHwid: limit,
  25. }
  26. if err := database.GetDB().Create(rec).Error; err != nil {
  27. t.Fatalf("seed client: %v", err)
  28. }
  29. return rec
  30. }
  31. func TestClientHwidGate(t *testing.T) {
  32. initClientHwidTestDB(t)
  33. svc := &ClientService{}
  34. seedHwidClient(t, 0)
  35. res, err := svc.EnforceHwidForSubID("sub-hwid", HwidRequest{})
  36. if err != nil {
  37. t.Fatalf("no-limit gate: %v", err)
  38. }
  39. if !res.Allowed || res.Active {
  40. t.Fatalf("no limit should allow missing HWID without active headers: %+v", res)
  41. }
  42. }
  43. func TestClientHwidGateRegistersAndBlocks(t *testing.T) {
  44. initClientHwidTestDB(t)
  45. svc := &ClientService{}
  46. rec := seedHwidClient(t, 2)
  47. res, err := svc.EnforceHwidForSubID(rec.SubID, HwidRequest{})
  48. if err != nil {
  49. t.Fatalf("missing HWID gate: %v", err)
  50. }
  51. if res.Allowed || !res.Active || !res.NotSupported {
  52. t.Fatalf("missing HWID should be denied as not supported: %+v", res)
  53. }
  54. firstRaw := "device-one"
  55. for _, raw := range []string{firstRaw, "device-two"} {
  56. res, err = svc.EnforceHwidForSubID(rec.SubID, HwidRequest{
  57. Hwid: raw,
  58. UserAgent: "Happ/1.0",
  59. DeviceOS: "android",
  60. OsVersion: "15",
  61. DeviceModel: raw + "-model",
  62. })
  63. if err != nil {
  64. t.Fatalf("register %s: %v", raw, err)
  65. }
  66. if !res.Allowed {
  67. t.Fatalf("register %s denied: %+v", raw, res)
  68. }
  69. }
  70. res, err = svc.EnforceHwidForSubID(rec.SubID, HwidRequest{Hwid: "device-three"})
  71. if err != nil {
  72. t.Fatalf("third HWID gate: %v", err)
  73. }
  74. if res.Allowed || !res.MaxDevicesReached || !res.LimitReached {
  75. t.Fatalf("third unique HWID should be denied after limit: %+v", res)
  76. }
  77. res, err = svc.EnforceHwidForSubID(rec.SubID, HwidRequest{
  78. Hwid: firstRaw,
  79. UserAgent: "Karing/2.0",
  80. DeviceOS: "ios",
  81. OsVersion: "18",
  82. DeviceModel: "updated-model",
  83. })
  84. if err != nil {
  85. t.Fatalf("existing HWID after full limit: %v", err)
  86. }
  87. if !res.Allowed || !res.LimitReached {
  88. t.Fatalf("existing registered HWID should pass after limit: %+v", res)
  89. }
  90. var hashes []string
  91. if err := database.GetDB().Model(&model.ClientHwid{}).Pluck("hwid_hash", &hashes).Error; err != nil {
  92. t.Fatalf("pluck hashes: %v", err)
  93. }
  94. if len(hashes) != 2 {
  95. t.Fatalf("stored HWIDs = %d, want 2", len(hashes))
  96. }
  97. for _, h := range hashes {
  98. if h == firstRaw || h == "device-two" || len(h) != 64 {
  99. t.Fatalf("raw HWID leaked or invalid hash stored: %q", h)
  100. }
  101. }
  102. list, err := svc.ListClientHwids(rec.Email)
  103. if err != nil {
  104. t.Fatalf("list HWIDs: %v", err)
  105. }
  106. if len(list) != 2 {
  107. t.Fatalf("list count = %d, want 2", len(list))
  108. }
  109. foundUpdated := false
  110. for _, row := range list {
  111. if len(row.Fingerprint) != hwidFingerprintLength {
  112. t.Fatalf("fingerprint length = %d, want %d: %q", len(row.Fingerprint), hwidFingerprintLength, row.Fingerprint)
  113. }
  114. if row.DeviceModel == "updated-model" && row.UserAgent == "Karing/2.0" && row.DeviceOS == "ios" && row.OsVersion == "18" {
  115. foundUpdated = true
  116. want := hashHwid(firstRaw)[:hwidFingerprintLength]
  117. if row.Fingerprint != want {
  118. t.Fatalf("fingerprint = %q, want %q", row.Fingerprint, want)
  119. }
  120. }
  121. }
  122. if !foundUpdated {
  123. t.Fatalf("updated HWID metadata missing: %#v", list)
  124. }
  125. if err := svc.setClientLimitHwidByEmail(nil, rec.Email, 1); err != nil {
  126. t.Fatalf("lower limit: %v", err)
  127. }
  128. var count int64
  129. if err := database.GetDB().Model(&model.ClientHwid{}).Where("sub_id = ?", rec.SubID).Count(&count).Error; err != nil {
  130. t.Fatalf("count after trim: %v", err)
  131. }
  132. if count != 1 {
  133. t.Fatalf("lowered limit should trim stored HWIDs to 1, got %d", count)
  134. }
  135. if err := svc.ClearClientHwids(rec.Email); err != nil {
  136. t.Fatalf("clear HWIDs: %v", err)
  137. }
  138. if err := database.GetDB().Model(&model.ClientHwid{}).Where("sub_id = ?", rec.SubID).Count(&count).Error; err != nil {
  139. t.Fatalf("count after clear: %v", err)
  140. }
  141. if count != 0 {
  142. t.Fatalf("clear should remove all HWIDs, got %d", count)
  143. }
  144. }
  145. func TestDeleteClientHwid(t *testing.T) {
  146. initClientHwidTestDB(t)
  147. svc := &ClientService{}
  148. db := database.GetDB()
  149. rec := seedHwidClient(t, 5)
  150. if _, err := svc.EnforceHwidForSubID(rec.SubID, HwidRequest{Hwid: "device-own"}); err != nil {
  151. t.Fatalf("register own device: %v", err)
  152. }
  153. list, err := svc.ListClientHwids(rec.Email)
  154. if err != nil || len(list) != 1 {
  155. t.Fatalf("list own devices: err=%v list=%+v", err, list)
  156. }
  157. ownID := list[0].Id
  158. other := &model.ClientRecord{Email: "[email protected]", SubID: "sub-other", UUID: "33333333-2222-4333-8444-555555555555", Enable: true, LimitHwid: 5}
  159. if err := db.Create(other).Error; err != nil {
  160. t.Fatalf("seed other client: %v", err)
  161. }
  162. if _, err := svc.EnforceHwidForSubID(other.SubID, HwidRequest{Hwid: "device-foreign"}); err != nil {
  163. t.Fatalf("register foreign device: %v", err)
  164. }
  165. otherList, err := svc.ListClientHwids(other.Email)
  166. if err != nil || len(otherList) != 1 {
  167. t.Fatalf("list foreign devices: err=%v list=%+v", err, otherList)
  168. }
  169. foreignID := otherList[0].Id
  170. if err := svc.DeleteClientHwid(rec.Email, foreignID); err == nil {
  171. t.Fatalf("deleting a foreign sub_id's device id should fail")
  172. }
  173. if list, err := svc.ListClientHwids(other.Email); err != nil || len(list) != 1 {
  174. t.Fatalf("foreign device should survive a cross-sub_id delete attempt: err=%v list=%+v", err, list)
  175. }
  176. if err := svc.DeleteClientHwid(rec.Email, 999999); err == nil {
  177. t.Fatalf("deleting an unknown id should fail")
  178. }
  179. if err := svc.DeleteClientHwid(rec.Email, ownID); err != nil {
  180. t.Fatalf("delete own device: %v", err)
  181. }
  182. if list, err := svc.ListClientHwids(rec.Email); err != nil || len(list) != 0 {
  183. t.Fatalf("own device should be gone: err=%v list=%+v", err, list)
  184. }
  185. }
  186. func TestClientHwidGateSharedSubIdUsesMaxLimit(t *testing.T) {
  187. initClientHwidTestDB(t)
  188. svc := &ClientService{}
  189. db := database.GetDB()
  190. subID := "shared-sub"
  191. if err := db.Create(&model.ClientRecord{Email: "[email protected]", SubID: subID, UUID: "11111111-2222-4333-8444-555555555555", Enable: true, LimitHwid: 0}).Error; err != nil {
  192. t.Fatalf("seed anchor: %v", err)
  193. }
  194. if err := db.Create(&model.ClientRecord{Email: "[email protected]", SubID: subID, UUID: "22222222-2222-4333-8444-555555555555", Enable: true, LimitHwid: 2}).Error; err != nil {
  195. t.Fatalf("seed second: %v", err)
  196. }
  197. res, err := svc.EnforceHwidForSubID(subID, HwidRequest{})
  198. if err != nil || !res.Active || res.Limit != 2 {
  199. t.Fatalf("expected active gate limit 2 from max row, err=%v res=%+v", err, res)
  200. }
  201. if res.Allowed || !res.NotSupported {
  202. t.Fatalf("missing HWID should be denied: %+v", res)
  203. }
  204. }
  205. func TestClientHwidSlotStatus(t *testing.T) {
  206. initClientHwidTestDB(t)
  207. svc := &ClientService{}
  208. db := database.GetDB()
  209. rec := seedHwidClient(t, 1)
  210. status, found, err := svc.HwidSlotStatusForSubID("no-such-sub")
  211. if err != nil || found || status != (HwidSlotStatus{}) {
  212. t.Fatalf("unknown subId = (%+v, %v, %v), want zero status and found=false", status, found, err)
  213. }
  214. status, found, err = svc.HwidSlotStatusForSubID(" " + rec.SubID + " ")
  215. if err != nil || !found {
  216. t.Fatalf("padded subId = (%+v, %v, %v), want found=true", status, found, err)
  217. }
  218. if want := (HwidSlotStatus{Active: true, Limit: 1, Remaining: 1}); status != want {
  219. t.Fatalf("empty slots = %+v, want %+v", status, want)
  220. }
  221. // A shared sub_id takes the highest limit, matching the enforcement gate.
  222. if err := db.Create(&model.ClientRecord{Email: "[email protected]", SubID: rec.SubID, UUID: "22222222-2222-4333-8444-555555555555", Enable: true, LimitHwid: 3}).Error; err != nil {
  223. t.Fatalf("seed second client: %v", err)
  224. }
  225. for _, hwid := range []string{"device-one", "device-two", "device-three"} {
  226. if _, err := svc.EnforceHwidForSubID(rec.SubID, HwidRequest{Hwid: hwid}); err != nil {
  227. t.Fatalf("register %s: %v", hwid, err)
  228. }
  229. }
  230. status, found, err = svc.HwidSlotStatusForSubID(rec.SubID)
  231. if err != nil || !found {
  232. t.Fatalf("shared subId = (%+v, %v, %v), want found=true", status, found, err)
  233. }
  234. if want := (HwidSlotStatus{Active: true, Limit: 3, Registered: 3, Full: true}); status != want {
  235. t.Fatalf("full slots = %+v, want %+v", status, want)
  236. }
  237. // Deleting the highest-limit client drops the effective limit below the
  238. // registered count, and remaining must clamp at zero instead of going negative.
  239. if err := db.Where("email = ?", "[email protected]").Delete(&model.ClientRecord{}).Error; err != nil {
  240. t.Fatalf("delete second client: %v", err)
  241. }
  242. status, _, err = svc.HwidSlotStatusForSubID(rec.SubID)
  243. if err != nil {
  244. t.Fatalf("lowered limit: %v", err)
  245. }
  246. if want := (HwidSlotStatus{Active: true, Limit: 1, Registered: 3, Remaining: 0, Full: true}); status != want {
  247. t.Fatalf("over-limit slots = %+v, want %+v", status, want)
  248. }
  249. if err := db.Model(&model.ClientRecord{}).Where("sub_id = ?", rec.SubID).UpdateColumn("enable", false).Error; err != nil {
  250. t.Fatalf("disable clients: %v", err)
  251. }
  252. status, found, err = svc.HwidSlotStatusForSubID(rec.SubID)
  253. if err != nil || found || status != (HwidSlotStatus{}) {
  254. t.Fatalf("disabled subId = (%+v, %v, %v), want zero status and found=false", status, found, err)
  255. }
  256. }