1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-06 16:06:56 +00:00
kyverno/pkg/openapi/validation.go

329 lines
7.8 KiB
Go
Raw Normal View History

2020-03-04 18:56:59 +05:30
package openapi
import (
2020-03-19 20:45:30 +05:30
"encoding/json"
"errors"
2020-03-04 18:56:59 +05:30
"fmt"
"strconv"
"strings"
"sync"
data "github.com/kyverno/kyverno/api"
"github.com/kyverno/kyverno/pkg/engine/utils"
2020-03-04 18:56:59 +05:30
"github.com/kyverno/kyverno/pkg/engine"
2020-03-04 18:56:59 +05:30
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
v1 "github.com/kyverno/kyverno/pkg/api/kyverno/v1"
2020-03-04 18:56:59 +05:30
openapi_v2 "github.com/googleapis/gnostic/OpenAPIv2"
"github.com/googleapis/gnostic/compiler"
"k8s.io/kube-openapi/pkg/util/proto"
"k8s.io/kube-openapi/pkg/util/proto/validation"
2020-03-20 11:43:21 -07:00
log "sigs.k8s.io/controller-runtime/pkg/log"
2020-03-04 18:56:59 +05:30
"gopkg.in/yaml.v2"
)
2020-11-17 13:07:30 -08:00
// Controller represents OpenAPIController
2020-03-27 19:06:06 +05:30
type Controller struct {
2020-06-01 19:36:01 -07:00
mutex sync.RWMutex
definitions map[string]*openapi_v2.Schema
// kindToDefinitionName holds the kind - definition map
// i.e. - Namespace: io.k8s.api.core.v1.Namespace
2020-03-04 18:56:59 +05:30
kindToDefinitionName map[string]string
2020-06-01 19:36:01 -07:00
crdList []string
2020-03-04 18:56:59 +05:30
models proto.Models
}
2020-11-17 13:07:30 -08:00
// NewOpenAPIController initializes a new instance of OpenAPIController
2020-03-27 19:06:06 +05:30
func NewOpenAPIController() (*Controller, error) {
2020-06-01 19:36:01 -07:00
controller := &Controller{
definitions: make(map[string]*openapi_v2.Schema),
kindToDefinitionName: make(map[string]string),
}
2020-03-27 19:06:06 +05:30
2020-03-06 01:09:38 +05:30
defaultDoc, err := getSchemaDocument()
if err != nil {
2020-03-27 19:06:06 +05:30
return nil, err
2020-03-06 01:09:38 +05:30
}
2020-03-04 18:56:59 +05:30
2020-11-17 13:07:30 -08:00
err = controller.useOpenAPIDocument(defaultDoc)
2020-03-06 01:09:38 +05:30
if err != nil {
2020-03-27 19:06:06 +05:30
return nil, err
2020-03-04 18:56:59 +05:30
}
2020-03-27 19:06:06 +05:30
return controller, nil
2020-03-04 18:56:59 +05:30
}
2020-11-17 13:07:30 -08:00
// ValidatePolicyFields ...
2020-03-29 09:09:26 +05:30
func (o *Controller) ValidatePolicyFields(policyRaw []byte) error {
2020-03-27 19:06:06 +05:30
o.mutex.RLock()
defer o.mutex.RUnlock()
2020-03-04 18:56:59 +05:30
var policy v1.ClusterPolicy
err := json.Unmarshal(policyRaw, &policy)
2020-03-19 20:45:30 +05:30
if err != nil {
return err
2020-03-04 18:56:59 +05:30
}
2020-03-19 20:45:30 +05:30
policyUnst, err := utils.ConvertToUnstructured(policyRaw)
if err != nil {
return err
}
2020-03-29 09:09:26 +05:30
err = o.ValidateResource(*policyUnst.DeepCopy(), "ClusterPolicy")
2020-03-19 20:45:30 +05:30
if err != nil {
return err
2020-03-04 18:56:59 +05:30
}
2020-04-01 19:06:13 +05:30
return o.ValidatePolicyMutation(policy)
2020-03-04 18:56:59 +05:30
}
2020-11-17 13:07:30 -08:00
// ValidateResource ...
2020-03-27 19:06:06 +05:30
func (o *Controller) ValidateResource(patchedResource unstructured.Unstructured, kind string) error {
o.mutex.RLock()
defer o.mutex.RUnlock()
2020-03-05 22:50:32 +05:30
var err error
2020-03-04 18:56:59 +05:30
2020-03-27 19:06:06 +05:30
kind = o.kindToDefinitionName[kind]
schema := o.models.LookupModel(kind)
2020-03-04 18:56:59 +05:30
if schema == nil {
2020-03-25 02:15:56 +05:30
// Check if kind is a CRD
schema, err = o.getCRDSchema(kind)
2020-03-05 22:50:32 +05:30
if err != nil || schema == nil {
2020-06-01 19:36:01 -07:00
return fmt.Errorf("pre-validation: couldn't find model %s, err: %v", kind, err)
2020-03-05 22:50:32 +05:30
}
delete(patchedResource.Object, "kind")
2020-03-04 18:56:59 +05:30
}
2020-03-05 22:50:32 +05:30
if errs := validation.ValidateModel(patchedResource.UnstructuredContent(), schema, kind); len(errs) > 0 {
2020-03-04 18:56:59 +05:30
var errorMessages []string
for i := range errs {
errorMessages = append(errorMessages, errs[i].Error())
}
return fmt.Errorf(strings.Join(errorMessages, "\n\n"))
}
return nil
}
2020-11-17 13:07:30 -08:00
// GetDefinitionNameFromKind ...
2020-03-27 19:06:06 +05:30
func (o *Controller) GetDefinitionNameFromKind(kind string) string {
o.mutex.RLock()
defer o.mutex.RUnlock()
return o.kindToDefinitionName[kind]
2020-03-06 03:00:18 +05:30
}
2020-11-17 13:07:30 -08:00
// ValidatePolicyMutation ...
2020-04-01 19:06:13 +05:30
func (o *Controller) ValidatePolicyMutation(policy v1.ClusterPolicy) error {
o.mutex.RLock()
defer o.mutex.RUnlock()
2020-03-04 18:56:59 +05:30
var kindToRules = make(map[string][]v1.Rule)
for _, rule := range policy.Spec.Rules {
if rule.HasMutate() {
for _, kind := range rule.MatchResources.Kinds {
kindToRules[kind] = append(kindToRules[kind], rule)
}
}
}
for kind, rules := range kindToRules {
2020-03-06 01:09:38 +05:30
newPolicy := *policy.DeepCopy()
2020-03-04 18:56:59 +05:30
newPolicy.Spec.Rules = rules
2020-03-29 09:09:26 +05:30
resource, _ := o.generateEmptyResource(o.definitions[o.kindToDefinitionName[kind]]).(map[string]interface{})
if resource == nil || len(resource) == 0 {
log.Log.V(2).Info("unable to validate resource. OpenApi definition not found", "kind", kind)
2020-03-05 22:50:32 +05:30
return nil
}
2020-03-04 18:56:59 +05:30
newResource := unstructured.Unstructured{Object: resource}
newResource.SetKind(kind)
patchedResource, err := engine.ForceMutate(nil, newPolicy, newResource)
2020-03-06 01:09:38 +05:30
if err != nil {
return err
2020-03-04 18:56:59 +05:30
}
2020-03-29 09:09:26 +05:30
err = o.ValidateResource(*patchedResource.DeepCopy(), kind)
2020-03-04 18:56:59 +05:30
if err != nil {
return err
}
}
return nil
}
2020-11-17 13:07:30 -08:00
func (o *Controller) useOpenAPIDocument(doc *openapi_v2.Document) error {
2020-03-27 19:06:06 +05:30
o.mutex.Lock()
defer o.mutex.Unlock()
2020-03-04 18:56:59 +05:30
for _, definition := range doc.GetDefinitions().AdditionalProperties {
2020-03-27 19:06:06 +05:30
o.definitions[definition.GetName()] = definition.GetValue()
2020-03-04 18:56:59 +05:30
path := strings.Split(definition.GetName(), ".")
2020-03-27 19:06:06 +05:30
o.kindToDefinitionName[path[len(path)-1]] = definition.GetName()
2020-03-04 18:56:59 +05:30
}
var err error
o.models, err = proto.NewOpenAPIData(doc)
2020-03-04 18:56:59 +05:30
if err != nil {
return err
}
return nil
}
func getSchemaDocument() (*openapi_v2.Document, error) {
var spec yaml.MapSlice
err := yaml.Unmarshal([]byte(data.SwaggerDoc), &spec)
if err != nil {
return nil, err
}
return openapi_v2.NewDocument(spec, compiler.NewContext("$root", nil))
}
2020-03-06 01:09:38 +05:30
// For crd, we do not store definition in document
func (o *Controller) getCRDSchema(kind string) (proto.Schema, error) {
2020-03-19 20:45:30 +05:30
if kind == "" {
return nil, errors.New("invalid kind")
}
2020-03-06 01:09:38 +05:30
path := proto.NewPath(kind)
2020-03-29 09:09:26 +05:30
definition := o.definitions[kind]
2020-03-19 20:45:30 +05:30
if definition == nil {
return nil, errors.New("could not find definition")
}
// This was added so crd's can access
// normal definitions from existing schema such as
// `metadata` - this maybe a breaking change.
// Removing this may cause policy validate to stop working
2020-03-29 09:09:26 +05:30
existingDefinitions, _ := o.models.(*proto.Definitions)
return (existingDefinitions).ParseSchema(definition, &path)
2020-03-06 01:09:38 +05:30
}
2020-03-27 19:06:06 +05:30
func (o *Controller) generateEmptyResource(kindSchema *openapi_v2.Schema) interface{} {
2020-03-04 18:56:59 +05:30
types := kindSchema.GetType().GetValue()
if kindSchema.GetXRef() != "" {
2020-03-27 19:06:06 +05:30
return o.generateEmptyResource(o.definitions[strings.TrimPrefix(kindSchema.GetXRef(), "#/definitions/")])
2020-03-04 18:56:59 +05:30
}
if len(types) != 1 {
2020-03-05 22:50:32 +05:30
if len(kindSchema.GetProperties().GetAdditionalProperties()) > 0 {
types = []string{"object"}
} else {
return nil
}
2020-03-04 18:56:59 +05:30
}
switch types[0] {
case "object":
return getObjectValue(kindSchema, o)
2020-03-04 18:56:59 +05:30
case "array":
return getArrayValue(kindSchema, o)
2020-03-04 18:56:59 +05:30
case "string":
return getStringValue(kindSchema)
2020-03-04 18:56:59 +05:30
case "integer":
return getNumericValue(kindSchema)
2020-03-04 18:56:59 +05:30
case "number":
return getNumericValue(kindSchema)
2020-03-04 18:56:59 +05:30
case "boolean":
return getBoolValue(kindSchema)
}
log.Log.Info("unknown type", types[0])
return nil
}
func getArrayValue(kindSchema *openapi_v2.Schema, o *Controller) interface{} {
var array []interface{}
for _, schema := range kindSchema.GetItems().GetSchema() {
array = append(array, o.generateEmptyResource(schema))
}
return array
}
func getObjectValue(kindSchema *openapi_v2.Schema, o *Controller) interface{} {
var props = make(map[string]interface{})
properties := kindSchema.GetProperties().GetAdditionalProperties()
if len(properties) == 0 {
return props
}
var wg sync.WaitGroup
var mutex sync.Mutex
wg.Add(len(properties))
for _, property := range properties {
go func(property *openapi_v2.NamedSchema) {
prop := o.generateEmptyResource(property.GetValue())
mutex.Lock()
props[property.GetName()] = prop
mutex.Unlock()
wg.Done()
}(property)
}
wg.Wait()
return props
}
func getBoolValue(kindSchema *openapi_v2.Schema) bool {
if d := kindSchema.GetDefault(); d != nil {
v := getAnyValue(d)
return string(v) == "true"
}
if e := kindSchema.GetExample(); e != nil {
v := getAnyValue(e)
return string(v) == "true"
}
return false
}
func getNumericValue(kindSchema *openapi_v2.Schema) int64 {
if d := kindSchema.GetDefault(); d != nil {
v := getAnyValue(d)
val, _ := strconv.Atoi(string(v))
return int64(val)
}
if e := kindSchema.GetExample(); e != nil {
v := getAnyValue(e)
val, _ := strconv.Atoi(string(v))
return int64(val)
}
return int64(0)
}
func getStringValue(kindSchema *openapi_v2.Schema) string {
if d := kindSchema.GetDefault(); d != nil {
v := getAnyValue(d)
return string(v)
}
if e := kindSchema.GetExample(); e != nil {
v := getAnyValue(e)
return string(v)
}
return ""
}
func getAnyValue(any *openapi_v2.Any) []byte {
if any != nil {
if val := any.GetValue(); val != nil {
return val.GetValue()
2020-03-04 18:56:59 +05:30
}
}
return nil
}