webhook_test.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package apiserver
  14. import (
  15. "context"
  16. "sync/atomic"
  17. "testing"
  18. "time"
  19. admissionv1beta1 "k8s.io/api/admissionregistration/v1beta1"
  20. v1 "k8s.io/api/core/v1"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/util/wait"
  23. auditinternal "k8s.io/apiserver/pkg/apis/audit"
  24. "k8s.io/apiserver/pkg/authorization/authorizer"
  25. "k8s.io/kubernetes/cmd/kube-apiserver/app/options"
  26. "k8s.io/kubernetes/pkg/master"
  27. "k8s.io/kubernetes/pkg/master/reconcilers"
  28. "k8s.io/kubernetes/test/integration/framework"
  29. )
  30. func TestWebhookLoopback(t *testing.T) {
  31. stopCh := make(chan struct{})
  32. defer close(stopCh)
  33. webhookPath := "/webhook-test"
  34. called := int32(0)
  35. client, _ := framework.StartTestServer(t, stopCh, framework.TestServerSetup{
  36. ModifyServerRunOptions: func(opts *options.ServerRunOptions) {
  37. },
  38. ModifyServerConfig: func(config *master.Config) {
  39. // Avoid resolveable kubernetes service
  40. config.ExtraConfig.EndpointReconcilerType = reconcilers.NoneEndpointReconcilerType
  41. // Hook into audit to watch requests
  42. config.GenericConfig.AuditBackend = auditSinkFunc(func(events ...*auditinternal.Event) {})
  43. config.GenericConfig.AuditPolicyChecker = auditChecker(func(attrs authorizer.Attributes) (auditinternal.Level, []auditinternal.Stage) {
  44. if attrs.GetPath() == webhookPath {
  45. if attrs.GetUser().GetName() != "system:apiserver" {
  46. t.Errorf("expected user %q, got %q", "system:apiserver", attrs.GetUser().GetName())
  47. }
  48. atomic.AddInt32(&called, 1)
  49. }
  50. return auditinternal.LevelNone, nil
  51. })
  52. },
  53. })
  54. fail := admissionv1beta1.Fail
  55. _, err := client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Create(context.TODO(), &admissionv1beta1.MutatingWebhookConfiguration{
  56. ObjectMeta: metav1.ObjectMeta{Name: "webhooktest.example.com"},
  57. Webhooks: []admissionv1beta1.MutatingWebhook{{
  58. Name: "webhooktest.example.com",
  59. ClientConfig: admissionv1beta1.WebhookClientConfig{
  60. Service: &admissionv1beta1.ServiceReference{Namespace: "default", Name: "kubernetes", Path: &webhookPath},
  61. },
  62. Rules: []admissionv1beta1.RuleWithOperations{{
  63. Operations: []admissionv1beta1.OperationType{admissionv1beta1.OperationAll},
  64. Rule: admissionv1beta1.Rule{APIGroups: []string{""}, APIVersions: []string{"v1"}, Resources: []string{"configmaps"}},
  65. }},
  66. FailurePolicy: &fail,
  67. }},
  68. }, metav1.CreateOptions{})
  69. if err != nil {
  70. t.Fatal(err)
  71. }
  72. err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (done bool, err error) {
  73. _, err = client.CoreV1().ConfigMaps("default").Create(context.TODO(), &v1.ConfigMap{
  74. ObjectMeta: metav1.ObjectMeta{Name: "webhook-test"},
  75. Data: map[string]string{"invalid key": "value"},
  76. }, metav1.CreateOptions{})
  77. if err == nil {
  78. t.Fatal("Unexpected success")
  79. }
  80. if called > 0 {
  81. return true, nil
  82. }
  83. t.Logf("%v", err)
  84. t.Logf("webhook not called yet, continuing...")
  85. return false, nil
  86. })
  87. if err != nil {
  88. t.Fatal(err)
  89. }
  90. }
  91. type auditChecker func(authorizer.Attributes) (auditinternal.Level, []auditinternal.Stage)
  92. func (f auditChecker) LevelAndStages(attrs authorizer.Attributes) (auditinternal.Level, []auditinternal.Stage) {
  93. return f(attrs)
  94. }
  95. type auditSinkFunc func(events ...*auditinternal.Event)
  96. func (f auditSinkFunc) ProcessEvents(events ...*auditinternal.Event) bool {
  97. f(events...)
  98. return true
  99. }
  100. func (auditSinkFunc) Run(stopCh <-chan struct{}) error {
  101. return nil
  102. }
  103. func (auditSinkFunc) Shutdown() {
  104. }
  105. func (auditSinkFunc) String() string {
  106. return ""
  107. }