{{- /*
Copyright Broadcom, Inc. All Rights Reserved.
SPDX-License-Identifier: APACHE-2.0
*/}}

{{- if and .Values.csiProvider.enabled .Values.csiProvider.networkPolicy.enabled }}
kind: NetworkPolicy
apiVersion: {{ include "common.capabilities.networkPolicy.apiVersion" . }}
metadata:
  name: {{ template "vault.csi-provider.fullname" . }}
  namespace: {{ include "common.names.namespace" . | quote }}
  labels: {{- include "common.labels.standard" ( dict "customLabels" .Values.commonLabels "context" $ ) | nindent 4 }}
    app.kubernetes.io/part-of: vault
    app.kubernetes.io/component: csi-provider
  {{- if .Values.commonAnnotations }}
  annotations: {{- include "common.tplvalues.render" ( dict "value" .Values.commonAnnotations "context" $ ) | nindent 4 }}
  {{- end }}
spec:
  {{- $podLabels := include "common.tplvalues.merge" ( dict "values" ( list .Values.csiProvider.podLabels .Values.commonLabels ) "context" . ) }}
  podSelector:
    matchLabels: {{- include "common.labels.matchLabels" ( dict "customLabels" $podLabels "context" $ ) | nindent 6 }}
      app.kubernetes.io/part-of: vault
      app.kubernetes.io/component: csi-provider
  policyTypes:
    - Ingress
    - Egress
  {{- if .Values.csiProvider.networkPolicy.allowExternalEgress }}
  egress:
    - {}
  {{- else }}
  egress:
    - ports:
        # Allow dns resolution
        - port: 53
          protocol: UDP
        - port: 53
          protocol: TCP
        # Allow access to kube-apiserver
        {{- range $port := .Values.csiProvider.networkPolicy.kubeAPIServerPorts }}
        - port: {{ $port }}
        {{- end }}
    {{- if .Values.csiProvider.networkPolicy.extraEgress }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.csiProvider.networkPolicy.extraEgress "context" $ ) | nindent 4 }}
    {{- end }}
  {{- end }}
  ingress:
    {{- if .Values.csiProvider.networkPolicy.extraIngress }}
    {{- include "common.tplvalues.render" ( dict "value" .Values.csiProvider.networkPolicy.extraIngress "context" $ ) | nindent 4 }}
    {{- end }}
{{- end }}
