| 1 |
/* |
| 2 |
Copyright 2020 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 |
"context" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"net/http" |
| 24 |
"time" |
| 25 |
|
| 26 |
apierrors "k8s.io/apimachinery/pkg/api/errors" |
| 27 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 28 |
"k8s.io/apimachinery/pkg/runtime" |
| 29 |
"k8s.io/apimachinery/pkg/runtime/schema" |
| 30 |
utilruntime "k8s.io/apimachinery/pkg/util/runtime" |
| 31 |
auditinternal "k8s.io/apiserver/pkg/apis/audit" |
| 32 |
"k8s.io/apiserver/pkg/audit" |
| 33 |
"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters" |
| 34 |
"k8s.io/apiserver/pkg/endpoints/request" |
| 35 |
"k8s.io/klog/v2" |
| 36 |
"k8s.io/utils/clock" |
| 37 |
) |
| 38 |
|
| 39 |
const ( |
| 40 |
// The 'timeout' query parameter in the request URL has an invalid duration specifier |
| 41 |
invalidTimeoutInURL = "invalid timeout specified in the request URL" |
| 42 |
) |
| 43 |
|
| 44 |
// WithRequestDeadline determines the timeout duration applicable to the given request and sets a new context |
| 45 |
// with the appropriate deadline. |
| 46 |
// auditWrapper provides an http.Handler that audits a failed request. |
| 47 |
// longRunning returns true if he given request is a long running request. |
| 48 |
// requestTimeoutMaximum specifies the default request timeout value. |
| 49 |
func WithRequestDeadline(handler http.Handler, sink audit.Sink, policy audit.PolicyRuleEvaluator, longRunning request.LongRunningRequestCheck, |
| 50 |
negotiatedSerializer runtime.NegotiatedSerializer, requestTimeoutMaximum time.Duration) http.Handler { |
| 51 |
return withRequestDeadline(handler, sink, policy, longRunning, negotiatedSerializer, requestTimeoutMaximum, clock.RealClock{}) |
| 52 |
} |
| 53 |
|
| 54 |
func withRequestDeadline(handler http.Handler, sink audit.Sink, policy audit.PolicyRuleEvaluator, longRunning request.LongRunningRequestCheck, |
| 55 |
negotiatedSerializer runtime.NegotiatedSerializer, requestTimeoutMaximum time.Duration, clock clock.PassiveClock) http.Handler { |
| 56 |
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 57 |
ctx := req.Context() |
| 58 |
|
| 59 |
requestInfo, ok := request.RequestInfoFrom(ctx) |
| 60 |
if !ok { |
| 61 |
handleError(w, req, http.StatusInternalServerError, nil, "no RequestInfo found in context, handler chain must be wrong") |
| 62 |
return |
| 63 |
} |
| 64 |
if longRunning(req, requestInfo) { |
| 65 |
handler.ServeHTTP(w, req) |
| 66 |
return |
| 67 |
} |
| 68 |
|
| 69 |
userSpecifiedTimeout, ok, err := parseTimeout(req) |
| 70 |
if err != nil { |
| 71 |
statusErr := apierrors.NewBadRequest(err.Error()) |
| 72 |
|
| 73 |
klog.Errorf("Error - %s: %#v", err.Error(), req.RequestURI) |
| 74 |
|
| 75 |
failed := failedErrorHandler(negotiatedSerializer, statusErr) |
| 76 |
failWithAudit := withFailedRequestAudit(failed, statusErr, sink, policy) |
| 77 |
failWithAudit.ServeHTTP(w, req) |
| 78 |
return |
| 79 |
} |
| 80 |
|
| 81 |
timeout := requestTimeoutMaximum |
| 82 |
if ok { |
| 83 |
// we use the default timeout enforced by the apiserver: |
| 84 |
// - if the user has specified a timeout of 0s, this implies no timeout on the user's part. |
| 85 |
// - if the user has specified a timeout that exceeds the maximum deadline allowed by the apiserver. |
| 86 |
if userSpecifiedTimeout > 0 && userSpecifiedTimeout < requestTimeoutMaximum { |
| 87 |
timeout = userSpecifiedTimeout |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
started := clock.Now() |
| 92 |
if requestStartedTimestamp, ok := request.ReceivedTimestampFrom(ctx); ok { |
| 93 |
started = requestStartedTimestamp |
| 94 |
} |
| 95 |
|
| 96 |
ctx, cancel := context.WithDeadline(ctx, started.Add(timeout)) |
| 97 |
defer cancel() |
| 98 |
|
| 99 |
req = req.WithContext(ctx) |
| 100 |
handler.ServeHTTP(w, req) |
| 101 |
}) |
| 102 |
} |
| 103 |
|
| 104 |
// withFailedRequestAudit decorates a failed http.Handler and is used to audit a failed request. |
| 105 |
// statusErr is used to populate the Message property of ResponseStatus. |
| 106 |
func withFailedRequestAudit(failedHandler http.Handler, statusErr *apierrors.StatusError, sink audit.Sink, policy audit.PolicyRuleEvaluator) http.Handler { |
| 107 |
if sink == nil || policy == nil { |
| 108 |
return failedHandler |
| 109 |
} |
| 110 |
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 111 |
ac, err := evaluatePolicyAndCreateAuditEvent(req, policy) |
| 112 |
if err != nil { |
| 113 |
utilruntime.HandleError(fmt.Errorf("failed to create audit event: %v", err)) |
| 114 |
responsewriters.InternalError(w, req, errors.New("failed to create audit event")) |
| 115 |
return |
| 116 |
} |
| 117 |
|
| 118 |
if !ac.Enabled() { |
| 119 |
failedHandler.ServeHTTP(w, req) |
| 120 |
return |
| 121 |
} |
| 122 |
ev := &ac.Event |
| 123 |
|
| 124 |
ev.ResponseStatus = &metav1.Status{} |
| 125 |
ev.Stage = auditinternal.StageResponseStarted |
| 126 |
if statusErr != nil { |
| 127 |
ev.ResponseStatus.Message = statusErr.Error() |
| 128 |
} |
| 129 |
|
| 130 |
rw := decorateResponseWriter(req.Context(), w, ev, sink, ac.RequestAuditConfig.OmitStages) |
| 131 |
failedHandler.ServeHTTP(rw, req) |
| 132 |
}) |
| 133 |
} |
| 134 |
|
| 135 |
// failedErrorHandler returns an http.Handler that uses the specified StatusError object |
| 136 |
// to render an error response to the request. |
| 137 |
func failedErrorHandler(s runtime.NegotiatedSerializer, statusError *apierrors.StatusError) http.Handler { |
| 138 |
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 139 |
ctx := req.Context() |
| 140 |
requestInfo, found := request.RequestInfoFrom(ctx) |
| 141 |
if !found { |
| 142 |
responsewriters.InternalError(w, req, errors.New("no RequestInfo found in the context")) |
| 143 |
return |
| 144 |
} |
| 145 |
|
| 146 |
gv := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion} |
| 147 |
responsewriters.ErrorNegotiated(statusError, s, gv, w, req) |
| 148 |
}) |
| 149 |
} |
| 150 |
|
| 151 |
// parseTimeout parses the given HTTP request URL and extracts the timeout query parameter |
| 152 |
// value if specified by the user. |
| 153 |
// If a timeout is not specified the function returns false and err is set to nil |
| 154 |
// If the value specified is malformed then the function returns false and err is set |
| 155 |
func parseTimeout(req *http.Request) (time.Duration, bool, error) { |
| 156 |
value := req.URL.Query().Get("timeout") |
| 157 |
if value == "" { |
| 158 |
return 0, false, nil |
| 159 |
} |
| 160 |
|
| 161 |
timeout, err := time.ParseDuration(value) |
| 162 |
if err != nil { |
| 163 |
return 0, false, fmt.Errorf("%s - %s", invalidTimeoutInURL, err.Error()) |
| 164 |
} |
| 165 |
|
| 166 |
return timeout, true, nil |
| 167 |
} |
| 168 |
|
| 169 |
// handleError does the following: |
| 170 |
// a) it writes the specified error code, and msg to the ResponseWriter |
| 171 |
// object, it does not print the given innerErr into the ResponseWriter object. |
| 172 |
// b) additionally, it prints the given msg, and innerErr to the log with other |
| 173 |
// request scoped data that helps identify the given request. |
| 174 |
func handleError(w http.ResponseWriter, r *http.Request, code int, innerErr error, msg string) { |
| 175 |
http.Error(w, msg, code) |
| 176 |
klog.ErrorSDepth(1, innerErr, msg, "method", r.Method, "URI", r.RequestURI, "auditID", audit.GetAuditIDTruncated(r.Context())) |
| 177 |
} |