-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsettings.go
50 lines (40 loc) · 1.31 KB
/
settings.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
import (
"encoding/json"
"fmt"
mapset "github.com/deckarep/golang-set/v2"
kubewarden "github.com/kubewarden/policy-sdk-go"
)
// Settings is the structure that describes the policy settings.
type Settings struct {
ForbiddenResources mapset.Set[string] `json:"forbiddenResources"`
DefaultResource string `json:"defaultResource"`
}
func (s *Settings) Valid() (bool, error) {
if s.DefaultResource == "" {
return false, fmt.Errorf("defaultResource cannot be empty")
}
if s.ForbiddenResources.Contains(s.DefaultResource) {
return false, fmt.Errorf("defaultResource cannot be forbidden")
}
return true, nil
}
func validateSettings(payload []byte) ([]byte, error) {
logger.Info("validating settings")
settings := Settings{
ForbiddenResources: mapset.NewSet[string](),
}
err := json.Unmarshal(payload, &settings)
if err != nil {
return kubewarden.RejectSettings(kubewarden.Message(fmt.Sprintf("Provided settings are not valid: %v", err)))
}
valid, err := settings.Valid()
if err != nil {
return kubewarden.RejectSettings(kubewarden.Message(fmt.Sprintf("Provided settings are not valid: %v", err)))
}
if valid {
return kubewarden.AcceptSettings()
}
logger.Warn("rejecting settings")
return kubewarden.RejectSettings(kubewarden.Message("Provided settings are not valid"))
}