github.com/zhyoulun/cilium@v1.6.12/test/k8sT/Policies.go (about)

     1  // Copyright 2017-2019 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package k8sTest
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"time"
    21  
    22  	. "github.com/cilium/cilium/test/ginkgo-ext"
    23  	"github.com/cilium/cilium/test/helpers"
    24  	. "github.com/onsi/gomega"
    25  	"github.com/onsi/gomega/types"
    26  	"github.com/sirupsen/logrus"
    27  )
    28  
    29  var _ = Describe("K8sPolicyTest", func() {
    30  
    31  	var (
    32  		kubectl              *helpers.Kubectl
    33  		demoPath             = helpers.ManifestGet("demo.yaml")
    34  		l3Policy             = helpers.ManifestGet("l3-l4-policy.yaml")
    35  		l7Policy             = helpers.ManifestGet("l7-policy.yaml")
    36  		l7PolicyKafka        = helpers.ManifestGet("l7-policy-kafka.yaml")
    37  		serviceAccountPolicy = helpers.ManifestGet("service-account.yaml")
    38  		knpDenyIngress       = helpers.ManifestGet("knp-default-deny-ingress.yaml")
    39  		knpDenyEgress        = helpers.ManifestGet("knp-default-deny-egress.yaml")
    40  		knpDenyIngressEgress = helpers.ManifestGet("knp-default-deny-ingress-egress.yaml")
    41  		cnpDenyIngress       = helpers.ManifestGet("cnp-default-deny-ingress.yaml")
    42  		cnpDenyEgress        = helpers.ManifestGet("cnp-default-deny-egress.yaml")
    43  		knpAllowIngress      = helpers.ManifestGet("knp-default-allow-ingress.yaml")
    44  		knpAllowEgress       = helpers.ManifestGet("knp-default-allow-egress.yaml")
    45  		cnpMatchExpression   = helpers.ManifestGet("cnp-matchexpressions.yaml")
    46  		app1Service          = "app1-service"
    47  		microscopeErr        error
    48  		microscopeCancel                        = func() error { return nil }
    49  		backgroundCancel     context.CancelFunc = func() { return }
    50  		backgroundError      error
    51  		apps                 = []string{helpers.App1, helpers.App2, helpers.App3}
    52  	)
    53  
    54  	BeforeAll(func() {
    55  		kubectl = helpers.CreateKubectl(helpers.K8s1VMName(), logger)
    56  		DeployCiliumAndDNS(kubectl)
    57  	})
    58  
    59  	AfterEach(func() {
    60  		ExpectAllPodsTerminated(kubectl)
    61  	})
    62  
    63  	AfterFailed(func() {
    64  		kubectl.CiliumReport(helpers.KubeSystemNamespace,
    65  			"cilium service list",
    66  			"cilium endpoint list")
    67  	})
    68  
    69  	AfterAll(func() {
    70  		ExpectAllPodsTerminated(kubectl)
    71  		kubectl.CloseSSHClient()
    72  	})
    73  
    74  	JustBeforeEach(func() {
    75  		microscopeErr, microscopeCancel = kubectl.MicroscopeStart()
    76  		Expect(microscopeErr).To(BeNil(), "Microscope cannot be started")
    77  
    78  		backgroundCancel, backgroundError = kubectl.BackgroundReport("uptime")
    79  		Expect(backgroundError).To(BeNil(), "Cannot start background report process")
    80  	})
    81  
    82  	JustAfterEach(func() {
    83  		kubectl.ValidateNoErrorsInLogs(CurrentGinkgoTestDescription().Duration)
    84  		Expect(microscopeCancel()).To(BeNil(), "cannot stop microscope")
    85  		backgroundCancel()
    86  	})
    87  
    88  	Context("Basic Test", func() {
    89  		var (
    90  			ciliumPod        string
    91  			clusterIP        string
    92  			appPods          map[string]string
    93  			namespaceForTest string
    94  		)
    95  
    96  		importPolicy := func(file, name string) {
    97  			_, err := kubectl.CiliumPolicyAction(
    98  				namespaceForTest, file, helpers.KubectlApply, helpers.HelperTimeout)
    99  			ExpectWithOffset(1, err).Should(BeNil(),
   100  				"policy %s cannot be applied in %q namespace", file, namespaceForTest)
   101  		}
   102  
   103  		// getMatcher returns a helper.CMDSucess() matcher for success or
   104  		// failure situations.
   105  		getMatcher := func(val bool) types.GomegaMatcher {
   106  			if val {
   107  				return helpers.CMDSuccess()
   108  			}
   109  			return Not(helpers.CMDSuccess())
   110  		}
   111  
   112  		validateConnectivity := func(expectWorldSuccess, expectClusterSuccess bool) {
   113  			for _, pod := range []string{appPods[helpers.App2], appPods[helpers.App3]} {
   114  				By("HTTP connectivity to 1.1.1.1")
   115  				res := kubectl.ExecPodCmd(
   116  					namespaceForTest, pod,
   117  					helpers.CurlFail("http://1.1.1.1/"))
   118  
   119  				ExpectWithOffset(1, res).To(getMatcher(expectWorldSuccess),
   120  					"HTTP egress connectivity to 1.1.1.1 from pod %q", pod)
   121  
   122  				By("ICMP connectivity to 8.8.8.8")
   123  				res = kubectl.ExecPodCmd(
   124  					namespaceForTest, pod,
   125  					helpers.Ping("8.8.8.8"))
   126  
   127  				ExpectWithOffset(1, res).To(getMatcher(expectWorldSuccess),
   128  					"ICMP egress connectivity to 8.8.8.8 from pod %q", pod)
   129  
   130  				By("DNS lookup of kubernetes.default.svc.cluster.local")
   131  				res = kubectl.ExecPodCmd(
   132  					namespaceForTest, pod,
   133  					"host -v kubernetes.default.svc.cluster.local")
   134  
   135  				// kube-dns is always whitelisted so this should always work
   136  				ExpectWithOffset(1, res).To(getMatcher(expectWorldSuccess || expectClusterSuccess),
   137  					"DNS connectivity of kubernetes.default.svc.cluster.local from pod %q", pod)
   138  
   139  				By("HTTP connectivity from pod to pod")
   140  				res = kubectl.ExecPodCmd(
   141  					namespaceForTest, pod,
   142  					helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   143  
   144  				ExpectWithOffset(1, res).To(getMatcher(expectClusterSuccess),
   145  					"HTTP connectivity to clusterIP %q of app1 from pod %q", clusterIP, appPods[helpers.App2])
   146  			}
   147  		}
   148  
   149  		BeforeAll(func() {
   150  			namespaceForTest = helpers.GenerateNamespaceForTest()
   151  			kubectl.NamespaceCreate(namespaceForTest).ExpectSuccess("could not create namespace")
   152  			kubectl.Apply(helpers.ApplyOptions{FilePath: demoPath, Namespace: namespaceForTest}).ExpectSuccess("could not create resource")
   153  
   154  			err := kubectl.WaitforPods(namespaceForTest, "-l zgroup=testapp", helpers.HelperTimeout)
   155  			Expect(err).Should(BeNil(), "Test pods are not ready after timeout")
   156  
   157  			ciliumPod, err = kubectl.GetCiliumPodOnNode(helpers.KubeSystemNamespace, helpers.K8s1)
   158  			Expect(err).Should(BeNil(), "cannot get CiliumPod")
   159  
   160  			clusterIP, _, err = kubectl.GetServiceHostPort(namespaceForTest, app1Service)
   161  			Expect(err).To(BeNil(), "Cannot get service in %q namespace", namespaceForTest)
   162  			appPods = helpers.GetAppPods(apps, namespaceForTest, kubectl, "id")
   163  			logger.WithFields(logrus.Fields{
   164  				"ciliumPod": ciliumPod,
   165  				"clusterIP": clusterIP}).Info("Initial data")
   166  
   167  		})
   168  
   169  		AfterAll(func() {
   170  			kubectl.NamespaceDelete(namespaceForTest)
   171  			kubectl.Delete(demoPath)
   172  		})
   173  
   174  		BeforeEach(func() {
   175  			status := kubectl.CiliumExec(
   176  				ciliumPod, fmt.Sprintf("cilium config %s=%s",
   177  					helpers.PolicyEnforcement, helpers.PolicyEnforcementDefault))
   178  			status.ExpectSuccess()
   179  
   180  			err := kubectl.CiliumEndpointWaitReady()
   181  			Expect(err).To(BeNil(), "Endpoints are not ready after timeout")
   182  
   183  			err = kubectl.WaitforPods(namespaceForTest, "-l zgroup=testapp", helpers.HelperTimeout)
   184  			Expect(err).Should(BeNil())
   185  
   186  		})
   187  
   188  		AfterEach(func() {
   189  			cmd := fmt.Sprintf("%s delete --all cnp,netpol -n %s", helpers.KubectlCmd, namespaceForTest)
   190  			_ = kubectl.Exec(cmd)
   191  		})
   192  
   193  		It("checks all kind of Kubernetes policies", func() {
   194  
   195  			logger.Infof("PolicyRulesTest: cluster service ip '%s'", clusterIP)
   196  
   197  			By("Testing L3/L4 rules")
   198  
   199  			_, err := kubectl.CiliumPolicyAction(
   200  				namespaceForTest, l3Policy, helpers.KubectlApply, helpers.HelperTimeout)
   201  			Expect(err).Should(BeNil())
   202  
   203  			for _, appName := range []string{helpers.App1, helpers.App2, helpers.App3} {
   204  				err = kubectl.WaitForCEPIdentity(namespaceForTest, appPods[appName])
   205  				Expect(err).Should(BeNil())
   206  			}
   207  
   208  			trace := kubectl.CiliumExec(ciliumPod, fmt.Sprintf(
   209  				"cilium policy trace --src-k8s-pod %s:%s --dst-k8s-pod %s:%s --dport 80/TCP",
   210  				namespaceForTest, appPods[helpers.App2], namespaceForTest, appPods[helpers.App1]))
   211  			trace.ExpectSuccess(trace.CombineOutput().String())
   212  			trace.ExpectContains("Final verdict: ALLOWED", "Policy trace output mismatch")
   213  
   214  			trace = kubectl.CiliumExec(ciliumPod, fmt.Sprintf(
   215  				"cilium policy trace --src-k8s-pod %s:%s --dst-k8s-pod %s:%s",
   216  				namespaceForTest, appPods[helpers.App3], namespaceForTest, appPods[helpers.App1]))
   217  			trace.ExpectSuccess(trace.CombineOutput().String())
   218  			trace.ExpectContains("Final verdict: DENIED", "Policy trace output mismatch")
   219  
   220  			res := kubectl.ExecPodCmd(
   221  				namespaceForTest, appPods[helpers.App2],
   222  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   223  			res.ExpectSuccess("%q cannot curl clusterIP %q", appPods[helpers.App2], clusterIP)
   224  
   225  			res = kubectl.ExecPodCmd(
   226  				namespaceForTest, appPods[helpers.App3],
   227  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   228  			res.ExpectFail("%q can curl to %q", appPods[helpers.App3], clusterIP)
   229  
   230  			_, err = kubectl.CiliumPolicyAction(
   231  				namespaceForTest, l3Policy,
   232  				helpers.KubectlDelete, helpers.HelperTimeout)
   233  			Expect(err).Should(BeNil(), "Cannot delete L3 Policy")
   234  
   235  			By("Testing L7 Policy")
   236  
   237  			_, err = kubectl.CiliumPolicyAction(
   238  				namespaceForTest, l7Policy, helpers.KubectlApply, helpers.HelperTimeout)
   239  			Expect(err).Should(BeNil(), "Cannot install %q policy", l7Policy)
   240  
   241  			res = kubectl.ExecPodCmd(
   242  				namespaceForTest, appPods[helpers.App2],
   243  				helpers.CurlFail("http://%s/public", clusterIP))
   244  			res.ExpectSuccess("Cannot connect from %q to 'http://%s/public'",
   245  				appPods[helpers.App2], clusterIP)
   246  
   247  			res = kubectl.ExecPodCmd(
   248  				namespaceForTest, appPods[helpers.App2],
   249  				helpers.CurlFail(fmt.Sprintf("http://%s/private", clusterIP)))
   250  			res.ExpectFail("Unexpected connection from %q to 'http://%s/private'",
   251  				appPods[helpers.App2], clusterIP)
   252  
   253  			res = kubectl.ExecPodCmd(
   254  				namespaceForTest, appPods[helpers.App3],
   255  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   256  			res.ExpectFail("Unexpected connection from %q to 'http://%s/public'",
   257  				appPods[helpers.App3], clusterIP)
   258  
   259  			res = kubectl.ExecPodCmd(
   260  				namespaceForTest, appPods[helpers.App3],
   261  				helpers.CurlFail("http://%s/private", clusterIP))
   262  			res.ExpectFail("Unexpected connection from %q to 'http://%s/private'",
   263  				appPods[helpers.App3], clusterIP)
   264  		}, 500)
   265  
   266  		It("Invalid Policy report status correctly", func() {
   267  			manifest := helpers.ManifestGet("invalid_cnp.yaml")
   268  			cnpName := "foo"
   269  			kubectl.Apply(helpers.ApplyOptions{FilePath: manifest, Namespace: namespaceForTest}).ExpectSuccess("Cannot apply policy manifest")
   270  
   271  			body := func() bool {
   272  				cnp := kubectl.GetCNP(namespaceForTest, cnpName)
   273  				if cnp != nil && len(cnp.Status.Nodes) > 0 {
   274  					for _, node := range cnp.Status.Nodes {
   275  						if node.Error == "" {
   276  							return false
   277  						}
   278  					}
   279  					return true
   280  				}
   281  				return false
   282  			}
   283  
   284  			err := helpers.WithTimeout(
   285  				body,
   286  				fmt.Sprintf("CNP %q does not report the status correctly after timeout", cnpName),
   287  				&helpers.TimeoutConfig{Timeout: 100 * time.Second})
   288  
   289  			Expect(err).To(BeNil(), "CNP status for invalid policy did not update correctly")
   290  		})
   291  
   292  		It("ServiceAccount Based Enforcement", func() {
   293  			// Load policy allowing serviceAccount of app2 to talk
   294  			// to app1 on port 80 TCP
   295  			_, err := kubectl.CiliumPolicyAction(
   296  				namespaceForTest, serviceAccountPolicy, helpers.KubectlApply, helpers.HelperTimeout)
   297  			Expect(err).Should(BeNil())
   298  
   299  			for _, appName := range []string{helpers.App1, helpers.App2, helpers.App3} {
   300  				err = kubectl.WaitForCEPIdentity(namespaceForTest, appPods[appName])
   301  				Expect(err).Should(BeNil())
   302  			}
   303  
   304  			trace := kubectl.CiliumExec(ciliumPod, fmt.Sprintf(
   305  				"cilium policy trace --src-k8s-pod %s:%s --dst-k8s-pod %s:%s --dport 80/TCP",
   306  				namespaceForTest, appPods[helpers.App2], namespaceForTest, appPods[helpers.App1]))
   307  			trace.ExpectSuccess(trace.CombineOutput().String())
   308  			trace.ExpectContains("Final verdict: ALLOWED", "Policy trace output mismatch")
   309  
   310  			trace = kubectl.CiliumExec(ciliumPod, fmt.Sprintf(
   311  				"cilium policy trace --src-k8s-pod %s:%s --dst-k8s-pod %s:%s",
   312  				namespaceForTest, appPods[helpers.App3], namespaceForTest, appPods[helpers.App1]))
   313  			trace.ExpectSuccess(trace.CombineOutput().String())
   314  			trace.ExpectContains("Final verdict: DENIED", "Policy trace output mismatch")
   315  
   316  			res := kubectl.ExecPodCmd(
   317  				namespaceForTest, appPods[helpers.App2],
   318  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   319  			res.ExpectSuccess("%q cannot curl clusterIP %q", appPods[helpers.App2], clusterIP)
   320  
   321  			res = kubectl.ExecPodCmd(
   322  				namespaceForTest, appPods[helpers.App3],
   323  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   324  			res.ExpectFail("%q can curl to %q", appPods[helpers.App3], clusterIP)
   325  
   326  		}, 500)
   327  
   328  		It("CNP test MatchExpressions key", func() {
   329  			_, err := kubectl.CiliumPolicyAction(
   330  				namespaceForTest, cnpMatchExpression, helpers.KubectlApply, helpers.HelperTimeout)
   331  			Expect(err).Should(BeNil(), "cannot install policy %s", cnpMatchExpression)
   332  
   333  			res := kubectl.ExecPodCmd(
   334  				namespaceForTest, appPods[helpers.App2],
   335  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   336  			res.ExpectSuccess("%q cannot curl clusterIP %q", appPods[helpers.App2], clusterIP)
   337  
   338  			res = kubectl.ExecPodCmd(
   339  				namespaceForTest, appPods[helpers.App3],
   340  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   341  			res.ExpectFail("%q can curl to %q", appPods[helpers.App3], clusterIP)
   342  
   343  		})
   344  
   345  		It("Denies traffic with k8s default-deny ingress policy", func() {
   346  
   347  			res := kubectl.ExecPodCmd(
   348  				namespaceForTest, appPods[helpers.App2],
   349  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   350  			res.ExpectSuccess("%q cannot curl clusterIP %q", appPods[helpers.App2], clusterIP)
   351  
   352  			res = kubectl.ExecPodCmd(
   353  				namespaceForTest, appPods[helpers.App3],
   354  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   355  			res.ExpectSuccess("%q cannot curl to %q", appPods[helpers.App3], clusterIP)
   356  
   357  			By("Installing knp ingress default-deny")
   358  
   359  			// Import the policy and wait for all required endpoints to enforce the policy
   360  			_, err := kubectl.CiliumPolicyAction(
   361  				namespaceForTest, knpDenyIngress, helpers.KubectlApply, helpers.HelperTimeout)
   362  			Expect(err).Should(BeNil(),
   363  				"L3 deny-ingress Policy cannot be applied in %q namespace", namespaceForTest)
   364  
   365  			By("Testing connectivity with ingress default-deny policy loaded")
   366  
   367  			res = kubectl.ExecPodCmd(
   368  				namespaceForTest, appPods[helpers.App2],
   369  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   370  			res.ExpectFail("Ingress connectivity should be denied by policy")
   371  
   372  			res = kubectl.ExecPodCmd(
   373  				namespaceForTest, appPods[helpers.App3],
   374  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   375  			res.ExpectFail("Ingress connectivity should be denied by policy")
   376  		})
   377  
   378  		It("Denies traffic with k8s default-deny egress policy", func() {
   379  			By("Installing knp egress default-deny")
   380  
   381  			_, err := kubectl.CiliumPolicyAction(
   382  				namespaceForTest, knpDenyEgress, helpers.KubectlApply, helpers.HelperTimeout)
   383  			Expect(err).Should(BeNil(),
   384  				"L3 deny-egress Policy cannot be applied in %q namespace", namespaceForTest)
   385  
   386  			By("Testing if egress policy enforcement is enabled on the endpoint")
   387  			for _, pod := range []string{appPods[helpers.App2], appPods[helpers.App3]} {
   388  				res := kubectl.ExecPodCmd(
   389  					namespaceForTest, pod,
   390  					helpers.CurlFail("http://1.1.1.1/"))
   391  				res.ExpectFail("Egress connectivity should be denied for pod %q", pod)
   392  
   393  				res = kubectl.ExecPodCmd(
   394  					namespaceForTest, pod,
   395  					helpers.Ping("8.8.8.8"))
   396  				res.ExpectFail("Egress ping connectivity should be denied for pod %q", pod)
   397  
   398  				res = kubectl.ExecPodCmd(
   399  					namespaceForTest, pod,
   400  					"host kubernetes.default.svc.cluster.local")
   401  				res.ExpectFail("Egress DNS connectivity should be denied for pod %q", pod)
   402  			}
   403  		})
   404  
   405  		It("Denies traffic with k8s default-deny ingress-egress policy", func() {
   406  			By("Installing knp ingress-egress default-deny")
   407  
   408  			_, err := kubectl.CiliumPolicyAction(
   409  				namespaceForTest, knpDenyIngressEgress, helpers.KubectlApply, helpers.HelperTimeout)
   410  			Expect(err).Should(BeNil(),
   411  				"L3 deny-ingress-egress policy cannot be applied in %q namespace", namespaceForTest)
   412  
   413  			By("Testing if egress and ingress policy enforcement is enabled on the endpoint")
   414  			for _, pod := range []string{appPods[helpers.App2], appPods[helpers.App3]} {
   415  				res := kubectl.ExecPodCmd(
   416  					namespaceForTest, pod,
   417  					helpers.CurlFail("http://1.1.1.1/"))
   418  				res.ExpectFail("Egress connectivity should be denied for pod %q", pod)
   419  
   420  				res = kubectl.ExecPodCmd(
   421  					namespaceForTest, pod,
   422  					helpers.Ping("8.8.8.8"))
   423  				res.ExpectFail("Egress ping connectivity should be denied for pod %q", pod)
   424  
   425  				res = kubectl.ExecPodCmd(
   426  					namespaceForTest, pod,
   427  					"host kubernetes.default.svc.cluster.local")
   428  				res.ExpectFail("Egress DNS connectivity should be denied for pod %q", pod)
   429  			}
   430  
   431  			By("Testing ingress connectivity with default-deny policy loaded")
   432  			res := kubectl.ExecPodCmd(
   433  				namespaceForTest, appPods[helpers.App2],
   434  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   435  			res.ExpectFail("Ingress connectivity should be denied by policy")
   436  
   437  			res = kubectl.ExecPodCmd(
   438  				namespaceForTest, appPods[helpers.App3],
   439  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   440  			res.ExpectFail("Ingress connectivity should be denied by policy")
   441  		})
   442  
   443  		It("Denies traffic with cnp default-deny ingress policy", func() {
   444  
   445  			By("Installing cnp ingress default-deny")
   446  
   447  			_, err := kubectl.CiliumPolicyAction(
   448  				namespaceForTest, cnpDenyIngress, helpers.KubectlApply, helpers.HelperTimeout)
   449  			Expect(err).Should(BeNil(),
   450  				"L3 deny-ingress Policy cannot be applied in %q namespace", namespaceForTest)
   451  
   452  			By("Testing connectivity with ingress default-deny policy loaded")
   453  
   454  			res := kubectl.ExecPodCmd(
   455  				namespaceForTest, appPods[helpers.App2],
   456  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   457  			res.ExpectFail("Ingress connectivity should be denied by policy")
   458  
   459  			By("Testing egress connnectivity works correctly")
   460  			res = kubectl.ExecPodCmd(
   461  				namespaceForTest, appPods[helpers.App2],
   462  				helpers.Ping("8.8.8.8"))
   463  			res.ExpectSuccess("Egress ping connectivity should work")
   464  		})
   465  
   466  		It("Denies traffic with cnp default-deny egress policy", func() {
   467  
   468  			By("Installing cnp egress default-deny")
   469  			_, err := kubectl.CiliumPolicyAction(
   470  				namespaceForTest, cnpDenyEgress, helpers.KubectlApply, helpers.HelperTimeout)
   471  			Expect(err).Should(BeNil(),
   472  				"L3 deny-egress Policy cannot be applied in %q namespace", namespaceForTest)
   473  
   474  			for _, pod := range apps {
   475  				res := kubectl.ExecPodCmd(
   476  					namespaceForTest, pod,
   477  					helpers.CurlFail("http://1.1.1.1/"))
   478  				res.ExpectFail("Egress connectivity should be denied for pod %q", pod)
   479  
   480  				res = kubectl.ExecPodCmd(
   481  					namespaceForTest, pod,
   482  					helpers.Ping("8.8.8.8"))
   483  				res.ExpectFail("Egress ping connectivity should be denied for pod %q", pod)
   484  
   485  				res = kubectl.ExecPodCmd(
   486  					namespaceForTest, pod,
   487  					"host kubernetes.default.svc.cluster.local")
   488  				res.ExpectFail("Egress DNS connectivity should be denied for pod %q", pod)
   489  			}
   490  		})
   491  
   492  		It("Allows traffic with k8s default-allow ingress policy", func() {
   493  			By("Installing ingress default-allow")
   494  			_, err := kubectl.CiliumPolicyAction(
   495  				namespaceForTest, knpAllowIngress, helpers.KubectlApply, helpers.HelperTimeout)
   496  			Expect(err).Should(BeNil(),
   497  				"L3 allow-ingress Policy cannot be applied in %q namespace", namespaceForTest)
   498  
   499  			By("Testing connectivity with ingress default-allow policy loaded")
   500  			res := kubectl.ExecPodCmd(
   501  				namespaceForTest, appPods[helpers.App2],
   502  				helpers.CurlFail("http://%s/public", clusterIP))
   503  			res.ExpectSuccess("Ingress connectivity should be allowed by policy")
   504  
   505  			res = kubectl.ExecPodCmd(
   506  				namespaceForTest, appPods[helpers.App3],
   507  				helpers.CurlFail("http://%s/public", clusterIP))
   508  			res.ExpectSuccess("Ingress connectivity should be allowed by policy")
   509  		})
   510  
   511  		It("Allows traffic with k8s default-allow egress policy", func() {
   512  			By("Installing egress default-allow")
   513  			_, err := kubectl.CiliumPolicyAction(
   514  				namespaceForTest, knpAllowEgress, helpers.KubectlApply, helpers.HelperTimeout)
   515  			Expect(err).Should(BeNil(),
   516  				"L3 allow-egress Policy cannot be applied in %q namespace", namespaceForTest)
   517  
   518  			By("Checking connectivity between pods and external services after installing egress policy")
   519  
   520  			for _, pod := range []string{appPods[helpers.App2], appPods[helpers.App3]} {
   521  				res := kubectl.ExecPodCmd(
   522  					namespaceForTest, pod,
   523  					helpers.CurlFail("http://1.1.1.1/"))
   524  				res.ExpectSuccess("Egress connectivity should be allowed for pod %q", pod)
   525  
   526  				res = kubectl.ExecPodCmd(
   527  					namespaceForTest, pod,
   528  					helpers.Ping("8.8.8.8"))
   529  				res.ExpectSuccess("Egress ping connectivity should be allowed for pod %q", pod)
   530  
   531  				res = kubectl.ExecPodCmd(
   532  					namespaceForTest, pod,
   533  					"host kubernetes.default.svc.cluster.local")
   534  				res.ExpectSuccess("Egress DNS connectivity should be allowed for pod %q", pod)
   535  			}
   536  		})
   537  
   538  		Context("Validate to-entities policies", func() {
   539  			const (
   540  				WorldConnectivityDeny  = false
   541  				WorldConnectivityAllow = true
   542  
   543  				ClusterConnectivityDeny  = false
   544  				ClusterConnectivityAllow = true
   545  			)
   546  
   547  			var (
   548  				cnpToEntitiesAll     = helpers.ManifestGet("cnp-to-entities-all.yaml")
   549  				cnpToEntitiesWorld   = helpers.ManifestGet("cnp-to-entities-world.yaml")
   550  				cnpToEntitiesCluster = helpers.ManifestGet("cnp-to-entities-cluster.yaml")
   551  				cnpToEntitiesHost    = helpers.ManifestGet("cnp-to-entities-host.yaml")
   552  			)
   553  
   554  			It("Validate toEntities All", func() {
   555  				By("Installing toEntities All")
   556  				importPolicy(cnpToEntitiesAll, "to-entities-all")
   557  
   558  				By("Verifying policy correctness")
   559  				validateConnectivity(WorldConnectivityAllow, ClusterConnectivityAllow)
   560  			})
   561  
   562  			It("Validate toEntities World", func() {
   563  				By("Installing toEntities World")
   564  				importPolicy(cnpToEntitiesWorld, "to-entities-world")
   565  
   566  				By("Verifying policy correctness")
   567  				validateConnectivity(WorldConnectivityAllow, ClusterConnectivityDeny)
   568  
   569  			})
   570  
   571  			It("Validate toEntities Cluster", func() {
   572  				By("Installing toEntities Cluster")
   573  				importPolicy(cnpToEntitiesCluster, "to-entities-cluster")
   574  
   575  				By("Verifying policy correctness")
   576  				validateConnectivity(WorldConnectivityDeny, ClusterConnectivityAllow)
   577  			})
   578  
   579  			It("Validate toEntities Host", func() {
   580  				By("Installing toEntities Host")
   581  				importPolicy(cnpToEntitiesHost, "to-entities-host")
   582  
   583  				By("Verifying policy correctness")
   584  				validateConnectivity(WorldConnectivityDeny, ClusterConnectivityDeny)
   585  			})
   586  		})
   587  
   588  		Context("Validate CNP update", func() {
   589  			const (
   590  				allowAll     = true
   591  				denyFromApp3 = false
   592  			)
   593  
   594  			var (
   595  				cnpUpdateAllow        = helpers.ManifestGet("cnp-update-allow-all.yaml")
   596  				cnpUpdateDeny         = helpers.ManifestGet("cnp-update-deny-ingress.yaml")
   597  				cnpUpdateNoSpecs      = helpers.ManifestGet("cnp-update-no-specs.yaml")
   598  				cnpUpdateDenyLabelled = helpers.ManifestGet("cnp-update-deny-ingress-labelled.yaml")
   599  			)
   600  
   601  			validateL3L4 := func(allowApp3 bool) {
   602  				res := kubectl.ExecPodCmd(
   603  					namespaceForTest, appPods[helpers.App2],
   604  					helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   605  				ExpectWithOffset(1, res).Should(helpers.CMDSuccess(),
   606  					"%q cannot curl clusterIP %q",
   607  					appPods[helpers.App2], clusterIP)
   608  
   609  				res = kubectl.ExecPodCmd(
   610  					namespaceForTest, appPods[helpers.App3],
   611  					helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   612  				ExpectWithOffset(1, res).To(getMatcher(allowApp3),
   613  					"%q curl clusterIP %q (expected to allow: %t)",
   614  					appPods[helpers.App3], clusterIP, allowApp3)
   615  			}
   616  
   617  			It("Enforces connectivity correctly when the same L3/L4 CNP is updated", func() {
   618  				By("Applying default allow policy")
   619  				_, err := kubectl.CiliumPolicyAction(
   620  					namespaceForTest, cnpUpdateAllow, helpers.KubectlApply, helpers.HelperTimeout)
   621  				Expect(err).Should(BeNil(), "%q Policy cannot be applied", cnpUpdateAllow)
   622  
   623  				validateL3L4(allowAll)
   624  
   625  				By("Applying l3-l4 policy")
   626  				_, err = kubectl.CiliumPolicyAction(
   627  					namespaceForTest, cnpUpdateDeny, helpers.KubectlApply, helpers.HelperTimeout)
   628  				Expect(err).Should(BeNil(), "%q Policy cannot be applied", cnpUpdateDeny)
   629  
   630  				validateL3L4(denyFromApp3)
   631  
   632  				By("Applying no-specs policy")
   633  				_, err = kubectl.CiliumPolicyAction(
   634  					namespaceForTest, cnpUpdateNoSpecs, helpers.KubectlApply, helpers.HelperTimeout)
   635  				switch helpers.GetCurrentK8SEnv() {
   636  				// In k8s 1.15 no-specs policy is not allowed by kube-apiserver
   637  				case "1.8", "1.9", "1.10", "1.11", "1.12", "1.13", "1.14":
   638  					Expect(err).Should(BeNil(), "%q Policy cannot be applied", cnpUpdateAllow)
   639  					validateL3L4(allowAll)
   640  				default:
   641  					Expect(err).Should(Not(BeNil()), "%q Policy cannot be applied", cnpUpdateAllow)
   642  					validateL3L4(denyFromApp3)
   643  				}
   644  
   645  				By("Applying l3-l4 policy with user-specified labels")
   646  				_, err = kubectl.CiliumPolicyAction(
   647  					namespaceForTest, cnpUpdateDenyLabelled, helpers.KubectlApply, helpers.HelperTimeout)
   648  				Expect(err).Should(BeNil(), "%q Policy cannot be applied", cnpUpdateDeny)
   649  
   650  				validateL3L4(denyFromApp3)
   651  
   652  				By("Applying default allow policy (should remove policy with user labels)")
   653  				_, err = kubectl.CiliumPolicyAction(
   654  					namespaceForTest, cnpUpdateAllow, helpers.KubectlApply, helpers.HelperTimeout)
   655  				Expect(err).Should(BeNil(), "%q Policy cannot be applied", cnpUpdateAllow)
   656  
   657  				validateL3L4(allowAll)
   658  			})
   659  
   660  			It("Verifies that a CNP with L7 HTTP rules can be replaced with L7 Kafka rules", func() {
   661  				By("Installing L7 Policy")
   662  
   663  				// This HTTP policy was already validated in the
   664  				// test "checks all kind of Kubernetes policies".
   665  				// Install it then move on.
   666  				_, err := kubectl.CiliumPolicyAction(
   667  					namespaceForTest, l7Policy, helpers.KubectlApply, helpers.HelperTimeout)
   668  				Expect(err).Should(BeNil(), "Cannot install %q policy", l7Policy)
   669  
   670  				// Update existing policy on port 80 from http to kafka
   671  				// to test ability to change L7 parser type of a port.
   672  				// Traffic cannot flow but policy must be able to be
   673  				// imported and applied to the endpoints.
   674  				_, err = kubectl.CiliumPolicyAction(
   675  					namespaceForTest, l7PolicyKafka, helpers.KubectlApply, helpers.HelperTimeout)
   676  				Expect(err).Should(BeNil(), "Cannot update L7 policy (%q) from parser http to kafka", l7PolicyKafka)
   677  
   678  				res := kubectl.ExecPodCmd(
   679  					namespaceForTest, appPods[helpers.App3],
   680  					helpers.CurlFail("http://%s/public", clusterIP))
   681  				res.ExpectFail("Unexpected connection from %q to 'http://%s/public'",
   682  					appPods[helpers.App3], clusterIP)
   683  
   684  				res = kubectl.ExecPodCmd(
   685  					namespaceForTest, appPods[helpers.App2],
   686  					helpers.CurlFail("http://%s/public", clusterIP))
   687  				res.ExpectFail("Unexpected connection from %q to 'http://%s/public'",
   688  					appPods[helpers.App2], clusterIP)
   689  			})
   690  		})
   691  
   692  	})
   693  
   694  	Context("GuestBook Examples", func() {
   695  		var (
   696  			deployment                = "guestbook_deployment.yaml"
   697  			groupLabel                = "zgroup=guestbook"
   698  			redisPolicy               = "guestbook-policy-redis.json"
   699  			redisPolicyName           = "guestbook-policy-redis"
   700  			redisPolicyDeprecated     = "guestbook-policy-redis-deprecated.json"
   701  			redisPolicyDeprecatedName = "guestbook-redis-deprecated"
   702  			webPolicy                 = "guestbook-policy-web.yaml"
   703  			webPolicyName             = "guestbook-policy-web"
   704  		)
   705  
   706  		var ciliumPods []string
   707  		var err error
   708  
   709  		BeforeEach(func() {
   710  			kubectl.ApplyDefault(helpers.ManifestGet(deployment))
   711  			ciliumPods, err := kubectl.GetCiliumPods(helpers.KubeSystemNamespace)
   712  			Expect(err).To(BeNil(), "cannot retrieve Cilium Pods")
   713  			Expect(ciliumPods).ShouldNot(BeEmpty(), "cannot retrieve Cilium pods")
   714  		})
   715  
   716  		getPolicyCmd := func(policy string) string {
   717  			return fmt.Sprintf("%s=%s %s=%s",
   718  				helpers.KubectlPolicyNameLabel, policy,
   719  				helpers.KubectlPolicyNameSpaceLabel, helpers.DefaultNamespace)
   720  		}
   721  
   722  		AfterEach(func() {
   723  
   724  			kubectl.Delete(helpers.ManifestGet(webPolicy)).ExpectSuccess(
   725  				"Web policy cannot be deleted")
   726  			k8sVersion := helpers.GetCurrentK8SEnv()
   727  			switch k8sVersion {
   728  			case "1.10", "1.11", "1.12", "1.13", "1.14", "1.15":
   729  				kubectl.Delete(helpers.ManifestGet(redisPolicyDeprecated)).ExpectSuccess(
   730  					"Redis deprecated policy cannot be deleted")
   731  			default:
   732  			}
   733  			kubectl.Delete(helpers.ManifestGet(deployment)).ExpectSuccess(
   734  				"Guestbook deployment cannot be deleted")
   735  
   736  			// This policy shouldn't be there, but test can fail before delete
   737  			// the policy and we want to make sure that it's deleted
   738  			kubectl.Delete(helpers.ManifestGet(redisPolicy))
   739  			for _, ciliumPod := range ciliumPods {
   740  				err := kubectl.WaitPolicyDeleted(ciliumPod, getPolicyCmd(webPolicyName))
   741  				Expect(err).To(
   742  					BeNil(), "WebPolicy is not deleted")
   743  
   744  				err = kubectl.WaitPolicyDeleted(ciliumPod, getPolicyCmd(redisPolicyName))
   745  				Expect(err).To(
   746  					BeNil(), "RedisPolicy is not deleted")
   747  			}
   748  			ExpectAllPodsTerminated(kubectl)
   749  		})
   750  
   751  		waitforPods := func() {
   752  
   753  			err = kubectl.WaitforPods(
   754  				helpers.DefaultNamespace,
   755  				fmt.Sprintf("-l %s", groupLabel), helpers.HelperTimeout)
   756  			ExpectWithOffset(1, err).Should(BeNil(), "Bookinfo pods are not ready after timeout")
   757  
   758  			err := kubectl.WaitForServiceEndpoints(
   759  				helpers.DefaultNamespace, "", "redis-master", helpers.HelperTimeout)
   760  			Expect(err).Should(BeNil(), "error waiting for redis-master service to be ready")
   761  
   762  			err = kubectl.WaitForServiceEndpoints(
   763  				helpers.DefaultNamespace, "", "redis-slave", helpers.HelperTimeout)
   764  			Expect(err).Should(BeNil(), "error waiting for redis-slave service to be ready")
   765  
   766  		}
   767  
   768  		policyCheckStatus := func(policyCheck string) {
   769  			for _, ciliumPod := range ciliumPods {
   770  				ExpectWithOffset(1, kubectl.CiliumIsPolicyLoaded(ciliumPod, policyCheck)).To(BeTrue(),
   771  					"Policy %q is not in cilium pod %s", policyCheck, ciliumPod)
   772  			}
   773  		}
   774  
   775  		testConnectivitytoRedis := func() {
   776  			webPods, err := kubectl.GetPodsNodes(helpers.DefaultNamespace, "-l k8s-app.guestbook=web")
   777  			Expect(err).To(BeNil(), "Cannot get web pods")
   778  
   779  			serviceIP, port, err := kubectl.GetServiceHostPort(helpers.DefaultNamespace, "redis-master")
   780  			Expect(err).To(BeNil(), "Cannot get hostPort of redis-master")
   781  
   782  			serviceName := "redis-master"
   783  			err = kubectl.WaitForKubeDNSEntry(serviceName, helpers.DefaultNamespace)
   784  			Expect(err).To(BeNil(), "DNS entry is not ready after timeout")
   785  
   786  			for pod := range webPods {
   787  
   788  				redisMetadata := map[string]int{serviceIP: port, serviceName: port}
   789  				for k, v := range redisMetadata {
   790  					command := fmt.Sprintf(`nc %s %d <<EOF
   791  PING
   792  EOF`, k, v)
   793  					res := kubectl.ExecPodCmd(helpers.DefaultNamespace, pod, command)
   794  					ExpectWithOffset(1, res).To(helpers.CMDSuccess(),
   795  						"Web pod %q cannot connect to redis-master on '%s:%d'", pod, k, v)
   796  				}
   797  			}
   798  		}
   799  		It("checks policy example", func() {
   800  
   801  			waitforPods()
   802  
   803  			By("Apply policy to web")
   804  			_, err = kubectl.CiliumPolicyAction(
   805  				helpers.DefaultNamespace, helpers.ManifestGet(webPolicy),
   806  				helpers.KubectlApply, helpers.HelperTimeout)
   807  			Expect(err).Should(BeNil(), "Cannot apply web-policy")
   808  
   809  			policyCheck := fmt.Sprintf("%s=%s %s=%s",
   810  				helpers.KubectlPolicyNameLabel, webPolicyName,
   811  				helpers.KubectlPolicyNameSpaceLabel, helpers.DefaultNamespace)
   812  			policyCheckStatus(policyCheck)
   813  
   814  			By("Apply policy to Redis")
   815  			_, err = kubectl.CiliumPolicyAction(
   816  				helpers.DefaultNamespace, helpers.ManifestGet(redisPolicy),
   817  				helpers.KubectlApply, helpers.HelperTimeout)
   818  
   819  			Expect(err).Should(BeNil(), "Cannot apply redis policy")
   820  
   821  			policyCheck = fmt.Sprintf("%s=%s %s=%s",
   822  				helpers.KubectlPolicyNameLabel, redisPolicyName,
   823  				helpers.KubectlPolicyNameSpaceLabel, helpers.DefaultNamespace)
   824  			policyCheckStatus(policyCheck)
   825  
   826  			testConnectivitytoRedis()
   827  
   828  			_, err = kubectl.CiliumPolicyAction(
   829  				helpers.DefaultNamespace, helpers.ManifestGet(redisPolicy),
   830  				helpers.KubectlDelete, helpers.HelperTimeout)
   831  			Expect(err).Should(BeNil(), "Cannot apply redis policy")
   832  
   833  			k8sVersion := helpers.GetCurrentK8SEnv()
   834  			switch k8sVersion {
   835  			case "1.10", "1.11", "1.12", "1.13", "1.14", "1.15":
   836  			default:
   837  				Skip(fmt.Sprintf("K8s %s doesn't support extensions/v1beta1 NetworkPolicies, skipping test", k8sVersion))
   838  			}
   839  
   840  			By("Apply deprecated policy to Redis")
   841  
   842  			_, err = kubectl.CiliumPolicyAction(
   843  				helpers.DefaultNamespace, helpers.ManifestGet(redisPolicyDeprecated),
   844  				helpers.KubectlApply, helpers.HelperTimeout)
   845  			Expect(err).Should(BeNil(), "Cannot apply redis deprecated policy err: %q", err)
   846  
   847  			policyCheck = fmt.Sprintf("%s=%s %s=%s",
   848  				helpers.KubectlPolicyNameLabel, redisPolicyDeprecatedName,
   849  				helpers.KubectlPolicyNameSpaceLabel, helpers.DefaultNamespace)
   850  			policyCheckStatus(policyCheck)
   851  
   852  			testConnectivitytoRedis()
   853  		})
   854  	})
   855  
   856  	Context("Namespaces policies", func() {
   857  
   858  		var (
   859  			err               error
   860  			secondNS          = "second"
   861  			appPods           map[string]string
   862  			appPodsNS         map[string]string
   863  			clusterIP         string
   864  			secondNSclusterIP string
   865  
   866  			demoPath           = helpers.ManifestGet("demo.yaml")
   867  			l3L4Policy         = helpers.ManifestGet("l3-l4-policy.yaml")
   868  			cnpSecondNS        = helpers.ManifestGet("cnp-second-namespaces.yaml")
   869  			netpolNsSelector   = fmt.Sprintf("%s -n %s", helpers.ManifestGet("netpol-namespace-selector.yaml"), secondNS)
   870  			l3l4PolicySecondNS = fmt.Sprintf("%s -n %s", l3L4Policy, secondNS)
   871  			demoManifest       = fmt.Sprintf("%s -n %s", demoPath, secondNS)
   872  		)
   873  
   874  		BeforeAll(func() {
   875  
   876  			res := kubectl.NamespaceCreate(secondNS)
   877  			res.ExpectSuccess("unable to create namespace %q", secondNS)
   878  
   879  			res = kubectl.Exec(fmt.Sprintf("kubectl label namespaces/%[1]s nslabel=%[1]s", secondNS))
   880  			res.ExpectSuccess("cannot create namespace labels")
   881  
   882  			res = kubectl.ApplyDefault(demoManifest)
   883  			res.ExpectSuccess("unable to apply manifest")
   884  
   885  			res = kubectl.ApplyDefault(demoPath)
   886  			res.ExpectSuccess("unable to apply manifest")
   887  
   888  			err := kubectl.WaitforPods(secondNS, "-l zgroup=testapp", helpers.HelperTimeout)
   889  			Expect(err).To(BeNil(),
   890  				"testapp pods are not ready after timeout in namspace %q", secondNS)
   891  
   892  			err = kubectl.WaitforPods(helpers.DefaultNamespace, "-l zgroup=testapp", helpers.HelperTimeout)
   893  			Expect(err).To(BeNil(),
   894  				"testapp pods are not ready after timeout in %q namespace", helpers.DefaultNamespace)
   895  
   896  			appPods = helpers.GetAppPods(apps, helpers.DefaultNamespace, kubectl, "id")
   897  			appPodsNS = helpers.GetAppPods(apps, secondNS, kubectl, "id")
   898  
   899  			clusterIP, _, err = kubectl.GetServiceHostPort(helpers.DefaultNamespace, app1Service)
   900  			Expect(err).To(BeNil(), "Cannot get service on %q namespace", helpers.DefaultNamespace)
   901  
   902  			secondNSclusterIP, _, err = kubectl.GetServiceHostPort(secondNS, app1Service)
   903  			Expect(err).To(BeNil(), "Cannot get service on %q namespace", secondNS)
   904  
   905  		})
   906  
   907  		AfterEach(func() {
   908  			// Explicitly do not check results to avoid incomplete teardown of test.
   909  			_ = kubectl.Delete(l3l4PolicySecondNS)
   910  			_ = kubectl.Delete(l3L4Policy)
   911  			_ = kubectl.Delete(netpolNsSelector)
   912  
   913  		})
   914  
   915  		AfterAll(func() {
   916  			_ = kubectl.Delete(demoPath)
   917  			_ = kubectl.Delete(demoManifest)
   918  			_ = kubectl.Delete(cnpSecondNS)
   919  			_ = kubectl.NamespaceDelete(secondNS)
   920  		})
   921  
   922  		It("Tests the same Policy in different namespaces", func() {
   923  			// Tests that the same policy(name,labels) can enforce based on the
   924  			// namespace and all works as expected.
   925  			By("Applying Policy in %q namespace", secondNS)
   926  			_, err = kubectl.CiliumPolicyAction(
   927  				secondNS, l3l4PolicySecondNS, helpers.KubectlApply, helpers.HelperTimeout)
   928  			Expect(err).Should(BeNil(),
   929  				"%q Policy cannot be applied in %q namespace", l3l4PolicySecondNS, secondNS)
   930  
   931  			By("Applying Policy in default namespace")
   932  			_, err = kubectl.CiliumPolicyAction(
   933  				helpers.DefaultNamespace, l3L4Policy, helpers.KubectlApply, helpers.HelperTimeout)
   934  			Expect(err).Should(BeNil(),
   935  				"%q Policy cannot be applied in %q namespace", l3L4Policy, helpers.DefaultNamespace)
   936  
   937  			By("Testing connectivity in %q namespace", secondNS)
   938  
   939  			res := kubectl.ExecPodCmd(
   940  				secondNS, appPodsNS[helpers.App2],
   941  				helpers.CurlFail(fmt.Sprintf("http://%s/public", secondNSclusterIP)))
   942  			res.ExpectSuccess("%q cannot curl service", appPods[helpers.App2])
   943  
   944  			res = kubectl.ExecPodCmd(
   945  				secondNS, appPodsNS[helpers.App3],
   946  				helpers.CurlFail(fmt.Sprintf("http://%s/public", secondNSclusterIP)))
   947  			res.ExpectFail("%q can curl to service", appPods[helpers.App3])
   948  
   949  			By("Testing connectivity in 'default' namespace")
   950  
   951  			res = kubectl.ExecPodCmd(
   952  				helpers.DefaultNamespace, appPods[helpers.App2],
   953  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   954  			res.ExpectSuccess("%q cannot curl clusterIP %q", appPods[helpers.App2], clusterIP)
   955  
   956  			res = kubectl.ExecPodCmd(
   957  				helpers.DefaultNamespace, appPods[helpers.App3],
   958  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
   959  			res.ExpectFail("%q can curl to %q", appPods[helpers.App3], clusterIP)
   960  		})
   961  
   962  		It("Kubernetes Network Policy by namespace selector", func() {
   963  			// Use namespace selector using Kubernetes Network Policy to make
   964  			// sure that it is translated correctly to Cilium and applies the
   965  			// policies to the right endpoints.
   966  			// KNP reference:
   967  			// https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.10/#networkpolicyspec-v1-networking-k8s-io
   968  			By("Testing connectivity across Namespaces without policy")
   969  			for _, pod := range []string{helpers.App2, helpers.App3} {
   970  				res := kubectl.ExecPodCmd(
   971  					helpers.DefaultNamespace, appPods[pod],
   972  					helpers.CurlFail(fmt.Sprintf("http://%s/public", secondNSclusterIP)))
   973  				res.ExpectSuccess("%q cannot curl service", appPods[pod])
   974  
   975  				res = kubectl.ExecPodCmd(
   976  					secondNS, appPodsNS[pod],
   977  					helpers.CurlFail(fmt.Sprintf("http://%s/public", secondNSclusterIP)))
   978  				res.ExpectSuccess("%q cannot curl service", appPodsNS[pod])
   979  			}
   980  
   981  			By("Applying Policy in %q namespace", secondNS)
   982  			_, err = kubectl.CiliumPolicyAction(
   983  				secondNS, netpolNsSelector, helpers.KubectlApply, helpers.HelperTimeout)
   984  			Expect(err).Should(BeNil(), "Policy cannot be applied")
   985  
   986  			for _, pod := range []string{helpers.App2, helpers.App3} {
   987  				// Make sure that the Default namespace can NOT connect to
   988  				// second namespace.
   989  				res := kubectl.ExecPodCmd(
   990  					helpers.DefaultNamespace, appPods[pod],
   991  					helpers.CurlFail(fmt.Sprintf("http://%s/public", secondNSclusterIP)))
   992  				res.ExpectFail("%q can curl to service, policy is not blocking"+
   993  					"communication to %q namespace", appPods[pod], secondNS)
   994  
   995  				// Second namespace pods can connect to the same namespace based on policy.
   996  				res = kubectl.ExecPodCmd(
   997  					secondNS, appPodsNS[pod],
   998  					helpers.CurlFail(fmt.Sprintf("http://%s/public", secondNSclusterIP)))
   999  				res.ExpectSuccess("%q cannot curl service", appPodsNS[pod])
  1000  			}
  1001  
  1002  			By("Delete Kubernetes Network Policies in %q namespace", secondNS)
  1003  			_, err = kubectl.CiliumPolicyAction(
  1004  				secondNS, netpolNsSelector, helpers.KubectlDelete, helpers.HelperTimeout)
  1005  			Expect(err).Should(BeNil(), "Policy %q cannot be deleted", netpolNsSelector)
  1006  
  1007  			for _, pod := range []string{helpers.App2, helpers.App3} {
  1008  				res := kubectl.ExecPodCmd(
  1009  					helpers.DefaultNamespace, appPods[pod],
  1010  					helpers.CurlFail(fmt.Sprintf("http://%s/public", secondNSclusterIP)))
  1011  				res.ExpectSuccess("%q cannot curl service", appPods[pod])
  1012  
  1013  				res = kubectl.ExecPodCmd(
  1014  					secondNS, appPodsNS[pod],
  1015  					helpers.CurlFail(fmt.Sprintf("http://%s/public", secondNSclusterIP)))
  1016  				res.ExpectSuccess("%q cannot curl service", appPodsNS[pod])
  1017  			}
  1018  		})
  1019  
  1020  		It("Cilium Network policy using namespace label and L7", func() {
  1021  
  1022  			_, err := kubectl.CiliumPolicyAction(
  1023  				helpers.DefaultNamespace, cnpSecondNS, helpers.KubectlApply, helpers.HelperTimeout)
  1024  			Expect(err).Should(BeNil(), "%q Policy cannot be applied", cnpSecondNS)
  1025  
  1026  			By("Testing connectivity in %q namespace", secondNS)
  1027  			res := kubectl.ExecPodCmd(
  1028  				secondNS, appPodsNS[helpers.App2],
  1029  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
  1030  			res.ExpectSuccess("Cannot curl service in %s ns", helpers.DefaultNamespace)
  1031  
  1032  			res = kubectl.ExecPodCmd(
  1033  				secondNS, appPodsNS[helpers.App3],
  1034  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
  1035  			res.ExpectSuccess("Cannot curl service in %s ns", helpers.DefaultNamespace)
  1036  
  1037  			By("Testing connectivity from 'default' namespace")
  1038  
  1039  			res = kubectl.ExecPodCmd(
  1040  				helpers.DefaultNamespace, appPods[helpers.App2],
  1041  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
  1042  			res.ExpectFail("Can connect when it should not")
  1043  
  1044  			res = kubectl.ExecPodCmd(
  1045  				helpers.DefaultNamespace, appPods[helpers.App3],
  1046  				helpers.CurlFail(fmt.Sprintf("http://%s/public", clusterIP)))
  1047  			res.ExpectFail("Can connect when it should not")
  1048  		})
  1049  
  1050  	})
  1051  })