external_hwid_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package sub
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "path/filepath"
  6. "testing"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  9. )
  10. // #6559: the Master panel must send a stable X-HWID when fetching external
  11. // subscriptions, otherwise an HWID-limited donor answers 404.
  12. func TestServerHwidStableAcrossCalls(t *testing.T) {
  13. if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
  14. t.Fatalf("InitDB: %v", err)
  15. }
  16. t.Cleanup(func() { _ = database.CloseDB() })
  17. first := serverHwid()
  18. if first == "" {
  19. t.Fatal("serverHwid returned empty")
  20. }
  21. second := serverHwid()
  22. if second != first {
  23. t.Fatalf("hwid not stable: %q vs %q", first, second)
  24. }
  25. var row model.Setting
  26. if err := database.GetDB().Where("key = ?", serverHwidKey).First(&row).Error; err != nil {
  27. t.Fatalf("hwid not persisted: %v", err)
  28. }
  29. if row.Value != first {
  30. t.Fatalf("persisted hwid %q != returned %q", row.Value, first)
  31. }
  32. }
  33. // The fetch must carry the stable id so an HWID-limited donor lets it through.
  34. func TestFetchSendsStableHwid(t *testing.T) {
  35. if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
  36. t.Fatalf("InitDB: %v", err)
  37. }
  38. t.Cleanup(func() { _ = database.CloseDB() })
  39. var gotHwid string
  40. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  41. gotHwid = r.Header.Get("X-HWID")
  42. _, _ = w.Write([]byte("vless://uuid@host:443?security=none#x"))
  43. }))
  44. defer srv.Close()
  45. res := fetchSubscriptionLinks(srv.URL)
  46. if res.err != nil {
  47. t.Fatalf("fetch: %v", res.err)
  48. }
  49. if len(res.links) != 1 {
  50. t.Fatalf("links = %v", res.links)
  51. }
  52. if gotHwid == "" {
  53. t.Fatal("X-HWID header missing on fetch")
  54. }
  55. if gotHwid != serverHwid() {
  56. t.Fatalf("sent %q != stable %q", gotHwid, serverHwid())
  57. }
  58. }