Kubernetes Network Policies with Microservices

6/16/2019

Problem:

Network policies with Kubernetes do not act as expected (egress & ingress seem switched to me?) More importantly, I can't seem to lock down web traffic from accessing the /api/ route directly without also blocking the frontend.

Code Setup:

Frontend (React) that uses Axios to talk to the backend. Setup as microservices and use Ingress to push around traffic appropriately based on the route. External managed DB.

Kubernetes Setup

  • Frontend Deployment and Service
  • API deployment and service
  • Ingress service that relies on http paths.
  • Externally managed DB outside the cluster.

Network Policy in question:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: api-blocking
spec:
  podSelector:
    matchLabels:
      component: api
  policyTypes:
    - Ingress
    - Egress
  ingress:
    - from:
        - ipBlock:
            cidr: 111.111.111.0/32
      ports:
        - port: 98711
  egress:
    - to:
        - podSelector:
            matchLabels:
              component: frontend
      ports:
        - port: 3000

Allowing ingress traffic to a particular CIDR with a specific port number allows the db fetch to happen appropriately. Allowing egress traffic to the frontend is what facilitates the frontend being able to grab backend data.

No combination of network policies though would prevent the user from going to /api/ to without it also collapsing the frontend. Hoping for a way to lock that down and only allow the specific client side pod to connect to the backend?

....After typing this out, maybe I need a network policy for the ingress-service??

Update: I attempted using a network plugin specific rule.

The way I wrote the rule was to allow only the "frontend" endpoint access /api/ http routes for both ingress and egress. It didn't seem to block it off from web traffic hitting the API.

Example of a portion of it with placeholder values:

ingress:
    - fromEndpoints:
        - matchLabels:
            component: frontend
      toPorts:
        - ports:
            - port: '1111'
          rules:
            http:
              - path: '/api/ping'
-- dizzy
kubernetes

1 Answer

6/16/2019

I can't seem to lock down web traffic from accessing the /api/ route directly without also blocking the frontend.

I don't think that is possible with the standard Network Policy object, as it's only allowing you to whitelist traffic based on pods, namespaces and IPs.

It seems to be possible to me more granular with Calico Network Policies (check for Application layer policy).

-- born4new
Source: StackOverflow