{{- if .Values.kyverno.enabled }}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: whitelist-internal-ingresses
  annotations:
    policies.kyverno.io/title: Concatenate Ingresss
    policies.kyverno.io/category: Other
    policies.kyverno.io/severity: medium
    policies.kyverno.io/subject: Ingress
    policies.kyverno.io/description: >-
      Ingresses with the label "internal=true" should be whitelisted. 
      If no whitelist exists, add the default values, otherwise append 
      whitelist to the already existing ones
spec:
  mutateExistingOnPolicyUpdate: false
  #precondition: has whitelist annotation or 
  rules:
  - name: ensure-nginx-whitelist-exists
    match:
      resources:
        kinds:
          - Ingress
        selector:
          matchLabels:
            internal: "true"
    mutate:
      patchStrategicMerge:
        metadata:
          annotations:
            +(nginx.ingress.kubernetes.io/whitelist-source-range): ""
  - name: append-existing-whitelist
    match:
      resources:
        kinds:
          - Ingress
        selector:
          matchLabels:
            internal: "true"
    preconditions:
      any:
      - key: "{{`{{request.object.metadata.annotations.\"nginx.ingress.kubernetes.io/whitelist-source-range\"}}`}}"
        operator: NotEquals
        value: ""
    mutate:
      patchStrategicMerge:
        metadata:
          annotations:
            {{- with .Values.cluster_config.ingress_whitelist_ips }}
            nginx.ingress.kubernetes.io/whitelist-source-range: "{{`{{ @ }}`}},{{ join "," . }}"
            {{- end }}
  - name: add-nginx-whitelist
    match:
      resources:
        kinds:
          - Ingress
        selector:
          matchLabels:
            internal: "true"
    preconditions:
      any:
      - key: "{{`{{request.object.metadata.annotations.\"nginx.ingress.kubernetes.io/whitelist-source-range\"}}`}}"
        operator: Equals
        value: ""
    mutate:
      patchStrategicMerge:
        metadata:
          annotations:
            {{- with .Values.cluster_config.ingress_whitelist_ips }}
            nginx.ingress.kubernetes.io/whitelist-source-range: "{{ join "," . }}"
            {{- end }}
{{- end }}

