Blocking Over-Threshold Images with Kyverno and Trivy Operator CRDs (and Why It Fails Open)

Kyverno's apiCall context can read Trivy Operator's VulnerabilityReport CRDs and block pods over a critical threshold. Three measured architectural limits explain why it can never be a first-deployment gate.

Blocking Over-Threshold Images with Kyverno and Trivy Operator CRDs (and Why It Fails Open)

Can Kyverno consume the VulnerabilityReport CRDs your Trivy Operator already produces, and refuse admission to a pod whose image is over a critical threshold? Yes — mechanically. We validated it offline against the live CRDs, and the policy is small. But the interesting part is not the apiCall; it is the three architectural limits we measured while building it, because they define what admission-time CVE gating can and cannot be.

The policy core

foreach:
  - list: "images.containers.*"
    context:
      - name: reportcount
        apiCall:
          urlPath: "/apis/aquasecurity.github.io/v1alpha1/namespaces/{{ request.namespace }}/vulnerabilityreports"
          jmesPath: "length(items[?report.artifact.digest=='{{ element.digest }}'])"
      - name: criticalcount
        apiCall:
          urlPath: "/apis/aquasecurity.github.io/v1alpha1/namespaces/{{ request.namespace }}/vulnerabilityreports"
          jmesPath: "sum([items[?report.artifact.digest=='{{ element.digest }}'].report.summary.criticalCount, [`0`]][])"
    deny:
      conditions:
        all:
          - key: "{{ reportcount }}"
            operator: GreaterThan
            value: 0
          - key: "{{ criticalcount }}"
            operator: GreaterThan
            value: 0   # tune per environment

Limit 1: the chicken-and-egg problem (it fails open, deliberately)

trivy-operator only creates a VulnerabilityReport for a workload that has already been admitted. For a brand-new image, the report does not exist at admission time, so the gate cannot see it. Our policy therefore requires reportcount > 0 before judging — it fails open on the unscanned case.

Consequence: this policy catches re-deploys, scale-ups, rollouts, and restarts of images that were scanned once. It is not a first-deployment gate. A first-deployment gate has to live in CI (Trivy exit codes) or in the registry (Harbor's pull blocking), not here.

Limit 2: keying by digest requires a digest

The report keys the image by report.artifact.digest. Kyverno's auto-populated images.containers.*.digest is only populated when the Pod spec itself carries the digest — so a require-image-digest policy is a prerequisite for this one to work reliably. Without it, the fallback is repository+tag, which is mutable and therefore unsound.

A wrinkle that cost us time: in our cluster a mutating policy rewrites docker.io/... to our Harbor proxy path, and the report records the rewritten registry.server. Any repository-based matching must account for the rewrite. Digest matching does not — another reason to pin digests first.

Limit 3: RBAC, empty arrays, and latency on a hot path

Three implementation notes that took real debugging:

The RBAC gap. Kyverno's default ClusterRole cannot read aquasecurity.github.io resources. An aggregated ClusterRole granting read on those CRDs is required, scoped as tightly as you dare.

The JMESPath empty-array trap. Kyverno's sum() errors on an empty array — "at least one element in the array is required" — which is exactly the unscanned-image case. Without a zero-guard, the context fails and the whole rule errors at admission:

sum([items[?...].report.summary.criticalCount, [`0`]][])

That [ ..., [0] ][] construct appends a zero and flattens, making the sum well-defined for zero reports. Verified with kyverno jp query against real CRDs before it ever saw a webhook.

The latency problem. Every pod admission performs a LIST of all VulnerabilityReports in the namespace, synchronously, inside the admission timeout. With 137 reports cluster-wide it is cheap. It is also an unbounded LIST on a hot path. Mitigations, in order of importance:

webhookConfiguration:
  failurePolicy: Ignore   # never wedge the cluster on this policy
background: false

plus a narrow namespace scope, widened one namespace at a time. The combination means: if the policy infrastructure has problems, pods keep admitting — which is the correct failure direction for a defence-in-depth layer. (For the registry allow-list we enforce the opposite way, because a wrong-registry image is a simpler, higher-confidence judgement.)

Where this fits

Three gates compared: CI and registry can gate a first deployment; admission control cannot
Three gates compared: CI and registry can gate a first deployment; admission control cannot

Only CI and the registry see an image before its first admission — which is why the admission layer fails open.

Treat admission-time CVE gating as a free bonus layer, not the primary gate:

GateLayerFirst deploy?Portable?
Trivy exit codes in CIpre-pushyesany CI
Harbor vulnerable-image pull blockingregistryyesany consumer
Kyverno + VulnerabilityReportadmissionno (fail-open)Kubernetes only

The measured performance context that makes the layered approach sane: a Trivy CLI gate on a small image returns in 203 ms. The admission-layer check is the one with real cost and real caveats, so it goes last and narrowest.

Series: Building a Container Image Security Stack. Next: Renovate — the tool that fixes what Copacetic structurally cannot, and why it was the find of the POC.