api_auth_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. package controller
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "net/http"
  6. "net/http/cookiejar"
  7. "net/http/httptest"
  8. "path/filepath"
  9. "testing"
  10. "github.com/gin-contrib/sessions"
  11. "github.com/gin-contrib/sessions/cookie"
  12. "github.com/gin-gonic/gin"
  13. "github.com/mhsanaei/3x-ui/v3/internal/database"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
  15. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  16. "github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
  17. "github.com/mhsanaei/3x-ui/v3/internal/web/session"
  18. )
  19. // newAPIAuthTestEngine builds a gin engine that mirrors the production auth
  20. // wiring: the sessions middleware, then checkAPIAuth guarding a sentinel
  21. // handler that reports whether c.Next() was reached and whether api_authed was
  22. // set. The APIController is the zero value, exactly as NewAPIController leaves
  23. // its service fields (they query the global DB), so this exercises the real
  24. // auth path. A fresh temp DB is initialised per test.
  25. func newAPIAuthTestEngine(t *testing.T) (*gin.Engine, *APIController) {
  26. t.Helper()
  27. gin.SetMode(gin.TestMode)
  28. dbDir := t.TempDir()
  29. t.Setenv("XUI_DB_FOLDER", dbDir)
  30. dbtest.InitDB(t, filepath.Join(dbDir, "x-ui.db"))
  31. engine := gin.New()
  32. store := cookie.NewStore([]byte("api-auth-test-secret"))
  33. engine.Use(sessions.Sessions("3x-ui", store))
  34. a := &APIController{}
  35. // Logs in as the first user so the session path can be exercised over a
  36. // cookie round-trip without reaching into checkAPIAuth's internals.
  37. engine.GET("/test-login", func(c *gin.Context) {
  38. u, err := a.userService.GetFirstUser()
  39. if err != nil {
  40. c.Status(http.StatusInternalServerError)
  41. return
  42. }
  43. if err := session.SetLoginUser(c, u); err != nil {
  44. c.Status(http.StatusInternalServerError)
  45. return
  46. }
  47. c.Status(http.StatusOK)
  48. })
  49. api := engine.Group("/panel/api")
  50. api.Use(a.checkAPIAuth)
  51. api.Use(a.enforceTokenScope)
  52. api.GET("/ping", func(c *gin.Context) {
  53. c.JSON(http.StatusOK, gin.H{"api_authed": c.GetBool("api_authed")})
  54. })
  55. api.GET("/server/status", func(c *gin.Context) {
  56. scope, _ := c.Get("api_token_scope")
  57. c.JSON(http.StatusOK, gin.H{"api_authed": c.GetBool("api_authed"), "scope": scope})
  58. })
  59. api.POST("/server/updatePanel", func(c *gin.Context) {
  60. c.JSON(http.StatusOK, gin.H{"reached": true})
  61. })
  62. api.POST("/clients/:email/detach", func(c *gin.Context) {
  63. c.JSON(http.StatusOK, gin.H{"reached": true})
  64. })
  65. api.POST("/inbounds/:id/resetTraffic", func(c *gin.Context) {
  66. c.JSON(http.StatusOK, gin.H{"reached": true})
  67. })
  68. api.POST("/clients/clientIpsByGuid", func(c *gin.Context) {
  69. c.JSON(http.StatusOK, gin.H{"reached": true})
  70. })
  71. return engine, a
  72. }
  73. // TestCheckAPIAuth_BearerSuccess characterizes the bearer-token path: a valid
  74. // token reaches the handler and sets api_authed (the contract the later
  75. // client-cert branch must match).
  76. func TestCheckAPIAuth_BearerSuccess(t *testing.T) {
  77. engine, _ := newAPIAuthTestEngine(t)
  78. const plaintext = "characterization-token-value"
  79. if err := database.GetDB().Create(&model.ApiToken{
  80. Name: "t1",
  81. Token: crypto.HashTokenSHA256(plaintext),
  82. Enabled: true,
  83. Scope: model.ApiScopeAdmin,
  84. }).Error; err != nil {
  85. t.Fatalf("seed token: %v", err)
  86. }
  87. req := httptest.NewRequest(http.MethodGet, "/panel/api/ping", nil)
  88. req.Header.Set("Authorization", "Bearer "+plaintext)
  89. w := httptest.NewRecorder()
  90. engine.ServeHTTP(w, req)
  91. if w.Code != http.StatusOK {
  92. t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
  93. }
  94. if got := w.Body.String(); got != `{"api_authed":true}` {
  95. t.Fatalf("body = %s, want api_authed true", got)
  96. }
  97. }
  98. // TestCheckAPIAuth_AcceptsVerifiedClientCert ensures verified mTLS authenticates
  99. // as node-sync rather than bypassing scope checks as admin.
  100. func TestCheckAPIAuth_AcceptsVerifiedClientCert(t *testing.T) {
  101. engine, _ := newAPIAuthTestEngine(t)
  102. req := httptest.NewRequest(http.MethodGet, "/panel/api/server/status", nil)
  103. req.TLS = &tls.ConnectionState{
  104. VerifiedChains: [][]*x509.Certificate{{&x509.Certificate{}}},
  105. }
  106. w := httptest.NewRecorder()
  107. engine.ServeHTTP(w, req)
  108. if w.Code != http.StatusOK {
  109. t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
  110. }
  111. if got := w.Body.String(); got != `{"api_authed":true,"scope":"node-sync"}` {
  112. t.Fatalf("body = %s, want node-sync scope", got)
  113. }
  114. forbidden := httptest.NewRequest(http.MethodPost, "/panel/api/server/updatePanel", nil)
  115. forbidden.TLS = &tls.ConnectionState{
  116. VerifiedChains: [][]*x509.Certificate{{&x509.Certificate{}}},
  117. }
  118. w = httptest.NewRecorder()
  119. engine.ServeHTTP(w, forbidden)
  120. if w.Code != http.StatusForbidden {
  121. t.Fatalf("updatePanel status = %d, want 403; body=%s", w.Code, w.Body.String())
  122. }
  123. }
  124. func TestNodeSyncScopeUsesFullPathPatterns(t *testing.T) {
  125. engine, _ := newAPIAuthTestEngine(t)
  126. cases := []struct {
  127. name string
  128. method string
  129. path string
  130. want int
  131. }{
  132. {"detach email parameter", http.MethodPost, "/panel/api/clients/[email protected]/detach", http.StatusOK},
  133. {"reset inbound id parameter", http.MethodPost, "/panel/api/inbounds/42/resetTraffic", http.StatusOK},
  134. {"client IP by guid endpoint", http.MethodPost, "/panel/api/clients/clientIpsByGuid", http.StatusOK},
  135. {"update panel forbidden", http.MethodPost, "/panel/api/server/updatePanel", http.StatusForbidden},
  136. }
  137. for _, tc := range cases {
  138. t.Run(tc.name, func(t *testing.T) {
  139. req := httptest.NewRequest(tc.method, tc.path, nil)
  140. req.TLS = &tls.ConnectionState{
  141. VerifiedChains: [][]*x509.Certificate{{&x509.Certificate{}}},
  142. }
  143. w := httptest.NewRecorder()
  144. engine.ServeHTTP(w, req)
  145. if w.Code != tc.want {
  146. t.Fatalf("status = %d, want %d; body=%s", w.Code, tc.want, w.Body.String())
  147. }
  148. })
  149. }
  150. }
  151. // TestCheckAPIAuth_EmptyVerifiedChainsFallsThrough asserts a TLS request with no
  152. // verified client chain is NOT treated as authenticated (it falls through to the
  153. // bearer/session paths) — so the cert branch can't accidentally authorize plain
  154. // browser HTTPS.
  155. func TestCheckAPIAuth_EmptyVerifiedChainsFallsThrough(t *testing.T) {
  156. engine, _ := newAPIAuthTestEngine(t)
  157. req := httptest.NewRequest(http.MethodGet, "/panel/api/ping", nil)
  158. req.TLS = &tls.ConnectionState{} // handshake done, but no client cert verified
  159. req.Header.Set("X-Requested-With", "XMLHttpRequest")
  160. w := httptest.NewRecorder()
  161. engine.ServeHTTP(w, req)
  162. if w.Code != http.StatusUnauthorized {
  163. t.Fatalf("status = %d, want 401 (unauthenticated, no verified chain)", w.Code)
  164. }
  165. }
  166. // TestCheckAPIAuth_RejectsUnauthenticated characterizes the reject paths:
  167. // no credential → 404 (masking); XHR or a presented (but invalid) Bearer → 401
  168. // so script authors can tell auth failure from a wrong base path.
  169. func TestCheckAPIAuth_RejectsUnauthenticated(t *testing.T) {
  170. engine, _ := newAPIAuthTestEngine(t)
  171. cases := []struct {
  172. name string
  173. xhr bool
  174. bearer string // empty = omit Authorization header
  175. want int
  176. }{
  177. {"xhr gets 401", true, "", http.StatusUnauthorized},
  178. {"non-xhr gets 404", false, "", http.StatusNotFound},
  179. {"invalid bearer gets 401", false, "definitely-not-a-token", http.StatusUnauthorized},
  180. {"invalid bearer xhr gets 401", true, "definitely-not-a-token", http.StatusUnauthorized},
  181. }
  182. for _, c := range cases {
  183. t.Run(c.name, func(t *testing.T) {
  184. req := httptest.NewRequest(http.MethodGet, "/panel/api/ping", nil)
  185. if c.xhr {
  186. req.Header.Set("X-Requested-With", "XMLHttpRequest")
  187. }
  188. if c.bearer != "" {
  189. req.Header.Set("Authorization", "Bearer "+c.bearer)
  190. }
  191. w := httptest.NewRecorder()
  192. engine.ServeHTTP(w, req)
  193. if w.Code != c.want {
  194. t.Fatalf("status = %d, want %d", w.Code, c.want)
  195. }
  196. })
  197. }
  198. }
  199. // TestCheckAPIAuth_SessionLoginPasses characterizes the session path: a
  200. // logged-in browser session (no bearer token) reaches the handler.
  201. func TestCheckAPIAuth_SessionLoginPasses(t *testing.T) {
  202. engine, _ := newAPIAuthTestEngine(t)
  203. db := database.GetDB()
  204. var n int64
  205. if err := db.Model(&model.User{}).Count(&n).Error; err != nil {
  206. t.Fatalf("count users: %v", err)
  207. }
  208. if n == 0 {
  209. if err := db.Create(&model.User{Username: "sess", Password: "x"}).Error; err != nil {
  210. t.Fatalf("seed user: %v", err)
  211. }
  212. }
  213. ts := httptest.NewServer(engine)
  214. defer ts.Close()
  215. jar, err := cookiejar.New(nil)
  216. if err != nil {
  217. t.Fatalf("cookiejar: %v", err)
  218. }
  219. client := &http.Client{Jar: jar}
  220. loginResp, err := client.Get(ts.URL + "/test-login")
  221. if err != nil {
  222. t.Fatalf("login: %v", err)
  223. }
  224. loginResp.Body.Close()
  225. if loginResp.StatusCode != http.StatusOK {
  226. t.Fatalf("login status = %d, want 200", loginResp.StatusCode)
  227. }
  228. pingResp, err := client.Get(ts.URL + "/panel/api/ping")
  229. if err != nil {
  230. t.Fatalf("ping: %v", err)
  231. }
  232. pingResp.Body.Close()
  233. if pingResp.StatusCode != http.StatusOK {
  234. t.Fatalf("session ping status = %d, want 200", pingResp.StatusCode)
  235. }
  236. }