2023-10-24 16:15:52 +05:30
|
|
|
package conditions
|
2022-12-09 11:24:04 +01:00
|
|
|
|
|
|
|
import (
|
2023-02-01 14:38:04 +08:00
|
|
|
"fmt"
|
|
|
|
|
2022-12-09 11:24:04 +01:00
|
|
|
"github.com/go-logr/logr"
|
|
|
|
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
2024-06-26 10:48:32 +02:00
|
|
|
kyvernov2 "github.com/kyverno/kyverno/api/kyverno/v2"
|
2022-12-09 11:24:04 +01:00
|
|
|
enginecontext "github.com/kyverno/kyverno/pkg/engine/context"
|
|
|
|
"github.com/kyverno/kyverno/pkg/engine/variables"
|
|
|
|
"github.com/kyverno/kyverno/pkg/engine/variables/operator"
|
|
|
|
)
|
|
|
|
|
2024-06-26 10:48:32 +02:00
|
|
|
func CheckAnyAllConditions(logger logr.Logger, ctx enginecontext.Interface, condition kyvernov2.AnyAllConditions) (bool, error) {
|
2022-12-09 11:24:04 +01:00
|
|
|
for _, condition := range condition.AllConditions {
|
|
|
|
if passed, err := checkCondition(logger, ctx, condition); err != nil {
|
|
|
|
return false, err
|
|
|
|
} else if !passed {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, condition := range condition.AnyConditions {
|
|
|
|
if passed, err := checkCondition(logger, ctx, condition); err != nil {
|
|
|
|
return false, err
|
|
|
|
} else if passed {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
}
|
2022-12-12 19:39:29 +01:00
|
|
|
return len(condition.AnyConditions) == 0, nil
|
2022-12-09 11:24:04 +01:00
|
|
|
}
|
|
|
|
|
2024-06-26 10:48:32 +02:00
|
|
|
func checkCondition(logger logr.Logger, ctx enginecontext.Interface, condition kyvernov2.Condition) (bool, error) {
|
2022-12-09 11:24:04 +01:00
|
|
|
key, err := variables.SubstituteAllInPreconditions(logger, ctx, condition.GetKey())
|
|
|
|
if err != nil {
|
2023-02-01 14:38:04 +08:00
|
|
|
return false, fmt.Errorf("failed to substitute variables in condition key: %w", err)
|
2022-12-09 11:24:04 +01:00
|
|
|
}
|
|
|
|
value, err := variables.SubstituteAllInPreconditions(logger, ctx, condition.GetValue())
|
|
|
|
if err != nil {
|
2023-02-01 14:38:04 +08:00
|
|
|
return false, fmt.Errorf("failed to substitute variables in condition value: %w", err)
|
2022-12-09 11:24:04 +01:00
|
|
|
}
|
|
|
|
handler := operator.CreateOperatorHandler(logger, ctx, kyvernov1.ConditionOperator(condition.Operator))
|
|
|
|
if handler == nil {
|
2023-02-01 14:38:04 +08:00
|
|
|
return false, fmt.Errorf("failed to create handler for condition operator: %w", err)
|
2022-12-09 11:24:04 +01:00
|
|
|
}
|
|
|
|
return handler.Evaluate(key, value), nil
|
|
|
|
}
|