hwid_controller_test.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package sub
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "os"
  7. "path/filepath"
  8. "reflect"
  9. "testing"
  10. "github.com/gin-gonic/gin"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  13. )
  14. func initHwidSubRouter(t *testing.T, limit int) (*gin.Engine, string) {
  15. t.Helper()
  16. tmp := t.TempDir()
  17. t.Chdir(tmp)
  18. if err := os.MkdirAll("internal/web/dist", 0o755); err != nil {
  19. t.Fatalf("mkdir dist: %v", err)
  20. }
  21. if err := os.WriteFile("internal/web/dist/subpage.html", []byte("<html><head></head><body></body></html>"), 0o644); err != nil {
  22. t.Fatalf("write subpage: %v", err)
  23. }
  24. t.Setenv("XUI_DB_FOLDER", tmp)
  25. if err := database.InitDB(filepath.Join(tmp, "x-ui.db")); err != nil {
  26. t.Fatalf("InitDB: %v", err)
  27. }
  28. t.Cleanup(func() { _ = database.CloseDB() })
  29. const subID = "sub-hwid-route"
  30. const email = "[email protected]"
  31. const uuid = "11111111-2222-4333-8444-555555555555"
  32. db := database.GetDB()
  33. ib := &model.Inbound{
  34. UserId: 1,
  35. Tag: "hwid-sub",
  36. Enable: true,
  37. Port: 443,
  38. Protocol: model.VLESS,
  39. Settings: `{"clients":[]}`,
  40. StreamSettings: `{"network":"tcp","security":"none"}`,
  41. }
  42. if err := db.Create(ib).Error; err != nil {
  43. t.Fatalf("seed inbound: %v", err)
  44. }
  45. client := &model.ClientRecord{Email: email, SubID: subID, UUID: uuid, Enable: true, LimitHwid: limit}
  46. if err := db.Create(client).Error; err != nil {
  47. t.Fatalf("seed client: %v", err)
  48. }
  49. if err := db.Create(&model.ClientInbound{ClientId: client.Id, InboundId: ib.Id}).Error; err != nil {
  50. t.Fatalf("seed client inbound: %v", err)
  51. }
  52. gin.SetMode(gin.TestMode)
  53. router := gin.New()
  54. NewSUBController(
  55. router.Group("/"),
  56. WithSUBPath("/sub/"),
  57. WithSUBJsonPath("/json/"),
  58. WithSUBClashPath("/clash/"),
  59. WithSUBClashAutoDetect(true),
  60. WithSUBJsonAutoDetect(true),
  61. WithSUBJsonEnabled(true),
  62. WithSUBClashEnabled(true),
  63. )
  64. return router, subID
  65. }
  66. func requestSub(t *testing.T, router *gin.Engine, method string, path string, hwid string, accept string) *httptest.ResponseRecorder {
  67. t.Helper()
  68. req := httptest.NewRequest(method, path, nil)
  69. req.Host = "sub.example.com"
  70. if hwid != "" {
  71. req.Header.Set("X-HWID", hwid)
  72. }
  73. if accept != "" {
  74. req.Header.Set("Accept", accept)
  75. }
  76. rec := httptest.NewRecorder()
  77. router.ServeHTTP(rec, req)
  78. return rec
  79. }
  80. func TestSubscriptionHwidGateAcrossBodyRoutes(t *testing.T) {
  81. router, subID := initHwidSubRouter(t, 1)
  82. // ?view=raw only tells /json/ and /clash/ to serve the body instead of the
  83. // HTML page, so it stays gated like the plain route (#GHSA-7ww3).
  84. bodyRoutes := []string{
  85. "/sub/" + subID,
  86. "/json/" + subID,
  87. "/clash/" + subID,
  88. "/json/" + subID + "?view=raw",
  89. "/clash/" + subID + "?view=RaW",
  90. }
  91. for _, path := range bodyRoutes {
  92. rec := requestSub(t, router, http.MethodGet, path, "", "")
  93. if rec.Code != http.StatusNotFound {
  94. t.Fatalf("%s missing HWID status = %d, want 404", path, rec.Code)
  95. }
  96. if rec.Header().Get("X-Hwid-Active") != "true" || rec.Header().Get("X-Hwid-Not-Supported") != "true" {
  97. t.Fatalf("%s missing HWID headers = %#v", path, rec.Header())
  98. }
  99. }
  100. rec := requestSub(t, router, http.MethodHead, "/sub/"+subID, "", "")
  101. if rec.Code != http.StatusNotFound || rec.Header().Get("X-Hwid-Not-Supported") != "true" {
  102. t.Fatalf("HEAD missing HWID = %d %#v", rec.Code, rec.Header())
  103. }
  104. for _, path := range bodyRoutes {
  105. rec = requestSub(t, router, http.MethodGet, path, "device-one", "")
  106. if rec.Code != http.StatusOK {
  107. t.Fatalf("%s registered HWID status = %d, body=%q", path, rec.Code, rec.Body.String())
  108. }
  109. if rec.Header().Get("X-Hwid-Active") != "true" {
  110. t.Fatalf("%s allowed response missing active HWID header", path)
  111. }
  112. }
  113. for _, path := range bodyRoutes {
  114. rec = requestSub(t, router, http.MethodGet, path, "device-two", "")
  115. if rec.Code != http.StatusNotFound {
  116. t.Fatalf("%s new HWID after limit status = %d, want 404", path, rec.Code)
  117. }
  118. if rec.Header().Get("X-Hwid-Max-Devices-Reached") != "true" || rec.Header().Get("X-Hwid-Limit") != "true" {
  119. t.Fatalf("%s limit headers missing: %#v", path, rec.Header())
  120. }
  121. }
  122. }
  123. func TestSubscriptionHwidGateSkipsHtmlInfoPage(t *testing.T) {
  124. router, subID := initHwidSubRouter(t, 1)
  125. rec := requestSub(t, router, http.MethodGet, "/sub/"+subID, "", "text/html")
  126. if rec.Code != http.StatusOK {
  127. t.Fatalf("HTML sub page status = %d, want 200, body=%q", rec.Code, rec.Body.String())
  128. }
  129. if rec.Header().Get("X-Hwid-Not-Supported") != "" {
  130. t.Fatalf("HTML sub page should not be HWID-gated: %#v", rec.Header())
  131. }
  132. }
  133. // Decoding into a map rather than the service struct keeps the exact field set
  134. // asserted, so an extra field leaking into the response fails the test.
  135. func assertHwidStatus(t *testing.T, rec *httptest.ResponseRecorder, active bool, limit, registered, remaining int, full bool) {
  136. t.Helper()
  137. if rec.Code != http.StatusOK {
  138. t.Fatalf("hwid-status status = %d, body=%q", rec.Code, rec.Body.String())
  139. }
  140. var got map[string]any
  141. if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
  142. t.Fatalf("decode hwid-status body %q: %v", rec.Body.String(), err)
  143. }
  144. want := map[string]any{
  145. "active": active,
  146. "limit": float64(limit),
  147. "registered": float64(registered),
  148. "remaining": float64(remaining),
  149. "full": full,
  150. }
  151. if len(got) != len(want) {
  152. t.Fatalf("hwid-status fields = %#v, want exactly %#v", got, want)
  153. }
  154. for key, value := range want {
  155. if got[key] != value {
  156. t.Fatalf("hwid-status[%q] = %#v, want %#v (body %#v)", key, got[key], value, got)
  157. }
  158. }
  159. }
  160. func TestSubscriptionHwidStatusCountsRegisteredDevices(t *testing.T) {
  161. router, subID := initHwidSubRouter(t, 2)
  162. statusPath := "/sub/" + subID + "/hwid-status"
  163. assertHwidStatus(t, requestSub(t, router, http.MethodGet, statusPath, "", ""), true, 2, 0, 2, false)
  164. for i, hwid := range []string{"device-one", "device-two"} {
  165. if rec := requestSub(t, router, http.MethodGet, "/sub/"+subID, hwid, ""); rec.Code != http.StatusOK {
  166. t.Fatalf("register %s = %d, want 200", hwid, rec.Code)
  167. }
  168. registered := i + 1
  169. rec := requestSub(t, router, http.MethodGet, statusPath, "", "")
  170. assertHwidStatus(t, rec, true, 2, registered, 2-registered, registered == 2)
  171. }
  172. if rec := requestSub(t, router, http.MethodHead, statusPath, "", ""); rec.Code != http.StatusOK {
  173. t.Fatalf("HEAD hwid-status = %d, want 200", rec.Code)
  174. }
  175. }
  176. // The endpoint must stay SELECT-only: asking about slots while carrying an
  177. // X-HWID header must not spend the slot the caller is asking about.
  178. func TestSubscriptionHwidStatusDoesNotRegisterDevice(t *testing.T) {
  179. router, subID := initHwidSubRouter(t, 1)
  180. rec := requestSub(t, router, http.MethodGet, "/sub/"+subID+"/hwid-status", "device-probe", "")
  181. assertHwidStatus(t, rec, true, 1, 0, 1, false)
  182. for _, header := range []string{"X-Hwid-Active", "X-Hwid-Limit", "X-Hwid-Not-Supported", "X-Hwid-Max-Devices-Reached"} {
  183. if value := rec.Header().Get(header); value != "" {
  184. t.Fatalf("hwid-status leaked gate header %s = %q", header, value)
  185. }
  186. }
  187. var count int64
  188. if err := database.GetDB().Model(&model.ClientHwid{}).Where("sub_id = ?", subID).Count(&count).Error; err != nil {
  189. t.Fatalf("count hwids: %v", err)
  190. }
  191. if count != 0 {
  192. t.Fatalf("client_hwids rows after status probe = %d, want 0", count)
  193. }
  194. if rec := requestSub(t, router, http.MethodGet, "/sub/"+subID, "device-probe", ""); rec.Code != http.StatusOK {
  195. t.Fatalf("subscription fetch after probe = %d, want 200", rec.Code)
  196. }
  197. }
  198. func TestSubscriptionHwidStatusWithoutLimit(t *testing.T) {
  199. router, subID := initHwidSubRouter(t, 0)
  200. assertHwidStatus(t, requestSub(t, router, http.MethodGet, "/sub/"+subID+"/hwid-status", "", ""), false, 0, 0, 0, false)
  201. }
  202. // An unknown and a disabled subscription must be indistinguishable, so a
  203. // caller cannot probe which subscription ids exist.
  204. func TestSubscriptionHwidStatusHidesUnknownVersusDisabled(t *testing.T) {
  205. router, subID := initHwidSubRouter(t, 1)
  206. unknown := requestSub(t, router, http.MethodGet, "/sub/does-not-exist/hwid-status", "", "")
  207. if unknown.Code != http.StatusNotFound {
  208. t.Fatalf("unknown subId status = %d, want 404", unknown.Code)
  209. }
  210. if err := database.GetDB().Model(&model.ClientRecord{}).
  211. Where("sub_id = ?", subID).
  212. UpdateColumn("enable", false).Error; err != nil {
  213. t.Fatalf("disable client: %v", err)
  214. }
  215. disabled := requestSub(t, router, http.MethodGet, "/sub/"+subID+"/hwid-status", "", "")
  216. if disabled.Code != unknown.Code {
  217. t.Fatalf("disabled status = %d, unknown status = %d, want identical", disabled.Code, unknown.Code)
  218. }
  219. if disabled.Body.String() != unknown.Body.String() {
  220. t.Fatalf("disabled body = %q, unknown body = %q, want identical", disabled.Body.String(), unknown.Body.String())
  221. }
  222. if !reflect.DeepEqual(disabled.Header(), unknown.Header()) {
  223. t.Fatalf("disabled headers = %#v, unknown headers = %#v, want identical", disabled.Header(), unknown.Header())
  224. }
  225. if disabled.Body.Len() != 0 {
  226. t.Fatalf("404 body = %q, want empty", disabled.Body.String())
  227. }
  228. }