router_security_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 TestEnabledDebugRoutesStillRequireAuthentication(t *testing.T) {
  40. router := setupRouterSecurityTest(t, true)
  41. recorder := httptest.NewRecorder()
  42. request := httptest.NewRequest(http.MethodPost, "/channel/test-event?plate=TEST", nil)
  43. router.ServeHTTP(recorder, request)
  44. require.Equal(t, http.StatusUnauthorized, recorder.Code)
  45. require.Contains(t, recorder.Body.String(), "未登录或非法访问")
  46. }