github.com/terraform-modules-krish/terratest@v0.29.0/modules/k8s/self_subject_access_review.go (about)

     1  package k8s
     2  
     3  import (
     4  	"context"
     5  
     6  	gruntwork-cli "github.com/terraform-modules-krish/go-commons/errors"
     7  	"github.com/stretchr/testify/require"
     8  	authv1 "k8s.io/api/authorization/v1"
     9  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    10  
    11  	"github.com/terraform-modules-krish/terratest/modules/logger"
    12  	"github.com/terraform-modules-krish/terratest/modules/testing"
    13  )
    14  
    15  // CanIDo returns whether or not the provided action is allowed by the client configured by the provided kubectl option.
    16  // This will fail if there are any errors accessing the kubernetes API (but not if the action is denied).
    17  func CanIDo(t testing.TestingT, options *KubectlOptions, action authv1.ResourceAttributes) bool {
    18  	allowed, err := CanIDoE(t, options, action)
    19  	require.NoError(t, err)
    20  	return allowed
    21  }
    22  
    23  // CanIDoE returns whether or not the provided action is allowed by the client configured by the provided kubectl option.
    24  // This will an error if there are problems accessing the kubernetes API (but not if the action is simply denied).
    25  func CanIDoE(t testing.TestingT, options *KubectlOptions, action authv1.ResourceAttributes) (bool, error) {
    26  	clientset, err := GetKubernetesClientFromOptionsE(t, options)
    27  	if err != nil {
    28  		return false, err
    29  	}
    30  	check := authv1.SelfSubjectAccessReview{
    31  		Spec: authv1.SelfSubjectAccessReviewSpec{ResourceAttributes: &action},
    32  	}
    33  	resp, err := clientset.AuthorizationV1().SelfSubjectAccessReviews().Create(context.Background(), &check, metav1.CreateOptions{})
    34  	if err != nil {
    35  		return false, errors.WithStackTrace(err)
    36  	}
    37  	if !resp.Status.Allowed {
    38  		logger.Logf(t, "Denied action %s on resource %s with name '%s' for reason %s", action.Verb, action.Resource, action.Name, resp.Status.Reason)
    39  	}
    40  	return resp.Status.Allowed, nil
    41  }