setting_test.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. package controller
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "path/filepath"
  7. "strconv"
  8. "strings"
  9. "testing"
  10. "github.com/gin-gonic/gin"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database"
  12. "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  14. "github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
  15. "github.com/mhsanaei/3x-ui/v3/internal/web/locale"
  16. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  17. "github.com/mhsanaei/3x-ui/v3/internal/web/service/discord"
  18. )
  19. func TestValidateRegex(t *testing.T) {
  20. gin.SetMode(gin.TestMode)
  21. router := gin.New()
  22. NewSettingController(router.Group("/panel/api"))
  23. tests := []struct {
  24. name string
  25. body string
  26. success bool
  27. }{
  28. {name: "Go RE2 inline flag", body: `{"regex":"(?m)^general-purpose$"}`, success: true},
  29. {name: "invalid expression", body: `{"regex":"["}`, success: false},
  30. }
  31. for _, tt := range tests {
  32. t.Run(tt.name, func(t *testing.T) {
  33. req := httptest.NewRequest(http.MethodPost, "/panel/api/setting/validateRegex", strings.NewReader(tt.body))
  34. req.Header.Set("Content-Type", "application/json")
  35. resp := httptest.NewRecorder()
  36. router.ServeHTTP(resp, req)
  37. if resp.Code != http.StatusOK {
  38. t.Fatalf("status = %d, want 200; body=%s", resp.Code, resp.Body.String())
  39. }
  40. needle := `"success":true`
  41. if !tt.success {
  42. needle = `"success":false`
  43. }
  44. if !strings.Contains(resp.Body.String(), needle) {
  45. t.Fatalf("body = %s, want %s", resp.Body.String(), needle)
  46. }
  47. })
  48. }
  49. }
  50. func TestAPITokenMutationRoutesEnforceExpectedScope(t *testing.T) {
  51. t.Setenv("XUI_DB_FOLDER", t.TempDir())
  52. dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
  53. row := &model.ApiToken{Name: "route-scope", Token: crypto.HashTokenSHA256("token"), Enabled: true, Scope: model.ApiScopeNodeSync}
  54. if err := database.GetDB().Create(row).Error; err != nil {
  55. t.Fatalf("seed token: %v", err)
  56. }
  57. gin.SetMode(gin.TestMode)
  58. router := gin.New()
  59. NewSettingController(router.Group("/panel/api"))
  60. for _, path := range []string{
  61. "/panel/api/setting/apiTokens/delete/" + strconv.Itoa(row.Id),
  62. "/panel/api/setting/apiTokens/setEnabled/" + strconv.Itoa(row.Id),
  63. } {
  64. body := `{"expectedScope":"admin","enabled":false}`
  65. req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
  66. req.Header.Set("Content-Type", "application/json")
  67. resp := httptest.NewRecorder()
  68. router.ServeHTTP(resp, req)
  69. if !strings.Contains(resp.Body.String(), `"success":false`) {
  70. t.Fatalf("%s accepted wrong expected scope: %s", path, resp.Body.String())
  71. }
  72. }
  73. var stored model.ApiToken
  74. if err := database.GetDB().First(&stored, row.Id).Error; err != nil {
  75. t.Fatalf("token was deleted by wrong scope: %v", err)
  76. }
  77. if !stored.Enabled {
  78. t.Fatal("token was disabled by wrong scope")
  79. }
  80. }
  81. // GHSA-xqqw-jqqv-99h6: a save that keeps 2FA enabled must not be able to
  82. // rebind the authenticator without presenting a current code.
  83. func TestUpdateSettingRequiresCodeToReplaceTwoFactorToken(t *testing.T) {
  84. t.Setenv("XUI_DB_FOLDER", t.TempDir())
  85. dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
  86. settingService := service.SettingService{}
  87. if err := settingService.SetTwoFactorToken("ORIGINALSECRET234567"); err != nil {
  88. t.Fatalf("seed token: %v", err)
  89. }
  90. if err := settingService.SetTwoFactorEnable(true); err != nil {
  91. t.Fatalf("seed enable: %v", err)
  92. }
  93. post := func(t *testing.T, mutate func(map[string]any)) string {
  94. t.Helper()
  95. base, err := settingService.GetAllSetting()
  96. if err != nil {
  97. t.Fatalf("GetAllSetting: %v", err)
  98. }
  99. raw, err := json.Marshal(base)
  100. if err != nil {
  101. t.Fatalf("marshal: %v", err)
  102. }
  103. body := map[string]any{}
  104. if err := json.Unmarshal(raw, &body); err != nil {
  105. t.Fatalf("unmarshal: %v", err)
  106. }
  107. mutate(body)
  108. payload, err := json.Marshal(body)
  109. if err != nil {
  110. t.Fatalf("marshal payload: %v", err)
  111. }
  112. gin.SetMode(gin.TestMode)
  113. router := gin.New()
  114. NewSettingController(router.Group("/panel/api"))
  115. req := httptest.NewRequest(http.MethodPost, "/panel/api/setting/update", strings.NewReader(string(payload)))
  116. req.Header.Set("Content-Type", "application/json")
  117. resp := httptest.NewRecorder()
  118. router.ServeHTTP(resp, req)
  119. return resp.Body.String()
  120. }
  121. t.Run("rebind without code is rejected", func(t *testing.T) {
  122. got := post(t, func(body map[string]any) {
  123. body["twoFactorEnable"] = true
  124. body["twoFactorToken"] = "ATTACKERSECRET567890"
  125. })
  126. if !strings.Contains(got, `"success":false`) {
  127. t.Fatalf("rebind without a 2FA code was accepted: %s", got)
  128. }
  129. stored, err := settingService.GetTwoFactorToken()
  130. if err != nil {
  131. t.Fatalf("GetTwoFactorToken: %v", err)
  132. }
  133. if stored != "ORIGINALSECRET234567" {
  134. t.Fatalf("stored 2FA secret = %q, want it unchanged", stored)
  135. }
  136. })
  137. t.Run("ordinary save with redacted token still succeeds", func(t *testing.T) {
  138. got := post(t, func(body map[string]any) {
  139. body["twoFactorEnable"] = true
  140. body["twoFactorToken"] = ""
  141. })
  142. if !strings.Contains(got, `"success":true`) {
  143. t.Fatalf("normal settings save was rejected: %s", got)
  144. }
  145. stored, err := settingService.GetTwoFactorToken()
  146. if err != nil {
  147. t.Fatalf("GetTwoFactorToken: %v", err)
  148. }
  149. if stored != "ORIGINALSECRET234567" {
  150. t.Fatalf("stored 2FA secret = %q, want it preserved", stored)
  151. }
  152. })
  153. }
  154. func TestTestDiscordEndpoint(t *testing.T) {
  155. gin.SetMode(gin.TestMode)
  156. // 1. Service not initialized
  157. SetDiscordService(nil)
  158. router := gin.New()
  159. router.Use(func(c *gin.Context) {
  160. c.Set("I18n", func(_ locale.I18nType, key string, _ ...string) string { return key })
  161. c.Next()
  162. })
  163. NewSettingController(router.Group("/panel/api"))
  164. req := httptest.NewRequest(http.MethodPost, "/panel/api/setting/testDiscord", nil)
  165. resp := httptest.NewRecorder()
  166. router.ServeHTTP(resp, req)
  167. if !strings.Contains(resp.Body.String(), `"success":false`) || !strings.Contains(resp.Body.String(), "pages.settings.discordNotInitialized") {
  168. t.Fatalf("expected uninitialized error, got %s", resp.Body.String())
  169. }
  170. // Setup DB
  171. t.Setenv("XUI_DB_FOLDER", t.TempDir())
  172. dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.db"))
  173. t.Cleanup(func() { SetDiscordService(nil) })
  174. settingService := service.SettingService{}
  175. svc := discord.NewDiscordService(settingService)
  176. SetDiscordService(svc)
  177. // 2. Discord bot disabled
  178. _ = settingService.SetDiscordBotEnable(false)
  179. req = httptest.NewRequest(http.MethodPost, "/panel/api/setting/testDiscord", nil)
  180. resp = httptest.NewRecorder()
  181. router.ServeHTTP(resp, req)
  182. if !strings.Contains(resp.Body.String(), `"success":false`) || !strings.Contains(resp.Body.String(), "pages.settings.discordBotNotEnabled") {
  183. t.Fatalf("expected disabled error, got %s", resp.Body.String())
  184. }
  185. // 3. Discord bot enabled but missing config
  186. _ = settingService.SetDiscordBotEnable(true)
  187. req = httptest.NewRequest(http.MethodPost, "/panel/api/setting/testDiscord", nil)
  188. resp = httptest.NewRecorder()
  189. router.ServeHTTP(resp, req)
  190. if !strings.Contains(resp.Body.String(), `"success":false`) || !strings.Contains(resp.Body.String(), "pages.settings.discordTestFailed") {
  191. t.Fatalf("expected send failure error, got %s", resp.Body.String())
  192. }
  193. // 4. Discord bot enabled with working server
  194. server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  195. w.WriteHeader(http.StatusOK)
  196. _, _ = w.Write([]byte(`{"id": "msg-1"}`))
  197. }))
  198. defer server.Close()
  199. _ = settingService.SetDiscordBotToken("test-bot-token")
  200. _ = settingService.SetDiscordChannelId("123456789")
  201. svc.SetBaseURL(server.URL)
  202. svc.SetHTTPClient(server.Client())
  203. req = httptest.NewRequest(http.MethodPost, "/panel/api/setting/testDiscord", nil)
  204. resp = httptest.NewRecorder()
  205. router.ServeHTTP(resp, req)
  206. if !strings.Contains(resp.Body.String(), `"success":true`) || !strings.Contains(resp.Body.String(), "pages.settings.discordTestSuccess") {
  207. t.Fatalf("expected success, got %s", resp.Body.String())
  208. }
  209. }