-
Notifications
You must be signed in to change notification settings - Fork 117
/
webhook.go
330 lines (295 loc) · 9.07 KB
/
webhook.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package project
import (
"context"
"fmt"
"github.com/kelseyhightower/envconfig"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/validation/field"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
kargoapi "github.com/akuity/kargo/api/v1alpha1"
"github.com/akuity/kargo/internal/logging"
)
var (
projectGroupKind = schema.GroupKind{
Group: kargoapi.GroupVersion.Group,
Kind: "Project",
}
projectGroupResource = schema.GroupResource{
Group: kargoapi.GroupVersion.Group,
Resource: "projects",
}
)
type WebhookConfig struct {
KargoNamespace string `envconfig:"KARGO_NAMESPACE" required:"true"`
}
func WebhookConfigFromEnv() WebhookConfig {
cfg := WebhookConfig{}
envconfig.MustProcess("", &cfg)
return cfg
}
type webhook struct {
cfg WebhookConfig
// The following behaviors are overridable for testing purposes:
validateSpecFn func(*field.Path, *kargoapi.ProjectSpec) field.ErrorList
ensureNamespaceFn func(context.Context, *kargoapi.Project) error
ensureProjectAdminPermissionsFn func(
context.Context,
*kargoapi.Project,
) error
getNamespaceFn func(
context.Context,
types.NamespacedName,
client.Object,
...client.GetOption,
) error
createNamespaceFn func(
context.Context,
client.Object,
...client.CreateOption,
) error
createRoleBindingFn func(
context.Context,
client.Object,
...client.CreateOption,
) error
}
func SetupWebhookWithManager(mgr ctrl.Manager, cfg WebhookConfig) error {
w := newWebhook(mgr.GetClient(), cfg)
return ctrl.NewWebhookManagedBy(mgr).
For(&kargoapi.Project{}).
WithValidator(w).
Complete()
}
func newWebhook(kubeClient client.Client, cfg WebhookConfig) *webhook {
w := &webhook{
cfg: cfg,
}
w.validateSpecFn = w.validateSpec
w.ensureNamespaceFn = w.ensureNamespace
w.ensureProjectAdminPermissionsFn = w.ensureProjectAdminPermissions
w.getNamespaceFn = kubeClient.Get
w.createNamespaceFn = kubeClient.Create
w.createRoleBindingFn = kubeClient.Create
return w
}
func (w *webhook) ValidateCreate(
ctx context.Context,
obj runtime.Object,
) (admission.Warnings, error) {
project := obj.(*kargoapi.Project) // nolint: forcetypeassert
if errs := w.validateSpecFn(field.NewPath("spec"), project.Spec); len(errs) > 0 {
return nil, apierrors.NewInvalid(projectGroupKind, project.Name, errs)
}
req, err := admission.RequestFromContext(ctx)
if err != nil {
return nil, apierrors.NewInternalError(
fmt.Errorf("error getting admission request from context: %w", err),
)
}
if req.DryRun != nil && *req.DryRun {
return nil, nil
}
// We synchronously ensure the existence of a namespace with the same name as
// the Project because resources following the Project in a manifest are
// likely to be scoped to that namespace.
if err := w.ensureNamespaceFn(ctx, project); err != nil {
return nil, err
}
// Ensure the Kargo API server and kargo-admin ServiceAccount receive
// permissions to manage ServiceAccounts, Roles, RoleBindings, and Secrets in
// the Project namespace just in time. This prevents us from having to give
// the Kargo API server carte blanche access these resources throughout the
// cluster. We do this synchronously because resources of these types are are
// likely to follow the Project in a manifest.
return nil, w.ensureProjectAdminPermissionsFn(ctx, project)
}
func (w *webhook) ValidateUpdate(
_ context.Context,
_ runtime.Object,
newObj runtime.Object,
) (admission.Warnings, error) {
project := newObj.(*kargoapi.Project) // nolint: forcetypeassert
if errs := w.validateSpecFn(field.NewPath("spec"), project.Spec); len(errs) > 0 {
return nil, apierrors.NewInvalid(projectGroupKind, project.Name, errs)
}
return nil, nil
}
func (w *webhook) ValidateDelete(
context.Context,
runtime.Object,
) (admission.Warnings, error) {
return nil, nil
}
func (w *webhook) validateSpec(
f *field.Path,
spec *kargoapi.ProjectSpec,
) field.ErrorList {
if spec == nil { // nil spec is valid
return nil
}
return w.validatePromotionPolicies(
f.Child("promotionPolicies"),
spec.PromotionPolicies,
)
}
func (w *webhook) validatePromotionPolicies(
f *field.Path,
promotionPolicies []kargoapi.PromotionPolicy,
) field.ErrorList {
stageNames := make(map[string]struct{}, len(promotionPolicies))
for _, promotionPolicy := range promotionPolicies {
if _, found := stageNames[promotionPolicy.Stage]; found {
return field.ErrorList{
field.Invalid(
f,
promotionPolicies,
fmt.Sprintf(
"multiple %s reference stage %s",
f.String(),
promotionPolicy.Stage,
),
),
}
}
stageNames[promotionPolicy.Stage] = struct{}{}
}
return nil
}
// ensureNamespace is used to ensure the existence of a namespace with the same
// name as the Project. If the namespace does not exist, it is created. If the
// namespace exists, it is checked for any ownership conflicts with the Project
// and will return an error if any are found.
func (w *webhook) ensureNamespace(
ctx context.Context,
project *kargoapi.Project,
) error {
logger := logging.LoggerFromContext(ctx).WithFields(log.Fields{
"project": project.Name,
"name": project.Name,
})
ns := &corev1.Namespace{}
err := w.getNamespaceFn(
ctx,
types.NamespacedName{Name: project.Name},
ns,
)
if err == nil {
// We found an existing namespace with the same name as the Project. Check
// for possible conflicts before proceeding.
//
// No owner, but not a Project namespace:
if (len(ns.OwnerReferences) == 0 &&
(ns.Labels == nil || ns.Labels[kargoapi.ProjectLabelKey] != kargoapi.LabelTrueValue)) ||
// Not owned by this Project:
(len(ns.OwnerReferences) == 1 && ns.OwnerReferences[0].UID != project.UID) ||
// Multiple owners:
len(ns.OwnerReferences) > 1 {
return apierrors.NewConflict(
projectGroupResource,
project.Name,
fmt.Errorf(
"failed to initialize Project %q because namespace %q already exists",
project.Name,
project.Name,
),
)
}
logger.Debug("namespace exists but no conflict was found")
return nil
}
if !apierrors.IsNotFound(err) {
return apierrors.NewInternalError(
fmt.Errorf("error getting namespace %q: %w", project.Name, err),
)
}
logger.Debug("namespace does not exist; creating it")
ns = &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: project.Name,
Labels: map[string]string{
kargoapi.ProjectLabelKey: kargoapi.LabelTrueValue,
},
// Note: We no longer use an owner reference here. If we did, and too
// much time were to pass between namespace creation and the completion of
// this webhook, Kubernetes would notice the absence of the owner, mistake
// the namespace for an orphan, and delete it. We do still want the
// Project to own the namespace, but we rely on the Project reconciler in
// the management controller to establish that relationship
// asynchronously.
},
}
// Project namespaces are owned by a Project. Deleting a Project
// automatically deletes the namespace. But we also want this to work in the
// other direction, where that behavior is not automatic. We add a finalizer
// to the namespace and use our own namespace reconciler to clear it after
// deleting the Project.
controllerutil.AddFinalizer(ns, kargoapi.FinalizerName)
if err := w.createNamespaceFn(ctx, ns); err != nil {
return apierrors.NewInternalError(
fmt.Errorf("error creating namespace %q: %w", project.Name, err),
)
}
logger.Debug("created namespace")
return nil
}
func (w *webhook) ensureProjectAdminPermissions(
ctx context.Context,
project *kargoapi.Project,
) error {
const roleBindingName = "kargo-project-admin"
logger := logging.LoggerFromContext(ctx).WithFields(log.Fields{
"project": project.Name,
"name": project.Name,
"namespace": project.Name,
"roleBinding": roleBindingName,
})
roleBinding := &rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: roleBindingName,
Namespace: project.Name,
},
RoleRef: rbacv1.RoleRef{
APIGroup: rbacv1.GroupName,
Kind: "ClusterRole",
Name: "kargo-project-admin",
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: "kargo-api",
Namespace: w.cfg.KargoNamespace,
},
{
Kind: "ServiceAccount",
Name: "kargo-admin",
Namespace: w.cfg.KargoNamespace,
},
},
}
if err := w.createRoleBindingFn(ctx, roleBinding); err != nil {
if apierrors.IsAlreadyExists(err) {
logger.Debug("role binding already exists in project namespace")
return nil
}
return apierrors.NewInternalError(
fmt.Errorf(
"error creating role binding %q in project namespace %q: %w",
roleBinding.Name,
project.Name,
err,
),
)
}
logger.Debug("granted API server and kargo-admin project admin permissions")
return nil
}