Copilot commented on code in PR #2580: URL: https://github.com/apache/apisix-ingress-controller/pull/2580#discussion_r2381441637
########## internal/webhook/v1/reference/checker.go: ########## @@ -0,0 +1,107 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You 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 reference + +import ( + "context" + "fmt" + + "github.com/go-logr/logr" + corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" +) + +// ServiceRef captures the information needed to validate a Service reference. +type ServiceRef struct { + Object client.Object + NamespacedName types.NamespacedName +} + +// SecretRef captures the information needed to validate a Secret reference. +type SecretRef struct { + Object client.Object + NamespacedName types.NamespacedName + Key *string +} + +// Checker performs reference lookups and returns admission warnings on failure. +type Checker struct { + client client.Client + log logr.Logger +} + +// NewChecker constructs a Checker instance. +func NewChecker(c client.Client, log logr.Logger) Checker { + return Checker{client: c, log: log} +} + +// Service ensures the referenced Service exists and returns warnings when it does not. +func (c Checker) Service(ctx context.Context, ref ServiceRef) admission.Warnings { + if ref.NamespacedName.Name == "" || ref.NamespacedName.Namespace == "" { + return nil + } + + var svc corev1.Service + if err := c.client.Get(ctx, ref.NamespacedName, &svc); err != nil { + if k8serrors.IsNotFound(err) { + msg := fmt.Sprintf("Referenced Service '%s/%s' not found", ref.NamespacedName.Namespace, ref.NamespacedName.Name) + return admission.Warnings{msg} + } + c.log.Error(err, "Failed to get Service", + "ownerKind", ref.Object.GetObjectKind().GroupVersionKind().Kind, + "ownerNamespace", ref.Object.GetNamespace(), + "ownerName", ref.Object.GetName(), + "serviceNamespace", ref.NamespacedName.Namespace, + "serviceName", ref.NamespacedName.Name, + ) + } + return nil +} + +// Secret ensures the referenced Secret (and optional key) exists and returns warnings when missing. +func (c Checker) Secret(ctx context.Context, ref SecretRef) admission.Warnings { + if ref.NamespacedName.Name == "" || ref.NamespacedName.Namespace == "" { + return nil + } + + var secret corev1.Secret + if err := c.client.Get(ctx, ref.NamespacedName, &secret); err != nil { + if k8serrors.IsNotFound(err) { + msg := fmt.Sprintf("Referenced Secret '%s/%s' not found", ref.NamespacedName.Namespace, ref.NamespacedName.Name) + return admission.Warnings{msg} + } + c.log.Error(err, "Failed to get Secret", + "ownerKind", ref.Object.GetObjectKind().GroupVersionKind().Kind, + "ownerNamespace", ref.Object.GetNamespace(), + "ownerName", ref.Object.GetName(), + "secretNamespace", ref.NamespacedName.Namespace, + "secretName", ref.NamespacedName.Name, + ) + return nil + } + + if ref.Key != nil { + if _, ok := secret.Data[*ref.Key]; !ok { + msg := fmt.Sprintf("Secret key '%s' not found in Secret '%s/%s'", *ref.Key, ref.NamespacedName.Namespace, ref.NamespacedName.Name) + return admission.Warnings{msg} + } + } Review Comment: The code checks for a key in `secret.Data` but doesn't handle the case where `secret.Data` is nil. This could cause a panic if the secret exists but has no data field initialized. ########## internal/webhook/v1/apisixroute_webhook.go: ########## @@ -0,0 +1,139 @@ +// Licensed to the Apache Software Foundation (ASF) under one or more +// contributor license agreements. See the NOTICE file distributed with +// this work for additional information regarding copyright ownership. +// The ASF licenses this file to You 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 v1 + +import ( + "context" + "fmt" + + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + logf "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/webhook" + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" + + apisixv2 "github.com/apache/apisix-ingress-controller/api/v2" + "github.com/apache/apisix-ingress-controller/internal/webhook/v1/reference" +) + +var apisixRouteLog = logf.Log.WithName("apisixroute-resource") + +func SetupApisixRouteWebhookWithManager(mgr ctrl.Manager) error { + return ctrl.NewWebhookManagedBy(mgr). + For(&apisixv2.ApisixRoute{}). + WithValidator(&ApisixRouteCustomValidator{Client: mgr.GetClient()}). + Complete() +} + +// +kubebuilder:webhook:path=/validate-apisix-apache-org-v2-apisixroute,mutating=false,failurePolicy=fail,sideEffects=None,groups=apisix.apache.org,resources=apisixroutes,verbs=create;update,versions=v2,name=vapisixroute-v2.kb.io,admissionReviewVersions=v1 + +type ApisixRouteCustomValidator struct { + Client client.Client +} + +var _ webhook.CustomValidator = &ApisixRouteCustomValidator{} + +func (v *ApisixRouteCustomValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) { + route, ok := obj.(*apisixv2.ApisixRoute) + if !ok { + return nil, fmt.Errorf("expected an ApisixRoute object but got %T", obj) + } + apisixRouteLog.Info("Validation for ApisixRoute upon creation", "name", route.GetName(), "namespace", route.GetNamespace()) + + return v.collectWarnings(ctx, route), nil +} + +func (v *ApisixRouteCustomValidator) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) { + route, ok := newObj.(*apisixv2.ApisixRoute) + if !ok { + return nil, fmt.Errorf("expected an ApisixRoute object for the newObj but got %T", newObj) + } + apisixRouteLog.Info("Validation for ApisixRoute upon update", "name", route.GetName(), "namespace", route.GetNamespace()) + + return v.collectWarnings(ctx, route), nil +} + +func (*ApisixRouteCustomValidator) ValidateDelete(context.Context, runtime.Object) (admission.Warnings, error) { + return nil, nil +} + +func (v *ApisixRouteCustomValidator) collectWarnings(ctx context.Context, route *apisixv2.ApisixRoute) admission.Warnings { + checker := reference.NewChecker(v.Client, apisixRouteLog) + namespace := route.GetNamespace() + + serviceVisited := make(map[types.NamespacedName]struct{}) + secretVisited := make(map[types.NamespacedName]struct{}) + + var warnings admission.Warnings + + addServiceWarning := func(nn types.NamespacedName) { + if nn.Name == "" || nn.Namespace == "" { + return + } + if _, seen := serviceVisited[nn]; seen { + return + } + serviceVisited[nn] = struct{}{} + warnings = append(warnings, checker.Service(ctx, reference.ServiceRef{ + Object: route, + NamespacedName: nn, + })...) + } + + addSecretWarning := func(nn types.NamespacedName) { + if nn.Name == "" || nn.Namespace == "" { + return + } + if _, seen := secretVisited[nn]; seen { + return + } + secretVisited[nn] = struct{}{} + warnings = append(warnings, checker.Secret(ctx, reference.SecretRef{ + Object: route, + NamespacedName: nn, + })...) Review Comment: [nitpick] The `addServiceWarning` and `addSecretWarning` functions are nearly identical and could be refactored to reduce duplication. Consider creating a generic helper function that takes the visited map and checker function as parameters. ```suggestion addWarning := func( nn types.NamespacedName, visited map[types.NamespacedName]struct{}, checkerFunc func(context.Context, interface{}) admission.Warnings, refConstructor func(*apisixv2.ApisixRoute, types.NamespacedName) interface{}, ) { if nn.Name == "" || nn.Namespace == "" { return } if _, seen := visited[nn]; seen { return } visited[nn] = struct{}{} warnings = append(warnings, checkerFunc(ctx, refConstructor(route, nn))...) } addServiceWarning := func(nn types.NamespacedName) { addWarning( nn, serviceVisited, func(ctx context.Context, ref interface{}) admission.Warnings { return checker.Service(ctx, ref.(reference.ServiceRef)) }, func(route *apisixv2.ApisixRoute, nn types.NamespacedName) interface{} { return reference.ServiceRef{ Object: route, NamespacedName: nn, } }, ) } addSecretWarning := func(nn types.NamespacedName) { addWarning( nn, secretVisited, func(ctx context.Context, ref interface{}) admission.Warnings { return checker.Secret(ctx, ref.(reference.SecretRef)) }, func(route *apisixv2.ApisixRoute, nn types.NamespacedName) interface{} { return reference.SecretRef{ Object: route, NamespacedName: nn, } }, ) ``` -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
