|
| 1 | +/* |
| 2 | +Copyright 2023 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package filters |
| 18 | + |
| 19 | +import ( |
| 20 | + "net/http" |
| 21 | + "net/http/httptest" |
| 22 | + "testing" |
| 23 | + "time" |
| 24 | + |
| 25 | + "github.com/google/go-cmp/cmp" |
| 26 | + auditinternal "k8s.io/apiserver/pkg/apis/audit" |
| 27 | + "k8s.io/apiserver/pkg/audit" |
| 28 | + authenticationuser "k8s.io/apiserver/pkg/authentication/user" |
| 29 | + apirequest "k8s.io/apiserver/pkg/endpoints/request" |
| 30 | + utilsclock "k8s.io/utils/clock" |
| 31 | + clocktesting "k8s.io/utils/clock/testing" |
| 32 | +) |
| 33 | + |
| 34 | +func TestWithShutdownResponseHeader(t *testing.T) { |
| 35 | + var ( |
| 36 | + signaledAt = time.Now() |
| 37 | + elapsedAt = signaledAt.Add(20 * time.Second) |
| 38 | + ) |
| 39 | + |
| 40 | + tests := []struct { |
| 41 | + name string |
| 42 | + optIn bool |
| 43 | + shutdownInitiated func() lifecycleEvent |
| 44 | + delayDuration time.Duration |
| 45 | + clock func() utilsclock.PassiveClock |
| 46 | + handlerInvoked int |
| 47 | + statusCodeExpected int |
| 48 | + responseHeader string |
| 49 | + }{ |
| 50 | + { |
| 51 | + name: "client did not opt in", |
| 52 | + shutdownInitiated: func() lifecycleEvent { |
| 53 | + return nil |
| 54 | + }, |
| 55 | + handlerInvoked: 1, |
| 56 | + statusCodeExpected: http.StatusOK, |
| 57 | + }, |
| 58 | + { |
| 59 | + name: "client opted in, shutdown not initiated", |
| 60 | + optIn: true, |
| 61 | + shutdownInitiated: func() lifecycleEvent { |
| 62 | + return fakeLifecycleSignal{ch: make(chan struct{})} |
| 63 | + }, |
| 64 | + delayDuration: 10 * time.Second, |
| 65 | + handlerInvoked: 1, |
| 66 | + statusCodeExpected: http.StatusOK, |
| 67 | + responseHeader: "shutdown=false shutdown-delay-duration=10s elapsed=0s host=foo", |
| 68 | + }, |
| 69 | + { |
| 70 | + name: "client opted in, shutdown initiated, signaled at is nil", |
| 71 | + optIn: true, |
| 72 | + delayDuration: 10 * time.Second, |
| 73 | + shutdownInitiated: func() lifecycleEvent { |
| 74 | + return fakeLifecycleSignal{ch: newClosedChannel(), at: nil} |
| 75 | + }, |
| 76 | + handlerInvoked: 1, |
| 77 | + statusCodeExpected: http.StatusOK, |
| 78 | + responseHeader: "shutdown=true shutdown-delay-duration=10s elapsed=0s host=foo", |
| 79 | + }, |
| 80 | + { |
| 81 | + name: "client opted in, shutdown initiated, signaled at is nil", |
| 82 | + optIn: true, |
| 83 | + delayDuration: 10 * time.Second, |
| 84 | + shutdownInitiated: func() lifecycleEvent { |
| 85 | + return fakeLifecycleSignal{ch: newClosedChannel(), at: nil} |
| 86 | + }, |
| 87 | + handlerInvoked: 1, |
| 88 | + statusCodeExpected: http.StatusOK, |
| 89 | + responseHeader: "shutdown=true shutdown-delay-duration=10s elapsed=0s host=foo", |
| 90 | + }, |
| 91 | + { |
| 92 | + name: "client opted in, shutdown delay duration is zero", |
| 93 | + optIn: true, |
| 94 | + delayDuration: 0, |
| 95 | + shutdownInitiated: func() lifecycleEvent { |
| 96 | + return fakeLifecycleSignal{ch: newClosedChannel(), at: &signaledAt} |
| 97 | + }, |
| 98 | + clock: func() utilsclock.PassiveClock { |
| 99 | + return clocktesting.NewFakeClock(elapsedAt) |
| 100 | + }, |
| 101 | + handlerInvoked: 1, |
| 102 | + statusCodeExpected: http.StatusOK, |
| 103 | + responseHeader: "shutdown=true shutdown-delay-duration=0s elapsed=20s host=foo", |
| 104 | + }, |
| 105 | + { |
| 106 | + name: "client opted in, shutdown initiated, signaled at is valied", |
| 107 | + optIn: true, |
| 108 | + delayDuration: 10 * time.Second, |
| 109 | + shutdownInitiated: func() lifecycleEvent { |
| 110 | + return fakeLifecycleSignal{ch: newClosedChannel(), at: &signaledAt} |
| 111 | + }, |
| 112 | + clock: func() utilsclock.PassiveClock { |
| 113 | + return clocktesting.NewFakeClock(elapsedAt) |
| 114 | + }, |
| 115 | + handlerInvoked: 1, |
| 116 | + statusCodeExpected: http.StatusOK, |
| 117 | + responseHeader: "shutdown=true shutdown-delay-duration=10s elapsed=20s host=foo", |
| 118 | + }, |
| 119 | + } |
| 120 | + |
| 121 | + for _, test := range tests { |
| 122 | + t.Run(test.name, func(t *testing.T) { |
| 123 | + var handlerInvoked int |
| 124 | + handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 125 | + handlerInvoked++ |
| 126 | + w.WriteHeader(http.StatusOK) |
| 127 | + }) |
| 128 | + |
| 129 | + event := test.shutdownInitiated() |
| 130 | + var clock utilsclock.PassiveClock = utilsclock.RealClock{} |
| 131 | + if test.clock != nil { |
| 132 | + clock = test.clock() |
| 133 | + } |
| 134 | + target := withShutdownResponseHeader(handler, event, test.delayDuration, "foo", clock) |
| 135 | + |
| 136 | + req, err := http.NewRequest(http.MethodGet, "/api/v1/namespaces", nil) |
| 137 | + if err != nil { |
| 138 | + t.Fatalf("failed to create new http request - %v", err) |
| 139 | + } |
| 140 | + if test.optIn { |
| 141 | + req.Header.Set("X-Openshift-If-Disruption", "true") |
| 142 | + } |
| 143 | + |
| 144 | + w := httptest.NewRecorder() |
| 145 | + w.Code = 0 |
| 146 | + target.ServeHTTP(w, req) |
| 147 | + |
| 148 | + if test.handlerInvoked != handlerInvoked { |
| 149 | + t.Errorf("expected the handler to be invoked: %d timed, but got: %d", test.handlerInvoked, handlerInvoked) |
| 150 | + } |
| 151 | + if test.statusCodeExpected != w.Result().StatusCode { |
| 152 | + t.Errorf("expected status code: %d, but got: %d", test.statusCodeExpected, w.Result().StatusCode) |
| 153 | + } |
| 154 | + |
| 155 | + key := "X-OpenShift-Disruption" |
| 156 | + switch { |
| 157 | + case len(test.responseHeader) == 0: |
| 158 | + if valueGot := w.Header().Get(key); len(valueGot) > 0 { |
| 159 | + t.Errorf("did not expect header to be added to the response, but got: %s", valueGot) |
| 160 | + } |
| 161 | + default: |
| 162 | + if valueGot := w.Header().Get(key); len(valueGot) == 0 || test.responseHeader != valueGot { |
| 163 | + t.Logf("got: %s", valueGot) |
| 164 | + t.Errorf("expected response header to match, diff: %s", cmp.Diff(test.responseHeader, valueGot)) |
| 165 | + } |
| 166 | + } |
| 167 | + }) |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +func TestWithStartupEarlyAnnotation(t *testing.T) { |
| 172 | + tests := []struct { |
| 173 | + name string |
| 174 | + readySignalFn func() lifecycleEvent |
| 175 | + user authenticationuser.Info |
| 176 | + remoteAddr string |
| 177 | + handlerInvoked int |
| 178 | + statusCodeExpected int |
| 179 | + annotationExpected string |
| 180 | + }{ |
| 181 | + { |
| 182 | + name: "server is ready", |
| 183 | + readySignalFn: func() lifecycleEvent { |
| 184 | + return fakeLifecycleSignal{ch: newClosedChannel()} |
| 185 | + }, |
| 186 | + handlerInvoked: 1, |
| 187 | + statusCodeExpected: http.StatusOK, |
| 188 | + }, |
| 189 | + { |
| 190 | + name: "server not ready, no user in request context", |
| 191 | + readySignalFn: func() lifecycleEvent { |
| 192 | + return fakeLifecycleSignal{ch: make(chan struct{})} |
| 193 | + }, |
| 194 | + handlerInvoked: 1, |
| 195 | + statusCodeExpected: http.StatusOK, |
| 196 | + annotationExpected: "early=true self= loopback=false", |
| 197 | + }, |
| 198 | + { |
| 199 | + name: "server not ready, self is true, not annotated", |
| 200 | + readySignalFn: func() lifecycleEvent { |
| 201 | + return fakeLifecycleSignal{ch: make(chan struct{})} |
| 202 | + }, |
| 203 | + user: &authenticationuser.DefaultInfo{Name: authenticationuser.APIServerUser}, |
| 204 | + handlerInvoked: 1, |
| 205 | + statusCodeExpected: http.StatusOK, |
| 206 | + }, |
| 207 | + { |
| 208 | + name: "server not ready, self is false, request is annotated", |
| 209 | + readySignalFn: func() lifecycleEvent { |
| 210 | + return fakeLifecycleSignal{ch: make(chan struct{})} |
| 211 | + }, |
| 212 | + user: &authenticationuser.DefaultInfo{Name: authenticationuser.Anonymous}, |
| 213 | + handlerInvoked: 1, |
| 214 | + statusCodeExpected: http.StatusOK, |
| 215 | + annotationExpected: "early=true self=false loopback=false", |
| 216 | + }, |
| 217 | + { |
| 218 | + name: "server not ready, self is false, looback is true, request is annotated", |
| 219 | + readySignalFn: func() lifecycleEvent { |
| 220 | + return fakeLifecycleSignal{ch: make(chan struct{})} |
| 221 | + }, |
| 222 | + user: &authenticationuser.DefaultInfo{Name: authenticationuser.Anonymous}, |
| 223 | + remoteAddr: "127.0.0.1:8080", |
| 224 | + handlerInvoked: 1, |
| 225 | + statusCodeExpected: http.StatusOK, |
| 226 | + annotationExpected: "early=true self=false loopback=true", |
| 227 | + }, |
| 228 | + } |
| 229 | + |
| 230 | + for _, test := range tests { |
| 231 | + t.Run(test.name, func(t *testing.T) { |
| 232 | + var handlerInvoked int |
| 233 | + handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 234 | + handlerInvoked++ |
| 235 | + w.WriteHeader(http.StatusOK) |
| 236 | + }) |
| 237 | + |
| 238 | + event := test.readySignalFn() |
| 239 | + target := WithStartupEarlyAnnotation(handler, event) |
| 240 | + |
| 241 | + req, err := http.NewRequest(http.MethodGet, "/api/v1/namespaces", nil) |
| 242 | + if err != nil { |
| 243 | + t.Fatalf("failed to create new http request - %v", err) |
| 244 | + } |
| 245 | + if test.remoteAddr != "" { |
| 246 | + req.RemoteAddr = test.remoteAddr |
| 247 | + } |
| 248 | + |
| 249 | + ctx := req.Context() |
| 250 | + if test.user != nil { |
| 251 | + ctx = apirequest.WithUser(ctx, test.user) |
| 252 | + } |
| 253 | + ctx = audit.WithAuditContext(ctx) |
| 254 | + req = req.WithContext(ctx) |
| 255 | + |
| 256 | + ac := audit.AuditContextFrom(req.Context()) |
| 257 | + if ac == nil { |
| 258 | + t.Fatalf("expected audit context inside the request context") |
| 259 | + } |
| 260 | + ac.Event = auditinternal.Event{ |
| 261 | + Level: auditinternal.LevelMetadata, |
| 262 | + } |
| 263 | + |
| 264 | + w := httptest.NewRecorder() |
| 265 | + w.Code = 0 |
| 266 | + target.ServeHTTP(w, req) |
| 267 | + |
| 268 | + if test.handlerInvoked != handlerInvoked { |
| 269 | + t.Errorf("expected the handler to be invoked: %d timed, but got: %d", test.handlerInvoked, handlerInvoked) |
| 270 | + } |
| 271 | + if test.statusCodeExpected != w.Result().StatusCode { |
| 272 | + t.Errorf("expected status code: %d, but got: %d", test.statusCodeExpected, w.Result().StatusCode) |
| 273 | + } |
| 274 | + |
| 275 | + key := "apiserver.k8s.io/startup" |
| 276 | + switch { |
| 277 | + case len(test.annotationExpected) == 0: |
| 278 | + if valueGot, ok := ac.Event.Annotations[key]; ok { |
| 279 | + t.Errorf("did not expect annotation to be added, but got: %s", valueGot) |
| 280 | + } |
| 281 | + default: |
| 282 | + if valueGot, ok := ac.Event.Annotations[key]; !ok || test.annotationExpected != valueGot { |
| 283 | + t.Errorf("expected annotation: %s, but got: %s", test.annotationExpected, valueGot) |
| 284 | + } |
| 285 | + } |
| 286 | + }) |
| 287 | + } |
| 288 | +} |
| 289 | + |
| 290 | +func TestIsLoopback(t *testing.T) { |
| 291 | + tests := []struct { |
| 292 | + address string |
| 293 | + want bool |
| 294 | + }{ |
| 295 | + { |
| 296 | + address: "www.foo.bar:80", |
| 297 | + want: false, |
| 298 | + }, |
| 299 | + { |
| 300 | + address: "www.foo.bar", |
| 301 | + want: false, |
| 302 | + }, |
| 303 | + { |
| 304 | + address: "127.0.0.1:8080", |
| 305 | + want: true, |
| 306 | + }, |
| 307 | + { |
| 308 | + address: "127.0.0.1", |
| 309 | + want: true, |
| 310 | + }, |
| 311 | + { |
| 312 | + address: "192.168.0.1", |
| 313 | + want: false, |
| 314 | + }, |
| 315 | + // localhost does not work |
| 316 | + { |
| 317 | + address: "localhost:8080", |
| 318 | + want: false, |
| 319 | + }, |
| 320 | + { |
| 321 | + address: "localhost", |
| 322 | + want: false, |
| 323 | + }, |
| 324 | + } |
| 325 | + |
| 326 | + for _, test := range tests { |
| 327 | + t.Run(test.address, func(t *testing.T) { |
| 328 | + if got := isLoopback(test.address); test.want != got { |
| 329 | + t.Errorf("expected isLoopback to return: %t, but got: %t", test.want, got) |
| 330 | + } |
| 331 | + }) |
| 332 | + } |
| 333 | +} |
| 334 | + |
| 335 | +func TestExemptIfHealthProbe(t *testing.T) { |
| 336 | + tests := []struct { |
| 337 | + path string |
| 338 | + exempt bool |
| 339 | + }{ |
| 340 | + { |
| 341 | + path: "/apis/v1/foo/bar", |
| 342 | + exempt: false, |
| 343 | + }, |
| 344 | + { |
| 345 | + path: "/readyz", |
| 346 | + exempt: true, |
| 347 | + }, |
| 348 | + { |
| 349 | + path: "http://foo.bar///healthz?verbose=1", |
| 350 | + exempt: true, |
| 351 | + }, |
| 352 | + { |
| 353 | + path: "/livez", |
| 354 | + exempt: true, |
| 355 | + }, |
| 356 | + } |
| 357 | + |
| 358 | + for _, test := range tests { |
| 359 | + t.Run(test.path, func(t *testing.T) { |
| 360 | + req, err := http.NewRequest(http.MethodGet, test.path, nil) |
| 361 | + if err != nil { |
| 362 | + t.Fatalf("failed to create new http request - %v", err) |
| 363 | + } |
| 364 | + if got := exemptIfHealthProbe(req); test.exempt != got { |
| 365 | + t.Errorf("expected exemptIfHealthProbe to return: %t, but got: %t", test.exempt, got) |
| 366 | + } |
| 367 | + }) |
| 368 | + } |
| 369 | +} |
| 370 | + |
| 371 | +type fakeLifecycleSignal struct { |
| 372 | + ch <-chan struct{} |
| 373 | + at *time.Time |
| 374 | +} |
| 375 | + |
| 376 | +func (s fakeLifecycleSignal) Name() string { return "initiated" } |
| 377 | +func (s fakeLifecycleSignal) Signaled() <-chan struct{} { return s.ch } |
| 378 | +func (s fakeLifecycleSignal) SignaledAt() *time.Time { return s.at } |
| 379 | + |
| 380 | +func newClosedChannel() <-chan struct{} { |
| 381 | + ch := make(chan struct{}) |
| 382 | + close(ch) |
| 383 | + return ch |
| 384 | +} |
0 commit comments