generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 85
Ensures Gateway-API object fields obey kubebuilder max item validation #249
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
carmal891
wants to merge
1
commit into
kubernetes-sigs:main
Choose a base branch
from
carmal891:feat/validate_kube_builder_max_item
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| package i2gw | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "go/ast" | ||
| "reflect" | ||
| "strconv" | ||
| "strings" | ||
|
|
||
| "golang.org/x/tools/go/packages" | ||
| "k8s.io/apimachinery/pkg/util/validation/field" | ||
| ) | ||
|
|
||
| const ( | ||
| KubebuilderMaxItemsMarker = "kubebuilder:validation:MaxItems" | ||
| MaxItemsPrefix = "MaxItems=" | ||
| ) | ||
|
|
||
| // ValidateMaxItems validate fields presnet in the gateway resources object | ||
| func ValidateMaxItems(gwResources *GatewayResources) field.ErrorList { | ||
| var errs field.ErrorList | ||
| maxItemsMap, err := loadGatewayAPITypes() | ||
| if err != nil { | ||
| return append(errs, field.InternalError(nil, | ||
| fmt.Errorf("unable to fetch kubebuilder max items : %v", err))) | ||
| } | ||
|
|
||
| for _, gw := range gwResources.Gateways { | ||
|
|
||
| if reflect.ValueOf(gw).IsZero() { | ||
| continue | ||
| } | ||
|
|
||
| v := reflect.ValueOf(gw) | ||
| if v.Kind() == reflect.Ptr { | ||
| //Get the struct | ||
| v = v.Elem() | ||
| } | ||
|
|
||
| spec := v.FieldByName("Spec") | ||
| if !spec.IsValid() || spec.IsZero() { | ||
| errs = append(errs, field.Required( | ||
| field.NewPath("spec"), | ||
| "spec field missing or empty in gateway resource", | ||
| )) | ||
| return errs | ||
| } | ||
|
|
||
| gatewayErrs := validateSpecFields(spec, maxItemsMap, field.NewPath("spec")) | ||
| errs = append(errs, gatewayErrs...) | ||
|
|
||
| } | ||
| return errs | ||
| } | ||
|
|
||
| // validateSpecFields check fields in spec that are slices and whether exceeded max items limit | ||
| func validateSpecFields(spec reflect.Value, maxItemsMap map[string]int, path *field.Path) field.ErrorList { | ||
| var errs field.ErrorList | ||
|
|
||
| t := spec.Type() | ||
|
|
||
| for i := 0; i < spec.NumField(); i++ { | ||
| fieldVal := spec.Field(i) | ||
| fieldType := t.Field(i) | ||
| fieldName := fieldType.Name | ||
|
|
||
| if fieldVal.Kind() == reflect.Slice && fieldVal.Len() > 0 { | ||
| if maxItems, exists := maxItemsMap[fieldName]; exists { | ||
| if fieldVal.Len() > maxItems { | ||
| errs = append(errs, field.TooMany( | ||
| path.Child(strings.ToLower(fieldName)), | ||
| fieldVal.Len(), | ||
| maxItems, | ||
| )) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return errs | ||
| } | ||
|
|
||
| // loadGatewayAPITypes scans the Gateway API packages and extracts | ||
| // the `+kubebuilder:validation:MaxItems` values defined in struct field comments | ||
| func loadGatewayAPITypes() (map[string]int, error) { | ||
|
|
||
| cfg := &packages.Config{ | ||
| Mode: packages.NeedFiles | packages.NeedSyntax, | ||
| } | ||
|
|
||
| pkgs, err := packages.Load(cfg, | ||
| "sigs.k8s.io/gateway-api/apis/v1", | ||
| "sigs.k8s.io/gateway-api/apis/v1alpha2", | ||
| "sigs.k8s.io/gateway-api/apis/v1beta1", | ||
| "sigs.k8s.io/gateway-api/apis/v1alpha3", | ||
| ) | ||
|
|
||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to load gateway-api package: %w", err) | ||
| } | ||
|
|
||
| maxItemsMap := make(map[string]int) | ||
|
|
||
| for _, pkg := range pkgs { | ||
| for _, file := range pkg.Syntax { | ||
| ast.Inspect(file, func(n ast.Node) bool { | ||
| switch x := n.(type) { | ||
| case *ast.Field: | ||
| if x.Doc != nil { | ||
| for _, comment := range x.Doc.List { | ||
| if strings.Contains(comment.Text, KubebuilderMaxItemsMarker) { | ||
| fieldName := x.Names[0].Name | ||
| if strings.Contains(comment.Text, MaxItemsPrefix) { | ||
| parts := strings.Split(comment.Text, MaxItemsPrefix) | ||
| if len(parts) > 1 { | ||
| valueStr := strings.Split(parts[1], " ")[0] | ||
| if maxItems, err := strconv.Atoi(valueStr); err == nil { | ||
| maxItemsMap[fieldName] = maxItems | ||
| } | ||
|
|
||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| return true | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| return maxItemsMap, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| package i2gw | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "k8s.io/apimachinery/pkg/types" | ||
| gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" | ||
| ) | ||
|
|
||
| func TestValidateMaxItems(t *testing.T) { | ||
|
|
||
| gwResources := &GatewayResources{ | ||
| Gateways: map[types.NamespacedName]gatewayv1.Gateway{ | ||
| {Namespace: "default", Name: "gw1"}: { | ||
| Spec: gatewayv1.GatewaySpec{ | ||
| //Allowed Listeners is 64 | ||
| Listeners: make([]gatewayv1.Listener, 65), | ||
| }, | ||
| }, | ||
| }, | ||
| } | ||
|
|
||
| errs := ValidateMaxItems(gwResources) | ||
|
|
||
| if len(errs) < 1 { | ||
| t.Errorf("expected error, got %d", len(errs)) | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.