webhook_test.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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. "sync/atomic"
  16. "testing"
  17. "time"
  18. admissionv1beta1 "k8s.io/api/admissionregistration/v1beta1"
  19. v1 "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/util/wait"
  22. auditinternal "k8s.io/apiserver/pkg/apis/audit"
  23. "k8s.io/apiserver/pkg/authorization/authorizer"
  24. "k8s.io/kubernetes/cmd/kube-apiserver/app/options"
  25. "k8s.io/kubernetes/pkg/master"
  26. "k8s.io/kubernetes/pkg/master/reconcilers"
  27. "k8s.io/kubernetes/test/integration/framework"
  28. )
  29. func TestWebhookLoopback(t *testing.T) {
  30. stopCh := make(chan struct{})
  31. defer close(stopCh)
  32. webhookPath := "/webhook-test"
  33. called := int32(0)
  34. client, _ := framework.StartTestServer(t, stopCh, framework.TestServerSetup{
  35. ModifyServerRunOptions: func(opts *options.ServerRunOptions) {
  36. },
  37. ModifyServerConfig: func(config *master.Config) {
  38. // Avoid resolveable kubernetes service
  39. config.ExtraConfig.EndpointReconcilerType = reconcilers.NoneEndpointReconcilerType
  40. // Hook into audit to watch requests
  41. config.GenericConfig.AuditBackend = auditSinkFunc(func(events ...*auditinternal.Event) {})
  42. config.GenericConfig.AuditPolicyChecker = auditChecker(func(attrs authorizer.Attributes) (auditinternal.Level, []auditinternal.Stage) {
  43. if attrs.GetPath() == webhookPath {
  44. if attrs.GetUser().GetName() != "system:apiserver" {
  45. t.Errorf("expected user %q, got %q", "system:apiserver", attrs.GetUser().GetName())
  46. }
  47. atomic.AddInt32(&called, 1)
  48. }
  49. return auditinternal.LevelNone, nil
  50. })
  51. },
  52. })
  53. fail := admissionv1beta1.Fail
  54. _, err := client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Create(&admissionv1beta1.MutatingWebhookConfiguration{
  55. ObjectMeta: metav1.ObjectMeta{Name: "webhooktest.example.com"},
  56. Webhooks: []admissionv1beta1.MutatingWebhook{{
  57. Name: "webhooktest.example.com",
  58. ClientConfig: admissionv1beta1.WebhookClientConfig{
  59. Service: &admissionv1beta1.ServiceReference{Namespace: "default", Name: "kubernetes", Path: &webhookPath},
  60. },
  61. Rules: []admissionv1beta1.RuleWithOperations{{
  62. Operations: []admissionv1beta1.OperationType{admissionv1beta1.OperationAll},
  63. Rule: admissionv1beta1.Rule{APIGroups: []string{""}, APIVersions: []string{"v1"}, Resources: []string{"configmaps"}},
  64. }},
  65. FailurePolicy: &fail,
  66. }},
  67. })
  68. if err != nil {
  69. t.Fatal(err)
  70. }
  71. err = wait.PollImmediate(100*time.Millisecond, 30*time.Second, func() (done bool, err error) {
  72. _, err = client.CoreV1().ConfigMaps("default").Create(&v1.ConfigMap{
  73. ObjectMeta: metav1.ObjectMeta{Name: "webhook-test"},
  74. Data: map[string]string{"invalid key": "value"},
  75. })
  76. if err == nil {
  77. t.Fatal("Unexpected success")
  78. }
  79. if called > 0 {
  80. return true, nil
  81. }
  82. t.Logf("%v", err)
  83. t.Logf("webhook not called yet, continuing...")
  84. return false, nil
  85. })
  86. if err != nil {
  87. t.Fatal(err)
  88. }
  89. }
  90. type auditChecker func(authorizer.Attributes) (auditinternal.Level, []auditinternal.Stage)
  91. func (f auditChecker) LevelAndStages(attrs authorizer.Attributes) (auditinternal.Level, []auditinternal.Stage) {
  92. return f(attrs)
  93. }
  94. type auditSinkFunc func(events ...*auditinternal.Event)
  95. func (f auditSinkFunc) ProcessEvents(events ...*auditinternal.Event) bool {
  96. f(events...)
  97. return true
  98. }
  99. func (auditSinkFunc) Run(stopCh <-chan struct{}) error {
  100. return nil
  101. }
  102. func (auditSinkFunc) Shutdown() {
  103. }
  104. func (auditSinkFunc) String() string {
  105. return ""
  106. }