router_security_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package initialize
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/gin-gonic/gin"
  7. "github.com/stretchr/testify/require"
  8. "go.uber.org/zap"
  9. "wails-app/internal/config"
  10. "wails-app/internal/global"
  11. )
  12. func setupRouterSecurityTest(t *testing.T, debugRoutes bool) *gin.Engine {
  13. t.Helper()
  14. previousConfig := global.GVA_CONFIG
  15. previousLog := global.GVA_LOG
  16. t.Cleanup(func() {
  17. global.GVA_CONFIG = previousConfig
  18. global.GVA_LOG = previousLog
  19. })
  20. global.GVA_CONFIG = config.Server{}
  21. global.GVA_CONFIG.System.DebugRoutes = debugRoutes
  22. global.GVA_CONFIG.Local.StorePath = "/uploads"
  23. global.GVA_LOG = zap.NewNop()
  24. gin.SetMode(gin.TestMode)
  25. return Routers()
  26. }
  27. func TestDebugRoutesAreNotRegisteredByDefault(t *testing.T) {
  28. router := setupRouterSecurityTest(t, false)
  29. routes := map[string]string{}
  30. for _, route := range router.Routes() {
  31. routes[route.Path] = route.Method
  32. }
  33. require.Equal(t, "POST", routes["/ticket-machine/button"])
  34. require.NotContains(t, routes, "/ticket-machine/test")
  35. require.NotContains(t, routes, "/ticket-machine/debug")
  36. require.NotContains(t, routes, "/ticket-machine/usb-list")
  37. require.NotContains(t, routes, "/channel/test-event")
  38. }
  39. func TestIncidentRoutesRegisteredAndRequireAuth(t *testing.T) {
  40. router := setupRouterSecurityTest(t, false)
  41. cases := []struct{ method, path string }{
  42. {http.MethodGet, "/incident/list"},
  43. {http.MethodGet, "/incident/stats"},
  44. {http.MethodGet, "/incident/1"},
  45. {http.MethodPost, "/incident"},
  46. {http.MethodPost, "/incident/1/transition"},
  47. }
  48. for _, tc := range cases {
  49. recorder := httptest.NewRecorder()
  50. request := httptest.NewRequest(tc.method, tc.path, nil)
  51. router.ServeHTTP(recorder, request)
  52. // 未登录一律 401(说明路由存在且受 JWT 保护)
  53. require.Equal(t, http.StatusUnauthorized, recorder.Code, "%s %s", tc.method, tc.path)
  54. }
  55. }
  56. func TestEnabledDebugRoutesStillRequireAuthentication(t *testing.T) {
  57. router := setupRouterSecurityTest(t, true)
  58. recorder := httptest.NewRecorder()
  59. request := httptest.NewRequest(http.MethodPost, "/channel/test-event?plate=TEST", nil)
  60. router.ServeHTTP(recorder, request)
  61. require.Equal(t, http.StatusUnauthorized, recorder.Code)
  62. require.Contains(t, recorder.Body.String(), "未登录或非法访问")
  63. }