in pkg/utils/helper.go [116:165]
func (s *SecurityGroupForPods) filterPodSecurityGroups(
sgpList *vpcresourcesv1beta1.SecurityGroupPolicyList,
pod *corev1.Pod,
sa *corev1.ServiceAccount,
) []string {
var sgList []string
sgpLogger := s.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
}