2023-03-15 16:00:52 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2016-03-24 13:41:51 +00:00
|
|
|
package policies
|
|
|
|
|
|
|
|
import "sort"
|
|
|
|
|
|
|
|
// ComparePolicies checks whether the given policy sets are equivalent, as in,
|
|
|
|
// they contain the same values. The benefit of this method is that it leaves
|
|
|
|
// the "default" policy out of its comparisons as it may be added later by core
|
|
|
|
// after a set of policies has been saved by a backend.
|
|
|
|
func EquivalentPolicies(a, b []string) bool {
|
|
|
|
if a == nil && b == nil {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
if a == nil || b == nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// First we'll build maps to ensure unique values and filter default
|
|
|
|
mapA := map[string]bool{}
|
|
|
|
mapB := map[string]bool{}
|
|
|
|
for _, keyA := range a {
|
|
|
|
if keyA == "default" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
mapA[keyA] = true
|
|
|
|
}
|
|
|
|
for _, keyB := range b {
|
|
|
|
if keyB == "default" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
mapB[keyB] = true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Now we'll build our checking slices
|
|
|
|
var sortedA, sortedB []string
|
2021-04-08 16:43:39 +00:00
|
|
|
for keyA := range mapA {
|
2016-03-24 13:41:51 +00:00
|
|
|
sortedA = append(sortedA, keyA)
|
|
|
|
}
|
2021-04-08 16:43:39 +00:00
|
|
|
for keyB := range mapB {
|
2016-03-24 13:41:51 +00:00
|
|
|
sortedB = append(sortedB, keyB)
|
|
|
|
}
|
|
|
|
sort.Strings(sortedA)
|
|
|
|
sort.Strings(sortedB)
|
|
|
|
|
|
|
|
// Finally, compare
|
|
|
|
if len(sortedA) != len(sortedB) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2016-03-24 14:23:09 +00:00
|
|
|
for i := range sortedA {
|
2016-03-24 13:41:51 +00:00
|
|
|
if sortedA[i] != sortedB[i] {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|