/
trigger_validation.go
276 lines (250 loc) · 7.82 KB
/
trigger_validation.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
/*
Copyright 2020 The Knative 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 v1
import (
"context"
"encoding/json"
"fmt"
"regexp"
cesqlparser "github.com/cloudevents/sdk-go/sql/v2/parser"
"go.uber.org/zap"
corev1 "k8s.io/api/core/v1"
"knative.dev/pkg/apis"
"knative.dev/pkg/kmp"
"knative.dev/pkg/logging"
"knative.dev/eventing/pkg/apis/feature"
)
var (
// Only allow lowercase alphanumeric, starting with letters.
validAttributeName = regexp.MustCompile(`^[a-z][a-z0-9]*$`)
)
// Validate the Trigger.
func (t *Trigger) Validate(ctx context.Context) *apis.FieldError {
errs := t.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec")
errs = t.validateAnnotation(errs, DependencyAnnotation, t.validateDependencyAnnotation)
errs = t.validateAnnotation(errs, InjectionAnnotation, t.validateInjectionAnnotation)
if apis.IsInUpdate(ctx) {
original := apis.GetBaseline(ctx).(*Trigger)
errs = errs.Also(t.CheckImmutableFields(ctx, original))
}
return errs
}
// Validate the TriggerSpec.
func (ts *TriggerSpec) Validate(ctx context.Context) (errs *apis.FieldError) {
if ts.Broker == "" {
errs = errs.Also(apis.ErrMissingField("broker"))
}
return errs.Also(
ValidateAttributeFilters(ts.Filter).ViaField("filter"),
).Also(
ValidateSubscriptionAPIFiltersList(ctx, ts.Filters).ViaField("filters"),
).Also(
ts.Subscriber.Validate(ctx).ViaField("subscriber"),
).Also(
ts.Delivery.Validate(ctx).ViaField("delivery"),
)
}
// CheckImmutableFields checks that any immutable fields were not changed.
func (t *Trigger) CheckImmutableFields(ctx context.Context, original *Trigger) *apis.FieldError {
if original == nil {
return nil
}
if diff, err := kmp.ShortDiff(original.Spec.Broker, t.Spec.Broker); err != nil {
return &apis.FieldError{
Message: "Failed to diff Trigger",
Paths: []string{"spec"},
Details: err.Error(),
}
} else if diff != "" {
return &apis.FieldError{
Message: "Immutable fields changed (-old +new)",
Paths: []string{"spec", "broker"},
Details: diff,
}
}
return nil
}
func GetObjRefFromDependencyAnnotation(dependencyAnnotation string) (corev1.ObjectReference, error) {
var objectRef corev1.ObjectReference
if err := json.Unmarshal([]byte(dependencyAnnotation), &objectRef); err != nil {
return objectRef, err
}
return objectRef, nil
}
func (t *Trigger) validateAnnotation(errs *apis.FieldError, annotation string, function func(string) *apis.FieldError) *apis.FieldError {
if annotationValue, ok := t.GetAnnotations()[annotation]; ok {
annotationPrefix := fmt.Sprintf("metadata.annotations[%s]", annotation)
errs = errs.Also(function(annotationValue).ViaField(annotationPrefix))
}
return errs
}
func (t *Trigger) validateDependencyAnnotation(dependencyAnnotation string) *apis.FieldError {
depObjRef, err := GetObjRefFromDependencyAnnotation(dependencyAnnotation)
if err != nil {
return &apis.FieldError{
Message: fmt.Sprintf("The provided annotation was not a corev1.ObjectReference: %q", dependencyAnnotation),
Details: err.Error(),
Paths: []string{""},
}
}
var errs *apis.FieldError
if depObjRef.Namespace != "" && depObjRef.Namespace != t.GetNamespace() {
fe := &apis.FieldError{
Message: fmt.Sprintf("Namespace must be empty or equal to the trigger namespace %q", t.GetNamespace()),
Paths: []string{"namespace"},
}
errs = errs.Also(fe)
}
if depObjRef.Kind == "" {
fe := apis.ErrMissingField("kind")
errs = errs.Also(fe)
}
if depObjRef.Name == "" {
fe := apis.ErrMissingField("name")
errs = errs.Also(fe)
}
if depObjRef.APIVersion == "" {
fe := apis.ErrMissingField("apiVersion")
errs = errs.Also(fe)
}
return errs
}
func (t *Trigger) validateInjectionAnnotation(injectionAnnotation string) *apis.FieldError {
if injectionAnnotation != "enabled" && injectionAnnotation != "disabled" {
return &apis.FieldError{
Message: fmt.Sprintf(`The provided injection annotation value can only be "enabled" or "disabled", not %q`, injectionAnnotation),
Paths: []string{""},
}
}
if t.Spec.Broker != "default" {
return &apis.FieldError{
Message: fmt.Sprintf("The provided injection annotation is only used for default broker, but non-default broker specified here: %q", t.Spec.Broker),
Paths: []string{""},
}
}
return nil
}
func ValidateAttributeFilters(filter *TriggerFilter) (errs *apis.FieldError) {
if filter == nil {
return nil
}
return errs.Also(ValidateAttributesNames(filter.Attributes).ViaField("attributes"))
}
func ValidateAttributesNames(attrs map[string]string) (errs *apis.FieldError) {
for attr := range attrs {
if !validAttributeName.MatchString(attr) {
errs = errs.Also(apis.ErrInvalidKeyName(attr, apis.CurrentField, "Attribute name must start with a letter and can only contain lowercase alphanumeric").ViaKey(attr))
}
}
return errs
}
func ValidateSubscriptionAPIFiltersList(ctx context.Context, filters []SubscriptionsAPIFilter) (errs *apis.FieldError) {
if filters == nil || !feature.FromContext(ctx).IsEnabled(feature.NewTriggerFilters) {
return nil
}
for i, f := range filters {
f := f
errs = errs.Also(ValidateSubscriptionAPIFilter(ctx, &f)).ViaIndex(i)
}
return errs
}
func ValidateCESQLExpression(ctx context.Context, expression string) (errs *apis.FieldError) {
if expression == "" {
return nil
}
// Need to recover in case Parse panics
defer func() {
if r := recover(); r != nil {
logging.FromContext(ctx).Debug("Warning! Calling CESQL Parser panicked. Treating expression as invalid.", zap.Any("recovered value", r), zap.String("CESQL", expression))
errs = apis.ErrInvalidValue(expression, apis.CurrentField)
}
}()
if _, err := cesqlparser.Parse(expression); err != nil {
return apis.ErrInvalidValue(expression, apis.CurrentField, err.Error())
}
return nil
}
func ValidateSubscriptionAPIFilter(ctx context.Context, filter *SubscriptionsAPIFilter) (errs *apis.FieldError) {
if filter == nil {
return nil
}
errs = errs.Also(
ValidateOneOf(filter),
).Also(
ValidateAttributesNames(filter.Exact).ViaField("exact"),
).Also(
ValidateAttributesNames(filter.Prefix).ViaField("prefix"),
).Also(
ValidateAttributesNames(filter.Suffix).ViaField("suffix"),
).Also(
ValidateSubscriptionAPIFiltersList(ctx, filter.All).ViaField("all"),
).Also(
ValidateSubscriptionAPIFiltersList(ctx, filter.Any).ViaField("any"),
).Also(
ValidateSubscriptionAPIFilter(ctx, filter.Not).ViaField("not"),
).Also(
ValidateCESQLExpression(ctx, filter.CESQL).ViaField("cesql"),
)
return errs
}
func ValidateOneOf(filter *SubscriptionsAPIFilter) (err *apis.FieldError) {
if filter != nil && hasMultipleDialects(filter) {
return apis.ErrGeneric("multiple dialects found, filters can have only one dialect set")
}
return nil
}
func hasMultipleDialects(filter *SubscriptionsAPIFilter) bool {
dialectFound := false
if len(filter.Exact) > 0 {
dialectFound = true
}
if len(filter.Prefix) > 0 {
if dialectFound {
return true
} else {
dialectFound = true
}
}
if len(filter.Suffix) > 0 {
if dialectFound {
return true
} else {
dialectFound = true
}
}
if len(filter.All) > 0 {
if dialectFound {
return true
} else {
dialectFound = true
}
}
if len(filter.Any) > 0 {
if dialectFound {
return true
} else {
dialectFound = true
}
}
if filter.Not != nil {
if dialectFound {
return true
} else {
dialectFound = true
}
}
if filter.CESQL != "" && dialectFound {
return true
}
return false
}