-
Notifications
You must be signed in to change notification settings - Fork 759
/
match.go
323 lines (272 loc) Β· 10.1 KB
/
match.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
package match
import (
"errors"
"fmt"
"reflect"
"github.com/open-policy-agent/gatekeeper/pkg/mutation/types"
"github.com/open-policy-agent/gatekeeper/pkg/util"
corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"sigs.k8s.io/controller-runtime/pkg/client"
)
var ErrMatch = errors.New("failed to run Match criteria")
// Wildcard represents matching any Group, Version, or Kind.
// Only for use in Match, not ApplyTo.
const Wildcard = "*"
// Match selects objects to apply mutations to.
// +kubebuilder:object:generate=true
type Match struct {
// Source determines whether generated or original resources are matched.
// Accepts `Generated`|`Original`|`All` (defaults to `All`). A value of
// `Generated` will only match generated resources, while `Original` will only
// match regular resources.
// +kubebuilder:validation:Enum=All;Generated;Original
Source string `json:"source,omitempty"`
Kinds []Kinds `json:"kinds,omitempty"`
// Scope determines if cluster-scoped and/or namespaced-scoped resources
// are matched. Accepts `*`, `Cluster`, or `Namespaced`. (defaults to `*`)
Scope apiextensionsv1.ResourceScope `json:"scope,omitempty"`
// Namespaces is a list of namespace names. If defined, a constraint only
// applies to resources in a listed namespace. Namespaces also supports a
// prefix or suffix based glob. For example, `namespaces: [kube-*]` matches both
// `kube-system` and `kube-public`, and `namespaces: [*-system]` matches both
// `kube-system` and `gatekeeper-system`.
Namespaces []util.Wildcard `json:"namespaces,omitempty"`
// ExcludedNamespaces is a list of namespace names. If defined, a
// constraint only applies to resources not in a listed namespace.
// ExcludedNamespaces also supports a prefix or suffix based glob. For example,
// `excludedNamespaces: [kube-*]` matches both `kube-system` and
// `kube-public`, and `excludedNamespaces: [*-system]` matches both `kube-system` and
// `gatekeeper-system`.
ExcludedNamespaces []util.Wildcard `json:"excludedNamespaces,omitempty"`
// LabelSelector is the combination of two optional fields: `matchLabels`
// and `matchExpressions`. These two fields provide different methods of
// selecting or excluding k8s objects based on the label keys and values
// included in object metadata. All selection expressions from both
// sections are ANDed to determine if an object meets the cumulative
// requirements of the selector.
LabelSelector *metav1.LabelSelector `json:"labelSelector,omitempty"`
// NamespaceSelector is a label selector against an object's containing
// namespace or the object itself, if the object is a namespace.
NamespaceSelector *metav1.LabelSelector `json:"namespaceSelector,omitempty"`
// Name is the name of an object. If defined, it will match against objects with the specified
// name. Name also supports a prefix or suffix glob. For example, `name: pod-*` would match
// both `pod-a` and `pod-b`, and `name: *-pod` would match both `a-pod` and `b-pod`.
Name util.Wildcard `json:"name,omitempty"`
}
// Kinds accepts a list of objects with apiGroups and kinds fields
// that list the groups/kinds of objects to which the mutation will apply.
// If multiple groups/kinds objects are specified,
// only one match is needed for the resource to be in scope.
// +kubebuilder:object:generate=true
type Kinds struct {
// APIGroups is the API groups the resources belong to. '*' is all groups.
// If '*' is present, the length of the slice must be one.
// Required.
APIGroups []string `json:"apiGroups,omitempty" protobuf:"bytes,1,rep,name=apiGroups"`
Kinds []string `json:"kinds,omitempty"`
}
// Matchable represent an object to be matched along with its metadata.
type Matchable struct {
Object client.Object
Namespace *corev1.Namespace
Source types.SourceType
}
// Matches verifies if the given object belonging to the given namespace
// matches Match. Only returns true if all parts of the Match succeed.
func Matches(match *Match, target *Matchable) (bool, error) {
if reflect.ValueOf(target.Object).IsNil() {
// Simply checking if obj == nil is insufficient here.
// obj can be an interface pointer to nil, such as client.Object(nil), which
// is not equal to just "nil".
return false, fmt.Errorf("%w: obj must be non-nil", ErrMatch)
}
// We fail the match if any of these returns false.
topLevelMatchers := []matchFunc{
kindsMatch,
scopeMatch,
namespacesMatch,
excludedNamespacesMatch,
labelSelectorMatch,
namespaceSelectorMatch,
namesMatch,
sourceMatch,
}
for _, fn := range topLevelMatchers {
matches, err := fn(match, target)
if err != nil {
return false, fmt.Errorf("%w: %v", ErrMatch, err)
}
if !matches {
// One of the matchers didn't match, so we can exit early.
return false, nil
}
}
return true, nil
}
// matchFunc defines the matching logic of a Top Level Matcher. A TLM receives the match criteria,
// an object, and the namespace of the object and decides if there is a reason why the object does
// not match. If the TLM associated with the matching function is not defined by the user, the
// matchFunc should return true.
type matchFunc func(match *Match, target *Matchable) (bool, error)
func namespaceSelectorMatch(match *Match, target *Matchable) (bool, error) {
obj := target.Object
ns := target.Namespace
if match.NamespaceSelector == nil {
return true, nil
}
isNamespace := IsNamespace(obj)
if !isNamespace && ns == nil && obj.GetNamespace() == "" {
// Match all non-Namespace cluster-scoped objects.
return true, nil
}
selector, err := metav1.LabelSelectorAsSelector(match.NamespaceSelector)
if err != nil {
return false, err
}
if isNamespace {
return selector.Matches(labels.Set(obj.GetLabels())), nil
}
if ns == nil {
return false, fmt.Errorf("namespace selector for namespace-scoped object but missing Namespace")
}
return selector.Matches(labels.Set(ns.Labels)), nil
}
func labelSelectorMatch(match *Match, target *Matchable) (bool, error) {
obj := target.Object
if match.LabelSelector == nil {
return true, nil
}
selector, err := metav1.LabelSelectorAsSelector(match.LabelSelector)
if err != nil {
return false, err
}
return selector.Matches(labels.Set(obj.GetLabels())), nil
}
func excludedNamespacesMatch(match *Match, target *Matchable) (bool, error) {
obj := target.Object
ns := target.Namespace
// If we don't have a namespace, we can't disqualify the match
var namespace string
switch {
case len(match.ExcludedNamespaces) == 0:
return true, nil
case IsNamespace(obj):
namespace = obj.GetName()
case ns != nil:
namespace = ns.Name
case obj.GetNamespace() != "":
// Fall back to the Namespace the Object declares in case it isn't specified,
// such as for the gator CLI.
namespace = obj.GetNamespace()
default:
// obj is cluster-scoped and not a Namespace.
return true, nil
}
for _, n := range match.ExcludedNamespaces {
if n.Matches(namespace) {
return false, nil
}
}
return true, nil
}
func namespacesMatch(match *Match, target *Matchable) (bool, error) {
obj := target.Object
ns := target.Namespace
// If we don't have a namespace, we can't disqualify the match
var namespace string
switch {
case len(match.Namespaces) == 0:
return true, nil
case IsNamespace(obj):
namespace = obj.GetName()
case ns != nil:
namespace = ns.Name
case obj.GetNamespace() != "":
// Fall back to the Namespace the Object declares in case it isn't specified,
// such as for the gator CLI.
namespace = obj.GetNamespace()
default:
return true, nil
}
for _, n := range match.Namespaces {
if n.Matches(namespace) {
return true, nil
}
}
return false, nil
}
func kindsMatch(match *Match, target *Matchable) (bool, error) {
if len(match.Kinds) == 0 {
return true, nil
}
gvk := target.Object.GetObjectKind().GroupVersionKind()
for _, kk := range match.Kinds {
kindMatches := len(kk.Kinds) == 0 || contains(kk.Kinds, Wildcard) || contains(kk.Kinds, gvk.Kind)
if !kindMatches {
continue
}
groupMatches := len(kk.APIGroups) == 0 || contains(kk.APIGroups, Wildcard) || contains(kk.APIGroups, gvk.Group)
if groupMatches {
return true, nil
}
}
return false, nil
}
func namesMatch(match *Match, target *Matchable) (bool, error) {
// A blank string could be undefined or an intentional blank string by the user. Either way,
// we will assume this means "any name". This goes with the undefined == match everything
// pattern that we've already got going in the Match.
if match.Name == "" {
return true, nil
}
return match.Name.Matches(target.Object.GetName()), nil
}
func scopeMatch(match *Match, target *Matchable) (bool, error) {
hasNamespace := target.Object.GetNamespace() != "" || target.Namespace != nil
isNamespace := IsNamespace(target.Object)
switch match.Scope {
case apiextensionsv1.ClusterScoped:
return isNamespace || !hasNamespace, nil
case apiextensionsv1.NamespaceScoped:
return !isNamespace && hasNamespace, nil
default:
// This includes invalid scopes, such as typos like "cluster" or "Namespace".
return true, nil
}
}
func sourceMatch(match *Match, target *Matchable) (bool, error) {
mSrc := types.SourceType(match.Source)
tSrc := target.Source
// An empty 'source' field will default to 'All'
if mSrc == "" {
mSrc = types.SourceTypeDefault
} else if !types.IsValidSource(mSrc) {
return false, fmt.Errorf("invalid source field %q", mSrc)
}
if tSrc == "" && mSrc != types.SourceTypeAll {
return false, fmt.Errorf("source field not specified for resource %s", target.Object.GetName())
}
if mSrc == types.SourceTypeAll {
return true, nil
}
if !types.IsValidSource(tSrc) {
return false, fmt.Errorf("invalid source field %q", tSrc)
}
return mSrc == tSrc, nil
}
func IsNamespace(obj client.Object) bool {
return obj.GetObjectKind().GroupVersionKind().Kind == "Namespace" &&
obj.GetObjectKind().GroupVersionKind().Group == ""
}
// contains returns true is element is in set.
func contains(set []string, element string) bool {
for _, s := range set {
if s == element {
return true
}
}
return false
}