From 79f8e6efab7c1079265ecbf2485117a486af0eb7 Mon Sep 17 00:00:00 2001 From: Dexter Yan Date: Thu, 23 Mar 2023 04:33:54 +1300 Subject: [PATCH] feat(support-bundle): check if the cluster IsNamespacedScopeRBAC and use current namespace (#1055) feat(support-bundle): add IsNamespacedScope check --- cmd/troubleshoot/cli/run.go | 21 ++++++++++++++++----- pkg/k8sutil/namespace.go | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 5 deletions(-) create mode 100644 pkg/k8sutil/namespace.go diff --git a/cmd/troubleshoot/cli/run.go b/cmd/troubleshoot/cli/run.go index 8d9244c4..d26d3637 100644 --- a/cmd/troubleshoot/cli/run.go +++ b/cmd/troubleshoot/cli/run.go @@ -114,11 +114,6 @@ func runTroubleshoot(v *viper.Viper, arg []string) error { return errors.Wrap(err, "unable to parse selector") } - namespace := "" - if v.GetString("namespace") != "" { - namespace = v.GetString("namespace") - } - config, err := k8sutil.GetRESTConfig() if err != nil { return errors.Wrap(err, "failed to convert kube flags to rest config") @@ -129,6 +124,22 @@ func runTroubleshoot(v *viper.Viper, arg []string) error { return errors.Wrap(err, "failed to convert create k8s client") } + namespace := "" + + if v.GetString("namespace") != "" { + namespace = v.GetString("namespace") + } else { + IsNamespacedScopeRBAC, err := k8sutil.IsNamespacedScopeRBAC(client) + if err != nil { + return errors.Wrap(err, "failed to check if cluster is namespaced") + } + + if !IsNamespacedScopeRBAC { + kubeconfig := k8sutil.GetKubeconfig() + namespace, _, _ = kubeconfig.Namespace() + } + } + var bundlesFromCluster []string // Search cluster for Troubleshoot objects in cluster diff --git a/pkg/k8sutil/namespace.go b/pkg/k8sutil/namespace.go new file mode 100644 index 00000000..0d6ec0b3 --- /dev/null +++ b/pkg/k8sutil/namespace.go @@ -0,0 +1,34 @@ +package k8sutil + +import ( + "context" + + authorizationv1 "k8s.io/api/authorization/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" +) + +func IsNamespacedScopeRBAC(client kubernetes.Interface) (bool, error) { + ctx := context.Background() + + sar := &authorizationv1.SelfSubjectAccessReview{ + Spec: authorizationv1.SelfSubjectAccessReviewSpec{ + ResourceAttributes: &authorizationv1.ResourceAttributes{ + Namespace: "", + Verb: "list", + Resource: "secrets,configmaps", + }, + }, + } + + resp, err := client.AuthorizationV1().SelfSubjectAccessReviews().Create(ctx, sar, metav1.CreateOptions{}) + if err != nil { + return false, err + } + + if resp.Status.Allowed { + return true, nil + } else { + return false, nil + } +}