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 577944a
Show file tree
Hide file tree
Showing 9 changed files with 487 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,13 @@ rules:
- patch
- update
- watch
- apiGroups:
- authorization.k8s.io
resources:
- subjectaccessreviews
verbs:
- create
- get
- apiGroups:
- bootstrap.cluster.x-k8s.io
resources:
Expand Down Expand Up @@ -844,4 +851,56 @@ webhooks:
resources:
- rke2configs
sideEffects: None
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
annotations:
cert-manager.io/inject-ca-from: rancher-turtles-system/rancher-turtles-etcdsnapshotrestore-serving-cert
labels:
turtles-capi.cattle.io: etcd-restore
name: rancher-turtles-etcdsnapshotrestore-validating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1
clientConfig:
service:
name: rancher-turtles-etcdsnapshotrestore-webhook-service
namespace: rancher-turtles-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: rancher-turtles-etcdsnapshotrestore-webhook-service
namespace: rancher-turtles-system
path: /validate-turtles-capi-cattle-io-v1alpha1-etcdsnapshotrestore
failurePolicy: Fail
matchPolicy: Equivalent
name: etcdsnapshotrestore.kb.io
rules:
- apiGroups:
- turtles-capi.cattle.io
apiVersions:
- v1alpha1
operations:
- CREATE
- UPDATE
resources:
- etcdsnapshotrestores
sideEffects: None
{{- end }}
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-etcdsnapshotrestore
failurePolicy: Fail
matchPolicy: Equivalent
name: etcdsnapshotrestore.kb.io
rules:
- apiGroups:
- turtles-capi.cattle.io
apiVersions:
- v1alpha1
operations:
- CREATE
- UPDATE
resources:
- etcdsnapshotrestores
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.EtcdSnapshotRestoreWebhook{
Client: mgr.GetClient(),
}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "EtcdSnapshotRestore")
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-etcdsnapshotrestore,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,sideEffects=None,groups=turtles-capi.cattle.io,resources=etcdsnapshotrestores,verbs=create;update,versions=v1alpha1,name=etcdsnapshotrestore.kb.io,admissionReviewVersions=v1

// EtcdSnapshotRestoreWebhook defines a webhook for EtcdSnapshotRestore.
type EtcdSnapshotRestoreWebhook struct {
client.Client
}

var _ webhook.CustomValidator = &EtcdSnapshotRestoreWebhook{}

// SetupWebhookWithManager sets up and registers the webhook with the manager.
func (r *EtcdSnapshotRestoreWebhook) 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 *EtcdSnapshotRestoreWebhook) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
logger := log.FromContext(ctx)

logger.Info("Validating EtcdSnapshotRestore")

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 *EtcdSnapshotRestoreWebhook) 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 *EtcdSnapshotRestoreWebhook) ValidateDelete(_ context.Context, obj runtime.Object) (admission.Warnings, error) {
return nil, nil
}

func (r *EtcdSnapshotRestoreWebhook) 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("EtcdSnapshotRestore").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
}
Loading

0 comments on commit 577944a

Please sign in to comment.