-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsettings.go
57 lines (46 loc) · 1.68 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
package main
import (
"encoding/json"
"fmt"
mapset "github.com/deckarep/golang-set/v2"
kubewarden "github.com/kubewarden/policy-sdk-go"
kubewardenProtocol "github.com/kubewarden/policy-sdk-go/protocol"
)
// Settings defines the settings of the policy
type Settings struct {
RequiredAnnotations map[string]string `json:"requiredAnnotations"`
ForbiddenAnnotations mapset.Set[string] `json:"forbiddenAnnotations"`
}
func NewSettingsFromValidationReq(validationReq *kubewardenProtocol.ValidationRequest) (Settings, error) {
settings := Settings{
// this is required to make the unmarshal work
ForbiddenAnnotations: mapset.NewSet[string](),
}
if err := json.Unmarshal(validationReq.Settings, &settings); err != nil {
return Settings{}, fmt.Errorf("cannot unmarshal settings %w", err)
}
return settings, nil
}
func validateSettings(input []byte) ([]byte, error) {
settings := &Settings{
// this is required to make the unmarshal work
ForbiddenAnnotations: mapset.NewSet[string](),
}
if err := json.Unmarshal(input, &settings); err != nil {
return kubewarden.RejectSettings(kubewarden.Message(fmt.Sprintf("cannot unmarshal settings: %v", err)))
}
return validateCliSettings(settings)
}
func validateCliSettings(settings *Settings) ([]byte, error) {
required := mapset.NewSet[string]()
for key := range settings.RequiredAnnotations {
required.Add(key)
}
forbiddenButRequired := settings.ForbiddenAnnotations.Intersect(required)
if forbiddenButRequired.Cardinality() > 0 {
return kubewarden.RejectSettings(kubewarden.Message(
"The following annotations are forbidden and required at the same time: " + forbiddenButRequired.String(),
))
}
return kubewarden.AcceptSettings()
}