{{/*
K2 — secret-not-in-env (security, permissive default).

Container env vars must not carry plaintext secret values. Heuristic:
deny env entries whose `value:` is set (i.e. inline literal) AND whose
name matches a secret-like regex (case-insensitive `*PASSWORD*`,
`*TOKEN*`, `*KEY*`, `*SECRET*`). Secrets that flow via `valueFrom.
secretKeyRef` are accepted — they're tagged in the audit log but the
plaintext doesn't end up in the Pod spec.

The full "secret mounted as file vs as env" preference is stricter
than this rule (env is observable via /proc/<pid>/environ for any
process inside the container), but flipping that on by default would
break too many third-party charts. The rule here covers the worst
violators: literally pasting a password into a yaml file.

Default mode permissive per design §4.3.
*/}}
{{- if .Values.compliancePolicies.secretNotInEnv.enabled -}}
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: secret-not-in-env
  labels:
    app.kubernetes.io/name: bp-kyverno
    app.kubernetes.io/component: compliance-policy
    catalyst.openova.io/policy-tier: compliance
    catalyst.openova.io/policy-domain: security
  annotations:
    policies.kyverno.io/title: Plaintext secrets must not appear in container env
    policies.kyverno.io/category: catalyst-compliance
    policies.kyverno.io/severity: high
    policies.kyverno.io/description: >-
      Container env entries with names matching *PASSWORD* / *TOKEN* /
      *KEY* / *SECRET* must use valueFrom.secretKeyRef, not a
      plaintext value.
spec:
  validationFailureAction: {{ .Values.compliancePolicies.secretNotInEnv.action | default "Audit" }}
  background: true
  rules:
    - name: deny-plaintext-secret-env
      match:
        any:
          - resources:
              kinds:
                - Pod
                - Deployment
                - StatefulSet
                - DaemonSet
                - Job
                - CronJob
      exclude:
        any:
          - resources:
              namespaces:
                {{- range $ns := .Values.compliancePolicies.secretNotInEnv.excludeNamespaces }}
                - {{ $ns }}
                {{- end }}
      validate:
        message: >-
          A container env entry with a secret-shaped name carries a
          plaintext value. Use valueFrom.secretKeyRef to source it from
          a Secret instead.
        foreach:
          - list: "request.object.spec.containers || request.object.spec.template.spec.containers"
            foreach:
              - list: "element.env || `[]`"
                deny:
                  conditions:
                    all:
                      - key: '{{ `{{ element.value || '''' }}` }}'
                        operator: NotEquals
                        value: ""
                      - key: '{{ `{{ element.name }}` }}'
                        operator: Match
                        value: "*(?i)(PASSWORD|TOKEN|KEY|SECRET)*"
{{- end -}}
