-
Notifications
You must be signed in to change notification settings - Fork 450
/
admission.go
169 lines (145 loc) · 5.65 KB
/
admission.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
// Copyright (c) 2021 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package resourcesize
import (
"context"
"fmt"
"net/http"
"strings"
"github.com/go-logr/logr"
authenticationv1 "k8s.io/api/authentication/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apiserver/pkg/authentication/serviceaccount"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
apisconfig "github.com/gardener/gardener/pkg/admissioncontroller/apis/config"
confighelper "github.com/gardener/gardener/pkg/admissioncontroller/apis/config/helper"
"github.com/gardener/gardener/pkg/admissioncontroller/metrics"
acadmission "github.com/gardener/gardener/pkg/admissioncontroller/webhooks/admission"
"github.com/gardener/gardener/pkg/logger"
)
const (
// HandlerName is the name of this admission webhook handler.
HandlerName = "resource_size_validator"
// WebhookPath is the HTTP handler path for this admission webhook handler.
WebhookPath = "/webhooks/validate-resource-size"
// metricReasonSizeExceeded is a metric reason value for a reason when an object size was exceeded.
metricReasonSizeExceeded = "Size Exceeded"
)
// New creates a new webhook handler validating that the resource size of a request doesn't exceed the configured
// limits.
func New(logger logr.Logger, config *apisconfig.ResourceAdmissionConfiguration) *handler {
return &handler{logger: logger, config: config}
}
type handler struct {
logger logr.Logger
config *apisconfig.ResourceAdmissionConfiguration
decoder *admission.Decoder
}
var _ admission.Handler = &handler{}
func (h *handler) InjectDecoder(d *admission.Decoder) error {
h.decoder = d
return nil
}
func (h *handler) Handle(_ context.Context, request admission.Request) admission.Response {
requestLogger := logger.NewIDLogger(h.logger.WithValues(
"user", request.UserInfo.Username,
"resource", request.Resource, "name", request.Name,
))
if request.Namespace != "" {
requestLogger = requestLogger.WithValues("namespace", request.Namespace)
}
response := h.admitRequestSize(request, requestLogger)
if !response.Allowed {
metrics.RejectedResources.WithLabelValues(
fmt.Sprint(request.Operation),
request.Kind.Kind,
request.Namespace,
metricReasonSizeExceeded,
).Inc()
}
return response
}
func (h *handler) admitRequestSize(request admission.Request, requestLogger logr.Logger) admission.Response {
if request.SubResource != "" {
return acadmission.Allowed("subresources are not handled")
}
if isUnrestrictedUser(request.UserInfo, h.config.UnrestrictedSubjects) {
return acadmission.Allowed("user is unrestricted")
}
requestedResource := &request.Resource
if request.RequestResource != nil {
// Use original requested requestedResource if available, see doc string of `admissionv1.RequestResource`.
requestedResource = request.RequestResource
}
limit := findLimitForGVR(h.config.Limits, requestedResource)
if limit == nil {
return acadmission.Allowed("no limit configured for requested resource")
}
objectSize := len(request.Object.Raw)
if limit.CmpInt64(int64(objectSize)) == -1 {
if h.config.OperationMode == nil || *h.config.OperationMode == apisconfig.AdmissionModeBlock {
requestLogger.Info("Maximum resource size exceeded, rejected request",
"requestObjectSize", objectSize, "limit", limit)
return admission.Errored(http.StatusUnprocessableEntity, fmt.Errorf("maximum resource size exceeded! Size in request: %d bytes, max allowed: %s", objectSize, limit))
}
requestLogger.Info("Maximum resource size exceeded, request will be denied in blocking mode",
"requestObjectSize", objectSize, "limit", limit)
}
return acadmission.Allowed("resource size ok")
}
func serviceAccountMatch(userInfo authenticationv1.UserInfo, subjects []rbacv1.Subject) bool {
for _, subject := range subjects {
if subject.Kind == rbacv1.ServiceAccountKind {
if confighelper.ServiceAccountMatches(subject, userInfo) {
return true
}
}
}
return false
}
func userMatch(userInfo authenticationv1.UserInfo, subjects []rbacv1.Subject) bool {
for _, subject := range subjects {
var match bool
switch subject.Kind {
case rbacv1.UserKind:
match = confighelper.UserMatches(subject, userInfo)
case rbacv1.GroupKind:
match = confighelper.UserGroupMatches(subject, userInfo)
}
if match {
return true
}
}
return false
}
func isUnrestrictedUser(userInfo authenticationv1.UserInfo, subjects []rbacv1.Subject) bool {
isServiceAccount := strings.HasPrefix(userInfo.Username, serviceaccount.ServiceAccountUsernamePrefix)
if isServiceAccount {
return serviceAccountMatch(userInfo, subjects)
}
return userMatch(userInfo, subjects)
}
func findLimitForGVR(limits []apisconfig.ResourceLimit, gvr *metav1.GroupVersionResource) *resource.Quantity {
for _, limit := range limits {
size := limit.Size
if confighelper.APIGroupMatches(limit, gvr.Group) &&
confighelper.VersionMatches(limit, gvr.Version) &&
confighelper.ResourceMatches(limit, gvr.Resource) {
return &size
}
}
return nil
}