client_hwid_test.go 10 KB

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