sponsor_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. {"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. dbtest.InitDB(t, config.GetDBPath())
  126. var hits atomic.Int32
  127. srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  128. hits.Add(1)
  129. isLogo := strings.HasPrefix(r.URL.Path, "/media/")
  130. if (isLogo && failSponsorLogos.Load()) || (!isLogo && failSponsorList.Load()) {
  131. w.WriteHeader(http.StatusBadGateway)
  132. return
  133. }
  134. switch r.URL.Path {
  135. case "/media/acme.png":
  136. _, _ = w.Write(pngMagic)
  137. case "/media/fake.png":
  138. _, _ = w.Write([]byte("<svg onload=alert(1)>"))
  139. default:
  140. _, _ = w.Write([]byte(body))
  141. }
  142. }))
  143. t.Cleanup(srv.Close)
  144. prevURL, prevBase, prevNow := sponsorsURL, sponsorLogoBase, sponsorNow
  145. sponsorsURL, sponsorLogoBase = srv.URL+"/sponsors.json", srv.URL+"/media/"
  146. resetSponsorCache()
  147. t.Cleanup(func() {
  148. sponsorsURL, sponsorLogoBase, sponsorNow = prevURL, prevBase, prevNow
  149. failSponsorList.Store(false)
  150. failSponsorLogos.Store(false)
  151. resetSponsorCache()
  152. })
  153. return &hits
  154. }
  155. var failSponsorList, failSponsorLogos atomic.Bool
  156. func TestGetSponsorsKeepsLastListWhenRefreshFails(t *testing.T) {
  157. hits := setupSponsorServer(t, `{"sponsors":[{"id":"acme","slots":["page"],
  158. "until":"2099-01-01T00:00:00Z","link":"https://acme.example/"}]}`)
  159. now := sponsorTestNow
  160. sponsorNow = func() time.Time { return now }
  161. svc := &PanelService{}
  162. if got, err := svc.GetSponsors(); err != nil || len(got.Sponsors) != 1 {
  163. t.Fatalf("first call = %+v, %v; want 1 sponsor", got, err)
  164. }
  165. failSponsorList.Store(true)
  166. now = now.Add(sponsorsTTL)
  167. got, err := svc.GetSponsors()
  168. if err != nil || len(got.Sponsors) != 1 || got.Sponsors[0].ID != "acme" {
  169. t.Fatalf("after failed refresh = %+v, %v; want the last good sponsor kept", got, err)
  170. }
  171. now = now.Add(sponsorsErrTTL - time.Second)
  172. if _, err := svc.GetSponsors(); err != nil {
  173. t.Fatal(err)
  174. }
  175. if n := hits.Load(); n != 2 {
  176. t.Fatalf("remote hits = %d, want 2 (failed refresh retried only after sponsorsErrTTL)", n)
  177. }
  178. }
  179. func TestGetSponsorLogoCachesFailuresAndKeepsLastImage(t *testing.T) {
  180. hits := setupSponsorServer(t, `{"sponsors":[
  181. {"id":"acme","slots":["page"],"until":"2099-01-01T00:00:00Z","link":"https://a.example/","logo":"acme.png"},
  182. {"id":"fake","slots":["page"],"until":"2099-01-01T00:00:00Z","link":"https://f.example/","logo":"fake.png"}]}`)
  183. now := sponsorTestNow
  184. sponsorNow = func() time.Time { return now }
  185. svc := &PanelService{}
  186. const wantErr = "sponsor logo fake.png has content type text/plain; charset=utf-8"
  187. for range 2 {
  188. if _, _, err := svc.GetSponsorLogo("fake.png"); err == nil || err.Error() != wantErr {
  189. t.Fatalf("fake.png err = %v, want %q", err, wantErr)
  190. }
  191. }
  192. if n := hits.Load(); n != 2 {
  193. t.Fatalf("remote hits = %d, want 2 (list + one fake.png fetch; the failure must be cached)", n)
  194. }
  195. if _, _, err := svc.GetSponsorLogo("acme.png"); err != nil {
  196. t.Fatal(err)
  197. }
  198. failSponsorLogos.Store(true)
  199. now = now.Add(sponsorsTTL)
  200. data, ctype, err := svc.GetSponsorLogo("acme.png")
  201. if err != nil || ctype != "image/png" || string(data) != string(pngMagic) {
  202. t.Fatalf("acme.png after failed refresh = %q, %q, %v; want the last good image", data, ctype, err)
  203. }
  204. }
  205. func resetSponsorCache() {
  206. sponsorsMu.Lock()
  207. defer sponsorsMu.Unlock()
  208. sponsorsRaw, sponsorsErr, sponsorsRetryAt = nil, nil, time.Time{}
  209. logosMu.Lock()
  210. defer logosMu.Unlock()
  211. logos = map[string]sponsorLogo{}
  212. }
  213. var pngMagic = []byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR")
  214. func TestGetSponsorLogo(t *testing.T) {
  215. hits := setupSponsorServer(t, `{"sponsors":[
  216. {"id":"acme","slots":["page"],"until":"2099-01-01T00:00:00Z","link":"https://a.example/","logo":"acme.png"},
  217. {"id":"fake","slots":["page"],"until":"2099-01-01T00:00:00Z","link":"https://f.example/","logo":"fake.png"},
  218. {"id":"old","slots":["page"],"until":"2000-01-01T00:00:00Z","link":"https://o.example/","logo":"old.png"}]}`)
  219. svc := &PanelService{}
  220. data, ctype, err := svc.GetSponsorLogo("acme.png")
  221. if err != nil || ctype != "image/png" || string(data) != string(pngMagic) {
  222. t.Fatalf("acme.png = %q, %q, %v; want png bytes", data, ctype, err)
  223. }
  224. before := hits.Load()
  225. if _, _, err := svc.GetSponsorLogo("acme.png"); err != nil {
  226. t.Fatal(err)
  227. }
  228. if hits.Load() != before {
  229. t.Fatalf("second logo fetch hit the remote; want cached")
  230. }
  231. for _, name := range []string{"old.png", "other.png", "../sponsors.json"} {
  232. if _, _, err := svc.GetSponsorLogo(name); !errors.Is(err, ErrSponsorLogoUnknown) {
  233. t.Errorf("%s: err = %v, want ErrSponsorLogoUnknown", name, err)
  234. }
  235. }
  236. _, _, err = svc.GetSponsorLogo("fake.png")
  237. if want := "sponsor logo fake.png has content type text/plain; charset=utf-8"; err == nil || err.Error() != want {
  238. t.Errorf("fake.png: err = %v, want %q", err, want)
  239. }
  240. }
  241. func TestGetSponsorsCachesAndExpiresWhileCached(t *testing.T) {
  242. hits := setupSponsorServer(t, `{"sponsors":[{"id":"acme","slots":["page"],
  243. "until":"2026-10-15T00:30:00Z","link":"https://acme.example/"}]}`)
  244. now := sponsorTestNow
  245. sponsorNow = func() time.Time { return now }
  246. svc := &PanelService{}
  247. got, err := svc.GetSponsors()
  248. if err != nil || len(got.Sponsors) != 1 {
  249. t.Fatalf("first call = %+v, %v; want 1 sponsor", got, err)
  250. }
  251. now = now.Add(45 * time.Minute)
  252. got, err = svc.GetSponsors()
  253. if err != nil || len(got.Sponsors) != 0 {
  254. t.Fatalf("after until = %+v, %v; want 0 sponsors", got, err)
  255. }
  256. if n := hits.Load(); n != 1 {
  257. t.Fatalf("remote hits = %d, want 1 (cached within TTL)", n)
  258. }
  259. now = now.Add(sponsorsTTL)
  260. if _, err := svc.GetSponsors(); err != nil {
  261. t.Fatal(err)
  262. }
  263. if n := hits.Load(); n != 2 {
  264. t.Fatalf("remote hits after TTL = %d, want 2", n)
  265. }
  266. }
  267. func TestGetSponsorsRejectsOversizeBody(t *testing.T) {
  268. setupSponsorServer(t, `{"contact":"`+strings.Repeat("a", maxSponsorsBytes)+`"}`)
  269. _, err := (&PanelService{}).GetSponsors()
  270. want := sponsorsURL + " exceeds 262144 bytes"
  271. if err == nil || err.Error() != want {
  272. t.Fatalf("err = %v, want %q", err, want)
  273. }
  274. }
  275. func TestGetSponsorsDebugReadsLocalCheckout(t *testing.T) {
  276. hits := setupSponsorServer(t, `{"sponsors":[]}`)
  277. t.Setenv("XUI_DEBUG", "true")
  278. root := t.TempDir()
  279. local := filepath.Join(root, "sponsors", "3X")
  280. if err := os.MkdirAll(local, 0o700); err != nil {
  281. t.Fatal(err)
  282. }
  283. if err := os.Mkdir(filepath.Join(root, "3x-ui"), 0o700); err != nil {
  284. t.Fatal(err)
  285. }
  286. t.Chdir(filepath.Join(root, "3x-ui"))
  287. write := func(id string) {
  288. t.Helper()
  289. body := `{"sponsors":[{"id":"` + id + `","slots":["page"],"until":"2099-01-01T00:00:00Z","link":"https://a.example/"}]}`
  290. if err := os.WriteFile(filepath.Join(local, "sponsors.json"), []byte(body), 0o600); err != nil {
  291. t.Fatal(err)
  292. }
  293. }
  294. svc := &PanelService{}
  295. for _, id := range []string{"first", "edited"} {
  296. write(id)
  297. got, err := svc.GetSponsors()
  298. if err != nil || len(got.Sponsors) != 1 || got.Sponsors[0].ID != id {
  299. t.Fatalf("GetSponsors() = %+v, %v; want local sponsor %q", got, err, id)
  300. }
  301. }
  302. if n := hits.Load(); n != 0 {
  303. t.Fatalf("remote hits = %d, want 0 in debug mode", n)
  304. }
  305. }