2020-03-11 18:14:23 -07:00
|
|
|
package mutate
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
|
2021-10-29 18:13:20 +02:00
|
|
|
kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
|
2020-10-07 11:12:31 -07:00
|
|
|
commonAnchors "github.com/kyverno/kyverno/pkg/engine/anchor/common"
|
|
|
|
"github.com/kyverno/kyverno/pkg/policy/common"
|
2020-03-11 18:14:23 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
// Mutate provides implementation to validate 'mutate' rule
|
|
|
|
type Mutate struct {
|
|
|
|
// rule to hold 'mutate' rule specifications
|
|
|
|
rule kyverno.Mutation
|
|
|
|
}
|
|
|
|
|
|
|
|
//NewMutateFactory returns a new instance of Mutate validation checker
|
|
|
|
func NewMutateFactory(rule kyverno.Mutation) *Mutate {
|
|
|
|
m := Mutate{
|
|
|
|
rule: rule,
|
|
|
|
}
|
|
|
|
return &m
|
|
|
|
}
|
|
|
|
|
2020-03-11 18:14:42 -07:00
|
|
|
//Validate validates the 'mutate' rule
|
2020-03-11 18:14:23 -07:00
|
|
|
func (m *Mutate) Validate() (string, error) {
|
|
|
|
rule := m.rule
|
|
|
|
// JSON Patches
|
|
|
|
if len(rule.Patches) != 0 {
|
|
|
|
for i, patch := range rule.Patches {
|
|
|
|
if err := validatePatch(patch); err != nil {
|
|
|
|
return fmt.Sprintf("patch[%d]", i), err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Overlay
|
|
|
|
if rule.Overlay != nil {
|
2020-08-29 06:52:22 +05:30
|
|
|
path, err := common.ValidatePattern(rule.Overlay, "/", []commonAnchors.IsAnchor{commonAnchors.IsConditionAnchor, commonAnchors.IsAddingAnchor})
|
2020-03-11 18:14:23 -07:00
|
|
|
if err != nil {
|
|
|
|
return path, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Validate if all mandatory PolicyPatch fields are set
|
|
|
|
func validatePatch(pp kyverno.Patch) error {
|
|
|
|
if pp.Path == "" {
|
|
|
|
return errors.New("JSONPatch field 'path' is mandatory")
|
|
|
|
}
|
|
|
|
if pp.Operation == "add" || pp.Operation == "replace" {
|
|
|
|
if pp.Value == nil {
|
|
|
|
return fmt.Errorf("JSONPatch field 'value' is mandatory for operation '%s'", pp.Operation)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
} else if pp.Operation == "remove" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-10-12 23:29:20 +02:00
|
|
|
return fmt.Errorf("unsupported JSONPatch operation '%s'", pp.Operation)
|
2020-03-11 18:14:23 -07:00
|
|
|
}
|