Plumb context to admission Admit/Validate

This commit is contained in:
Jordan Liggitt 2019-08-19 10:48:08 -04:00
parent 89d5c1f3ea
commit 61774cd717
109 changed files with 404 additions and 323 deletions

View File

@ -17,6 +17,7 @@ limitations under the License.
package admission package admission
import ( import (
"context"
"testing" "testing"
"k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/admission"
@ -24,7 +25,7 @@ import (
type doNothingAdmission struct{} type doNothingAdmission struct{}
func (doNothingAdmission) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (doNothingAdmission) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
return nil return nil
} }
func (doNothingAdmission) Handles(o admission.Operation) bool { return false } func (doNothingAdmission) Handles(o admission.Operation) bool { return false }

View File

@ -177,7 +177,7 @@ func (r *RollbackREST) Create(ctx context.Context, name string, obj runtime.Obje
} }
if createValidation != nil { if createValidation != nil {
if err := createValidation(obj.DeepCopyObject()); err != nil { if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
return nil, err return nil, err
} }
} }
@ -320,17 +320,17 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update
} }
func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc { func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc {
return func(obj runtime.Object) error { return func(ctx context.Context, obj runtime.Object) error {
scale, err := scaleFromDeployment(obj.(*apps.Deployment)) scale, err := scaleFromDeployment(obj.(*apps.Deployment))
if err != nil { if err != nil {
return err return err
} }
return f(scale) return f(ctx, scale)
} }
} }
func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc { func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc {
return func(obj, old runtime.Object) error { return func(ctx context.Context, obj, old runtime.Object) error {
newScale, err := scaleFromDeployment(obj.(*apps.Deployment)) newScale, err := scaleFromDeployment(obj.(*apps.Deployment))
if err != nil { if err != nil {
return err return err
@ -339,7 +339,7 @@ func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjec
if err != nil { if err != nil {
return err return err
} }
return f(newScale, oldScale) return f(ctx, newScale, oldScale)
} }
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package storage package storage
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"reflect" "reflect"
@ -394,7 +395,7 @@ func TestCreateDeploymentRollbackValidation(t *testing.T) {
} }
validationError := fmt.Errorf("admission deny") validationError := fmt.Errorf("admission deny")
alwaysDenyValidationFunc := func(obj runtime.Object) error { return validationError } alwaysDenyValidationFunc := func(ctx context.Context, obj runtime.Object) error { return validationError }
_, err := rollbackStorage.Create(ctx, rollback.Name, &rollback, alwaysDenyValidationFunc, &metav1.CreateOptions{}) _, err := rollbackStorage.Create(ctx, rollback.Name, &rollback, alwaysDenyValidationFunc, &metav1.CreateOptions{})
if err == nil || validationError != err { if err == nil || validationError != err {

View File

@ -225,17 +225,17 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update
} }
func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc { func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc {
return func(obj runtime.Object) error { return func(ctx context.Context, obj runtime.Object) error {
scale, err := scaleFromReplicaSet(obj.(*apps.ReplicaSet)) scale, err := scaleFromReplicaSet(obj.(*apps.ReplicaSet))
if err != nil { if err != nil {
return err return err
} }
return f(scale) return f(ctx, scale)
} }
} }
func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc { func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc {
return func(obj, old runtime.Object) error { return func(ctx context.Context, obj, old runtime.Object) error {
newScale, err := scaleFromReplicaSet(obj.(*apps.ReplicaSet)) newScale, err := scaleFromReplicaSet(obj.(*apps.ReplicaSet))
if err != nil { if err != nil {
return err return err
@ -244,7 +244,7 @@ func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjec
if err != nil { if err != nil {
return err return err
} }
return f(newScale, oldScale) return f(ctx, newScale, oldScale)
} }
} }

View File

@ -212,17 +212,17 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update
} }
func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc { func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc {
return func(obj runtime.Object) error { return func(ctx context.Context, obj runtime.Object) error {
scale, err := scaleFromStatefulSet(obj.(*apps.StatefulSet)) scale, err := scaleFromStatefulSet(obj.(*apps.StatefulSet))
if err != nil { if err != nil {
return err return err
} }
return f(scale) return f(ctx, scale)
} }
} }
func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc { func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc {
return func(obj, old runtime.Object) error { return func(ctx context.Context, obj, old runtime.Object) error {
newScale, err := scaleFromStatefulSet(obj.(*apps.StatefulSet)) newScale, err := scaleFromStatefulSet(obj.(*apps.StatefulSet))
if err != nil { if err != nil {
return err return err
@ -231,7 +231,7 @@ func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjec
if err != nil { if err != nil {
return err return err
} }
return f(newScale, oldScale) return f(ctx, newScale, oldScale)
} }
} }

View File

@ -69,7 +69,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
} }
if createValidation != nil { if createValidation != nil {
if err := createValidation(obj.DeepCopyObject()); err != nil { if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
return nil, err return nil, err
} }
} }

View File

@ -64,7 +64,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
} }
if createValidation != nil { if createValidation != nil {
if err := createValidation(obj.DeepCopyObject()); err != nil { if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
return nil, err return nil, err
} }
} }

View File

@ -61,7 +61,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
} }
if createValidation != nil { if createValidation != nil {
if err := createValidation(obj.DeepCopyObject()); err != nil { if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
return nil, err return nil, err
} }
} }

View File

@ -67,7 +67,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
} }
if createValidation != nil { if createValidation != nil {
if err := createValidation(obj.DeepCopyObject()); err != nil { if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
return nil, err return nil, err
} }
} }

View File

@ -56,7 +56,7 @@ func (r *REST) Create(ctx context.Context, obj runtime.Object, createValidation
} }
if createValidation != nil { if createValidation != nil {
if err := createValidation(obj.DeepCopyObject()); err != nil { if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
return nil, err return nil, err
} }
} }

View File

@ -178,7 +178,7 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va
// wrong type // wrong type
return nil, fmt.Errorf("expected *api.Namespace, got %v", existing) return nil, fmt.Errorf("expected *api.Namespace, got %v", existing)
} }
if err := deleteValidation(existingNamespace); err != nil { if err := deleteValidation(ctx, existingNamespace); err != nil {
return nil, err return nil, err
} }
// Set the deletion timestamp if needed // Set the deletion timestamp if needed

View File

@ -116,7 +116,7 @@ func (r *EvictionREST) Create(ctx context.Context, obj runtime.Object, createVal
pod := obj.(*api.Pod) pod := obj.(*api.Pod)
if createValidation != nil { if createValidation != nil {
if err := createValidation(eviction.DeepCopyObject()); err != nil { if err := createValidation(ctx, eviction.DeepCopyObject()); err != nil {
return nil, err return nil, err
} }
} }

View File

@ -160,7 +160,7 @@ func (r *BindingREST) Create(ctx context.Context, obj runtime.Object, createVali
} }
if createValidation != nil { if createValidation != nil {
if err := createValidation(binding.DeepCopyObject()); err != nil { if err := createValidation(ctx, binding.DeepCopyObject()); err != nil {
return nil, err return nil, err
} }
} }

View File

@ -203,14 +203,15 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update
} }
func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc { func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc {
return func(obj runtime.Object) error { return func(ctx context.Context, obj runtime.Object) error {
return f(scaleFromRC(obj.(*api.ReplicationController))) return f(ctx, scaleFromRC(obj.(*api.ReplicationController)))
} }
} }
func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc { func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc {
return func(obj, old runtime.Object) error { return func(ctx context.Context, obj, old runtime.Object) error {
return f( return f(
ctx,
scaleFromRC(obj.(*api.ReplicationController)), scaleFromRC(obj.(*api.ReplicationController)),
scaleFromRC(old.(*api.ReplicationController)), scaleFromRC(old.(*api.ReplicationController)),
) )

View File

@ -59,7 +59,7 @@ var gvk = schema.GroupVersionKind{
func (r *TokenREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) { func (r *TokenREST) Create(ctx context.Context, name string, obj runtime.Object, createValidation rest.ValidateObjectFunc, options *metav1.CreateOptions) (runtime.Object, error) {
if createValidation != nil { if createValidation != nil {
if err := createValidation(obj.DeepCopyObject()); err != nil { if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
return nil, err return nil, err
} }
} }

View File

@ -115,14 +115,15 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update
} }
func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc { func toScaleCreateValidation(f rest.ValidateObjectFunc) rest.ValidateObjectFunc {
return func(obj runtime.Object) error { return func(ctx context.Context, obj runtime.Object) error {
return f(scaleFromRC(obj.(*api.ReplicationController))) return f(ctx, scaleFromRC(obj.(*api.ReplicationController)))
} }
} }
func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc { func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc) rest.ValidateObjectUpdateFunc {
return func(obj, old runtime.Object) error { return func(ctx context.Context, obj, old runtime.Object) error {
return f( return f(
ctx,
scaleFromRC(obj.(*api.ReplicationController)), scaleFromRC(obj.(*api.ReplicationController)),
scaleFromRC(old.(*api.ReplicationController)), scaleFromRC(old.(*api.ReplicationController)),
) )

View File

@ -17,6 +17,7 @@ limitations under the License.
package admit package admit
import ( import (
"context"
"io" "io"
"k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/admission"
@ -40,12 +41,12 @@ var _ admission.MutationInterface = alwaysAdmit{}
var _ admission.ValidationInterface = alwaysAdmit{} var _ admission.ValidationInterface = alwaysAdmit{}
// Admit makes an admission decision based on the request attributes // Admit makes an admission decision based on the request attributes
func (alwaysAdmit) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (alwaysAdmit) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
return nil return nil
} }
// Validate makes an admission decision based on the request attributes. It is NOT allowed to mutate. // Validate makes an admission decision based on the request attributes. It is NOT allowed to mutate.
func (alwaysAdmit) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (alwaysAdmit) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
return nil return nil
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package admit package admit
import ( import (
"context"
"testing" "testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -27,7 +28,7 @@ import (
func TestAdmissionNonNilAttribute(t *testing.T) { func TestAdmissionNonNilAttribute(t *testing.T) {
handler := admissiontesting.WithReinvocationTesting(t, NewAlwaysAdmit().(*alwaysAdmit)) handler := admissiontesting.WithReinvocationTesting(t, NewAlwaysAdmit().(*alwaysAdmit))
err := handler.Admit(admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error returned from admission handler") t.Errorf("Unexpected error returned from admission handler")
} }
@ -35,7 +36,7 @@ func TestAdmissionNonNilAttribute(t *testing.T) {
func TestAdmissionNilAttribute(t *testing.T) { func TestAdmissionNilAttribute(t *testing.T) {
handler := NewAlwaysAdmit() handler := NewAlwaysAdmit()
err := handler.(*alwaysAdmit).Admit(nil, nil) err := handler.(*alwaysAdmit).Admit(context.TODO(), nil, nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error returned from admission handler") t.Errorf("Unexpected error returned from admission handler")
} }

View File

@ -25,6 +25,7 @@ limitations under the License.
package alwayspullimages package alwayspullimages
import ( import (
"context"
"io" "io"
apierrors "k8s.io/apimachinery/pkg/api/errors" apierrors "k8s.io/apimachinery/pkg/api/errors"
@ -55,7 +56,7 @@ var _ admission.MutationInterface = &AlwaysPullImages{}
var _ admission.ValidationInterface = &AlwaysPullImages{} var _ admission.ValidationInterface = &AlwaysPullImages{}
// Admit makes an admission decision based on the request attributes // Admit makes an admission decision based on the request attributes
func (a *AlwaysPullImages) Admit(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { func (a *AlwaysPullImages) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {
// Ignore all calls to subresources or resources other than pods. // Ignore all calls to subresources or resources other than pods.
if shouldIgnore(attributes) { if shouldIgnore(attributes) {
return nil return nil
@ -74,7 +75,7 @@ func (a *AlwaysPullImages) Admit(attributes admission.Attributes, o admission.Ob
} }
// Validate makes sure that all containers are set to always pull images // Validate makes sure that all containers are set to always pull images
func (*AlwaysPullImages) Validate(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { func (*AlwaysPullImages) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {
if shouldIgnore(attributes) { if shouldIgnore(attributes) {
return nil return nil
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package alwayspullimages package alwayspullimages
import ( import (
"context"
"testing" "testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -48,7 +49,7 @@ func TestAdmission(t *testing.T) {
}, },
}, },
} }
err := handler.Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error returned from admission handler") t.Errorf("Unexpected error returned from admission handler")
} }
@ -91,7 +92,7 @@ func TestValidate(t *testing.T) {
`pods "123" is forbidden: spec.containers[0].imagePullPolicy: Unsupported value: "": supported values: "Always", ` + `pods "123" is forbidden: spec.containers[0].imagePullPolicy: Unsupported value: "": supported values: "Always", ` +
`pods "123" is forbidden: spec.containers[1].imagePullPolicy: Unsupported value: "Never": supported values: "Always", ` + `pods "123" is forbidden: spec.containers[1].imagePullPolicy: Unsupported value: "Never": supported values: "Always", ` +
`pods "123" is forbidden: spec.containers[2].imagePullPolicy: Unsupported value: "IfNotPresent": supported values: "Always"]` `pods "123" is forbidden: spec.containers[2].imagePullPolicy: Unsupported value: "IfNotPresent": supported values: "Always"]`
err := handler.Validate(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Fatal("missing expected error") t.Fatal("missing expected error")
} }
@ -146,7 +147,7 @@ func TestOtherResources(t *testing.T) {
for _, tc := range tests { for _, tc := range tests {
handler := admissiontesting.WithReinvocationTesting(t, &AlwaysPullImages{}) handler := admissiontesting.WithReinvocationTesting(t, &AlwaysPullImages{})
err := handler.Admit(admission.NewAttributesRecord(tc.object, nil, api.Kind(tc.kind).WithVersion("version"), namespace, name, api.Resource(tc.resource).WithVersion("version"), tc.subresource, admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Admit(context.TODO(), admission.NewAttributesRecord(tc.object, nil, api.Kind(tc.kind).WithVersion("version"), namespace, name, api.Resource(tc.resource).WithVersion("version"), tc.subresource, admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if tc.expectError { if tc.expectError {
if err == nil { if err == nil {

View File

@ -17,6 +17,7 @@ limitations under the License.
package antiaffinity package antiaffinity
import ( import (
"context"
"fmt" "fmt"
"io" "io"
@ -52,7 +53,7 @@ func NewInterPodAntiAffinity() *Plugin {
// Validate will deny any pod that defines AntiAffinity topology key other than v1.LabelHostname i.e. "kubernetes.io/hostname" // Validate will deny any pod that defines AntiAffinity topology key other than v1.LabelHostname i.e. "kubernetes.io/hostname"
// in requiredDuringSchedulingRequiredDuringExecution and requiredDuringSchedulingIgnoredDuringExecution. // in requiredDuringSchedulingRequiredDuringExecution and requiredDuringSchedulingIgnoredDuringExecution.
func (p *Plugin) Validate(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { func (p *Plugin) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {
// Ignore all calls to subresources or resources other than pods. // Ignore all calls to subresources or resources other than pods.
if len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != api.Resource("pods") { if len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != api.Resource("pods") {
return nil return nil

View File

@ -17,6 +17,7 @@ limitations under the License.
package antiaffinity package antiaffinity
import ( import (
"context"
"testing" "testing"
v1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
@ -199,7 +200,7 @@ func TestInterPodAffinityAdmission(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
pod.Spec.Affinity = test.affinity pod.Spec.Affinity = test.affinity
err := handler.Validate(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil)
if test.errorExpected && err == nil { if test.errorExpected && err == nil {
t.Errorf("Expected error for Anti Affinity %+v but did not get an error", test.affinity) t.Errorf("Expected error for Anti Affinity %+v but did not get an error", test.affinity)
@ -267,7 +268,7 @@ func TestOtherResources(t *testing.T) {
for _, tc := range tests { for _, tc := range tests {
handler := &Plugin{} handler := &Plugin{}
err := handler.Validate(admission.NewAttributesRecord(tc.object, nil, api.Kind(tc.kind).WithVersion("version"), namespace, name, api.Resource(tc.resource).WithVersion("version"), tc.subresource, admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(tc.object, nil, api.Kind(tc.kind).WithVersion("version"), namespace, name, api.Resource(tc.resource).WithVersion("version"), tc.subresource, admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if tc.expectError { if tc.expectError {
if err == nil { if err == nil {

View File

@ -17,6 +17,7 @@ limitations under the License.
package defaulttolerationseconds package defaulttolerationseconds
import ( import (
"context"
"flag" "flag"
"fmt" "fmt"
"io" "io"
@ -81,7 +82,7 @@ func NewDefaultTolerationSeconds() *Plugin {
} }
// Admit makes an admission decision based on the request attributes // Admit makes an admission decision based on the request attributes
func (p *Plugin) Admit(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { func (p *Plugin) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {
if attributes.GetResource().GroupResource() != api.Resource("pods") { if attributes.GetResource().GroupResource() != api.Resource("pods") {
return nil return nil
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package defaulttolerationseconds package defaulttolerationseconds
import ( import (
"context"
"testing" "testing"
"k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/admission"
@ -264,7 +265,7 @@ func TestForgivenessAdmission(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
err := handler.Admit(admission.NewAttributesRecord(&test.requestedPod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) err := handler.Admit(context.TODO(), admission.NewAttributesRecord(&test.requestedPod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("[%s]: unexpected error %v for pod %+v", test.description, err, test.requestedPod) t.Errorf("[%s]: unexpected error %v for pod %+v", test.description, err, test.requestedPod)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package deny package deny
import ( import (
"context"
"errors" "errors"
"io" "io"
@ -42,12 +43,12 @@ var _ admission.MutationInterface = alwaysDeny{}
var _ admission.ValidationInterface = alwaysDeny{} var _ admission.ValidationInterface = alwaysDeny{}
// Admit makes an admission decision based on the request attributes. // Admit makes an admission decision based on the request attributes.
func (alwaysDeny) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (alwaysDeny) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
return admission.NewForbidden(a, errors.New("admission control is denying all modifications")) return admission.NewForbidden(a, errors.New("admission control is denying all modifications"))
} }
// Validate makes an admission decision based on the request attributes. It is NOT allowed to mutate. // Validate makes an admission decision based on the request attributes. It is NOT allowed to mutate.
func (alwaysDeny) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (alwaysDeny) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
return admission.NewForbidden(a, errors.New("admission control is denying all modifications")) return admission.NewForbidden(a, errors.New("admission control is denying all modifications"))
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package deny package deny
import ( import (
"context"
"testing" "testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -27,7 +28,7 @@ import (
func TestAdmission(t *testing.T) { func TestAdmission(t *testing.T) {
handler := admissiontesting.WithReinvocationTesting(t, NewAlwaysDeny().(*alwaysDeny)) handler := admissiontesting.WithReinvocationTesting(t, NewAlwaysDeny().(*alwaysDeny))
err := handler.Admit(admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Error("Expected error returned from admission handler") t.Error("Expected error returned from admission handler")
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package eventratelimit package eventratelimit
import ( import (
"context"
"io" "io"
apierrors "k8s.io/apimachinery/pkg/api/errors" apierrors "k8s.io/apimachinery/pkg/api/errors"
@ -81,7 +82,7 @@ func newEventRateLimit(config *eventratelimitapi.Configuration, clock flowcontro
} }
// Validate makes admission decisions while enforcing event rate limits // Validate makes admission decisions while enforcing event rate limits
func (a *Plugin) Validate(attr admission.Attributes, o admission.ObjectInterfaces) (err error) { func (a *Plugin) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) (err error) {
// ignore all operations that do not correspond to an Event kind // ignore all operations that do not correspond to an Event kind
if attr.GetKind().GroupKind() != api.Kind("Event") { if attr.GetKind().GroupKind() != api.Kind("Event") {
return nil return nil

View File

@ -17,6 +17,7 @@ limitations under the License.
package eventratelimit package eventratelimit
import ( import (
"context"
"net/http" "net/http"
"testing" "testing"
"time" "time"
@ -507,7 +508,7 @@ func TestEventRateLimiting(t *testing.T) {
clock.Step(rq.delay) clock.Step(rq.delay)
} }
attributes := attributesForRequest(rq) attributes := attributesForRequest(rq)
err = eventratelimit.Validate(attributes, nil) err = eventratelimit.Validate(context.TODO(), attributes, nil)
if rq.accepted != (err == nil) { if rq.accepted != (err == nil) {
expectedAction := "admitted" expectedAction := "admitted"
if !rq.accepted { if !rq.accepted {

View File

@ -17,6 +17,7 @@ limitations under the License.
package exec package exec
import ( import (
"context"
"fmt" "fmt"
"io" "io"
@ -112,7 +113,7 @@ func (d *DenyExec) ValidateInitialization() error {
} }
// Validate makes an admission decision based on the request attributes // Validate makes an admission decision based on the request attributes
func (d *DenyExec) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (d *DenyExec) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
path := a.GetResource().Resource path := a.GetResource().Resource
if subresource := a.GetSubresource(); subresource != "" { if subresource := a.GetSubresource(); subresource != "" {
path = path + "/" + subresource path = path + "/" + subresource

View File

@ -17,6 +17,7 @@ limitations under the License.
package exec package exec
import ( import (
"context"
"testing" "testing"
corev1 "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1"
@ -120,7 +121,7 @@ func testAdmission(t *testing.T, pod *corev1.Pod, handler *DenyExec, shouldAccep
// pods/exec // pods/exec
{ {
err := handler.Validate(admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), "test", pod.Name, api.Resource("pods").WithVersion("version"), "exec", admission.Connect, nil, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), "test", pod.Name, api.Resource("pods").WithVersion("version"), "exec", admission.Connect, nil, false, nil), nil)
if shouldAccept && err != nil { if shouldAccept && err != nil {
t.Errorf("Unexpected error returned from admission handler: %v", err) t.Errorf("Unexpected error returned from admission handler: %v", err)
} }
@ -131,7 +132,7 @@ func testAdmission(t *testing.T, pod *corev1.Pod, handler *DenyExec, shouldAccep
// pods/attach // pods/attach
{ {
err := handler.Validate(admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), "test", pod.Name, api.Resource("pods").WithVersion("version"), "attach", admission.Connect, nil, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), "test", pod.Name, api.Resource("pods").WithVersion("version"), "attach", admission.Connect, nil, false, nil), nil)
if shouldAccept && err != nil { if shouldAccept && err != nil {
t.Errorf("Unexpected error returned from admission handler: %v", err) t.Errorf("Unexpected error returned from admission handler: %v", err)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package extendedresourcetoleration package extendedresourcetoleration
import ( import (
"context"
"fmt" "fmt"
"io" "io"
@ -56,7 +57,7 @@ type plugin struct {
// a toleration with key "example.com/device", operator "Exists" and effect "NoSchedule". // a toleration with key "example.com/device", operator "Exists" and effect "NoSchedule".
// The rationale for this is described in: // The rationale for this is described in:
// https://github.com/kubernetes/kubernetes/issues/55080 // https://github.com/kubernetes/kubernetes/issues/55080
func (p *plugin) Admit(attributes admission.Attributes, o admission.ObjectInterfaces) error { func (p *plugin) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error {
// Ignore all calls to subresources or resources other than pods. // Ignore all calls to subresources or resources other than pods.
if len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != core.Resource("pods") { if len(attributes.GetSubresource()) != 0 || attributes.GetResource().GroupResource() != core.Resource("pods") {
return nil return nil

View File

@ -17,6 +17,7 @@ limitations under the License.
package extendedresourcetoleration package extendedresourcetoleration
import ( import (
"context"
"testing" "testing"
"k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/api/resource"
@ -355,7 +356,7 @@ func TestAdmit(t *testing.T) {
}, },
} }
for i, test := range tests { for i, test := range tests {
err := plugin.Admit(admission.NewAttributesRecord(&test.requestedPod, nil, core.Kind("Pod").WithVersion("version"), "foo", "name", core.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) err := plugin.Admit(context.TODO(), admission.NewAttributesRecord(&test.requestedPod, nil, core.Kind("Pod").WithVersion("version"), "foo", "name", core.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("[%d: %s] unexpected error %v for pod %+v", i, test.description, err, test.requestedPod) t.Errorf("[%d: %s] unexpected error %v for pod %+v", i, test.description, err, test.requestedPod)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package gc package gc
import ( import (
"context"
"fmt" "fmt"
"io" "io"
@ -84,7 +85,7 @@ func (a *gcPermissionsEnforcement) isWhiteListed(groupResource schema.GroupResou
return false return false
} }
func (a *gcPermissionsEnforcement) Validate(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { func (a *gcPermissionsEnforcement) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {
// // if the request is in the whitelist, we skip mutation checks for this resource. // // if the request is in the whitelist, we skip mutation checks for this resource.
if a.isWhiteListed(attributes.GetResource().GroupResource(), attributes.GetSubresource()) { if a.isWhiteListed(attributes.GetResource().GroupResource(), attributes.GetSubresource()) {
return nil return nil

View File

@ -17,6 +17,7 @@ limitations under the License.
package gc package gc
import ( import (
"context"
"fmt" "fmt"
"strings" "strings"
"testing" "testing"
@ -310,7 +311,7 @@ func TestGCAdmission(t *testing.T) {
user := &user.DefaultInfo{Name: tc.username} user := &user.DefaultInfo{Name: tc.username}
attributes := admission.NewAttributesRecord(tc.newObj, tc.oldObj, schema.GroupVersionKind{}, metav1.NamespaceDefault, "foo", tc.resource, tc.subresource, operation, options, false, user) attributes := admission.NewAttributesRecord(tc.newObj, tc.oldObj, schema.GroupVersionKind{}, metav1.NamespaceDefault, "foo", tc.resource, tc.subresource, operation, options, false, user)
err = gcAdmit.Validate(attributes, nil) err = gcAdmit.Validate(context.TODO(), attributes, nil)
if !tc.checkError(err) { if !tc.checkError(err) {
t.Errorf("unexpected err: %v", err) t.Errorf("unexpected err: %v", err)
} }
@ -615,7 +616,7 @@ func TestBlockOwnerDeletionAdmission(t *testing.T) {
user := &user.DefaultInfo{Name: tc.username} user := &user.DefaultInfo{Name: tc.username}
attributes := admission.NewAttributesRecord(tc.newObj, tc.oldObj, schema.GroupVersionKind{}, metav1.NamespaceDefault, "foo", tc.resource, tc.subresource, operation, options, false, user) attributes := admission.NewAttributesRecord(tc.newObj, tc.oldObj, schema.GroupVersionKind{}, metav1.NamespaceDefault, "foo", tc.resource, tc.subresource, operation, options, false, user)
err := gcAdmit.Validate(attributes, nil) err := gcAdmit.Validate(context.TODO(), attributes, nil)
if !tc.checkError(err) { if !tc.checkError(err) {
t.Errorf("%v: unexpected err: %v", tc.name, err) t.Errorf("%v: unexpected err: %v", tc.name, err)
} }

View File

@ -19,6 +19,7 @@ limitations under the License.
package imagepolicy package imagepolicy
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -131,7 +132,7 @@ func (a *Plugin) webhookError(pod *api.Pod, attributes admission.Attributes, err
} }
// Validate makes an admission decision based on the request attributes // Validate makes an admission decision based on the request attributes
func (a *Plugin) Validate(attributes admission.Attributes, o admission.ObjectInterfaces) (err error) { func (a *Plugin) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) (err error) {
// Ignore all calls to subresources or resources other than pods. // Ignore all calls to subresources or resources other than pods.
if attributes.GetSubresource() != "" || attributes.GetResource().GroupResource() != api.Resource("pods") { if attributes.GetSubresource() != "" || attributes.GetResource().GroupResource() != api.Resource("pods") {
return nil return nil

View File

@ -17,6 +17,7 @@ limitations under the License.
package imagepolicy package imagepolicy
import ( import (
"context"
"crypto/tls" "crypto/tls"
"crypto/x509" "crypto/x509"
"encoding/json" "encoding/json"
@ -488,7 +489,7 @@ func TestTLSConfig(t *testing.T) {
// Allow all and see if we get an error. // Allow all and see if we get an error.
service.Allow() service.Allow()
err = wh.Validate(attr, nil) err = wh.Validate(context.TODO(), attr, nil)
if tt.wantAllowed { if tt.wantAllowed {
if err != nil { if err != nil {
t.Errorf("expected successful admission") t.Errorf("expected successful admission")
@ -510,7 +511,7 @@ func TestTLSConfig(t *testing.T) {
} }
service.Deny() service.Deny()
if err := wh.Validate(attr, nil); err == nil { if err := wh.Validate(context.TODO(), attr, nil); err == nil {
t.Errorf("%s: incorrectly admitted with DenyAll policy", tt.test) t.Errorf("%s: incorrectly admitted with DenyAll policy", tt.test)
} }
}) })
@ -527,7 +528,7 @@ type webhookCacheTestCase struct {
func testWebhookCacheCases(t *testing.T, serv *mockService, wh *Plugin, attr admission.Attributes, tests []webhookCacheTestCase) { func testWebhookCacheCases(t *testing.T, serv *mockService, wh *Plugin, attr admission.Attributes, tests []webhookCacheTestCase) {
for _, test := range tests { for _, test := range tests {
serv.statusCode = test.statusCode serv.statusCode = test.statusCode
err := wh.Validate(attr, nil) err := wh.Validate(context.TODO(), attr, nil)
authorized := err == nil authorized := err == nil
if test.expectedErr && err == nil { if test.expectedErr && err == nil {
@ -760,7 +761,7 @@ func TestContainerCombinations(t *testing.T) {
attr := admission.NewAttributesRecord(tt.pod, nil, api.Kind("Pod").WithVersion("version"), "namespace", "", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{}) attr := admission.NewAttributesRecord(tt.pod, nil, api.Kind("Pod").WithVersion("version"), "namespace", "", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{})
err = wh.Validate(attr, nil) err = wh.Validate(context.TODO(), attr, nil)
if tt.wantAllowed { if tt.wantAllowed {
if err != nil { if err != nil {
t.Errorf("expected successful admission: %s", tt.test) t.Errorf("expected successful admission: %s", tt.test)
@ -856,7 +857,7 @@ func TestDefaultAllow(t *testing.T) {
annotations := make(map[string]string) annotations := make(map[string]string)
attr = &fakeAttributes{attr, annotations} attr = &fakeAttributes{attr, annotations}
err = wh.Validate(attr, nil) err = wh.Validate(context.TODO(), attr, nil)
if tt.wantAllowed { if tt.wantAllowed {
if err != nil { if err != nil {
t.Errorf("expected successful admission") t.Errorf("expected successful admission")
@ -964,7 +965,7 @@ func TestAnnotationFiltering(t *testing.T) {
attr := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "namespace", "", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{}) attr := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "namespace", "", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{})
err = wh.Validate(attr, nil) err = wh.Validate(context.TODO(), attr, nil)
if err != nil { if err != nil {
t.Errorf("expected successful admission") t.Errorf("expected successful admission")
} }
@ -1056,7 +1057,7 @@ func TestReturnedAnnotationAdd(t *testing.T) {
annotations := make(map[string]string) annotations := make(map[string]string)
attr = &fakeAttributes{attr, annotations} attr = &fakeAttributes{attr, annotations}
err = wh.Validate(attr, nil) err = wh.Validate(context.TODO(), attr, nil)
if !reflect.DeepEqual(annotations, tt.expectedAnnotations) { if !reflect.DeepEqual(annotations, tt.expectedAnnotations) {
t.Errorf("got audit annotations: %v; want: %v", annotations, tt.expectedAnnotations) t.Errorf("got audit annotations: %v; want: %v", annotations, tt.expectedAnnotations)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package limitranger package limitranger
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"sort" "sort"
@ -102,12 +103,12 @@ func (l *LimitRanger) ValidateInitialization() error {
} }
// Admit admits resources into cluster that do not violate any defined LimitRange in the namespace // Admit admits resources into cluster that do not violate any defined LimitRange in the namespace
func (l *LimitRanger) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (l *LimitRanger) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
return l.runLimitFunc(a, l.actions.MutateLimit) return l.runLimitFunc(a, l.actions.MutateLimit)
} }
// Validate admits resources into cluster that do not violate any defined LimitRange in the namespace // Validate admits resources into cluster that do not violate any defined LimitRange in the namespace
func (l *LimitRanger) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (l *LimitRanger) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
return l.runLimitFunc(a, l.actions.ValidateLimit) return l.runLimitFunc(a, l.actions.ValidateLimit)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package limitranger package limitranger
import ( import (
"context"
"fmt" "fmt"
"strconv" "strconv"
"testing" "testing"
@ -706,20 +707,20 @@ func TestLimitRangerIgnoresSubresource(t *testing.T) {
informerFactory.Start(wait.NeverStop) informerFactory.Start(wait.NeverStop)
testPod := validPod("testPod", 1, api.ResourceRequirements{}) testPod := validPod("testPod", 1, api.ResourceRequirements{})
err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected an error since the pod did not specify resource limits in its create call") t.Errorf("Expected an error since the pod did not specify resource limits in its create call")
} }
err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Expected not to call limitranger actions on pod updates") t.Errorf("Expected not to call limitranger actions on pod updates")
} }
err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "status", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "status", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Should have ignored calls to any subresource of pod %v", err) t.Errorf("Should have ignored calls to any subresource of pod %v", err)
} }
@ -736,20 +737,20 @@ func TestLimitRangerAdmitPod(t *testing.T) {
informerFactory.Start(wait.NeverStop) informerFactory.Start(wait.NeverStop)
testPod := validPod("testPod", 1, api.ResourceRequirements{}) testPod := validPod("testPod", 1, api.ResourceRequirements{})
err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected an error since the pod did not specify resource limits in its create call") t.Errorf("Expected an error since the pod did not specify resource limits in its create call")
} }
err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Expected not to call limitranger actions on pod updates") t.Errorf("Expected not to call limitranger actions on pod updates")
} }
err = handler.Validate(admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "status", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&testPod, nil, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "testPod", api.Resource("pods").WithVersion("version"), "status", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Should have ignored calls to any subresource of pod %v", err) t.Errorf("Should have ignored calls to any subresource of pod %v", err)
} }
@ -758,7 +759,7 @@ func TestLimitRangerAdmitPod(t *testing.T) {
terminatingPod := validPod("terminatingPod", 1, api.ResourceRequirements{}) terminatingPod := validPod("terminatingPod", 1, api.ResourceRequirements{})
now := metav1.Now() now := metav1.Now()
terminatingPod.DeletionTimestamp = &now terminatingPod.DeletionTimestamp = &now
err = handler.Validate(admission.NewAttributesRecord(&terminatingPod, &terminatingPod, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "terminatingPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&terminatingPod, &terminatingPod, api.Kind("Pod").WithVersion("version"), limitRange.Namespace, "terminatingPod", api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("LimitRange should ignore a pod marked for termination") t.Errorf("LimitRange should ignore a pod marked for termination")
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package autoprovision package autoprovision
import ( import (
"context"
"fmt" "fmt"
"io" "io"
@ -55,7 +56,7 @@ var _ = genericadmissioninitializer.WantsExternalKubeInformerFactory(&Provision{
var _ = genericadmissioninitializer.WantsExternalKubeClientSet(&Provision{}) var _ = genericadmissioninitializer.WantsExternalKubeClientSet(&Provision{})
// Admit makes an admission decision based on the request attributes // Admit makes an admission decision based on the request attributes
func (p *Provision) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *Provision) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
// Don't create a namespace if the request is for a dry-run. // Don't create a namespace if the request is for a dry-run.
if a.IsDryRun() { if a.IsDryRun() {
return nil return nil

View File

@ -17,6 +17,7 @@ limitations under the License.
package autoprovision package autoprovision
import ( import (
"context"
"fmt" "fmt"
"testing" "testing"
"time" "time"
@ -100,7 +101,7 @@ func TestAdmission(t *testing.T) {
informerFactory.Start(wait.NeverStop) informerFactory.Start(wait.NeverStop)
pod := newPod(namespace) pod := newPod(namespace)
err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("unexpected error returned from admission handler") t.Errorf("unexpected error returned from admission handler")
} }
@ -120,7 +121,7 @@ func TestAdmissionNamespaceExists(t *testing.T) {
informerFactory.Start(wait.NeverStop) informerFactory.Start(wait.NeverStop)
pod := newPod(namespace) pod := newPod(namespace)
err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("unexpected error returned from admission handler") t.Errorf("unexpected error returned from admission handler")
} }
@ -140,7 +141,7 @@ func TestAdmissionDryRun(t *testing.T) {
informerFactory.Start(wait.NeverStop) informerFactory.Start(wait.NeverStop)
pod := newPod(namespace) pod := newPod(namespace)
err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil) err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil)
if err != nil { if err != nil {
t.Errorf("unexpected error returned from admission handler") t.Errorf("unexpected error returned from admission handler")
} }
@ -161,7 +162,7 @@ func TestIgnoreAdmission(t *testing.T) {
chainHandler := admissiontesting.WithReinvocationTesting(t, admission.NewChainHandler(handler)) chainHandler := admissiontesting.WithReinvocationTesting(t, admission.NewChainHandler(handler))
pod := newPod(namespace) pod := newPod(namespace)
err = admissiontesting.WithReinvocationTesting(t, chainHandler).Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err = admissiontesting.WithReinvocationTesting(t, chainHandler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("unexpected error returned from admission handler") t.Errorf("unexpected error returned from admission handler")
} }
@ -183,7 +184,7 @@ func TestAdmissionWithLatentCache(t *testing.T) {
informerFactory.Start(wait.NeverStop) informerFactory.Start(wait.NeverStop)
pod := newPod(namespace) pod := newPod(namespace)
err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("unexpected error returned from admission handler") t.Errorf("unexpected error returned from admission handler")
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package exists package exists
import ( import (
"context"
"fmt" "fmt"
"io" "io"
@ -54,7 +55,7 @@ var _ = genericadmissioninitializer.WantsExternalKubeInformerFactory(&Exists{})
var _ = genericadmissioninitializer.WantsExternalKubeClientSet(&Exists{}) var _ = genericadmissioninitializer.WantsExternalKubeClientSet(&Exists{})
// Validate makes an admission decision based on the request attributes // Validate makes an admission decision based on the request attributes
func (e *Exists) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { func (e *Exists) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
// if we're here, then we've already passed authentication, so we're allowed to do what we're trying to do // if we're here, then we've already passed authentication, so we're allowed to do what we're trying to do
// if we're here, then the API server has found a route, which means that if we have a non-empty namespace // if we're here, then the API server has found a route, which means that if we have a non-empty namespace
// its a namespaced resource. // its a namespaced resource.

View File

@ -17,6 +17,7 @@ limitations under the License.
package exists package exists
import ( import (
"context"
"fmt" "fmt"
"testing" "testing"
"time" "time"
@ -88,7 +89,7 @@ func TestAdmissionNamespaceExists(t *testing.T) {
informerFactory.Start(wait.NeverStop) informerFactory.Start(wait.NeverStop)
pod := newPod(namespace) pod := newPod(namespace)
err = handler.Validate(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("unexpected error returned from admission handler") t.Errorf("unexpected error returned from admission handler")
} }
@ -108,7 +109,7 @@ func TestAdmissionNamespaceDoesNotExist(t *testing.T) {
informerFactory.Start(wait.NeverStop) informerFactory.Start(wait.NeverStop)
pod := newPod(namespace) pod := newPod(namespace)
err = handler.Validate(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
actions := "" actions := ""
for _, action := range mockClient.Actions() { for _, action := range mockClient.Actions() {

View File

@ -17,6 +17,7 @@ limitations under the License.
package noderestriction package noderestriction
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"strings" "strings"
@ -105,7 +106,7 @@ var (
) )
// Admit checks the admission policy and triggers corresponding actions // Admit checks the admission policy and triggers corresponding actions
func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
nodeName, isNode := p.nodeIdentifier.NodeIdentity(a.GetUserInfo()) nodeName, isNode := p.nodeIdentifier.NodeIdentity(a.GetUserInfo())
// Our job is just to restrict nodes // Our job is just to restrict nodes

View File

@ -17,6 +17,7 @@ limitations under the License.
package noderestriction package noderestriction
import ( import (
"context"
"fmt" "fmt"
"reflect" "reflect"
"strings" "strings"
@ -1210,7 +1211,7 @@ func Test_nodePlugin_Admit(t *testing.T) {
c.features = tt.features c.features = tt.features
} }
c.podsGetter = tt.podsGetter c.podsGetter = tt.podsGetter
err := c.Admit(tt.attributes, nil) err := c.Admit(context.TODO(), tt.attributes, nil)
if (err == nil) != (len(tt.err) == 0) { if (err == nil) != (len(tt.err) == 0) {
t.Errorf("nodePlugin.Admit() error = %v, expected %v", err, tt.err) t.Errorf("nodePlugin.Admit() error = %v, expected %v", err, tt.err)
return return

View File

@ -17,8 +17,10 @@ limitations under the License.
package nodetaint package nodetaint
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/admission"
utilfeature "k8s.io/apiserver/pkg/util/feature" utilfeature "k8s.io/apiserver/pkg/util/feature"
"k8s.io/component-base/featuregate" "k8s.io/component-base/featuregate"
@ -65,7 +67,7 @@ var (
) )
// Admit is the main function that checks node identity and adds taints as needed. // Admit is the main function that checks node identity and adds taints as needed.
func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
// If TaintNodesByCondition is not enabled, we don't need to do anything. // If TaintNodesByCondition is not enabled, we don't need to do anything.
if !p.features.Enabled(features.TaintNodesByCondition) { if !p.features.Enabled(features.TaintNodesByCondition) {
return nil return nil

View File

@ -17,7 +17,9 @@ limitations under the License.
package nodetaint package nodetaint
import ( import (
"context"
"reflect" "reflect"
"testing" "testing"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@ -106,7 +108,7 @@ func Test_nodeTaints(t *testing.T) {
if tt.features != nil { if tt.features != nil {
c.features = tt.features c.features = tt.features
} }
err := c.Admit(attributes, nil) err := c.Admit(context.TODO(), attributes, nil)
if err != nil { if err != nil {
t.Errorf("nodePlugin.Admit() error = %v", err) t.Errorf("nodePlugin.Admit() error = %v", err)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package podnodeselector package podnodeselector
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"reflect" "reflect"
@ -96,7 +97,7 @@ func readConfig(config io.Reader) *pluginConfig {
} }
// Admit enforces that pod and its namespace node label selectors matches at least a node in the cluster. // Admit enforces that pod and its namespace node label selectors matches at least a node in the cluster.
func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
if shouldIgnore(a) { if shouldIgnore(a) {
return nil return nil
} }
@ -119,11 +120,11 @@ func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) err
// second selector wins // second selector wins
podNodeSelectorLabels := labels.Merge(namespaceNodeSelector, pod.Spec.NodeSelector) podNodeSelectorLabels := labels.Merge(namespaceNodeSelector, pod.Spec.NodeSelector)
pod.Spec.NodeSelector = map[string]string(podNodeSelectorLabels) pod.Spec.NodeSelector = map[string]string(podNodeSelectorLabels)
return p.Validate(a, o) return p.Validate(ctx, a, o)
} }
// Validate ensures that the pod node selector is allowed // Validate ensures that the pod node selector is allowed
func (p *Plugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
if shouldIgnore(a) { if shouldIgnore(a) {
return nil return nil
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package podnodeselector package podnodeselector
import ( import (
"context"
"testing" "testing"
"time" "time"
@ -161,7 +162,7 @@ func TestPodAdmission(t *testing.T) {
handler.clusterNodeSelectors[namespace.Name] = test.whitelist handler.clusterNodeSelectors[namespace.Name] = test.whitelist
pod.Spec = api.PodSpec{NodeSelector: test.podNodeSelector} pod.Spec = api.PodSpec{NodeSelector: test.podNodeSelector}
err := handler.Admit(admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Admit(context.TODO(), admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if test.admit && err != nil { if test.admit && err != nil {
t.Errorf("Test: %s, expected no error but got: %s", test.testName, err) t.Errorf("Test: %s, expected no error but got: %s", test.testName, err)
} else if !test.admit && err == nil { } else if !test.admit && err == nil {
@ -170,7 +171,7 @@ func TestPodAdmission(t *testing.T) {
if test.admit && !labels.Equals(test.mergedNodeSelector, labels.Set(pod.Spec.NodeSelector)) { if test.admit && !labels.Equals(test.mergedNodeSelector, labels.Set(pod.Spec.NodeSelector)) {
t.Errorf("Test: %s, expected: %s but got: %s", test.testName, test.mergedNodeSelector, pod.Spec.NodeSelector) t.Errorf("Test: %s, expected: %s but got: %s", test.testName, test.mergedNodeSelector, pod.Spec.NodeSelector)
} }
err = handler.Validate(admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if test.admit && err != nil { if test.admit && err != nil {
t.Errorf("Test: %s, expected no error but got: %s", test.testName, err) t.Errorf("Test: %s, expected no error but got: %s", test.testName, err)
} else if !test.admit && err == nil { } else if !test.admit && err == nil {

View File

@ -17,6 +17,7 @@ limitations under the License.
package podpreset package podpreset
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"reflect" "reflect"
@ -96,7 +97,7 @@ func (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactor
} }
// Admit injects a pod with the specific fields for each pod preset it matches. // Admit injects a pod with the specific fields for each pod preset it matches.
func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
// Ignore all calls to subresources or resources other than pods. // Ignore all calls to subresources or resources other than pods.
// Ignore all operations other than CREATE. // Ignore all operations other than CREATE.
if len(a.GetSubresource()) != 0 || a.GetResource().GroupResource() != api.Resource("pods") || a.GetOperation() != admission.Create { if len(a.GetSubresource()) != 0 || a.GetResource().GroupResource() != api.Resource("pods") || a.GetOperation() != admission.Create {

View File

@ -17,6 +17,7 @@ limitations under the License.
package podpreset package podpreset
import ( import (
"context"
"fmt" "fmt"
"reflect" "reflect"
"testing" "testing"
@ -828,7 +829,7 @@ func admitPod(t *testing.T, pod *api.Pod, pip *settingsv1alpha1.PodPreset) error
&user.DefaultInfo{}, &user.DefaultInfo{},
) )
err := plugin.Admit(attrs, nil) err := plugin.Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
return err return err
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package podtolerationrestriction package podtolerationrestriction
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@ -73,7 +74,7 @@ type Plugin struct {
} }
// Admit checks the admission policy and triggers corresponding actions // Admit checks the admission policy and triggers corresponding actions
func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
if shouldIgnore(a) { if shouldIgnore(a) {
return nil return nil
} }
@ -127,11 +128,11 @@ func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) err
// Final merge of tolerations irrespective of pod type, if the user while creating pods gives // Final merge of tolerations irrespective of pod type, if the user while creating pods gives
// conflicting tolerations(with same key+effect), the existing ones should be overwritten by latest one // conflicting tolerations(with same key+effect), the existing ones should be overwritten by latest one
pod.Spec.Tolerations = tolerations.MergeTolerations(finalTolerations, []api.Toleration{}) pod.Spec.Tolerations = tolerations.MergeTolerations(finalTolerations, []api.Toleration{})
return p.Validate(a, o) return p.Validate(ctx, a, o)
} }
// Validate we can obtain a whitelist of tolerations // Validate we can obtain a whitelist of tolerations
func (p *Plugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
if shouldIgnore(a) { if shouldIgnore(a) {
return nil return nil
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package podtolerationrestriction package podtolerationrestriction
import ( import (
"context"
"encoding/json" "encoding/json"
"testing" "testing"
"time" "time"
@ -266,7 +267,7 @@ func TestPodAdmission(t *testing.T) {
handler.pluginConfig = &pluginapi.Configuration{Default: test.defaultClusterTolerations, Whitelist: test.clusterWhitelist} handler.pluginConfig = &pluginapi.Configuration{Default: test.defaultClusterTolerations, Whitelist: test.clusterWhitelist}
pod := test.pod pod := test.pod
pod.Spec.Tolerations = test.podTolerations pod.Spec.Tolerations = test.podTolerations
err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "testNamespace", namespace.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if test.admit && err != nil { if test.admit && err != nil {
t.Errorf("Test: %s, expected no error but got: %s", test.testName, err) t.Errorf("Test: %s, expected no error but got: %s", test.testName, err)
} else if !test.admit && err == nil { } else if !test.admit && err == nil {
@ -343,7 +344,7 @@ func TestIgnoreUpdatingInitializedPod(t *testing.T) {
} }
// if the update of initialized pod is not ignored, an error will be returned because the pod's Tolerations conflicts with namespace's Tolerations. // if the update of initialized pod is not ignored, an error will be returned because the pod's Tolerations conflicts with namespace's Tolerations.
err = admissiontesting.WithReinvocationTesting(t, handler).Admit(admission.NewAttributesRecord(pod, pod, api.Kind("Pod").WithVersion("version"), "testNamespace", pod.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.CreateOptions{}, false, nil), nil) err = admissiontesting.WithReinvocationTesting(t, handler).Admit(context.TODO(), admission.NewAttributesRecord(pod, pod, api.Kind("Pod").WithVersion("version"), "testNamespace", pod.ObjectMeta.Name, api.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("expected no error, got: %v", err) t.Errorf("expected no error, got: %v", err)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package priority package priority
import ( import (
"context"
"fmt" "fmt"
"io" "io"
@ -98,7 +99,7 @@ var (
// Admit checks Pods and admits or rejects them. It also resolves the priority of pods based on their PriorityClass. // Admit checks Pods and admits or rejects them. It also resolves the priority of pods based on their PriorityClass.
// Note that pod validation mechanism prevents update of a pod priority. // Note that pod validation mechanism prevents update of a pod priority.
func (p *priorityPlugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *priorityPlugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
operation := a.GetOperation() operation := a.GetOperation()
// Ignore all calls to subresources // Ignore all calls to subresources
if len(a.GetSubresource()) != 0 { if len(a.GetSubresource()) != 0 {
@ -118,7 +119,7 @@ func (p *priorityPlugin) Admit(a admission.Attributes, o admission.ObjectInterfa
} }
// Validate checks PriorityClasses and admits or rejects them. // Validate checks PriorityClasses and admits or rejects them.
func (p *priorityPlugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *priorityPlugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
operation := a.GetOperation() operation := a.GetOperation()
// Ignore all calls to subresources // Ignore all calls to subresources
if len(a.GetSubresource()) != 0 { if len(a.GetSubresource()) != 0 {

View File

@ -17,6 +17,7 @@ limitations under the License.
package priority package priority
import ( import (
"context"
"testing" "testing"
"k8s.io/klog" "k8s.io/klog"
@ -191,7 +192,7 @@ func TestPriorityClassAdmission(t *testing.T) {
false, false,
test.userInfo, test.userInfo,
) )
err := ctrl.Validate(attrs, nil) err := ctrl.Validate(context.TODO(), attrs, nil)
klog.Infof("Got %v", err) klog.Infof("Got %v", err)
if err != nil && !test.expectError { if err != nil && !test.expectError {
t.Errorf("Test %q: unexpected error received: %v", test.name, err) t.Errorf("Test %q: unexpected error received: %v", test.name, err)
@ -287,7 +288,7 @@ func TestDefaultPriority(t *testing.T) {
test.name, test.expectedDefaultNameBefore, test.expectedDefaultBefore, pcName, defaultPriority) test.name, test.expectedDefaultNameBefore, test.expectedDefaultBefore, pcName, defaultPriority)
} }
if test.attributes != nil { if test.attributes != nil {
err := ctrl.Validate(test.attributes, nil) err := ctrl.Validate(context.TODO(), test.attributes, nil)
if err != nil { if err != nil {
t.Errorf("Test %q: unexpected error received: %v", test.name, err) t.Errorf("Test %q: unexpected error received: %v", test.name, err)
} }
@ -701,7 +702,7 @@ func TestPodAdmission(t *testing.T) {
false, false,
nil, nil,
) )
err := admissiontesting.WithReinvocationTesting(t, ctrl).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, ctrl).Admit(context.TODO(), attrs, nil)
klog.Infof("Got %v", err) klog.Infof("Got %v", err)
if !test.expectError { if !test.expectError {
if err != nil { if err != nil {

View File

@ -17,6 +17,7 @@ limitations under the License.
package resourcequota package resourcequota
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"time" "time"
@ -131,7 +132,7 @@ func (a *QuotaAdmission) ValidateInitialization() error {
} }
// Validate makes admission decisions while enforcing quota // Validate makes admission decisions while enforcing quota
func (a *QuotaAdmission) Validate(attr admission.Attributes, o admission.ObjectInterfaces) (err error) { func (a *QuotaAdmission) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) (err error) {
// ignore all operations that correspond to sub-resource actions // ignore all operations that correspond to sub-resource actions
if attr.GetSubresource() != "" { if attr.GetSubresource() != "" {
return nil return nil

View File

@ -17,6 +17,7 @@ limitations under the License.
package resourcequota package resourcequota
import ( import (
"context"
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
@ -153,7 +154,7 @@ func TestAdmissionIgnoresDelete(t *testing.T) {
evaluator: evaluator, evaluator: evaluator,
} }
namespace := "default" namespace := "default"
err := handler.Validate(admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), namespace, "name", corev1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), namespace, "name", corev1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("ResourceQuota should admit all deletes: %v", err) t.Errorf("ResourceQuota should admit all deletes: %v", err)
} }
@ -190,11 +191,11 @@ func TestAdmissionIgnoresSubresources(t *testing.T) {
} }
informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota)
newPod := validPod("123", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", ""))) newPod := validPod("123", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected an error because the pod exceeded allowed quota") t.Errorf("Expected an error because the pod exceeded allowed quota")
} }
err = handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "subresource", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Did not expect an error because the action went to a subresource: %v", err) t.Errorf("Did not expect an error because the action went to a subresource: %v", err)
} }
@ -235,7 +236,7 @@ func TestAdmitBelowQuotaLimit(t *testing.T) {
} }
informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota)
newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", ""))) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -318,13 +319,13 @@ func TestAdmitDryRun(t *testing.T) {
informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota)
newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", ""))) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
newPod = validPod("too-large-pod", 1, getResourceRequirements(getResourceList("100m", "60Gi"), getResourceList("", ""))) newPod = validPod("too-large-pod", 1, getResourceRequirements(getResourceList("100m", "60Gi"), getResourceList("", "")))
err = handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, true, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected error but got none") t.Errorf("Expected error but got none")
} }
@ -384,7 +385,7 @@ func TestAdmitHandlesOldObjects(t *testing.T) {
Ports: []api.ServicePort{{Port: 1234}}, Ports: []api.ServicePort{{Port: 1234}},
}, },
} }
err := handler.Validate(admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -485,7 +486,7 @@ func TestAdmitHandlesNegativePVCUpdates(t *testing.T) {
}, },
} }
err := handler.Validate(admission.NewAttributesRecord(newPVC, oldPVC, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPVC.Namespace, newPVC.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPVC, oldPVC, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPVC.Namespace, newPVC.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -544,7 +545,7 @@ func TestAdmitHandlesPVCUpdates(t *testing.T) {
}, },
} }
err := handler.Validate(admission.NewAttributesRecord(newPVC, oldPVC, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPVC.Namespace, newPVC.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPVC, oldPVC, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPVC.Namespace, newPVC.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -641,7 +642,7 @@ func TestAdmitHandlesCreatingUpdates(t *testing.T) {
Ports: []api.ServicePort{{Port: 1234}}, Ports: []api.ServicePort{{Port: 1234}},
}, },
} }
err := handler.Validate(admission.NewAttributesRecord(newService, oldService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newService, oldService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -724,7 +725,7 @@ func TestAdmitExceedQuotaLimit(t *testing.T) {
} }
informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota)
newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected an error exceeding quota") t.Errorf("Expected an error exceeding quota")
} }
@ -770,7 +771,7 @@ func TestAdmitEnforceQuotaConstraints(t *testing.T) {
informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota)
// verify all values are specified as required on the quota // verify all values are specified as required on the quota
newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("200m", ""))) newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("200m", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected an error because the pod does not specify a memory limit") t.Errorf("Expected an error because the pod does not specify a memory limit")
} }
@ -821,7 +822,7 @@ func TestAdmitPodInNamespaceWithoutQuota(t *testing.T) {
newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("200m", ""))) newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("200m", "")))
// Add to the lru cache so we do not do a live client lookup // Add to the lru cache so we do not do a live client lookup
liveLookupCache.Add(newPod.Namespace, liveLookupEntry{expiry: time.Now().Add(time.Duration(30 * time.Second)), items: []*corev1.ResourceQuota{}}) liveLookupCache.Add(newPod.Namespace, liveLookupEntry{expiry: time.Now().Add(time.Duration(30 * time.Second)), items: []*corev1.ResourceQuota{}})
err = handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Did not expect an error because the pod is in a different namespace than the quota") t.Errorf("Did not expect an error because the pod is in a different namespace than the quota")
} }
@ -890,7 +891,7 @@ func TestAdmitBelowTerminatingQuotaLimit(t *testing.T) {
newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", ""))) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "2Gi"), getResourceList("", "")))
activeDeadlineSeconds := int64(30) activeDeadlineSeconds := int64(30)
newPod.Spec.ActiveDeadlineSeconds = &activeDeadlineSeconds newPod.Spec.ActiveDeadlineSeconds = &activeDeadlineSeconds
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -994,7 +995,7 @@ func TestAdmitBelowBestEffortQuotaLimit(t *testing.T) {
// create a pod that is best effort because it does not make a request for anything // create a pod that is best effort because it does not make a request for anything
newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("", ""), getResourceList("", ""))) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("", ""), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -1084,7 +1085,7 @@ func TestAdmitBestEffortQuotaLimitIgnoresBurstable(t *testing.T) {
} }
informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota)
newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "1Gi"), getResourceList("", ""))) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("100m", "1Gi"), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -1193,7 +1194,7 @@ func TestAdmissionSetsMissingNamespace(t *testing.T) {
// unset the namespace // unset the namespace
newPod.ObjectMeta.Namespace = "" newPod.ObjectMeta.Namespace = ""
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Got unexpected error: %v", err) t.Errorf("Got unexpected error: %v", err)
} }
@ -1236,14 +1237,14 @@ func TestAdmitRejectsNegativeUsage(t *testing.T) {
informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota) informerFactory.Core().V1().ResourceQuotas().Informer().GetIndexer().Add(resourceQuota)
// verify quota rejects negative pvc storage requests // verify quota rejects negative pvc storage requests
newPvc := validPersistentVolumeClaim("not-allowed-pvc", getResourceRequirements(api.ResourceList{api.ResourceStorage: resource.MustParse("-1Gi")}, api.ResourceList{})) newPvc := validPersistentVolumeClaim("not-allowed-pvc", getResourceRequirements(api.ResourceList{api.ResourceStorage: resource.MustParse("-1Gi")}, api.ResourceList{}))
err := handler.Validate(admission.NewAttributesRecord(newPvc, nil, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPvc.Namespace, newPvc.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPvc, nil, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPvc.Namespace, newPvc.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected an error because the pvc has negative storage usage") t.Errorf("Expected an error because the pvc has negative storage usage")
} }
// verify quota accepts non-negative pvc storage requests // verify quota accepts non-negative pvc storage requests
newPvc = validPersistentVolumeClaim("not-allowed-pvc", getResourceRequirements(api.ResourceList{api.ResourceStorage: resource.MustParse("1Gi")}, api.ResourceList{})) newPvc = validPersistentVolumeClaim("not-allowed-pvc", getResourceRequirements(api.ResourceList{api.ResourceStorage: resource.MustParse("1Gi")}, api.ResourceList{}))
err = handler.Validate(admission.NewAttributesRecord(newPvc, nil, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPvc.Namespace, newPvc.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(newPvc, nil, api.Kind("PersistentVolumeClaim").WithVersion("version"), newPvc.Namespace, newPvc.Name, corev1.Resource("persistentvolumeclaims").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -1284,7 +1285,7 @@ func TestAdmitWhenUnrelatedResourceExceedsQuota(t *testing.T) {
// create a pod that should pass existing quota // create a pod that should pass existing quota
newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("", ""), getResourceList("", ""))) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("", ""), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -1318,7 +1319,7 @@ func TestAdmitLimitedResourceNoQuota(t *testing.T) {
evaluator: evaluator, evaluator: evaluator,
} }
newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected an error for consuming a limited resource without quota.") t.Errorf("Expected an error for consuming a limited resource without quota.")
} }
@ -1352,7 +1353,7 @@ func TestAdmitLimitedResourceNoQuotaIgnoresNonMatchingResources(t *testing.T) {
evaluator: evaluator, evaluator: evaluator,
} }
newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Fatalf("Unexpected error: %v", err) t.Fatalf("Unexpected error: %v", err)
} }
@ -1400,7 +1401,7 @@ func TestAdmitLimitedResourceWithQuota(t *testing.T) {
} }
indexer.Add(resourceQuota) indexer.Add(resourceQuota)
newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
} }
@ -1460,7 +1461,7 @@ func TestAdmitLimitedResourceWithMultipleQuota(t *testing.T) {
indexer.Add(resourceQuota1) indexer.Add(resourceQuota1)
indexer.Add(resourceQuota2) indexer.Add(resourceQuota2)
newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) newPod := validPod("allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
} }
@ -1508,7 +1509,7 @@ func TestAdmitLimitedResourceWithQuotaThatDoesNotCover(t *testing.T) {
} }
indexer.Add(resourceQuota) indexer.Add(resourceQuota)
newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", ""))) newPod := validPod("not-allowed-pod", 1, getResourceRequirements(getResourceList("3", "2Gi"), getResourceList("", "")))
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Fatalf("Expected an error since the quota did not cover cpu") t.Fatalf("Expected an error since the quota did not cover cpu")
} }
@ -2169,7 +2170,7 @@ func TestAdmitLimitedScopeWithCoverQuota(t *testing.T) {
if testCase.anotherQuota != nil { if testCase.anotherQuota != nil {
indexer.Add(testCase.anotherQuota) indexer.Add(testCase.anotherQuota)
} }
err := handler.Validate(admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newPod, nil, api.Kind("Pod").WithVersion("version"), newPod.Namespace, newPod.Name, corev1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if testCase.expErr == "" { if testCase.expErr == "" {
if err != nil { if err != nil {
t.Fatalf("Testcase, %v, failed with unexpected error: %v. ExpErr: %v", testCase.description, err, testCase.expErr) t.Fatalf("Testcase, %v, failed with unexpected error: %v. ExpErr: %v", testCase.description, err, testCase.expErr)
@ -2221,7 +2222,7 @@ func TestAdmitZeroDeltaUsageWithoutCoveringQuota(t *testing.T) {
Spec: api.ServiceSpec{Type: api.ServiceTypeLoadBalancer}, Spec: api.ServiceSpec{Type: api.ServiceTypeLoadBalancer},
} }
err := handler.Validate(admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.CreateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("unexpected error: %v", err) t.Errorf("unexpected error: %v", err)
} }
@ -2267,7 +2268,7 @@ func TestAdmitRejectIncreaseUsageWithoutCoveringQuota(t *testing.T) {
Spec: api.ServiceSpec{Type: api.ServiceTypeLoadBalancer}, Spec: api.ServiceSpec{Type: api.ServiceTypeLoadBalancer},
} }
err := handler.Validate(admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected an error for consuming a limited resource without quota.") t.Errorf("Expected an error for consuming a limited resource without quota.")
} }
@ -2313,7 +2314,7 @@ func TestAdmitAllowDecreaseUsageWithoutCoveringQuota(t *testing.T) {
}, },
} }
err := handler.Validate(admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(newService, existingService, api.Kind("Service").WithVersion("version"), newService.Namespace, newService.Name, corev1.Resource("services").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Expected no error for decreasing a limited resource without quota, got %v", err) t.Errorf("Expected no error for decreasing a limited resource without quota, got %v", err)
} }

View File

@ -22,6 +22,7 @@ limitations under the License.
package runtimeclass package runtimeclass
import ( import (
"context"
"fmt" "fmt"
"io" "io"
@ -79,7 +80,7 @@ func (r *RuntimeClass) ValidateInitialization() error {
} }
// Admit makes an admission decision based on the request attributes // Admit makes an admission decision based on the request attributes
func (r *RuntimeClass) Admit(attributes admission.Attributes, o admission.ObjectInterfaces) error { func (r *RuntimeClass) Admit(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error {
// Ignore all calls to subresources or resources other than pods. // Ignore all calls to subresources or resources other than pods.
if shouldIgnore(attributes) { if shouldIgnore(attributes) {
@ -101,7 +102,7 @@ func (r *RuntimeClass) Admit(attributes admission.Attributes, o admission.Object
} }
// Validate makes sure that pod adhere's to RuntimeClass's definition // Validate makes sure that pod adhere's to RuntimeClass's definition
func (r *RuntimeClass) Validate(attributes admission.Attributes, o admission.ObjectInterfaces) error { func (r *RuntimeClass) Validate(ctx context.Context, attributes admission.Attributes, o admission.ObjectInterfaces) error {
// Ignore all calls to subresources or resources other than pods. // Ignore all calls to subresources or resources other than pods.
if shouldIgnore(attributes) { if shouldIgnore(attributes) {

View File

@ -17,6 +17,10 @@ limitations under the License.
package runtimeclass package runtimeclass
import ( import (
"context"
"strconv"
"testing"
corev1 "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1"
"k8s.io/api/node/v1beta1" "k8s.io/api/node/v1beta1"
"k8s.io/apimachinery/pkg/api/resource" "k8s.io/apimachinery/pkg/api/resource"
@ -28,8 +32,6 @@ import (
featuregatetesting "k8s.io/component-base/featuregate/testing" featuregatetesting "k8s.io/component-base/featuregate/testing"
"k8s.io/kubernetes/pkg/apis/core" "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/features" "k8s.io/kubernetes/pkg/features"
"strconv"
"testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -217,7 +219,7 @@ func TestValidate(t *testing.T) {
attrs := admission.NewAttributesRecord(tc.pod, nil, core.Kind("Pod").WithVersion("version"), tc.pod.Namespace, tc.pod.Name, core.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{}) attrs := admission.NewAttributesRecord(tc.pod, nil, core.Kind("Pod").WithVersion("version"), tc.pod.Namespace, tc.pod.Name, core.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{})
errs := rt.Validate(attrs, o) errs := rt.Validate(context.TODO(), attrs, o)
if tc.expectError { if tc.expectError {
assert.NotEmpty(t, errs) assert.NotEmpty(t, errs)
} else { } else {

View File

@ -17,6 +17,7 @@ limitations under the License.
package podsecuritypolicy package podsecuritypolicy
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"sort" "sort"
@ -109,7 +110,7 @@ func (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactor
// 3. Try to generate and validate a PSP with providers. If we find one then admit the pod // 3. Try to generate and validate a PSP with providers. If we find one then admit the pod
// with the validated PSP. If we don't find any reject the pod and give all errors from the // with the validated PSP. If we don't find any reject the pod and give all errors from the
// failed attempts. // failed attempts.
func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
if ignore, err := shouldIgnore(a); err != nil { if ignore, err := shouldIgnore(a); err != nil {
return err return err
} else if ignore { } else if ignore {
@ -150,7 +151,7 @@ func (p *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) err
} }
// Validate verifies attributes against the PodSecurityPolicy // Validate verifies attributes against the PodSecurityPolicy
func (p *Plugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
if ignore, err := shouldIgnore(a); err != nil { if ignore, err := shouldIgnore(a); err != nil {
return err return err
} else if ignore { } else if ignore {

View File

@ -17,6 +17,7 @@ limitations under the License.
package podsecuritypolicy package podsecuritypolicy
import ( import (
"context"
"fmt" "fmt"
"reflect" "reflect"
"strings" "strings"
@ -479,7 +480,7 @@ func TestFailClosedOnInvalidPod(t *testing.T) {
pod := &v1.Pod{} pod := &v1.Pod{}
attrs := kadmission.NewAttributesRecord(pod, nil, kapi.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, kapi.Resource("pods").WithVersion("version"), "", kadmission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{}) attrs := kadmission.NewAttributesRecord(pod, nil, kapi.Kind("Pod").WithVersion("version"), pod.Namespace, pod.Name, kapi.Resource("pods").WithVersion("version"), "", kadmission.Create, &metav1.CreateOptions{}, false, &user.DefaultInfo{})
err := plugin.Admit(attrs, nil) err := plugin.Admit(context.TODO(), attrs, nil)
if err == nil { if err == nil {
t.Fatalf("expected versioned pod object to fail mutating admission") t.Fatalf("expected versioned pod object to fail mutating admission")
} }
@ -487,7 +488,7 @@ func TestFailClosedOnInvalidPod(t *testing.T) {
t.Errorf("expected type error on Admit but got: %v", err) t.Errorf("expected type error on Admit but got: %v", err)
} }
err = plugin.Validate(attrs, nil) err = plugin.Validate(context.TODO(), attrs, nil)
if err == nil { if err == nil {
t.Fatalf("expected versioned pod object to fail validating admission") t.Fatalf("expected versioned pod object to fail validating admission")
} }
@ -1785,7 +1786,7 @@ func testPSPAdmitAdvanced(testCaseName string, op kadmission.Operation, psps []*
attrs := kadmission.NewAttributesRecord(pod, oldPod, kapi.Kind("Pod").WithVersion("version"), pod.Namespace, "", kapi.Resource("pods").WithVersion("version"), "", op, nil, false, userInfo) attrs := kadmission.NewAttributesRecord(pod, oldPod, kapi.Kind("Pod").WithVersion("version"), pod.Namespace, "", kapi.Resource("pods").WithVersion("version"), "", op, nil, false, userInfo)
annotations := make(map[string]string) annotations := make(map[string]string)
attrs = &fakeAttributes{attrs, annotations} attrs = &fakeAttributes{attrs, annotations}
err := admissiontesting.WithReinvocationTesting(t, plugin).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, plugin).Admit(context.TODO(), attrs, nil)
if shouldPassAdmit && err != nil { if shouldPassAdmit && err != nil {
t.Errorf("%s: expected no errors on Admit but received %v", testCaseName, err) t.Errorf("%s: expected no errors on Admit but received %v", testCaseName, err)
@ -1813,7 +1814,7 @@ func testPSPAdmitAdvanced(testCaseName string, op kadmission.Operation, psps []*
t.Errorf("%s: expected errors on Admit but received none", testCaseName) t.Errorf("%s: expected errors on Admit but received none", testCaseName)
} }
err = plugin.Validate(attrs, nil) err = plugin.Validate(context.TODO(), attrs, nil)
psp := "" psp := ""
if shouldPassAdmit && op == kadmission.Create { if shouldPassAdmit && op == kadmission.Create {
psp = expectedPSP psp = expectedPSP

View File

@ -17,6 +17,7 @@ limitations under the License.
package scdeny package scdeny
import ( import (
"context"
"fmt" "fmt"
"io" "io"
@ -50,7 +51,7 @@ func NewSecurityContextDeny() *Plugin {
} }
// Validate will deny any pod that defines SupplementalGroups, SELinuxOptions, RunAsUser or FSGroup // Validate will deny any pod that defines SupplementalGroups, SELinuxOptions, RunAsUser or FSGroup
func (p *Plugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
if a.GetSubresource() != "" || a.GetResource().GroupResource() != api.Resource("pods") { if a.GetSubresource() != "" || a.GetResource().GroupResource() != api.Resource("pods") {
return nil return nil
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package scdeny package scdeny
import ( import (
"context"
"testing" "testing"
"k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/admission"
@ -82,7 +83,7 @@ func TestAdmission(t *testing.T) {
p.Spec.SecurityContext = tc.podSc p.Spec.SecurityContext = tc.podSc
p.Spec.Containers[0].SecurityContext = tc.sc p.Spec.Containers[0].SecurityContext = tc.sc
err := handler.Validate(admission.NewAttributesRecord(p, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(p, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil)
if err != nil && !tc.expectError { if err != nil && !tc.expectError {
t.Errorf("%v: unexpected error: %v", tc.name, err) t.Errorf("%v: unexpected error: %v", tc.name, err)
} else if err == nil && tc.expectError { } else if err == nil && tc.expectError {
@ -96,7 +97,7 @@ func TestAdmission(t *testing.T) {
p.Spec.InitContainers = p.Spec.Containers p.Spec.InitContainers = p.Spec.Containers
p.Spec.Containers = nil p.Spec.Containers = nil
err = handler.Validate(admission.NewAttributesRecord(p, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) err = handler.Validate(context.TODO(), admission.NewAttributesRecord(p, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil)
if err != nil && !tc.expectError { if err != nil && !tc.expectError {
t.Errorf("%v: unexpected error: %v", tc.name, err) t.Errorf("%v: unexpected error: %v", tc.name, err)
} else if err == nil && tc.expectError { } else if err == nil && tc.expectError {
@ -140,7 +141,7 @@ func TestPodSecurityContextAdmission(t *testing.T) {
} }
for _, test := range tests { for _, test := range tests {
pod.Spec.SecurityContext = &test.securityContext pod.Spec.SecurityContext = &test.securityContext
err := handler.Validate(admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil) err := handler.Validate(context.TODO(), admission.NewAttributesRecord(&pod, nil, api.Kind("Pod").WithVersion("version"), "foo", "name", api.Resource("pods").WithVersion("version"), "", "ignored", nil, false, nil), nil)
if test.errorExpected && err == nil { if test.errorExpected && err == nil {
t.Errorf("Expected error for security context %+v but did not get an error", test.securityContext) t.Errorf("Expected error for security context %+v but did not get an error", test.securityContext)

View File

@ -17,6 +17,7 @@ limitations under the License.
package serviceaccount package serviceaccount
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"math/rand" "math/rand"
@ -154,7 +155,7 @@ func (s *Plugin) ValidateInitialization() error {
} }
// Admit verifies if the pod should be admitted // Admit verifies if the pod should be admitted
func (s *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (s *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
if shouldIgnore(a) { if shouldIgnore(a) {
return nil return nil
} }
@ -165,7 +166,7 @@ func (s *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) (er
// That makes the kubelet very angry and confused, and it immediately deletes the pod (because the spec doesn't match) // That makes the kubelet very angry and confused, and it immediately deletes the pod (because the spec doesn't match)
// That said, don't allow mirror pods to reference ServiceAccounts or SecretVolumeSources either // That said, don't allow mirror pods to reference ServiceAccounts or SecretVolumeSources either
if _, isMirrorPod := pod.Annotations[api.MirrorPodAnnotationKey]; isMirrorPod { if _, isMirrorPod := pod.Annotations[api.MirrorPodAnnotationKey]; isMirrorPod {
return s.Validate(a, o) return s.Validate(ctx, a, o)
} }
// Set the default service account if needed // Set the default service account if needed
@ -192,11 +193,11 @@ func (s *Plugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) (er
} }
} }
return s.Validate(a, o) return s.Validate(ctx, a, o)
} }
// Validate the data we obtained // Validate the data we obtained
func (s *Plugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (s *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
if shouldIgnore(a) { if shouldIgnore(a) {
return nil return nil
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package serviceaccount package serviceaccount
import ( import (
"context"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
@ -66,7 +67,7 @@ func TestIgnoresNonPodResource(t *testing.T) {
pod := &api.Pod{} pod := &api.Pod{}
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("CustomResource").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("CustomResource").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
handler := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()) handler := admissiontesting.WithReinvocationTesting(t, NewServiceAccount())
err := handler.Admit(attrs, nil) err := handler.Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Expected non-pod resource allowed, got err: %v", err) t.Errorf("Expected non-pod resource allowed, got err: %v", err)
} }
@ -75,7 +76,7 @@ func TestIgnoresNonPodResource(t *testing.T) {
func TestIgnoresNilObject(t *testing.T) { func TestIgnoresNilObject(t *testing.T) {
attrs := admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(nil, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
handler := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()) handler := admissiontesting.WithReinvocationTesting(t, NewServiceAccount())
err := handler.Admit(attrs, nil) err := handler.Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Expected nil object allowed allowed, got err: %v", err) t.Errorf("Expected nil object allowed allowed, got err: %v", err)
} }
@ -85,7 +86,7 @@ func TestIgnoresNonPodObject(t *testing.T) {
obj := &api.Namespace{} obj := &api.Namespace{}
attrs := admission.NewAttributesRecord(obj, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(obj, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
handler := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()) handler := admissiontesting.WithReinvocationTesting(t, NewServiceAccount())
err := handler.Admit(attrs, nil) err := handler.Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Expected non pod object allowed, got err: %v", err) t.Errorf("Expected non pod object allowed, got err: %v", err)
} }
@ -105,7 +106,7 @@ func TestIgnoresMirrorPod(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Expected mirror pod without service account or secrets allowed, got err: %v", err) t.Errorf("Expected mirror pod without service account or secrets allowed, got err: %v", err)
} }
@ -123,7 +124,7 @@ func TestRejectsMirrorPodWithServiceAccount(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(context.TODO(), attrs, nil)
if err == nil { if err == nil {
t.Errorf("Expected a mirror pod to be prevented from referencing a service account") t.Errorf("Expected a mirror pod to be prevented from referencing a service account")
} }
@ -143,7 +144,7 @@ func TestRejectsMirrorPodWithSecretVolumes(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(context.TODO(), attrs, nil)
if err == nil { if err == nil {
t.Errorf("Expected a mirror pod to be prevented from referencing a secret volume") t.Errorf("Expected a mirror pod to be prevented from referencing a secret volume")
} }
@ -168,7 +169,7 @@ func TestRejectsMirrorPodWithServiceAccountTokenVolumeProjections(t *testing.T)
}, },
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), "myns", "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, NewServiceAccount()).Admit(context.TODO(), attrs, nil)
if err == nil { if err == nil {
t.Errorf("Expected a mirror pod to be prevented from referencing a ServiceAccountToken volume projection") t.Errorf("Expected a mirror pod to be prevented from referencing a ServiceAccountToken volume projection")
} }
@ -193,7 +194,7 @@ func TestAssignsDefaultServiceAccountAndToleratesMissingAPIToken(t *testing.T) {
pod := &api.Pod{} pod := &api.Pod{}
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -221,7 +222,7 @@ func TestAssignsDefaultServiceAccountAndRejectsMissingAPIToken(t *testing.T) {
pod := &api.Pod{} pod := &api.Pod{}
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err == nil || !errors.IsServerTimeout(err) { if err == nil || !errors.IsServerTimeout(err) {
t.Errorf("Expected server timeout error for missing API token: %v", err) t.Errorf("Expected server timeout error for missing API token: %v", err)
} }
@ -246,7 +247,7 @@ func TestFetchesUncachedServiceAccount(t *testing.T) {
pod := &api.Pod{} pod := &api.Pod{}
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -268,7 +269,7 @@ func TestDeniesInvalidServiceAccount(t *testing.T) {
pod := &api.Pod{} pod := &api.Pod{}
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err == nil { if err == nil {
t.Errorf("Expected error for missing service account, got none") t.Errorf("Expected error for missing service account, got none")
} }
@ -334,7 +335,7 @@ func TestAutomountsAPIToken(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -363,7 +364,7 @@ func TestAutomountsAPIToken(t *testing.T) {
}, },
} }
attrs = admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs = admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
if pod.Spec.ServiceAccountName != DefaultServiceAccountName { if pod.Spec.ServiceAccountName != DefaultServiceAccountName {
@ -445,7 +446,7 @@ func TestRespectsExistingMount(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -475,7 +476,7 @@ func TestRespectsExistingMount(t *testing.T) {
}, },
} }
attrs = admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs = admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
if pod.Spec.ServiceAccountName != DefaultServiceAccountName { if pod.Spec.ServiceAccountName != DefaultServiceAccountName {
@ -521,7 +522,7 @@ func TestAllowsReferencedSecret(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod1, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod1, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -545,7 +546,7 @@ func TestAllowsReferencedSecret(t *testing.T) {
}, },
} }
attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -569,7 +570,7 @@ func TestAllowsReferencedSecret(t *testing.T) {
}, },
} }
attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
} }
@ -599,7 +600,7 @@ func TestRejectsUnreferencedSecretVolumes(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod1, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod1, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err == nil { if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err == nil {
t.Errorf("Expected rejection for using a secret the service account does not reference") t.Errorf("Expected rejection for using a secret the service account does not reference")
} }
@ -623,7 +624,7 @@ func TestRejectsUnreferencedSecretVolumes(t *testing.T) {
}, },
} }
attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err == nil || !strings.Contains(err.Error(), "with envVar") { if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err == nil || !strings.Contains(err.Error(), "with envVar") {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -647,7 +648,7 @@ func TestRejectsUnreferencedSecretVolumes(t *testing.T) {
}, },
} }
attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs = admission.NewAttributesRecord(pod2, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err == nil || !strings.Contains(err.Error(), "with envVar") { if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err == nil || !strings.Contains(err.Error(), "with envVar") {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
} }
@ -678,7 +679,7 @@ func TestAllowUnreferencedSecretVolumesForPermissiveSAs(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err == nil { if err == nil {
t.Errorf("Expected rejection for using a secret the service account does not reference") t.Errorf("Expected rejection for using a secret the service account does not reference")
} }
@ -710,7 +711,7 @@ func TestAllowsReferencedImagePullSecrets(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -739,7 +740,7 @@ func TestRejectsUnreferencedImagePullSecrets(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err == nil { if err == nil {
t.Errorf("Expected rejection for using a secret the service account does not reference") t.Errorf("Expected rejection for using a secret the service account does not reference")
} }
@ -772,7 +773,7 @@ func TestDoNotAddImagePullSecrets(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -806,7 +807,7 @@ func TestAddImagePullSecrets(t *testing.T) {
pod := &api.Pod{} pod := &api.Pod{}
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }
@ -887,7 +888,7 @@ func TestMultipleReferencedSecrets(t *testing.T) {
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil); err != nil { if err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -1041,7 +1042,7 @@ func TestAutomountIsBackwardsCompatible(t *testing.T) {
}, },
} }
attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil) attrs := admission.NewAttributesRecord(pod, nil, api.Kind("Pod").WithVersion("version"), ns, "myname", api.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil)
err := admissiontesting.WithReinvocationTesting(t, admit).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, admit).Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error: %v", err) t.Errorf("Unexpected error: %v", err)
} }

View File

@ -97,7 +97,7 @@ func nodeSelectorRequirementKeysExistInNodeSelectorTerms(reqs []api.NodeSelector
return false return false
} }
func (l *persistentVolumeLabel) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (l *persistentVolumeLabel) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
if a.GetResource().GroupResource() != api.Resource("persistentvolumes") { if a.GetResource().GroupResource() != api.Resource("persistentvolumes") {
return nil return nil
} }

View File

@ -757,7 +757,7 @@ func Test_PVLAdmission(t *testing.T) {
setPVLabeler(testcase.handler, testcase.pvlabeler) setPVLabeler(testcase.handler, testcase.pvlabeler)
handler := admissiontesting.WithReinvocationTesting(t, admission.NewChainHandler(testcase.handler)) handler := admissiontesting.WithReinvocationTesting(t, admission.NewChainHandler(testcase.handler))
err := handler.Admit(admission.NewAttributesRecord(testcase.preAdmissionPV, nil, api.Kind("PersistentVolume").WithVersion("version"), testcase.preAdmissionPV.Namespace, testcase.preAdmissionPV.Name, api.Resource("persistentvolumes").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err := handler.Admit(context.TODO(), admission.NewAttributesRecord(testcase.preAdmissionPV, nil, api.Kind("PersistentVolume").WithVersion("version"), testcase.preAdmissionPV.Namespace, testcase.preAdmissionPV.Name, api.Resource("persistentvolumes").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if !reflect.DeepEqual(err, testcase.err) { if !reflect.DeepEqual(err, testcase.err) {
t.Logf("expected error: %q", testcase.err) t.Logf("expected error: %q", testcase.err)
t.Logf("actual error: %q", err) t.Logf("actual error: %q", err)

View File

@ -17,6 +17,7 @@ limitations under the License.
package resize package resize
import ( import (
"context"
"fmt" "fmt"
"io" "io"
@ -71,7 +72,7 @@ func (pvcr *persistentVolumeClaimResize) ValidateInitialization() error {
return nil return nil
} }
func (pvcr *persistentVolumeClaimResize) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { func (pvcr *persistentVolumeClaimResize) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
if a.GetResource().GroupResource() != api.Resource("persistentvolumeclaims") { if a.GetResource().GroupResource() != api.Resource("persistentvolumeclaims") {
return nil return nil
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package resize package resize
import ( import (
"context"
"fmt" "fmt"
"strings" "strings"
"testing" "testing"
@ -257,7 +258,7 @@ func TestPVCResizeAdmission(t *testing.T) {
operationOptions := &metav1.CreateOptions{} operationOptions := &metav1.CreateOptions{}
attributes := admission.NewAttributesRecord(tc.newObj, tc.oldObj, schema.GroupVersionKind{}, metav1.NamespaceDefault, "foo", tc.resource, tc.subresource, operation, operationOptions, false, nil) attributes := admission.NewAttributesRecord(tc.newObj, tc.oldObj, schema.GroupVersionKind{}, metav1.NamespaceDefault, "foo", tc.resource, tc.subresource, operation, operationOptions, false, nil)
err := ctrl.Validate(attributes, nil) err := ctrl.Validate(context.TODO(), attributes, nil)
if !tc.checkError(err) { if !tc.checkError(err) {
t.Errorf("%v: unexpected err: %v", tc.name, err) t.Errorf("%v: unexpected err: %v", tc.name, err)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package setdefault package setdefault
import ( import (
"context"
"fmt" "fmt"
"io" "io"
@ -85,7 +86,7 @@ func (a *claimDefaulterPlugin) ValidateInitialization() error {
// 1. Find available StorageClasses. // 1. Find available StorageClasses.
// 2. Figure which is the default // 2. Figure which is the default
// 3. Write to the PVClaim // 3. Write to the PVClaim
func (a *claimDefaulterPlugin) Admit(attr admission.Attributes, o admission.ObjectInterfaces) error { func (a *claimDefaulterPlugin) Admit(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error {
if attr.GetResource().GroupResource() != api.Resource("persistentvolumeclaims") { if attr.GetResource().GroupResource() != api.Resource("persistentvolumeclaims") {
return nil return nil
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package setdefault package setdefault
import ( import (
"context"
"testing" "testing"
"k8s.io/klog" "k8s.io/klog"
@ -213,7 +214,7 @@ func TestAdmission(t *testing.T) {
false, // dryRun false, // dryRun
nil, // userInfo nil, // userInfo
) )
err := admissiontesting.WithReinvocationTesting(t, ctrl).Admit(attrs, nil) err := admissiontesting.WithReinvocationTesting(t, ctrl).Admit(context.TODO(), attrs, nil)
klog.Infof("Got %v", err) klog.Infof("Got %v", err)
if err != nil && !test.expectError { if err != nil && !test.expectError {
t.Errorf("Test %q: unexpected error received: %v", test.name, err) t.Errorf("Test %q: unexpected error received: %v", test.name, err)

View File

@ -17,6 +17,7 @@ limitations under the License.
package storageobjectinuseprotection package storageobjectinuseprotection
import ( import (
"context"
"io" "io"
"k8s.io/klog" "k8s.io/klog"
@ -65,7 +66,7 @@ var (
// //
// This prevents users from deleting a PVC that's used by a running pod. // This prevents users from deleting a PVC that's used by a running pod.
// This also prevents admin from deleting a PV that's bound by a PVC // This also prevents admin from deleting a PV that's bound by a PVC
func (c *storageProtectionPlugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (c *storageProtectionPlugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
if !feature.DefaultFeatureGate.Enabled(features.StorageObjectInUseProtection) { if !feature.DefaultFeatureGate.Enabled(features.StorageObjectInUseProtection) {
return nil return nil
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package storageobjectinuseprotection package storageobjectinuseprotection
import ( import (
"context"
"reflect" "reflect"
"testing" "testing"
@ -136,7 +137,7 @@ func TestAdmit(t *testing.T) {
nil, // userInfo nil, // userInfo
) )
err := ctrl.Admit(attrs, nil) err := ctrl.Admit(context.TODO(), attrs, nil)
if err != nil { if err != nil {
t.Errorf("Test %q: got unexpected error: %v", test.name, err) t.Errorf("Test %q: got unexpected error: %v", test.name, err)
} }

View File

@ -297,17 +297,17 @@ func (r *ScaleREST) Update(ctx context.Context, name string, objInfo rest.Update
} }
func toScaleCreateValidation(f rest.ValidateObjectFunc, specReplicasPath, statusReplicasPath, labelSelectorPath string) rest.ValidateObjectFunc { func toScaleCreateValidation(f rest.ValidateObjectFunc, specReplicasPath, statusReplicasPath, labelSelectorPath string) rest.ValidateObjectFunc {
return func(obj runtime.Object) error { return func(ctx context.Context, obj runtime.Object) error {
scale, _, err := scaleFromCustomResource(obj.(*unstructured.Unstructured), specReplicasPath, statusReplicasPath, labelSelectorPath) scale, _, err := scaleFromCustomResource(obj.(*unstructured.Unstructured), specReplicasPath, statusReplicasPath, labelSelectorPath)
if err != nil { if err != nil {
return err return err
} }
return f(scale) return f(ctx, scale)
} }
} }
func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc, specReplicasPath, statusReplicasPath, labelSelectorPath string) rest.ValidateObjectUpdateFunc { func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc, specReplicasPath, statusReplicasPath, labelSelectorPath string) rest.ValidateObjectUpdateFunc {
return func(obj, old runtime.Object) error { return func(ctx context.Context, obj, old runtime.Object) error {
newScale, _, err := scaleFromCustomResource(obj.(*unstructured.Unstructured), specReplicasPath, statusReplicasPath, labelSelectorPath) newScale, _, err := scaleFromCustomResource(obj.(*unstructured.Unstructured), specReplicasPath, statusReplicasPath, labelSelectorPath)
if err != nil { if err != nil {
return err return err
@ -316,7 +316,7 @@ func toScaleUpdateValidation(f rest.ValidateObjectUpdateFunc, specReplicasPath,
if err != nil { if err != nil {
return err return err
} }
return f(newScale, oldScale) return f(ctx, newScale, oldScale)
} }
} }

View File

@ -119,7 +119,7 @@ func (r *REST) Delete(ctx context.Context, name string, deleteValidation rest.Va
// wrong type // wrong type
return nil, fmt.Errorf("expected *apiextensions.CustomResourceDefinition, got %v", existing) return nil, fmt.Errorf("expected *apiextensions.CustomResourceDefinition, got %v", existing)
} }
if err := deleteValidation(existingCRD); err != nil { if err := deleteValidation(ctx, existingCRD); err != nil {
return nil, err return nil, err
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package admission package admission
import ( import (
"context"
"fmt" "fmt"
auditinternal "k8s.io/apiserver/pkg/apis/audit" auditinternal "k8s.io/apiserver/pkg/apis/audit"
@ -44,7 +45,7 @@ func WithAudit(i Interface, ae *auditinternal.Event) Interface {
return &auditHandler{i, ae} return &auditHandler{i, ae}
} }
func (handler auditHandler) Admit(a Attributes, o ObjectInterfaces) error { func (handler auditHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error {
if !handler.Interface.Handles(a.GetOperation()) { if !handler.Interface.Handles(a.GetOperation()) {
return nil return nil
} }
@ -53,13 +54,13 @@ func (handler auditHandler) Admit(a Attributes, o ObjectInterfaces) error {
} }
var err error var err error
if mutator, ok := handler.Interface.(MutationInterface); ok { if mutator, ok := handler.Interface.(MutationInterface); ok {
err = mutator.Admit(a, o) err = mutator.Admit(ctx, a, o)
handler.logAnnotations(a) handler.logAnnotations(a)
} }
return err return err
} }
func (handler auditHandler) Validate(a Attributes, o ObjectInterfaces) error { func (handler auditHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error {
if !handler.Interface.Handles(a.GetOperation()) { if !handler.Interface.Handles(a.GetOperation()) {
return nil return nil
} }
@ -68,7 +69,7 @@ func (handler auditHandler) Validate(a Attributes, o ObjectInterfaces) error {
} }
var err error var err error
if validator, ok := handler.Interface.(ValidationInterface); ok { if validator, ok := handler.Interface.(ValidationInterface); ok {
err = validator.Validate(a, o) err = validator.Validate(ctx, a, o)
handler.logAnnotations(a) handler.logAnnotations(a)
} }
return err return err

View File

@ -17,6 +17,7 @@ limitations under the License.
package admission package admission
import ( import (
"context"
"fmt" "fmt"
"testing" "testing"
@ -45,14 +46,14 @@ var _ Interface = &fakeHandler{}
var _ MutationInterface = &fakeHandler{} var _ MutationInterface = &fakeHandler{}
var _ ValidationInterface = &fakeHandler{} var _ ValidationInterface = &fakeHandler{}
func (h fakeHandler) Admit(a Attributes, o ObjectInterfaces) error { func (h fakeHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error {
for k, v := range h.admitAnnotations { for k, v := range h.admitAnnotations {
a.AddAnnotation(k, v) a.AddAnnotation(k, v)
} }
return h.admit return h.admit
} }
func (h fakeHandler) Validate(a Attributes, o ObjectInterfaces) error { func (h fakeHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error {
for k, v := range h.validateAnnotations { for k, v := range h.validateAnnotations {
a.AddAnnotation(k, v) a.AddAnnotation(k, v)
} }
@ -149,13 +150,13 @@ func TestWithAudit(t *testing.T) {
require.True(t, ok) require.True(t, ok)
auditMutator, ok := auditHandler.(MutationInterface) auditMutator, ok := auditHandler.(MutationInterface)
require.True(t, ok) require.True(t, ok)
assert.Equal(t, mutator.Admit(a, nil), auditMutator.Admit(a, nil), tcName+": WithAudit decorator should not effect the return value") assert.Equal(t, mutator.Admit(context.TODO(), a, nil), auditMutator.Admit(context.TODO(), a, nil), tcName+": WithAudit decorator should not effect the return value")
validator, ok := handler.(ValidationInterface) validator, ok := handler.(ValidationInterface)
require.True(t, ok) require.True(t, ok)
auditValidator, ok := auditHandler.(ValidationInterface) auditValidator, ok := auditHandler.(ValidationInterface)
require.True(t, ok) require.True(t, ok)
assert.Equal(t, validator.Validate(a, nil), auditValidator.Validate(a, nil), tcName+": WithAudit decorator should not effect the return value") assert.Equal(t, validator.Validate(context.TODO(), a, nil), auditValidator.Validate(context.TODO(), a, nil), tcName+": WithAudit decorator should not effect the return value")
annotations := make(map[string]string, len(tc.admitAnnotations)+len(tc.validateAnnotations)) annotations := make(map[string]string, len(tc.admitAnnotations)+len(tc.validateAnnotations))
for k, v := range tc.admitAnnotations { for k, v := range tc.admitAnnotations {

View File

@ -16,6 +16,8 @@ limitations under the License.
package admission package admission
import "context"
// chainAdmissionHandler is an instance of admission.NamedHandler that performs admission control using // chainAdmissionHandler is an instance of admission.NamedHandler that performs admission control using
// a chain of admission handlers // a chain of admission handlers
type chainAdmissionHandler []Interface type chainAdmissionHandler []Interface
@ -26,13 +28,13 @@ func NewChainHandler(handlers ...Interface) chainAdmissionHandler {
} }
// Admit performs an admission control check using a chain of handlers, and returns immediately on first error // Admit performs an admission control check using a chain of handlers, and returns immediately on first error
func (admissionHandler chainAdmissionHandler) Admit(a Attributes, o ObjectInterfaces) error { func (admissionHandler chainAdmissionHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error {
for _, handler := range admissionHandler { for _, handler := range admissionHandler {
if !handler.Handles(a.GetOperation()) { if !handler.Handles(a.GetOperation()) {
continue continue
} }
if mutator, ok := handler.(MutationInterface); ok { if mutator, ok := handler.(MutationInterface); ok {
err := mutator.Admit(a, o) err := mutator.Admit(ctx, a, o)
if err != nil { if err != nil {
return err return err
} }
@ -42,13 +44,13 @@ func (admissionHandler chainAdmissionHandler) Admit(a Attributes, o ObjectInterf
} }
// Validate performs an admission control check using a chain of handlers, and returns immediately on first error // Validate performs an admission control check using a chain of handlers, and returns immediately on first error
func (admissionHandler chainAdmissionHandler) Validate(a Attributes, o ObjectInterfaces) error { func (admissionHandler chainAdmissionHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error {
for _, handler := range admissionHandler { for _, handler := range admissionHandler {
if !handler.Handles(a.GetOperation()) { if !handler.Handles(a.GetOperation()) {
continue continue
} }
if validator, ok := handler.(ValidationInterface); ok { if validator, ok := handler.(ValidationInterface); ok {
err := validator.Validate(a, o) err := validator.Validate(ctx, a, o)
if err != nil { if err != nil {
return err return err
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package admission package admission
import ( import (
"context"
"fmt" "fmt"
"testing" "testing"
@ -32,7 +33,7 @@ type FakeHandler struct {
validate, validateCalled bool validate, validateCalled bool
} }
func (h *FakeHandler) Admit(a Attributes, o ObjectInterfaces) (err error) { func (h *FakeHandler) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) (err error) {
h.admitCalled = true h.admitCalled = true
if h.admit { if h.admit {
return nil return nil
@ -40,7 +41,7 @@ func (h *FakeHandler) Admit(a Attributes, o ObjectInterfaces) (err error) {
return fmt.Errorf("Don't admit") return fmt.Errorf("Don't admit")
} }
func (h *FakeHandler) Validate(a Attributes, o ObjectInterfaces) (err error) { func (h *FakeHandler) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) (err error) {
h.validateCalled = true h.validateCalled = true
if h.validate { if h.validate {
return nil return nil
@ -125,7 +126,7 @@ func TestAdmitAndValidate(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Logf("testcase = %s", test.name) t.Logf("testcase = %s", test.name)
// call admit and check that validate was not called at all // call admit and check that validate was not called at all
err := test.chain.Admit(NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) err := test.chain.Admit(context.TODO(), NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil)
accepted := (err == nil) accepted := (err == nil)
if accepted != test.accept { if accepted != test.accept {
t.Errorf("unexpected result of admit call: %v", accepted) t.Errorf("unexpected result of admit call: %v", accepted)
@ -146,7 +147,7 @@ func TestAdmitAndValidate(t *testing.T) {
} }
// call validate and check that admit was not called at all // call validate and check that admit was not called at all
err = test.chain.Validate(NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) err = test.chain.Validate(context.TODO(), NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil)
accepted = (err == nil) accepted = (err == nil)
if accepted != test.accept { if accepted != test.accept {
t.Errorf("unexpected result of validate call: %v\n", accepted) t.Errorf("unexpected result of validate call: %v\n", accepted)

View File

@ -17,6 +17,7 @@ limitations under the License.
package initializer_test package initializer_test
import ( import (
"context"
"testing" "testing"
"time" "time"
@ -72,7 +73,7 @@ type WantExternalKubeInformerFactory struct {
func (self *WantExternalKubeInformerFactory) SetExternalKubeInformerFactory(sf informers.SharedInformerFactory) { func (self *WantExternalKubeInformerFactory) SetExternalKubeInformerFactory(sf informers.SharedInformerFactory) {
self.sf = sf self.sf = sf
} }
func (self *WantExternalKubeInformerFactory) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (self *WantExternalKubeInformerFactory) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
return nil return nil
} }
func (self *WantExternalKubeInformerFactory) Handles(o admission.Operation) bool { return false } func (self *WantExternalKubeInformerFactory) Handles(o admission.Operation) bool { return false }
@ -87,7 +88,7 @@ type WantExternalKubeClientSet struct {
} }
func (self *WantExternalKubeClientSet) SetExternalKubeClientSet(cs kubernetes.Interface) { self.cs = cs } func (self *WantExternalKubeClientSet) SetExternalKubeClientSet(cs kubernetes.Interface) { self.cs = cs }
func (self *WantExternalKubeClientSet) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (self *WantExternalKubeClientSet) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
return nil return nil
} }
func (self *WantExternalKubeClientSet) Handles(o admission.Operation) bool { return false } func (self *WantExternalKubeClientSet) Handles(o admission.Operation) bool { return false }
@ -102,7 +103,7 @@ type WantAuthorizerAdmission struct {
} }
func (self *WantAuthorizerAdmission) SetAuthorizer(a authorizer.Authorizer) { self.auth = a } func (self *WantAuthorizerAdmission) SetAuthorizer(a authorizer.Authorizer) { self.auth = a }
func (self *WantAuthorizerAdmission) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (self *WantAuthorizerAdmission) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
return nil return nil
} }
func (self *WantAuthorizerAdmission) Handles(o admission.Operation) bool { return false } func (self *WantAuthorizerAdmission) Handles(o admission.Operation) bool { return false }
@ -124,7 +125,7 @@ type clientCertWanter struct {
} }
func (s *clientCertWanter) SetClientCert(cert, key []byte) { s.gotCert, s.gotKey = cert, key } func (s *clientCertWanter) SetClientCert(cert, key []byte) { s.gotCert, s.gotKey = cert, key }
func (s *clientCertWanter) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (s *clientCertWanter) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
return nil return nil
} }
func (s *clientCertWanter) Handles(o admission.Operation) bool { return false } func (s *clientCertWanter) Handles(o admission.Operation) bool { return false }

View File

@ -17,6 +17,7 @@ limitations under the License.
package admission package admission
import ( import (
"context"
"io" "io"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
@ -120,8 +121,9 @@ type Interface interface {
type MutationInterface interface { type MutationInterface interface {
Interface Interface
// Admit makes an admission decision based on the request attributes // Admit makes an admission decision based on the request attributes.
Admit(a Attributes, o ObjectInterfaces) (err error) // Context is used only for timeout/deadline/cancellation and tracing information.
Admit(ctx context.Context, a Attributes, o ObjectInterfaces) (err error)
} }
// ValidationInterface is an abstract, pluggable interface for Admission Control decisions. // ValidationInterface is an abstract, pluggable interface for Admission Control decisions.
@ -129,7 +131,8 @@ type ValidationInterface interface {
Interface Interface
// Validate makes an admission decision based on the request attributes. It is NOT allowed to mutate // Validate makes an admission decision based on the request attributes. It is NOT allowed to mutate
Validate(a Attributes, o ObjectInterfaces) (err error) // Context is used only for timeout/deadline/cancellation and tracing information.
Validate(ctx context.Context, a Attributes, o ObjectInterfaces) (err error)
} }
// Operation is the type of resource operation being checked for admission control // Operation is the type of resource operation being checked for admission control

View File

@ -17,6 +17,7 @@ limitations under the License.
package metrics package metrics
import ( import (
"context"
"fmt" "fmt"
"strconv" "strconv"
"time" "time"
@ -75,27 +76,27 @@ type pluginHandlerWithMetrics struct {
} }
// Admit performs a mutating admission control check and emit metrics. // Admit performs a mutating admission control check and emit metrics.
func (p pluginHandlerWithMetrics) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (p pluginHandlerWithMetrics) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
mutatingHandler, ok := p.Interface.(admission.MutationInterface) mutatingHandler, ok := p.Interface.(admission.MutationInterface)
if !ok { if !ok {
return nil return nil
} }
start := time.Now() start := time.Now()
err := mutatingHandler.Admit(a, o) err := mutatingHandler.Admit(ctx, a, o)
p.observer(time.Since(start), err != nil, a, stepAdmit, p.extraLabels...) p.observer(time.Since(start), err != nil, a, stepAdmit, p.extraLabels...)
return err return err
} }
// Validate performs a non-mutating admission control check and emits metrics. // Validate performs a non-mutating admission control check and emits metrics.
func (p pluginHandlerWithMetrics) Validate(a admission.Attributes, o admission.ObjectInterfaces) error { func (p pluginHandlerWithMetrics) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
validatingHandler, ok := p.Interface.(admission.ValidationInterface) validatingHandler, ok := p.Interface.(admission.ValidationInterface)
if !ok { if !ok {
return nil return nil
} }
start := time.Now() start := time.Now()
err := validatingHandler.Validate(a, o) err := validatingHandler.Validate(ctx, a, o)
p.observer(time.Since(start), err != nil, a, stepValidate, p.extraLabels...) p.observer(time.Since(start), err != nil, a, stepValidate, p.extraLabels...)
return err return err
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package metrics package metrics
import ( import (
"context"
"fmt" "fmt"
"testing" "testing"
"time" "time"
@ -36,8 +37,8 @@ var (
func TestObserveAdmissionStep(t *testing.T) { func TestObserveAdmissionStep(t *testing.T) {
Metrics.reset() Metrics.reset()
handler := WithStepMetrics(&mutatingAndValidatingFakeHandler{admission.NewHandler(admission.Create), true, true}) handler := WithStepMetrics(&mutatingAndValidatingFakeHandler{admission.NewHandler(admission.Create), true, true})
handler.(admission.MutationInterface).Admit(attr, nil) handler.(admission.MutationInterface).Admit(context.TODO(), attr, nil)
handler.(admission.ValidationInterface).Validate(attr, nil) handler.(admission.ValidationInterface).Validate(context.TODO(), attr, nil)
wantLabels := map[string]string{ wantLabels := map[string]string{
"operation": string(admission.Create), "operation": string(admission.Create),
"type": "admit", "type": "admit",
@ -54,8 +55,8 @@ func TestObserveAdmissionStep(t *testing.T) {
func TestObserveAdmissionController(t *testing.T) { func TestObserveAdmissionController(t *testing.T) {
Metrics.reset() Metrics.reset()
handler := WithControllerMetrics(&mutatingAndValidatingFakeHandler{admission.NewHandler(admission.Create), true, true}, "a") handler := WithControllerMetrics(&mutatingAndValidatingFakeHandler{admission.NewHandler(admission.Create), true, true}, "a")
handler.(admission.MutationInterface).Admit(attr, nil) handler.(admission.MutationInterface).Admit(context.TODO(), attr, nil)
handler.(admission.ValidationInterface).Validate(attr, nil) handler.(admission.ValidationInterface).Validate(context.TODO(), attr, nil)
wantLabels := map[string]string{ wantLabels := map[string]string{
"name": "a", "name": "a",
"operation": string(admission.Create), "operation": string(admission.Create),
@ -154,7 +155,7 @@ func TestWithMetrics(t *testing.T) {
h := WithMetrics(test.handler, Metrics.ObserveAdmissionController, test.name) h := WithMetrics(test.handler, Metrics.ObserveAdmissionController, test.name)
// test mutation // test mutation
err := h.(admission.MutationInterface).Admit(admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) err := h.(admission.MutationInterface).Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil)
if test.admit && err != nil { if test.admit && err != nil {
t.Errorf("expected admit to succeed, but failed: %v", err) t.Errorf("expected admit to succeed, but failed: %v", err)
continue continue
@ -179,7 +180,7 @@ func TestWithMetrics(t *testing.T) {
} }
// test validation // test validation
err = h.(admission.ValidationInterface).Validate(admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil) err = h.(admission.ValidationInterface).Validate(context.TODO(), admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{}, test.ns, "", schema.GroupVersionResource{}, "", test.operation, test.options, false, nil), nil)
if test.validate && err != nil { if test.validate && err != nil {
t.Errorf("expected admit to succeed, but failed: %v", err) t.Errorf("expected admit to succeed, but failed: %v", err)
continue continue
@ -206,14 +207,14 @@ type mutatingAndValidatingFakeHandler struct {
validate bool validate bool
} }
func (h *mutatingAndValidatingFakeHandler) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (h *mutatingAndValidatingFakeHandler) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
if h.admit { if h.admit {
return nil return nil
} }
return fmt.Errorf("don't admit") return fmt.Errorf("don't admit")
} }
func (h *mutatingAndValidatingFakeHandler) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (h *mutatingAndValidatingFakeHandler) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
if h.validate { if h.validate {
return nil return nil
} }
@ -225,7 +226,7 @@ type validatingFakeHandler struct {
validate bool validate bool
} }
func (h *validatingFakeHandler) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (h *validatingFakeHandler) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
if h.validate { if h.validate {
return nil return nil
} }
@ -237,7 +238,7 @@ type mutatingFakeHandler struct {
admit bool admit bool
} }
func (h *mutatingFakeHandler) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (h *mutatingFakeHandler) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
if h.admit { if h.admit {
return nil return nil
} }

View File

@ -17,13 +17,14 @@ limitations under the License.
package lifecycle package lifecycle
import ( import (
"context"
"fmt" "fmt"
"io" "io"
"time" "time"
"k8s.io/klog" "k8s.io/klog"
"k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
@ -73,7 +74,7 @@ var _ = initializer.WantsExternalKubeInformerFactory(&Lifecycle{})
var _ = initializer.WantsExternalKubeClientSet(&Lifecycle{}) var _ = initializer.WantsExternalKubeClientSet(&Lifecycle{})
// Admit makes an admission decision based on the request attributes // Admit makes an admission decision based on the request attributes
func (l *Lifecycle) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (l *Lifecycle) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
// prevent deletion of immortal namespaces // prevent deletion of immortal namespaces
if a.GetOperation() == admission.Delete && a.GetKind().GroupKind() == v1.SchemeGroupVersion.WithKind("Namespace").GroupKind() && l.immortalNamespaces.Has(a.GetName()) { if a.GetOperation() == admission.Delete && a.GetKind().GroupKind() == v1.SchemeGroupVersion.WithKind("Namespace").GroupKind() && l.immortalNamespaces.Has(a.GetName()) {
return errors.NewForbidden(a.GetResource().GroupResource(), a.GetName(), fmt.Errorf("this namespace may not be deleted")) return errors.NewForbidden(a.GetResource().GroupResource(), a.GetName(), fmt.Errorf("this namespace may not be deleted"))

View File

@ -17,6 +17,7 @@ limitations under the License.
package lifecycle package lifecycle
import ( import (
"context"
"fmt" "fmt"
"testing" "testing"
"time" "time"
@ -104,7 +105,7 @@ func TestAccessReviewCheckOnMissingNamespace(t *testing.T) {
} }
informerFactory.Start(wait.NeverStop) informerFactory.Start(wait.NeverStop)
err = handler.Admit(admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{Group: "authorization.k8s.io", Version: "v1", Kind: "LocalSubjectAccesReview"}, namespace, "", schema.GroupVersionResource{Group: "authorization.k8s.io", Version: "v1", Resource: "localsubjectaccessreviews"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, schema.GroupVersionKind{Group: "authorization.k8s.io", Version: "v1", Kind: "LocalSubjectAccesReview"}, namespace, "", schema.GroupVersionResource{Group: "authorization.k8s.io", Version: "v1", Resource: "localsubjectaccessreviews"}, "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Error(err) t.Error(err)
} }
@ -124,7 +125,7 @@ func TestAdmissionNamespaceDoesNotExist(t *testing.T) {
informerFactory.Start(wait.NeverStop) informerFactory.Start(wait.NeverStop)
pod := newPod(namespace) pod := newPod(namespace)
err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
actions := "" actions := ""
for _, action := range mockClient.Actions() { for _, action := range mockClient.Actions() {
@ -134,19 +135,19 @@ func TestAdmissionNamespaceDoesNotExist(t *testing.T) {
} }
// verify create operations in the namespace cause an error // verify create operations in the namespace cause an error
err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected error rejecting creates in a namespace when it is missing") t.Errorf("Expected error rejecting creates in a namespace when it is missing")
} }
// verify update operations in the namespace cause an error // verify update operations in the namespace cause an error
err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected error rejecting updates in a namespace when it is missing") t.Errorf("Expected error rejecting updates in a namespace when it is missing")
} }
// verify delete operations in the namespace can proceed // verify delete operations in the namespace can proceed
err = handler.Admit(admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error returned from admission handler: %v", err) t.Errorf("Unexpected error returned from admission handler: %v", err)
} }
@ -166,7 +167,7 @@ func TestAdmissionNamespaceActive(t *testing.T) {
informerFactory.Start(wait.NeverStop) informerFactory.Start(wait.NeverStop)
pod := newPod(namespace) pod := newPod(namespace)
err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("unexpected error returned from admission handler") t.Errorf("unexpected error returned from admission handler")
} }
@ -187,31 +188,31 @@ func TestAdmissionNamespaceTerminating(t *testing.T) {
pod := newPod(namespace) pod := newPod(namespace)
// verify create operations in the namespace cause an error // verify create operations in the namespace cause an error
err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected error rejecting creates in a namespace when it is terminating") t.Errorf("Expected error rejecting creates in a namespace when it is terminating")
} }
// verify update operations in the namespace can proceed // verify update operations in the namespace can proceed
err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Update, &metav1.UpdateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error returned from admission handler: %v", err) t.Errorf("Unexpected error returned from admission handler: %v", err)
} }
// verify delete operations in the namespace can proceed // verify delete operations in the namespace can proceed
err = handler.Admit(admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error returned from admission handler: %v", err) t.Errorf("Unexpected error returned from admission handler: %v", err)
} }
// verify delete of namespace default can never proceed // verify delete of namespace default can never proceed
err = handler.Admit(admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), "", metav1.NamespaceDefault, v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), "", metav1.NamespaceDefault, v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected an error that this namespace can never be deleted") t.Errorf("Expected an error that this namespace can never be deleted")
} }
// verify delete of namespace other than default can proceed // verify delete of namespace other than default can proceed
err = handler.Admit(admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), "", "other", v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), "", "other", v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Did not expect an error %v", err) t.Errorf("Did not expect an error %v", err)
} }
@ -238,7 +239,7 @@ func TestAdmissionNamespaceForceLiveLookup(t *testing.T) {
pod := newPod(namespace) pod := newPod(namespace)
// verify create operations in the namespace is allowed // verify create operations in the namespace is allowed
err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Unexpected error rejecting creates in an active namespace") t.Errorf("Unexpected error rejecting creates in an active namespace")
} }
@ -248,7 +249,7 @@ func TestAdmissionNamespaceForceLiveLookup(t *testing.T) {
getCalls = 0 getCalls = 0
// verify delete of namespace can proceed // verify delete of namespace can proceed
err = handler.Admit(admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), namespace, namespace, v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(nil, nil, v1.SchemeGroupVersion.WithKind("Namespace").GroupKind().WithVersion("version"), namespace, namespace, v1.Resource("namespaces").WithVersion("version"), "", admission.Delete, &metav1.DeleteOptions{}, false, nil), nil)
if err != nil { if err != nil {
t.Errorf("Expected namespace deletion to be allowed") t.Errorf("Expected namespace deletion to be allowed")
} }
@ -261,7 +262,7 @@ func TestAdmissionNamespaceForceLiveLookup(t *testing.T) {
phases[namespace] = v1.NamespaceTerminating phases[namespace] = v1.NamespaceTerminating
// verify create operations in the namespace cause an error // verify create operations in the namespace cause an error
err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected error rejecting creates in a namespace right after deleting it") t.Errorf("Expected error rejecting creates in a namespace right after deleting it")
} }
@ -274,7 +275,7 @@ func TestAdmissionNamespaceForceLiveLookup(t *testing.T) {
fakeClock.Step(forceLiveLookupTTL) fakeClock.Step(forceLiveLookupTTL)
// verify create operations in the namespace cause an error // verify create operations in the namespace cause an error
err = handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) err = handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if err == nil { if err == nil {
t.Errorf("Expected error rejecting creates in a namespace right after deleting it") t.Errorf("Expected error rejecting creates in a namespace right after deleting it")
} }
@ -287,7 +288,7 @@ func TestAdmissionNamespaceForceLiveLookup(t *testing.T) {
fakeClock.Step(time.Millisecond) fakeClock.Step(time.Millisecond)
// verify create operations in the namespace don't force a live lookup after the timeout // verify create operations in the namespace don't force a live lookup after the timeout
handler.Admit(admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil) handler.Admit(context.TODO(), admission.NewAttributesRecord(&pod, nil, v1.SchemeGroupVersion.WithKind("Pod").GroupKind().WithVersion("version"), pod.Namespace, pod.Name, v1.Resource("pods").WithVersion("version"), "", admission.Create, &metav1.CreateOptions{}, false, nil), nil)
if getCalls != 0 { if getCalls != 0 {
t.Errorf("Expected no live lookup of the namespace at t=forceLiveLookupTTL+1ms, got %d", getCalls) t.Errorf("Expected no live lookup of the namespace at t=forceLiveLookupTTL+1ms, got %d", getCalls)
} }

View File

@ -211,7 +211,7 @@ type attrWithResourceOverride struct {
func (a *attrWithResourceOverride) GetResource() schema.GroupVersionResource { return a.resource } func (a *attrWithResourceOverride) GetResource() schema.GroupVersionResource { return a.resource }
// Dispatch is called by the downstream Validate or Admit methods. // Dispatch is called by the downstream Validate or Admit methods.
func (a *Webhook) Dispatch(attr admission.Attributes, o admission.ObjectInterfaces) error { func (a *Webhook) Dispatch(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error {
if rules.IsWebhookConfigurationResource(attr) { if rules.IsWebhookConfigurationResource(attr) {
return nil return nil
} }
@ -219,8 +219,5 @@ func (a *Webhook) Dispatch(attr admission.Attributes, o admission.ObjectInterfac
return admission.NewForbidden(attr, fmt.Errorf("not yet ready to handle request")) return admission.NewForbidden(attr, fmt.Errorf("not yet ready to handle request"))
} }
hooks := a.hookSource.Webhooks() hooks := a.hookSource.Webhooks()
// TODO: Figure out if adding one second timeout make sense here.
ctx := context.TODO()
return a.dispatcher.Dispatch(ctx, attr, o, hooks) return a.dispatcher.Dispatch(ctx, attr, o, hooks)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package mutating package mutating
import ( import (
"context"
"io" "io"
"k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/admission"
@ -70,6 +71,6 @@ func (a *Plugin) ValidateInitialization() error {
} }
// Admit makes an admission decision based on the request attributes. // Admit makes an admission decision based on the request attributes.
func (a *Plugin) Admit(attr admission.Attributes, o admission.ObjectInterfaces) error { func (a *Plugin) Admit(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error {
return a.Webhook.Dispatch(attr, o) return a.Webhook.Dispatch(ctx, attr, o)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package mutating package mutating
import ( import (
"context"
"fmt" "fmt"
"net/url" "net/url"
"reflect" "reflect"
@ -80,7 +81,7 @@ func TestAdmit(t *testing.T) {
attr = webhooktesting.NewAttribute(ns, tt.AdditionalLabels, tt.IsDryRun) attr = webhooktesting.NewAttribute(ns, tt.AdditionalLabels, tt.IsDryRun)
} }
err = wh.Admit(attr, objectInterfaces) err = wh.Admit(context.TODO(), attr, objectInterfaces)
if tt.ExpectAllow != (err == nil) { if tt.ExpectAllow != (err == nil) {
t.Errorf("expected allowed=%v, but got err=%v", tt.ExpectAllow, err) t.Errorf("expected allowed=%v, but got err=%v", tt.ExpectAllow, err)
} }
@ -163,7 +164,7 @@ func TestAdmitCachedClient(t *testing.T) {
continue continue
} }
err = wh.Admit(webhooktesting.NewAttribute(ns, nil, false), objectInterfaces) err = wh.Admit(context.TODO(), webhooktesting.NewAttribute(ns, nil, false), objectInterfaces)
if tt.ExpectAllow != (err == nil) { if tt.ExpectAllow != (err == nil) {
t.Errorf("%s: expected allowed=%v, but got err=%v", tt.Name, tt.ExpectAllow, err) t.Errorf("%s: expected allowed=%v, but got err=%v", tt.Name, tt.ExpectAllow, err)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package validating package validating
import ( import (
"context"
"io" "io"
"k8s.io/apiserver/pkg/admission" "k8s.io/apiserver/pkg/admission"
@ -61,6 +62,6 @@ func NewValidatingAdmissionWebhook(configFile io.Reader) (*Plugin, error) {
} }
// Validate makes an admission decision based on the request attributes. // Validate makes an admission decision based on the request attributes.
func (a *Plugin) Validate(attr admission.Attributes, o admission.ObjectInterfaces) error { func (a *Plugin) Validate(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error {
return a.Webhook.Dispatch(attr, o) return a.Webhook.Dispatch(ctx, attr, o)
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package validating package validating
import ( import (
"context"
"net/url" "net/url"
"strings" "strings"
"testing" "testing"
@ -67,7 +68,7 @@ func TestValidate(t *testing.T) {
} }
attr := webhooktesting.NewAttribute(ns, nil, tt.IsDryRun) attr := webhooktesting.NewAttribute(ns, nil, tt.IsDryRun)
err = wh.Validate(attr, objectInterfaces) err = wh.Validate(context.TODO(), attr, objectInterfaces)
if tt.ExpectAllow != (err == nil) { if tt.ExpectAllow != (err == nil) {
t.Errorf("%s: expected allowed=%v, but got err=%v", tt.Name, tt.ExpectAllow, err) t.Errorf("%s: expected allowed=%v, but got err=%v", tt.Name, tt.ExpectAllow, err)
} }
@ -132,7 +133,7 @@ func TestValidateCachedClient(t *testing.T) {
continue continue
} }
err = wh.Validate(webhooktesting.NewAttribute(ns, nil, false), objectInterfaces) err = wh.Validate(context.TODO(), webhooktesting.NewAttribute(ns, nil, false), objectInterfaces)
if tt.ExpectAllow != (err == nil) { if tt.ExpectAllow != (err == nil) {
t.Errorf("%s: expected allowed=%v, but got err=%v", tt.Name, tt.ExpectAllow, err) t.Errorf("%s: expected allowed=%v, but got err=%v", tt.Name, tt.ExpectAllow, err)
} }

View File

@ -16,6 +16,8 @@ limitations under the License.
package admission package admission
import "context"
// newReinvocationHandler creates a handler that wraps the provided admission chain and reinvokes it // newReinvocationHandler creates a handler that wraps the provided admission chain and reinvokes it
// if needed according to re-invocation policy of the webhooks. // if needed according to re-invocation policy of the webhooks.
func newReinvocationHandler(admissionChain Interface) Interface { func newReinvocationHandler(admissionChain Interface) Interface {
@ -30,9 +32,9 @@ type reinvoker struct {
// admission chain if needed according to the reinvocation policy. Plugins are expected to check // admission chain if needed according to the reinvocation policy. Plugins are expected to check
// the admission attributes' reinvocation context against their reinvocation policy to decide if // the admission attributes' reinvocation context against their reinvocation policy to decide if
// they should re-run, and to update the reinvocation context if they perform any mutations. // they should re-run, and to update the reinvocation context if they perform any mutations.
func (r *reinvoker) Admit(a Attributes, o ObjectInterfaces) error { func (r *reinvoker) Admit(ctx context.Context, a Attributes, o ObjectInterfaces) error {
if mutator, ok := r.admissionChain.(MutationInterface); ok { if mutator, ok := r.admissionChain.(MutationInterface); ok {
err := mutator.Admit(a, o) err := mutator.Admit(ctx, a, o)
if err != nil { if err != nil {
return err return err
} }
@ -42,16 +44,16 @@ func (r *reinvoker) Admit(a Attributes, o ObjectInterfaces) error {
// Calling admit a second time will reinvoke all in-tree plugins // Calling admit a second time will reinvoke all in-tree plugins
// as well as any webhook plugins that need to be reinvoked based on the // as well as any webhook plugins that need to be reinvoked based on the
// reinvocation policy. // reinvocation policy.
return mutator.Admit(a, o) return mutator.Admit(ctx, a, o)
} }
} }
return nil return nil
} }
// Validate performs an admission control check using the wrapped admission chain, and returns immediately on first error. // Validate performs an admission control check using the wrapped admission chain, and returns immediately on first error.
func (r *reinvoker) Validate(a Attributes, o ObjectInterfaces) error { func (r *reinvoker) Validate(ctx context.Context, a Attributes, o ObjectInterfaces) error {
if validator, ok := r.admissionChain.(ValidationInterface); ok { if validator, ok := r.admissionChain.(ValidationInterface); ok {
return validator.Validate(a, o) return validator.Validate(ctx, a, o)
} }
return nil return nil
} }

View File

@ -17,6 +17,7 @@ limitations under the License.
package testing package testing
import ( import (
"context"
"reflect" "reflect"
"testing" "testing"
@ -40,11 +41,11 @@ type reinvoker struct {
// Admit reinvokes the admission handler and reports a test error if the admission handler performs // Admit reinvokes the admission handler and reports a test error if the admission handler performs
// non-idempotent mutatations to the admission object. // non-idempotent mutatations to the admission object.
func (r *reinvoker) Admit(a admission.Attributes, o admission.ObjectInterfaces) error { func (r *reinvoker) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
r.t.Helper() r.t.Helper()
outputs := []runtime.Object{} outputs := []runtime.Object{}
for i := 0; i < 2; i++ { for i := 0; i < 2; i++ {
err := r.admission.Admit(a, o) err := r.admission.Admit(ctx, a, o)
if err != nil { if err != nil {
return err return err
} }

View File

@ -77,7 +77,7 @@ import (
type alwaysMutatingDeny struct{} type alwaysMutatingDeny struct{}
func (alwaysMutatingDeny) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (alwaysMutatingDeny) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
return admission.NewForbidden(a, errors.New("Mutating admission control is denying all modifications")) return admission.NewForbidden(a, errors.New("Mutating admission control is denying all modifications"))
} }
@ -87,7 +87,7 @@ func (alwaysMutatingDeny) Handles(operation admission.Operation) bool {
type alwaysValidatingDeny struct{} type alwaysValidatingDeny struct{}
func (alwaysValidatingDeny) Validate(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (alwaysValidatingDeny) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
return admission.NewForbidden(a, errors.New("Validating admission control is denying all modifications")) return admission.NewForbidden(a, errors.New("Validating admission control is denying all modifications"))
} }
@ -448,7 +448,7 @@ func (storage *SimpleRESTStorage) Delete(ctx context.Context, id string, deleteV
if err := storage.errors["delete"]; err != nil { if err := storage.errors["delete"]; err != nil {
return nil, false, err return nil, false, err
} }
if err := deleteValidation(&storage.item); err != nil { if err := deleteValidation(ctx, &storage.item); err != nil {
return nil, false, err return nil, false, err
} }
var obj runtime.Object = &metav1.Status{Status: metav1.StatusSuccess} var obj runtime.Object = &metav1.Status{Status: metav1.StatusSuccess}
@ -477,7 +477,7 @@ func (storage *SimpleRESTStorage) Create(ctx context.Context, obj runtime.Object
if storage.injectedFunction != nil { if storage.injectedFunction != nil {
obj, err = storage.injectedFunction(obj) obj, err = storage.injectedFunction(obj)
} }
if err := createValidation(obj); err != nil { if err := createValidation(ctx, obj); err != nil {
return nil, err return nil, err
} }
return obj, err return obj, err
@ -496,7 +496,7 @@ func (storage *SimpleRESTStorage) Update(ctx context.Context, name string, objIn
if storage.injectedFunction != nil { if storage.injectedFunction != nil {
obj, err = storage.injectedFunction(obj) obj, err = storage.injectedFunction(obj)
} }
if err := updateValidation(&storage.item, obj); err != nil { if err := updateValidation(ctx, &storage.item, obj); err != nil {
return nil, false, err return nil, false, err
} }
return obj, false, err return obj, false, err
@ -654,7 +654,7 @@ func (storage *NamedCreaterRESTStorage) Create(ctx context.Context, name string,
if storage.injectedFunction != nil { if storage.injectedFunction != nil {
obj, err = storage.injectedFunction(obj) obj, err = storage.injectedFunction(obj)
} }
if err := createValidation(obj); err != nil { if err := createValidation(ctx, obj); err != nil {
return nil, err return nil, err
} }
return obj, err return obj, err

View File

@ -132,7 +132,7 @@ func createHandler(r rest.NamedCreater, scope *RequestScope, admit admission.Int
userInfo, _ := request.UserFrom(ctx) userInfo, _ := request.UserFrom(ctx)
admissionAttributes := admission.NewAttributesRecord(obj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, options, dryrun.IsDryRun(options.DryRun), userInfo) admissionAttributes := admission.NewAttributesRecord(obj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, options, dryrun.IsDryRun(options.DryRun), userInfo)
if mutatingAdmission, ok := admit.(admission.MutationInterface); ok && mutatingAdmission.Handles(admission.Create) { if mutatingAdmission, ok := admit.(admission.MutationInterface); ok && mutatingAdmission.Handles(admission.Create) {
err = mutatingAdmission.Admit(admissionAttributes, scope) err = mutatingAdmission.Admit(ctx, admissionAttributes, scope)
if err != nil { if err != nil {
scope.err(err, w, req) scope.err(err, w, req)
return return

View File

@ -239,7 +239,7 @@ func PatchResource(r rest.Patcher, scope *RequestScope, admit admission.Interfac
} }
} }
type mutateObjectUpdateFunc func(obj, old runtime.Object) error type mutateObjectUpdateFunc func(ctx context.Context, obj, old runtime.Object) error
// patcher breaks the process of patch application and retries into smaller // patcher breaks the process of patch application and retries into smaller
// pieces of functionality. // pieces of functionality.
@ -515,7 +515,7 @@ func (p *patcher) applyAdmission(ctx context.Context, patchedObject runtime.Obje
} }
if p.admissionCheck != nil && p.admissionCheck.Handles(operation) { if p.admissionCheck != nil && p.admissionCheck.Handles(operation) {
attributes := p.admissionAttributes(ctx, patchedObject, currentObject, operation, options) attributes := p.admissionAttributes(ctx, patchedObject, currentObject, operation, options)
return patchedObject, p.admissionCheck.Admit(attributes, p.objectInterfaces) return patchedObject, p.admissionCheck.Admit(ctx, attributes, p.objectInterfaces)
} }
return patchedObject, nil return patchedObject, nil
} }

View File

@ -163,14 +163,14 @@ func ConnectResource(connecter rest.Connecter, scope *RequestScope, admit admiss
userInfo, _ := request.UserFrom(ctx) userInfo, _ := request.UserFrom(ctx)
// TODO: remove the mutating admission here as soon as we have ported all plugin that handle CONNECT // TODO: remove the mutating admission here as soon as we have ported all plugin that handle CONNECT
if mutatingAdmission, ok := admit.(admission.MutationInterface); ok { if mutatingAdmission, ok := admit.(admission.MutationInterface); ok {
err = mutatingAdmission.Admit(admission.NewAttributesRecord(opts, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Connect, nil, false, userInfo), scope) err = mutatingAdmission.Admit(ctx, admission.NewAttributesRecord(opts, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Connect, nil, false, userInfo), scope)
if err != nil { if err != nil {
scope.err(err, w, req) scope.err(err, w, req)
return return
} }
} }
if validatingAdmission, ok := admit.(admission.ValidationInterface); ok { if validatingAdmission, ok := admit.(admission.ValidationInterface); ok {
err = validatingAdmission.Validate(admission.NewAttributesRecord(opts, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Connect, nil, false, userInfo), scope) err = validatingAdmission.Validate(ctx, admission.NewAttributesRecord(opts, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Connect, nil, false, userInfo), scope)
if err != nil { if err != nil {
scope.err(err, w, req) scope.err(err, w, req)
return return

View File

@ -260,11 +260,11 @@ func (p *testPatcher) Update(ctx context.Context, name string, objInfo rest.Upda
} }
if currentPod == nil { if currentPod == nil {
if err := createValidation(currentPod); err != nil { if err := createValidation(ctx, currentPod); err != nil {
return nil, false, err return nil, false, err
} }
} else { } else {
if err := updateValidation(currentPod, inPod); err != nil { if err := updateValidation(ctx, currentPod, inPod); err != nil {
return nil, false, err return nil, false, err
} }
} }
@ -351,13 +351,13 @@ func (tc *patchTestCase) Run(t *testing.T) {
admissionMutation := tc.admissionMutation admissionMutation := tc.admissionMutation
if admissionMutation == nil { if admissionMutation == nil {
admissionMutation = func(updatedObject runtime.Object, currentObject runtime.Object) error { admissionMutation = func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return nil return nil
} }
} }
admissionValidation := tc.admissionValidation admissionValidation := tc.admissionValidation
if admissionValidation == nil { if admissionValidation == nil {
admissionValidation = func(updatedObject runtime.Object, currentObject runtime.Object) error { admissionValidation = func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return nil return nil
} }
} }
@ -718,7 +718,7 @@ func TestPatchWithAdmissionRejection(t *testing.T) {
for _, test := range []Test{ for _, test := range []Test{
{ {
name: "TestPatchWithMutatingAdmissionRejection", name: "TestPatchWithMutatingAdmissionRejection",
admissionMutation: func(updatedObject runtime.Object, currentObject runtime.Object) error { admissionMutation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return errors.New("mutating admission failure") return errors.New("mutating admission failure")
}, },
admissionValidation: rest.ValidateAllObjectUpdateFunc, admissionValidation: rest.ValidateAllObjectUpdateFunc,
@ -727,17 +727,17 @@ func TestPatchWithAdmissionRejection(t *testing.T) {
{ {
name: "TestPatchWithValidatingAdmissionRejection", name: "TestPatchWithValidatingAdmissionRejection",
admissionMutation: rest.ValidateAllObjectUpdateFunc, admissionMutation: rest.ValidateAllObjectUpdateFunc,
admissionValidation: func(updatedObject runtime.Object, currentObject runtime.Object) error { admissionValidation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return errors.New("validating admission failure") return errors.New("validating admission failure")
}, },
expectedError: "validating admission failure", expectedError: "validating admission failure",
}, },
{ {
name: "TestPatchWithBothAdmissionRejections", name: "TestPatchWithBothAdmissionRejections",
admissionMutation: func(updatedObject runtime.Object, currentObject runtime.Object) error { admissionMutation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return errors.New("mutating admission failure") return errors.New("mutating admission failure")
}, },
admissionValidation: func(updatedObject runtime.Object, currentObject runtime.Object) error { admissionValidation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
return errors.New("validating admission failure") return errors.New("validating admission failure")
}, },
expectedError: "mutating admission failure", expectedError: "mutating admission failure",
@ -777,7 +777,7 @@ func TestPatchWithVersionConflictThenAdmissionFailure(t *testing.T) {
tc := &patchTestCase{ tc := &patchTestCase{
name: "TestPatchWithVersionConflictThenAdmissionFailure", name: "TestPatchWithVersionConflictThenAdmissionFailure",
admissionMutation: func(updatedObject runtime.Object, currentObject runtime.Object) error { admissionMutation: func(ctx context.Context, updatedObject runtime.Object, currentObject runtime.Object) error {
if seen { if seen {
return errors.New("admission failure") return errors.New("admission failure")
} }
@ -951,8 +951,8 @@ func (f mutateObjectUpdateFunc) Handles(operation admission.Operation) bool {
return true return true
} }
func (f mutateObjectUpdateFunc) Admit(a admission.Attributes, o admission.ObjectInterfaces) (err error) { func (f mutateObjectUpdateFunc) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) (err error) {
return f(a.GetObject(), a.GetOldObject()) return f(ctx, a.GetObject(), a.GetOldObject())
} }
func TestTransformDecodeErrorEnsuresBadRequestError(t *testing.T) { func TestTransformDecodeErrorEnsuresBadRequestError(t *testing.T) {

View File

@ -140,11 +140,11 @@ func UpdateResource(r rest.Updater, scope *RequestScope, admit admission.Interfa
return nil, fmt.Errorf("unexpected error when extracting UID from oldObj: %v", err.Error()) return nil, fmt.Errorf("unexpected error when extracting UID from oldObj: %v", err.Error())
} else if !isNotZeroObject { } else if !isNotZeroObject {
if mutatingAdmission.Handles(admission.Create) { if mutatingAdmission.Handles(admission.Create) {
return newObj, mutatingAdmission.Admit(admission.NewAttributesRecord(newObj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, updateToCreateOptions(options), dryrun.IsDryRun(options.DryRun), userInfo), scope) return newObj, mutatingAdmission.Admit(ctx, admission.NewAttributesRecord(newObj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, updateToCreateOptions(options), dryrun.IsDryRun(options.DryRun), userInfo), scope)
} }
} else { } else {
if mutatingAdmission.Handles(admission.Update) { if mutatingAdmission.Handles(admission.Update) {
return newObj, mutatingAdmission.Admit(admission.NewAttributesRecord(newObj, oldObj, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Update, options, dryrun.IsDryRun(options.DryRun), userInfo), scope) return newObj, mutatingAdmission.Admit(ctx, admission.NewAttributesRecord(newObj, oldObj, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Update, options, dryrun.IsDryRun(options.DryRun), userInfo), scope)
} }
} }
return newObj, nil return newObj, nil
@ -205,7 +205,7 @@ func withAuthorization(validate rest.ValidateObjectFunc, a authorizer.Authorizer
var authorizerDecision authorizer.Decision var authorizerDecision authorizer.Decision
var authorizerReason string var authorizerReason string
var authorizerErr error var authorizerErr error
return func(obj runtime.Object) error { return func(ctx context.Context, obj runtime.Object) error {
if a == nil { if a == nil {
return errors.NewInternalError(fmt.Errorf("no authorizer provided, unable to authorize a create on update")) return errors.NewInternalError(fmt.Errorf("no authorizer provided, unable to authorize a create on update"))
} }
@ -215,7 +215,7 @@ func withAuthorization(validate rest.ValidateObjectFunc, a authorizer.Authorizer
// an authorizer like RBAC could encounter evaluation errors and still allow the request, so authorizer decision is checked before error here. // an authorizer like RBAC could encounter evaluation errors and still allow the request, so authorizer decision is checked before error here.
if authorizerDecision == authorizer.DecisionAllow { if authorizerDecision == authorizer.DecisionAllow {
// Continue to validating admission // Continue to validating admission
return validate(obj) return validate(ctx, obj)
} }
if authorizerErr != nil { if authorizerErr != nil {
return errors.NewInternalError(authorizerErr) return errors.NewInternalError(authorizerErr)

View File

@ -52,7 +52,7 @@ func (s *DryRunnableStorage) Delete(ctx context.Context, key string, out runtime
if err := preconditions.Check(key, out); err != nil { if err := preconditions.Check(key, out); err != nil {
return err return err
} }
return deleteValidation(out) return deleteValidation(ctx, out)
} }
return s.Storage.Delete(ctx, key, out, preconditions, deleteValidation) return s.Storage.Delete(ctx, key, out, preconditions, deleteValidation)
} }

View File

@ -342,7 +342,7 @@ func (e *Store) Create(ctx context.Context, obj runtime.Object, createValidation
// at this point we have a fully formed object. It is time to call the validators that the apiserver // at this point we have a fully formed object. It is time to call the validators that the apiserver
// handling chain wants to enforce. // handling chain wants to enforce.
if createValidation != nil { if createValidation != nil {
if err := createValidation(obj.DeepCopyObject()); err != nil { if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
return nil, err return nil, err
} }
} }
@ -504,7 +504,7 @@ func (e *Store) Update(ctx context.Context, name string, objInfo rest.UpdatedObj
// at this point we have a fully formed object. It is time to call the validators that the apiserver // at this point we have a fully formed object. It is time to call the validators that the apiserver
// handling chain wants to enforce. // handling chain wants to enforce.
if createValidation != nil { if createValidation != nil {
if err := createValidation(obj.DeepCopyObject()); err != nil { if err := createValidation(ctx, obj.DeepCopyObject()); err != nil {
return nil, nil, err return nil, nil, err
} }
} }
@ -546,7 +546,7 @@ func (e *Store) Update(ctx context.Context, name string, objInfo rest.UpdatedObj
// at this point we have a fully formed object. It is time to call the validators that the apiserver // at this point we have a fully formed object. It is time to call the validators that the apiserver
// handling chain wants to enforce. // handling chain wants to enforce.
if updateValidation != nil { if updateValidation != nil {
if err := updateValidation(obj.DeepCopyObject(), existing.DeepCopyObject()); err != nil { if err := updateValidation(ctx, obj.DeepCopyObject(), existing.DeepCopyObject()); err != nil {
return nil, nil, err return nil, nil, err
} }
} }
@ -812,7 +812,7 @@ func (e *Store) updateForGracefulDeletionAndFinalizers(ctx context.Context, name
false, /* ignoreNotFound */ false, /* ignoreNotFound */
&preconditions, &preconditions,
storage.SimpleUpdate(func(existing runtime.Object) (runtime.Object, error) { storage.SimpleUpdate(func(existing runtime.Object) (runtime.Object, error) {
if err := deleteValidation(existing); err != nil { if err := deleteValidation(ctx, existing); err != nil {
return nil, err return nil, err
} }
graceful, pendingGraceful, err := rest.BeforeDelete(e.DeleteStrategy, ctx, existing, options) graceful, pendingGraceful, err := rest.BeforeDelete(e.DeleteStrategy, ctx, existing, options)

View File

@ -1713,11 +1713,11 @@ func TestQualifiedResource(t *testing.T) {
} }
} }
func denyCreateValidation(obj runtime.Object) error { func denyCreateValidation(ctx context.Context, obj runtime.Object) error {
return fmt.Errorf("admission denied") return fmt.Errorf("admission denied")
} }
func denyUpdateValidation(obj, old runtime.Object) error { func denyUpdateValidation(ctx context.Context, obj, old runtime.Object) error {
return fmt.Errorf("admission denied") return fmt.Errorf("admission denied")
} }
@ -1933,7 +1933,7 @@ func TestRetryDeleteValidation(t *testing.T) {
updated := make(chan struct{}) updated := make(chan struct{})
var readyOnce, updatedOnce sync.Once var readyOnce, updatedOnce sync.Once
var called int var called int
deleteValidation := func(runtime.Object) error { deleteValidation := func(ctx context.Context, obj runtime.Object) error {
readyOnce.Do(func() { readyOnce.Do(func() {
close(ready) close(ready)
}) })

Some files were not shown because too many files have changed in this diff Show More