<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gyasmine on Medium]]></title>
        <description><![CDATA[Stories by Gyasmine on Medium]]></description>
        <link>https://medium.com/@gyasmine29?source=rss-499790578132------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZTC95YyZqlZ6_5xg</url>
            <title>Stories by Gyasmine on Medium</title>
            <link>https://medium.com/@gyasmine29?source=rss-499790578132------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 04:49:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gyasmine29/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Kyverno beyond security: Guardrails, Paved Roads, Scaffolding, and Trust]]></title>
            <link>https://medium.com/@gyasmine29/kyverno-beyond-security-guardrails-paved-roads-scaffolding-and-trust-e6fd6a4c6cd9?source=rss-499790578132------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6fd6a4c6cd9</guid>
            <category><![CDATA[kyverno]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <dc:creator><![CDATA[Gyasmine]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 09:23:55 GMT</pubDate>
            <atom:updated>2026-09-30T09:41:49.531Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a local platform with CEL policies, ArgoCD, and Cilium, tested end to end in CI on vCluster</h4><p>Ask most teams where Kyverno lives and they’ll say security. It ships with a bundle of Pod Security Standards, blocks the occasional root container, and mostly sits there as a bouncer.</p><p>A brilliant CNCF post by Koray Oksay, <a href="https://www.cncf.io/blog/2026/08/19/kyverno-is-a-platform-primitive-not-a-security-tool/">“<strong>Kyverno is a platform primitive, not a security tool</strong>”</a>, challenges this narrative; Kyverno does four things: validate, mutate, generate, and verify images. Only the first one is a gate. The other three fix, furnish, and establish trust. His point is that Kyverno is a building block of the platform, much like Pods and Services, that just happens to be good at security too.</p><p>That idea became this project. In my <a href="https://github.com/GHARBIyasmine/gitops-platform-demo">previous one</a>, I explored multi-tenancy in Kubernetes and how tenant isolation can be achieved with nested vClusters, ArgoCD, and Cilium network policies, which was about what happens <em>between</em> workloads at runtime. This time I went to the moment a resource enters the cluster, and asked what should be rejected, what should be quietly fixed, what should be created for you, and what must be signed to run.</p><p>So, I built my local Kyverno-platform: CEL-based policies in four pillars (guardrails, paved roads, scaffolding, trust), delivered with ArgoCD and tested in CI. Let’s walk through it !</p><h4>Kyverno in a nutshell</h4><p>Kyverno is a policy engine built for Kubernetes. When you create or change a resource, the API server sends it through admission webhooks before it is stored, and Kyverno plugs into that step. Unlike Rego-based tools, you don’t learn a separate language for the engine itself: policies are Kubernetes resources, written in YAML like everything else in your cluster.</p><p>What a policy can do with a resource at that moment comes down to four verbs:</p><ul><li><strong>Validate</strong>: accept or reject it.</li><li><strong>Mutate</strong>: change it on its way in.</li><li><strong>Generate</strong>: create other resources in response to it.</li><li><strong>Verify images</strong>: check that the container images are signed and attested.</li></ul><h4>The new CEL-based kinds</h4><p>Historically, all four verbs lived inside one kind, ClusterPolicy (and its namespaced twin, Policy). That model is being phased out: ClusterPolicy is deprecated as of Kyverno 1.19, with removal planned for 1.20 (estimated November 2026). Its replacements are dedicated kinds, one per verb, written in CEL, the Common Expression Language that Kubernetes itself uses in ValidatingAdmissionPolicy. CEL is fast, safe (it can&#39;t loop forever), and lets you reuse one expression language across your stack. Koray Oksay&#39;s <a href="https://platformengineering.org/blog/scaling-kubernetes-governance-a-platform-engineers-guide-to-kyverno-and-cel">guide to Kyverno and CEL</a> covers the details well.</p><p>Since I wanted this project to still work after ClusterPolicy is gone, every policy in it uses the new kinds.</p><h4>Four verbs, four pillars</h4><p>The project is organized around a taxonomy from Oksay’s platform-primitive post. Each verb gets a kind and a role:</p><ul><li>validate → ValidatingPolicy→ Guardrails</li><li>mutate → MutatingPolicy→ Paved roads</li><li>generate → GeneratingPolicy→ Scaffolding</li><li>verify images → ImageValidatingPolicy→ Trust</li></ul><p>These pillars are more than a way to sort files. In the admission chain, mutation runs before validation, so paved roads quietly fix most manifests first, and guardrails only fire on what could not be fixed. That’s why the repo is designed this way, and we’ll see it in action later.</p><h4>Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fx3a2IuLMhSREiEknXwsgw.png" /></figure><p>Let’s break down what we have in this project:</p><p><strong>The cluster</strong></p><ul><li>Everything runs on a <strong>vind cluster</strong> (vCluster in Docker) with one control plane and two workers.</li><li>Two things are installed by hand, because everything else depends on them: <strong>Cilium</strong> as the CNI, and <strong>ArgoCD</strong>.</li></ul><p><strong>Preparing the secrets backend</strong></p><ul><li>I don’t have HashiCorp Vault or a cloud secrets manager, so I created a dedicated namespace holding a <strong>dummy secret</strong> that plays the role of the vault.</li><li>The External Secrets Operator (ESO) treats it as a real backend: its provider is the Kubernetes cluster itself.</li></ul><p><strong>Preparing the signed images</strong></p><ul><li>The trust pillar only admits images it can verify, so I needed one to verify. I built my own image and pushed it to <strong>GitHub Container Registry (GHCR)</strong>, the one registry the policy trusts.</li><li>The image carries two pieces of proof: a <strong>cosign signature</strong> (who built it) and a signed <strong>CycloneDX SBOM attestation</strong> (what’s inside it).</li></ul><p><strong>GitOps: one root app</strong></p><ul><li>A single <strong>ArgoCD root app</strong> bootstraps the rest unto the cluster.</li><li>It installs, in order of dependency: <strong>ESO</strong>, <strong>Kyverno</strong>, the infra that both need (credentials, roles…), and finally the <strong>policies</strong>.</li></ul><h4>Environement setup</h4><p>Vind ships with Flannel and kube-proxy enabled by default. Flannel does not enfore network policies. So, if we want to use Cilium instead, we need to disable both at cluster creation time using a custom config file and install Cilium ourselves afterward.</p><p>In the following config file, we define a 2-worker-node cluster and turn off the built-in CNI and kube-proxy so Cilium can take over both roles.</p><pre>#vind-cilium.yaml<br>experimental:<br>  docker:<br>    nodes:<br>      - name: &quot;worker-1&quot;<br>      - name: &quot;worker-2&quot;<br>deploy:<br>  kubeProxy:<br>    enabled: false   # Cilium will replace kube-proxy<br>  cni:<br>    flannel:<br>      enabled: false  # Cilium will replace Flannel</pre><p>With the config file above, we spin up the cluster using the following command :</p><pre># create platform vind cluster<br>vclsuter use driver docker<br>vcluster create kyverno-platform -f vind-cilium.yaml</pre><p>At this stage, the cluster has no working pod networking yet so don’t be alarmed if nodes show NotReady or pods stay Pending until you install Cilium in the next step.</p><p>Cilium needs to know the Kubernetes API server’s address and port directly to bootstrap kubeProxyReplacement mode. Grab it using this command:</p><pre># find API server IP and PORT<br>kubectl get endpoints kubernetes -n default</pre><p>Now install Cilium, replacing both kube-proxy and Flannel. Swap in the IP and port from the previous step’s output.</p><p><strong>⚠️ Heads-up:</strong> This is specific to setups using <strong>WSL2 + Docker Desktop</strong></p><ul><li>We use<strong> </strong>l7Proxy=false . This is a WSL2 limitation as the stock WSL2 kernel doesn’t support loadable netfilter modules (ip_tables, xt_TPROXY). without this flag, Cilium&#39;s embedded DNS/L7 proxy tries to install its TPROXY rule, which is the exact could not load module ip_tables / TPROXY revision 0 not supported failure that kept bracking CoreDNS.</li><li>We use bpf.masquerade=true to move masquerading from iptables into eBPF. Leaving masquerading on iptables means it depends on the same ip_tables/netfilter kernel modules the WSL2 kernel doesn&#39;t support.</li><li>we use --set envoy.enabled=false to avoid pulling in Cilium&#39;s separate Envoy proxy component, which isn&#39;t needed for basic kube-proxy replacement and adds startup overhead in an already resource-constrained local dev setup (especially relevant if you&#39;re running this inside WSL2/Docker Desktop, where memory is already shared and limited).</li></ul><pre># configure cilium as cni<br>helm repo add cilium https://helm.cilium.io<br>helm repo update<br>helm install cilium cilium/cilium --version 1.19.8 \<br>  --namespace kube-system \<br>  --set k8sServiceHost=&lt;API_SERVER_IP&gt; \<br>  --set k8sServicePort=&lt;API_SERVER_PORT&gt; \<br>  --set kubeProxyReplacement=true \<br>  --set ipam.mode=kubernetes \<br>  --set l7Proxy=false \<br>  --set bpf.masquerade=true \<br>  --set image.pullPolicy=IfNotPresent \<br>  --set envoy.enabled=false</pre><p>Now that networking has been sorted, let’s install Argo CD into the host cluster.</p><pre>helm repo add argo https://argoproj.github.io/argo-helm<br>helm repo update<br><br># Installer ArgoCD dans son propre namespace<br>helm install argocd argo/argo-cd \<br>  --namespace argocd \<br>  --create-namespace \<br>  --version 10.9.2 \<br>  --set server.service.type=ClusterIP</pre><p>Now let’s move on to preparing our dummy vault. The plan is simple: a dedicated namespace called secret-backend holds one plain Kubernetes Secret, and the External Secrets Operator (ESO) will read from it as if it were a real vault.</p><p>First, create the namespace:</p><pre>kubectl create namespace secret-backend</pre><p>Then create the dummy secret inside it:</p><pre>kubectl create secret generic demo-db-credentials \<br>  -n secret-backend \<br>  --from-literal=username=demo_app \<br>  --from-literal=password=&#39;S3cretDemoPass!&#39;</pre><p>With the installations done, there’s one more thing to prepare before we get to the manifests: the images. The trust pillar needs one image that is properly signed and one that isn’t, so we can watch Kyverno accept the first and reject the second. To create them, we first need two tools: cosign for signing and syft for generating the SBOM.</p><pre># cosign<br>curl -O -L &quot;https://github.com/sigstore/cosign/releases/latest/download/cosign-linux-amd64&quot;<br>sudo mv cosign-linux-amd64 /usr/local/bin/cosign<br>sudo chmod +x /usr/local/bin/cosign</pre><pre># syft<br>curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b /usr/local/bin</pre><p>For the demo, I took a plain nginx image and pushed it to GitHub Container Registry (GHCR). To do the same, create a GitHub Personal Access Token (classic) with the write:packages, read:packages, and delete:packages scopes, then log in to ghcr.io with your GitHub username and that token:</p><pre>echo &quot;$GITHUB_TOKEN&quot; | docker login ghcr.io --username gharbiyasmine --password-stdin</pre><p>Then pull, tag, and push:</p><pre>docker pull nginx:1.25<br>docker tag nginx:1.25 ghcr.io/gharbiyasmine/kyverno-demo:1.0.0<br>docker push ghcr.io/gharbiyasmine/kyverno-demo:1.0.0</pre><p>The image will show up in the Packages tab of your GitHub profile. One gotcha here: GitHub makes newly pushed images <strong>private</strong> by default, and a private image can’t be pulled by the cluster without credentials, which leaves Kyverno timing out while it tries to reach it. Since this is a demo, I simply switched the package’s visibility to public.</p><p>Now for the trust part. Generate a key pair once, sign the image, then build its SBOM with syft and attach it as a signed attestation:</p><pre># generate a key pair (one-time)<br># produces cosign.key (private, never commit it) and cosign.pub (public)<br>cosign generate-key-pair</pre><pre># sign the image<br>cosign sign --key cosign.key ghcr.io/gharbiyasmine/kyverno-demo:1.0.0</pre><pre># generate the SBOM and attest it (the type must match what the policy expects: cyclonedx)<br>syft ghcr.io/gharbiyasmine/kyverno-demo:1.0.0 -o cyclonedx-json &gt; sbom.json<br>cosign attest --key cosign.key --predicate sbom.json --type cyclonedx ghcr.io/gharbiyasmine/kyverno-demo:1.0.0</pre><p>Finally, before Kyverno gets involved, check both proofs on their own:</p><pre>cosign verify --key cosign.pub ghcr.io/gharbiyasmine/kyverno-demo:1.0.0<br>cosign verify-attestation --key cosign.pub --type cyclonedx ghcr.io/gharbiyasmine/kyverno-demo:1.0.0</pre><p>This last step is worth the thirty seconds. If a policy misbehaves later, you’ll already know the signature and attestation are fine, so the problem is in the policy and not in the image.</p><p>Now for the image that should be rejected. I used a different base image, Alpine, pushed under a separate name (kyverno-demo-unsigned), and deliberately never signed it or attached an SBOM:</p><pre>docker pull alpine:3.20<br>docker tag alpine:3.20 ghcr.io/gharbiyasmine/kyverno-demo-unsigned:1.0.0<br>docker push ghcr.io/gharbiyasmine/kyverno-demo-unsigned:1.0.0</pre><p>As before, GitHub will publish it as private, so switch this package to public too. Otherwise Kyverno will fail to reach the image, and you’d get a timeout when what you want to demonstrate is a clean rejection for a missing signature.</p><h4>Inside ArgoCD: one root app, seven waves</h4><p>Everything after the manual installs is driven by a single <strong>root application</strong> using the app-of-apps pattern. Instead of applying a dozen manifests myself, I point ArgoCD at one folder, and it creates the child applications that install everything else.</p><p>The order matters. If ESO, Kyverno, and the policies were all applied at once, ArgoCD would try to create resources whose CRDs or webhooks don’t exist yet, and the sync would fail in confusing ways. So each piece gets its own <strong>sync wave</strong>, and ArgoCD only moves to the next wave when the previous one is done:</p><ol><li><strong>ESO CRDs</strong>: As any other operator, CRDs <strong>must</strong> be installed first. ExternalSecret, ClusterSecretStore, and friends must exist before anything can reference them.</li><li><strong>ESO itself</strong>: the operator and its webhook. It has to be running before it can accept a store.</li><li><strong>ESO credentials</strong>: the ServiceAccount, Role, and RoleBinding that allow ESO to read from the secret-backend namespace. The store in the next step points at them.</li><li><strong>ClusterSecretStore</strong>: the “fake vault” connection, using those credentials.</li><li><strong>Kyverno</strong>: the policy engine and its CRDs, installed after ESO so that policies can reference ESO’s kinds.</li><li><strong>Kyverno cluster role</strong>: grants Kyverno permission to create ExternalSecrets, which it can&#39;t do by default since they are a custom resource.</li><li><strong>Policies</strong>: last, because a policy needs Kyverno’s CRDs, its webhook, and the ESO resources it generates all in place.</li></ol><p>I misordered a couple of these on my first try, and the result was a very confusing evening. Double-check your waves people ! 😆</p><h4>The elephant in the room: the policies</h4><p>Now for the heart of the project: 18 policies, split across the four pillars. Each one is a small, single-purpose resource, and together they decide what gets rejected, fixed, created, or trusted in the cluster.</p><p>To keep this article from turning into a wall of YAML, I’ll walk through one policy per pillar in detail. The rest are in the repo (link below), organized by pillar.</p><p><strong>Guardrails/ (validate)</strong></p><ol><li>require resource limits + requests on all containers</li><li>block :latest image tags</li><li>enforce namespace labels</li><li>block privilege escalation</li><li>require readOnlyRootFilesystem</li><li>enforce a trusted image registry allowlist</li><li>require securityContext on pods</li><li>block hostPath volumes</li><li>block raw kind: Secret creation unless owned by the ESO controller identity</li><li>block host network</li><li>block host PID and host IPC</li></ol><pre>apiVersion: policies.kyverno.io/v1<br>kind: ValidatingPolicy<br>metadata:<br>  name: block-privilege-escalation<br>spec:<br>  validationActions:<br>    - Deny<br>  matchConstraints:<br>    resourceRules:<br>      - apiGroups: [&quot;&quot;]<br>        apiVersions: [&quot;v1&quot;]<br>        operations: [&quot;CREATE&quot;, &quot;UPDATE&quot;]<br>        resources: [&quot;pods&quot;]<br>  validations:<br>    - message: &gt;-<br>        Privilege escalation is disallowed. Every container must set<br>        securityContext.allowPrivilegeEscalation to false.<br>      expression: &gt;<br>        object.spec.containers.all(c,<br>          has(c.securityContext) &amp;&amp;<br>          has(c.securityContext.allowPrivilegeEscalation) &amp;&amp;<br>          c.securityContext.allowPrivilegeEscalation == false<br>        )</pre><p>The rule lives in the expression field, which is plain CEL:</p><ul><li>object.spec.containers.all(c, ...) walks through every container in the Pod and requires the condition to be true for all of them. One container that fails the check is enough to reject the whole Pod.</li><li>has(c.securityContext) and has(c.securityContext.allowPrivilegeEscalation) check that the fields exist before they&#39;re read. In CEL, reading a missing field is an error, and &amp;&amp; stops at the first false, so the guard comes first.</li><li>c.securityContext.allowPrivilegeEscalation == false is the actual requirement.</li></ul><p><strong>Paved-roads/ (mutate)</strong></p><ol><li>default resource requests/limits, auto-injected if missing</li><li>default securityContext, auto-injected if missing</li></ol><p>This policy gives every container that forgot to declare resources a sensible default, so nobody has to write them and nothing runs unbounded.</p><pre>apiVersion: policies.kyverno.io/v1<br>kind: MutatingPolicy<br>metadata:<br>  name: default-resource-limits<br>spec:<br>  matchConstraints:<br>    resourceRules:<br>      - apiGroups: [&quot;&quot;]<br>        apiVersions: [&quot;v1&quot;]<br>        operations: [&quot;CREATE&quot;, &quot;UPDATE&quot;]<br>        resources: [&quot;pods&quot;]<br>  mutations:<br>    - patchType: ApplyConfiguration<br>      applyConfiguration:<br>        expression: &gt;<br>          Object{<br>            spec: Object.spec{<br>              containers: object.spec.containers.map(c,<br>                has(c.resources) &amp;&amp; (has(c.resources.requests) || has(c.resources.limits))<br>                  ? Object.spec.containers{ name: c.name }<br>                  : Object.spec.containers{<br>                      name: c.name,<br>                      resources: Object.spec.containers.resources{<br>                        requests: Object.spec.containers.resources.requests{<br>                          cpu: &quot;100m&quot;,<br>                          memory: &quot;128Mi&quot;<br>                        },<br>                        limits: Object.spec.containers.resources.limits{<br>                          cpu: &quot;500m&quot;,<br>                          memory: &quot;256Mi&quot;<br>                        }<br>                      }<br>                    }<br>              )<br>            }<br>          }</pre><p>Unlike the guardrail, the expression here doesn&#39;t return true or false. It returns a <strong>partial Pod</strong>, and Kyverno merges it into the incoming object (patchType: ApplyConfiguration). Three parts of it do the work:</p><ul><li>Object{ spec: Object.spec{ ... } } is how CEL builds a typed object that follows the Pod schema. You describe only the fields you want to set, and everything else in the Pod is left alone.</li><li>containers: object.spec.containers.map(c, ...) loops over every container and returns a small entry for each one. The name is what lets the merge match each entry to the container it belongs to, so the image, ports, and the rest stay untouched.</li><li>The ternary is the heart of it: has(c.resources) &amp;&amp; (has(c.resources.requests) || has(c.resources.limits)). If the developer declared any requests or limits, the container gets only { name: c.name }, which merges as a no-op. If they declared nothing, it gets the defaults: 100m CPU and 128Mi memory as requests, 500m and 256Mi as limits.</li></ul><p><strong>Trust/ (verify images)</strong></p><ol><li>verifyImages policy checking both cosign signature <em>and</em> SBOM/provenance attestation on the demo image</li></ol><pre>apiVersion: policies.kyverno.io/v1<br>kind: ImageValidatingPolicy<br>metadata:<br>  name: verify-signed-images<br>spec:<br>  webhookConfiguration:<br>    timeoutSeconds: 30<br>  evaluation:<br>    background:<br>      enabled: false<br>  matchConstraints:<br>    resourceRules:<br>      - apiGroups: [&quot;&quot;]<br>        apiVersions: [&quot;v1&quot;]<br>        operations: [&quot;CREATE&quot;]<br>        resources: [&quot;pods&quot;]<br>  matchImageReferences:<br>    - glob: &quot;ghcr.io/gharbiyasmine/*&quot;<br>  attestors:<br>    - name: cosignKey<br>      cosign:<br>        key:<br>          # the contents of cosign.pub here <br>          data: |<br>            -----BEGIN PUBLIC KEY-----<br>            MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoF4LIFK4VXPdleNipefMIOvrNbv3<br>            L++B6c0mzgJt7fB+eB6CEgyrTm5SUIjU2Ux6REDgLA5L+djwUN9Shes8XA==<br>            -----END PUBLIC KEY-----<br>  attestations:<br>    - name: sbom<br>      intoto:<br>        # Must match the --type value passed to `cosign attest`.<br>        type: https://cyclonedx.org/bom<br>  validations:<br>    - expression: &gt;<br>        images.containers.map(image,<br>          verifyImageSignatures(image, [attestors.cosignKey])<br>        ).all(e, e &gt; 0)<br>      message: &quot;Image signature verification failed.&quot; <br>    - expression: &gt;<br>        images.containers.map(image,<br>          verifyAttestationSignatures(image, attestations.sbom, [attestors.cosignKey])<br>        ).all(e, e &gt; 0)<br>      message: &quot;Signed SBOM attestation is missing or failed verification.&quot;</pre><ul><li>matchImageReferences decides which images the policy cares about: anything under ghcr.io/gharbiyasmine/*. This is what you&#39;d change to point it at your own registry.</li><li>attestors holds the public key (cosign.pub, the one from the signing step). A signature only means something relative to a key you trust, and this is where you say which one.</li><li>attestations declares the SBOM type to look for, https://cyclonedx.org/bom. It has to match the --type cyclonedx we passed to cosign attest, otherwise the attestation won&#39;t be found.</li></ul><p>The two validations are where the checking happens:</p><pre>images.containers.map(image,<br>  verifyImageSignatures(image, [attestors.cosignKey])<br>).all(e, e &gt; 0)</pre><p>images.containers is the list of images in the Pod. For each one, verifyImageSignatures checks the registry for a signature made by our key and returns how many valid ones it found. .all(e, e &gt; 0) then requires at least one for every image, so a single unsigned container is enough to reject the Pod.</p><p>The second expression does the same with verifyAttestationSignatures, asking for a signed SBOM instead of a signature. That&#39;s why an image needs both proofs to get in, and each check has its own error message so a rejection tells you which one is missing.</p><p><strong>Scaffolding/ (generate)</strong></p><ol><li>auto-generate ResourceQuota</li><li>auto-generate LimitRange</li><li>auto-generate default-deny NetworkPolicy</li><li>auto-generate an ExternalSecret referencing the fake-vault ClusterSecretStore</li></ol><pre>apiVersion: policies.kyverno.io/v1<br>kind: GeneratingPolicy<br>metadata:<br>  name: generate-external-secret<br>spec:<br>  evaluation:<br>    synchronize:<br>      enabled: true<br>    generateExisting:<br>      enabled: true<br>  matchConstraints:<br>    resourceRules:<br>      - apiGroups: [&quot;&quot;]<br>        apiVersions: [&quot;v1&quot;]<br>        operations: [&quot;CREATE&quot;]<br>        resources: [&quot;namespaces&quot;]<br>  # secret-backend is excluded for the same reason as the others, plus<br>  # one more: it&#39;s the source of truth ESO reads from, not a consumer so<br>  # it should never get an ExternalSecret pointed at itself.<br>  matchConditions:<br>    - name: exclude-infra-namespaces<br>      expression: &gt;<br>        !(object.metadata.name in [<br>          &quot;kube-system&quot;, &quot;kube-public&quot;, &quot;kube-node-lease&quot;, &quot;default&quot;,<br>          &quot;kyverno&quot;, &quot;argocd&quot;, &quot;external-secrets&quot;, &quot;secret-backend&quot;<br>        ])<br>  variables:<br>    - name: nsName<br>      expression: &quot;object.metadata.name&quot;<br>  generate:<br>    - template:<br>        interpolate: cel<br>        value: |<br>          apiVersion: external-secrets.io/v1<br>          kind: ExternalSecret<br>          metadata:<br>            name: default-external-secret<br>            namespace: (( variables.nsName ))<br>          spec:<br>            refreshInterval: 1h<br>            secretStoreRef:<br>              name: fake-vault<br>              kind: ClusterSecretStore<br>            target:<br>              name: synced-db-credentials<br>              creationPolicy: Owner<br>            data:<br>              - secretKey: username<br>                remoteRef:<br>                  key: demo-db-credentials<br>                  property: username<br>              - secretKey: password<br>                remoteRef:<br>                  key: demo-db-credentials<br>                  property: password</pre><p>Nothing is patched or rejected here. The policy watches for namespaces and generates a new resource in response. Four parts do the work:</p><ul><li>matchConstraints triggers on CREATE of a namespaces resource. The trigger is the namespace itself, not a Pod.</li><li>matchConditions holds the one CEL expression that decides who gets furnished:</li></ul><pre>!(object.metadata.name in [   &quot;kube-system&quot;, &quot;kube-public&quot;, &quot;kube-node-lease&quot;, &quot;default&quot;,   &quot;kyverno&quot;, &quot;argocd&quot;, &quot;external-secrets&quot;, &quot;secret-backend&quot; ])</pre><ul><li>It’s true for every namespace <em>except</em> the infrastructure ones, so only tenant namespaces receive the resource. secret-backend is on the list for a specific reason: it&#39;s the source ESO reads from, not a consumer, so it should never get an ExternalSecret pointing at itself. Although, kyverno already excludes the majority of these namespaces by default which can be inspected in global ConfigMap named kyverno to filter out specific resources, kinds, namespaces, or user groups from being processed</li><li>variables gives the namespace name a short handle, nsName, so the template can reuse it.</li><li>generate holds the template. It creates an ExternalSecret in the new namespace that points at the fake-vault ClusterSecretStore we set up earlier and reads the username and password properties of demo-db-credentials. ESO then turns it into a regular Secret called synced-db-credentials, refreshed every hour. The (( variables.nsName )) placeholder puts the resource in the namespace that triggered the policy.</li></ul><p><strong>⚠️Limitation of Kyverno v1.19.1</strong> (fix implemented in a later version):<strong>⚠️</strong></p><p>Kyverno’s ImageValidatingPolicy (IVPOL) combines two mechanisms: it first mutates the resource, resolving the image tag to its digest and rewriting the reference as image@sha256:..., and only then runs its validation expressions against that mutated, digest-pinned image.</p><p>The issue arises from webhook ordering. Kubernetes invokes mutating webhooks within a shared MutatingWebhookConfiguration in the order their entries were registered, and as of v1.19.1 Kyverno registers the IVPOL&#39;s mutating step <em>before</em> any regular MutatingPolicy mutation.</p><p>So consider a common pattern: one policy rewrites a container&#39;s image registry (e.g. prefixing it with an internal registry), and a separate ImageValidatingPolicy verifies that image&#39;s signature. In practice, the IVPOL&#39;s mutating step runs first and resolves a digest for the <em>original, unrewritten</em> image reference. The registry-rewrite policy then runs second and changes the image name, silently invalidating the digest that was just attached. By the time validation runs, the image reference no longer matches what was verified, and the request is rejected with a &quot;digest missing&quot; error, so the resource is never created.</p><p>This is compounded by how Kubernetes’ reinvocationPolicy works: a mutating webhook set to IfNeeded is guaranteed to be re-invoked if a later webhook further modifies the object, which would let the IVPOL correctly <strong>re-resolve</strong> the digest after the registry rewrite. Currently, however, Kyverno hardcodes this field to Never for the mutating webhook, so it never gets a second chance to run after another policy mutates the resource.</p><p>I confirmed this in the Kyverno source, and a fix (setting reinvocationPolicy: IfNeeded) is already merged and slated for the next release.</p><h4>Testing, Testing and more Testing</h4><p>Policies are code, so I tested them like code, in two layers.</p><p><strong>Layer 1: unit tests with the Kyverno CLI:</strong></p><ul><li>All the pillars are evaluated offline with kyverno test, with no cluster required.</li><li>Each policy gets its own directory with the policy, a set of good and bad resources, and the expected outcome. For validating policies that means pass/fail per resource. For mutating policies I assert the exact patched output, because &quot;the policy didn&#39;t error&quot; says nothing about whether the defaults it injected are correct. For generating policies I assert the exact resource that gets created. These tests run in seconds and gate everything else in CI.</li></ul><p><strong>Layer 2: end-to-end tests with Chainsaw.</strong> Some behavior can’t be proven offline. Image signature and SBOM attestation verification needs a real registry and real signatures, and proving that infrastructure namespaces are excluded from generation requires a live cluster with generateExisting enabled. Chainsaw runs these against a vind cluster in CI, which installs External Secrets, Kyverno, and the policies in the same order ArgoCD would.</p><p><strong>What I learned along the way:</strong></p><ul><li><strong>The CLI test schema matters.</strong> The new CEL-based policy kinds need the newer cli.kyverno.io/v1alpha1 test manifest with per-kind flags such as isValidatingPolicy. The older bare schema fails with a confusing OpenAPI error.</li><li><strong>Your own guardrails apply to your test harness.</strong> Chainsaw’s throwaway namespaces were rejected by my namespace-label policy until I gave them a label template.</li></ul><p>The main takeaway is that unit tests prove each policy’s logic, while e2e tests prove the policies work together on a real cluster, and this project needed both. Though, I would like to add that I did test some of these policies myself first on ephemeral clusters many many times when I first started writing them to make sure they were behaving well (looking at you ImageValidatingPolicy)</p><h4>Conclusion</h4><p>Another project, another year shaved off my life 😅 But that sigh of relief when the ArgoCD dashboard finally turns green and everything just works is hard to beat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VP_EyvgUJzjsxmkgP1IcWg.png" /></figure><p>It was a genuinely enriching experience, and I’m glad I took the time to learn how Kyverno works from the inside. It deserves a place in your toolkit, and not only as a gatekeeper: as this project showed, it can also fix, furnish, and verify what enters your cluster. And as always, WSL2 made sure that no debugging session went without a little extra headache.</p><p><strong>For the full code, check out my </strong><a href="https://github.com/GHARBIyasmine/kyverno-platform"><strong>GitHub repo</strong></a><strong>.</strong> Feel free to connect with me on <a href="https://www.linkedin.com/in/yasmine-gharbi-39b67221a/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6fd6a4c6cd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vind GitOps Platform | Multi-Tenant vCluster Environments with ArgoCD + Cilium (WSL + Docker…]]></title>
            <link>https://medium.com/@gyasmine29/vind-gitops-platform-multi-tenant-vcluster-environments-with-argocd-cilium-wsl-docker-8d0097f36fd4?source=rss-499790578132------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d0097f36fd4</guid>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[cilium]]></category>
            <category><![CDATA[argo-cd]]></category>
            <dc:creator><![CDATA[Gyasmine]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 13:02:11 GMT</pubDate>
            <atom:updated>2026-09-14T13:02:11.469Z</atom:updated>
            <content:encoded><![CDATA[<h3>Vind GitOps Platform | Multi-Tenant vCluster Environments with ArgoCD + Cilium (WSL + Docker Desktop edition)</h3><p>Kubernetes multi-tenancy is usually solved one of two ways: namespaces with RBAC and network policy doing the heavy lifting, or fully separate clusters with all the cost of running more control planes than you need. Either way, more trouble than it should be.</p><p>Nested virtual clusters are the interesting middle ground: isolated control planes per tenant, without standing up real infrastructure for each one. So I built one locally: Vind as the host, nested vClusters as tenants, Argo CD driving deployments into them from Git, Cilium making sure tenants can’t see each other on the wire.</p><p>I built it on <strong>WSL2 </strong>with <strong>Docker Desktop</strong>, not native Linux. Since most tutorials assume the latter, expect unfamiliar territory whenever there’s an extra virtualization layer in the way (yay ! 😅).</p><p>That’s exactly why this build log exists: what broke, what surprised me, and how I got through it.</p><h4>Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oDoZxeMh6OYL5h4ieiRx0A.png" /></figure><p>Let’s break this down a bit :</p><ul><li>At the center we have a single <strong>vind</strong> cluster ( vCluster’s own “vCluster in Docker” driver) with one control plane and two workers. It acts as the management plane and our host cluster, hosting both Argo CD and Cilium, and nothing else.</li><li>Three tenants (<strong>dev</strong>, <strong>staging</strong>, <strong>prod)</strong> live as nested vClusters <em>inside</em> that management cluster, each with its own control plane, deployed as pods rather than standalone Docker instances in their own namespace.</li><li>Argo CD registers all three as remote clusters and ships one sample workload into each via the app-of-apps pattern — a single root object fanning out into per-tenant Applications, nothing deployed by hand after bootstrap.</li><li>Cilium replaces the default CNI and kube-proxy outright: flatter networking for an already-nested setup, and it’s the piece actually doing the isolating using a CiliumNetworkPolicy per tenant, deny-by-default except same-namespace traffic and the specific access Argo CD needs.</li></ul><p>Now that we explored the architecture, from here on, we get to explore how to get everything up and ready.</p><h4>Environment setup</h4><p>Vind ships with Flannel and kube-proxy enabled by default. So, if we want to use Cilium instead, we need to disable both at cluster creation time using a custom config file and install Cilium ourselves afterward.</p><p>In the following config file, we define a 2-worker-node cluster and turn off the built-in CNI and kube-proxy so Cilium can take over both roles.</p><pre>#vind-cilium.yaml<br><br>experimental:<br>  docker:<br>    nodes:<br>      - name: &quot;worker-1&quot;<br>      - name: &quot;worker-2&quot;<br>deploy:<br>  kubeProxy:<br>    enabled: false   # Cilium will replace kube-proxy<br>  cni:<br>    flannel:<br>      enabled: false  # Cilium will replace Flannel</pre><p>With the config file above, we spin up the host cluster. This is the “platform” cluster that will later house our nested tenant vclusters (dev, staging, prod).</p><pre># create platform vind cluster<br>vclsuter use driver docker<br>vcluster create platform -f vind-cilium.yaml</pre><p>At this stage, the cluster has no working pod networking yet so don’t be alarmed if nodes show NotReady or pods stay Pending until you install Cilium in the next step.</p><p>Cilium needs to know the Kubernetes API server’s address and port directly to bootstrap kubeProxyReplacement mode. Grab it using this command:</p><pre># find API server IP and PORT<br>kubectl get endpoints kubernetes -n default</pre><p>Now install Cilium, replacing both kube-proxy and Flannel. Swap in the IP and port from the previous step’s output.</p><p><strong>⚠️ Heads-up:</strong> we use --set envoy.enabled=false to avoid pulling in Cilium&#39;s separate Envoy proxy component, which isn&#39;t needed for basic kube-proxy replacement and adds startup overhead in an already resource-constrained local dev setup (especially relevant if you&#39;re running this inside WSL2/Docker Desktop, where memory is already shared and limited).</p><pre># configure cilium as cni<br>helm repo add cilium https://helm.cilium.io<br><br>helm repo update<br><br>helm install cilium cilium/cilium \<br>  --version 1.16.0 \<br>  --namespace kube-system \<br>  --set kubeProxyReplacement=true \<br>  --set k8sServiceHost=&lt;API SERVER IP&gt; \<br>  --set k8sServicePort=&lt;PORT&gt; \<br>  --set image.pullPolicy=IfNotPresent \<br>  --set ipam.mode=kubernetes \<br>  --set envoy.enabled=false</pre><p>Now that networking has been sorted, let’s install Argo CD into the host cluster. This will manage deployments across all your nested tenant vclusters from a single place.</p><pre># configure Argocd<br>kubectl create namespace argocd<br><br>kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml</pre><p>Now, let’s create our first nested tenant vcluster inside platform.</p><p><strong>⚠️ </strong>But before that, let’s talk about --background-proxy=false flag: vcluster normally spins up a separate <strong>background proxy</strong> <strong>container</strong> to handle the local connect tunnel, but in a nested Docker-in-WSL setup this proxy container&#39;s ports frequently fail to map back to the host correctly, causing vcluster connect to hang and eventually fail with a context deadline exceeded error. Disabling it forces a simpler, more reliable connection path but bear in mind that it will keep your current terminal occupied so you need to open another terminal if you wish to execute commands inside the tenant cluster.</p><p>In addition to that, pay attention to the --driver helmflag. This tells the CLI to deploy the tenant cluster as a pod inside whichever Kubernetes cluster the current context points to. Otherwise, it will create another Docker-level vind cluster instead.</p><p>Disconnect afterward before creating the other tenant clusters so your kubectl context returns to platform</p><pre>#create the nested vclusters<br>vcluster create dev --driver helm -n vc-dev --background-proxy=false<br><br>vcluster disconnect</pre><h4>Adding the clusters to Argo CD</h4><p>To let Argo CD manage dev, it needs a kubeconfig for it.</p><pre>#get the kubeconfig of the tenant cluster<br>vcluster connect dev -n vc-dev --driver-helm --print &gt; kubeconf-dev.yaml</pre><p><strong>⚠️ </strong>The --print flag dumps the kubeconfig vcluster generates internally for a local connect session, meaning its server URL points to localhost on a randomly assigned port, an address that&#39;s meaningless outside that session. To make this kubeconfig usable elsewhere, we need to replace that address with the actual in-cluster address of dev&#39;s virtual control plane.</p><p>Running kubectl get svc -n vc-dev shows us the service to target:</p><pre>kubectl get svc -n vc-dev <br><br>NAME                           TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                  AGE<br>dev                            ClusterIP   10.102.122.239   &lt;none&gt;        443/TCP,10250/TCP        11h<br>dev-headless                   ClusterIP   None             &lt;none&gt;        443/TCP                  11h<br>dev-node-worker-2              ClusterIP   10.107.248.137   &lt;none&gt;        10250/TCP                10h<br>kube-dns-x-kube-system-x-dev   ClusterIP   10.109.245.195   &lt;none&gt;        53/UDP,53/TCP,9153/TCP   10h</pre><p>The dev service exposes port 443. Since Argo CD runs inside the same host cluster as the tenant vclusters, we can address that service using its short in-cluster DNS name rather than a fully-qualified one. That gives us the server URL https://dev.vc-dev:443, which is what we plug into the kubeconfig.</p><p><strong>⚠️ </strong>It’s worth being precise here, because a close-but-wrong address will fail in a confusing way as it did for me. At first I used the fully-qualified dev.vc-dev.svc.cluster.local, since that&#39;s the more &quot;complete&quot; in-cluster DNS form but vcluster&#39;s generated TLS certificate for the tenant API server is issued for a specific, shorter set of SANs (dev, dev.vc-dev, and a few others) and does not include the .svc.cluster.local suffix and you can see that in the error message I got :</p><pre>x509: certificate is valid for kubernetes.default.svc.cluster.local, ..., dev, dev.vc-dev, ..., not dev.vc-dev.svc.cluster.local</pre><p>Now that our kubeconfig is ready, we will copy it into the argocd-server pod and running the command from inside the cluster.</p><pre>#copy the kubeconfig file into the argocd server container <br>kubectl cp kubeconf-dev.yaml argocd/&lt;argocd-server-pod-name&gt;:/tmp/kubeconf-dev.yaml -n argocd</pre><pre>#exec into the argocd server container <br>kubectl exec -it -n argocd &lt;argocd-server-pod-name&gt; -- sh</pre><pre>#login into argocd with username and password <br>$ argocd login localhost:8080 --insecure --username admin --pasword PASSWORD</pre><p>Finally, register dev with Argo CD, using the right context name and the path where you copied it inside the pod. A quick kubectl config get-contexts will show you the exact context name to use like the example below:</p><pre>#add cluster to argocd with the right context name and the kubeconfig that we copied<br>argocd cluster add vcluster_dev_vc-dev_vcluster-docker_platform --kubeconfig=/tmp/kubeconf-dev.yaml --name dev</pre><p>Repeat the steps to register the other tenant clusters.</p><h4>Tenant isolation with Cilium</h4><p>By default, every pod on the cluster can reach every other pod, regardless of which tenant it belongs to as ‘dev’, ‘staging’, and ‘prod’ all share the same underlying network. That defeats half the point of splitting them into separate vclusters in the first place, so the goal is simple: pods in vc-dev should only talk to other pods in vc-dev, and the same for staging and prod.</p><p>This is enforced with two CiliumNetworkPolicy objects per tenant namespace:</p><p>The first governs the namespace broadly: same-namespace traffic and egress to the host&#39;s API server via Cilium&#39;s reserved kube-apiserver entity.</p><pre>apiVersion: cilium.io/v2<br>kind: CiliumNetworkPolicy<br>metadata:<br>  name: tenant-isolation<br>  namespace: vc-dev<br>spec:<br>  endpointSelector: {}<br>  ingress:<br>    - fromEndpoints:<br>        - matchLabels:<br>            k8s:io.kubernetes.pod.namespace: vc-dev<br>  egress:<br>    - toEndpoints:<br>        - matchLabels:<br>            k8s:io.kubernetes.pod.namespace: vc-dev<br>    - toEntities:<br>        - kube-apiserver</pre><p>That kube-apiserver egress rule wasn&#39;t in the first version I applied, and its absence prevented the resources from being provisioned on the tenant cluster later on: the tenant&#39;s own vcluster syncer pod needs to call back out to the host&#39;s real API server to stay in sync, and with nothing else in the egress list covering that traffic, the policy silently blocked it.</p><p>The second policy is narrower on purpose: it targets <em>only</em> the syncer pod itself (app: vcluster, release: dev), not the namespace as a whole, and allows exactly one thing in: Argo CD&#39;s application controller, on the syncer&#39;s actual port.</p><pre>apiVersion: cilium.io/v2<br>kind: CiliumNetworkPolicy<br>metadata:<br>  name: vcluster-control-plane-ingress<br>  namespace: vc-dev<br>spec:<br>  endpointSelector:<br>    matchLabels:<br>      app: vcluster<br>      release: dev<br>  ingress:<br>    - fromEndpoints:<br>        - matchLabels:<br>            k8s:io.kubernetes.pod.namespace: argocd<br>            app.kubernetes.io/name: argocd-application-controller<br>      toPorts:<br>        - ports:<br>            - port: &quot;8443&quot;<br>              protocol: TCP</pre><h4>Deploying workloads with the app-of-apps pattern</h4><p>With the clusters registered, there’s exactly one more manual kubectl apply for the rest of this project: a root Application pointing at a directory in Git.</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br>  name: root-app<br>  namespace: argocd<br>spec:<br>  project: default<br>  source:<br>    repoURL: https://github.com/GHARBIyasmine/gitops-platform-demo.git<br>    targetRevision: main<br>    path: apps<br>    directory:<br>      recurse: true<br>      exclude: &#39;{guestbook/**,platform/cilium-policies/**}&#39;<br>  destination:<br>    server: https://kubernetes.default.svc<br>    namespace: argocd<br>  syncPolicy:<br>    automated:<br>      selfHeal: true<br>      prune: true</pre><pre>kubectl apply -f clusters/vind-platform/root-app.yaml</pre><p>Argo CD reads that directory, finds three more Application manifests inside it, one for each tenant, and creates them itself. That&#39;s the whole pattern: one object whose job is to point at other objects, so adding or changing an environment later is a one Git commit away.</p><p>Each child Application also carries its own sync policy, and this is where the three tenants diverge:</p><pre># dev — auto-sync, self-heal<br># staging — auto-sync, no self-heal<br># prod — no automated block, manual sync only</pre><ul><li>Dev takes every commit immediately, drift included.</li><li>Staging auto-syncs too, but won’t overwrite a manual investigation mid-flight.</li><li>Prod does nothing until someone runs argocd app sync guestbook-prod.</li></ul><p>It also applies the Cilium Network Policies on the host cluster not on the tenant clusters because the real pods live on the host nodes. Remember, the tenant cluster is a virtual control plane; it has no nodes of its own. Cilium runs on the host nodes, so policies must be applied where Cilium can enforce them i.e. on the host.</p><h4>CI validation</h4><p>We added a CI validation workflow to make sure no broken YAML goes unnoticed before we merge with the main branch and for that we used Kubeconfom with custom CRDs for CiliumNetworkPolicies as well.</p><p>The job does three things:</p><ul><li>Install Kustomize</li><li>Render every overlay plus the Cilium policy set</li><li>Then validate the rendered output against Kubernetes’ real schemas.</li></ul><p>In the validation step, we highlight the args used with Kubeconform:</p><pre>args: &quot;-summary -strict -ignore-missing-schemas -schema-location default \<br>       -schema-location https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json \<br>       rendered&quot;</pre><ul><li>-strict rejects unknown fields, not just malformed ones.</li><li>-schema-location default covers core Kubernetes types, but CiliumNetworkPolicy is a CRD, not a core API type, so it needs a second schema source which is the community-maintained CRDs-catalog</li><li>-ignore-missing-schemas so the job doesn&#39;t hard-fail on any future CRD that catalog doesn&#39;t happen to cover.</li></ul><h4>Wrap-up</h4><p>Well, there you have it folks! Now you have a vind host, three nested tenants, Argo CD reconciling all of it from Git, and Cilium enforcing that they can’t see each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQnKPy-4h1_cCdDBncwjmQ.png" /></figure><p>Along the way there were genuine unexpected hiccups, and most of them traced back to the same root: WSL2 + Docker Desktop puts an extra layer or two between you and what you’re actually running, and that layer doesn’t always behave the way the docs assume it will. On a plain Linux box, most of this would have just worked from the start, and I’d have learned a lot less.</p><p><strong>For the full code, check out my </strong><a href="https://github.com/GHARBIyasmine/gitops-platform-demo.git"><strong>GitHub repo</strong></a><strong>.</strong> Feel free to connect with me on <a href="https://www.linkedin.com/in/yasmine-gharbi-39b67221a/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d0097f36fd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating Penetration Testing with SecureCodeBox on Kubernetes Kind Clusters Using GitHub Actions]]></title>
            <link>https://medium.com/@gyasmine29/automating-penetration-testing-with-securecodebox-on-kubernetes-kind-clusters-using-github-actions-27230b8b087c?source=rss-499790578132------2</link>
            <guid isPermaLink="false">https://medium.com/p/27230b8b087c</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[securecodebox]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[kubernetes-operator]]></category>
            <dc:creator><![CDATA[Gyasmine]]></dc:creator>
            <pubDate>Tue, 07 Jan 2025 13:32:10 GMT</pubDate>
            <atom:updated>2025-01-07T16:44:09.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*Cxa-Xuq_LsaUZ6bY.png" /></figure><h4><strong>Introduction</strong></h4><p>Security testing is a crucial part of modern software development, but it often gets overlooked because manual penetration tests can be slow and hard to fit into fast-paced DevOps workflows. That’s where automation steps in to save the day.</p><p>In this blog, I’ll walk you through a simple example that not only <strong>automates penetration testing using SecureCodeBox </strong>— an open-source tool that simplifies security scans — but also <strong>generates reports to track issues and regressions</strong> while integrating <strong>custom warnings</strong> using echo commands for specific test logic. We’ll set up a pipeline with <strong>GitHub Actions</strong> to demonstrate how you can integrate security checks into your workflow without slowing things down.</p><p>This demo showcases the potential of SecureCodeBox to streamline security testing and highlights how you can use it to detect vulnerabilities early in your development process. Let’s dive in!</p><h4><strong>What is SecureCodeBox?</strong></h4><blockquote><strong>SecureCodeBox</strong> is a <strong>kubernetes-based</strong>, <strong>modularized toolchain</strong> for <strong>continuous security scans</strong> of your software project. Its goal is to <strong>orchestrate</strong> and easily automate a bunch of security-testing tools out of the box.</blockquote><p>SecureCodeBox operates as a Kubernetes-based operator, leveraging the declarative nature of Kubernetes to orchestrate security tools seamlessly. Its architecture revolves around “scans” and “scan results” as custom resources, enabling you to easily define, execute, and manage security tests in your cluster. Each scan is powered by popular open-source tools like <strong>nmap</strong>, <strong>Nikto</strong>, and <strong>OWASP ZAP</strong>, making it highly versatile for a wide range of security needs.</p><p>One of its standout features is its modular design, which allows you to pick and choose the scanners you need, avoiding unnecessary overhead. Additionally, SecureCodeBox is built with scalability in mind — it integrates smoothly into CI/CD pipelines and can handle anything from small-scale projects to enterprise-grade workloads. With SecureCodeBox, automating security testing is not just straightforward but also adaptable to the unique needs of your software development process.</p><blockquote>The default secureCodeBox Operator includes a <a href="https://min.io/"><strong>MinIO</strong></a><strong> </strong>instance, which acts as a <strong>local S3 filestorage API</strong> used by the secureCodeBox to <strong>store the results files</strong> <strong>of its scans.</strong> You can switch it out with a S3 compatible API provided by most cloud providers.</blockquote><p>The following figure illustrates an overview of its architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LxZCiZ7u8b4sUYqBwXXK8g.png" /><figcaption>SecureCodeBox — Architecture Diagram</figcaption></figure><h4><strong>Overview of the project</strong></h4><p>In this project, we’ll build a GitHub Actions pipeline that deploys <strong>SecureCodeBox</strong> alongside a target application in a <strong>Kubernetes kind cluster</strong>. For the target, we’ll use the <strong>Juice-Shop demo app</strong>, and the security test will feature an <strong>advanced ZAP scan</strong>, both well-documented in the <a href="https://www.securecodebox.io/docs/how-tos/scanning-web-applications">official SecureCodeBox tutorials.</a></p><p>The project is structured around the following milestones:</p><ul><li><strong>Automated Deployment</strong>: Set up a kind cluster, deploy the SecureCodeBox operator, and launch the Juice-Shop target application.</li><li><strong>Penetration Testing</strong>: Perform a full authenticated scan using the ZAP-Advanced scanner.</li><li><strong>Scan Monitoring</strong>: Track the status of the scan and retrieve detailed findings.</li><li><strong>Baseline Comparison</strong>: Compare scan results against a baseline to identify regressions or improvements.</li><li><strong>Continuous Integration</strong>: Automatically save findings and update reports directly in the repository.</li></ul><h4>Regression logic</h4><p>In this section, we’ll dive deeper into the regression logic, starting with how the baseline reports are created.</p><ol><li><strong>Constructing Scan Result Reports</strong></li></ol><p>SecureCodeBox provides a JSON file with detailed scan results, but these files are lengthy and not ideal for regression testing. This highlighted the need for a more concise and focused result file.</p><p>While exploring potential solutions, I discovered an interesting approach. After the scan completes, running the following command:</p><pre>Kubectl get scan zap-authenticated-full-scan-juiceshop -oyaml</pre><p>reveals an invaluable section called <strong>“findings”</strong> under the <strong>“status”</strong> field. This section offers a simplified version of the results, summarizing issue categories, their respective counts, and the total number of issues. This condensed format is perfect for regression testing, making it easy to track changes over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*ufBAN3zGlE1twy8LByG_4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*2jFt8jYuAfAvAQ81Fa9A2g.png" /></figure><p>To extract the relevant information, we use the following commands to gather key details from the scan results and then structure them into a JSON file:</p><pre>scan_name=$(kubectl get scan &quot;$SCAN_NAME&quot; -o=jsonpath=&#39;{.metadata.name}&#39;)<br>scan_uid=$(kubectl get scan &quot;$SCAN_NAME&quot; -o=jsonpath=&#39;{.metadata.uid}&#39;)<br>scan_findings_categories=$(kubectl get scan &quot;$SCAN_NAME&quot; -o=jsonpath=&#39;{.status.findings.categories}&#39;)<br>scan_findings_count=$(kubectl get scan &quot;$SCAN_NAME&quot; -o=jsonpath=&#39;{.status.findings.count}&#39;)</pre><p>These commands help us retrieve the scan’s name, unique identifier, findings categories, and total issue count. Using this data, we construct a JSON file in the following format:</p><pre>{<br>  &quot;scan_name&quot;: &quot;zap-authenticated-full-scan-juiceshop&quot;,<br>  &quot;scan_uid&quot;: &quot;d6c243c6-2142-49ef-961f-12d4ca50bc87&quot;,<br>  &quot;findings&quot;: {<br>    &quot;count&quot;: 12,<br>    &quot;categories&quot;: {<br>        &quot;Authentication Request Identified&quot;:1,<br>        &quot;Cloud Metadata Potentially Exposed&quot;:1,<br>        &quot;Content Security Policy (CSP) Header Not Set&quot;:1,<br>        &quot;Cross-Domain JavaScript Source File Inclusion&quot;:1,<br>        &quot;Cross-Domain Misconfiguration&quot;:1,<br>        &quot;Information Disclosure - Suspicious Comments&quot;:1,<br>        &quot;Modern Web Application&quot;:1,<br>        &quot;Private IP Disclosure&quot;:1,<br>        &quot;SQL Injection - SQLite&quot;:1,<br>        &quot;Session Management Response Identified&quot;:1,<br>        &quot;Timestamp Disclosure - Unix&quot;:1,<br>        &quot;User Agent Fuzzer&quot;:1<br>      }<br>  }<br>}</pre><p>2. <strong>Comparison and Testing logic</strong></p><p>The diagram below illustrates the core logic of the pipeline, showcasing how it manages different scenarios during its execution, such as detecting regressions, identifying new vulnerabilities, or confirming improvements in security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qO9YgdsxXWM3GknI" /></figure><h4>Building the Penetration Testing Pipeline</h4><p>The workflow is triggered on:</p><ul><li>Push Events: When changes are pushed to the main branch.</li><li>Manual Dispatch: Using the workflow_dispatch event.</li></ul><pre>on:<br>  push:<br>    branches:<br>      - main<br>  workflow_dispatch:</pre><p><strong>Jobs and Steps</strong></p><p>The pipeline consists of a single job that begins by defining essential environment variables:</p><pre>runs-on: ubuntu-latest<br>    env:<br>      TARGET_APP: juice-shop<br>      TARGET_APP_HELM: oci://ghcr.io/securecodebox/helm/juice-shop<br>      SCANNER: zap-advanced<br>      SCANNER_HELM: oci://ghcr.io/securecodebox/helm/zap-advanced<br>      SCAN_NAME: zap-authenticated-full-scan-juiceshop</pre><p><strong>Key Steps:</strong></p><ol><li><strong>Set Up Kubernetes Cluster:</strong> Deploys a Kind cluster and configures kubectl.</li></ol><pre>- name: Set up kind cluster<br>  uses: engineerd/setup-kind@v0.5.0<br>  with:<br>    version: &quot;v0.17.0&quot;<br><br><br>- name: Set up kubectl<br>  uses: azure/setup-kubectl@v3<br>  with:<br>    version: v1.27.1</pre><p>2. <strong>Checkout to the repository:</strong></p><pre>- name: Checkout repository<br>  uses: actions/checkout@v3</pre><p><strong>3. Install Helm and Jq:</strong> Installs Helm for managing SecureCodeBox components and Jq for ease of processing and manipulating JSON.</p><pre>- name: Install Helm<br>  uses: azure/setup-helm@v1<br>  with:<br>    version: v3.8.0<br><br>- name: Install jq<br>  run: sudo apt-get install -y jq</pre><p><strong>4. Deploy SecureCodeBox:</strong> Installs the SecureCodeBox operator.</p><pre>- name: Deploy SecureCodeBox<br>  run: |<br>    helm --namespace securecodebox-system upgrade --install --create-namespace securecodebox-operator oci://ghcr.io/securecodebox/helm/operator</pre><p><strong>5. Deploy Juice-Shop:</strong> Sets up the Juice-Shop demo target application.</p><pre>- name: Deploy Juice-Shop Demo Target<br>  run: |<br>    helm upgrade --install $TARGET_APP $TARGET_APP_HELM</pre><p><strong>6. Deploy ZAP-Advanced Scanner:</strong> Installs the ZAP-Advanced scanner.</p><pre>- name: Deploy ZAP-Advanced Scanner<br>  run: |<br>    helm upgrade --install $SCANNER $SCANNER_HELM</pre><p><strong>7. Initiate Scan:</strong> Runs a ZAP scan against the Juice-Shop target.</p><pre>- name: Apply scan.yaml<br>  run: kubectl apply -f ./scan.yaml</pre><p><strong>8. Monitor Scan Progress:</strong> Waits for the scan to complete.</p><pre>- name: Wait for ZAP Scan Results<br>  run: |<br>    # Poll for the scan state to become &quot;Done&quot;<br>    while true; do<br>      # Fetch the scan status and check for &quot;Done&quot; state<br>      scan_state=$(kubectl get scan &quot;$SCAN_NAME&quot; -o=jsonpath=&#39;{.status.state}&#39;)<br><br>      # Print the current scan state for debugging<br>      echo &quot;Current scan state: $scan_state&quot;<br><br>      # Break out of loop if scan is done<br>      if [[ &quot;$scan_state&quot; == &quot;Done&quot; ]]; then<br>        echo &quot;Scan completed!&quot;<br>        break<br>      fi<br><br>      # Wait 30 seconds before checking again<br>      sleep 30<br>    done</pre><p><strong>9. Retrieve Results:</strong> Downloads scan findings and generates summary reports.</p><p>In this step, we perform the following actions :</p><ul><li><strong>Set Up Port Forwarding to MinIO: </strong>Accesses the MinIO service locally on port 9000.</li><li><strong>Install the MinIO Client (mc): </strong>Downloads and configures the mc tool for interacting with MinIO.</li><li><strong>Configure MinIO Client Alias: </strong>Sets up an alias named local to interact with the MinIO instance using admin credentials.</li><li><strong>Retrieve Scan Metadata: </strong>Extracts key details of the completed scan, such as its unique ID (scan_uid), name (scan_name), and categorized findings, using kubectl commands.</li><li><strong>Process and Validate Findings:<br>-</strong> Strips newline characters from the findings and assigns a default value of 0 if no findings are present.<br>- Outputs the count and categories of findings for review.<br>- Ends the pipeline early if no issues are detected, passing the pipeline.</li><li><strong>Generate Report Files: </strong>Creates a summary JSON file and copies the full findings report from MinIO to the GitHub workspace for further use.</li><li><strong>Save Reports Locally</strong></li></ul><pre>- name: Retrieve ZAP Scan Results<br>  run: |<br>    kubectl port-forward -n securecodebox-system service/securecodebox-operator-minio 9000:9000 &amp;<br>    sleep 5<br><br>    curl -O https://dl.min.io/client/mc/release/linux-amd64/mc<br>    chmod +x mc<br>    sudo mv mc /usr/local/bin<br><br>    mc alias set local http://localhost:9000 admin password<br><br>    scan_uid=$(kubectl get scan &quot;$SCAN_NAME&quot; -o=jsonpath=&#39;{.metadata.uid}&#39;)<br>    # echo &quot;SCAN_UID=${scan_uid}&quot; &gt;&gt; $GITHUB_ENV<br>    <br>    scan_name=$(kubectl get scan &quot;$SCAN_NAME&quot; -o=jsonpath=&#39;{.metadata.name}&#39;)<br>    scan_findings_categories=$(kubectl get scan &quot;$SCAN_NAME&quot; -o=jsonpath=&#39;{.status.findings.categories}&#39;)<br>    scan_findings_categories=$(echo &quot;$scan_findings_categories&quot; | tr -d &#39;\n&#39;)<br><br>    scan_findings_count=$(kubectl get scan &quot;$SCAN_NAME&quot; -o=jsonpath=&#39;{.status.findings.count}&#39;)<br>    scan_findings_count=$(echo &quot;$scan_findings_count&quot; | tr -d &#39;\n&#39;)<br>    scan_findings_count=${scan_findings_count:-0} # Default to 0 if empty<br>    <br>    echo &quot;Scan findings count: $scan_findings_count&quot;<br>    echo &quot;SCAN_FINDINGS_COUNT=$scan_findings_count&quot; &gt;&gt; $GITHUB_ENV<br><br>    echo &quot;Categories: ${scan_findings_categories}&quot;<br>    echo &quot;Count: ${scan_findings_count}&quot;<br><br>    # Check if findings count is zero<br>    if [[ &quot;$scan_findings_count&quot; -eq 0 ]]; then<br>      echo &quot;No issues found. Pipeline passes.&quot;<br>      exit 0<br>    fi<br><br>    # Create summary file and findings file<br>    summary_file=&quot;$GITHUB_WORKSPACE/report-summary.json&quot;<br>    echo &quot;SUMMARY_FILE=${summary_file}&quot; &gt;&gt; $GITHUB_ENV<br>    echo &quot;{<br>      \&quot;scan_name\&quot;: \&quot;${scan_name}\&quot;,<br>      \&quot;scan_uid\&quot;: \&quot;${scan_uid}\&quot;,<br>      \&quot;findings\&quot;: {<br>        \&quot;count\&quot;: ${scan_findings_count},<br>        \&quot;categories\&quot;: ${scan_findings_categories}<br>      }<br>    }&quot; &gt; ${summary_file}<br>    <br>    mc cp local/securecodebox/scan-${scan_uid}/findings.json $GITHUB_WORKSPACE/findings.json<br>    <br>    echo &quot;Reports saved locally.&quot;</pre><p><strong>10. Configure Git:</strong> Configure the user that will commit to the repo.</p><pre>- name: Configure Git<br>  if: env.SCAN_FINDINGS_COUNT != &#39;0&#39; # Ensures this step is skipped if count is 0<br>  run: |<br>    git config --global user.name &quot;github-actions[bot]&quot;<br>    git config --global user.email &quot;github-actions[bot]@users.noreply.github.com&quot;</pre><p><strong>11. Baseline Comparison:</strong> Fetch and compares the findings with a baseline to track issues and improvements.</p><ul><li><strong>Retrieve Baseline Report:<br>- </strong>Sets up a directory for the baseline report.<br>- Copies the baseline report from the repository.<br>- Checks if the baseline report exists; if not, sets the current scan as the new baseline and pushes it to the repository.</li></ul><pre>- name: Retrieve Baseline Report<br>  if: env.SCAN_FINDINGS_COUNT != &#39;0&#39; # Ensures this step is skipped if count is 0<br>  run: |<br>    BASELINE_DIR=&quot;$GITHUB_WORKSPACE/baseline&quot;<br>    mkdir -p &quot;$BASELINE_DIR&quot;<br><br>    # Copy the baseline report from the repository to the temporary directory<br>    git ls-files | grep &#39;^report-summary\.json$&#39; | xargs -I{} cp {} &quot;$BASELINE_DIR/&quot;<br><br>    BASELINE_REPORT=&quot;$BASELINE_DIR/report-summary.json&quot;<br>    if [[ ! -f &quot;$BASELINE_REPORT&quot; ]]; then<br>      echo &quot;::warning::No baseline report found. Skipping comparison. Treating as new issues.&quot;<br>      mv &quot;$SUMMARY_FILE&quot; &quot;$BASELINE_DIR/report-summary.json&quot;<br>      git add &quot;$BASELINE_DIR/report-summary.json&quot; findings.json<br>      git commit -m &quot;Set initial baseline report&quot;<br>      git push<br>      exit 1<br>    fi<br>    echo &quot;Baseline report located at: $BASELINE_REPORT&quot;</pre><ul><li><strong>Compare Current Scan with Baseline:<br>- </strong>Extracts categories from the current and baseline reports.<br>- Compares categories to detect new findings, regressions, or persistent issues.<br>- Flags any categories no longer present as improvements.</li></ul><pre><br>- name: Check Baseline and Compare<br>  if: env.SCAN_FINDINGS_COUNT != &#39;0&#39; # Ensures this step is skipped if count is 0<br>  run: |<br>    BASELINE_REPORT=&quot;$GITHUB_WORKSPACE/baseline/report-summary.json&quot;<br>    CURRENT_REPORT=&quot;$SUMMARY_FILE&quot;<br><br>    BASELINE_CATEGORIES=$(jq -r &#39;.findings.categories | keys[]&#39; &quot;$BASELINE_REPORT&quot;)<br>    CURRENT_CATEGORIES=$(jq -r &#39;.findings.categories | keys[]&#39; &quot;$CURRENT_REPORT&quot;)<br><br>    echo &quot;Baseline found. Proceeding with comparison.&quot;<br>    echo &quot;Comparing $CURRENT_REPORT with $BASELINE_REPORT&quot;<br><br>    echo &quot;Baseline Categories: $BASELINE_CATEGORIES&quot;<br>    echo &quot;Current Categories: $CURRENT_CATEGORIES&quot;<br><br>    # Loop through current categories<br>    echo &quot;$CURRENT_CATEGORIES&quot; | while IFS= read -r category; do<br>      if ! echo &quot;$BASELINE_CATEGORIES&quot; | grep -Fxq &quot;$category&quot;; then<br>        echo &quot;::warning::New category detected: $category&quot;<br>      else<br>        BASELINE_COUNT=$(jq -r &quot;.findings.categories[\&quot;$category\&quot;]&quot; &quot;$BASELINE_REPORT&quot;)<br>        CURRENT_COUNT=$(jq -r &quot;.findings.categories[\&quot;$category\&quot;]&quot; &quot;$CURRENT_REPORT&quot;)<br>        if [[ &quot;$CURRENT_COUNT&quot; -gt &quot;$BASELINE_COUNT&quot; ]]; then<br>          echo &quot;::warning::Category &#39;$category&#39; count increased from $BASELINE_COUNT to $CURRENT_COUNT.&quot;<br>        elif [[ &quot;$CURRENT_COUNT&quot; -lt &quot;$BASELINE_COUNT&quot; ]]; then<br>          echo &quot;::warning::Category &#39;$category&#39; count decreased from $BASELINE_COUNT to $CURRENT_COUNT. Improvement noted. Issue Still persists&quot;<br>        else<br>          echo &quot;::warning::Category &#39;$category&#39; count remains the same: $CURRENT_COUNT. Persistent issue.&quot;<br>        fi<br>      fi<br>    done<br>    <br>    # Loop through baseline categories<br>    echo &quot;$BASELINE_CATEGORIES&quot; | while IFS= read -r baseline_category; do<br>      if ! echo &quot;$CURRENT_CATEGORIES&quot; | grep -Fxq &quot;$baseline_category&quot;; then<br>        echo &quot;::notice::Category &#39;$baseline_category&#39; is no longer present. Improvement noted.&quot;<br>      fi<br>    done</pre><p><strong>12. Save Reports:</strong> Commits findings and updates baseline reports in the repository.</p><pre>- name: Save Reports and Fail Pipeline<br>  if: env.SCAN_FINDINGS_COUNT != &#39;0&#39; # Ensures this step is skipped if count is 0<br>  run: |<br>    BASELINE_REPORT=&quot;$GITHUB_WORKSPACE/baseline/report-summary.json&quot;<br>    CURRENT_REPORT=&quot;$SUMMARY_FILE&quot;<br><br>    mv &quot;$CURRENT_REPORT&quot; &quot;$BASELINE_REPORT&quot;<br>    git add &quot;$BASELINE_REPORT&quot; findings.json<br>    git commit -m &quot;Update findings and report summaries [skip ci]&quot; || echo &quot;No changes to commit&quot;<br>    git push<br>    echo &quot;::error::Pipeline failed due to security issues.&quot;<br>    exit 1<br>  env:<br>    GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}</pre><h4>Pipeline testing and results</h4><p>Below are images capturing the echoes generated under various scenarios:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*31R1u_nC7seu9QOEgROtAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*_-yhnt7JsiQ3UApvgr-Aeg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*2dQq6W8hcOLCwVCCtrextg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*RJfFBGjKkqxAD0wIK4TNLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*R-gKT4TtmF_6hPTx6c6g3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*wUa6i8D82IPQA8bOU-geOg.png" /></figure><h4>Conclusion</h4><p>That’s it ! Thanks so much for reading until the end and I hope you found it helpful.</p><p>This project highlights how SecureCodeBox, GitHub Actions, and Kubernetes can streamline penetration testing in CI/CD workflows. From setting up automated scans to tracking regressions, we’ve built a pipeline that ensures security stays a priority throughout development.</p><p><strong>For the full pipeline setup, check out my </strong><a href="https://github.com/GHARBIyasmine/SecureCodeBox-Penetration-testing/"><strong>GitHub</strong></a><strong>.</strong> Feel free to connect with me on <a href="https://www.linkedin.com/in/yasmine-gharbi-39b67221a/">LinkedIn</a> to share thoughts or ask questions!</p><h4>References</h4><ul><li><a href="https://www.securecodebox.io/docs/how-tos">Overview | secureCodeBox</a></li><li><a href="https://www.securecodebox.io/docs/how-tos/scanning-web-applications">Scanning Web Applications | secureCodeBox</a></li><li><a href="https://github.com/secureCodeBox/integration-pipeline-jenkins-examples/blob/master/Jenkinsfile">integration-pipeline-jenkins-examples/Jenkinsfile at master · secureCodeBox/integration-pipeline-jenkins-examples</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27230b8b087c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>