Skip to content

Commit

Permalink
Add id field validator and apply to context ids
Browse files Browse the repository at this point in the history
To avoid entry of invalid ids to the context fields.

Signed-off-by: Kobi Samoray <[email protected]>
  • Loading branch information
ksamoray committed Jul 25, 2024
1 parent a4cf354 commit 97e7fea
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
9 changes: 9 additions & 0 deletions nsxt/policy_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"log"
"regexp"
"strings"
"time"

Expand Down Expand Up @@ -447,6 +448,14 @@ func isPolicyPath(policyPath string) bool {
return true
}

func isValidID(id string) bool {
v, err := regexp.MatchString("^[0-9a-zA-Z_\\-]+$", id)
if err != nil {
return false
}
return v
}

func getPolicyIDFromPath(path string) string {
tokens := strings.Split(path, "/")
return tokens[len(tokens)-1]
Expand Down
4 changes: 2 additions & 2 deletions nsxt/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@ func getContextSchema(isRequired, isComputed, isVPC bool) *schema.Schema {
Description: "Id of the project which the resource belongs to.",
Required: true,
ForceNew: true,
ValidateFunc: validation.StringIsNotWhiteSpace,
ValidateFunc: validateID(),
},
}
if isVPC {
Expand All @@ -696,7 +696,7 @@ func getContextSchema(isRequired, isComputed, isVPC bool) *schema.Schema {
Description: "Id of the VPC which the resource belongs to.",
Required: true,
ForceNew: true,
ValidateFunc: validation.StringIsNotWhiteSpace,
ValidateFunc: validateID(),
}
}
return &schema.Schema{
Expand Down
16 changes: 16 additions & 0 deletions nsxt/validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,22 @@ func validatePolicyPath() schema.SchemaValidateFunc {
}
}

func validateID() schema.SchemaValidateFunc {
return func(i interface{}, k string) (s []string, es []error) {
v, ok := i.(string)
if !ok {
es = append(es, fmt.Errorf("expected type of %s to be string", k))
return
}

if !isValidID(v) {
es = append(es, fmt.Errorf("invalid ID atrribute: %s", v))
}

return
}
}

func validateVLANId(i interface{}, k string) (s []string, es []error) {
var vlan int
vlan, ok := i.(int)
Expand Down

0 comments on commit 97e7fea

Please sign in to comment.