{{- if (eq (include "istio.enabled" .) "true") }}
{{- $fullName := (include "k8s.serviceFullname" .) }}
{{- $svcName := (include "k8s.serviceName" .) }}
{{- $labels := (include "k8s.labels" .) | fromJson }}
{{- if .Values.istio.security.enabled }}
---
apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: {{ $fullName }}-req-auth
  labels:
  {{- range $key, $value := $labels }}
    {{ $key }}: {{ $value }}
  {{- end }}
spec:
  {{- with .Values.istio.security.requestAuth.matchLabels }}
  selector:
    matchLabels:
      {{- toYaml . | nindent 6 }}
  {{- end }}
  {{- with .Values.istio.security.requestAuth.jwtRules }}
  jwtRules:
    {{- toYaml . | nindent 4 }}
  {{- end }}
{{- end }}

{{- if .Values.istio.security.authPolicies }}
{{- range $ap := .Values.istio.security.authPolicies }}
{{- $apName := ($ap.policy).name | required "error Istio Security AuthorizationPolicy name missing!" }}
{{- $apAction := ($ap.policy).action | required (cat "error Istio Security AuthorizationPolicy action missing for policy:" $apName) | upper}}
---
apiVersion: security.istio.io/v1beta1
kind: AuthorizationPolicy
metadata:
  name: {{ $svcName }}-{{ $apName }}-auth-pol
  labels:
  {{- range $key, $value := $labels }}
    {{ $key }}: {{ $value }}
  {{- end }}
spec:
  {{- with ($ap.policy).matchLabels }}
  selector:
    matchLabels:
      {{- toYaml . | nindent 6 }}
  {{- end }}
  action: {{ $apAction }}
{{- if not (empty ($ap.policy).rules) }}
  rules:
    {{- toYaml ($ap.policy).rules | nindent 4 }}
{{- end }}
{{- if and (eq $apAction "CUSTOM") ($ap.policy).provider }}
  provider: {{ ($ap.policy).provider }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}
