package middleware import ( "apiserver/utils" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "go.uber.org/zap" ) // bug-1949: every IP-whitelist failure must stop the request before the // handler runs. func TestWhitelistIPMiddleware_AbortsOnFailure(t *testing.T) { prevLog := utils.Log utils.Log = zap.NewNop() t.Cleanup(func() { utils.Log = prevLog }) tests := []struct { name string remoteAddr string wantStatus int }{ {"unparsable client IP", "not-an-address", http.StatusBadRequest}, {"client IP not whitelisted", "192.0.2.10:4000", http.StatusForbidden}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gin.SetMode(gin.TestMode) r := gin.New() handlerRan := false r.Use(WhitelistIPMiddleware([]string{"10.0.0.0/8"})) r.GET("/ping", func(ctx *gin.Context) { handlerRan = true ctx.String(http.StatusOK, "pong") }) req := httptest.NewRequest(http.MethodGet, "/ping", nil) req.RemoteAddr = tt.remoteAddr w := httptest.NewRecorder() r.ServeHTTP(w, req) if handlerRan { t.Errorf("handler ran after the IP whitelist rejected %q (status %d)", tt.remoteAddr, w.Code) } if w.Code != tt.wantStatus { t.Errorf("status = %d, want %d", w.Code, tt.wantStatus) } }) } } func TestPathMatchesPattern(t *testing.T) { cases := []struct { pattern string path string want bool }{ // wildcard patterns {"/xce/v1/hosts/*", "/xce/v1/hosts/host1", true}, {"/xce/v1/jobs/*", "/xce/v1/jobs/123/control", true}, {"/xce/v1/roles/*", "/xce/v1/roles/cluster_admin", true}, {"/xce/v1/users/*", "/xce/v1/users/current", true}, {"/xce/v1/users/*", "/xce/v1/users/admin/basic_user", true}, // advisor findings (scheduler-advisor P1): the POST whitelist must // admit the advisor's report path or the URL middleware 403s before // the router (and its advisor:report check) is ever reached. {"/xce/v1/advisor/findings", "/xce/v1/advisor/findings", true}, {"/xce/v1/advisor/findings", "/xce/v1/advisor/findings/extra", false}, // exact patterns {"/xce/v1/hosts", "/xce/v1/hosts", true}, {"/xce/v1/hosts", "/xce/v1/host", false}, {"/xce/v1/roles", "/xce/v1/roles", true}, {"/xce/v1/roles", "/xce/v1/role", false}, {"/xce/v1/clusters", "/xce/v1/clusters", true}, {"/ping", "/ping", true}, {"/ping", "/pin", false}, } for _, tc := range cases { got := pathMatchesPattern(tc.path, tc.pattern) if got != tc.want { t.Errorf("pathMatchesPattern(%q, %q) = %v, want %v", tc.path, tc.pattern, got, tc.want) } } }