# Only the platform team may add, change, or remove the namespace labels that
# switch admission control on and off (the bundle's security.cenroq.io keys and
# native Pod Security Admission's pod-security.kubernetes.io keys).
# In the kind lab the cluster admin's group is kubeadm:cluster-admins; use your
# own platform group in a real cluster.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: protect-admission-labels
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
    - apiGroups: [""]
      apiVersions: ["v1"]
      operations: ["CREATE", "UPDATE"]
      resources: ["namespaces"]
  matchConditions:
  - name: not-platform-team
    expression: "!('kubeadm:cluster-admins' in request.userInfo.groups)"
  variables:
  - name: newLabels
    expression: "has(object.metadata.labels) ? object.metadata.labels : {}"
  - name: oldLabels
    expression: >-
      request.operation == 'UPDATE' && has(oldObject.metadata.labels)
      ? oldObject.metadata.labels : {}
  validations:
  - expression: >-
      variables.newLabels.all(k,
        !(k.contains('security.cenroq.io/') || k.startsWith('pod-security.kubernetes.io/'))
        || (k in variables.oldLabels && variables.oldLabels[k] == variables.newLabels[k]))
      && variables.oldLabels.all(k,
        !(k.contains('security.cenroq.io/') || k.startsWith('pod-security.kubernetes.io/'))
        || k in variables.newLabels)
    message: "Admission-control labels on namespaces can only be changed by the platform team."
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: protect-admission-labels
spec:
  policyName: protect-admission-labels
  validationActions: ["Deny"]
