Fall Cleaning #3: Locking the Shed (Kyverno, Network Policies & Secrets)

Goal & Abstract of Blog Post:

  • Goal:
    • Before the app touches AWS data, it got three locks that were proven in the cluster, including an unsigned image being rejected and a live secret rotation with no restart:
      • Secret delivered from Secrets Manager without ever touching Git or Terraform state
        • (signed images only)
      • Network that denies everything except two paths
        • (default-deny networking)
      • Admission check that refuses any image my CI didn’t sign
        • (settings pulled from secrets manager w/pod ID)

Github PRs:

StepCategoryFilesDecision baked in
App secret in Secrets ManagerPR-1:
– AWS / Infra
– new app-secrets.tf
– edit outputs.tf
– Write-only value
– Never in state
– Reads this one ARN only
Pod Identity: Kyverno reads ECRPR-1:
– AWS / Infra
– new kyverno-ecr.tf– ECR read on the say-when-app repo only
App uses the tokenPR-2:
– app
– app/main.py
– tests/test_main.py
– /admin/status: 200 with the token, 401 without; the token is read from a file on each request
New signed imagePR-2:
– App / CI
— (CI)– CI builds, scans, signs; note the new commit SHA
External Secrets for the appPR-3:
– GitOps
-new secretstore.yaml
– externalsecret.yaml
– edit deployment.yaml (volume + new image tag)
– lab-app.yaml (allow SecretStore and ExternalSecret)
– Token mounted read-only at /etc/say-when/secrets/
Default-deny networkPR-3:
– GitOps
– new networkpolicy-default-deny.yaml
– networkpolicy-allow.yaml
– edit lab-app.yaml (allow NetworkPolicy)
-Allow only Envoy → app :8080 and app → DNS
Signed images onlyPR-3:
– GitOps / Security
– new apps/kyverno/policies/verify-say-when-image.yaml– Audit mode; identity = your build.yaml on main
Prove itProof (cluster up)—– Secret synced · /admin/status 401/200 · network blocked · Kyverno passes the real image
Flip to DenyPR-4:
– GitOps / Security
– edit the policy: Audit → Deny– Only after step 8 shows the real image passing
Prove Deny, then tear downProof (cluster up)—– An unsigned image is rejected; token rotation is picked up live
  • PR 1 and PR 2
    • Are independent – Do them in any order.
  • PR 3
    • Waits for PR 2’s CI run, because the Deployment needs the new image’s commit SHA.
  • PR 4
    • Happens mid-session, only after the real image is shown passing in Audit.

Step 1: AWS Infra – App Secret in Secrets Manager

App secret in Secrets Manager

  • Purpose:
    • One secret, read by External Secrets Operator and synced into the say-when namespace, the app reads it as a mounted file.
      • Token
        • Generated ephemerally and written with the write-only secret_string_wo argument.
          • It is never stored in Terraform state or plan output.
      • Lifetime
        • Tied to the cluster workspace. Destroyed with recovery_window_in_days = 0, so every rebuild gets a fresh token.
  • Supplemental:
    • External Secrets uses one AWS identity for the whole operator. That means any namespace allowed to create a SecretStore could ask for any secret that role can read, the demo secret included.
    • Only lab-app will be allowed to create a SecretStore in say-when.
    • The stronger fix is a per-namespace IAM role that the SecretStore assumes.

infa/app-secrets.tf

PieceChoiceWhy
ephemeral "random_password" + secret_string_woThe value is generated and written without being savedTerraform state is a file. Anything in it can leak. Write-only arguments keep the token out of state and plans entirely, the same as your demo secret.
special = false, 48 charactersLetters and digits onlyIt goes in an HTTP header. With no special characters, there’s no escaping trouble.
recovery_window_in_days = 0Deleted immediately on destroyOtherwise AWS holds a deleted secret for 7–30 days, and recreating the same name fails during that window.
A separate IAM policy on the existing ESO roleIt reads exactly one ARNThe demo policy stays untouched, and each secret’s access is its own reviewable object.
Lives in the cluster workspaceDestroyed with the clusterEvery rebuild gets a new token, so rotation happens for free

Step 2: AWS Infra – Pod ID, Kyverno reads ECR

Pod Identity: Kyverno reads ECR

infra/kyverno-ecr.tf

  • Kyverno’s built-in AWS credential helper uses the standard credential chain, which picks up EKS Pod Identity:
    • Setup is an IAM role
    • A narrow policy
    • Association to Kyverno’s service account.
    • There are no keys and no image-pull secrets.
  • The ECR repo belongs to bootstrap/github-actions (separate state), so it is looked up by name here, not managed.
  • 2 pieces involved:
    • Admission controller
      • Checks pods as they’re created
    • Reports controller
      • Re-checks running pods in the background and writes policy reports
=======
helm repo add kyverno https://kyverno.github.io/kyverno/ 2>/dev/null
=======
helm repo update kyverno
=======
helm template kyverno kyverno/kyverno --version 3.9.1 -n kyverno \
| grep -A3 "^kind: ServiceAccount" | grep "name:"
=======
PieceChoiceWhy
data "aws_ecr_repository"Looks up the repo, doesn’t own itThe repo lives in bootstrap/github-actions, which has its own state and must survive cluster teardowns. This workspace only needs its ARN.
Its own role (not ESO’s)kyverno-ecr-read-pod-identity-roleOne identity per job. Kyverno can read images but not secrets, and ESO can read secrets but not images.
Read-only actions on one repo ARNNo Put*, no other reposKyverno only checks signatures. If it were ever compromised, it couldn’t push or tamper.
GetAuthorizationToken on *UnavoidableAWS doesn’t support scoping that action to a repository. The token alone grants nothing without the repo-scoped actions.
ListImages + DescribeImagesIncludedCosign 3 stores signatures as untagged referrer images linked to the digest, as you saw in ECR. These let Kyverno find them.
for_each over two service accountsOne role, two associationsThe admission and reports controllers both verify images. A third would be a one-line change.
depends_on the Pod Identity agentOrderingAn association does nothing until the agent add-on is running, the same as your ESO association.

Step 3: App – App uses Token

App use Token

app/main.py

  • Adds import hmac and Header in the FastAPI import.
=======
import hmac
from fastapi import FastAPI, Header, HTTPException, Response
=======
# The admin token arrives as a file mounted from a Kubernetes Secret
# (synced from AWS Secrets Manager by External Secrets, Fall #3).
ADMIN_TOKEN_FILE_DEFAULT = "/etc/say-when/secrets/admin_token"
=======
ChoiceWhy
Read the file per requestWhen External Secrets updates the Secret, the kubelet refreshes the mounted file, and the very next request uses the new token. That’s the same live-update trick as the chores.
A header (X-Admin-Token), not ?token=Query strings end up in access logs, browser history and proxies. Headers usually don’t. FastAPI maps x_admin_token to the X-Admin-Token header automatically.
hmac.compare_digestA constant-time comparison. A plain == stops at the first wrong character, so response timing can leak how much of a guess was right.
No file → 503, wrong token → 401It fails closed: if the Secret is missing, admin is unavailable, never open. A 503 also tells you in Part 8 that the mount is missing, which a 401 wouldn’t.
Returns the version and the chore count, never the tokenProves the secret arrived without echoing it anywhere.
Not added to the HTTPRoute/admin stays internal-only. You’ll test it with a port-forward to the Service. The public front door returns 404, like /metrics.

app/test_main.py

  • monkeypatch sets the environment variable for one test only.
  • tmp_path gives each test its own throwaway folder.
  • Both are built into pytest, so nothing new is installed, and the tests never touch your real filesystem.
=======
pytest -q
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
14 passed, 1 warning in 0.86s
=======

Step 4: App – New Signed Image in CI

New Signed Image

  • Quick sanity check of process being followed
    • Build image
    • Scan w/Trivy
    • AWS Credz, Login to ECR
    • Push image
    • SBOM
    • Cosign
    • Verify Signature
    • Post stuff..
=======
aws sso login \
--profile "$AWS_PROFILE" \
--use-device-code
=======
aws sts get-caller-identity
=======
aws ecr describe-images --repository-name say-when-app \
--image-ids imageTag= \
--query 'imageDetails[0].{pushed:imagePushedAt,tag:imageTags[0]}' --output table
=======
----------------------------------------------------------------------------------
| DescribeImages |
+-----------------------------------+--------------------------------------------+
| pushed | tag |
+-----------------------------------+--------------------------------------------+
| 2026-11-23T13:41:04.148000-06:00 | xyz |
+-----------------------------------+--------------------------------------------+

Step 5: Gitops – External Secrets for App

Summary of files updated

ChoiceWhy
Argo manages the ExternalSecret; ESO creates the SecretThe token value never appears in Git, in Argo’s UI or in a diff. Secret is still not on the lab-app allow-list, so nobody can sneak in a raw Secret through GitOps.
A namespaced SecretStore, no credentialsIt uses ESO’s Pod Identity, and IAM limits that role to the two secrets granted in Terraform. (The shared-identity tradeoff from step 1 still applies; it’s on the Fall #10 list.)
refreshInterval: 1mSo the step 10 rotation demo shows up within a minute. In production you’d use something like 1h to make fewer AWS calls.
fsGroup: 10001 + defaultMode: 0440Secret files are owned by root. Without fsGroup, a 0440 file is unreadable to your non-root uid 10001, and /admin/status would return 503. fsGroup gives the group to 10001, and 0440 means only that group can read it.
Mounted at /etc/say-when/secrets/, items maps one keyOnly the admin_token key becomes a file. It’s a separate folder from the chores mount, so the two volumes don’t collide.
New tag ce7d608…The commit CI just built, scanned, signed and pushed.
Not optionalIf the Secret hasn’t synced yet, the pods wait (ContainerCreating) and start once it exists, a visible failure instead of a silent 503.

apps/say-when-app/secretstore.yaml

apps/say-when-app/externalsecret.yaml

apps/say-when-app/deployment.yaml

================
template:
spec:
securitycontext:
runAsUser: 10001
fsGroup: 10001 # NEW: mounted Secret files owned by group 10001
================
containers:
env:
- name: ADMIN_TOKEN_FILE # NEW
value: /etc/say-when/secrets/admin_token
volumeMounts:
- name: app-settings # NEW
mountPath: /etc/say-when/secrets
readOnly: true
================
volumes:
- name: app-settings # NEW
secret:
secretName: say-when-app-settings
defaultMode: 0440 # owner + group read only; group = fsGroup 10001
items:
- key: admin_token
path: admin_token

applications/lab/projects/lab-app.yaml


================
    # Fall #3: secrets arrive through External Secrets, never as raw Secrets.
    - group: external-secrets.io
      kind: SecretStore
================
    - group: external-secrets.io
      kind: ExternalSecret
================
    # Fall #3: default-deny networking for the app.
    - group: networking.k8s.io
      kind: NetworkPolicy
================

Step 6: Gitops – Default Deny Network

  • Any pod in the cluster can call your app, and your app can call anything, including the internet.
  • Default-deny flips that:
    • Nothing in or out unless explicitly allowed.
    • Your VPC CNI already enforces NetworkPolicies (enableNetworkPolicy = "true" in infra/eks.tf), so these take effect for real & reads the file – not the network.
  • The app needs exactly two paths:
    • in: Envoy → app on 8080
    • out: app → DNS

Summary of files updated

ChoiceWhy
Deny both directionsIngress-only deny (like your monitoring policy) stops attackers getting in. Egress deny stops a compromised app calling out to download tools or send data elsewhere.
namespaceSelector and podSelector in one itemTwo selectors under one - mean AND: “Envoy pods of this Gateway, in that namespace”. Written as two separate - items they’d mean OR, which would allow every pod in envoy-gateway-system, a classic NetworkPolicy mistake.
owning-gateway-name: say-whenThe same label you used in Fall #2 to find the Envoy Service. Envoy Gateway puts it on the proxy pods too, so the demo Gateway’s Envoy can’t reach your app.
DNS only, on UDP and TCP 53DNS falls back to TCP for large answers. Without this rule, even resolving a Service name would fail.
No Prometheus rule yetNothing scrapes /metrics until Fall #7. That post adds one allow rule.

apps/say-when-app/networkpolicy-default-deny.yaml

aapps/say-when-app/networkpolicy-allow.yaml

Step 7: Gitops – Signed Image’s Only for Security

  • Same manual cli command of cosign verify in Fall #1… now run automatically on every pod.
  • Sources:
    • kyverno
    • An ImageValidatingPolicy’s keyless attestor lists accepted signers as identities with a subject and issuer.
      • For private registries, the policy declares its own credentials.
    • The supported providers are default, amazon, google, azure, and github, and there are no global credential helpers: providers must be declared per-policy.
      • So the policy says providers: [amazon], which uses the Pod Identity role from step 2.

Summary of updates

ChoiceWhy
Scoped to say-when onlyPlatform images (Argo, Envoy, Prometheus…) aren’t signed by your workflow. A cluster-wide rule would block them.
glob: "*"Matches every image in the namespace. If it matched only your ECR repo, nginx:latest would skip verification and slip in.
Audit + failurePolicy: IgnoreFirst you learn whether verification works (results go to PolicyReports) without risking your own pods being blocked. Deny + Fail is PR 4, mid-session.
> 0At least one valid signature from the ci attestor.
lab-security-manifests ApplicationSet already syncs everything in apps/kyverno/policies/, so no new Application is needed.

apps/kyverno/policies/verify-say-when-image.yaml

  • Purpose:
    • Every container image in say-when must carry a Cosign keyless signature from the say_when_app build workflow on main.
      • This is the same check as `cosign verify` in Fall #1, run at admission.
    • Rollout:
      • Audit first (results land in PolicyReports, nothing is blocked; failurePolicy Ignore so a verifier error can’t stall the app).
      • After the real image is shown passing, flip to Deny + Fail.
      • Registry auth: providers:
        • [amazon] uses Kyverno’s EKS Pod Identity role (say_when_infra kyverno-ecr.tf), read-only on say-when-app.
  • Sources:

applications/lab/projects/lab-security.yaml

===========
- group: policies.kyverno.io
kind: ImageValidatingPolicy
===========

Step 8: Show-Off & spin Cluster up

  • HCP Terraform → infra → New run → Plan and apply
  • Argo Green
    • About 10 minutes
    • ait for everything to be Synced / Healthy, especially external-secrets, kyverno, kyverno-policies and say-when-app.
  • Did Secrets Arrive?
    • About 5 minutes
===========
aws eks update-kubeconfig --name say-when-east --region us-east-1
===========
kubectl get nodes -L kubernetes.io/arch
===========
kubectl -n say-when get externalsecret say-when-app-settings
===========
kubectl -n say-when get secret say-when-app-settings
===========
kubectl -n say-when get pods -o wide
===========
CheckResult
ExternalSecret✅ SecretSynced, READY True, refreshed 18 s ago
Secret✅ exists, 1 key (admin_token)
Pods✅ 2/2 READY 1/1 on different On-Demand nodes
Unknown: probes vs default-deny✅ Resolved. The pods are Ready with default-deny in place, so the VPC CNI’s policy engine lets the kubelet’s /healthz probes through. No extra rule needed.
Image✅ ce7d608c…, with a digest appended:

Below are a few tests to confirm your a-ok: admin endpt, network boundary, kyverno audit, audit to fail

  • 4 steps below
    • admin endpoint
    • network boundary
      • envoy forword
      • ingress blocked
      • Egress Blocked, DNS allowed
    • kyverno audit
      • poilcyreport
      • imagevalidatingpolicy
      • unsigned image – busybox
    • gitops – audit to fail
      • rotate passy
GoalProof
Settings from Secrets Manager via Pod IdentityExternalSecret synced; /admin/status 401/401/200
Default-deny networkingEnvoy allowed, /admin 404, other namespace blocked, internet blocked, DNS allowed
Signed images onlyAudit: app PASS / busybox FAIL → Deny: busybox refused, signed rollout admitted
Live rotationOld token 401, new 200, no restarts

Admin Endpoint

  • About 5 minutes
  • PF straight to the Service.
    • Port-forward travels through the kubelet, not the pod network, so NetworkPolicies don’t apply to it:
TestResult
Token from Secrets Manager✅ 48 characters, never printed
No token✅ 401
Wrong token✅ 401
Right token✅ 200: admin: true, version: ce7d608…, chores: 10
  • After PF, test these out.
URLYou’ll see
http://localhost:8081/docsThe Swagger page, now with /admin/status listed, and the version badge showing ce7d608…
http://localhost:8081/admin/status401, because a browser can’t send the X-Admin-Token header from the address bar
http://localhost:8081/choresThe 10 chores
http://localhost:8081/metricsWorks here, since this is the internal path. Through Envoy (8888) it’s a 404

Network boundary

  • About 10 minutes
  • Basically what were doing is –
A (from)B (to)ExpectThe tool, in plain words
Your laptop, through Envoythe appallowedport-forward to Envoy, then curl
Your laptop, through Envoy/admin404same, different path
A pod in another namespacethe appblockedstart a throwaway pod there, have it wget the app
Inside the appDNS / the internetallowed / blockedrun a command inside the app’s container (exec)

CLI: Envoy Forward

===========
SVC=$(kubectl -n envoy-gateway-system get svc -l gateway.envoyproxy.io/owning-gateway-name=say-when -o name)
kubectl -n envoy-gateway-system port-forward "$SVC" 8888:80 >/dev/null 2>&1 &
sleep 3
curl -s -H 'Host: cleanup.local' localhost:8888/version; echo # → ce7d608… (Envoy → app allowed)
curl -s -o /dev/null -w '/admin via Envoy → %{http_code}\n' -H 'Host: cleanup.local' localhost:8888/admin/status # → 404 (not routed)
===========

CLI: Ingress Blocked

===========
kubectl run nettest --rm -i --restart=Never --image=public.ecr.aws/docker/library/busybox:1.36 \
-- wget -T 5 -qO- http://say-when-app.say-when:8080/healthz ; echo "exit: $?"
===========

CLI: Egress Blocked, DNS allowed

===========
kubectl -n say-when exec deploy/say-when-app -- python -c \
"import socket; print('DNS ok:', socket.gethostbyname('kubernetes.default.svc.cluster.local'))"
kubectl -n say-when exec deploy/say-when-app -- python -c \
"import urllib.request; urllib.request.urlopen('https://example.com', timeout=5)" ; echo "exit: $?"
===========
Error from server: admission webhook "vpol.validate.kyverno.svc-fail" denied the request:
Policy disallow-privilege-escalation failed: Containers must set securityContext.allowPrivilegeEscalation to false.
exit: 1
===========
  • After doing the 3 tests below, you should see
DirectionTestResult
In, allowedEnvoy → app✅ {"version":"ce7d608…"}
In, not routed/admin via Envoy✅ 404
In, deniedA pod in default → app✅ BLOCKED (5 s timeout)
Out, allowedApp → DNS✅ 172.20.0.1
Out, deniedApp → internet✅ Network is unreachable

K9s: The 3 tests above can be done in K9s

What you wantIn k9s
See the policies:netpol → select one → d (describe) shows exactly what’s allowed in and out
Port-forward (instead of kubectl port-forward):svc → select say-when-app (or the Envoy service) → Shift+F → pick the port
Get inside the app (instead of kubectl exec):pods → select a say-when-app pod → s (shell). Then just type: python -c "import urllib.request; urllib.request.urlopen('https://example.com', timeout=5)"
Watch a test pod run:pods → watch nettest appear → select it → l (logs) to see BLOCKED
Why something was refused (like Kyverno’s denial):events, which shows the newest refusals and errors first

Kyverno Audit

  • About 10 minutes
  • Look for a PASS – test an unsigned image. Save this throwaway pod, which follows every other rule (restricted PSS, limits, no latest)

PolicyReport

===========
kubectl -n say-when get policyreports -o wide
===========
NAME KIND NAME PASS FAIL WARN ERROR SKIP AGE
2cae43da- Pod say-when-app-6cb5944c9b-mktx9 9 0 0 0 0 38m
2d97e3f9- Deployment say-when-app 9 0 0 0 0 90m
740b64c3- ReplicaSet say-when-app-6cb5944c9b 9 0 0 0 0 87m
fd93ae08- Pod say-when-app-6cb5944c9b-qk9ds 9 0 0 0 0 38m
===========

ImageValidatingPolicy

===========
kubectl get imagevalidatingpolicy verify-say-when-image
===========
NAME AGE READY
verify-say-when-image 92m true
===========

Unsigned test busybox

===========
kubectl run unsigned-test -n say-when \
--image=public.ecr.aws/docker/library/busybox:1.36 \
--dry-run=client -o yaml -- sleep 600 > /tmp/mypod.yaml
===========
kubectl apply --dry-run=server -f /tmp/mypod.yaml
===========

All Passed:

What that proves:

  • Kyverno’s own log names the reason: failed to verify cosign signatures: no signatures found for busybox. What that proves:
    • ✅ Kyverno can read Cosign 3’s referrer-style signatures from ECR. This was the big unknown, and it’s what made Audit-first worth it.
    • ✅ Pod Identity works for Kyverno. The docs only mentioned IRSA, but the amazon provider picked up the Pod Identity role from kyverno-ecr.tf.
    • ✅ glob: "*" catches public images too. A busybox from public.ecr.aws was checked and failed.
    • ✅ Audit really only logs. unsigned-test was created anyway.

Step 9: Gitops – Flip to Deny

  • About 10 minutes
    • Kyverno: enforce signed images in say-when (Deny, failurePolicy Fail)
    • Audit showed say-when-app PASS (Cosign 3 referrers via ECR + Pod Identity) and unsigned busybox FAIL. Now enforce.
  • Can do in CLI or ArgoCD UI & K9s
===========
kubectl -n argocd annotate application kyverno-policies argocd.argoproj.io/refresh=normal --overwrite
sleep 30
===========
kubectl get imagevalidatingpolicy verify-say-when-image -o jsonpath='{.spec.validationActions}{"\n"}' # → ["Deny"]
===========

Prove directions – unassigned image should be rejected

  • Expect admission webhook … denied the request: Images in say-when must be signed.
===========
kubectl apply -f /tmp/unsigned-test.yam
===========
Error from server: error when creating "/tmp/unsigned-test.yaml": admission webhook
Images in say-when must be signed by the say_when_app build workflow on main.
===========

Signed image is Admitted

  • New pods only start if Kyverno verified their signature live.
===========
kubectl -n say-when rollout restart deploy/say-when-app
===========
kubectl -n say-when rollout status deploy/say-when-app
===========
NAME READY STATUS RESTARTS AGE
say-when-app-5 1/1 Running 0 22s
say-when-app- 1/1 Running 0 9s
say-when-app-6 1/1 Terminating 0 70m
===========

Rotate token, no restart

  • About 10 minutes
  • If old token still returns 200…wait 60 seconds & try try again.
  • PF 8081
    • If rollout restart killed it: rerun the port-forward
  • Acitivity outside of Terraform
    • Rotating is fine here since the value is write-only
    • Terraform never compares it, and the secret is deleted at teardown anyway.
===========
NEW=$(python3 -c "import secrets,string; a=string.ascii_letters+string.digits; print(''.join(secrets.choice(a) for _ in range(48)))")
aws secretsmanager put-secret-value --secret-id say-when/app/settings \
--secret-string "{\"admin_token\":\"$NEW\"}" >/dev/null && echo "rotated"
===========
kubectl -n say-when get pods # note names and ages
===========
rotated at 11:55:21
===========

===========sleep 150    # ESO refresh (1m) + kubelet file refresh (~1m)
curl -s -o /dev/null -w 'old token → %{http_code}\n' -H "X-Admin-Token: $TOKEN" localhost:8081/admin/status   # → 401
curl -s -o /dev/null -w 'new token → %{http_code}\n' -H "X-Admin-Token: $NEW"   localhost:8081/admin/status   # → 200
===========
kubectl -n say-when get pods
===========
old token → 401
new token → 200
NAME                            READY   STATUS    RESTARTS   AGE
say-when-app-578f8676bd-2cspl   1/1     Running   0          7m7s
say-when-app-578f8676bd-7lsgm   1/1     Running   0          6m54s
NAME                    STORETYPE     STORE                 REFRESH INTERVAL   STATUS         READY   LAST SYNC
say-when-app-settings   SecretStore   aws-secrets-manager   1m                 SecretSynced   True    14s
===========

Step 10: Spin Cluster down

  • About 15 minutes
  • Queue an HCP destroy plan, then confirm.
===========
kill $(jobs -p) 2>/dev/null; unset TOKEN NEW
===========
rm -f /tmp/unsigned-test.yaml
===========
aws ec2 describe-volumes --region us-east-1 \
--filters Name=status,Values=available \
Name=tag:kubernetes.io/created-for/pvc/namespace,Values=monitoring \
--query 'Volumes[].VolumeId' --output text