ops_ingress_reject_routes_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package routes
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/Wei-Shaw/sub2api/internal/handler"
  7. adminhandler "github.com/Wei-Shaw/sub2api/internal/handler/admin"
  8. servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
  9. "github.com/gin-gonic/gin"
  10. "github.com/stretchr/testify/require"
  11. )
  12. func TestIngressRejectAdminRoutesRequireAdminAuthentication(t *testing.T) {
  13. gin.SetMode(gin.TestMode)
  14. router := gin.New()
  15. handlers := &handler.Handlers{Admin: &handler.AdminHandlers{Ops: adminhandler.NewOpsHandler(nil)}}
  16. adminAuth := servermiddleware.AdminAuthMiddleware(func(c *gin.Context) {
  17. if c.GetHeader("Authorization") == "" {
  18. servermiddleware.AbortWithError(c, http.StatusUnauthorized, "UNAUTHORIZED", "Authorization required")
  19. return
  20. }
  21. servermiddleware.AbortWithError(c, http.StatusForbidden, "FORBIDDEN", "Admin access required")
  22. })
  23. auditLog := servermiddleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() })
  24. stepUp := servermiddleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() })
  25. RegisterAdminRoutes(router.Group("/api/v1"), handlers, adminAuth, auditLog, stepUp, nil, nil, nil)
  26. for _, path := range []string{
  27. "/api/v1/admin/ops/ingress-rejections",
  28. "/api/v1/admin/ops/ingress-rejections/health",
  29. } {
  30. for _, tc := range []struct {
  31. name string
  32. auth string
  33. wantStatus int
  34. }{
  35. {name: "unauthenticated", wantStatus: http.StatusUnauthorized},
  36. {name: "non-admin", auth: "Bearer user-token", wantStatus: http.StatusForbidden},
  37. } {
  38. t.Run(path+"/"+tc.name, func(t *testing.T) {
  39. recorder := httptest.NewRecorder()
  40. request := httptest.NewRequest(http.MethodGet, path, nil)
  41. if tc.auth != "" {
  42. request.Header.Set("Authorization", tc.auth)
  43. }
  44. router.ServeHTTP(recorder, request)
  45. require.Equal(t, tc.wantStatus, recorder.Code)
  46. })
  47. }
  48. }
  49. }