{{- $name := "restrict-volume-types" }}
{{- if eq (include "kyverno-policies.podSecurityRestricted" (merge (dict "name" $name) .)) "true" }}
{{- include "kyverno-policies.supportedKyvernoCheck" (dict "top" . "ver" ">= 1.6.0-0") }}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: {{ $name }}
  annotations:
    {{- with .Values.autogenControllers }}
    pod-policies.kyverno.io/autogen-controllers: {{ . }}
    {{- end }}
    policies.kyverno.io/title: Restrict Volume Types
    policies.kyverno.io/category: Pod Security Standards (Restricted)
    {{- if .Values.podSecuritySeverity }}
    policies.kyverno.io/severity: {{ .Values.podSecuritySeverity | quote }}
    {{- end }}
    policies.kyverno.io/subject: Pod,Volume
    policies.kyverno.io/minversion: 1.6.0
    kyverno.io/kubernetes-version: "1.22-1.23"
    kyverno.io/kyverno-version: 1.6.0
    policies.kyverno.io/description: >-
      In addition to restricting HostPath volumes, the restricted pod security profile
      limits usage of non-core volume types to those defined through PersistentVolumes.
      This policy blocks any other type of volume other than those in the allow list.
  labels: {{ include "kyverno-policies.labels" . | nindent 4 }}
spec:
  {{- with index .Values "validationFailureActionByPolicy" $name }}
  validationFailureAction: {{ toYaml . }}
  {{- else }}
  validationFailureAction: {{ .Values.validationFailureAction }}
  {{- end }}
  {{- with concat (index .Values "validationFailureActionOverrides" "all") (default list (index .Values "validationFailureActionOverrides" $name)) }}
  validationFailureActionOverrides: {{ toYaml . | nindent 4 }}
  {{- end }}
  background: {{ .Values.background }}
  failurePolicy: {{ .Values.failurePolicy }}
  rules:
    - name: restricted-volumes
      match:
        any:
        - resources:
            kinds:
              - Pod
      {{- with index .Values "policyExclude" $name }}
      exclude:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with index .Values "policyPreconditions" $name }}
      preconditions:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      validate:
        message: >-
          Only the following types of volumes may be used: configMap, csi, downwardAPI,
          emptyDir, ephemeral, persistentVolumeClaim, projected, and secret.
        deny:
          conditions:
            all:
            - key: "{{`{{ request.object.spec.volumes[].keys(@)[] || '' }}`}}"
              operator: AnyNotIn
              value:
              - name
              - configMap
              - csi
              - downwardAPI
              - emptyDir
              - ephemeral
              - persistentVolumeClaim
              - projected
              - secret
              - ''
{{- end }}
