apiVersion: templates.gatekeeper.sh/v1 kind: ConstraintTemplate metadata: name: k8sdisallowanonymous annotations: metadata.gatekeeper.sh/title: "Disallow Anonymous Access" metadata.gatekeeper.sh/version: 1.1.0 description: Disallows associating ClusterRole and Role resources to the system:anonymous user and system:unauthenticated group. spec: crd: spec: names: kind: K8sDisallowAnonymous validation: # Schema for the `parameters` field openAPIV3Schema: type: object properties: allowedRoles: description: >- The list of ClusterRoles and Roles that may be associated with the `system:unauthenticated` group and `system:anonymous` user. type: array items: type: string disallowAuthenticated: description: >- A boolean indicating whether `system:authenticated` should also be disallowed by this policy. type: boolean default: false targets: - target: admission.k8s.gatekeeper.sh rego: | package k8sdisallowanonymous violation[{"msg": msg}] { not is_allowed(input.review.object.roleRef, object.get(input, ["parameters", "allowedRoles"], [])) group := ["system:unauthenticated", "system:anonymous"][_] subject_is(input.review.object.subjects[_], group) msg := message(group) } violation[{"msg": msg}] { not is_allowed(input.review.object.roleRef, object.get(input, ["parameters", "allowedRoles"], [])) object.get(input, ["parameters", "disallowAuthenticated"], false) group := "system:authenticated" subject_is(input.review.object.subjects[_], group) msg := message(group) } is_allowed(role, allowedRoles) { role.name == allowedRoles[_] } subject_is(subject, expected) { subject.name == expected } message(name) := val { val := sprintf("%v is not allowed as a subject name in %v %v", [name, input.review.object.kind, input.review.object.metadata.name]) }