# A third-party image in p05-capstone must be pinned by digest. The guide's
# own locally built images (bookstore/...) are exempt: the build produced
# their tags, and chapter 07.03 is where they get a digest in the pipeline.
#
# PodSecurity restricted does not look at image references, so this rule is
# the one the namespace needs in addition. Chapter 07 covers why admission is
# ordered this way, and 05.03 covers why a tag can move.
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: p05-capstone-digest-pinned
  labels:
    app.kubernetes.io/part-of: bookstore
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
      # kubectl debug adds an ephemeral container through this subresource,
      # which is an UPDATE of pods/ephemeralcontainers, not of pods.
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["UPDATE"]
        resources: ["pods/ephemeralcontainers"]
  validations:
    - expression: >-
        object.spec.containers.all(c, c.image.contains('@sha256:') ||
        c.image.startsWith('bookstore/')) &&
        (!has(object.spec.initContainers) ||
        object.spec.initContainers.all(c, c.image.contains('@sha256:') ||
        c.image.startsWith('bookstore/'))) &&
        (!has(object.spec.ephemeralContainers) ||
        object.spec.ephemeralContainers.all(c, c.image.contains('@sha256:') ||
        c.image.startsWith('bookstore/')))
      message: "p05-capstone: every third-party image must be pinned by digest (05.03)."
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: p05-capstone-digest-pinned
  labels:
    app.kubernetes.io/part-of: bookstore
spec:
  policyName: p05-capstone-digest-pinned
  validationActions: [Deny, Audit]
  matchResources:
    namespaceSelector:
      matchLabels:
        kubernetes.io/metadata.name: p05-capstone
