-
Notifications
You must be signed in to change notification settings - Fork 117
/
webhook.go
320 lines (290 loc) · 7.84 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
package warehouse
import (
"context"
"fmt"
"strings"
"github.com/Masterminds/semver/v3"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"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/webhook/admission"
kargoapi "github.com/akuity/kargo/api/v1alpha1"
"github.com/akuity/kargo/internal/git"
"github.com/akuity/kargo/internal/helm"
"github.com/akuity/kargo/internal/image"
libWebhook "github.com/akuity/kargo/internal/webhook"
)
var warehouseGroupKind = schema.GroupKind{
Group: kargoapi.GroupVersion.Group,
Kind: "Warehouse",
}
type webhook struct {
client client.Client
// The following behaviors are overridable for testing purposes:
validateProjectFn func(
context.Context,
client.Client,
schema.GroupKind,
client.Object,
) error
validateCreateOrUpdateFn func(*kargoapi.Warehouse) (admission.Warnings, error)
validateSpecFn func(*field.Path, *kargoapi.WarehouseSpec) field.ErrorList
}
func SetupWebhookWithManager(mgr ctrl.Manager) error {
w := newWebhook(mgr.GetClient())
return ctrl.NewWebhookManagedBy(mgr).
For(&kargoapi.Warehouse{}).
WithDefaulter(w).
WithValidator(w).
Complete()
}
func newWebhook(kubeClient client.Client) *webhook {
w := &webhook{
client: kubeClient,
}
w.validateProjectFn = libWebhook.ValidateProject
w.validateCreateOrUpdateFn = w.validateCreateOrUpdate
w.validateSpecFn = w.validateSpec
return w
}
func (w *webhook) Default(_ context.Context, obj runtime.Object) error {
warehouse := obj.(*kargoapi.Warehouse) // nolint: forcetypeassert
// Sync the shard label to the convenience shard field
if warehouse.Spec.Shard != "" {
if warehouse.Labels == nil {
warehouse.Labels = make(map[string]string, 1)
}
warehouse.Labels[kargoapi.ShardLabelKey] = warehouse.Spec.Shard
} else {
delete(warehouse.Labels, kargoapi.ShardLabelKey)
}
return nil
}
func (w *webhook) ValidateCreate(
ctx context.Context,
obj runtime.Object,
) (admission.Warnings, error) {
warehouse := obj.(*kargoapi.Warehouse) // nolint: forcetypeassert
if err := w.validateProjectFn(
ctx,
w.client,
warehouseGroupKind,
warehouse,
); err != nil {
return nil, err
}
return w.validateCreateOrUpdateFn(warehouse)
}
func (w *webhook) ValidateUpdate(
_ context.Context,
_ runtime.Object,
newObj runtime.Object,
) (admission.Warnings, error) {
warehouse := newObj.(*kargoapi.Warehouse) // nolint: forcetypeassert
return w.validateCreateOrUpdateFn(warehouse)
}
func (w *webhook) ValidateDelete(
context.Context,
runtime.Object,
) (admission.Warnings, error) {
// No-op
return nil, nil
}
func (w *webhook) validateCreateOrUpdate(
warehouse *kargoapi.Warehouse,
) (admission.Warnings, error) {
if errs :=
w.validateSpecFn(field.NewPath("spec"), &warehouse.Spec); len(errs) > 0 {
return nil, apierrors.NewInvalid(warehouseGroupKind, warehouse.Name, errs)
}
return nil, nil
}
func (w *webhook) validateSpec(
f *field.Path,
spec *kargoapi.WarehouseSpec,
) field.ErrorList {
if spec == nil { // nil spec is caught by declarative validations
return nil
}
return w.validateSubs(f.Child("subscriptions"), spec.Subscriptions)
}
func (w *webhook) validateSubs(
f *field.Path,
subs []kargoapi.RepoSubscription,
) field.ErrorList {
if len(subs) == 0 {
return nil
}
var errs field.ErrorList
seen := make(uniqueSubSet, len(subs))
for i, sub := range subs {
errs = append(errs, w.validateSub(f.Index(i), sub, seen)...)
}
return errs
}
func (w *webhook) validateSub(
f *field.Path,
sub kargoapi.RepoSubscription,
seen uniqueSubSet,
) field.ErrorList {
var errs field.ErrorList
var repoTypes int
if sub.Git != nil {
repoTypes++
errs = append(errs, w.validateGitSub(f.Child("git"), *sub.Git, seen)...)
}
if sub.Image != nil {
repoTypes++
errs = append(errs, w.validateImageSub(f.Child("image"), *sub.Image, seen)...)
}
if sub.Chart != nil {
repoTypes++
errs = append(errs, w.validateChartSub(f.Child("chart"), *sub.Chart, seen)...)
}
if repoTypes != 1 {
errs = append(
errs,
field.Invalid(
f,
sub,
fmt.Sprintf(
"exactly one of %s.git, %s.image, or %s.chart must be non-empty",
f.String(),
f.String(),
f.String(),
),
),
)
}
return errs
}
func (w *webhook) validateGitSub(
f *field.Path,
sub kargoapi.GitSubscription,
seen uniqueSubSet,
) field.ErrorList {
var errs field.ErrorList
if err := validateSemverConstraint(
f.Child("semverConstraint"),
sub.SemverConstraint,
); err != nil {
errs = append(errs, err)
}
if err := seen.addGit(sub, f); err != nil {
errs = append(errs, field.Invalid(f, sub.RepoURL, err.Error()))
}
return errs
}
func (w *webhook) validateImageSub(
f *field.Path,
sub kargoapi.ImageSubscription,
seen uniqueSubSet,
) field.ErrorList {
var errs field.ErrorList
if err := validateSemverConstraint(
f.Child("semverConstraint"),
sub.SemverConstraint,
); err != nil {
errs = field.ErrorList{err}
}
if sub.Platform != "" {
if !image.ValidatePlatformConstraint(sub.Platform) {
errs = append(errs, field.Invalid(f.Child("platform"), sub.Platform, ""))
}
}
if err := seen.addImage(sub, f); err != nil {
errs = append(errs, field.Invalid(f, sub.RepoURL, err.Error()))
}
return errs
}
func (w *webhook) validateChartSub(
f *field.Path,
sub kargoapi.ChartSubscription,
seen uniqueSubSet,
) field.ErrorList {
var errs field.ErrorList
if err := validateSemverConstraint(
f.Child("semverConstraint"),
sub.SemverConstraint,
); err != nil {
errs = append(errs, err)
}
if strings.HasPrefix(sub.RepoURL, "oci://") && sub.Name != "" {
errs = append(
errs,
field.Invalid(
f.Child("name"),
sub.Name,
"must be empty if repoURL starts with oci://",
),
)
}
isHTTP := strings.HasPrefix(sub.RepoURL, "http://") || strings.HasPrefix(sub.RepoURL, "https://")
if isHTTP && sub.Name == "" {
errs = append(
errs,
field.Invalid(
f.Child("name"),
sub.Name,
"must be non-empty if repoURL starts with http:// or https://",
),
)
}
if err := seen.addChart(sub, isHTTP, f); err != nil {
errs = append(errs, field.Invalid(f, sub.RepoURL, err.Error()))
}
return errs
}
func validateSemverConstraint(
f *field.Path,
semverConstraint string,
) *field.Error {
if semverConstraint == "" {
return nil
}
if _, err := semver.NewConstraint(semverConstraint); err != nil {
return field.Invalid(f, semverConstraint, "")
}
return nil
}
type subscriptionKey struct {
kind string
id string
}
type uniqueSubSet map[subscriptionKey]*field.Path
func (s uniqueSubSet) addGit(sub kargoapi.GitSubscription, p *field.Path) error {
k := subscriptionKey{kind: "git", id: git.NormalizeURL(sub.RepoURL)}
if _, exists := s[k]; exists {
return fmt.Errorf("subscription for Git repository already exists at %q", s[k])
}
s[k] = p
return nil
}
func (s uniqueSubSet) addImage(sub kargoapi.ImageSubscription, p *field.Path) error {
// The normalization of Helm chart repository URLs can also be used here
// to ensure the uniqueness of the image reference as it does the job of
// ensuring lower-casing, etc. without introducing unwanted side effects.
k := subscriptionKey{kind: "image", id: helm.NormalizeChartRepositoryURL(sub.RepoURL)}
if _, exists := s[k]; exists {
return fmt.Errorf("subscription for image repository already exists at %q", s[k])
}
s[k] = p
return nil
}
func (s uniqueSubSet) addChart(sub kargoapi.ChartSubscription, isHTTP bool, p *field.Path) error {
k := subscriptionKey{kind: "chart", id: helm.NormalizeChartRepositoryURL(sub.RepoURL)}
if isHTTP {
k.id = k.id + ":" + sub.Name
}
if _, exists := s[k]; exists {
if isHTTP {
return fmt.Errorf("subscription for chart %q already exists at %q", sub.Name, s[k])
}
return fmt.Errorf("subscription for chart already exists at %q", s[k])
}
s[k] = p
return nil
}