yonahd / kor

A Golang Tool to discover unused Kubernetes Resources
MIT License
974 stars 91 forks source link

feature: Discover second-level unused NetworkPoliciess #312

Closed doronkg closed 2 months ago

doronkg commented 3 months ago

This issue as an enhancement to #296.

Currently, unused NetworkPolicies are considered as so, if the labels under .spec.podSelector match no running pods in the cluster, therefore, the NetworkPolicy is never applied.

In addition to this field, there are the following fields:

In cases where multiple label selectors / rules are set in a NetworkPolicy, they are "OR'd", meaning if at least one of them matches, the NetworkPolicy is applied and should be considered as used.

Therefore, a NetworkPolicy should be considered as second-level unused when .spec.podSelector matches existing pods, but none of the ingress/egress rules matches existing pods/namespaces. In other words, the NetworkPolicy handles no traffic to the matched pods.

NOTE: the second-level discovery could be tricky for the following reasons:

  1. Performance - each NetworkPolicy can be set with multiple ingress/egress rules hence a wide list of labels to iterate.
  2. False-positives - if a NetworkPolicy is set with multiple ingress/egress rules, and say only one label in the list doesn't match existing pods/namespaces, it could be mapped as unused even if the other rules do apply and potentially be deleted.
Multi-Rule NetworkPolicy Example ```console apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: complex-network-policy namespace: default spec: podSelector: matchLabels: app: myapp policyTypes: - Ingress ingress: - from: - podSelector: matchLabels: app: frontend - podSelector: matchLabels: app: backend ports: - protocol: TCP port: 80 - from: - podSelector: matchLabels: app: database - podSelector: matchLabels: app: cache ports: - protocol: TCP port: 6379 ```

Originally posted by @doronkg in https://github.com/yonahd/kor/issues/296#issuecomment-2167520160