/
helper.go
148 lines (128 loc) · 5.02 KB
/
helper.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
// Copyright 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://aws.amazon.com/apache2.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 utils
import (
"context"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
vpcresourcesv1beta1 "github.com/aws/amazon-vpc-resource-controller-k8s/apis/vpcresources/v1beta1"
)
// Include checks if a string existing in a string slice and returns true or false.
func Include(target string, values []string) bool {
for _, value := range values {
if value == target {
return true
}
}
return false
}
// RemoveDuplicatedSg removes duplicated items from a string slice.
// It returns a no duplicates string slice.
func RemoveDuplicatedSg(list []string) []string {
set := make(map[string]bool)
var processedList []string
for _, sg := range list {
if _, ok := set[sg]; !ok {
processedList = append(processedList, sg)
set[sg] = true
}
}
return processedList
}
type K8sCacheHelper interface {
GetPodSecurityGroups(pod *corev1.Pod) ([]string, error)
GetSecurityGroupsFromPod(podId types.NamespacedName) ([]string, error)
}
// GetPodSecurityGroups decide if the testPod can be mutated to inject ENI annotation for security groups.
// The function returns security group list and true or false for mutating testPod.
func (kch *k8sCacheHelper) GetPodSecurityGroups(pod *corev1.Pod) ([]string, error) {
helperLog := kch.Log.WithValues("Pod name", pod.Name, "Pod namespace", pod.Namespace)
// Build SGP list from cache.
ctx := context.Background()
sgpList := &vpcresourcesv1beta1.SecurityGroupPolicyList{}
if err := kch.Client.List(ctx, sgpList, &client.ListOptions{Namespace: pod.Namespace}); err != nil {
// If the CRD was removed intentionally or accidentally, we don't want to interrupt pods creation.
// GroupVersionResource or GroupKind not matched check.
if meta.IsNoMatchError(err) {
helperLog.Error(err,
"Webhook couldn't find SGP definition: "+
"GroupVersionResource or GroupKind didn't match. Will allow regular pods creation.")
return nil, nil
}
helperLog.Error(err, "Client Listing SGP failed in Webhook.")
return nil, err
}
sa := &corev1.ServiceAccount{}
key := types.NamespacedName{
Namespace: pod.Namespace,
Name: pod.Spec.ServiceAccountName}
// Get metadata of SA associated with Pod from cache
if err := kch.Client.Get(ctx, key, sa); err != nil {
return nil, err
}
sgList := kch.filterPodSecurityGroups(sgpList, pod, sa)
if len(sgList) > 0 {
helperLog.V(1).Info("Pod matched a SecurityGroupPolicy and will get the following Security Groups:",
"Security Groups", sgList)
}
return sgList, nil
}
func (kch *k8sCacheHelper) filterPodSecurityGroups(
sgpList *vpcresourcesv1beta1.SecurityGroupPolicyList,
pod *corev1.Pod,
sa *corev1.ServiceAccount) []string {
var sgList []string
sgpLogger := kch.Log.WithValues("Pod name", pod.Name, "Pod namespace", pod.Namespace)
for _, sgp := range sgpList.Items {
hasPodSelector := sgp.Spec.PodSelector != nil
hasSASelector := sgp.Spec.ServiceAccountSelector != nil
hasSecurityGroup := sgp.Spec.SecurityGroups.Groups != nil && len(sgp.Spec.SecurityGroups.Groups) > 0
if (!hasPodSelector && !hasSASelector) || !hasSecurityGroup {
sgpLogger.Info(
"Found an invalid SecurityGroupPolicy due to either both of podSelector and saSelector are null, "+
"or security groups is nil or empty.",
"Invalid SGP", types.NamespacedName{Name: sgp.Name, Namespace: sgp.Namespace},
"Security Groups", sgp.Spec.SecurityGroups)
continue
}
podMatched, saMatched := false, false
if podSelector, podSelectorError :=
metav1.LabelSelectorAsSelector(sgp.Spec.PodSelector); podSelectorError == nil {
if podSelector.Matches(labels.Set(pod.Labels)) {
podMatched = true
}
} else {
sgpLogger.Error(podSelectorError, "Failed converting SGP pod selector to match pod labels.",
"SGP name", sgp.Name, "SGP namespace", sgp.Namespace)
}
if saSelector, saSelectorError :=
metav1.LabelSelectorAsSelector(sgp.Spec.ServiceAccountSelector); saSelectorError == nil {
if saSelector.Matches(labels.Set(sa.Labels)) {
saMatched = true
}
} else {
sgpLogger.Error(saSelectorError, "Failed converting SGP SA selector to match pod labels.",
"SGP name", sgp.Name, "SGP namespace", sgp.Namespace)
}
if (hasPodSelector && !podMatched) || (hasSASelector && !saMatched) {
continue
}
sgList = append(sgList, sgp.Spec.SecurityGroups.Groups...)
}
sgList = RemoveDuplicatedSg(sgList)
return sgList
}