setting_test.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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/model"
  13. "github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
  14. "github.com/mhsanaei/3x-ui/v3/internal/web/service"
  15. )
  16. func TestValidateRegex(t *testing.T) {
  17. gin.SetMode(gin.TestMode)
  18. router := gin.New()
  19. NewSettingController(router.Group("/panel/api"))
  20. tests := []struct {
  21. name string
  22. body string
  23. success bool
  24. }{
  25. {name: "Go RE2 inline flag", body: `{"regex":"(?m)^general-purpose$"}`, success: true},
  26. {name: "invalid expression", body: `{"regex":"["}`, success: false},
  27. }
  28. for _, tt := range tests {
  29. t.Run(tt.name, func(t *testing.T) {
  30. req := httptest.NewRequest(http.MethodPost, "/panel/api/setting/validateRegex", strings.NewReader(tt.body))
  31. req.Header.Set("Content-Type", "application/json")
  32. resp := httptest.NewRecorder()
  33. router.ServeHTTP(resp, req)
  34. if resp.Code != http.StatusOK {
  35. t.Fatalf("status = %d, want 200; body=%s", resp.Code, resp.Body.String())
  36. }
  37. needle := `"success":true`
  38. if !tt.success {
  39. needle = `"success":false`
  40. }
  41. if !strings.Contains(resp.Body.String(), needle) {
  42. t.Fatalf("body = %s, want %s", resp.Body.String(), needle)
  43. }
  44. })
  45. }
  46. }
  47. func TestAPITokenMutationRoutesEnforceExpectedScope(t *testing.T) {
  48. t.Setenv("XUI_DB_FOLDER", t.TempDir())
  49. if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
  50. t.Fatalf("InitDB: %v", err)
  51. }
  52. t.Cleanup(func() { _ = database.CloseDB() })
  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. if err := database.InitDB(filepath.Join(t.TempDir(), "x-ui.db")); err != nil {
  86. t.Fatalf("InitDB: %v", err)
  87. }
  88. t.Cleanup(func() { _ = database.CloseDB() })
  89. settingService := service.SettingService{}
  90. if err := settingService.SetTwoFactorToken("ORIGINALSECRET234567"); err != nil {
  91. t.Fatalf("seed token: %v", err)
  92. }
  93. if err := settingService.SetTwoFactorEnable(true); err != nil {
  94. t.Fatalf("seed enable: %v", err)
  95. }
  96. post := func(t *testing.T, mutate func(map[string]any)) string {
  97. t.Helper()
  98. base, err := settingService.GetAllSetting()
  99. if err != nil {
  100. t.Fatalf("GetAllSetting: %v", err)
  101. }
  102. raw, err := json.Marshal(base)
  103. if err != nil {
  104. t.Fatalf("marshal: %v", err)
  105. }
  106. body := map[string]any{}
  107. if err := json.Unmarshal(raw, &body); err != nil {
  108. t.Fatalf("unmarshal: %v", err)
  109. }
  110. mutate(body)
  111. payload, err := json.Marshal(body)
  112. if err != nil {
  113. t.Fatalf("marshal payload: %v", err)
  114. }
  115. gin.SetMode(gin.TestMode)
  116. router := gin.New()
  117. NewSettingController(router.Group("/panel/api"))
  118. req := httptest.NewRequest(http.MethodPost, "/panel/api/setting/update", strings.NewReader(string(payload)))
  119. req.Header.Set("Content-Type", "application/json")
  120. resp := httptest.NewRecorder()
  121. router.ServeHTTP(resp, req)
  122. return resp.Body.String()
  123. }
  124. t.Run("rebind without code is rejected", func(t *testing.T) {
  125. got := post(t, func(body map[string]any) {
  126. body["twoFactorEnable"] = true
  127. body["twoFactorToken"] = "ATTACKERSECRET567890"
  128. })
  129. if !strings.Contains(got, `"success":false`) {
  130. t.Fatalf("rebind without a 2FA code was accepted: %s", got)
  131. }
  132. stored, err := settingService.GetTwoFactorToken()
  133. if err != nil {
  134. t.Fatalf("GetTwoFactorToken: %v", err)
  135. }
  136. if stored != "ORIGINALSECRET234567" {
  137. t.Fatalf("stored 2FA secret = %q, want it unchanged", stored)
  138. }
  139. })
  140. t.Run("ordinary save with redacted token still succeeds", func(t *testing.T) {
  141. got := post(t, func(body map[string]any) {
  142. body["twoFactorEnable"] = true
  143. body["twoFactorToken"] = ""
  144. })
  145. if !strings.Contains(got, `"success":true`) {
  146. t.Fatalf("normal settings save was rejected: %s", got)
  147. }
  148. stored, err := settingService.GetTwoFactorToken()
  149. if err != nil {
  150. t.Fatalf("GetTwoFactorToken: %v", err)
  151. }
  152. if stored != "ORIGINALSECRET234567" {
  153. t.Fatalf("stored 2FA secret = %q, want it preserved", stored)
  154. }
  155. })
  156. }