Skip to content

Commit

Permalink
change webhook
Browse files Browse the repository at this point in the history
Signed-off-by: Aleksandr Zimin <alexandr.zimin@flant.com>
  • Loading branch information
AleksZimin committed May 27, 2024
1 parent b99a0a2 commit b8fd5ca
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions images/webhooks/src/handlers/scValidator.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package handlers

import (
"context"
"encoding/json"
"fmt"

"k8s.io/klog/v2"
Expand Down Expand Up @@ -46,6 +47,17 @@ func SCValidate(ctx context.Context, arReview *model.AdmissionReview, obj metav1
return &kwhvalidating.ValidatorResult{Valid: true},
nil
} else {
changed, err := isStorageClassChangedExceptAnnotations(arReview.OldObjectRaw, arReview.NewObjectRaw)
if err != nil {
return nil, err
}

if !changed {
klog.Infof("User %s is allowed to change annotations for storage classes with provisioner %s", arReview.UserInfo.Username, localCSIProvisioner)
return &kwhvalidating.ValidatorResult{Valid: true},
nil
}

klog.Infof("User %s is not allowed to manage storage classes with provisioner %s", arReview.UserInfo.Username, localCSIProvisioner)
return &kwhvalidating.ValidatorResult{Valid: false, Message: fmt.Sprintf("Manual operations with the StorageClass that uses the %s provisioner are not allowed. Please use LocalStorageClass instead.", localCSIProvisioner)},
nil
Expand All @@ -56,3 +68,34 @@ func SCValidate(ctx context.Context, arReview *model.AdmissionReview, obj metav1
}

}

func isStorageClassChangedExceptAnnotations(oldObjectRaw, newObjectRaw []byte) (bool, error) {
var oldObject, newObject storagev1.StorageClass

if err := json.Unmarshal(oldObjectRaw, &oldObject); err != nil {
err := fmt.Errorf("Failed to unmarshal old object: %v", err)
return false, err
}

if err := json.Unmarshal(newObjectRaw, &newObject); err != nil {
err := fmt.Errorf("Failed to unmarshal new object: %v", err)
return false, err
}

// Save and clear annotations for comparison
oldAnnotations := oldObject.Annotations
newAnnotations := newObject.Annotations
oldObject.Annotations = nil
newObject.Annotations = nil

// Compare objects excluding annotations
if fmt.Sprintf("%+v", oldObject) != fmt.Sprintf("%+v", newObject) {
return true, nil
}

// Restore annotations
oldObject.Annotations = oldAnnotations
newObject.Annotations = newAnnotations

return false, nil
}

0 comments on commit b8fd5ca

Please sign in to comment.