generated from kubewarden/go-policy-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsettings.go
78 lines (62 loc) · 2.04 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"fmt"
"regexp"
mapset "github.com/deckarep/golang-set"
kubewarden "github.com/kubewarden/policy-sdk-go"
kubewarden_protocol "github.com/kubewarden/policy-sdk-go/protocol"
"github.com/mailru/easyjson"
)
const invalidSettingsMessage = "Provided settings are not valid"
type Settings struct {
DeniedLabels mapset.Set
ConstrainedLabels map[string]*regexp.Regexp
}
func NewSettingsFromValidationReq(validationReq *kubewarden_protocol.ValidationRequest) (Settings, error) {
return newSettings(validationReq.Settings)
}
func (s *Settings) Validate() error {
constrainedLabels := mapset.NewThreadUnsafeSet()
for label := range s.ConstrainedLabels {
constrainedLabels.Add(label)
}
constrainedAndDenied := constrainedLabels.Intersect(s.DeniedLabels)
if constrainedAndDenied.Cardinality() != 0 {
return fmt.Errorf("the following labels cannot be constrained and denied at the same time: %v", constrainedAndDenied)
}
return nil
}
func newSettings(settingsJson []byte) (Settings, error) {
basicSettings := BasicSettings{}
err := easyjson.Unmarshal(settingsJson, &basicSettings)
if err != nil {
return Settings{}, err
}
deniedLabels := mapset.NewThreadUnsafeSet()
for _, label := range basicSettings.DeniedLabels {
deniedLabels.Add(label)
}
constrainedLabels := make(map[string]*regexp.Regexp)
for name, expr := range basicSettings.ConstrainedLabels {
reg, err := regexp.Compile(expr)
if err != nil {
return Settings{}, fmt.Errorf("compiling regexp %s: %w", expr, err)
}
constrainedLabels[name] = reg
}
return Settings{
DeniedLabels: deniedLabels,
ConstrainedLabels: constrainedLabels,
}, nil
}
func validateSettings(payload []byte) ([]byte, error) {
settings, err := newSettings(payload)
if err != nil {
return kubewarden.RejectSettings(kubewarden.Message(fmt.Sprintf("%s: %v", invalidSettingsMessage, err)))
}
err = settings.Validate()
if err != nil {
return kubewarden.RejectSettings(kubewarden.Message(fmt.Sprintf("%s: %v", invalidSettingsMessage, err)))
}
return kubewarden.AcceptSettings()
}