/
auth.go
282 lines (224 loc) · 8.22 KB
/
auth.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
275
276
277
278
279
280
281
282
/*
Copyright 2023 The aerospike-operator Authors.
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 auth
import (
"context"
"fmt"
"reflect"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
v1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"github.com/aerospike/aerospike-kubernetes-operator-ctl/pkg/configuration"
"github.com/aerospike/aerospike-kubernetes-operator-ctl/pkg/internal"
)
const (
ServiceAccountName = "aerospike-operator-controller-manager"
ClusterRoleName = "aerospike-cluster"
ClusterRoleBindingName = "aerospike-cluster"
RoleBindingName = "aerospike-cluster"
)
func Create(ctx context.Context, params *configuration.Parameters) error {
subjects := make([]interface{}, 0, len(params.Namespaces))
for ns := range params.Namespaces {
sa := &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: ServiceAccountName,
Namespace: ns,
},
}
// Create SA and check namespace existence
if err := params.K8sClient.Create(ctx, sa); err != nil {
if errors.IsNotFound(err) {
params.Logger.Error(fmt.Sprintf("namespace: %s not found, skipping RBAC resources", ns))
continue
}
if !errors.IsAlreadyExists(err) {
return err
}
params.Logger.Info("Resource already exists, skipping", zap.String("kind", internal.ServiceAccountKind),
zap.String("name", ServiceAccountName), zap.String("namespace", ns))
} else {
params.Logger.Info("Created resource", zap.String("kind", internal.ServiceAccountKind),
zap.String("name", ServiceAccountName), zap.String("namespace", ns))
}
sub := map[string]interface{}{
"kind": internal.ServiceAccountKind,
"name": ServiceAccountName,
"namespace": ns,
}
// If RBAC scope is namespace, then create RoleBinding and continue
if !params.ClusterScope {
if err := createOrUpdateBinding(
ctx, params,
v1.SchemeGroupVersion.WithKind(internal.RoleBindingKind),
types.NamespacedName{Name: RoleBindingName, Namespace: ns},
[]interface{}{sub}); err != nil {
return err
}
continue
}
subjects = append(subjects, sub)
}
// Return from here if namespace scope or no change in subjects
if !params.ClusterScope || len(subjects) == 0 {
return nil
}
return createOrUpdateBinding(
ctx, params,
v1.SchemeGroupVersion.WithKind(internal.ClusterRoleBindingKind),
types.NamespacedName{Name: ClusterRoleBindingName},
subjects)
}
func createOrUpdateBinding(
ctx context.Context, params *configuration.Parameters, gvk schema.GroupVersionKind,
nsNm types.NamespacedName, subjects interface{},
) error {
unstruct := &unstructured.Unstructured{}
unstruct.SetGroupVersionKind(gvk)
unstruct.SetName(nsNm.Name)
unstruct.SetNamespace(nsNm.Namespace)
roleRef := map[string]interface{}{
"apiGroup": v1.GroupName,
"kind": internal.ClusterRoleKind,
"name": ClusterRoleName,
}
unstruct.Object["subjects"] = subjects
unstruct.Object["roleRef"] = roleRef
if err := params.K8sClient.Create(ctx, unstruct); err != nil {
if errors.IsAlreadyExists(err) {
params.Logger.Info("Resource already exists, trying to update", zap.String("kind", gvk.Kind),
zap.String("name", nsNm.Name), zap.String("namespace", nsNm.Namespace))
currentResource := &unstructured.Unstructured{}
currentResource.SetGroupVersionKind(gvk)
if gErr := params.K8sClient.Get(ctx, nsNm, currentResource); gErr != nil {
return gErr
}
if !reflect.DeepEqual(currentResource.Object["roleRef"], unstruct.Object["roleRef"]) {
return fmt.Errorf("%s: %s already exists with different roleRe,"+
"can't update roleRef to %s", gvk.Kind, nsNm.Name, ClusterRoleName)
}
if !reflect.DeepEqual(currentResource.Object["subjects"], unstruct.Object["subjects"]) {
currentResource.Object["subjects"] = mergeSubjects(currentResource.Object["subjects"].([]interface{}),
unstruct.Object["subjects"].([]interface{}))
if uErr := params.K8sClient.Update(ctx, currentResource); uErr != nil {
return uErr
}
params.Logger.Info("Updated resource", zap.String("kind", gvk.Kind),
zap.String("name", nsNm.Name), zap.String("namespace", nsNm.Namespace))
return nil
}
params.Logger.Info("Update not required, skipping", zap.String("kind", gvk.Kind),
zap.String("name", nsNm.Name), zap.String("namespace", nsNm.Namespace))
return nil
}
}
params.Logger.Info("Created resource", zap.String("kind", gvk.Kind),
zap.String("name", nsNm.Name), zap.String("namespace", nsNm.Namespace))
return nil
}
func mergeSubjects(baseSub, patchSub []interface{}) []interface{} {
var newSubs []interface{}
for patchIdx := range patchSub {
var matched bool
for baseIdx := range baseSub {
if reflect.DeepEqual(baseSub[baseIdx].(map[string]interface{}), patchSub[patchIdx].(map[string]interface{})) {
matched = true
break
}
}
if !matched {
newSubs = append(newSubs, patchSub[patchIdx])
}
}
if len(newSubs) > 0 {
baseSub = append(baseSub, newSubs...)
}
return baseSub
}
func Delete(ctx context.Context, params *configuration.Parameters) error {
for ns := range params.Namespaces {
// Delete serviceAccount
deleteResource(
ctx, params,
corev1.SchemeGroupVersion.WithKind(internal.ServiceAccountKind),
types.NamespacedName{Name: ServiceAccountName, Namespace: ns})
// If RBAC scope is namespace, then delete RoleBinding
if !params.ClusterScope {
deleteResource(
ctx, params,
v1.SchemeGroupVersion.WithKind(internal.RoleBindingKind),
types.NamespacedName{Name: RoleBindingName, Namespace: ns})
}
}
// Return from here if namespace scope
if !params.ClusterScope {
return nil
}
crb := &v1.ClusterRoleBinding{}
if err := params.K8sClient.Get(ctx, types.NamespacedName{
Name: ClusterRoleBindingName,
}, crb); err != nil {
return err
}
// Removed subject entries for the given namespaces
filtered := make([]v1.Subject, 0, len(crb.Subjects))
for _, sub := range crb.Subjects {
if sub.Kind == internal.ServiceAccountKind &&
sub.Name == ServiceAccountName && params.Namespaces.Has(sub.Namespace) {
continue
}
filtered = append(filtered, sub)
}
if len(filtered) == 0 {
deleteResource(
ctx, params,
v1.SchemeGroupVersion.WithKind(internal.ClusterRoleBindingKind),
types.NamespacedName{Name: ClusterRoleBindingName})
return nil
}
if len(filtered) == len(crb.Subjects) {
params.Logger.Info("Update not required, skipping", zap.String("kind", internal.ClusterRoleBindingKind),
zap.String("name", ClusterRoleBindingName))
return nil
}
crb.Subjects = filtered
params.Logger.Info(fmt.Sprintf("Updating %s subjects", internal.ClusterRoleKind),
zap.String("name", ClusterRoleName))
return params.K8sClient.Update(ctx, crb)
}
func deleteResource(
ctx context.Context, params *configuration.Parameters, gvk schema.GroupVersionKind,
nsNm types.NamespacedName) {
unstruct := &unstructured.Unstructured{}
unstruct.SetGroupVersionKind(gvk)
unstruct.SetName(nsNm.Name)
unstruct.SetNamespace(nsNm.Namespace)
if err := params.K8sClient.Delete(ctx, unstruct); err != nil {
if errors.IsNotFound(err) {
params.Logger.Warn("Resource not found for deletion, skipping", zap.String("kind", gvk.Kind),
zap.String("name", nsNm.Name), zap.String("namespace", nsNm.Namespace))
} else {
// TODO: Should we error out or continue if we are not able to delete?
params.Logger.Error("failed to delete resource", zap.String("kind", gvk.Kind),
zap.String("name", nsNm.Name), zap.String("namespace", nsNm.Namespace), zap.Error(err))
}
return
}
params.Logger.Info("Deleted resource", zap.String("kind", gvk.Kind),
zap.String("name", nsNm.Name), zap.String("namespace", nsNm.Namespace))
}