From 70eccc8a4c6ee256af672456abeac595b422887c Mon Sep 17 00:00:00 2001 From: Dyanngg Date: Fri, 7 Jul 2023 15:21:54 -0700 Subject: [PATCH] Address comments Signed-off-by: Dyanngg --- .../antrea/crds/clusternetworkpolicy.yaml | 24 +- build/yamls/antrea-aks.yml | 24 +- build/yamls/antrea-crds.yml | 24 +- build/yamls/antrea-eks.yml | 24 +- build/yamls/antrea-gke.yml | 24 +- build/yamls/antrea-ipsec.yml | 24 +- build/yamls/antrea.yml | 24 +- .../yamls/antrea-multicluster-leader.yml | 96 +++- .../networkpolicy/clusternetworkpolicy.go | 128 ++++-- .../clusternetworkpolicy_test.go | 110 ++++- .../networkpolicy/networkpolicy_controller.go | 14 +- pkg/controller/networkpolicy/validate.go | 11 +- pkg/controller/networkpolicy/validate_test.go | 59 +++ test/e2e/antreapolicy_test.go | 126 ++--- test/e2e/nodenetworkpolicy_test.go | 434 ++++++++---------- 15 files changed, 700 insertions(+), 446 deletions(-) diff --git a/build/charts/antrea/crds/clusternetworkpolicy.yaml b/build/charts/antrea/crds/clusternetworkpolicy.yaml index 6027b25f055..a6e2cca2530 100644 --- a/build/charts/antrea/crds/clusternetworkpolicy.yaml +++ b/build/charts/antrea/crds/clusternetworkpolicy.yaml @@ -344,10 +344,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -609,10 +605,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1084,11 +1076,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: @@ -1360,11 +1358,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: diff --git a/build/yamls/antrea-aks.yml b/build/yamls/antrea-aks.yml index 91e1b16562b..70fae74e2e4 100644 --- a/build/yamls/antrea-aks.yml +++ b/build/yamls/antrea-aks.yml @@ -1041,10 +1041,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1306,10 +1302,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1781,11 +1773,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: @@ -2057,11 +2055,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: diff --git a/build/yamls/antrea-crds.yml b/build/yamls/antrea-crds.yml index 4c3adb11adc..277103d5550 100644 --- a/build/yamls/antrea-crds.yml +++ b/build/yamls/antrea-crds.yml @@ -1034,10 +1034,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1299,10 +1295,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1774,11 +1766,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: @@ -2050,11 +2048,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: diff --git a/build/yamls/antrea-eks.yml b/build/yamls/antrea-eks.yml index 5e26a048ce6..6ac10ce53f7 100644 --- a/build/yamls/antrea-eks.yml +++ b/build/yamls/antrea-eks.yml @@ -1041,10 +1041,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1306,10 +1302,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1781,11 +1773,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: @@ -2057,11 +2055,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: diff --git a/build/yamls/antrea-gke.yml b/build/yamls/antrea-gke.yml index cc4f29ea16f..a4f7e8d7a89 100644 --- a/build/yamls/antrea-gke.yml +++ b/build/yamls/antrea-gke.yml @@ -1041,10 +1041,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1306,10 +1302,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1781,11 +1773,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: @@ -2057,11 +2055,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: diff --git a/build/yamls/antrea-ipsec.yml b/build/yamls/antrea-ipsec.yml index 17bc18db10c..57c7630bd41 100644 --- a/build/yamls/antrea-ipsec.yml +++ b/build/yamls/antrea-ipsec.yml @@ -1041,10 +1041,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1306,10 +1302,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1781,11 +1773,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: @@ -2057,11 +2055,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: diff --git a/build/yamls/antrea.yml b/build/yamls/antrea.yml index ebf23c25f54..c4b5abcb9a6 100644 --- a/build/yamls/antrea.yml +++ b/build/yamls/antrea.yml @@ -1041,10 +1041,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1306,10 +1302,6 @@ spec: enum: - Self type: string - sameLabels: - type: array - items: - type: string ipBlock: type: object properties: @@ -1781,11 +1773,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: @@ -2057,11 +2055,17 @@ spec: type: object namespaces: type: object + maxProperties: 1 + minProperties: 1 properties: match: + type: string enum: - Self - type: string + sameLabels: + type: array + items: + type: string ipBlock: type: object properties: diff --git a/multicluster/build/yamls/antrea-multicluster-leader.yml b/multicluster/build/yamls/antrea-multicluster-leader.yml index 8c8a4c10ad8..38f2c43342c 100644 --- a/multicluster/build/yamls/antrea-multicluster-leader.yml +++ b/multicluster/build/yamls/antrea-multicluster-leader.yml @@ -1143,9 +1143,17 @@ spec: ingress/egress rules. Cannot be set with NamespaceSelector.' properties: match: - description: NamespaceMatchType describes Namespace - matching strategy. + description: Selects from the same Namespace of + the appliedTo workloads. type: string + sameLabels: + description: Selects Namespaces that share the + same values for the given set of label keys + with the appliedTo Namespace. Namespaces must + have all the label keys. + items: + type: string + type: array type: object nodeSelector: description: Select certain Nodes which match the @@ -1550,9 +1558,17 @@ spec: ingress/egress rules. Cannot be set with NamespaceSelector.' properties: match: - description: NamespaceMatchType describes Namespace - matching strategy. + description: Selects from the same Namespace of + the appliedTo workloads. type: string + sameLabels: + description: Selects Namespaces that share the + same values for the given set of label keys + with the appliedTo Namespace. Namespaces must + have all the label keys. + items: + type: string + type: array type: object nodeSelector: description: Select certain Nodes which match the @@ -2107,9 +2123,17 @@ spec: ingress/egress rules. Cannot be set with NamespaceSelector.' properties: match: - description: NamespaceMatchType describes Namespace - matching strategy. + description: Selects from the same Namespace of + the appliedTo workloads. type: string + sameLabels: + description: Selects Namespaces that share the + same values for the given set of label keys + with the appliedTo Namespace. Namespaces must + have all the label keys. + items: + type: string + type: array type: object nodeSelector: description: Select certain Nodes which match the @@ -2514,9 +2538,17 @@ spec: ingress/egress rules. Cannot be set with NamespaceSelector.' properties: match: - description: NamespaceMatchType describes Namespace - matching strategy. + description: Selects from the same Namespace of + the appliedTo workloads. type: string + sameLabels: + description: Selects Namespaces that share the + same values for the given set of label keys + with the appliedTo Namespace. Namespaces must + have all the label keys. + items: + type: string + type: array type: object nodeSelector: description: Select certain Nodes which match the @@ -4054,9 +4086,17 @@ spec: ingress/egress rules. Cannot be set with NamespaceSelector.' properties: match: - description: NamespaceMatchType describes Namespace - matching strategy. + description: Selects from the same Namespace of + the appliedTo workloads. type: string + sameLabels: + description: Selects Namespaces that share the + same values for the given set of label keys + with the appliedTo Namespace. Namespaces must + have all the label keys. + items: + type: string + type: array type: object nodeSelector: description: Select certain Nodes which match the @@ -4461,9 +4501,17 @@ spec: ingress/egress rules. Cannot be set with NamespaceSelector.' properties: match: - description: NamespaceMatchType describes Namespace - matching strategy. + description: Selects from the same Namespace of + the appliedTo workloads. type: string + sameLabels: + description: Selects Namespaces that share the + same values for the given set of label keys + with the appliedTo Namespace. Namespaces must + have all the label keys. + items: + type: string + type: array type: object nodeSelector: description: Select certain Nodes which match the @@ -5018,9 +5066,17 @@ spec: ingress/egress rules. Cannot be set with NamespaceSelector.' properties: match: - description: NamespaceMatchType describes Namespace - matching strategy. + description: Selects from the same Namespace of + the appliedTo workloads. type: string + sameLabels: + description: Selects Namespaces that share the + same values for the given set of label keys + with the appliedTo Namespace. Namespaces must + have all the label keys. + items: + type: string + type: array type: object nodeSelector: description: Select certain Nodes which match the @@ -5425,9 +5481,17 @@ spec: ingress/egress rules. Cannot be set with NamespaceSelector.' properties: match: - description: NamespaceMatchType describes Namespace - matching strategy. + description: Selects from the same Namespace of + the appliedTo workloads. type: string + sameLabels: + description: Selects Namespaces that share the + same values for the given set of label keys + with the appliedTo Namespace. Namespaces must + have all the label keys. + items: + type: string + type: array type: object nodeSelector: description: Select certain Nodes which match the diff --git a/pkg/controller/networkpolicy/clusternetworkpolicy.go b/pkg/controller/networkpolicy/clusternetworkpolicy.go index 42cbdb36c31..99971bbd6b8 100644 --- a/pkg/controller/networkpolicy/clusternetworkpolicy.go +++ b/pkg/controller/networkpolicy/clusternetworkpolicy.go @@ -35,8 +35,7 @@ import ( ) const ( - labelValueUndefined = "Undefined" - labelValueSeparater = "," + labelValueSeparator = "," ) func getACNPReference(cnp *crdv1beta1.ClusterNetworkPolicy) *controlplane.NetworkPolicyReference { @@ -125,16 +124,13 @@ func (n *NetworkPolicyController) filterPerNamespaceRuleACNPsByNSLabels(nsLabels } affectedPolicies := sets.New[string]() - objs, _ := n.acnpInformer.Informer().GetIndexer().ByIndex(perNamespaceRuleIndex, hasSuchRule) + objs, _ := n.acnpInformer.Informer().GetIndexer().ByIndex(perNamespaceRuleIndex, indexValueTrue) for _, obj := range objs { cnp := obj.(*crdv1beta1.ClusterNetworkPolicy) if affected := func() bool { if len(cnp.Spec.AppliedTo) > 0 { // The policy has only spec level AppliedTo. - if namespaceLabelMatches(cnp.Spec.AppliedTo) { - return true - } - return false + return namespaceLabelMatches(cnp.Spec.AppliedTo) } // The policy has rule level AppliedTo. // It needs to check each rule's peers. If any peer of the rule has PeerNamespaces selector and its @@ -157,6 +153,36 @@ func (n *NetworkPolicyController) filterPerNamespaceRuleACNPsByNSLabels(nsLabels return affectedPolicies } +// getACNPsWithRulesMatchingAnyLabelKey gets all ACNPs that have relevant rules based on Namespace label keys. +func (n *NetworkPolicyController) getACNPsWithRulesMatchingAnyLabelKey(labelKeys sets.Set[string]) sets.Set[string] { + matchedPolicyNames := sets.New[string]() + for k := range labelKeys { + objs, _ := n.acnpInformer.Informer().GetIndexer().ByIndex(namespaceRuleLabelKeyIndex, k) + for _, obj := range objs { + cnp := obj.(*crdv1beta1.ClusterNetworkPolicy) + matchedPolicyNames.Insert(cnp.Name) + } + } + return matchedPolicyNames +} + +// getACNPsWithRulesMatchingAnyUpdatedLabels gets all ACNPs that have rules based on Namespace +// label keys, which have changes in value across Namespace update. +func (n *NetworkPolicyController) getACNPsWithRulesMatchingAnyUpdatedLabels(oldNSLabels, newNSLabels map[string]string) sets.Set[string] { + updatedLabelKeys := sets.New[string]() + for k, v := range oldNSLabels { + if v2, ok := newNSLabels[k]; !ok || v2 != v { + updatedLabelKeys.Insert(k) + } + } + for k, v2 := range newNSLabels { + if v, ok := oldNSLabels[k]; !ok || v != v2 { + updatedLabelKeys.Insert(k) + } + } + return n.getACNPsWithRulesMatchingAnyLabelKey(updatedLabelKeys) +} + // addNamespace receives Namespace ADD events and triggers all ClusterNetworkPolicies that have a // per-namespace rule applied to this Namespace to be re-processed. func (n *NetworkPolicyController) addNamespace(obj interface{}) { @@ -185,6 +211,10 @@ func (n *NetworkPolicyController) updateNamespace(oldObj, curObj interface{}) { affectedACNPsByOldLabels := n.filterPerNamespaceRuleACNPsByNSLabels(oldNamespace.Labels) affectedACNPsByCurLabels := n.filterPerNamespaceRuleACNPsByNSLabels(curNamespace.Labels) affectedACNPs := utilsets.SymmetricDifferenceString(affectedACNPsByOldLabels, affectedACNPsByCurLabels) + // Any ACNPs that has Namespace label rules that refers to the label key set that has + // changed during the Namespace update will need to be re-processed. + acnpsWithRulesMatchingNSLabelKeys := n.getACNPsWithRulesMatchingAnyUpdatedLabels(oldNamespace.Labels, curNamespace.Labels) + affectedACNPs = affectedACNPs.Union(acnpsWithRulesMatchingNSLabelKeys) for cnpName := range affectedACNPs { // Ignore the ClusterNetworkPolicy if it has been removed during the process. if cnp, err := n.acnpLister.Get(cnpName); err == nil { @@ -345,7 +375,7 @@ func (n *NetworkPolicyController) processClusterNetworkPolicy(cnp *crdv1beta1.Cl atgPerAffectedNS := map[string]*antreatypes.AppliedToGroup{} // When appliedTo is set at spec level and the ACNP has rules that select peer Namespaces by sameLabels, // this field tracks the labels of all Namespaces selected by the appliedTo. - affectedNSAndLabels := map[string]map[string]string{} + labelsPerAffectedNS := map[string]labels.Set{} // clusterSetScopeSelectorKeys keeps track of all the ClusterSet-scoped selector keys of the policy. // During policy peer processing, any ClusterSet-scoped selector will be registered with the // labelIdentityInterface and added to this set. By the end of the function, this set will @@ -357,10 +387,10 @@ func (n *NetworkPolicyController) processClusterNetworkPolicy(cnp *crdv1beta1.Cl atg := n.createAppliedToGroup(at.ServiceAccount.Namespace, serviceAccountNameToPodSelector(at.ServiceAccount.Name), nil, nil, nil) appliedToGroups = mergeAppliedToGroups(appliedToGroups, atg) atgPerAffectedNS[at.ServiceAccount.Namespace] = atg - affectedNSAndLabels[at.ServiceAccount.Namespace] = n.getNamespaceLabels(at.ServiceAccount.Namespace) + labelsPerAffectedNS[at.ServiceAccount.Namespace] = n.getNamespaceLabels(at.ServiceAccount.Namespace) } else { - affectedNSAndLabels = n.getAffectedNamespacesForAppliedTo(at) - for ns := range affectedNSAndLabels { + labelsPerAffectedNS = n.getAffectedNamespacesForAppliedTo(at) + for ns := range labelsPerAffectedNS { atg := n.createAppliedToGroup(ns, at.PodSelector, nil, at.ExternalEntitySelector, nil) appliedToGroups = mergeAppliedToGroups(appliedToGroups, atg) atgPerAffectedNS[ns] = atg @@ -448,9 +478,9 @@ func (n *NetworkPolicyController) processClusterNetworkPolicy(cnp *crdv1beta1.Cl } if len(nsLabelPeers) > 0 { if len(cnp.Spec.AppliedTo) > 0 { - // All affected Namespaces and their labels are already stored in affectedNSAndLabels + // All affected Namespaces and their labels are already stored in labelsPerAffectedNS for _, peer := range nsLabelPeers { - nsGroupByLabelVal := groupNamespacesByLabelValue(affectedNSAndLabels, peer.Namespaces.SameLabels) + nsGroupByLabelVal := groupNamespacesByLabelValue(labelsPerAffectedNS, peer.Namespaces.SameLabels) for labelValues, groupedNamespaces := range nsGroupByLabelVal { peer, atgs, ags, selKeys := n.toAntreaPeerForSameLabelNamespaces(peer, cnp, atgPerAffectedNS, labelValues, groupedNamespaces) clusterSetScopeSelectorKeys = clusterSetScopeSelectorKeys.Union(selKeys) @@ -459,22 +489,22 @@ func (n *NetworkPolicyController) processClusterNetworkPolicy(cnp *crdv1beta1.Cl } } else { atgPerRuleAffectedNS := map[string]*antreatypes.AppliedToGroup{} - ruleAffectedNSLabels := map[string]map[string]string{} + labelsPerRuleAffectedNS := map[string]labels.Set{} for _, at := range cnpRule.AppliedTo { if at.ServiceAccount != nil { atg := n.createAppliedToGroup(at.ServiceAccount.Namespace, serviceAccountNameToPodSelector(at.ServiceAccount.Name), nil, nil, nil) atgPerRuleAffectedNS[at.ServiceAccount.Namespace] = atg - ruleAffectedNSLabels[at.ServiceAccount.Namespace] = n.getNamespaceLabels(at.ServiceAccount.Namespace) + labelsPerRuleAffectedNS[at.ServiceAccount.Namespace] = n.getNamespaceLabels(at.ServiceAccount.Namespace) } else { - ruleAffectedNSLabels = n.getAffectedNamespacesForAppliedTo(at) - for ns := range ruleAffectedNSLabels { + labelsPerRuleAffectedNS = n.getAffectedNamespacesForAppliedTo(at) + for ns := range labelsPerRuleAffectedNS { atg := n.createAppliedToGroup(ns, at.PodSelector, nil, at.ExternalEntitySelector, nil) atgPerRuleAffectedNS[ns] = atg } } } for _, peer := range nsLabelPeers { - nsGroupByLabelVal := groupNamespacesByLabelValue(ruleAffectedNSLabels, peer.Namespaces.SameLabels) + nsGroupByLabelVal := groupNamespacesByLabelValue(labelsPerRuleAffectedNS, peer.Namespaces.SameLabels) for labelValues, groupedNamespaces := range nsGroupByLabelVal { peer, atgs, ags, selKeys := n.toAntreaPeerForSameLabelNamespaces(peer, cnp, atgPerRuleAffectedNS, labelValues, groupedNamespaces) clusterSetScopeSelectorKeys = clusterSetScopeSelectorKeys.Union(selKeys) @@ -542,14 +572,42 @@ func hasPerNamespaceRule(cnp *crdv1beta1.ClusterNetworkPolicy) bool { return false } -func (n *NetworkPolicyController) getNamespaceLabels(ns string) map[string]string { - namespace, _ := n.namespaceLister.Get(ns) +func namespaceRuleLabelKeys(cnp *crdv1beta1.ClusterNetworkPolicy) sets.Set[string] { + keys := sets.New[string]() + for _, ingress := range cnp.Spec.Ingress { + for _, peer := range ingress.From { + if peer.Namespaces != nil { + for _, k := range peer.Namespaces.SameLabels { + keys.Insert(k) + } + } + } + } + for _, egress := range cnp.Spec.Egress { + for _, peer := range egress.To { + if peer.Namespaces != nil { + for _, k := range peer.Namespaces.SameLabels { + keys.Insert(k) + } + } + } + } + return keys +} + +func (n *NetworkPolicyController) getNamespaceLabels(ns string) labels.Set { + namespace, err := n.namespaceLister.Get(ns) + if err != nil { + // The Namespace referred to (by ServiceAccount etc.) does not exist yet. + // ACNP will be re-queued once that Namespace event is received. + return labels.Set{} + } return namespace.Labels } // groupNamespaceByLabelValue groups Namespaces if they have the same label value for all the -// label keys listed. If a Namespace is missing at least one of the label keys, it will be -// not be grouped. Example: +// label keys listed. If a Namespace is missing at least one of the label keys, it will not +// be grouped. Example: // // ns1: app=web, tier=test, tenant=t1 // ns2: app=web, tier=test, tenant=t2 @@ -560,10 +618,10 @@ func (n *NetworkPolicyController) getNamespaceLabels(ns string) map[string]strin // Result after grouping: // "web,test,": [ns1, ns2] // "web,production,": [ns3, ns4] -func groupNamespacesByLabelValue(affectedNSAndLabels map[string]map[string]string, labelKeys []string) map[string][]string { +func groupNamespacesByLabelValue(affectedNSAndLabels map[string]labels.Set, labelKeys []string) map[string][]string { nsGroupedByLabelVal := map[string][]string{} for ns, nsLabels := range affectedNSAndLabels { - if groupKey := getLabelValues(nsLabels, labelKeys); groupKey != labelValueUndefined { + if groupKey := getLabelValues(nsLabels, labelKeys); groupKey != "" { nsGroupedByLabelVal[groupKey] = append(nsGroupedByLabelVal[groupKey], ns) } } @@ -573,19 +631,17 @@ func groupNamespacesByLabelValue(affectedNSAndLabels map[string]map[string]strin func getLabelValues(labels map[string]string, labelKeys []string) string { key := "" for _, k := range labelKeys { - if v, ok := labels[k]; !ok { - return labelValueUndefined - } else { - key += v + labelValueSeparater + if v, ok := labels[k]; ok { + key += v + labelValueSeparator } } return key } -// labelKeyValPairsToSelector creates a LabelSelector based on a list of label keys +// convertSameLabelsToSelector creates a LabelSelector based on a list of label keys // and their expected values. -func labelKeyValPairsToSelector(labelKeys []string, labelValues string) *metav1.LabelSelector { - labelValuesSep := strings.Split(labelValues, labelValueSeparater) +func convertSameLabelsToSelector(labelKeys []string, labelValues string) *metav1.LabelSelector { + labelValuesSep := strings.Split(labelValues, labelValueSeparator) labelMatchCriteria := map[string]string{} for i := range labelKeys { labelMatchCriteria[labelKeys[i]] = labelValuesSep[i] @@ -603,10 +659,10 @@ func (n *NetworkPolicyController) toAntreaPeerForSameLabelNamespaces(peer crdv1b namespacesByLabelValues []string) (*controlplane.NetworkPolicyPeer, []*antreatypes.AppliedToGroup, []*antreatypes.AddressGroup, sets.Set[string]) { labelKeys := peer.Namespaces.SameLabels var labelIdentities []uint32 - uniqueLabelIDs := map[uint32]struct{}{} + uniqueLabelIDs := sets.New[uint32]() clusterSetScopeSelectorKeys := sets.New[string]() // select Namespaces who, for specific label keys, have the same values as the appliedTo Namespaces. - nsSelForSameLabels := labelKeyValPairsToSelector(labelKeys, labelValues) + nsSelForSameLabels := convertSameLabelsToSelector(labelKeys, labelValues) addressGroups := []*antreatypes.AddressGroup{n.createAddressGroup("", peer.PodSelector, nsSelForSameLabels, peer.ExternalEntitySelector, nil)} if n.stretchNPEnabled && peer.Scope == crdv1beta1.ScopeClusterSet { newClusterSetScopeSelector := antreatypes.NewGroupSelector("", peer.PodSelector, nsSelForSameLabels, peer.ExternalEntitySelector, nil) @@ -615,7 +671,7 @@ func (n *NetworkPolicyController) toAntreaPeerForSameLabelNamespaces(peer crdv1b // with the labelIdentityInterface. matchedLabelIDs := n.labelIdentityInterface.AddSelector(newClusterSetScopeSelector, internalNetworkPolicyKeyFunc(np)) for _, id := range matchedLabelIDs { - uniqueLabelIDs[id] = struct{}{} + uniqueLabelIDs.Insert(id) } } for id := range uniqueLabelIDs { @@ -681,8 +737,8 @@ func splitPeersByScope(rule crdv1beta1.Rule, dir controlplane.Direction) ([]crdv // getAffectedNamespacesForAppliedTo computes the Namespaces currently affected by the appliedTo // Namespace selectors, and returns these Namespaces along with their labels. -func (n *NetworkPolicyController) getAffectedNamespacesForAppliedTo(appliedTo crdv1beta1.AppliedTo) map[string]map[string]string { - affectedNSAndLabels := map[string]map[string]string{} +func (n *NetworkPolicyController) getAffectedNamespacesForAppliedTo(appliedTo crdv1beta1.AppliedTo) map[string]labels.Set { + affectedNSAndLabels := map[string]labels.Set{} nsLabelSelector := appliedTo.NamespaceSelector if appliedTo.Group != "" { diff --git a/pkg/controller/networkpolicy/clusternetworkpolicy_test.go b/pkg/controller/networkpolicy/clusternetworkpolicy_test.go index 450d42bf47d..65a3462c401 100644 --- a/pkg/controller/networkpolicy/clusternetworkpolicy_test.go +++ b/pkg/controller/networkpolicy/clusternetworkpolicy_test.go @@ -26,6 +26,7 @@ import ( v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/sets" "antrea.io/antrea/multicluster/controllers/multicluster/common" @@ -1957,9 +1958,9 @@ func TestProcessClusterNetworkPolicy(t *testing.T) { } } -func TestAddCNP(t *testing.T) { +func TestAddACNP(t *testing.T) { _, npc := newController(nil, nil) - cnp := getCNP() + cnp := getACNP() npc.addCNP(cnp) require.Equal(t, 1, npc.internalNetworkPolicyQueue.Len()) key, done := npc.internalNetworkPolicyQueue.Get() @@ -1968,9 +1969,9 @@ func TestAddCNP(t *testing.T) { assert.False(t, done) } -func TestUpdateCNP(t *testing.T) { +func TestUpdateACNP(t *testing.T) { _, npc := newController(nil, nil) - cnp := getCNP() + cnp := getACNP() newCNP := cnp.DeepCopy() // Make a change to the CNP. newCNP.Annotations = map[string]string{"foo": "bar"} @@ -1982,9 +1983,9 @@ func TestUpdateCNP(t *testing.T) { assert.False(t, done) } -func TestDeleteCNP(t *testing.T) { +func TestDeleteACNP(t *testing.T) { _, npc := newController(nil, nil) - cnp := getCNP() + cnp := getACNP() npc.deleteCNP(cnp) require.Equal(t, 1, npc.internalNetworkPolicyQueue.Len()) key, done := npc.internalNetworkPolicyQueue.Get() @@ -2206,7 +2207,7 @@ func TestProcessRefGroupOrClusterGroup(t *testing.T) { // util functions for testing. -func getCNP() *crdv1beta1.ClusterNetworkPolicy { +func getACNP() *crdv1beta1.ClusterNetworkPolicy { p10 := float64(10) allowAction := crdv1beta1.RuleActionAllow selectorA := metav1.LabelSelector{MatchLabels: map[string]string{"foo1": "bar1"}} @@ -2360,3 +2361,98 @@ func TestFilterPerNamespaceRuleACNPsByNSLabels(t *testing.T) { }) } } + +func TestGetACNPsWithRulesMatchingLabelKeysAcrossNSUpdate(t *testing.T) { + acnp1 := &crdv1beta1.ClusterNetworkPolicy{ + ObjectMeta: metav1.ObjectMeta{Name: "acnp-with-tier-label-rule"}, + Spec: crdv1beta1.ClusterNetworkPolicySpec{ + AppliedTo: []crdv1beta1.AppliedTo{ + { + NamespaceSelector: &metav1.LabelSelector{}, + }, + }, + Ingress: []crdv1beta1.Rule{ + { + From: []crdv1beta1.NetworkPolicyPeer{ + { + Namespaces: &crdv1beta1.PeerNamespaces{ + SameLabels: []string{"tier"}, + }, + }, + }, + }, + }, + }, + } + acnp2 := &crdv1beta1.ClusterNetworkPolicy{ + ObjectMeta: metav1.ObjectMeta{Name: "acnp-with-tier-and-purpose-label-rule"}, + Spec: crdv1beta1.ClusterNetworkPolicySpec{ + AppliedTo: []crdv1beta1.AppliedTo{ + { + NamespaceSelector: &metav1.LabelSelector{}, + }, + }, + Ingress: []crdv1beta1.Rule{ + { + From: []crdv1beta1.NetworkPolicyPeer{ + { + Namespaces: &crdv1beta1.PeerNamespaces{ + SameLabels: []string{"tier", "purpose"}, + }, + }, + }, + }, + }, + }, + } + tests := []struct { + name string + oldNSLabels labels.Set + newNSLabels labels.Set + want sets.Set[string] + }{ + { + name: "Namespace updated to have tier label", + oldNSLabels: map[string]string{ + "kubernetes.io/metadata.name": "ns1", + }, + newNSLabels: map[string]string{ + "kubernetes.io/metadata.name": "ns1", + "tier": "production", + }, + want: sets.New[string](acnp1.Name, acnp2.Name), + }, + { + name: "Namespace updated to have purpose label", + oldNSLabels: map[string]string{ + "kubernetes.io/metadata.name": "ns2", + }, + newNSLabels: map[string]string{ + "kubernetes.io/metadata.name": "ns2", + "purpose": "test", + }, + want: sets.New[string](acnp2.Name), + }, + { + name: "Namespace updated for irrelevant label", + oldNSLabels: map[string]string{ + "kubernetes.io/metadata.name": "ns3", + "tier": "production", + }, + newNSLabels: map[string]string{ + "kubernetes.io/metadata.name": "ns2", + "tier": "production", + "owned-by": "dev-team", + }, + want: sets.New[string](), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, c := newController(nil, []runtime.Object{acnp1, acnp2}) + c.acnpStore.Add(acnp1) + c.acnpStore.Add(acnp2) + assert.Equal(t, tt.want, c.getACNPsWithRulesMatchingAnyUpdatedLabels(tt.oldNSLabels, tt.newNSLabels)) + }) + } +} diff --git a/pkg/controller/networkpolicy/networkpolicy_controller.go b/pkg/controller/networkpolicy/networkpolicy_controller.go index 2bf2df779a2..2dbac533f0b 100644 --- a/pkg/controller/networkpolicy/networkpolicy_controller.go +++ b/pkg/controller/networkpolicy/networkpolicy_controller.go @@ -93,9 +93,9 @@ const ( addressGroupType grouping.GroupType = "addressGroup" internalGroupType grouping.GroupType = "internalGroup" - perNamespaceRuleIndex = "hasPerNamespaceRule" - namespaceLabelRuleIndex = "namespaceRuleLabelKeys" - hasSuchRule = "true" + perNamespaceRuleIndex = "hasPerNamespaceRule" + namespaceRuleLabelKeyIndex = "namespaceRuleLabelKeys" + indexValueTrue = "true" ) var ( @@ -334,13 +334,13 @@ var acnpIndexers = cache.Indexers{ if !ok { return []string{}, nil } - if hasPerNSRule := hasPerNamespaceRule(acnp); hasPerNSRule { - return []string{hasSuchRule}, nil + if hasPerNamespaceRule(acnp) { + return []string{indexValueTrue}, nil } return []string{}, nil }, - namespaceLabelRuleIndex: func(obj interface{}) ([]string, error) { - cnp, ok := obj.(*secv1alpha1.ClusterNetworkPolicy) + namespaceRuleLabelKeyIndex: func(obj interface{}) ([]string, error) { + cnp, ok := obj.(*secv1beta1.ClusterNetworkPolicy) if !ok { return []string{}, nil } diff --git a/pkg/controller/networkpolicy/validate.go b/pkg/controller/networkpolicy/validate.go index c03919eb0ee..5639866e452 100644 --- a/pkg/controller/networkpolicy/validate.go +++ b/pkg/controller/networkpolicy/validate.go @@ -656,8 +656,15 @@ func (v *antreaPolicyValidator) validatePeers(ingress, egress []crdv1beta1.Rule) if peer.NamespaceSelector != nil && peer.Namespaces != nil { return "namespaces and namespaceSelector cannot be set at the same time for a single NetworkPolicyPeer", false } - if peer.Namespaces != nil && numFieldsSetInStruct(*peer.Namespaces) > 1 { - return "only one matching criteria can be specified in a single peer namespaces field", false + if peer.Namespaces != nil { + if numFieldsSetInStruct(*peer.Namespaces) > 1 { + return "only one matching criteria can be specified in a single peer namespaces field", false + } + for _, k := range peer.Namespaces.SameLabels { + if err := validation.IsQualifiedName(k); err != nil { + return fmt.Sprintf("Invalid label key in sameLabels rule: %s", k), false + } + } } peerFieldsNum := numFieldsSetInStruct(peer) if peer.Group != "" && peerFieldsNum > 1 { diff --git a/pkg/controller/networkpolicy/validate_test.go b/pkg/controller/networkpolicy/validate_test.go index 43b20fe13ca..271da1e06c1 100644 --- a/pkg/controller/networkpolicy/validate_test.go +++ b/pkg/controller/networkpolicy/validate_test.go @@ -703,6 +703,65 @@ func TestValidateAntreaClusterNetworkPolicy(t *testing.T) { operation: admv1.Create, expectedReason: "namespaces and namespaceSelector cannot be set at the same time for a single NetworkPolicyPeer", }, + { + name: "acnp-double-peer-namespace-field", + policy: &crdv1beta1.ClusterNetworkPolicy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "acnp-double-peer-namespace-field", + }, + Spec: crdv1beta1.ClusterNetworkPolicySpec{ + AppliedTo: []crdv1beta1.AppliedTo{ + { + NamespaceSelector: &metav1.LabelSelector{}, + }, + }, + Ingress: []crdv1beta1.Rule{ + { + Action: &allowAction, + From: []crdv1beta1.NetworkPolicyPeer{ + { + Namespaces: &crdv1beta1.PeerNamespaces{ + Match: crdv1beta1.NamespaceMatchSelf, + SameLabels: []string{"test"}, + }, + }, + }, + }, + }, + }, + }, + operation: admv1.Create, + expectedReason: "only one matching criteria can be specified in a single peer namespaces field", + }, + { + name: "acnp-invalid-rule-samelabels-key", + policy: &crdv1beta1.ClusterNetworkPolicy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "acnp-invalid-rule-samelabels-key", + }, + Spec: crdv1beta1.ClusterNetworkPolicySpec{ + AppliedTo: []crdv1beta1.AppliedTo{ + { + NamespaceSelector: &metav1.LabelSelector{}, + }, + }, + Ingress: []crdv1beta1.Rule{ + { + Action: &allowAction, + From: []crdv1beta1.NetworkPolicyPeer{ + { + Namespaces: &crdv1beta1.PeerNamespaces{ + SameLabels: []string{"&illegalKey"}, + }, + }, + }, + }, + }, + }, + }, + operation: admv1.Update, + expectedReason: "Invalid label key in sameLabels rule: &illegalKey", + }, { name: "acnp-toservice-set-with-to", policy: &crdv1beta1.ClusterNetworkPolicy{ diff --git a/test/e2e/antreapolicy_test.go b/test/e2e/antreapolicy_test.go index e083576273b..47c210953df 100644 --- a/test/e2e/antreapolicy_test.go +++ b/test/e2e/antreapolicy_test.go @@ -249,7 +249,7 @@ func testMutateACNPNoTier(t *testing.T) { func testMutateANNPNoTier(t *testing.T) { invalidNpErr := fmt.Errorf("ANNP tier not mutated to default tier") builder := &AntreaNetworkPolicySpecBuilder{} - builder = builder.SetName(getNS("x"), "anp-no-tier"). + builder = builder.SetName(getNS("x"), "annp-no-tier"). SetAppliedToGroup([]ANNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}}}). SetPriority(10.0) annp := builder.Get() @@ -1748,24 +1748,24 @@ func testACNPPriorityOverride(t *testing.T) { SetPriority(1.001). SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}, NSSelector: map[string]string{"ns": getNS("x")}}}) // Highest priority. Drops traffic from z/b to x/a. - builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) + builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) builder2 := &ClusterNetworkPolicySpecBuilder{} builder2 = builder2.SetName("acnp-priority2"). SetPriority(1.002). SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}, NSSelector: map[string]string{"ns": getNS("x")}}}) // Medium priority. Allows traffic from z to x/a. - builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) + builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) builder3 := &ClusterNetworkPolicySpecBuilder{} builder3 = builder3.SetName("acnp-priority3"). SetPriority(1.003). SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{"ns": getNS("x")}}}) // Lowest priority. Drops traffic from z to x. - builder3.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) + builder3.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachabilityTwoACNPs := NewReachability(allPods, Connected) reachabilityTwoACNPs.Expect(getPod("z", "a"), getPod("x", "b"), Dropped) @@ -1819,8 +1819,8 @@ func testACNPTierOverride(t *testing.T) { SetPriority(100). SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}, NSSelector: map[string]string{"ns": getNS("x")}}}) // Highest priority tier. Drops traffic from z/b to x/a. - builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) + builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) builder2 := &ClusterNetworkPolicySpecBuilder{} builder2 = builder2.SetName("acnp-tier-securityops"). @@ -1828,8 +1828,8 @@ func testACNPTierOverride(t *testing.T) { SetPriority(10). SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}, NSSelector: map[string]string{"ns": getNS("x")}}}) // Medium priority tier. Allows traffic from z to x/a. - builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) + builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) builder3 := &ClusterNetworkPolicySpecBuilder{} builder3 = builder3.SetName("acnp-tier-application"). @@ -1837,8 +1837,8 @@ func testACNPTierOverride(t *testing.T) { SetPriority(1). SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{"ns": getNS("x")}}}) // Lowest priority tier. Drops traffic from z to x. - builder3.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) + builder3.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachabilityTwoACNPs := NewReachability(allPods, Connected) reachabilityTwoACNPs.Expect(getPod("z", "a"), getPod("x", "b"), Dropped) @@ -1899,8 +1899,8 @@ func testACNPCustomTiers(t *testing.T) { SetPriority(100). SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}, NSSelector: map[string]string{"ns": getNS("x")}}}) // Medium priority tier. Allows traffic from z to x/a. - builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) + builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) builder2 := &ClusterNetworkPolicySpecBuilder{} builder2 = builder2.SetName("acnp-tier-low"). @@ -1908,8 +1908,8 @@ func testACNPCustomTiers(t *testing.T) { SetPriority(1). SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{"ns": getNS("x")}}}) // Lowest priority tier. Drops traffic from z to x. - builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) + builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachabilityTwoACNPs := NewReachability(allPods, Connected) reachabilityTwoACNPs.Expect(getPod("z", "a"), getPod("x", "b"), Dropped) @@ -1944,8 +1944,8 @@ func testACNPPriorityConflictingRule(t *testing.T) { builder1 = builder1.SetName("acnp-drop"). SetPriority(1). SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{"ns": getNS("x")}}}) - builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) + builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) builder2 := &ClusterNetworkPolicySpecBuilder{} builder2 = builder2.SetName("acnp-allow"). @@ -1953,8 +1953,8 @@ func testACNPPriorityConflictingRule(t *testing.T) { SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{"ns": getNS("x")}}}) // The following ingress rule will take no effect as it is exactly the same as ingress rule of cnp-drop, // but cnp-allow has lower priority. - builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) + builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) reachabilityBothACNP := NewReachability(allPods, Connected) reachabilityBothACNP.ExpectEgressToNamespace(getPod("z", "a"), getNS("x"), Dropped) @@ -1983,22 +1983,22 @@ func testACNPRulePriority(t *testing.T) { builder1 = builder1.SetName("acnp-deny"). SetPriority(5). SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{"ns": getNS("x")}}}) - builder1.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("y")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) + builder1.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("y")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) // This rule should take no effect as it will be overridden by the first rule of cnp-allow - builder1.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) + builder1.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) builder2 := &ClusterNetworkPolicySpecBuilder{} // acnp-allow will also apply to all pods in namespace x builder2 = builder2.SetName("acnp-allow"). SetPriority(5). SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{"ns": getNS("x")}}}) - builder2.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) + builder2.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) // This rule should take no effect as it will be overridden by the first rule of cnp-drop - builder2.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("y")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) + builder2.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("y")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) // Only egress from pods in namespace x to namespace y should be denied reachabilityBothACNP := NewReachability(allPods, Connected) @@ -2026,8 +2026,8 @@ func testACNPPortRange(t *testing.T) { builder = builder.SetName("acnp-deny-a-to-z-egress-port-range"). SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}}}) - builder.AddEgress(ProtocolTCP, &p8080, nil, &p8082, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "acnp-port-range", nil) + builder.AddEgress(ProtocolTCP, &p8080, nil, &p8082, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "acnp-port-range", nil) reachability := NewReachability(allPods, Connected) reachability.ExpectEgressToNamespace(getPod("x", "a"), getNS("z"), Dropped) @@ -2056,8 +2056,8 @@ func testACNPRejectEgress(t *testing.T) { builder = builder.SetName("acnp-reject-a-to-z-egress"). SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}}}) - builder.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionReject, "", "", nil) + builder.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionReject, "", "", nil) reachability := NewReachability(allPods, Connected) reachability.ExpectEgressToNamespace(getPod("x", "a"), getNS("z"), Rejected) @@ -2085,8 +2085,8 @@ func testACNPRejectIngress(t *testing.T, protocol AntreaPolicyProtocol) { builder = builder.SetName("acnp-reject-a-from-z-ingress"). SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}}}) - builder.AddIngress(protocol, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionReject, "", "", nil) + builder.AddIngress(protocol, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionReject, "", "", nil) reachability := NewReachability(allPods, Connected) reachability.ExpectIngressFromNamespace(getPod("x", "a"), getNS("z"), Rejected) @@ -2574,8 +2574,8 @@ func testAuditLoggingBasic(t *testing.T, data *TestData) { builder = builder.SetName(npName). SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}, NSSelector: map[string]string{"ns": getNS("x")}}}) - builder.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", ruleName, nil) + builder.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", ruleName, nil) builder.AddEgressLogging(logLabel) npRef := fmt.Sprintf("AntreaClusterNetworkPolicy:%s", npName) @@ -2747,7 +2747,7 @@ func testAppliedToPerRule(t *testing.T) { annpATGrp2 := ANNPAppliedToSpec{PodSelector: map[string]string{"pod": "b"}, PodSelectorMatchExp: nil} builder.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, map[string]string{"ns": getNS("x")}, nil, nil, nil, nil, []ANNPAppliedToSpec{annpATGrp1}, crdv1beta1.RuleActionDrop, "", "") - builder.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, map[string]string{"ns": getNS("x")}, nil, + builder.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, map[string]string{"ns": getNS("z")}, nil, nil, nil, nil, []ANNPAppliedToSpec{annpATGrp2}, crdv1beta1.RuleActionDrop, "", "") reachability := NewReachability(allPods, Connected) @@ -2769,10 +2769,10 @@ func testAppliedToPerRule(t *testing.T) { cnpATGrp2 := ACNPAppliedToSpec{ PodSelector: map[string]string{"pod": "b"}, NSSelector: map[string]string{"ns": getNS("y")}, PodSelectorMatchExp: nil, NSSelectorMatchExp: nil} - builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, map[string]string{"ns": getNS("x")}, - nil, nil, nil, nil, nil, []ACNPAppliedToSpec{cnpATGrp1}, crdv1beta1.RuleActionDrop, "", "", nil) - builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, map[string]string{"ns": getNS("z")}, - nil, nil, nil, nil, nil, []ACNPAppliedToSpec{cnpATGrp2}, crdv1beta1.RuleActionDrop, "", "", nil) + builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, nil, map[string]string{"ns": getNS("x")}, + nil, nil, nil, nil, []ACNPAppliedToSpec{cnpATGrp1}, crdv1beta1.RuleActionDrop, "", "", nil) + builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, nil, map[string]string{"ns": getNS("z")}, + nil, nil, nil, nil, []ACNPAppliedToSpec{cnpATGrp2}, crdv1beta1.RuleActionDrop, "", "", nil) reachability2 := NewReachability(allPods, Connected) reachability2.Expect(getPod("x", "b"), getPod("x", "a"), Dropped) @@ -2857,8 +2857,8 @@ func testACNPClusterGroupServiceRefCreateAndUpdate(t *testing.T, data *TestData) builderUpdated := &ClusterNetworkPolicySpecBuilder{} builderUpdated = builderUpdated.SetName("cnp-cg-svc-ref").SetPriority(1.0) builderUpdated.SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}, NSSelector: map[string]string{"ns": getNS("x")}}}) - builderUpdated.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, map[string]string{"ns": getNS("y")}, - nil, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) + builderUpdated.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, map[string]string{"pod": "b"}, nil, map[string]string{"ns": getNS("y")}, + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) // Pod x/a should not allow ingress from y/b per the updated ACNP spec. testStep3 := &TestStep{ @@ -3049,7 +3049,7 @@ func testACNPNamespaceIsolation(t *testing.T) { // deny ingress traffic except from own namespace, which is always allowed. builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, selfNamespace, nil, crdv1beta1.RuleActionAllow, "", "", nil) - builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{}, nil, nil, + builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{}, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachability := NewReachability(allPods, Dropped) @@ -3068,7 +3068,7 @@ func testACNPNamespaceIsolation(t *testing.T) { SetPriority(1.0) builder2.AddEgress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, selfNamespace, []ACNPAppliedToSpec{{NSSelector: map[string]string{"ns": getNS("x")}}}, crdv1beta1.RuleActionAllow, "", "", nil) - builder2.AddEgress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{}, nil, nil, nil, nil, + builder2.AddEgress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{}, nil, nil, nil, nil, []ACNPAppliedToSpec{{NSSelector: map[string]string{"ns": getNS("x")}}}, crdv1beta1.RuleActionDrop, "", "", nil) reachability2 := NewReachability(allPods, Connected) @@ -3101,7 +3101,7 @@ func testACNPStrictNamespacesIsolation(t *testing.T) { SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{}}}) builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, selfNamespace, nil, crdv1beta1.RuleActionPass, "", "", nil) - builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{}, nil, nil, nil, nil, + builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{}, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) // deny ingress traffic except from own namespace, which is delegated to Namespace owners (who can create K8s // NetworkPolicies to regulate intra-Namespace traffic) @@ -3148,7 +3148,7 @@ func testACNPStrictNamespacesIsolationByLabels(t *testing.T) { SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{}}}) builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, samePurposeTierLabels, nil, crdv1beta1.RuleActionPass, "", "", nil) - builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{}, nil, nil, nil, nil, + builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{}, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) // prod1 and prod2 Namespaces should be able to connect to each other. The same goes for dev1 and // dev2 Namespaces. However, any prod Namespace should not be able to connect to any dev Namespace @@ -3192,7 +3192,7 @@ func testACNPStrictNamespacesIsolationBySingleLabel(t *testing.T, data *TestData SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{}}}) builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, samePurposeTierLabels, nil, crdv1beta1.RuleActionPass, "", "", nil) - builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{}, nil, nil, nil, nil, + builder.AddIngress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{}, nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) // Namespaces are split into two logical groups, purpose=test (prod1,2 and dev1,2) and purpose=test-exclusion // (no-tier). The two groups of Namespace should not be able to connect to each other. @@ -3257,7 +3257,7 @@ func testACNPStrictNamespacesIsolationBySingleLabel(t *testing.T, data *TestData func testFQDNPolicy(t *testing.T) { // The ipv6-only test env doesn't have IPv6 access to the web. skipIfNotIPv4Cluster(t) - // It is convenient to have higher log verbosity for FQDNtests for troubleshooting failures. + // It is convenient to have higher log verbosity for FQDN tests for troubleshooting failures. logLevel := log.GetLevel() log.SetLevel(log.TraceLevel) defer log.SetLevel(logLevel) @@ -3282,31 +3282,31 @@ func testFQDNPolicy(t *testing.T) { // All client Pods below are randomly chosen from test Namespaces. testcases := []podToAddrTestStep{ { - Pod(getNS("x") + "/a"), + getPod("x", "a"), "docs.github.com", 80, Rejected, }, { - Pod(getNS("x") + "/b"), + getPod("x", "b"), "api.github.com", 80, Rejected, }, { - Pod(getNS("y") + "/a"), + getPod("y", "a"), "wayfair.com", 80, Dropped, }, { - Pod(getNS("y") + "/b"), + getPod("y", "b"), "stackoverflow.com", 80, Dropped, }, { - Pod(getNS("z") + "/a"), + getPod("z", "a"), "facebook.com", 80, Connected, @@ -3382,7 +3382,7 @@ func testFQDNPolicyInClusterService(t *testing.T) { for _, service := range services { eachServiceCases := []podToAddrTestStep{ { - Pod(getNS("y") + "/b"), + getPod("y", "b"), // To indicate the server Name is a FQDN, end it with a dot. Then DNS resolver won't attempt to append // domain names (e.g. svc.cluster.local, cluster.local) when resolving it, making it get resolution // result more quickly. @@ -3391,13 +3391,13 @@ func testFQDNPolicyInClusterService(t *testing.T) { Rejected, }, { - Pod(getNS("z") + "/c"), + getPod("z", "c"), svcDNSName(service) + ".", 80, Dropped, }, { - Pod(getNS("x") + "/c"), + getPod("x", "c"), svcDNSName(service) + ".", 80, Connected, @@ -3428,7 +3428,7 @@ func testFQDNPolicyInClusterService(t *testing.T) { func testFQDNPolicyTCP(t *testing.T) { // The ipv6-only test env doesn't have IPv6 access to the web. skipIfNotIPv4Cluster(t) - // It is convenient to have higher log verbosity for FQDNtests for troubleshooting failures. + // It is convenient to have higher log verbosity for FQDN tests for troubleshooting failures. logLevel := log.GetLevel() log.SetLevel(log.TraceLevel) defer log.SetLevel(logLevel) @@ -3646,13 +3646,13 @@ func testACNPNodeSelectorEgress(t *testing.T) { if clusterInfo.podV4NetworkCIDR != "" { ipv4Testcases := []podToAddrTestStep{ { - Pod(getNS("x") + "/a"), + getPod("x", "a"), controlPlaneNodeIPv4(), 6443, Dropped, }, { - Pod(getNS("x") + "/b"), + getPod("x", "b"), controlPlaneNodeIPv4(), 6443, Connected, @@ -3664,13 +3664,13 @@ func testACNPNodeSelectorEgress(t *testing.T) { if clusterInfo.podV6NetworkCIDR != "" { ipv6Testcases := []podToAddrTestStep{ { - Pod(getNS("x") + "/a"), + getPod("x", "a"), controlPlaneNodeIPv6(), 6443, Dropped, }, { - Pod(getNS("x") + "/b"), + getPod("x", "b"), controlPlaneNodeIPv6(), 6443, Connected, diff --git a/test/e2e/nodenetworkpolicy_test.go b/test/e2e/nodenetworkpolicy_test.go index be9cb945ecd..592556d962c 100644 --- a/test/e2e/nodenetworkpolicy_test.go +++ b/test/e2e/nodenetworkpolicy_test.go @@ -37,10 +37,7 @@ func initializeAntreaNodeNetworkPolicy(t *testing.T, data *TestData, toHostNetwo p8082 = 8082 p8085 = 8085 pods = []string{"a"} - suffix := randName("") - namespaces = make(map[string]string) - namespaces["x"] = "x-" + suffix - namespaces["y"] = "y-" + suffix + namespaces = initNamespaceMeta(formFactorNormal) nodes = make(map[string]string) nodes["x"] = controlPlaneNodeName() nodes["y"] = workerNodeName(1) @@ -50,7 +47,6 @@ func initializeAntreaNodeNetworkPolicy(t *testing.T, data *TestData, toHostNetwo hostNetworks["y"] = true } else { hostNetworks["y"] = false - namespaces["z"] = "z-" + suffix nodes["z"] = workerNodeName(1) hostNetworks["z"] = false } @@ -58,7 +54,7 @@ func initializeAntreaNodeNetworkPolicy(t *testing.T, data *TestData, toHostNetwo for _, podName := range pods { for _, ns := range namespaces { - allPods = append(allPods, NewPod(ns, podName)) + allPods = append(allPods, NewPod(ns.Name, podName)) } } @@ -139,25 +135,23 @@ func testNodeACNPAllowNoDefaultIsolation(t *testing.T, protocol AntreaPolicyProt SetPriority(1.1). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder1.AddIngress(protocol, &p81, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionAllow, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) builder2 := &ClusterNetworkPolicySpecBuilder{} builder2 = builder2.SetName("acnp-allow-x-to-y-egress"). SetPriority(1.1). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder2.AddEgress(protocol, &p81, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionAllow, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) reachability := NewReachability(allPods, Connected) testStep := []*TestStep{ { - "Port 81", - reachability, - []metav1.Object{builder1.Get(), builder2.Get()}, - []int32{81}, - protocol, - 0, - nil, + Name: "Port 81", + Reachability: reachability, + TestResources: []metav1.Object{builder1.Get(), builder2.Get()}, + Ports: []int32{81}, + Protocol: protocol, }, } testCase := []*TestCase{ @@ -189,19 +183,17 @@ func testNodeACNPDropEgress(t *testing.T, protocol AntreaPolicyProtocol) { SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder.AddEgress(protocol, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachability := NewReachability(allPods, Connected) - reachability.Expect(Pod(namespaces["x"]+"/a"), Pod(namespaces["y"]+"/a"), Dropped) + reachability.Expect(getPod("x", "a"), getPod("y", "a"), Dropped) testStep := []*TestStep{ { - "Port 80", - reachability, - []metav1.Object{builder.Get()}, - []int32{80}, - protocol, - 0, - nil, + Name: "Port 80", + Reachability: reachability, + TestResources: []metav1.Object{builder.Get()}, + Ports: []int32{80}, + Protocol: protocol, }, } testCase := []*TestCase{ @@ -225,19 +217,17 @@ func testNodeACNPDropIngress(t *testing.T, protocol AntreaPolicyProtocol) { SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder.AddIngress(protocol, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachability := NewReachability(allPods, Connected) - reachability.Expect(Pod(namespaces["y"]+"/a"), Pod(namespaces["x"]+"/a"), Dropped) + reachability.Expect(getPod("y", "a"), getPod("x", "a"), Dropped) testStep := []*TestStep{ { - "Port 80", - reachability, - []metav1.Object{builder.Get()}, - []int32{80}, - protocol, - 0, - nil, + Name: "Port 80", + Reachability: reachability, + TestResources: []metav1.Object{builder.Get()}, + Ports: []int32{80}, + Protocol: protocol, }, } testCase := []*TestCase{ @@ -253,19 +243,17 @@ func testNodeACNPPortRange(t *testing.T) { SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder.AddEgress(ProtocolTCP, &p8080, nil, &p8082, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, "", "acnp-port-range", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "acnp-port-range", nil) reachability := NewReachability(allPods, Connected) - reachability.Expect(Pod(namespaces["x"]+"/a"), Pod(namespaces["y"]+"/a"), Dropped) + reachability.Expect(getPod("x", "a"), getPod("y", "a"), Dropped) testSteps := []*TestStep{ { - fmt.Sprintf("ACNP Drop Ports 8080:8082"), - reachability, - []metav1.Object{builder.Get()}, - []int32{8080, 8081, 8082}, - ProtocolTCP, - 0, - nil, + Name: fmt.Sprintf("ACNP Drop Ports 8080:8082"), + Reachability: reachability, + TestResources: []metav1.Object{builder.Get()}, + Ports: []int32{8080, 8081, 8082}, + Protocol: ProtocolTCP, }, } @@ -280,7 +268,7 @@ func testNodeACNPPortRange(t *testing.T) { // This test retrieves the port range from the client Pod and uses it in sourcePort and sourceEndPort of an ACNP rule to // verify that packets can be matched by source port. func testNodeACNPSourcePort(t *testing.T) { - portStart, portEnd, err := k8sUtils.getTCPv4SourcePortRangeFromPod(namespaces["x"], "a") + portStart, portEnd, err := k8sUtils.getTCPv4SourcePortRangeFromPod(getNS("x"), "a") failOnError(err, t) builder := &ClusterNetworkPolicySpecBuilder{} builder = builder.SetName("acnp-source-port"). @@ -304,37 +292,31 @@ func testNodeACNPSourcePort(t *testing.T) { nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachability := NewReachability(allPods, Connected) - reachability.Expect(Pod(namespaces["y"]+"/a"), Pod(namespaces["x"]+"/a"), Dropped) + reachability.Expect(getPod("y", "a"), getPod("x", "a"), Dropped) // After adding the dst port constraint of port 80, traffic on port 81 should not be affected. updatedReachability := NewReachability(allPods, Connected) testSteps := []*TestStep{ { - "Port 80", - reachability, - []metav1.Object{builder.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Port 80", + Reachability: reachability, + TestResources: []metav1.Object{builder.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, { - "Port 81", - updatedReachability, - []metav1.Object{builder2.Get()}, - []int32{81}, - ProtocolTCP, - 0, - nil, + Name: "Port 81", + Reachability: updatedReachability, + TestResources: []metav1.Object{builder2.Get()}, + Ports: []int32{81}, + Protocol: ProtocolTCP, }, { - "Port range 80-81", - reachability, - []metav1.Object{builder3.Get()}, - []int32{80, 81}, - ProtocolTCP, - 0, - nil, + Name: "Port range 80-81", + Reachability: reachability, + TestResources: []metav1.Object{builder3.Get()}, + Ports: []int32{80, 81}, + Protocol: ProtocolTCP, }, } testCase := []*TestCase{ @@ -367,7 +349,7 @@ func testNodeACNPRejectEgress(t *testing.T, protocol AntreaPolicyProtocol) { SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder.AddEgress(protocol, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionReject, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionReject, "", "", nil) reachability := NewReachability(allPods, Connected) @@ -376,16 +358,14 @@ func testNodeACNPRejectEgress(t *testing.T, protocol AntreaPolicyProtocol) { if protocol == ProtocolSCTP { expectedResult = Dropped } - reachability.Expect(Pod(namespaces["x"]+"/a"), Pod(namespaces["y"]+"/a"), expectedResult) + reachability.Expect(getPod("x", "a"), getPod("y", "a"), expectedResult) testStep := []*TestStep{ { - "Port 80", - reachability, - []metav1.Object{builder.Get()}, - []int32{80}, - protocol, - 0, - nil, + Name: "Port 80", + Reachability: reachability, + TestResources: []metav1.Object{builder.Get()}, + Ports: []int32{80}, + Protocol: protocol, }, } testCase := []*TestCase{ @@ -401,19 +381,17 @@ func testNodeACNPRejectIngress(t *testing.T, protocol AntreaPolicyProtocol) { SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder.AddIngress(protocol, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionReject, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionReject, "", "", nil) reachability := NewReachability(allPods, Connected) - reachability.Expect(Pod(namespaces["y"]+"/a"), Pod(namespaces["x"]+"/a"), Rejected) + reachability.Expect(getPod("y", "a"), getPod("x", "a"), Rejected) testStep := []*TestStep{ { - "Port 80", - reachability, - []metav1.Object{builder.Get()}, - []int32{80}, - protocol, - 0, - nil, + Name: "Port 80", + Reachability: reachability, + TestResources: []metav1.Object{builder.Get()}, + Ports: []int32{80}, + Protocol: protocol, }, } testCase := []*TestCase{ @@ -429,31 +407,27 @@ func testNodeACNPNoEffectOnOtherProtocols(t *testing.T) { SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachability1 := NewReachability(allPods, Connected) - reachability1.Expect(Pod(namespaces["y"]+"/a"), Pod(namespaces["x"]+"/a"), Dropped) + reachability1.Expect(getPod("y", "a"), getPod("x", "a"), Dropped) reachability2 := NewReachability(allPods, Connected) testStep := []*TestStep{ { - "Port 80", - reachability1, - []metav1.Object{builder.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Port 80", + Reachability: reachability1, + TestResources: []metav1.Object{builder.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, { - "Port 80", - reachability2, - []metav1.Object{builder.Get()}, - []int32{80}, - ProtocolUDP, - 0, - nil, + Name: "Port 80", + Reachability: reachability2, + TestResources: []metav1.Object{builder.Get()}, + Ports: []int32{80}, + Protocol: ProtocolUDP, }, } testCase := []*TestCase{ @@ -471,7 +445,7 @@ func testNodeACNPPriorityOverride(t *testing.T) { SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) // Highest priority. Drops traffic from y to x. builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) builder2 := &ClusterNetworkPolicySpecBuilder{} builder2 = builder2.SetName("acnp-priority2"). @@ -479,7 +453,7 @@ func testNodeACNPPriorityOverride(t *testing.T) { SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) // Medium priority. Allows traffic from y to x. builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionAllow, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) builder3 := &ClusterNetworkPolicySpecBuilder{} builder3 = builder3.SetName("acnp-priority3"). @@ -487,34 +461,30 @@ func testNodeACNPPriorityOverride(t *testing.T) { SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) // Lowest priority. Drops traffic from y to x. builder3.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachabilityTwoACNPs := NewReachability(allPods, Connected) reachabilityAllACNPs := NewReachability(allPods, Connected) - reachabilityAllACNPs.Expect(Pod(namespaces["y"]+"/a"), Pod(namespaces["x"]+"/a"), Dropped) + reachabilityAllACNPs.Expect(getPod("y", "a"), getPod("x", "a"), Dropped) testStepTwoACNP := []*TestStep{ { - "Two Policies with different priorities", - reachabilityTwoACNPs, - []metav1.Object{builder3.Get(), builder2.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Two Policies with different priorities", + Reachability: reachabilityTwoACNPs, + TestResources: []metav1.Object{builder3.Get(), builder2.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, } // Create the Policies in specific order to make sure that priority re-assignments work as expected. testStepAll := []*TestStep{ { - "All three Policies", - reachabilityAllACNPs, - []metav1.Object{builder3.Get(), builder1.Get(), builder2.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "All three Policies", + Reachability: reachabilityAllACNPs, + TestResources: []metav1.Object{builder3.Get(), builder1.Get(), builder2.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, } testCase := []*TestCase{ @@ -534,51 +504,47 @@ func testNodeACNPTierOverride(t *testing.T) { SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) // Highest priority tier. Drops traffic from y to x. builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) builder2 := &ClusterNetworkPolicySpecBuilder{} builder2 = builder2.SetName("acnp-tier-securityops"). SetTier("securityops"). SetPriority(10). - SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}, NSSelector: map[string]string{"ns": namespaces["x"]}}}) + SetAppliedToGroup([]ACNPAppliedToSpec{{PodSelector: map[string]string{"pod": "a"}, NSSelector: map[string]string{"ns": getNS("x")}}}) // Medium priority tier. Allows traffic from y to x. builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionAllow, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) builder3 := &ClusterNetworkPolicySpecBuilder{} builder3 = builder3.SetName("acnp-tier-application"). SetTier("application"). SetPriority(1). - SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{"ns": namespaces["x"]}}}) + SetAppliedToGroup([]ACNPAppliedToSpec{{NSSelector: map[string]string{"ns": getNS("x")}}}) // Lowest priority tier. Drops traffic from y to x. builder3.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachabilityTwoACNPs := NewReachability(allPods, Connected) reachabilityAllACNPs := NewReachability(allPods, Connected) - reachabilityAllACNPs.Expect(Pod(namespaces["y"]+"/a"), Pod(namespaces["x"]+"/a"), Dropped) + reachabilityAllACNPs.Expect(getPod("y", "a"), getPod("x", "a"), Dropped) testStepTwoACNP := []*TestStep{ { - "Two Policies in different tiers", - reachabilityTwoACNPs, - []metav1.Object{builder3.Get(), builder2.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Two Policies in different tiers", + Reachability: reachabilityTwoACNPs, + TestResources: []metav1.Object{builder3.Get(), builder2.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, } testStepAll := []*TestStep{ { - "All three Policies in different tiers", - reachabilityAllACNPs, - []metav1.Object{builder3.Get(), builder1.Get(), builder2.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "All three Policies in different tiers", + Reachability: reachabilityAllACNPs, + TestResources: []metav1.Object{builder3.Get(), builder1.Get(), builder2.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, } testCase := []*TestCase{ @@ -606,7 +572,7 @@ func testNodeACNPCustomTiers(t *testing.T) { SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) // Medium priority tier. Allows traffic from y to x. builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionAllow, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) builder2 := &ClusterNetworkPolicySpecBuilder{} builder2 = builder2.SetName("acnp-tier-low"). @@ -615,32 +581,28 @@ func testNodeACNPCustomTiers(t *testing.T) { SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) // Lowest priority tier. Drops traffic from y to x. builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachabilityOneACNP := NewReachability(allPods, Connected) - reachabilityOneACNP.Expect(Pod(namespaces["y"]+"/a"), Pod(namespaces["x"]+"/a"), Dropped) + reachabilityOneACNP.Expect(getPod("y", "a"), getPod("x", "a"), Dropped) testStepOneACNP := []*TestStep{ { - "One Policy", - reachabilityOneACNP, - []metav1.Object{builder2.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "One Policy", + Reachability: reachabilityOneACNP, + TestResources: []metav1.Object{builder2.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, } reachabilityTwoACNPs := NewReachability(allPods, Connected) testStepTwoACNP := []*TestStep{ { - "Two Policies in different tiers", - reachabilityTwoACNPs, - []metav1.Object{builder2.Get(), builder1.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Two Policies in different tiers", + Reachability: reachabilityTwoACNPs, + TestResources: []metav1.Object{builder2.Get(), builder1.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, } testCase := []*TestCase{ @@ -663,7 +625,7 @@ func testNodeACNPPriorityConflictingRule(t *testing.T) { SetPriority(1). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder1.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) builder2 := &ClusterNetworkPolicySpecBuilder{} builder2 = builder2.SetName("acnp-allow"). @@ -672,19 +634,17 @@ func testNodeACNPPriorityConflictingRule(t *testing.T) { // The following ingress rule will take no effect as it is exactly the same as ingress rule of cnp-drop, // but cnp-allow has lower priority. builder2.AddIngress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{labelNodeHostname: nodes["y"]}, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionAllow, "", "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionAllow, "", "", nil) reachabilityBothACNP := NewReachability(allPods, Connected) - reachabilityBothACNP.Expect(Pod(namespaces["y"]+"/a"), Pod(namespaces["x"]+"/a"), Dropped) + reachabilityBothACNP.Expect(getPod("y", "a"), getPod("x", "a"), Dropped) testStep := []*TestStep{ { - "Both ACNP", - reachabilityBothACNP, - []metav1.Object{builder1.Get(), builder2.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Both ACNP", + Reachability: reachabilityBothACNP, + TestResources: []metav1.Object{builder1.Get(), builder2.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, } testCase := []*TestCase{ @@ -699,19 +659,17 @@ func testNodeACNPNamespaceIsolation(t *testing.T) { SetTier("baseline"). SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) - builder1.AddEgress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": namespaces["y"]}, nil, nil, nil, - false, nil, crdv1beta1.RuleActionDrop, "", "", nil) + builder1.AddEgress(ProtocolTCP, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, map[string]string{"ns": getNS("y")}, nil, nil, nil, + nil, nil, crdv1beta1.RuleActionDrop, "", "", nil) reachability1 := NewReachability(allPods, Connected) - reachability1.ExpectEgressToNamespace(Pod(namespaces["x"]+"/a"), namespaces["y"], Dropped) + reachability1.ExpectEgressToNamespace(getPod("x", "a"), getNS("y"), Dropped) testStep1 := &TestStep{ - "Port 80", - reachability1, - []metav1.Object{builder1.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Port 80", + Reachability: reachability1, + TestResources: []metav1.Object{builder1.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, } testCase := []*TestCase{ @@ -723,40 +681,36 @@ func testNodeACNPNamespaceIsolation(t *testing.T) { func testNodeACNPClusterGroupUpdate(t *testing.T) { cgName := "cg-ns-z-then-y" cgBuilder := &ClusterGroupSpecBuilder{} - cgBuilder = cgBuilder.SetName(cgName).SetNamespaceSelector(map[string]string{"ns": namespaces["z"]}, nil) + cgBuilder = cgBuilder.SetName(cgName).SetNamespaceSelector(map[string]string{"ns": getNS("z")}, nil) // Update CG NS selector to group Pods from Namespace Y updatedCgBuilder := &ClusterGroupSpecBuilder{} - updatedCgBuilder = updatedCgBuilder.SetName(cgName).SetNamespaceSelector(map[string]string{"ns": namespaces["y"]}, nil) + updatedCgBuilder = updatedCgBuilder.SetName(cgName).SetNamespaceSelector(map[string]string{"ns": getNS("y")}, nil) builder := &ClusterNetworkPolicySpecBuilder{} builder = builder.SetName("acnp-deny-a-to-cg-with-z-egress"). SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, cgName, "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, cgName, "", nil) reachability := NewReachability(allPods, Connected) - reachability.ExpectEgressToNamespace(Pod(namespaces["x"]+"/a"), namespaces["z"], Dropped) + reachability.ExpectEgressToNamespace(getPod("x", "a"), getNS("z"), Dropped) updatedReachability := NewReachability(allPods, Connected) - updatedReachability.ExpectEgressToNamespace(Pod(namespaces["x"]+"/a"), namespaces["y"], Dropped) + updatedReachability.ExpectEgressToNamespace(getPod("x", "a"), getNS("y"), Dropped) testStep := []*TestStep{ { - "Port 80", - reachability, - []metav1.Object{cgBuilder.Get(), builder.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Port 80", + Reachability: reachability, + TestResources: []metav1.Object{cgBuilder.Get(), builder.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, { - "Port 80 - update", - updatedReachability, - []metav1.Object{updatedCgBuilder.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Port 80 - update", + Reachability: updatedReachability, + TestResources: []metav1.Object{updatedCgBuilder.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, } testCase := []*TestCase{ @@ -766,8 +720,8 @@ func testNodeACNPClusterGroupUpdate(t *testing.T) { } func testNodeACNPClusterGroupRefRuleIPBlocks(t *testing.T) { - podYAIP, _ := podIPs[namespaces["y"]+"/a"] - podZAIP, _ := podIPs[namespaces["z"]+"/a"] + podYAIP, _ := podIPs[getNS("y")+"/a"] + podZAIP, _ := podIPs[getNS("z")+"/a"] // There are three situations of a Pod's IP(s): // 1. Only one IPv4 address. // 2. Only one IPv6 address. @@ -799,22 +753,20 @@ func testNodeACNPClusterGroupRefRuleIPBlocks(t *testing.T) { SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, cgName, "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, cgName, "", nil) builder.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, cgName2, "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, cgName2, "", nil) reachability := NewReachability(allPods, Connected) - reachability.Expect(Pod(namespaces["x"]+"/a"), Pod(namespaces["y"]+"/a"), Dropped) - reachability.Expect(Pod(namespaces["x"]+"/a"), Pod(namespaces["z"]+"/a"), Dropped) + reachability.Expect(getPod("x", "a"), getPod("y", "a"), Dropped) + reachability.Expect(getPod("x", "a"), getPod("z", "a"), Dropped) testStep := []*TestStep{ { - "Port 80", - reachability, - []metav1.Object{builder.Get(), cgBuilder.Get(), cgBuilder2.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Port 80", + Reachability: reachability, + TestResources: []metav1.Object{builder.Get(), cgBuilder.Get(), cgBuilder2.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, }, } testCase := []*TestCase{ @@ -826,7 +778,7 @@ func testNodeACNPClusterGroupRefRuleIPBlocks(t *testing.T) { func testNodeACNPNestedClusterGroupCreateAndUpdate(t *testing.T, data *TestData) { cg1Name := "cg-1" cgBuilder1 := &ClusterGroupSpecBuilder{} - cgBuilder1 = cgBuilder1.SetName(cg1Name).SetNamespaceSelector(map[string]string{"ns": namespaces["y"]}, nil) + cgBuilder1 = cgBuilder1.SetName(cg1Name).SetNamespaceSelector(map[string]string{"ns": getNS("y")}, nil) cgNestedName := "cg-nested" cgBuilderNested := &ClusterGroupSpecBuilder{} cgBuilderNested = cgBuilderNested.SetName(cgNestedName).SetChildGroups([]string{cg1Name}) @@ -835,35 +787,31 @@ func testNodeACNPNestedClusterGroupCreateAndUpdate(t *testing.T, data *TestData) builder = builder.SetName("cnp-nested-cg").SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}). AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, - false, nil, crdv1beta1.RuleActionDrop, cgNestedName, "", nil) + nil, nil, crdv1beta1.RuleActionDrop, cgNestedName, "", nil) reachability := NewReachability(allPods, Connected) - reachability.ExpectEgressToNamespace(Pod(namespaces["x"]+"/a"), namespaces["y"], Dropped) + reachability.ExpectEgressToNamespace(getPod("x", "a"), getNS("y"), Dropped) testStep1 := &TestStep{ - "Port 80", - reachability, + Name: "Port 80", + Reachability: reachability, // Note in this testcase the ClusterGroup is created after the ACNP - []metav1.Object{builder.Get(), cgBuilder1.Get(), cgBuilderNested.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + TestResources: []metav1.Object{builder.Get(), cgBuilder1.Get(), cgBuilderNested.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, } cg2Name := "cg-2" cgBuilder2 := &ClusterGroupSpecBuilder{} - cgBuilder2 = cgBuilder2.SetName(cg2Name).SetNamespaceSelector(map[string]string{"ns": namespaces["z"]}, nil) + cgBuilder2 = cgBuilder2.SetName(cg2Name).SetNamespaceSelector(map[string]string{"ns": getNS("z")}, nil) cgBuilderNested = cgBuilderNested.SetChildGroups([]string{cg2Name}) reachability2 := NewReachability(allPods, Connected) - reachability2.ExpectEgressToNamespace(Pod(namespaces["x"]+"/a"), namespaces["z"], Dropped) + reachability2.ExpectEgressToNamespace(getPod("x", "a"), getNS("z"), Dropped) testStep2 := &TestStep{ - "Port 80 updated", - reachability2, - []metav1.Object{cgBuilder2.Get(), cgBuilderNested.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Port 80 updated", + Reachability: reachability2, + TestResources: []metav1.Object{cgBuilder2.Get(), cgBuilderNested.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, } testSteps := []*TestStep{testStep1, testStep2} @@ -874,8 +822,8 @@ func testNodeACNPNestedClusterGroupCreateAndUpdate(t *testing.T, data *TestData) } func testNodeACNPNestedIPBlockClusterGroupCreateAndUpdate(t *testing.T) { - podYAIP, _ := podIPs[namespaces["y"]+"/a"] - podZAIP, _ := podIPs[namespaces["z"]+"/a"] + podYAIP, _ := podIPs[getPodName("y", "a")] + podZAIP, _ := podIPs[getPodName("z", "a")] genCIDR := func(ip string) string { switch IPFamily(ip) { case "v4": @@ -905,33 +853,29 @@ func testNodeACNPNestedIPBlockClusterGroupCreateAndUpdate(t *testing.T) { SetPriority(1.0). SetAppliedToGroup([]ACNPAppliedToSpec{{NodeSelector: map[string]string{labelNodeHostname: nodes["x"]}}}) builder.AddEgress(ProtocolTCP, &p80, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, - nil, nil, nil, false, nil, crdv1beta1.RuleActionDrop, cgParentName, "", nil) + nil, nil, nil, nil, nil, crdv1beta1.RuleActionDrop, cgParentName, "", nil) reachability := NewReachability(allPods, Connected) - reachability.Expect(Pod(namespaces["x"]+"/a"), Pod(namespaces["y"]+"/a"), Dropped) - reachability.Expect(Pod(namespaces["x"]+"/a"), Pod(namespaces["z"]+"/a"), Dropped) + reachability.Expect(getPod("x", "a"), getPod("y", "a"), Dropped) + reachability.Expect(getPod("x", "a"), getPod("z", "a"), Dropped) testStep := &TestStep{ - "Port 80", - reachability, - []metav1.Object{builder.Get(), cgBuilder1.Get(), cgBuilder2.Get(), cgParent.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Port 80", + Reachability: reachability, + TestResources: []metav1.Object{builder.Get(), cgBuilder1.Get(), cgBuilder2.Get(), cgParent.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, } cgParent = cgParent.SetChildGroups([]string{cg1Name}) reachability2 := NewReachability(allPods, Connected) - reachability2.Expect(Pod(namespaces["x"]+"/a"), Pod(namespaces["y"]+"/a"), Dropped) + reachability2.Expect(getPod("x", "a"), getPod("y", "a"), Dropped) testStep2 := &TestStep{ - "Port 80, updated", - reachability2, - []metav1.Object{cgParent.Get()}, - []int32{80}, - ProtocolTCP, - 0, - nil, + Name: "Port 80, updated", + Reachability: reachability2, + TestResources: []metav1.Object{cgParent.Get()}, + Ports: []int32{80}, + Protocol: ProtocolTCP, } testCase := []*TestCase{