sponsor_test.go 11 KB

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