apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8sazureenforceapparmor
spec:
  crd:
    spec:
      names:
        kind: K8sAzureEnforceAppArmor
      validation:
        # Schema for the `parameters` field
        openAPIV3Schema:
          properties:
            allowedProfiles:
              type: array
              items:
                type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sazureenforceapparmor

        violation[{"msg": msg, "details": {}}] {
            metadata := input.review.object.metadata
            container := input_containers[_]
            not input_apparmor_allowed(container, metadata)
            msg := sprintf("AppArmor profile is not allowed, pod: %v, container: %v. Allowed profiles: %v", [input.review.object.metadata.name, container.name, input.parameters.allowedProfiles])
        }

        input_apparmor_allowed(container, metadata) {
            metadata.annotations[key] == input.parameters.allowedProfiles[_]
            key == sprintf("container.apparmor.security.beta.kubernetes.io/%v", [container.name])
        }

        input_containers[c] {
            c := input.review.object.spec.containers[_]
        }
        input_containers[c] {
            c := input.review.object.spec.initContainers[_]
        }
