timeout_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. Copyright 2019 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 admissionwebhook
  14. import (
  15. "context"
  16. "crypto/tls"
  17. "crypto/x509"
  18. "encoding/json"
  19. "fmt"
  20. "io/ioutil"
  21. "net/http"
  22. "net/http/httptest"
  23. "sort"
  24. "strings"
  25. "sync"
  26. "testing"
  27. "time"
  28. "k8s.io/api/admission/v1beta1"
  29. admissionv1beta1 "k8s.io/api/admissionregistration/v1beta1"
  30. corev1 "k8s.io/api/core/v1"
  31. v1 "k8s.io/api/core/v1"
  32. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  33. "k8s.io/apimachinery/pkg/types"
  34. "k8s.io/apimachinery/pkg/util/wait"
  35. clientset "k8s.io/client-go/kubernetes"
  36. "k8s.io/client-go/rest"
  37. kubeapiservertesting "k8s.io/kubernetes/cmd/kube-apiserver/app/testing"
  38. "k8s.io/kubernetes/test/integration/framework"
  39. )
  40. const (
  41. testTimeoutClientUsername = "webhook-timeout-integration-client"
  42. )
  43. // TestWebhookTimeoutWithWatchCache ensures that the admission webhook timeout policy is applied correctly with the watch cache enabled.
  44. func TestWebhookTimeoutWithWatchCache(t *testing.T) {
  45. testWebhookTimeout(t, true)
  46. }
  47. // TestWebhookTimeoutWithoutWatchCache ensures that the admission webhook timeout policy is applied correctly without the watch cache enabled.
  48. func TestWebhookTimeoutWithoutWatchCache(t *testing.T) {
  49. testWebhookTimeout(t, false)
  50. }
  51. type invocation struct {
  52. path string
  53. timeoutSeconds int
  54. }
  55. // testWebhookTimeout ensures that the admission webhook timeout policy is applied correctly.
  56. func testWebhookTimeout(t *testing.T, watchCache bool) {
  57. type testWebhook struct {
  58. path string
  59. timeoutSeconds int32
  60. policy admissionv1beta1.FailurePolicyType
  61. objectSelector *metav1.LabelSelector
  62. }
  63. testCases := []struct {
  64. name string
  65. timeoutSeconds int32
  66. mutatingWebhooks []testWebhook
  67. validatingWebhooks []testWebhook
  68. expectInvocations []invocation
  69. expectError bool
  70. errorContains string
  71. }{
  72. {
  73. name: "minimum of request timeout or webhook timeout propagated",
  74. timeoutSeconds: 10,
  75. mutatingWebhooks: []testWebhook{
  76. {path: "/mutating/1/0s", policy: admissionv1beta1.Fail, timeoutSeconds: 20},
  77. {path: "/mutating/2/0s", policy: admissionv1beta1.Fail, timeoutSeconds: 5},
  78. },
  79. validatingWebhooks: []testWebhook{
  80. {path: "/validating/3/0s", policy: admissionv1beta1.Fail, timeoutSeconds: 20},
  81. {path: "/validating/4/0s", policy: admissionv1beta1.Fail, timeoutSeconds: 5},
  82. },
  83. expectInvocations: []invocation{
  84. {path: "/mutating/1/0s", timeoutSeconds: 10}, // from request
  85. {path: "/mutating/2/0s", timeoutSeconds: 5}, // from webhook config
  86. {path: "/validating/3/0s", timeoutSeconds: 10}, // from request
  87. {path: "/validating/4/0s", timeoutSeconds: 5}, // from webhook config
  88. },
  89. },
  90. {
  91. name: "webhooks consume client timeout available, not webhook timeout",
  92. timeoutSeconds: 10,
  93. mutatingWebhooks: []testWebhook{
  94. {path: "/mutating/1/1s", policy: admissionv1beta1.Fail, timeoutSeconds: 20},
  95. {path: "/mutating/2/1s", policy: admissionv1beta1.Fail, timeoutSeconds: 5},
  96. {path: "/mutating/3/1s", policy: admissionv1beta1.Fail, timeoutSeconds: 20},
  97. },
  98. validatingWebhooks: []testWebhook{
  99. {path: "/validating/4/1s", policy: admissionv1beta1.Fail, timeoutSeconds: 5},
  100. {path: "/validating/5/1s", policy: admissionv1beta1.Fail, timeoutSeconds: 10},
  101. {path: "/validating/6/1s", policy: admissionv1beta1.Fail, timeoutSeconds: 20},
  102. },
  103. expectInvocations: []invocation{
  104. {path: "/mutating/1/1s", timeoutSeconds: 10}, // from request
  105. {path: "/mutating/2/1s", timeoutSeconds: 5}, // from webhook config (less than request - 1s consumed)
  106. {path: "/mutating/3/1s", timeoutSeconds: 8}, // from request - 2s consumed
  107. {path: "/validating/4/1s", timeoutSeconds: 5}, // from webhook config (less than request - 3s consumed by mutating)
  108. {path: "/validating/5/1s", timeoutSeconds: 7}, // from request - 3s consumed by mutating
  109. {path: "/validating/6/1s", timeoutSeconds: 7}, // from request - 3s consumed by mutating
  110. },
  111. },
  112. {
  113. name: "timed out client requests skip later mutating webhooks (regardless of failure policy) and fail",
  114. timeoutSeconds: 3,
  115. mutatingWebhooks: []testWebhook{
  116. {path: "/mutating/1/5s", policy: admissionv1beta1.Ignore, timeoutSeconds: 4},
  117. {path: "/mutating/2/1s", policy: admissionv1beta1.Ignore, timeoutSeconds: 5},
  118. {path: "/mutating/3/1s", policy: admissionv1beta1.Ignore, timeoutSeconds: 5},
  119. },
  120. expectInvocations: []invocation{
  121. {path: "/mutating/1/5s", timeoutSeconds: 3}, // from request
  122. },
  123. expectError: true,
  124. errorContains: "request did not complete within requested timeout",
  125. },
  126. }
  127. roots := x509.NewCertPool()
  128. if !roots.AppendCertsFromPEM(localhostCert) {
  129. t.Fatal("Failed to append Cert from PEM")
  130. }
  131. cert, err := tls.X509KeyPair(localhostCert, localhostKey)
  132. if err != nil {
  133. t.Fatalf("Failed to build cert with error: %+v", err)
  134. }
  135. recorder := &timeoutRecorder{invocations: []invocation{}}
  136. webhookServer := httptest.NewUnstartedServer(newTimeoutWebhookHandler(recorder))
  137. webhookServer.TLS = &tls.Config{
  138. RootCAs: roots,
  139. Certificates: []tls.Certificate{cert},
  140. }
  141. webhookServer.StartTLS()
  142. defer webhookServer.Close()
  143. s := kubeapiservertesting.StartTestServerOrDie(t, kubeapiservertesting.NewDefaultTestServerOptions(), []string{
  144. "--disable-admission-plugins=ServiceAccount",
  145. fmt.Sprintf("--watch-cache=%v", watchCache),
  146. }, framework.SharedEtcd())
  147. defer s.TearDownFn()
  148. // Configure a client with a distinct user name so that it is easy to distinguish requests
  149. // made by the client from requests made by controllers. We use this to filter out requests
  150. // before recording them to ensure we don't accidentally mistake requests from controllers
  151. // as requests made by the client.
  152. clientConfig := rest.CopyConfig(s.ClientConfig)
  153. clientConfig.Timeout = 0 // no timeout, we want to set this manually
  154. clientConfig.Impersonate.UserName = testTimeoutClientUsername
  155. clientConfig.Impersonate.Groups = []string{"system:masters", "system:authenticated"}
  156. client, err := clientset.NewForConfig(clientConfig)
  157. if err != nil {
  158. t.Fatalf("unexpected error: %v", err)
  159. }
  160. _, err = client.CoreV1().Pods("default").Create(context.TODO(), timeoutMarkerFixture, metav1.CreateOptions{})
  161. if err != nil {
  162. t.Fatal(err)
  163. }
  164. for i, tt := range testCases {
  165. t.Run(tt.name, func(t *testing.T) {
  166. upCh := recorder.Reset()
  167. ns := fmt.Sprintf("reinvoke-%d", i)
  168. _, err = client.CoreV1().Namespaces().Create(context.TODO(), &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ns}}, metav1.CreateOptions{})
  169. if err != nil {
  170. t.Fatal(err)
  171. }
  172. mutatingWebhooks := []admissionv1beta1.MutatingWebhook{}
  173. for j, webhook := range tt.mutatingWebhooks {
  174. name := fmt.Sprintf("admission.integration.test.%d.%s", j, strings.Replace(strings.TrimPrefix(webhook.path, "/"), "/", "-", -1))
  175. endpoint := webhookServer.URL + webhook.path
  176. mutatingWebhooks = append(mutatingWebhooks, admissionv1beta1.MutatingWebhook{
  177. Name: name,
  178. ClientConfig: admissionv1beta1.WebhookClientConfig{
  179. URL: &endpoint,
  180. CABundle: localhostCert,
  181. },
  182. Rules: []admissionv1beta1.RuleWithOperations{{
  183. Operations: []admissionv1beta1.OperationType{admissionv1beta1.OperationAll},
  184. Rule: admissionv1beta1.Rule{APIGroups: []string{""}, APIVersions: []string{"v1"}, Resources: []string{"pods"}},
  185. }},
  186. ObjectSelector: webhook.objectSelector,
  187. FailurePolicy: &tt.mutatingWebhooks[j].policy,
  188. TimeoutSeconds: &tt.mutatingWebhooks[j].timeoutSeconds,
  189. AdmissionReviewVersions: []string{"v1beta1"},
  190. })
  191. }
  192. mutatingCfg, err := client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Create(context.TODO(), &admissionv1beta1.MutatingWebhookConfiguration{
  193. ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("admission.integration.test-%d", i)},
  194. Webhooks: mutatingWebhooks,
  195. }, metav1.CreateOptions{})
  196. if err != nil {
  197. t.Fatal(err)
  198. }
  199. defer func() {
  200. err := client.AdmissionregistrationV1beta1().MutatingWebhookConfigurations().Delete(context.TODO(), mutatingCfg.GetName(), &metav1.DeleteOptions{})
  201. if err != nil {
  202. t.Fatal(err)
  203. }
  204. }()
  205. validatingWebhooks := []admissionv1beta1.ValidatingWebhook{}
  206. for j, webhook := range tt.validatingWebhooks {
  207. name := fmt.Sprintf("admission.integration.test.%d.%s", j, strings.Replace(strings.TrimPrefix(webhook.path, "/"), "/", "-", -1))
  208. endpoint := webhookServer.URL + webhook.path
  209. validatingWebhooks = append(validatingWebhooks, admissionv1beta1.ValidatingWebhook{
  210. Name: name,
  211. ClientConfig: admissionv1beta1.WebhookClientConfig{
  212. URL: &endpoint,
  213. CABundle: localhostCert,
  214. },
  215. Rules: []admissionv1beta1.RuleWithOperations{{
  216. Operations: []admissionv1beta1.OperationType{admissionv1beta1.OperationAll},
  217. Rule: admissionv1beta1.Rule{APIGroups: []string{""}, APIVersions: []string{"v1"}, Resources: []string{"pods"}},
  218. }},
  219. ObjectSelector: webhook.objectSelector,
  220. FailurePolicy: &tt.validatingWebhooks[j].policy,
  221. TimeoutSeconds: &tt.validatingWebhooks[j].timeoutSeconds,
  222. AdmissionReviewVersions: []string{"v1beta1"},
  223. })
  224. }
  225. validatingCfg, err := client.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().Create(context.TODO(), &admissionv1beta1.ValidatingWebhookConfiguration{
  226. ObjectMeta: metav1.ObjectMeta{Name: fmt.Sprintf("admission.integration.test-%d", i)},
  227. Webhooks: validatingWebhooks,
  228. }, metav1.CreateOptions{})
  229. if err != nil {
  230. t.Fatal(err)
  231. }
  232. defer func() {
  233. err := client.AdmissionregistrationV1beta1().ValidatingWebhookConfigurations().Delete(context.TODO(), validatingCfg.GetName(), &metav1.DeleteOptions{})
  234. if err != nil {
  235. t.Fatal(err)
  236. }
  237. }()
  238. // wait until new webhook is called the first time
  239. if err := wait.PollImmediate(time.Millisecond*5, wait.ForeverTestTimeout, func() (bool, error) {
  240. _, err = client.CoreV1().Pods("default").Patch(context.TODO(), timeoutMarkerFixture.Name, types.JSONPatchType, []byte("[]"), metav1.PatchOptions{})
  241. select {
  242. case <-upCh:
  243. return true, nil
  244. default:
  245. t.Logf("Waiting for webhook to become effective, getting marker object: %v", err)
  246. return false, nil
  247. }
  248. }); err != nil {
  249. t.Fatal(err)
  250. }
  251. pod := &corev1.Pod{
  252. TypeMeta: metav1.TypeMeta{APIVersion: "v1", Kind: "Pod"},
  253. ObjectMeta: metav1.ObjectMeta{
  254. Namespace: ns,
  255. Name: "labeled",
  256. Labels: map[string]string{"x": "true"},
  257. },
  258. Spec: corev1.PodSpec{
  259. Containers: []v1.Container{{
  260. Name: "fake-name",
  261. Image: "fakeimage",
  262. }},
  263. },
  264. }
  265. body, err := json.Marshal(pod)
  266. if err != nil {
  267. t.Fatal(err)
  268. }
  269. // set the timeout parameter manually so we don't actually cut off the request client-side, and wait for the server response
  270. err = client.CoreV1().RESTClient().Post().Resource("pods").Namespace(ns).Body(body).Param("timeout", fmt.Sprintf("%ds", tt.timeoutSeconds)).Do(context.TODO()).Error()
  271. // _, err = testClient.CoreV1().Pods(ns).Create(pod)
  272. if tt.expectError {
  273. if err == nil {
  274. t.Fatalf("expected error but got none")
  275. }
  276. if tt.errorContains != "" {
  277. if !strings.Contains(err.Error(), tt.errorContains) {
  278. t.Errorf("expected an error saying %q, but got: %v", tt.errorContains, err)
  279. }
  280. }
  281. return
  282. }
  283. if err != nil {
  284. t.Fatal(err)
  285. }
  286. if tt.expectInvocations != nil {
  287. for i, invocation := range tt.expectInvocations {
  288. if len(recorder.invocations) <= i {
  289. t.Errorf("expected invocation of %s, got none", invocation.path)
  290. continue
  291. }
  292. if recorder.invocations[i].path != invocation.path {
  293. t.Errorf("expected invocation of %s, got %s", invocation.path, recorder.invocations[i].path)
  294. continue
  295. }
  296. if recorder.invocations[i].timeoutSeconds != invocation.timeoutSeconds {
  297. t.Errorf("expected invocation of %s with timeout %d, got %d", invocation.path, invocation.timeoutSeconds, recorder.invocations[i].timeoutSeconds)
  298. continue
  299. }
  300. }
  301. if len(recorder.invocations) > len(tt.expectInvocations) {
  302. for _, invocation := range recorder.invocations[len(tt.expectInvocations):] {
  303. t.Errorf("unexpected invocation of %s", invocation.path)
  304. }
  305. }
  306. }
  307. })
  308. }
  309. }
  310. type timeoutRecorder struct {
  311. mu sync.Mutex
  312. upCh chan struct{}
  313. upOnce sync.Once
  314. invocations []invocation
  315. }
  316. // Reset zeros out all counts and returns a channel that is closed when the first admission of the
  317. // marker object is received.
  318. func (i *timeoutRecorder) Reset() chan struct{} {
  319. i.mu.Lock()
  320. defer i.mu.Unlock()
  321. i.invocations = []invocation{}
  322. i.upCh = make(chan struct{})
  323. i.upOnce = sync.Once{}
  324. return i.upCh
  325. }
  326. func (i *timeoutRecorder) MarkerReceived() {
  327. i.mu.Lock()
  328. defer i.mu.Unlock()
  329. i.upOnce.Do(func() {
  330. close(i.upCh)
  331. })
  332. }
  333. func (i *timeoutRecorder) RecordInvocation(call invocation) {
  334. i.mu.Lock()
  335. defer i.mu.Unlock()
  336. i.invocations = append(i.invocations, call)
  337. sort.SliceStable(i.invocations, func(a, b int) bool {
  338. aValidating := strings.Contains(i.invocations[a].path, "validating")
  339. bValidating := strings.Contains(i.invocations[b].path, "validating")
  340. switch {
  341. case aValidating && bValidating:
  342. // sort validating by path
  343. return strings.Compare(i.invocations[a].path, i.invocations[b].path) < 0
  344. case !aValidating && !bValidating:
  345. // keep mutating in original order
  346. return a < b
  347. case aValidating && !bValidating:
  348. // put validating last
  349. return false
  350. default:
  351. return true
  352. }
  353. })
  354. }
  355. func newTimeoutWebhookHandler(recorder *timeoutRecorder) http.Handler {
  356. allow := func(w http.ResponseWriter) {
  357. w.Header().Set("Content-Type", "application/json")
  358. json.NewEncoder(w).Encode(&v1beta1.AdmissionReview{
  359. Response: &v1beta1.AdmissionResponse{
  360. Allowed: true,
  361. },
  362. })
  363. }
  364. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  365. defer r.Body.Close()
  366. data, err := ioutil.ReadAll(r.Body)
  367. if err != nil {
  368. http.Error(w, err.Error(), 400)
  369. }
  370. review := v1beta1.AdmissionReview{}
  371. if err := json.Unmarshal(data, &review); err != nil {
  372. http.Error(w, err.Error(), 400)
  373. }
  374. if review.Request.UserInfo.Username != testTimeoutClientUsername {
  375. // skip requests not originating from this integration test's client
  376. allow(w)
  377. return
  378. }
  379. if len(review.Request.Object.Raw) == 0 {
  380. http.Error(w, err.Error(), 400)
  381. }
  382. pod := &corev1.Pod{}
  383. if err := json.Unmarshal(review.Request.Object.Raw, pod); err != nil {
  384. http.Error(w, err.Error(), 400)
  385. }
  386. // When resetting between tests, a marker object is patched until this webhook
  387. // observes it, at which point it is considered ready.
  388. if pod.Namespace == timeoutMarkerFixture.Namespace && pod.Name == timeoutMarkerFixture.Name {
  389. recorder.MarkerReceived()
  390. allow(w)
  391. return
  392. }
  393. timeout, err := time.ParseDuration(r.URL.Query().Get("timeout"))
  394. if err != nil {
  395. http.Error(w, err.Error(), http.StatusBadRequest)
  396. }
  397. invocation := invocation{path: r.URL.Path, timeoutSeconds: int(timeout.Round(time.Second) / time.Second)}
  398. recorder.RecordInvocation(invocation)
  399. switch {
  400. case strings.HasSuffix(r.URL.Path, "/0s"):
  401. allow(w)
  402. case strings.HasSuffix(r.URL.Path, "/1s"):
  403. time.Sleep(time.Second)
  404. allow(w)
  405. case strings.HasSuffix(r.URL.Path, "/5s"):
  406. time.Sleep(5 * time.Second)
  407. allow(w)
  408. default:
  409. http.NotFound(w, r)
  410. }
  411. })
  412. }
  413. var timeoutMarkerFixture = &corev1.Pod{
  414. ObjectMeta: metav1.ObjectMeta{
  415. Namespace: "default",
  416. Name: "marker",
  417. },
  418. Spec: corev1.PodSpec{
  419. Containers: []v1.Container{{
  420. Name: "fake-name",
  421. Image: "fakeimage",
  422. }},
  423. },
  424. }