diff --git a/constraint/pkg/externaldata/cache.go b/constraint/pkg/externaldata/cache.go index f286a3a9a..edf378954 100644 --- a/constraint/pkg/externaldata/cache.go +++ b/constraint/pkg/externaldata/cache.go @@ -2,6 +2,7 @@ package externaldata import ( "fmt" + "strings" "sync" "github.com/open-policy-agent/frameworks/constraint/pkg/apis/externaldata/v1alpha1" @@ -29,11 +30,25 @@ func (c *ProviderCache) Get(key string) (v1alpha1.Provider, error) { return v1alpha1.Provider{}, fmt.Errorf("key is not found in provider cache") } -func (c *ProviderCache) Upsert(provider *v1alpha1.Provider) { +func (c *ProviderCache) Upsert(provider *v1alpha1.Provider) error { c.mux.Lock() defer c.mux.Unlock() + if !isValidName(provider.Name) { + return fmt.Errorf("provider name can not be empty. value %s", provider.Name) + } + if !isValidURL(provider.Spec.ProxyURL) { + return fmt.Errorf("invalid provider proxy url. value: %s", provider.Spec.ProxyURL) + } + if !isValidTimeout(provider.Spec.Timeout) { + return fmt.Errorf("provider timeout should be a positive integer. value: %d", provider.Spec.Timeout) + } + if !isValidFailurePolicy(string(provider.Spec.FailurePolicy)) { + return fmt.Errorf("provider failure policy should be either Ignore or Fail. value: %s", provider.Spec.FailurePolicy) + } + c.cache[provider.GetName()] = *provider.DeepCopy() + return nil } func (c *ProviderCache) Remove(name string) { @@ -42,3 +57,28 @@ func (c *ProviderCache) Remove(name string) { delete(c.cache, name) } + +func isValidName(name string) bool { + return len(name) != 0 +} + +func isValidURL(url string) bool { + if len(url) == 0 { + return false + } + if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") { + return false + } + return true +} + +func isValidTimeout(timeout int) bool { + return timeout >= 0 +} + +func isValidFailurePolicy(policy string) bool { + if !strings.EqualFold(policy, string(v1alpha1.Ignore)) || !strings.EqualFold(policy, string(v1alpha1.Fail)) { + return false + } + return true +}