hwid_controller_test.go 8.8 KB

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