/
managedcluster_validating.go
274 lines (242 loc) · 8.96 KB
/
managedcluster_validating.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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package v1
import (
"context"
"fmt"
"strings"
operatorhelpers "github.com/openshift/library-go/pkg/operator/v1helpers"
authenticationv1 "k8s.io/api/authentication/v1"
authorizationv1 "k8s.io/api/authorization/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
apimachineryvalidation "k8s.io/apimachinery/pkg/api/validation"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
clusterv1beta2 "open-cluster-management.io/api/cluster/v1beta2"
v1 "open-cluster-management.io/api/cluster/v1"
"open-cluster-management.io/registration/pkg/helpers"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
corev1 "k8s.io/api/core/v1"
)
var _ webhook.CustomValidator = &ManagedClusterWebhook{}
// ValidateCreate implements webhook.Validator so a webhook will be registered for the type
func (r *ManagedClusterWebhook) ValidateCreate(ctx context.Context, obj runtime.Object) error {
managedCluster, ok := obj.(*v1.ManagedCluster)
if !ok {
return apierrors.NewBadRequest("Request cluster obj format is not right")
}
req, err := admission.RequestFromContext(ctx)
if err != nil {
return apierrors.NewBadRequest(err.Error())
}
//Validate if Spec.ManagedClusterClientConfigs is Valid HTTPS URL
err = r.validateManagedClusterObj(*managedCluster)
if err != nil {
return err
}
// the HubAcceptsClient field is changed, we need to:
// 1. check whether cluster namespace is terminating.
// 2. check the request user whether has been allowed to change the HubAcceptsClient field with
// SubjectAccessReview api.
if managedCluster.Spec.HubAcceptsClient {
if err := r.validateAcceptByClusterNamespace(managedCluster.Name); err != nil {
return err
}
if err := r.allowUpdateAcceptField(managedCluster.Name, req.UserInfo); err != nil {
return err
}
}
// check whether the request user has been allowed to set clusterset label
var clusterSetName string
if len(managedCluster.Labels) > 0 {
clusterSetName = managedCluster.Labels[clusterv1beta2.ClusterSetLabel]
}
return r.allowSetClusterSetLabel(req.UserInfo, "", clusterSetName)
}
// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type
func (r *ManagedClusterWebhook) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) error {
managedCluster, ok := newObj.(*v1.ManagedCluster)
if !ok {
return apierrors.NewBadRequest("Request new cluster obj format is not right")
}
oldManagedCluster, ok := oldObj.(*v1.ManagedCluster)
if !ok {
return apierrors.NewBadRequest("Request old cluster obj format is not right")
}
req, err := admission.RequestFromContext(ctx)
if err != nil {
return apierrors.NewBadRequest(err.Error())
}
//Validate if Spec.ManagedClusterClientConfigs is Valid HTTPS URL
err = r.validateManagedClusterObj(*managedCluster)
if err != nil {
return err
}
// the HubAcceptsClient field is changed, we need to:
// 1. check whether cluster namespace is terminating.
// 2. check the request user whether has been allowed to change the HubAcceptsClient field with
// SubjectAccessReview api.
if managedCluster.Spec.HubAcceptsClient != oldManagedCluster.Spec.HubAcceptsClient {
if managedCluster.Spec.HubAcceptsClient {
if err := r.validateAcceptByClusterNamespace(managedCluster.Name); err != nil {
return err
}
if err := r.allowUpdateAcceptField(managedCluster.Name, req.UserInfo); err != nil {
return err
}
}
}
// check whether the request user has been allowed to set clusterset label
var originalClusterSetName, currentClusterSetName string
if len(oldManagedCluster.Labels) > 0 {
originalClusterSetName = oldManagedCluster.Labels[clusterv1beta2.ClusterSetLabel]
}
if len(managedCluster.Labels) > 0 {
currentClusterSetName = managedCluster.Labels[clusterv1beta2.ClusterSetLabel]
}
return r.allowSetClusterSetLabel(req.UserInfo, originalClusterSetName, currentClusterSetName)
}
// ValidateDelete implements webhook.Validator so a webhook will be registered for the type
func (r *ManagedClusterWebhook) ValidateDelete(_ context.Context, obj runtime.Object) error {
return nil
}
// validateManagedClusterObj validates the fileds of ManagedCluster object
func (r *ManagedClusterWebhook) validateManagedClusterObj(cluster v1.ManagedCluster) error {
errs := []error{}
// The cluster name must be the same format of namespace name.
if errMsgs := apimachineryvalidation.ValidateNamespaceName(cluster.Name, false); len(errMsgs) > 0 {
errs = append(errs, fmt.Errorf("metadata.name format is not correct: %s", strings.Join(errMsgs, ",")))
}
// there are no spoke client configs, finish the validation process
if len(cluster.Spec.ManagedClusterClientConfigs) == 0 {
return nil
}
// validate the url in spoke client configs
for _, clientConfig := range cluster.Spec.ManagedClusterClientConfigs {
if !helpers.IsValidHTTPSURL(clientConfig.URL) {
errs = append(errs, fmt.Errorf("url %q is invalid in client configs", clientConfig.URL))
}
}
if len(errs) != 0 {
return apierrors.NewBadRequest(operatorhelpers.NewMultiLineAggregate(errs).Error())
}
return nil
}
// allowUpdateHubAcceptsClientField using SubjectAccessReview API to check whether a request user has been authorized to update
// HubAcceptsClient field
func (r *ManagedClusterWebhook) allowUpdateAcceptField(clusterName string, userInfo authenticationv1.UserInfo) error {
extra := make(map[string]authorizationv1.ExtraValue)
for k, v := range userInfo.Extra {
extra[k] = authorizationv1.ExtraValue(v)
}
sar := &authorizationv1.SubjectAccessReview{
Spec: authorizationv1.SubjectAccessReviewSpec{
User: userInfo.Username,
UID: userInfo.UID,
Groups: userInfo.Groups,
Extra: extra,
ResourceAttributes: &authorizationv1.ResourceAttributes{
Group: "register.open-cluster-management.io",
Resource: "managedclusters",
Verb: "update",
Subresource: "accept",
Name: clusterName,
},
},
}
sar, err := r.kubeClient.AuthorizationV1().SubjectAccessReviews().Create(context.TODO(), sar, metav1.CreateOptions{})
if err != nil {
return apierrors.NewForbidden(
v1.Resource("managedclusters/accept"),
clusterName,
err,
)
}
if !sar.Status.Allowed {
return apierrors.NewForbidden(
v1.Resource("managedclusters/accept"),
clusterName,
fmt.Errorf("user %q cannot update the HubAcceptsClient field", userInfo.Username),
)
}
return nil
}
// validateClusterNamespace checks the cluster namespace, if the namespace is terminating, reject the accept request.
func (r *ManagedClusterWebhook) validateAcceptByClusterNamespace(clusterName string) error {
clusterNamespace, err := r.kubeClient.CoreV1().Namespaces().Get(context.TODO(), clusterName, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
return nil
}
if err != nil {
return apierrors.NewForbidden(
v1.Resource("managedclusters/accept"),
clusterName,
err,
)
}
if clusterNamespace.Status.Phase == corev1.NamespaceTerminating {
return apierrors.NewForbidden(
v1.Resource("managedclusters/accept"),
clusterName,
fmt.Errorf("cluster namespace %q is terminating", clusterName),
)
}
return nil
}
// allowSetClusterSetLabel checks whether a request user has been authorized to set clusterset label
func (r *ManagedClusterWebhook) allowSetClusterSetLabel(userInfo authenticationv1.UserInfo, originalClusterSet, newClusterSet string) error {
if originalClusterSet == newClusterSet {
return nil
}
if len(originalClusterSet) > 0 {
err := r.allowUpdateClusterSet(userInfo, originalClusterSet)
if err != nil {
return err
}
}
if len(newClusterSet) > 0 {
err := r.allowUpdateClusterSet(userInfo, newClusterSet)
if err != nil {
return err
}
}
return nil
}
// allowUpdateClusterSet checks whether a request user has been authorized to add/remove a ManagedCluster
// to/from the ManagedClusterSet
func (r *ManagedClusterWebhook) allowUpdateClusterSet(userInfo authenticationv1.UserInfo, clusterSetName string) error {
extra := make(map[string]authorizationv1.ExtraValue)
for k, v := range userInfo.Extra {
extra[k] = authorizationv1.ExtraValue(v)
}
sar := &authorizationv1.SubjectAccessReview{
Spec: authorizationv1.SubjectAccessReviewSpec{
User: userInfo.Username,
UID: userInfo.UID,
Groups: userInfo.Groups,
Extra: extra,
ResourceAttributes: &authorizationv1.ResourceAttributes{
Group: "cluster.open-cluster-management.io",
Resource: "managedclustersets",
Subresource: "join",
Name: clusterSetName,
Verb: "create",
},
},
}
sar, err := r.kubeClient.AuthorizationV1().SubjectAccessReviews().Create(context.TODO(), sar, metav1.CreateOptions{})
if err != nil {
return apierrors.NewForbidden(
v1.Resource("managedclustersets/join"),
clusterSetName,
err,
)
}
if !sar.Status.Allowed {
return apierrors.NewForbidden(
v1.Resource("managedclustersets/join"),
clusterSetName,
fmt.Errorf("user %q cannot add/remove a ManagedCluster to/from ManagedClusterSet %q", userInfo.Username, clusterSetName),
)
}
return nil
}