2019-12-30 17:08:50 -08:00
package validate
import (
"errors"
"fmt"
"strconv"
2020-03-17 11:05:20 -07:00
"github.com/go-logr/logr"
2020-10-07 11:12:31 -07:00
"github.com/kyverno/kyverno/pkg/engine/anchor"
commonAnchors "github.com/kyverno/kyverno/pkg/engine/anchor/common"
"github.com/kyverno/kyverno/pkg/engine/common"
"github.com/kyverno/kyverno/pkg/engine/operator"
2020-12-08 22:52:37 -08:00
"github.com/kyverno/kyverno/pkg/engine/wildcards"
2019-12-30 17:08:50 -08:00
)
2020-02-14 12:05:13 -08:00
// ValidateResourceWithPattern is a start of element-by-element validation process
2020-02-13 13:57:48 -08:00
// It assumes that validation is started from root, so "/" is passed
2021-07-23 20:53:37 +03:00
func ValidateResourceWithPattern ( logger logr . Logger , resource , pattern interface { } ) ( string , error ) {
2020-08-29 06:52:22 +05:30
// newAnchorMap - to check anchor key has values
ac := common . NewAnchorMap ( )
2021-07-23 20:53:37 +03:00
elemPath , err := validateResourceElement ( logger , resource , pattern , pattern , "/" , ac )
2020-02-13 13:57:48 -08:00
if err != nil {
2020-12-08 22:52:37 -08:00
if common . IsConditionalAnchorError ( err . Error ( ) ) {
return "" , nil
}
2020-08-29 06:52:22 +05:30
if ! ac . IsAnchorError ( ) {
2020-12-04 09:28:30 -08:00
return elemPath , err
2020-08-29 06:52:22 +05:30
}
2020-02-13 13:57:48 -08:00
}
return "" , nil
}
2019-12-30 17:08:50 -08:00
// validateResourceElement detects the element type (map, array, nil, string, int, bool, float)
// and calls corresponding handler
// Pattern tree and resource tree can have different structure. In this case validation fails
2020-08-29 06:52:22 +05:30
func validateResourceElement ( log logr . Logger , resourceElement , patternElement , originPattern interface { } , path string , ac * common . AnchorKey ) ( string , error ) {
2019-12-30 17:08:50 -08:00
switch typedPatternElement := patternElement . ( type ) {
// map
case map [ string ] interface { } :
typedResourceElement , ok := resourceElement . ( map [ string ] interface { } )
if ! ok {
2020-03-17 11:05:20 -07:00
log . V ( 4 ) . Info ( "Pattern and resource have different structures." , "path" , path , "expected" , fmt . Sprintf ( "%T" , patternElement ) , "current" , fmt . Sprintf ( "%T" , resourceElement ) )
2019-12-30 17:08:50 -08:00
return path , fmt . Errorf ( "Pattern and resource have different structures. Path: %s. Expected %T, found %T" , path , patternElement , resourceElement )
}
2020-08-29 06:52:22 +05:30
// CheckAnchorInResource - check anchor anchor key exists in resource and update the AnchorKey fields.
ac . CheckAnchorInResource ( typedPatternElement , typedResourceElement )
return validateMap ( log , typedResourceElement , typedPatternElement , originPattern , path , ac )
2019-12-30 17:08:50 -08:00
// array
case [ ] interface { } :
typedResourceElement , ok := resourceElement . ( [ ] interface { } )
if ! ok {
2020-03-17 11:05:20 -07:00
log . V ( 4 ) . Info ( "Pattern and resource have different structures." , "path" , path , "expected" , fmt . Sprintf ( "%T" , patternElement ) , "current" , fmt . Sprintf ( "%T" , resourceElement ) )
2019-12-30 17:08:50 -08:00
return path , fmt . Errorf ( "Validation rule Failed at path %s, resource does not satisfy the expected overlay pattern" , path )
}
2020-08-29 06:52:22 +05:30
return validateArray ( log , typedResourceElement , typedPatternElement , originPattern , path , ac )
2019-12-30 17:08:50 -08:00
// elementary values
case string , float64 , int , int64 , bool , nil :
/*Analyze pattern */
2020-12-04 09:28:30 -08:00
2021-04-28 23:31:55 +03:00
switch resource := resourceElement . ( type ) {
case [ ] interface { } :
for _ , res := range resource {
if ! ValidateValueWithPattern ( log , res , patternElement ) {
return path , fmt . Errorf ( "Validation rule failed at '%s' to validate value '%v' with pattern '%v'" , path , resourceElement , patternElement )
}
}
return "" , nil
default :
if ! ValidateValueWithPattern ( log , resourceElement , patternElement ) {
return path , fmt . Errorf ( "Validation rule failed at '%s' to validate value '%v' with pattern '%v'" , path , resourceElement , patternElement )
}
2019-12-30 17:08:50 -08:00
}
default :
2020-03-17 11:05:20 -07:00
log . V ( 4 ) . Info ( "Pattern contains unknown type" , "path" , path , "current" , fmt . Sprintf ( "%T" , patternElement ) )
2019-12-30 17:08:50 -08:00
return path , fmt . Errorf ( "Validation rule failed at '%s', pattern contains unknown type" , path )
}
return "" , nil
}
// If validateResourceElement detects map element inside resource and pattern trees, it goes to validateMap
// For each element of the map we must detect the type again, so we pass these elements to validateResourceElement
2020-08-29 06:52:22 +05:30
func validateMap ( log logr . Logger , resourceMap , patternMap map [ string ] interface { } , origPattern interface { } , path string , ac * common . AnchorKey ) ( string , error ) {
2020-12-04 09:28:30 -08:00
patternMap = wildcards . ExpandInMetadata ( patternMap , resourceMap )
2019-12-30 17:08:50 -08:00
// check if there is anchor in pattern
// Phase 1 : Evaluate all the anchors
// Phase 2 : Evaluate non-anchors
anchors , resources := anchor . GetAnchorsResourcesFromMap ( patternMap )
// Evaluate anchors
for key , patternElement := range anchors {
2020-12-04 09:28:30 -08:00
2019-12-30 17:08:50 -08:00
// get handler for each pattern in the pattern
// - Conditional
2020-01-24 12:05:53 -08:00
// - Existence
2019-12-30 17:08:50 -08:00
// - Equality
handler := anchor . CreateElementHandler ( key , patternElement , path )
2020-08-29 06:52:22 +05:30
handlerPath , err := handler . Handle ( validateResourceElement , resourceMap , origPattern , ac )
2019-12-30 17:08:50 -08:00
// if there are resource values at same level, then anchor acts as conditional instead of a strict check
// but if there are non then its a if then check
if err != nil {
2020-08-29 06:52:22 +05:30
// If Conditional anchor fails then we don't process the resources
if commonAnchors . IsConditionAnchor ( key ) {
2020-12-08 22:52:37 -08:00
ac . AnchorError = common . NewConditionalAnchorError ( fmt . Sprintf ( "condition anchor did not satisfy: %s" , err . Error ( ) ) )
log . V ( 3 ) . Info ( ac . AnchorError . Message )
return "" , ac . AnchorError . Error ( )
2019-12-30 17:08:50 -08:00
}
return handlerPath , err
}
}
2020-12-04 09:28:30 -08:00
2019-12-30 17:08:50 -08:00
// Evaluate resources
2020-08-29 06:52:22 +05:30
// getSortedNestedAnchorResource - keeps the anchor key to start of the list
sortedResourceKeys := getSortedNestedAnchorResource ( resources )
for e := sortedResourceKeys . Front ( ) ; e != nil ; e = e . Next ( ) {
key := e . Value . ( string )
handler := anchor . CreateElementHandler ( key , resources [ key ] , path )
handlerPath , err := handler . Handle ( validateResourceElement , resourceMap , origPattern , ac )
2019-12-30 17:08:50 -08:00
if err != nil {
return handlerPath , err
}
}
return "" , nil
}
2020-08-29 06:52:22 +05:30
func validateArray ( log logr . Logger , resourceArray , patternArray [ ] interface { } , originPattern interface { } , path string , ac * common . AnchorKey ) ( string , error ) {
2019-12-30 17:08:50 -08:00
if 0 == len ( patternArray ) {
return path , fmt . Errorf ( "Pattern Array empty" )
}
switch typedPatternElement := patternArray [ 0 ] . ( type ) {
case map [ string ] interface { } :
// This is special case, because maps in arrays can have anchors that must be
// processed with the special way affecting the entire array
2020-12-04 09:28:30 -08:00
elemPath , err := validateArrayOfMaps ( log , resourceArray , typedPatternElement , originPattern , path , ac )
2019-12-30 17:08:50 -08:00
if err != nil {
2020-12-04 09:28:30 -08:00
return elemPath , err
2019-12-30 17:08:50 -08:00
}
2021-04-28 23:31:55 +03:00
case string , float64 , int , int64 , bool , nil :
elemPath , err := validateResourceElement ( log , resourceArray , typedPatternElement , originPattern , path , ac )
if err != nil {
return elemPath , err
}
2019-12-30 17:08:50 -08:00
default :
// In all other cases - detect type and handle each array element with validateResourceElement
2020-07-09 11:50:05 -07:00
if len ( resourceArray ) >= len ( patternArray ) {
for i , patternElement := range patternArray {
currentPath := path + strconv . Itoa ( i ) + "/"
2020-12-04 09:28:30 -08:00
elemPath , err := validateResourceElement ( log , resourceArray [ i ] , patternElement , originPattern , currentPath , ac )
2020-07-09 11:50:05 -07:00
if err != nil {
2020-12-08 22:52:37 -08:00
if common . IsConditionalAnchorError ( err . Error ( ) ) {
continue
}
2020-12-04 09:28:30 -08:00
return elemPath , err
2020-07-09 11:50:05 -07:00
}
2019-12-30 17:08:50 -08:00
}
2020-08-06 10:46:10 +05:30
} else {
2020-07-09 11:50:05 -07:00
return "" , fmt . Errorf ( "Validate Array failed, array length mismatch, resource Array len is %d and pattern Array len is %d" , len ( resourceArray ) , len ( patternArray ) )
2019-12-30 17:08:50 -08:00
}
}
return "" , nil
}
2020-03-17 11:05:20 -07:00
func getValueFromPattern ( log logr . Logger , patternMap map [ string ] interface { } , keys [ ] string , currentKeyIndex int ) ( interface { } , error ) {
2019-12-30 17:08:50 -08:00
for key , pattern := range patternMap {
rawKey := getRawKeyIfWrappedWithAttributes ( key )
if rawKey == keys [ len ( keys ) - 1 ] && currentKeyIndex == len ( keys ) - 1 {
return pattern , nil
} else if rawKey != keys [ currentKeyIndex ] && currentKeyIndex != len ( keys ) - 1 {
continue
}
switch typedPattern := pattern . ( type ) {
case [ ] interface { } :
if keys [ currentKeyIndex ] == rawKey {
for i , value := range typedPattern {
resourceMap , ok := value . ( map [ string ] interface { } )
if ! ok {
2020-03-17 11:05:20 -07:00
log . V ( 4 ) . Info ( "Pattern and resource have different structures." , "expected" , fmt . Sprintf ( "%T" , pattern ) , "current" , fmt . Sprintf ( "%T" , value ) )
2019-12-30 17:08:50 -08:00
return nil , fmt . Errorf ( "Validation rule failed, resource does not have expected pattern %v" , patternMap )
}
if keys [ currentKeyIndex + 1 ] == strconv . Itoa ( i ) {
2020-03-17 11:05:20 -07:00
return getValueFromPattern ( log , resourceMap , keys , currentKeyIndex + 2 )
2019-12-30 17:08:50 -08:00
}
2020-03-24 00:35:05 +05:30
// TODO : SA4004: the surrounding loop is unconditionally terminated (staticcheck)
2019-12-30 17:08:50 -08:00
return nil , errors . New ( "Reference to non-existent place in the document" )
}
2020-03-24 00:35:05 +05:30
return nil , nil // Just a hack to fix the lint
2019-12-30 17:08:50 -08:00
}
return nil , errors . New ( "Reference to non-existent place in the document" )
case map [ string ] interface { } :
if keys [ currentKeyIndex ] == rawKey {
2020-03-17 11:05:20 -07:00
return getValueFromPattern ( log , typedPattern , keys , currentKeyIndex + 1 )
2019-12-30 17:08:50 -08:00
}
return nil , errors . New ( "Reference to non-existent place in the document" )
case string , float64 , int , int64 , bool , nil :
continue
}
}
2020-12-04 09:28:30 -08:00
elemPath := ""
2019-12-30 17:08:50 -08:00
for _ , elem := range keys {
2020-12-04 09:28:30 -08:00
elemPath = "/" + elem + elemPath
2019-12-30 17:08:50 -08:00
}
2020-12-04 09:28:30 -08:00
return nil , fmt . Errorf ( "No value found for specified reference: %s" , elemPath )
2019-12-30 17:08:50 -08:00
}
// validateArrayOfMaps gets anchors from pattern array map element, applies anchors logic
// and then validates each map due to the pattern
2020-08-29 06:52:22 +05:30
func validateArrayOfMaps ( log logr . Logger , resourceMapArray [ ] interface { } , patternMap map [ string ] interface { } , originPattern interface { } , path string , ac * common . AnchorKey ) ( string , error ) {
2019-12-30 17:08:50 -08:00
for i , resourceElement := range resourceMapArray {
// check the types of resource element
// expect it to be map, but can be anything ?:(
currentPath := path + strconv . Itoa ( i ) + "/"
2020-08-29 06:52:22 +05:30
returnpath , err := validateResourceElement ( log , resourceElement , patternMap , originPattern , currentPath , ac )
2019-12-30 17:08:50 -08:00
if err != nil {
2020-12-08 22:52:37 -08:00
if common . IsConditionalAnchorError ( err . Error ( ) ) {
continue
}
2019-12-30 17:08:50 -08:00
return returnpath , err
}
}
return "" , nil
}
2020-01-24 09:37:12 -08:00
func isStringIsReference ( str string ) bool {
if len ( str ) < len ( operator . ReferenceSign ) {
return false
}
return str [ 0 ] == '$' && str [ 1 ] == '(' && str [ len ( str ) - 1 ] == ')'
}