Merge pull request #123405 from cici37/vapGA

[KEP-3488]Promote ValidatingAdmissionPolicy to GA
This commit is contained in:
Kubernetes Prow Robot 2024-03-05 18:29:53 -08:00 committed by GitHub
commit 2b521e5f8e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
99 changed files with 17091 additions and 851 deletions

View File

@ -1255,6 +1255,67 @@
"watch"
]
},
{
"categories": [
"api-extensions"
],
"resource": "validatingadmissionpolicies",
"responseKind": {
"group": "",
"kind": "ValidatingAdmissionPolicy",
"version": ""
},
"scope": "Cluster",
"singularResource": "validatingadmissionpolicy",
"subresources": [
{
"responseKind": {
"group": "",
"kind": "ValidatingAdmissionPolicy",
"version": ""
},
"subresource": "status",
"verbs": [
"get",
"patch",
"update"
]
}
],
"verbs": [
"create",
"delete",
"deletecollection",
"get",
"list",
"patch",
"update",
"watch"
]
},
{
"categories": [
"api-extensions"
],
"resource": "validatingadmissionpolicybindings",
"responseKind": {
"group": "",
"kind": "ValidatingAdmissionPolicyBinding",
"version": ""
},
"scope": "Cluster",
"singularResource": "validatingadmissionpolicybinding",
"verbs": [
"create",
"delete",
"deletecollection",
"get",
"list",
"patch",
"update",
"watch"
]
},
{
"categories": [
"api-extensions"

View File

@ -23,6 +23,57 @@
"watch"
]
},
{
"categories": [
"api-extensions"
],
"kind": "ValidatingAdmissionPolicy",
"name": "validatingadmissionpolicies",
"namespaced": false,
"singularName": "validatingadmissionpolicy",
"storageVersionHash": "P/h9c6yIbaY=",
"verbs": [
"create",
"delete",
"deletecollection",
"get",
"list",
"patch",
"update",
"watch"
]
},
{
"kind": "ValidatingAdmissionPolicy",
"name": "validatingadmissionpolicies/status",
"namespaced": false,
"singularName": "",
"verbs": [
"get",
"patch",
"update"
]
},
{
"categories": [
"api-extensions"
],
"kind": "ValidatingAdmissionPolicyBinding",
"name": "validatingadmissionpolicybindings",
"namespaced": false,
"singularName": "validatingadmissionpolicybinding",
"storageVersionHash": "XYju31JKYek=",
"verbs": [
"create",
"delete",
"deletecollection",
"get",
"list",
"patch",
"update",
"watch"
]
},
{
"categories": [
"api-extensions"

File diff suppressed because it is too large Load Diff

View File

@ -299,7 +299,7 @@ func CreateKubeAPIServerConfig(opts options.CompletedOptions) (
CloudConfigFile: opts.CloudProvider.CloudConfigFile,
}
serviceResolver := buildServiceResolver(opts.EnableAggregatorRouting, genericConfig.LoopbackClientConfig.Host, versionedInformers)
pluginInitializers, admissionPostStartHook, err := admissionConfig.New(proxyTransport, genericConfig.EgressSelector, serviceResolver, genericConfig.TracerProvider)
pluginInitializers, err := admissionConfig.New(proxyTransport, genericConfig.EgressSelector, serviceResolver, genericConfig.TracerProvider)
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to create admission plugin initializer: %v", err)
}
@ -321,9 +321,6 @@ func CreateKubeAPIServerConfig(opts options.CompletedOptions) (
if err != nil {
return nil, nil, nil, fmt.Errorf("failed to apply admission: %w", err)
}
if err := config.GenericConfig.AddPostStartHook("start-kube-apiserver-admission-initializer", admissionPostStartHook); err != nil {
return nil, nil, nil, err
}
if config.GenericConfig.EgressSelector != nil {
// Use the config.GenericConfig.EgressSelector lookup to find the dialer to connect to the kubelet

View File

@ -52,8 +52,8 @@ func startValidatingAdmissionPolicyStatusController(ctx context.Context, control
RestMapper: controllerContext.RESTMapper,
}
c, err := validatingadmissionpolicystatus.NewController(
controllerContext.InformerFactory.Admissionregistration().V1beta1().ValidatingAdmissionPolicies(),
controllerContext.ClientBuilder.ClientOrDie(names.ValidatingAdmissionPolicyStatusController).AdmissionregistrationV1beta1().ValidatingAdmissionPolicies(),
controllerContext.InformerFactory.Admissionregistration().V1().ValidatingAdmissionPolicies(),
controllerContext.ClientBuilder.ClientOrDie(names.ValidatingAdmissionPolicyStatusController).AdmissionregistrationV1().ValidatingAdmissionPolicies(),
typeChecker,
)

View File

@ -151,6 +151,10 @@ func TestDefaulting(t *testing.T) {
{Group: "admissionregistration.k8s.io", Version: "v1beta1", Kind: "ValidatingAdmissionPolicyList"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1beta1", Kind: "ValidatingAdmissionPolicyBinding"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1beta1", Kind: "ValidatingAdmissionPolicyBindingList"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1", Kind: "ValidatingAdmissionPolicy"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1", Kind: "ValidatingAdmissionPolicyList"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1", Kind: "ValidatingAdmissionPolicyBinding"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1", Kind: "ValidatingAdmissionPolicyBindingList"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1", Kind: "ValidatingWebhookConfiguration"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1", Kind: "ValidatingWebhookConfigurationList"}: {},
{Group: "admissionregistration.k8s.io", Version: "v1", Kind: "MutatingWebhookConfiguration"}: {},

View File

@ -93,3 +93,27 @@ func SetDefaults_ServiceReference(obj *admissionregistrationv1.ServiceReference)
obj.Port = utilpointer.Int32(443)
}
}
// SetDefaults_ValidatingAdmissionPolicySpec sets defaults for ValidatingAdmissionPolicySpec
func SetDefaults_ValidatingAdmissionPolicySpec(obj *admissionregistrationv1.ValidatingAdmissionPolicySpec) {
if obj.FailurePolicy == nil {
policy := admissionregistrationv1.Fail
obj.FailurePolicy = &policy
}
}
// SetDefaults_MatchResources sets defaults for MatchResources
func SetDefaults_MatchResources(obj *admissionregistrationv1.MatchResources) {
if obj.MatchPolicy == nil {
policy := admissionregistrationv1.Equivalent
obj.MatchPolicy = &policy
}
if obj.NamespaceSelector == nil {
selector := metav1.LabelSelector{}
obj.NamespaceSelector = &selector
}
if obj.ObjectSelector == nil {
selector := metav1.LabelSelector{}
obj.ObjectSelector = &selector
}
}

View File

@ -132,3 +132,91 @@ func TestDefaultAdmissionWebhook(t *testing.T) {
})
}
}
func TestDefaultAdmissionPolicy(t *testing.T) {
fail := v1.Fail
equivalent := v1.Equivalent
allScopes := v1.AllScopes
tests := []struct {
name string
original runtime.Object
expected runtime.Object
}{
{
name: "ValidatingAdmissionPolicy",
original: &v1.ValidatingAdmissionPolicy{
Spec: v1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1.MatchResources{},
},
},
expected: &v1.ValidatingAdmissionPolicy{
Spec: v1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1.MatchResources{
MatchPolicy: &equivalent,
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
},
FailurePolicy: &fail,
},
},
},
{
name: "ValidatingAdmissionPolicyBinding",
original: &v1.ValidatingAdmissionPolicyBinding{
Spec: v1.ValidatingAdmissionPolicyBindingSpec{
MatchResources: &v1.MatchResources{},
},
},
expected: &v1.ValidatingAdmissionPolicyBinding{
Spec: v1.ValidatingAdmissionPolicyBindingSpec{
MatchResources: &v1.MatchResources{
MatchPolicy: &equivalent,
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
},
},
},
},
{
name: "scope=*",
original: &v1.ValidatingAdmissionPolicy{
Spec: v1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1.MatchResources{
ResourceRules: []v1.NamedRuleWithOperations{{}},
},
},
},
expected: &v1.ValidatingAdmissionPolicy{
Spec: v1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1.MatchResources{
MatchPolicy: &equivalent,
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
Scope: &allScopes, // defaulted
},
},
},
},
},
FailurePolicy: &fail,
},
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
original := test.original
expected := test.expected
legacyscheme.Scheme.Default(original)
if !apiequality.Semantic.DeepEqual(original, expected) {
t.Error(cmp.Diff(expected, original))
}
})
}
}

View File

@ -38,6 +38,26 @@ func init() {
// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(s *runtime.Scheme) error {
if err := s.AddGeneratedConversionFunc((*v1.AuditAnnotation)(nil), (*admissionregistration.AuditAnnotation)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_AuditAnnotation_To_admissionregistration_AuditAnnotation(a.(*v1.AuditAnnotation), b.(*admissionregistration.AuditAnnotation), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.AuditAnnotation)(nil), (*v1.AuditAnnotation)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_AuditAnnotation_To_v1_AuditAnnotation(a.(*admissionregistration.AuditAnnotation), b.(*v1.AuditAnnotation), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ExpressionWarning)(nil), (*admissionregistration.ExpressionWarning)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ExpressionWarning_To_admissionregistration_ExpressionWarning(a.(*v1.ExpressionWarning), b.(*admissionregistration.ExpressionWarning), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.ExpressionWarning)(nil), (*v1.ExpressionWarning)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_ExpressionWarning_To_v1_ExpressionWarning(a.(*admissionregistration.ExpressionWarning), b.(*v1.ExpressionWarning), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.MatchCondition)(nil), (*admissionregistration.MatchCondition)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_MatchCondition_To_admissionregistration_MatchCondition(a.(*v1.MatchCondition), b.(*admissionregistration.MatchCondition), scope)
}); err != nil {
@ -48,6 +68,16 @@ func RegisterConversions(s *runtime.Scheme) error {
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.MatchResources)(nil), (*admissionregistration.MatchResources)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_MatchResources_To_admissionregistration_MatchResources(a.(*v1.MatchResources), b.(*admissionregistration.MatchResources), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.MatchResources)(nil), (*v1.MatchResources)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_MatchResources_To_v1_MatchResources(a.(*admissionregistration.MatchResources), b.(*v1.MatchResources), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.MutatingWebhook)(nil), (*admissionregistration.MutatingWebhook)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_MutatingWebhook_To_admissionregistration_MutatingWebhook(a.(*v1.MutatingWebhook), b.(*admissionregistration.MutatingWebhook), scope)
}); err != nil {
@ -78,6 +108,36 @@ func RegisterConversions(s *runtime.Scheme) error {
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.NamedRuleWithOperations)(nil), (*admissionregistration.NamedRuleWithOperations)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_NamedRuleWithOperations_To_admissionregistration_NamedRuleWithOperations(a.(*v1.NamedRuleWithOperations), b.(*admissionregistration.NamedRuleWithOperations), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.NamedRuleWithOperations)(nil), (*v1.NamedRuleWithOperations)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_NamedRuleWithOperations_To_v1_NamedRuleWithOperations(a.(*admissionregistration.NamedRuleWithOperations), b.(*v1.NamedRuleWithOperations), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ParamKind)(nil), (*admissionregistration.ParamKind)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ParamKind_To_admissionregistration_ParamKind(a.(*v1.ParamKind), b.(*admissionregistration.ParamKind), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.ParamKind)(nil), (*v1.ParamKind)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_ParamKind_To_v1_ParamKind(a.(*admissionregistration.ParamKind), b.(*v1.ParamKind), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ParamRef)(nil), (*admissionregistration.ParamRef)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ParamRef_To_admissionregistration_ParamRef(a.(*v1.ParamRef), b.(*admissionregistration.ParamRef), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.ParamRef)(nil), (*v1.ParamRef)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_ParamRef_To_v1_ParamRef(a.(*admissionregistration.ParamRef), b.(*v1.ParamRef), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ServiceReference)(nil), (*admissionregistration.ServiceReference)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ServiceReference_To_admissionregistration_ServiceReference(a.(*v1.ServiceReference), b.(*admissionregistration.ServiceReference), scope)
}); err != nil {
@ -88,6 +148,86 @@ func RegisterConversions(s *runtime.Scheme) error {
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.TypeChecking)(nil), (*admissionregistration.TypeChecking)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_TypeChecking_To_admissionregistration_TypeChecking(a.(*v1.TypeChecking), b.(*admissionregistration.TypeChecking), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.TypeChecking)(nil), (*v1.TypeChecking)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_TypeChecking_To_v1_TypeChecking(a.(*admissionregistration.TypeChecking), b.(*v1.TypeChecking), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ValidatingAdmissionPolicy)(nil), (*admissionregistration.ValidatingAdmissionPolicy)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ValidatingAdmissionPolicy_To_admissionregistration_ValidatingAdmissionPolicy(a.(*v1.ValidatingAdmissionPolicy), b.(*admissionregistration.ValidatingAdmissionPolicy), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.ValidatingAdmissionPolicy)(nil), (*v1.ValidatingAdmissionPolicy)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_ValidatingAdmissionPolicy_To_v1_ValidatingAdmissionPolicy(a.(*admissionregistration.ValidatingAdmissionPolicy), b.(*v1.ValidatingAdmissionPolicy), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ValidatingAdmissionPolicyBinding)(nil), (*admissionregistration.ValidatingAdmissionPolicyBinding)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ValidatingAdmissionPolicyBinding_To_admissionregistration_ValidatingAdmissionPolicyBinding(a.(*v1.ValidatingAdmissionPolicyBinding), b.(*admissionregistration.ValidatingAdmissionPolicyBinding), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.ValidatingAdmissionPolicyBinding)(nil), (*v1.ValidatingAdmissionPolicyBinding)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_ValidatingAdmissionPolicyBinding_To_v1_ValidatingAdmissionPolicyBinding(a.(*admissionregistration.ValidatingAdmissionPolicyBinding), b.(*v1.ValidatingAdmissionPolicyBinding), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ValidatingAdmissionPolicyBindingList)(nil), (*admissionregistration.ValidatingAdmissionPolicyBindingList)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ValidatingAdmissionPolicyBindingList_To_admissionregistration_ValidatingAdmissionPolicyBindingList(a.(*v1.ValidatingAdmissionPolicyBindingList), b.(*admissionregistration.ValidatingAdmissionPolicyBindingList), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.ValidatingAdmissionPolicyBindingList)(nil), (*v1.ValidatingAdmissionPolicyBindingList)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_ValidatingAdmissionPolicyBindingList_To_v1_ValidatingAdmissionPolicyBindingList(a.(*admissionregistration.ValidatingAdmissionPolicyBindingList), b.(*v1.ValidatingAdmissionPolicyBindingList), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ValidatingAdmissionPolicyBindingSpec)(nil), (*admissionregistration.ValidatingAdmissionPolicyBindingSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ValidatingAdmissionPolicyBindingSpec_To_admissionregistration_ValidatingAdmissionPolicyBindingSpec(a.(*v1.ValidatingAdmissionPolicyBindingSpec), b.(*admissionregistration.ValidatingAdmissionPolicyBindingSpec), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.ValidatingAdmissionPolicyBindingSpec)(nil), (*v1.ValidatingAdmissionPolicyBindingSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_ValidatingAdmissionPolicyBindingSpec_To_v1_ValidatingAdmissionPolicyBindingSpec(a.(*admissionregistration.ValidatingAdmissionPolicyBindingSpec), b.(*v1.ValidatingAdmissionPolicyBindingSpec), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ValidatingAdmissionPolicyList)(nil), (*admissionregistration.ValidatingAdmissionPolicyList)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ValidatingAdmissionPolicyList_To_admissionregistration_ValidatingAdmissionPolicyList(a.(*v1.ValidatingAdmissionPolicyList), b.(*admissionregistration.ValidatingAdmissionPolicyList), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.ValidatingAdmissionPolicyList)(nil), (*v1.ValidatingAdmissionPolicyList)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_ValidatingAdmissionPolicyList_To_v1_ValidatingAdmissionPolicyList(a.(*admissionregistration.ValidatingAdmissionPolicyList), b.(*v1.ValidatingAdmissionPolicyList), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ValidatingAdmissionPolicySpec)(nil), (*admissionregistration.ValidatingAdmissionPolicySpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ValidatingAdmissionPolicySpec_To_admissionregistration_ValidatingAdmissionPolicySpec(a.(*v1.ValidatingAdmissionPolicySpec), b.(*admissionregistration.ValidatingAdmissionPolicySpec), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.ValidatingAdmissionPolicySpec)(nil), (*v1.ValidatingAdmissionPolicySpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_ValidatingAdmissionPolicySpec_To_v1_ValidatingAdmissionPolicySpec(a.(*admissionregistration.ValidatingAdmissionPolicySpec), b.(*v1.ValidatingAdmissionPolicySpec), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ValidatingAdmissionPolicyStatus)(nil), (*admissionregistration.ValidatingAdmissionPolicyStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ValidatingAdmissionPolicyStatus_To_admissionregistration_ValidatingAdmissionPolicyStatus(a.(*v1.ValidatingAdmissionPolicyStatus), b.(*admissionregistration.ValidatingAdmissionPolicyStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.ValidatingAdmissionPolicyStatus)(nil), (*v1.ValidatingAdmissionPolicyStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_ValidatingAdmissionPolicyStatus_To_v1_ValidatingAdmissionPolicyStatus(a.(*admissionregistration.ValidatingAdmissionPolicyStatus), b.(*v1.ValidatingAdmissionPolicyStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.ValidatingWebhook)(nil), (*admissionregistration.ValidatingWebhook)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_ValidatingWebhook_To_admissionregistration_ValidatingWebhook(a.(*v1.ValidatingWebhook), b.(*admissionregistration.ValidatingWebhook), scope)
}); err != nil {
@ -118,6 +258,26 @@ func RegisterConversions(s *runtime.Scheme) error {
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.Validation)(nil), (*admissionregistration.Validation)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_Validation_To_admissionregistration_Validation(a.(*v1.Validation), b.(*admissionregistration.Validation), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.Validation)(nil), (*v1.Validation)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_Validation_To_v1_Validation(a.(*admissionregistration.Validation), b.(*v1.Validation), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.Variable)(nil), (*admissionregistration.Variable)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_Variable_To_admissionregistration_Variable(a.(*v1.Variable), b.(*admissionregistration.Variable), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*admissionregistration.Variable)(nil), (*v1.Variable)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_admissionregistration_Variable_To_v1_Variable(a.(*admissionregistration.Variable), b.(*v1.Variable), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*v1.WebhookClientConfig)(nil), (*admissionregistration.WebhookClientConfig)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v1_WebhookClientConfig_To_admissionregistration_WebhookClientConfig(a.(*v1.WebhookClientConfig), b.(*admissionregistration.WebhookClientConfig), scope)
}); err != nil {
@ -151,6 +311,50 @@ func RegisterConversions(s *runtime.Scheme) error {
return nil
}
func autoConvert_v1_AuditAnnotation_To_admissionregistration_AuditAnnotation(in *v1.AuditAnnotation, out *admissionregistration.AuditAnnotation, s conversion.Scope) error {
out.Key = in.Key
out.ValueExpression = in.ValueExpression
return nil
}
// Convert_v1_AuditAnnotation_To_admissionregistration_AuditAnnotation is an autogenerated conversion function.
func Convert_v1_AuditAnnotation_To_admissionregistration_AuditAnnotation(in *v1.AuditAnnotation, out *admissionregistration.AuditAnnotation, s conversion.Scope) error {
return autoConvert_v1_AuditAnnotation_To_admissionregistration_AuditAnnotation(in, out, s)
}
func autoConvert_admissionregistration_AuditAnnotation_To_v1_AuditAnnotation(in *admissionregistration.AuditAnnotation, out *v1.AuditAnnotation, s conversion.Scope) error {
out.Key = in.Key
out.ValueExpression = in.ValueExpression
return nil
}
// Convert_admissionregistration_AuditAnnotation_To_v1_AuditAnnotation is an autogenerated conversion function.
func Convert_admissionregistration_AuditAnnotation_To_v1_AuditAnnotation(in *admissionregistration.AuditAnnotation, out *v1.AuditAnnotation, s conversion.Scope) error {
return autoConvert_admissionregistration_AuditAnnotation_To_v1_AuditAnnotation(in, out, s)
}
func autoConvert_v1_ExpressionWarning_To_admissionregistration_ExpressionWarning(in *v1.ExpressionWarning, out *admissionregistration.ExpressionWarning, s conversion.Scope) error {
out.FieldRef = in.FieldRef
out.Warning = in.Warning
return nil
}
// Convert_v1_ExpressionWarning_To_admissionregistration_ExpressionWarning is an autogenerated conversion function.
func Convert_v1_ExpressionWarning_To_admissionregistration_ExpressionWarning(in *v1.ExpressionWarning, out *admissionregistration.ExpressionWarning, s conversion.Scope) error {
return autoConvert_v1_ExpressionWarning_To_admissionregistration_ExpressionWarning(in, out, s)
}
func autoConvert_admissionregistration_ExpressionWarning_To_v1_ExpressionWarning(in *admissionregistration.ExpressionWarning, out *v1.ExpressionWarning, s conversion.Scope) error {
out.FieldRef = in.FieldRef
out.Warning = in.Warning
return nil
}
// Convert_admissionregistration_ExpressionWarning_To_v1_ExpressionWarning is an autogenerated conversion function.
func Convert_admissionregistration_ExpressionWarning_To_v1_ExpressionWarning(in *admissionregistration.ExpressionWarning, out *v1.ExpressionWarning, s conversion.Scope) error {
return autoConvert_admissionregistration_ExpressionWarning_To_v1_ExpressionWarning(in, out, s)
}
func autoConvert_v1_MatchCondition_To_admissionregistration_MatchCondition(in *v1.MatchCondition, out *admissionregistration.MatchCondition, s conversion.Scope) error {
out.Name = in.Name
out.Expression = in.Expression
@ -173,6 +377,74 @@ func Convert_admissionregistration_MatchCondition_To_v1_MatchCondition(in *admis
return autoConvert_admissionregistration_MatchCondition_To_v1_MatchCondition(in, out, s)
}
func autoConvert_v1_MatchResources_To_admissionregistration_MatchResources(in *v1.MatchResources, out *admissionregistration.MatchResources, s conversion.Scope) error {
out.NamespaceSelector = (*metav1.LabelSelector)(unsafe.Pointer(in.NamespaceSelector))
out.ObjectSelector = (*metav1.LabelSelector)(unsafe.Pointer(in.ObjectSelector))
if in.ResourceRules != nil {
in, out := &in.ResourceRules, &out.ResourceRules
*out = make([]admissionregistration.NamedRuleWithOperations, len(*in))
for i := range *in {
if err := Convert_v1_NamedRuleWithOperations_To_admissionregistration_NamedRuleWithOperations(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.ResourceRules = nil
}
if in.ExcludeResourceRules != nil {
in, out := &in.ExcludeResourceRules, &out.ExcludeResourceRules
*out = make([]admissionregistration.NamedRuleWithOperations, len(*in))
for i := range *in {
if err := Convert_v1_NamedRuleWithOperations_To_admissionregistration_NamedRuleWithOperations(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.ExcludeResourceRules = nil
}
out.MatchPolicy = (*admissionregistration.MatchPolicyType)(unsafe.Pointer(in.MatchPolicy))
return nil
}
// Convert_v1_MatchResources_To_admissionregistration_MatchResources is an autogenerated conversion function.
func Convert_v1_MatchResources_To_admissionregistration_MatchResources(in *v1.MatchResources, out *admissionregistration.MatchResources, s conversion.Scope) error {
return autoConvert_v1_MatchResources_To_admissionregistration_MatchResources(in, out, s)
}
func autoConvert_admissionregistration_MatchResources_To_v1_MatchResources(in *admissionregistration.MatchResources, out *v1.MatchResources, s conversion.Scope) error {
out.NamespaceSelector = (*metav1.LabelSelector)(unsafe.Pointer(in.NamespaceSelector))
out.ObjectSelector = (*metav1.LabelSelector)(unsafe.Pointer(in.ObjectSelector))
if in.ResourceRules != nil {
in, out := &in.ResourceRules, &out.ResourceRules
*out = make([]v1.NamedRuleWithOperations, len(*in))
for i := range *in {
if err := Convert_admissionregistration_NamedRuleWithOperations_To_v1_NamedRuleWithOperations(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.ResourceRules = nil
}
if in.ExcludeResourceRules != nil {
in, out := &in.ExcludeResourceRules, &out.ExcludeResourceRules
*out = make([]v1.NamedRuleWithOperations, len(*in))
for i := range *in {
if err := Convert_admissionregistration_NamedRuleWithOperations_To_v1_NamedRuleWithOperations(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.ExcludeResourceRules = nil
}
out.MatchPolicy = (*v1.MatchPolicyType)(unsafe.Pointer(in.MatchPolicy))
return nil
}
// Convert_admissionregistration_MatchResources_To_v1_MatchResources is an autogenerated conversion function.
func Convert_admissionregistration_MatchResources_To_v1_MatchResources(in *admissionregistration.MatchResources, out *v1.MatchResources, s conversion.Scope) error {
return autoConvert_admissionregistration_MatchResources_To_v1_MatchResources(in, out, s)
}
func autoConvert_v1_MutatingWebhook_To_admissionregistration_MutatingWebhook(in *v1.MutatingWebhook, out *admissionregistration.MutatingWebhook, s conversion.Scope) error {
out.Name = in.Name
if err := Convert_v1_WebhookClientConfig_To_admissionregistration_WebhookClientConfig(&in.ClientConfig, &out.ClientConfig, s); err != nil {
@ -323,6 +595,80 @@ func Convert_admissionregistration_MutatingWebhookConfigurationList_To_v1_Mutati
return autoConvert_admissionregistration_MutatingWebhookConfigurationList_To_v1_MutatingWebhookConfigurationList(in, out, s)
}
func autoConvert_v1_NamedRuleWithOperations_To_admissionregistration_NamedRuleWithOperations(in *v1.NamedRuleWithOperations, out *admissionregistration.NamedRuleWithOperations, s conversion.Scope) error {
out.ResourceNames = *(*[]string)(unsafe.Pointer(&in.ResourceNames))
if err := Convert_v1_RuleWithOperations_To_admissionregistration_RuleWithOperations(&in.RuleWithOperations, &out.RuleWithOperations, s); err != nil {
return err
}
return nil
}
// Convert_v1_NamedRuleWithOperations_To_admissionregistration_NamedRuleWithOperations is an autogenerated conversion function.
func Convert_v1_NamedRuleWithOperations_To_admissionregistration_NamedRuleWithOperations(in *v1.NamedRuleWithOperations, out *admissionregistration.NamedRuleWithOperations, s conversion.Scope) error {
return autoConvert_v1_NamedRuleWithOperations_To_admissionregistration_NamedRuleWithOperations(in, out, s)
}
func autoConvert_admissionregistration_NamedRuleWithOperations_To_v1_NamedRuleWithOperations(in *admissionregistration.NamedRuleWithOperations, out *v1.NamedRuleWithOperations, s conversion.Scope) error {
out.ResourceNames = *(*[]string)(unsafe.Pointer(&in.ResourceNames))
if err := Convert_admissionregistration_RuleWithOperations_To_v1_RuleWithOperations(&in.RuleWithOperations, &out.RuleWithOperations, s); err != nil {
return err
}
return nil
}
// Convert_admissionregistration_NamedRuleWithOperations_To_v1_NamedRuleWithOperations is an autogenerated conversion function.
func Convert_admissionregistration_NamedRuleWithOperations_To_v1_NamedRuleWithOperations(in *admissionregistration.NamedRuleWithOperations, out *v1.NamedRuleWithOperations, s conversion.Scope) error {
return autoConvert_admissionregistration_NamedRuleWithOperations_To_v1_NamedRuleWithOperations(in, out, s)
}
func autoConvert_v1_ParamKind_To_admissionregistration_ParamKind(in *v1.ParamKind, out *admissionregistration.ParamKind, s conversion.Scope) error {
out.APIVersion = in.APIVersion
out.Kind = in.Kind
return nil
}
// Convert_v1_ParamKind_To_admissionregistration_ParamKind is an autogenerated conversion function.
func Convert_v1_ParamKind_To_admissionregistration_ParamKind(in *v1.ParamKind, out *admissionregistration.ParamKind, s conversion.Scope) error {
return autoConvert_v1_ParamKind_To_admissionregistration_ParamKind(in, out, s)
}
func autoConvert_admissionregistration_ParamKind_To_v1_ParamKind(in *admissionregistration.ParamKind, out *v1.ParamKind, s conversion.Scope) error {
out.APIVersion = in.APIVersion
out.Kind = in.Kind
return nil
}
// Convert_admissionregistration_ParamKind_To_v1_ParamKind is an autogenerated conversion function.
func Convert_admissionregistration_ParamKind_To_v1_ParamKind(in *admissionregistration.ParamKind, out *v1.ParamKind, s conversion.Scope) error {
return autoConvert_admissionregistration_ParamKind_To_v1_ParamKind(in, out, s)
}
func autoConvert_v1_ParamRef_To_admissionregistration_ParamRef(in *v1.ParamRef, out *admissionregistration.ParamRef, s conversion.Scope) error {
out.Name = in.Name
out.Namespace = in.Namespace
out.Selector = (*metav1.LabelSelector)(unsafe.Pointer(in.Selector))
out.ParameterNotFoundAction = (*admissionregistration.ParameterNotFoundActionType)(unsafe.Pointer(in.ParameterNotFoundAction))
return nil
}
// Convert_v1_ParamRef_To_admissionregistration_ParamRef is an autogenerated conversion function.
func Convert_v1_ParamRef_To_admissionregistration_ParamRef(in *v1.ParamRef, out *admissionregistration.ParamRef, s conversion.Scope) error {
return autoConvert_v1_ParamRef_To_admissionregistration_ParamRef(in, out, s)
}
func autoConvert_admissionregistration_ParamRef_To_v1_ParamRef(in *admissionregistration.ParamRef, out *v1.ParamRef, s conversion.Scope) error {
out.Name = in.Name
out.Namespace = in.Namespace
out.Selector = (*metav1.LabelSelector)(unsafe.Pointer(in.Selector))
out.ParameterNotFoundAction = (*v1.ParameterNotFoundActionType)(unsafe.Pointer(in.ParameterNotFoundAction))
return nil
}
// Convert_admissionregistration_ParamRef_To_v1_ParamRef is an autogenerated conversion function.
func Convert_admissionregistration_ParamRef_To_v1_ParamRef(in *admissionregistration.ParamRef, out *v1.ParamRef, s conversion.Scope) error {
return autoConvert_admissionregistration_ParamRef_To_v1_ParamRef(in, out, s)
}
func autoConvert_v1_Rule_To_admissionregistration_Rule(in *v1.Rule, out *admissionregistration.Rule, s conversion.Scope) error {
out.APIGroups = *(*[]string)(unsafe.Pointer(&in.APIGroups))
out.APIVersions = *(*[]string)(unsafe.Pointer(&in.APIVersions))
@ -385,6 +731,282 @@ func Convert_admissionregistration_ServiceReference_To_v1_ServiceReference(in *a
return autoConvert_admissionregistration_ServiceReference_To_v1_ServiceReference(in, out, s)
}
func autoConvert_v1_TypeChecking_To_admissionregistration_TypeChecking(in *v1.TypeChecking, out *admissionregistration.TypeChecking, s conversion.Scope) error {
out.ExpressionWarnings = *(*[]admissionregistration.ExpressionWarning)(unsafe.Pointer(&in.ExpressionWarnings))
return nil
}
// Convert_v1_TypeChecking_To_admissionregistration_TypeChecking is an autogenerated conversion function.
func Convert_v1_TypeChecking_To_admissionregistration_TypeChecking(in *v1.TypeChecking, out *admissionregistration.TypeChecking, s conversion.Scope) error {
return autoConvert_v1_TypeChecking_To_admissionregistration_TypeChecking(in, out, s)
}
func autoConvert_admissionregistration_TypeChecking_To_v1_TypeChecking(in *admissionregistration.TypeChecking, out *v1.TypeChecking, s conversion.Scope) error {
out.ExpressionWarnings = *(*[]v1.ExpressionWarning)(unsafe.Pointer(&in.ExpressionWarnings))
return nil
}
// Convert_admissionregistration_TypeChecking_To_v1_TypeChecking is an autogenerated conversion function.
func Convert_admissionregistration_TypeChecking_To_v1_TypeChecking(in *admissionregistration.TypeChecking, out *v1.TypeChecking, s conversion.Scope) error {
return autoConvert_admissionregistration_TypeChecking_To_v1_TypeChecking(in, out, s)
}
func autoConvert_v1_ValidatingAdmissionPolicy_To_admissionregistration_ValidatingAdmissionPolicy(in *v1.ValidatingAdmissionPolicy, out *admissionregistration.ValidatingAdmissionPolicy, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
if err := Convert_v1_ValidatingAdmissionPolicySpec_To_admissionregistration_ValidatingAdmissionPolicySpec(&in.Spec, &out.Spec, s); err != nil {
return err
}
if err := Convert_v1_ValidatingAdmissionPolicyStatus_To_admissionregistration_ValidatingAdmissionPolicyStatus(&in.Status, &out.Status, s); err != nil {
return err
}
return nil
}
// Convert_v1_ValidatingAdmissionPolicy_To_admissionregistration_ValidatingAdmissionPolicy is an autogenerated conversion function.
func Convert_v1_ValidatingAdmissionPolicy_To_admissionregistration_ValidatingAdmissionPolicy(in *v1.ValidatingAdmissionPolicy, out *admissionregistration.ValidatingAdmissionPolicy, s conversion.Scope) error {
return autoConvert_v1_ValidatingAdmissionPolicy_To_admissionregistration_ValidatingAdmissionPolicy(in, out, s)
}
func autoConvert_admissionregistration_ValidatingAdmissionPolicy_To_v1_ValidatingAdmissionPolicy(in *admissionregistration.ValidatingAdmissionPolicy, out *v1.ValidatingAdmissionPolicy, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
if err := Convert_admissionregistration_ValidatingAdmissionPolicySpec_To_v1_ValidatingAdmissionPolicySpec(&in.Spec, &out.Spec, s); err != nil {
return err
}
if err := Convert_admissionregistration_ValidatingAdmissionPolicyStatus_To_v1_ValidatingAdmissionPolicyStatus(&in.Status, &out.Status, s); err != nil {
return err
}
return nil
}
// Convert_admissionregistration_ValidatingAdmissionPolicy_To_v1_ValidatingAdmissionPolicy is an autogenerated conversion function.
func Convert_admissionregistration_ValidatingAdmissionPolicy_To_v1_ValidatingAdmissionPolicy(in *admissionregistration.ValidatingAdmissionPolicy, out *v1.ValidatingAdmissionPolicy, s conversion.Scope) error {
return autoConvert_admissionregistration_ValidatingAdmissionPolicy_To_v1_ValidatingAdmissionPolicy(in, out, s)
}
func autoConvert_v1_ValidatingAdmissionPolicyBinding_To_admissionregistration_ValidatingAdmissionPolicyBinding(in *v1.ValidatingAdmissionPolicyBinding, out *admissionregistration.ValidatingAdmissionPolicyBinding, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
if err := Convert_v1_ValidatingAdmissionPolicyBindingSpec_To_admissionregistration_ValidatingAdmissionPolicyBindingSpec(&in.Spec, &out.Spec, s); err != nil {
return err
}
return nil
}
// Convert_v1_ValidatingAdmissionPolicyBinding_To_admissionregistration_ValidatingAdmissionPolicyBinding is an autogenerated conversion function.
func Convert_v1_ValidatingAdmissionPolicyBinding_To_admissionregistration_ValidatingAdmissionPolicyBinding(in *v1.ValidatingAdmissionPolicyBinding, out *admissionregistration.ValidatingAdmissionPolicyBinding, s conversion.Scope) error {
return autoConvert_v1_ValidatingAdmissionPolicyBinding_To_admissionregistration_ValidatingAdmissionPolicyBinding(in, out, s)
}
func autoConvert_admissionregistration_ValidatingAdmissionPolicyBinding_To_v1_ValidatingAdmissionPolicyBinding(in *admissionregistration.ValidatingAdmissionPolicyBinding, out *v1.ValidatingAdmissionPolicyBinding, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
if err := Convert_admissionregistration_ValidatingAdmissionPolicyBindingSpec_To_v1_ValidatingAdmissionPolicyBindingSpec(&in.Spec, &out.Spec, s); err != nil {
return err
}
return nil
}
// Convert_admissionregistration_ValidatingAdmissionPolicyBinding_To_v1_ValidatingAdmissionPolicyBinding is an autogenerated conversion function.
func Convert_admissionregistration_ValidatingAdmissionPolicyBinding_To_v1_ValidatingAdmissionPolicyBinding(in *admissionregistration.ValidatingAdmissionPolicyBinding, out *v1.ValidatingAdmissionPolicyBinding, s conversion.Scope) error {
return autoConvert_admissionregistration_ValidatingAdmissionPolicyBinding_To_v1_ValidatingAdmissionPolicyBinding(in, out, s)
}
func autoConvert_v1_ValidatingAdmissionPolicyBindingList_To_admissionregistration_ValidatingAdmissionPolicyBindingList(in *v1.ValidatingAdmissionPolicyBindingList, out *admissionregistration.ValidatingAdmissionPolicyBindingList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]admissionregistration.ValidatingAdmissionPolicyBinding, len(*in))
for i := range *in {
if err := Convert_v1_ValidatingAdmissionPolicyBinding_To_admissionregistration_ValidatingAdmissionPolicyBinding(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
// Convert_v1_ValidatingAdmissionPolicyBindingList_To_admissionregistration_ValidatingAdmissionPolicyBindingList is an autogenerated conversion function.
func Convert_v1_ValidatingAdmissionPolicyBindingList_To_admissionregistration_ValidatingAdmissionPolicyBindingList(in *v1.ValidatingAdmissionPolicyBindingList, out *admissionregistration.ValidatingAdmissionPolicyBindingList, s conversion.Scope) error {
return autoConvert_v1_ValidatingAdmissionPolicyBindingList_To_admissionregistration_ValidatingAdmissionPolicyBindingList(in, out, s)
}
func autoConvert_admissionregistration_ValidatingAdmissionPolicyBindingList_To_v1_ValidatingAdmissionPolicyBindingList(in *admissionregistration.ValidatingAdmissionPolicyBindingList, out *v1.ValidatingAdmissionPolicyBindingList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]v1.ValidatingAdmissionPolicyBinding, len(*in))
for i := range *in {
if err := Convert_admissionregistration_ValidatingAdmissionPolicyBinding_To_v1_ValidatingAdmissionPolicyBinding(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
// Convert_admissionregistration_ValidatingAdmissionPolicyBindingList_To_v1_ValidatingAdmissionPolicyBindingList is an autogenerated conversion function.
func Convert_admissionregistration_ValidatingAdmissionPolicyBindingList_To_v1_ValidatingAdmissionPolicyBindingList(in *admissionregistration.ValidatingAdmissionPolicyBindingList, out *v1.ValidatingAdmissionPolicyBindingList, s conversion.Scope) error {
return autoConvert_admissionregistration_ValidatingAdmissionPolicyBindingList_To_v1_ValidatingAdmissionPolicyBindingList(in, out, s)
}
func autoConvert_v1_ValidatingAdmissionPolicyBindingSpec_To_admissionregistration_ValidatingAdmissionPolicyBindingSpec(in *v1.ValidatingAdmissionPolicyBindingSpec, out *admissionregistration.ValidatingAdmissionPolicyBindingSpec, s conversion.Scope) error {
out.PolicyName = in.PolicyName
out.ParamRef = (*admissionregistration.ParamRef)(unsafe.Pointer(in.ParamRef))
if in.MatchResources != nil {
in, out := &in.MatchResources, &out.MatchResources
*out = new(admissionregistration.MatchResources)
if err := Convert_v1_MatchResources_To_admissionregistration_MatchResources(*in, *out, s); err != nil {
return err
}
} else {
out.MatchResources = nil
}
out.ValidationActions = *(*[]admissionregistration.ValidationAction)(unsafe.Pointer(&in.ValidationActions))
return nil
}
// Convert_v1_ValidatingAdmissionPolicyBindingSpec_To_admissionregistration_ValidatingAdmissionPolicyBindingSpec is an autogenerated conversion function.
func Convert_v1_ValidatingAdmissionPolicyBindingSpec_To_admissionregistration_ValidatingAdmissionPolicyBindingSpec(in *v1.ValidatingAdmissionPolicyBindingSpec, out *admissionregistration.ValidatingAdmissionPolicyBindingSpec, s conversion.Scope) error {
return autoConvert_v1_ValidatingAdmissionPolicyBindingSpec_To_admissionregistration_ValidatingAdmissionPolicyBindingSpec(in, out, s)
}
func autoConvert_admissionregistration_ValidatingAdmissionPolicyBindingSpec_To_v1_ValidatingAdmissionPolicyBindingSpec(in *admissionregistration.ValidatingAdmissionPolicyBindingSpec, out *v1.ValidatingAdmissionPolicyBindingSpec, s conversion.Scope) error {
out.PolicyName = in.PolicyName
out.ParamRef = (*v1.ParamRef)(unsafe.Pointer(in.ParamRef))
if in.MatchResources != nil {
in, out := &in.MatchResources, &out.MatchResources
*out = new(v1.MatchResources)
if err := Convert_admissionregistration_MatchResources_To_v1_MatchResources(*in, *out, s); err != nil {
return err
}
} else {
out.MatchResources = nil
}
out.ValidationActions = *(*[]v1.ValidationAction)(unsafe.Pointer(&in.ValidationActions))
return nil
}
// Convert_admissionregistration_ValidatingAdmissionPolicyBindingSpec_To_v1_ValidatingAdmissionPolicyBindingSpec is an autogenerated conversion function.
func Convert_admissionregistration_ValidatingAdmissionPolicyBindingSpec_To_v1_ValidatingAdmissionPolicyBindingSpec(in *admissionregistration.ValidatingAdmissionPolicyBindingSpec, out *v1.ValidatingAdmissionPolicyBindingSpec, s conversion.Scope) error {
return autoConvert_admissionregistration_ValidatingAdmissionPolicyBindingSpec_To_v1_ValidatingAdmissionPolicyBindingSpec(in, out, s)
}
func autoConvert_v1_ValidatingAdmissionPolicyList_To_admissionregistration_ValidatingAdmissionPolicyList(in *v1.ValidatingAdmissionPolicyList, out *admissionregistration.ValidatingAdmissionPolicyList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]admissionregistration.ValidatingAdmissionPolicy, len(*in))
for i := range *in {
if err := Convert_v1_ValidatingAdmissionPolicy_To_admissionregistration_ValidatingAdmissionPolicy(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
// Convert_v1_ValidatingAdmissionPolicyList_To_admissionregistration_ValidatingAdmissionPolicyList is an autogenerated conversion function.
func Convert_v1_ValidatingAdmissionPolicyList_To_admissionregistration_ValidatingAdmissionPolicyList(in *v1.ValidatingAdmissionPolicyList, out *admissionregistration.ValidatingAdmissionPolicyList, s conversion.Scope) error {
return autoConvert_v1_ValidatingAdmissionPolicyList_To_admissionregistration_ValidatingAdmissionPolicyList(in, out, s)
}
func autoConvert_admissionregistration_ValidatingAdmissionPolicyList_To_v1_ValidatingAdmissionPolicyList(in *admissionregistration.ValidatingAdmissionPolicyList, out *v1.ValidatingAdmissionPolicyList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]v1.ValidatingAdmissionPolicy, len(*in))
for i := range *in {
if err := Convert_admissionregistration_ValidatingAdmissionPolicy_To_v1_ValidatingAdmissionPolicy(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
// Convert_admissionregistration_ValidatingAdmissionPolicyList_To_v1_ValidatingAdmissionPolicyList is an autogenerated conversion function.
func Convert_admissionregistration_ValidatingAdmissionPolicyList_To_v1_ValidatingAdmissionPolicyList(in *admissionregistration.ValidatingAdmissionPolicyList, out *v1.ValidatingAdmissionPolicyList, s conversion.Scope) error {
return autoConvert_admissionregistration_ValidatingAdmissionPolicyList_To_v1_ValidatingAdmissionPolicyList(in, out, s)
}
func autoConvert_v1_ValidatingAdmissionPolicySpec_To_admissionregistration_ValidatingAdmissionPolicySpec(in *v1.ValidatingAdmissionPolicySpec, out *admissionregistration.ValidatingAdmissionPolicySpec, s conversion.Scope) error {
out.ParamKind = (*admissionregistration.ParamKind)(unsafe.Pointer(in.ParamKind))
if in.MatchConstraints != nil {
in, out := &in.MatchConstraints, &out.MatchConstraints
*out = new(admissionregistration.MatchResources)
if err := Convert_v1_MatchResources_To_admissionregistration_MatchResources(*in, *out, s); err != nil {
return err
}
} else {
out.MatchConstraints = nil
}
out.Validations = *(*[]admissionregistration.Validation)(unsafe.Pointer(&in.Validations))
out.FailurePolicy = (*admissionregistration.FailurePolicyType)(unsafe.Pointer(in.FailurePolicy))
out.AuditAnnotations = *(*[]admissionregistration.AuditAnnotation)(unsafe.Pointer(&in.AuditAnnotations))
out.MatchConditions = *(*[]admissionregistration.MatchCondition)(unsafe.Pointer(&in.MatchConditions))
out.Variables = *(*[]admissionregistration.Variable)(unsafe.Pointer(&in.Variables))
return nil
}
// Convert_v1_ValidatingAdmissionPolicySpec_To_admissionregistration_ValidatingAdmissionPolicySpec is an autogenerated conversion function.
func Convert_v1_ValidatingAdmissionPolicySpec_To_admissionregistration_ValidatingAdmissionPolicySpec(in *v1.ValidatingAdmissionPolicySpec, out *admissionregistration.ValidatingAdmissionPolicySpec, s conversion.Scope) error {
return autoConvert_v1_ValidatingAdmissionPolicySpec_To_admissionregistration_ValidatingAdmissionPolicySpec(in, out, s)
}
func autoConvert_admissionregistration_ValidatingAdmissionPolicySpec_To_v1_ValidatingAdmissionPolicySpec(in *admissionregistration.ValidatingAdmissionPolicySpec, out *v1.ValidatingAdmissionPolicySpec, s conversion.Scope) error {
out.ParamKind = (*v1.ParamKind)(unsafe.Pointer(in.ParamKind))
if in.MatchConstraints != nil {
in, out := &in.MatchConstraints, &out.MatchConstraints
*out = new(v1.MatchResources)
if err := Convert_admissionregistration_MatchResources_To_v1_MatchResources(*in, *out, s); err != nil {
return err
}
} else {
out.MatchConstraints = nil
}
out.Validations = *(*[]v1.Validation)(unsafe.Pointer(&in.Validations))
out.MatchConditions = *(*[]v1.MatchCondition)(unsafe.Pointer(&in.MatchConditions))
out.FailurePolicy = (*v1.FailurePolicyType)(unsafe.Pointer(in.FailurePolicy))
out.AuditAnnotations = *(*[]v1.AuditAnnotation)(unsafe.Pointer(&in.AuditAnnotations))
out.Variables = *(*[]v1.Variable)(unsafe.Pointer(&in.Variables))
return nil
}
// Convert_admissionregistration_ValidatingAdmissionPolicySpec_To_v1_ValidatingAdmissionPolicySpec is an autogenerated conversion function.
func Convert_admissionregistration_ValidatingAdmissionPolicySpec_To_v1_ValidatingAdmissionPolicySpec(in *admissionregistration.ValidatingAdmissionPolicySpec, out *v1.ValidatingAdmissionPolicySpec, s conversion.Scope) error {
return autoConvert_admissionregistration_ValidatingAdmissionPolicySpec_To_v1_ValidatingAdmissionPolicySpec(in, out, s)
}
func autoConvert_v1_ValidatingAdmissionPolicyStatus_To_admissionregistration_ValidatingAdmissionPolicyStatus(in *v1.ValidatingAdmissionPolicyStatus, out *admissionregistration.ValidatingAdmissionPolicyStatus, s conversion.Scope) error {
out.ObservedGeneration = in.ObservedGeneration
out.TypeChecking = (*admissionregistration.TypeChecking)(unsafe.Pointer(in.TypeChecking))
out.Conditions = *(*[]metav1.Condition)(unsafe.Pointer(&in.Conditions))
return nil
}
// Convert_v1_ValidatingAdmissionPolicyStatus_To_admissionregistration_ValidatingAdmissionPolicyStatus is an autogenerated conversion function.
func Convert_v1_ValidatingAdmissionPolicyStatus_To_admissionregistration_ValidatingAdmissionPolicyStatus(in *v1.ValidatingAdmissionPolicyStatus, out *admissionregistration.ValidatingAdmissionPolicyStatus, s conversion.Scope) error {
return autoConvert_v1_ValidatingAdmissionPolicyStatus_To_admissionregistration_ValidatingAdmissionPolicyStatus(in, out, s)
}
func autoConvert_admissionregistration_ValidatingAdmissionPolicyStatus_To_v1_ValidatingAdmissionPolicyStatus(in *admissionregistration.ValidatingAdmissionPolicyStatus, out *v1.ValidatingAdmissionPolicyStatus, s conversion.Scope) error {
out.ObservedGeneration = in.ObservedGeneration
out.TypeChecking = (*v1.TypeChecking)(unsafe.Pointer(in.TypeChecking))
out.Conditions = *(*[]metav1.Condition)(unsafe.Pointer(&in.Conditions))
return nil
}
// Convert_admissionregistration_ValidatingAdmissionPolicyStatus_To_v1_ValidatingAdmissionPolicyStatus is an autogenerated conversion function.
func Convert_admissionregistration_ValidatingAdmissionPolicyStatus_To_v1_ValidatingAdmissionPolicyStatus(in *admissionregistration.ValidatingAdmissionPolicyStatus, out *v1.ValidatingAdmissionPolicyStatus, s conversion.Scope) error {
return autoConvert_admissionregistration_ValidatingAdmissionPolicyStatus_To_v1_ValidatingAdmissionPolicyStatus(in, out, s)
}
func autoConvert_v1_ValidatingWebhook_To_admissionregistration_ValidatingWebhook(in *v1.ValidatingWebhook, out *admissionregistration.ValidatingWebhook, s conversion.Scope) error {
out.Name = in.Name
if err := Convert_v1_WebhookClientConfig_To_admissionregistration_WebhookClientConfig(&in.ClientConfig, &out.ClientConfig, s); err != nil {
@ -533,6 +1155,54 @@ func Convert_admissionregistration_ValidatingWebhookConfigurationList_To_v1_Vali
return autoConvert_admissionregistration_ValidatingWebhookConfigurationList_To_v1_ValidatingWebhookConfigurationList(in, out, s)
}
func autoConvert_v1_Validation_To_admissionregistration_Validation(in *v1.Validation, out *admissionregistration.Validation, s conversion.Scope) error {
out.Expression = in.Expression
out.Message = in.Message
out.Reason = (*metav1.StatusReason)(unsafe.Pointer(in.Reason))
out.MessageExpression = in.MessageExpression
return nil
}
// Convert_v1_Validation_To_admissionregistration_Validation is an autogenerated conversion function.
func Convert_v1_Validation_To_admissionregistration_Validation(in *v1.Validation, out *admissionregistration.Validation, s conversion.Scope) error {
return autoConvert_v1_Validation_To_admissionregistration_Validation(in, out, s)
}
func autoConvert_admissionregistration_Validation_To_v1_Validation(in *admissionregistration.Validation, out *v1.Validation, s conversion.Scope) error {
out.Expression = in.Expression
out.Message = in.Message
out.Reason = (*metav1.StatusReason)(unsafe.Pointer(in.Reason))
out.MessageExpression = in.MessageExpression
return nil
}
// Convert_admissionregistration_Validation_To_v1_Validation is an autogenerated conversion function.
func Convert_admissionregistration_Validation_To_v1_Validation(in *admissionregistration.Validation, out *v1.Validation, s conversion.Scope) error {
return autoConvert_admissionregistration_Validation_To_v1_Validation(in, out, s)
}
func autoConvert_v1_Variable_To_admissionregistration_Variable(in *v1.Variable, out *admissionregistration.Variable, s conversion.Scope) error {
out.Name = in.Name
out.Expression = in.Expression
return nil
}
// Convert_v1_Variable_To_admissionregistration_Variable is an autogenerated conversion function.
func Convert_v1_Variable_To_admissionregistration_Variable(in *v1.Variable, out *admissionregistration.Variable, s conversion.Scope) error {
return autoConvert_v1_Variable_To_admissionregistration_Variable(in, out, s)
}
func autoConvert_admissionregistration_Variable_To_v1_Variable(in *admissionregistration.Variable, out *v1.Variable, s conversion.Scope) error {
out.Name = in.Name
out.Expression = in.Expression
return nil
}
// Convert_admissionregistration_Variable_To_v1_Variable is an autogenerated conversion function.
func Convert_admissionregistration_Variable_To_v1_Variable(in *admissionregistration.Variable, out *v1.Variable, s conversion.Scope) error {
return autoConvert_admissionregistration_Variable_To_v1_Variable(in, out, s)
}
func autoConvert_v1_WebhookClientConfig_To_admissionregistration_WebhookClientConfig(in *v1.WebhookClientConfig, out *admissionregistration.WebhookClientConfig, s conversion.Scope) error {
out.URL = (*string)(unsafe.Pointer(in.URL))
if in.Service != nil {

View File

@ -36,6 +36,18 @@ func RegisterDefaults(scheme *runtime.Scheme) error {
scheme.AddTypeDefaultingFunc(&v1.MutatingWebhookConfigurationList{}, func(obj interface{}) {
SetObjectDefaults_MutatingWebhookConfigurationList(obj.(*v1.MutatingWebhookConfigurationList))
})
scheme.AddTypeDefaultingFunc(&v1.ValidatingAdmissionPolicy{}, func(obj interface{}) {
SetObjectDefaults_ValidatingAdmissionPolicy(obj.(*v1.ValidatingAdmissionPolicy))
})
scheme.AddTypeDefaultingFunc(&v1.ValidatingAdmissionPolicyBinding{}, func(obj interface{}) {
SetObjectDefaults_ValidatingAdmissionPolicyBinding(obj.(*v1.ValidatingAdmissionPolicyBinding))
})
scheme.AddTypeDefaultingFunc(&v1.ValidatingAdmissionPolicyBindingList{}, func(obj interface{}) {
SetObjectDefaults_ValidatingAdmissionPolicyBindingList(obj.(*v1.ValidatingAdmissionPolicyBindingList))
})
scheme.AddTypeDefaultingFunc(&v1.ValidatingAdmissionPolicyList{}, func(obj interface{}) {
SetObjectDefaults_ValidatingAdmissionPolicyList(obj.(*v1.ValidatingAdmissionPolicyList))
})
scheme.AddTypeDefaultingFunc(&v1.ValidatingWebhookConfiguration{}, func(obj interface{}) {
SetObjectDefaults_ValidatingWebhookConfiguration(obj.(*v1.ValidatingWebhookConfiguration))
})
@ -66,6 +78,49 @@ func SetObjectDefaults_MutatingWebhookConfigurationList(in *v1.MutatingWebhookCo
}
}
func SetObjectDefaults_ValidatingAdmissionPolicy(in *v1.ValidatingAdmissionPolicy) {
SetDefaults_ValidatingAdmissionPolicySpec(&in.Spec)
if in.Spec.MatchConstraints != nil {
SetDefaults_MatchResources(in.Spec.MatchConstraints)
for i := range in.Spec.MatchConstraints.ResourceRules {
a := &in.Spec.MatchConstraints.ResourceRules[i]
SetDefaults_Rule(&a.RuleWithOperations.Rule)
}
for i := range in.Spec.MatchConstraints.ExcludeResourceRules {
a := &in.Spec.MatchConstraints.ExcludeResourceRules[i]
SetDefaults_Rule(&a.RuleWithOperations.Rule)
}
}
}
func SetObjectDefaults_ValidatingAdmissionPolicyBinding(in *v1.ValidatingAdmissionPolicyBinding) {
if in.Spec.MatchResources != nil {
SetDefaults_MatchResources(in.Spec.MatchResources)
for i := range in.Spec.MatchResources.ResourceRules {
a := &in.Spec.MatchResources.ResourceRules[i]
SetDefaults_Rule(&a.RuleWithOperations.Rule)
}
for i := range in.Spec.MatchResources.ExcludeResourceRules {
a := &in.Spec.MatchResources.ExcludeResourceRules[i]
SetDefaults_Rule(&a.RuleWithOperations.Rule)
}
}
}
func SetObjectDefaults_ValidatingAdmissionPolicyBindingList(in *v1.ValidatingAdmissionPolicyBindingList) {
for i := range in.Items {
a := &in.Items[i]
SetObjectDefaults_ValidatingAdmissionPolicyBinding(a)
}
}
func SetObjectDefaults_ValidatingAdmissionPolicyList(in *v1.ValidatingAdmissionPolicyList) {
for i := range in.Items {
a := &in.Items[i]
SetObjectDefaults_ValidatingAdmissionPolicy(a)
}
}
func SetObjectDefaults_ValidatingWebhookConfiguration(in *v1.ValidatingWebhookConfiguration) {
for i := range in.Webhooks {
a := &in.Webhooks[i]

View File

@ -21,15 +21,15 @@ import (
"fmt"
"time"
"k8s.io/api/admissionregistration/v1beta1"
"k8s.io/api/admissionregistration/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
validatingadmissionpolicy "k8s.io/apiserver/pkg/admission/plugin/policy/validating"
admissionregistrationv1beta1apply "k8s.io/client-go/applyconfigurations/admissionregistration/v1beta1"
informerv1beta1 "k8s.io/client-go/informers/admissionregistration/v1beta1"
admissionregistrationv1beta1 "k8s.io/client-go/kubernetes/typed/admissionregistration/v1beta1"
admissionregistrationv1apply "k8s.io/client-go/applyconfigurations/admissionregistration/v1"
informerv1 "k8s.io/client-go/informers/admissionregistration/v1"
admissionregistrationv1 "k8s.io/client-go/kubernetes/typed/admissionregistration/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
)
@ -40,10 +40,10 @@ const ControllerName = "validatingadmissionpolicy-status"
// Controller is the ValidatingAdmissionPolicy Status controller that reconciles the Status field of each policy object.
// This controller runs type checks against referred types for each policy definition.
type Controller struct {
policyInformer informerv1beta1.ValidatingAdmissionPolicyInformer
policyInformer informerv1.ValidatingAdmissionPolicyInformer
policyQueue workqueue.RateLimitingInterface
policySynced cache.InformerSynced
policyClient admissionregistrationv1beta1.ValidatingAdmissionPolicyInterface
policyClient admissionregistrationv1.ValidatingAdmissionPolicyInterface
// typeChecker checks the policy's expressions for type errors.
// Type of params is defined in policy.Spec.ParamsKind
@ -66,7 +66,7 @@ func (c *Controller) Run(ctx context.Context, workers int) {
<-ctx.Done()
}
func NewController(policyInformer informerv1beta1.ValidatingAdmissionPolicyInformer, policyClient admissionregistrationv1beta1.ValidatingAdmissionPolicyInterface, typeChecker *validatingadmissionpolicy.TypeChecker) (*Controller, error) {
func NewController(policyInformer informerv1.ValidatingAdmissionPolicyInformer, policyClient admissionregistrationv1.ValidatingAdmissionPolicyInterface, typeChecker *validatingadmissionpolicy.TypeChecker) (*Controller, error) {
c := &Controller{
policyInformer: policyInformer,
policyQueue: workqueue.NewRateLimitingQueueWithConfig(workqueue.DefaultControllerRateLimiter(), workqueue.RateLimitingQueueConfig{Name: ControllerName}),
@ -89,7 +89,7 @@ func NewController(policyInformer informerv1beta1.ValidatingAdmissionPolicyInfor
}
func (c *Controller) enqueuePolicy(policy any) {
if policy, ok := policy.(*v1beta1.ValidatingAdmissionPolicy); ok {
if policy, ok := policy.(*v1.ValidatingAdmissionPolicy); ok {
// policy objects are cluster-scoped, no point include its namespace.
key := policy.ObjectMeta.Name
if key == "" {
@ -138,7 +138,7 @@ func (c *Controller) processNextWorkItem(ctx context.Context) bool {
return true
}
func (c *Controller) reconcile(ctx context.Context, policy *v1beta1.ValidatingAdmissionPolicy) error {
func (c *Controller) reconcile(ctx context.Context, policy *v1.ValidatingAdmissionPolicy) error {
if policy == nil {
return nil
}
@ -146,16 +146,16 @@ func (c *Controller) reconcile(ctx context.Context, policy *v1beta1.ValidatingAd
return nil
}
warnings := c.typeChecker.Check(policy)
warningsConfig := make([]*admissionregistrationv1beta1apply.ExpressionWarningApplyConfiguration, 0, len(warnings))
warningsConfig := make([]*admissionregistrationv1apply.ExpressionWarningApplyConfiguration, 0, len(warnings))
for _, warning := range warnings {
warningsConfig = append(warningsConfig, admissionregistrationv1beta1apply.ExpressionWarning().
warningsConfig = append(warningsConfig, admissionregistrationv1apply.ExpressionWarning().
WithFieldRef(warning.FieldRef).
WithWarning(warning.Warning))
}
applyConfig := admissionregistrationv1beta1apply.ValidatingAdmissionPolicy(policy.Name).
WithStatus(admissionregistrationv1beta1apply.ValidatingAdmissionPolicyStatus().
applyConfig := admissionregistrationv1apply.ValidatingAdmissionPolicy(policy.Name).
WithStatus(admissionregistrationv1apply.ValidatingAdmissionPolicyStatus().
WithObservedGeneration(policy.Generation).
WithTypeChecking(admissionregistrationv1beta1apply.TypeChecking().
WithTypeChecking(admissionregistrationv1apply.TypeChecking().
WithExpressionWarnings(warningsConfig...)))
_, err := c.policyClient.ApplyStatus(ctx, applyConfig, metav1.ApplyOptions{FieldManager: ControllerName, Force: true})
return err

View File

@ -23,7 +23,6 @@ import (
"time"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
"k8s.io/apimachinery/pkg/api/meta/testrestmapper"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
@ -38,13 +37,13 @@ import (
func TestTypeChecking(t *testing.T) {
for _, tc := range []struct {
name string
policy *admissionregistrationv1beta1.ValidatingAdmissionPolicy
assertFieldRef func(warnings []admissionregistrationv1beta1.ExpressionWarning, t *testing.T) // warning.fieldRef
assertWarnings func(warnings []admissionregistrationv1beta1.ExpressionWarning, t *testing.T) // warning.warning
policy *admissionregistrationv1.ValidatingAdmissionPolicy
assertFieldRef func(warnings []admissionregistrationv1.ExpressionWarning, t *testing.T) // warning.fieldRef
assertWarnings func(warnings []admissionregistrationv1.ExpressionWarning, t *testing.T) // warning.warning
}{
{
name: "deployment with correct expression",
policy: withGVRMatch([]string{"apps"}, []string{"v1"}, []string{"deployments"}, withValidations([]admissionregistrationv1beta1.Validation{
policy: withGVRMatch([]string{"apps"}, []string{"v1"}, []string{"deployments"}, withValidations([]admissionregistrationv1.Validation{
{
Expression: "object.spec.replicas > 1",
},
@ -54,7 +53,7 @@ func TestTypeChecking(t *testing.T) {
},
{
name: "deployment with type confusion",
policy: withGVRMatch([]string{"apps"}, []string{"v1"}, []string{"deployments"}, withValidations([]admissionregistrationv1beta1.Validation{
policy: withGVRMatch([]string{"apps"}, []string{"v1"}, []string{"deployments"}, withValidations([]admissionregistrationv1.Validation{
{
Expression: "object.spec.replicas < 100", // this one passes
},
@ -67,7 +66,7 @@ func TestTypeChecking(t *testing.T) {
},
{
name: "two expressions different type checking errors",
policy: withGVRMatch([]string{"apps"}, []string{"v1"}, []string{"deployments"}, withValidations([]admissionregistrationv1beta1.Validation{
policy: withGVRMatch([]string{"apps"}, []string{"v1"}, []string{"deployments"}, withValidations([]admissionregistrationv1.Validation{
{
Expression: "object.spec.nonExistingFirst > 1",
},
@ -83,7 +82,7 @@ func TestTypeChecking(t *testing.T) {
},
{
name: "one expression, two warnings",
policy: withGVRMatch([]string{"apps"}, []string{"v1"}, []string{"deployments"}, withValidations([]admissionregistrationv1beta1.Validation{
policy: withGVRMatch([]string{"apps"}, []string{"v1"}, []string{"deployments"}, withValidations([]admissionregistrationv1.Validation{
{
Expression: "object.spec.replicas < 100", // this one passes
},
@ -107,8 +106,8 @@ func TestTypeChecking(t *testing.T) {
RestMapper: testrestmapper.TestOnlyStaticRESTMapper(scheme.Scheme),
}
controller, err := NewController(
informerFactory.Admissionregistration().V1beta1().ValidatingAdmissionPolicies(),
client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies(),
informerFactory.Admissionregistration().V1().ValidatingAdmissionPolicies(),
client.AdmissionregistrationV1().ValidatingAdmissionPolicies(),
typeChecker,
)
if err != nil {
@ -120,7 +119,7 @@ func TestTypeChecking(t *testing.T) {
name := policy.Name
// wait until the typeChecking is set, which means the type checking
// is complete.
updated, err := client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Get(ctx, name, metav1.GetOptions{})
updated, err := client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Get(ctx, name, metav1.GetOptions{})
if err != nil {
return false, err
}
@ -143,8 +142,8 @@ func TestTypeChecking(t *testing.T) {
}
func toBe(expected ...string) func(warnings []admissionregistrationv1beta1.ExpressionWarning, t *testing.T) {
return func(warnings []admissionregistrationv1beta1.ExpressionWarning, t *testing.T) {
func toBe(expected ...string) func(warnings []admissionregistrationv1.ExpressionWarning, t *testing.T) {
return func(warnings []admissionregistrationv1.ExpressionWarning, t *testing.T) {
if len(expected) != len(warnings) {
t.Fatalf("mismatched length, expect %d, got %d", len(expected), len(warnings))
}
@ -156,8 +155,8 @@ func toBe(expected ...string) func(warnings []admissionregistrationv1beta1.Expre
}
}
func toHaveSubstring(substrings ...string) func(warnings []admissionregistrationv1beta1.ExpressionWarning, t *testing.T) {
return func(warnings []admissionregistrationv1beta1.ExpressionWarning, t *testing.T) {
func toHaveSubstring(substrings ...string) func(warnings []admissionregistrationv1.ExpressionWarning, t *testing.T) {
return func(warnings []admissionregistrationv1.ExpressionWarning, t *testing.T) {
if len(substrings) != len(warnings) {
t.Fatalf("mismatched length, expect %d, got %d", len(substrings), len(warnings))
}
@ -169,8 +168,8 @@ func toHaveSubstring(substrings ...string) func(warnings []admissionregistration
}
}
func toHaveMultipleSubstrings(substrings ...[]string) func(warnings []admissionregistrationv1beta1.ExpressionWarning, t *testing.T) {
return func(warnings []admissionregistrationv1beta1.ExpressionWarning, t *testing.T) {
func toHaveMultipleSubstrings(substrings ...[]string) func(warnings []admissionregistrationv1.ExpressionWarning, t *testing.T) {
return func(warnings []admissionregistrationv1.ExpressionWarning, t *testing.T) {
if len(substrings) != len(warnings) {
t.Fatalf("mismatched length, expect %d, got %d", len(substrings), len(warnings))
}
@ -184,19 +183,19 @@ func toHaveMultipleSubstrings(substrings ...[]string) func(warnings []admissionr
}
}
func toHaveLengthOf(n int) func(warnings []admissionregistrationv1beta1.ExpressionWarning, t *testing.T) {
return func(warnings []admissionregistrationv1beta1.ExpressionWarning, t *testing.T) {
func toHaveLengthOf(n int) func(warnings []admissionregistrationv1.ExpressionWarning, t *testing.T) {
return func(warnings []admissionregistrationv1.ExpressionWarning, t *testing.T) {
if n != len(warnings) {
t.Fatalf("mismatched length, expect %d, got %d", n, len(warnings))
}
}
}
func withGVRMatch(groups []string, versions []string, resources []string, policy *admissionregistrationv1beta1.ValidatingAdmissionPolicy) *admissionregistrationv1beta1.ValidatingAdmissionPolicy {
policy.Spec.MatchConstraints = &admissionregistrationv1beta1.MatchResources{
ResourceRules: []admissionregistrationv1beta1.NamedRuleWithOperations{
func withGVRMatch(groups []string, versions []string, resources []string, policy *admissionregistrationv1.ValidatingAdmissionPolicy) *admissionregistrationv1.ValidatingAdmissionPolicy {
policy.Spec.MatchConstraints = &admissionregistrationv1.MatchResources{
ResourceRules: []admissionregistrationv1.NamedRuleWithOperations{
{
RuleWithOperations: admissionregistrationv1beta1.RuleWithOperations{
RuleWithOperations: admissionregistrationv1.RuleWithOperations{
Operations: []admissionregistrationv1.OperationType{
"*",
},
@ -212,13 +211,13 @@ func withGVRMatch(groups []string, versions []string, resources []string, policy
return policy
}
func withValidations(validations []admissionregistrationv1beta1.Validation, policy *admissionregistrationv1beta1.ValidatingAdmissionPolicy) *admissionregistrationv1beta1.ValidatingAdmissionPolicy {
func withValidations(validations []admissionregistrationv1.Validation, policy *admissionregistrationv1.ValidatingAdmissionPolicy) *admissionregistrationv1.ValidatingAdmissionPolicy {
policy.Spec.Validations = validations
return policy
}
func makePolicy(name string) *admissionregistrationv1beta1.ValidatingAdmissionPolicy {
return &admissionregistrationv1beta1.ValidatingAdmissionPolicy{
func makePolicy(name string) *admissionregistrationv1.ValidatingAdmissionPolicy {
return &admissionregistrationv1.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{Name: name},
}
}

View File

@ -56,34 +56,36 @@ var GVRToStorageVersionHash = map[string]string{
"autoscaling/v2/horizontalpodautoscalers": "qwQve8ut294=",
"batch/v1/jobs": "mudhfqk/qZY=",
"batch/v1/cronjobs": "sd5LIXh4Fjs=",
"certificates.k8s.io/v1/certificatesigningrequests": "95fRKMXA+00=",
"coordination.k8s.io/v1/leases": "gqkMMb/YqFM=",
"discovery.k8s.io/v1/endpointslices": "Nx3SIv6I0mE=",
"networking.k8s.io/v1/networkpolicies": "YpfwF18m1G8=",
"networking.k8s.io/v1/ingresses": "39NQlfNR+bo=",
"networking.k8s.io/v1/ingressclasses": "l/iqIbDgFyQ=",
"node.k8s.io/v1/runtimeclasses": "WQTu1GL3T2Q=",
"policy/v1/poddisruptionbudgets": "EVWiDmWqyJw=",
"rbac.authorization.k8s.io/v1/clusterrolebindings": "48tpQ8gZHFc=",
"rbac.authorization.k8s.io/v1/clusterroles": "bYE5ZWDrJ44=",
"rbac.authorization.k8s.io/v1/rolebindings": "eGsCzGH6b1g=",
"rbac.authorization.k8s.io/v1/roles": "7FuwZcIIItM=",
"scheduling.k8s.io/v1/priorityclasses": "1QwjyaZjj3Y=",
"storage.k8s.io/v1/csidrivers": "hL6j/rwBV5w=",
"storage.k8s.io/v1/csinodes": "Pe62DkZtjuo=",
"storage.k8s.io/v1/storageclasses": "K+m6uJwbjGY=",
"storage.k8s.io/v1/csistoragecapacities": "xeVl+2Ly1kE=",
"storage.k8s.io/v1/volumeattachments": "tJx/ezt6UDU=",
"apps/v1/controllerrevisions": "85nkx63pcBU=",
"apps/v1/daemonsets": "dd7pWHUlMKQ=",
"apps/v1/deployments": "8aSe+NMegvE=",
"apps/v1/replicasets": "P1RzHs8/mWQ=",
"apps/v1/statefulsets": "H+vl74LkKdo=",
"admissionregistration.k8s.io/v1/mutatingwebhookconfigurations": "Sqi0GUgDaX0=",
"admissionregistration.k8s.io/v1/validatingwebhookconfigurations": "B0wHjQmsGNk=",
"events.k8s.io/v1/events": "r2yiGXH7wu8=",
"flowcontrol.apiserver.k8s.io/v1beta3/flowschemas": "GJVAJZSZBIw=",
"flowcontrol.apiserver.k8s.io/v1beta3/prioritylevelconfigurations": "Kir5PVfvNeI=",
"flowcontrol.apiserver.k8s.io/v1/flowschemas": "GJVAJZSZBIw=",
"flowcontrol.apiserver.k8s.io/v1/prioritylevelconfigurations": "Kir5PVfvNeI=",
"certificates.k8s.io/v1/certificatesigningrequests": "95fRKMXA+00=",
"coordination.k8s.io/v1/leases": "gqkMMb/YqFM=",
"discovery.k8s.io/v1/endpointslices": "Nx3SIv6I0mE=",
"networking.k8s.io/v1/networkpolicies": "YpfwF18m1G8=",
"networking.k8s.io/v1/ingresses": "39NQlfNR+bo=",
"networking.k8s.io/v1/ingressclasses": "l/iqIbDgFyQ=",
"node.k8s.io/v1/runtimeclasses": "WQTu1GL3T2Q=",
"policy/v1/poddisruptionbudgets": "EVWiDmWqyJw=",
"rbac.authorization.k8s.io/v1/clusterrolebindings": "48tpQ8gZHFc=",
"rbac.authorization.k8s.io/v1/clusterroles": "bYE5ZWDrJ44=",
"rbac.authorization.k8s.io/v1/rolebindings": "eGsCzGH6b1g=",
"rbac.authorization.k8s.io/v1/roles": "7FuwZcIIItM=",
"scheduling.k8s.io/v1/priorityclasses": "1QwjyaZjj3Y=",
"storage.k8s.io/v1/csidrivers": "hL6j/rwBV5w=",
"storage.k8s.io/v1/csinodes": "Pe62DkZtjuo=",
"storage.k8s.io/v1/storageclasses": "K+m6uJwbjGY=",
"storage.k8s.io/v1/csistoragecapacities": "xeVl+2Ly1kE=",
"storage.k8s.io/v1/volumeattachments": "tJx/ezt6UDU=",
"apps/v1/controllerrevisions": "85nkx63pcBU=",
"apps/v1/daemonsets": "dd7pWHUlMKQ=",
"apps/v1/deployments": "8aSe+NMegvE=",
"apps/v1/replicasets": "P1RzHs8/mWQ=",
"apps/v1/statefulsets": "H+vl74LkKdo=",
"admissionregistration.k8s.io/v1/mutatingwebhookconfigurations": "Sqi0GUgDaX0=",
"admissionregistration.k8s.io/v1/validatingwebhookconfigurations": "B0wHjQmsGNk=",
"admissionregistration.k8s.io/v1/validatingadmissionpolicies": "P/h9c6yIbaY=",
"admissionregistration.k8s.io/v1/validatingadmissionpolicybindings": "XYju31JKYek=",
"events.k8s.io/v1/events": "r2yiGXH7wu8=",
"flowcontrol.apiserver.k8s.io/v1beta3/flowschemas": "GJVAJZSZBIw=",
"flowcontrol.apiserver.k8s.io/v1beta3/prioritylevelconfigurations": "Kir5PVfvNeI=",
"flowcontrol.apiserver.k8s.io/v1/flowschemas": "GJVAJZSZBIw=",
"flowcontrol.apiserver.k8s.io/v1/prioritylevelconfigurations": "Kir5PVfvNeI=",
}

View File

@ -1269,7 +1269,7 @@ var defaultKubernetesFeatureGates = map[featuregate.Feature]featuregate.FeatureS
genericfeatures.UnauthenticatedHTTP2DOSMitigation: {Default: true, PreRelease: featuregate.Beta},
genericfeatures.ValidatingAdmissionPolicy: {Default: false, PreRelease: featuregate.Beta},
genericfeatures.ValidatingAdmissionPolicy: {Default: true, PreRelease: featuregate.GA, LockToDefault: true}, // remove in 1.32
genericfeatures.WatchBookmark: {Default: true, PreRelease: featuregate.GA, LockToDefault: true},

View File

@ -33,16 +33,32 @@ import (
func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenAPIDefinition {
return map[string]common.OpenAPIDefinition{
"k8s.io/api/admissionregistration/v1.AuditAnnotation": schema_k8sio_api_admissionregistration_v1_AuditAnnotation(ref),
"k8s.io/api/admissionregistration/v1.ExpressionWarning": schema_k8sio_api_admissionregistration_v1_ExpressionWarning(ref),
"k8s.io/api/admissionregistration/v1.MatchCondition": schema_k8sio_api_admissionregistration_v1_MatchCondition(ref),
"k8s.io/api/admissionregistration/v1.MatchResources": schema_k8sio_api_admissionregistration_v1_MatchResources(ref),
"k8s.io/api/admissionregistration/v1.MutatingWebhook": schema_k8sio_api_admissionregistration_v1_MutatingWebhook(ref),
"k8s.io/api/admissionregistration/v1.MutatingWebhookConfiguration": schema_k8sio_api_admissionregistration_v1_MutatingWebhookConfiguration(ref),
"k8s.io/api/admissionregistration/v1.MutatingWebhookConfigurationList": schema_k8sio_api_admissionregistration_v1_MutatingWebhookConfigurationList(ref),
"k8s.io/api/admissionregistration/v1.NamedRuleWithOperations": schema_k8sio_api_admissionregistration_v1_NamedRuleWithOperations(ref),
"k8s.io/api/admissionregistration/v1.ParamKind": schema_k8sio_api_admissionregistration_v1_ParamKind(ref),
"k8s.io/api/admissionregistration/v1.ParamRef": schema_k8sio_api_admissionregistration_v1_ParamRef(ref),
"k8s.io/api/admissionregistration/v1.Rule": schema_k8sio_api_admissionregistration_v1_Rule(ref),
"k8s.io/api/admissionregistration/v1.RuleWithOperations": schema_k8sio_api_admissionregistration_v1_RuleWithOperations(ref),
"k8s.io/api/admissionregistration/v1.ServiceReference": schema_k8sio_api_admissionregistration_v1_ServiceReference(ref),
"k8s.io/api/admissionregistration/v1.TypeChecking": schema_k8sio_api_admissionregistration_v1_TypeChecking(ref),
"k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicy": schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicy(ref),
"k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicyBinding": schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicyBinding(ref),
"k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicyBindingList": schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicyBindingList(ref),
"k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicyBindingSpec": schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicyBindingSpec(ref),
"k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicyList": schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicyList(ref),
"k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicySpec": schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicySpec(ref),
"k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicyStatus": schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicyStatus(ref),
"k8s.io/api/admissionregistration/v1.ValidatingWebhook": schema_k8sio_api_admissionregistration_v1_ValidatingWebhook(ref),
"k8s.io/api/admissionregistration/v1.ValidatingWebhookConfiguration": schema_k8sio_api_admissionregistration_v1_ValidatingWebhookConfiguration(ref),
"k8s.io/api/admissionregistration/v1.ValidatingWebhookConfigurationList": schema_k8sio_api_admissionregistration_v1_ValidatingWebhookConfigurationList(ref),
"k8s.io/api/admissionregistration/v1.Validation": schema_k8sio_api_admissionregistration_v1_Validation(ref),
"k8s.io/api/admissionregistration/v1.Variable": schema_k8sio_api_admissionregistration_v1_Variable(ref),
"k8s.io/api/admissionregistration/v1.WebhookClientConfig": schema_k8sio_api_admissionregistration_v1_WebhookClientConfig(ref),
"k8s.io/api/admissionregistration/v1alpha1.AuditAnnotation": schema_k8sio_api_admissionregistration_v1alpha1_AuditAnnotation(ref),
"k8s.io/api/admissionregistration/v1alpha1.ExpressionWarning": schema_k8sio_api_admissionregistration_v1alpha1_ExpressionWarning(ref),
@ -1170,6 +1186,66 @@ func GetOpenAPIDefinitions(ref common.ReferenceCallback) map[string]common.OpenA
}
}
func schema_k8sio_api_admissionregistration_v1_AuditAnnotation(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "AuditAnnotation describes how to produce an audit annotation for an API request.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"key": {
SchemaProps: spec.SchemaProps{
Description: "key specifies the audit annotation key. The audit annotation keys of a ValidatingAdmissionPolicy must be unique. The key must be a qualified name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.\n\nThe key is combined with the resource name of the ValidatingAdmissionPolicy to construct an audit annotation key: \"{ValidatingAdmissionPolicy name}/{key}\".\n\nIf an admission webhook uses the same resource name as this ValidatingAdmissionPolicy and the same audit annotation key, the annotation key will be identical. In this case, the first annotation written with the key will be included in the audit event and all subsequent annotations with the same key will be discarded.\n\nRequired.",
Default: "",
Type: []string{"string"},
Format: "",
},
},
"valueExpression": {
SchemaProps: spec.SchemaProps{
Description: "valueExpression represents the expression which is evaluated by CEL to produce an audit annotation value. The expression must evaluate to either a string or null value. If the expression evaluates to a string, the audit annotation is included with the string value. If the expression evaluates to null or empty string the audit annotation will be omitted. The valueExpression may be no longer than 5kb in length. If the result of the valueExpression is more than 10kb in length, it will be truncated to 10kb.\n\nIf multiple ValidatingAdmissionPolicyBinding resources match an API request, then the valueExpression will be evaluated for each binding. All unique values produced by the valueExpressions will be joined together in a comma-separated list.\n\nRequired.",
Default: "",
Type: []string{"string"},
Format: "",
},
},
},
Required: []string{"key", "valueExpression"},
},
},
}
}
func schema_k8sio_api_admissionregistration_v1_ExpressionWarning(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "ExpressionWarning is a warning information that targets a specific expression.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"fieldRef": {
SchemaProps: spec.SchemaProps{
Description: "The path to the field that refers the expression. For example, the reference to the expression of the first item of validations is \"spec.validations[0].expression\"",
Default: "",
Type: []string{"string"},
Format: "",
},
},
"warning": {
SchemaProps: spec.SchemaProps{
Description: "The content of type checking information in a human-readable form. Each line of the warning contains the type that the expression is checked against, followed by the type check error from the compiler.",
Default: "",
Type: []string{"string"},
Format: "",
},
},
},
Required: []string{"fieldRef", "warning"},
},
},
}
}
func schema_k8sio_api_admissionregistration_v1_MatchCondition(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
@ -1200,6 +1276,84 @@ func schema_k8sio_api_admissionregistration_v1_MatchCondition(ref common.Referen
}
}
func schema_k8sio_api_admissionregistration_v1_MatchResources(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "MatchResources decides whether to run the admission control policy on an object based on whether it meets the match criteria. The exclude rules take precedence over include rules (if a resource matches both, it is excluded)",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"namespaceSelector": {
SchemaProps: spec.SchemaProps{
Description: "NamespaceSelector decides whether to run the admission control policy on an object based on whether the namespace for that object matches the selector. If the object itself is a namespace, the matching is performed on object.metadata.labels. If the object is another cluster scoped resource, it never skips the policy.\n\nFor example, to run the webhook on any objects whose namespace is not associated with \"runlevel\" of \"0\" or \"1\"; you will set the selector as follows: \"namespaceSelector\": {\n \"matchExpressions\": [\n {\n \"key\": \"runlevel\",\n \"operator\": \"NotIn\",\n \"values\": [\n \"0\",\n \"1\"\n ]\n }\n ]\n}\n\nIf instead you want to only run the policy on any objects whose namespace is associated with the \"environment\" of \"prod\" or \"staging\"; you will set the selector as follows: \"namespaceSelector\": {\n \"matchExpressions\": [\n {\n \"key\": \"environment\",\n \"operator\": \"In\",\n \"values\": [\n \"prod\",\n \"staging\"\n ]\n }\n ]\n}\n\nSee https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ for more examples of label selectors.\n\nDefault to the empty LabelSelector, which matches everything.",
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"),
},
},
"objectSelector": {
SchemaProps: spec.SchemaProps{
Description: "ObjectSelector decides whether to run the validation based on if the object has matching labels. objectSelector is evaluated against both the oldObject and newObject that would be sent to the cel validation, and is considered to match if either object matches the selector. A null object (oldObject in the case of create, or newObject in the case of delete) or an object that cannot have labels (like a DeploymentRollback or a PodProxyOptions object) is not considered to match. Use the object selector only if the webhook is opt-in, because end users may skip the admission webhook by setting the labels. Default to the empty LabelSelector, which matches everything.",
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"),
},
},
"resourceRules": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Description: "ResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy matches. The policy cares about an operation if it matches _any_ Rule.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.NamedRuleWithOperations"),
},
},
},
},
},
"excludeResourceRules": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Description: "ExcludeResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy should not care about. The exclude rules take precedence over include rules (if a resource matches both, it is excluded)",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.NamedRuleWithOperations"),
},
},
},
},
},
"matchPolicy": {
SchemaProps: spec.SchemaProps{
Description: "matchPolicy defines how the \"MatchResources\" list is used to match incoming requests. Allowed values are \"Exact\" or \"Equivalent\".\n\n- Exact: match a request only if it exactly matches a specified rule. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, but \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the ValidatingAdmissionPolicy.\n\n- Equivalent: match a request if modifies a resource listed in rules, even via another API group or version. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, and \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the ValidatingAdmissionPolicy.\n\nDefaults to \"Equivalent\"\n\nPossible enum values:\n - `\"Equivalent\"` means requests should be sent to the webhook if they modify a resource listed in rules via another API group or version.\n - `\"Exact\"` means requests should only be sent to the webhook if they exactly match a given rule.",
Type: []string{"string"},
Format: "",
Enum: []interface{}{"Equivalent", "Exact"},
},
},
},
},
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-map-type": "atomic",
},
},
},
Dependencies: []string{
"k8s.io/api/admissionregistration/v1.NamedRuleWithOperations", "k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"},
}
}
func schema_k8sio_api_admissionregistration_v1_MutatingWebhook(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
@ -1456,6 +1610,211 @@ func schema_k8sio_api_admissionregistration_v1_MutatingWebhookConfigurationList(
}
}
func schema_k8sio_api_admissionregistration_v1_NamedRuleWithOperations(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "NamedRuleWithOperations is a tuple of Operations and Resources with ResourceNames.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"resourceNames": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Description: "ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: "",
Type: []string{"string"},
Format: "",
},
},
},
},
},
"operations": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Description: "Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: "",
Type: []string{"string"},
Format: "",
Enum: []interface{}{"*", "CONNECT", "CREATE", "DELETE", "UPDATE"},
},
},
},
},
},
"apiGroups": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Description: "APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: "",
Type: []string{"string"},
Format: "",
},
},
},
},
},
"apiVersions": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Description: "APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: "",
Type: []string{"string"},
Format: "",
},
},
},
},
},
"resources": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Description: "Resources is a list of resources this rule applies to.\n\nFor example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources.\n\nIf wildcard is present, the validation rule will ensure resources do not overlap with each other.\n\nDepending on the enclosing object, subresources might not be allowed. Required.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: "",
Type: []string{"string"},
Format: "",
},
},
},
},
},
"scope": {
SchemaProps: spec.SchemaProps{
Description: "scope specifies the scope of this rule. Valid values are \"Cluster\", \"Namespaced\", and \"*\" \"Cluster\" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. \"Namespaced\" means that only namespaced resources will match this rule. \"*\" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is \"*\".",
Type: []string{"string"},
Format: "",
},
},
},
},
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-map-type": "atomic",
},
},
},
}
}
func schema_k8sio_api_admissionregistration_v1_ParamKind(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "ParamKind is a tuple of Group Kind and Version.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"apiVersion": {
SchemaProps: spec.SchemaProps{
Description: "APIVersion is the API group version the resources belong to. In format of \"group/version\". Required.",
Type: []string{"string"},
Format: "",
},
},
"kind": {
SchemaProps: spec.SchemaProps{
Description: "Kind is the API kind the resources belong to. Required.",
Type: []string{"string"},
Format: "",
},
},
},
},
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-map-type": "atomic",
},
},
},
}
}
func schema_k8sio_api_admissionregistration_v1_ParamRef(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "ParamRef describes how to locate the params to be used as input to expressions of rules applied by a policy binding.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"name": {
SchemaProps: spec.SchemaProps{
Description: "name is the name of the resource being referenced.\n\nOne of `name` or `selector` must be set, but `name` and `selector` are mutually exclusive properties. If one is set, the other must be unset.\n\nA single parameter used for all admission requests can be configured by setting the `name` field, leaving `selector` blank, and setting namespace if `paramKind` is namespace-scoped.",
Type: []string{"string"},
Format: "",
},
},
"namespace": {
SchemaProps: spec.SchemaProps{
Description: "namespace is the namespace of the referenced resource. Allows limiting the search for params to a specific namespace. Applies to both `name` and `selector` fields.\n\nA per-namespace parameter may be used by specifying a namespace-scoped `paramKind` in the policy and leaving this field empty.\n\n- If `paramKind` is cluster-scoped, this field MUST be unset. Setting this field results in a configuration error.\n\n- If `paramKind` is namespace-scoped, the namespace of the object being evaluated for admission will be used when this field is left unset. Take care that if this is left empty the binding must not match any cluster-scoped resources, which will result in an error.",
Type: []string{"string"},
Format: "",
},
},
"selector": {
SchemaProps: spec.SchemaProps{
Description: "selector can be used to match multiple param objects based on their labels. Supply selector: {} to match all resources of the ParamKind.\n\nIf multiple params are found, they are all evaluated with the policy expressions and the results are ANDed together.\n\nOne of `name` or `selector` must be set, but `name` and `selector` are mutually exclusive properties. If one is set, the other must be unset.",
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"),
},
},
"parameterNotFoundAction": {
SchemaProps: spec.SchemaProps{
Description: "`parameterNotFoundAction` controls the behavior of the binding when the resource exists, and name or selector is valid, but there are no parameters matched by the binding. If the value is set to `Allow`, then no matched parameters will be treated as successful validation by the binding. If set to `Deny`, then no matched parameters will be subject to the `failurePolicy` of the policy.\n\nAllowed values are `Allow` or `Deny`\n\nRequired",
Type: []string{"string"},
Format: "",
},
},
},
},
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-map-type": "atomic",
},
},
},
Dependencies: []string{
"k8s.io/apimachinery/pkg/apis/meta/v1.LabelSelector"},
}
}
func schema_k8sio_api_admissionregistration_v1_Rule(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
@ -1681,6 +2040,459 @@ func schema_k8sio_api_admissionregistration_v1_ServiceReference(ref common.Refer
}
}
func schema_k8sio_api_admissionregistration_v1_TypeChecking(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "TypeChecking contains results of type checking the expressions in the ValidatingAdmissionPolicy",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"expressionWarnings": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Description: "The type checking warnings for each expression.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.ExpressionWarning"),
},
},
},
},
},
},
},
},
Dependencies: []string{
"k8s.io/api/admissionregistration/v1.ExpressionWarning"},
}
}
func schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicy(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
Type: []string{"string"},
Format: "",
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
Type: []string{"string"},
Format: "",
},
},
"metadata": {
SchemaProps: spec.SchemaProps{
Description: "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.",
Default: map[string]interface{}{},
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"),
},
},
"spec": {
SchemaProps: spec.SchemaProps{
Description: "Specification of the desired behavior of the ValidatingAdmissionPolicy.",
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicySpec"),
},
},
"status": {
SchemaProps: spec.SchemaProps{
Description: "The status of the ValidatingAdmissionPolicy, including warnings that are useful to determine if the policy behaves in the expected way. Populated by the system. Read-only.",
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicyStatus"),
},
},
},
},
},
Dependencies: []string{
"k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicySpec", "k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicyStatus", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"},
}
}
func schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicyBinding(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "ValidatingAdmissionPolicyBinding binds the ValidatingAdmissionPolicy with paramerized resources. ValidatingAdmissionPolicyBinding and parameter CRDs together define how cluster administrators configure policies for clusters.\n\nFor a given admission request, each binding will cause its policy to be evaluated N times, where N is 1 for policies/bindings that don't use params, otherwise N is the number of parameters selected by the binding.\n\nThe CEL expressions of a policy must have a computed CEL cost below the maximum CEL budget. Each evaluation of the policy is given an independent CEL cost budget. Adding/removing policies, bindings, or params can not affect whether a given (policy, binding, param) combination is within its own CEL budget.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
Type: []string{"string"},
Format: "",
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
Type: []string{"string"},
Format: "",
},
},
"metadata": {
SchemaProps: spec.SchemaProps{
Description: "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.",
Default: map[string]interface{}{},
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"),
},
},
"spec": {
SchemaProps: spec.SchemaProps{
Description: "Specification of the desired behavior of the ValidatingAdmissionPolicyBinding.",
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicyBindingSpec"),
},
},
},
},
},
Dependencies: []string{
"k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicyBindingSpec", "k8s.io/apimachinery/pkg/apis/meta/v1.ObjectMeta"},
}
}
func schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicyBindingList(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "ValidatingAdmissionPolicyBindingList is a list of ValidatingAdmissionPolicyBinding.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
Type: []string{"string"},
Format: "",
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
Type: []string{"string"},
Format: "",
},
},
"metadata": {
SchemaProps: spec.SchemaProps{
Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
Default: map[string]interface{}{},
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"),
},
},
"items": {
SchemaProps: spec.SchemaProps{
Description: "List of PolicyBinding.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicyBinding"),
},
},
},
},
},
},
},
},
Dependencies: []string{
"k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicyBinding", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"},
}
}
func schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicyBindingSpec(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "ValidatingAdmissionPolicyBindingSpec is the specification of the ValidatingAdmissionPolicyBinding.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"policyName": {
SchemaProps: spec.SchemaProps{
Description: "PolicyName references a ValidatingAdmissionPolicy name which the ValidatingAdmissionPolicyBinding binds to. If the referenced resource does not exist, this binding is considered invalid and will be ignored Required.",
Type: []string{"string"},
Format: "",
},
},
"paramRef": {
SchemaProps: spec.SchemaProps{
Description: "paramRef specifies the parameter resource used to configure the admission control policy. It should point to a resource of the type specified in ParamKind of the bound ValidatingAdmissionPolicy. If the policy specifies a ParamKind and the resource referred to by ParamRef does not exist, this binding is considered mis-configured and the FailurePolicy of the ValidatingAdmissionPolicy applied. If the policy does not specify a ParamKind then this field is ignored, and the rules are evaluated without a param.",
Ref: ref("k8s.io/api/admissionregistration/v1.ParamRef"),
},
},
"matchResources": {
SchemaProps: spec.SchemaProps{
Description: "MatchResources declares what resources match this binding and will be validated by it. Note that this is intersected with the policy's matchConstraints, so only requests that are matched by the policy can be selected by this. If this is unset, all resources matched by the policy are validated by this binding When resourceRules is unset, it does not constrain resource matching. If a resource is matched by the other fields of this object, it will be validated. Note that this is differs from ValidatingAdmissionPolicy matchConstraints, where resourceRules are required.",
Ref: ref("k8s.io/api/admissionregistration/v1.MatchResources"),
},
},
"validationActions": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "set",
},
},
SchemaProps: spec.SchemaProps{
Description: "validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced. If a validation evaluates to false it is always enforced according to these actions.\n\nFailures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according to these actions only if the FailurePolicy is set to Fail, otherwise the failures are ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.\n\nvalidationActions is declared as a set of action values. Order does not matter. validationActions may not contain duplicates of the same action.\n\nThe supported actions values are:\n\n\"Deny\" specifies that a validation failure results in a denied request.\n\n\"Warn\" specifies that a validation failure is reported to the request client in HTTP Warning headers, with a warning code of 299. Warnings can be sent both for allowed or denied admission responses.\n\n\"Audit\" specifies that a validation failure is included in the published audit event for the request. The audit event will contain a `validation.policy.admission.k8s.io/validation_failure` audit annotation with a value containing the details of the validation failures, formatted as a JSON list of objects, each with the following fields: - message: The validation failure message string - policy: The resource name of the ValidatingAdmissionPolicy - binding: The resource name of the ValidatingAdmissionPolicyBinding - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy - validationActions: The enforcement actions enacted for the validation failure Example audit annotation: `\"validation.policy.admission.k8s.io/validation_failure\": \"[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]\"`\n\nClients should expect to handle additional values by ignoring any values not recognized.\n\n\"Deny\" and \"Warn\" may not be used together since this combination needlessly duplicates the validation failure both in the API response body and the HTTP warning headers.\n\nRequired.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: "",
Type: []string{"string"},
Format: "",
Enum: []interface{}{"Audit", "Deny", "Warn"},
},
},
},
},
},
},
},
},
Dependencies: []string{
"k8s.io/api/admissionregistration/v1.MatchResources", "k8s.io/api/admissionregistration/v1.ParamRef"},
}
}
func schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicyList(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "ValidatingAdmissionPolicyList is a list of ValidatingAdmissionPolicy.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"kind": {
SchemaProps: spec.SchemaProps{
Description: "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
Type: []string{"string"},
Format: "",
},
},
"apiVersion": {
SchemaProps: spec.SchemaProps{
Description: "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources",
Type: []string{"string"},
Format: "",
},
},
"metadata": {
SchemaProps: spec.SchemaProps{
Description: "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
Default: map[string]interface{}{},
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"),
},
},
"items": {
SchemaProps: spec.SchemaProps{
Description: "List of ValidatingAdmissionPolicy.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicy"),
},
},
},
},
},
},
},
},
Dependencies: []string{
"k8s.io/api/admissionregistration/v1.ValidatingAdmissionPolicy", "k8s.io/apimachinery/pkg/apis/meta/v1.ListMeta"},
}
}
func schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicySpec(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "ValidatingAdmissionPolicySpec is the specification of the desired behavior of the AdmissionPolicy.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"paramKind": {
SchemaProps: spec.SchemaProps{
Description: "ParamKind specifies the kind of resources used to parameterize this policy. If absent, there are no parameters for this policy and the param CEL variable will not be provided to validation expressions. If ParamKind refers to a non-existent kind, this policy definition is mis-configured and the FailurePolicy is applied. If paramKind is specified but paramRef is unset in ValidatingAdmissionPolicyBinding, the params variable will be null.",
Ref: ref("k8s.io/api/admissionregistration/v1.ParamKind"),
},
},
"matchConstraints": {
SchemaProps: spec.SchemaProps{
Description: "MatchConstraints specifies what resources this policy is designed to validate. The AdmissionPolicy cares about a request if it matches _all_ Constraints. However, in order to prevent clusters from being put into an unstable state that cannot be recovered from via the API ValidatingAdmissionPolicy cannot match ValidatingAdmissionPolicy and ValidatingAdmissionPolicyBinding. Required.",
Ref: ref("k8s.io/api/admissionregistration/v1.MatchResources"),
},
},
"validations": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Description: "Validations contain CEL expressions which is used to apply the validation. Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is required.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.Validation"),
},
},
},
},
},
"failurePolicy": {
SchemaProps: spec.SchemaProps{
Description: "failurePolicy defines how to handle failures for the admission policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions or bindings.\n\nA policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource.\n\nfailurePolicy does not define how validations that evaluate to false are handled.\n\nWhen failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions define how failures are enforced.\n\nAllowed values are Ignore or Fail. Defaults to Fail.\n\nPossible enum values:\n - `\"Fail\"` means that an error calling the webhook causes the admission to fail.\n - `\"Ignore\"` means that an error calling the webhook is ignored.",
Type: []string{"string"},
Format: "",
Enum: []interface{}{"Fail", "Ignore"},
},
},
"auditAnnotations": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-type": "atomic",
},
},
SchemaProps: spec.SchemaProps{
Description: "auditAnnotations contains CEL expressions which are used to produce audit annotations for the audit event of the API request. validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is required.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.AuditAnnotation"),
},
},
},
},
},
"matchConditions": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-map-keys": []interface{}{
"name",
},
"x-kubernetes-list-type": "map",
"x-kubernetes-patch-merge-key": "name",
"x-kubernetes-patch-strategy": "merge",
},
},
SchemaProps: spec.SchemaProps{
Description: "MatchConditions is a list of conditions that must be met for a request to be validated. Match conditions filter requests that have already been matched by the rules, namespaceSelector, and objectSelector. An empty list of matchConditions matches all requests. There are a maximum of 64 match conditions allowed.\n\nIf a parameter object is provided, it can be accessed via the `params` handle in the same manner as validation expressions.\n\nThe exact matching logic is (in order):\n 1. If ANY matchCondition evaluates to FALSE, the policy is skipped.\n 2. If ALL matchConditions evaluate to TRUE, the policy is evaluated.\n 3. If any matchCondition evaluates to an error (but none are FALSE):\n - If failurePolicy=Fail, reject the request\n - If failurePolicy=Ignore, the policy is skipped",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.MatchCondition"),
},
},
},
},
},
"variables": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-map-keys": []interface{}{
"name",
},
"x-kubernetes-list-type": "map",
"x-kubernetes-patch-merge-key": "name",
"x-kubernetes-patch-strategy": "merge",
},
},
SchemaProps: spec.SchemaProps{
Description: "Variables contain definitions of variables that can be used in composition of other expressions. Each variable is defined as a named CEL expression. The variables defined here will be available under `variables` in other expressions of the policy except MatchConditions because MatchConditions are evaluated before the rest of the policy.\n\nThe expression of a variable can refer to other variables defined earlier in the list but not those after. Thus, Variables must be sorted by the order of first appearance and acyclic.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/api/admissionregistration/v1.Variable"),
},
},
},
},
},
},
},
},
Dependencies: []string{
"k8s.io/api/admissionregistration/v1.AuditAnnotation", "k8s.io/api/admissionregistration/v1.MatchCondition", "k8s.io/api/admissionregistration/v1.MatchResources", "k8s.io/api/admissionregistration/v1.ParamKind", "k8s.io/api/admissionregistration/v1.Validation", "k8s.io/api/admissionregistration/v1.Variable"},
}
}
func schema_k8sio_api_admissionregistration_v1_ValidatingAdmissionPolicyStatus(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "ValidatingAdmissionPolicyStatus represents the status of an admission validation policy.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"observedGeneration": {
SchemaProps: spec.SchemaProps{
Description: "The generation observed by the controller.",
Type: []string{"integer"},
Format: "int64",
},
},
"typeChecking": {
SchemaProps: spec.SchemaProps{
Description: "The results of type checking for each expression. Presence of this field indicates the completion of the type checking.",
Ref: ref("k8s.io/api/admissionregistration/v1.TypeChecking"),
},
},
"conditions": {
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-list-map-keys": []interface{}{
"type",
},
"x-kubernetes-list-type": "map",
},
},
SchemaProps: spec.SchemaProps{
Description: "The conditions represent the latest available observations of a policy's current state.",
Type: []string{"array"},
Items: &spec.SchemaOrArray{
Schema: &spec.Schema{
SchemaProps: spec.SchemaProps{
Default: map[string]interface{}{},
Ref: ref("k8s.io/apimachinery/pkg/apis/meta/v1.Condition"),
},
},
},
},
},
},
},
},
Dependencies: []string{
"k8s.io/api/admissionregistration/v1.TypeChecking", "k8s.io/apimachinery/pkg/apis/meta/v1.Condition"},
}
}
func schema_k8sio_api_admissionregistration_v1_ValidatingWebhook(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
@ -1929,6 +2741,84 @@ func schema_k8sio_api_admissionregistration_v1_ValidatingWebhookConfigurationLis
}
}
func schema_k8sio_api_admissionregistration_v1_Validation(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "Validation specifies the CEL expression which is used to apply the validation.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"expression": {
SchemaProps: spec.SchemaProps{
Description: "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources. - 'variables' - Map of composited variables, from its name to its lazily evaluated value.\n For example, a variable named 'foo' can be accessed as 'variables.foo'.\n- 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.",
Default: "",
Type: []string{"string"},
Format: "",
},
},
"message": {
SchemaProps: spec.SchemaProps{
Description: "Message represents the message displayed when validation fails. The message is required if the Expression contains line breaks. The message must not contain line breaks. If unset, the message is \"failed rule: {Rule}\". e.g. \"must be a URL with the host matching spec.host\" If the Expression contains line breaks. Message is required. The message must not contain line breaks. If unset, the message is \"failed Expression: {Expression}\".",
Type: []string{"string"},
Format: "",
},
},
"reason": {
SchemaProps: spec.SchemaProps{
Description: "Reason represents a machine-readable description of why this validation failed. If this is the first validation in the list to fail, this reason, as well as the corresponding HTTP response code, are used in the HTTP response to the client. The currently supported reasons are: \"Unauthorized\", \"Forbidden\", \"Invalid\", \"RequestEntityTooLarge\". If not set, StatusReasonInvalid is used in the response to the client.",
Type: []string{"string"},
Format: "",
},
},
"messageExpression": {
SchemaProps: spec.SchemaProps{
Description: "messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. Since messageExpression is used as a failure message, it must evaluate to a string. If both message and messageExpression are present on a validation, then messageExpression will be used if validation fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged. messageExpression has access to all the same variables as the `expression` except for 'authorizer' and 'authorizer.requestResource'. Example: \"object.x must be less than max (\"+string(params.max)+\")\"",
Type: []string{"string"},
Format: "",
},
},
},
Required: []string{"expression"},
},
},
}
}
func schema_k8sio_api_admissionregistration_v1_Variable(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{
SchemaProps: spec.SchemaProps{
Description: "Variable is the definition of a variable that is used for composition. A variable is defined as a named expression.",
Type: []string{"object"},
Properties: map[string]spec.Schema{
"name": {
SchemaProps: spec.SchemaProps{
Description: "Name is the name of the variable. The name must be a valid CEL identifier and unique among all variables. The variable can be accessed in other expressions through `variables` For example, if name is \"foo\", the variable will be available as `variables.foo`",
Default: "",
Type: []string{"string"},
Format: "",
},
},
"expression": {
SchemaProps: spec.SchemaProps{
Description: "Expression is the expression that will be evaluated as the value of the variable. The CEL expression has access to the same identifiers as the CEL expressions in Validation.",
Default: "",
Type: []string{"string"},
Format: "",
},
},
},
Required: []string{"name", "expression"},
},
VendorExtensible: spec.VendorExtensible{
Extensions: spec.Extensions{
"x-kubernetes-map-type": "atomic",
},
},
},
}
}
func schema_k8sio_api_admissionregistration_v1_WebhookClientConfig(ref common.ReferenceCallback) common.OpenAPIDefinition {
return common.OpenAPIDefinition{
Schema: spec.Schema{

View File

@ -19,23 +19,17 @@ package admission
import (
"net/http"
"os"
"time"
"k8s.io/klog/v2"
"go.opentelemetry.io/otel/trace"
utilwait "k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apiserver/pkg/admission"
webhookinit "k8s.io/apiserver/pkg/admission/plugin/webhook/initializer"
genericapiserver "k8s.io/apiserver/pkg/server"
"k8s.io/apiserver/pkg/server/egressselector"
"k8s.io/apiserver/pkg/util/webhook"
cacheddiscovery "k8s.io/client-go/discovery/cached/memory"
externalinformers "k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/kubernetes/pkg/kubeapiserver/admission/exclusion"
quotainstall "k8s.io/kubernetes/pkg/quota/v1/install"
)
@ -48,7 +42,7 @@ type Config struct {
}
// New sets up the plugins and admission start hooks needed for admission
func (c *Config) New(proxyTransport *http.Transport, egressSelector *egressselector.EgressSelector, serviceResolver webhook.ServiceResolver, tp trace.TracerProvider) ([]admission.PluginInitializer, genericapiserver.PostStartHookFunc, error) {
func (c *Config) New(proxyTransport *http.Transport, egressSelector *egressselector.EgressSelector, serviceResolver webhook.ServiceResolver, tp trace.TracerProvider) ([]admission.PluginInitializer, error) {
webhookAuthResolverWrapper := webhook.NewDefaultAuthenticationInfoResolverWrapper(proxyTransport, egressSelector, c.LoopbackClientConfig, tp)
webhookPluginInitializer := webhookinit.NewPluginInitializer(webhookAuthResolverWrapper, serviceResolver)
@ -60,24 +54,11 @@ func (c *Config) New(proxyTransport *http.Transport, egressSelector *egressselec
klog.Fatalf("Error reading from cloud configuration file %s: %#v", c.CloudConfigFile, err)
}
}
clientset, err := kubernetes.NewForConfig(c.LoopbackClientConfig)
if err != nil {
return nil, nil, err
}
discoveryClient := cacheddiscovery.NewMemCacheClient(clientset.Discovery())
discoveryRESTMapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)
kubePluginInitializer := NewPluginInitializer(
cloudConfig,
discoveryRESTMapper,
quotainstall.NewQuotaConfigurationForAdmission(),
exclusion.Excluded(),
)
admissionPostStartHook := func(context genericapiserver.PostStartHookContext) error {
discoveryRESTMapper.Reset()
go utilwait.Until(discoveryRESTMapper.Reset, 30*time.Second, context.StopCh)
return nil
}
return []admission.PluginInitializer{webhookPluginInitializer, kubePluginInitializer}, admissionPostStartHook, nil
return []admission.PluginInitializer{webhookPluginInitializer, kubePluginInitializer}, nil
}

View File

@ -17,7 +17,6 @@ limitations under the License.
package admission
import (
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/initializer"
@ -34,7 +33,6 @@ type WantsCloudConfig interface {
// PluginInitializer is used for initialization of the Kubernetes specific admission plugins.
type PluginInitializer struct {
cloudConfig []byte
restMapper meta.RESTMapper
quotaConfiguration quota.Configuration
excludedAdmissionResources []schema.GroupResource
}
@ -46,13 +44,11 @@ var _ admission.PluginInitializer = &PluginInitializer{}
// all public, this construction method is pointless boilerplate.
func NewPluginInitializer(
cloudConfig []byte,
restMapper meta.RESTMapper,
quotaConfiguration quota.Configuration,
excludedAdmissionResources []schema.GroupResource,
) *PluginInitializer {
return &PluginInitializer{
cloudConfig: cloudConfig,
restMapper: restMapper,
quotaConfiguration: quotaConfiguration,
excludedAdmissionResources: excludedAdmissionResources,
}
@ -65,10 +61,6 @@ func (i *PluginInitializer) Initialize(plugin admission.Interface) {
wants.SetCloudConfig(i.cloudConfig)
}
if wants, ok := plugin.(initializer.WantsRESTMapper); ok {
wants.SetRESTMapper(i.restMapper)
}
if wants, ok := plugin.(initializer.WantsQuotaConfiguration); ok {
wants.SetQuotaConfiguration(i.quotaConfiguration)
}

View File

@ -20,7 +20,6 @@ import (
"context"
"testing"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/admission"
quota "k8s.io/apiserver/pkg/quota/v1"
@ -49,7 +48,7 @@ func (p *WantsCloudConfigAdmissionPlugin) SetCloudConfig(cloudConfig []byte) {
func TestCloudConfigAdmissionPlugin(t *testing.T) {
cloudConfig := []byte("cloud-configuration")
initializer := NewPluginInitializer(cloudConfig, nil, nil, nil)
initializer := NewPluginInitializer(cloudConfig, nil, nil)
wantsCloudConfigAdmission := &WantsCloudConfigAdmissionPlugin{}
initializer.Initialize(wantsCloudConfigAdmission)
@ -58,51 +57,6 @@ func TestCloudConfigAdmissionPlugin(t *testing.T) {
}
}
type doNothingRESTMapper struct{}
func (doNothingRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
return schema.GroupVersionKind{}, nil
}
func (doNothingRESTMapper) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) {
return nil, nil
}
func (doNothingRESTMapper) ResourceFor(input schema.GroupVersionResource) (schema.GroupVersionResource, error) {
return schema.GroupVersionResource{}, nil
}
func (doNothingRESTMapper) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
return nil, nil
}
func (doNothingRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error) {
return nil, nil
}
func (doNothingRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*meta.RESTMapping, error) {
return nil, nil
}
func (doNothingRESTMapper) ResourceSingularizer(resource string) (singular string, err error) {
return "", nil
}
type WantsRESTMapperAdmissionPlugin struct {
doNothingAdmission
doNothingPluginInitialization
mapper meta.RESTMapper
}
func (p *WantsRESTMapperAdmissionPlugin) SetRESTMapper(mapper meta.RESTMapper) {
p.mapper = mapper
}
func TestRESTMapperAdmissionPlugin(t *testing.T) {
mapper := doNothingRESTMapper{}
initializer := NewPluginInitializer(nil, mapper, nil, nil)
wantsRESTMapperAdmission := &WantsRESTMapperAdmissionPlugin{}
initializer.Initialize(wantsRESTMapperAdmission)
if wantsRESTMapperAdmission.mapper == nil {
t.Errorf("Expected REST mapper to be initialized but found nil")
}
}
type doNothingQuotaConfiguration struct{}
func (doNothingQuotaConfiguration) IgnoredResources() map[schema.GroupResource]struct{} { return nil }
@ -121,7 +75,7 @@ func (p *WantsQuotaConfigurationAdmissionPlugin) SetQuotaConfiguration(config qu
func TestQuotaConfigurationAdmissionPlugin(t *testing.T) {
config := doNothingQuotaConfiguration{}
initializer := NewPluginInitializer(nil, nil, config, nil)
initializer := NewPluginInitializer(nil, config, nil)
wantsQuotaConfigurationAdmission := &WantsQuotaConfigurationAdmissionPlugin{}
initializer.Initialize(wantsQuotaConfigurationAdmission)

View File

@ -68,6 +68,14 @@ func (p RESTStorageProvider) NewRESTStorage(apiResourceConfigSource serverstorag
func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.APIResourceConfigSource, restOptionsGetter generic.RESTOptionsGetter) (map[string]rest.Storage, error) {
storage := map[string]rest.Storage{}
// use a simple wrapper so that initialization order won't cause a nil getter
var policyGetter rest.Getter
r, err := resolver.NewDiscoveryResourceResolver(p.DiscoveryClient)
if err != nil {
return storage, err
}
// validatingwebhookconfigurations
if resource := "validatingwebhookconfigurations"; apiResourceConfigSource.ResourceEnabled(admissionregistrationv1.SchemeGroupVersion.WithResource(resource)) {
validatingStorage, err := validatingwebhookconfigurationstorage.NewREST(restOptionsGetter)
@ -86,6 +94,26 @@ func (p RESTStorageProvider) v1Storage(apiResourceConfigSource serverstorage.API
storage[resource] = mutatingStorage
}
// validatingadmissionpolicies
if resource := "validatingadmissionpolicies"; apiResourceConfigSource.ResourceEnabled(admissionregistrationv1.SchemeGroupVersion.WithResource(resource)) {
policyStorage, policyStatusStorage, err := validatingadmissionpolicystorage.NewREST(restOptionsGetter, p.Authorizer, r)
if err != nil {
return storage, err
}
policyGetter = policyStorage
storage[resource] = policyStorage
storage[resource+"/status"] = policyStatusStorage
}
// validatingadmissionpolicybindings
if resource := "validatingadmissionpolicybindings"; apiResourceConfigSource.ResourceEnabled(admissionregistrationv1.SchemeGroupVersion.WithResource(resource)) {
policyBindingStorage, err := policybindingstorage.NewREST(restOptionsGetter, p.Authorizer, &policybindingstorage.DefaultPolicyGetter{Getter: policyGetter}, r)
if err != nil {
return storage, err
}
storage[resource] = policyBindingStorage
}
return storage, nil
}

View File

@ -138,6 +138,9 @@ func (v *validatingAdmissionPolicyStrategy) GetResetFields() map[fieldpath.APIVe
"admissionregistration.k8s.io/v1beta1": fieldpath.NewSet(
fieldpath.MakePathOrDie("status"),
),
"admissionregistration.k8s.io/v1": fieldpath.NewSet(
fieldpath.MakePathOrDie("status"),
),
}
return fields
@ -177,6 +180,10 @@ func (s *validatingAdmissionPolicyStatusStrategy) GetResetFields() map[fieldpath
fieldpath.MakePathOrDie("spec"),
fieldpath.MakePathOrDie("metadata"),
),
"admissionregistration.k8s.io/v1": fieldpath.NewSet(
fieldpath.MakePathOrDie("spec"),
fieldpath.MakePathOrDie("metadata"),
),
}
}

View File

@ -115,7 +115,6 @@ func newGCPermissionsEnforcement() (*gcPermissionsEnforcement, error) {
whiteList: whiteList,
}
genericPluginInitializer := initializer.New(nil, nil, nil, fakeAuthorizer{}, nil, nil)
fakeDiscoveryClient := &fakediscovery.FakeDiscovery{Fake: &coretesting.Fake{}}
fakeDiscoveryClient.Resources = []*metav1.APIResourceList{
{
@ -133,13 +132,14 @@ func newGCPermissionsEnforcement() (*gcPermissionsEnforcement, error) {
},
},
}
restMapperRes, err := restmapper.GetAPIGroupResources(fakeDiscoveryClient)
if err != nil {
return nil, fmt.Errorf("unexpected error while constructing resource list from fake discovery client: %v", err)
}
restMapper := restmapper.NewDiscoveryRESTMapper(restMapperRes)
pluginInitializer := kubeadmission.NewPluginInitializer(nil, restMapper, nil, nil)
genericPluginInitializer := initializer.New(nil, nil, nil, fakeAuthorizer{}, nil, nil, restMapper)
pluginInitializer := kubeadmission.NewPluginInitializer(nil, nil, nil)
initializersChain := admission.PluginInitializers{}
initializersChain = append(initializersChain, genericPluginInitializer)
initializersChain = append(initializersChain, pluginInitializer)

View File

@ -817,7 +817,7 @@ func newHandlerForTest(c clientset.Interface) (*LimitRanger, informers.SharedInf
if err != nil {
return nil, f, err
}
pluginInitializer := genericadmissioninitializer.New(c, nil, f, nil, nil, nil)
pluginInitializer := genericadmissioninitializer.New(c, nil, f, nil, nil, nil, nil)
pluginInitializer.Initialize(handler)
err = admission.ValidateInitialization(handler)
return handler, f, err

View File

@ -41,7 +41,7 @@ import (
func newHandlerForTest(c clientset.Interface) (admission.MutationInterface, informers.SharedInformerFactory, error) {
f := informers.NewSharedInformerFactory(c, 5*time.Minute)
handler := NewProvision()
pluginInitializer := genericadmissioninitializer.New(c, nil, f, nil, nil, nil)
pluginInitializer := genericadmissioninitializer.New(c, nil, f, nil, nil, nil, nil)
pluginInitializer.Initialize(handler)
err := admission.ValidateInitialization(handler)
return handler, f, err

View File

@ -39,7 +39,7 @@ import (
func newHandlerForTest(c kubernetes.Interface) (admission.ValidationInterface, informers.SharedInformerFactory, error) {
f := informers.NewSharedInformerFactory(c, 5*time.Minute)
handler := NewExists()
pluginInitializer := genericadmissioninitializer.New(c, nil, f, nil, nil, nil)
pluginInitializer := genericadmissioninitializer.New(c, nil, f, nil, nil, nil, nil)
pluginInitializer.Initialize(handler)
err := admission.ValidateInitialization(handler)
return handler, f, err

View File

@ -198,7 +198,7 @@ func TestHandles(t *testing.T) {
func newHandlerForTest(c kubernetes.Interface) (*Plugin, informers.SharedInformerFactory, error) {
f := informers.NewSharedInformerFactory(c, 5*time.Minute)
handler := NewPodNodeSelector(nil)
pluginInitializer := genericadmissioninitializer.New(c, nil, f, nil, nil, nil)
pluginInitializer := genericadmissioninitializer.New(c, nil, f, nil, nil, nil, nil)
pluginInitializer.Initialize(handler)
err := admission.ValidateInitialization(handler)
return handler, f, err

View File

@ -355,7 +355,7 @@ func newHandlerForTest(c kubernetes.Interface) (*Plugin, informers.SharedInforme
return nil, nil, err
}
handler := NewPodTolerationsPlugin(pluginConfig)
pluginInitializer := genericadmissioninitializer.New(c, nil, f, nil, nil, nil)
pluginInitializer := genericadmissioninitializer.New(c, nil, f, nil, nil, nil, nil)
pluginInitializer.Initialize(handler)
err = admission.ValidateInitialization(handler)
return handler, f, err

View File

@ -114,8 +114,8 @@ func createHandlerWithConfig(kubeClient kubernetes.Interface, informerFactory in
}
initializers := admission.PluginInitializers{
genericadmissioninitializer.New(kubeClient, nil, informerFactory, nil, nil, stopCh),
kubeapiserveradmission.NewPluginInitializer(nil, nil, quotaConfiguration, nil),
genericadmissioninitializer.New(kubeClient, nil, informerFactory, nil, nil, stopCh, nil),
kubeapiserveradmission.NewPluginInitializer(nil, quotaConfiguration, nil),
}
initializers.Initialize(handler)

View File

@ -544,5 +544,22 @@ items:
- kind: ServiceAccount
name: ttl-controller
namespace: kube-system
- apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
annotations:
rbac.authorization.kubernetes.io/autoupdate: "true"
creationTimestamp: null
labels:
kubernetes.io/bootstrapping: rbac-defaults
name: system:controller:validatingadmissionpolicy-status-controller
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: system:controller:validatingadmissionpolicy-status-controller
subjects:
- kind: ServiceAccount
name: validatingadmissionpolicy-status-controller
namespace: kube-system
kind: List
metadata: {}

View File

@ -1543,5 +1543,40 @@ items:
- create
- patch
- update
- apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
annotations:
rbac.authorization.kubernetes.io/autoupdate: "true"
creationTimestamp: null
labels:
kubernetes.io/bootstrapping: rbac-defaults
name: system:controller:validatingadmissionpolicy-status-controller
rules:
- apiGroups:
- admissionregistration.k8s.io
resources:
- validatingadmissionpolicies
verbs:
- get
- list
- watch
- apiGroups:
- admissionregistration.k8s.io
resources:
- validatingadmissionpolicies/status
verbs:
- get
- patch
- update
- apiGroups:
- ""
- events.k8s.io
resources:
- events
verbs:
- create
- patch
- update
kind: List
metadata: {}

File diff suppressed because it is too large Load Diff

View File

@ -28,6 +28,56 @@ import "k8s.io/apimachinery/pkg/runtime/schema/generated.proto";
// Package-wide variables from generator "generated".
option go_package = "k8s.io/api/admissionregistration/v1";
// AuditAnnotation describes how to produce an audit annotation for an API request.
message AuditAnnotation {
// key specifies the audit annotation key. The audit annotation keys of
// a ValidatingAdmissionPolicy must be unique. The key must be a qualified
// name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.
//
// The key is combined with the resource name of the
// ValidatingAdmissionPolicy to construct an audit annotation key:
// "{ValidatingAdmissionPolicy name}/{key}".
//
// If an admission webhook uses the same resource name as this ValidatingAdmissionPolicy
// and the same audit annotation key, the annotation key will be identical.
// In this case, the first annotation written with the key will be included
// in the audit event and all subsequent annotations with the same key
// will be discarded.
//
// Required.
optional string key = 1;
// valueExpression represents the expression which is evaluated by CEL to
// produce an audit annotation value. The expression must evaluate to either
// a string or null value. If the expression evaluates to a string, the
// audit annotation is included with the string value. If the expression
// evaluates to null or empty string the audit annotation will be omitted.
// The valueExpression may be no longer than 5kb in length.
// If the result of the valueExpression is more than 10kb in length, it
// will be truncated to 10kb.
//
// If multiple ValidatingAdmissionPolicyBinding resources match an
// API request, then the valueExpression will be evaluated for
// each binding. All unique values produced by the valueExpressions
// will be joined together in a comma-separated list.
//
// Required.
optional string valueExpression = 2;
}
// ExpressionWarning is a warning information that targets a specific expression.
message ExpressionWarning {
// The path to the field that refers the expression.
// For example, the reference to the expression of the first item of
// validations is "spec.validations[0].expression"
optional string fieldRef = 2;
// The content of type checking information in a human-readable form.
// Each line of the warning contains the type that the expression is checked
// against, followed by the type check error from the compiler.
optional string warning = 3;
}
// MatchCondition represents a condition which must by fulfilled for a request to be sent to a webhook.
message MatchCondition {
// Name is an identifier for this match condition, used for strategic merging of MatchConditions,
@ -57,6 +107,101 @@ message MatchCondition {
optional string expression = 2;
}
// MatchResources decides whether to run the admission control policy on an object based
// on whether it meets the match criteria.
// The exclude rules take precedence over include rules (if a resource matches both, it is excluded)
// +structType=atomic
message MatchResources {
// NamespaceSelector decides whether to run the admission control policy on an object based
// on whether the namespace for that object matches the selector. If the
// object itself is a namespace, the matching is performed on
// object.metadata.labels. If the object is another cluster scoped resource,
// it never skips the policy.
//
// For example, to run the webhook on any objects whose namespace is not
// associated with "runlevel" of "0" or "1"; you will set the selector as
// follows:
// "namespaceSelector": {
// "matchExpressions": [
// {
// "key": "runlevel",
// "operator": "NotIn",
// "values": [
// "0",
// "1"
// ]
// }
// ]
// }
//
// If instead you want to only run the policy on any objects whose
// namespace is associated with the "environment" of "prod" or "staging";
// you will set the selector as follows:
// "namespaceSelector": {
// "matchExpressions": [
// {
// "key": "environment",
// "operator": "In",
// "values": [
// "prod",
// "staging"
// ]
// }
// ]
// }
//
// See
// https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/
// for more examples of label selectors.
//
// Default to the empty LabelSelector, which matches everything.
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector namespaceSelector = 1;
// ObjectSelector decides whether to run the validation based on if the
// object has matching labels. objectSelector is evaluated against both
// the oldObject and newObject that would be sent to the cel validation, and
// is considered to match if either object matches the selector. A null
// object (oldObject in the case of create, or newObject in the case of
// delete) or an object that cannot have labels (like a
// DeploymentRollback or a PodProxyOptions object) is not considered to
// match.
// Use the object selector only if the webhook is opt-in, because end
// users may skip the admission webhook by setting the labels.
// Default to the empty LabelSelector, which matches everything.
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector objectSelector = 2;
// ResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy matches.
// The policy cares about an operation if it matches _any_ Rule.
// +listType=atomic
// +optional
repeated NamedRuleWithOperations resourceRules = 3;
// ExcludeResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy should not care about.
// The exclude rules take precedence over include rules (if a resource matches both, it is excluded)
// +listType=atomic
// +optional
repeated NamedRuleWithOperations excludeResourceRules = 4;
// matchPolicy defines how the "MatchResources" list is used to match incoming requests.
// Allowed values are "Exact" or "Equivalent".
//
// - Exact: match a request only if it exactly matches a specified rule.
// For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1,
// but "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`,
// a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the ValidatingAdmissionPolicy.
//
// - Equivalent: match a request if modifies a resource listed in rules, even via another API group or version.
// For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1,
// and "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`,
// a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the ValidatingAdmissionPolicy.
//
// Defaults to "Equivalent"
// +optional
optional string matchPolicy = 7;
}
// MutatingWebhook describes an admission webhook and the resources and operations it applies to.
message MutatingWebhook {
// The name of the admission webhook.
@ -251,6 +396,88 @@ message MutatingWebhookConfigurationList {
repeated MutatingWebhookConfiguration items = 2;
}
// NamedRuleWithOperations is a tuple of Operations and Resources with ResourceNames.
// +structType=atomic
message NamedRuleWithOperations {
// ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.
// +listType=atomic
// +optional
repeated string resourceNames = 1;
// RuleWithOperations is a tuple of Operations and Resources.
optional RuleWithOperations ruleWithOperations = 2;
}
// ParamKind is a tuple of Group Kind and Version.
// +structType=atomic
message ParamKind {
// APIVersion is the API group version the resources belong to.
// In format of "group/version".
// Required.
optional string apiVersion = 1;
// Kind is the API kind the resources belong to.
// Required.
optional string kind = 2;
}
// ParamRef describes how to locate the params to be used as input to
// expressions of rules applied by a policy binding.
// +structType=atomic
message ParamRef {
// name is the name of the resource being referenced.
//
// One of `name` or `selector` must be set, but `name` and `selector` are
// mutually exclusive properties. If one is set, the other must be unset.
//
// A single parameter used for all admission requests can be configured
// by setting the `name` field, leaving `selector` blank, and setting namespace
// if `paramKind` is namespace-scoped.
optional string name = 1;
// namespace is the namespace of the referenced resource. Allows limiting
// the search for params to a specific namespace. Applies to both `name` and
// `selector` fields.
//
// A per-namespace parameter may be used by specifying a namespace-scoped
// `paramKind` in the policy and leaving this field empty.
//
// - If `paramKind` is cluster-scoped, this field MUST be unset. Setting this
// field results in a configuration error.
//
// - If `paramKind` is namespace-scoped, the namespace of the object being
// evaluated for admission will be used when this field is left unset. Take
// care that if this is left empty the binding must not match any cluster-scoped
// resources, which will result in an error.
//
// +optional
optional string namespace = 2;
// selector can be used to match multiple param objects based on their labels.
// Supply selector: {} to match all resources of the ParamKind.
//
// If multiple params are found, they are all evaluated with the policy expressions
// and the results are ANDed together.
//
// One of `name` or `selector` must be set, but `name` and `selector` are
// mutually exclusive properties. If one is set, the other must be unset.
//
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.LabelSelector selector = 3;
// `parameterNotFoundAction` controls the behavior of the binding when the resource
// exists, and name or selector is valid, but there are no parameters
// matched by the binding. If the value is set to `Allow`, then no
// matched parameters will be treated as successful validation by the binding.
// If set to `Deny`, then no matched parameters will be subject to the
// `failurePolicy` of the policy.
//
// Allowed values are `Allow` or `Deny`
//
// Required
optional string parameterNotFoundAction = 4;
}
// Rule is a tuple of APIGroups, APIVersion, and Resources.It is recommended
// to make sure that all the tuple expansions are valid.
message Rule {
@ -334,6 +561,248 @@ message ServiceReference {
optional int32 port = 4;
}
// TypeChecking contains results of type checking the expressions in the
// ValidatingAdmissionPolicy
message TypeChecking {
// The type checking warnings for each expression.
// +optional
// +listType=atomic
repeated ExpressionWarning expressionWarnings = 1;
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +k8s:prerelease-lifecycle-gen:introduced=1.30
// ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it.
message ValidatingAdmissionPolicy {
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1;
// Specification of the desired behavior of the ValidatingAdmissionPolicy.
optional ValidatingAdmissionPolicySpec spec = 2;
// The status of the ValidatingAdmissionPolicy, including warnings that are useful to determine if the policy
// behaves in the expected way.
// Populated by the system.
// Read-only.
// +optional
optional ValidatingAdmissionPolicyStatus status = 3;
}
// ValidatingAdmissionPolicyBinding binds the ValidatingAdmissionPolicy with paramerized resources.
// ValidatingAdmissionPolicyBinding and parameter CRDs together define how cluster administrators configure policies for clusters.
//
// For a given admission request, each binding will cause its policy to be
// evaluated N times, where N is 1 for policies/bindings that don't use
// params, otherwise N is the number of parameters selected by the binding.
//
// The CEL expressions of a policy must have a computed CEL cost below the maximum
// CEL budget. Each evaluation of the policy is given an independent CEL cost budget.
// Adding/removing policies, bindings, or params can not affect whether a
// given (policy, binding, param) combination is within its own CEL budget.
message ValidatingAdmissionPolicyBinding {
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.ObjectMeta metadata = 1;
// Specification of the desired behavior of the ValidatingAdmissionPolicyBinding.
optional ValidatingAdmissionPolicyBindingSpec spec = 2;
}
// ValidatingAdmissionPolicyBindingList is a list of ValidatingAdmissionPolicyBinding.
message ValidatingAdmissionPolicyBindingList {
// Standard list metadata.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1;
// List of PolicyBinding.
repeated ValidatingAdmissionPolicyBinding items = 2;
}
// ValidatingAdmissionPolicyBindingSpec is the specification of the ValidatingAdmissionPolicyBinding.
message ValidatingAdmissionPolicyBindingSpec {
// PolicyName references a ValidatingAdmissionPolicy name which the ValidatingAdmissionPolicyBinding binds to.
// If the referenced resource does not exist, this binding is considered invalid and will be ignored
// Required.
optional string policyName = 1;
// paramRef specifies the parameter resource used to configure the admission control policy.
// It should point to a resource of the type specified in ParamKind of the bound ValidatingAdmissionPolicy.
// If the policy specifies a ParamKind and the resource referred to by ParamRef does not exist, this binding is considered mis-configured and the FailurePolicy of the ValidatingAdmissionPolicy applied.
// If the policy does not specify a ParamKind then this field is ignored, and the rules are evaluated without a param.
// +optional
optional ParamRef paramRef = 2;
// MatchResources declares what resources match this binding and will be validated by it.
// Note that this is intersected with the policy's matchConstraints, so only requests that are matched by the policy can be selected by this.
// If this is unset, all resources matched by the policy are validated by this binding
// When resourceRules is unset, it does not constrain resource matching. If a resource is matched by the other fields of this object, it will be validated.
// Note that this is differs from ValidatingAdmissionPolicy matchConstraints, where resourceRules are required.
// +optional
optional MatchResources matchResources = 3;
// validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced.
// If a validation evaluates to false it is always enforced according to these actions.
//
// Failures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according
// to these actions only if the FailurePolicy is set to Fail, otherwise the failures are
// ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.
//
// validationActions is declared as a set of action values. Order does
// not matter. validationActions may not contain duplicates of the same action.
//
// The supported actions values are:
//
// "Deny" specifies that a validation failure results in a denied request.
//
// "Warn" specifies that a validation failure is reported to the request client
// in HTTP Warning headers, with a warning code of 299. Warnings can be sent
// both for allowed or denied admission responses.
//
// "Audit" specifies that a validation failure is included in the published
// audit event for the request. The audit event will contain a
// `validation.policy.admission.k8s.io/validation_failure` audit annotation
// with a value containing the details of the validation failures, formatted as
// a JSON list of objects, each with the following fields:
// - message: The validation failure message string
// - policy: The resource name of the ValidatingAdmissionPolicy
// - binding: The resource name of the ValidatingAdmissionPolicyBinding
// - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy
// - validationActions: The enforcement actions enacted for the validation failure
// Example audit annotation:
// `"validation.policy.admission.k8s.io/validation_failure": "[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]"`
//
// Clients should expect to handle additional values by ignoring
// any values not recognized.
//
// "Deny" and "Warn" may not be used together since this combination
// needlessly duplicates the validation failure both in the
// API response body and the HTTP warning headers.
//
// Required.
// +listType=set
repeated string validationActions = 4;
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +k8s:prerelease-lifecycle-gen:introduced=1.30
// ValidatingAdmissionPolicyList is a list of ValidatingAdmissionPolicy.
message ValidatingAdmissionPolicyList {
// Standard list metadata.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
// +optional
optional k8s.io.apimachinery.pkg.apis.meta.v1.ListMeta metadata = 1;
// List of ValidatingAdmissionPolicy.
repeated ValidatingAdmissionPolicy items = 2;
}
// ValidatingAdmissionPolicySpec is the specification of the desired behavior of the AdmissionPolicy.
message ValidatingAdmissionPolicySpec {
// ParamKind specifies the kind of resources used to parameterize this policy.
// If absent, there are no parameters for this policy and the param CEL variable will not be provided to validation expressions.
// If ParamKind refers to a non-existent kind, this policy definition is mis-configured and the FailurePolicy is applied.
// If paramKind is specified but paramRef is unset in ValidatingAdmissionPolicyBinding, the params variable will be null.
// +optional
optional ParamKind paramKind = 1;
// MatchConstraints specifies what resources this policy is designed to validate.
// The AdmissionPolicy cares about a request if it matches _all_ Constraints.
// However, in order to prevent clusters from being put into an unstable state that cannot be recovered from via the API
// ValidatingAdmissionPolicy cannot match ValidatingAdmissionPolicy and ValidatingAdmissionPolicyBinding.
// Required.
optional MatchResources matchConstraints = 2;
// Validations contain CEL expressions which is used to apply the validation.
// Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is
// required.
// +listType=atomic
// +optional
repeated Validation validations = 3;
// failurePolicy defines how to handle failures for the admission policy. Failures can
// occur from CEL expression parse errors, type check errors, runtime errors and invalid
// or mis-configured policy definitions or bindings.
//
// A policy is invalid if spec.paramKind refers to a non-existent Kind.
// A binding is invalid if spec.paramRef.name refers to a non-existent resource.
//
// failurePolicy does not define how validations that evaluate to false are handled.
//
// When failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions
// define how failures are enforced.
//
// Allowed values are Ignore or Fail. Defaults to Fail.
// +optional
optional string failurePolicy = 4;
// auditAnnotations contains CEL expressions which are used to produce audit
// annotations for the audit event of the API request.
// validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is
// required.
// +listType=atomic
// +optional
repeated AuditAnnotation auditAnnotations = 5;
// MatchConditions is a list of conditions that must be met for a request to be validated.
// Match conditions filter requests that have already been matched by the rules,
// namespaceSelector, and objectSelector. An empty list of matchConditions matches all requests.
// There are a maximum of 64 match conditions allowed.
//
// If a parameter object is provided, it can be accessed via the `params` handle in the same
// manner as validation expressions.
//
// The exact matching logic is (in order):
// 1. If ANY matchCondition evaluates to FALSE, the policy is skipped.
// 2. If ALL matchConditions evaluate to TRUE, the policy is evaluated.
// 3. If any matchCondition evaluates to an error (but none are FALSE):
// - If failurePolicy=Fail, reject the request
// - If failurePolicy=Ignore, the policy is skipped
//
// +patchMergeKey=name
// +patchStrategy=merge
// +listType=map
// +listMapKey=name
// +optional
repeated MatchCondition matchConditions = 6;
// Variables contain definitions of variables that can be used in composition of other expressions.
// Each variable is defined as a named CEL expression.
// The variables defined here will be available under `variables` in other expressions of the policy
// except MatchConditions because MatchConditions are evaluated before the rest of the policy.
//
// The expression of a variable can refer to other variables defined earlier in the list but not those after.
// Thus, Variables must be sorted by the order of first appearance and acyclic.
// +patchMergeKey=name
// +patchStrategy=merge
// +listType=map
// +listMapKey=name
// +optional
repeated Variable variables = 7;
}
// ValidatingAdmissionPolicyStatus represents the status of an admission validation policy.
message ValidatingAdmissionPolicyStatus {
// The generation observed by the controller.
// +optional
optional int64 observedGeneration = 1;
// The results of type checking for each expression.
// Presence of this field indicates the completion of the type checking.
// +optional
optional TypeChecking typeChecking = 2;
// The conditions represent the latest available observations of a policy's current state.
// +optional
// +listType=map
// +listMapKey=type
repeated k8s.io.apimachinery.pkg.apis.meta.v1.Condition conditions = 3;
}
// ValidatingWebhook describes an admission webhook and the resources and operations it applies to.
message ValidatingWebhook {
// The name of the admission webhook.
@ -510,6 +979,97 @@ message ValidatingWebhookConfigurationList {
repeated ValidatingWebhookConfiguration items = 2;
}
// Validation specifies the CEL expression which is used to apply the validation.
message Validation {
// Expression represents the expression which will be evaluated by CEL.
// ref: https://github.com/google/cel-spec
// CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:
//
// - 'object' - The object from the incoming request. The value is null for DELETE requests.
// - 'oldObject' - The existing object. The value is null for CREATE requests.
// - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)).
// - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind.
// - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources.
// - 'variables' - Map of composited variables, from its name to its lazily evaluated value.
// For example, a variable named 'foo' can be accessed as 'variables.foo'.
// - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.
// See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz
// - 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the
// request resource.
//
// The `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the
// object. No other metadata properties are accessible.
//
// Only property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible.
// Accessible property names are escaped according to the following rules when accessed in the expression:
// - '__' escapes to '__underscores__'
// - '.' escapes to '__dot__'
// - '-' escapes to '__dash__'
// - '/' escapes to '__slash__'
// - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:
// "true", "false", "null", "in", "as", "break", "const", "continue", "else", "for", "function", "if",
// "import", "let", "loop", "package", "namespace", "return".
// Examples:
// - Expression accessing a property named "namespace": {"Expression": "object.__namespace__ > 0"}
// - Expression accessing a property named "x-prop": {"Expression": "object.x__dash__prop > 0"}
// - Expression accessing a property named "redact__d": {"Expression": "object.redact__underscores__d > 0"}
//
// Equality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1].
// Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:
// - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and
// non-intersecting elements in `Y` are appended, retaining their partial order.
// - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values
// are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with
// non-intersecting keys are appended, retaining their partial order.
// Required.
optional string Expression = 1;
// Message represents the message displayed when validation fails. The message is required if the Expression contains
// line breaks. The message must not contain line breaks.
// If unset, the message is "failed rule: {Rule}".
// e.g. "must be a URL with the host matching spec.host"
// If the Expression contains line breaks. Message is required.
// The message must not contain line breaks.
// If unset, the message is "failed Expression: {Expression}".
// +optional
optional string message = 2;
// Reason represents a machine-readable description of why this validation failed.
// If this is the first validation in the list to fail, this reason, as well as the
// corresponding HTTP response code, are used in the
// HTTP response to the client.
// The currently supported reasons are: "Unauthorized", "Forbidden", "Invalid", "RequestEntityTooLarge".
// If not set, StatusReasonInvalid is used in the response to the client.
// +optional
optional string reason = 3;
// messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails.
// Since messageExpression is used as a failure message, it must evaluate to a string.
// If both message and messageExpression are present on a validation, then messageExpression will be used if validation fails.
// If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced
// as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string
// that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and
// the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged.
// messageExpression has access to all the same variables as the `expression` except for 'authorizer' and 'authorizer.requestResource'.
// Example:
// "object.x must be less than max ("+string(params.max)+")"
// +optional
optional string messageExpression = 4;
}
// Variable is the definition of a variable that is used for composition. A variable is defined as a named expression.
// +structType=atomic
message Variable {
// Name is the name of the variable. The name must be a valid CEL identifier and unique among all variables.
// The variable can be accessed in other expressions through `variables`
// For example, if name is "foo", the variable will be available as `variables.foo`
optional string Name = 1;
// Expression is the expression that will be evaluated as the value of the variable.
// The CEL expression has access to the same identifiers as the CEL expressions in Validation.
optional string Expression = 2;
}
// WebhookClientConfig contains the information to make a TLS
// connection with the webhook
message WebhookClientConfig {

View File

@ -50,6 +50,10 @@ func addKnownTypes(scheme *runtime.Scheme) error {
&ValidatingWebhookConfigurationList{},
&MutatingWebhookConfiguration{},
&MutatingWebhookConfigurationList{},
&ValidatingAdmissionPolicy{},
&ValidatingAdmissionPolicyList{},
&ValidatingAdmissionPolicyBinding{},
&ValidatingAdmissionPolicyBindingList{},
)
metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
return nil

View File

@ -91,6 +91,18 @@ const (
Fail FailurePolicyType = "Fail"
)
// ParameterNotFoundActionType specifies a failure policy that defines how a binding
// is evaluated when the param referred by its perNamespaceParamRef is not found.
type ParameterNotFoundActionType string
const (
// Allow means all requests will be admitted if no param resources
// could be found.
AllowAction ParameterNotFoundActionType = "Allow"
// Deny means all requests will be denied if no param resources are found.
DenyAction ParameterNotFoundActionType = "Deny"
)
// MatchPolicyType specifies the type of match policy.
// +enum
type MatchPolicyType string
@ -120,6 +132,584 @@ const (
SideEffectClassNoneOnDryRun SideEffectClass = "NoneOnDryRun"
)
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +k8s:prerelease-lifecycle-gen:introduced=1.30
// ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it.
type ValidatingAdmissionPolicy struct {
metav1.TypeMeta `json:",inline"`
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.
// +optional
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Specification of the desired behavior of the ValidatingAdmissionPolicy.
Spec ValidatingAdmissionPolicySpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
// The status of the ValidatingAdmissionPolicy, including warnings that are useful to determine if the policy
// behaves in the expected way.
// Populated by the system.
// Read-only.
// +optional
Status ValidatingAdmissionPolicyStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}
// ValidatingAdmissionPolicyStatus represents the status of an admission validation policy.
type ValidatingAdmissionPolicyStatus struct {
// The generation observed by the controller.
// +optional
ObservedGeneration int64 `json:"observedGeneration,omitempty" protobuf:"varint,1,opt,name=observedGeneration"`
// The results of type checking for each expression.
// Presence of this field indicates the completion of the type checking.
// +optional
TypeChecking *TypeChecking `json:"typeChecking,omitempty" protobuf:"bytes,2,opt,name=typeChecking"`
// The conditions represent the latest available observations of a policy's current state.
// +optional
// +listType=map
// +listMapKey=type
Conditions []metav1.Condition `json:"conditions,omitempty" protobuf:"bytes,3,rep,name=conditions"`
}
// ValidatingAdmissionPolicyConditionType is the condition type of admission validation policy.
type ValidatingAdmissionPolicyConditionType string
// TypeChecking contains results of type checking the expressions in the
// ValidatingAdmissionPolicy
type TypeChecking struct {
// The type checking warnings for each expression.
// +optional
// +listType=atomic
ExpressionWarnings []ExpressionWarning `json:"expressionWarnings,omitempty" protobuf:"bytes,1,rep,name=expressionWarnings"`
}
// ExpressionWarning is a warning information that targets a specific expression.
type ExpressionWarning struct {
// The path to the field that refers the expression.
// For example, the reference to the expression of the first item of
// validations is "spec.validations[0].expression"
FieldRef string `json:"fieldRef" protobuf:"bytes,2,opt,name=fieldRef"`
// The content of type checking information in a human-readable form.
// Each line of the warning contains the type that the expression is checked
// against, followed by the type check error from the compiler.
Warning string `json:"warning" protobuf:"bytes,3,opt,name=warning"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +k8s:prerelease-lifecycle-gen:introduced=1.30
// ValidatingAdmissionPolicyList is a list of ValidatingAdmissionPolicy.
type ValidatingAdmissionPolicyList struct {
metav1.TypeMeta `json:",inline"`
// Standard list metadata.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
// +optional
metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// List of ValidatingAdmissionPolicy.
Items []ValidatingAdmissionPolicy `json:"items,omitempty" protobuf:"bytes,2,rep,name=items"`
}
// ValidatingAdmissionPolicySpec is the specification of the desired behavior of the AdmissionPolicy.
type ValidatingAdmissionPolicySpec struct {
// ParamKind specifies the kind of resources used to parameterize this policy.
// If absent, there are no parameters for this policy and the param CEL variable will not be provided to validation expressions.
// If ParamKind refers to a non-existent kind, this policy definition is mis-configured and the FailurePolicy is applied.
// If paramKind is specified but paramRef is unset in ValidatingAdmissionPolicyBinding, the params variable will be null.
// +optional
ParamKind *ParamKind `json:"paramKind,omitempty" protobuf:"bytes,1,rep,name=paramKind"`
// MatchConstraints specifies what resources this policy is designed to validate.
// The AdmissionPolicy cares about a request if it matches _all_ Constraints.
// However, in order to prevent clusters from being put into an unstable state that cannot be recovered from via the API
// ValidatingAdmissionPolicy cannot match ValidatingAdmissionPolicy and ValidatingAdmissionPolicyBinding.
// Required.
MatchConstraints *MatchResources `json:"matchConstraints,omitempty" protobuf:"bytes,2,rep,name=matchConstraints"`
// Validations contain CEL expressions which is used to apply the validation.
// Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is
// required.
// +listType=atomic
// +optional
Validations []Validation `json:"validations,omitempty" protobuf:"bytes,3,rep,name=validations"`
// failurePolicy defines how to handle failures for the admission policy. Failures can
// occur from CEL expression parse errors, type check errors, runtime errors and invalid
// or mis-configured policy definitions or bindings.
//
// A policy is invalid if spec.paramKind refers to a non-existent Kind.
// A binding is invalid if spec.paramRef.name refers to a non-existent resource.
//
// failurePolicy does not define how validations that evaluate to false are handled.
//
// When failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions
// define how failures are enforced.
//
// Allowed values are Ignore or Fail. Defaults to Fail.
// +optional
FailurePolicy *FailurePolicyType `json:"failurePolicy,omitempty" protobuf:"bytes,4,opt,name=failurePolicy,casttype=FailurePolicyType"`
// auditAnnotations contains CEL expressions which are used to produce audit
// annotations for the audit event of the API request.
// validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is
// required.
// +listType=atomic
// +optional
AuditAnnotations []AuditAnnotation `json:"auditAnnotations,omitempty" protobuf:"bytes,5,rep,name=auditAnnotations"`
// MatchConditions is a list of conditions that must be met for a request to be validated.
// Match conditions filter requests that have already been matched by the rules,
// namespaceSelector, and objectSelector. An empty list of matchConditions matches all requests.
// There are a maximum of 64 match conditions allowed.
//
// If a parameter object is provided, it can be accessed via the `params` handle in the same
// manner as validation expressions.
//
// The exact matching logic is (in order):
// 1. If ANY matchCondition evaluates to FALSE, the policy is skipped.
// 2. If ALL matchConditions evaluate to TRUE, the policy is evaluated.
// 3. If any matchCondition evaluates to an error (but none are FALSE):
// - If failurePolicy=Fail, reject the request
// - If failurePolicy=Ignore, the policy is skipped
//
// +patchMergeKey=name
// +patchStrategy=merge
// +listType=map
// +listMapKey=name
// +optional
MatchConditions []MatchCondition `json:"matchConditions,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,6,rep,name=matchConditions"`
// Variables contain definitions of variables that can be used in composition of other expressions.
// Each variable is defined as a named CEL expression.
// The variables defined here will be available under `variables` in other expressions of the policy
// except MatchConditions because MatchConditions are evaluated before the rest of the policy.
//
// The expression of a variable can refer to other variables defined earlier in the list but not those after.
// Thus, Variables must be sorted by the order of first appearance and acyclic.
// +patchMergeKey=name
// +patchStrategy=merge
// +listType=map
// +listMapKey=name
// +optional
Variables []Variable `json:"variables,omitempty" patchStrategy:"merge" patchMergeKey:"name" protobuf:"bytes,7,rep,name=variables"`
}
// ParamKind is a tuple of Group Kind and Version.
// +structType=atomic
type ParamKind struct {
// APIVersion is the API group version the resources belong to.
// In format of "group/version".
// Required.
APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,1,rep,name=apiVersion"`
// Kind is the API kind the resources belong to.
// Required.
Kind string `json:"kind,omitempty" protobuf:"bytes,2,rep,name=kind"`
}
// Validation specifies the CEL expression which is used to apply the validation.
type Validation struct {
// Expression represents the expression which will be evaluated by CEL.
// ref: https://github.com/google/cel-spec
// CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:
//
// - 'object' - The object from the incoming request. The value is null for DELETE requests.
// - 'oldObject' - The existing object. The value is null for CREATE requests.
// - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)).
// - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind.
// - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources.
// - 'variables' - Map of composited variables, from its name to its lazily evaluated value.
// For example, a variable named 'foo' can be accessed as 'variables.foo'.
// - 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.
// See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz
// - 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the
// request resource.
//
// The `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the
// object. No other metadata properties are accessible.
//
// Only property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible.
// Accessible property names are escaped according to the following rules when accessed in the expression:
// - '__' escapes to '__underscores__'
// - '.' escapes to '__dot__'
// - '-' escapes to '__dash__'
// - '/' escapes to '__slash__'
// - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:
// "true", "false", "null", "in", "as", "break", "const", "continue", "else", "for", "function", "if",
// "import", "let", "loop", "package", "namespace", "return".
// Examples:
// - Expression accessing a property named "namespace": {"Expression": "object.__namespace__ > 0"}
// - Expression accessing a property named "x-prop": {"Expression": "object.x__dash__prop > 0"}
// - Expression accessing a property named "redact__d": {"Expression": "object.redact__underscores__d > 0"}
//
// Equality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1].
// Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:
// - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and
// non-intersecting elements in `Y` are appended, retaining their partial order.
// - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values
// are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with
// non-intersecting keys are appended, retaining their partial order.
// Required.
Expression string `json:"expression" protobuf:"bytes,1,opt,name=Expression"`
// Message represents the message displayed when validation fails. The message is required if the Expression contains
// line breaks. The message must not contain line breaks.
// If unset, the message is "failed rule: {Rule}".
// e.g. "must be a URL with the host matching spec.host"
// If the Expression contains line breaks. Message is required.
// The message must not contain line breaks.
// If unset, the message is "failed Expression: {Expression}".
// +optional
Message string `json:"message,omitempty" protobuf:"bytes,2,opt,name=message"`
// Reason represents a machine-readable description of why this validation failed.
// If this is the first validation in the list to fail, this reason, as well as the
// corresponding HTTP response code, are used in the
// HTTP response to the client.
// The currently supported reasons are: "Unauthorized", "Forbidden", "Invalid", "RequestEntityTooLarge".
// If not set, StatusReasonInvalid is used in the response to the client.
// +optional
Reason *metav1.StatusReason `json:"reason,omitempty" protobuf:"bytes,3,opt,name=reason"`
// messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails.
// Since messageExpression is used as a failure message, it must evaluate to a string.
// If both message and messageExpression are present on a validation, then messageExpression will be used if validation fails.
// If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced
// as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string
// that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and
// the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged.
// messageExpression has access to all the same variables as the `expression` except for 'authorizer' and 'authorizer.requestResource'.
// Example:
// "object.x must be less than max ("+string(params.max)+")"
// +optional
MessageExpression string `json:"messageExpression,omitempty" protobuf:"bytes,4,opt,name=messageExpression"`
}
// Variable is the definition of a variable that is used for composition. A variable is defined as a named expression.
// +structType=atomic
type Variable struct {
// Name is the name of the variable. The name must be a valid CEL identifier and unique among all variables.
// The variable can be accessed in other expressions through `variables`
// For example, if name is "foo", the variable will be available as `variables.foo`
Name string `json:"name" protobuf:"bytes,1,opt,name=Name"`
// Expression is the expression that will be evaluated as the value of the variable.
// The CEL expression has access to the same identifiers as the CEL expressions in Validation.
Expression string `json:"expression" protobuf:"bytes,2,opt,name=Expression"`
}
// AuditAnnotation describes how to produce an audit annotation for an API request.
type AuditAnnotation struct {
// key specifies the audit annotation key. The audit annotation keys of
// a ValidatingAdmissionPolicy must be unique. The key must be a qualified
// name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.
//
// The key is combined with the resource name of the
// ValidatingAdmissionPolicy to construct an audit annotation key:
// "{ValidatingAdmissionPolicy name}/{key}".
//
// If an admission webhook uses the same resource name as this ValidatingAdmissionPolicy
// and the same audit annotation key, the annotation key will be identical.
// In this case, the first annotation written with the key will be included
// in the audit event and all subsequent annotations with the same key
// will be discarded.
//
// Required.
Key string `json:"key" protobuf:"bytes,1,opt,name=key"`
// valueExpression represents the expression which is evaluated by CEL to
// produce an audit annotation value. The expression must evaluate to either
// a string or null value. If the expression evaluates to a string, the
// audit annotation is included with the string value. If the expression
// evaluates to null or empty string the audit annotation will be omitted.
// The valueExpression may be no longer than 5kb in length.
// If the result of the valueExpression is more than 10kb in length, it
// will be truncated to 10kb.
//
// If multiple ValidatingAdmissionPolicyBinding resources match an
// API request, then the valueExpression will be evaluated for
// each binding. All unique values produced by the valueExpressions
// will be joined together in a comma-separated list.
//
// Required.
ValueExpression string `json:"valueExpression" protobuf:"bytes,2,opt,name=valueExpression"`
}
// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +k8s:prerelease-lifecycle-gen:introduced=1.30
// ValidatingAdmissionPolicyBinding binds the ValidatingAdmissionPolicy with paramerized resources.
// ValidatingAdmissionPolicyBinding and parameter CRDs together define how cluster administrators configure policies for clusters.
//
// For a given admission request, each binding will cause its policy to be
// evaluated N times, where N is 1 for policies/bindings that don't use
// params, otherwise N is the number of parameters selected by the binding.
//
// The CEL expressions of a policy must have a computed CEL cost below the maximum
// CEL budget. Each evaluation of the policy is given an independent CEL cost budget.
// Adding/removing policies, bindings, or params can not affect whether a
// given (policy, binding, param) combination is within its own CEL budget.
type ValidatingAdmissionPolicyBinding struct {
metav1.TypeMeta `json:",inline"`
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.
// +optional
metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// Specification of the desired behavior of the ValidatingAdmissionPolicyBinding.
Spec ValidatingAdmissionPolicyBindingSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +k8s:prerelease-lifecycle-gen:introduced=1.30
// ValidatingAdmissionPolicyBindingList is a list of ValidatingAdmissionPolicyBinding.
type ValidatingAdmissionPolicyBindingList struct {
metav1.TypeMeta `json:",inline"`
// Standard list metadata.
// More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
// +optional
metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
// List of PolicyBinding.
Items []ValidatingAdmissionPolicyBinding `json:"items,omitempty" protobuf:"bytes,2,rep,name=items"`
}
// ValidatingAdmissionPolicyBindingSpec is the specification of the ValidatingAdmissionPolicyBinding.
type ValidatingAdmissionPolicyBindingSpec struct {
// PolicyName references a ValidatingAdmissionPolicy name which the ValidatingAdmissionPolicyBinding binds to.
// If the referenced resource does not exist, this binding is considered invalid and will be ignored
// Required.
PolicyName string `json:"policyName,omitempty" protobuf:"bytes,1,rep,name=policyName"`
// paramRef specifies the parameter resource used to configure the admission control policy.
// It should point to a resource of the type specified in ParamKind of the bound ValidatingAdmissionPolicy.
// If the policy specifies a ParamKind and the resource referred to by ParamRef does not exist, this binding is considered mis-configured and the FailurePolicy of the ValidatingAdmissionPolicy applied.
// If the policy does not specify a ParamKind then this field is ignored, and the rules are evaluated without a param.
// +optional
ParamRef *ParamRef `json:"paramRef,omitempty" protobuf:"bytes,2,rep,name=paramRef"`
// MatchResources declares what resources match this binding and will be validated by it.
// Note that this is intersected with the policy's matchConstraints, so only requests that are matched by the policy can be selected by this.
// If this is unset, all resources matched by the policy are validated by this binding
// When resourceRules is unset, it does not constrain resource matching. If a resource is matched by the other fields of this object, it will be validated.
// Note that this is differs from ValidatingAdmissionPolicy matchConstraints, where resourceRules are required.
// +optional
MatchResources *MatchResources `json:"matchResources,omitempty" protobuf:"bytes,3,rep,name=matchResources"`
// validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced.
// If a validation evaluates to false it is always enforced according to these actions.
//
// Failures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according
// to these actions only if the FailurePolicy is set to Fail, otherwise the failures are
// ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.
//
// validationActions is declared as a set of action values. Order does
// not matter. validationActions may not contain duplicates of the same action.
//
// The supported actions values are:
//
// "Deny" specifies that a validation failure results in a denied request.
//
// "Warn" specifies that a validation failure is reported to the request client
// in HTTP Warning headers, with a warning code of 299. Warnings can be sent
// both for allowed or denied admission responses.
//
// "Audit" specifies that a validation failure is included in the published
// audit event for the request. The audit event will contain a
// `validation.policy.admission.k8s.io/validation_failure` audit annotation
// with a value containing the details of the validation failures, formatted as
// a JSON list of objects, each with the following fields:
// - message: The validation failure message string
// - policy: The resource name of the ValidatingAdmissionPolicy
// - binding: The resource name of the ValidatingAdmissionPolicyBinding
// - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy
// - validationActions: The enforcement actions enacted for the validation failure
// Example audit annotation:
// `"validation.policy.admission.k8s.io/validation_failure": "[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]"`
//
// Clients should expect to handle additional values by ignoring
// any values not recognized.
//
// "Deny" and "Warn" may not be used together since this combination
// needlessly duplicates the validation failure both in the
// API response body and the HTTP warning headers.
//
// Required.
// +listType=set
ValidationActions []ValidationAction `json:"validationActions,omitempty" protobuf:"bytes,4,rep,name=validationActions"`
}
// ParamRef describes how to locate the params to be used as input to
// expressions of rules applied by a policy binding.
// +structType=atomic
type ParamRef struct {
// name is the name of the resource being referenced.
//
// One of `name` or `selector` must be set, but `name` and `selector` are
// mutually exclusive properties. If one is set, the other must be unset.
//
// A single parameter used for all admission requests can be configured
// by setting the `name` field, leaving `selector` blank, and setting namespace
// if `paramKind` is namespace-scoped.
//
Name string `json:"name,omitempty" protobuf:"bytes,1,rep,name=name"`
// namespace is the namespace of the referenced resource. Allows limiting
// the search for params to a specific namespace. Applies to both `name` and
// `selector` fields.
//
// A per-namespace parameter may be used by specifying a namespace-scoped
// `paramKind` in the policy and leaving this field empty.
//
// - If `paramKind` is cluster-scoped, this field MUST be unset. Setting this
// field results in a configuration error.
//
// - If `paramKind` is namespace-scoped, the namespace of the object being
// evaluated for admission will be used when this field is left unset. Take
// care that if this is left empty the binding must not match any cluster-scoped
// resources, which will result in an error.
//
// +optional
Namespace string `json:"namespace,omitempty" protobuf:"bytes,2,rep,name=namespace"`
// selector can be used to match multiple param objects based on their labels.
// Supply selector: {} to match all resources of the ParamKind.
//
// If multiple params are found, they are all evaluated with the policy expressions
// and the results are ANDed together.
//
// One of `name` or `selector` must be set, but `name` and `selector` are
// mutually exclusive properties. If one is set, the other must be unset.
//
// +optional
Selector *metav1.LabelSelector `json:"selector,omitempty" protobuf:"bytes,3,rep,name=selector"`
// `parameterNotFoundAction` controls the behavior of the binding when the resource
// exists, and name or selector is valid, but there are no parameters
// matched by the binding. If the value is set to `Allow`, then no
// matched parameters will be treated as successful validation by the binding.
// If set to `Deny`, then no matched parameters will be subject to the
// `failurePolicy` of the policy.
//
// Allowed values are `Allow` or `Deny`
//
// Required
ParameterNotFoundAction *ParameterNotFoundActionType `json:"parameterNotFoundAction,omitempty" protobuf:"bytes,4,rep,name=parameterNotFoundAction"`
}
// MatchResources decides whether to run the admission control policy on an object based
// on whether it meets the match criteria.
// The exclude rules take precedence over include rules (if a resource matches both, it is excluded)
// +structType=atomic
type MatchResources struct {
// NamespaceSelector decides whether to run the admission control policy on an object based
// on whether the namespace for that object matches the selector. If the
// object itself is a namespace, the matching is performed on
// object.metadata.labels. If the object is another cluster scoped resource,
// it never skips the policy.
//
// For example, to run the webhook on any objects whose namespace is not
// associated with "runlevel" of "0" or "1"; you will set the selector as
// follows:
// "namespaceSelector": {
// "matchExpressions": [
// {
// "key": "runlevel",
// "operator": "NotIn",
// "values": [
// "0",
// "1"
// ]
// }
// ]
// }
//
// If instead you want to only run the policy on any objects whose
// namespace is associated with the "environment" of "prod" or "staging";
// you will set the selector as follows:
// "namespaceSelector": {
// "matchExpressions": [
// {
// "key": "environment",
// "operator": "In",
// "values": [
// "prod",
// "staging"
// ]
// }
// ]
// }
//
// See
// https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/
// for more examples of label selectors.
//
// Default to the empty LabelSelector, which matches everything.
// +optional
NamespaceSelector *metav1.LabelSelector `json:"namespaceSelector,omitempty" protobuf:"bytes,1,opt,name=namespaceSelector"`
// ObjectSelector decides whether to run the validation based on if the
// object has matching labels. objectSelector is evaluated against both
// the oldObject and newObject that would be sent to the cel validation, and
// is considered to match if either object matches the selector. A null
// object (oldObject in the case of create, or newObject in the case of
// delete) or an object that cannot have labels (like a
// DeploymentRollback or a PodProxyOptions object) is not considered to
// match.
// Use the object selector only if the webhook is opt-in, because end
// users may skip the admission webhook by setting the labels.
// Default to the empty LabelSelector, which matches everything.
// +optional
ObjectSelector *metav1.LabelSelector `json:"objectSelector,omitempty" protobuf:"bytes,2,opt,name=objectSelector"`
// ResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy matches.
// The policy cares about an operation if it matches _any_ Rule.
// +listType=atomic
// +optional
ResourceRules []NamedRuleWithOperations `json:"resourceRules,omitempty" protobuf:"bytes,3,rep,name=resourceRules"`
// ExcludeResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy should not care about.
// The exclude rules take precedence over include rules (if a resource matches both, it is excluded)
// +listType=atomic
// +optional
ExcludeResourceRules []NamedRuleWithOperations `json:"excludeResourceRules,omitempty" protobuf:"bytes,4,rep,name=excludeResourceRules"`
// matchPolicy defines how the "MatchResources" list is used to match incoming requests.
// Allowed values are "Exact" or "Equivalent".
//
// - Exact: match a request only if it exactly matches a specified rule.
// For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1,
// but "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`,
// a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the ValidatingAdmissionPolicy.
//
// - Equivalent: match a request if modifies a resource listed in rules, even via another API group or version.
// For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1,
// and "rules" only included `apiGroups:["apps"], apiVersions:["v1"], resources: ["deployments"]`,
// a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the ValidatingAdmissionPolicy.
//
// Defaults to "Equivalent"
// +optional
MatchPolicy *MatchPolicyType `json:"matchPolicy,omitempty" protobuf:"bytes,7,opt,name=matchPolicy,casttype=MatchPolicyType"`
}
// ValidationAction specifies a policy enforcement action.
// +enum
type ValidationAction string
const (
// Deny specifies that a validation failure results in a denied request.
Deny ValidationAction = "Deny"
// Warn specifies that a validation failure is reported to the request client
// in HTTP Warning headers, with a warning code of 299. Warnings can be sent
// both for allowed or denied admission responses.
Warn ValidationAction = "Warn"
// Audit specifies that a validation failure is included in the published
// audit event for the request. The audit event will contain a
// `validation.policy.admission.k8s.io/validation_failure` audit annotation
// with a value containing the details of the validation failure.
Audit ValidationAction = "Audit"
)
// NamedRuleWithOperations is a tuple of Operations and Resources with ResourceNames.
// +structType=atomic
type NamedRuleWithOperations struct {
// ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.
// +listType=atomic
// +optional
ResourceNames []string `json:"resourceNames,omitempty" protobuf:"bytes,1,rep,name=resourceNames"`
// RuleWithOperations is a tuple of Operations and Resources.
RuleWithOperations `json:",inline" protobuf:"bytes,2,opt,name=ruleWithOperations"`
}
// +genclient
// +genclient:nonNamespaced
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

View File

@ -27,6 +27,26 @@ package v1
// Those methods can be generated by using hack/update-codegen.sh
// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT.
var map_AuditAnnotation = map[string]string{
"": "AuditAnnotation describes how to produce an audit annotation for an API request.",
"key": "key specifies the audit annotation key. The audit annotation keys of a ValidatingAdmissionPolicy must be unique. The key must be a qualified name ([A-Za-z0-9][-A-Za-z0-9_.]*) no more than 63 bytes in length.\n\nThe key is combined with the resource name of the ValidatingAdmissionPolicy to construct an audit annotation key: \"{ValidatingAdmissionPolicy name}/{key}\".\n\nIf an admission webhook uses the same resource name as this ValidatingAdmissionPolicy and the same audit annotation key, the annotation key will be identical. In this case, the first annotation written with the key will be included in the audit event and all subsequent annotations with the same key will be discarded.\n\nRequired.",
"valueExpression": "valueExpression represents the expression which is evaluated by CEL to produce an audit annotation value. The expression must evaluate to either a string or null value. If the expression evaluates to a string, the audit annotation is included with the string value. If the expression evaluates to null or empty string the audit annotation will be omitted. The valueExpression may be no longer than 5kb in length. If the result of the valueExpression is more than 10kb in length, it will be truncated to 10kb.\n\nIf multiple ValidatingAdmissionPolicyBinding resources match an API request, then the valueExpression will be evaluated for each binding. All unique values produced by the valueExpressions will be joined together in a comma-separated list.\n\nRequired.",
}
func (AuditAnnotation) SwaggerDoc() map[string]string {
return map_AuditAnnotation
}
var map_ExpressionWarning = map[string]string{
"": "ExpressionWarning is a warning information that targets a specific expression.",
"fieldRef": "The path to the field that refers the expression. For example, the reference to the expression of the first item of validations is \"spec.validations[0].expression\"",
"warning": "The content of type checking information in a human-readable form. Each line of the warning contains the type that the expression is checked against, followed by the type check error from the compiler.",
}
func (ExpressionWarning) SwaggerDoc() map[string]string {
return map_ExpressionWarning
}
var map_MatchCondition = map[string]string{
"": "MatchCondition represents a condition which must by fulfilled for a request to be sent to a webhook.",
"name": "Name is an identifier for this match condition, used for strategic merging of MatchConditions, as well as providing an identifier for logging purposes. A good name should be descriptive of the associated expression. Name must be a qualified name consisting of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName', or 'my.name', or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]') with an optional DNS subdomain prefix and '/' (e.g. 'example.com/MyName')\n\nRequired.",
@ -37,6 +57,19 @@ func (MatchCondition) SwaggerDoc() map[string]string {
return map_MatchCondition
}
var map_MatchResources = map[string]string{
"": "MatchResources decides whether to run the admission control policy on an object based on whether it meets the match criteria. The exclude rules take precedence over include rules (if a resource matches both, it is excluded)",
"namespaceSelector": "NamespaceSelector decides whether to run the admission control policy on an object based on whether the namespace for that object matches the selector. If the object itself is a namespace, the matching is performed on object.metadata.labels. If the object is another cluster scoped resource, it never skips the policy.\n\nFor example, to run the webhook on any objects whose namespace is not associated with \"runlevel\" of \"0\" or \"1\"; you will set the selector as follows: \"namespaceSelector\": {\n \"matchExpressions\": [\n {\n \"key\": \"runlevel\",\n \"operator\": \"NotIn\",\n \"values\": [\n \"0\",\n \"1\"\n ]\n }\n ]\n}\n\nIf instead you want to only run the policy on any objects whose namespace is associated with the \"environment\" of \"prod\" or \"staging\"; you will set the selector as follows: \"namespaceSelector\": {\n \"matchExpressions\": [\n {\n \"key\": \"environment\",\n \"operator\": \"In\",\n \"values\": [\n \"prod\",\n \"staging\"\n ]\n }\n ]\n}\n\nSee https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/ for more examples of label selectors.\n\nDefault to the empty LabelSelector, which matches everything.",
"objectSelector": "ObjectSelector decides whether to run the validation based on if the object has matching labels. objectSelector is evaluated against both the oldObject and newObject that would be sent to the cel validation, and is considered to match if either object matches the selector. A null object (oldObject in the case of create, or newObject in the case of delete) or an object that cannot have labels (like a DeploymentRollback or a PodProxyOptions object) is not considered to match. Use the object selector only if the webhook is opt-in, because end users may skip the admission webhook by setting the labels. Default to the empty LabelSelector, which matches everything.",
"resourceRules": "ResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy matches. The policy cares about an operation if it matches _any_ Rule.",
"excludeResourceRules": "ExcludeResourceRules describes what operations on what resources/subresources the ValidatingAdmissionPolicy should not care about. The exclude rules take precedence over include rules (if a resource matches both, it is excluded)",
"matchPolicy": "matchPolicy defines how the \"MatchResources\" list is used to match incoming requests. Allowed values are \"Exact\" or \"Equivalent\".\n\n- Exact: match a request only if it exactly matches a specified rule. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, but \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would not be sent to the ValidatingAdmissionPolicy.\n\n- Equivalent: match a request if modifies a resource listed in rules, even via another API group or version. For example, if deployments can be modified via apps/v1, apps/v1beta1, and extensions/v1beta1, and \"rules\" only included `apiGroups:[\"apps\"], apiVersions:[\"v1\"], resources: [\"deployments\"]`, a request to apps/v1beta1 or extensions/v1beta1 would be converted to apps/v1 and sent to the ValidatingAdmissionPolicy.\n\nDefaults to \"Equivalent\"",
}
func (MatchResources) SwaggerDoc() map[string]string {
return map_MatchResources
}
var map_MutatingWebhook = map[string]string{
"": "MutatingWebhook describes an admission webhook and the resources and operations it applies to.",
"name": "The name of the admission webhook. Name should be fully qualified, e.g., imagepolicy.kubernetes.io, where \"imagepolicy\" is the name of the webhook, and kubernetes.io is the name of the organization. Required.",
@ -77,6 +110,37 @@ func (MutatingWebhookConfigurationList) SwaggerDoc() map[string]string {
return map_MutatingWebhookConfigurationList
}
var map_NamedRuleWithOperations = map[string]string{
"": "NamedRuleWithOperations is a tuple of Operations and Resources with ResourceNames.",
"resourceNames": "ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed.",
}
func (NamedRuleWithOperations) SwaggerDoc() map[string]string {
return map_NamedRuleWithOperations
}
var map_ParamKind = map[string]string{
"": "ParamKind is a tuple of Group Kind and Version.",
"apiVersion": "APIVersion is the API group version the resources belong to. In format of \"group/version\". Required.",
"kind": "Kind is the API kind the resources belong to. Required.",
}
func (ParamKind) SwaggerDoc() map[string]string {
return map_ParamKind
}
var map_ParamRef = map[string]string{
"": "ParamRef describes how to locate the params to be used as input to expressions of rules applied by a policy binding.",
"name": "name is the name of the resource being referenced.\n\nOne of `name` or `selector` must be set, but `name` and `selector` are mutually exclusive properties. If one is set, the other must be unset.\n\nA single parameter used for all admission requests can be configured by setting the `name` field, leaving `selector` blank, and setting namespace if `paramKind` is namespace-scoped.",
"namespace": "namespace is the namespace of the referenced resource. Allows limiting the search for params to a specific namespace. Applies to both `name` and `selector` fields.\n\nA per-namespace parameter may be used by specifying a namespace-scoped `paramKind` in the policy and leaving this field empty.\n\n- If `paramKind` is cluster-scoped, this field MUST be unset. Setting this field results in a configuration error.\n\n- If `paramKind` is namespace-scoped, the namespace of the object being evaluated for admission will be used when this field is left unset. Take care that if this is left empty the binding must not match any cluster-scoped resources, which will result in an error.",
"selector": "selector can be used to match multiple param objects based on their labels. Supply selector: {} to match all resources of the ParamKind.\n\nIf multiple params are found, they are all evaluated with the policy expressions and the results are ANDed together.\n\nOne of `name` or `selector` must be set, but `name` and `selector` are mutually exclusive properties. If one is set, the other must be unset.",
"parameterNotFoundAction": "`parameterNotFoundAction` controls the behavior of the binding when the resource exists, and name or selector is valid, but there are no parameters matched by the binding. If the value is set to `Allow`, then no matched parameters will be treated as successful validation by the binding. If set to `Deny`, then no matched parameters will be subject to the `failurePolicy` of the policy.\n\nAllowed values are `Allow` or `Deny`\n\nRequired",
}
func (ParamRef) SwaggerDoc() map[string]string {
return map_ParamRef
}
var map_Rule = map[string]string{
"": "Rule is a tuple of APIGroups, APIVersion, and Resources.It is recommended to make sure that all the tuple expansions are valid.",
"apiGroups": "APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required.",
@ -110,6 +174,94 @@ func (ServiceReference) SwaggerDoc() map[string]string {
return map_ServiceReference
}
var map_TypeChecking = map[string]string{
"": "TypeChecking contains results of type checking the expressions in the ValidatingAdmissionPolicy",
"expressionWarnings": "The type checking warnings for each expression.",
}
func (TypeChecking) SwaggerDoc() map[string]string {
return map_TypeChecking
}
var map_ValidatingAdmissionPolicy = map[string]string{
"": "ValidatingAdmissionPolicy describes the definition of an admission validation policy that accepts or rejects an object without changing it.",
"metadata": "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.",
"spec": "Specification of the desired behavior of the ValidatingAdmissionPolicy.",
"status": "The status of the ValidatingAdmissionPolicy, including warnings that are useful to determine if the policy behaves in the expected way. Populated by the system. Read-only.",
}
func (ValidatingAdmissionPolicy) SwaggerDoc() map[string]string {
return map_ValidatingAdmissionPolicy
}
var map_ValidatingAdmissionPolicyBinding = map[string]string{
"": "ValidatingAdmissionPolicyBinding binds the ValidatingAdmissionPolicy with paramerized resources. ValidatingAdmissionPolicyBinding and parameter CRDs together define how cluster administrators configure policies for clusters.\n\nFor a given admission request, each binding will cause its policy to be evaluated N times, where N is 1 for policies/bindings that don't use params, otherwise N is the number of parameters selected by the binding.\n\nThe CEL expressions of a policy must have a computed CEL cost below the maximum CEL budget. Each evaluation of the policy is given an independent CEL cost budget. Adding/removing policies, bindings, or params can not affect whether a given (policy, binding, param) combination is within its own CEL budget.",
"metadata": "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.",
"spec": "Specification of the desired behavior of the ValidatingAdmissionPolicyBinding.",
}
func (ValidatingAdmissionPolicyBinding) SwaggerDoc() map[string]string {
return map_ValidatingAdmissionPolicyBinding
}
var map_ValidatingAdmissionPolicyBindingList = map[string]string{
"": "ValidatingAdmissionPolicyBindingList is a list of ValidatingAdmissionPolicyBinding.",
"metadata": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
"items": "List of PolicyBinding.",
}
func (ValidatingAdmissionPolicyBindingList) SwaggerDoc() map[string]string {
return map_ValidatingAdmissionPolicyBindingList
}
var map_ValidatingAdmissionPolicyBindingSpec = map[string]string{
"": "ValidatingAdmissionPolicyBindingSpec is the specification of the ValidatingAdmissionPolicyBinding.",
"policyName": "PolicyName references a ValidatingAdmissionPolicy name which the ValidatingAdmissionPolicyBinding binds to. If the referenced resource does not exist, this binding is considered invalid and will be ignored Required.",
"paramRef": "paramRef specifies the parameter resource used to configure the admission control policy. It should point to a resource of the type specified in ParamKind of the bound ValidatingAdmissionPolicy. If the policy specifies a ParamKind and the resource referred to by ParamRef does not exist, this binding is considered mis-configured and the FailurePolicy of the ValidatingAdmissionPolicy applied. If the policy does not specify a ParamKind then this field is ignored, and the rules are evaluated without a param.",
"matchResources": "MatchResources declares what resources match this binding and will be validated by it. Note that this is intersected with the policy's matchConstraints, so only requests that are matched by the policy can be selected by this. If this is unset, all resources matched by the policy are validated by this binding When resourceRules is unset, it does not constrain resource matching. If a resource is matched by the other fields of this object, it will be validated. Note that this is differs from ValidatingAdmissionPolicy matchConstraints, where resourceRules are required.",
"validationActions": "validationActions declares how Validations of the referenced ValidatingAdmissionPolicy are enforced. If a validation evaluates to false it is always enforced according to these actions.\n\nFailures defined by the ValidatingAdmissionPolicy's FailurePolicy are enforced according to these actions only if the FailurePolicy is set to Fail, otherwise the failures are ignored. This includes compilation errors, runtime errors and misconfigurations of the policy.\n\nvalidationActions is declared as a set of action values. Order does not matter. validationActions may not contain duplicates of the same action.\n\nThe supported actions values are:\n\n\"Deny\" specifies that a validation failure results in a denied request.\n\n\"Warn\" specifies that a validation failure is reported to the request client in HTTP Warning headers, with a warning code of 299. Warnings can be sent both for allowed or denied admission responses.\n\n\"Audit\" specifies that a validation failure is included in the published audit event for the request. The audit event will contain a `validation.policy.admission.k8s.io/validation_failure` audit annotation with a value containing the details of the validation failures, formatted as a JSON list of objects, each with the following fields: - message: The validation failure message string - policy: The resource name of the ValidatingAdmissionPolicy - binding: The resource name of the ValidatingAdmissionPolicyBinding - expressionIndex: The index of the failed validations in the ValidatingAdmissionPolicy - validationActions: The enforcement actions enacted for the validation failure Example audit annotation: `\"validation.policy.admission.k8s.io/validation_failure\": \"[{\"message\": \"Invalid value\", {\"policy\": \"policy.example.com\", {\"binding\": \"policybinding.example.com\", {\"expressionIndex\": \"1\", {\"validationActions\": [\"Audit\"]}]\"`\n\nClients should expect to handle additional values by ignoring any values not recognized.\n\n\"Deny\" and \"Warn\" may not be used together since this combination needlessly duplicates the validation failure both in the API response body and the HTTP warning headers.\n\nRequired.",
}
func (ValidatingAdmissionPolicyBindingSpec) SwaggerDoc() map[string]string {
return map_ValidatingAdmissionPolicyBindingSpec
}
var map_ValidatingAdmissionPolicyList = map[string]string{
"": "ValidatingAdmissionPolicyList is a list of ValidatingAdmissionPolicy.",
"metadata": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds",
"items": "List of ValidatingAdmissionPolicy.",
}
func (ValidatingAdmissionPolicyList) SwaggerDoc() map[string]string {
return map_ValidatingAdmissionPolicyList
}
var map_ValidatingAdmissionPolicySpec = map[string]string{
"": "ValidatingAdmissionPolicySpec is the specification of the desired behavior of the AdmissionPolicy.",
"paramKind": "ParamKind specifies the kind of resources used to parameterize this policy. If absent, there are no parameters for this policy and the param CEL variable will not be provided to validation expressions. If ParamKind refers to a non-existent kind, this policy definition is mis-configured and the FailurePolicy is applied. If paramKind is specified but paramRef is unset in ValidatingAdmissionPolicyBinding, the params variable will be null.",
"matchConstraints": "MatchConstraints specifies what resources this policy is designed to validate. The AdmissionPolicy cares about a request if it matches _all_ Constraints. However, in order to prevent clusters from being put into an unstable state that cannot be recovered from via the API ValidatingAdmissionPolicy cannot match ValidatingAdmissionPolicy and ValidatingAdmissionPolicyBinding. Required.",
"validations": "Validations contain CEL expressions which is used to apply the validation. Validations and AuditAnnotations may not both be empty; a minimum of one Validations or AuditAnnotations is required.",
"failurePolicy": "failurePolicy defines how to handle failures for the admission policy. Failures can occur from CEL expression parse errors, type check errors, runtime errors and invalid or mis-configured policy definitions or bindings.\n\nA policy is invalid if spec.paramKind refers to a non-existent Kind. A binding is invalid if spec.paramRef.name refers to a non-existent resource.\n\nfailurePolicy does not define how validations that evaluate to false are handled.\n\nWhen failurePolicy is set to Fail, ValidatingAdmissionPolicyBinding validationActions define how failures are enforced.\n\nAllowed values are Ignore or Fail. Defaults to Fail.",
"auditAnnotations": "auditAnnotations contains CEL expressions which are used to produce audit annotations for the audit event of the API request. validations and auditAnnotations may not both be empty; a least one of validations or auditAnnotations is required.",
"matchConditions": "MatchConditions is a list of conditions that must be met for a request to be validated. Match conditions filter requests that have already been matched by the rules, namespaceSelector, and objectSelector. An empty list of matchConditions matches all requests. There are a maximum of 64 match conditions allowed.\n\nIf a parameter object is provided, it can be accessed via the `params` handle in the same manner as validation expressions.\n\nThe exact matching logic is (in order):\n 1. If ANY matchCondition evaluates to FALSE, the policy is skipped.\n 2. If ALL matchConditions evaluate to TRUE, the policy is evaluated.\n 3. If any matchCondition evaluates to an error (but none are FALSE):\n - If failurePolicy=Fail, reject the request\n - If failurePolicy=Ignore, the policy is skipped",
"variables": "Variables contain definitions of variables that can be used in composition of other expressions. Each variable is defined as a named CEL expression. The variables defined here will be available under `variables` in other expressions of the policy except MatchConditions because MatchConditions are evaluated before the rest of the policy.\n\nThe expression of a variable can refer to other variables defined earlier in the list but not those after. Thus, Variables must be sorted by the order of first appearance and acyclic.",
}
func (ValidatingAdmissionPolicySpec) SwaggerDoc() map[string]string {
return map_ValidatingAdmissionPolicySpec
}
var map_ValidatingAdmissionPolicyStatus = map[string]string{
"": "ValidatingAdmissionPolicyStatus represents the status of an admission validation policy.",
"observedGeneration": "The generation observed by the controller.",
"typeChecking": "The results of type checking for each expression. Presence of this field indicates the completion of the type checking.",
"conditions": "The conditions represent the latest available observations of a policy's current state.",
}
func (ValidatingAdmissionPolicyStatus) SwaggerDoc() map[string]string {
return map_ValidatingAdmissionPolicyStatus
}
var map_ValidatingWebhook = map[string]string{
"": "ValidatingWebhook describes an admission webhook and the resources and operations it applies to.",
"name": "The name of the admission webhook. Name should be fully qualified, e.g., imagepolicy.kubernetes.io, where \"imagepolicy\" is the name of the webhook, and kubernetes.io is the name of the organization. Required.",
@ -149,6 +301,28 @@ func (ValidatingWebhookConfigurationList) SwaggerDoc() map[string]string {
return map_ValidatingWebhookConfigurationList
}
var map_Validation = map[string]string{
"": "Validation specifies the CEL expression which is used to apply the validation.",
"expression": "Expression represents the expression which will be evaluated by CEL. ref: https://github.com/google/cel-spec CEL expressions have access to the contents of the API request/response, organized into CEL variables as well as some other useful variables:\n\n- 'object' - The object from the incoming request. The value is null for DELETE requests. - 'oldObject' - The existing object. The value is null for CREATE requests. - 'request' - Attributes of the API request([ref](/pkg/apis/admission/types.go#AdmissionRequest)). - 'params' - Parameter resource referred to by the policy binding being evaluated. Only populated if the policy has a ParamKind. - 'namespaceObject' - The namespace object that the incoming object belongs to. The value is null for cluster-scoped resources. - 'variables' - Map of composited variables, from its name to its lazily evaluated value.\n For example, a variable named 'foo' can be accessed as 'variables.foo'.\n- 'authorizer' - A CEL Authorizer. May be used to perform authorization checks for the principal (user or service account) of the request.\n See https://pkg.go.dev/k8s.io/apiserver/pkg/cel/library#Authz\n- 'authorizer.requestResource' - A CEL ResourceCheck constructed from the 'authorizer' and configured with the\n request resource.\n\nThe `apiVersion`, `kind`, `metadata.name` and `metadata.generateName` are always accessible from the root of the object. No other metadata properties are accessible.\n\nOnly property names of the form `[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible. Accessible property names are escaped according to the following rules when accessed in the expression: - '__' escapes to '__underscores__' - '.' escapes to '__dot__' - '-' escapes to '__dash__' - '/' escapes to '__slash__' - Property names that exactly match a CEL RESERVED keyword escape to '__{keyword}__'. The keywords are:\n\t \"true\", \"false\", \"null\", \"in\", \"as\", \"break\", \"const\", \"continue\", \"else\", \"for\", \"function\", \"if\",\n\t \"import\", \"let\", \"loop\", \"package\", \"namespace\", \"return\".\nExamples:\n - Expression accessing a property named \"namespace\": {\"Expression\": \"object.__namespace__ > 0\"}\n - Expression accessing a property named \"x-prop\": {\"Expression\": \"object.x__dash__prop > 0\"}\n - Expression accessing a property named \"redact__d\": {\"Expression\": \"object.redact__underscores__d > 0\"}\n\nEquality on arrays with list type of 'set' or 'map' ignores element order, i.e. [1, 2] == [2, 1]. Concatenation on arrays with x-kubernetes-list-type use the semantics of the list type:\n - 'set': `X + Y` performs a union where the array positions of all elements in `X` are preserved and\n non-intersecting elements in `Y` are appended, retaining their partial order.\n - 'map': `X + Y` performs a merge where the array positions of all keys in `X` are preserved but the values\n are overwritten by values in `Y` when the key sets of `X` and `Y` intersect. Elements in `Y` with\n non-intersecting keys are appended, retaining their partial order.\nRequired.",
"message": "Message represents the message displayed when validation fails. The message is required if the Expression contains line breaks. The message must not contain line breaks. If unset, the message is \"failed rule: {Rule}\". e.g. \"must be a URL with the host matching spec.host\" If the Expression contains line breaks. Message is required. The message must not contain line breaks. If unset, the message is \"failed Expression: {Expression}\".",
"reason": "Reason represents a machine-readable description of why this validation failed. If this is the first validation in the list to fail, this reason, as well as the corresponding HTTP response code, are used in the HTTP response to the client. The currently supported reasons are: \"Unauthorized\", \"Forbidden\", \"Invalid\", \"RequestEntityTooLarge\". If not set, StatusReasonInvalid is used in the response to the client.",
"messageExpression": "messageExpression declares a CEL expression that evaluates to the validation failure message that is returned when this rule fails. Since messageExpression is used as a failure message, it must evaluate to a string. If both message and messageExpression are present on a validation, then messageExpression will be used if validation fails. If messageExpression results in a runtime error, the runtime error is logged, and the validation failure message is produced as if the messageExpression field were unset. If messageExpression evaluates to an empty string, a string with only spaces, or a string that contains line breaks, then the validation failure message will also be produced as if the messageExpression field were unset, and the fact that messageExpression produced an empty string/string with only spaces/string with line breaks will be logged. messageExpression has access to all the same variables as the `expression` except for 'authorizer' and 'authorizer.requestResource'. Example: \"object.x must be less than max (\"+string(params.max)+\")\"",
}
func (Validation) SwaggerDoc() map[string]string {
return map_Validation
}
var map_Variable = map[string]string{
"": "Variable is the definition of a variable that is used for composition. A variable is defined as a named expression.",
"name": "Name is the name of the variable. The name must be a valid CEL identifier and unique among all variables. The variable can be accessed in other expressions through `variables` For example, if name is \"foo\", the variable will be available as `variables.foo`",
"expression": "Expression is the expression that will be evaluated as the value of the variable. The CEL expression has access to the same identifiers as the CEL expressions in Validation.",
}
func (Variable) SwaggerDoc() map[string]string {
return map_Variable
}
var map_WebhookClientConfig = map[string]string{
"": "WebhookClientConfig contains the information to make a TLS connection with the webhook",
"url": "`url` gives the location of the webhook, in standard URL form (`scheme://host:port/path`). Exactly one of `url` or `service` must be specified.\n\nThe `host` should not refer to a service running in the cluster; use the `service` field instead. The host might be resolved via external DNS in some apiservers (e.g., `kube-apiserver` cannot resolve in-cluster DNS as that would be a layering violation). `host` may also be an IP address.\n\nPlease note that using `localhost` or `127.0.0.1` as a `host` is risky unless you take great care to run this webhook on all hosts which run an apiserver which might need to make calls to this webhook. Such installs are likely to be non-portable, i.e., not easy to turn up in a new cluster.\n\nThe scheme must be \"https\"; the URL must begin with \"https://\".\n\nA path is optional, and if present may be any string permissible in a URL. You may use the path to pass an arbitrary string to the webhook, for example, a cluster identifier.\n\nAttempting to use a user or basic auth e.g. \"user:password@\" is not allowed. Fragments (\"#...\") and query parameters (\"?...\") are not allowed, either.",

View File

@ -26,6 +26,38 @@ import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *AuditAnnotation) DeepCopyInto(out *AuditAnnotation) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AuditAnnotation.
func (in *AuditAnnotation) DeepCopy() *AuditAnnotation {
if in == nil {
return nil
}
out := new(AuditAnnotation)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ExpressionWarning) DeepCopyInto(out *ExpressionWarning) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExpressionWarning.
func (in *ExpressionWarning) DeepCopy() *ExpressionWarning {
if in == nil {
return nil
}
out := new(ExpressionWarning)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MatchCondition) DeepCopyInto(out *MatchCondition) {
*out = *in
@ -42,6 +74,51 @@ func (in *MatchCondition) DeepCopy() *MatchCondition {
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MatchResources) DeepCopyInto(out *MatchResources) {
*out = *in
if in.NamespaceSelector != nil {
in, out := &in.NamespaceSelector, &out.NamespaceSelector
*out = new(metav1.LabelSelector)
(*in).DeepCopyInto(*out)
}
if in.ObjectSelector != nil {
in, out := &in.ObjectSelector, &out.ObjectSelector
*out = new(metav1.LabelSelector)
(*in).DeepCopyInto(*out)
}
if in.ResourceRules != nil {
in, out := &in.ResourceRules, &out.ResourceRules
*out = make([]NamedRuleWithOperations, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.ExcludeResourceRules != nil {
in, out := &in.ExcludeResourceRules, &out.ExcludeResourceRules
*out = make([]NamedRuleWithOperations, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.MatchPolicy != nil {
in, out := &in.MatchPolicy, &out.MatchPolicy
*out = new(MatchPolicyType)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MatchResources.
func (in *MatchResources) DeepCopy() *MatchResources {
if in == nil {
return nil
}
out := new(MatchResources)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *MutatingWebhook) DeepCopyInto(out *MutatingWebhook) {
*out = *in
@ -177,6 +254,70 @@ func (in *MutatingWebhookConfigurationList) DeepCopyObject() runtime.Object {
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *NamedRuleWithOperations) DeepCopyInto(out *NamedRuleWithOperations) {
*out = *in
if in.ResourceNames != nil {
in, out := &in.ResourceNames, &out.ResourceNames
*out = make([]string, len(*in))
copy(*out, *in)
}
in.RuleWithOperations.DeepCopyInto(&out.RuleWithOperations)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NamedRuleWithOperations.
func (in *NamedRuleWithOperations) DeepCopy() *NamedRuleWithOperations {
if in == nil {
return nil
}
out := new(NamedRuleWithOperations)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ParamKind) DeepCopyInto(out *ParamKind) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ParamKind.
func (in *ParamKind) DeepCopy() *ParamKind {
if in == nil {
return nil
}
out := new(ParamKind)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ParamRef) DeepCopyInto(out *ParamRef) {
*out = *in
if in.Selector != nil {
in, out := &in.Selector, &out.Selector
*out = new(metav1.LabelSelector)
(*in).DeepCopyInto(*out)
}
if in.ParameterNotFoundAction != nil {
in, out := &in.ParameterNotFoundAction, &out.ParameterNotFoundAction
*out = new(ParameterNotFoundActionType)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ParamRef.
func (in *ParamRef) DeepCopy() *ParamRef {
if in == nil {
return nil
}
out := new(ParamRef)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Rule) DeepCopyInto(out *Rule) {
*out = *in
@ -261,6 +402,260 @@ func (in *ServiceReference) DeepCopy() *ServiceReference {
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *TypeChecking) DeepCopyInto(out *TypeChecking) {
*out = *in
if in.ExpressionWarnings != nil {
in, out := &in.ExpressionWarnings, &out.ExpressionWarnings
*out = make([]ExpressionWarning, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TypeChecking.
func (in *TypeChecking) DeepCopy() *TypeChecking {
if in == nil {
return nil
}
out := new(TypeChecking)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ValidatingAdmissionPolicy) DeepCopyInto(out *ValidatingAdmissionPolicy) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValidatingAdmissionPolicy.
func (in *ValidatingAdmissionPolicy) DeepCopy() *ValidatingAdmissionPolicy {
if in == nil {
return nil
}
out := new(ValidatingAdmissionPolicy)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ValidatingAdmissionPolicy) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ValidatingAdmissionPolicyBinding) DeepCopyInto(out *ValidatingAdmissionPolicyBinding) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValidatingAdmissionPolicyBinding.
func (in *ValidatingAdmissionPolicyBinding) DeepCopy() *ValidatingAdmissionPolicyBinding {
if in == nil {
return nil
}
out := new(ValidatingAdmissionPolicyBinding)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ValidatingAdmissionPolicyBinding) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ValidatingAdmissionPolicyBindingList) DeepCopyInto(out *ValidatingAdmissionPolicyBindingList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]ValidatingAdmissionPolicyBinding, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValidatingAdmissionPolicyBindingList.
func (in *ValidatingAdmissionPolicyBindingList) DeepCopy() *ValidatingAdmissionPolicyBindingList {
if in == nil {
return nil
}
out := new(ValidatingAdmissionPolicyBindingList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ValidatingAdmissionPolicyBindingList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ValidatingAdmissionPolicyBindingSpec) DeepCopyInto(out *ValidatingAdmissionPolicyBindingSpec) {
*out = *in
if in.ParamRef != nil {
in, out := &in.ParamRef, &out.ParamRef
*out = new(ParamRef)
(*in).DeepCopyInto(*out)
}
if in.MatchResources != nil {
in, out := &in.MatchResources, &out.MatchResources
*out = new(MatchResources)
(*in).DeepCopyInto(*out)
}
if in.ValidationActions != nil {
in, out := &in.ValidationActions, &out.ValidationActions
*out = make([]ValidationAction, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValidatingAdmissionPolicyBindingSpec.
func (in *ValidatingAdmissionPolicyBindingSpec) DeepCopy() *ValidatingAdmissionPolicyBindingSpec {
if in == nil {
return nil
}
out := new(ValidatingAdmissionPolicyBindingSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ValidatingAdmissionPolicyList) DeepCopyInto(out *ValidatingAdmissionPolicyList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]ValidatingAdmissionPolicy, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValidatingAdmissionPolicyList.
func (in *ValidatingAdmissionPolicyList) DeepCopy() *ValidatingAdmissionPolicyList {
if in == nil {
return nil
}
out := new(ValidatingAdmissionPolicyList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ValidatingAdmissionPolicyList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ValidatingAdmissionPolicySpec) DeepCopyInto(out *ValidatingAdmissionPolicySpec) {
*out = *in
if in.ParamKind != nil {
in, out := &in.ParamKind, &out.ParamKind
*out = new(ParamKind)
**out = **in
}
if in.MatchConstraints != nil {
in, out := &in.MatchConstraints, &out.MatchConstraints
*out = new(MatchResources)
(*in).DeepCopyInto(*out)
}
if in.Validations != nil {
in, out := &in.Validations, &out.Validations
*out = make([]Validation, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
if in.FailurePolicy != nil {
in, out := &in.FailurePolicy, &out.FailurePolicy
*out = new(FailurePolicyType)
**out = **in
}
if in.AuditAnnotations != nil {
in, out := &in.AuditAnnotations, &out.AuditAnnotations
*out = make([]AuditAnnotation, len(*in))
copy(*out, *in)
}
if in.MatchConditions != nil {
in, out := &in.MatchConditions, &out.MatchConditions
*out = make([]MatchCondition, len(*in))
copy(*out, *in)
}
if in.Variables != nil {
in, out := &in.Variables, &out.Variables
*out = make([]Variable, len(*in))
copy(*out, *in)
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValidatingAdmissionPolicySpec.
func (in *ValidatingAdmissionPolicySpec) DeepCopy() *ValidatingAdmissionPolicySpec {
if in == nil {
return nil
}
out := new(ValidatingAdmissionPolicySpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ValidatingAdmissionPolicyStatus) DeepCopyInto(out *ValidatingAdmissionPolicyStatus) {
*out = *in
if in.TypeChecking != nil {
in, out := &in.TypeChecking, &out.TypeChecking
*out = new(TypeChecking)
(*in).DeepCopyInto(*out)
}
if in.Conditions != nil {
in, out := &in.Conditions, &out.Conditions
*out = make([]metav1.Condition, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ValidatingAdmissionPolicyStatus.
func (in *ValidatingAdmissionPolicyStatus) DeepCopy() *ValidatingAdmissionPolicyStatus {
if in == nil {
return nil
}
out := new(ValidatingAdmissionPolicyStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *ValidatingWebhook) DeepCopyInto(out *ValidatingWebhook) {
*out = *in
@ -391,6 +786,43 @@ func (in *ValidatingWebhookConfigurationList) DeepCopyObject() runtime.Object {
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Validation) DeepCopyInto(out *Validation) {
*out = *in
if in.Reason != nil {
in, out := &in.Reason, &out.Reason
*out = new(metav1.StatusReason)
**out = **in
}
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Validation.
func (in *Validation) DeepCopy() *Validation {
if in == nil {
return nil
}
out := new(Validation)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Variable) DeepCopyInto(out *Variable) {
*out = *in
return
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Variable.
func (in *Variable) DeepCopy() *Variable {
if in == nil {
return nil
}
out := new(Variable)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *WebhookClientConfig) DeepCopyInto(out *WebhookClientConfig) {
*out = *in

View File

@ -0,0 +1,171 @@
{
"kind": "ValidatingAdmissionPolicy",
"apiVersion": "admissionregistration.k8s.io/v1",
"metadata": {
"name": "nameValue",
"generateName": "generateNameValue",
"namespace": "namespaceValue",
"selfLink": "selfLinkValue",
"uid": "uidValue",
"resourceVersion": "resourceVersionValue",
"generation": 7,
"creationTimestamp": "2008-01-01T01:01:01Z",
"deletionTimestamp": "2009-01-01T01:01:01Z",
"deletionGracePeriodSeconds": 10,
"labels": {
"labelsKey": "labelsValue"
},
"annotations": {
"annotationsKey": "annotationsValue"
},
"ownerReferences": [
{
"apiVersion": "apiVersionValue",
"kind": "kindValue",
"name": "nameValue",
"uid": "uidValue",
"controller": true,
"blockOwnerDeletion": true
}
],
"finalizers": [
"finalizersValue"
],
"managedFields": [
{
"manager": "managerValue",
"operation": "operationValue",
"apiVersion": "apiVersionValue",
"time": "2004-01-01T01:01:01Z",
"fieldsType": "fieldsTypeValue",
"fieldsV1": {},
"subresource": "subresourceValue"
}
]
},
"spec": {
"paramKind": {
"apiVersion": "apiVersionValue",
"kind": "kindValue"
},
"matchConstraints": {
"namespaceSelector": {
"matchLabels": {
"matchLabelsKey": "matchLabelsValue"
},
"matchExpressions": [
{
"key": "keyValue",
"operator": "operatorValue",
"values": [
"valuesValue"
]
}
]
},
"objectSelector": {
"matchLabels": {
"matchLabelsKey": "matchLabelsValue"
},
"matchExpressions": [
{
"key": "keyValue",
"operator": "operatorValue",
"values": [
"valuesValue"
]
}
]
},
"resourceRules": [
{
"resourceNames": [
"resourceNamesValue"
],
"operations": [
"operationsValue"
],
"apiGroups": [
"apiGroupsValue"
],
"apiVersions": [
"apiVersionsValue"
],
"resources": [
"resourcesValue"
],
"scope": "scopeValue"
}
],
"excludeResourceRules": [
{
"resourceNames": [
"resourceNamesValue"
],
"operations": [
"operationsValue"
],
"apiGroups": [
"apiGroupsValue"
],
"apiVersions": [
"apiVersionsValue"
],
"resources": [
"resourcesValue"
],
"scope": "scopeValue"
}
],
"matchPolicy": "matchPolicyValue"
},
"validations": [
{
"expression": "expressionValue",
"message": "messageValue",
"reason": "reasonValue",
"messageExpression": "messageExpressionValue"
}
],
"failurePolicy": "failurePolicyValue",
"auditAnnotations": [
{
"key": "keyValue",
"valueExpression": "valueExpressionValue"
}
],
"matchConditions": [
{
"name": "nameValue",
"expression": "expressionValue"
}
],
"variables": [
{
"name": "nameValue",
"expression": "expressionValue"
}
]
},
"status": {
"observedGeneration": 1,
"typeChecking": {
"expressionWarnings": [
{
"fieldRef": "fieldRefValue",
"warning": "warningValue"
}
]
},
"conditions": [
{
"type": "typeValue",
"status": "statusValue",
"observedGeneration": 3,
"lastTransitionTime": "2004-01-01T01:01:01Z",
"reason": "reasonValue",
"message": "messageValue"
}
]
}
}

View File

@ -0,0 +1,108 @@
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
annotations:
annotationsKey: annotationsValue
creationTimestamp: "2008-01-01T01:01:01Z"
deletionGracePeriodSeconds: 10
deletionTimestamp: "2009-01-01T01:01:01Z"
finalizers:
- finalizersValue
generateName: generateNameValue
generation: 7
labels:
labelsKey: labelsValue
managedFields:
- apiVersion: apiVersionValue
fieldsType: fieldsTypeValue
fieldsV1: {}
manager: managerValue
operation: operationValue
subresource: subresourceValue
time: "2004-01-01T01:01:01Z"
name: nameValue
namespace: namespaceValue
ownerReferences:
- apiVersion: apiVersionValue
blockOwnerDeletion: true
controller: true
kind: kindValue
name: nameValue
uid: uidValue
resourceVersion: resourceVersionValue
selfLink: selfLinkValue
uid: uidValue
spec:
auditAnnotations:
- key: keyValue
valueExpression: valueExpressionValue
failurePolicy: failurePolicyValue
matchConditions:
- expression: expressionValue
name: nameValue
matchConstraints:
excludeResourceRules:
- apiGroups:
- apiGroupsValue
apiVersions:
- apiVersionsValue
operations:
- operationsValue
resourceNames:
- resourceNamesValue
resources:
- resourcesValue
scope: scopeValue
matchPolicy: matchPolicyValue
namespaceSelector:
matchExpressions:
- key: keyValue
operator: operatorValue
values:
- valuesValue
matchLabels:
matchLabelsKey: matchLabelsValue
objectSelector:
matchExpressions:
- key: keyValue
operator: operatorValue
values:
- valuesValue
matchLabels:
matchLabelsKey: matchLabelsValue
resourceRules:
- apiGroups:
- apiGroupsValue
apiVersions:
- apiVersionsValue
operations:
- operationsValue
resourceNames:
- resourceNamesValue
resources:
- resourcesValue
scope: scopeValue
paramKind:
apiVersion: apiVersionValue
kind: kindValue
validations:
- expression: expressionValue
message: messageValue
messageExpression: messageExpressionValue
reason: reasonValue
variables:
- expression: expressionValue
name: nameValue
status:
conditions:
- lastTransitionTime: "2004-01-01T01:01:01Z"
message: messageValue
observedGeneration: 3
reason: reasonValue
status: statusValue
type: typeValue
observedGeneration: 1
typeChecking:
expressionWarnings:
- fieldRef: fieldRefValue
warning: warningValue

View File

@ -0,0 +1,142 @@
{
"kind": "ValidatingAdmissionPolicyBinding",
"apiVersion": "admissionregistration.k8s.io/v1",
"metadata": {
"name": "nameValue",
"generateName": "generateNameValue",
"namespace": "namespaceValue",
"selfLink": "selfLinkValue",
"uid": "uidValue",
"resourceVersion": "resourceVersionValue",
"generation": 7,
"creationTimestamp": "2008-01-01T01:01:01Z",
"deletionTimestamp": "2009-01-01T01:01:01Z",
"deletionGracePeriodSeconds": 10,
"labels": {
"labelsKey": "labelsValue"
},
"annotations": {
"annotationsKey": "annotationsValue"
},
"ownerReferences": [
{
"apiVersion": "apiVersionValue",
"kind": "kindValue",
"name": "nameValue",
"uid": "uidValue",
"controller": true,
"blockOwnerDeletion": true
}
],
"finalizers": [
"finalizersValue"
],
"managedFields": [
{
"manager": "managerValue",
"operation": "operationValue",
"apiVersion": "apiVersionValue",
"time": "2004-01-01T01:01:01Z",
"fieldsType": "fieldsTypeValue",
"fieldsV1": {},
"subresource": "subresourceValue"
}
]
},
"spec": {
"policyName": "policyNameValue",
"paramRef": {
"name": "nameValue",
"namespace": "namespaceValue",
"selector": {
"matchLabels": {
"matchLabelsKey": "matchLabelsValue"
},
"matchExpressions": [
{
"key": "keyValue",
"operator": "operatorValue",
"values": [
"valuesValue"
]
}
]
},
"parameterNotFoundAction": "parameterNotFoundActionValue"
},
"matchResources": {
"namespaceSelector": {
"matchLabels": {
"matchLabelsKey": "matchLabelsValue"
},
"matchExpressions": [
{
"key": "keyValue",
"operator": "operatorValue",
"values": [
"valuesValue"
]
}
]
},
"objectSelector": {
"matchLabels": {
"matchLabelsKey": "matchLabelsValue"
},
"matchExpressions": [
{
"key": "keyValue",
"operator": "operatorValue",
"values": [
"valuesValue"
]
}
]
},
"resourceRules": [
{
"resourceNames": [
"resourceNamesValue"
],
"operations": [
"operationsValue"
],
"apiGroups": [
"apiGroupsValue"
],
"apiVersions": [
"apiVersionsValue"
],
"resources": [
"resourcesValue"
],
"scope": "scopeValue"
}
],
"excludeResourceRules": [
{
"resourceNames": [
"resourceNamesValue"
],
"operations": [
"operationsValue"
],
"apiGroups": [
"apiGroupsValue"
],
"apiVersions": [
"apiVersionsValue"
],
"resources": [
"resourcesValue"
],
"scope": "scopeValue"
}
],
"matchPolicy": "matchPolicyValue"
},
"validationActions": [
"validationActionsValue"
]
}
}

View File

@ -0,0 +1,92 @@
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
annotations:
annotationsKey: annotationsValue
creationTimestamp: "2008-01-01T01:01:01Z"
deletionGracePeriodSeconds: 10
deletionTimestamp: "2009-01-01T01:01:01Z"
finalizers:
- finalizersValue
generateName: generateNameValue
generation: 7
labels:
labelsKey: labelsValue
managedFields:
- apiVersion: apiVersionValue
fieldsType: fieldsTypeValue
fieldsV1: {}
manager: managerValue
operation: operationValue
subresource: subresourceValue
time: "2004-01-01T01:01:01Z"
name: nameValue
namespace: namespaceValue
ownerReferences:
- apiVersion: apiVersionValue
blockOwnerDeletion: true
controller: true
kind: kindValue
name: nameValue
uid: uidValue
resourceVersion: resourceVersionValue
selfLink: selfLinkValue
uid: uidValue
spec:
matchResources:
excludeResourceRules:
- apiGroups:
- apiGroupsValue
apiVersions:
- apiVersionsValue
operations:
- operationsValue
resourceNames:
- resourceNamesValue
resources:
- resourcesValue
scope: scopeValue
matchPolicy: matchPolicyValue
namespaceSelector:
matchExpressions:
- key: keyValue
operator: operatorValue
values:
- valuesValue
matchLabels:
matchLabelsKey: matchLabelsValue
objectSelector:
matchExpressions:
- key: keyValue
operator: operatorValue
values:
- valuesValue
matchLabels:
matchLabelsKey: matchLabelsValue
resourceRules:
- apiGroups:
- apiGroupsValue
apiVersions:
- apiVersionsValue
operations:
- operationsValue
resourceNames:
- resourceNamesValue
resources:
- resourcesValue
scope: scopeValue
paramRef:
name: nameValue
namespace: namespaceValue
parameterNotFoundAction: parameterNotFoundActionValue
selector:
matchExpressions:
- key: keyValue
operator: operatorValue
values:
- valuesValue
matchLabels:
matchLabelsKey: matchLabelsValue
policyName: policyNameValue
validationActions:
- validationActionsValue

View File

@ -90,7 +90,7 @@ users:
"--kubeconfig", fakeKubeConfig.Name(),
// disable admission and filters that require talking to kube-apiserver
"--enable-priority-and-fairness=false",
"--disable-admission-plugins", "NamespaceLifecycle,MutatingAdmissionWebhook,ValidatingAdmissionWebhook"},
"--disable-admission-plugins", "NamespaceLifecycle,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ValidatingAdmissionPolicy"},
flags...,
), nil)
if err != nil {

View File

@ -17,6 +17,7 @@ limitations under the License.
package initializer
import (
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/authorization/authorizer"
"k8s.io/client-go/dynamic"
@ -32,6 +33,7 @@ type pluginInitializer struct {
authorizer authorizer.Authorizer
featureGates featuregate.FeatureGate
stopCh <-chan struct{}
restMapper meta.RESTMapper
}
// New creates an instance of admission plugins initializer.
@ -44,6 +46,7 @@ func New(
authz authorizer.Authorizer,
featureGates featuregate.FeatureGate,
stopCh <-chan struct{},
restMapper meta.RESTMapper,
) pluginInitializer {
return pluginInitializer{
externalClient: extClientset,
@ -52,6 +55,7 @@ func New(
authorizer: authz,
featureGates: featureGates,
stopCh: stopCh,
restMapper: restMapper,
}
}
@ -83,6 +87,9 @@ func (i pluginInitializer) Initialize(plugin admission.Interface) {
if wants, ok := plugin.(WantsAuthorizer); ok {
wants.SetAuthorizer(i.authorizer)
}
if wants, ok := plugin.(WantsRESTMapper); ok {
wants.SetRESTMapper(i.restMapper)
}
}
var _ admission.PluginInitializer = pluginInitializer{}

View File

@ -21,6 +21,8 @@ import (
"testing"
"time"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/initializer"
"k8s.io/apiserver/pkg/authorization/authorizer"
@ -32,7 +34,7 @@ import (
// TestWantsAuthorizer ensures that the authorizer is injected
// when the WantsAuthorizer interface is implemented by a plugin.
func TestWantsAuthorizer(t *testing.T) {
target := initializer.New(nil, nil, nil, &TestAuthorizer{}, nil, nil)
target := initializer.New(nil, nil, nil, &TestAuthorizer{}, nil, nil, nil)
wantAuthorizerAdmission := &WantAuthorizerAdmission{}
target.Initialize(wantAuthorizerAdmission)
if wantAuthorizerAdmission.auth == nil {
@ -44,7 +46,7 @@ func TestWantsAuthorizer(t *testing.T) {
// when the WantsExternalKubeClientSet interface is implemented by a plugin.
func TestWantsExternalKubeClientSet(t *testing.T) {
cs := &fake.Clientset{}
target := initializer.New(cs, nil, nil, &TestAuthorizer{}, nil, nil)
target := initializer.New(cs, nil, nil, &TestAuthorizer{}, nil, nil, nil)
wantExternalKubeClientSet := &WantExternalKubeClientSet{}
target.Initialize(wantExternalKubeClientSet)
if wantExternalKubeClientSet.cs != cs {
@ -57,7 +59,7 @@ func TestWantsExternalKubeClientSet(t *testing.T) {
func TestWantsExternalKubeInformerFactory(t *testing.T) {
cs := &fake.Clientset{}
sf := informers.NewSharedInformerFactory(cs, time.Duration(1)*time.Second)
target := initializer.New(cs, nil, sf, &TestAuthorizer{}, nil, nil)
target := initializer.New(cs, nil, sf, &TestAuthorizer{}, nil, nil, nil)
wantExternalKubeInformerFactory := &WantExternalKubeInformerFactory{}
target.Initialize(wantExternalKubeInformerFactory)
if wantExternalKubeInformerFactory.sf != sf {
@ -69,7 +71,7 @@ func TestWantsExternalKubeInformerFactory(t *testing.T) {
// when the WantsShutdownSignal interface is implemented by a plugin.
func TestWantsShutdownNotification(t *testing.T) {
stopCh := make(chan struct{})
target := initializer.New(nil, nil, nil, &TestAuthorizer{}, nil, stopCh)
target := initializer.New(nil, nil, nil, &TestAuthorizer{}, nil, stopCh, nil)
wantDrainedNotification := &WantDrainedNotification{}
target.Initialize(wantDrainedNotification)
if wantDrainedNotification.stopCh == nil {
@ -149,3 +151,59 @@ type TestAuthorizer struct{}
func (t *TestAuthorizer) Authorize(ctx context.Context, a authorizer.Attributes) (authorized authorizer.Decision, reason string, err error) {
return authorizer.DecisionNoOpinion, "", nil
}
func TestRESTMapperAdmissionPlugin(t *testing.T) {
initializer := initializer.New(nil, nil, nil, &TestAuthorizer{}, nil, nil, &doNothingRESTMapper{})
wantsRESTMapperAdmission := &WantsRESTMapperAdmissionPlugin{}
initializer.Initialize(wantsRESTMapperAdmission)
if wantsRESTMapperAdmission.mapper == nil {
t.Errorf("Expected REST mapper to be initialized but found nil")
}
}
type WantsRESTMapperAdmissionPlugin struct {
doNothingAdmission
doNothingPluginInitialization
mapper meta.RESTMapper
}
func (p *WantsRESTMapperAdmissionPlugin) SetRESTMapper(mapper meta.RESTMapper) {
p.mapper = mapper
}
type doNothingRESTMapper struct{}
func (doNothingRESTMapper) KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error) {
return schema.GroupVersionKind{}, nil
}
func (doNothingRESTMapper) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) {
return nil, nil
}
func (doNothingRESTMapper) ResourceFor(input schema.GroupVersionResource) (schema.GroupVersionResource, error) {
return schema.GroupVersionResource{}, nil
}
func (doNothingRESTMapper) ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error) {
return nil, nil
}
func (doNothingRESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error) {
return nil, nil
}
func (doNothingRESTMapper) RESTMappings(gk schema.GroupKind, versions ...string) ([]*meta.RESTMapping, error) {
return nil, nil
}
func (doNothingRESTMapper) ResourceSingularizer(resource string) (singular string, err error) {
return "", nil
}
type doNothingAdmission struct{}
func (doNothingAdmission) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
return nil
}
func (doNothingAdmission) Handles(o admission.Operation) bool { return false }
func (doNothingAdmission) Validate() error { return nil }
type doNothingPluginInitialization struct{}
func (doNothingPluginInitialization) ValidateInitialization() error { return nil }

View File

@ -53,7 +53,7 @@ func newHandlerForTestWithClock(c clientset.Interface, cacheClock clock.Clock) (
if err != nil {
return nil, f, err
}
pluginInitializer := kubeadmission.New(c, nil, f, nil, nil, nil)
pluginInitializer := kubeadmission.New(c, nil, f, nil, nil, nil, nil)
pluginInitializer.Initialize(handler)
err = admission.ValidateInitialization(handler)
return handler, f, err

View File

@ -17,15 +17,15 @@ limitations under the License.
package generic
import (
"k8s.io/api/admissionregistration/v1beta1"
"k8s.io/api/admissionregistration/v1"
"k8s.io/apimachinery/pkg/types"
)
type PolicyAccessor interface {
GetName() string
GetNamespace() string
GetParamKind() *v1beta1.ParamKind
GetMatchConstraints() *v1beta1.MatchResources
GetParamKind() *v1.ParamKind
GetMatchConstraints() *v1.MatchResources
}
type BindingAccessor interface {
@ -36,7 +36,7 @@ type BindingAccessor interface {
// which is cluster-scoped, so namespace is usually left blank.
// But we leave the door open to add a namespaced vesion in the future
GetPolicyName() types.NamespacedName
GetParamRef() *v1beta1.ParamRef
GetParamRef() *v1.ParamRef
GetMatchResources() *v1beta1.MatchResources
GetMatchResources() *v1.MatchResources
}

View File

@ -22,7 +22,7 @@ import (
"fmt"
"time"
"k8s.io/api/admissionregistration/v1beta1"
"k8s.io/api/admissionregistration/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -217,10 +217,10 @@ func (d *policyDispatcher[P, B, E]) Dispatch(ctx context.Context, a admission.At
// configuration. If the policy-binding has no param configuration, it
// returns a single-element list with a nil param.
func CollectParams(
paramKind *v1beta1.ParamKind,
paramKind *v1.ParamKind,
paramInformer informers.GenericInformer,
paramScope meta.RESTScope,
paramRef *v1beta1.ParamRef,
paramRef *v1.ParamRef,
namespace string,
) ([]runtime.Object, error) {
// If definition has paramKind, paramRef is required in binding.
@ -326,7 +326,7 @@ func CollectParams(
}
// Apply fail action for params not found case
if len(params) == 0 && paramRef.ParameterNotFoundAction != nil && *paramRef.ParameterNotFoundAction == v1beta1.DenyAction {
if len(params) == 0 && paramRef.ParameterNotFoundAction != nil && *paramRef.ParameterNotFoundAction == v1.DenyAction {
return nil, errors.New("no params found for policy binding with `Deny` parameterNotFoundAction")
}

View File

@ -19,7 +19,7 @@ package generic
import (
"fmt"
"k8s.io/api/admissionregistration/v1beta1"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
@ -89,7 +89,7 @@ func (c *matcher) GetNamespace(name string) (*corev1.Namespace, error) {
var _ matching.MatchCriteria = &matchCriteria{}
type matchCriteria struct {
constraints *v1beta1.MatchResources
constraints *admissionregistrationv1.MatchResources
}
// GetParsedNamespaceSelector returns the converted LabelSelector which implements labels.Selector
@ -103,6 +103,6 @@ func (m *matchCriteria) GetParsedObjectSelector() (labels.Selector, error) {
}
// GetMatchResources returns the matchConstraints
func (m *matchCriteria) GetMatchResources() v1beta1.MatchResources {
func (m *matchCriteria) GetMatchResources() admissionregistrationv1.MatchResources {
return *m.constraints
}

View File

@ -20,7 +20,7 @@ import (
"testing"
"github.com/stretchr/testify/require"
"k8s.io/api/admissionregistration/v1beta1"
"k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
@ -110,7 +110,7 @@ func TestPolicySourceHasSyncedInitialList(t *testing.T) {
ObjectMeta: metav1.ObjectMeta{
Name: "policy2",
},
ParamKind: &v1beta1.ParamKind{
ParamKind: &v1.ParamKind{
APIVersion: "policy.example.com/v1",
Kind: "FakeParam",
},
@ -177,7 +177,7 @@ type FakePolicy struct {
metav1.TypeMeta
metav1.ObjectMeta
ParamKind *v1beta1.ParamKind
ParamKind *v1.ParamKind
}
var _ generic.PolicyAccessor = &FakePolicy{}
@ -199,11 +199,11 @@ func (fp *FakePolicy) GetNamespace() string {
return fp.Namespace
}
func (fp *FakePolicy) GetParamKind() *v1beta1.ParamKind {
func (fp *FakePolicy) GetParamKind() *v1.ParamKind {
return fp.ParamKind
}
func (fb *FakePolicy) GetMatchConstraints() *v1beta1.MatchResources {
func (fb *FakePolicy) GetMatchConstraints() *v1.MatchResources {
return nil
}
@ -221,11 +221,11 @@ func (fb *FakeBinding) GetPolicyName() types.NamespacedName {
}
}
func (fb *FakeBinding) GetMatchResources() *v1beta1.MatchResources {
func (fb *FakeBinding) GetMatchResources() *v1.MatchResources {
return nil
}
func (fb *FakeBinding) GetParamRef() *v1beta1.ParamRef {
func (fb *FakeBinding) GetParamRef() *v1.ParamRef {
return nil
}

View File

@ -216,6 +216,7 @@ func NewPolicyTestContext[P, B runtime.Object, E Evaluator](
fakeAuthorizer{},
featureGate,
testContext.Done(),
fakeRestMapper,
)
genericInitializer.Initialize(plugin)
plugin.SetRESTMapper(fakeRestMapper)

View File

@ -20,7 +20,6 @@ import (
"fmt"
v1 "k8s.io/api/admissionregistration/v1"
"k8s.io/api/admissionregistration/v1beta1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/admission"
@ -36,7 +35,7 @@ type MatchCriteria interface {
namespace.NamespaceSelectorProvider
object.ObjectSelectorProvider
GetMatchResources() v1beta1.MatchResources
GetMatchResources() v1.MatchResources
}
// Matcher decides if a request matches against matchCriteria
@ -121,7 +120,7 @@ func (m *Matcher) Matches(attr admission.Attributes, o admission.ObjectInterface
return true, matchResource, matchKind, nil
}
func matchesResourceRules(namedRules []v1beta1.NamedRuleWithOperations, matchPolicy *v1beta1.MatchPolicyType, attr admission.Attributes, o admission.ObjectInterfaces) (bool, schema.GroupVersionResource, schema.GroupVersionKind, error) {
func matchesResourceRules(namedRules []v1.NamedRuleWithOperations, matchPolicy *v1.MatchPolicyType, attr admission.Attributes, o admission.ObjectInterfaces) (bool, schema.GroupVersionResource, schema.GroupVersionKind, error) {
matchKind := attr.GetKind()
matchResource := attr.GetResource()
@ -150,7 +149,7 @@ func matchesResourceRules(namedRules []v1beta1.NamedRuleWithOperations, matchPol
// if match policy is undefined or exact, don't perform fuzzy matching
// note that defaulting to fuzzy matching is set by the API
if matchPolicy == nil || *matchPolicy == v1beta1.Exact {
if matchPolicy == nil || *matchPolicy == v1.Exact {
return false, schema.GroupVersionResource{}, schema.GroupVersionKind{}, nil
}

View File

@ -22,7 +22,6 @@ import (
"testing"
v1 "k8s.io/api/admissionregistration/v1"
"k8s.io/api/admissionregistration/v1beta1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -38,10 +37,10 @@ import (
var _ MatchCriteria = &fakeCriteria{}
type fakeCriteria struct {
matchResources v1beta1.MatchResources
matchResources v1.MatchResources
}
func (fc *fakeCriteria) GetMatchResources() v1beta1.MatchResources {
func (fc *fakeCriteria) GetMatchResources() v1.MatchResources {
return fc.matchResources
}
@ -65,8 +64,8 @@ func TestMatcher(t *testing.T) {
a := &Matcher{namespaceMatcher: &namespace.Matcher{}, objectMatcher: &object.Matcher{}}
allScopes := v1.AllScopes
exactMatch := v1beta1.Exact
equivalentMatch := v1beta1.Equivalent
exactMatch := v1.Exact
equivalentMatch := v1.Equivalent
mapper := runtime.NewEquivalentResourceRegistryWithIdentity(func(resource schema.GroupResource) string {
if resource.Resource == "deployments" {
@ -95,7 +94,7 @@ func TestMatcher(t *testing.T) {
testcases := []struct {
name string
criteria *v1beta1.MatchResources
criteria *v1.MatchResources
attrs admission.Attributes
expectMatches bool
@ -105,17 +104,17 @@ func TestMatcher(t *testing.T) {
}{
{
name: "no rules (just write)",
criteria: &v1beta1.MatchResources{NamespaceSelector: &metav1.LabelSelector{}, ResourceRules: []v1beta1.NamedRuleWithOperations{}},
criteria: &v1.MatchResources{NamespaceSelector: &metav1.LabelSelector{}, ResourceRules: []v1.NamedRuleWithOperations{}},
attrs: admission.NewAttributesRecord(nil, nil, gvk("apps", "v1", "Deployment"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false,
},
{
name: "wildcard rule, match as requested",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"*"}, Scope: &allScopes},
},
@ -126,21 +125,21 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, prefer exact match",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
@ -151,16 +150,16 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, match miss",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
@ -170,17 +169,17 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, exact match miss",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
MatchPolicy: &exactMatch,
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
@ -190,17 +189,17 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, equivalent match, prefer extensions",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
MatchPolicy: &equivalentMatch,
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
@ -212,17 +211,17 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, equivalent match, prefer apps",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
MatchPolicy: &equivalentMatch,
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
@ -235,21 +234,21 @@ func TestMatcher(t *testing.T) {
{
name: "specific rules, subresource prefer exact match",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
@ -260,16 +259,16 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, subresource match miss",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
@ -279,17 +278,17 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, subresource exact match miss",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
MatchPolicy: &exactMatch,
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
@ -299,17 +298,17 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, subresource equivalent match, prefer extensions",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
MatchPolicy: &equivalentMatch,
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
@ -321,17 +320,17 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, subresource equivalent match, prefer apps",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
MatchPolicy: &equivalentMatch,
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
@ -343,12 +342,12 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, prefer exact match and name match",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
ResourceRules: []v1.NamedRuleWithOperations{{
ResourceNames: []string{"name"},
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
@ -359,12 +358,12 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, prefer exact match and name match miss",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
ResourceRules: []v1.NamedRuleWithOperations{{
ResourceNames: []string{"wrong-name"},
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
@ -374,13 +373,13 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, subresource equivalent match, prefer extensions and name match",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
MatchPolicy: &equivalentMatch,
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
ResourceRules: []v1.NamedRuleWithOperations{{
ResourceNames: []string{"name"},
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
@ -392,13 +391,13 @@ func TestMatcher(t *testing.T) {
},
{
name: "specific rules, subresource equivalent match, prefer extensions and name match miss",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
MatchPolicy: &equivalentMatch,
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
ResourceRules: []v1.NamedRuleWithOperations{{
ResourceNames: []string{"wrong-name"},
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
@ -408,17 +407,17 @@ func TestMatcher(t *testing.T) {
},
{
name: "exclude resource match on miss",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"*"}, Scope: &allScopes},
},
}},
ExcludeResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ExcludeResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
@ -430,17 +429,17 @@ func TestMatcher(t *testing.T) {
},
{
name: "exclude resource miss on match",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"*"}, Scope: &allScopes},
},
}},
ExcludeResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ExcludeResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
@ -451,11 +450,11 @@ func TestMatcher(t *testing.T) {
},
{
name: "treat empty ResourceRules as match",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ExcludeResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
ExcludeResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments"}, Scope: &allScopes},
},
@ -466,23 +465,23 @@ func TestMatcher(t *testing.T) {
},
{
name: "treat non-empty ResourceRules as no match",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{}},
ResourceRules: []v1.NamedRuleWithOperations{{}},
},
attrs: admission.NewAttributesRecord(nil, nil, gvk("autoscaling", "v1", "Scale"), "ns", "name", gvr("apps", "v1", "deployments"), "", admission.Create, &metav1.CreateOptions{}, false, nil),
expectMatches: false,
},
{
name: "erroring namespace selector on otherwise non-matching rule doesn't error",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{MatchExpressions: []metav1.LabelSelectorRequirement{{Key: "key ", Operator: "In", Values: []string{"bad value"}}}},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"deployments"}},
Operations: []v1beta1.OperationType{"*"},
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"deployments"}},
Operations: []v1.OperationType{"*"},
},
}},
},
@ -492,13 +491,13 @@ func TestMatcher(t *testing.T) {
},
{
name: "erroring namespace selector on otherwise matching rule errors",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{MatchExpressions: []metav1.LabelSelectorRequirement{{Key: "key", Operator: "In", Values: []string{"bad value"}}}},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"pods"}},
Operations: []v1beta1.OperationType{"*"},
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"pods"}},
Operations: []v1.OperationType{"*"},
},
}},
},
@ -508,13 +507,13 @@ func TestMatcher(t *testing.T) {
},
{
name: "erroring object selector on otherwise non-matching rule doesn't error",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{MatchExpressions: []metav1.LabelSelectorRequirement{{Key: "key", Operator: "In", Values: []string{"bad value"}}}},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"deployments"}},
Operations: []v1beta1.OperationType{"*"},
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"deployments"}},
Operations: []v1.OperationType{"*"},
},
}},
},
@ -524,13 +523,13 @@ func TestMatcher(t *testing.T) {
},
{
name: "erroring object selector on otherwise matching rule errors",
criteria: &v1beta1.MatchResources{
criteria: &v1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{},
ObjectSelector: &metav1.LabelSelector{MatchExpressions: []metav1.LabelSelectorRequirement{{Key: "key", Operator: "In", Values: []string{"bad value"}}}},
ResourceRules: []v1beta1.NamedRuleWithOperations{{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"pods"}},
Operations: []v1beta1.OperationType{"*"},
ResourceRules: []v1.NamedRuleWithOperations{{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{APIGroups: []string{"*"}, APIVersions: []string{"*"}, Resources: []string{"pods"}},
Operations: []v1.OperationType{"*"},
},
}},
},
@ -601,7 +600,7 @@ func (f fakeNamespaceLister) Get(name string) (*corev1.Namespace, error) {
func BenchmarkMatcher(b *testing.B) {
allScopes := v1.AllScopes
equivalentMatch := v1beta1.Equivalent
equivalentMatch := v1.Equivalent
namespace1Labels := map[string]string{"ns": "ns1"}
namespace1 := corev1.Namespace{
@ -642,19 +641,19 @@ func BenchmarkMatcher(b *testing.B) {
nsSelector[fmt.Sprintf("key-%d", i)] = fmt.Sprintf("val-%d", i)
}
mr := v1beta1.MatchResources{
mr := v1.MatchResources{
MatchPolicy: &equivalentMatch,
NamespaceSelector: &metav1.LabelSelector{MatchLabels: nsSelector},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{
ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"apps"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
},
{
RuleWithOperations: v1beta1.RuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{APIGroups: []string{"extensions"}, APIVersions: []string{"v1beta1"}, Resources: []string{"deployments", "deployments/scale"}, Scope: &allScopes},
},
@ -674,7 +673,7 @@ func BenchmarkMatcher(b *testing.B) {
func BenchmarkShouldCallHookWithComplexRule(b *testing.B) {
allScopes := v1.AllScopes
equivalentMatch := v1beta1.Equivalent
equivalentMatch := v1.Equivalent
namespace1Labels := map[string]string{"ns": "ns1"}
namespace1 := corev1.Namespace{
@ -710,16 +709,16 @@ func BenchmarkShouldCallHookWithComplexRule(b *testing.B) {
mapper.RegisterKindFor(gvr("apps", "v1beta1", "statefulset"), "scale", gvk("apps", "v1beta1", "Scale"))
mapper.RegisterKindFor(gvr("apps", "v1alpha2", "statefulset"), "scale", gvk("apps", "v1beta2", "Scale"))
mr := v1beta1.MatchResources{
mr := v1.MatchResources{
MatchPolicy: &equivalentMatch,
NamespaceSelector: &metav1.LabelSelector{MatchLabels: map[string]string{"a": "b"}},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{},
ResourceRules: []v1.NamedRuleWithOperations{},
}
for i := 0; i < 100; i++ {
rule := v1beta1.NamedRuleWithOperations{
RuleWithOperations: v1beta1.RuleWithOperations{
rule := v1.NamedRuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{
APIGroups: []string{fmt.Sprintf("app-%d", i)},
@ -744,7 +743,7 @@ func BenchmarkShouldCallHookWithComplexRule(b *testing.B) {
func BenchmarkShouldCallHookWithComplexSelectorAndRule(b *testing.B) {
allScopes := v1.AllScopes
equivalentMatch := v1beta1.Equivalent
equivalentMatch := v1.Equivalent
namespace1Labels := map[string]string{"ns": "ns1"}
namespace1 := corev1.Namespace{
@ -785,16 +784,16 @@ func BenchmarkShouldCallHookWithComplexSelectorAndRule(b *testing.B) {
nsSelector[fmt.Sprintf("key-%d", i)] = fmt.Sprintf("val-%d", i)
}
mr := v1beta1.MatchResources{
mr := v1.MatchResources{
MatchPolicy: &equivalentMatch,
NamespaceSelector: &metav1.LabelSelector{MatchLabels: nsSelector},
ObjectSelector: &metav1.LabelSelector{},
ResourceRules: []v1beta1.NamedRuleWithOperations{},
ResourceRules: []v1.NamedRuleWithOperations{},
}
for i := 0; i < 100; i++ {
rule := v1beta1.NamedRuleWithOperations{
RuleWithOperations: v1beta1.RuleWithOperations{
rule := v1.NamedRuleWithOperations{
RuleWithOperations: v1.RuleWithOperations{
Operations: []v1.OperationType{"*"},
Rule: v1.Rule{
APIGroups: []string{fmt.Sprintf("app-%d", i)},

View File

@ -17,25 +17,25 @@ limitations under the License.
package validating
import (
"k8s.io/api/admissionregistration/v1beta1"
"k8s.io/api/admissionregistration/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apiserver/pkg/admission/plugin/policy/generic"
)
func NewValidatingAdmissionPolicyAccessor(obj *v1beta1.ValidatingAdmissionPolicy) generic.PolicyAccessor {
func NewValidatingAdmissionPolicyAccessor(obj *v1.ValidatingAdmissionPolicy) generic.PolicyAccessor {
return &validatingAdmissionPolicyAccessor{
ValidatingAdmissionPolicy: obj,
}
}
func NewValidatingAdmissionPolicyBindingAccessor(obj *v1beta1.ValidatingAdmissionPolicyBinding) generic.BindingAccessor {
func NewValidatingAdmissionPolicyBindingAccessor(obj *v1.ValidatingAdmissionPolicyBinding) generic.BindingAccessor {
return &validatingAdmissionPolicyBindingAccessor{
ValidatingAdmissionPolicyBinding: obj,
}
}
type validatingAdmissionPolicyAccessor struct {
*v1beta1.ValidatingAdmissionPolicy
*v1.ValidatingAdmissionPolicy
}
func (v *validatingAdmissionPolicyAccessor) GetNamespace() string {
@ -46,16 +46,16 @@ func (v *validatingAdmissionPolicyAccessor) GetName() string {
return v.Name
}
func (v *validatingAdmissionPolicyAccessor) GetParamKind() *v1beta1.ParamKind {
func (v *validatingAdmissionPolicyAccessor) GetParamKind() *v1.ParamKind {
return v.Spec.ParamKind
}
func (v *validatingAdmissionPolicyAccessor) GetMatchConstraints() *v1beta1.MatchResources {
func (v *validatingAdmissionPolicyAccessor) GetMatchConstraints() *v1.MatchResources {
return v.Spec.MatchConstraints
}
type validatingAdmissionPolicyBindingAccessor struct {
*v1beta1.ValidatingAdmissionPolicyBinding
*v1.ValidatingAdmissionPolicyBinding
}
func (v *validatingAdmissionPolicyBindingAccessor) GetNamespace() string {
@ -73,10 +73,10 @@ func (v *validatingAdmissionPolicyBindingAccessor) GetPolicyName() types.Namespa
}
}
func (v *validatingAdmissionPolicyBindingAccessor) GetMatchResources() *v1beta1.MatchResources {
func (v *validatingAdmissionPolicyBindingAccessor) GetMatchResources() *v1.MatchResources {
return v.Spec.MatchResources
}
func (v *validatingAdmissionPolicyBindingAccessor) GetParamRef() *v1beta1.ParamRef {
func (v *validatingAdmissionPolicyBindingAccessor) GetParamRef() *v1.ParamRef {
return v.Spec.ParamRef
}

View File

@ -27,7 +27,7 @@ import (
"github.com/stretchr/testify/require"
"k8s.io/api/admissionregistration/v1beta1"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -61,18 +61,18 @@ var (
}
// Common objects
denyPolicy *v1beta1.ValidatingAdmissionPolicy = &v1beta1.ValidatingAdmissionPolicy{
denyPolicy *admissionregistrationv1.ValidatingAdmissionPolicy = &admissionregistrationv1.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "denypolicy.example.com",
ResourceVersion: "1",
},
Spec: v1beta1.ValidatingAdmissionPolicySpec{
ParamKind: &v1beta1.ParamKind{
Spec: admissionregistrationv1.ValidatingAdmissionPolicySpec{
ParamKind: &admissionregistrationv1.ParamKind{
APIVersion: paramsGVK.GroupVersion().String(),
Kind: paramsGVK.Kind,
},
FailurePolicy: ptrTo(v1beta1.Fail),
Validations: []v1beta1.Validation{
FailurePolicy: ptrTo(admissionregistrationv1.Fail),
Validations: []admissionregistrationv1.Validation{
{
Expression: "messageId for deny policy",
},
@ -93,61 +93,61 @@ var (
},
}
denyBinding *v1beta1.ValidatingAdmissionPolicyBinding = &v1beta1.ValidatingAdmissionPolicyBinding{
denyBinding *admissionregistrationv1.ValidatingAdmissionPolicyBinding = &admissionregistrationv1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "denybinding.example.com",
ResourceVersion: "1",
},
Spec: v1beta1.ValidatingAdmissionPolicyBindingSpec{
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: denyPolicy.Name,
ParamRef: &v1beta1.ParamRef{
ParamRef: &admissionregistrationv1.ParamRef{
Name: fakeParams.GetName(),
Namespace: fakeParams.GetNamespace(),
// fake object tracker does not populate defaults
ParameterNotFoundAction: ptrTo(v1beta1.DenyAction),
ParameterNotFoundAction: ptrTo(admissionregistrationv1.DenyAction),
},
ValidationActions: []v1beta1.ValidationAction{v1beta1.Deny},
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny},
},
}
denyBindingWithNoParamRef *v1beta1.ValidatingAdmissionPolicyBinding = &v1beta1.ValidatingAdmissionPolicyBinding{
denyBindingWithNoParamRef *admissionregistrationv1.ValidatingAdmissionPolicyBinding = &admissionregistrationv1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "denybinding.example.com",
ResourceVersion: "1",
},
Spec: v1beta1.ValidatingAdmissionPolicyBindingSpec{
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: denyPolicy.Name,
ValidationActions: []v1beta1.ValidationAction{v1beta1.Deny},
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny},
},
}
denyBindingWithAudit = &v1beta1.ValidatingAdmissionPolicyBinding{
denyBindingWithAudit = &admissionregistrationv1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "denybinding.example.com",
ResourceVersion: "1",
},
Spec: v1beta1.ValidatingAdmissionPolicyBindingSpec{
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: denyPolicy.Name,
ValidationActions: []v1beta1.ValidationAction{v1beta1.Audit},
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Audit},
},
}
denyBindingWithWarn = &v1beta1.ValidatingAdmissionPolicyBinding{
denyBindingWithWarn = &admissionregistrationv1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "denybinding.example.com",
ResourceVersion: "1",
},
Spec: v1beta1.ValidatingAdmissionPolicyBindingSpec{
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: denyPolicy.Name,
ValidationActions: []v1beta1.ValidationAction{v1beta1.Warn},
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Warn},
},
}
denyBindingWithAll = &v1beta1.ValidatingAdmissionPolicyBinding{
denyBindingWithAll = &admissionregistrationv1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "denybinding.example.com",
ResourceVersion: "1",
},
Spec: v1beta1.ValidatingAdmissionPolicyBindingSpec{
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: denyPolicy.Name,
ValidationActions: []v1beta1.ValidationAction{v1beta1.Deny, v1beta1.Warn, v1beta1.Audit},
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny, admissionregistrationv1.Warn, admissionregistrationv1.Audit},
},
}
)
@ -277,7 +277,7 @@ type fakeMatcher struct {
BindingMatchFuncs map[types.NamespacedName]func(generic.BindingAccessor, admission.Attributes) bool
}
func (f *fakeMatcher) RegisterDefinition(definition *v1beta1.ValidatingAdmissionPolicy, matchFunc func(generic.PolicyAccessor, admission.Attributes) bool) {
func (f *fakeMatcher) RegisterDefinition(definition *admissionregistrationv1.ValidatingAdmissionPolicy, matchFunc func(generic.PolicyAccessor, admission.Attributes) bool) {
namespace, name := definition.Namespace, definition.Name
key := types.NamespacedName{
Name: name,
@ -292,7 +292,7 @@ func (f *fakeMatcher) RegisterDefinition(definition *v1beta1.ValidatingAdmission
}
}
func (f *fakeMatcher) RegisterBinding(binding *v1beta1.ValidatingAdmissionPolicyBinding, matchFunc func(generic.BindingAccessor, admission.Attributes) bool) {
func (f *fakeMatcher) RegisterBinding(binding *admissionregistrationv1.ValidatingAdmissionPolicyBinding, matchFunc func(generic.BindingAccessor, admission.Attributes) bool) {
namespace, name := binding.Namespace, binding.Name
key := types.NamespacedName{
Name: name,
@ -644,19 +644,19 @@ func TestReconfigureBinding(t *testing.T) {
}
})
denyBinding2 := &v1beta1.ValidatingAdmissionPolicyBinding{
denyBinding2 := &admissionregistrationv1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "denybinding.example.com",
ResourceVersion: "2",
},
Spec: v1beta1.ValidatingAdmissionPolicyBindingSpec{
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: denyPolicy.Name,
ParamRef: &v1beta1.ParamRef{
ParamRef: &admissionregistrationv1.ParamRef{
Name: fakeParams2.GetName(),
Namespace: fakeParams2.GetNamespace(),
ParameterNotFoundAction: ptrTo(v1beta1.DenyAction),
ParameterNotFoundAction: ptrTo(admissionregistrationv1.DenyAction),
},
ValidationActions: []v1beta1.ValidationAction{v1beta1.Deny},
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny},
},
}
@ -805,7 +805,7 @@ func TestInvalidParamSourceGVK(t *testing.T) {
passedParams := make(chan *unstructured.Unstructured)
badPolicy := *denyPolicy
badPolicy.Spec.ParamKind = &v1beta1.ParamKind{
badPolicy.Spec.ParamKind = &admissionregistrationv1.ParamKind{
APIVersion: paramsGVK.GroupVersion().String(),
Kind: "BadParamKind",
}
@ -985,13 +985,13 @@ func TestMultiplePoliciesSharedParamType(t *testing.T) {
// Use ConfigMap native-typed param
policy1 := *denyPolicy
policy1.Name = "denypolicy1.example.com"
policy1.Spec = v1beta1.ValidatingAdmissionPolicySpec{
ParamKind: &v1beta1.ParamKind{
policy1.Spec = admissionregistrationv1.ValidatingAdmissionPolicySpec{
ParamKind: &admissionregistrationv1.ParamKind{
APIVersion: paramsGVK.GroupVersion().String(),
Kind: paramsGVK.Kind,
},
FailurePolicy: ptrTo(v1beta1.Fail),
Validations: []v1beta1.Validation{
FailurePolicy: ptrTo(admissionregistrationv1.Fail),
Validations: []admissionregistrationv1.Validation{
{
Expression: "policy1",
},
@ -1000,13 +1000,13 @@ func TestMultiplePoliciesSharedParamType(t *testing.T) {
policy2 := *denyPolicy
policy2.Name = "denypolicy2.example.com"
policy2.Spec = v1beta1.ValidatingAdmissionPolicySpec{
ParamKind: &v1beta1.ParamKind{
policy2.Spec = admissionregistrationv1.ValidatingAdmissionPolicySpec{
ParamKind: &admissionregistrationv1.ParamKind{
APIVersion: paramsGVK.GroupVersion().String(),
Kind: paramsGVK.Kind,
},
FailurePolicy: ptrTo(v1beta1.Fail),
Validations: []v1beta1.Validation{
FailurePolicy: ptrTo(admissionregistrationv1.Fail),
Validations: []admissionregistrationv1.Validation{
{
Expression: "policy2",
},
@ -1106,7 +1106,7 @@ func TestNativeTypeParam(t *testing.T) {
// Use ConfigMap native-typed param
nativeTypeParamPolicy := *denyPolicy
nativeTypeParamPolicy.Spec.ParamKind = &v1beta1.ParamKind{
nativeTypeParamPolicy.Spec.ParamKind = &admissionregistrationv1.ParamKind{
APIVersion: "v1",
Kind: "ConfigMap",
}
@ -1208,7 +1208,7 @@ func TestAuditValidationAction(t *testing.T) {
expected := []validating.ValidationFailureValue{{
ExpressionIndex: 0,
Message: "I'm sorry Dave",
ValidationActions: []v1beta1.ValidationAction{v1beta1.Audit},
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Audit},
Binding: "denybinding.example.com",
Policy: noParamSourcePolicy.Name,
}}
@ -1305,7 +1305,7 @@ func TestAllValidationActions(t *testing.T) {
expected := []validating.ValidationFailureValue{{
ExpressionIndex: 0,
Message: "I'm sorry Dave",
ValidationActions: []v1beta1.ValidationAction{v1beta1.Deny, v1beta1.Warn, v1beta1.Audit},
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny, admissionregistrationv1.Warn, admissionregistrationv1.Audit},
Binding: "denybinding.example.com",
Policy: noParamSourcePolicy.Name,
}}
@ -1325,13 +1325,13 @@ func TestNamespaceParamRefName(t *testing.T) {
// Use ConfigMap native-typed param
nativeTypeParamPolicy := *denyPolicy
nativeTypeParamPolicy.Spec.ParamKind = &v1beta1.ParamKind{
nativeTypeParamPolicy.Spec.ParamKind = &admissionregistrationv1.ParamKind{
APIVersion: "v1",
Kind: "ConfigMap",
}
namespaceParamBinding := *denyBinding
namespaceParamBinding.Spec.ParamRef = &v1beta1.ParamRef{
namespaceParamBinding.Spec.ParamRef = &admissionregistrationv1.ParamRef{
Name: "replicas-test.example.com",
}
lock := sync.Mutex{}
@ -1543,7 +1543,7 @@ func testParamRefCase(t *testing.T, paramIsClusterScoped, nameIsSet, namespaceIs
// Create a cluster scoped and a namespace scoped CRD
policy := *denyPolicy
binding := *denyBinding
binding.Spec.ParamRef = &v1beta1.ParamRef{}
binding.Spec.ParamRef = &admissionregistrationv1.ParamRef{}
paramRef := binding.Spec.ParamRef
shouldErrorOnClusterScopedRequests := !namespaceIsSet && !paramIsClusterScoped
@ -1557,12 +1557,12 @@ func testParamRefCase(t *testing.T, paramIsClusterScoped, nameIsSet, namespaceIs
otherNonmatchingLabels := labels.Set{"notaffiliated": "no"}
if paramIsClusterScoped {
policy.Spec.ParamKind = &v1beta1.ParamKind{
policy.Spec.ParamKind = &admissionregistrationv1.ParamKind{
APIVersion: clusterScopedParamsGVK.GroupVersion().String(),
Kind: clusterScopedParamsGVK.Kind,
}
} else {
policy.Spec.ParamKind = &v1beta1.ParamKind{
policy.Spec.ParamKind = &admissionregistrationv1.ParamKind{
APIVersion: paramsGVK.GroupVersion().String(),
Kind: paramsGVK.Kind,
}
@ -1581,9 +1581,9 @@ func testParamRefCase(t *testing.T, paramIsClusterScoped, nameIsSet, namespaceIs
}
if denyNotFound {
paramRef.ParameterNotFoundAction = ptrTo(v1beta1.DenyAction)
paramRef.ParameterNotFoundAction = ptrTo(admissionregistrationv1.DenyAction)
} else {
paramRef.ParameterNotFoundAction = ptrTo(v1beta1.AllowAction)
paramRef.ParameterNotFoundAction = ptrTo(admissionregistrationv1.AllowAction)
}
compiler := &fakeCompiler{}
@ -1815,20 +1815,20 @@ func TestNamespaceParamRefClusterScopedParamError(t *testing.T) {
// Use ValidatingAdmissionPolicy for param type since it is cluster-scoped
nativeTypeParamPolicy := *denyPolicy
nativeTypeParamPolicy.Spec.ParamKind = &v1beta1.ParamKind{
nativeTypeParamPolicy.Spec.ParamKind = &admissionregistrationv1.ParamKind{
APIVersion: "admissionregistration.k8s.io/v1beta1",
Kind: "ValidatingAdmissionPolicy",
}
namespaceParamBinding := *denyBinding
namespaceParamBinding.Spec.ParamRef = &v1beta1.ParamRef{
namespaceParamBinding.Spec.ParamRef = &admissionregistrationv1.ParamRef{
Name: "other-param-to-use-with-no-label.example.com",
Namespace: "mynamespace",
}
compiler.RegisterDefinition(&nativeTypeParamPolicy, func(ctx context.Context, matchedResource schema.GroupVersionResource, versionedAttr *admission.VersionedAttributes, versionedParams runtime.Object, namespace *v1.Namespace, runtimeCELCostBudget int64, authz authorizer.Authorizer) validating.ValidateResult {
evaluations.Add(1)
if _, ok := versionedParams.(*v1beta1.ValidatingAdmissionPolicy); ok {
if _, ok := versionedParams.(*admissionregistrationv1.ValidatingAdmissionPolicy); ok {
return validating.ValidateResult{
Decisions: []validating.PolicyDecision{
{

View File

@ -22,7 +22,7 @@ import (
"fmt"
"strings"
"k8s.io/api/admissionregistration/v1beta1"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
v1 "k8s.io/api/core/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -59,8 +59,8 @@ func NewDispatcher(
// that determined the decision
type policyDecisionWithMetadata struct {
PolicyDecision
Definition *v1beta1.ValidatingAdmissionPolicy
Binding *v1beta1.ValidatingAdmissionPolicyBinding
Definition *admissionregistrationv1.ValidatingAdmissionPolicy
Binding *admissionregistrationv1.ValidatingAdmissionPolicyBinding
}
// Dispatch implements generic.Dispatcher.
@ -68,21 +68,21 @@ func (c *dispatcher) Dispatch(ctx context.Context, a admission.Attributes, o adm
var deniedDecisions []policyDecisionWithMetadata
addConfigError := func(err error, definition *v1beta1.ValidatingAdmissionPolicy, binding *v1beta1.ValidatingAdmissionPolicyBinding) {
addConfigError := func(err error, definition *admissionregistrationv1.ValidatingAdmissionPolicy, binding *admissionregistrationv1.ValidatingAdmissionPolicyBinding) {
// we always default the FailurePolicy if it is unset and validate it in API level
var policy v1beta1.FailurePolicyType
var policy admissionregistrationv1.FailurePolicyType
if definition.Spec.FailurePolicy == nil {
policy = v1beta1.Fail
policy = admissionregistrationv1.Fail
} else {
policy = *definition.Spec.FailurePolicy
}
// apply FailurePolicy specified in ValidatingAdmissionPolicy, the default would be Fail
switch policy {
case v1beta1.Ignore:
case admissionregistrationv1.Ignore:
// TODO: add metrics for ignored error here
return
case v1beta1.Fail:
case admissionregistrationv1.Fail:
var message string
if binding == nil {
message = fmt.Errorf("failed to configure policy: %w", err).Error()
@ -228,17 +228,17 @@ func (c *dispatcher) Dispatch(ctx context.Context, a admission.Attributes, o adm
case ActionDeny:
for _, action := range binding.Spec.ValidationActions {
switch action {
case v1beta1.Deny:
case admissionregistrationv1.Deny:
deniedDecisions = append(deniedDecisions, policyDecisionWithMetadata{
Definition: definition,
Binding: binding,
PolicyDecision: decision,
})
celmetrics.Metrics.ObserveRejection(ctx, decision.Elapsed, definition.Name, binding.Name, "active")
case v1beta1.Audit:
case admissionregistrationv1.Audit:
publishValidationFailureAnnotation(binding, i, decision, versionedAttr)
celmetrics.Metrics.ObserveAudit(ctx, decision.Elapsed, definition.Name, binding.Name, "active")
case v1beta1.Warn:
case admissionregistrationv1.Warn:
warning.AddWarning(ctx, "", fmt.Sprintf("Validation failed for ValidatingAdmissionPolicy '%s' with binding '%s': %s", definition.Name, binding.Name, decision.Message))
celmetrics.Metrics.ObserveWarn(ctx, decision.Elapsed, definition.Name, binding.Name, "active")
}
@ -302,7 +302,7 @@ func (c *dispatcher) Dispatch(ctx context.Context, a admission.Attributes, o adm
return nil
}
func publishValidationFailureAnnotation(binding *v1beta1.ValidatingAdmissionPolicyBinding, expressionIndex int, decision PolicyDecision, attributes admission.Attributes) {
func publishValidationFailureAnnotation(binding *admissionregistrationv1.ValidatingAdmissionPolicyBinding, expressionIndex int, decision PolicyDecision, attributes admission.Attributes) {
key := "validation.policy.admission.k8s.io/validation_failure"
// Marshal to a list of failures since, in the future, we may need to support multiple failures
valueJSON, err := utiljson.Marshal([]ValidationFailureValue{{
@ -326,11 +326,11 @@ const maxAuditAnnotationValueLength = 10 * 1024
// validationFailureValue defines the JSON format of a "validation.policy.admission.k8s.io/validation_failure" audit
// annotation value.
type ValidationFailureValue struct {
Message string `json:"message"`
Policy string `json:"policy"`
Binding string `json:"binding"`
ExpressionIndex int `json:"expressionIndex"`
ValidationActions []v1beta1.ValidationAction `json:"validationActions"`
Message string `json:"message"`
Policy string `json:"policy"`
Binding string `json:"binding"`
ExpressionIndex int `json:"expressionIndex"`
ValidationActions []admissionregistrationv1.ValidationAction `json:"validationActions"`
}
type auditAnnotationCollector struct {

View File

@ -21,7 +21,6 @@ import (
"io"
v1 "k8s.io/api/admissionregistration/v1"
"k8s.io/api/admissionregistration/v1beta1"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/initializer"
@ -62,8 +61,8 @@ func Register(plugins *admission.Plugins) {
}
// Plugin is an implementation of admission.Interface.
type Policy = v1beta1.ValidatingAdmissionPolicy
type PolicyBinding = v1beta1.ValidatingAdmissionPolicyBinding
type Policy = v1.ValidatingAdmissionPolicy
type PolicyBinding = v1.ValidatingAdmissionPolicyBinding
type PolicyEvaluator = Validator
type PolicyHook = generic.PolicyHook[*Policy, *PolicyBinding, PolicyEvaluator]
@ -84,8 +83,8 @@ func NewPlugin(_ io.Reader) *Plugin {
handler,
func(f informers.SharedInformerFactory, client kubernetes.Interface, dynamicClient dynamic.Interface, restMapper meta.RESTMapper) generic.Source[PolicyHook] {
return generic.NewPolicySource(
f.Admissionregistration().V1beta1().ValidatingAdmissionPolicies().Informer(),
f.Admissionregistration().V1beta1().ValidatingAdmissionPolicyBindings().Informer(),
f.Admissionregistration().V1().ValidatingAdmissionPolicies().Informer(),
f.Admissionregistration().V1().ValidatingAdmissionPolicyBindings().Informer(),
NewValidatingAdmissionPolicyAccessor,
NewValidatingAdmissionPolicyBindingAccessor,
compilePolicy,
@ -117,7 +116,7 @@ func compilePolicy(policy *Policy) Validator {
}
optionalVars := cel.OptionalVariableDeclarations{HasParams: hasParam, HasAuthorizer: true}
expressionOptionalVars := cel.OptionalVariableDeclarations{HasParams: hasParam, HasAuthorizer: false}
failurePolicy := convertv1beta1FailurePolicyTypeTov1FailurePolicyType(policy.Spec.FailurePolicy)
failurePolicy := policy.Spec.FailurePolicy
var matcher matchconditions.Matcher = nil
matchConditions := policy.Spec.MatchConditions
@ -132,31 +131,17 @@ func compilePolicy(policy *Policy) Validator {
matcher = matchconditions.NewMatcher(filterCompiler.Compile(matchExpressionAccessors, optionalVars, environment.StoredExpressions), failurePolicy, "policy", "validate", policy.Name)
}
res := NewValidator(
filterCompiler.Compile(convertv1beta1Validations(policy.Spec.Validations), optionalVars, environment.StoredExpressions),
filterCompiler.Compile(convertv1Validations(policy.Spec.Validations), optionalVars, environment.StoredExpressions),
matcher,
filterCompiler.Compile(convertv1beta1AuditAnnotations(policy.Spec.AuditAnnotations), optionalVars, environment.StoredExpressions),
filterCompiler.Compile(convertv1beta1MessageExpressions(policy.Spec.Validations), expressionOptionalVars, environment.StoredExpressions),
filterCompiler.Compile(convertv1AuditAnnotations(policy.Spec.AuditAnnotations), optionalVars, environment.StoredExpressions),
filterCompiler.Compile(convertv1MessageExpressions(policy.Spec.Validations), expressionOptionalVars, environment.StoredExpressions),
failurePolicy,
)
return res
}
func convertv1beta1FailurePolicyTypeTov1FailurePolicyType(policyType *v1beta1.FailurePolicyType) *v1.FailurePolicyType {
if policyType == nil {
return nil
}
var v1FailPolicy v1.FailurePolicyType
if *policyType == v1beta1.Fail {
v1FailPolicy = v1.Fail
} else if *policyType == v1beta1.Ignore {
v1FailPolicy = v1.Ignore
}
return &v1FailPolicy
}
func convertv1beta1Validations(inputValidations []v1beta1.Validation) []cel.ExpressionAccessor {
func convertv1Validations(inputValidations []v1.Validation) []cel.ExpressionAccessor {
celExpressionAccessor := make([]cel.ExpressionAccessor, len(inputValidations))
for i, validation := range inputValidations {
validation := ValidationCondition{
@ -169,7 +154,7 @@ func convertv1beta1Validations(inputValidations []v1beta1.Validation) []cel.Expr
return celExpressionAccessor
}
func convertv1beta1MessageExpressions(inputValidations []v1beta1.Validation) []cel.ExpressionAccessor {
func convertv1MessageExpressions(inputValidations []v1.Validation) []cel.ExpressionAccessor {
celExpressionAccessor := make([]cel.ExpressionAccessor, len(inputValidations))
for i, validation := range inputValidations {
if validation.MessageExpression != "" {
@ -182,7 +167,7 @@ func convertv1beta1MessageExpressions(inputValidations []v1beta1.Validation) []c
return celExpressionAccessor
}
func convertv1beta1AuditAnnotations(inputValidations []v1beta1.AuditAnnotation) []cel.ExpressionAccessor {
func convertv1AuditAnnotations(inputValidations []v1.AuditAnnotation) []cel.ExpressionAccessor {
celExpressionAccessor := make([]cel.ExpressionAccessor, len(inputValidations))
for i, validation := range inputValidations {
validation := AuditAnnotationCondition{
@ -194,7 +179,7 @@ func convertv1beta1AuditAnnotations(inputValidations []v1beta1.AuditAnnotation)
return celExpressionAccessor
}
func convertv1beta1Variables(variables []v1beta1.Variable) []cel.NamedExpressionAccessor {
func convertv1beta1Variables(variables []v1.Variable) []cel.NamedExpressionAccessor {
namedExpressions := make([]cel.NamedExpressionAccessor, len(variables))
for i, variable := range variables {
namedExpressions[i] = &Variable{Name: variable.Name, Expression: variable.Expression}

View File

@ -25,7 +25,7 @@ import (
"github.com/google/cel-go/cel"
"k8s.io/api/admissionregistration/v1beta1"
"k8s.io/api/admissionregistration/v1"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/runtime/schema"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
@ -57,7 +57,7 @@ type TypeCheckingContext struct {
paramGVK schema.GroupVersionKind
paramDeclType *apiservercel.DeclType
variables []v1beta1.Variable
variables []v1.Variable
}
type typeOverwrite struct {
@ -105,18 +105,18 @@ func (r *TypeCheckingResult) String() string {
// as []ExpressionWarning that is ready to be set in policy.Status
// The result is nil if type checking returns no warning.
// The policy object is NOT mutated. The caller should update Status accordingly
func (c *TypeChecker) Check(policy *v1beta1.ValidatingAdmissionPolicy) []v1beta1.ExpressionWarning {
func (c *TypeChecker) Check(policy *v1.ValidatingAdmissionPolicy) []v1.ExpressionWarning {
ctx := c.CreateContext(policy)
// warnings to return, note that the capacity is optimistically set to zero
var warnings []v1beta1.ExpressionWarning // intentionally not setting capacity
var warnings []v1.ExpressionWarning // intentionally not setting capacity
// check main validation expressions and their message expressions, located in spec.validations[*]
fieldRef := field.NewPath("spec", "validations")
for i, v := range policy.Spec.Validations {
results := c.CheckExpression(ctx, v.Expression)
if len(results) != 0 {
warnings = append(warnings, v1beta1.ExpressionWarning{
warnings = append(warnings, v1.ExpressionWarning{
FieldRef: fieldRef.Index(i).Child("expression").String(),
Warning: results.String(),
})
@ -127,7 +127,7 @@ func (c *TypeChecker) Check(policy *v1beta1.ValidatingAdmissionPolicy) []v1beta1
}
results = c.CheckExpression(ctx, v.MessageExpression)
if len(results) != 0 {
warnings = append(warnings, v1beta1.ExpressionWarning{
warnings = append(warnings, v1.ExpressionWarning{
FieldRef: fieldRef.Index(i).Child("messageExpression").String(),
Warning: results.String(),
})
@ -138,7 +138,7 @@ func (c *TypeChecker) Check(policy *v1beta1.ValidatingAdmissionPolicy) []v1beta1
}
// CreateContext resolves all types and their schemas from a policy definition and creates the context.
func (c *TypeChecker) CreateContext(policy *v1beta1.ValidatingAdmissionPolicy) *TypeCheckingContext {
func (c *TypeChecker) CreateContext(policy *v1.ValidatingAdmissionPolicy) *TypeCheckingContext {
ctx := new(TypeCheckingContext)
allGvks := c.typesToCheck(policy)
gvks := make([]schema.GroupVersionKind, 0, len(allGvks))
@ -250,7 +250,7 @@ func (c *TypeChecker) declType(gvk schema.GroupVersionKind) (*apiservercel.DeclT
return common.SchemaDeclType(&openapi.Schema{Schema: s}, true).MaybeAssignTypeName(generateUniqueTypeName(gvk.Kind)), nil
}
func (c *TypeChecker) paramsGVK(policy *v1beta1.ValidatingAdmissionPolicy) schema.GroupVersionKind {
func (c *TypeChecker) paramsGVK(policy *v1.ValidatingAdmissionPolicy) schema.GroupVersionKind {
if policy.Spec.ParamKind == nil {
return schema.GroupVersionKind{}
}
@ -263,7 +263,7 @@ func (c *TypeChecker) paramsGVK(policy *v1beta1.ValidatingAdmissionPolicy) schem
// typesToCheck extracts a list of GVKs that needs type checking from the policy
// the result is sorted in the order of Group, Version, and Kind
func (c *TypeChecker) typesToCheck(p *v1beta1.ValidatingAdmissionPolicy) []schema.GroupVersionKind {
func (c *TypeChecker) typesToCheck(p *v1.ValidatingAdmissionPolicy) []schema.GroupVersionKind {
gvks := sets.New[schema.GroupVersionKind]()
if p.Spec.MatchConstraints == nil || len(p.Spec.MatchConstraints.ResourceRules) == 0 {
return nil
@ -333,7 +333,7 @@ func (c *TypeChecker) typesToCheck(p *v1beta1.ValidatingAdmissionPolicy) []schem
return sortGVKList(gvks.UnsortedList())
}
func extractGroups(rule *v1beta1.Rule) []string {
func extractGroups(rule *v1.Rule) []string {
groups := make([]string, 0, len(rule.APIGroups))
for _, group := range rule.APIGroups {
// give up if wildcard
@ -345,7 +345,7 @@ func extractGroups(rule *v1beta1.Rule) []string {
return groups
}
func extractVersions(rule *v1beta1.Rule) []string {
func extractVersions(rule *v1.Rule) []string {
versions := make([]string, 0, len(rule.APIVersions))
for _, version := range rule.APIVersions {
if strings.ContainsAny(version, "*") {
@ -356,7 +356,7 @@ func extractVersions(rule *v1beta1.Rule) []string {
return versions
}
func extractResources(rule *v1beta1.Rule) []string {
func extractResources(rule *v1.Rule) []string {
resources := make([]string, 0, len(rule.Resources))
for _, resource := range rule.Resources {
// skip wildcard and subresources

View File

@ -22,7 +22,7 @@ import (
"strings"
"testing"
"k8s.io/api/admissionregistration/v1beta1"
"k8s.io/api/admissionregistration/v1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
@ -36,7 +36,7 @@ import (
var (
scheme *runtime.Scheme = func() *runtime.Scheme {
res := runtime.NewScheme()
if err := v1beta1.AddToScheme(res); err != nil {
if err := v1.AddToScheme(res); err != nil {
panic(err)
}
@ -58,21 +58,21 @@ func must3[T any, I any](val T, _ I, err error) T {
func TestExtractTypeNames(t *testing.T) {
for _, tc := range []struct {
name string
policy *v1beta1.ValidatingAdmissionPolicy
policy *v1.ValidatingAdmissionPolicy
expected []schema.GroupVersionKind // must be sorted
}{
{
name: "empty",
policy: &v1beta1.ValidatingAdmissionPolicy{},
policy: &v1.ValidatingAdmissionPolicy{},
expected: nil,
},
{
name: "specific",
policy: &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1beta1.MatchResources{ResourceRules: []v1beta1.NamedRuleWithOperations{
policy: &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1.MatchResources{ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"deployments"},
@ -89,19 +89,19 @@ func TestExtractTypeNames(t *testing.T) {
},
{
name: "multiple",
policy: &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1beta1.MatchResources{ResourceRules: []v1beta1.NamedRuleWithOperations{
policy: &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1.MatchResources{ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"deployments"},
},
},
}, {
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{""},
APIVersions: []string{"v1"},
Resources: []string{"pods"},
@ -122,11 +122,11 @@ func TestExtractTypeNames(t *testing.T) {
},
{
name: "all resources",
policy: &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1beta1.MatchResources{ResourceRules: []v1beta1.NamedRuleWithOperations{
policy: &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1.MatchResources{ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"*"},
@ -139,11 +139,11 @@ func TestExtractTypeNames(t *testing.T) {
},
{
name: "sub resources",
policy: &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1beta1.MatchResources{ResourceRules: []v1beta1.NamedRuleWithOperations{
policy: &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1.MatchResources{ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"pods/*"},
@ -156,11 +156,11 @@ func TestExtractTypeNames(t *testing.T) {
},
{
name: "mixtures",
policy: &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1beta1.MatchResources{ResourceRules: []v1beta1.NamedRuleWithOperations{
policy: &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
MatchConstraints: &v1.MatchResources{ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"deployments"},
@ -168,8 +168,8 @@ func TestExtractTypeNames(t *testing.T) {
},
},
{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"*"},
Resources: []string{"deployments"},
@ -196,16 +196,16 @@ func TestExtractTypeNames(t *testing.T) {
}
func TestTypeCheck(t *testing.T) {
deploymentPolicy := &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
Validations: []v1beta1.Validation{
deploymentPolicy := &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
Validations: []v1.Validation{
{
Expression: "object.foo == 'bar'",
},
},
MatchConstraints: &v1beta1.MatchResources{ResourceRules: []v1beta1.NamedRuleWithOperations{
MatchConstraints: &v1.MatchResources{ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"deployments"},
@ -218,8 +218,8 @@ func TestTypeCheck(t *testing.T) {
deploymentPolicyWithBadMessageExpression := deploymentPolicy.DeepCopy()
deploymentPolicyWithBadMessageExpression.Spec.Validations[0].MessageExpression = "object.foo + 114514" // confusion
multiExpressionPolicy := &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
Validations: []v1beta1.Validation{
multiExpressionPolicy := &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
Validations: []v1.Validation{
{
Expression: "object.foo == 'bar'",
},
@ -227,10 +227,10 @@ func TestTypeCheck(t *testing.T) {
Expression: "object.bar == 'foo'",
},
},
MatchConstraints: &v1beta1.MatchResources{ResourceRules: []v1beta1.NamedRuleWithOperations{
MatchConstraints: &v1.MatchResources{ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"deployments"},
@ -239,20 +239,20 @@ func TestTypeCheck(t *testing.T) {
},
}},
}}
paramsRefPolicy := &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
ParamKind: &v1beta1.ParamKind{
paramsRefPolicy := &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
ParamKind: &v1.ParamKind{
APIVersion: "v1",
Kind: "DoesNotMatter",
},
Validations: []v1beta1.Validation{
Validations: []v1.Validation{
{
Expression: "object.foo == params.bar",
},
},
MatchConstraints: &v1beta1.MatchResources{ResourceRules: []v1beta1.NamedRuleWithOperations{
MatchConstraints: &v1.MatchResources{ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"deployments"},
@ -261,16 +261,16 @@ func TestTypeCheck(t *testing.T) {
},
}},
}}
authorizerPolicy := &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
Validations: []v1beta1.Validation{
authorizerPolicy := &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
Validations: []v1.Validation{
{
Expression: "authorizer.group('').resource('endpoints').check('create').allowed()",
},
},
MatchConstraints: &v1beta1.MatchResources{ResourceRules: []v1beta1.NamedRuleWithOperations{
MatchConstraints: &v1.MatchResources{ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"deployments"},
@ -279,16 +279,16 @@ func TestTypeCheck(t *testing.T) {
},
}},
}}
authorizerInvalidPolicy := &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
Validations: []v1beta1.Validation{
authorizerInvalidPolicy := &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
Validations: []v1.Validation{
{
Expression: "authorizer.allowed()",
},
},
MatchConstraints: &v1beta1.MatchResources{ResourceRules: []v1beta1.NamedRuleWithOperations{
MatchConstraints: &v1.MatchResources{ResourceRules: []v1.NamedRuleWithOperations{
{
RuleWithOperations: v1beta1.RuleWithOperations{
Rule: v1beta1.Rule{
RuleWithOperations: v1.RuleWithOperations{
Rule: v1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"deployments"},
@ -300,12 +300,12 @@ func TestTypeCheck(t *testing.T) {
for _, tc := range []struct {
name string
schemaToReturn *spec.Schema
policy *v1beta1.ValidatingAdmissionPolicy
policy *v1.ValidatingAdmissionPolicy
assertions []assertionFunc
}{
{
name: "empty",
policy: &v1beta1.ValidatingAdmissionPolicy{},
policy: &v1.ValidatingAdmissionPolicy{},
assertions: []assertionFunc{toBeEmpty},
},
{
@ -439,14 +439,14 @@ func TestTypeCheck(t *testing.T) {
},
{
name: "variables valid",
policy: &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
Variables: []v1beta1.Variable{
policy: &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
Variables: []v1.Variable{
{
Name: "works",
Expression: "true",
},
},
Validations: []v1beta1.Validation{
Validations: []v1.Validation{
{
Expression: "variables.works",
},
@ -466,14 +466,14 @@ func TestTypeCheck(t *testing.T) {
},
{
name: "variables missing field",
policy: &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
Variables: []v1beta1.Variable{
policy: &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
Variables: []v1.Variable{
{
Name: "works",
Expression: "true",
},
},
Validations: []v1beta1.Validation{
Validations: []v1.Validation{
{
Expression: "variables.nonExisting",
},
@ -497,14 +497,14 @@ func TestTypeCheck(t *testing.T) {
},
{
name: "variables field wrong type",
policy: &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
Variables: []v1beta1.Variable{
policy: &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
Variables: []v1.Variable{
{
Name: "name",
Expression: "'something'",
},
},
Validations: []v1beta1.Validation{
Validations: []v1.Validation{
{
Expression: "variables.name == object.foo", // foo is int64
},
@ -528,14 +528,14 @@ func TestTypeCheck(t *testing.T) {
},
{
name: "error in variables, not reported during type checking.",
policy: &v1beta1.ValidatingAdmissionPolicy{Spec: v1beta1.ValidatingAdmissionPolicySpec{
Variables: []v1beta1.Variable{
policy: &v1.ValidatingAdmissionPolicy{Spec: v1.ValidatingAdmissionPolicySpec{
Variables: []v1.Variable{
{
Name: "name",
Expression: "object.foo == 'str'",
},
},
Validations: []v1beta1.Validation{
Validations: []v1.Validation{
{
Expression: "variables.name == object.foo", // foo is int64
},
@ -593,14 +593,14 @@ func (r *fakeSchemaResolver) ResolveSchema(gvk schema.GroupVersionKind) (*spec.S
return r.schemaToReturn, nil
}
func toBeEmpty(warnings []v1beta1.ExpressionWarning, t *testing.T) {
func toBeEmpty(warnings []v1.ExpressionWarning, t *testing.T) {
if len(warnings) != 0 {
t.Fatalf("expected empty but got %v", warnings)
}
}
func toContain(substring string) func(warnings []v1beta1.ExpressionWarning, t *testing.T) {
return func(warnings []v1beta1.ExpressionWarning, t *testing.T) {
func toContain(substring string) func(warnings []v1.ExpressionWarning, t *testing.T) {
return func(warnings []v1.ExpressionWarning, t *testing.T) {
if len(warnings) == 0 {
t.Errorf("expected containing %q but got empty", substring)
}
@ -612,8 +612,8 @@ func toContain(substring string) func(warnings []v1beta1.ExpressionWarning, t *t
}
}
func toHaveLengthOf(expected int) func(warnings []v1beta1.ExpressionWarning, t *testing.T) {
return func(warnings []v1beta1.ExpressionWarning, t *testing.T) {
func toHaveLengthOf(expected int) func(warnings []v1.ExpressionWarning, t *testing.T) {
return func(warnings []v1.ExpressionWarning, t *testing.T) {
got := len(warnings)
if expected != got {
t.Errorf("expect warnings to have length of %d, but got %d", expected, got)
@ -621,8 +621,8 @@ func toHaveLengthOf(expected int) func(warnings []v1beta1.ExpressionWarning, t *
}
}
func toHaveFieldRef(paths ...string) func(warnings []v1beta1.ExpressionWarning, t *testing.T) {
return func(warnings []v1beta1.ExpressionWarning, t *testing.T) {
func toHaveFieldRef(paths ...string) func(warnings []v1.ExpressionWarning, t *testing.T) {
return func(warnings []v1.ExpressionWarning, t *testing.T) {
if len(paths) != len(warnings) {
t.Errorf("expect warnings to have length of %d, but got %d", len(paths), len(warnings))
}
@ -634,4 +634,4 @@ func toHaveFieldRef(paths ...string) func(warnings []v1beta1.ExpressionWarning,
}
}
type assertionFunc func(warnings []v1beta1.ExpressionWarning, t *testing.T)
type assertionFunc func(warnings []v1.ExpressionWarning, t *testing.T)

View File

@ -101,7 +101,10 @@ const (
// owner: @cici37 @jpbetz
// kep: http://kep.k8s.io/3488
// alpha: v1.26
// beta: v1.28
// stable: v1.30
//
// Note: the feature gate can be removed in 1.32
// Enables expression validation in Admission Control
ValidatingAdmissionPolicy featuregate.Feature = "ValidatingAdmissionPolicy"
@ -309,7 +312,7 @@ var defaultKubernetesFeatureGates = map[featuregate.Feature]featuregate.FeatureS
APIServingWithRoutine: {Default: true, PreRelease: featuregate.Beta},
ValidatingAdmissionPolicy: {Default: false, PreRelease: featuregate.Beta},
ValidatingAdmissionPolicy: {Default: true, PreRelease: featuregate.GA, LockToDefault: true}, // remove in 1.32
CustomResourceValidationExpressions: {Default: true, PreRelease: featuregate.GA, LockToDefault: true}, // remove in 1.31

View File

@ -19,12 +19,14 @@ package options
import (
"fmt"
"strings"
"time"
"github.com/spf13/pflag"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/sets"
utilwait "k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apiserver/pkg/admission"
"k8s.io/apiserver/pkg/admission/initializer"
admissionmetrics "k8s.io/apiserver/pkg/admission/metrics"
@ -36,9 +38,11 @@ import (
apiserverapiv1 "k8s.io/apiserver/pkg/apis/apiserver/v1"
apiserverapiv1alpha1 "k8s.io/apiserver/pkg/apis/apiserver/v1alpha1"
"k8s.io/apiserver/pkg/server"
cacheddiscovery "k8s.io/client-go/discovery/cached/memory"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/restmapper"
"k8s.io/component-base/featuregate"
)
@ -143,11 +147,24 @@ func (a *AdmissionOptions) ApplyTo(
return fmt.Errorf("failed to read plugin config: %v", err)
}
discoveryClient := cacheddiscovery.NewMemCacheClient(kubeClient.Discovery())
discoveryRESTMapper := restmapper.NewDeferredDiscoveryRESTMapper(discoveryClient)
genericInitializer := initializer.New(kubeClient, dynamicClient, informers, c.Authorization.Authorizer, features,
c.DrainedNotify())
c.DrainedNotify(), discoveryRESTMapper)
initializersChain := admission.PluginInitializers{genericInitializer}
initializersChain = append(initializersChain, pluginInitializers...)
admissionPostStartHook := func(context server.PostStartHookContext) error {
discoveryRESTMapper.Reset()
go utilwait.Until(discoveryRESTMapper.Reset, 30*time.Second, context.StopCh)
return nil
}
err = c.AddPostStartHook("start-apiserver-admission-initializer", admissionPostStartHook)
if err != nil {
return fmt.Errorf("failed to add post start hook for policy admission: %w", err)
}
admissionChain, err := a.Plugins.NewFromPlugins(pluginNames, pluginsConfigProvider, initializersChain, a.Decorators)
if err != nil {
return err

View File

@ -0,0 +1,48 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
// AuditAnnotationApplyConfiguration represents an declarative configuration of the AuditAnnotation type for use
// with apply.
type AuditAnnotationApplyConfiguration struct {
Key *string `json:"key,omitempty"`
ValueExpression *string `json:"valueExpression,omitempty"`
}
// AuditAnnotationApplyConfiguration constructs an declarative configuration of the AuditAnnotation type for use with
// apply.
func AuditAnnotation() *AuditAnnotationApplyConfiguration {
return &AuditAnnotationApplyConfiguration{}
}
// WithKey sets the Key field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Key field is set to the value of the last call.
func (b *AuditAnnotationApplyConfiguration) WithKey(value string) *AuditAnnotationApplyConfiguration {
b.Key = &value
return b
}
// WithValueExpression sets the ValueExpression field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ValueExpression field is set to the value of the last call.
func (b *AuditAnnotationApplyConfiguration) WithValueExpression(value string) *AuditAnnotationApplyConfiguration {
b.ValueExpression = &value
return b
}

View File

@ -0,0 +1,48 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
// ExpressionWarningApplyConfiguration represents an declarative configuration of the ExpressionWarning type for use
// with apply.
type ExpressionWarningApplyConfiguration struct {
FieldRef *string `json:"fieldRef,omitempty"`
Warning *string `json:"warning,omitempty"`
}
// ExpressionWarningApplyConfiguration constructs an declarative configuration of the ExpressionWarning type for use with
// apply.
func ExpressionWarning() *ExpressionWarningApplyConfiguration {
return &ExpressionWarningApplyConfiguration{}
}
// WithFieldRef sets the FieldRef field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the FieldRef field is set to the value of the last call.
func (b *ExpressionWarningApplyConfiguration) WithFieldRef(value string) *ExpressionWarningApplyConfiguration {
b.FieldRef = &value
return b
}
// WithWarning sets the Warning field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Warning field is set to the value of the last call.
func (b *ExpressionWarningApplyConfiguration) WithWarning(value string) *ExpressionWarningApplyConfiguration {
b.Warning = &value
return b
}

View File

@ -0,0 +1,90 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
import (
apiadmissionregistrationv1 "k8s.io/api/admissionregistration/v1"
v1 "k8s.io/client-go/applyconfigurations/meta/v1"
)
// MatchResourcesApplyConfiguration represents an declarative configuration of the MatchResources type for use
// with apply.
type MatchResourcesApplyConfiguration struct {
NamespaceSelector *v1.LabelSelectorApplyConfiguration `json:"namespaceSelector,omitempty"`
ObjectSelector *v1.LabelSelectorApplyConfiguration `json:"objectSelector,omitempty"`
ResourceRules []NamedRuleWithOperationsApplyConfiguration `json:"resourceRules,omitempty"`
ExcludeResourceRules []NamedRuleWithOperationsApplyConfiguration `json:"excludeResourceRules,omitempty"`
MatchPolicy *apiadmissionregistrationv1.MatchPolicyType `json:"matchPolicy,omitempty"`
}
// MatchResourcesApplyConfiguration constructs an declarative configuration of the MatchResources type for use with
// apply.
func MatchResources() *MatchResourcesApplyConfiguration {
return &MatchResourcesApplyConfiguration{}
}
// WithNamespaceSelector sets the NamespaceSelector field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the NamespaceSelector field is set to the value of the last call.
func (b *MatchResourcesApplyConfiguration) WithNamespaceSelector(value *v1.LabelSelectorApplyConfiguration) *MatchResourcesApplyConfiguration {
b.NamespaceSelector = value
return b
}
// WithObjectSelector sets the ObjectSelector field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ObjectSelector field is set to the value of the last call.
func (b *MatchResourcesApplyConfiguration) WithObjectSelector(value *v1.LabelSelectorApplyConfiguration) *MatchResourcesApplyConfiguration {
b.ObjectSelector = value
return b
}
// WithResourceRules adds the given value to the ResourceRules field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the ResourceRules field.
func (b *MatchResourcesApplyConfiguration) WithResourceRules(values ...*NamedRuleWithOperationsApplyConfiguration) *MatchResourcesApplyConfiguration {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithResourceRules")
}
b.ResourceRules = append(b.ResourceRules, *values[i])
}
return b
}
// WithExcludeResourceRules adds the given value to the ExcludeResourceRules field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the ExcludeResourceRules field.
func (b *MatchResourcesApplyConfiguration) WithExcludeResourceRules(values ...*NamedRuleWithOperationsApplyConfiguration) *MatchResourcesApplyConfiguration {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithExcludeResourceRules")
}
b.ExcludeResourceRules = append(b.ExcludeResourceRules, *values[i])
}
return b
}
// WithMatchPolicy sets the MatchPolicy field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the MatchPolicy field is set to the value of the last call.
func (b *MatchResourcesApplyConfiguration) WithMatchPolicy(value apiadmissionregistrationv1.MatchPolicyType) *MatchResourcesApplyConfiguration {
b.MatchPolicy = &value
return b
}

View File

@ -0,0 +1,94 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
import (
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
)
// NamedRuleWithOperationsApplyConfiguration represents an declarative configuration of the NamedRuleWithOperations type for use
// with apply.
type NamedRuleWithOperationsApplyConfiguration struct {
ResourceNames []string `json:"resourceNames,omitempty"`
RuleWithOperationsApplyConfiguration `json:",inline"`
}
// NamedRuleWithOperationsApplyConfiguration constructs an declarative configuration of the NamedRuleWithOperations type for use with
// apply.
func NamedRuleWithOperations() *NamedRuleWithOperationsApplyConfiguration {
return &NamedRuleWithOperationsApplyConfiguration{}
}
// WithResourceNames adds the given value to the ResourceNames field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the ResourceNames field.
func (b *NamedRuleWithOperationsApplyConfiguration) WithResourceNames(values ...string) *NamedRuleWithOperationsApplyConfiguration {
for i := range values {
b.ResourceNames = append(b.ResourceNames, values[i])
}
return b
}
// WithOperations adds the given value to the Operations field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the Operations field.
func (b *NamedRuleWithOperationsApplyConfiguration) WithOperations(values ...admissionregistrationv1.OperationType) *NamedRuleWithOperationsApplyConfiguration {
for i := range values {
b.Operations = append(b.Operations, values[i])
}
return b
}
// WithAPIGroups adds the given value to the APIGroups field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the APIGroups field.
func (b *NamedRuleWithOperationsApplyConfiguration) WithAPIGroups(values ...string) *NamedRuleWithOperationsApplyConfiguration {
for i := range values {
b.APIGroups = append(b.APIGroups, values[i])
}
return b
}
// WithAPIVersions adds the given value to the APIVersions field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the APIVersions field.
func (b *NamedRuleWithOperationsApplyConfiguration) WithAPIVersions(values ...string) *NamedRuleWithOperationsApplyConfiguration {
for i := range values {
b.APIVersions = append(b.APIVersions, values[i])
}
return b
}
// WithResources adds the given value to the Resources field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the Resources field.
func (b *NamedRuleWithOperationsApplyConfiguration) WithResources(values ...string) *NamedRuleWithOperationsApplyConfiguration {
for i := range values {
b.Resources = append(b.Resources, values[i])
}
return b
}
// WithScope sets the Scope field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Scope field is set to the value of the last call.
func (b *NamedRuleWithOperationsApplyConfiguration) WithScope(value admissionregistrationv1.ScopeType) *NamedRuleWithOperationsApplyConfiguration {
b.Scope = &value
return b
}

View File

@ -0,0 +1,48 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
// ParamKindApplyConfiguration represents an declarative configuration of the ParamKind type for use
// with apply.
type ParamKindApplyConfiguration struct {
APIVersion *string `json:"apiVersion,omitempty"`
Kind *string `json:"kind,omitempty"`
}
// ParamKindApplyConfiguration constructs an declarative configuration of the ParamKind type for use with
// apply.
func ParamKind() *ParamKindApplyConfiguration {
return &ParamKindApplyConfiguration{}
}
// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the APIVersion field is set to the value of the last call.
func (b *ParamKindApplyConfiguration) WithAPIVersion(value string) *ParamKindApplyConfiguration {
b.APIVersion = &value
return b
}
// WithKind sets the Kind field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Kind field is set to the value of the last call.
func (b *ParamKindApplyConfiguration) WithKind(value string) *ParamKindApplyConfiguration {
b.Kind = &value
return b
}

View File

@ -0,0 +1,71 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
import (
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
v1 "k8s.io/client-go/applyconfigurations/meta/v1"
)
// ParamRefApplyConfiguration represents an declarative configuration of the ParamRef type for use
// with apply.
type ParamRefApplyConfiguration struct {
Name *string `json:"name,omitempty"`
Namespace *string `json:"namespace,omitempty"`
Selector *v1.LabelSelectorApplyConfiguration `json:"selector,omitempty"`
ParameterNotFoundAction *admissionregistrationv1.ParameterNotFoundActionType `json:"parameterNotFoundAction,omitempty"`
}
// ParamRefApplyConfiguration constructs an declarative configuration of the ParamRef type for use with
// apply.
func ParamRef() *ParamRefApplyConfiguration {
return &ParamRefApplyConfiguration{}
}
// WithName sets the Name field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Name field is set to the value of the last call.
func (b *ParamRefApplyConfiguration) WithName(value string) *ParamRefApplyConfiguration {
b.Name = &value
return b
}
// WithNamespace sets the Namespace field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Namespace field is set to the value of the last call.
func (b *ParamRefApplyConfiguration) WithNamespace(value string) *ParamRefApplyConfiguration {
b.Namespace = &value
return b
}
// WithSelector sets the Selector field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Selector field is set to the value of the last call.
func (b *ParamRefApplyConfiguration) WithSelector(value *v1.LabelSelectorApplyConfiguration) *ParamRefApplyConfiguration {
b.Selector = value
return b
}
// WithParameterNotFoundAction sets the ParameterNotFoundAction field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ParameterNotFoundAction field is set to the value of the last call.
func (b *ParamRefApplyConfiguration) WithParameterNotFoundAction(value admissionregistrationv1.ParameterNotFoundActionType) *ParamRefApplyConfiguration {
b.ParameterNotFoundAction = &value
return b
}

View File

@ -0,0 +1,44 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
// TypeCheckingApplyConfiguration represents an declarative configuration of the TypeChecking type for use
// with apply.
type TypeCheckingApplyConfiguration struct {
ExpressionWarnings []ExpressionWarningApplyConfiguration `json:"expressionWarnings,omitempty"`
}
// TypeCheckingApplyConfiguration constructs an declarative configuration of the TypeChecking type for use with
// apply.
func TypeChecking() *TypeCheckingApplyConfiguration {
return &TypeCheckingApplyConfiguration{}
}
// WithExpressionWarnings adds the given value to the ExpressionWarnings field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the ExpressionWarnings field.
func (b *TypeCheckingApplyConfiguration) WithExpressionWarnings(values ...*ExpressionWarningApplyConfiguration) *TypeCheckingApplyConfiguration {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithExpressionWarnings")
}
b.ExpressionWarnings = append(b.ExpressionWarnings, *values[i])
}
return b
}

View File

@ -0,0 +1,256 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
import (
apiadmissionregistrationv1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
managedfields "k8s.io/apimachinery/pkg/util/managedfields"
internal "k8s.io/client-go/applyconfigurations/internal"
v1 "k8s.io/client-go/applyconfigurations/meta/v1"
)
// ValidatingAdmissionPolicyApplyConfiguration represents an declarative configuration of the ValidatingAdmissionPolicy type for use
// with apply.
type ValidatingAdmissionPolicyApplyConfiguration struct {
v1.TypeMetaApplyConfiguration `json:",inline"`
*v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"`
Spec *ValidatingAdmissionPolicySpecApplyConfiguration `json:"spec,omitempty"`
Status *ValidatingAdmissionPolicyStatusApplyConfiguration `json:"status,omitempty"`
}
// ValidatingAdmissionPolicy constructs an declarative configuration of the ValidatingAdmissionPolicy type for use with
// apply.
func ValidatingAdmissionPolicy(name string) *ValidatingAdmissionPolicyApplyConfiguration {
b := &ValidatingAdmissionPolicyApplyConfiguration{}
b.WithName(name)
b.WithKind("ValidatingAdmissionPolicy")
b.WithAPIVersion("admissionregistration.k8s.io/v1")
return b
}
// ExtractValidatingAdmissionPolicy extracts the applied configuration owned by fieldManager from
// validatingAdmissionPolicy. If no managedFields are found in validatingAdmissionPolicy for fieldManager, a
// ValidatingAdmissionPolicyApplyConfiguration is returned with only the Name, Namespace (if applicable),
// APIVersion and Kind populated. It is possible that no managed fields were found for because other
// field managers have taken ownership of all the fields previously owned by fieldManager, or because
// the fieldManager never owned fields any fields.
// validatingAdmissionPolicy must be a unmodified ValidatingAdmissionPolicy API object that was retrieved from the Kubernetes API.
// ExtractValidatingAdmissionPolicy provides a way to perform a extract/modify-in-place/apply workflow.
// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously
// applied if another fieldManager has updated or force applied any of the previously applied fields.
// Experimental!
func ExtractValidatingAdmissionPolicy(validatingAdmissionPolicy *apiadmissionregistrationv1.ValidatingAdmissionPolicy, fieldManager string) (*ValidatingAdmissionPolicyApplyConfiguration, error) {
return extractValidatingAdmissionPolicy(validatingAdmissionPolicy, fieldManager, "")
}
// ExtractValidatingAdmissionPolicyStatus is the same as ExtractValidatingAdmissionPolicy except
// that it extracts the status subresource applied configuration.
// Experimental!
func ExtractValidatingAdmissionPolicyStatus(validatingAdmissionPolicy *apiadmissionregistrationv1.ValidatingAdmissionPolicy, fieldManager string) (*ValidatingAdmissionPolicyApplyConfiguration, error) {
return extractValidatingAdmissionPolicy(validatingAdmissionPolicy, fieldManager, "status")
}
func extractValidatingAdmissionPolicy(validatingAdmissionPolicy *apiadmissionregistrationv1.ValidatingAdmissionPolicy, fieldManager string, subresource string) (*ValidatingAdmissionPolicyApplyConfiguration, error) {
b := &ValidatingAdmissionPolicyApplyConfiguration{}
err := managedfields.ExtractInto(validatingAdmissionPolicy, internal.Parser().Type("io.k8s.api.admissionregistration.v1.ValidatingAdmissionPolicy"), fieldManager, b, subresource)
if err != nil {
return nil, err
}
b.WithName(validatingAdmissionPolicy.Name)
b.WithKind("ValidatingAdmissionPolicy")
b.WithAPIVersion("admissionregistration.k8s.io/v1")
return b, nil
}
// WithKind sets the Kind field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Kind field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithKind(value string) *ValidatingAdmissionPolicyApplyConfiguration {
b.Kind = &value
return b
}
// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the APIVersion field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithAPIVersion(value string) *ValidatingAdmissionPolicyApplyConfiguration {
b.APIVersion = &value
return b
}
// WithName sets the Name field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Name field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithName(value string) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.Name = &value
return b
}
// WithGenerateName sets the GenerateName field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the GenerateName field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithGenerateName(value string) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.GenerateName = &value
return b
}
// WithNamespace sets the Namespace field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Namespace field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithNamespace(value string) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.Namespace = &value
return b
}
// WithUID sets the UID field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the UID field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithUID(value types.UID) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.UID = &value
return b
}
// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ResourceVersion field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithResourceVersion(value string) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.ResourceVersion = &value
return b
}
// WithGeneration sets the Generation field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Generation field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithGeneration(value int64) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.Generation = &value
return b
}
// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the CreationTimestamp field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.CreationTimestamp = &value
return b
}
// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the DeletionTimestamp field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.DeletionTimestamp = &value
return b
}
// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.DeletionGracePeriodSeconds = &value
return b
}
// WithLabels puts the entries into the Labels field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, the entries provided by each call will be put on the Labels field,
// overwriting an existing map entries in Labels field with the same key.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithLabels(entries map[string]string) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
if b.Labels == nil && len(entries) > 0 {
b.Labels = make(map[string]string, len(entries))
}
for k, v := range entries {
b.Labels[k] = v
}
return b
}
// WithAnnotations puts the entries into the Annotations field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, the entries provided by each call will be put on the Annotations field,
// overwriting an existing map entries in Annotations field with the same key.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithAnnotations(entries map[string]string) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
if b.Annotations == nil && len(entries) > 0 {
b.Annotations = make(map[string]string, len(entries))
}
for k, v := range entries {
b.Annotations[k] = v
}
return b
}
// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the OwnerReferences field.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
for i := range values {
if values[i] == nil {
panic("nil value passed to WithOwnerReferences")
}
b.OwnerReferences = append(b.OwnerReferences, *values[i])
}
return b
}
// WithFinalizers adds the given value to the Finalizers field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the Finalizers field.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithFinalizers(values ...string) *ValidatingAdmissionPolicyApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
for i := range values {
b.Finalizers = append(b.Finalizers, values[i])
}
return b
}
func (b *ValidatingAdmissionPolicyApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {
if b.ObjectMetaApplyConfiguration == nil {
b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{}
}
}
// WithSpec sets the Spec field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Spec field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithSpec(value *ValidatingAdmissionPolicySpecApplyConfiguration) *ValidatingAdmissionPolicyApplyConfiguration {
b.Spec = value
return b
}
// WithStatus sets the Status field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Status field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyApplyConfiguration) WithStatus(value *ValidatingAdmissionPolicyStatusApplyConfiguration) *ValidatingAdmissionPolicyApplyConfiguration {
b.Status = value
return b
}

View File

@ -0,0 +1,247 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
import (
apiadmissionregistrationv1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
managedfields "k8s.io/apimachinery/pkg/util/managedfields"
internal "k8s.io/client-go/applyconfigurations/internal"
v1 "k8s.io/client-go/applyconfigurations/meta/v1"
)
// ValidatingAdmissionPolicyBindingApplyConfiguration represents an declarative configuration of the ValidatingAdmissionPolicyBinding type for use
// with apply.
type ValidatingAdmissionPolicyBindingApplyConfiguration struct {
v1.TypeMetaApplyConfiguration `json:",inline"`
*v1.ObjectMetaApplyConfiguration `json:"metadata,omitempty"`
Spec *ValidatingAdmissionPolicyBindingSpecApplyConfiguration `json:"spec,omitempty"`
}
// ValidatingAdmissionPolicyBinding constructs an declarative configuration of the ValidatingAdmissionPolicyBinding type for use with
// apply.
func ValidatingAdmissionPolicyBinding(name string) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b := &ValidatingAdmissionPolicyBindingApplyConfiguration{}
b.WithName(name)
b.WithKind("ValidatingAdmissionPolicyBinding")
b.WithAPIVersion("admissionregistration.k8s.io/v1")
return b
}
// ExtractValidatingAdmissionPolicyBinding extracts the applied configuration owned by fieldManager from
// validatingAdmissionPolicyBinding. If no managedFields are found in validatingAdmissionPolicyBinding for fieldManager, a
// ValidatingAdmissionPolicyBindingApplyConfiguration is returned with only the Name, Namespace (if applicable),
// APIVersion and Kind populated. It is possible that no managed fields were found for because other
// field managers have taken ownership of all the fields previously owned by fieldManager, or because
// the fieldManager never owned fields any fields.
// validatingAdmissionPolicyBinding must be a unmodified ValidatingAdmissionPolicyBinding API object that was retrieved from the Kubernetes API.
// ExtractValidatingAdmissionPolicyBinding provides a way to perform a extract/modify-in-place/apply workflow.
// Note that an extracted apply configuration will contain fewer fields than what the fieldManager previously
// applied if another fieldManager has updated or force applied any of the previously applied fields.
// Experimental!
func ExtractValidatingAdmissionPolicyBinding(validatingAdmissionPolicyBinding *apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding, fieldManager string) (*ValidatingAdmissionPolicyBindingApplyConfiguration, error) {
return extractValidatingAdmissionPolicyBinding(validatingAdmissionPolicyBinding, fieldManager, "")
}
// ExtractValidatingAdmissionPolicyBindingStatus is the same as ExtractValidatingAdmissionPolicyBinding except
// that it extracts the status subresource applied configuration.
// Experimental!
func ExtractValidatingAdmissionPolicyBindingStatus(validatingAdmissionPolicyBinding *apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding, fieldManager string) (*ValidatingAdmissionPolicyBindingApplyConfiguration, error) {
return extractValidatingAdmissionPolicyBinding(validatingAdmissionPolicyBinding, fieldManager, "status")
}
func extractValidatingAdmissionPolicyBinding(validatingAdmissionPolicyBinding *apiadmissionregistrationv1.ValidatingAdmissionPolicyBinding, fieldManager string, subresource string) (*ValidatingAdmissionPolicyBindingApplyConfiguration, error) {
b := &ValidatingAdmissionPolicyBindingApplyConfiguration{}
err := managedfields.ExtractInto(validatingAdmissionPolicyBinding, internal.Parser().Type("io.k8s.api.admissionregistration.v1.ValidatingAdmissionPolicyBinding"), fieldManager, b, subresource)
if err != nil {
return nil, err
}
b.WithName(validatingAdmissionPolicyBinding.Name)
b.WithKind("ValidatingAdmissionPolicyBinding")
b.WithAPIVersion("admissionregistration.k8s.io/v1")
return b, nil
}
// WithKind sets the Kind field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Kind field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithKind(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.Kind = &value
return b
}
// WithAPIVersion sets the APIVersion field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the APIVersion field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithAPIVersion(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.APIVersion = &value
return b
}
// WithName sets the Name field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Name field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithName(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.Name = &value
return b
}
// WithGenerateName sets the GenerateName field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the GenerateName field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithGenerateName(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.GenerateName = &value
return b
}
// WithNamespace sets the Namespace field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Namespace field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithNamespace(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.Namespace = &value
return b
}
// WithUID sets the UID field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the UID field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithUID(value types.UID) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.UID = &value
return b
}
// WithResourceVersion sets the ResourceVersion field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ResourceVersion field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithResourceVersion(value string) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.ResourceVersion = &value
return b
}
// WithGeneration sets the Generation field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Generation field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithGeneration(value int64) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.Generation = &value
return b
}
// WithCreationTimestamp sets the CreationTimestamp field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the CreationTimestamp field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithCreationTimestamp(value metav1.Time) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.CreationTimestamp = &value
return b
}
// WithDeletionTimestamp sets the DeletionTimestamp field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the DeletionTimestamp field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithDeletionTimestamp(value metav1.Time) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.DeletionTimestamp = &value
return b
}
// WithDeletionGracePeriodSeconds sets the DeletionGracePeriodSeconds field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the DeletionGracePeriodSeconds field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithDeletionGracePeriodSeconds(value int64) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
b.DeletionGracePeriodSeconds = &value
return b
}
// WithLabels puts the entries into the Labels field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, the entries provided by each call will be put on the Labels field,
// overwriting an existing map entries in Labels field with the same key.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithLabels(entries map[string]string) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
if b.Labels == nil && len(entries) > 0 {
b.Labels = make(map[string]string, len(entries))
}
for k, v := range entries {
b.Labels[k] = v
}
return b
}
// WithAnnotations puts the entries into the Annotations field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, the entries provided by each call will be put on the Annotations field,
// overwriting an existing map entries in Annotations field with the same key.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithAnnotations(entries map[string]string) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
if b.Annotations == nil && len(entries) > 0 {
b.Annotations = make(map[string]string, len(entries))
}
for k, v := range entries {
b.Annotations[k] = v
}
return b
}
// WithOwnerReferences adds the given value to the OwnerReferences field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the OwnerReferences field.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithOwnerReferences(values ...*v1.OwnerReferenceApplyConfiguration) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
for i := range values {
if values[i] == nil {
panic("nil value passed to WithOwnerReferences")
}
b.OwnerReferences = append(b.OwnerReferences, *values[i])
}
return b
}
// WithFinalizers adds the given value to the Finalizers field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the Finalizers field.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithFinalizers(values ...string) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.ensureObjectMetaApplyConfigurationExists()
for i := range values {
b.Finalizers = append(b.Finalizers, values[i])
}
return b
}
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) ensureObjectMetaApplyConfigurationExists() {
if b.ObjectMetaApplyConfiguration == nil {
b.ObjectMetaApplyConfiguration = &v1.ObjectMetaApplyConfiguration{}
}
}
// WithSpec sets the Spec field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Spec field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingApplyConfiguration) WithSpec(value *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) *ValidatingAdmissionPolicyBindingApplyConfiguration {
b.Spec = value
return b
}

View File

@ -0,0 +1,72 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
import (
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
)
// ValidatingAdmissionPolicyBindingSpecApplyConfiguration represents an declarative configuration of the ValidatingAdmissionPolicyBindingSpec type for use
// with apply.
type ValidatingAdmissionPolicyBindingSpecApplyConfiguration struct {
PolicyName *string `json:"policyName,omitempty"`
ParamRef *ParamRefApplyConfiguration `json:"paramRef,omitempty"`
MatchResources *MatchResourcesApplyConfiguration `json:"matchResources,omitempty"`
ValidationActions []admissionregistrationv1.ValidationAction `json:"validationActions,omitempty"`
}
// ValidatingAdmissionPolicyBindingSpecApplyConfiguration constructs an declarative configuration of the ValidatingAdmissionPolicyBindingSpec type for use with
// apply.
func ValidatingAdmissionPolicyBindingSpec() *ValidatingAdmissionPolicyBindingSpecApplyConfiguration {
return &ValidatingAdmissionPolicyBindingSpecApplyConfiguration{}
}
// WithPolicyName sets the PolicyName field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the PolicyName field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithPolicyName(value string) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration {
b.PolicyName = &value
return b
}
// WithParamRef sets the ParamRef field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ParamRef field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithParamRef(value *ParamRefApplyConfiguration) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration {
b.ParamRef = value
return b
}
// WithMatchResources sets the MatchResources field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the MatchResources field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithMatchResources(value *MatchResourcesApplyConfiguration) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration {
b.MatchResources = value
return b
}
// WithValidationActions adds the given value to the ValidationActions field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the ValidationActions field.
func (b *ValidatingAdmissionPolicyBindingSpecApplyConfiguration) WithValidationActions(values ...admissionregistrationv1.ValidationAction) *ValidatingAdmissionPolicyBindingSpecApplyConfiguration {
for i := range values {
b.ValidationActions = append(b.ValidationActions, values[i])
}
return b
}

View File

@ -0,0 +1,117 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
import (
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
)
// ValidatingAdmissionPolicySpecApplyConfiguration represents an declarative configuration of the ValidatingAdmissionPolicySpec type for use
// with apply.
type ValidatingAdmissionPolicySpecApplyConfiguration struct {
ParamKind *ParamKindApplyConfiguration `json:"paramKind,omitempty"`
MatchConstraints *MatchResourcesApplyConfiguration `json:"matchConstraints,omitempty"`
Validations []ValidationApplyConfiguration `json:"validations,omitempty"`
FailurePolicy *admissionregistrationv1.FailurePolicyType `json:"failurePolicy,omitempty"`
AuditAnnotations []AuditAnnotationApplyConfiguration `json:"auditAnnotations,omitempty"`
MatchConditions []MatchConditionApplyConfiguration `json:"matchConditions,omitempty"`
Variables []VariableApplyConfiguration `json:"variables,omitempty"`
}
// ValidatingAdmissionPolicySpecApplyConfiguration constructs an declarative configuration of the ValidatingAdmissionPolicySpec type for use with
// apply.
func ValidatingAdmissionPolicySpec() *ValidatingAdmissionPolicySpecApplyConfiguration {
return &ValidatingAdmissionPolicySpecApplyConfiguration{}
}
// WithParamKind sets the ParamKind field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ParamKind field is set to the value of the last call.
func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithParamKind(value *ParamKindApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {
b.ParamKind = value
return b
}
// WithMatchConstraints sets the MatchConstraints field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the MatchConstraints field is set to the value of the last call.
func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithMatchConstraints(value *MatchResourcesApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {
b.MatchConstraints = value
return b
}
// WithValidations adds the given value to the Validations field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the Validations field.
func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithValidations(values ...*ValidationApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithValidations")
}
b.Validations = append(b.Validations, *values[i])
}
return b
}
// WithFailurePolicy sets the FailurePolicy field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the FailurePolicy field is set to the value of the last call.
func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithFailurePolicy(value admissionregistrationv1.FailurePolicyType) *ValidatingAdmissionPolicySpecApplyConfiguration {
b.FailurePolicy = &value
return b
}
// WithAuditAnnotations adds the given value to the AuditAnnotations field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the AuditAnnotations field.
func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithAuditAnnotations(values ...*AuditAnnotationApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithAuditAnnotations")
}
b.AuditAnnotations = append(b.AuditAnnotations, *values[i])
}
return b
}
// WithMatchConditions adds the given value to the MatchConditions field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the MatchConditions field.
func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithMatchConditions(values ...*MatchConditionApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithMatchConditions")
}
b.MatchConditions = append(b.MatchConditions, *values[i])
}
return b
}
// WithVariables adds the given value to the Variables field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the Variables field.
func (b *ValidatingAdmissionPolicySpecApplyConfiguration) WithVariables(values ...*VariableApplyConfiguration) *ValidatingAdmissionPolicySpecApplyConfiguration {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithVariables")
}
b.Variables = append(b.Variables, *values[i])
}
return b
}

View File

@ -0,0 +1,66 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
import (
metav1 "k8s.io/client-go/applyconfigurations/meta/v1"
)
// ValidatingAdmissionPolicyStatusApplyConfiguration represents an declarative configuration of the ValidatingAdmissionPolicyStatus type for use
// with apply.
type ValidatingAdmissionPolicyStatusApplyConfiguration struct {
ObservedGeneration *int64 `json:"observedGeneration,omitempty"`
TypeChecking *TypeCheckingApplyConfiguration `json:"typeChecking,omitempty"`
Conditions []metav1.ConditionApplyConfiguration `json:"conditions,omitempty"`
}
// ValidatingAdmissionPolicyStatusApplyConfiguration constructs an declarative configuration of the ValidatingAdmissionPolicyStatus type for use with
// apply.
func ValidatingAdmissionPolicyStatus() *ValidatingAdmissionPolicyStatusApplyConfiguration {
return &ValidatingAdmissionPolicyStatusApplyConfiguration{}
}
// WithObservedGeneration sets the ObservedGeneration field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the ObservedGeneration field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyStatusApplyConfiguration) WithObservedGeneration(value int64) *ValidatingAdmissionPolicyStatusApplyConfiguration {
b.ObservedGeneration = &value
return b
}
// WithTypeChecking sets the TypeChecking field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the TypeChecking field is set to the value of the last call.
func (b *ValidatingAdmissionPolicyStatusApplyConfiguration) WithTypeChecking(value *TypeCheckingApplyConfiguration) *ValidatingAdmissionPolicyStatusApplyConfiguration {
b.TypeChecking = value
return b
}
// WithConditions adds the given value to the Conditions field in the declarative configuration
// and returns the receiver, so that objects can be build by chaining "With" function invocations.
// If called multiple times, values provided by each call will be appended to the Conditions field.
func (b *ValidatingAdmissionPolicyStatusApplyConfiguration) WithConditions(values ...*metav1.ConditionApplyConfiguration) *ValidatingAdmissionPolicyStatusApplyConfiguration {
for i := range values {
if values[i] == nil {
panic("nil value passed to WithConditions")
}
b.Conditions = append(b.Conditions, *values[i])
}
return b
}

View File

@ -0,0 +1,70 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
import (
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// ValidationApplyConfiguration represents an declarative configuration of the Validation type for use
// with apply.
type ValidationApplyConfiguration struct {
Expression *string `json:"expression,omitempty"`
Message *string `json:"message,omitempty"`
Reason *v1.StatusReason `json:"reason,omitempty"`
MessageExpression *string `json:"messageExpression,omitempty"`
}
// ValidationApplyConfiguration constructs an declarative configuration of the Validation type for use with
// apply.
func Validation() *ValidationApplyConfiguration {
return &ValidationApplyConfiguration{}
}
// WithExpression sets the Expression field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Expression field is set to the value of the last call.
func (b *ValidationApplyConfiguration) WithExpression(value string) *ValidationApplyConfiguration {
b.Expression = &value
return b
}
// WithMessage sets the Message field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Message field is set to the value of the last call.
func (b *ValidationApplyConfiguration) WithMessage(value string) *ValidationApplyConfiguration {
b.Message = &value
return b
}
// WithReason sets the Reason field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Reason field is set to the value of the last call.
func (b *ValidationApplyConfiguration) WithReason(value v1.StatusReason) *ValidationApplyConfiguration {
b.Reason = &value
return b
}
// WithMessageExpression sets the MessageExpression field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the MessageExpression field is set to the value of the last call.
func (b *ValidationApplyConfiguration) WithMessageExpression(value string) *ValidationApplyConfiguration {
b.MessageExpression = &value
return b
}

View File

@ -0,0 +1,48 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by applyconfiguration-gen. DO NOT EDIT.
package v1
// VariableApplyConfiguration represents an declarative configuration of the Variable type for use
// with apply.
type VariableApplyConfiguration struct {
Name *string `json:"name,omitempty"`
Expression *string `json:"expression,omitempty"`
}
// VariableApplyConfiguration constructs an declarative configuration of the Variable type for use with
// apply.
func Variable() *VariableApplyConfiguration {
return &VariableApplyConfiguration{}
}
// WithName sets the Name field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Name field is set to the value of the last call.
func (b *VariableApplyConfiguration) WithName(value string) *VariableApplyConfiguration {
b.Name = &value
return b
}
// WithExpression sets the Expression field in the declarative configuration to the given value
// and returns the receiver, so that objects can be built by chaining "With" function invocations.
// If called multiple times, the Expression field is set to the value of the last call.
func (b *VariableApplyConfiguration) WithExpression(value string) *VariableApplyConfiguration {
b.Expression = &value
return b
}

View File

@ -39,6 +39,28 @@ func Parser() *typed.Parser {
var parserOnce sync.Once
var parser *typed.Parser
var schemaYAML = typed.YAMLObject(`types:
- name: io.k8s.api.admissionregistration.v1.AuditAnnotation
map:
fields:
- name: key
type:
scalar: string
default: ""
- name: valueExpression
type:
scalar: string
default: ""
- name: io.k8s.api.admissionregistration.v1.ExpressionWarning
map:
fields:
- name: fieldRef
type:
scalar: string
default: ""
- name: warning
type:
scalar: string
default: ""
- name: io.k8s.api.admissionregistration.v1.MatchCondition
map:
fields:
@ -50,6 +72,31 @@ var schemaYAML = typed.YAMLObject(`types:
type:
scalar: string
default: ""
- name: io.k8s.api.admissionregistration.v1.MatchResources
map:
fields:
- name: excludeResourceRules
type:
list:
elementType:
namedType: io.k8s.api.admissionregistration.v1.NamedRuleWithOperations
elementRelationship: atomic
- name: matchPolicy
type:
scalar: string
- name: namespaceSelector
type:
namedType: io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector
- name: objectSelector
type:
namedType: io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector
- name: resourceRules
type:
list:
elementType:
namedType: io.k8s.api.admissionregistration.v1.NamedRuleWithOperations
elementRelationship: atomic
elementRelationship: atomic
- name: io.k8s.api.admissionregistration.v1.MutatingWebhook
map:
fields:
@ -123,6 +170,69 @@ var schemaYAML = typed.YAMLObject(`types:
elementRelationship: associative
keys:
- name
- name: io.k8s.api.admissionregistration.v1.NamedRuleWithOperations
map:
fields:
- name: apiGroups
type:
list:
elementType:
scalar: string
elementRelationship: atomic
- name: apiVersions
type:
list:
elementType:
scalar: string
elementRelationship: atomic
- name: operations
type:
list:
elementType:
scalar: string
elementRelationship: atomic
- name: resourceNames
type:
list:
elementType:
scalar: string
elementRelationship: atomic
- name: resources
type:
list:
elementType:
scalar: string
elementRelationship: atomic
- name: scope
type:
scalar: string
elementRelationship: atomic
- name: io.k8s.api.admissionregistration.v1.ParamKind
map:
fields:
- name: apiVersion
type:
scalar: string
- name: kind
type:
scalar: string
elementRelationship: atomic
- name: io.k8s.api.admissionregistration.v1.ParamRef
map:
fields:
- name: name
type:
scalar: string
- name: namespace
type:
scalar: string
- name: parameterNotFoundAction
type:
scalar: string
- name: selector
type:
namedType: io.k8s.apimachinery.pkg.apis.meta.v1.LabelSelector
elementRelationship: atomic
- name: io.k8s.api.admissionregistration.v1.RuleWithOperations
map:
fields:
@ -170,6 +280,128 @@ var schemaYAML = typed.YAMLObject(`types:
- name: port
type:
scalar: numeric
- name: io.k8s.api.admissionregistration.v1.TypeChecking
map:
fields:
- name: expressionWarnings
type:
list:
elementType:
namedType: io.k8s.api.admissionregistration.v1.ExpressionWarning
elementRelationship: atomic
- name: io.k8s.api.admissionregistration.v1.ValidatingAdmissionPolicy
map:
fields:
- name: apiVersion
type:
scalar: string
- name: kind
type:
scalar: string
- name: metadata
type:
namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta
default: {}
- name: spec
type:
namedType: io.k8s.api.admissionregistration.v1.ValidatingAdmissionPolicySpec
default: {}
- name: status
type:
namedType: io.k8s.api.admissionregistration.v1.ValidatingAdmissionPolicyStatus
default: {}
- name: io.k8s.api.admissionregistration.v1.ValidatingAdmissionPolicyBinding
map:
fields:
- name: apiVersion
type:
scalar: string
- name: kind
type:
scalar: string
- name: metadata
type:
namedType: io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta
default: {}
- name: spec
type:
namedType: io.k8s.api.admissionregistration.v1.ValidatingAdmissionPolicyBindingSpec
default: {}
- name: io.k8s.api.admissionregistration.v1.ValidatingAdmissionPolicyBindingSpec
map:
fields:
- name: matchResources
type:
namedType: io.k8s.api.admissionregistration.v1.MatchResources
- name: paramRef
type:
namedType: io.k8s.api.admissionregistration.v1.ParamRef
- name: policyName
type:
scalar: string
- name: validationActions
type:
list:
elementType:
scalar: string
elementRelationship: associative
- name: io.k8s.api.admissionregistration.v1.ValidatingAdmissionPolicySpec
map:
fields:
- name: auditAnnotations
type:
list:
elementType:
namedType: io.k8s.api.admissionregistration.v1.AuditAnnotation
elementRelationship: atomic
- name: failurePolicy
type:
scalar: string
- name: matchConditions
type:
list:
elementType:
namedType: io.k8s.api.admissionregistration.v1.MatchCondition
elementRelationship: associative
keys:
- name
- name: matchConstraints
type:
namedType: io.k8s.api.admissionregistration.v1.MatchResources
- name: paramKind
type:
namedType: io.k8s.api.admissionregistration.v1.ParamKind
- name: validations
type:
list:
elementType:
namedType: io.k8s.api.admissionregistration.v1.Validation
elementRelationship: atomic
- name: variables
type:
list:
elementType:
namedType: io.k8s.api.admissionregistration.v1.Variable
elementRelationship: associative
keys:
- name
- name: io.k8s.api.admissionregistration.v1.ValidatingAdmissionPolicyStatus
map:
fields:
- name: conditions
type:
list:
elementType:
namedType: io.k8s.apimachinery.pkg.apis.meta.v1.Condition
elementRelationship: associative
keys:
- type
- name: observedGeneration
type:
scalar: numeric
- name: typeChecking
type:
namedType: io.k8s.api.admissionregistration.v1.TypeChecking
- name: io.k8s.api.admissionregistration.v1.ValidatingWebhook
map:
fields:
@ -240,6 +472,34 @@ var schemaYAML = typed.YAMLObject(`types:
elementRelationship: associative
keys:
- name
- name: io.k8s.api.admissionregistration.v1.Validation
map:
fields:
- name: expression
type:
scalar: string
default: ""
- name: message
type:
scalar: string
- name: messageExpression
type:
scalar: string
- name: reason
type:
scalar: string
- name: io.k8s.api.admissionregistration.v1.Variable
map:
fields:
- name: expression
type:
scalar: string
default: ""
- name: name
type:
scalar: string
default: ""
elementRelationship: atomic
- name: io.k8s.api.admissionregistration.v1.WebhookClientConfig
map:
fields:

View File

@ -123,22 +123,50 @@ import (
func ForKind(kind schema.GroupVersionKind) interface{} {
switch kind {
// Group=admissionregistration.k8s.io, Version=v1
case v1.SchemeGroupVersion.WithKind("AuditAnnotation"):
return &admissionregistrationv1.AuditAnnotationApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("ExpressionWarning"):
return &admissionregistrationv1.ExpressionWarningApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("MatchCondition"):
return &admissionregistrationv1.MatchConditionApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("MatchResources"):
return &admissionregistrationv1.MatchResourcesApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("MutatingWebhook"):
return &admissionregistrationv1.MutatingWebhookApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("MutatingWebhookConfiguration"):
return &admissionregistrationv1.MutatingWebhookConfigurationApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("NamedRuleWithOperations"):
return &admissionregistrationv1.NamedRuleWithOperationsApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("ParamKind"):
return &admissionregistrationv1.ParamKindApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("ParamRef"):
return &admissionregistrationv1.ParamRefApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("Rule"):
return &admissionregistrationv1.RuleApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("RuleWithOperations"):
return &admissionregistrationv1.RuleWithOperationsApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("ServiceReference"):
return &admissionregistrationv1.ServiceReferenceApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("TypeChecking"):
return &admissionregistrationv1.TypeCheckingApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("ValidatingAdmissionPolicy"):
return &admissionregistrationv1.ValidatingAdmissionPolicyApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("ValidatingAdmissionPolicyBinding"):
return &admissionregistrationv1.ValidatingAdmissionPolicyBindingApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("ValidatingAdmissionPolicyBindingSpec"):
return &admissionregistrationv1.ValidatingAdmissionPolicyBindingSpecApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("ValidatingAdmissionPolicySpec"):
return &admissionregistrationv1.ValidatingAdmissionPolicySpecApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("ValidatingAdmissionPolicyStatus"):
return &admissionregistrationv1.ValidatingAdmissionPolicyStatusApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("ValidatingWebhook"):
return &admissionregistrationv1.ValidatingWebhookApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("ValidatingWebhookConfiguration"):
return &admissionregistrationv1.ValidatingWebhookConfigurationApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("Validation"):
return &admissionregistrationv1.ValidationApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("Variable"):
return &admissionregistrationv1.VariableApplyConfiguration{}
case v1.SchemeGroupVersion.WithKind("WebhookClientConfig"):
return &admissionregistrationv1.WebhookClientConfigApplyConfiguration{}

View File

@ -26,6 +26,10 @@ import (
type Interface interface {
// MutatingWebhookConfigurations returns a MutatingWebhookConfigurationInformer.
MutatingWebhookConfigurations() MutatingWebhookConfigurationInformer
// ValidatingAdmissionPolicies returns a ValidatingAdmissionPolicyInformer.
ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInformer
// ValidatingAdmissionPolicyBindings returns a ValidatingAdmissionPolicyBindingInformer.
ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInformer
// ValidatingWebhookConfigurations returns a ValidatingWebhookConfigurationInformer.
ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInformer
}
@ -46,6 +50,16 @@ func (v *version) MutatingWebhookConfigurations() MutatingWebhookConfigurationIn
return &mutatingWebhookConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}
}
// ValidatingAdmissionPolicies returns a ValidatingAdmissionPolicyInformer.
func (v *version) ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInformer {
return &validatingAdmissionPolicyInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}
}
// ValidatingAdmissionPolicyBindings returns a ValidatingAdmissionPolicyBindingInformer.
func (v *version) ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInformer {
return &validatingAdmissionPolicyBindingInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}
}
// ValidatingWebhookConfigurations returns a ValidatingWebhookConfigurationInformer.
func (v *version) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInformer {
return &validatingWebhookConfigurationInformer{factory: v.factory, tweakListOptions: v.tweakListOptions}

View File

@ -0,0 +1,89 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package v1
import (
"context"
time "time"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
watch "k8s.io/apimachinery/pkg/watch"
internalinterfaces "k8s.io/client-go/informers/internalinterfaces"
kubernetes "k8s.io/client-go/kubernetes"
v1 "k8s.io/client-go/listers/admissionregistration/v1"
cache "k8s.io/client-go/tools/cache"
)
// ValidatingAdmissionPolicyInformer provides access to a shared informer and lister for
// ValidatingAdmissionPolicies.
type ValidatingAdmissionPolicyInformer interface {
Informer() cache.SharedIndexInformer
Lister() v1.ValidatingAdmissionPolicyLister
}
type validatingAdmissionPolicyInformer struct {
factory internalinterfaces.SharedInformerFactory
tweakListOptions internalinterfaces.TweakListOptionsFunc
}
// NewValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredValidatingAdmissionPolicyInformer(client, resyncPeriod, indexers, nil)
}
// NewFilteredValidatingAdmissionPolicyInformer constructs a new informer for ValidatingAdmissionPolicy type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredValidatingAdmissionPolicyInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().List(context.TODO(), options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Watch(context.TODO(), options)
},
},
&admissionregistrationv1.ValidatingAdmissionPolicy{},
resyncPeriod,
indexers,
)
}
func (f *validatingAdmissionPolicyInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
return NewFilteredValidatingAdmissionPolicyInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}
func (f *validatingAdmissionPolicyInformer) Informer() cache.SharedIndexInformer {
return f.factory.InformerFor(&admissionregistrationv1.ValidatingAdmissionPolicy{}, f.defaultInformer)
}
func (f *validatingAdmissionPolicyInformer) Lister() v1.ValidatingAdmissionPolicyLister {
return v1.NewValidatingAdmissionPolicyLister(f.Informer().GetIndexer())
}

View File

@ -0,0 +1,89 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by informer-gen. DO NOT EDIT.
package v1
import (
"context"
time "time"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
watch "k8s.io/apimachinery/pkg/watch"
internalinterfaces "k8s.io/client-go/informers/internalinterfaces"
kubernetes "k8s.io/client-go/kubernetes"
v1 "k8s.io/client-go/listers/admissionregistration/v1"
cache "k8s.io/client-go/tools/cache"
)
// ValidatingAdmissionPolicyBindingInformer provides access to a shared informer and lister for
// ValidatingAdmissionPolicyBindings.
type ValidatingAdmissionPolicyBindingInformer interface {
Informer() cache.SharedIndexInformer
Lister() v1.ValidatingAdmissionPolicyBindingLister
}
type validatingAdmissionPolicyBindingInformer struct {
factory internalinterfaces.SharedInformerFactory
tweakListOptions internalinterfaces.TweakListOptionsFunc
}
// NewValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredValidatingAdmissionPolicyBindingInformer(client, resyncPeriod, indexers, nil)
}
// NewFilteredValidatingAdmissionPolicyBindingInformer constructs a new informer for ValidatingAdmissionPolicyBinding type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredValidatingAdmissionPolicyBindingInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().List(context.TODO(), options)
},
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().Watch(context.TODO(), options)
},
},
&admissionregistrationv1.ValidatingAdmissionPolicyBinding{},
resyncPeriod,
indexers,
)
}
func (f *validatingAdmissionPolicyBindingInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
return NewFilteredValidatingAdmissionPolicyBindingInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}
func (f *validatingAdmissionPolicyBindingInformer) Informer() cache.SharedIndexInformer {
return f.factory.InformerFor(&admissionregistrationv1.ValidatingAdmissionPolicyBinding{}, f.defaultInformer)
}
func (f *validatingAdmissionPolicyBindingInformer) Lister() v1.ValidatingAdmissionPolicyBindingLister {
return v1.NewValidatingAdmissionPolicyBindingLister(f.Informer().GetIndexer())
}

View File

@ -100,6 +100,10 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource
// Group=admissionregistration.k8s.io, Version=v1
case v1.SchemeGroupVersion.WithResource("mutatingwebhookconfigurations"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Admissionregistration().V1().MutatingWebhookConfigurations().Informer()}, nil
case v1.SchemeGroupVersion.WithResource("validatingadmissionpolicies"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Admissionregistration().V1().ValidatingAdmissionPolicies().Informer()}, nil
case v1.SchemeGroupVersion.WithResource("validatingadmissionpolicybindings"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Admissionregistration().V1().ValidatingAdmissionPolicyBindings().Informer()}, nil
case v1.SchemeGroupVersion.WithResource("validatingwebhookconfigurations"):
return &genericInformer{resource: resource.GroupResource(), informer: f.Admissionregistration().V1().ValidatingWebhookConfigurations().Informer()}, nil

View File

@ -29,6 +29,8 @@ import (
type AdmissionregistrationV1Interface interface {
RESTClient() rest.Interface
MutatingWebhookConfigurationsGetter
ValidatingAdmissionPoliciesGetter
ValidatingAdmissionPolicyBindingsGetter
ValidatingWebhookConfigurationsGetter
}
@ -41,6 +43,14 @@ func (c *AdmissionregistrationV1Client) MutatingWebhookConfigurations() Mutating
return newMutatingWebhookConfigurations(c)
}
func (c *AdmissionregistrationV1Client) ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInterface {
return newValidatingAdmissionPolicies(c)
}
func (c *AdmissionregistrationV1Client) ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInterface {
return newValidatingAdmissionPolicyBindings(c)
}
func (c *AdmissionregistrationV1Client) ValidatingWebhookConfigurations() ValidatingWebhookConfigurationInterface {
return newValidatingWebhookConfigurations(c)
}

View File

@ -32,6 +32,14 @@ func (c *FakeAdmissionregistrationV1) MutatingWebhookConfigurations() v1.Mutatin
return &FakeMutatingWebhookConfigurations{c}
}
func (c *FakeAdmissionregistrationV1) ValidatingAdmissionPolicies() v1.ValidatingAdmissionPolicyInterface {
return &FakeValidatingAdmissionPolicies{c}
}
func (c *FakeAdmissionregistrationV1) ValidatingAdmissionPolicyBindings() v1.ValidatingAdmissionPolicyBindingInterface {
return &FakeValidatingAdmissionPolicyBindings{c}
}
func (c *FakeAdmissionregistrationV1) ValidatingWebhookConfigurations() v1.ValidatingWebhookConfigurationInterface {
return &FakeValidatingWebhookConfigurations{c}
}

View File

@ -0,0 +1,178 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
"context"
json "encoding/json"
"fmt"
v1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
admissionregistrationv1 "k8s.io/client-go/applyconfigurations/admissionregistration/v1"
testing "k8s.io/client-go/testing"
)
// FakeValidatingAdmissionPolicies implements ValidatingAdmissionPolicyInterface
type FakeValidatingAdmissionPolicies struct {
Fake *FakeAdmissionregistrationV1
}
var validatingadmissionpoliciesResource = v1.SchemeGroupVersion.WithResource("validatingadmissionpolicies")
var validatingadmissionpoliciesKind = v1.SchemeGroupVersion.WithKind("ValidatingAdmissionPolicy")
// Get takes name of the validatingAdmissionPolicy, and returns the corresponding validatingAdmissionPolicy object, and an error if there is any.
func (c *FakeValidatingAdmissionPolicies) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ValidatingAdmissionPolicy, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootGetAction(validatingadmissionpoliciesResource, name), &v1.ValidatingAdmissionPolicy{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicy), err
}
// List takes label and field selectors, and returns the list of ValidatingAdmissionPolicies that match those selectors.
func (c *FakeValidatingAdmissionPolicies) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ValidatingAdmissionPolicyList, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootListAction(validatingadmissionpoliciesResource, validatingadmissionpoliciesKind, opts), &v1.ValidatingAdmissionPolicyList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v1.ValidatingAdmissionPolicyList{ListMeta: obj.(*v1.ValidatingAdmissionPolicyList).ListMeta}
for _, item := range obj.(*v1.ValidatingAdmissionPolicyList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested validatingAdmissionPolicies.
func (c *FakeValidatingAdmissionPolicies) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewRootWatchAction(validatingadmissionpoliciesResource, opts))
}
// Create takes the representation of a validatingAdmissionPolicy and creates it. Returns the server's representation of the validatingAdmissionPolicy, and an error, if there is any.
func (c *FakeValidatingAdmissionPolicies) Create(ctx context.Context, validatingAdmissionPolicy *v1.ValidatingAdmissionPolicy, opts metav1.CreateOptions) (result *v1.ValidatingAdmissionPolicy, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootCreateAction(validatingadmissionpoliciesResource, validatingAdmissionPolicy), &v1.ValidatingAdmissionPolicy{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicy), err
}
// Update takes the representation of a validatingAdmissionPolicy and updates it. Returns the server's representation of the validatingAdmissionPolicy, and an error, if there is any.
func (c *FakeValidatingAdmissionPolicies) Update(ctx context.Context, validatingAdmissionPolicy *v1.ValidatingAdmissionPolicy, opts metav1.UpdateOptions) (result *v1.ValidatingAdmissionPolicy, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootUpdateAction(validatingadmissionpoliciesResource, validatingAdmissionPolicy), &v1.ValidatingAdmissionPolicy{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicy), err
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeValidatingAdmissionPolicies) UpdateStatus(ctx context.Context, validatingAdmissionPolicy *v1.ValidatingAdmissionPolicy, opts metav1.UpdateOptions) (*v1.ValidatingAdmissionPolicy, error) {
obj, err := c.Fake.
Invokes(testing.NewRootUpdateSubresourceAction(validatingadmissionpoliciesResource, "status", validatingAdmissionPolicy), &v1.ValidatingAdmissionPolicy{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicy), err
}
// Delete takes name of the validatingAdmissionPolicy and deletes it. Returns an error if one occurs.
func (c *FakeValidatingAdmissionPolicies) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewRootDeleteActionWithOptions(validatingadmissionpoliciesResource, name, opts), &v1.ValidatingAdmissionPolicy{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeValidatingAdmissionPolicies) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {
action := testing.NewRootDeleteCollectionAction(validatingadmissionpoliciesResource, listOpts)
_, err := c.Fake.Invokes(action, &v1.ValidatingAdmissionPolicyList{})
return err
}
// Patch applies the patch and returns the patched validatingAdmissionPolicy.
func (c *FakeValidatingAdmissionPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ValidatingAdmissionPolicy, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootPatchSubresourceAction(validatingadmissionpoliciesResource, name, pt, data, subresources...), &v1.ValidatingAdmissionPolicy{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicy), err
}
// Apply takes the given apply declarative configuration, applies it and returns the applied validatingAdmissionPolicy.
func (c *FakeValidatingAdmissionPolicies) Apply(ctx context.Context, validatingAdmissionPolicy *admissionregistrationv1.ValidatingAdmissionPolicyApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ValidatingAdmissionPolicy, err error) {
if validatingAdmissionPolicy == nil {
return nil, fmt.Errorf("validatingAdmissionPolicy provided to Apply must not be nil")
}
data, err := json.Marshal(validatingAdmissionPolicy)
if err != nil {
return nil, err
}
name := validatingAdmissionPolicy.Name
if name == nil {
return nil, fmt.Errorf("validatingAdmissionPolicy.Name must be provided to Apply")
}
obj, err := c.Fake.
Invokes(testing.NewRootPatchSubresourceAction(validatingadmissionpoliciesResource, *name, types.ApplyPatchType, data), &v1.ValidatingAdmissionPolicy{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicy), err
}
// ApplyStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().
func (c *FakeValidatingAdmissionPolicies) ApplyStatus(ctx context.Context, validatingAdmissionPolicy *admissionregistrationv1.ValidatingAdmissionPolicyApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ValidatingAdmissionPolicy, err error) {
if validatingAdmissionPolicy == nil {
return nil, fmt.Errorf("validatingAdmissionPolicy provided to Apply must not be nil")
}
data, err := json.Marshal(validatingAdmissionPolicy)
if err != nil {
return nil, err
}
name := validatingAdmissionPolicy.Name
if name == nil {
return nil, fmt.Errorf("validatingAdmissionPolicy.Name must be provided to Apply")
}
obj, err := c.Fake.
Invokes(testing.NewRootPatchSubresourceAction(validatingadmissionpoliciesResource, *name, types.ApplyPatchType, data, "status"), &v1.ValidatingAdmissionPolicy{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicy), err
}

View File

@ -0,0 +1,145 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
"context"
json "encoding/json"
"fmt"
v1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
admissionregistrationv1 "k8s.io/client-go/applyconfigurations/admissionregistration/v1"
testing "k8s.io/client-go/testing"
)
// FakeValidatingAdmissionPolicyBindings implements ValidatingAdmissionPolicyBindingInterface
type FakeValidatingAdmissionPolicyBindings struct {
Fake *FakeAdmissionregistrationV1
}
var validatingadmissionpolicybindingsResource = v1.SchemeGroupVersion.WithResource("validatingadmissionpolicybindings")
var validatingadmissionpolicybindingsKind = v1.SchemeGroupVersion.WithKind("ValidatingAdmissionPolicyBinding")
// Get takes name of the validatingAdmissionPolicyBinding, and returns the corresponding validatingAdmissionPolicyBinding object, and an error if there is any.
func (c *FakeValidatingAdmissionPolicyBindings) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ValidatingAdmissionPolicyBinding, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootGetAction(validatingadmissionpolicybindingsResource, name), &v1.ValidatingAdmissionPolicyBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicyBinding), err
}
// List takes label and field selectors, and returns the list of ValidatingAdmissionPolicyBindings that match those selectors.
func (c *FakeValidatingAdmissionPolicyBindings) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ValidatingAdmissionPolicyBindingList, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootListAction(validatingadmissionpolicybindingsResource, validatingadmissionpolicybindingsKind, opts), &v1.ValidatingAdmissionPolicyBindingList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v1.ValidatingAdmissionPolicyBindingList{ListMeta: obj.(*v1.ValidatingAdmissionPolicyBindingList).ListMeta}
for _, item := range obj.(*v1.ValidatingAdmissionPolicyBindingList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested validatingAdmissionPolicyBindings.
func (c *FakeValidatingAdmissionPolicyBindings) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewRootWatchAction(validatingadmissionpolicybindingsResource, opts))
}
// Create takes the representation of a validatingAdmissionPolicyBinding and creates it. Returns the server's representation of the validatingAdmissionPolicyBinding, and an error, if there is any.
func (c *FakeValidatingAdmissionPolicyBindings) Create(ctx context.Context, validatingAdmissionPolicyBinding *v1.ValidatingAdmissionPolicyBinding, opts metav1.CreateOptions) (result *v1.ValidatingAdmissionPolicyBinding, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootCreateAction(validatingadmissionpolicybindingsResource, validatingAdmissionPolicyBinding), &v1.ValidatingAdmissionPolicyBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicyBinding), err
}
// Update takes the representation of a validatingAdmissionPolicyBinding and updates it. Returns the server's representation of the validatingAdmissionPolicyBinding, and an error, if there is any.
func (c *FakeValidatingAdmissionPolicyBindings) Update(ctx context.Context, validatingAdmissionPolicyBinding *v1.ValidatingAdmissionPolicyBinding, opts metav1.UpdateOptions) (result *v1.ValidatingAdmissionPolicyBinding, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootUpdateAction(validatingadmissionpolicybindingsResource, validatingAdmissionPolicyBinding), &v1.ValidatingAdmissionPolicyBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicyBinding), err
}
// Delete takes name of the validatingAdmissionPolicyBinding and deletes it. Returns an error if one occurs.
func (c *FakeValidatingAdmissionPolicyBindings) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewRootDeleteActionWithOptions(validatingadmissionpolicybindingsResource, name, opts), &v1.ValidatingAdmissionPolicyBinding{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeValidatingAdmissionPolicyBindings) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {
action := testing.NewRootDeleteCollectionAction(validatingadmissionpolicybindingsResource, listOpts)
_, err := c.Fake.Invokes(action, &v1.ValidatingAdmissionPolicyBindingList{})
return err
}
// Patch applies the patch and returns the patched validatingAdmissionPolicyBinding.
func (c *FakeValidatingAdmissionPolicyBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ValidatingAdmissionPolicyBinding, err error) {
obj, err := c.Fake.
Invokes(testing.NewRootPatchSubresourceAction(validatingadmissionpolicybindingsResource, name, pt, data, subresources...), &v1.ValidatingAdmissionPolicyBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicyBinding), err
}
// Apply takes the given apply declarative configuration, applies it and returns the applied validatingAdmissionPolicyBinding.
func (c *FakeValidatingAdmissionPolicyBindings) Apply(ctx context.Context, validatingAdmissionPolicyBinding *admissionregistrationv1.ValidatingAdmissionPolicyBindingApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ValidatingAdmissionPolicyBinding, err error) {
if validatingAdmissionPolicyBinding == nil {
return nil, fmt.Errorf("validatingAdmissionPolicyBinding provided to Apply must not be nil")
}
data, err := json.Marshal(validatingAdmissionPolicyBinding)
if err != nil {
return nil, err
}
name := validatingAdmissionPolicyBinding.Name
if name == nil {
return nil, fmt.Errorf("validatingAdmissionPolicyBinding.Name must be provided to Apply")
}
obj, err := c.Fake.
Invokes(testing.NewRootPatchSubresourceAction(validatingadmissionpolicybindingsResource, *name, types.ApplyPatchType, data), &v1.ValidatingAdmissionPolicyBinding{})
if obj == nil {
return nil, err
}
return obj.(*v1.ValidatingAdmissionPolicyBinding), err
}

View File

@ -20,4 +20,8 @@ package v1
type MutatingWebhookConfigurationExpansion interface{}
type ValidatingAdmissionPolicyExpansion interface{}
type ValidatingAdmissionPolicyBindingExpansion interface{}
type ValidatingWebhookConfigurationExpansion interface{}

View File

@ -0,0 +1,243 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v1
import (
"context"
json "encoding/json"
"fmt"
"time"
v1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
admissionregistrationv1 "k8s.io/client-go/applyconfigurations/admissionregistration/v1"
scheme "k8s.io/client-go/kubernetes/scheme"
rest "k8s.io/client-go/rest"
)
// ValidatingAdmissionPoliciesGetter has a method to return a ValidatingAdmissionPolicyInterface.
// A group's client should implement this interface.
type ValidatingAdmissionPoliciesGetter interface {
ValidatingAdmissionPolicies() ValidatingAdmissionPolicyInterface
}
// ValidatingAdmissionPolicyInterface has methods to work with ValidatingAdmissionPolicy resources.
type ValidatingAdmissionPolicyInterface interface {
Create(ctx context.Context, validatingAdmissionPolicy *v1.ValidatingAdmissionPolicy, opts metav1.CreateOptions) (*v1.ValidatingAdmissionPolicy, error)
Update(ctx context.Context, validatingAdmissionPolicy *v1.ValidatingAdmissionPolicy, opts metav1.UpdateOptions) (*v1.ValidatingAdmissionPolicy, error)
UpdateStatus(ctx context.Context, validatingAdmissionPolicy *v1.ValidatingAdmissionPolicy, opts metav1.UpdateOptions) (*v1.ValidatingAdmissionPolicy, error)
Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error
DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error
Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.ValidatingAdmissionPolicy, error)
List(ctx context.Context, opts metav1.ListOptions) (*v1.ValidatingAdmissionPolicyList, error)
Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)
Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ValidatingAdmissionPolicy, err error)
Apply(ctx context.Context, validatingAdmissionPolicy *admissionregistrationv1.ValidatingAdmissionPolicyApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ValidatingAdmissionPolicy, err error)
ApplyStatus(ctx context.Context, validatingAdmissionPolicy *admissionregistrationv1.ValidatingAdmissionPolicyApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ValidatingAdmissionPolicy, err error)
ValidatingAdmissionPolicyExpansion
}
// validatingAdmissionPolicies implements ValidatingAdmissionPolicyInterface
type validatingAdmissionPolicies struct {
client rest.Interface
}
// newValidatingAdmissionPolicies returns a ValidatingAdmissionPolicies
func newValidatingAdmissionPolicies(c *AdmissionregistrationV1Client) *validatingAdmissionPolicies {
return &validatingAdmissionPolicies{
client: c.RESTClient(),
}
}
// Get takes name of the validatingAdmissionPolicy, and returns the corresponding validatingAdmissionPolicy object, and an error if there is any.
func (c *validatingAdmissionPolicies) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ValidatingAdmissionPolicy, err error) {
result = &v1.ValidatingAdmissionPolicy{}
err = c.client.Get().
Resource("validatingadmissionpolicies").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do(ctx).
Into(result)
return
}
// List takes label and field selectors, and returns the list of ValidatingAdmissionPolicies that match those selectors.
func (c *validatingAdmissionPolicies) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ValidatingAdmissionPolicyList, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
result = &v1.ValidatingAdmissionPolicyList{}
err = c.client.Get().
Resource("validatingadmissionpolicies").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Do(ctx).
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested validatingAdmissionPolicies.
func (c *validatingAdmissionPolicies) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Resource("validatingadmissionpolicies").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch(ctx)
}
// Create takes the representation of a validatingAdmissionPolicy and creates it. Returns the server's representation of the validatingAdmissionPolicy, and an error, if there is any.
func (c *validatingAdmissionPolicies) Create(ctx context.Context, validatingAdmissionPolicy *v1.ValidatingAdmissionPolicy, opts metav1.CreateOptions) (result *v1.ValidatingAdmissionPolicy, err error) {
result = &v1.ValidatingAdmissionPolicy{}
err = c.client.Post().
Resource("validatingadmissionpolicies").
VersionedParams(&opts, scheme.ParameterCodec).
Body(validatingAdmissionPolicy).
Do(ctx).
Into(result)
return
}
// Update takes the representation of a validatingAdmissionPolicy and updates it. Returns the server's representation of the validatingAdmissionPolicy, and an error, if there is any.
func (c *validatingAdmissionPolicies) Update(ctx context.Context, validatingAdmissionPolicy *v1.ValidatingAdmissionPolicy, opts metav1.UpdateOptions) (result *v1.ValidatingAdmissionPolicy, err error) {
result = &v1.ValidatingAdmissionPolicy{}
err = c.client.Put().
Resource("validatingadmissionpolicies").
Name(validatingAdmissionPolicy.Name).
VersionedParams(&opts, scheme.ParameterCodec).
Body(validatingAdmissionPolicy).
Do(ctx).
Into(result)
return
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *validatingAdmissionPolicies) UpdateStatus(ctx context.Context, validatingAdmissionPolicy *v1.ValidatingAdmissionPolicy, opts metav1.UpdateOptions) (result *v1.ValidatingAdmissionPolicy, err error) {
result = &v1.ValidatingAdmissionPolicy{}
err = c.client.Put().
Resource("validatingadmissionpolicies").
Name(validatingAdmissionPolicy.Name).
SubResource("status").
VersionedParams(&opts, scheme.ParameterCodec).
Body(validatingAdmissionPolicy).
Do(ctx).
Into(result)
return
}
// Delete takes name of the validatingAdmissionPolicy and deletes it. Returns an error if one occurs.
func (c *validatingAdmissionPolicies) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {
return c.client.Delete().
Resource("validatingadmissionpolicies").
Name(name).
Body(&opts).
Do(ctx).
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *validatingAdmissionPolicies) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {
var timeout time.Duration
if listOpts.TimeoutSeconds != nil {
timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Resource("validatingadmissionpolicies").
VersionedParams(&listOpts, scheme.ParameterCodec).
Timeout(timeout).
Body(&opts).
Do(ctx).
Error()
}
// Patch applies the patch and returns the patched validatingAdmissionPolicy.
func (c *validatingAdmissionPolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ValidatingAdmissionPolicy, err error) {
result = &v1.ValidatingAdmissionPolicy{}
err = c.client.Patch(pt).
Resource("validatingadmissionpolicies").
Name(name).
SubResource(subresources...).
VersionedParams(&opts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}
// Apply takes the given apply declarative configuration, applies it and returns the applied validatingAdmissionPolicy.
func (c *validatingAdmissionPolicies) Apply(ctx context.Context, validatingAdmissionPolicy *admissionregistrationv1.ValidatingAdmissionPolicyApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ValidatingAdmissionPolicy, err error) {
if validatingAdmissionPolicy == nil {
return nil, fmt.Errorf("validatingAdmissionPolicy provided to Apply must not be nil")
}
patchOpts := opts.ToPatchOptions()
data, err := json.Marshal(validatingAdmissionPolicy)
if err != nil {
return nil, err
}
name := validatingAdmissionPolicy.Name
if name == nil {
return nil, fmt.Errorf("validatingAdmissionPolicy.Name must be provided to Apply")
}
result = &v1.ValidatingAdmissionPolicy{}
err = c.client.Patch(types.ApplyPatchType).
Resource("validatingadmissionpolicies").
Name(*name).
VersionedParams(&patchOpts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}
// ApplyStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating ApplyStatus().
func (c *validatingAdmissionPolicies) ApplyStatus(ctx context.Context, validatingAdmissionPolicy *admissionregistrationv1.ValidatingAdmissionPolicyApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ValidatingAdmissionPolicy, err error) {
if validatingAdmissionPolicy == nil {
return nil, fmt.Errorf("validatingAdmissionPolicy provided to Apply must not be nil")
}
patchOpts := opts.ToPatchOptions()
data, err := json.Marshal(validatingAdmissionPolicy)
if err != nil {
return nil, err
}
name := validatingAdmissionPolicy.Name
if name == nil {
return nil, fmt.Errorf("validatingAdmissionPolicy.Name must be provided to Apply")
}
result = &v1.ValidatingAdmissionPolicy{}
err = c.client.Patch(types.ApplyPatchType).
Resource("validatingadmissionpolicies").
Name(*name).
SubResource("status").
VersionedParams(&patchOpts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}

View File

@ -0,0 +1,197 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v1
import (
"context"
json "encoding/json"
"fmt"
"time"
v1 "k8s.io/api/admissionregistration/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
admissionregistrationv1 "k8s.io/client-go/applyconfigurations/admissionregistration/v1"
scheme "k8s.io/client-go/kubernetes/scheme"
rest "k8s.io/client-go/rest"
)
// ValidatingAdmissionPolicyBindingsGetter has a method to return a ValidatingAdmissionPolicyBindingInterface.
// A group's client should implement this interface.
type ValidatingAdmissionPolicyBindingsGetter interface {
ValidatingAdmissionPolicyBindings() ValidatingAdmissionPolicyBindingInterface
}
// ValidatingAdmissionPolicyBindingInterface has methods to work with ValidatingAdmissionPolicyBinding resources.
type ValidatingAdmissionPolicyBindingInterface interface {
Create(ctx context.Context, validatingAdmissionPolicyBinding *v1.ValidatingAdmissionPolicyBinding, opts metav1.CreateOptions) (*v1.ValidatingAdmissionPolicyBinding, error)
Update(ctx context.Context, validatingAdmissionPolicyBinding *v1.ValidatingAdmissionPolicyBinding, opts metav1.UpdateOptions) (*v1.ValidatingAdmissionPolicyBinding, error)
Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error
DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error
Get(ctx context.Context, name string, opts metav1.GetOptions) (*v1.ValidatingAdmissionPolicyBinding, error)
List(ctx context.Context, opts metav1.ListOptions) (*v1.ValidatingAdmissionPolicyBindingList, error)
Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error)
Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ValidatingAdmissionPolicyBinding, err error)
Apply(ctx context.Context, validatingAdmissionPolicyBinding *admissionregistrationv1.ValidatingAdmissionPolicyBindingApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ValidatingAdmissionPolicyBinding, err error)
ValidatingAdmissionPolicyBindingExpansion
}
// validatingAdmissionPolicyBindings implements ValidatingAdmissionPolicyBindingInterface
type validatingAdmissionPolicyBindings struct {
client rest.Interface
}
// newValidatingAdmissionPolicyBindings returns a ValidatingAdmissionPolicyBindings
func newValidatingAdmissionPolicyBindings(c *AdmissionregistrationV1Client) *validatingAdmissionPolicyBindings {
return &validatingAdmissionPolicyBindings{
client: c.RESTClient(),
}
}
// Get takes name of the validatingAdmissionPolicyBinding, and returns the corresponding validatingAdmissionPolicyBinding object, and an error if there is any.
func (c *validatingAdmissionPolicyBindings) Get(ctx context.Context, name string, options metav1.GetOptions) (result *v1.ValidatingAdmissionPolicyBinding, err error) {
result = &v1.ValidatingAdmissionPolicyBinding{}
err = c.client.Get().
Resource("validatingadmissionpolicybindings").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do(ctx).
Into(result)
return
}
// List takes label and field selectors, and returns the list of ValidatingAdmissionPolicyBindings that match those selectors.
func (c *validatingAdmissionPolicyBindings) List(ctx context.Context, opts metav1.ListOptions) (result *v1.ValidatingAdmissionPolicyBindingList, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
result = &v1.ValidatingAdmissionPolicyBindingList{}
err = c.client.Get().
Resource("validatingadmissionpolicybindings").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Do(ctx).
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested validatingAdmissionPolicyBindings.
func (c *validatingAdmissionPolicyBindings) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Resource("validatingadmissionpolicybindings").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch(ctx)
}
// Create takes the representation of a validatingAdmissionPolicyBinding and creates it. Returns the server's representation of the validatingAdmissionPolicyBinding, and an error, if there is any.
func (c *validatingAdmissionPolicyBindings) Create(ctx context.Context, validatingAdmissionPolicyBinding *v1.ValidatingAdmissionPolicyBinding, opts metav1.CreateOptions) (result *v1.ValidatingAdmissionPolicyBinding, err error) {
result = &v1.ValidatingAdmissionPolicyBinding{}
err = c.client.Post().
Resource("validatingadmissionpolicybindings").
VersionedParams(&opts, scheme.ParameterCodec).
Body(validatingAdmissionPolicyBinding).
Do(ctx).
Into(result)
return
}
// Update takes the representation of a validatingAdmissionPolicyBinding and updates it. Returns the server's representation of the validatingAdmissionPolicyBinding, and an error, if there is any.
func (c *validatingAdmissionPolicyBindings) Update(ctx context.Context, validatingAdmissionPolicyBinding *v1.ValidatingAdmissionPolicyBinding, opts metav1.UpdateOptions) (result *v1.ValidatingAdmissionPolicyBinding, err error) {
result = &v1.ValidatingAdmissionPolicyBinding{}
err = c.client.Put().
Resource("validatingadmissionpolicybindings").
Name(validatingAdmissionPolicyBinding.Name).
VersionedParams(&opts, scheme.ParameterCodec).
Body(validatingAdmissionPolicyBinding).
Do(ctx).
Into(result)
return
}
// Delete takes name of the validatingAdmissionPolicyBinding and deletes it. Returns an error if one occurs.
func (c *validatingAdmissionPolicyBindings) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {
return c.client.Delete().
Resource("validatingadmissionpolicybindings").
Name(name).
Body(&opts).
Do(ctx).
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *validatingAdmissionPolicyBindings) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {
var timeout time.Duration
if listOpts.TimeoutSeconds != nil {
timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Resource("validatingadmissionpolicybindings").
VersionedParams(&listOpts, scheme.ParameterCodec).
Timeout(timeout).
Body(&opts).
Do(ctx).
Error()
}
// Patch applies the patch and returns the patched validatingAdmissionPolicyBinding.
func (c *validatingAdmissionPolicyBindings) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result *v1.ValidatingAdmissionPolicyBinding, err error) {
result = &v1.ValidatingAdmissionPolicyBinding{}
err = c.client.Patch(pt).
Resource("validatingadmissionpolicybindings").
Name(name).
SubResource(subresources...).
VersionedParams(&opts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}
// Apply takes the given apply declarative configuration, applies it and returns the applied validatingAdmissionPolicyBinding.
func (c *validatingAdmissionPolicyBindings) Apply(ctx context.Context, validatingAdmissionPolicyBinding *admissionregistrationv1.ValidatingAdmissionPolicyBindingApplyConfiguration, opts metav1.ApplyOptions) (result *v1.ValidatingAdmissionPolicyBinding, err error) {
if validatingAdmissionPolicyBinding == nil {
return nil, fmt.Errorf("validatingAdmissionPolicyBinding provided to Apply must not be nil")
}
patchOpts := opts.ToPatchOptions()
data, err := json.Marshal(validatingAdmissionPolicyBinding)
if err != nil {
return nil, err
}
name := validatingAdmissionPolicyBinding.Name
if name == nil {
return nil, fmt.Errorf("validatingAdmissionPolicyBinding.Name must be provided to Apply")
}
result = &v1.ValidatingAdmissionPolicyBinding{}
err = c.client.Patch(types.ApplyPatchType).
Resource("validatingadmissionpolicybindings").
Name(*name).
VersionedParams(&patchOpts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
}

View File

@ -22,6 +22,14 @@ package v1
// MutatingWebhookConfigurationLister.
type MutatingWebhookConfigurationListerExpansion interface{}
// ValidatingAdmissionPolicyListerExpansion allows custom methods to be added to
// ValidatingAdmissionPolicyLister.
type ValidatingAdmissionPolicyListerExpansion interface{}
// ValidatingAdmissionPolicyBindingListerExpansion allows custom methods to be added to
// ValidatingAdmissionPolicyBindingLister.
type ValidatingAdmissionPolicyBindingListerExpansion interface{}
// ValidatingWebhookConfigurationListerExpansion allows custom methods to be added to
// ValidatingWebhookConfigurationLister.
type ValidatingWebhookConfigurationListerExpansion interface{}

View File

@ -0,0 +1,68 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v1
import (
v1 "k8s.io/api/admissionregistration/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// ValidatingAdmissionPolicyLister helps list ValidatingAdmissionPolicies.
// All objects returned here must be treated as read-only.
type ValidatingAdmissionPolicyLister interface {
// List lists all ValidatingAdmissionPolicies in the indexer.
// Objects returned here must be treated as read-only.
List(selector labels.Selector) (ret []*v1.ValidatingAdmissionPolicy, err error)
// Get retrieves the ValidatingAdmissionPolicy from the index for a given name.
// Objects returned here must be treated as read-only.
Get(name string) (*v1.ValidatingAdmissionPolicy, error)
ValidatingAdmissionPolicyListerExpansion
}
// validatingAdmissionPolicyLister implements the ValidatingAdmissionPolicyLister interface.
type validatingAdmissionPolicyLister struct {
indexer cache.Indexer
}
// NewValidatingAdmissionPolicyLister returns a new ValidatingAdmissionPolicyLister.
func NewValidatingAdmissionPolicyLister(indexer cache.Indexer) ValidatingAdmissionPolicyLister {
return &validatingAdmissionPolicyLister{indexer: indexer}
}
// List lists all ValidatingAdmissionPolicies in the indexer.
func (s *validatingAdmissionPolicyLister) List(selector labels.Selector) (ret []*v1.ValidatingAdmissionPolicy, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1.ValidatingAdmissionPolicy))
})
return ret, err
}
// Get retrieves the ValidatingAdmissionPolicy from the index for a given name.
func (s *validatingAdmissionPolicyLister) Get(name string) (*v1.ValidatingAdmissionPolicy, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1.Resource("validatingadmissionpolicy"), name)
}
return obj.(*v1.ValidatingAdmissionPolicy), nil
}

View File

@ -0,0 +1,68 @@
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by lister-gen. DO NOT EDIT.
package v1
import (
v1 "k8s.io/api/admissionregistration/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// ValidatingAdmissionPolicyBindingLister helps list ValidatingAdmissionPolicyBindings.
// All objects returned here must be treated as read-only.
type ValidatingAdmissionPolicyBindingLister interface {
// List lists all ValidatingAdmissionPolicyBindings in the indexer.
// Objects returned here must be treated as read-only.
List(selector labels.Selector) (ret []*v1.ValidatingAdmissionPolicyBinding, err error)
// Get retrieves the ValidatingAdmissionPolicyBinding from the index for a given name.
// Objects returned here must be treated as read-only.
Get(name string) (*v1.ValidatingAdmissionPolicyBinding, error)
ValidatingAdmissionPolicyBindingListerExpansion
}
// validatingAdmissionPolicyBindingLister implements the ValidatingAdmissionPolicyBindingLister interface.
type validatingAdmissionPolicyBindingLister struct {
indexer cache.Indexer
}
// NewValidatingAdmissionPolicyBindingLister returns a new ValidatingAdmissionPolicyBindingLister.
func NewValidatingAdmissionPolicyBindingLister(indexer cache.Indexer) ValidatingAdmissionPolicyBindingLister {
return &validatingAdmissionPolicyBindingLister{indexer: indexer}
}
// List lists all ValidatingAdmissionPolicyBindings in the indexer.
func (s *validatingAdmissionPolicyBindingLister) List(selector labels.Selector) (ret []*v1.ValidatingAdmissionPolicyBinding, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1.ValidatingAdmissionPolicyBinding))
})
return ret, err
}
// Get retrieves the ValidatingAdmissionPolicyBinding from the index for a given name.
func (s *validatingAdmissionPolicyBindingLister) Get(name string) (*v1.ValidatingAdmissionPolicyBinding, error) {
obj, exists, err := s.indexer.GetByKey(name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1.Resource("validatingadmissionpolicybinding"), name)
}
return obj.(*v1.ValidatingAdmissionPolicyBinding), nil
}

View File

@ -37,7 +37,7 @@ var (
"[+]ping ok",
"[+]log ok",
"[+]etcd ok",
"[+]poststarthook/start-kube-apiserver-admission-initializer ok",
"[+]poststarthook/start-apiserver-admission-initializer ok",
"[+]poststarthook/generic-apiserver-start-informers ok",
"[+]poststarthook/start-apiextensions-informers ok",
"[+]poststarthook/start-apiextensions-controllers ok",
@ -58,7 +58,7 @@ var (
"[+]ping ok",
"[+]log ok",
"[+]etcd ok",
"[+]poststarthook/start-kube-apiserver-admission-initializer ok",
"[+]poststarthook/start-apiserver-admission-initializer ok",
"[+]poststarthook/generic-apiserver-start-informers ok",
"[+]poststarthook/start-apiextensions-informers ok",
"[+]poststarthook/start-apiextensions-controllers ok",
@ -80,7 +80,7 @@ var (
"[+]log ok",
"[+]etcd ok",
"[+]informer-sync ok",
"[+]poststarthook/start-kube-apiserver-admission-initializer ok",
"[+]poststarthook/start-apiserver-admission-initializer ok",
"[+]poststarthook/generic-apiserver-start-informers ok",
"[+]poststarthook/start-apiextensions-informers ok",
"[+]poststarthook/start-apiextensions-controllers ok",

View File

@ -18,14 +18,12 @@ package apimachinery
import (
"context"
"fmt"
"time"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
appsv1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
@ -52,11 +50,6 @@ var _ = SIGDescribe("ValidatingAdmissionPolicy [Privileged:ClusterAdmin]", frame
var err error
client, err = clientset.NewForConfig(f.ClientConfig())
framework.ExpectNoError(err, "initializing client")
_, err = client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().List(context.Background(), metav1.ListOptions{})
if apierrors.IsNotFound(err) {
// TODO: feature check should fail after GA graduation
ginkgo.Skip(fmt.Sprintf("server does not support ValidatingAdmissionPolicy v1beta1: %v, feature gate not enabled?", err))
}
extensionsClient, err = apiextensionsclientset.NewForConfig(f.ClientConfig())
framework.ExpectNoError(err, "initializing api-extensions client")
})
@ -76,25 +69,25 @@ var _ = SIGDescribe("ValidatingAdmissionPolicy [Privileged:ClusterAdmin]", frame
StartResourceRule().
MatchResource([]string{"apps"}, []string{"v1"}, []string{"deployments"}).
EndResourceRule().
WithValidation(admissionregistrationv1beta1.Validation{
WithValidation(admissionregistrationv1.Validation{
Expression: "object.spec.replicas > 1",
MessageExpression: "'wants replicas > 1, got ' + object.spec.replicas",
}).
WithValidation(admissionregistrationv1beta1.Validation{
WithValidation(admissionregistrationv1.Validation{
Expression: "namespaceObject.metadata.name == '" + f.UniqueName + "'",
Message: "Internal error! Other namespace should not be allowed.",
}).
Build()
policy, err := client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
policy, err := client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
framework.ExpectNoError(err, "create policy")
ginkgo.DeferCleanup(func(ctx context.Context, name string) error {
return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
}, policy.Name)
binding := createBinding(f.UniqueName+".binding.example.com", f.UniqueName, policy.Name)
binding, err = client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicyBindings().Create(ctx, binding, metav1.CreateOptions{})
binding, err = client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().Create(ctx, binding, metav1.CreateOptions{})
framework.ExpectNoError(err, "create policy binding")
ginkgo.DeferCleanup(func(ctx context.Context, name string) error {
return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicyBindings().Delete(ctx, name, metav1.DeleteOptions{})
return client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().Delete(ctx, name, metav1.DeleteOptions{})
}, binding.Name)
})
ginkgo.By("waiting until the marker is denied", func() {
@ -127,27 +120,27 @@ var _ = SIGDescribe("ValidatingAdmissionPolicy [Privileged:ClusterAdmin]", frame
})
ginkgo.It("should type check validation expressions", func(ctx context.Context) {
var policy *admissionregistrationv1beta1.ValidatingAdmissionPolicy
var policy *admissionregistrationv1.ValidatingAdmissionPolicy
ginkgo.By("creating the policy with correct types", func() {
policy = newValidatingAdmissionPolicyBuilder(f.UniqueName+".correct-policy.example.com").
MatchUniqueNamespace(f.UniqueName).
StartResourceRule().
MatchResource([]string{"apps"}, []string{"v1"}, []string{"deployments"}).
EndResourceRule().
WithValidation(admissionregistrationv1beta1.Validation{
WithValidation(admissionregistrationv1.Validation{
Expression: "object.spec.replicas > 1",
}).
Build()
var err error
policy, err = client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
policy, err = client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
framework.ExpectNoError(err, "create policy")
ginkgo.DeferCleanup(func(ctx context.Context, name string) error {
return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
}, policy.Name)
})
ginkgo.By("waiting for the type check to finish without any warnings", func() {
err := wait.PollUntilContextCancel(ctx, 100*time.Millisecond, true, func(ctx context.Context) (done bool, err error) {
policy, err = client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Get(ctx, policy.Name, metav1.GetOptions{})
policy, err = client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Get(ctx, policy.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
@ -165,21 +158,21 @@ var _ = SIGDescribe("ValidatingAdmissionPolicy [Privileged:ClusterAdmin]", frame
StartResourceRule().
MatchResource([]string{"apps"}, []string{"v1"}, []string{"deployments"}).
EndResourceRule().
WithValidation(admissionregistrationv1beta1.Validation{
WithValidation(admissionregistrationv1.Validation{
Expression: "object.spec.replicas > '1'", // confusion: int > string
MessageExpression: "'wants replicas > 1, got ' + object.spec.replicas", // confusion: string + int
}).
Build()
var err error
policy, err = client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
policy, err = client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
framework.ExpectNoError(err, "create policy")
ginkgo.DeferCleanup(func(ctx context.Context, name string) error {
return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
}, policy.Name)
})
ginkgo.By("waiting for the type check to finish with warnings", func() {
err := wait.PollUntilContextCancel(ctx, 100*time.Millisecond, true, func(ctx context.Context) (done bool, err error) {
policy, err = client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Get(ctx, policy.Name, metav1.GetOptions{})
policy, err = client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Get(ctx, policy.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
@ -208,31 +201,31 @@ var _ = SIGDescribe("ValidatingAdmissionPolicy [Privileged:ClusterAdmin]", frame
StartResourceRule().
MatchResource([]string{"apps"}, []string{"v1"}, []string{"deployments"}).
EndResourceRule().
WithVariable(admissionregistrationv1beta1.Variable{
WithVariable(admissionregistrationv1.Variable{
Name: "replicas",
Expression: "object.spec.replicas",
}).
WithVariable(admissionregistrationv1beta1.Variable{
WithVariable(admissionregistrationv1.Variable{
Name: "oddReplicas",
Expression: "variables.replicas % 2 == 1",
}).
WithValidation(admissionregistrationv1beta1.Validation{
WithValidation(admissionregistrationv1.Validation{
Expression: "variables.replicas > 1",
}).
WithValidation(admissionregistrationv1beta1.Validation{
WithValidation(admissionregistrationv1.Validation{
Expression: "variables.oddReplicas",
}).
Build()
policy, err := client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
policy, err := client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
framework.ExpectNoError(err, "create policy")
ginkgo.DeferCleanup(func(ctx context.Context, name string) error {
return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
}, policy.Name)
binding := createBinding(f.UniqueName+".binding.example.com", f.UniqueName, policy.Name)
binding, err = client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicyBindings().Create(ctx, binding, metav1.CreateOptions{})
binding, err = client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().Create(ctx, binding, metav1.CreateOptions{})
framework.ExpectNoError(err, "create policy binding")
ginkgo.DeferCleanup(func(ctx context.Context, name string) error {
return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicyBindings().Delete(ctx, name, metav1.DeleteOptions{})
return client.AdmissionregistrationV1().ValidatingAdmissionPolicyBindings().Delete(ctx, name, metav1.DeleteOptions{})
}, binding.Name)
})
ginkgo.By("waiting until the marker is denied", func() {
@ -268,7 +261,7 @@ var _ = SIGDescribe("ValidatingAdmissionPolicy [Privileged:ClusterAdmin]", frame
crd := crontabExampleCRD()
crd.Spec.Group = "stable." + f.UniqueName
crd.Name = crd.Spec.Names.Plural + "." + crd.Spec.Group
var policy *admissionregistrationv1beta1.ValidatingAdmissionPolicy
var policy *admissionregistrationv1.ValidatingAdmissionPolicy
ginkgo.By("creating the CRD", func() {
var err error
crd, err = extensionsClient.ApiextensionsV1().CustomResourceDefinitions().Create(ctx, crd, metav1.CreateOptions{})
@ -290,19 +283,19 @@ var _ = SIGDescribe("ValidatingAdmissionPolicy [Privileged:ClusterAdmin]", frame
StartResourceRule().
MatchResource([]string{crd.Spec.Group}, []string{"v1"}, []string{"crontabs"}).
EndResourceRule().
WithValidation(admissionregistrationv1beta1.Validation{
WithValidation(admissionregistrationv1.Validation{
Expression: "object.spec.replicas > 1",
}).
Build()
policy, err := client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
policy, err := client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
framework.ExpectNoError(err, "create policy")
ginkgo.DeferCleanup(func(ctx context.Context, name string) error {
return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
}, policy.Name)
})
ginkgo.By("waiting for the type check to finish without warnings", func() {
err := wait.PollUntilContextCancel(ctx, 100*time.Millisecond, true, func(ctx context.Context) (done bool, err error) {
policy, err = client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Get(ctx, policy.Name, metav1.GetOptions{})
policy, err = client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Get(ctx, policy.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
@ -320,22 +313,22 @@ var _ = SIGDescribe("ValidatingAdmissionPolicy [Privileged:ClusterAdmin]", frame
StartResourceRule().
MatchResource([]string{crd.Spec.Group}, []string{"v1"}, []string{"crontabs"}).
EndResourceRule().
WithValidation(admissionregistrationv1beta1.Validation{
WithValidation(admissionregistrationv1.Validation{
Expression: "object.spec.replicas > '1'", // type confusion
}).
WithValidation(admissionregistrationv1beta1.Validation{
WithValidation(admissionregistrationv1.Validation{
Expression: "object.spec.maxRetries < 10", // not yet existing field
}).
Build()
policy, err := client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
policy, err := client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Create(ctx, policy, metav1.CreateOptions{})
framework.ExpectNoError(err, "create policy")
ginkgo.DeferCleanup(func(ctx context.Context, name string) error {
return client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
return client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Delete(ctx, name, metav1.DeleteOptions{})
}, policy.Name)
})
ginkgo.By("waiting for the type check to finish with warnings", func() {
err := wait.PollUntilContextCancel(ctx, 100*time.Millisecond, true, func(ctx context.Context) (done bool, err error) {
policy, err = client.AdmissionregistrationV1beta1().ValidatingAdmissionPolicies().Get(ctx, policy.Name, metav1.GetOptions{})
policy, err = client.AdmissionregistrationV1().ValidatingAdmissionPolicies().Get(ctx, policy.Name, metav1.GetOptions{})
if err != nil {
return false, err
}
@ -357,17 +350,17 @@ var _ = SIGDescribe("ValidatingAdmissionPolicy [Privileged:ClusterAdmin]", frame
})
})
func createBinding(bindingName string, uniqueLabel string, policyName string) *admissionregistrationv1beta1.ValidatingAdmissionPolicyBinding {
return &admissionregistrationv1beta1.ValidatingAdmissionPolicyBinding{
func createBinding(bindingName string, uniqueLabel string, policyName string) *admissionregistrationv1.ValidatingAdmissionPolicyBinding {
return &admissionregistrationv1.ValidatingAdmissionPolicyBinding{
ObjectMeta: metav1.ObjectMeta{Name: bindingName},
Spec: admissionregistrationv1beta1.ValidatingAdmissionPolicyBindingSpec{
Spec: admissionregistrationv1.ValidatingAdmissionPolicyBindingSpec{
PolicyName: policyName,
MatchResources: &admissionregistrationv1beta1.MatchResources{
MatchResources: &admissionregistrationv1.MatchResources{
NamespaceSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{uniqueLabel: "true"},
},
},
ValidationActions: []admissionregistrationv1beta1.ValidationAction{admissionregistrationv1beta1.Deny},
ValidationActions: []admissionregistrationv1.ValidationAction{admissionregistrationv1.Deny},
},
}
}
@ -427,17 +420,17 @@ func basicReplicaSet(name string, replicas int32) *appsv1.ReplicaSet {
}
type validatingAdmissionPolicyBuilder struct {
policy *admissionregistrationv1beta1.ValidatingAdmissionPolicy
policy *admissionregistrationv1.ValidatingAdmissionPolicy
}
type resourceRuleBuilder struct {
policyBuilder *validatingAdmissionPolicyBuilder
resourceRule *admissionregistrationv1beta1.NamedRuleWithOperations
resourceRule *admissionregistrationv1.NamedRuleWithOperations
}
func newValidatingAdmissionPolicyBuilder(policyName string) *validatingAdmissionPolicyBuilder {
return &validatingAdmissionPolicyBuilder{
policy: &admissionregistrationv1beta1.ValidatingAdmissionPolicy{
policy: &admissionregistrationv1.ValidatingAdmissionPolicy{
ObjectMeta: metav1.ObjectMeta{Name: policyName},
},
}
@ -445,7 +438,7 @@ func newValidatingAdmissionPolicyBuilder(policyName string) *validatingAdmission
func (b *validatingAdmissionPolicyBuilder) MatchUniqueNamespace(uniqueLabel string) *validatingAdmissionPolicyBuilder {
if b.policy.Spec.MatchConstraints == nil {
b.policy.Spec.MatchConstraints = &admissionregistrationv1beta1.MatchResources{}
b.policy.Spec.MatchConstraints = &admissionregistrationv1.MatchResources{}
}
b.policy.Spec.MatchConstraints.NamespaceSelector = &metav1.LabelSelector{
MatchLabels: map[string]string{
@ -458,10 +451,10 @@ func (b *validatingAdmissionPolicyBuilder) MatchUniqueNamespace(uniqueLabel stri
func (b *validatingAdmissionPolicyBuilder) StartResourceRule() *resourceRuleBuilder {
return &resourceRuleBuilder{
policyBuilder: b,
resourceRule: &admissionregistrationv1beta1.NamedRuleWithOperations{
RuleWithOperations: admissionregistrationv1beta1.RuleWithOperations{
resourceRule: &admissionregistrationv1.NamedRuleWithOperations{
RuleWithOperations: admissionregistrationv1.RuleWithOperations{
Operations: []admissionregistrationv1.OperationType{admissionregistrationv1.Create, admissionregistrationv1.Update},
Rule: admissionregistrationv1beta1.Rule{
Rule: admissionregistrationv1.Rule{
APIGroups: []string{"apps"},
APIVersions: []string{"v1"},
Resources: []string{"deployments"},
@ -477,7 +470,7 @@ func (rb *resourceRuleBuilder) CreateAndUpdate() *resourceRuleBuilder {
}
func (rb *resourceRuleBuilder) MatchResource(groups []string, versions []string, resources []string) *resourceRuleBuilder {
rb.resourceRule.Rule = admissionregistrationv1beta1.Rule{
rb.resourceRule.Rule = admissionregistrationv1.Rule{
APIGroups: groups,
APIVersions: versions,
Resources: resources,
@ -488,23 +481,23 @@ func (rb *resourceRuleBuilder) MatchResource(groups []string, versions []string,
func (rb *resourceRuleBuilder) EndResourceRule() *validatingAdmissionPolicyBuilder {
b := rb.policyBuilder
if b.policy.Spec.MatchConstraints == nil {
b.policy.Spec.MatchConstraints = &admissionregistrationv1beta1.MatchResources{}
b.policy.Spec.MatchConstraints = &admissionregistrationv1.MatchResources{}
}
b.policy.Spec.MatchConstraints.ResourceRules = append(b.policy.Spec.MatchConstraints.ResourceRules, *rb.resourceRule)
return b
}
func (b *validatingAdmissionPolicyBuilder) WithValidation(validation admissionregistrationv1beta1.Validation) *validatingAdmissionPolicyBuilder {
func (b *validatingAdmissionPolicyBuilder) WithValidation(validation admissionregistrationv1.Validation) *validatingAdmissionPolicyBuilder {
b.policy.Spec.Validations = append(b.policy.Spec.Validations, validation)
return b
}
func (b *validatingAdmissionPolicyBuilder) WithVariable(variable admissionregistrationv1beta1.Variable) *validatingAdmissionPolicyBuilder {
func (b *validatingAdmissionPolicyBuilder) WithVariable(variable admissionregistrationv1.Variable) *validatingAdmissionPolicyBuilder {
b.policy.Spec.Variables = append(b.policy.Spec.Variables, variable)
return b
}
func (b *validatingAdmissionPolicyBuilder) Build() *admissionregistrationv1beta1.ValidatingAdmissionPolicy {
func (b *validatingAdmissionPolicyBuilder) Build() *admissionregistrationv1.ValidatingAdmissionPolicy {
return b.policy
}

View File

@ -145,6 +145,9 @@ var (
gvr("admissionregistration.k8s.io", "v1beta1", "validatingadmissionpolicies"): true,
gvr("admissionregistration.k8s.io", "v1beta1", "validatingadmissionpolicies/status"): true,
gvr("admissionregistration.k8s.io", "v1beta1", "validatingadmissionpolicybindings"): true,
gvr("admissionregistration.k8s.io", "v1", "validatingadmissionpolicies"): true,
gvr("admissionregistration.k8s.io", "v1", "validatingadmissionpolicies/status"): true,
gvr("admissionregistration.k8s.io", "v1", "validatingadmissionpolicybindings"): true,
}
parentResources = map[schema.GroupVersionResource]schema.GroupVersionResource{

View File

@ -65,6 +65,7 @@ var resetFieldsStatusData = map[schema.GroupVersionResource]string{
// standard for []metav1.Condition
gvr("admissionregistration.k8s.io", "v1alpha1", "validatingadmissionpolicies"): `{"status": {"conditions":[{"type":"Accepted","status":"True","lastTransitionTime":"2020-01-01T00:00:00Z","reason":"RuleApplied","message":"Rule was applied"}]}}`,
gvr("admissionregistration.k8s.io", "v1beta1", "validatingadmissionpolicies"): `{"status": {"conditions":[{"type":"Accepted","status":"True","lastTransitionTime":"2020-01-01T00:00:00Z","reason":"RuleApplied","message":"Rule was applied"}]}}`,
gvr("admissionregistration.k8s.io", "v1", "validatingadmissionpolicies"): `{"status": {"conditions":[{"type":"Accepted","status":"True","lastTransitionTime":"2020-01-01T00:00:00Z","reason":"RuleApplied","message":"Rule was applied"}]}}`,
gvr("networking.k8s.io", "v1alpha1", "servicecidrs"): `{"status": {"conditions":[{"type":"Accepted","status":"True","lastTransitionTime":"2020-01-01T00:00:00Z","reason":"RuleApplied","message":"Rule was applied"}]}}`,
}
@ -156,6 +157,7 @@ var resetFieldsSpecData = map[schema.GroupVersionResource]string{
gvr("internal.apiserver.k8s.io", "v1alpha1", "storageversions"): `{}`,
gvr("admissionregistration.k8s.io", "v1alpha1", "validatingadmissionpolicies"): `{"metadata": {"labels": {"a":"c"}}, "spec": {"paramKind": {"apiVersion": "apps/v1", "kind": "Deployment"}}}`,
gvr("admissionregistration.k8s.io", "v1beta1", "validatingadmissionpolicies"): `{"metadata": {"labels": {"a":"c"}}, "spec": {"paramKind": {"apiVersion": "apps/v1", "kind": "Deployment"}}}`,
gvr("admissionregistration.k8s.io", "v1", "validatingadmissionpolicies"): `{"metadata": {"labels": {"a":"c"}}, "spec": {"paramKind": {"apiVersion": "apps/v1", "kind": "Deployment"}}}`,
}
// TestResetFields makes sure that fieldManager does not own fields reset by the storage strategy.

View File

@ -58,6 +58,7 @@ var statusData = map[schema.GroupVersionResource]string{
// standard for []metav1.Condition
gvr("admissionregistration.k8s.io", "v1alpha1", "validatingadmissionpolicies"): `{"status": {"conditions":[{"type":"Accepted","status":"False","lastTransitionTime":"2020-01-01T00:00:00Z","reason":"RuleApplied","message":"Rule was applied"}]}}`,
gvr("admissionregistration.k8s.io", "v1beta1", "validatingadmissionpolicies"): `{"status": {"conditions":[{"type":"Accepted","status":"False","lastTransitionTime":"2020-01-01T00:00:00Z","reason":"RuleApplied","message":"Rule was applied"}]}}`,
gvr("admissionregistration.k8s.io", "v1", "validatingadmissionpolicies"): `{"status": {"conditions":[{"type":"Accepted","status":"False","lastTransitionTime":"2020-01-01T00:00:00Z","reason":"RuleApplied","message":"Rule was applied"}]}}`,
}
const statusDefault = `{"status": {"conditions": [{"type": "MyStatus", "status":"True"}]}}`

View File

@ -143,6 +143,9 @@ var (
gvr("admissionregistration.k8s.io", "v1beta1", "validatingadmissionpolicies"): true,
gvr("admissionregistration.k8s.io", "v1beta1", "validatingadmissionpolicies/status"): true,
gvr("admissionregistration.k8s.io", "v1beta1", "validatingadmissionpolicybindings"): true,
gvr("admissionregistration.k8s.io", "v1", "validatingadmissionpolicies"): true,
gvr("admissionregistration.k8s.io", "v1", "validatingadmissionpolicies/status"): true,
gvr("admissionregistration.k8s.io", "v1", "validatingadmissionpolicybindings"): true,
// transient resource exemption
gvr("authentication.k8s.io", "v1", "selfsubjectreviews"): true,
gvr("authentication.k8s.io", "v1beta1", "selfsubjectreviews"): true,

View File

@ -339,6 +339,16 @@ func GetEtcdStorageDataForNamespace(namespace string) map[schema.GroupVersionRes
Stub: `{"metadata":{"name":"hook2","creationTimestamp":null},"webhooks":[{"name":"externaladmissionhook.k8s.io","clientConfig":{"service":{"namespace":"ns","name":"n"},"caBundle":null},"rules":[{"operations":["CREATE"],"apiGroups":["group"],"apiVersions":["version"],"resources":["resource"]}],"failurePolicy":"Ignore","sideEffects":"None","admissionReviewVersions":["v1beta1"]}]}`,
ExpectedEtcdPath: "/registry/mutatingwebhookconfigurations/hook2",
},
gvr("admissionregistration.k8s.io", "v1", "validatingadmissionpolicies"): {
Stub: `{"metadata":{"name":"vap1","creationTimestamp":null},"spec":{"paramKind":{"apiVersion":"test.example.com/v1","kind":"Example"},"matchConstraints":{"resourceRules": [{"resourceNames": ["fakeName"], "apiGroups":["apps"],"apiVersions":["v1"],"operations":["CREATE", "UPDATE"], "resources":["deployments"]}]},"validations":[{"expression":"object.spec.replicas <= params.maxReplicas","message":"Too many replicas"}]}}`,
ExpectedEtcdPath: "/registry/validatingadmissionpolicies/vap1",
ExpectedGVK: gvkP("admissionregistration.k8s.io", "v1beta1", "ValidatingAdmissionPolicy"),
},
gvr("admissionregistration.k8s.io", "v1", "validatingadmissionpolicybindings"): {
Stub: `{"metadata":{"name":"pb1","creationTimestamp":null},"spec":{"policyName":"replicalimit-policy.example.com","paramRef":{"name":"replica-limit-test.example.com","parameterNotFoundAction":"Deny"},"validationActions":["Deny"]}}`,
ExpectedEtcdPath: "/registry/validatingadmissionpolicybindings/pb1",
ExpectedGVK: gvkP("admissionregistration.k8s.io", "v1beta1", "ValidatingAdmissionPolicyBinding"),
},
// --
// k8s.io/kubernetes/pkg/apis/admissionregistration/v1beta1
@ -354,13 +364,13 @@ func GetEtcdStorageDataForNamespace(namespace string) map[schema.GroupVersionRes
// k8s.io/kubernetes/pkg/apis/admissionregistration/v1alpha1
gvr("admissionregistration.k8s.io", "v1alpha1", "validatingadmissionpolicies"): {
Stub: `{"metadata":{"name":"vap1","creationTimestamp":null},"spec":{"paramKind":{"apiVersion":"test.example.com/v1","kind":"Example"},"matchConstraints":{"resourceRules": [{"resourceNames": ["fakeName"], "apiGroups":["apps"],"apiVersions":["v1"],"operations":["CREATE", "UPDATE"], "resources":["deployments"]}]},"validations":[{"expression":"object.spec.replicas <= params.maxReplicas","message":"Too many replicas"}]}}`,
ExpectedEtcdPath: "/registry/validatingadmissionpolicies/vap1",
Stub: `{"metadata":{"name":"vap1a1","creationTimestamp":null},"spec":{"paramKind":{"apiVersion":"test.example.com/v1","kind":"Example"},"matchConstraints":{"resourceRules": [{"resourceNames": ["fakeName"], "apiGroups":["apps"],"apiVersions":["v1"],"operations":["CREATE", "UPDATE"], "resources":["deployments"]}]},"validations":[{"expression":"object.spec.replicas <= params.maxReplicas","message":"Too many replicas"}]}}`,
ExpectedEtcdPath: "/registry/validatingadmissionpolicies/vap1a1",
ExpectedGVK: gvkP("admissionregistration.k8s.io", "v1beta1", "ValidatingAdmissionPolicy"),
},
gvr("admissionregistration.k8s.io", "v1alpha1", "validatingadmissionpolicybindings"): {
Stub: `{"metadata":{"name":"pb1","creationTimestamp":null},"spec":{"policyName":"replicalimit-policy.example.com","paramRef":{"name":"replica-limit-test.example.com"},"validationActions":["Deny"]}}`,
ExpectedEtcdPath: "/registry/validatingadmissionpolicybindings/pb1",
Stub: `{"metadata":{"name":"pb1a1","creationTimestamp":null},"spec":{"policyName":"replicalimit-policy.example.com","paramRef":{"name":"replica-limit-test.example.com"},"validationActions":["Deny"]}}`,
ExpectedEtcdPath: "/registry/validatingadmissionpolicybindings/pb1a1",
ExpectedGVK: gvkP("admissionregistration.k8s.io", "v1beta1", "ValidatingAdmissionPolicyBinding"),
},
// --