generated from kubewarden/go-policy-template
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsettings.go
105 lines (87 loc) · 2.25 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"encoding/json"
mapset "github.com/deckarep/golang-set/v2"
"github.com/kubewarden/gjson"
kubewarden "github.com/kubewarden/policy-sdk-go"
)
type Settings struct {
AllowedTypes mapset.Set[string] `json:"allowedTypes"`
}
// Builds a new Settings instance starting from a validation
// request payload:
//
// {
// "request": ...,
// "settings": {
// "allowedTypes": [
// "configMap",
// "downwardAPI",
// "emptyDir",
// "persistentVolumeClaim",
// "secret",
// "projected"
// ]
// }
// }
func NewSettingsFromValidationReq(payload []byte) (Settings, error) {
settingsJson := gjson.GetBytes(payload, "settings")
settings := Settings{}
err := json.Unmarshal([]byte(settingsJson.Raw), &settings)
if err != nil {
return Settings{}, err
}
return settings, nil
}
// Builds a new Settings instance starting from a Settings
// payload:
//
// {
// "allowedTypes": [
// "configMap",
// "downwardAPI",
// "emptyDir",
// "persistentVolumeClaim",
// "secret",
// "projected"
// ]
// }
func NewSettingsFromValidateSettingsPayload(payload []byte) (Settings, error) {
settings := Settings{}
err := json.Unmarshal(payload, &settings)
if err != nil {
return Settings{}, err
}
return settings, nil
}
func (s *Settings) Valid() bool {
if s.AllowedTypes.Contains("*") && (s.AllowedTypes.Cardinality() != 1) {
return false
}
return true
}
func (s *Settings) UnmarshalJSON(data []byte) error {
// This is needed becaus golang-set v2.3.0 has a bug that prevents
// the correct unmarshalling of ThreadUnsafeSet types.
rawSettings := struct {
AllowedTypes []string `json:"allowedTypes"`
}{}
err := json.Unmarshal(data, &rawSettings)
if err != nil {
return err
}
s.AllowedTypes = mapset.NewThreadUnsafeSet[string](rawSettings.AllowedTypes...)
return nil
}
func validateSettings(payload []byte) ([]byte, error) {
logger.Info("validating settings")
settings, err := NewSettingsFromValidateSettingsPayload(payload)
if err != nil {
return kubewarden.RejectSettings(kubewarden.Message(err.Error()))
}
if settings.Valid() {
return kubewarden.AcceptSettings()
}
logger.Warn("rejecting settings")
return kubewarden.RejectSettings(kubewarden.Message("Provided settings are not valid"))
}