-
Notifications
You must be signed in to change notification settings - Fork 176
/
Copy pathhandler.go
484 lines (424 loc) · 12.9 KB
/
handler.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
/*
Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License.
A copy of the License is located at
http://www.apache.org/licenses/LICENSE-2.0
or in the "license" file accompanying this file. This file 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 handler
import (
"encoding/csv"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"path/filepath"
"strconv"
"strings"
"github.com/aws/amazon-eks-pod-identity-webhook/pkg"
"github.com/aws/amazon-eks-pod-identity-webhook/pkg/cache"
"k8s.io/api/admission/v1beta1"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/klog"
)
type podUpdateSettings struct {
skipContainers map[string]bool
useRegionalSTS bool
}
// newPodUpdateSettings returns the update settings for a particular pod
func newPodUpdateSettings(annotationDomain string, pod *corev1.Pod, useRegionalSTS bool) *podUpdateSettings {
settings := &podUpdateSettings{
useRegionalSTS: useRegionalSTS,
}
skippedNames := map[string]bool{}
skipContainersKey := annotationDomain + "/" + pkg.SkipContainersAnnotation
if value, ok := pod.Annotations[skipContainersKey]; ok {
r := csv.NewReader(strings.NewReader(value))
// error means we don't skip any
podNames, err := r.Read()
if err != nil {
klog.Infof("Could parse skip containers annotation on pod %s/%s: %v", pod.Namespace, pod.Name, err)
}
for _, name := range podNames {
skippedNames[name] = true
}
}
settings.skipContainers = skippedNames
return settings
}
func init() {
_ = corev1.AddToScheme(runtimeScheme)
_ = admissionregistrationv1beta1.AddToScheme(runtimeScheme)
}
var (
runtimeScheme = runtime.NewScheme()
codecs = serializer.NewCodecFactory(runtimeScheme)
deserializer = codecs.UniversalDeserializer()
)
// ModifierOpt is an option type for setting up a Modifier
type ModifierOpt func(*Modifier)
// WithServiceAccountCache sets the modifiers cache
func WithServiceAccountCache(c cache.ServiceAccountCache) ModifierOpt {
return func(m *Modifier) { m.Cache = c }
}
// WithMountPath sets the modifier mountPath
func WithMountPath(mountpath string) ModifierOpt {
return func(m *Modifier) { m.MountPath = mountpath }
}
// WithExpiration sets the modifier expiration
func WithExpiration(exp int64) ModifierOpt {
return func(m *Modifier) { m.Expiration = exp }
}
// WithRegion sets the modifier region
func WithRegion(region string) ModifierOpt {
return func(m *Modifier) { m.Region = region }
}
// WithRegionalSTS sets the modifier RegionalSTSEndpoint
func WithRegionalSTS(enabled bool) ModifierOpt {
return func(m *Modifier) { m.RegionalSTSEndpoint = enabled }
}
// WithAnnotationDomain adds an annotation domain
func WithAnnotationDomain(domain string) ModifierOpt {
return func(m *Modifier) { m.AnnotationDomain = domain }
}
// NewModifier returns a Modifier with default values
func NewModifier(opts ...ModifierOpt) *Modifier {
mod := &Modifier{
AnnotationDomain: "eks.amazonaws.com",
MountPath: "/var/run/secrets/eks.amazonaws.com/serviceaccount",
Expiration: 86400,
RegionalSTSEndpoint: false,
volName: "aws-iam-token",
tokenName: "token",
}
for _, opt := range opts {
opt(mod)
}
return mod
}
// Modifier holds configuration values for pod modifications
type Modifier struct {
AnnotationDomain string
Expiration int64
MountPath string
Region string
RegionalSTSEndpoint bool
Cache cache.ServiceAccountCache
volName string
tokenName string
}
type patchOperation struct {
Op string `json:"op"`
Path string `json:"path"`
Value interface{} `json:"value,omitempty"`
}
func logContext(podName, podGenerateName, serviceAccountName, namespace string) string {
name := podName
if len(podName) == 0 {
name = podGenerateName
}
return fmt.Sprintf("Pod=%s, "+
"ServiceAccount=%s, "+
"Namespace=%s",
name,
serviceAccountName,
namespace)
}
func (m *Modifier) addEnvToContainer(container *corev1.Container, tokenFilePath, roleName string, podSettings *podUpdateSettings) bool {
// return if this is a named skipped container
if _, ok := podSettings.skipContainers[container.Name]; ok {
klog.V(4).Infof("Container %s was annotated to be skipped", container.Name)
return false
}
var (
reservedKeysDefined bool
regionKeyDefined bool
regionalStsKeyDefined bool
)
reservedKeys := map[string]string{
"AWS_ROLE_ARN": "",
"AWS_WEB_IDENTITY_TOKEN_FILE": "",
}
awsRegionKeys := map[string]string{
"AWS_REGION": "",
"AWS_DEFAULT_REGION": "",
}
stsKey := "AWS_STS_REGIONAL_ENDPOINTS"
for _, env := range container.Env {
if _, ok := reservedKeys[env.Name]; ok {
reservedKeysDefined = true
}
if _, ok := awsRegionKeys[env.Name]; ok {
// Don't set both region keys if any region key is already set
regionKeyDefined = true
}
if env.Name == stsKey {
regionalStsKeyDefined = true
}
}
if reservedKeysDefined && regionKeyDefined && regionalStsKeyDefined {
klog.V(4).Infof("Container %s has necessary env variables already present",
container.Name)
return false
}
changed := false
env := container.Env
if !regionalStsKeyDefined && m.RegionalSTSEndpoint && podSettings.useRegionalSTS {
env = append(env,
corev1.EnvVar{
Name: stsKey,
Value: "regional",
},
)
changed = true
}
if !regionKeyDefined && m.Region != "" {
env = append(env,
corev1.EnvVar{
Name: "AWS_DEFAULT_REGION",
Value: m.Region,
},
corev1.EnvVar{
Name: "AWS_REGION",
Value: m.Region,
},
)
changed = true
}
if !reservedKeysDefined {
env = append(env, corev1.EnvVar{
Name: "AWS_ROLE_ARN",
Value: roleName,
})
env = append(env, corev1.EnvVar{
Name: "AWS_WEB_IDENTITY_TOKEN_FILE",
Value: tokenFilePath,
})
changed = true
}
container.Env = env
volExists := false
for _, vol := range container.VolumeMounts {
if vol.Name == m.volName {
volExists = true
}
}
if !volExists {
container.VolumeMounts = append(
container.VolumeMounts,
corev1.VolumeMount{
Name: m.volName,
ReadOnly: true,
MountPath: m.MountPath,
},
)
changed = true
}
return changed
}
func (m *Modifier) updatePodSpec(pod *corev1.Pod, roleName, audience string, regionalSTS bool, tokenExpiration int64) ([]patchOperation, bool) {
updateSettings := newPodUpdateSettings(m.AnnotationDomain, pod, regionalSTS)
tokenFilePath := filepath.Join(m.MountPath, m.tokenName)
betaNodeSelector, _ := pod.Spec.NodeSelector["beta.kubernetes.io/os"]
nodeSelector, _ := pod.Spec.NodeSelector["kubernetes.io/os"]
if (betaNodeSelector == "windows") || nodeSelector == "windows" {
// Convert the unix file path to a windows file path
// Eg. /var/run/secrets/eks.amazonaws.com/serviceaccount/token to
// C:\var\run\secrets\eks.amazonaws.com\serviceaccount\token
tokenFilePath = "C:" + strings.Replace(tokenFilePath, `/`, `\`, -1)
}
var changed bool
var initContainers = []corev1.Container{}
for i := range pod.Spec.InitContainers {
container := pod.Spec.InitContainers[i]
changed = m.addEnvToContainer(&container, tokenFilePath, roleName, updateSettings)
initContainers = append(initContainers, container)
}
var containers = []corev1.Container{}
for i := range pod.Spec.Containers {
container := pod.Spec.Containers[i]
changed = m.addEnvToContainer(&container, tokenFilePath, roleName, updateSettings)
containers = append(containers, container)
}
expirationKey := m.AnnotationDomain + "/" + pkg.TokenExpirationAnnotation
if expirationStr, ok := pod.Annotations[expirationKey]; ok {
if expiration, err := strconv.ParseInt(expirationStr, 10, 64); err != nil {
klog.V(4).Infof("Found invalid value for token expiration, using %d seconds as default: %v", tokenExpiration, err)
} else {
tokenExpiration = pkg.ValidateMinTokenExpiration(expiration)
}
}
volume := corev1.Volume{
Name: m.volName,
VolumeSource: corev1.VolumeSource{
Projected: &corev1.ProjectedVolumeSource{
Sources: []corev1.VolumeProjection{
{
ServiceAccountToken: &corev1.ServiceAccountTokenProjection{
Audience: audience,
ExpirationSeconds: &tokenExpiration,
Path: m.tokenName,
},
},
},
},
},
}
patch := []patchOperation{}
// skip adding volume if it already exists
volExists := false
for _, vol := range pod.Spec.Volumes {
if vol.Name == m.volName {
volExists = true
}
}
if !volExists {
volPatch := patchOperation{
Op: "add",
Path: "/spec/volumes/0",
Value: volume,
}
if pod.Spec.Volumes == nil {
volPatch = patchOperation{
Op: "add",
Path: "/spec/volumes",
Value: []corev1.Volume{
volume,
},
}
}
patch = append(patch, volPatch)
changed = true
}
patch = append(patch, patchOperation{
Op: "add",
Path: "/spec/containers",
Value: containers,
})
if len(initContainers) > 0 {
patch = append(patch, patchOperation{
Op: "add",
Path: "/spec/initContainers",
Value: initContainers,
})
}
return patch, changed
}
// MutatePod takes a AdmissionReview, mutates the pod, and returns an AdmissionResponse
func (m *Modifier) MutatePod(ar *v1beta1.AdmissionReview) *v1beta1.AdmissionResponse {
badRequest := &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: "bad content",
},
}
if ar == nil {
return badRequest
}
req := ar.Request
if req == nil {
return badRequest
}
var pod corev1.Pod
if err := json.Unmarshal(req.Object.Raw, &pod); err != nil {
klog.Errorf("Could not unmarshal raw object: %v", err)
klog.Errorf("Object: %v", string(req.Object.Raw))
return &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
pod.Namespace = req.Namespace
podRole, audience, regionalSTS, tokenExpiration := m.Cache.Get(pod.Spec.ServiceAccountName, pod.Namespace)
// determine whether to perform mutation
if podRole == "" {
klog.V(4).Infof("Pod was not mutated. Reason: "+
"Service account did not have the right annotations or was not found in the cache. %s",
logContext(pod.Name,
pod.GenerateName,
pod.Spec.ServiceAccountName,
pod.Namespace))
return &v1beta1.AdmissionResponse{
Allowed: true,
}
}
patch, changed := m.updatePodSpec(&pod, podRole, audience, regionalSTS, tokenExpiration)
patchBytes, err := json.Marshal(patch)
if err != nil {
klog.Errorf("Error marshaling pod update: %v", err.Error())
return &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
// TODO: klog structured logging can make this better
if changed {
klog.V(3).Infof("Pod was mutated. %s",
logContext(pod.Name, pod.GenerateName, pod.Spec.ServiceAccountName, pod.Namespace))
} else {
klog.V(3).Infof("Pod was not mutated. Reason: "+
"Required volume mounts and env variables were already present. %s",
logContext(pod.Name, pod.GenerateName, pod.Spec.ServiceAccountName, pod.Namespace))
}
return &v1beta1.AdmissionResponse{
Allowed: true,
Patch: patchBytes,
PatchType: func() *v1beta1.PatchType {
pt := v1beta1.PatchTypeJSONPatch
return &pt
}(),
}
}
// Handle handles pod modification requests
func (m *Modifier) Handle(w http.ResponseWriter, r *http.Request) {
var body []byte
if r.Body != nil {
if data, err := ioutil.ReadAll(r.Body); err == nil {
body = data
}
}
// verify the content type is accurate
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
klog.Errorf("Content-Type=%s, expected application/json", contentType)
http.Error(w, "Invalid Content-Type, expected `application/json`", http.StatusUnsupportedMediaType)
return
}
var admissionResponse *v1beta1.AdmissionResponse
ar := v1beta1.AdmissionReview{}
if _, _, err := deserializer.Decode(body, nil, &ar); err != nil {
klog.Errorf("Can't decode body: %v", err)
admissionResponse = &v1beta1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
} else {
admissionResponse = m.MutatePod(&ar)
}
admissionReview := v1beta1.AdmissionReview{}
if admissionResponse != nil {
admissionReview.Response = admissionResponse
if ar.Request != nil {
admissionReview.Response.UID = ar.Request.UID
}
}
resp, err := json.Marshal(admissionReview)
if err != nil {
klog.Errorf("Can't encode response: %v", err)
http.Error(w, fmt.Sprintf("could not encode response: %v", err), http.StatusInternalServerError)
}
if _, err := w.Write(resp); err != nil {
klog.Errorf("Can't write response: %v", err)
http.Error(w, fmt.Sprintf("could not write response: %v", err), http.StatusInternalServerError)
}
}