diff --git a/helper/policyutil/policyutil.go b/helper/policyutil/policyutil.go index 09fee92fd5..14f25c391f 100644 --- a/helper/policyutil/policyutil.go +++ b/helper/policyutil/policyutil.go @@ -3,13 +3,29 @@ package policyutil import ( "sort" "strings" + + "github.com/hashicorp/vault/helper/strutil" ) func ParsePolicies(policiesRaw string) []string { + if policiesRaw == "" { + return []string{"default"} + } + policies := strings.Split(policiesRaw, ",") + + return SanitizePolicies(policies) +} + +func SanitizePolicies(policies []string) []string { defaultFound := false for i, p := range policies { policies[i] = strings.ToLower(strings.TrimSpace(p)) + // Eliminate unnamed policies. + if policies[i] == "" { + continue + } + // If 'root' policy is present, ignore all other policies. if policies[i] == "root" { policies = []string{"root"} @@ -26,10 +42,7 @@ func ParsePolicies(policiesRaw string) []string { policies = append(policies, "default") } - // Sort to make the computations on policies consistent. - sort.Strings(policies) - - return policies + return strutil.RemoveDuplicates(policies) } // ComparePolicies checks whether the given policy sets are equivalent, as in, diff --git a/helper/strutil/strutil.go b/helper/strutil/strutil.go index de558e8cfd..dd76bea362 100644 --- a/helper/strutil/strutil.go +++ b/helper/strutil/strutil.go @@ -1,5 +1,10 @@ package strutil +import ( + "sort" + "strings" +) + // StrListContains looks for a string in a list of strings. func StrListContains(haystack []string, needle string) bool { for _, item := range haystack { @@ -20,3 +25,35 @@ func StrListSubset(super, sub []string) bool { } return true } + +// Parses a comma separated list of strings into a slice of strings. +// The return slice will be sorted and will not contain duplicate or +// empty items. The values will be converted to lower case. +func ParseStrings(input string) []string { + var parsed []string + if input == "" { + // Don't return nil + return parsed + } + return RemoveDuplicates(strings.Split(input, ",")) +} + +// Removes duplicate and empty elements from a slice of strings. +// This also converts the items in the slice to lower case and +// returns a sorted slice. +func RemoveDuplicates(items []string) []string { + itemsMap := map[string]bool{} + for _, item := range items { + item = strings.ToLower(strings.TrimSpace(item)) + if item == "" { + continue + } + itemsMap[item] = true + } + items = []string{} + for item, _ := range itemsMap { + items = append(items, item) + } + sort.Strings(items) + return items +}