Skip to content

Commit

Permalink
add validations for provider upsert
Browse files Browse the repository at this point in the history
Signed-off-by: Sertac Ozercan <sozercan@gmail.com>
  • Loading branch information
sozercan committed Aug 21, 2021
1 parent 343a919 commit e551920
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion constraint/pkg/externaldata/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package externaldata

import (
"fmt"
"strings"
"sync"

"github.com/open-policy-agent/frameworks/constraint/pkg/apis/externaldata/v1alpha1"
Expand Down Expand Up @@ -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) {
Expand All @@ -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
}

0 comments on commit e551920

Please sign in to comment.