Kubernetes Hour 5: Security and Multi-tenancy

From “how a request gets through” to “how a team is kept inside its own namespace”: authentication → authorization → admission → runtime hardening → secrets → tenant isolation and audit
Kubernetes v1.37.1kind v0.33.0AKS optionalVerified against official docs · 2026-11
Overall learning goals
  • Trace the full path of an API request through Authentication → Authorization → Admission (mutating → validating) → etcd, and use the 401 / 403 / admission-denial messages to tell which layer it got stuck at.
  • Design identities for people (X.509 certificates, OIDC / Entra ID) and for workloads (ServiceAccount, Workload Identity), and write least-privilege RBAC.
  • Use Pod Security Admission (restricted) and securityContext to harden the shop web / api / db workloads to “non-root, read-only root filesystem, drop ALL, seccomp RuntimeDefault”.
  • Write organization-wide rules with ValidatingAdmissionPolicy (CEL), such as banning :latest and requiring limits, and understand the trade-offs between webhooks, Kyverno, and Gatekeeper.
  • Know that Secrets are only base64-encoded in etcd by default. Enable encryption at rest and verify the k8s:enc: prefix. Use Key Vault with the CSI driver or ESO to keep keys outside the cluster.
  • Build a “soft tenant” for a team: Namespace + Quota + LimitRange + default-deny NetworkPolicy + RBAC + PSS + audit logging.

1-hour timetable

#TimeModuleCore contentAnimation / interactionLab
0Before classWarm-up4C security model, threat model, shop security baseline check—Hands-on test: “what can a compromised Pod do”
100–07AuthenticationX.509 (CN/O), SA JWT, OIDC / AuthenticationConfiguration, exec plugins, whoamiauthn → authz → admission request chainIssue a certificate for alice through the CSR API
207–15Authorization (RBAC)Role/ClusterRole/Binding, subresources, aggregation, dangerous permissions, can-iRBAC decision simulatorDeveloper role + least-privilege CI ServiceAccount
315–22ServiceAccount and Workload IdentityProjected tokens, TokenRequest, issuer discovery, AKS Workload IDToken exchange flow animationDecode the SA JWT; AKS reads Key Vault (optional)
422–29Pod Security StandardsPrivileged/Baseline/Restricted, PSA labels, dry-run, exemptionsPod fields → three-level evaluatorLabel shop as restricted and fix it
529–36securityContext and container hardeningrunAs*, read-only root, capabilities, seccomp, AppArmor, userns, supply chainHardening switches → attack outcomesHarden podinfo and verify
636–44Admission controlVAP (CEL), MAP (v1.36 GA), webhooks, Kyverno/Gatekeeper, manifest-based admissionAdmission chain animationVAP bans :latest + requires limits
744–52Secret security and external keysEncryptionConfiguration, KMS v2, Key Vault CSI, ESO, Sealed Secrets/SOPSetcd encrypted write/readEnable aescbc in kind and verify with etcdctl
852–60Multi-tenancy and auditResourceQuota, LimitRange, isolation layers, vCluster, Audit PolicyQuota simulator + troubleshooting decision treeTeam tenant + audit logs
—After classCheat sheet · Capstone labBuild a “team tenant” for shop, end to endFinal quiz: 12 questionsCapstone lab

Knowledge coverage matrix

Target skillModuleKey commands / objectsLabQuiz
Identify which layer (authn / authz / admission) a request is stuck atM1 · M6kubectl auth whoami, -v=8✓✓
Issue an X.509 certificate for a user and configure kubeconfigM1CertificateSigningRequest, kubectl certificate approve✓✓
Log in to the cluster with OIDC / Entra IDM1 · M2AuthenticationConfiguration, kubeloginAKS optional✓
Write least-privilege RBAC and audit itM2kubectl auth can-i --list --as, auth reconcile✓✓
Identify dangerous permissions (secrets, pods/exec, escalate, bind, impersonate)M2 · M7kubectl-who-can, rbac-tool✓✓
Short-lived, bound workload identityM3kubectl create token, projected volumes✓✓
Passwordless Pod access to Azure resourcesM3 · M7az identity federated-credential createAKS optional✓
Namespace-level Pod security baselineM4pod-security.kubernetes.io/enforce, --dry-run=server✓✓
Container runtime hardeningM5securityContext, seccomp, capabilities✓✓
Organization-wide policy as codeM6ValidatingAdmissionPolicy, CEL✓✓
Secret encryption at rest and external keysM7EncryptionConfiguration, etcdctl, SecretProviderClass✓✓
Tenant resources and isolationM8ResourceQuota, LimitRange, NetworkPolicy✓✓
Audit “who did what, and when”M8Audit Policy, AKS kube-audit-admin✓✓

Topics excluded from this hour (time limit)

TopicWhy it is not in this hourWhere to learn it
NetworkPolicy syntax detailsCovered in hour 3; this hour only reuses “default deny”Hour 3
Runtime threat detection (Falco, Tetragon, Defender for Containers)Belongs to detection and response; needs its own hourfalco.org; Microsoft Defender for Containers docs
Service mesh mTLS (Istio / Linkerd)Belongs to east-west traffic security; a lot of configurationistio.io / linkerd.io
Node and control-plane CIS hardening (kube-bench)Managed clusters (AKS) leave most control-plane hardening to the platformCIS Kubernetes Benchmark, kube-bench
Image vulnerability scanning and SBOM pipelineThe Docker hour covered the build side; this hour covers only verification on the admission sideDocker hour modules 4 and 8; Trivy / Grype
The full secret flow in GitOpsBelongs to the GitOps topicGitOps and Argo CD course

How to use this course material

10 pages per module
Principles · diagrams · animation · commands · lab · production case · troubleshooting · quiz · voice · video. Start with “animation” to build intuition, then go to “lab” to try it yourself.
Learning progress
A module counts toward progress when your quiz score is ≥ 70% or you click “Mark this module complete.” Progress is saved in this browser's localStorage.
English voice
The “Voice” tab reads the narration script aloud with the browser's Web Speech API (en-US). If no English voice pack is installed, a notice appears, and the script can go straight into another TTS tool.
Version notes This hour is based on Kubernetes v1.37.1. Stage information used in this hour: Pod Security Admission v1.25 GA (PSP removed in the same release); kubectl auth whoami (SelfSubjectReview) v1.28 GA; KMS v2 v1.29 GA; ValidatingAdmissionPolicy v1.30 GA; the AppArmor field appArmorProfile v1.30 GA; structured authentication configuration AuthenticationConfiguration v1.34 GA; MutatingAdmissionPolicy v1.36 GA (admissionregistration.k8s.io/v1); User Namespaces (hostUsers: false) v1.36 GA; Pod Certificates / ClusterTrustBundle and SELinuxMount v1.37 GA; manifest-based admission control v1.37 Beta (enabled by default). AKS commands follow the Microsoft Learn pages dated 2026-07 to 10.
Lab safety note Modules 7 and 8 modify the static Pod manifest of the kind control plane (/etc/kubernetes/manifests/kube-apiserver.yaml). This is only suitable for a local lab cluster. Do not copy it to shared or production clusters. For managed clusters such as AKS, use the KMS and diagnostic settings the platform provides.

Module 0 · Warm-up

Reuse the kind cluster lab and namespace shop from hours 1–4, and first see how unsafe things currently are
Before class ≈ 10 minkind labAKS aks-lab optional
Prerequisites
  • Completed hours 1–4: the kind cluster lab (1 control plane + 2 workers), with web (nginx), api (podinfo 6.17.0), and db (postgres:17 StatefulSet) running in namespace shop, plus an existing Gateway and NetworkPolicy.
  • Lab machine: Azure VM Standard_D4s_v5 (Ubuntu 24.04, resource group rg-k8s-lab, canadacentral), or Docker Desktop on your local machine.
  • Tools: kubectl 1.37, kind v0.33.0, jq, openssl. The AKS part also needs Azure CLI 2.47+ (required for Workload ID).

4C security model: which layer this hour covers

Cloud / data center: Azure subscription, VNet, NSG, Entra ID, Key Vault, node images Cluster: API server authentication/authorization/admission, etcd encryption, audit, NetworkPolicy, tenant isolation ← main focus of M1–M4 and M6–M8 Container: securityContext, seccomp, capabilities, read-only root, image signing ← M4 · M5 Code: dependency vulnerabilities, input validation, TLS, no secrets in code ← M3 (Workload ID) · M7 A weakness in an outer layer makes the defenses in the inner layers useless. If Cloud is compromised, even the best RBAC does not help. Conversely, strong inner layers limit the blast radius when an outer layer is breached.
Figure 0-1 4C security model (Cloud / Cluster / Container / Code). Source: kubernetes.io Cloud Native Security concept page

Threat model for this hour: after the api Pod is hit by RCE, what can the attacker do?

Attack stepPossible in a default cluster?Which control in this hour blocks it
Read the mounted SA token: /var/run/secrets/kubernetes.io/serviceaccount/tokenYes (automounted by default)M3: automountServiceAccountToken: false, dedicated SA
Use the token to call the API: list Secrets, create a privileged PodDepends on RBAC. The default SA has almost no permissions, but people often bind edit to it casuallyM2: least privilege, no secrets list / create pods
Run as root, write to the root filesystem, install toolsThe official nginx image starts its master process as rootM5: runAsNonRoot, readOnlyRootFilesystem
Mount hostPath / escape to the node from a privileged containerPossible without PSAM4: PSA restricted; M6: VAP
Lateral access to db:5432, cloud metadata at 169.254.169.254Partly blocked in hour 3NetworkPolicy default deny + egress allowlist (reused in M8)
Read Secret plaintext from an etcd backup or from node diskPossible (only base64 by default)M7: EncryptionConfiguration / KMS v2
Afterward, you cannot trace who did whatkind does not enable auditing by defaultM8: Audit Policy

Step 1: Confirm the cluster and the app

kubectl config use-context kind-lab
kubectl get nodes
kubectl -n shop get deploy,sts,svc,networkpolicy
kubectl version | head -2
NAME                STATUS   ROLES           AGE   VERSION
lab-control-plane   Ready    control-plane   3d    v1.37.0
lab-worker          Ready    <none>          3d    v1.37.0
lab-worker2         Ready    <none>          3d    v1.37.0
NAME                  READY   UP-TO-DATE   AVAILABLE
deployment.apps/api   2/2     2            2
deployment.apps/web   2/2     2            2
NAME                  READY
statefulset.apps/db   1/1

Step 2: shop security baseline (warm-up)

# Which user does each Pod run as? Is the SA token automounted?
for p in $(kubectl -n shop get pod -o name); do
  echo "== $p"
  kubectl -n shop exec $p -- id 2>/dev/null || echo "(no id command)"
  kubectl -n shop get $p -o jsonpath='{.spec.serviceAccountName}{" automount="}{.spec.automountServiceAccountToken}{" runAsNonRoot="}{.spec.securityContext.runAsNonRoot}{"\n"}'
done

# Does the namespace have Pod Security labels?
kubectl get ns shop --show-labels
== pod/api-6c9f7d8b5-2xkqz
uid=100(app) gid=101(app) groups=101(app)
default automount= runAsNonRoot=
== pod/web-7d4b9c6f8-l9ptd
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),...
default automount= runAsNonRoot=
== pod/db-0
uid=0(root) gid=0(root) groups=0(root)
default automount= runAsNonRoot=
NAME   STATUS   AGE   LABELS
shop   Active   3d    kubernetes.io/metadata.name=shop

Note: the podinfo image's Dockerfile uses USER app (non-root, but a non-numeric username, which will make the runAsNonRoot check fail in M4/M5). The nginx and postgres official images start their entry processes as root (postgres drops privileges to the postgres user afterward). Use the uid values from your actual images. An empty automount= means the field is not set explicitly; by default the token is automounted.

Step 3: Play the attacker once

API_POD=$(kubectl -n shop get pod -l app=api -o jsonpath='{.items[0].metadata.name}')
kubectl -n shop exec -it $API_POD -- sh -c '
  TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)
  CA=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
  curl -s --cacert $CA -H "Authorization: Bearer $TOKEN" \
    https://kubernetes.default.svc/api/v1/namespaces/shop/secrets | head -20'
{
  "kind": "Status",
  "apiVersion": "v1",
  "status": "Failure",
  "message": "secrets is forbidden: User \"system:serviceaccount:shop:default\" cannot list resource \"secrets\" in API group \"\" in the namespace \"shop\"",
  "reason": "Forbidden",
  "code": 403
}
Reading this 403 The attacker has passed authentication (the API server knows it is system:serviceaccount:shop:default), but authorization failed. If your team ever ran kubectl create rolebinding ... --clusterrole=edit --serviceaccount=shop:default, this call would return all Secrets. The goal of this hour is to make every layer “default deny.” If the podinfo image has no curl, use wget -qO- with --header instead, or use a temporary container via kubectl debug.

Optional: prepare the AKS cluster aks-lab (the Azure parts of M3, M7, and M8)

RG=rg-k8s-lab; LOC=canadacentral; AKS=aks-lab
az group create -n $RG -l $LOC
az aks create -g $RG -n $AKS \
  --node-count 2 --node-vm-size Standard_D2s_v5 \
  --enable-oidc-issuer --enable-workload-identity \
  --enable-aad --enable-azure-rbac \
  --generate-ssh-keys
az aks get-credentials -g $RG -n $AKS
Costs, permissions, and cleanup
  • Costs (estimate; use the Azure pricing calculator as the reference): the Free tier control plane is not charged. Two Standard_D2s_v5 nodes in canadacentral cost on the order of US$0.20 per hour, plus managed disks, load balancers, and public IPs. Log Analytics is billed by ingestion volume, and audit logs can be very large. Delete everything on the day you finish.
  • Permissions: creating the cluster requires Contributor on the subscription or resource group. Assigning Key Vault roles to the managed identity in M3 requires a role that can create role assignments: Owner, User Access Administrator, or Role Based Access Control Administrator. Microsoft Learn states clearly that Contributor and Key Vault Contributor cannot create role assignments.
  • Entra integration: after --enable-aad --enable-azure-rbac, you must be granted a role such as “Azure Kubernetes Service RBAC Cluster Admin” before you can operate the cluster (covered in detail in M2).
  • Cleanup: az group delete -n rg-k8s-lab --yes --no-wait (this also deletes the VM and AKS; to keep the VM and delete only the cluster, use az aks delete -g rg-k8s-lab -n aks-lab --yes --no-wait). If Key Vault has purge protection enabled, its name stays reserved for a period after deletion.
Self-check list

Module 1 · Authentication: how the API server knows “who you are”

00:00 – 07:00 · Kubernetes has no User object. Identity comes entirely from the credentials sent with the request.
7 minAuthenticationConfiguration GA v1.34whoami GA v1.28Pod Certificates GA v1.37★★★★★
Learning goals
  • List the API server's authenticator chain: X.509 client certificates, bearer tokens (ServiceAccount JWT, OIDC JWT, webhook), anonymous access, and the rule that any single success is enough.
  • Explain how an X.509 certificate maps CN → username and O → groups. Use the CSR API to issue a certificate for a user and write it into kubeconfig.
  • Understand how the exec credential plugin in kubeconfig (AKS's kubelogin) relates to OIDC.
Prerequisites: TLS/PKI basics, JWT structure. Importance: ★★★★★ (the starting point for all 401 troubleshooting)

What: authentication is the first gate in the request chain

Every HTTPS request that reaches kube-apiserver passes through these steps in order: Authentication (who you are) → Authorization (what you can do) → Admission (whether the object is compliant or needs changes) → validate and write to etcd. In the authentication stage, the API server tries each enabled authenticator in turn, and the first one that succeeds determines the user info: username, uid, groups, extra. If all of them fail, you get 401 Unauthorized. Every authenticated user automatically belongs to the group system:authenticated.

Key point Kubernetes has no User object: kubectl get users does not exist. “User alice” is just the CN in a certificate, or a claim in an OIDC token. Deleting a user means revoking credentials. A certificate cannot be revoked on its own; you can only wait for it to expire or rotate the CA. So in production, use OIDC (Entra ID) for people, and keep certificates only for break-glass access. ServiceAccount is the API object (M3).

Why: why there are so many authentication methods

AuthenticatorCredentialTypical userIdentity mappingProduction recommendation
X.509 client certificateCertificate signed by the cluster CA (--client-ca-file)kubeadm admins, kubelet, control-plane componentsCN=username, O=group (multiple allowed)Only for components and emergency accounts. Cannot be revoked, so use a short validity period
ServiceAccount tokenJWT issued by the API server (bound, projected, with an expiry)Workloads inside Pods, CIsystem:serviceaccount:<ns>:<name>, groups system:serviceaccounts and system:serviceaccounts:<ns>Use short-lived tokens from TokenRequest. Since v1.24, long-lived Secret tokens are no longer generated automatically
OIDC (JWT authenticator)ID token issued by an external IdPPeople (Entra ID, Okta, Keycloak)Mapped from claims: --oidc-username-claim or AuthenticationConfiguration.jwt.claimMappings (CEL supported)Preferred for human users: centrally managed, MFA, access ends when the person leaves
Webhook tokenOpaque token, checked by an external service through TokenReviewEarly AKS AAD, in-house systemsReturned by a webhookUse with caution: if the webhook is down, nobody can log in
AnonymousNo credentialsHealth checkssystem:anonymous / group system:unauthenticatedVia AuthenticationConfiguration.anonymous.conditions, allow only /livez, /readyz, and /healthz (v1.34 GA)

How: structured authentication configuration (v1.34 GA)

The traditional OIDC setup is a set of --oidc-* startup flags, and it can configure only one issuer. --authentication-config points to an apiserver.config.k8s.io/v1 AuthenticationConfiguration file. It can configure multiple JWT issuers, map usernames and groups with CEL expressions, and set claim validation rules. Changes to the file take effect without restarting the API server (dynamic reload). It is mutually exclusive with the --oidc-* flags. If anonymous is configured in the file, you can no longer use --anonymous-auth.

When: which identity to choose

  • People → OIDC (AKS: Microsoft Entra integration + kubelogin). One identity per person; groups come from the IdP.
  • Workloads inside the cluster → ServiceAccount (M3).
  • CI outside the cluster → prefer OIDC federation (GitHub Actions OIDC → Entra → AKS), then short-lived kubectl create token. Avoid long-lived Secret tokens.
  • Control-plane components and emergency accounts → X.509, with a short validity period, stored in a vault.

New in v1.37 GA: Pod Certificates and ClusterTrustBundle (brief overview)

In v1.37, Pod Certificates (KEP-4317) and ClusterTrustBundles (KEP-3257) both reach GA, providing “native X.509 workload identity” for Pods. A Pod declares a podCertificate in a projected volume and sets a signerName. The kubelet generates the Pod's private key and submits a PodCertificateRequest. The controller for that signer issues the certificate. The kubelet writes the private key and certificate chain into the projected volume and rotates them automatically before expiry. A Pod can also mount trust anchors (CA bundles) through a clusterTrustBundle projection source, for mutual TLS verification. This suits service-to-service mTLS and certificate authentication to external systems. Note: Kubernetes provides only the framework; you must deploy the signer controller yourself (for example, an implementation from a project such as cert-manager). Illustration (fields follow the official docs):

volumes:
- name: identity
  projected:
    sources:
    - podCertificate:
        signerName: example.com/workload-signer
        keyType: ED25519
        credentialBundlePath: credentialbundle.pem
    - clusterTrustBundle:
        signerName: example.com/workload-signer
        labelSelector: {}
        path: trust-bundle.pem

Comparison with similar technologies

Comparison itemKubernetesAzure (ARM)Linux
User directoryNone; provided by an external IdP or certificatesEntra ID/etc/passwd, LDAP
Workload identityServiceAccount JWTManaged identityService account uid
Failure response401 Unauthorized401 / AADSTS error codesPermission denied (PAM)
Common misconceptions ① “I can run kubectl get pods, so authentication must be fine.” This can also mean an anonymous user was authorized, which is extremely dangerous. Confirm with kubectl auth whoami. ② “Removing a user from an Entra group takes effect immediately.” An ID token already issued stays valid until it expires (usually about 1 hour), and so does a token cached by kubelogin. ③ “A certificate can be revoked before it expires.” Kubernetes does not check CRL or OCSP.

Architecture diagram: authenticator chain

kubectl (alice)client cert Pod (api)Bearer SA JWT kubelogin (bob)Bearer Entra ID token kube-apiserver: Authentication ① x509: verify the chain to client-ca → CN / O ② ServiceAccount JWT: signature + bound object still exists ③ JWT (OIDC): issuer / aud / expiry / CEL mapping ④ webhook TokenReview (if configured) ⑤ anonymous (only /livez, /readyz, /healthz) Any success → UserInfo; all fail → 401 UserInfo username: alice groups: [dev-team, system:authenticated] → passed to Authorization
Figure 1-1 Authenticator chain: different credentials produce the same UserInfo, and RBAC later looks only at the UserInfo

Flow diagram: issuing a user certificate through the CSR API

openssl genrsaPrivate key stays local openssl req/CN=alice/O=dev-team CSR objectsigner kube-apiserver-client approveRequires certificatesigningrequests/approval kube-controller-managerSigned with the cluster CA kubeconfigcert + key
Figure 1-2 The private key never leaves the user's machine. The cluster sees only the CSR (public key + subject), which the signer in controller-manager signs

Step-by-step animation: a request passes through authn → authz → admission → etcd

Choose a scenario, then click “Play” or “Next step.” Each step highlights the current component, and the terminal shows the real HTTP request, audit fields, or error message.

Clientkubectl / Pod TLS :6443Handshake AuthnWho are you → 401 AuthzNode,RBAC → 403 MutatingMAP / webhook ValidatingPSA / VAP / webhook etcdPersist + watch
After choosing a scenario, click “Play.”
$ # waiting for a scenario to be chosen

Core commands and flags

CommandPurposeKey flags / notes
kubectl auth whoamiShows what the API server thinks you are (SelfSubjectReview, v1.28 GA)-o yaml shows the extra fields. Use with --as to verify a simulated identity
kubectl config view --minifyShows the credential type used by the current context--raw is needed to show the certificate contents
kubectl get csr / certificate approve|denyManage certificate signing requestssignerName: kubernetes.io/kube-apiserver-client, expirationSeconds
kubectl config set-credentialsWrite into user credentials--client-certificate --client-key --embed-certs=true; or --exec-command
kubectl -v=8 get podsView the actual HTTP requests and response codesWhen troubleshooting 401/403, check Response Status
kubelogin convert-kubeconfig -l azurecliAKS: switch the kubeconfig to exec plugin mode-l: devicecode / azurecli / spn / msi / workloadidentity
kubectl auth whoami
kubectl auth whoami --as=system:serviceaccount:shop:ci -o yaml
ATTRIBUTE                                           VALUE
Username                                            kubernetes-admin
Groups                                              [kubeadm:cluster-admins system:authenticated]
---
apiVersion: authentication.k8s.io/v1
kind: SelfSubjectReview
status:
  userInfo:
    groups:
    - system:serviceaccounts
    - system:serviceaccounts:shop
    - system:authenticated
    username: system:serviceaccount:shop:ci

How to verify: in kind, the admin user is kubernetes-admin, in group kubeadm:cluster-admins. Since kubeadm v1.29 it no longer belongs directly to system:masters, and it can be revoked through RBAC. Common error: older kubectl versions lack this subcommand, so upgrade kubectl. Production use: debugging OIDC mapping. Confirm that the Entra groups appear correctly in Groups.

Structured authentication configuration example (OIDC for a self-managed cluster, v1.34 GA)

apiVersion: apiserver.config.k8s.io/v1
kind: AuthenticationConfiguration
jwt:
- issuer:
    url: https://login.microsoftonline.com/<TENANT_ID>/v2.0
    audiences:
    - <APP_CLIENT_ID>
    audienceMatchPolicy: MatchAny
  claimValidationRules:
  - expression: 'claims.tid == "<TENANT_ID>"'
    message: "token must come from our tenant"
  claimMappings:
    username:
      expression: '"oidc:" + claims.preferred_username'
    groups:
      expression: 'claims.groups.map(g, "oidc:" + g)'
anonymous:
  enabled: true
  conditions:
  - path: /livez
  - path: /readyz
  - path: /healthz

kube-apiserver flag: --authentication-config=/etc/kubernetes/auth/authn-config.yaml (cannot be used together with --oidc-*). username.claim and username.expression are mutually exclusive. When using claim, prefix must be set explicitly (an empty string is allowed). Adding a prefix to usernames (such as oidc:) stops external users from impersonating built-in identities that start with system:. AKS manages the API server, so you cannot change these settings. Use AKS's Entra integration instead.

exec credential plugin (AKS's kubelogin)

users:
- name: clusterUser_rg-k8s-lab_aks-lab
  user:
    exec:
      apiVersion: client.authentication.k8s.io/v1beta1
      command: kubelogin
      args:
      - get-token
      - --login
      - azurecli
      - --server-id
      - 6dae42f8-4368-4678-94ff-3960e28e3630
      interactiveMode: IfAvailable
      provideClusterInfo: false

Each time kubectl needs credentials, it runs kubelogin get-token. The plugin writes the Entra token to stdout as an ExecCredential JSON, and kubectl sends it as a bearer token. 6dae42f8-… is the well-known ID of the AKS Entra server application. The plugin apiVersion supports client.authentication.k8s.io/v1 and v1beta1. With v1, interactiveMode is required. Common error: exec: executable kubelogin not found → run az aks install-cli or install kubelogin from GitHub.

Lab 1: Issue a certificate for developer alice through the CSR API (about 5 min, kind lab)

Generate a private key and CSR (CN=username, O=group):
mkdir -p ~/k8s-h5/m1 && cd ~/k8s-h5/m1
openssl genrsa -out alice.key 2048
openssl req -new -key alice.key -out alice.csr -subj "/CN=alice/O=dev-team"
openssl req -in alice.csr -noout -subject
subject=CN = alice, O = dev-team
Submit a CertificateSigningRequest (valid for 24 hours):
cat <<EOF | kubectl apply -f -
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
  name: alice
spec:
  request: $(base64 -w0 < alice.csr)
  signerName: kubernetes.io/kube-apiserver-client
  expirationSeconds: 86400
  usages:
  - client auth
EOF
kubectl get csr alice
NAME    AGE   SIGNERNAME                            REQUESTOR          REQUESTEDDURATION   CONDITION
alice   3s    kubernetes.io/kube-apiserver-client   kubernetes-admin   24h                 Pending
Approve and retrieve the certificate:
kubectl certificate approve alice
kubectl get csr alice -o jsonpath='{.status.certificate}' | base64 -d > alice.crt
openssl x509 -in alice.crt -noout -subject -issuer -enddate
certificatesigningrequest.certificates.k8s.io/alice approved
subject=CN = alice, O = dev-team
issuer=CN = kubernetes
notAfter=Nov 16 10:12:03 2026 GMT
Write into kubeconfig and verify identity:
kubectl config set-credentials alice --client-certificate=alice.crt --client-key=alice.key --embed-certs=true
kubectl config set-context alice@lab --cluster=kind-lab --user=alice --namespace=shop
kubectl --context alice@lab auth whoami
kubectl --context alice@lab get pods
ATTRIBUTE   VALUE
Username    alice
Groups      [dev-team system:authenticated]
Error from server (Forbidden): pods is forbidden: User "alice" cannot list resource "pods" in API group "" in the namespace "shop"

Verification: authentication succeeds (whoami works) and authorization fails (403). This is the problem M2 solves. Note: alice's identity comes entirely from the certificate. No “User” object was created.

Compare with a 401: access with a forged token:
APISERVER=$(kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}')
curl -sk -H "Authorization: Bearer not-a-real-token" $APISERVER/api/v1/namespaces/shop/pods | jq '{code,reason,message}'
{
  "code": 401,
  "reason": "Unauthorized",
  "message": "Unauthorized"
}
Cleanup (keep alice for use in M2): you can delete the CSR object, and the certificate remains valid: kubectl delete csr alice. At the end of the course, delete the context: kubectl config delete-context alice@lab; kubectl config delete-user alice.
Risk Anyone who can approve any kube-apiserver-client CSR can issue themselves a certificate with O=system:masters, which is equivalent to cluster admin, because the system:masters group bypasses RBAC. In production, tightly control the certificatesigningrequests/approval permission and the approve permission on signers.

Case 1: An employee leaves, but their certificate is still valid for one more year

Problem: an admin.conf generated early with kubeadm was copied to several engineers, and one of them has since left. Certificates cannot be revoked. Approach: ① immediately delete all RoleBindings for the CN/O of that certificate (this does not help if O=system:masters; in that case you can only rotate the CA); ② migrate to OIDC (AKS: Entra integration + --disable-local-accounts); ③ set expirationSeconds to a few hours for newly issued emergency certificates. Limitation: rotating the cluster CA affects all kubelets and components and needs a maintenance window (AKS: az aks rotate-certs causes roughly 30 minutes of downtime; check the official docs for current details).

Case 2: AKS with local accounts disabled, only Entra login allowed

az aks update -g rg-k8s-lab -n aks-lab --disable-local-accounts
az aks get-credentials -g rg-k8s-lab -n aks-lab --overwrite-existing
kubelogin convert-kubeconfig -l azurecli
kubectl auth whoami

Effect: az aks get-credentials --admin no longer works. All access carries an Entra identity and goes into the audit log. Limitation: you need a contingency plan for Entra outages (keep an emergency Entra group protected by PIM). CI must switch to Workload Identity or a service principal with kubelogin.

Case 3: A cluster after two IdPs are merged

Problem: two companies merged, and the self-managed cluster must accept two OIDC issuers at the same time. Approach: configure two jwt entries in AuthenticationConfiguration, each with its own prefix (corp-a: / corp-b:), and bind RBAC to the prefixed groups. Limitation: managed clusters (AKS, EKS, GKE) generally do not expose this file, and each issuer's discovery endpoint must be reachable from the API server.

Common errors and fixes

error: You must be logged in to the server (Unauthorized)

Cause: authentication failure (401). Possible causes: certificate expired or not signed by the cluster CA, token expired, OIDC audience mismatch, or a stale kubelogin cache.

kubectl -v=8 get ns 2>&1 | grep -E "Response Status|Authorization"
kubectl config view --minify --raw -o jsonpath='{.users[0].user.client-certificate-data}' | base64 -d | openssl x509 -noout -enddate -issuer
kubelogin remove-tokens   # AKS: clear the cache and log in again

On a self-managed cluster, check the kube-apiserver logs for Unable to authenticate the request and the reason (such as x509: certificate has expired or oidc: verify token: ... audience).

x509: certificate signed by unknown authority

Cause: the client does not trust the API server's serving certificate. The certificate-authority-data in kubeconfig is wrong, or the CA changed after the cluster was rebuilt. This is unrelated to client certificate authentication.

kind get kubeconfig --name lab > /tmp/lab.kubeconfig   # re-export
kubectl --kubeconfig /tmp/lab.kubeconfig get nodes

Do not use --insecure-skip-tls-verify to hide the problem.

CSR stays Pending, or Approved but has no status.certificate

Cause: Pending means nobody has approved it. Approved but no certificate means the signer did not sign it: the signerName is wrong, or usages does not match what the signer requires (for example, kube-apiserver-client does not accept server auth), or the controller-manager has no signing key configured.

kubectl get csr alice -o yaml | grep -A5 conditions
kubectl -n kube-system logs -l component=kube-controller-manager | grep -i csr | tail
getting credentials: exec: executable kubelogin not found

Cause: the kubeconfig uses an exec plugin, but the plugin is not installed on this machine or is not on PATH. This is common in CI containers.

az aks install-cli          # installs both kubectl and kubelogin
which kubelogin && kubelogin --version
Command-line exercise
1. Issue a client certificate for user bob (group qa) that is valid for only 2 hours. Write out the key fields of the CSR.
spec:
  request: <base64 of bob.csr with /CN=bob/O=qa>
  signerName: kubernetes.io/kube-apiserver-client
  expirationSeconds: 7200
  usages: ["client auth"]

Then run kubectl certificate approve bob and retrieve .status.certificate.

2. Without switching context, confirm the username and groups that the API server sees for the ServiceAccount shop:api.
kubectl auth whoami --as=system:serviceaccount:shop:api

Note: using --as requires that you have the impersonate permission yourself.

Scenario analysis
A colleague says: “I just removed an Entra account from the aks-admins group, but they can still run kubectl delete 30 minutes later. Is Azure RBAC broken?”

Not necessarily. An Entra access token that was already issued stays valid until it expires (usually 60–90 minutes), and kubelogin also caches tokens. Changes to Azure RBAC role assignments can also take several minutes to propagate. Handling: waiting for the token to expire is slow, and asking the user to run kubelogin remove-tokens locally is not enough to revoke access, since an attacker will not cooperate. In an emergency, revoke that user's sessions and refresh tokens in Entra, and check for K8s RoleBindings bound directly to that user (by UPN or objectId). Long term, use PIM so that admin permissions are activated on demand and only for short periods.

Verified teaching video

▶
Kubernetes Security Best Practices you need to know | THE Guide for securing your K8s cluster! — TechWorld with Nana
English · duration and publication date follow the YouTube page · Purpose: a big-picture review of security topics such as authentication, RBAC, Secrets, and etcd. It was recorded before v1.37, so use this hour for version details.

I could not find a video specifically about “X.509 / CSR / AuthenticationConfiguration” whose title and channel I could verify, so only the one above is listed.

Official documentation

Video storyboard script (for a video generation tool)

This course file cannot generate video or MP3 directly, so it provides a storyboard and narration script.

Shot 1 · 0:00–0:20
Visual: the terminal runs kubectl get users and returns an error. Subtitle: “Kubernetes has no user objects.”
Narration: In Kubernetes, you cannot find any “user” object. The API server looks only at the credentials you bring.
Shot 2 · 0:20–1:00
Visual: Figure 1-1 animation. Three kinds of credentials enter the authenticator chain and converge into a UserInfo card.
Narration: A client certificate, a ServiceAccount token, or an OIDC token: whichever authenticator succeeds gives you a username and groups. If all of them fail, you get a 401.
Shot 3 · 1:00–1:50
Visual: openssl generates a CSR, with the subject highlighted as CN=alice, O=dev-team. Then kubectl certificate approve.
Narration: The certificate's CN is the username, and O is the group. The private key always stays local. The cluster only signs the certificate.
Shot 4 · 1:50–2:30
Visual: whoami succeeds, get pods returns 403, and a red box labels it “Authentication passed · Authorization failed.”
Narration: 401 means “I don't know you.” 403 means “I know you, but you don't have permission.” Next, we use RBAC to grant authorization.
Or score ≥ 70% on the quiz

Module 2 · Authorization (RBAC): who can do what to which resources

07:00 – 15:00 · Default deny, additive only. Writing correct RBAC is harder than writing more RBAC.
8 minrbac.authorization.k8s.io/v1 GA★★★★★
Learning goals
  • Tell apart the scope combinations of Role, ClusterRole, RoleBinding, and ClusterRoleBinding. Understand verbs, resources, subresources (pods/log, pods/exec), and resourceNames.
  • Recognize permissions that look harmless but effectively amount to cluster admin.
  • Use kubectl auth can-i --list --as fluently to verify permissions, and use kubectl auth reconcile to manage RBAC manifests.
  • Understand the two AKS modes: Kubernetes RBAC with Entra groups, or Azure RBAC for Kubernetes.
Prerequisite: UserInfo from M1. Importance: ★★★★★

What: the four RBAC objects

ObjectScopeContentsTypical use
RoleNamespaceA set of rules (apiGroups × resources × verbs [× resourceNames])The team's permissions in shop
ClusterRoleClusterSame as above, and can also describe cluster-level resources (nodes, namespaces, PVs) and non-resource URLs (/healthz)Reusable permission templates, such as view, edit, and admin
RoleBindingNamespaceGrants a Role or ClusterRole to a subject, effective only within this namespace“Bind the ClusterRole view to dev-team in shop”
ClusterRoleBindingClusterGrants a ClusterRole to a subject, effective across all namespaces and cluster-level resourcesPlatform team, monitoring systems

Subjects come in three types: User (a string, from authentication), Group (a string), and ServiceAccount (an API object inside a namespace). RBAC has only allow rules, no deny rules. The permissions from multiple bindings are combined as a union. The authorizer is evaluated in the order set by --authorization-mode (default Node,RBAC for kubeadm and kind), and any allow lets the request through.

Why: least privilege and “permission equals capability”

The RBAC unit is the “API verb,” but the security impact must be judged by “capability.” The permissions below look narrow on paper but can be escalated to higher privileges:

PermissionWhy it is dangerous
get/list/watch secretslist and watch return the full contents of Secrets, not just their names. With an SA token Secret or a database password, an attacker can move laterally.
create pods (and create/patch deployments, jobs, cronjobs, statefulsets, daemonsets)A Pod can mount any Secret in its namespace and run as any ServiceAccount, which is equivalent to reading all Secrets and getting all SA permissions. Without PSA, one can also create a privileged Pod and escape to the node.
pods/exec, pods/attach, pods/ephemeralcontainersEnter any container and read its environment variables, mounted tokens, and Secret files.
escalate, bind (roles/clusterroles)RBAC by default forbids creating roles or bindings with more permissions than you have. These two verbs bypass that protection.
impersonate (users/groups/serviceaccounts)Impersonate anyone with --as=system:admin --as-group=system:masters
nodes/proxyDirectly access the kubelet API and run commands in any Pod on the node, bypassing the pods/exec audit at the API server layer
create serviceaccounts/tokenIssue tokens for any SA
update/patch admission webhook configurations, certificatesigningrequests/approvalDisable security policies, or issue yourself a system:masters certificate
* wildcardIncludes resources and verbs added in the future

How: how a rule is matched

Request attributes = user/groups + verb (get, list, watch, create, update, patch, delete, deletecollection, plus use, bind, escalate, impersonate, approve) + apiGroup + resource[/subresource] + namespace + name. In a rule, resourceNames can only constrain verbs that act “by name” (get, update, patch, delete). It cannot restrict list, watch, or create by name, because at create time the name is not yet in the URL. The core group is written as "". Deployments are in the apps group.

Default user-facing ClusterRoles

ClusterRoleCapabilityNotes
viewRead most objectsCannot read Secrets, nor read Roles or RoleBindings
editRead and write most objectsCan read and write Secrets, and can run Pods as any SA in the namespace. Cannot change Roles or RoleBindings.
adminNamespace admin: can create Roles and RoleBindings within the namespaceCannot modify ResourceQuota or the Namespace itself
cluster-adminEverythingWhen bound with a RoleBinding, it grants full permissions only within that namespace

These roles are aggregated ClusterRoles. A ClusterRole with the label rbac.authorization.k8s.io/aggregate-to-view: "true" (or aggregate-to-edit / aggregate-to-admin) is merged in automatically by a controller. Operators that install CRDs often use this so that view and edit users can also access the new resources.

When: choosing Role or ClusterRole

  • If the permission is used in only one namespace → Role + RoleBinding.
  • If the same set of permissions must be reused across several namespaces → ClusterRole + a RoleBinding in each namespace.
  • If you truly need access across all namespaces or to cluster-level resources → ClusterRoleBinding (use as few as possible).

Comparison with similar technologies

Kubernetes RBACAzure RBAC for Kubernetes (AKS)AWS EKS Access Entries
Where policy is storedIn-cluster API objectsARM role assignments (scope can go down to …/namespaces/shop)EKS API + access policies
Deny rulesNoneSupports deny assignments (platform level)None
SubjectsUser, Group, and SA stringsEntra users, groups, service principalsIAM principals
AuditingK8s audit logAzure activity log + K8s auditCloudTrail + audit
Common misconceptions ① “If a RoleBinding binds a ClusterRole, it gets cluster-wide permissions.” Wrong: a RoleBinding always takes effect only within its own namespace. ② “resourceNames can restrict list.” It cannot. ③ “I only gave developers create deployments and not secrets, so they cannot see passwords.” They can create a Pod that mounts that Secret and then read it from the logs. A real boundary needs PSA, VAP, and GitOps working together (M4, M6).

Architecture diagram: relationships and scopes between objects

namespace: shop Group dev-teamFrom the certificate O / OIDC SA shop:ciAPI object RoleBindingdev-team-developer RoleBindingci-deployer Roleshop-developer Roleci-deployer A RoleBinding can also reference a ClusterRole ClusterRole view / edit / adminAggregation: aggregate-to-view label ClusterRoleBindingAll namespaces + cluster resources(nodes, namespaces, PVs)
Figure 2-1 The scope of a RoleBinding depends only on the namespace it lives in, not on whether it references a Role or a ClusterRole

Flow diagram: RBAC authorization decision

Request attributesuser/groups verbresource ns name Node authorizerOnly handles system:node:*Otherwise NoOpinion Collect bindingsCRBs (all) + RBs in this namespaceSubject matches user / group / SA Match rules one by oneapiGroup·resource·verbresourceNames Match → AllowReason written to audit No match at all403 Forbidden
Figure 2-2 RBAC has no deny: if any rule in any binding allows the request, it goes through

Interactive: RBAC decision simulator

The simulator includes bindings that match the lab (see the table below). Choose a subject, verb, resource, and namespace to see which binding matches, or why the request is denied. The decision logic is the same as the RBAC authorizer: collect ClusterRoleBindings and the RoleBindings in the target namespace → match subjects → match rules one by one.








After choosing, click “Evaluate.”
$ kubectl auth can-i ...
View the bindings in the simulator

Core commands and flags

CommandPurposeKey flags
kubectl auth can-i VERB RESOURCECheck a single permission (SelfSubjectAccessReview / SubjectAccessReview)-n, --as, --as-group, --subresource, RESOURCE/NAME
kubectl auth can-i --listList all of a subject's permissions within a namespace--as=system:serviceaccount:NS:SA
kubectl create role / rolebindingGenerate RBAC imperatively (suited to --dry-run=client -o yaml to produce manifests)--verb --resource --resource-name; --clusterrole --group --serviceaccount
kubectl auth reconcile -fApply RBAC manifests in a “merge” fashion, handling issues such as the immutable roleRef correctly--remove-extra-permissions, --remove-extra-subjects, --dry-run=client
kubectl get rolebindings,clusterrolebindings -A -o wideInventory bindingsFilter subjects with jq
kubectl who-can (plugin kubectl-who-can), rbac-toolReverse lookup of “who can read secrets”, and RBAC visualizationInstall via krew (third-party tool; follow the project's docs)
# 1) Simulate alice with --as + --as-group (the O in the certificate is not picked up automatically, so the group must be specified explicitly)
kubectl auth can-i --list -n shop --as=alice --as-group=dev-team

# 2) The CI check the exercise asks for
kubectl auth can-i create deployments --as=system:serviceaccount:shop:ci -n shop

# 3) Subresources and names
kubectl auth can-i get pods --subresource=log --as=alice --as-group=dev-team -n shop
kubectl auth can-i patch deployments/api --as=system:serviceaccount:shop:ci -n shop
Resources                                       Non-Resource URLs   Resource Names   Verbs
selfsubjectreviews.authentication.k8s.io        []                  []               [create]
selfsubjectaccessreviews.authorization.k8s.io   []                  []               [create]
deployments.apps                                []                  []               [get list watch create update patch]
pods/log                                        []                  []               [get list watch]
pods                                            []                  []               [get list watch]
...
no
yes
yes

Common error: using only --as=alice without --as-group gives a different result from the real alice. Production use: run can-i in CI as an RBAC regression test. Fail the build if a permission that should be no turns into yes.

Aggregated ClusterRole: let view users read CRDs too

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: gateway-routes-view
  labels:
    rbac.authorization.k8s.io/aggregate-to-view: "true"
    rbac.authorization.k8s.io/aggregate-to-edit: "true"
rules:
- apiGroups: ["gateway.networking.k8s.io"]
  resources: ["httproutes", "gateways"]
  verbs: ["get", "list", "watch"]
kubectl auth reconcile -f gateway-routes-view.yaml
kubectl get clusterrole view -o yaml | grep -A3 httproutes

AKS: Azure RBAC for Kubernetes bound to Entra groups

# Option A: Azure RBAC (--enable-azure-rbac at cluster creation); the scope can be as narrow as a namespace
AKS_ID=$(az aks show -g rg-k8s-lab -n aks-lab --query id -o tsv)
DEV_GROUP_ID=$(az ad group show -g "shop-developers" --query id -o tsv)
az role assignment create --role "Azure Kubernetes Service RBAC Reader" \
  --assignee-object-id $DEV_GROUP_ID --assignee-principal-type Group \
  --scope $AKS_ID/namespaces/shop

# Option B: Kubernetes RBAC, with the subject set to the objectId of the Entra group
kubectl create rolebinding shop-dev-entra -n shop --clusterrole=view --group=$DEV_GROUP_ID

Built-in roles: Azure Kubernetes Service RBAC Reader / Writer / Admin / Cluster Admin (Reader cannot view Secrets). Authorization order: once Azure RBAC is enabled, a request first passes the Azure authorization webhook and then Kubernetes RBAC, and any allow lets it through. Role assignments can take several minutes to propagate.

Lab 2: developer read-only + deploy, CI with least privilege (about 6 min, kind lab)

Write the RBAC manifests:
mkdir -p ~/k8s-h5/m2 && cd ~/k8s-h5/m2
cat > rbac-shop.yaml <<'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata: {name: shop-developer, namespace: shop}
rules:
- apiGroups: [""]
  resources: ["pods", "pods/log", "services", "configmaps", "events", "endpoints"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["apps"]
  resources: ["deployments", "replicasets", "statefulsets"]
  verbs: ["get", "list", "watch"]
- apiGroups: ["apps"]
  resources: ["deployments"]
  verbs: ["create", "update", "patch"]
- apiGroups: ["apps"]
  resources: ["deployments/scale"]
  verbs: ["update", "patch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata: {name: dev-team-developer, namespace: shop}
subjects:
- kind: Group
  name: dev-team
  apiGroup: rbac.authorization.k8s.io
roleRef: {kind: Role, name: shop-developer, apiGroup: rbac.authorization.k8s.io}
---
apiVersion: v1
kind: ServiceAccount
metadata: {name: ci, namespace: shop}
automountServiceAccountToken: false
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata: {name: ci-deployer, namespace: shop}
rules:
- apiGroups: ["apps"]
  resources: ["deployments"]
  resourceNames: ["api", "web"]
  verbs: ["get", "patch", "update"]
- apiGroups: ["apps"]
  resources: ["deployments", "replicasets"]
  verbs: ["list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata: {name: ci-deployer, namespace: shop}
subjects:
- kind: ServiceAccount
  name: ci
  namespace: shop
roleRef: {kind: Role, name: ci-deployer, apiGroup: rbac.authorization.k8s.io}
EOF
kubectl auth reconcile -f rbac-shop.yaml
role.rbac.authorization.k8s.io/shop-developer reconciled
rolebinding.rbac.authorization.k8s.io/dev-team-developer reconciled
role.rbac.authorization.k8s.io/ci-deployer reconciled
rolebinding.rbac.authorization.k8s.io/ci-deployer reconciled

auth reconcile handles only RBAC objects. The ServiceAccount must be applied separately with kubectl apply -f rbac-shop.yaml. Applying RBAC objects repeatedly is harmless.

kubectl apply -f rbac-shop.yaml
Verify with the real alice certificate (the context created in M1):
kubectl --context alice@lab get pods
kubectl --context alice@lab logs deploy/api --tail=2
kubectl --context alice@lab get secrets
kubectl --context alice@lab exec deploy/api -- id
NAME                   READY   STATUS    RESTARTS   AGE
api-6c9f7d8b5-2xkqz    1/1     Running   0          2d
...
{"level":"info","ts":"...","msg":"Starting podinfo","version":"6.17.0",...}
Error from server (Forbidden): secrets is forbidden: User "alice" cannot list resource "secrets" in API group "" in the namespace "shop"
Error from server (Forbidden): pods "api-6c9f7d8b5-2xkqz" is forbidden: User "alice" cannot create resource "pods/exec" in API group "" in the namespace "shop"
Verify CI's least privilege:
for check in "create deployments" "patch deployments/api" "patch deployments/db" "get secrets" "create pods" "list replicasets"; do
  printf "%-28s %s\n" "$check" "$(kubectl auth can-i $check --as=system:serviceaccount:shop:ci -n shop)"
done
create deployments           no
patch deployments/api        yes
patch deployments/db         no
get secrets                  no
create pods                  no
list replicasets             yes
Actually run a release as the CI identity (short-lived token, covered in detail in M3):
CI_TOKEN=$(kubectl create token ci -n shop --duration=10m)
kubectl --token=$CI_TOKEN -n shop set image deploy/api api=ghcr.io/stefanprodan/podinfo:6.17.0
kubectl --token=$CI_TOKEN -n shop rollout status deploy/api --timeout=60s
kubectl --token=$CI_TOKEN -n shop delete deploy/api
deployment.apps/api image updated   (if the image has not changed, it shows unchanged or no output)
deployment "api" successfully rolled out
Error from server (Forbidden): deployments.apps "api" is forbidden: User "system:serviceaccount:shop:ci" cannot delete resource "deployments" in API group "apps" in the namespace "shop"

Note that api= in set image is the container name. If you used a different container name in earlier hours, first confirm it with kubectl -n shop get deploy api -o jsonpath='{.spec.template.spec.containers[*].name}'.

Find out “who can read Secrets” (without installing a plugin):
kubectl get rolebindings,clusterrolebindings -A -o json | jq -r '
  .items[] | select(.roleRef.name|test("^(cluster-admin|admin|edit)$"))
  | "\(.kind)/\(.metadata.namespace // "-")/\(.metadata.name) -> \(.roleRef.name): \([.subjects[]?|.kind+":"+.name]|join(","))"'
Cleanup: the RBAC from this module is still used in the Capstone lab, so keep it. To delete it: kubectl delete -f rbac-shop.yaml.
Think about it alice has create deployments. She can deploy a Deployment that mounts the db-credentials Secret and then print its contents with kubectl logs, so the “cannot read Secrets” rule in RBAC is bypassed. PSA (M4) cannot stop Secret mounts. You need M6's VAP (for example, to forbid developers from creating Pod templates that mount Secret volumes or use envFrom secretRef), or have only the GitOps controller deploy.

Case 1: the monitoring system's ClusterRoleBinding becomes a backdoor

Problem: a logging agent's Helm chart creates by default a ClusterRole that includes secrets: [get, list, watch] (to read TLS certificates) and binds it to the DaemonSet's SA. Any compromised Pod on a node that can obtain that agent's token (via hostPath or a same-node escape) can read every Secret in the cluster. Approach: audit the third-party chart with kubectl auth can-i --list --as=system:serviceaccount:logging:agent, and change Secret access to a Role limited to a specific namespace with resourceNames. Limitation: if the agent needs list, resourceNames cannot constrain it, and you can only narrow the namespace scope.

Case 2: a read-only GitOps cluster

Approach: human users get only view (without Secrets) + pods/log. All write operations are done by the SA of Argo CD or Flux. For emergency write access, activate the “shop-breakglass” group through Entra PIM. The group is bound to admin and valid for 1 hour. Limitation: make sure the GitOps controller's own SA permissions are controlled (it usually needs close to cluster-admin), and enable branch protection on its repository.

Case 3: namespace authorization with Azure RBAC on AKS

az role assignment create --role "Azure Kubernetes Service RBAC Writer" \
  --assignee-object-id $DEV_GROUP_ID --assignee-principal-type Group \
  --scope $AKS_ID/namespaces/shop

Effect: permission management is centralized in Azure, with regular reviews through Access Reviews. Limitation: the built-in Azure RBAC roles are coarse-grained. When you need subresource-level control (such as forbidding pods/exec), you can create an Azure custom role (DataActions) or layer it on top of Kubernetes RBAC.

Common errors and fixes

Error from server (Forbidden): pods is forbidden: User "alice" cannot list resource "pods" in API group "" in the namespace "shop"

How to read it: user = alice, verb = list, resource = pods, group = core group, namespace = shop. Check each item:

kubectl auth can-i list pods -n shop --as=alice --as-group=dev-team
kubectl get rolebinding -n shop -o wide | grep -E "alice|dev-team"
kubectl describe role shop-developer -n shop

Common causes: group name case mismatch (RBAC is case-sensitive), RoleBinding created in the wrong namespace, Deployment written with the core group "" instead of apps, or pods granted without pods/log.

roles.rbac.authorization.k8s.io "x" is forbidden: user "bob" is attempting to grant RBAC permissions not currently held

Cause: RBAC's anti-escalation mechanism. You can create or bind only permissions you already hold, unless you have escalate (to create roles) or bind (to bind roles).

Fix: have a higher-privileged admin create it, or give the namespace admin the ClusterRole admin (which can grant permissions within the admin scope inside that namespace). Do not grant escalate just to save effort.

The RoleBinding "x" is invalid: roleRef: Invalid value: ... cannot change roleRef

Cause: roleRef cannot be changed after creation. Fix: delete and recreate it, or use kubectl auth reconcile -f, which deletes and recreates it automatically.

AKS: Error from server (Forbidden): ... User "xxxx@contoso.com" cannot list resource "pods" ... : User does not have access to the resource in Azure. Update role assignment to allow access.

Cause: Azure RBAC is enabled, but this Entra identity has no AKS RBAC role at the cluster or namespace scope, or the assignment has not propagated yet.

az role assignment list --scope $AKS_ID --include-inherited -o table
az role assignment list --scope $AKS_ID/namespaces/shop -o table
Command-line exercise
1. Use a single command to generate a Role YAML that allows only get and list on pods and pods/log (do not create it yet).
kubectl create role log-reader -n shop --verb=get,list --resource=pods,pods/log --dry-run=client -o yaml
2. Check whether the default SA in kube-system can list Secrets in all namespaces.
kubectl auth can-i list secrets -A --as=system:serviceaccount:kube-system:default
Scenario analysis question
Security scan report: SA shop:reporter has only get, list permissions on pods and nodes/proxy, and the developers say it is “read-only.” Is that conclusion correct?

No. nodes/proxy grants access to the kubelet API. The kubelet accepts a GET request over WebSocket to call endpoints such as /exec and /run. That means you can run commands in any Pod on that node, and these actions do not appear as pods/exec in the API server audit log. Remove nodes/proxy. If you need metrics, use nodes/metrics or nodes/stats instead. Kubelet fine-grained authorization is GA as of v1.36, so you can grant only the subresources you need.

Verified teaching videos

▶
Kubernetes Security Best Practices you need to know | THE Guide for securing your K8s cluster! — TechWorld with Nana
English · Use: the “User and permission management (RBAC)” section can serve as a conceptual review for this module

Talks such as Liz Rice’s “Getting to Grips with Kubernetes RBAC” from GOTO 2019 came up in search, but I could not directly verify the YouTube video IDs, so no links are listed.

Official documentation

Video storyboard

This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:30
Visual:Four cards, Role, ClusterRole, RoleBinding, and ClusterRoleBinding, arranged in a 2×2 matrix. The horizontal axis is “Define permissions / Grant permissions,” and the vertical axis is “Namespace / Cluster.”
Narration:RBAC has only four objects. Two define permissions, and two grant them.
Shot 2 · 0:30–1:10
Visual:A simulator shows alice's get pods request allowed and get secrets denied, with the reason string displayed.
Narration:RBAC has no deny rules. If no rule allows a request, it is denied.
Shot 3 · 1:10–2:00
Visual:A red warning list: list secrets, create pods, pods/exec, escalate, bind, impersonate, nodes/proxy.
Narration:These permissions look narrow, but each one can be escalated to cluster admin.
Shot 4 · 2:00–2:30
Visual:A terminal loops over can-i, with the yes/no output aligned in a table.
Narration:Add can-i to your pipeline as a regression test for permissions.
or score ≥ 70% on the quiz

Module 3 · ServiceAccount and Workload Identity

15:00 – 22:00 · Short-lived, bound, federated workload identity: call the API from inside the cluster, exchange for cloud tokens from outside it, with no secrets at any step
7 minTokenRequest / projected volume GAAKS Workload ID GA★★★★★
Learning objectives
  • Explain the three properties of a projected SA token, audience, expiration time, and bound object, and how the kubelet rotates it automatically.
  • Use kubectl create token (TokenRequest API) to issue a short-lived token, and decode the JWT claims.
  • Understand how Service Account Issuer Discovery (the OIDC discovery document plus JWKS) lets external systems trust Kubernetes tokens.
  • Configure Microsoft Entra Workload ID on AKS: OIDC issuer, user-assigned managed identity, federated credential, SA annotation, and Pod label, so Pods can read Key Vault without passwords.
Prerequisites: M1, M2; Azure managed identities. Importance: ★★★★★

What: a ServiceAccount is the “user” for a workload

Every namespace gets a default ServiceAccount when it is created. A Pod uses it if it does not set serviceAccountName. The kubelet mounts a projected volume at /var/run/secrets/kubernetes.io/serviceaccount/. It contains three files: token, ca.crt, and namespace.

Why: from long-lived Secret tokens to bound tokens

PropertyOld: Secret-based token (auto-generated before v1.24)New: TokenRequest / projected token
Validity periodPermanentHas an expiration. The projected volume can set expirationSeconds, with a minimum of 600 seconds. The kubelet refreshes it when 20% of its lifetime remains or when it is older than 24 hours.
Bound toNoneBound to the Pod (and its node). The token becomes invalid as soon as the Pod is deleted
AudienceNoneCan set aud to stop the token from being used on other systems
StorageStored in etcd as a SecretNot written to etcd. It stays only in the node's tmpfs
Current statusNo longer auto-generated since v1.24. Unused legacy tokens are automatically marked invalid and cleaned up (LegacyServiceAccountTokenCleanUp, GA in v1.30)Default approach

How: the lifecycle of a projected token

  1. For each Pod, the kubelet calls POST /api/v1/namespaces/shop/serviceaccounts/api/token (TokenRequest). The request includes the audience, expirationSeconds, and boundObjectRef (the Pod name and UID).
  2. kube-apiserver signs the JWT with the private key from --service-account-signing-key-file. The iss claim is set to --service-account-issuer.
  3. The kubelet writes the token to a tmpfs volume in the Pod and refreshes it automatically before it expires. Applications must re-read the file periodically, not just read it once at startup.
  4. When a request reaches the API server, the ServiceAccount authenticator checks the signature and expiration time, and confirms that the bound Pod still exists.

Service Account Issuer Discovery and OIDC federation

The API server serves /.well-known/openid-configuration and /openid/v1/jwks. After external systems (Entra ID, AWS IAM, Vault) read the public keys, they can verify SA tokens on their own. This is the basis of Workload Identity Federation: a Pod uses an SA token with audience=api://AzureADTokenExchange to exchange it with Entra ID for an Azure access token. When AKS is enabled with --enable-oidc-issuer, the issuer is a publicly reachable URL (https://{region}.oic.prod-aks.azure.com/{tenant}/{uuid}/).

Components of AKS Microsoft Entra Workload ID

ComponentRoleConfiguration
OIDC issuerPublishes the public signing key for SA tokensaz aks update --enable-oidc-issuer
Workload Identity admission webhookInjects environment variables and a projected token volume into labeled Pods--enable-workload-identity
User-assigned managed identity (UAMI)An identity on the Azure side, granted permissions on resources such as Key Vaultaz identity create
Federated identity credential (FIC)Trust relationship: issuer + subject (system:serviceaccount:ns:sa) + audienceaz identity federated-credential create (up to 20 per identity)
SA annotationazure.workload.identity/client-id: <UAMI clientId>Restart the Pod after changing the annotation
Pod labelazure.workload.identity/use: "true" (required; only Pods with this label are modified by the webhook)Set in the Pod template's metadata.labels
Injected environment variablesAZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_FEDERATED_TOKEN_FILE, AZURE_AUTHORITY_HOSTRead automatically by DefaultAzureCredential in the Azure Identity SDK

When

  • Pod calls the Kubernetes API → use a dedicated SA with minimal RBAC.
  • Pod calls Azure, AWS, or GCP → use Workload Identity Federation, and do not put a client secret in a Secret.
  • Pod never calls the API → automountServiceAccountToken: false.

Comparison with similar technologies

AKS Workload IDAKS Pod Identity (deprecated)Node managed identity (kubelet identity)EKS IRSA / Pod Identity
GranularityPer SAPer PodEntire node pool (shared by all Pods)Per SA
MechanismOIDC federationIntercepts IMDS (NMI DaemonSet)IMDSOIDC federation / Agent
RecommendationRecommendedDeprecated as of 2022-10-24; migrateOnly for node componentsAWS equivalent
Common misconceptions ① “Workload ID requires storing the Entra token in a Secret.” No. The SDK exchanges the projected SA token on demand each time. ② “The SA token's expiration time is the same as the Azure token's expiration time.” No. The two are unrelated. The Entra access token has its own lifetime (the docs say it can last up to 24 hours). ③ “After you disable automount, Workload ID stops working.” No. Workload ID uses a separate projected volume injected by the webhook (with audience api://AzureADTokenExchange). It is unrelated to the default token volume.

Architecture diagram: projected tokens and issuer discovery

Node: kubelet Pod api (SA: api)/var/run/secrets/kubernetes.io/serviceaccount/tokenaud=https://kubernetes.default.svc… exp=1h/var/run/secrets/azure/tokens/… aud=api://AzureADTokenExchange kubelet: TokenRequest → write to tmpfsAuto-refresh at 20% lifetime remainingPod deleted → token invalid POST …/serviceaccounts/api/token kube-apiserverJWT signed with private key/.well-known/openid-configuration/openid/v1/jwks (public keys)--service-account-issuer External relying partyMicrosoft Entra IDAWS STSHashiCorp VaultFetch JWKS to verify signatureCheck iss / sub / aud
Figure 3-1: The API server signs SA tokens. Any system that can get the JWKS public keys can verify them independently.

Flow diagram: Workload ID token exchange

SDK reads tokenAZURE_FEDERATED_TOKEN_FILE POST /oauth2/v2.0/tokenclient_assertion=SA JWTclient_id=UAMI Entra ID validatesFIC: issuer+subject+audFetch AKS JWKS Return access tokenscope=vault…/.default Key VaultAzure RBAC checkSecrets User
Figure 3-2: No long-lived keys are used at any point. The SA JWT rotates every hour, and the SDK caches the Entra token and refreshes it as needed.

Step-by-step animation: Workload Identity token exchange

It starts when the Pod is created and ends when Key Vault is read. Each step shows the real API call, HTTP request, or JWT field.

kube-apiserver+ WI webhook kubeletTokenRequest Pod (SDK)DefaultAzureCredential Microsoft Entra IDtoken endpoint AKS OIDC issuerJWKS public keys Azure Key Vaultsecrets/my-secret
Click “Play.”
$ kubectl apply -f pod-wi.yaml

Core commands and flags

CommandPurposeKey flags
kubectl create token SACall TokenRequest to issue a short-lived token--duration=10m, --audience=X, --bound-object-kind=Pod --bound-object-name=…
kubectl create serviceaccountCreate an SASet automountServiceAccountToken: false in the YAML
kubectl get --raw /.well-known/openid-configurationView the issuer discovery documentView public keys at /openid/v1/jwks
az aks update --enable-oidc-issuer --enable-workload-identityEnable the OIDC issuer and Workload ID on AKSQuery: --query oidcIssuerProfile.issuerUrl
az identity federated-credential createEstablish federated trust--issuer --subject system:serviceaccount:NS:SA --audience api://AzureADTokenExchange
# Small function that decodes the JWT payload (base64url → base64, with padding added)
jwt() { p=$(echo "$1" | cut -d. -f2 | tr '_-' '/+'); while [ $(( ${#p} % 4 )) -ne 0 ]; do p="$p="; done; echo "$p" | base64 -d | jq .; }
TOKEN=$(kubectl create token ci -n shop --duration=10m --audience=shop-ci)
jwt "$TOKEN"
{
  "aud": ["shop-ci"],
  "exp": 1763201403,
  "iat": 1763200803,
  "iss": "https://kubernetes.default.svc.cluster.local",
  "jti": "7f1b0c2e-…",
  "kubernetes.io": {
    "namespace": "shop",
    "serviceaccount": { "name": "ci", "uid": "3c0d…" }
  },
  "nbf": 1763200803,
  "sub": "system:serviceaccount:shop:ci"
}

How to verify: exp - iat = 600 (10 minutes). Common error: a token issued with --audience=shop-ci gets a 401 when used against the API server, because the API server accepts only its own audience (--api-audiences). That is the point of audience. Production use: for CI outside the cluster, use a very short --duration, or better, use OIDC federation.

kubectl --token="$TOKEN" get deploy -n shop          # 401: audience mismatch
kubectl get --raw /.well-known/openid-configuration | jq
kubectl get --raw /openid/v1/jwks | jq '.keys[0] | {kty, alg, kid}'
error: You must be logged in to the server (Unauthorized)
{
  "issuer": "https://kubernetes.default.svc.cluster.local",
  "jwks_uri": "https://172.18.0.3:6443/openid/v1/jwks",
  "response_types_supported": ["id_token"],
  "subject_types_supported": ["public"],
  "id_token_signing_alg_values_supported": ["RS256"]
}
{ "kty": "RSA", "alg": "RS256", "kid": "Xb3…" }

The issuer in kind is an in-cluster address that external systems cannot reach, so it is only good for demos. AKS's OIDC issuer is a public URL. To allow anonymous access to the discovery endpoints, bind the ClusterRole system:service-account-issuer-discovery.

Explicitly declare a projected token for a workload (custom audience and expiration time)

apiVersion: v1
kind: Pod
metadata: {name: token-demo, namespace: shop}
spec:
  serviceAccountName: api
  automountServiceAccountToken: false      # do not mount the default token
  containers:
  - name: c
    image: busybox:1.37
    command: ["sh", "-c", "sleep 3600"]
    volumeMounts:
    - {name: vault-token, mountPath: /var/run/secrets/tokens, readOnly: true}
  volumes:
  - name: vault-token
    projected:
      sources:
      - serviceAccountToken:
          path: vault-token
          audience: vault
          expirationSeconds: 3600

Lab 3A: give api a dedicated SA and turn off unneeded tokens (kind lab, about 3 minutes)

Create an SA and have api use it:
kubectl -n shop create serviceaccount api --dry-run=client -o yaml | \
  sed '/^metadata:/i automountServiceAccountToken: false' | kubectl apply -f -
kubectl -n shop patch deploy api --type=merge -p '{"spec":{"template":{"spec":{"serviceAccountName":"api","automountServiceAccountToken":false}}}}'
kubectl -n shop rollout status deploy/api
kubectl -n shop exec deploy/api -- ls /var/run/secrets/kubernetes.io/serviceaccount/ 2>&1 | head -2
serviceaccount/api created
deployment.apps/api patched
deployment "api" successfully rolled out
ls: /var/run/secrets/kubernetes.io/serviceaccount/: No such file or directory

Verify: Repeat the “attacker” command from Module 0, step 3. There is no token left in the container to steal. podinfo does not call the Kubernetes API, so it does not need a token.

Do the same for the default SA (so that any Pod without an SA specified cannot get a token):
kubectl -n shop patch serviceaccount default -p '{"automountServiceAccountToken": false}'
Watch automatic token rotation:
kubectl apply -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata: {name: token-demo, namespace: shop}
spec:
  serviceAccountName: api
  automountServiceAccountToken: false
  containers:
  - name: c
    image: busybox:1.37
    command: ["sh","-c","sleep 3600"]
    volumeMounts: [{name: t, mountPath: /var/run/secrets/tokens, readOnly: true}]
  volumes:
  - name: t
    projected:
      sources:
      - serviceAccountToken: {path: demo, audience: demo, expirationSeconds: 600}
EOF
kubectl -n shop wait --for=condition=Ready pod/token-demo
jwt "$(kubectl -n shop exec token-demo -- cat /var/run/secrets/tokens/demo)" | jq '{aud, exp, iat, pod: ."kubernetes.io".pod.name}'
{
  "aud": ["demo"],
  "exp": 1763201410,
  "iat": 1763200810,
  "pod": "token-demo"
}

Run it again after about 8 minutes (80% of 600 seconds). The iat value will have changed, because the kubelet has refreshed the file. Note: if the shop namespace already has the M4 restricted label, this busybox Pod needs a securityContext (see M4/M5).

Clean up: kubectl -n shop delete pod token-demo

Lab 3B (optional, AKS aks-lab): read Key Vault without passwords using Workload ID (about 15 minutes)

Cost / permissions / risk Key Vault Standard tier is billed per operation (the cost of this lab is negligible). Managed identities are free. You need Owner, User Access Administrator, or Role Based Access Control Administrator to create role assignments. Azure role assignments can take up to 10 minutes to propagate, and 403 errors during that time are normal.
Variables and feature enablement (skip the update if Module 0 already created it with the same parameters):
export RG=rg-k8s-lab LOC=canadacentral AKS=aks-lab
export SUFFIX=$(openssl rand -hex 3)
export UAMI=id-shop-api KV=kv-shop-$SUFFIX NS=wi-demo SA=api-wi
az aks update -g $RG -n $AKS --enable-oidc-issuer --enable-workload-identity
export AKS_OIDC_ISSUER=$(az aks show -g $RG -n $AKS --query "oidcIssuerProfile.issuerUrl" -o tsv)
echo $AKS_OIDC_ISSUER
https://canadacentral.oic.prod-aks.azure.com/00000000-0000-0000-0000-000000000000/11111111-1111-1111-1111-111111111111/
Managed identity + Key Vault + role assignments:
az identity create -g $RG -n $UAMI -l $LOC
export CLIENT_ID=$(az identity show -g $RG -n $UAMI --query clientId -o tsv)
export PRINCIPAL_ID=$(az identity show -g $RG -n $UAMI --query principalId -o tsv)

az keyvault create -g $RG -n $KV -l $LOC --enable-purge-protection --enable-rbac-authorization
export KV_ID=$(az keyvault show -g $RG -n $KV --query id -o tsv)
export KV_URL=$(az keyvault show -g $RG -n $KV --query properties.vaultUri -o tsv)

# Permission for you to write secrets
az role assignment create --assignee "$(az ad signed-in-user show --query id -o tsv)" \
  --role "Key Vault Secrets Officer" --scope $KV_ID
az keyvault secret set --vault-name $KV --name db-password --value 'S3cure-From-KV!'

# Read-only access for the workload identity
az role assignment create --assignee-object-id $PRINCIPAL_ID --assignee-principal-type ServicePrincipal \
  --role "Key Vault Secrets User" --scope $KV_ID
SA (with annotation) + federated credential:
kubectl create namespace $NS
kubectl apply -f - <<EOF
apiVersion: v1
kind: ServiceAccount
metadata:
  name: $SA
  namespace: $NS
  annotations:
    azure.workload.identity/client-id: "$CLIENT_ID"
EOF
az identity federated-credential create --name fic-$NS-$SA \
  --identity-name $UAMI --resource-group $RG \
  --issuer "$AKS_OIDC_ISSUER" \
  --subject system:serviceaccount:$NS:$SA \
  --audience api://AzureADTokenExchange
Deploy a verification Pod (the official sample image msal-go, which reads Key Vault and prints the result):
kubectl apply -f - <<EOF
apiVersion: v1
kind: Pod
metadata:
  name: kv-reader
  namespace: $NS
  labels:
    azure.workload.identity/use: "true"
spec:
  serviceAccountName: $SA
  containers:
  - name: oidc
    image: ghcr.io/azure/azure-workload-identity/msal-go
    env:
    - {name: KEYVAULT_URL, value: "$KV_URL"}
    - {name: SECRET_NAME, value: db-password}
  nodeSelector:
    kubernetes.io/os: linux
EOF
kubectl -n $NS wait --for=condition=Ready pod/kv-reader --timeout=120s
kubectl -n $NS get pod kv-reader -o jsonpath='{range .spec.containers[0].env[*]}{.name}{"\n"}{end}'
kubectl -n $NS logs kv-reader | tail -2
KEYVAULT_URL
SECRET_NAME
AZURE_CLIENT_ID
AZURE_TENANT_ID
AZURE_FEDERATED_TOKEN_FILE
AZURE_AUTHORITY_HOST
I1115 10:35:09.795900       1 main.go:63] "successfully got secret" secret="S3cure-From-KV!"

Verify: The last four environment variables are injected by the webhook. Neither the Pod YAML nor any Secret contains a password or client secret. Negative test: remove the Pod label and recreate the Pod. The logs should show an authentication failure.

Clean up:
kubectl delete namespace $NS
az identity delete -g $RG -n $UAMI
az keyvault delete -g $RG -n $KV      # purge protection is enabled, so the name stays reserved during the retention period
# When finished: az group delete -n rg-k8s-lab --yes --no-wait

Case 1: Migrating from a service principal password in a Secret to Workload ID

Problem: The order service uses AZURE_CLIENT_SECRET (stored in a K8s Secret) to access Storage. The password expires every six months and has caused an outage, and it was once accidentally committed to Git. Approach: Create a UAMI and FIC for each service, change the code to use DefaultAzureCredential (supported in .NET Azure.Identity ≥ 1.9.0 and other versions), add the label to the Pod template, and delete the Secret. Limit: Each UAMI can have up to 20 FICs, which can be reached with multiple clusters (blue-green, multi-region). AKS identity bindings let several clusters share one FIC. A new FIC takes a few seconds to propagate.

Case 2: Deploying to AKS from GitHub Actions without keys

Approach: Also based on OIDC federation. Add an FIC to the Entra application or UAMI, with subject repo:org/shop:environment:prod and issuer https://token.actions.githubusercontent.com. The workflow uses azure/login to get an Azure token, then uses kubelogin (-l workloadidentity or azurecli) to access AKS. On the Kubernetes side, grant only ci-deployer-level permissions. Limit: The subject must match exactly (branch or environment). Wildcards require the newer “flexible FIC” feature. Check the Entra documentation for details.

Case 3: A third-party SaaS needs to read cluster information

Approach: Do not issue a long-lived kubeconfig. Create an SA and a read-only Role for it, issue a token with --duration=1h through TokenRequest, and have automation refresh it regularly. Or have the SaaS trust your issuer through OIDC federation. Limit: The API server's --service-account-max-token-expiration caps the maximum lifetime.

Common errors and fixes

AADSTS70021: No matching federated identity record found for presented assertion.

Cause: The FIC's issuer, subject, or audience does not match the SA token. The most common causes are a misspelled namespace or SA name, a mismatched trailing slash in the issuer, or a changed issuer after the cluster was rebuilt.

az identity federated-credential list -g $RG --identity-name $UAMI -o table
az aks show -g $RG -n $AKS --query oidcIssuerProfile.issuerUrl -o tsv
kubectl -n $NS exec kv-reader -- sh -c 'cat $AZURE_FEDERATED_TOKEN_FILE' | cut -d. -f2 | base64 -d 2>/dev/null
The Pod has no AZURE_CLIENT_ID or AZURE_FEDERATED_TOKEN_FILE environment variables

Cause: The Pod is missing the label azure.workload.identity/use: "true" (the label was put on the Deployment instead of the Pod template), the cluster does not have --enable-workload-identity enabled, or the SA annotation was added after the Pod was created (the Pod must be restarted).

kubectl get pod kv-reader -n $NS --show-labels
kubectl get mutatingwebhookconfiguration | grep -i workload
kubectl -n kube-system get pods | grep -i workload-identity
error: failed to create token: serviceaccounts "ci" not found / "the server could not find the requested resource"

Cause: The SA does not exist in that namespace, or the kubectl version is too old (create token requires kubectl 1.24 or later).

kubectl -n shop get sa
kubectl version --client
After the app has run for 1 hour, it starts returning 401 Unauthorized when calling the Kubernetes API

Cause: The app reads the token file once at startup and caches it. The projected token has rotated, and the old token has expired. Fix: Use the official client-go or SDK, which re-reads the file automatically, or re-read the file yourself on a schedule.

Command-line exercise
1. Issue a 15-minute token for SA shop:ci that is bound to a Pod.
kubectl create token ci -n shop --duration=15m --bound-object-kind=Pod --bound-object-name=runner-0 --bound-object-uid=$(kubectl -n shop get pod runner-0 -o jsonpath='{.metadata.uid}')

The token becomes invalid as soon as the Pod is deleted.

2. Write down the two required settings that let a Pod use Workload ID.

ServiceAccount annotation azure.workload.identity/client-id: <UAMI clientId>, and Pod template label azure.workload.identity/use: "true", with serviceAccountName set. The Azure side also needs a matching FIC and resource role assignments.

Scenario analysis question
The team set the FIC subject of one UAMI to system:serviceaccount:shop:default. They say, “This way every Pod can access Key Vault, which is convenient.” What is the problem?

This gives Key Vault access to every Pod in shop that uses the default SA, including compromised and debugging Pods. That breaks least privilege, and anyone who can create a Pod in shop can read all the secrets. Each workload that needs access should have its own SA and its own FIC (and its own UAMI if needed). The default SA should not be bound to any cloud identity, and automount should be turned off.

Verified teaching videos

▶
Azure AD Workload Identity on AKS | KubeCon 2022 — Microsoft Azure
English · recorded in 2022 (the product was then called Azure AD Workload Identity, now Microsoft Entra Workload ID) · Use: builds intuition for OIDC federation and token exchange. For commands, follow this lesson and Microsoft Learn.

Official documentation

Video storyboard

This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:25
Visual:AZURE_CLIENT_SECRET in the Secret is crossed out in red.
Narration:A workload that accesses cloud resources should not carry a password.
Shot 2 · 0:25–1:10
Visual:The kubelet sends a TokenRequest. The three JWT parts expand, with iss, sub, aud, and exp highlighted.
Narration:Kubernetes issues a short-lived token for each Pod. It includes the audience, the expiration time, and the bound Pod. Nothing is left out.
Shot 3 · 1:10–2:10
Visual:Animation: Pod → Entra ID → fetch JWKS → return access token → Key Vault.
Narration:Entra ID verifies the token with the cluster's public keys, then exchanges it for an Azure token based on the federated credential.
Shot 4 · 2:10–2:40
Visual:kubectl logs shows successfully got secret.
Narration:No long-lived keys are used anywhere in the process.
or score ≥ 70% on the quiz

Module 4 · Pod Security Standards and Pod Security Admission

22:00 – 29:00 · Use three namespace labels to turn “no privileged containers” into a cluster-wide enforced rule
7 minPSA GA v1.25PSP removed in v1.25★★★★★
Learning objectives
  • Name the fields that each of the three levels (Privileged, Baseline, and Restricted) restricts.
  • Use the pod-security.kubernetes.io/{enforce,audit,warn} and -version labels, and preview the impact with kubectl label --dry-run=server.
  • Understand that enforce applies only to Pods (not Deployments), and does not affect Pods that are already running.
  • Upgrade the shop namespace to restricted and fix all workloads that violate it.
Prerequisites: Linux users and the capabilities concept (covered in depth in M5). Importance: ★★★★★

What: the standards (PSS) and the enforcer (PSA)

Pod Security Standards is a documented policy definition with three levels. Pod Security Admission is a built-in validating admission plugin in kube-apiserver (GA in v1.25, enabled by default). It enforces these standards on Pods based on namespace labels. It replaces PodSecurityPolicy (PSP), which was removed in v1.25.

LevelPurposeMain restrictions
PrivilegedNo restrictionsNone. For namespaces that hold system components such as CNI, storage drivers, and log agents
BaselinePrevents known privilege escalations and works with most imagesDisallows privileged, hostNetwork/hostPID/hostIPC, hostPath, hostPort (by default), and non-default capabilities (only AUDIT_WRITE, CHOWN, DAC_OVERRIDE, FOWNER, FSETID, KILL, MKNOD, NET_BIND_SERVICE, SETFCAP, SETGID, SETPCAP, SETUID, and SYS_CHROOT are allowed). Also disallows seccomp or AppArmor set to Unconfined, unsafe sysctls, procMount Unmasked, and custom SELinux user or role. Starting in v1.34, it also disallows the host field in probes and lifecycle hooks.
RestrictedCurrent best practices for hardening PodsEverything in Baseline, plus allowPrivilegeEscalation: false, runAsNonRoot: true, runAsUser must not be 0, seccomp must be RuntimeDefault or Localhost (leaving it unset is not allowed), capabilities.drop must include ALL, add may only include NET_BIND_SERVICE, and volume types are limited to configMap / csi / downwardAPI / emptyDir / ephemeral / persistentVolumeClaim / projected / secret

Why: why use namespace labels

The problem with PSP is that which policy applies depends on RBAC authorization, which is hard to reason about. PSA simplifies policy selection to “namespace level + mode.” It does not mutate anything; it only makes allow or deny decisions. When you need finer control, such as “images must come from a private registry,” add a VAP from M6 or Kyverno.

How: the three modes and version pinning

LabelBehaviorApplies to
pod-security.kubernetes.io/enforce: restrictedViolating Pods are rejected (403 Forbidden)Pods only. It does not apply to workload objects such as Deployments. They are accepted, but the ReplicaSet fails when it creates Pods
pod-security.kubernetes.io/warn: restrictedAllowed, but a Warning is returned to the clientPods and workload objects
pod-security.kubernetes.io/audit: restrictedAllowed, with an annotation added to the audit eventPods and workload objects
pod-security.kubernetes.io/enforce-version: v1.37Pins the policy to the definition of a specific version. Can be set to latestPrevents new rules from suddenly rejecting Pods when the cluster is upgraded

Other points: when you add or change the enforce label on a namespace, PSA evaluates existing Pods and returns warnings, but it does not evict them. They are rejected only when they are recreated. Exemptions can be configured statically only in the API server's admission configuration file (usernames, runtimeClassNames, namespaces). Do not exempt controller SAs (for example, replicaset-controller). Doing so would effectively exempt everyone who can create a Deployment.

When: which level to use for each type of namespace

  • Application namespaces (shop) → enforce: restricted (or start with baseline and warn on restricted as a transition).
  • Platform components (ingress / gateway, monitoring) → baseline, with a few components privileged.
  • kube-system, CNI, CSI → privileged (AKS manages its own system namespaces).
  • We recommend setting the cluster default (through the admission configuration defaults) to baseline enforce and restricted warn.

Comparison with similar technologies

PSAPSP (removed)VAP (M6)Kyverno / Gatekeeper
DeploymentBuilt inBuilt inBuilt inRequires installing a webhook
GranularityNamespace × 3 levelsSelected by RBACAny CEL ruleAny rule + mutate/generate
Mutates PodsNoYes (default)No (MAP can)Yes
AKSAvailable—AvailableAzure Policy for AKS is based on Gatekeeper
Common misconceptions ① “Once you add the enforce label, a violating Deployment fails to apply.” No. The apply succeeds with only a warning, but the Pods never start. Check the FailedCreate events in kubectl describe rs. ② “restricted adds a securityContext for me automatically.” No. PSA does not mutate. ③ “runAsNonRoot: true is enough.” Not if the image's USER is a non-numeric name (such as app in podinfo). The kubelet cannot verify it, and the container reports CreateContainerConfigError. You also need to set a numeric runAsUser.

Architecture diagram: how the three levels nest

Privileged: allows everything (kube-system, CNI, CSI node plugins) Baseline: blocks privileged · host namespaces · hostPath · hostPort · dangerous capabilities · Unconfined seccomp/AppArmor · unsafe sysctls Restricted: on top of Baseline, also requires ✓ runAsNonRoot: true, runAsUser ≠ 0 ✓ allowPrivilegeEscalation: false ✓ seccompProfile.type: RuntimeDefault | Localhost ✓ capabilities.drop: ["ALL"] (add only NET_BIND_SERVICE) ✓ Volume type allowlist (no hostPath, nfs, or similar) Windows Pods (os.name=windows) relax some Linux-only checks
Figure 4-1: The levels are nested. Meeting Restricted always means meeting Baseline.

Flow diagram: how PSA makes decisions in the admission chain

Create Pod / Deployment(authn/authz already passed) Mutating phase completeDefaults and webhook injection PodSecurity pluginRead namespace labels enforce violation → 403 warn → Warning header audit → audit annotation Continue to VAP / write to etcd
Figure 4-2: PSA runs after mutating, so sidecars injected by webhooks are also checked.

Interactive: Pod fields → the three level checkers

Select the security settings for a Pod. The right side shows in real time whether it passes Privileged, Baseline, and Restricted, along with the actual violation messages that PSA returns (matching violates PodSecurity "restricted:latest": …).

Core commands and flags

CommandPurposeNotes
kubectl label --dry-run=server --overwrite ns NS pod-security.kubernetes.io/enforce=restrictedDry run: which existing Pods would violate the policyThe server runs the PSA evaluation but does not save changes
kubectl label ns NS pod-security.kubernetes.io/warn=restricted pod-security.kubernetes.io/warn-version=latestWarn only, during the transitionSet multiple labels at once
kubectl get ns -L pod-security.kubernetes.io/enforceCheck the level for each namespace-L shows the label as a column
kubectl describe rs -n NSView the FailedCreate events for Pods that a Deployment could not createenforce does not apply to the Deployment itself
kubectl get events -n NS --field-selector reason=FailedCreateQuick lookup—
kubectl label --dry-run=server --overwrite ns shop pod-security.kubernetes.io/enforce=restricted
Warning: existing pods in namespace "shop" violate the new PodSecurity enforce level "restricted:latest"
Warning: api-6c9f7d8b5-2xkqz (and 1 other pod): allowPrivilegeEscalation != false, unrestricted capabilities, runAsNonRoot != true, seccompProfile
Warning: db-0: allowPrivilegeEscalation != false, unrestricted capabilities, runAsNonRoot != true, seccompProfile
Warning: web-7d4b9c6f8-l9ptd (and 1 other pod): allowPrivilegeEscalation != false, unrestricted capabilities, runAsNonRoot != true, seccompProfile
namespace/shop labeled (server dry run)

How to verify: The output ends with (server dry run), and kubectl get ns shop --show-labels does not change. Common error: If you forget --overwrite and the label already exists, you get already has a value.

A Pod template snippet that satisfies restricted

spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 10001
    runAsGroup: 10001
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: app
    securityContext:
      allowPrivilegeEscalation: false
      capabilities:
        drop: ["ALL"]

Cluster-wide defaults and exemptions (self-managed cluster, kube-apiserver --admission-control-config-file)

apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
- name: PodSecurity
  configuration:
    apiVersion: pod-security.admission.config.k8s.io/v1
    kind: PodSecurityConfiguration
    defaults:
      enforce: "baseline"
      enforce-version: "latest"
      warn: "restricted"
      warn-version: "latest"
      audit: "restricted"
      audit-version: "latest"
    exemptions:
      usernames: []
      runtimeClasses: []
      namespaces: ["kube-system"]

AKS does not expose API server parameters. Apply the labels to the namespace, or use the built-in Pod security initiative in Azure Policy for AKS.

Lab 4: upgrade shop to restricted (about 8 minutes, kind lab)

First, turn on warn and audit, and observe the impact:
kubectl label --overwrite ns shop \
  pod-security.kubernetes.io/warn=restricted pod-security.kubernetes.io/warn-version=latest \
  pod-security.kubernetes.io/audit=restricted pod-security.kubernetes.io/audit-version=latest
kubectl -n shop rollout restart deploy/api   # Trigger one Pod template evaluation
namespace/shop labeled
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "api" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "api" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "api" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "api" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
deployment.apps/api restarted
Fix api (podinfo): the image USER is the non-numeric app, so you must set a numeric UID explicitly:
kubectl -n shop patch deploy api --type=json -p='[
 {"op":"add","path":"/spec/template/spec/securityContext","value":{"runAsNonRoot":true,"runAsUser":10001,"runAsGroup":10001,"seccompProfile":{"type":"RuntimeDefault"}}},
 {"op":"add","path":"/spec/template/spec/containers/0/securityContext","value":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}
]'
kubectl -n shop rollout status deploy/api
Fix web: the official nginx image needs to start as root and bind port 80. Switch to the unprivileged image maintained by NGINX, nginxinc/nginx-unprivileged:1.29-alpine (runs as UID 101 and listens on 8080):
kubectl -n shop set image deploy/web '*=nginxinc/nginx-unprivileged:1.29-alpine'
kubectl -n shop patch deploy web --type=json -p='[
 {"op":"add","path":"/spec/template/spec/securityContext","value":{"runAsNonRoot":true,"runAsUser":101,"runAsGroup":101,"seccompProfile":{"type":"RuntimeDefault"}}},
 {"op":"add","path":"/spec/template/spec/containers/0/securityContext","value":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}},
 {"op":"add","path":"/spec/template/spec/containers/0/ports","value":[{"name":"http","containerPort":8080}]}
]'
kubectl -n shop patch svc web --type=json -p='[{"op":"replace","path":"/spec/ports/0/targetPort","value":8080}]'
kubectl -n shop rollout status deploy/web
Check the configuration from earlier hours. If web set up a probe with port: 80 in hour 2, mounts a custom nginx.conf (listen 80), or if the NetworkPolicy from hour 3 allows only port 80, change those to 8080 as well. After making the changes, access it once through the Gateway to confirm.
Fix db (postgres:17): run as the postgres user (UID/GID 999), and use fsGroup to make the data volume writable:
kubectl -n shop patch sts db --type=json -p='[
 {"op":"add","path":"/spec/template/spec/securityContext","value":{"runAsNonRoot":true,"runAsUser":999,"runAsGroup":999,"fsGroup":999,"seccompProfile":{"type":"RuntimeDefault"}}},
 {"op":"add","path":"/spec/template/spec/containers/0/securityContext","value":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}
]'
kubectl -n shop rollout status sts/db
kubectl -n shop exec db-0 -- id
uid=999(postgres) gid=999(postgres) groups=999(postgres)

An existing data directory was already chowned to 999 by the entrypoint script during its first initialization, so it can run as 999 directly. If the data volume is new, the postgres image can also complete initdb when it starts as non-root (PGDATA must be writable).

Dry-run again, then enforce for real and pin the version:
kubectl label --dry-run=server --overwrite ns shop pod-security.kubernetes.io/enforce=restricted
kubectl label --overwrite ns shop pod-security.kubernetes.io/enforce=restricted pod-security.kubernetes.io/enforce-version=v1.37
kubectl get ns shop -o jsonpath='{.metadata.labels}' | jq
namespace/shop labeled (server dry run)
namespace/shop labeled
{
  "kubernetes.io/metadata.name": "shop",
  "pod-security.kubernetes.io/audit": "restricted",
  "pod-security.kubernetes.io/audit-version": "latest",
  "pod-security.kubernetes.io/enforce": "restricted",
  "pod-security.kubernetes.io/enforce-version": "v1.37",
  "pod-security.kubernetes.io/warn": "restricted",
  "pod-security.kubernetes.io/warn-version": "latest"
}

The first dry run no longer prints any warnings, which means all existing Pods comply.

Verify rejection:
kubectl -n shop run bad --image=busybox:1.37 --restart=Never -- sleep 60
kubectl -n shop create deploy bad --image=busybox:1.37 -- sleep 3600
kubectl -n shop get events --field-selector reason=FailedCreate | tail -2
Error from server (Forbidden): pods "bad" is forbidden: violates PodSecurity "restricted:v1.37": allowPrivilegeEscalation != false (container "bad" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "bad" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "bad" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "bad" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
Warning: would violate PodSecurity "restricted:latest": ...
deployment.apps/bad created
... Warning   FailedCreate   replicaset/bad-5d8f…   Error creating: pods "bad-5d8f…" is forbidden: violates PodSecurity "restricted:v1.37": ...
Clean up: kubectl -n shop delete deploy bad. Keep the restricted label. Later modules build on it.

Case 1: Rolling out to 300 namespaces in stages

Approach: Week 1: set warn=restricted, audit=restricted on all namespaces. Collect the pod-security.kubernetes.io/audit-violations annotations and report them by team. Weeks 2–4: switch compliant namespaces to enforce=restricted, and set the rest to enforce=baseline first. Always pin enforce-version, and evaluate new versions only after cluster upgrades. Limit: Audit annotations are visible only when audit logging is enabled (M8).

Case 2: A log agent needs hostPath

Approach: Put the agent in its own namespace, logging, with enforce=privileged (or when baseline is not enough). Use RBAC to limit who can create Pods in that namespace, and keep application namespaces at restricted. Limit: This namespace becomes a high-value target, so you need a VAP to further limit where images come from.

Case 3: AKS + Azure Policy

Approach: Enable the Azure Policy add-on and assign the built-in initiative “Kubernetes cluster pod security restricted standards for Linux-based workloads.” Evaluate with the Audit effect first, then change it to Deny. Keep it alongside the PSA labels. Limit: Azure Policy is based on the Gatekeeper webhook, so policy sync can take minutes. Check the Azure portal for the exact initiative name.

Common errors and fixes

Error: container has runAsNonRoot and image has non-numeric user (app), cannot verify user is non-root

Cause: The Pod sets runAsNonRoot: true, but the image's USER is a user name rather than a numeric UID, so the kubelet cannot confirm that it is not root. The Pod status is CreateContainerConfigError.

kubectl -n shop describe pod -l app=api | grep -A3 "Warning"
docker image inspect ghcr.io/stefanprodan/podinfo:6.17.0 -f '{{.Config.User}}'

Fix: Add runAsUser: 10001 (any non-zero number) to the securityContext, or make the image use USER 10001.

The Deployment shows 0/2 READY, but kubectl apply succeeds with no errors

Cause: enforce does not apply to the Deployment itself. The ReplicaSet's attempt to create Pods is rejected.

kubectl -n shop describe rs -l app=web | grep -A2 FailedCreate
nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)

Cause: The container runs as non-root and drops all capabilities, so it cannot bind to ports below 1024.

Fix: Use an image that listens on 8080 (nginx-unprivileged). Or, within what restricted allows, add capabilities.add: ["NET_BIND_SERVICE"]. Note that a non-root process also needs file capabilities or ambient capabilities for this to take effect. The simplest option is to change the port.

Warning: existing pods in namespace "x" violate the new PodSecurity enforce level ... Will these Pods be deleted?

No. PSA makes its decision only when a Pod is created or updated. Existing Pods keep running until they are recreated, during a rolling update, node eviction, or a rebuild after an OOM kill. Only then are they rejected. That can happen in the middle of the night, so clear all warnings before you set enforce.

Command-line exercise
1. Set namespace staging to enforce baseline and warn restricted, and pin both to v1.37.
kubectl label --overwrite ns staging \
  pod-security.kubernetes.io/enforce=baseline pod-security.kubernetes.io/enforce-version=v1.37 \
  pod-security.kubernetes.io/warn=restricted pod-security.kubernetes.io/warn-version=v1.37
2. List all namespaces that do not yet have an enforce label.
kubectl get ns -L pod-security.kubernetes.io/enforce | awk 'NR==1 || $4==""'
Scenario analysis question
shop is already restricted. After Istio sidecar injection, all new Pods are rejected, and the message says the istio-init container needs NET_ADMIN. What should you do?

PSA runs after mutating, so it checks the injected init container. NET_ADMIN is already disallowed at baseline. Options: use the Istio CNI plugin (a node-level DaemonSet sets up iptables, so the Pod no longer needs a NET_ADMIN init container), or use ambient mode. Do not downgrade the namespace to privileged just to support the sidecar.

Verified teaching videos

No verified video focused on Pod Security Admission was found. KubeCon talks such as “Practical Challenges with Pod Security Admission” and “The Hitchhiker's Guide to Pod Security” came up in search, but I could not directly verify their YouTube links. For a broader review, see:

▶
Kubernetes Security Best Practices you need to know — TechWorld with Nana
English · The video may still mention PSP (removed in v1.25). Follow the PSA content in this lesson.

Official documentation

Video storyboard

This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.

Shot 1 · 0:00–0:30
Visual:Three concentric circles: Privileged, Baseline, and Restricted, lighting up one after another.
Narration:Pod Security Standards have only three levels, and each level inward is stricter.
Shot 2 · 0:30–1:10
Visual:Three labels are attached to a namespace object: enforce, warn, and audit.
Narration:enforce rejects, warn alerts, and audit records. Warn first, then enforce.
Shot 3 · 1:10–1:50
Visual:A terminal runs label --dry-run=server, and warnings appear line by line. After a patch, it runs again and the warnings disappear.
Narration:Use a server-side dry run. Clear the warnings first, then apply the enforce label.
Shot 4 · 1:50–2:20
Visual:The Deployment applies successfully but shows 0/2 READY. The camera moves to the FailedCreate event on the ReplicaSet.
Narration:Enforce mode blocks only Pods, so look for the cause in the ReplicaSet events.
or score ≥ 70% on the quiz

Module 5 · securityContext and Container Hardening

29:00 – 36:00 · Translate the --read-only --cap-drop ALL --security-opt no-new-privileges flags from the Docker course into Kubernetes
7 minAppArmor field GA v1.30User Namespaces GA v1.36SELinuxMount GA v1.37★★★★☆
Learning objectives
  • Distinguish between Pod-level and container-level securityContext, and understand runAsUser, runAsGroup, runAsNonRoot, fsGroup, and supplementalGroups.
  • Understand which kinds of attacks each of these blocks: allowPrivilegeEscalation (no_new_privs), readOnlyRootFilesystem, capabilities, seccomp, AppArmor, SELinux, and user namespaces.
  • Apply full hardening to podinfo, and verify it with id, /proc/1/status, and a file-write test.
  • Understand image supply chain controls: signature verification (cosign / Notation), registry allowlists, and digest pinning.
Prerequisites: Docker course modules 3 and 4 (non-root, capabilities). Importance: ★★★★☆

What: a map of securityContext fields

FieldLevelKernel mechanismWhat it blocksDocker equivalent
runAsUser / runAsGroupPod / containerProcess UID/GIDReading and writing files as root, and exploiting root-only vulnerabilities--user
runAsNonRootPod / containerChecked by the kubelet before startupImage unexpectedly runs as root—
fsGroup, fsGroupChangePolicyPodVolume file group + setgidNon-root cannot write to the PVC—
allowPrivilegeEscalation: falseContainerno_new_privsPrivilege escalation through setuid programs (sudo, older ping)--security-opt no-new-privileges
readOnlyRootFilesystem: trueContainerRead-only root mountDropping backdoors, tampering with binaries, installing tools--read-only
capabilities.drop: ["ALL"]ContainerLinux capabilitiesNET_RAW spoofing, CHOWN, DAC_OVERRIDE bypassing file permissions, and so on--cap-drop ALL
seccompProfile: RuntimeDefaultPod / containerseccomp-bpf syscall filteringDangerous syscalls such as unshare, mount, keyctl, and bpf, and the kernel vulnerabilities behind themEnabled by default in Docker
appArmorProfile (GA in v1.30, replaces the old annotation)Pod / containerAppArmor LSMRestricts file and network access by path--security-opt apparmor=
seLinuxOptions, seLinuxChangePolicyPod / containerSELinux labelsCross-container file access (RHEL-based systems)--security-opt label=
hostUsers: false (GA in v1.36)Poduser namespaceRoot inside the container is not root on the node. After an escape, it is still an unprivileged user--userns-remap
privileged: trueContainerTurns off nearly all isolation— (this is the risk itself)--privileged

Note: Like Docker, Kubernetes (containerd/CRI) has historically defaulted to Unconfined when no seccompProfile is set. The kubelet's --seccomp-default (SeccompDefault, GA in v1.27) can change the node default to RuntimeDefault. Even so, set it explicitly in the Pod. PSA restricted also requires an explicit setting.

Why: defense in depth

Application vulnerabilities (RCE) are almost unavoidable. The goal of securityContext is that once an attacker has a shell, they are not root, cannot write to disk, cannot install tools, cannot call dangerous system calls, cannot escalate privileges, and even if they escape to the node, they are only an unprivileged user. Each control is small, but together they make a “container escape” orders of magnitude harder.

How: a few details that are easy to get wrong

  • Container level overrides Pod level: for fields with the same name, the container-level setting wins. capabilities, readOnlyRootFilesystem, allowPrivilegeEscalation, and privileged can be set only at the container level.
  • readOnlyRootFilesystem needs writable directories: mount an emptyDir at /tmp and cache directories (you can set medium: Memory + sizeLimit).
  • Recursive chown for fsGroup is slow: for large volumes, use fsGroupChangePolicy: OnRootMismatch.
  • runAsNonRoot + non-numeric USER: you must add a numeric runAsUser (you already ran into this in M4).
  • User namespace requirements: Linux 6.3+ (tmpfs idmap mount), containerd 2.0+ / CRI-O 1.25+, runc 1.2+ or crun 1.9+, and a filesystem that supports idmap mounts for the volume (ext4, xfs, btrfs, tmpfs, overlayfs, and so on).
  • SELinuxMount (GA in v1.37, on by default): volumes are mounted with -o context= instead of being relabeled recursively, which is faster. However, Pods with different SELinux labels on the same node that share a volume may fail to start. To keep the old behavior, set seLinuxChangePolicy: Recursive on the Pod. Nodes without SELinux enabled (such as Ubuntu or kind) are not affected.

Image supply chain: run only trusted images

Control pointToolHow to enforce it in K8s
SigningSigstore cosign (keyless or key pair), Notary Project Notation (ACR + Key Vault certificates)Kyverno image verification policies, Ratify + Gatekeeper (the AKS image integrity feature is based on this; check the official documentation for current status)
Registry allowlistAllow only myacr.azurecr.io/VAP (extended in the M6 lab), built-in Azure Policy
Immutable referencesUse an @sha256: digestVAP blocks :latest / requires a digest
Pull credentialsAKS node managed identity + AcrPullNo imagePullSecrets needed

When

All application Pods use the “restricted template + read-only root + emptyDir” by default. Make exceptions only when truly needed. For example, if a Pod needs to bind port 443, change the port first. If it needs NET_ADMIN, move it to a separate namespace and get approval.

Comparison with similar technologies

Isolation strengthOptionCost
Standardrunc + securityContext (this lesson)Almost none
Strongeruser namespaces (hostUsers: false)Kernel and runtime version requirements
SandboxgVisor and Kata Containers (AKS Pod Sandboxing) through RuntimeClassPerformance overhead and compatibility limits
StrongestSeparate node pool / separate clusterCost
Common misconceptions ① “It's fine to run as root in a container, because namespaces provide isolation.” Kernel vulnerabilities and misconfigured mounts can turn container root directly into node root. ② “privileged just grants a little more permission.” A privileged container can access all devices and mount node disks. That is equivalent to node root. ③ “drop ALL will break the application.” Most applications that listen on ports above 1024 need no capabilities at all.

Architecture diagram: the layers a system call must pass through

Attacker shell (RCE)Inside the api container ① UID 10001 (non-root) ② no_new_privs (blocks setuid escalation) ③ capabilities = empty set ④ read-only root filesystem Linux kernel ⑤ seccomp: syscall allowlist ⑥ LSM: AppArmor / SELinux ⑦ user namespace mapping Node resourcesFilesystem / devices / network stackOther containers / kubelet credentialsprivileged: true goes directly tobypass ③, ⑤, and ⑥ and expose all devices
Figure 5-1: User-space controls (①–④) and kernel controls (⑤–⑦) stack on top of each other

Flow diagram: how the kubelet passes securityContext to the runtime

Pod specsecurityContext kubeletrunAsNonRoot check CRI CreateContainerLinuxContainerSecurityContext containerdGenerate OCI config.json runcsetuid/caps/seccomp
Figure 5-2: The path is the same as in Docker course M1. In both cases, the settings end up in OCI config.json, and runc applies them before exec.

Interactive: hardening switches → what an attacker can do in the container

Turn each securityContext setting on or off. The right side shows the results of typical commands run by an attacker in a shell. The results reflect real kernel behavior (UID checks, no_new_privs, capability checks, seccomp returning EPERM, read-only mounts returning EROFS, and user namespace mapping).

Core commands and flags

CommandPurposeNotes
kubectl exec POD -- idCheck UID/GIDIf the image has no id command, use cat /proc/1/status
kubectl exec POD -- grep -E 'Uid|Cap|NoNewPrivs|Seccomp' /proc/1/statusView the kernel's perspective directlyCapEff: 0000000000000000, NoNewPrivs: 1, Seccomp: 2 (filter mode)
kubectl debug -it POD --image=busybox:1.37 --target=CONTAINERTroubleshoot with an ephemeral container (without changing the original image)In a restricted namespace, ephemeral containers must also satisfy PSA. Add --profile=restricted, and the image must be able to run as non-root (this profile does not set a UID).
kubectl explain pod.spec.securityContext --recursiveView fieldsContainer level: pod.spec.containers.securityContext
cosign verify --certificate-identity … --certificate-oidc-issuer … IMGVerify a keyless signatureThird-party tool. For parameters, see the Sigstore documentation.
kubectl -n shop exec deploy/api -- grep -E 'Uid|CapEff|NoNewPrivs|Seccomp:' /proc/1/status
Uid:	10001	10001	10001	10001
CapEff:	0000000000000000
NoNewPrivs:	1
Seccomp:	2

How to read it: CapEff all zeros means no effective capabilities. Seccomp: 2 means a filter is enabled. NoNewPrivs: 1 corresponds to allowPrivilegeEscalation: false. Common error: setting capabilities only at the Pod level. That field exists only at the container level, so apply fails with an unknown field error.

Full hardening template (container level + Pod level)

spec:
  automountServiceAccountToken: false
  securityContext:
    runAsNonRoot: true
    runAsUser: 10001
    runAsGroup: 10001
    fsGroup: 10001
    fsGroupChangePolicy: OnRootMismatch
    seccompProfile: {type: RuntimeDefault}
    appArmorProfile: {type: RuntimeDefault}     # takes effect when the node has AppArmor enabled (enabled by default on Ubuntu)
  containers:
  - name: api
    image: ghcr.io/stefanprodan/podinfo:6.17.0
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      privileged: false
      capabilities: {drop: ["ALL"]}
    volumeMounts:
    - {name: tmp, mountPath: /tmp}
  volumes:
  - name: tmp
    emptyDir: {medium: Memory, sizeLimit: 64Mi}

Optional: user namespaces (GA in v1.36)

spec:
  hostUsers: false     # map container UIDs 0..65535 to an unprivileged UID range on the node
kubectl -n shop exec POD -- cat /proc/self/uid_map
uname -r                                   # node kernel must be 6.3 or later
         0 1879441408      65536

Lab 5: fully harden podinfo and verify it (about 6 minutes, kind lab)

First, record the state before hardening (M4 already added the required restricted settings):
kubectl -n shop exec deploy/api -- sh -c 'id; touch /evil && echo "root fs writable"; touch /tmp/x && echo "tmp writable"'
uid=10001 gid=10001 groups=10001
touch: /evil: Permission denied
tmp writable

A non-root user can no longer write to /, but it can still write to directories such as /tmp and /home/app. An attacker can drop binaries there.

Add a read-only root filesystem + an in-memory emptyDir:
kubectl -n shop patch deploy api --type=json -p='[
 {"op":"add","path":"/spec/template/spec/containers/0/securityContext/readOnlyRootFilesystem","value":true},
 {"op":"add","path":"/spec/template/spec/volumes","value":[{"name":"tmp","emptyDir":{"medium":"Memory","sizeLimit":"64Mi"}},{"name":"data","emptyDir":{"sizeLimit":"128Mi"}}]},
 {"op":"add","path":"/spec/template/spec/containers/0/volumeMounts","value":[{"name":"tmp","mountPath":"/tmp"},{"name":"data","mountPath":"/data"}]}
]'
kubectl -n shop rollout status deploy/api

If earlier hours already defined volumes / volumeMounts for api, the add above will overwrite them. Check first with kubectl -n shop get deploy api -o yaml, and use kubectl edit if needed. /data is the default data directory for podinfo (--data-path).

Verify:
kubectl -n shop exec deploy/api -- sh -c 'id; touch /home/app/x 2>&1; touch /tmp/ok && echo tmp-ok'
kubectl -n shop exec deploy/api -- grep -E 'CapEff|NoNewPrivs|Seccomp:' /proc/1/status
kubectl -n shop exec deploy/api -- wget -qO- localhost:9898/healthz
uid=10001 gid=10001 groups=10001
touch: /home/app/x: Read-only file system
tmp-ok
CapEff:	0000000000000000
NoNewPrivs:	1
Seccomp:	2
{"status":"OK"}

What to check: The error changes from Permission denied (permissions) to Read-only file system (EROFS, at the mount level). Even root cannot write. The app's health checks still pass.

Verify seccomp blocking (run a one-time busybox Pod that satisfies restricted in shop):
kubectl -n shop run sctest --rm -i --restart=Never --image=busybox:1.37 --overrides='{
 "spec":{"securityContext":{"runAsNonRoot":true,"runAsUser":10001,"seccompProfile":{"type":"RuntimeDefault"}},
  "containers":[{"name":"sctest","image":"busybox:1.37","command":["sh","-c","unshare -r id || echo blocked"],
   "securityContext":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}]}}'
unshare: unshare(0x10000000): Operation not permitted
blocked
pod "sctest" deleted

The RuntimeDefault seccomp profile blocks unshare when it tries to create a user namespace. Without CAP_SYS_ADMIN, flags such as CLONE_NEWUSER are rejected, and the call returns EPERM. The wording may differ slightly across busybox versions. Note that kubectl debug --profile=restricted sets fields such as runAsNonRoot but not a UID. Busybox runs as root by default, and the kubelet rejects that, so this step uses --overrides to set the UID explicitly.

Harden web and db the same way (read-only root + writable directories) as an exercise after class. For a reference answer, see step 3 of the Capstone lab.
Clean up: Nothing to clean up. The hardening settings stay in place.

Case 1: Blast radius of a Log4Shell-style RCE

Problem: A Java service has an RCE. The attacker tries to download a cryptominer to /tmp and run it. Approach: Use a read-only root, and mount /tmp as an emptyDir with noexec set through node mount options. (Kubernetes does not natively support setting noexec on emptyDir. Instead, you can combine a read-only root with a dedicated writable directory in place of /tmp, or use AppArmor or SELinux to restrict execution.) Use an egress NetworkPolicy to block access to the internet. Limit: securityContext alone cannot stop an interpreted language from executing code in memory, so add runtime detection (Falco or Defender).

Case 2: Migrating from Docker Hub to a private ACR with signing

Approach: In CI, build with az acr build, then sign with Notation using a Key Vault certificate. Verify the signature at admission. A VAP allows only images with the shopacr.azurecr.io/ prefix, and they must include a digest. Configuration: see the paramKind example in M6 VAP. Limit: Third-party base images must first be imported with az acr import and then re-signed, or exempted in the policy.

Case 3: Enabling user namespaces in a multi-tenant cluster

Approach: New node pools use node images with kernel 6.3 or later and containerd 2.x. On top of PSA restricted, use a VAP to require hostUsers == false. Limit: Some volumes that share UIDs with the node (such as certain NFS shares) do not support idmap mounts. For availability on AKS and the required node image versions, follow the official documentation.

Common errors and fixes

Error: failed to create containerd task: ... open /tmp/...: read-only file system / the app reports "Read-only file system"

Cause: readOnlyRootFilesystem is enabled, but the app needs to write to a directory (cache, pid, or temporary files).

kubectl -n shop logs deploy/web --previous | tail
# nginx-unprivileged needs /tmp (for the pid file, client_temp, and so on)

Fix: Mount an emptyDir at that directory. Do not turn off the read-only root just to make things easier.

open /var/lib/postgresql/data/pgdata: permission denied (db goes into CrashLoopBackOff after hardening)

Cause: The data volume files are not owned by 999, and fsGroup is not set. Or, after drop ALL, the entrypoint script cannot run chown.

kubectl -n shop logs db-0 --previous | tail -5
kubectl -n shop get sts db -o jsonpath='{.spec.template.spec.securityContext}'

Fix: Set fsGroup: 999. (When the kubelet mounts the volume, it changes the group to 999 and adds the setgid bit.) If the historical data ownership is a mess, have an administrator temporarily lower the namespace enforce level to baseline. Run a Job once as root that executes chown -R 999:999, then restore restricted. Record the change in your change log.

Error from server (BadRequest): ... unknown field "spec.template.spec.securityContext.capabilities"

Cause: capabilities, readOnlyRootFilesystem, allowPrivilegeEscalation, and privileged exist only in the container-level securityContext.

kubectl explain pod.spec.securityContext | head -30
kubectl explain pod.spec.containers.securityContext | head -30
Pod stuck in ContainerCreating after setting hostUsers: false: ... idmapped mounts ... not supported

Cause: the node kernel, runtime, or volume filesystem does not support idmap mounts.

kubectl get node -o wide          # check KERNEL-VERSION and CONTAINER-RUNTIME
kubectl describe pod POD | tail -20
Command-line task
1. Without entering a shell, confirm in one command that the web Pod's effective capabilities are empty.
kubectl -n shop exec deploy/web -- grep CapEff /proc/1/status
2. Write the minimal YAML snippet that keeps the container root filesystem read-only while /var/cache/app stays writable.
securityContext: {readOnlyRootFilesystem: true}
volumeMounts: [{name: cache, mountPath: /var/cache/app}]
# Pod level:
volumes: [{name: cache, emptyDir: {}}]
Scenario analysis
A monitoring exporter requires privileged: true to read hardware sensors. How would you handle this?

First confirm the minimum requirement: it usually only needs to read specific /sys paths or device files. Replace privileged with a read-only hostPath plus a specific capability (such as SYS_RAWIO); put it in a separate baseline/privileged namespace and restrict who can deploy into it; use a VAP to require that images in that namespace come from trusted repositories and include a digest; isolate the node (dedicated node pool + taint). Refuse to enable privileged in business namespaces.

Verified teaching videos

▶
Kubernetes Security Best Practices you need to know — TechWorld with Nana
English · Purpose: conceptual review of best practices such as image security and running as non-root

No verified video was found that specifically covers seccomp / capabilities / user namespaces.

Official docs

Video shot script

This course cannot generate video or MP3 directly, so it provides a shot list and narration script.

Shot 1 · 0:00–0:20
Visual: attacker terminal: id shows uid=0.
Narration: The moment the app is compromised, the container configuration decides how far the attacker can go.
Shot 2 · 0:20–1:20
Visual: toggle panel switches turn on one by one: non-root, no privilege escalation, drop ALL, seccomp, read-only root. Each time one turns on, an attack command on the right turns red.
Narration: Each switch is small, but stacked together, they leave the attacker almost no room to move.
Shot 3 · 1:20–2:00
Visual: in /proc/1/status, CapEff is all zeros, NoNewPrivs is 1, and Seccomp 2 is highlighted in turn.
Narration: Don't trust the YAML. Verify from the kernel's point of view.
or score ≥ 70% on the quiz

Module 6 · Admission Control: ValidatingAdmissionPolicy · MutatingAdmissionPolicy · Webhook

36:00 – 44:00 · Policy as code: use CEL to validate and mutate inside the API Server, instead of depending on the availability of an external webhook
8 minVAP GA v1.30MAP GA v1.36Manifest-based Beta v1.37★★★★★
Learning objectives
  • Describe the admission phase order: mutating (built-in plugins → MAP → mutating webhooks) → object schema validation → validating (built-in plugins such as PodSecurity and ResourceQuota → VAP → validating webhooks).
  • Write a ValidatingAdmissionPolicy and a Binding (including validationActions and paramKind), and read the rejection messages.
  • Understand the webhook failurePolicy, timeoutSeconds, and namespaceSelector, and the risk of “a webhook outage blocking the cluster.”
  • Compare VAP / MAP, Kyverno, and OPA Gatekeeper, and understand manifest-based admission control in v1.37 Beta.
Prerequisites: M1 request chain, M4 PSA. Importance: ★★★★★

What: the admission controller is the “last gate before writing to etcd”

Admission applies only to write operations (create, update, delete, connect), not to get/list/watch. It runs in two phases: mutating (can modify the object, for example by injecting a sidecar or setting defaults) and validating (can only allow or reject). If any validating controller rejects the request, the whole request fails.

TypeExamplesWhere it runsLanguagePhase
Built-in pluginsNamespaceLifecycle, LimitRanger, ServiceAccount, DefaultStorageClass, PodSecurity, ResourceQuota, NodeRestrictionIn-process in the API ServerGo (compiled into the binary)Fixed per type
ValidatingAdmissionPolicyForbid :latest, require limitsIn-process in the API ServerCELvalidating (GA in v1.30)
MutatingAdmissionPolicySet defaults, inject labelsIn-process in the API ServerCEL (ApplyConfiguration / JSONPatch)mutating (GA in v1.36, admissionregistration.k8s.io/v1)
Dynamic webhooksKyverno, Gatekeeper, Istio injection, Workload IDHTTPS services inside or outside the clusterAnyMutating/ValidatingWebhookConfiguration

Why: why prefer VAP/MAP

  • No extra point of failure: you don't need to deploy, scale, or upgrade a webhook service, and a crashed webhook Pod won't cause failed calling webhook to block every deployment.
  • Low latency: CEL is evaluated in-process, with no network round trip. CEL has a cost budget, so it can't loop forever.
  • Declarative: the policy is itself an API object, so you can manage it with GitOps and inspect it with kubectl explain.

How: the three objects of VAP

ObjectRoleKey fields
ValidatingAdmissionPolicyDefines “what to check”matchConstraints (resources/operations), matchConditions (CEL pre-filter), validations[].expression / message / messageExpression / reason, variables, paramKind, failurePolicy, auditAnnotations
ValidatingAdmissionPolicyBindingDefines “where and with what action it takes effect”policyName, validationActions: [Deny | Warn | Audit], matchResources.namespaceSelector, paramRef
Parameter resource (optional)Separates the configurable data (allow list) from the logicAny resource, such as a ConfigMap or CRD

Variables available in CEL: object, oldObject (on UPDATE), request (user, operation, namespace), params, namespaceObject, authorizer (for RBAC checks inside a policy), variables.

Key webhook parameters and risks

FieldRecommendationReason
failurePolicyUse Fail for security policies; use Ignore for non-critical mutating changesFail: reject requests when the webhook is unavailable (safe, but can block). Ignore: allow them through (available, but the policy is ineffective).
timeoutSeconds1–5 seconds (default 10, max 30)A slow webhook slows down every apply
namespaceSelector / objectSelectorExclude kube-system and the namespace where the webhook itself runsOtherwise, when the webhook Pod is recreated, it has to pass through itself: deadlock
matchConditions (CEL)Filters on the API Server side firstReduces pointless webhook calls
sideEffects: None, admissionReviewVersions: ["v1"]RequiredSupports dry-run

v1.37 Beta: manifest-based admission control

KEP-5793: webhooks and CEL policies can be loaded from manifest files on the API Server node's disk. Set staticManifestsDir in the plugin configuration of AdmissionConfiguration. These policies take effect from API Server startup, keep working when etcd is unavailable, and can protect the API-based admission objects themselves from being deleted or modified (API-based webhooks and policies cannot intercept operations on their own configuration objects). The files are watched and reloaded automatically; an invalid update keeps the last valid configuration. Limits: object names must end with .static.k8s.io, and they cannot reference API resources (so there is no paramKind, and webhooks can only use a URL). Feature gate ManifestBasedAdmissionControlConfig: Alpha in v1.36, enabled by default in Beta in v1.37. Whether managed clusters (AKS) expose this capability is up to the platform.

When: which one to choose

  • Simple validation (field presence, value ranges, image prefix) → VAP.
  • Simple defaults and labels → MAP.
  • Needs external data (calling an API, checking image signatures), generating resources, or complex reporting → Kyverno / Gatekeeper / a custom webhook.
  • “Floor” policies that cluster admins must not be able to delete (self-managed clusters) → manifest-based.

Comparison with similar tools (versions verified 2026-11)

VAP / MAPKyverno (v1.20.0, 2026-11-12)OPA Gatekeeper (v3.23.1, 2026-08-27)
Policy languageCELYAML (ClusterPolicy) and the newer CEL-based policy types (ValidatingPolicy, MutatingPolicy, GeneratingPolicy, ImageValidatingPolicy, etc.)Rego (ConstraintTemplate), also supports the CEL engine
DeploymentBuilt-inWebhook + controllerWebhook + controller
Mutate / GenerateMAP can mutate; cannot generateYesSupports mutation; no generation
Image signature verificationNot supported (no external calls)Supported (cosign / Notation)Requires Ratify
Background audit of existing resourcesNo (only at request time)PolicyReportAudit controller
AKS integrationNativeSelf-installedAzure Policy for AKS is based on Gatekeeper
Common misconceptions ① “VAP checks existing resources.” No. It only checks subsequent write requests. But UPDATE is checked too, so a historically non-compliant Deployment can no longer be updated (even patches other than scale are rejected). So use Warn/Audit first, then Deny. ② “A field changed by a mutating webhook won't be checked again by validating.” It will be; validating sees the final object. ③ “failurePolicy: Fail is the safest.” If the webhook doesn't exclude kube-system, a single webhook failure can prevent system Pods such as CoreDNS from being recreated.

Architecture diagram: admission chain

authn+authzPassed Mutating phase (can modify the object) Built-in: ServiceAccount, LimitRanger, DefaultStorageClass… MutatingAdmissionPolicy (CEL) MutatingAdmissionWebhook (HTTPS) May be called again when reinvocationPolicy: IfNeeded is set SchemaOpenAPI validation Validating phase PodSecurity, ResourceQuota ValidatingAdmissionPolicy ValidatingWebhook (parallel) Any rejection → request fails etcdPersisted
Figure 6-1: mutating runs serially, validating webhooks run in parallel; manifest-based policies and API policies take effect in the same phase

Data flow: object relationships in VAP

ValidatingAdmissionPolicymatchConstraints: deploymentsvalidations: CEL expressionparamKind: ConfigMap (optional) ValidatingAdmissionPolicyBindingpolicyNamevalidationActions: [Deny]namespaceSelector: shop ConfigMap allowed-registriesallowedPrefixes:shopacr.azurecr.io/,ghcr.io/stefanprodan/ References the policyparamRef
Figure 6-2: one policy can have multiple bindings: Warn in the dev namespace, Deny in the prod namespace

Step-by-step animation: real decisions in the admission chain

RequestCREATE deploy MAPCEL mutation Mutating WHHTTPS POST SchemaOpenAPI PSA warnWorkload VAPCEL evaluation etcd201 Created
Choose a scenario and play.

Core commands and flags

CommandPurposeNotes
kubectl get validatingadmissionpolicies,validatingadmissionpolicybindingsList VAPs and bindingsUse the full resource name where possible. Check whether a short name exists with kubectl api-resources --api-group=admissionregistration.k8s.io
kubectl get validatingadmissionpolicy NAME -o jsonpath='{.status}'Check the type-checking resultstatus.typeChecking.expressionWarnings points out misspelled field names
kubectl get mutatingwebhookconfigurations,validatingwebhookconfigurationsInventory webhooksCheck failurePolicy / namespaceSelector
kubectl apply --dry-run=server -f x.yamlWalk through admission end to end (without saving)The webhook must declare sideEffects: None
kubectl api-resources --api-group=admissionregistration.k8s.ioConfirm the MAP/VAP API is availableIn v1.37, MAP is v1

VAP with parameters: allow only trusted registries

apiVersion: v1
kind: ConfigMap
metadata: {name: allowed-registries, namespace: shop}
data:
  allowedPrefixes: "ghcr.io/stefanprodan/,nginxinc/,docker.io/library/postgres,postgres:,shopacr.azurecr.io/"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata: {name: shop-allowed-registries}
spec:
  failurePolicy: Fail
  paramKind: {apiVersion: v1, kind: ConfigMap}
  matchConstraints:
    resourceRules:
    - apiGroups: [""]
      apiVersions: ["v1"]
      operations: ["CREATE", "UPDATE"]
      resources: ["pods"]
  validations:
  - expression: >-
      object.spec.containers.all(c,
        params.data.allowedPrefixes.split(',').exists(p, c.image.startsWith(p)))
    messageExpression: >-
      'image not from an allowed registry: ' +
      object.spec.containers.map(c, c.image).join(', ')
    reason: Forbidden
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata: {name: shop-allowed-registries}
spec:
  policyName: shop-allowed-registries
  validationActions: [Warn, Audit]          # observe first, then change to [Deny]
  paramRef:
    name: allowed-registries
    namespace: shop
    parameterNotFoundAction: Deny
  matchResources:
    namespaceSelector:
      matchLabels: {kubernetes.io/metadata.name: shop}

This matches Pods, so Pods created by a Deployment are also checked, and rejections appear in the ReplicaSet events. split and join come from the Kubernetes CEL string extension library.

MutatingAdmissionPolicy (v1.36 GA): token auto-mount is disabled by default when not declared

apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicy
metadata: {name: default-no-automount}
spec:
  failurePolicy: Fail
  reinvocationPolicy: Never
  matchConstraints:
    resourceRules:
    - apiGroups: [""]
      apiVersions: ["v1"]
      operations: ["CREATE"]
      resources: ["pods"]
  matchConditions:
  - name: not-set
    expression: "!has(object.spec.automountServiceAccountToken)"
  mutations:
  - patchType: ApplyConfiguration
    applyConfiguration:
      expression: >
        Object{
          spec: Object.spec{
            automountServiceAccountToken: false
          }
        }
---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicyBinding
metadata: {name: default-no-automount}
spec:
  policyName: default-no-automount
  matchResources:
    namespaceSelector:
      matchLabels: {kubernetes.io/metadata.name: shop}

Note: scenarios that need the default token, such as Workload ID, are affected. (Workload ID itself uses a separately injected volume and is not affected, but applications that call the Kubernetes API must explicitly set true.)

Secure defaults for dynamic webhooks

apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata: {name: image-signature-check}
webhooks:
- name: verify.images.example.com
  admissionReviewVersions: ["v1"]
  sideEffects: None
  failurePolicy: Fail
  timeoutSeconds: 5
  clientConfig:
    service: {name: verifier, namespace: policy-system, path: /validate, port: 443}
    caBundle: <BASE64_CA>
  rules:
  - apiGroups: [""]
    apiVersions: ["v1"]
    operations: ["CREATE", "UPDATE"]
    resources: ["pods"]
  namespaceSelector:
    matchExpressions:
    - key: kubernetes.io/metadata.name
      operator: NotIn
      values: ["kube-system", "policy-system"]
  matchConditions:
  - name: skip-node-users
    expression: "!request.userInfo.username.startsWith('system:node:')"

Manifest-based admission (v1.37 Beta, self-managed clusters)

apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
- name: ValidatingAdmissionPolicy
  configuration:
    apiVersion: apiserver.config.k8s.io/v1
    kind: ValidatingAdmissionPolicyConfiguration
    staticManifestsDir: "/etc/kubernetes/admission/validating-policies/"

All .yaml/.yml/.json files in the directory are loaded. Object names must end with .static.k8s.io (for example deny-privileged.static.k8s.io), and a binding can only reference policies in the same manifest set.

Lab 6: VAP that forbids :latest and requires resources.limits (about 7 minutes, kind lab)

First check whether existing workloads comply (to avoid being unable to update after switching to Deny):
kubectl -n shop get deploy,sts -o json | jq -r '.items[] | .kind+"/"+.metadata.name+": "+
  ([.spec.template.spec.containers[] | .image+" limits="+((.resources.limits // {})|keys|join(","))] | join("; "))'
Deployment/api: ghcr.io/stefanprodan/podinfo:6.17.0 limits=cpu,memory
Deployment/web: nginxinc/nginx-unprivileged:1.29-alpine limits=
StatefulSet/db: postgres:17 limits=cpu,memory

If something is missing (such as web), add it first:

kubectl -n shop set resources deploy/web --requests=cpu=50m,memory=64Mi --limits=cpu=200m,memory=128Mi
Create the policy and binding (Warn + Audit first):
mkdir -p ~/k8s-h5/m6 && cd ~/k8s-h5/m6
cat > vap-shop.yaml <<'EOF'
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
  name: shop-image-and-limits
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
    - apiGroups: ["apps"]
      apiVersions: ["v1"]
      operations: ["CREATE", "UPDATE"]
      resources: ["deployments", "statefulsets", "daemonsets"]
  variables:
  - name: containers
    expression: >-
      object.spec.template.spec.containers +
      (has(object.spec.template.spec.initContainers) ? object.spec.template.spec.initContainers : [])
  validations:
  - expression: >-
      variables.containers.all(c,
        c.image.contains('@sha256:') ||
        (c.image.matches(':[A-Za-z0-9_][A-Za-z0-9_.-]*$') && !c.image.endsWith(':latest')))
    message: "Image must use a fixed tag or digest; :latest or a missing tag is not allowed"
    reason: Forbidden
  - expression: >-
      variables.containers.all(c,
        has(c.resources) && has(c.resources.limits) &&
        'cpu' in c.resources.limits && 'memory' in c.resources.limits)
    messageExpression: >-
      'the following containers are missing resources.limits.cpu/memory: ' +
      variables.containers.filter(c, !has(c.resources) || !has(c.resources.limits) ||
        !('cpu' in c.resources.limits) || !('memory' in c.resources.limits)).map(c, c.name).join(', ')
    reason: Invalid
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
  name: shop-image-and-limits
spec:
  policyName: shop-image-and-limits
  validationActions: [Warn, Audit]
  matchResources:
    namespaceSelector:
      matchLabels:
        kubernetes.io/metadata.name: shop
EOF
kubectl apply -f vap-shop.yaml
kubectl get validatingadmissionpolicy shop-image-and-limits -o jsonpath='{.status.typeChecking}'; echo
validatingadmissionpolicy.admissionregistration.k8s.io/shop-image-and-limits created
validatingadmissionpolicybinding.admissionregistration.k8s.io/shop-image-and-limits created
{}

An empty typeChecking means the expression type checks passed; if a field name is misspelled, expressionWarnings appears. Note that the heredoc uses 'EOF', and the && in the YAML is CEL's logical AND.

Observe in Warn mode:
kubectl -n shop create deploy try-latest --image=nginxinc/nginx-unprivileged:latest --dry-run=server
Warning: Validation failed for ValidatingAdmissionPolicy 'shop-image-and-limits' with binding 'shop-image-and-limits': Image must use a fixed tag or digest; :latest or a missing tag is not allowed
Warning: would violate PodSecurity "restricted:latest": ...
deployment.apps/try-latest created (server dry run)
Switch to Deny and verify the rejection messages:
kubectl patch validatingadmissionpolicybinding shop-image-and-limits --type=merge -p '{"spec":{"validationActions":["Deny"]}}'
kubectl -n shop create deploy try-latest --image=nginxinc/nginx-unprivileged:latest
kubectl -n shop create deploy try-notag --image=nginxinc/nginx-unprivileged
kubectl -n shop create deploy try-nolimit --image=nginxinc/nginx-unprivileged:1.29-alpine
validatingadmissionpolicybinding.admissionregistration.k8s.io/shop-image-and-limits patched
error: failed to create deployment: deployments.apps "try-latest" is forbidden: ValidatingAdmissionPolicy 'shop-image-and-limits' with binding 'shop-image-and-limits' denied request: Image must use a fixed tag or digest; :latest or a missing tag is not allowed
error: failed to create deployment: deployments.apps "try-notag" is forbidden: ValidatingAdmissionPolicy 'shop-image-and-limits' with binding 'shop-image-and-limits' denied request: Image must use a fixed tag or digest; :latest or a missing tag is not allowed
error: failed to create deployment: deployments.apps "try-nolimit" is invalid: ValidatingAdmissionPolicy 'shop-image-and-limits' with binding 'shop-image-and-limits' denied request: the following containers are missing resources.limits.cpu/memory: nginx-unprivileged

reason: Invalid returns 422 (“is invalid”), and Forbidden returns 403 (“is forbidden”). The exact wording depends on your kubectl version's output.

Verify that a compliant Deployment passes and that existing workloads can still be updated:
kubectl -n shop rollout restart deploy/api deploy/web
kubectl -n shop rollout status deploy/web
Cleanup: keep the policy for the capstone lab. To delete it: kubectl delete -f vap-shop.yaml.

Case 1: a Gatekeeper webhook failure freezes the cluster

Problem: during a node pool upgrade, all 3 Gatekeeper replicas were evicted. With failurePolicy: Fail and gatekeeper-system not excluded, its own Pods could not be created: deadlock. Fix: exclude its own namespace and kube-system; use a PDB and anti-affinity; migrate the critical simple rules to VAP; prepare a “circuit breaker” (a runbook for kubectl delete validatingwebhookconfiguration …). Limit: deleting the webhook configuration itself requires high privileges and should go through a break-glass process.

Case 2: “must carry a team label” in multi-tenancy

validations:
- expression: "has(object.metadata.labels) && 'team' in object.metadata.labels"
  message: "all workloads must have a team label (used for cost allocation and alert routing)"
- expression: "object.metadata.labels.team == namespaceObject.metadata.labels.team"
  message: "the team label must match the namespace's team label"

Effect: uses namespaceObject to prevent a team from applying another team's label to its resources. Limit: the second expression requires that both the namespace and the object have the label first (protect it with matchConditions or has()).

Case 3: migrating custom rules from the PSP era

Fix: PSA covers the standard items. Custom PSP items such as “allowed hostPath prefixes” and “forbidden specific sysctls” are rewritten with VAP. Run Audit for a week first, count the hits through the validation.policy.admission.k8s.io/validation_failure annotation in the audit log, then switch to Deny.

Common errors and fixes

Internal error occurred: failed calling webhook "x.example.com": failed to call webhook: Post "https://svc.ns.svc:443/validate?timeout=10s": context deadline exceeded

Cause: the webhook service is unreachable or too slow, and failurePolicy: Fail is set.

kubectl get validatingwebhookconfiguration x -o jsonpath='{.webhooks[*].failurePolicy} {.webhooks[*].timeoutSeconds}'
kubectl -n NS get endpointslices -l kubernetes.io/service-name=SVC
kubectl -n NS get pods -o wide

Fix: restore the webhook Pod. In an emergency, temporarily change failurePolicy to Ignore or delete the configuration (and record the change). Long term: exclude system namespaces, shorten the timeout, and migrate to VAP.

ValidatingAdmissionPolicy 'x' with binding 'y' denied request: failed expression: ...

Cause: the policy has no message, so only the failing expression is shown. Read the expression to find the violated condition, then add a message / messageExpression to the policy.

The policy seems not to work: a violating Deployment is still created successfully
kubectl get validatingadmissionpolicybinding -o yaml | grep -A3 -E "policyName|validationActions|namespaceSelector"
kubectl get validatingadmissionpolicy x -o jsonpath='{.status}'

Common causes: no Binding was created (a Policy alone does nothing); validationActions is Warn/Audit; namespaceSelector doesn't match; apiGroups is "" instead of apps; or an expression references a field that may not exist, causing a runtime error with failurePolicy: Ignore.

no such key: limits / evaluation error (CEL runtime error)

Cause: the expression accesses the optional field c.resources.limits.cpu directly, which errors when the field is absent. Fix: check first with has() or in, or use the ?. optional syntax (follow the official CEL docs).

Command-line task
1. Without saving anything, run a Deployment through all admission controllers and see whether it gets rejected.
kubectl apply --dry-run=server -f deploy.yaml
2. Change the binding from Deny back to warn-only.
kubectl patch validatingadmissionpolicybinding shop-image-and-limits --type=merge -p '{"spec":{"validationActions":["Warn","Audit"]}}'
Scenario analysis
You wrote a VAP that requires Deployments to set limits, and in M8 you configured a LimitRange with default limits for shop. A developer complains: “LimitRange fills in limits automatically, so why is the Deployment still rejected?”

LimitRange is an admission plugin that acts on Pods (it fills in defaults when a Pod is created) and does not modify the Deployment object. VAP matches the Deployment, so it can't see the defaults. Options: ① keep the VAP and require explicit declarations (recommended, since the config doubles as documentation); ② match Pods instead (LimitRanger runs first in the mutating phase, so VAP sees the filled-in values); ③ use MAP to fill in defaults on the Deployment.

Verified teaching videos

No verified video found. (KubeCon EU 2025 “EVAPorating Kubernetes Security Risk: Adopting Validating Admission Policy,” the DevOps Toolkit admission controller series, and others were found, but I could not directly verify their YouTube links.) Refer to the official tutorials and the shot script below.

Official docs

Video shot script

This course cannot generate video or MP3 directly, so it provides a shot list and narration script.

Shot 1 · 0:00–0:30
Visual: the request moves down the admission chain. The mutating section is orange, and the validating section is green.
Narration: Admission control is the last gate before writing to etcd. Change first, then validate.
Shot 2 · 0:30–1:20
Visual: the VAP YAML in the editor, with the CEL expression highlighted word by word. A denied request message appears in the terminal.
Narration: One line of CEL is enough to forbid the latest tag, without deploying any webhook.
Shot 3 · 1:20–2:10
Visual: the webhook Pod turns gray, and every kubectl apply hangs with context deadline exceeded.
Narration: An external webhook is a new point of failure. Exclude system namespaces, set a short timeout, and use built-in policies whenever you can.
or score ≥ 70% on the quiz

Module 7 · Secret Security and External Secrets

44:00 – 52:00 · base64 is not encryption: encryption at rest, KMS v2, Key Vault CSI, External Secrets, and secrets in GitOps
8 minKMS v2 GA v1.29SecretProviderClass v1ESO external-secrets.io/v1★★★★★
Learning objectives
  • Show that Secrets are plaintext in etcd by default (only base64/protobuf-encoded), and that after enabling EncryptionConfiguration, etcdctl shows the k8s:enc: prefix.
  • Compare the aescbc / aesgcm / secretbox / kms v2 providers, and learn the correct order for key rotation.
  • Understand AKS's KMS + Key Vault options (legacy KMS and the new KMS data encryption).
  • Choose between “getting keys into the cluster” and “keeping keys outside the cluster”: Secrets Store CSI Driver, External Secrets Operator, Sealed Secrets, and SOPS.
Prerequisites: M2 (risk of listing Secrets), M3 (Workload ID). Importance: ★★★★★

What: where Secrets actually live, and in what form

The data field of a Secret object is base64-encoded. This only carries binary data and provides no confidentiality at all. The API Server serializes the object (protobuf) and writes it to etcd at /registry/secrets/<ns>/<name>. By default there is no encryption at rest: anyone who can read the etcd data directory, an etcd snapshot backup, or a node disk image can read the plaintext.

Why: the threat surface

Leak pathControls
RBAC: get/list/watch secrets, or create Pods and mount themM2 least privilege, M6 VAP to restrict mounts
etcd data files / snapshots / backupsEncryptionConfiguration / KMS v2 (this module)
Inside the Pod: environment variables appear in crash dumps, /proc/1/environ, and debug outputMount as files instead of env; read-only root
Plaintext YAML in a Git repositorySealed Secrets, SOPS, ESO (only references stored in Git)
Node: kubelet writes Secret volumes to tmpfsNode isolation; restrict which nodes sensitive workloads can be scheduled onto

How: encryption-at-rest providers

ProviderAlgorithmKey storageAssessment
identityNo encryption—Default; keep it at the end of the list to read old data
aescbcAES-CBC + PKCS#7In the config file (plaintext!)Official docs note a padding oracle risk; not recommended for new deployments
aesgcmAES-GCMIn the config fileFast, but keys must be rotated every 200,000 writes (random nonce limit)
secretboxXSalsa20 + Poly1305In the config fileA better choice among local key schemes
kms v2 (GA in v1.29)Envelope encryption: a DEK is generated for each write (or as needed) to encrypt the data, and the DEK is encrypted by a KEK in an external KMSExternal KMS (Azure Key Vault, HSM)Recommended for production. KMS v1 is deprecated and disabled by default.

The weakness of local key schemes (aescbc/aesgcm/secretbox) is that the encryption key is written to a file on the control plane node. Anyone who gets the node disk gets both the key and the ciphertext. These schemes mainly protect against “only the etcd backup was leaked.” KMS v2 keeps the KEK in Key Vault/HSM, and supports auditing and revocation.

How it takes effect and how it is rotated

  1. kube-apiserver flag --encryption-provider-config=FILE. In the providers list, the first entry is used for writes; all providers can be used for reads.
  2. After enabling, only newly written objects are encrypted. Existing objects must be rewritten: kubectl get secrets -A -o json | kubectl replace -f -, or use Storage Version Migration (storagemigration.k8s.io/v1, GA in v1.37).
  3. Rotation: ① add the new key as the second entry in the list and restart all API Servers (so they can all read it); ② move the new key to the first position and restart; ③ rewrite all Secrets; ④ delete the old key and restart. With multiple control plane instances, wait for every instance to finish each step.
  4. v1.37 Beta: can identify and delete resources that “cannot be decrypted” (for example, after a key is lost), to help with recovery.

Keep keys outside the cluster

OptionPrincipleCreates a K8s Secret?Use case
Secrets Store CSI Driver + Azure Key Vault providerWhen the Pod starts, the CSI driver uses Workload ID to pull from Key Vault and mounts the values as filesNo by default; optional secretObjects syncs them to a SecretAKS add-on azure-keyvault-secrets-provider; keys don't go into etcd
External Secrets Operator (v2.15.0, 2026-11-10)A controller periodically syncs from external storage and generates a K8s SecretYesMulti-cloud or multiple backends; needs env references or a third-party chart
Sealed SecretsEncrypted with the cluster controller's public key. Git stores a SealedSecret, which is decrypted into a Secret inside the cluster.YesPure GitOps, no external secret store
SOPS (+ age / Azure Key Vault key)Encrypts the values in YAML within Git; Flux/Argo plugins decrypt themYesGitOps, integrated with Key Vault

When

  • Any cluster should enable encryption at rest: on AKS, use KMS (platform key or customer key); for self-managed clusters, use KMS v2.
  • If the application can read files → CSI driver (keys never enter etcd). If it must use env or a Secret → ESO.
  • GitOps repo → never commit plaintext Secrets.

Comparison with similar technologies

K8s Secret + KMS v2CSI + Key VaultESO
Source of truthetcdKey VaultKey Vault (the synced copy lives in etcd)
RotationUpdate the Secret manuallyAutomatic rotation can be enabled (polling interval)refreshInterval
When Key Vault is unavailableNot affectedNew Pods can't startAlready-synced Secrets still work
Common misconceptions ① “With etcd encryption on, kubectl get secret -o yaml no longer shows plaintext.” Encryption applies only at the storage layer. The API decrypts automatically on read, and RBAC is still the first line of defense. ② “With list permission, you can only see names.” List returns full objects, including data. ③ “Setting a Secret to immutable: true makes it more secure.” It mainly prevents accidental changes and reduces watch pressure on the API Server. It is not encryption.

Architecture diagram: KMS v2 envelope encryption

kubectl createsecret db-cred kube-apiserver ① Serialize the object (protobuf) ② Encrypt the data with a DEK (AES-GCM) ③ The KMS plugin encrypts the DEK with a KEK (cached) gRPC KMS pluginUnix socket Key VaultKEK never leaves etcd /registry/secrets/shop/db-credk8s:enc:kms:v2:azurekmsprovider:[encrypted DEK + ciphertext + annotations]
Figure 7-1: etcd holds only ciphertext and the encrypted DEK. Without the KEK in Key Vault, the backup cannot be decrypted.

Data flow: CSI driver mounts from Key Vault

kubelet mounts the volumedriver: secrets-store CSI driverReads the SecretProviderClass Azure providerSA token → Entra token Key VaultGET secret Pod file/mnt/secrets-store/…
Figure 7-2: key values don't pass through the API Server or etcd (unless secretObjects sync is configured)

Step-by-step animation: etcd encrypted write and read

Choose an encryption provider and play the “write” and “read” flows. The terminal shows the matching raw etcdctl output (a hex excerpt) and the API Server behavior.

kubectlcreate / get kube-apiservertransformer Key sourceNone etcd/registry/secrets AttackerObtains an etcd snapshot
Choose a provider and play.

Core commands and flags

CommandPurposeNotes
kubectl create secret generic N --from-literal=k=vCreate a Secret--from-file. In production, avoid plaintext on the command line (it goes into shell history).
etcdctl get /registry/secrets/NS/NAME | hexdump -CView raw bytes in etcdRequires etcd client certificates
kubectl get secrets -A -o json | kubectl replace -f -Rewrite all Secrets (after encryption takes effect or after rotation)The “object has been modified” error can be ignored; retry
az aks update --kms-infrastructure-encryption EnabledAKS new KMS data encryption (platform-managed key)Preview feature. Requires the aks-preview extension and the KMSPMKPreview feature registration; K8s ≥ 1.33
az aks update --enable-azure-keyvault-kms --azure-keyvault-kms-key-id …AKS KMS (customer-managed key)--azure-keyvault-kms-key-vault-network-access Public|Private
az aks enable-addons --addons azure-keyvault-secrets-providerEnable the Key Vault CSI add-on--enable-secret-rotation enables rotation

EncryptionConfiguration (self-managed cluster)

apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
- resources: ["secrets"]
  providers:
  - kms:                                  # production: KMS v2
      apiVersion: v2
      name: azurekmsprovider
      endpoint: unix:///opt/azurekms.socket
      timeout: 3s
  - secretbox:                            # or a local key (lab)
      keys:
      - name: key1
        secret: <base64 of a 32-byte random value>
  - identity: {}                          # read previously unencrypted data

AKS: KMS and Key Vault

# Legacy KMS (customer-managed key, public Key Vault): requires a user-assigned identity, and that identity needs the Key Vault Crypto User role
az aks update -g rg-k8s-lab -n aks-lab \
  --enable-azure-keyvault-kms \
  --azure-keyvault-kms-key-vault-network-access "Public" \
  --azure-keyvault-kms-key-id $KEY_ID
kubectl get secrets --all-namespaces -o json | kubectl replace -f -

# New KMS data encryption (preview, K8s 1.33+): platform-managed key, automatic rotation
az extension add --name aks-preview
az feature register --namespace Microsoft.ContainerService --name KMSPMKPreview
az aks update -g rg-k8s-lab -n aks-lab --kms-infrastructure-encryption Enabled
az aks show -g rg-k8s-lab -n aks-lab --query securityProfile

Microsoft Learn labels the first one as the legacy experience and recommends the new KMS data encryption for 1.33+ new clusters (platform-managed key, or customer-managed key with automatic rotation, with no need to manually rewrite Secrets). The new experience is currently labeled preview and is not recommended for production. Deleting the key or Key Vault that KMS uses makes the Secrets unrecoverable.

Secrets Store CSI Driver (Workload ID method)

apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata: {name: shop-kv, namespace: shop}
spec:
  provider: azure
  parameters:
    usePodIdentity: "false"
    clientID: "<UAMI_CLIENT_ID>"
    keyvaultName: "<KV_NAME>"
    tenantId: "<TENANT_ID>"
    objects: |
      array:
        - |
          objectName: db-password
          objectType: secret
---
# Pod fragment (requires SA annotation + label azure.workload.identity/use: "true")
volumes:
- name: kv
  csi:
    driver: secrets-store.csi.k8s.io
    readOnly: true
    volumeAttributes: {secretProviderClass: shop-kv}

External Secrets Operator (check the ESO docs for the API version)

apiVersion: external-secrets.io/v1
kind: SecretStore
metadata: {name: azure-kv, namespace: shop}
spec:
  provider:
    azurekv:
      authType: WorkloadIdentity
      vaultUrl: "https://<KV_NAME>.vault.azure.net"
      serviceAccountRef: {name: eso-kv}
---
apiVersion: external-secrets.io/v1
kind: ExternalSecret
metadata: {name: db-credentials, namespace: shop}
spec:
  refreshInterval: 1h
  secretStoreRef: {kind: SecretStore, name: azure-kv}
  target: {name: db-credentials, creationPolicy: Owner}
  data:
  - secretKey: password
    remoteRef: {key: db-password}

GitOps: Sealed Secrets and SOPS

kubectl create secret generic db-credentials -n shop --from-literal=password=x --dry-run=client -o yaml \
  | kubeseal --format yaml > db-credentials.sealed.yaml       # safe to commit to Git
sops --encrypt --azure-kv "https://<KV>.vault.azure.net/keys/sops/<VERSION>" \
  --encrypted-regex '^(data|stringData)$' secret.yaml > secret.enc.yaml

Lab 7: Enable encryption at rest on kind and verify with etcdctl (about 8 minutes)

Risk warning This lab modifies the kube-apiserver static Pod manifest on the kind control plane. A misconfiguration can prevent the API Server from starting, which makes every kubectl command fail. The steps include backup and rollback commands. Do not run this on a shared cluster.
Set up the etcdctl alias and confirm the “plaintext”:
ETCD="kubectl -n kube-system exec etcd-lab-control-plane -- etcdctl --endpoints=https://127.0.0.1:2379 \
  --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key"
kubectl -n shop create secret generic enc-before --from-literal=password=PlainText-123
$ETCD get /registry/secrets/shop/enc-before | hexdump -C | head -12
00000000  2f 72 65 67 69 73 74 72  79 2f 73 65 63 72 65 74  |/registry/secret|
00000010  73 2f 73 68 6f 70 2f 65  6e 63 2d 62 65 66 6f 72  |s/shop/enc-befor|
00000020  65 0a 6b 38 73 00 0a 0c  0a 02 76 31 12 06 53 65  |e.k8s.....v1..Se|
...
000000b0  77 6f 72 64 12 0d 50 6c  61 69 6e 54 65 78 74 2d  |word..PlainText-|
000000c0  31 32 33 1a 06 4f 70 61  71 75 65 1a 00 22 00 0a  |123..Opaque.."..|

k8s\x00 is the protobuf encoding prefix, and PlainText-123 is directly visible. There is no encryption.

Generate the encryption config and copy it to the control plane node:
mkdir -p ~/k8s-h5/m7 && cd ~/k8s-h5/m7
cat > encryption-config.yaml <<EOF
apiVersion: apiserver.config.k8s.io/v1
kind: EncryptionConfiguration
resources:
- resources: ["secrets"]
  providers:
  - aescbc:
      keys:
      - name: key1
        secret: $(head -c 32 /dev/urandom | base64)
  - identity: {}
EOF
docker cp encryption-config.yaml lab-control-plane:/etc/kubernetes/pki/encryption-config.yaml
docker exec lab-control-plane cp /etc/kubernetes/manifests/kube-apiserver.yaml /root/kube-apiserver.yaml.bak

Why /etc/kubernetes/pki/: kubeadm already mounts this directory read-only into the kube-apiserver container as a hostPath, so you don't need to change volumes. The backup must not go in the manifests directory, because kubelet treats every file there as a static Pod. This lab uses aescbc only so the prefix is easy to recognize. For new deployments, prefer secretbox or KMS v2.

Add the flag to kube-apiserver and wait for the restart:
docker exec lab-control-plane sed -i \
  's|^    - kube-apiserver$|    - kube-apiserver\n    - --encryption-provider-config=/etc/kubernetes/pki/encryption-config.yaml|' \
  /etc/kubernetes/manifests/kube-apiserver.yaml
docker exec lab-control-plane grep -n encryption-provider /etc/kubernetes/manifests/kube-apiserver.yaml
# kubelet recreates the API Server after it detects the manifest change, about 30–60 seconds
until kubectl get --raw /readyz >/dev/null 2>&1; do echo waiting; sleep 5; done; echo ready
17:    - --encryption-provider-config=/etc/kubernetes/pki/encryption-config.yaml
waiting
waiting
ready

Rollback (if the API Server won't start): docker exec lab-control-plane cp /root/kube-apiserver.yaml.bak /etc/kubernetes/manifests/kube-apiserver.yaml. Find the cause with docker exec lab-control-plane crictl ps -a | grep apiserver and crictl logs <ID>.

Verify that new Secrets are encrypted and that old Secrets need rewriting:
kubectl -n shop create secret generic enc-after --from-literal=password=PlainText-456
$ETCD get /registry/secrets/shop/enc-after | hexdump -C | head -4
$ETCD get /registry/secrets/shop/enc-before | head -c 120 | strings | head -3
kubectl -n shop get secrets -o json | kubectl replace -f -
$ETCD get /registry/secrets/shop/enc-before | head -c 80 | strings | head -2
kubectl -n shop get secret enc-after -o jsonpath='{.data.password}' | base64 -d; echo
00000000  2f 72 65 67 69 73 74 72  79 2f 73 65 63 72 65 74  |/registry/secret|
00000010  73 2f 73 68 6f 70 2f 65  6e 63 2d 61 66 74 65 72  |s/shop/enc-after|
00000020  0a 6b 38 73 3a 65 6e 63  3a 61 65 73 63 62 63 3a  |.k8s:enc:aescbc:|
00000030  76 31 3a 6b 65 79 31 3a  ...                      |v1:key1:........|
/registry/secrets/shop/enc-before
k8s
...
/registry/secrets/shop/enc-before
k8s:enc:aescbc:v1:key1:
PlainText-456

Checkpoint: etcd shows the k8s:enc:aescbc:v1:key1: prefix followed by ciphertext. Reading through the API still returns plaintext (transparent decryption), and RBAC remains the first line of defense.

(Optional) Key rotation drill: add key2 to the config, placed after key1 → restart the API Server → move key2 to the first position → restart again → rewrite with kubectl replace → delete key1 → restart. Watch the etcd prefix change from key1 to key2. Note: when you change only the encryption config file, kubelet does not recreate the API Server (the manifest content hasn't changed), and by default the API Server does not reload the file automatically (unless you set --encryption-provider-config-automatic-reload=true). To trigger a restart, temporarily move the manifest out and then back in:
docker exec lab-control-plane sh -c 'mv /etc/kubernetes/manifests/kube-apiserver.yaml /root/apiserver.tmp && sleep 20 && mv /root/apiserver.tmp /etc/kubernetes/manifests/kube-apiserver.yaml'
until kubectl get --raw /readyz >/dev/null 2>&1; do sleep 5; done; echo ready
Cleanup: keeping the encryption config is fine (it doesn't affect later labs). Delete the demo Secrets with kubectl -n shop delete secret enc-before enc-after. To fully revert: first change the providers order so identity comes first and rewrite all Secrets, then restore the backup manifest. Deleting the flag directly makes already-encrypted Secrets unreadable.

Case 1: an etcd backup uploaded to a public storage bucket

Problem: a self-managed cluster's etcd snapshot was accidentally placed in a public Blob container. Impact analysis: with KMS v2 enabled, Secrets in the snapshot cannot be decrypted without the Key Vault KEK, but unencrypted resources such as ConfigMaps still leak. Fix: revoke Blob access, rotate the KEK, and assess whether ConfigMaps contain sensitive data (they should not). Lesson: also add sensitive CRDs other than configmaps, such as certificate or token CRDs, to the resources list.

Case 2: zero-downtime database password rotation

Fix: create a new version in Key Vault → ESO (refreshInterval: 15m) or CSI (with rotation enabled) syncs the new value in → the application hot-reloads the file, or a Reloader-style tool triggers a rolling restart → the database uses a dual-password transition period. Limits: Secrets injected as environment variables are not hot-updated and require a Pod restart. CSI mounts that use subPath are not updated.

Case 3: plaintext accidentally committed to the GitOps repo

Fix: rotate the leaked credentials immediately (cleaning up Git history does not undo the leak). Add secret scanning to CI (gitleaks, etc.). Require that the repo contains only SealedSecret or SOPS-encrypted files, or ExternalSecret references. Use a VAP to reject Secret objects submitted by the GitOps controller that lack a specific annotation.

Common errors and fixes

The connection to the server 127.0.0.1:xxxxx was refused (after editing the kube-apiserver manifest)

Cause: the API Server failed to start. The encryption config file path is outside the container's mounts, there is a YAML syntax error, or the key length is not 16/24/32 bytes.

docker exec lab-control-plane crictl ps -a | grep kube-apiserver
docker exec lab-control-plane sh -c 'crictl logs $(crictl ps -a --name kube-apiserver -q | head -1) 2>&1 | tail -20'
docker exec lab-control-plane cp /root/kube-apiserver.yaml.bak /etc/kubernetes/manifests/kube-apiserver.yaml   # rollback
Internal error occurred: unable to transform key "/registry/secrets/...": no matching prefix found / failed to decrypt

Cause: data in etcd was encrypted with a key that is no longer in the current config. The key was removed too early during rotation, or the API Servers have inconsistent configs.

Fix: add the old key back to the providers list (it doesn't need to be first), restart, rewrite all Secrets, and only then delete it. v1.37 Beta can identify and delete undecryptable resources, for cases where recovery is truly impossible.

MountVolume.SetUp failed for volume "kv" : rpc error: ... failed to get secret objectType:secret, objectName:db-password ... StatusCode=403

Cause: Key Vault denied the request. Possible reasons: the UAMI lacks the Key Vault Secrets User role, the role assignment has not propagated yet (up to 10 minutes), the Key Vault firewall blocks the request, or the clientID/tenantId in the SecretProviderClass is wrong.

kubectl -n shop describe pod POD | tail -15
az role assignment list --scope $KV_ID -o table
kubectl -n kube-system logs -l app=secrets-store-provider-azure --tail=50
ExternalSecret status SecretSyncedError: could not get secret data from provider
kubectl -n shop describe externalsecret db-credentials
kubectl -n shop get secretstore azure-kv -o yaml | grep -A5 status

Check the SecretStore identity (the Workload ID SA annotation, and the FIC subject must be the SA that ESO uses), and check that the name in Key Vault matches remoteRef.key.

Command-line task
1. Without using any tool other than jsonpath, read the plaintext password from the db-credentials Secret.
kubectl -n shop get secret db-credentials -o jsonpath='{.data.password}' | base64 -d

This shows that having get secrets permission means having the plaintext.

2. After enabling encryption, rewrite only the Secrets in the shop namespace.
kubectl -n shop get secrets -o json | kubectl replace -f -
Scenario analysis
The security team requires that “no database password may be stored in Kubernetes,” but the shop db uses the POSTGRES_PASSWORD environment variable. Propose a workable solution.

The postgres image supports POSTGRES_PASSWORD_FILE. Use the Secrets Store CSI Driver with Workload ID to mount the password from Key Vault as a file (such as /mnt/secrets-store/db-password), and set POSTGRES_PASSWORD_FILE to point to it. Don't configure secretObjects, so no such Secret exists in etcd. The api side likewise reads it as a file. Trade-off: new Pods can't start when Key Vault is unavailable, so you need to monitor the availability of the CSI driver and Key Vault.

Verified teaching videos

▶
Kubernetes Security Best Practices you need to know — TechWorld with Nana
English · Purpose: conceptual review of the Secret encryption and etcd security chapter

Found community videos related to External Secrets Operator, but could not verify that their YouTube titles match their channels, so they are not listed.

Official docs

Video shot script

This course cannot generate video or MP3 directly, so it provides a shot list and narration script.

Shot 1 · 0:00–0:30
Visual: a base64 string is decoded into the plaintext password in one step.
Narration: Base64 is not encryption. Anyone can reverse it.
Shot 2 · 0:30–1:20
Visual: PlainText is highlighted in the hexdump. After encryption is enabled, it becomes k8s:enc:aescbc:v1:key1 followed by gibberish.
Narration: With encryption at rest enabled, only ciphertext is left in etcd.
Shot 3 · 1:20–2:10
Visual: envelope encryption animation. The DEK is placed in an envelope, and the envelope is locked by the KEK in Key Vault.
Narration: In production, use KMS v2. The master key never leaves Key Vault.
Shot 4 · 2:10–2:40
Visual: the CSI driver mounts the key from Key Vault directly into the Pod, and the etcd icon is crossed out.
Narration: Going one step further, keep the keys out of the cluster entirely.
or score ≥ 70% on the quiz

Module 8 · Multi-tenancy: Quota · LimitRange · Isolation Layers · Audit

52:00 – 60:00 · A namespace is a “soft” tenant boundary. Stack the controls from the first 7 modules, then use audit logs to prove they work.
8 minResourceQuota / LimitRange v1audit.k8s.io/v1★★★★☆
Learning objectives
  • List the control layers of soft multi-tenancy: Namespace + RBAC + NetworkPolicy + ResourceQuota + LimitRange + PSS + admission policies + node isolation. Also know when you need vCluster or separate clusters (hard multi-tenancy).
  • Write a ResourceQuota (compute resources, object counts, scopes / PriorityClass) and a LimitRange (default requests/limits, min/max).
  • Write an Audit Policy (None / Metadata / Request / RequestResponse, and stages). Enable auditing on kind, and collect kube-audit-admin through diagnostic settings on AKS.
  • Use the interactive troubleshooting tree to locate 401 / 403 / PSA / VAP / webhook / quota / Workload ID issues.
Prerequisites: M1–M7, hour 2 requests/limits, hour 3 NetworkPolicy. Importance: ★★★★☆

What: two forms of multi-tenancy

FormTypical scenarioTrust assumptionImplementation
Soft multi-tenancyMultiple teams in the same company (the shop team, the payments team)Tenants are largely trusted; the main concerns are accidental mistakes and blast radiusOne or more namespaces per team, plus the stacked controls in this module
Hard multi-tenancySaaS running code and untrusted workloads for external customersTenants do not trust each other, so malicious escapes must be preventedvCluster (a separate virtual control plane per tenant) + sandboxed runtime + dedicated node pools; or a separate cluster per tenant

Why: what namespaces alone do not isolate

A namespace is only a name scope and a point to attach policies. By default, Pods in different namespaces can reach each other over the network, nodes share a kernel, cluster-wide resources (CRDs, ClusterRoles, PVs, Nodes, admission webhooks) are global, and one team can consume the entire cluster's CPU. So you must stack controls:

LayerControlCovered in
Identity and accessTeam groups → RoleBinding (admin / custom), no ClusterRoleBindingM1, M2
NetworkDefault-deny ingress/egress, plus explicit allows (including DNS)Hour 3
ResourcesResourceQuota (totals) + LimitRange (defaults and bounds per Pod/container)This module
Workload securityPSA restricted + securityContextM4, M5
Organizational policyVAP: image sources, labels, forbid modifying tolerations / nodeSelectorM6
SecretsPer-team Key Vault / UAMI, with the FIC subject scoped precisely to the SAM3, M7
NodesDedicated node pools + taints; use policy to enforce nodeSelector/tolerations on tenant PodsThis module
TraceableAudit logsThis module

How: ResourceQuota and LimitRange

  • ResourceQuota (validating admission + controller accounting): limits the total resources in a namespace, such as requests.cpu, limits.memory, requests.storage, pods, services.loadbalancers, and count/deployments.apps. Once a quota is set on cpu/memory, every new Pod must declare matching requests/limits, or it is rejected. Scopes: BestEffort, NotBestEffort, Terminating, NotTerminating, PriorityClass (scopeSelector), CrossNamespacePodAffinity.
  • LimitRange (mutating + validating admission): fills in default requests/limits for containers that don't declare them, and validates min / max / maxLimitRequestRatio. It can also limit PVC size. It applies only at Pod creation. It does not modify existing Pods or Deployment objects.
  • Together: LimitRange ensures every Pod has requests/limits, so Quota can count them.

How: audit logs

LevelWhat is recordedApplies to
NoneNot recordedHealth checks and high-frequency read-only system components
MetadataUser, verb, resource, namespace, response code, timestamp, source IP, and authorization decision annotations, but not request or response bodiesSecrets, ConfigMaps, TokenReviews (to avoid writing secrets into logs)
RequestMetadata + request bodyWrite operations in business namespaces
RequestResponsePlus response bodyCritical operations such as RBAC changes. High volume, so use with care.

Stages: RequestReceived → ResponseStarted (only for long-running connections such as watch) → ResponseComplete → Panic. Use omitStages: ["RequestReceived"] to cut log volume roughly in half. Rules are matched in order, and the first matching rule wins. Backends: log (file or stdout) and webhook.

When

  • Every business namespace should have a Quota, a LimitRange, a default-deny NetworkPolicy, and PSA labels.
  • Untrusted external code → hard multi-tenancy.
  • Auditing: must be enabled on production clusters. On AKS, prefer kube-audit-admin (it excludes get/list, at a much lower cost).

Comparison with similar technologies

Namespace (soft)vClusterSeparate cluster
Control planeSharedA virtual API Server per tenant (running in a host namespace); workloads sync to the host clusterSeparate
Can tenants install CRDs or have cluster-admin?NoYes (within the virtual cluster)Yes
Node/kernel isolationNo (unless node pools are isolated)Not by default (can be combined with dedicated nodes or sandboxes)Yes
Cost and operationsLowestMediumHighest (AKS Fleet Manager can help manage multiple clusters)
Common misconceptions (1) "Setting a ResourceQuota prevents nodes from being overloaded." Quotas count requests and limits, not actual usage. At the node level you also need sensible requests and kubelet eviction settings. (2) "LimitRange fixes Pods that are already running." It does not. (3) "Setting audit logging to RequestResponse is the safest option." It writes Secret contents into the log, which leaks them, and the volume is huge.

Architecture diagram: control overlays for one team tenant

Namespace shop (team=shop) RBAC: dev-team / ci PSA restricted NetworkPolicy default deny ResourceQuota: cpu 4/8 · mem 8Gi/16Gi · pods 30 LimitRange: default 200m/256Mi · max 2/2Gi VAP: pinned tags · limits · trusted registries Workload ID: UAMI → this team's Key Vault web · api · db (hardened Pods) Cluster level (platform team)CRDs, ClusterRoles, webhooks, PVsAudit policy → logs / Log Analyticsetcd encryption / KMSTenants cannot modify Node pools (optional isolation)taint: team=shop:NoScheduleVAP enforces nodeSelector/tolerationsHard isolation: vCluster / separate clusters
Figure 8-1: Soft multi-tenancy = a stack of "default deny" controls; if any layer is missing, cross-tenant impact follows.

Flow chart: how one request produces an audit event

Request arrivesstage RequestReceived Match Policy rulesFirst match → level authn/authz/admissionAdd annotations (decision, PSA) ResponseCompleteresponseStatus.code Backendlog file / webhook
Figure 8-2: Rejected requests (401/403) are audited too, which is the basis for tracing attacks.

Interactive: ResourceQuota + LimitRange simulator

Simulated shop namespace: quota requests.cpu=4, limits.cpu=8, requests.memory=8Gi, limits.memory=16Gi, pods=30, services.loadbalancers=0. Toggle the LimitRange switch, run operations, and see how admission fills in default values, how quota accumulates, and the real errors and audit events returned.

$ kubectl describe quota shop-compute -n shop

Core commands and flags

CommandPurposeNotes
kubectl describe quota -n NSView quota Used / HardQuota usage is updated asynchronously by the controller, so it can lag by a few seconds.
kubectl describe limitrange -n NSView defaults and limits—
kubectl create quota NAME --hard=pods=10,requests.cpu=2 -n NSCreate a quota imperativelyUse YAML for complex quotas
kubectl get pod POD -o jsonpath='{.spec.containers[*].resources}'Confirm the defaults LimitRange filled in—
kubectl -n kube-system logs kube-apiserver-lab-control-plane | grep '"kind":"Event"'kind: view audit events written to stdoutSee the lab
az monitor diagnostic-settings create … --logs '[{"category":"kube-audit-admin","enabled":true}]'AKS: send audit logs to Log Analyticskube-audit includes everything (including get/list), so the volume is large.

ResourceQuota (compute + object counts + PriorityClass scope)

apiVersion: v1
kind: ResourceQuota
metadata: {name: shop-compute, namespace: shop}
spec:
  hard:
    requests.cpu: "4"
    requests.memory: 8Gi
    limits.cpu: "8"
    limits.memory: 16Gi
    pods: "30"
    persistentvolumeclaims: "5"
    requests.storage: 50Gi
    services.loadbalancers: "0"
    services.nodeports: "0"
    count/secrets: "30"
    count/deployments.apps: "20"
---
apiVersion: v1
kind: ResourceQuota
metadata: {name: shop-critical-pods, namespace: shop}
spec:
  hard:
    pods: "3"
  scopeSelector:
    matchExpressions:
    - scopeName: PriorityClass
      operator: In
      values: ["system-cluster-critical", "shop-critical"]

The second quota limits shop to at most 3 Pods that use high-priority PriorityClasses, so a tenant cannot use high priority to preempt others. To forbid a tenant from using a priority class, set pods: "0".

LimitRange

apiVersion: v1
kind: LimitRange
metadata: {name: shop-defaults, namespace: shop}
spec:
  limits:
  - type: Container
    defaultRequest: {cpu: 50m, memory: 64Mi}
    default: {cpu: 200m, memory: 256Mi}
    min: {cpu: 10m, memory: 16Mi}
    max: {cpu: "2", memory: 2Gi}
  - type: PersistentVolumeClaim
    max: {storage: 20Gi}

Audit Policy (for the lab)

apiVersion: audit.k8s.io/v1
kind: Policy
omitStages: ["RequestReceived"]
rules:
# 1. Do not record health checks and high-frequency noise
- level: None
  nonResourceURLs: ["/healthz*", "/livez*", "/readyz*", "/version"]
- level: None
  resources: [{group: "", resources: ["events"]}, {group: "coordination.k8s.io", resources: ["leases"]}]
# 2. Record only metadata for sensitive resources (do not write secrets into the log)
- level: Metadata
  resources:
  - {group: "", resources: ["secrets", "configmaps", "serviceaccounts/token"]}
  - {group: "authentication.k8s.io", resources: ["tokenreviews"]}
# 3. Record the full request and response for permission changes
- level: RequestResponse
  resources: [{group: "rbac.authorization.k8s.io"}]
# 4. exec / attach / port-forward must be traceable
- level: Metadata
  resources: [{group: "", resources: ["pods/exec", "pods/attach", "pods/portforward"]}]
# 5. Record the request body for write operations in business namespaces
- level: Request
  verbs: ["create", "update", "patch", "delete", "deletecollection"]
  namespaces: ["shop"]
# 6. Do not record other read-only requests; record metadata for other write operations
- level: None
  verbs: ["get", "list", "watch"]
- level: Metadata

AKS: diagnostic settings and KQL

LAW_ID=$(az monitor log-analytics workspace create -g rg-k8s-lab -n law-k8s-lab --query id -o tsv)
AKS_ID=$(az aks show -g rg-k8s-lab -n aks-lab --query id -o tsv)
az monitor diagnostic-settings create --name aks-audit --resource $AKS_ID --workspace $LAW_ID \
  --logs '[{"category":"kube-audit-admin","enabled":true}]' --export-to-resource-specific true
AKSAuditAdmin
| where TimeGenerated > ago(1h)
| where ObjectRef has '"namespace":"shop"'
| project TimeGenerated, User, Verb, ObjectRef, ResponseStatus
| order by TimeGenerated desc

In resource-specific mode, audit data goes to the AKSAudit / AKSAuditAdmin tables; in Azure diagnostics mode it goes to AzureDiagnostics. Log Analytics charges by ingestion volume, and kube-audit (which includes all read requests) can be very large.

Lab 8: Quotas, Defaults, and Audit (about 10 minutes, kind lab)

Apply the LimitRange and ResourceQuota (use the YAML on the "Commands" tab, and save it as quota.yaml and limitrange.yaml):
mkdir -p ~/k8s-h5/m8 && cd ~/k8s-h5/m8
# After saving the two YAML blocks from the "Commands" tab separately:
kubectl apply -f limitrange.yaml -f quota.yaml
kubectl -n shop describe quota shop-compute
Name:                   shop-compute
Namespace:              shop
Resource                Used    Hard
--------                ----    ----
count/deployments.apps  2       20
count/secrets           3       30
limits.cpu              1300m   8
limits.memory           1664Mi  16Gi
persistentvolumeclaims  1       5
pods                    5       30
requests.cpu            350m    4
requests.memory         448Mi   8Gi
requests.storage        5Gi     50Gi
services.loadbalancers  0       0
services.nodeports      0       0
Verify that LimitRange fills in defaults (create a compliant Pod without a resources block):
kubectl -n shop run lr-test --image=nginxinc/nginx-unprivileged:1.29-alpine --restart=Never --overrides='{
 "spec":{"securityContext":{"runAsNonRoot":true,"runAsUser":101,"seccompProfile":{"type":"RuntimeDefault"}},
  "containers":[{"name":"lr-test","image":"nginxinc/nginx-unprivileged:1.29-alpine",
   "securityContext":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}]}}'
kubectl -n shop get pod lr-test -o jsonpath='{.spec.containers[0].resources}'; echo
pod/lr-test created
{"limits":{"cpu":"200m","memory":"256Mi"},"requests":{"cpu":"50m","memory":"64Mi"}}

This is a Pod (not a Deployment), so the M6 VAP does not check it. After LimitRanger adds the defaults in the mutating phase, ResourceQuota can count it.

Trigger a quota overrun:
kubectl -n shop create service loadbalancer lb-test --tcp=80:8080
kubectl -n shop scale deploy/web --replicas=40
sleep 5; kubectl -n shop get deploy web
kubectl -n shop get events --field-selector reason=FailedCreate | tail -1
kubectl -n shop scale deploy/web --replicas=2
error: failed to create LoadBalancer service: services "lb-test" is forbidden: exceeded quota: shop-compute, requested: services.loadbalancers=1, used: services.loadbalancers=0, limited: services.loadbalancers=0
deployment.apps/web scaled
NAME   READY   UP-TO-DATE   AVAILABLE
web    27/40   27           27
... Warning  FailedCreate  replicaset/web-…  Error creating: pods "web-…-x7k2p" is forbidden: exceeded quota: shop-compute, requested: pods=1, used: pods=30, limited: pods=30

The exact READY count depends on other Pods' usage. The limit may also be hit first on another dimension, such as limits.cpu.

Enable auditing in kind (same static manifest method as M7; audit output goes to the API server's stdout):
# Save the Audit Policy from the "Commands" tab as audit-policy.yaml
docker cp audit-policy.yaml lab-control-plane:/etc/kubernetes/pki/audit-policy.yaml
docker exec lab-control-plane cp /etc/kubernetes/manifests/kube-apiserver.yaml /root/kube-apiserver.yaml.bak2
docker exec lab-control-plane sed -i \
  's|^    - kube-apiserver$|    - kube-apiserver\\n    - --audit-policy-file=/etc/kubernetes/pki/audit-policy.yaml\\n    - --audit-log-path=-|' \
  /etc/kubernetes/manifests/kube-apiserver.yaml
until kubectl get --raw /readyz >/dev/null 2>&1; do sleep 5; done; echo ready

--audit-log-path=- writes to standard output, so you can read it directly with kubectl logs without mounting a log directory. When you create a new cluster, you can also configure this in kind-config.yaml by following kind's official "Auditing" docs, using kubeadmConfigPatches + extraMounts. (In kubeadm v1beta4, extraArgs changed to a name/value list format, so follow the kind and kubeadm docs.)

Generate events and query them:
kubectl --context alice@lab get secrets            # 403
kubectl -n shop exec deploy/api -- id                # admin exec
kubectl -n shop delete pod lr-test
sleep 3
kubectl -n kube-system logs kube-apiserver-lab-control-plane --since=2m | grep '^{"kind":"Event"' | \
  jq -c 'select(.objectRef.namespace=="shop") | {user: .user.username, verb, res: (.objectRef.resource + "/" + (.objectRef.subresource // "")), name: .objectRef.name, code: .responseStatus.code, decision: .annotations["authorization.k8s.io/decision"]}'
{"user":"alice","verb":"list","res":"secrets/","name":null,"code":403,"decision":"forbid"}
{"user":"kubernetes-admin","verb":"create","res":"pods/exec","name":"api-7f6d9c…","code":101,"decision":"allow"}
{"user":"kubernetes-admin","verb":"delete","res":"pods/","name":"lr-test","code":200,"decision":"allow"}

Checkpoints: denied reads are also recorded (code 403), and exec appears as a create action on pods/exec (101 Switching Protocols).

Cleanup: keep the quota and LimitRange for the capstone lab. You can keep the audit config. To revert it: docker exec lab-control-plane cp /root/kube-apiserver.yaml.bak2 /etc/kubernetes/manifests/kube-apiserver.yaml (note that this backup already includes the M7 encryption flags).

Case 1: A CronJob storm from one team takes down a shared cluster

Problem: A team's CronJob was misconfigured (concurrencyPolicy: Allow, jobs getting stuck), and it created thousands of Pods overnight. Scheduler and etcd load spiked and affected every team. Fix: set pods and count/jobs.batch quotas plus compute quotas in each namespace, and use LimitRange to make sure every Pod has requests. Limitation: quotas do not limit API request rate. API Priority and Fairness (APF) handles that layer.

Case 2: Security incident investigation: "Who deleted the production database Secret?"

Approach: Turn on kube-audit-admin in AKS, then query with KQL for Verb == "delete" on secrets in ObjectRef to get the user UPN, source IP, User-Agent, and time. Confirm the identity with Entra sign-in logs. Limitation: if everyone acts through a shared SA or an admin certificate, audit can only see that shared identity. This is why M1 recommends OIDC for people.

Case 3: A SaaS platform runs plugins for external customers

Approach: one vCluster per customer (the customer holds cluster-admin in their virtual cluster). The matching namespace in the host cluster is restricted + quota + default-deny network. Plugin Pods use the Kata RuntimeClass (AKS Pod Sandboxing) and are scheduled to dedicated node pools. Limitation: operational complexity and cost rise significantly. For high-value customers, separate clusters remain the simplest strong isolation.

Common errors and fixes

pods "x" is forbidden: failed quota: shop-compute: must specify limits.cpu for: app; limits.memory for: app

Cause: the namespace has cpu/memory quotas, but the Pod does not declare the matching limits/requests and there is no LimitRange default.

kubectl -n shop get limitrange
kubectl -n shop describe quota

Fix: add LimitRange defaults, or declare them explicitly in the Pod template (matching the M6 VAP requirement).

exceeded quota: shop-compute, requested: limits.memory=2Gi, used: limits.memory=15Gi, limited: limits.memory=16Gi

Cause: quota is exhausted. During a rolling update, maxSurge temporarily adds Pods, so this often appears only at release time.

kubectl -n shop describe quota shop-compute
kubectl -n shop get pods -o custom-columns=NAME:.metadata.name,LIM_MEM:.spec.containers[*].resources.limits.memory

Fix: raise the quota (through approval), lower maxSurge or set maxUnavailable, or clean up unused workloads.

Pod "x" is invalid: spec.containers[0].resources.limits.memory: Invalid value / maximum memory usage per Container is 2Gi, but limit is 4Gi

Cause: violates the max or min in a LimitRange.

kubectl -n shop describe limitrange shop-defaults

Interactive troubleshooting decision tree (all topics in this hour)

Command-line exercises
1. Create a quota with one command: shop may have at most 10 Pods and no LoadBalancer Services.
kubectl create quota shop-small -n shop --hard=pods=10,services.loadbalancers=0
2. Find all 403 requests from the kind audit log in the last 10 minutes, along with the users and resources.
kubectl -n kube-system logs kube-apiserver-lab-control-plane --since=10m | grep '^{"kind":"Event"' | \
  jq -c 'select(.responseStatus.code==403) | {u:.user.username, v:.verb, r:.objectRef.resource, ns:.objectRef.namespace}'
Scenario analysis
The platform team gives each team a namespace and binds the team lead to the ClusterRole admin. A lead added tolerations and nodeSelector to their own Pod, and it landed on the payments team's dedicated node pool. How do you prevent this?

Taints and tolerations only attract or repel; they are not a security boundary. Anyone who can create a Pod can add tolerations. Enforce this with an admission policy: use a VAP (matching Pods, based on namespaceObject.metadata.labels.team) that requires a Pod's nodeSelector to point to its own team's node pool and allows only its own team's taints in tolerations. Or enable the built-in PodNodeSelector / PodTolerationRestriction admission plugins (self-managed clusters). Also, the kubelets on the node pool run only that team's workloads, combined with NetworkPolicy.

Verified teaching videos

▶
Kubernetes Explained in 100 Seconds — Fireship
English · Purpose: quick review of namespaces, Pods, the control plane and other concepts, as background for the multi-tenancy discussion (no security details)
▶
Kubernetes Security Best Practices you need to know — TechWorld with Nana
English · Purpose: review of best practices for namespace isolation, network policies, and auditing

No verified video was found that specifically covers ResourceQuota, Audit Policy, or vCluster.

Official documentation

Video storyboard script

This lesson material cannot generate video or MP3 directly, so the storyboards and narration script are provided.

Shot 1 · 0:00–0:30
Visual: an apartment building where each namespace is a room number; the walls are dashed lines.
Narration: A namespace is just a room number, not a wall. Walls come from stacking control layers.
Shot 2 · 0:30–1:20
Visual: a quota progress bar fills up as you scale out; the last Pod is rejected and an exceeded quota message appears.
Narration: LimitRange fills in default values for each Pod, while ResourceQuota controls the total for the whole tenant.
Shot 3 · 1:20–2:10
Visual: audit log JSON scrolls, and jq filters alice's 403 records.
Narration: Denied requests leave a trail too. The audit log answers: who did what, to what, and when.
or score ≥ 70% on the quiz

Command cheat sheet

Kubernetes v1.37 Security and Multi-tenancy · every code block has a one-click copy button
After-class reference

Authentication and identity

kubectl auth whoami [-o yaml] [--as=U --as-group=G]
kubectl config view --minify
kubectl -v=8 get ns 2>&1 | grep "Response Status"
openssl req -new -key u.key -out u.csr -subj "/CN=user/O=group"
kubectl certificate approve|deny CSR
kubectl get csr CSR -o jsonpath='{.status.certificate}' | base64 -d > u.crt
kubectl config set-credentials U --client-certificate=u.crt --client-key=u.key --embed-certs
kubelogin convert-kubeconfig -l azurecli

RBAC

kubectl auth can-i VERB RES[/NAME] -n NS --as=U --as-group=G
kubectl auth can-i --list -n NS --as=system:serviceaccount:NS:SA
kubectl auth can-i get pods --subresource=log -n NS
kubectl create role R --verb=get,list --resource=pods,pods/log -n NS --dry-run=client -o yaml
kubectl create rolebinding B --role=R --group=G -n NS
kubectl create rolebinding B --clusterrole=view --serviceaccount=NS:SA -n NS
kubectl auth reconcile -f rbac.yaml [--remove-extra-permissions]
kubectl get rolebindings,clusterrolebindings -A -o wide

ServiceAccounts and Workload ID

kubectl create token SA -n NS --duration=10m [--audience=X]
kubectl patch sa default -n NS -p '{"automountServiceAccountToken":false}'
kubectl get --raw /.well-known/openid-configuration | jq
az aks update -g RG -n AKS --enable-oidc-issuer --enable-workload-identity
az aks show -g RG -n AKS --query oidcIssuerProfile.issuerUrl -o tsv
az identity federated-credential create --name F --identity-name UAMI -g RG \
  --issuer $ISSUER --subject system:serviceaccount:NS:SA --audience api://AzureADTokenExchange
# SA annotation azure.workload.identity/client-id; Pod label azure.workload.identity/use: "true"

Pod Security Admission

kubectl label --dry-run=server --overwrite ns NS pod-security.kubernetes.io/enforce=restricted
kubectl label --overwrite ns NS \
  pod-security.kubernetes.io/enforce=restricted pod-security.kubernetes.io/enforce-version=v1.37 \
  pod-security.kubernetes.io/warn=restricted pod-security.kubernetes.io/audit=restricted
kubectl get ns -L pod-security.kubernetes.io/enforce
kubectl get events -n NS --field-selector reason=FailedCreate

Container hardening checks

kubectl exec POD -- id
kubectl exec POD -- grep -E 'Uid|CapEff|NoNewPrivs|Seccomp:' /proc/1/status
kubectl exec POD -- touch /x          # expect: Read-only file system
kubectl exec POD -- cat /proc/self/uid_map   # non-identity mapping when hostUsers:false
kubectl explain pod.spec.containers.securityContext

Admission policies

kubectl get validatingadmissionpolicies,validatingadmissionpolicybindings
kubectl get mutatingadmissionpolicies,mutatingadmissionpolicybindings
kubectl get validatingadmissionpolicy P -o jsonpath='{.status.typeChecking}'
kubectl patch validatingadmissionpolicybinding B --type=merge -p '{"spec":{"validationActions":["Deny"]}}'
kubectl get validatingwebhookconfigurations -o custom-columns=N:.metadata.name,FP:.webhooks[*].failurePolicy,T:.webhooks[*].timeoutSeconds
kubectl apply --dry-run=server -f x.yaml

Secrets and encryption

kubectl get secret S -o jsonpath='{.data.K}' | base64 -d
etcdctl get /registry/secrets/NS/S | hexdump -C | head    # expect k8s:enc:
kubectl get secrets -A -o json | kubectl replace -f -      # re-write after encryption or rotation
az aks update -g RG -n AKS --enable-azure-keyvault-kms --azure-keyvault-kms-key-id $KEY_ID \
  --azure-keyvault-kms-key-vault-network-access Public
az aks enable-addons -g RG -n AKS --addons azure-keyvault-secrets-provider
kubeseal --format yaml < secret.yaml > sealed.yaml

Multi-tenancy and auditing

kubectl describe quota -n NS; kubectl describe limitrange -n NS
kubectl create quota Q -n NS --hard=pods=30,requests.cpu=4,services.loadbalancers=0
kubectl -n kube-system logs kube-apiserver-lab-control-plane | grep '^{"kind":"Event"' | jq -c '{u:.user.username,v:.verb,r:.objectRef.resource,c:.responseStatus.code}'
az monitor diagnostic-settings create --name aks-audit --resource $AKS_ID --workspace $LAW_ID \
  --logs '[{"category":"kube-audit-admin","enabled":true}]' --export-to-resource-specific true

Quick troubleshooting table

Symptom / errorWhich layer it is stuck atWhat to do firstCommon causes
Unauthorized / 401Authenticationkubectl -v=8, check the certificate enddate, kubelogin remove-tokensExpired certificate or token, audience mismatch
... is forbidden: User "x" cannot VERB resource ... / 403Authorizationkubectl auth can-i ... --as --as-groupMissing RoleBinding, wrong namespace, wrong apiGroup, subresource
violates PodSecurity "restricted:..."Admission: PSAAdd securityContext fields one by one, following the messagerunAsNonRoot, seccomp, drop ALL, allowPrivilegeEscalation
ValidatingAdmissionPolicy 'x' ... denied requestAdmission: VAPRead the message; set validationActions to Warn to troubleshoot:latest, missing limits, registry not on the allow list
failed calling webhook ... context deadline exceededAdmission: webhookCheck the webhook Pods, the EndpointSlice, and failurePolicyWebhook is down, or a NetworkPolicy blocks API server → webhook traffic
exceeded quota / failed quota: must specifyAdmission: ResourceQuotakubectl describe quotaQuota exhausted, or missing LimitRange defaults
CreateContainerConfigError: non-numeric userkubeletAdd a numeric runAsUserImage USER is a username
AADSTS70021Entra ID (outside the cluster)Compare FIC issuer, subject, and audienceSA or namespace name mismatch, or issuer changed

For the interactive troubleshooting flow, see Module 8 → Troubleshooting → Decision tree.

Recommended config snippet: business namespace "security baseline bundle"

apiVersion: v1
kind: Namespace
metadata:
  name: team-x
  labels:
    team: team-x
    pod-security.kubernetes.io/enforce: restricted
    pod-security.kubernetes.io/enforce-version: v1.37
    pod-security.kubernetes.io/warn: restricted
    pod-security.kubernetes.io/audit: restricted
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: default-deny-all, namespace: team-x}
spec:
  podSelector: {}
  policyTypes: ["Ingress", "Egress"]
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: allow-dns, namespace: team-x}
spec:
  podSelector: {}
  policyTypes: ["Egress"]
  egress:
  - to:
    - namespaceSelector: {matchLabels: {kubernetes.io/metadata.name: kube-system}}
      podSelector: {matchLabels: {k8s-app: kube-dns}}
    ports: [{protocol: UDP, port: 53}, {protocol: TCP, port: 53}]
---
apiVersion: v1
kind: ServiceAccount
metadata: {name: default, namespace: team-x}
automountServiceAccountToken: false
# + ResourceQuota, LimitRange (see Module 8) + RoleBinding (see Module 2)

Capstone lab + final quiz

Build a "team tenant" for shop: identity → permissions → Pod security → admission policies → resources → network → audit verification
After class ≈ 40 minutesCovers all modulesAKS parts optional
Scenario: The company decides to let the shop team run its own workloads in a shared cluster. The security team's requirements: (1) developers (Entra or certificate group dev-team) can only view and deploy, and cannot read Secrets or exec; (2) CI can only update the api and web images; (3) the namespace enforces PSS restricted, with all containers non-root and a read-only root filesystem; (4) :latest is forbidden, and limits must be set; (5) team resources are capped; (6) the network is default-deny; (7) all denials and exec must be traceable in the audit log; (8) (AKS optional) api reads Key Vault through Workload ID, so the cluster holds no database password.
Namespace labels and network baseline (M4, Hour 3)
kubectl label --overwrite ns shop team=shop \
  pod-security.kubernetes.io/enforce=restricted pod-security.kubernetes.io/enforce-version=v1.37 \
  pod-security.kubernetes.io/warn=restricted pod-security.kubernetes.io/audit=restricted
kubectl -n shop get networkpolicy
# If hour 3 did not create the default deny, apply default-deny-all + allow-dns from the cheat sheet, and confirm the allow rules and ports for web→api→db (web has changed to 8080)
Team RBAC and CI least privilege (M1, M2, M3)
kubectl auth reconcile -f ~/k8s-h5/m2/rbac-shop.yaml && kubectl apply -f ~/k8s-h5/m2/rbac-shop.yaml
for c in "get pods" "get pods --subresource=log" "create deployments" "get secrets" "create pods --subresource=exec"; do
  printf "dev  %-36s %s\n" "$c" "$(kubectl auth can-i $c -n shop --as=alice --as-group=dev-team)"; done
for c in "patch deployments/api" "patch deployments/db" "create deployments" "get secrets"; do
  printf "ci   %-36s %s\n" "$c" "$(kubectl auth can-i $c -n shop --as=system:serviceaccount:shop:ci)"; done
dev  get pods                             yes
dev  get pods --subresource=log           yes
dev  create deployments                   yes
dev  get secrets                          no
dev  create pods --subresource=exec       no
ci   patch deployments/api                yes
ci   patch deployments/db                 no
ci   create deployments                   no
ci   get secrets                          no
Workload hardening (M3, M5): confirm that all three use dedicated or token-free ServiceAccounts, a read-only root filesystem, and drop ALL:
# web: read-only root + /tmp emptyDir (nginx-unprivileged keeps its pid and temp files in /tmp)
kubectl -n shop patch deploy web --type=json -p='[
 {"op":"add","path":"/spec/template/spec/automountServiceAccountToken","value":false},
 {"op":"add","path":"/spec/template/spec/containers/0/securityContext/readOnlyRootFilesystem","value":true},
 {"op":"add","path":"/spec/template/spec/volumes","value":[{"name":"tmp","emptyDir":{}}]},
 {"op":"add","path":"/spec/template/spec/containers/0/volumeMounts","value":[{"name":"tmp","mountPath":"/tmp"}]}
]'
# db: read-only root + writable /var/run/postgresql and /tmp (the data directory is itself a PVC)
kubectl -n shop get sts db -o jsonpath='{.spec.template.spec.containers[0].volumeMounts}'; echo
kubectl -n shop get pods -o custom-columns='POD:.metadata.name,SA:.spec.serviceAccountName,RO:.spec.containers[*].securityContext.readOnlyRootFilesystem,USER:.spec.securityContext.runAsUser'

For the db read-only root, you need to append emptyDir mounts for /var/run/postgresql and /tmp to the existing volumeMounts. Add them manually with kubectl edit sts db -n shop so a JSON patch does not overwrite the data volume mount. If web already has volumes or volumeMounts, merge into them as well instead of overwriting.

Admission policy (M6):
kubectl apply -f ~/k8s-h5/m6/vap-shop.yaml
kubectl patch validatingadmissionpolicybinding shop-image-and-limits --type=merge -p '{"spec":{"validationActions":["Deny"]}}'
kubectl --context alice@lab -n shop create deploy hack --image=busybox:latest -- sleep 1d
error: failed to create deployment: deployments.apps "hack" is forbidden: ValidatingAdmissionPolicy 'shop-image-and-limits' with binding 'shop-image-and-limits' denied request: images must use a pinned tag or digest; :latest or a missing tag is not allowed
Quota and defaults (M8):
kubectl apply -f ~/k8s-h5/m8/limitrange.yaml -f ~/k8s-h5/m8/quota.yaml
kubectl -n shop describe quota shop-compute | head -20
Audit verification (M8): as alice, try to read a Secret and exec; as admin, exec once; then find these 3 records in the audit log:
kubectl --context alice@lab -n shop get secret db-credentials
kubectl --context alice@lab -n shop exec deploy/api -- id
kubectl -n shop exec deploy/api -- id
kubectl -n kube-system logs kube-apiserver-lab-control-plane --since=3m | grep '^{"kind":"Event"' | \
  jq -c 'select(.objectRef.namespace=="shop" and (.objectRef.resource=="secrets" or .objectRef.subresource=="exec")) | {u:.user.username,v:.verb,r:.objectRef.resource,s:.objectRef.subresource,c:.responseStatus.code}'
{"u":"alice","v":"get","r":"secrets","s":null,"c":403}
{"u":"alice","v":"create","r":"pods","s":"exec","c":403}
{"u":"kubernetes-admin","v":"create","r":"pods","s":"exec","c":101}
(AKS optional) Workload ID reads Key Vault (M3, M7): repeat lab 3B on aks-lab, but create the SA in the shop namespace (named api), change the FIC subject to system:serviceaccount:shop:api, and mount db-password as a file with a SecretProviderClass, with postgres using POSTGRES_PASSWORD_FILE. Verify that no database password appears in kubectl get secrets -n shop. When finished, run az group delete -n rg-k8s-lab --yes --no-wait.
Wrap-up: keep the kind lab environment for hour 6, which uses Helm, Kustomize, and GitOps to manage these manifests. To reset: kind delete cluster --name lab.
Acceptance checklist

Open-ended self-check (answer first, then expand the reference answer)

1. What layer does a request get stuck at for a 401 versus a 403? Give one cause for each.

401 = authentication failed (the API server does not recognize you): expired certificate, expired token, or audience mismatch. 403 = authorization failed (it recognizes you but does not allow the action): missing RoleBinding, or bound in the wrong namespace. Admission rejections also often return 403 Forbidden, but the message states whether it came from PodSecurity, ValidatingAdmissionPolicy, or quota.

2. Why can the "create deployments" permission be equivalent to "read all Secrets"? How do you mitigate it?

A user can create a Pod that mounts any Secret or runs as any ServiceAccount in the namespace. Mitigations: a VAP that restricts Secret volumes, envFrom, and serviceAccountName; only the GitOps controller deploys; sensitive Secrets go in Key Vault and Workload ID grants access precisely to one SA.

3. What are the three improvements of projected SA tokens over the old Secret-based tokens?

They expire and rotate automatically; they are bound to the Pod (invalid once the Pod is deleted); and you can set the audience. They are also not stored in etcd.

4. After PSA enforce is turned on, what happens to already-running non-compliant Pods? And to Deployments?

Existing Pods are unaffected (only warnings), but they are rejected when recreated. The Deployment object itself is accepted, because enforce does not apply to workload objects. The ReplicaSet fails to create Pods; see the FailedCreate events.

5. When should you use VAP, and when do you still need Kyverno or Gatekeeper?

Pure object field validation → VAP (no extra point of failure). External data (image signature checks, API calls), generating resources, background audit reports, or complex mutation → Kyverno or Gatekeeper.

6. After you enable etcd encryption, can kubectl get secret -o yaml still show plaintext? What does that tell you?

Yes (just base64-decode it). Encryption at rest only protects against storage-layer leaks such as snapshots and disks. API access control still depends on RBAC. You need both.

Final quiz (12 questions, covering all modules)

Sources and versions

Verification basis for all technical facts in this hour (verified on 2026-11-15)
TopicVerification resultSource (page date / access date)
Kubernetes version1.37.1 (2026-09-15) is the latest patch; 1.37 was released on 2026-08-26kubernetes.io/releases · v1.37 release blog (accessed 2026-11-15)
Pod Certificates / ClusterTrustBundlev1.37 Stable (KEP-4317, KEP-3257); used through a podCertificate projected volume with signerNamev1.37 release blog (2026-08-26)
Manifest-based admission controlv1.36 Alpha, v1.37 Beta enabled by default; staticManifestsDir; object name suffix .static.k8s.io; feature gate ManifestBasedAdmissionControlConfigManifest-Based Admission Control · v1.36 blog (2026-05-04)
MutatingAdmissionPolicyStable since v1.36, enabled by default, admissionregistration.k8s.io/v1Mutating Admission Policy (accessed 2026-11-15)
Structured authentication configurationAuthenticationConfiguration (apiserver.config.k8s.io/v1) Stable since v1.34 (introduced in v1.29); anonymous authenticator configuration stable in v1.34; kubectl auth whoami (SelfSubjectReview) Stable since v1.28; exec plugin supports client.authentication.k8s.io/v1 and v1beta1; X.509 CN → user, O → groupsAuthenticating (accessed 2026-11-15)
User NamespacesStable since v1.36 (introduced in v1.28, feature gate locked); requires Linux 6.3+, containerd 2.0+ or CRI-O 1.25+, and runc 1.2+ or crun 1.9+User Namespaces (accessed 2026-11-15)
SELinuxMountv1.37 Stable and enabled by default; seLinuxChangePolicy: Recursive keeps the old behaviorv1.37 release blog
Pod Security Standards / AdmissionBaseline and Restricted fields and allowed values; v1.37 adds two new safe sysctls; enforce does not apply to workload objects; version labels can be v1.37 or latestPod Security Standards · Pod Security Admission (accessed 2026-11-15)
Kubelet fine-grained API authorizationv1.36 GA (replaces the broad permissions of nodes/proxy)Kubernetes Blog (article title dated 2026-04-24)
AKS Workload IDCommands: --enable-oidc-issuer --enable-workload-identity, az identity federated-credential create … --audience api://AzureADTokenExchange; SA annotation azure.workload.identity/client-id; Pod label azure.workload.identity/use: "true" (required); up to 20 FICs per managed identity; Contributor cannot create role assignments; Azure CLI ≥ 2.47.0Deploy and configure (2026-07-31) · Overview (2026-10-06)
AKS KMSlegacy KMS: --enable-azure-keyvault-kms and related parameters; Secrets must be rewritten after switching. New KMS data encryption (preview, 1.33+): --kms-infrastructure-encryption Enabled, requires aks-preview and KMSPMKPreviewlegacy KMS (2025-12-22) · KMS data encryption (2025-12-19, updated 2026-10-21)
Secrets Store CSI (Azure)secrets-store.csi.x-k8s.io/v1 SecretProviderClass; with Workload ID, use clientID; add-on azure-keyvault-secrets-providerCSI identity access (2026-09-02)
Tool versionsExternal Secrets Operator v2.15.0 (2026-11-10); Kyverno v1.20.0 (2026-11-12); OPA Gatekeeper v3.23.1 (2026-08-27)GitHub Releases: ESO · Kyverno · Gatekeeper (accessed 2026-11-15)
podinfo image userThe Dockerfile creates non-root user app and sets USER app (non-numeric), so an explicit runAsUser is requiredpodinfo Dockerfile (accessed 2026-11-15)
nginx unprivileged imagenginxinc/nginx-unprivileged:1.29-alpine exists (last updated 2026-05-11), listens on 8080, UID 101Docker Hub (accessed 2026-11-15)
kind auditingOfficial examples: audit.k8s.io/v1 Policy, kubeadmConfigPatches + extraMountskind: Auditing (accessed 2026-11-15)
KMS v2, VAP, PSA, and AppArmor fieldsKMS v2 GA in v1.29; VAP GA in v1.30; PSA GA in v1.25 (PSP removed); appArmorProfile GA in v1.30Course standard §3 verified facts + the matching kubernetes.io docs

Video verification notes

Titles and channels were verified through the YouTube oEmbed endpoint (the video IDs match): TechWorld with Nana, "Kubernetes Security Best Practices you need to know | THE Guide for securing your K8s cluster!" (oBf5lrmquYI); Microsoft Azure, "Azure AD Workload Identity on AKS | KubeCon 2022" (5WUP8KAzwCo); Fireship, "Kubernetes Explained in 100 Seconds" (PziYflu8cB8). Duration and publish date were not available from the endpoint, so check the YouTube pages for those. Videos that were found but whose links could not be verified, and so are not listed: Liz Rice, "Getting to Grips with Kubernetes RBAC" (GOTO 2019); KubeCon, "Practical Challenges with Pod Security Admission" and "The Hitchhiker's Guide to Pod Security"; KubeCon EU 2025, "EVAPorating Kubernetes Security Risk"; and several External Secrets Operator community videos. All of these videos are in English and were recorded before v1.37, so rely on this hour and the official docs for version details.

Voice narration notes

The "Voice" tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time. The result depends on the voices installed on the operating system (the voice names vary by platform, such as English voices on Windows or macOS). The environment that built this lesson cannot reach a TTS service, so an MP3 cannot be embedded. For offline audio, send the narration script to a TTS service such as Azure AI Speech. The "Video" tab of each module provides a storyboard script that you can hand to a video generation tool.

Known limitations

  • Pod names, UIDs, timestamps, IPs, hashes, hex bytes, and line numbers in the "expected output" are sample values. Error wording may differ slightly between kubectl minor versions.
  • Modules 7 and 8 enable encryption and auditing by editing the kind static Pod manifests, and they place config files in the mounted /etc/kubernetes/pki/ directory. This is a lab shortcut, not a production practice.
  • When kind configures audit through kubeadmConfigPatches, kubeadm v1beta4 extraArgs uses a name/value list format. Check compatibility of the syntax in kind's official example against the kind docs for each kind version. This lab uses the static manifest approach instead, which does not depend on that format.
  • The Pod Certificates projected volume fields (keyType, credentialBundlePath, etc.) are illustrative only. Follow the v1.37 official docs. You must deploy the signer controller yourself.
  • For the ESO azurekv provider fields, the API version of Kyverno's new policy types, the Azure Policy built-in initiative name, and the status of the AKS image integrity feature, follow the respective project or product docs.
  • AKS costs are order-of-magnitude estimates; use the Azure pricing calculator. AKS new KMS data encryption is a preview feature.
  • Animations and simulators are simplified demonstrations of the real mechanisms (for example, the RBAC simulator includes only the bindings used in the lab). They do not replace real checks such as kubectl auth can-i.