apiVersion: templates.gatekeeper.sh/v1beta1
kind: ConstraintTemplate
metadata:
  name: k8sazureserviceallowedports
spec:
  crd:
    spec:
      names:
        kind: K8sAzureServiceAllowedPorts
        listKind: K8sAzureServiceAllowedPortsList
        plural: k8sazureserviceallowedports
        singular: k8sazureserviceallowedports
      validation:
        # Schema for the `parameters` field
        openAPIV3Schema:
          properties:
            allowedPorts:
              type: array
              items:
                type: string
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sazureserviceallowedports

        violation[{"msg": msg}] {
          service := input.review.object
          not service_is_kubernetes(service)
          port = service.spec.ports[_]
          format_int(port.port, 10, portstr)
          satisfied := [good | allowedPort := input.parameters.allowedPorts[_]; good := (portstr == allowedPort)]
          not any(satisfied)
          msg := sprintf("Port %v for service %v has not been allowed.", [portstr, service.metadata.name])
        }

        service_is_kubernetes(service) = true {
          service.metadata.namespace == "default"
          service.metadata.name == "kubernetes"
        }
