/
create.go
433 lines (373 loc) · 14.3 KB
/
create.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
package commands
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/plexsystems/konstraint/internal/rego"
v1 "github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1"
"github.com/open-policy-agent/frameworks/constraint/pkg/apis/templates/v1beta1"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/yaml"
)
const (
legacyMigrationMessage = " are set with legacy annotations, this functionality will be removed in a future release. Please migrate to OPA Metadata annotations. See konstraint convert."
)
func newCreateCommand() *cobra.Command {
cmd := cobra.Command{
Use: "create <dir>",
Short: "Create Gatekeeper constraints from Rego policies",
Example: `Create constraints in the same directories as the policies
konstraint create examples
Save the constraints in a specific directory
konstraint create examples --output generated-constraints
Create constraints with the Gatekeeper enforcement action set to dryrun
konstraint create examples --dryrun`,
RunE: func(cmd *cobra.Command, args []string) error {
if err := viper.BindPFlag("dryrun", cmd.PersistentFlags().Lookup("dryrun")); err != nil {
return fmt.Errorf("bind dryrun flag: %w", err)
}
if err := viper.BindPFlag("output", cmd.PersistentFlags().Lookup("output")); err != nil {
return fmt.Errorf("bind output flag: %w", err)
}
if err := viper.BindPFlag("skip-constraints", cmd.PersistentFlags().Lookup("skip-constraints")); err != nil {
return fmt.Errorf("bind skip-constraints flag: %w", err)
}
if err := viper.BindPFlag("constraint-template-version", cmd.PersistentFlags().Lookup("constraint-template-version")); err != nil {
return fmt.Errorf("bind constraint-template-version flag: %w", err)
}
if err := viper.BindPFlag("partial-constraints", cmd.PersistentFlags().Lookup("partial-constraints")); err != nil {
return fmt.Errorf("bind partial-constraints flag: %w", err)
}
path := "."
if len(args) > 0 {
path = args[0]
}
return runCreateCommand(path)
},
}
cmd.PersistentFlags().StringP("output", "o", "", "Specify an output directory for the Gatekeeper resources")
cmd.PersistentFlags().BoolP("dryrun", "d", false, "Sets the enforcement action of the constraints to dryrun, overriding the @enforcement tag")
cmd.PersistentFlags().Bool("skip-constraints", false, "Skip generation of constraints")
cmd.PersistentFlags().String("constraint-template-version", "v1beta1", "Set the version of ConstraintTemplates")
cmd.PersistentFlags().Bool("partial-constraints", false, "Generate partial Constraints for policies with parameters")
return &cmd
}
func runCreateCommand(path string) error {
violations, err := rego.GetViolations(path)
if err != nil {
return fmt.Errorf("get violations: %w", err)
}
for _, violation := range violations {
logger := log.WithFields(log.Fields{
"name": violation.Kind(),
"src": violation.Path(),
})
if violation.SkipTemplate() {
logger.Info("Skipping constrainttemplate generation due to configuration")
continue
}
if !isValidEnforcementAction(violation.Enforcement()) {
return fmt.Errorf("enforcement action (%v) is invalid in policy: %s", violation.Enforcement(), violation.Path())
}
templateFileName := "template.yaml"
constraintFileName := "constraint.yaml"
outputDir := filepath.Dir(violation.Path())
if viper.GetString("output") != "" {
outputDir = viper.GetString("output")
templateFileName = fmt.Sprintf("template_%s.yaml", violation.Kind())
constraintFileName = fmt.Sprintf("constraint_%s.yaml", violation.Kind())
}
if err := os.MkdirAll(outputDir, os.ModePerm); err != nil {
return fmt.Errorf("create output dir: %w", err)
}
constraintTemplateVersion := viper.GetString("constraint-template-version")
var constraintTemplate any
switch constraintTemplateVersion {
case "v1":
constraintTemplate = getConstraintTemplatev1(violation, logger)
case "v1beta1":
constraintTemplate = getConstraintTemplatev1beta1(violation, logger)
default:
return fmt.Errorf("unsupported API version for constrainttemplate: %s", constraintTemplateVersion)
}
constraintTemplateBytes, err := yaml.Marshal(constraintTemplate)
if err != nil {
return fmt.Errorf("marshal constrainttemplate: %w", err)
}
if err := os.WriteFile(filepath.Join(outputDir, templateFileName), constraintTemplateBytes, 0644); err != nil {
return fmt.Errorf("writing template: %w", err)
}
if viper.GetBool("skip-constraints") || violation.SkipConstraint() {
logger.Info("Skipping constraint generation due to configuration")
continue
}
// Skip Constraint generation if there are parameters on the template.
if !viper.GetBool("partial-constraints") && (len(violation.Parameters()) > 0 || len(violation.AnnotationParameters()) > 0) {
logger.Warn("Skipping constraint generation due to use of parameters")
continue
}
constraint, err := getConstraint(violation, logger)
if err != nil {
return fmt.Errorf("get constraint: %w", err)
}
constraintBytes, err := yaml.Marshal(constraint)
if err != nil {
return fmt.Errorf("marshal constraint: %w", err)
}
if err := os.WriteFile(filepath.Join(outputDir, constraintFileName), constraintBytes, 0644); err != nil {
return fmt.Errorf("writing constraint: %w", err)
}
}
log.WithField("num_policies", len(violations)).Info("completed successfully")
return nil
}
func getConstraintTemplatev1(violation rego.Rego, logger *log.Entry) *v1.ConstraintTemplate {
constraintTemplate := v1.ConstraintTemplate{
TypeMeta: metav1.TypeMeta{
APIVersion: "templates.gatekeeper.sh/v1",
Kind: "ConstraintTemplate",
},
ObjectMeta: metav1.ObjectMeta{
Name: violation.Name(),
},
Spec: v1.ConstraintTemplateSpec{
CRD: v1.CRD{
Spec: v1.CRDSpec{
Names: v1.Names{
Kind: violation.Kind(),
},
},
},
Targets: []v1.Target{
{
Target: "admission.k8s.gatekeeper.sh",
Libs: violation.Dependencies(),
Rego: violation.Source(),
},
},
},
}
if len(violation.Parameters()) > 0 {
logger.Warn("Parameters" + legacyMigrationMessage)
constraintTemplate.Spec.CRD.Spec.Validation = &v1.Validation{
OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{
Properties: violation.GetOpenAPISchemaProperties(),
Type: "object",
},
}
}
if len(violation.AnnotationParameters()) > 0 {
if constraintTemplate.Spec.CRD.Spec.Validation != nil {
logger.Warn("Parameters already set with legacy annotations, overwriting the parameters using values from OPA Metadata")
}
constraintTemplate.Spec.CRD.Spec.Validation = &v1.Validation{
OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{
Properties: violation.AnnotationParameters(),
Type: "object",
},
}
}
return &constraintTemplate
}
func getConstraintTemplatev1beta1(violation rego.Rego, logger *log.Entry) *v1beta1.ConstraintTemplate {
constraintTemplate := v1beta1.ConstraintTemplate{
TypeMeta: metav1.TypeMeta{
APIVersion: "templates.gatekeeper.sh/v1beta1",
Kind: "ConstraintTemplate",
},
ObjectMeta: metav1.ObjectMeta{
Name: violation.Name(),
},
Spec: v1beta1.ConstraintTemplateSpec{
CRD: v1beta1.CRD{
Spec: v1beta1.CRDSpec{
Names: v1beta1.Names{
Kind: violation.Kind(),
},
},
},
Targets: []v1beta1.Target{
{
Target: "admission.k8s.gatekeeper.sh",
Libs: violation.Dependencies(),
Rego: violation.Source(),
},
},
},
}
if len(violation.Parameters()) > 0 {
logger.Warn("Parameters" + legacyMigrationMessage)
constraintTemplate.Spec.CRD.Spec.Validation = &v1beta1.Validation{
OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{
Properties: violation.GetOpenAPISchemaProperties(),
},
}
}
if len(violation.AnnotationParameters()) > 0 {
if constraintTemplate.Spec.CRD.Spec.Validation != nil {
logger.Warn("Parameters already set with legacy annotations, overwriting the parameters using values from OPA Metadata")
}
constraintTemplate.Spec.CRD.Spec.Validation = &v1beta1.Validation{
OpenAPIV3Schema: &apiextensionsv1.JSONSchemaProps{
Properties: violation.AnnotationParameters(),
},
}
}
return &constraintTemplate
}
func getConstraint(violation rego.Rego, logger *log.Entry) (*unstructured.Unstructured, error) {
gvk := schema.GroupVersionKind{
Group: "constraints.gatekeeper.sh",
Version: "v1beta1",
Kind: violation.Kind(),
}
var constraint unstructured.Unstructured
constraint.SetGroupVersionKind(gvk)
constraint.SetName(violation.Name())
annotations := violation.Annotations()
if annotations != nil {
constraint.SetAnnotations(annotations)
}
labels := violation.Labels()
if labels != nil {
constraint.SetLabels(labels)
}
if violation.Enforcement() != "deny" {
if err := unstructured.SetNestedField(constraint.Object, violation.Enforcement(), "spec", "enforcementAction"); err != nil {
return nil, fmt.Errorf("set constraint enforcement: %w", err)
}
}
// The dryrun flag overrides any enforcement action specified in the rego header.
dryrun := viper.GetBool("dryrun")
if dryrun {
if err := unstructured.SetNestedField(constraint.Object, "dryrun", "spec", "enforcementAction"); err != nil {
return nil, fmt.Errorf("set constraint dryrun: %w", err)
}
}
matchers, err := violation.Matchers()
if err != nil {
return nil, fmt.Errorf("get matchers: %w", err)
}
if len(matchers.KindMatchers) > 0 {
logger.Warn("Kind Matchers" + legacyMigrationMessage)
if err := setKindMatcher(&constraint, matchers.KindMatchers); err != nil {
return nil, fmt.Errorf("set kind matcher: %w", err)
}
}
if len(matchers.MatchLabelsMatcher) > 0 {
logger.Warn("Match Labels Matchers" + legacyMigrationMessage)
if err := setMatchLabelsMatcher(&constraint, matchers.MatchLabelsMatcher); err != nil {
return nil, fmt.Errorf("set match labels matcher: %w", err)
}
}
if len(matchers.MatchExpressionsMatcher) > 0 {
logger.Warn("Match Expressions Matchers" + legacyMigrationMessage)
if err := setMatchExpressionsMatcher(&constraint, matchers.MatchExpressionsMatcher); err != nil {
return nil, fmt.Errorf("set match expressions matcher: %w", err)
}
}
if len(matchers.NamespaceMatcher) > 0 {
logger.Warn("Namespace Matchers" + legacyMigrationMessage)
if err := setNestedStringSlice(&constraint, matchers.NamespaceMatcher, "spec", "match", "namespaces"); err != nil {
return nil, fmt.Errorf("set namespace matcher: %w", err)
}
}
if len(matchers.ExcludedNamespaceMatcher) > 0 {
logger.Warn("Excluded Namespace Matchers" + legacyMigrationMessage)
if err := setNestedStringSlice(&constraint, matchers.ExcludedNamespaceMatcher, "spec", "match", "excludedNamespaces"); err != nil {
return nil, fmt.Errorf("set namespace matcher: %w", err)
}
}
metadataMatchers, ok := violation.GetAnnotation("matchers")
if ok {
if len(matchers.KindMatchers) > 0 ||
len(matchers.MatchLabelsMatcher) > 0 ||
len(matchers.MatchExpressionsMatcher) > 0 ||
len(matchers.NamespaceMatcher) > 0 ||
len(matchers.ExcludedNamespaceMatcher) > 0 {
logger.Warn("Overwriting matchers set with legacy annotations using matchers from OPA Metadata.")
}
if err := unstructured.SetNestedField(constraint.Object, metadataMatchers, "spec", "match"); err != nil {
return nil, fmt.Errorf("set matchers from metadata annotation: %w", err)
}
}
if viper.GetBool("partial-constraints") {
if len(violation.Parameters()) > 0 {
logger.Warn("Parameters" + legacyMigrationMessage)
if err := addParametersToConstraintLegacy(&constraint, violation.Parameters()); err != nil {
return nil, fmt.Errorf("add parameters %v to constraint: %w", violation.Parameters(), err)
}
}
if len(violation.AnnotationParameters()) > 0 {
if err := addParametersToConstraint(&constraint, violation.AnnotationParameters()); err != nil {
return nil, fmt.Errorf("add parameters %v to constraint: %w", violation.AnnotationParameters(), err)
}
}
}
return &constraint, nil
}
func addParametersToConstraint(constraint *unstructured.Unstructured, parameters map[string]apiextensionsv1.JSONSchemaProps) error {
params := make(map[string]any, len(parameters))
for p := range parameters {
params[p] = nil
}
if err := unstructured.SetNestedField(constraint.Object, params, "spec", "parameters"); err != nil {
return fmt.Errorf("set parameters map: %w", err)
}
return nil
}
func addParametersToConstraintLegacy(constraint *unstructured.Unstructured, parameters []rego.Parameter) error {
params := make(map[string]interface{}, len(parameters))
for _, p := range parameters {
params[p.Name] = nil
}
if err := unstructured.SetNestedField(constraint.Object, params, "spec", "parameters"); err != nil {
return fmt.Errorf("set parameters map: %w", err)
}
return nil
}
func setKindMatcher(constraint *unstructured.Unstructured, kindMatchers rego.KindMatchers) error {
if err := unstructured.SetNestedSlice(constraint.Object, kindMatchers.ToSpec(), "spec", "match", "kinds"); err != nil {
return fmt.Errorf("set constraint kinds matchers: %w", err)
}
return nil
}
func setMatchLabelsMatcher(constraint *unstructured.Unstructured, matcher rego.MatchLabelsMatcher) error {
if err := unstructured.SetNestedStringMap(constraint.Object, matcher, "spec", "match", "labelSelector", "matchLabels"); err != nil {
return fmt.Errorf("set constraint labelSelector.matchLabels matchers: %w", err)
}
return nil
}
func setMatchExpressionsMatcher(constraint *unstructured.Unstructured, matcher []rego.MatchExpressionMatcher) error {
marshalled, err := json.Marshal(matcher)
if err != nil {
return err
}
var unmarshalled []interface{}
if err := json.Unmarshal(marshalled, &unmarshalled); err != nil {
return err
}
return unstructured.SetNestedSlice(constraint.Object, unmarshalled, "spec", "match", "labelSelector", "matchExpressions")
}
func setNestedStringSlice(constraint *unstructured.Unstructured, slice []string, path ...string) error {
var values []interface{}
for _, s := range slice {
values = append(values, interface{}(s))
}
return unstructured.SetNestedSlice(constraint.Object, values, path...)
}
func isValidEnforcementAction(action string) bool {
for _, a := range []string{"deny", "dryrun", "warn"} {
if a == action {
return true
}
}
return false
}