/
mutatingwebhook.go
254 lines (219 loc) · 8.25 KB
/
mutatingwebhook.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
package mutatingwebhook
// Much of this code comes from https://github.com/knative/pkg/blob/f5c1a03ab4f1efa8642fc7021960c1b86da5613f/webhook/resourcesemantics/defaulting/defaulting.go
// Upstream support for a generic admission webhook is tracked in https://github.com/knative/pkg/issues/2644
import (
"context"
"fmt"
"log"
"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1beta1"
"go.uber.org/zap"
"gomodules.xyz/jsonpatch/v2"
admissionv1 "k8s.io/api/admission/v1"
admissionregistrationv1 "k8s.io/api/admissionregistration/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes"
admissionlisters "k8s.io/client-go/listers/admissionregistration/v1"
corelisters "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
defaultconfig "github.com/tektoncd/experimental/concurrency/pkg/apis/config"
kubeclient "knative.dev/pkg/client/injection/kube/client"
mwhinformer "knative.dev/pkg/client/injection/kube/informers/admissionregistration/v1/mutatingwebhookconfiguration"
"knative.dev/pkg/controller"
secretinformer "knative.dev/pkg/injection/clients/namespacedkube/informers/core/v1/secret"
"knative.dev/pkg/kmp"
"knative.dev/pkg/logging"
"knative.dev/pkg/ptr"
pkgreconciler "knative.dev/pkg/reconciler"
"knative.dev/pkg/system"
"knative.dev/pkg/webhook"
certresources "knative.dev/pkg/webhook/certificates/resources"
"knative.dev/pkg/webhook/json"
)
var (
pendPipelineRunPatchBytes []byte
)
func init() {
var err error
pendPipelineRunPatchBytes, err = json.Marshal([]jsonpatch.JsonPatchOperation{
{
Operation: "add",
Path: "/spec/status",
Value: v1beta1.PipelineRunSpecStatusPending,
}, {
Operation: "add",
Path: "/metadata/labels/tekton.dev~1ok-to-start", // ~1 is used to escape "/" characters in keys
Value: "true",
}})
if err != nil {
log.Fatalf("failed to marshal PipelineRun patch bytes: %v", err)
}
}
// NewAdmissionController constructs a reconciler
func NewAdmissionController(
ctx context.Context,
name, path string,
wc func(context.Context) context.Context,
) *controller.Impl {
client := kubeclient.Get(ctx)
mwhInformer := mwhinformer.Get(ctx)
secretInformer := secretinformer.Get(ctx)
options := webhook.GetOptions(ctx)
key := types.NamespacedName{Name: name}
wh := &reconciler{
LeaderAwareFuncs: pkgreconciler.LeaderAwareFuncs{
// Have this reconciler enqueue our singleton whenever it becomes leader.
PromoteFunc: func(bkt pkgreconciler.Bucket, enq func(pkgreconciler.Bucket, types.NamespacedName)) error {
enq(bkt, key)
return nil
},
},
key: key,
path: path,
withContext: wc,
secretName: options.SecretName,
client: client,
mwhlister: mwhInformer.Lister(),
secretlister: secretInformer.Lister(),
}
logger := logging.FromContext(ctx)
const queueName = "MutatingWebhook"
c := controller.NewContext(ctx, wh, controller.ControllerOptions{WorkQueueName: queueName, Logger: logger.Named(queueName)})
// Reconcile when the named MutatingWebhookConfiguration changes.
mwhInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: controller.FilterWithName(name),
// It doesn't matter what we enqueue because we will always Reconcile
// the named MWH resource.
Handler: controller.HandleAll(c.Enqueue),
})
// Reconcile when the cert bundle changes.
secretInformer.Informer().AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: controller.FilterWithNameAndNamespace(system.Namespace(), wh.secretName),
// It doesn't matter what we enqueue because we will always Reconcile
// the named MWH resource.
Handler: controller.HandleAll(c.Enqueue),
})
return c
}
// reconciler implements the AdmissionController for resources
type reconciler struct {
webhook.StatelessAdmissionImpl
pkgreconciler.LeaderAwareFuncs
key types.NamespacedName
path string
withContext func(context.Context) context.Context
client kubernetes.Interface
mwhlister admissionlisters.MutatingWebhookConfigurationLister
secretlister corelisters.SecretLister
secretName string
}
var _ controller.Reconciler = (*reconciler)(nil)
var _ pkgreconciler.LeaderAware = (*reconciler)(nil)
var _ webhook.AdmissionController = (*reconciler)(nil)
var _ webhook.StatelessAdmissionController = (*reconciler)(nil)
// Reconcile implements controller.Reconciler
func (ac *reconciler) Reconcile(ctx context.Context, key string) error {
logger := logging.FromContext(ctx)
if !ac.IsLeaderFor(ac.key) {
return controller.NewSkipKey(key)
}
// Look up the webhook secret, and fetch the CA cert bundle.
secret, err := ac.secretlister.Secrets(system.Namespace()).Get(ac.secretName)
if err != nil {
logger.Errorw("Error fetching secret", zap.Error(err))
return err
}
caCert, ok := secret.Data[certresources.CACert]
if !ok {
return fmt.Errorf("secret %q is missing %q key", ac.secretName, certresources.CACert)
}
// Reconcile the webhook configuration.
return ac.reconcileMutatingWebhook(ctx, caCert)
}
// Path implements AdmissionController
func (ac *reconciler) Path() string {
return ac.path
}
// Admit implements AdmissionController
func (ac *reconciler) Admit(ctx context.Context, request *admissionv1.AdmissionRequest) *admissionv1.AdmissionResponse {
if ac.withContext != nil {
ctx = ac.withContext(ctx)
}
logger := logging.FromContext(ctx)
cfg := defaultconfig.FromContext(ctx)
if len(cfg.AllowedNamespaces) > 0 && !cfg.AllowedNamespaces.Has(request.Namespace) {
logger.Infof("PipelineRun %s/%s is not in an allowed namespace, skipping concurrency controls", request.Namespace, request.Name)
return &admissionv1.AdmissionResponse{Allowed: true}
} else {
logger.Infof("PipelineRun %s/%s is in an allowed namespace, applying concurrency controls", request.Namespace, request.Name)
}
return &admissionv1.AdmissionResponse{
Patch: pendPipelineRunPatchBytes,
Allowed: true,
PatchType: func() *admissionv1.PatchType {
pt := admissionv1.PatchTypeJSONPatch
return &pt
}(),
}
}
func (ac *reconciler) reconcileMutatingWebhook(ctx context.Context, caCert []byte) error {
logger := logging.FromContext(ctx)
rules := []admissionregistrationv1.RuleWithOperations{{
Operations: []admissionregistrationv1.OperationType{
admissionregistrationv1.Create,
},
Rule: admissionregistrationv1.Rule{
APIGroups: []string{"tekton.dev"},
APIVersions: []string{"v1beta1"},
Resources: []string{"pipelineruns"},
},
}}
configuredWebhook, err := ac.mwhlister.Get(ac.key.Name)
if err != nil {
return fmt.Errorf("error retrieving webhook: %w", err)
}
current := configuredWebhook.DeepCopy()
ns, err := ac.client.CoreV1().Namespaces().Get(ctx, system.Namespace(), metav1.GetOptions{})
if err != nil {
return fmt.Errorf("failed to fetch namespace: %w", err)
}
nsRef := *metav1.NewControllerRef(ns, corev1.SchemeGroupVersion.WithKind("Namespace"))
current.OwnerReferences = []metav1.OwnerReference{nsRef}
for i, wh := range current.Webhooks {
if wh.Name != current.Name {
continue
}
cur := ¤t.Webhooks[i]
cur.Rules = rules
cur.NamespaceSelector = webhook.EnsureLabelSelectorExpressions(
cur.NamespaceSelector,
&metav1.LabelSelector{
MatchExpressions: []metav1.LabelSelectorRequirement{{
Key: "webhooks.knative.dev/exclude",
Operator: metav1.LabelSelectorOpDoesNotExist,
}},
})
cur.ClientConfig.CABundle = caCert
if cur.ClientConfig.Service == nil {
return fmt.Errorf("missing service reference for webhook: %s", wh.Name)
}
cur.ClientConfig.Service.Path = ptr.String(ac.Path())
cur.ReinvocationPolicy = ptrReinvocationPolicyType(admissionregistrationv1.IfNeededReinvocationPolicy)
}
if ok, err := kmp.SafeEqual(configuredWebhook, current); err != nil {
return fmt.Errorf("error diffing webhooks: %w", err)
} else if !ok {
logger.Info("Updating webhook")
mwhclient := ac.client.AdmissionregistrationV1().MutatingWebhookConfigurations()
if _, err := mwhclient.Update(ctx, current, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("failed to update webhook: %w", err)
}
} else {
logger.Info("Webhook is valid")
}
return nil
}
func ptrReinvocationPolicyType(r admissionregistrationv1.ReinvocationPolicyType) *admissionregistrationv1.ReinvocationPolicyType {
return &r
}