sponsor_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. package panel
  2. import (
  3. "errors"
  4. "net/http"
  5. "net/http/httptest"
  6. "os"
  7. "path/filepath"
  8. "slices"
  9. "strings"
  10. "sync/atomic"
  11. "testing"
  12. "time"
  13. "github.com/mhsanaei/3x-ui/v3/internal/config"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database"
  15. )
  16. var sponsorTestNow = time.Date(2026, 10, 15, 0, 0, 0, 0, time.UTC)
  17. func validSponsor() Sponsor {
  18. return Sponsor{
  19. ID: "acme",
  20. Name: "Acme",
  21. Slots: []string{"dashboard", "sidebar"},
  22. Until: sponsorTestNow.Add(24 * time.Hour),
  23. Logo: "acme.png",
  24. Link: "https://acme.example/",
  25. }
  26. }
  27. func TestActiveSponsorsFilters(t *testing.T) {
  28. cases := []struct {
  29. name string
  30. mutate func(*Sponsor)
  31. kept bool
  32. }{
  33. {"valid", func(*Sponsor) {}, true},
  34. {"expired", func(s *Sponsor) { s.Until = sponsorTestNow }, false},
  35. {"enable false with future until", func(s *Sponsor) { s.Enable = new(false) }, false},
  36. {"enable true without until", func(s *Sponsor) { s.Enable, s.Until = new(true), time.Time{} }, false},
  37. {"enable true with future until", func(s *Sponsor) { s.Enable = new(true) }, true},
  38. {"missing id", func(s *Sponsor) { s.ID = "" }, false},
  39. {"http link", func(s *Sponsor) { s.Link = "http://acme.example/" }, false},
  40. {"javascript link", func(s *Sponsor) { s.Link = "javascript:alert(1)" }, false},
  41. {"only unknown slots", func(s *Sponsor) { s.Slots = []string{"subpage"} }, false},
  42. }
  43. for _, tc := range cases {
  44. t.Run(tc.name, func(t *testing.T) {
  45. sp := validSponsor()
  46. tc.mutate(&sp)
  47. got := activeSponsors(&SponsorList{Sponsors: []Sponsor{sp}}, sponsorTestNow)
  48. if kept := len(got.Sponsors) == 1; kept != tc.kept {
  49. t.Fatalf("kept = %v, want %v", kept, tc.kept)
  50. }
  51. })
  52. }
  53. }
  54. func TestActiveSponsorsCapsSidebarAtThree(t *testing.T) {
  55. raw := &SponsorList{}
  56. for _, id := range []string{"expired", "a", "b", "c", "d", "e"} {
  57. sp := validSponsor()
  58. sp.ID = id
  59. sp.Slots = []string{"sidebar", "page"}
  60. if id == "expired" {
  61. sp.Until = sponsorTestNow
  62. }
  63. if id == "e" {
  64. sp.Slots = []string{"sidebar"}
  65. }
  66. raw.Sponsors = append(raw.Sponsors, sp)
  67. }
  68. got := activeSponsors(raw, sponsorTestNow)
  69. want := map[string][]string{
  70. "a": {"sidebar", "page"}, "b": {"sidebar", "page"}, "c": {"sidebar", "page"}, "d": {"page"},
  71. }
  72. if len(got.Sponsors) != len(want) {
  73. t.Fatalf("got %d sponsors, want %d (e has only sidebar and must drop)", len(got.Sponsors), len(want))
  74. }
  75. for _, sp := range got.Sponsors {
  76. if !slices.Equal(sp.Slots, want[sp.ID]) {
  77. t.Errorf("%s slots = %v, want %v", sp.ID, sp.Slots, want[sp.ID])
  78. }
  79. }
  80. }
  81. func TestActiveSponsorsLogoName(t *testing.T) {
  82. cases := []struct{ logo, want string }{
  83. {"acme.png", "/sponsors/logo/acme.png"},
  84. {"VPS.png", "/sponsors/logo/VPS.png"},
  85. {"../x.png", ""},
  86. {"https://evil.example/x.png", ""},
  87. {"..png", ""},
  88. {"logo.svg", ""},
  89. {"", ""},
  90. }
  91. for _, tc := range cases {
  92. t.Run(tc.logo, func(t *testing.T) {
  93. sp := validSponsor()
  94. sp.Logo = tc.logo
  95. got := activeSponsors(&SponsorList{Sponsors: []Sponsor{sp}}, sponsorTestNow)
  96. if len(got.Sponsors) != 1 {
  97. t.Fatalf("sponsor dropped for logo %q; want it kept", tc.logo)
  98. }
  99. if got.Sponsors[0].Logo != tc.want {
  100. t.Errorf("logo = %q, want %q", got.Sponsors[0].Logo, tc.want)
  101. }
  102. })
  103. }
  104. }
  105. func TestActiveSponsorsResolvesLogoAndSlots(t *testing.T) {
  106. sp := validSponsor()
  107. sp.Slots = []string{"subpage", "login"}
  108. got := activeSponsors(&SponsorList{Contact: "javascript:x", Sponsors: []Sponsor{sp}}, sponsorTestNow)
  109. if len(got.Sponsors) != 1 {
  110. t.Fatalf("got %d sponsors, want 1", len(got.Sponsors))
  111. }
  112. if want := "/sponsors/logo/acme.png"; got.Sponsors[0].Logo != want {
  113. t.Errorf("logo = %q, want %q", got.Sponsors[0].Logo, want)
  114. }
  115. if s := got.Sponsors[0].Slots; len(s) != 1 || s[0] != "login" {
  116. t.Errorf("slots = %v, want [login]", s)
  117. }
  118. if got.Contact != "" {
  119. t.Errorf("contact = %q, want empty for non-https", got.Contact)
  120. }
  121. }
  122. func setupSponsorServer(t *testing.T, body string) *atomic.Int32 {
  123. t.Helper()
  124. t.Setenv("XUI_DB_FOLDER", t.TempDir())
  125. if err := database.InitDB(config.GetDBPath()); err != nil {
  126. t.Fatalf("init db: %v", err)
  127. }
  128. t.Cleanup(func() { _ = database.CloseDB() })
  129. var hits atomic.Int32
  130. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  131. hits.Add(1)
  132. isLogo := strings.HasPrefix(r.URL.Path, "/media/")
  133. if (isLogo && failSponsorLogos.Load()) || (!isLogo && failSponsorList.Load()) {
  134. w.WriteHeader(http.StatusBadGateway)
  135. return
  136. }
  137. switch r.URL.Path {
  138. case "/media/acme.png":
  139. _, _ = w.Write(pngMagic)
  140. case "/media/fake.png":
  141. _, _ = w.Write([]byte("<svg onload=alert(1)>"))
  142. default:
  143. _, _ = w.Write([]byte(body))
  144. }
  145. }))
  146. t.Cleanup(srv.Close)
  147. prevURL, prevBase, prevNow := sponsorsURL, sponsorLogoBase, sponsorNow
  148. sponsorsURL, sponsorLogoBase = srv.URL+"/sponsors.json", srv.URL+"/media/"
  149. resetSponsorCache()
  150. t.Cleanup(func() {
  151. sponsorsURL, sponsorLogoBase, sponsorNow = prevURL, prevBase, prevNow
  152. failSponsorList.Store(false)
  153. failSponsorLogos.Store(false)
  154. resetSponsorCache()
  155. })
  156. return &hits
  157. }
  158. var failSponsorList, failSponsorLogos atomic.Bool
  159. func TestGetSponsorsKeepsLastListWhenRefreshFails(t *testing.T) {
  160. hits := setupSponsorServer(t, `{"sponsors":[{"id":"acme","slots":["page"],
  161. "until":"2099-01-01T00:00:00Z","link":"https://acme.example/"}]}`)
  162. now := sponsorTestNow
  163. sponsorNow = func() time.Time { return now }
  164. svc := &PanelService{}
  165. if got, err := svc.GetSponsors(); err != nil || len(got.Sponsors) != 1 {
  166. t.Fatalf("first call = %+v, %v; want 1 sponsor", got, err)
  167. }
  168. failSponsorList.Store(true)
  169. now = now.Add(sponsorsTTL)
  170. got, err := svc.GetSponsors()
  171. if err != nil || len(got.Sponsors) != 1 || got.Sponsors[0].ID != "acme" {
  172. t.Fatalf("after failed refresh = %+v, %v; want the last good sponsor kept", got, err)
  173. }
  174. now = now.Add(sponsorsErrTTL - time.Second)
  175. if _, err := svc.GetSponsors(); err != nil {
  176. t.Fatal(err)
  177. }
  178. if n := hits.Load(); n != 2 {
  179. t.Fatalf("remote hits = %d, want 2 (failed refresh retried only after sponsorsErrTTL)", n)
  180. }
  181. }
  182. func TestGetSponsorLogoCachesFailuresAndKeepsLastImage(t *testing.T) {
  183. hits := setupSponsorServer(t, `{"sponsors":[
  184. {"id":"acme","slots":["page"],"until":"2099-01-01T00:00:00Z","link":"https://a.example/","logo":"acme.png"},
  185. {"id":"fake","slots":["page"],"until":"2099-01-01T00:00:00Z","link":"https://f.example/","logo":"fake.png"}]}`)
  186. now := sponsorTestNow
  187. sponsorNow = func() time.Time { return now }
  188. svc := &PanelService{}
  189. const wantErr = "sponsor logo fake.png has content type text/plain; charset=utf-8"
  190. for range 2 {
  191. if _, _, err := svc.GetSponsorLogo("fake.png"); err == nil || err.Error() != wantErr {
  192. t.Fatalf("fake.png err = %v, want %q", err, wantErr)
  193. }
  194. }
  195. if n := hits.Load(); n != 2 {
  196. t.Fatalf("remote hits = %d, want 2 (list + one fake.png fetch; the failure must be cached)", n)
  197. }
  198. if _, _, err := svc.GetSponsorLogo("acme.png"); err != nil {
  199. t.Fatal(err)
  200. }
  201. failSponsorLogos.Store(true)
  202. now = now.Add(sponsorsTTL)
  203. data, ctype, err := svc.GetSponsorLogo("acme.png")
  204. if err != nil || ctype != "image/png" || string(data) != string(pngMagic) {
  205. t.Fatalf("acme.png after failed refresh = %q, %q, %v; want the last good image", data, ctype, err)
  206. }
  207. }
  208. func resetSponsorCache() {
  209. sponsorsMu.Lock()
  210. defer sponsorsMu.Unlock()
  211. sponsorsRaw, sponsorsErr, sponsorsRetryAt = nil, nil, time.Time{}
  212. logosMu.Lock()
  213. defer logosMu.Unlock()
  214. logos = map[string]sponsorLogo{}
  215. }
  216. var pngMagic = []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR")
  217. func TestGetSponsorLogo(t *testing.T) {
  218. hits := setupSponsorServer(t, `{"sponsors":[
  219. {"id":"acme","slots":["page"],"until":"2099-01-01T00:00:00Z","link":"https://a.example/","logo":"acme.png"},
  220. {"id":"fake","slots":["page"],"until":"2099-01-01T00:00:00Z","link":"https://f.example/","logo":"fake.png"},
  221. {"id":"old","slots":["page"],"until":"2000-01-01T00:00:00Z","link":"https://o.example/","logo":"old.png"}]}`)
  222. svc := &PanelService{}
  223. data, ctype, err := svc.GetSponsorLogo("acme.png")
  224. if err != nil || ctype != "image/png" || string(data) != string(pngMagic) {
  225. t.Fatalf("acme.png = %q, %q, %v; want png bytes", data, ctype, err)
  226. }
  227. before := hits.Load()
  228. if _, _, err := svc.GetSponsorLogo("acme.png"); err != nil {
  229. t.Fatal(err)
  230. }
  231. if hits.Load() != before {
  232. t.Fatalf("second logo fetch hit the remote; want cached")
  233. }
  234. for _, name := range []string{"old.png", "other.png", "../sponsors.json"} {
  235. if _, _, err := svc.GetSponsorLogo(name); !errors.Is(err, ErrSponsorLogoUnknown) {
  236. t.Errorf("%s: err = %v, want ErrSponsorLogoUnknown", name, err)
  237. }
  238. }
  239. _, _, err = svc.GetSponsorLogo("fake.png")
  240. if want := "sponsor logo fake.png has content type text/plain; charset=utf-8"; err == nil || err.Error() != want {
  241. t.Errorf("fake.png: err = %v, want %q", err, want)
  242. }
  243. }
  244. func TestGetSponsorsCachesAndExpiresWhileCached(t *testing.T) {
  245. hits := setupSponsorServer(t, `{"sponsors":[{"id":"acme","slots":["page"],
  246. "until":"2026-10-15T00:30:00Z","link":"https://acme.example/"}]}`)
  247. now := sponsorTestNow
  248. sponsorNow = func() time.Time { return now }
  249. svc := &PanelService{}
  250. got, err := svc.GetSponsors()
  251. if err != nil || len(got.Sponsors) != 1 {
  252. t.Fatalf("first call = %+v, %v; want 1 sponsor", got, err)
  253. }
  254. now = now.Add(45 * time.Minute)
  255. got, err = svc.GetSponsors()
  256. if err != nil || len(got.Sponsors) != 0 {
  257. t.Fatalf("after until = %+v, %v; want 0 sponsors", got, err)
  258. }
  259. if n := hits.Load(); n != 1 {
  260. t.Fatalf("remote hits = %d, want 1 (cached within TTL)", n)
  261. }
  262. now = now.Add(sponsorsTTL)
  263. if _, err := svc.GetSponsors(); err != nil {
  264. t.Fatal(err)
  265. }
  266. if n := hits.Load(); n != 2 {
  267. t.Fatalf("remote hits after TTL = %d, want 2", n)
  268. }
  269. }
  270. func TestGetSponsorsRejectsOversizeBody(t *testing.T) {
  271. setupSponsorServer(t, `{"contact":"`+strings.Repeat("a", maxSponsorsBytes)+`"}`)
  272. _, err := (&PanelService{}).GetSponsors()
  273. want := sponsorsURL + " exceeds 262144 bytes"
  274. if err == nil || err.Error() != want {
  275. t.Fatalf("err = %v, want %q", err, want)
  276. }
  277. }
  278. func TestGetSponsorsDebugReadsLocalCheckout(t *testing.T) {
  279. hits := setupSponsorServer(t, `{"sponsors":[]}`)
  280. t.Setenv("XUI_DEBUG", "true")
  281. root := t.TempDir()
  282. local := filepath.Join(root, "sponsors", "3X")
  283. if err := os.MkdirAll(local, 0o700); err != nil {
  284. t.Fatal(err)
  285. }
  286. if err := os.Mkdir(filepath.Join(root, "3x-ui"), 0o700); err != nil {
  287. t.Fatal(err)
  288. }
  289. t.Chdir(filepath.Join(root, "3x-ui"))
  290. write := func(id string) {
  291. t.Helper()
  292. body := `{"sponsors":[{"id":"` + id + `","slots":["page"],"until":"2099-01-01T00:00:00Z","link":"https://a.example/"}]}`
  293. if err := os.WriteFile(filepath.Join(local, "sponsors.json"), []byte(body), 0o600); err != nil {
  294. t.Fatal(err)
  295. }
  296. }
  297. svc := &PanelService{}
  298. for _, id := range []string{"first", "edited"} {
  299. write(id)
  300. got, err := svc.GetSponsors()
  301. if err != nil || len(got.Sponsors) != 1 || got.Sponsors[0].ID != id {
  302. t.Fatalf("GetSponsors() = %+v, %v; want local sponsor %q", got, err, id)
  303. }
  304. }
  305. if n := hits.Load(); n != 0 {
  306. t.Fatalf("remote hits = %d, want 0 in debug mode", n)
  307. }
  308. }