api_auth_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. func TestPanelUpdateRequiresNodeAdminScope(t *testing.T) {
  99. engine, _ := newAPIAuthTestEngine(t)
  100. cases := []struct {
  101. name string
  102. scope string
  103. wantCode int
  104. wantBody string
  105. }{
  106. {"node sync denied", model.ApiScopeNodeSync, http.StatusForbidden, `{"msg":"this API token is not permitted to access this endpoint","success":false}`},
  107. {"node admin allowed", model.ApiScopeNodeAdmin, http.StatusOK, `{"reached":true}`},
  108. {"monitor denied", model.ApiScopeMonitor, http.StatusForbidden, `{"msg":"this API token is not permitted to access this endpoint","success":false}`},
  109. }
  110. for _, tc := range cases {
  111. t.Run(tc.name, func(t *testing.T) {
  112. plaintext := tc.name + "-token"
  113. if err := database.GetDB().Create(&model.ApiToken{
  114. Name: tc.name,
  115. Token: crypto.HashTokenSHA256(plaintext),
  116. Enabled: true,
  117. Scope: tc.scope,
  118. }).Error; err != nil {
  119. t.Fatalf("seed token: %v", err)
  120. }
  121. req := httptest.NewRequest(http.MethodPost, "/panel/api/server/updatePanel", nil)
  122. req.Header.Set("Authorization", "Bearer "+plaintext)
  123. w := httptest.NewRecorder()
  124. engine.ServeHTTP(w, req)
  125. if w.Code != tc.wantCode || w.Body.String() != tc.wantBody {
  126. t.Fatalf("response = %d %s, want %d %s", w.Code, w.Body.String(), tc.wantCode, tc.wantBody)
  127. }
  128. })
  129. }
  130. }
  131. // TestCheckAPIAuth_AcceptsVerifiedClientCert ensures verified mTLS authenticates
  132. // as node-sync rather than bypassing scope checks as admin.
  133. func TestCheckAPIAuth_AcceptsVerifiedClientCert(t *testing.T) {
  134. engine, _ := newAPIAuthTestEngine(t)
  135. req := httptest.NewRequest(http.MethodGet, "/panel/api/server/status", nil)
  136. req.TLS = &tls.ConnectionState{
  137. VerifiedChains: [][]*x509.Certificate{{&x509.Certificate{}}},
  138. }
  139. w := httptest.NewRecorder()
  140. engine.ServeHTTP(w, req)
  141. if w.Code != http.StatusOK {
  142. t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
  143. }
  144. if got := w.Body.String(); got != `{"api_authed":true,"scope":"node-sync"}` {
  145. t.Fatalf("body = %s, want node-sync scope", got)
  146. }
  147. forbidden := httptest.NewRequest(http.MethodPost, "/panel/api/server/updatePanel", nil)
  148. forbidden.TLS = &tls.ConnectionState{
  149. VerifiedChains: [][]*x509.Certificate{{&x509.Certificate{}}},
  150. }
  151. w = httptest.NewRecorder()
  152. engine.ServeHTTP(w, forbidden)
  153. if w.Code != http.StatusForbidden {
  154. t.Fatalf("updatePanel status = %d, want 403; body=%s", w.Code, w.Body.String())
  155. }
  156. for _, legacyScope := range []string{model.ApiScopeAdmin, model.ApiScopeMonitor, model.ApiScopeNodeSync} {
  157. plaintext := "mtls-" + legacyScope + "-token"
  158. if err := database.GetDB().Create(&model.ApiToken{
  159. Name: "mtls-" + legacyScope,
  160. Token: crypto.HashTokenSHA256(plaintext),
  161. Enabled: true,
  162. Scope: legacyScope,
  163. }).Error; err != nil {
  164. t.Fatalf("seed %s token: %v", legacyScope, err)
  165. }
  166. legacy := httptest.NewRequest(http.MethodGet, "/panel/api/server/status", nil)
  167. legacy.Header.Set("Authorization", "Bearer "+plaintext)
  168. legacy.TLS = &tls.ConnectionState{
  169. VerifiedChains: [][]*x509.Certificate{{&x509.Certificate{}}},
  170. }
  171. w = httptest.NewRecorder()
  172. engine.ServeHTTP(w, legacy)
  173. if w.Code != http.StatusOK || w.Body.String() != `{"api_authed":true,"scope":"node-sync"}` {
  174. t.Fatalf("mTLS %s response = %d %s, want preserved node-sync scope", legacyScope, w.Code, w.Body.String())
  175. }
  176. }
  177. const plaintext = "mtls-node-admin-token"
  178. if err := database.GetDB().Create(&model.ApiToken{
  179. Name: "mtls-node-admin",
  180. Token: crypto.HashTokenSHA256(plaintext),
  181. Enabled: true,
  182. Scope: model.ApiScopeNodeAdmin,
  183. }).Error; err != nil {
  184. t.Fatalf("seed node-admin token: %v", err)
  185. }
  186. allowed := httptest.NewRequest(http.MethodPost, "/panel/api/server/updatePanel", nil)
  187. allowed.Header.Set("Authorization", "Bearer "+plaintext)
  188. allowed.TLS = &tls.ConnectionState{
  189. VerifiedChains: [][]*x509.Certificate{{&x509.Certificate{}}},
  190. }
  191. w = httptest.NewRecorder()
  192. engine.ServeHTTP(w, allowed)
  193. if w.Code != http.StatusOK || w.Body.String() != `{"reached":true}` {
  194. t.Fatalf("mTLS node-admin response = %d %s, want 200 update launch", w.Code, w.Body.String())
  195. }
  196. }
  197. func TestNodeSyncScopeUsesFullPathPatterns(t *testing.T) {
  198. engine, _ := newAPIAuthTestEngine(t)
  199. cases := []struct {
  200. name string
  201. method string
  202. path string
  203. want int
  204. }{
  205. {"detach email parameter", http.MethodPost, "/panel/api/clients/[email protected]/detach", http.StatusOK},
  206. {"reset inbound id parameter", http.MethodPost, "/panel/api/inbounds/42/resetTraffic", http.StatusOK},
  207. {"client IP by guid endpoint", http.MethodPost, "/panel/api/clients/clientIpsByGuid", http.StatusOK},
  208. {"update panel forbidden", http.MethodPost, "/panel/api/server/updatePanel", http.StatusForbidden},
  209. }
  210. for _, tc := range cases {
  211. t.Run(tc.name, func(t *testing.T) {
  212. req := httptest.NewRequest(tc.method, tc.path, nil)
  213. req.TLS = &tls.ConnectionState{
  214. VerifiedChains: [][]*x509.Certificate{{&x509.Certificate{}}},
  215. }
  216. w := httptest.NewRecorder()
  217. engine.ServeHTTP(w, req)
  218. if w.Code != tc.want {
  219. t.Fatalf("status = %d, want %d; body=%s", w.Code, tc.want, w.Body.String())
  220. }
  221. })
  222. }
  223. }
  224. // TestCheckAPIAuth_EmptyVerifiedChainsFallsThrough asserts a TLS request with no
  225. // verified client chain is NOT treated as authenticated (it falls through to the
  226. // bearer/session paths) — so the cert branch can't accidentally authorize plain
  227. // browser HTTPS.
  228. func TestCheckAPIAuth_EmptyVerifiedChainsFallsThrough(t *testing.T) {
  229. engine, _ := newAPIAuthTestEngine(t)
  230. req := httptest.NewRequest(http.MethodGet, "/panel/api/ping", nil)
  231. req.TLS = &tls.ConnectionState{} // handshake done, but no client cert verified
  232. req.Header.Set("X-Requested-With", "XMLHttpRequest")
  233. w := httptest.NewRecorder()
  234. engine.ServeHTTP(w, req)
  235. if w.Code != http.StatusUnauthorized {
  236. t.Fatalf("status = %d, want 401 (unauthenticated, no verified chain)", w.Code)
  237. }
  238. }
  239. // TestCheckAPIAuth_RejectsUnauthenticated characterizes the reject paths:
  240. // no credential → 404 (masking); XHR or a presented (but invalid) Bearer → 401
  241. // so script authors can tell auth failure from a wrong base path.
  242. func TestCheckAPIAuth_RejectsUnauthenticated(t *testing.T) {
  243. engine, _ := newAPIAuthTestEngine(t)
  244. cases := []struct {
  245. name string
  246. xhr bool
  247. bearer string // empty = omit Authorization header
  248. want int
  249. }{
  250. {"xhr gets 401", true, "", http.StatusUnauthorized},
  251. {"non-xhr gets 404", false, "", http.StatusNotFound},
  252. {"invalid bearer gets 401", false, "definitely-not-a-token", http.StatusUnauthorized},
  253. {"invalid bearer xhr gets 401", true, "definitely-not-a-token", http.StatusUnauthorized},
  254. }
  255. for _, c := range cases {
  256. t.Run(c.name, func(t *testing.T) {
  257. req := httptest.NewRequest(http.MethodGet, "/panel/api/ping", nil)
  258. if c.xhr {
  259. req.Header.Set("X-Requested-With", "XMLHttpRequest")
  260. }
  261. if c.bearer != "" {
  262. req.Header.Set("Authorization", "Bearer "+c.bearer)
  263. }
  264. w := httptest.NewRecorder()
  265. engine.ServeHTTP(w, req)
  266. if w.Code != c.want {
  267. t.Fatalf("status = %d, want %d", w.Code, c.want)
  268. }
  269. })
  270. }
  271. }
  272. // TestCheckAPIAuth_SessionLoginPasses characterizes the session path: a
  273. // logged-in browser session (no bearer token) reaches the handler.
  274. func TestCheckAPIAuth_SessionLoginPasses(t *testing.T) {
  275. engine, _ := newAPIAuthTestEngine(t)
  276. db := database.GetDB()
  277. var n int64
  278. if err := db.Model(&model.User{}).Count(&n).Error; err != nil {
  279. t.Fatalf("count users: %v", err)
  280. }
  281. if n == 0 {
  282. if err := db.Create(&model.User{Username: "sess", Password: "x"}).Error; err != nil {
  283. t.Fatalf("seed user: %v", err)
  284. }
  285. }
  286. ts := httptest.NewServer(engine)
  287. defer ts.Close()
  288. jar, err := cookiejar.New(nil)
  289. if err != nil {
  290. t.Fatalf("cookiejar: %v", err)
  291. }
  292. client := &http.Client{Jar: jar}
  293. loginResp, err := client.Get(ts.URL + "/test-login")
  294. if err != nil {
  295. t.Fatalf("login: %v", err)
  296. }
  297. loginResp.Body.Close()
  298. if loginResp.StatusCode != http.StatusOK {
  299. t.Fatalf("login status = %d, want 200", loginResp.StatusCode)
  300. }
  301. pingResp, err := client.Get(ts.URL + "/panel/api/ping")
  302. if err != nil {
  303. t.Fatalf("ping: %v", err)
  304. }
  305. pingResp.Body.Close()
  306. if pingResp.StatusCode != http.StatusOK {
  307. t.Fatalf("session ping status = %d, want 200", pingResp.StatusCode)
  308. }
  309. }