sponsor_test.go 10 KB

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