From 7f5f267eef10cf0238adb5a3a74e8bb071cefd16 Mon Sep 17 00:00:00 2001 From: Radek Simko Date: Mon, 10 Jul 2017 00:22:38 +0100 Subject: [PATCH] Enforce field names to be alphanum lowercase + underscores --- helper/schema/schema.go | 14 +++++++++++- helper/schema/schema_test.go | 42 ++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/helper/schema/schema.go b/helper/schema/schema.go index 632672ae0693..acb5618ba265 100644 --- a/helper/schema/schema.go +++ b/helper/schema/schema.go @@ -15,6 +15,7 @@ import ( "fmt" "os" "reflect" + "regexp" "sort" "strconv" "strings" @@ -661,7 +662,13 @@ func (m schemaMap) InternalValidate(topSchemaMap schemaMap) error { if v.ValidateFunc != nil { switch v.Type { case TypeList, TypeSet: - return fmt.Errorf("ValidateFunc is not yet supported on lists or sets.") + return fmt.Errorf("%s: ValidateFunc is not yet supported on lists or sets.", k) + } + } + + if v.Deprecated == "" && v.Removed == "" { + if !isValidFieldName(k) { + return fmt.Errorf("%s: Field name may only contain lowercase alphanumeric characters & underscores.", k) } } } @@ -669,6 +676,11 @@ func (m schemaMap) InternalValidate(topSchemaMap schemaMap) error { return nil } +func isValidFieldName(name string) bool { + re := regexp.MustCompile("^[a-z0-9_]+$") + return re.MatchString(name) +} + func (m schemaMap) diff( k string, schema *Schema, diff --git a/helper/schema/schema_test.go b/helper/schema/schema_test.go index 0a9583aa8556..d5259364ffc1 100644 --- a/helper/schema/schema_test.go +++ b/helper/schema/schema_test.go @@ -3353,6 +3353,48 @@ func TestSchemaMap_InternalValidate(t *testing.T) { }, true, }, + + "invalid field name format #1": { + map[string]*Schema{ + "with space": &Schema{ + Type: TypeString, + Optional: true, + }, + }, + true, + }, + + "invalid field name format #2": { + map[string]*Schema{ + "WithCapitals": &Schema{ + Type: TypeString, + Optional: true, + }, + }, + true, + }, + + "invalid field name format of a Deprecated field": { + map[string]*Schema{ + "WithCapitals": &Schema{ + Type: TypeString, + Optional: true, + Deprecated: "Use with_underscores instead", + }, + }, + false, + }, + + "invalid field name format of a Removed field": { + map[string]*Schema{ + "WithCapitals": &Schema{ + Type: TypeString, + Optional: true, + Removed: "Use with_underscores instead", + }, + }, + false, + }, } for tn, tc := range cases {