Files
troubleshoot/pkg/supportbundle/rbac.go
Diamon Wiggins 8105fa00e9 Refactor Remote Host Collection (#1633)
* refactor remote collectors

* add remotecollect params struct

* remove commented checkrbac function

* removed unused function

* add temp comments

* refactor to not require RemoteCollect method per collector

* removed unneeded param

* removed unneeded param

* more refactor

* more refactor

* remove unneeded function

* remove debug print

* fix analyzer results

* move rbac to separate file

* be more specific with rbac function name

* fix imports

* fix node list file

* make k8s rest client config consistent with in cluster collection

* add ctx and otel tracing

* add test for allCollectedData

* move runHostCollectorsInPod to spec instead of metadata

* make generate

* fix broken references to supportbundle metadata

* add e2e tests

* update loader tests

* fix tests

* fix hostos remote collector spec

* update remoteHostCollectrs.yaml

---------

Co-authored-by: Dexter Yan <yanshaocong@gmail.com>
2024-10-09 18:38:49 +13:00

73 lines
1.8 KiB
Go

package supportbundle
import (
"context"
"fmt"
"github.com/pkg/errors"
"github.com/replicatedhq/troubleshoot/pkg/collect"
authorizationv1 "k8s.io/api/authorization/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
// Custom error type for RBAC permission errors
type RBACPermissionError struct {
Forbidden []error
}
func (e *RBACPermissionError) Error() string {
return fmt.Sprintf("insufficient permissions: %v", e.Forbidden)
}
func (e *RBACPermissionError) HasErrors() bool {
return len(e.Forbidden) > 0
}
// checkRBAC checks if the current user has the necessary permissions to run the collectors
func checkRemoteCollectorRBAC(ctx context.Context, clientConfig *rest.Config, title string, namespace string) error {
client, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
return errors.Wrap(err, "failed to create client from config")
}
var forbidden []error
spec := authorizationv1.SelfSubjectAccessReviewSpec{
ResourceAttributes: &authorizationv1.ResourceAttributes{
Namespace: namespace,
Verb: "create,delete",
Group: "",
Version: "",
Resource: "pods,configmap",
Subresource: "",
Name: "",
},
NonResourceAttributes: nil,
}
sar := &authorizationv1.SelfSubjectAccessReview{
Spec: spec,
}
resp, err := client.AuthorizationV1().SelfSubjectAccessReviews().Create(ctx, sar, metav1.CreateOptions{})
if err != nil {
return errors.Wrap(err, "failed to run subject review")
}
if !resp.Status.Allowed {
forbidden = append(forbidden, collect.RBACError{
DisplayName: title,
Namespace: spec.ResourceAttributes.Namespace,
Resource: spec.ResourceAttributes.Resource,
Verb: spec.ResourceAttributes.Verb,
})
}
if len(forbidden) > 0 {
return &RBACPermissionError{Forbidden: forbidden}
}
return nil
}