From 4c389128d220b788000e45e3f11e5a5da98ddb60 Mon Sep 17 00:00:00 2001 From: Shraddha Bang Date: Thu, 18 Apr 2024 13:19:36 -0700 Subject: [PATCH] Add validation for vpcID in tgb spec --- webhooks/elbv2/targetgroupbinding_validator.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/webhooks/elbv2/targetgroupbinding_validator.go b/webhooks/elbv2/targetgroupbinding_validator.go index 1b0ce5c82..506804a2c 100644 --- a/webhooks/elbv2/targetgroupbinding_validator.go +++ b/webhooks/elbv2/targetgroupbinding_validator.go @@ -2,6 +2,7 @@ package elbv2 import ( "context" + "regexp" "strings" awssdk "github.com/aws/aws-sdk-go/aws" @@ -20,6 +21,8 @@ import ( const apiPathValidateELBv2TargetGroupBinding = "/validate-elbv2-k8s-aws-v1beta1-targetgroupbinding" +var vpcIDPatternRegex = regexp.MustCompile("^(?:vpc-[0-9a-f]{8}|vpc-[0-9a-f]{17})$") + // NewTargetGroupBindingValidator returns a validator for TargetGroupBinding CRD. func NewTargetGroupBindingValidator(k8sClient client.Client, elbv2Client services.ELBV2, vpcID string, logger logr.Logger) *targetGroupBindingValidator { return &targetGroupBindingValidator{ @@ -165,6 +168,9 @@ func (v *targetGroupBindingValidator) checkTargetGroupVpcID(ctx context.Context, if tgb.Spec.VpcID == "" { return nil } + if !vpcIDPatternRegex.MatchString(tgb.Spec.VpcID) { + return errors.Errorf("ValidationError: vpcID %v failed to satisfy constraint: VPC Id must begin with 'vpc-' followed by 8 or 17 lowercase letters (a-f) or numbers.", tgb.Spec.VpcID) + } vpcID, err := v.getVpcIDFromAWS(ctx, tgb.Spec.TargetGroupARN) if err != nil { return errors.Wrap(err, "unable to get target group VpcID")