api_auth_test.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. "reflect"
  10. "testing"
  11. "github.com/gin-contrib/sessions"
  12. "github.com/gin-contrib/sessions/cookie"
  13. "github.com/gin-gonic/gin"
  14. "github.com/mhsanaei/3x-ui/v3/internal/database"
  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. if err := database.InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
  31. t.Fatalf("InitDB: %v", err)
  32. }
  33. t.Cleanup(func() { _ = database.CloseDB() })
  34. engine := gin.New()
  35. store := cookie.NewStore([]byte("api-auth-test-secret"))
  36. engine.Use(sessions.Sessions("3x-ui", store))
  37. a := &APIController{}
  38. // Logs in as the first user so the session path can be exercised over a
  39. // cookie round-trip without reaching into checkAPIAuth's internals.
  40. engine.GET("/test-login", func(c *gin.Context) {
  41. u, err := a.userService.GetFirstUser()
  42. if err != nil {
  43. c.Status(http.StatusInternalServerError)
  44. return
  45. }
  46. if err := session.SetLoginUser(c, u); err != nil {
  47. c.Status(http.StatusInternalServerError)
  48. return
  49. }
  50. c.Status(http.StatusOK)
  51. })
  52. api := engine.Group("/panel/api")
  53. api.Use(a.checkAPIAuth)
  54. api.Use(a.enforceTokenScope)
  55. api.GET("/ping", func(c *gin.Context) {
  56. c.JSON(http.StatusOK, gin.H{"api_authed": c.GetBool("api_authed")})
  57. })
  58. api.GET("/server/status", func(c *gin.Context) {
  59. scope, _ := c.Get("api_token_scope")
  60. c.JSON(http.StatusOK, gin.H{"api_authed": c.GetBool("api_authed"), "scope": scope})
  61. })
  62. api.POST("/server/updatePanel", func(c *gin.Context) {
  63. c.JSON(http.StatusOK, gin.H{"reached": true})
  64. })
  65. api.POST("/clients/:email/detach", func(c *gin.Context) {
  66. c.JSON(http.StatusOK, gin.H{"reached": true})
  67. })
  68. api.POST("/inbounds/:id/resetTraffic", func(c *gin.Context) {
  69. c.JSON(http.StatusOK, gin.H{"reached": true})
  70. })
  71. api.POST("/clients/clientIpsByGuid", func(c *gin.Context) {
  72. c.JSON(http.StatusOK, gin.H{"reached": true})
  73. })
  74. return engine, a
  75. }
  76. // TestCheckAPIAuth_BearerSuccess characterizes the bearer-token path: a valid
  77. // token reaches the handler and sets api_authed (the contract the later
  78. // client-cert branch must match).
  79. func TestCheckAPIAuth_BearerSuccess(t *testing.T) {
  80. engine, _ := newAPIAuthTestEngine(t)
  81. const plaintext = "characterization-token-value"
  82. if err := database.GetDB().Create(&model.ApiToken{
  83. Name: "t1",
  84. Token: crypto.HashTokenSHA256(plaintext),
  85. Enabled: true,
  86. Scope: model.ApiScopeAdmin,
  87. }).Error; err != nil {
  88. t.Fatalf("seed token: %v", err)
  89. }
  90. req := httptest.NewRequest(http.MethodGet, "/panel/api/ping", nil)
  91. req.Header.Set("Authorization", "Bearer "+plaintext)
  92. w := httptest.NewRecorder()
  93. engine.ServeHTTP(w, req)
  94. if w.Code != http.StatusOK {
  95. t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
  96. }
  97. if got := w.Body.String(); got != `{"api_authed":true}` {
  98. t.Fatalf("body = %s, want api_authed true", got)
  99. }
  100. }
  101. // TestCheckAPIAuth_AcceptsVerifiedClientCert ensures verified mTLS authenticates
  102. // as node-sync rather than bypassing scope checks as admin.
  103. func TestCheckAPIAuth_AcceptsVerifiedClientCert(t *testing.T) {
  104. engine, _ := newAPIAuthTestEngine(t)
  105. req := httptest.NewRequest(http.MethodGet, "/panel/api/server/status", nil)
  106. req.TLS = &tls.ConnectionState{
  107. VerifiedChains: [][]*x509.Certificate{{&x509.Certificate{}}},
  108. }
  109. w := httptest.NewRecorder()
  110. engine.ServeHTTP(w, req)
  111. if w.Code != http.StatusOK {
  112. t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
  113. }
  114. if got := w.Body.String(); got != `{"api_authed":true,"scope":"node-sync"}` {
  115. t.Fatalf("body = %s, want node-sync scope", got)
  116. }
  117. forbidden := httptest.NewRequest(http.MethodPost, "/panel/api/server/updatePanel", nil)
  118. forbidden.TLS = &tls.ConnectionState{
  119. VerifiedChains: [][]*x509.Certificate{{&x509.Certificate{}}},
  120. }
  121. w = httptest.NewRecorder()
  122. engine.ServeHTTP(w, forbidden)
  123. if w.Code != http.StatusForbidden {
  124. t.Fatalf("updatePanel status = %d, want 403; body=%s", w.Code, w.Body.String())
  125. }
  126. }
  127. func TestNodeSyncScopeAllowlistMatchesRemoteInventory(t *testing.T) {
  128. expected := map[string]map[string]struct{}{
  129. "/server/status": {http.MethodGet: {}},
  130. "/inbounds/list": {http.MethodGet: {}},
  131. "/inbounds/add": {http.MethodPost: {}},
  132. "/inbounds/del/:id": {http.MethodPost: {}},
  133. "/inbounds/update/:id": {http.MethodPost: {}},
  134. "/clients/add": {http.MethodPost: {}},
  135. "/clients/del/:email": {http.MethodPost: {}},
  136. "/clients/:email/detach": {http.MethodPost: {}},
  137. "/clients/update/:email": {http.MethodPost: {}},
  138. "/server/restartXrayService": {http.MethodPost: {}},
  139. "/server/getWebCertFiles": {http.MethodGet: {}},
  140. "/server/descendants": {http.MethodGet: {}},
  141. "/clients/resetTraffic/:email": {http.MethodPost: {}},
  142. "/inbounds/resetAllTraffics": {http.MethodPost: {}},
  143. "/inbounds/:id/resetTraffic": {http.MethodPost: {}},
  144. "/clients/onlinesByGuid": {http.MethodPost: {}},
  145. "/clients/onlines": {http.MethodPost: {}},
  146. "/clients/lastOnline": {http.MethodPost: {}},
  147. "/inbounds/pushClientTraffics": {http.MethodPost: {}},
  148. "/server/clientIps": {http.MethodGet: {}, http.MethodPost: {}},
  149. "/clients/clientIpsByGuid": {http.MethodPost: {}},
  150. "/hosts/list": {http.MethodGet: {}},
  151. }
  152. if !reflect.DeepEqual(nodeSyncScopeAllow, expected) {
  153. t.Fatalf("node-sync allowlist drift:\n got: %#v\nwant: %#v", nodeSyncScopeAllow, expected)
  154. }
  155. if _, ok := nodeSyncScopeAllow["/server/updatePanel"]; ok {
  156. t.Fatal("node-sync must not include /server/updatePanel")
  157. }
  158. }
  159. func TestNodeSyncScopeUsesFullPathPatterns(t *testing.T) {
  160. engine, _ := newAPIAuthTestEngine(t)
  161. cases := []struct {
  162. name string
  163. method string
  164. path string
  165. want int
  166. }{
  167. {"detach email parameter", http.MethodPost, "/panel/api/clients/[email protected]/detach", http.StatusOK},
  168. {"reset inbound id parameter", http.MethodPost, "/panel/api/inbounds/42/resetTraffic", http.StatusOK},
  169. {"client IP by guid endpoint", http.MethodPost, "/panel/api/clients/clientIpsByGuid", http.StatusOK},
  170. {"update panel forbidden", http.MethodPost, "/panel/api/server/updatePanel", http.StatusForbidden},
  171. }
  172. for _, tc := range cases {
  173. t.Run(tc.name, func(t *testing.T) {
  174. req := httptest.NewRequest(tc.method, tc.path, nil)
  175. req.TLS = &tls.ConnectionState{
  176. VerifiedChains: [][]*x509.Certificate{{&x509.Certificate{}}},
  177. }
  178. w := httptest.NewRecorder()
  179. engine.ServeHTTP(w, req)
  180. if w.Code != tc.want {
  181. t.Fatalf("status = %d, want %d; body=%s", w.Code, tc.want, w.Body.String())
  182. }
  183. })
  184. }
  185. }
  186. // TestCheckAPIAuth_EmptyVerifiedChainsFallsThrough asserts a TLS request with no
  187. // verified client chain is NOT treated as authenticated (it falls through to the
  188. // bearer/session paths) — so the cert branch can't accidentally authorize plain
  189. // browser HTTPS.
  190. func TestCheckAPIAuth_EmptyVerifiedChainsFallsThrough(t *testing.T) {
  191. engine, _ := newAPIAuthTestEngine(t)
  192. req := httptest.NewRequest(http.MethodGet, "/panel/api/ping", nil)
  193. req.TLS = &tls.ConnectionState{} // handshake done, but no client cert verified
  194. req.Header.Set("X-Requested-With", "XMLHttpRequest")
  195. w := httptest.NewRecorder()
  196. engine.ServeHTTP(w, req)
  197. if w.Code != http.StatusUnauthorized {
  198. t.Fatalf("status = %d, want 401 (unauthenticated, no verified chain)", w.Code)
  199. }
  200. }
  201. // TestCheckAPIAuth_RejectsUnauthenticated characterizes the reject paths: no
  202. // bearer token and no session yields 401 for XHR callers and 404 otherwise.
  203. func TestCheckAPIAuth_RejectsUnauthenticated(t *testing.T) {
  204. engine, _ := newAPIAuthTestEngine(t)
  205. cases := []struct {
  206. name string
  207. xhr bool
  208. want int
  209. }{
  210. {"xhr gets 401", true, http.StatusUnauthorized},
  211. {"non-xhr gets 404", false, http.StatusNotFound},
  212. }
  213. for _, c := range cases {
  214. t.Run(c.name, func(t *testing.T) {
  215. req := httptest.NewRequest(http.MethodGet, "/panel/api/ping", nil)
  216. if c.xhr {
  217. req.Header.Set("X-Requested-With", "XMLHttpRequest")
  218. }
  219. w := httptest.NewRecorder()
  220. engine.ServeHTTP(w, req)
  221. if w.Code != c.want {
  222. t.Fatalf("status = %d, want %d", w.Code, c.want)
  223. }
  224. })
  225. }
  226. }
  227. // TestCheckAPIAuth_SessionLoginPasses characterizes the session path: a
  228. // logged-in browser session (no bearer token) reaches the handler.
  229. func TestCheckAPIAuth_SessionLoginPasses(t *testing.T) {
  230. engine, _ := newAPIAuthTestEngine(t)
  231. db := database.GetDB()
  232. var n int64
  233. if err := db.Model(&model.User{}).Count(&n).Error; err != nil {
  234. t.Fatalf("count users: %v", err)
  235. }
  236. if n == 0 {
  237. if err := db.Create(&model.User{Username: "sess", Password: "x"}).Error; err != nil {
  238. t.Fatalf("seed user: %v", err)
  239. }
  240. }
  241. ts := httptest.NewServer(engine)
  242. defer ts.Close()
  243. jar, err := cookiejar.New(nil)
  244. if err != nil {
  245. t.Fatalf("cookiejar: %v", err)
  246. }
  247. client := &http.Client{Jar: jar}
  248. loginResp, err := client.Get(ts.URL + "/test-login")
  249. if err != nil {
  250. t.Fatalf("login: %v", err)
  251. }
  252. loginResp.Body.Close()
  253. if loginResp.StatusCode != http.StatusOK {
  254. t.Fatalf("login status = %d, want 200", loginResp.StatusCode)
  255. }
  256. pingResp, err := client.Get(ts.URL + "/panel/api/ping")
  257. if err != nil {
  258. t.Fatalf("ping: %v", err)
  259. }
  260. pingResp.Body.Close()
  261. if pingResp.StatusCode != http.StatusOK {
  262. t.Fatalf("session ping status = %d, want 200", pingResp.StatusCode)
  263. }
  264. }