package controllers import ( "apiserver/utils" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" "go.uber.org/zap" ) // bug-1949: a RequirePermission failure must stop the request before the // handler runs. func TestRequirePermission_AbortsOnInvalidToken(t *testing.T) { resetRBACState() prev := utils.AuthenticationYamlConfig utils.AuthenticationYamlConfig = &utils.Authentication{ Token: utils.TokenConfig{Type: "jwt", SecretKey: "rbac-abort-test-secret", TokenExpireTime: 3600}, } utils.Log = zap.NewNop() t.Cleanup(func() { utils.AuthenticationYamlConfig = prev }) gin.SetMode(gin.TestMode) r := gin.New() handlerRan := false r.GET("/protected", RequirePermission("host:view"), func(ctx *gin.Context) { handlerRan = true ReturnSuccess(ctx, http.StatusOK, "success", nil) }) for _, header := range []string{"", "Bearer not-a-jwt"} { handlerRan = false req := httptest.NewRequest(http.MethodGet, "/protected", nil) if header != "" { req.Header.Set("Authorization", header) } w := httptest.NewRecorder() r.ServeHTTP(w, req) if handlerRan { t.Errorf("Authorization %q: handler ran after RequirePermission failed (status %d)", header, w.Code) } if w.Code != http.StatusUnauthorized { t.Errorf("Authorization %q: status = %d, want %d", header, w.Code, http.StatusUnauthorized) } } }