-
Notifications
You must be signed in to change notification settings - Fork 805
/
validate_audit.go
228 lines (191 loc) · 6.85 KB
/
validate_audit.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
package webhooks
import (
"github.com/kyverno/kyverno/pkg/engine"
"github.com/kyverno/kyverno/pkg/utils"
"strings"
"time"
"github.com/pkg/errors"
"github.com/kyverno/kyverno/pkg/common"
client "github.com/kyverno/kyverno/pkg/dclient"
"github.com/go-logr/logr"
v1 "github.com/kyverno/kyverno/pkg/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/config"
"github.com/kyverno/kyverno/pkg/event"
"github.com/kyverno/kyverno/pkg/metrics"
"github.com/kyverno/kyverno/pkg/policycache"
"github.com/kyverno/kyverno/pkg/policyreport"
"github.com/kyverno/kyverno/pkg/resourcecache"
"github.com/kyverno/kyverno/pkg/userinfo"
"k8s.io/api/admission/v1beta1"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
informers "k8s.io/client-go/informers/core/v1"
rbacinformer "k8s.io/client-go/informers/rbac/v1"
listerv1 "k8s.io/client-go/listers/core/v1"
rbaclister "k8s.io/client-go/listers/rbac/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
)
const (
workQueueName = "validate-audit-handler"
workQueueRetryLimit = 3
)
// AuditHandler applies validate audit policies to the admission request
// the handler adds the request to the work queue and returns immediately
// the request is processed in background, with the exact same logic
// when process the admission request in the webhook
type AuditHandler interface {
Add(request *v1beta1.AdmissionRequest)
Run(workers int, stopCh <-chan struct{})
}
type auditHandler struct {
client *client.Client
queue workqueue.RateLimitingInterface
pCache policycache.Interface
eventGen event.Interface
prGenerator policyreport.GeneratorInterface
rbLister rbaclister.RoleBindingLister
rbSynced cache.InformerSynced
crbLister rbaclister.ClusterRoleBindingLister
crbSynced cache.InformerSynced
nsLister listerv1.NamespaceLister
nsListerSynced cache.InformerSynced
log logr.Logger
configHandler config.Interface
resCache resourcecache.ResourceCache
promConfig *metrics.PromConfig
}
// NewValidateAuditHandler returns a new instance of audit policy handler
func NewValidateAuditHandler(pCache policycache.Interface,
eventGen event.Interface,
prGenerator policyreport.GeneratorInterface,
rbInformer rbacinformer.RoleBindingInformer,
crbInformer rbacinformer.ClusterRoleBindingInformer,
namespaces informers.NamespaceInformer,
log logr.Logger,
dynamicConfig config.Interface,
resCache resourcecache.ResourceCache,
client *client.Client,
promConfig *metrics.PromConfig) AuditHandler {
return &auditHandler{
pCache: pCache,
queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), workQueueName),
eventGen: eventGen,
rbLister: rbInformer.Lister(),
rbSynced: rbInformer.Informer().HasSynced,
crbLister: crbInformer.Lister(),
crbSynced: crbInformer.Informer().HasSynced,
nsLister: namespaces.Lister(),
nsListerSynced: namespaces.Informer().HasSynced,
log: log,
prGenerator: prGenerator,
configHandler: dynamicConfig,
resCache: resCache,
client: client,
promConfig: promConfig,
}
}
func (h *auditHandler) Add(request *v1beta1.AdmissionRequest) {
h.log.V(4).Info("admission request added", "uid", request.UID, "kind", request.Kind.Kind, "namespace", request.Namespace, "name", request.Name, "operation", request.Operation)
h.queue.Add(request)
}
func (h *auditHandler) Run(workers int, stopCh <-chan struct{}) {
h.log.V(4).Info("starting")
defer func() {
utilruntime.HandleCrash()
h.log.V(4).Info("shutting down")
}()
if !cache.WaitForCacheSync(stopCh, h.rbSynced, h.crbSynced) {
h.log.Info("failed to sync informer cache")
}
for i := 0; i < workers; i++ {
go wait.Until(h.runWorker, time.Second, stopCh)
}
<-stopCh
}
func (h *auditHandler) runWorker() {
for h.processNextWorkItem() {
}
}
func (h *auditHandler) processNextWorkItem() bool {
obj, shutdown := h.queue.Get()
if shutdown {
return false
}
defer h.queue.Done(obj)
request, ok := obj.(*v1beta1.AdmissionRequest)
if !ok {
h.queue.Forget(obj)
h.log.Info("incorrect type: expecting type 'AdmissionRequest'", "object", obj)
return true
}
err := h.process(request)
h.handleErr(err, obj, request)
return true
}
func (h *auditHandler) process(request *v1beta1.AdmissionRequest) error {
var roles, clusterRoles []string
var err error
// time at which the corresponding the admission request's processing got initiated
admissionRequestTimestamp := time.Now().Unix()
logger := h.log.WithName("process")
policies := h.pCache.GetPolicies(policycache.ValidateAudit, request.Kind.Kind, request.Namespace)
// getRoleRef only if policy has roles/clusterroles defined
if containsRBACInfo(policies) {
roles, clusterRoles, err = userinfo.GetRoleRef(h.rbLister, h.crbLister, request, h.configHandler)
if err != nil {
logger.Error(err, "failed to get RBAC information for request")
}
}
userRequestInfo := v1.RequestInfo{
Roles: roles,
ClusterRoles: clusterRoles,
AdmissionUserInfo: request.UserInfo}
ctx, err := newVariablesContext(request, &userRequestInfo)
if err != nil {
return errors.Wrap(err, "unable to build variable context")
}
namespaceLabels := make(map[string]string)
if request.Kind.Kind != "Namespace" && request.Namespace != "" {
namespaceLabels = common.GetNamespaceSelectorsFromNamespaceLister(request.Kind.Kind, request.Namespace, h.nsLister, logger)
}
newResource, oldResource, err := utils.ExtractResources(nil, request)
if err != nil {
return errors.Wrap(err, "failed create parse resource")
}
if err := ctx.AddImageInfo(&newResource); err != nil {
return errors.Wrap(err, "failed add image information to policy rule context\"")
}
policyContext := &engine.PolicyContext{
NewResource: newResource,
OldResource: oldResource,
AdmissionInfo: userRequestInfo,
ExcludeGroupRole: h.configHandler.GetExcludeGroupRole(),
ExcludeResourceFunc: h.configHandler.ToFilter,
ResourceCache: h.resCache,
JSONContext: ctx,
Client: h.client,
}
vh := &validationHandler{
log: h.log,
eventGen: h.eventGen,
prGenerator: h.prGenerator,
}
vh.handleValidation(h.promConfig, request, policies, policyContext, namespaceLabels, admissionRequestTimestamp)
return nil
}
func (h *auditHandler) handleErr(err error, key interface{}, request *v1beta1.AdmissionRequest) {
logger := h.log.WithName("handleErr")
if err == nil {
h.queue.Forget(key)
return
}
k := strings.Join([]string{request.Kind.Kind, request.Namespace, request.Name}, "/")
if h.queue.NumRequeues(key) < workQueueRetryLimit {
logger.V(3).Info("retrying processing admission request", "key", k, "error", err.Error())
h.queue.AddRateLimited(key)
return
}
logger.Error(err, "failed to process admission request", "key", k)
h.queue.Forget(key)
}