Skip to content

Commit

Permalink
Add webhook that validated users RBAC rules
Browse files Browse the repository at this point in the history
Signed-off-by: Alexandr Demicev <alexandr.demicev@suse.com>
  • Loading branch information
alexander-demicev committed Sep 9, 2024
1 parent f7ef7df commit 6216ca0
Show file tree
Hide file tree
Showing 8 changed files with 428 additions and 5 deletions.
7 changes: 7 additions & 0 deletions exp/etcdrestore/config/rbac/role.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,13 @@ rules:
- patch
- update
- watch
- apiGroups:
- authorization.k8s.io
resources:
- subjectaccessreviews
verbs:
- create
- get
- apiGroups:
- bootstrap.cluster.x-k8s.io
resources:
Expand Down
48 changes: 48 additions & 0 deletions exp/etcdrestore/config/webhook/manifests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,51 @@ webhooks:
resources:
- rke2configs
sideEffects: None
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
name: validating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-turtles-capi-cattle-io-v1alpha1-etcdmachinesnapshot
failurePolicy: Fail
matchPolicy: Equivalent
name: etcdmachinesnapshot.kb.io
rules:
- apiGroups:
- turtles-capi.cattle.io
apiVersions:
- v1alpha1
operations:
- CREATE
- UPDATE
resources:
- etcdmachinesnapshots
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-turtles-capi-cattle-io-v1alpha1-etcdmachinesnapshotrestore
failurePolicy: Fail
matchPolicy: Equivalent
name: etcdmachinesnapshotrestore.kb.io
rules:
- apiGroups:
- turtles-capi.cattle.io
apiVersions:
- v1alpha1
operations:
- CREATE
- UPDATE
resources:
- etcdmachinesnapshotrestores
sideEffects: None
14 changes: 14 additions & 0 deletions exp/etcdrestore/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,4 +275,18 @@ func setupWebhooks(mgr ctrl.Manager) {
setupLog.Error(err, "unable to create webhook", "webhook", "RKE2Config")
os.Exit(1)
}

if err := (&expwebhooks.EtcdMachineSnapshotWebhook{
Client: mgr.GetClient(),
}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "EtcdMachineSnapshot")
os.Exit(1)
}

if err := (&expwebhooks.EtcdMachineSnapshotRestoreWebhook{
Client: mgr.GetClient(),
}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "EtcdMachineSnapshotRestore")
os.Exit(1)
}
}
101 changes: 101 additions & 0 deletions exp/etcdrestore/webhooks/etcdmachinesnapshot.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
Copyright © 2023 - 2024 SUSE LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package webhooks

import (
"context"
"fmt"

snapshotrestorev1 "github.com/rancher/turtles/exp/etcdrestore/api/v1alpha1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

// +kubebuilder:webhook:path=/validate-turtles-capi-cattle-io-v1alpha1-etcdmachinesnapshot,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,sideEffects=None,groups=turtles-capi.cattle.io,resources=etcdmachinesnapshots,verbs=create;update,versions=v1alpha1,name=etcdmachinesnapshot.kb.io,admissionReviewVersions=v1
// +kubebuilder:rbac:groups=authorization.k8s.io,resources=subjectaccessreviews,verbs=get;create

// EtcdMachineSnapshotWebhook defines a webhook for EtcdMachineSnapshot.
type EtcdMachineSnapshotWebhook struct {
client.Client
}

var _ webhook.CustomValidator = &EtcdMachineSnapshotWebhook{}

// SetupWebhookWithManager sets up and registers the webhook with the manager.
func (r *EtcdMachineSnapshotWebhook) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(&snapshotrestorev1.EtcdMachineSnapshot{}).
WithValidator(r).
Complete()
}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type.
func (r *EtcdMachineSnapshotWebhook) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
logger := log.FromContext(ctx)

logger.Info("Validating EtcdMachineSnapshot")

etcdMachineSnapshot, ok := obj.(*snapshotrestorev1.EtcdMachineSnapshot)
if !ok {
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a EtcdMachineSnapshot but got a %T", obj))
}

return r.validateSpec(ctx, etcdMachineSnapshot)
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type.
func (r *EtcdMachineSnapshotWebhook) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) {
logger := log.FromContext(ctx)

logger.Info("Validating EtcdMachineSnapshot")

etcdMachineSnapshot, ok := newObj.(*snapshotrestorev1.EtcdMachineSnapshot)
if !ok {
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a EtcdMachineSnapshot but got a %T", newObj))
}

return r.validateSpec(ctx, etcdMachineSnapshot)
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type.
func (r *EtcdMachineSnapshotWebhook) ValidateDelete(_ context.Context, obj runtime.Object) (admission.Warnings, error) {
return nil, nil
}

func (r *EtcdMachineSnapshotWebhook) validateSpec(ctx context.Context, etcdMachineSnapshot *snapshotrestorev1.EtcdMachineSnapshot) (admission.Warnings, error) {
var allErrs field.ErrorList

if etcdMachineSnapshot.Spec.ClusterName == "" {
allErrs = append(allErrs, field.Required(field.NewPath("spec.clusterName"), "clusterName is required"))
}

if len(allErrs) > 0 {
return nil, apierrors.NewInvalid(snapshotrestorev1.GroupVersion.WithKind("EtcdMachineSnapshot").GroupKind(), etcdMachineSnapshot.Name, allErrs)
}

if err := validateRBAC(ctx, r.Client, etcdMachineSnapshot.Spec.ClusterName, etcdMachineSnapshot.Namespace); err != nil {
return nil, apierrors.NewBadRequest(fmt.Sprintf("failed to validate RBAC: %v", err))
}

return nil, nil
}
92 changes: 92 additions & 0 deletions exp/etcdrestore/webhooks/etcdsnapshotrestore.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
Copyright © 2023 - 2024 SUSE LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package webhooks

import (
"context"
"fmt"

snapshotrestorev1 "github.com/rancher/turtles/exp/etcdrestore/api/v1alpha1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/validation/field"

ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

// +kubebuilder:webhook:path=/validate-turtles-capi-cattle-io-v1alpha1-etcdmachinesnapshotrestore,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,sideEffects=None,groups=turtles-capi.cattle.io,resources=etcdmachinesnapshotrestores,verbs=create;update,versions=v1alpha1,name=etcdmachinesnapshotrestore.kb.io,admissionReviewVersions=v1

// EtcdMachineSnapshotRestoreWebhook defines a webhook for EtcdMachineSnapshotRestore.
type EtcdMachineSnapshotRestoreWebhook struct {
client.Client
}

var _ webhook.CustomValidator = &EtcdMachineSnapshotRestoreWebhook{}

// SetupWebhookWithManager sets up and registers the webhook with the manager.
func (r *EtcdMachineSnapshotRestoreWebhook) SetupWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(&snapshotrestorev1.EtcdSnapshotRestore{}).
WithValidator(r).
Complete()
}

// ValidateCreate implements webhook.Validator so a webhook will be registered for the type.
func (r *EtcdMachineSnapshotRestoreWebhook) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
logger := log.FromContext(ctx)

logger.Info("Validating EtcdMachineSnapshot")

etcdSnapshotRestore, ok := obj.(*snapshotrestorev1.EtcdSnapshotRestore)
if !ok {
return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a EtcdSnapshotRestore but got a %T", obj))
}

return r.validateSpec(ctx, etcdSnapshotRestore)
}

// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type.
func (r *EtcdMachineSnapshotRestoreWebhook) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) {
return nil, nil
}

// ValidateDelete implements webhook.Validator so a webhook will be registered for the type.
func (r *EtcdMachineSnapshotRestoreWebhook) ValidateDelete(_ context.Context, obj runtime.Object) (admission.Warnings, error) {
return nil, nil
}

func (r *EtcdMachineSnapshotRestoreWebhook) validateSpec(ctx context.Context, etcdSnapshotRestore *snapshotrestorev1.EtcdSnapshotRestore) (admission.Warnings, error) {
var allErrs field.ErrorList

if etcdSnapshotRestore.Spec.ClusterName == "" {
allErrs = append(allErrs, field.Required(field.NewPath("spec.clusterName"), "clusterName is required"))
}

if len(allErrs) > 0 {
return nil, apierrors.NewInvalid(snapshotrestorev1.GroupVersion.WithKind("EtcdMachineSnapshot").GroupKind(), etcdSnapshotRestore.Name, allErrs)
}

if err := validateRBAC(ctx, r.Client, etcdSnapshotRestore.Spec.ClusterName, etcdSnapshotRestore.Namespace); err != nil {
return nil, apierrors.NewBadRequest(fmt.Sprintf("failed to validate RBAC: %v", err))
}

return nil, nil
}
60 changes: 60 additions & 0 deletions exp/etcdrestore/webhooks/rbac.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
Copyright © 2023 - 2024 SUSE LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package webhooks

import (
"context"
"fmt"

authv1 "k8s.io/api/authorization/v1"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

func validateRBAC(ctx context.Context, cl client.Client, clusterName, clusterNamespace string) error {
admissionRequest, err := admission.RequestFromContext(ctx)
if err != nil {
return fmt.Errorf("failed to get admission request from context: %w", err)
}

sar := authv1.SubjectAccessReview{
Spec: authv1.SubjectAccessReviewSpec{
ResourceAttributes: &authv1.ResourceAttributes{
Verb: "*",
Group: clusterv1.GroupVersion.Group,
Version: clusterv1.GroupVersion.Version,
Resource: "clusters",
Name: clusterName,
Namespace: clusterNamespace,
},
User: admissionRequest.UserInfo.Username,
Groups: admissionRequest.UserInfo.Groups,
UID: admissionRequest.UserInfo.UID,
},
}

if err := cl.Create(ctx, &sar); err != nil {
return err
}

if !sar.Status.Allowed {
return fmt.Errorf("user is not allowed to access the cluster: %s", sar.Status.Reason)
}

return nil
}
Loading

0 comments on commit 6216ca0

Please sign in to comment.