[config] fail on setting/unsetting invalid keys

This commit is contained in:
Alex Quick
2017-12-15 09:19:31 -05:00
parent 4bb221d89a
commit e7faec3e26
2 changed files with 36 additions and 0 deletions

View File

@@ -2,6 +2,7 @@ package config
import (
"fmt"
"regexp"
"github.com/dokku/dokku/plugins/common"
)
@@ -12,6 +13,9 @@ func Get(appName string, key string) (value string, ok bool) {
if err != nil {
return "", false
}
if err = validateKey(key); err != nil {
return "", false
}
return env.Get(key)
}
@@ -32,6 +36,11 @@ func SetMany(appName string, entries map[string]string, restart bool) (err error
return
}
keys := make([]string, 0, len(entries))
for k := range entries {
if err = validateKey(k); err != nil {
return
}
}
for k, v := range entries {
env.Set(k, v)
keys = append(keys, k)
@@ -58,6 +67,9 @@ func UnsetMany(appName string, keys []string, restart bool) (err error) {
}
var changed = false
for _, k := range keys {
if err = validateKey(k); err != nil {
return
}
common.LogInfo1(fmt.Sprintf("Unsetting %s", k))
env.Unset(k)
changed = true
@@ -84,3 +96,11 @@ func loadAppOrGlobalEnv(appName string) (env *Env, err error) {
}
return LoadAppEnv(appName)
}
func validateKey(key string) error {
r, _ := regexp.Compile("^[a-zA-Z_][a-zA-Z0-9_]*$")
if !r.MatchString(key) {
return fmt.Errorf("Invalid key name: '%s'", key)
}
return nil
}

View File

@@ -124,6 +124,22 @@ func TestEnvironmentLoading(t *testing.T) {
Expect(err).To(Succeed())
}
func TestInvalidKeys(t *testing.T) {
RegisterTestingT(t)
Expect(setupTestApp()).To(Succeed())
defer teardownTestApp()
invalidKeys := []string{"0invalidKey", "invalid:key", "invalid=Key", "!invalidKey"}
for _, key := range invalidKeys {
Expect(SetMany(testAppName, map[string]string{key: "value"}, false)).NotTo(Succeed())
Expect(UnsetMany(testAppName, []string{key}, false)).NotTo(Succeed())
value, ok := Get(testAppName, key)
Expect(ok).To(Equal(false))
value = GetWithDefault(testAppName, key, "default")
Expect(value).To(Equal("default"))
}
}
func expectValue(appName string, key string, expected string) {
v, ok := Get(appName, key)
Expect(ok).To(Equal(true))