/
matcher.go
93 lines (77 loc) 路 2.35 KB
/
matcher.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
package target
import (
"fmt"
"github.com/open-policy-agent/frameworks/constraint/pkg/core/constraints"
"github.com/open-policy-agent/gatekeeper/v3/pkg/mutation/match"
"github.com/open-policy-agent/gatekeeper/v3/pkg/mutation/types"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
var _ constraints.Matcher = &Matcher{}
// Matcher implements constraint.Matcher.
type Matcher struct {
match *match.Match
cache *nsCache
}
func (m *Matcher) Match(review interface{}) (bool, error) {
if m.match == nil {
// No-op if Match unspecified.
return true, nil
}
gkReq, ok := review.(*gkReview)
if !ok {
return false, fmt.Errorf("%w: expect %T, got %T", ErrReviewFormat, &gkReview{}, review)
}
obj, oldObj, ns, err := gkReviewToObject(gkReq)
if err != nil {
return false, err
}
if (ns == nil) && (gkReq.Namespace != "") {
ns = m.cache.GetNamespace(gkReq.Namespace)
}
return matchAny(m, ns, gkReq.source, obj, oldObj)
}
func matchAny(m *Matcher, ns *corev1.Namespace, source types.SourceType, objs ...*unstructured.Unstructured) (bool, error) {
nilObj := 0
for _, obj := range objs {
if obj == nil || obj.Object == nil {
nilObj++
continue
}
t := &match.Matchable{
Object: obj,
Namespace: ns,
Source: source,
}
matched, err := match.Matches(m.match, t)
if err != nil {
return false, fmt.Errorf("%w: %v :%w", ErrMatching, obj.GetName(), err)
}
if matched {
return true, nil
}
}
if nilObj == len(objs) {
return false, fmt.Errorf("%w: neither object nor old object are defined", ErrRequestObject)
}
return false, nil
}
func gkReviewToObject(req *gkReview) (*unstructured.Unstructured, *unstructured.Unstructured, *corev1.Namespace, error) {
var obj *unstructured.Unstructured
if req.Object.Raw != nil {
obj = &unstructured.Unstructured{}
err := obj.UnmarshalJSON(req.Object.Raw)
if err != nil {
return nil, nil, nil, fmt.Errorf("%w: failed to unmarshal gkReview object %s", ErrRequestObject, string(req.Object.Raw))
}
}
var oldObj *unstructured.Unstructured
if req.OldObject.Raw != nil {
oldObj = &unstructured.Unstructured{}
err := oldObj.UnmarshalJSON(req.OldObject.Raw)
if err != nil {
return nil, nil, nil, fmt.Errorf("%w: failed to unmarshal gkReview oldObject %s", ErrRequestObject, string(req.OldObject.Raw))
}
}
return obj, oldObj, req.namespace, nil
}