github.com/olli-ai/jx/v2@v2.0.400-0.20210921045218-14731b4dd448/pkg/kube/permissions.go (about)

     1  package kube
     2  
     3  import (
     4  	"github.com/jenkins-x/jx-logging/pkg/log"
     5  	v1 "k8s.io/api/authorization/v1"
     6  	"k8s.io/client-go/kubernetes"
     7  )
     8  
     9  // Resource is the representation of any Kubernetes resource
    10  type Resource string
    11  
    12  // Verb is the representation of the different verbs that can be checked for Kubernetes resources
    13  type Verb string
    14  
    15  const (
    16  	// ClusterRoleBindings is the clusterrolebindings.rbac.authorization.k8s.io resource
    17  	ClusterRoleBindings Resource = "clusterrolebindings"
    18  	// ClusterRoles is the clusterroles.rbac.authorization.k8s.io resource
    19  	ClusterRoles Resource = "clusterrole"
    20  	// CustomResourceDefinitions is the customresourcedefinitions.apiextensions.k8s.io resource
    21  	CustomResourceDefinitions Resource = "customresourcedefinitions"
    22  	// All is the representation of '*' meaning all resources
    23  	All Resource = "'*'"
    24  	// Create represents the create verb
    25  	Create Verb = "create"
    26  	// Delete represents the delete verb
    27  	Delete Verb = "delete"
    28  	// Get represents the get verb
    29  	Get Verb = "get"
    30  	// List represents the list verb
    31  	List Verb = "list"
    32  	// Update represents the update verb
    33  	Update Verb = "use"
    34  	// Watch represents the watch verb
    35  	Watch Verb = "watch"
    36  )
    37  
    38  // CanI will take a verb and a list of resources and it will check whether the current user / service account can
    39  // perform that verb against the resources in the Kubernetes cluster
    40  func CanI(kubeClient kubernetes.Interface, verb Verb, resources ...Resource) (bool, []error) {
    41  	var errList []error
    42  	for _, resource := range resources {
    43  		result, err := kubeClient.AuthorizationV1().SelfSubjectAccessReviews().Create(&v1.SelfSubjectAccessReview{
    44  			Spec: v1.SelfSubjectAccessReviewSpec{
    45  				ResourceAttributes: &v1.ResourceAttributes{
    46  					Verb:     string(verb),
    47  					Resource: string(resource),
    48  				},
    49  			},
    50  		})
    51  		if err != nil {
    52  			errList = append(errList, err)
    53  		} else {
    54  			if !result.Status.Allowed || result.Status.Denied {
    55  				log.Logger().Debugf("Authentication evaluation denied due to: %s", result.Status.Reason)
    56  				return false, errList
    57  			}
    58  		}
    59  	}
    60  
    61  	if len(errList) > 0 {
    62  		return false, errList
    63  	}
    64  	return true, nil
    65  }