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.
:latest and requiring limits, and understand the trade-offs between webhooks, Kyverno, and Gatekeeper.k8s:enc: prefix. Use Key Vault with the CSI driver or ESO to keep keys outside the cluster.| # | Time | Module | Core content | Animation / interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up | 4C security model, threat model, shop security baseline check | — | Hands-on test: “what can a compromised Pod do” |
| 1 | 00–07 | Authentication | X.509 (CN/O), SA JWT, OIDC / AuthenticationConfiguration, exec plugins, whoami | authn → authz → admission request chain | Issue a certificate for alice through the CSR API |
| 2 | 07–15 | Authorization (RBAC) | Role/ClusterRole/Binding, subresources, aggregation, dangerous permissions, can-i | RBAC decision simulator | Developer role + least-privilege CI ServiceAccount |
| 3 | 15–22 | ServiceAccount and Workload Identity | Projected tokens, TokenRequest, issuer discovery, AKS Workload ID | Token exchange flow animation | Decode the SA JWT; AKS reads Key Vault (optional) |
| 4 | 22–29 | Pod Security Standards | Privileged/Baseline/Restricted, PSA labels, dry-run, exemptions | Pod fields → three-level evaluator | Label shop as restricted and fix it |
| 5 | 29–36 | securityContext and container hardening | runAs*, read-only root, capabilities, seccomp, AppArmor, userns, supply chain | Hardening switches → attack outcomes | Harden podinfo and verify |
| 6 | 36–44 | Admission control | VAP (CEL), MAP (v1.36 GA), webhooks, Kyverno/Gatekeeper, manifest-based admission | Admission chain animation | VAP bans :latest + requires limits |
| 7 | 44–52 | Secret security and external keys | EncryptionConfiguration, KMS v2, Key Vault CSI, ESO, Sealed Secrets/SOPS | etcd encrypted write/read | Enable aescbc in kind and verify with etcdctl |
| 8 | 52–60 | Multi-tenancy and audit | ResourceQuota, LimitRange, isolation layers, vCluster, Audit Policy | Quota simulator + troubleshooting decision tree | Team tenant + audit logs |
| — | After class | Cheat sheet · Capstone lab | Build a “team tenant” for shop, end to end | Final quiz: 12 questions | Capstone lab |
| Target skill | Module | Key commands / objects | Lab | Quiz |
|---|---|---|---|---|
| Identify which layer (authn / authz / admission) a request is stuck at | M1 · M6 | kubectl auth whoami, -v=8 | ✓ | ✓ |
| Issue an X.509 certificate for a user and configure kubeconfig | M1 | CertificateSigningRequest, kubectl certificate approve | ✓ | ✓ |
| Log in to the cluster with OIDC / Entra ID | M1 · M2 | AuthenticationConfiguration, kubelogin | AKS optional | ✓ |
| Write least-privilege RBAC and audit it | M2 | kubectl auth can-i --list --as, auth reconcile | ✓ | ✓ |
| Identify dangerous permissions (secrets, pods/exec, escalate, bind, impersonate) | M2 · M7 | kubectl-who-can, rbac-tool | ✓ | ✓ |
| Short-lived, bound workload identity | M3 | kubectl create token, projected volumes | ✓ | ✓ |
| Passwordless Pod access to Azure resources | M3 · M7 | az identity federated-credential create | AKS optional | ✓ |
| Namespace-level Pod security baseline | M4 | pod-security.kubernetes.io/enforce, --dry-run=server | ✓ | ✓ |
| Container runtime hardening | M5 | securityContext, seccomp, capabilities | ✓ | ✓ |
| Organization-wide policy as code | M6 | ValidatingAdmissionPolicy, CEL | ✓ | ✓ |
| Secret encryption at rest and external keys | M7 | EncryptionConfiguration, etcdctl, SecretProviderClass | ✓ | ✓ |
| Tenant resources and isolation | M8 | ResourceQuota, LimitRange, NetworkPolicy | ✓ | ✓ |
| Audit “who did what, and when” | M8 | Audit Policy, AKS kube-audit-admin | ✓ | ✓ |
| Topic | Why it is not in this hour | Where to learn it |
|---|---|---|
| NetworkPolicy syntax details | Covered 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 hour | falco.org; Microsoft Defender for Containers docs |
| Service mesh mTLS (Istio / Linkerd) | Belongs to east-west traffic security; a lot of configuration | istio.io / linkerd.io |
| Node and control-plane CIS hardening (kube-bench) | Managed clusters (AKS) leave most control-plane hardening to the platform | CIS Kubernetes Benchmark, kube-bench |
| Image vulnerability scanning and SBOM pipeline | The Docker hour covered the build side; this hour covers only verification on the admission side | Docker hour modules 4 and 8; Trivy / Grype |
| The full secret flow in GitOps | Belongs to the GitOps topic | GitOps and Argo CD course |
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./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.lab and namespace shop from hours 1–4, and first see how unsafe things currently arelab (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.Standard_D4s_v5 (Ubuntu 24.04, resource group rg-k8s-lab, canadacentral), or Docker Desktop on your local machine.jq, openssl. The AKS part also needs Azure CLI 2.47+ (required for Workload ID).| Attack step | Possible in a default cluster? | Which control in this hour blocks it |
|---|---|---|
Read the mounted SA token: /var/run/secrets/kubernetes.io/serviceaccount/token | Yes (automounted by default) | M3: automountServiceAccountToken: false, dedicated SA |
| Use the token to call the API: list Secrets, create a privileged Pod | Depends on RBAC. The default SA has almost no permissions, but people often bind edit to it casually | M2: least privilege, no secrets list / create pods |
| Run as root, write to the root filesystem, install tools | The official nginx image starts its master process as root | M5: runAsNonRoot, readOnlyRootFilesystem |
| Mount hostPath / escape to the node from a privileged container | Possible without PSA | M4: PSA restricted; M6: VAP |
| Lateral access to db:5432, cloud metadata at 169.254.169.254 | Partly blocked in hour 3 | NetworkPolicy default deny + egress allowlist (reused in M8) |
| Read Secret plaintext from an etcd backup or from node disk | Possible (only base64 by default) | M7: EncryptionConfiguration / KMS v2 |
| Afterward, you cannot trace who did what | kind does not enable auditing by default | M8: Audit Policy |
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
# 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.
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
}
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.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
--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).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.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.
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).| Authenticator | Credential | Typical user | Identity mapping | Production recommendation |
|---|---|---|---|---|
| X.509 client certificate | Certificate signed by the cluster CA (--client-ca-file) | kubeadm admins, kubelet, control-plane components | CN=username, O=group (multiple allowed) | Only for components and emergency accounts. Cannot be revoked, so use a short validity period |
| ServiceAccount token | JWT issued by the API server (bound, projected, with an expiry) | Workloads inside Pods, CI | system: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 IdP | People (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 token | Opaque token, checked by an external service through TokenReview | Early AKS AAD, in-house systems | Returned by a webhook | Use with caution: if the webhook is down, nobody can log in |
| Anonymous | No credentials | Health checks | system:anonymous / group system:unauthenticated | Via AuthenticationConfiguration.anonymous.conditions, allow only /livez, /readyz, and /healthz (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.
kubectl create token. Avoid long-lived Secret tokens.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 item | Kubernetes | Azure (ARM) | Linux |
|---|---|---|---|
| User directory | None; provided by an external IdP or certificates | Entra ID | /etc/passwd, LDAP |
| Workload identity | ServiceAccount JWT | Managed identity | Service account uid |
| Failure response | 401 Unauthorized | 401 / AADSTS error codes | Permission denied (PAM) |
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.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.
| Command | Purpose | Key flags / notes |
|---|---|---|
kubectl auth whoami | Shows 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 --minify | Shows the credential type used by the current context | --raw is needed to show the certificate contents |
kubectl get csr / certificate approve|deny | Manage certificate signing requests | signerName: kubernetes.io/kube-apiserver-client, expirationSeconds |
kubectl config set-credentials | Write into user credentials | --client-certificate --client-key --embed-certs=true; or --exec-command |
kubectl -v=8 get pods | View the actual HTTP requests and response codes | When troubleshooting 401/403, check Response Status |
kubelogin convert-kubeconfig -l azurecli | AKS: 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.
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.
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.
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
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
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
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.
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"
}kubectl delete csr alice. At the end of the course, delete the context: kubectl config delete-context alice@lab; kubectl config delete-user alice.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.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).
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.
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.
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).
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.
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
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
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.
kubectl auth whoami --as=system:serviceaccount:shop:api
Note: using --as requires that you have the impersonate permission yourself.
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.
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.
This course file cannot generate video or MP3 directly, so it provides a storyboard and narration script.
kubectl get users and returns an error. Subtitle: “Kubernetes has no user objects.”pods/log, pods/exec), and resourceNames.kubectl auth can-i --list --as fluently to verify permissions, and use kubectl auth reconcile to manage RBAC manifests.| Object | Scope | Contents | Typical use |
|---|---|---|---|
| Role | Namespace | A set of rules (apiGroups × resources × verbs [× resourceNames]) | The team's permissions in shop |
| ClusterRole | Cluster | Same 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 |
| RoleBinding | Namespace | Grants a Role or ClusterRole to a subject, effective only within this namespace | “Bind the ClusterRole view to dev-team in shop” |
| ClusterRoleBinding | Cluster | Grants a ClusterRole to a subject, effective across all namespaces and cluster-level resources | Platform 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.
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:
| Permission | Why it is dangerous |
|---|---|
get/list/watch secrets | list 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/ephemeralcontainers | Enter 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/proxy | Directly 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/token | Issue tokens for any SA |
update/patch admission webhook configurations, certificatesigningrequests/approval | Disable security policies, or issue yourself a system:masters certificate |
* wildcard | Includes resources and verbs added in the future |
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.
| ClusterRole | Capability | Notes |
|---|---|---|
view | Read most objects | Cannot read Secrets, nor read Roles or RoleBindings |
edit | Read and write most objects | Can read and write Secrets, and can run Pods as any SA in the namespace. Cannot change Roles or RoleBindings. |
admin | Namespace admin: can create Roles and RoleBindings within the namespace | Cannot modify ResourceQuota or the Namespace itself |
cluster-admin | Everything | When 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.
| Kubernetes RBAC | Azure RBAC for Kubernetes (AKS) | AWS EKS Access Entries | |
|---|---|---|---|
| Where policy is stored | In-cluster API objects | ARM role assignments (scope can go down to …/namespaces/shop) | EKS API + access policies |
| Deny rules | None | Supports deny assignments (platform level) | None |
| Subjects | User, Group, and SA strings | Entra users, groups, service principals | IAM principals |
| Auditing | K8s audit log | Azure activity log + K8s audit | CloudTrail + audit |
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.
| Command | Purpose | Key flags |
|---|---|---|
kubectl auth can-i VERB RESOURCE | Check a single permission (SelfSubjectAccessReview / SubjectAccessReview) | -n, --as, --as-group, --subresource, RESOURCE/NAME |
kubectl auth can-i --list | List all of a subject's permissions within a namespace | --as=system:serviceaccount:NS:SA |
kubectl create role / rolebinding | Generate RBAC imperatively (suited to --dry-run=client -o yaml to produce manifests) | --verb --resource --resource-name; --clusterrole --group --serviceaccount |
kubectl auth reconcile -f | Apply 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 wide | Inventory bindings | Filter subjects with jq |
kubectl who-can (plugin kubectl-who-can), rbac-tool | Reverse lookup of “who can read secrets”, and RBAC visualization | Install 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.
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
# 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.
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
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"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
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}'.
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(","))"'kubectl delete -f rbac-shop.yaml.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.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.
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.
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.
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.
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.
Cause: roleRef cannot be changed after creation. Fix: delete and recreate it, or use kubectl auth reconcile -f, which deletes and recreates it automatically.
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
kubectl create role log-reader -n shop --verb=get,list --resource=pods,pods/log --dry-run=client -o yaml
kubectl auth can-i list secrets -A --as=system:serviceaccount:kube-system:default
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.
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.
This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.
kubectl create token (TokenRequest API) to issue a short-lived token, and decode the JWT claims.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.
| Property | Old: Secret-based token (auto-generated before v1.24) | New: TokenRequest / projected token |
|---|---|---|
| Validity period | Permanent | Has 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 to | None | Bound to the Pod (and its node). The token becomes invalid as soon as the Pod is deleted |
| Audience | None | Can set aud to stop the token from being used on other systems |
| Storage | Stored in etcd as a Secret | Not written to etcd. It stays only in the node's tmpfs |
| Current status | No longer auto-generated since v1.24. Unused legacy tokens are automatically marked invalid and cleaned up (LegacyServiceAccountTokenCleanUp, GA in v1.30) | Default approach |
POST /api/v1/namespaces/shop/serviceaccounts/api/token (TokenRequest). The request includes the audience, expirationSeconds, and boundObjectRef (the Pod name and UID).--service-account-signing-key-file. The iss claim is set to --service-account-issuer.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}/).
| Component | Role | Configuration |
|---|---|---|
| OIDC issuer | Publishes the public signing key for SA tokens | az aks update --enable-oidc-issuer |
| Workload Identity admission webhook | Injects 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 Vault | az identity create |
| Federated identity credential (FIC) | Trust relationship: issuer + subject (system:serviceaccount:ns:sa) + audience | az identity federated-credential create (up to 20 per identity) |
| SA annotation | azure.workload.identity/client-id: <UAMI clientId> | Restart the Pod after changing the annotation |
| Pod label | azure.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 variables | AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_FEDERATED_TOKEN_FILE, AZURE_AUTHORITY_HOST | Read automatically by DefaultAzureCredential in the Azure Identity SDK |
automountServiceAccountToken: false.| AKS Workload ID | AKS Pod Identity (deprecated) | Node managed identity (kubelet identity) | EKS IRSA / Pod Identity | |
|---|---|---|---|---|
| Granularity | Per SA | Per Pod | Entire node pool (shared by all Pods) | Per SA |
| Mechanism | OIDC federation | Intercepts IMDS (NMI DaemonSet) | IMDS | OIDC federation / Agent |
| Recommendation | Recommended | Deprecated as of 2022-10-24; migrate | Only for node components | AWS equivalent |
api://AzureADTokenExchange). It is unrelated to the default token volume.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.
| Command | Purpose | Key flags |
|---|---|---|
kubectl create token SA | Call TokenRequest to issue a short-lived token | --duration=10m, --audience=X, --bound-object-kind=Pod --bound-object-name=… |
kubectl create serviceaccount | Create an SA | Set automountServiceAccountToken: false in the YAML |
kubectl get --raw /.well-known/openid-configuration | View the issuer discovery document | View public keys at /openid/v1/jwks |
az aks update --enable-oidc-issuer --enable-workload-identity | Enable the OIDC issuer and Workload ID on AKS | Query: --query oidcIssuerProfile.issuerUrl |
az identity federated-credential create | Establish 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.
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
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.
kubectl -n shop patch serviceaccount default -p '{"automountServiceAccountToken": false}'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).
kubectl -n shop delete pod token-demoexport 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/
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
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://AzureADTokenExchangekubectl 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.
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
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.
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.
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.
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
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
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
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.
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.
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.
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.
This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.
AZURE_CLIENT_SECRET in the Secret is crossed out in red.pod-security.kubernetes.io/{enforce,audit,warn} and -version labels, and preview the impact with kubectl label --dry-run=server.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.
| Level | Purpose | Main restrictions |
|---|---|---|
| Privileged | No restrictions | None. For namespaces that hold system components such as CNI, storage drivers, and log agents |
| Baseline | Prevents known privilege escalations and works with most images | Disallows 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. |
| Restricted | Current best practices for hardening Pods | Everything 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 |
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.
| Label | Behavior | Applies to |
|---|---|---|
pod-security.kubernetes.io/enforce: restricted | Violating 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: restricted | Allowed, but a Warning is returned to the client | Pods and workload objects |
pod-security.kubernetes.io/audit: restricted | Allowed, with an annotation added to the audit event | Pods and workload objects |
pod-security.kubernetes.io/enforce-version: v1.37 | Pins the policy to the definition of a specific version. Can be set to latest | Prevents 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.
enforce: restricted (or start with baseline and warn on restricted as a transition).defaults) to baseline enforce and restricted warn.| PSA | PSP (removed) | VAP (M6) | Kyverno / Gatekeeper | |
|---|---|---|---|---|
| Deployment | Built in | Built in | Built in | Requires installing a webhook |
| Granularity | Namespace × 3 levels | Selected by RBAC | Any CEL rule | Any rule + mutate/generate |
| Mutates Pods | No | Yes (default) | No (MAP can) | Yes |
| AKS | Available | — | Available | Azure Policy for AKS is based on Gatekeeper |
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.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": …).
| Command | Purpose | Notes |
|---|---|---|
kubectl label --dry-run=server --overwrite ns NS pod-security.kubernetes.io/enforce=restricted | Dry run: which existing Pods would violate the policy | The 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=latest | Warn only, during the transition | Set multiple labels at once |
kubectl get ns -L pod-security.kubernetes.io/enforce | Check the level for each namespace | -L shows the label as a column |
kubectl describe rs -n NS | View the FailedCreate events for Pods that a Deployment could not create | enforce does not apply to the Deployment itself |
kubectl get events -n NS --field-selector reason=FailedCreate | Quick 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.
spec:
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
seccompProfile:
type: RuntimeDefault
containers:
- name: app
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
--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.
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
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/apinginxinc/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
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.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).
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.
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": ...
kubectl -n shop delete deploy bad. Keep the restricted label. Later modules build on it.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).
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.
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.
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.
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
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.
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.
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
kubectl get ns -L pod-security.kubernetes.io/enforce | awk 'NR==1 || $4==""'
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.
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:
This lesson cannot directly produce a video or MP3, so a storyboard and narration script are provided instead.
--read-only --cap-drop ALL --security-opt no-new-privileges flags from the Docker course into Kubernetesid, /proc/1/status, and a file-write test.| Field | Level | Kernel mechanism | What it blocks | Docker equivalent |
|---|---|---|---|---|
runAsUser / runAsGroup | Pod / container | Process UID/GID | Reading and writing files as root, and exploiting root-only vulnerabilities | --user |
runAsNonRoot | Pod / container | Checked by the kubelet before startup | Image unexpectedly runs as root | — |
fsGroup, fsGroupChangePolicy | Pod | Volume file group + setgid | Non-root cannot write to the PVC | — |
allowPrivilegeEscalation: false | Container | no_new_privs | Privilege escalation through setuid programs (sudo, older ping) | --security-opt no-new-privileges |
readOnlyRootFilesystem: true | Container | Read-only root mount | Dropping backdoors, tampering with binaries, installing tools | --read-only |
capabilities.drop: ["ALL"] | Container | Linux capabilities | NET_RAW spoofing, CHOWN, DAC_OVERRIDE bypassing file permissions, and so on | --cap-drop ALL |
seccompProfile: RuntimeDefault | Pod / container | seccomp-bpf syscall filtering | Dangerous syscalls such as unshare, mount, keyctl, and bpf, and the kernel vulnerabilities behind them | Enabled by default in Docker |
appArmorProfile (GA in v1.30, replaces the old annotation) | Pod / container | AppArmor LSM | Restricts file and network access by path | --security-opt apparmor= |
seLinuxOptions, seLinuxChangePolicy | Pod / container | SELinux labels | Cross-container file access (RHEL-based systems) | --security-opt label= |
hostUsers: false (GA in v1.36) | Pod | user namespace | Root inside the container is not root on the node. After an escape, it is still an unprivileged user | --userns-remap |
privileged: true | Container | Turns 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.
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.
emptyDir at /tmp and cache directories (you can set medium: Memory + sizeLimit).fsGroupChangePolicy: OnRootMismatch.-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.| Control point | Tool | How to enforce it in K8s |
|---|---|---|
| Signing | Sigstore 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 allowlist | Allow only myacr.azurecr.io/ | VAP (extended in the M6 lab), built-in Azure Policy |
| Immutable references | Use an @sha256: digest | VAP blocks :latest / requires a digest |
| Pull credentials | AKS node managed identity + AcrPull | No imagePullSecrets needed |
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.
| Isolation strength | Option | Cost |
|---|---|---|
| Standard | runc + securityContext (this lesson) | Almost none |
| Stronger | user namespaces (hostUsers: false) | Kernel and runtime version requirements |
| Sandbox | gVisor and Kata Containers (AKS Pod Sandboxing) through RuntimeClass | Performance overhead and compatibility limits |
| Strongest | Separate node pool / separate cluster | Cost |
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).
| Command | Purpose | Notes |
|---|---|---|
kubectl exec POD -- id | Check UID/GID | If the image has no id command, use cat /proc/1/status |
kubectl exec POD -- grep -E 'Uid|Cap|NoNewPrivs|Seccomp' /proc/1/status | View the kernel's perspective directly | CapEff: 0000000000000000, NoNewPrivs: 1, Seccomp: 2 (filter mode) |
kubectl debug -it POD --image=busybox:1.37 --target=CONTAINER | Troubleshoot 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 --recursive | View fields | Container level: pod.spec.containers.securityContext |
cosign verify --certificate-identity … --certificate-oidc-issuer … IMG | Verify a keyless signature | Third-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.
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}
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
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.
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).
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.
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.
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).
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.
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.
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.
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.
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
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
kubectl -n shop exec deploy/web -- grep CapEff /proc/1/status
securityContext: {readOnlyRootFilesystem: true}
volumeMounts: [{name: cache, mountPath: /var/cache/app}]
# Pod level:
volumes: [{name: cache, emptyDir: {}}]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.
No verified video was found that specifically covers seccomp / capabilities / user namespaces.
This course cannot generate video or MP3 directly, so it provides a shot list and narration script.
id shows uid=0.validationActions and paramKind), and read the rejection messages.failurePolicy, timeoutSeconds, and namespaceSelector, and the risk of “a webhook outage blocking the cluster.”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.
| Type | Examples | Where it runs | Language | Phase |
|---|---|---|---|---|
| Built-in plugins | NamespaceLifecycle, LimitRanger, ServiceAccount, DefaultStorageClass, PodSecurity, ResourceQuota, NodeRestriction | In-process in the API Server | Go (compiled into the binary) | Fixed per type |
| ValidatingAdmissionPolicy | Forbid :latest, require limits | In-process in the API Server | CEL | validating (GA in v1.30) |
| MutatingAdmissionPolicy | Set defaults, inject labels | In-process in the API Server | CEL (ApplyConfiguration / JSONPatch) | mutating (GA in v1.36, admissionregistration.k8s.io/v1) |
| Dynamic webhooks | Kyverno, Gatekeeper, Istio injection, Workload ID | HTTPS services inside or outside the cluster | Any | Mutating/ValidatingWebhookConfiguration |
failed calling webhook to block every deployment.kubectl explain.| Object | Role | Key fields |
|---|---|---|
ValidatingAdmissionPolicy | Defines “what to check” | matchConstraints (resources/operations), matchConditions (CEL pre-filter), validations[].expression / message / messageExpression / reason, variables, paramKind, failurePolicy, auditAnnotations |
ValidatingAdmissionPolicyBinding | Defines “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 logic | Any 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.
| Field | Recommendation | Reason |
|---|---|---|
failurePolicy | Use Fail for security policies; use Ignore for non-critical mutating changes | Fail: reject requests when the webhook is unavailable (safe, but can block). Ignore: allow them through (available, but the policy is ineffective). |
timeoutSeconds | 1–5 seconds (default 10, max 30) | A slow webhook slows down every apply |
namespaceSelector / objectSelector | Exclude kube-system and the namespace where the webhook itself runs | Otherwise, when the webhook Pod is recreated, it has to pass through itself: deadlock |
matchConditions (CEL) | Filters on the API Server side first | Reduces pointless webhook calls |
sideEffects: None, admissionReviewVersions: ["v1"] | Required | Supports dry-run |
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.
| VAP / MAP | Kyverno (v1.20.0, 2026-11-12) | OPA Gatekeeper (v3.23.1, 2026-08-27) | |
|---|---|---|---|
| Policy language | CEL | YAML (ClusterPolicy) and the newer CEL-based policy types (ValidatingPolicy, MutatingPolicy, GeneratingPolicy, ImageValidatingPolicy, etc.) | Rego (ConstraintTemplate), also supports the CEL engine |
| Deployment | Built-in | Webhook + controller | Webhook + controller |
| Mutate / Generate | MAP can mutate; cannot generate | Yes | Supports mutation; no generation |
| Image signature verification | Not supported (no external calls) | Supported (cosign / Notation) | Requires Ratify |
| Background audit of existing resources | No (only at request time) | PolicyReport | Audit controller |
| AKS integration | Native | Self-installed | Azure Policy for AKS is based on Gatekeeper |
| Command | Purpose | Notes |
|---|---|---|
kubectl get validatingadmissionpolicies,validatingadmissionpolicybindings | List VAPs and bindings | Use 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 result | status.typeChecking.expressionWarnings points out misspelled field names |
kubectl get mutatingwebhookconfigurations,validatingwebhookconfigurations | Inventory webhooks | Check failurePolicy / namespaceSelector |
kubectl apply --dry-run=server -f x.yaml | Walk through admission end to end (without saving) | The webhook must declare sideEffects: None |
kubectl api-resources --api-group=admissionregistration.k8s.io | Confirm the MAP/VAP API is available | In v1.37, MAP is v1 |
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.
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.)
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:')"
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.
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
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.
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)
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.
kubectl -n shop rollout restart deploy/api deploy/web kubectl -n shop rollout status deploy/web
kubectl delete -f vap-shop.yaml.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.
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()).
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.
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.
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.
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.
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).
kubectl apply --dry-run=server -f deploy.yaml
kubectl patch validatingadmissionpolicybinding shop-image-and-limits --type=merge -p '{"spec":{"validationActions":["Warn","Audit"]}}'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.
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.
This course cannot generate video or MP3 directly, so it provides a shot list and narration script.
EncryptionConfiguration, etcdctl shows the k8s:enc: prefix.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.
| Leak path | Controls |
|---|---|
RBAC: get/list/watch secrets, or create Pods and mount them | M2 least privilege, M6 VAP to restrict mounts |
| etcd data files / snapshots / backups | EncryptionConfiguration / KMS v2 (this module) |
Inside the Pod: environment variables appear in crash dumps, /proc/1/environ, and debug output | Mount as files instead of env; read-only root |
| Plaintext YAML in a Git repository | Sealed Secrets, SOPS, ESO (only references stored in Git) |
| Node: kubelet writes Secret volumes to tmpfs | Node isolation; restrict which nodes sensitive workloads can be scheduled onto |
| Provider | Algorithm | Key storage | Assessment |
|---|---|---|---|
identity | No encryption | — | Default; keep it at the end of the list to read old data |
aescbc | AES-CBC + PKCS#7 | In the config file (plaintext!) | Official docs note a padding oracle risk; not recommended for new deployments |
aesgcm | AES-GCM | In the config file | Fast, but keys must be rotated every 200,000 writes (random nonce limit) |
secretbox | XSalsa20 + Poly1305 | In the config file | A 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 KMS | External 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.
--encryption-provider-config=FILE. In the providers list, the first entry is used for writes; all providers can be used for reads.kubectl get secrets -A -o json | kubectl replace -f -, or use Storage Version Migration (storagemigration.k8s.io/v1, GA in v1.37).| Option | Principle | Creates a K8s Secret? | Use case |
|---|---|---|---|
| Secrets Store CSI Driver + Azure Key Vault provider | When the Pod starts, the CSI driver uses Workload ID to pull from Key Vault and mounts the values as files | No by default; optional secretObjects syncs them to a Secret | AKS 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 Secret | Yes | Multi-cloud or multiple backends; needs env references or a third-party chart |
| Sealed Secrets | Encrypted with the cluster controller's public key. Git stores a SealedSecret, which is decrypted into a Secret inside the cluster. | Yes | Pure GitOps, no external secret store |
| SOPS (+ age / Azure Key Vault key) | Encrypts the values in YAML within Git; Flux/Argo plugins decrypt them | Yes | GitOps, integrated with Key Vault |
| K8s Secret + KMS v2 | CSI + Key Vault | ESO | |
|---|---|---|---|
| Source of truth | etcd | Key Vault | Key Vault (the synced copy lives in etcd) |
| Rotation | Update the Secret manually | Automatic rotation can be enabled (polling interval) | refreshInterval |
| When Key Vault is unavailable | Not affected | New Pods can't start | Already-synced Secrets still work |
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.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.
| Command | Purpose | Notes |
|---|---|---|
kubectl create secret generic N --from-literal=k=v | Create a Secret | --from-file. In production, avoid plaintext on the command line (it goes into shell history). |
etcdctl get /registry/secrets/NS/NAME | hexdump -C | View raw bytes in etcd | Requires 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 Enabled | AKS 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-provider | Enable the Key Vault CSI add-on | --enable-secret-rotation enables rotation |
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
# 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.
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}
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}
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
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.
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.
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>.
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.
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
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.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.
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.
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.
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
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.
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
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.
kubectl -n shop get secret db-credentials -o jsonpath='{.data.password}' | base64 -dThis shows that having get secrets permission means having the plaintext.
kubectl -n shop get secrets -o json | kubectl replace -f -
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.
Found community videos related to External Secrets Operator, but could not verify that their YouTube titles match their channels, so they are not listed.
This course cannot generate video or MP3 directly, so it provides a shot list and narration script.
kube-audit-admin through diagnostic settings on AKS.| Form | Typical scenario | Trust assumption | Implementation |
|---|---|---|---|
| Soft multi-tenancy | Multiple teams in the same company (the shop team, the payments team) | Tenants are largely trusted; the main concerns are accidental mistakes and blast radius | One or more namespaces per team, plus the stacked controls in this module |
| Hard multi-tenancy | SaaS running code and untrusted workloads for external customers | Tenants do not trust each other, so malicious escapes must be prevented | vCluster (a separate virtual control plane per tenant) + sandboxed runtime + dedicated node pools; or a separate cluster per tenant |
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:
| Layer | Control | Covered in |
|---|---|---|
| Identity and access | Team groups → RoleBinding (admin / custom), no ClusterRoleBinding | M1, M2 |
| Network | Default-deny ingress/egress, plus explicit allows (including DNS) | Hour 3 |
| Resources | ResourceQuota (totals) + LimitRange (defaults and bounds per Pod/container) | This module |
| Workload security | PSA restricted + securityContext | M4, M5 |
| Organizational policy | VAP: image sources, labels, forbid modifying tolerations / nodeSelector | M6 |
| Secrets | Per-team Key Vault / UAMI, with the FIC subject scoped precisely to the SA | M3, M7 |
| Nodes | Dedicated node pools + taints; use policy to enforce nodeSelector/tolerations on tenant Pods | This module |
| Traceable | Audit logs | This module |
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.| Level | What is recorded | Applies to |
|---|---|---|
None | Not recorded | Health checks and high-frequency read-only system components |
Metadata | User, verb, resource, namespace, response code, timestamp, source IP, and authorization decision annotations, but not request or response bodies | Secrets, ConfigMaps, TokenReviews (to avoid writing secrets into logs) |
Request | Metadata + request body | Write operations in business namespaces |
RequestResponse | Plus response body | Critical 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.
kube-audit-admin (it excludes get/list, at a much lower cost).| Namespace (soft) | vCluster | Separate cluster | |
|---|---|---|---|
| Control plane | Shared | A virtual API Server per tenant (running in a host namespace); workloads sync to the host cluster | Separate |
| Can tenants install CRDs or have cluster-admin? | No | Yes (within the virtual cluster) | Yes |
| Node/kernel isolation | No (unless node pools are isolated) | Not by default (can be combined with dedicated nodes or sandboxes) | Yes |
| Cost and operations | Lowest | Medium | Highest (AKS Fleet Manager can help manage multiple clusters) |
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.
| Command | Purpose | Notes |
|---|---|---|
kubectl describe quota -n NS | View quota Used / Hard | Quota usage is updated asynchronously by the controller, so it can lag by a few seconds. |
kubectl describe limitrange -n NS | View defaults and limits | — |
kubectl create quota NAME --hard=pods=10,requests.cpu=2 -n NS | Create a quota imperatively | Use 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 stdout | See the lab |
az monitor diagnostic-settings create … --logs '[{"category":"kube-audit-admin","enabled":true}]' | AKS: send audit logs to Log Analytics | kube-audit includes everything (including get/list), so the volume is large. |
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".
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}
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
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.
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
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.
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.
# 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.)
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).
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).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.
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.
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.
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).
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.
Cause: violates the max or min in a LimitRange.
kubectl -n shop describe limitrange shop-defaults
kubectl create quota shop-small -n shop --hard=pods=10,services.loadbalancers=0
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}'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.
No verified video was found that specifically covers ResourceQuota, Audit Policy, or vCluster.
This lesson material cannot generate video or MP3 directly, so the storyboards and narration script are provided.
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 azureclikubectl 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
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"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
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
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.yamlkubectl 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.yamlkubectl 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| Symptom / error | Which layer it is stuck at | What to do first | Common causes |
|---|---|---|---|
Unauthorized / 401 | Authentication | kubectl -v=8, check the certificate enddate, kubelogin remove-tokens | Expired certificate or token, audience mismatch |
... is forbidden: User "x" cannot VERB resource ... / 403 | Authorization | kubectl auth can-i ... --as --as-group | Missing RoleBinding, wrong namespace, wrong apiGroup, subresource |
violates PodSecurity "restricted:..." | Admission: PSA | Add securityContext fields one by one, following the message | runAsNonRoot, seccomp, drop ALL, allowPrivilegeEscalation |
ValidatingAdmissionPolicy 'x' ... denied request | Admission: VAP | Read the message; set validationActions to Warn to troubleshoot | :latest, missing limits, registry not on the allow list |
failed calling webhook ... context deadline exceeded | Admission: webhook | Check the webhook Pods, the EndpointSlice, and failurePolicy | Webhook is down, or a NetworkPolicy blocks API server → webhook traffic |
exceeded quota / failed quota: must specify | Admission: ResourceQuota | kubectl describe quota | Quota exhausted, or missing LimitRange defaults |
CreateContainerConfigError: non-numeric user | kubelet | Add a numeric runAsUser | Image USER is a username |
AADSTS70021 | Entra ID (outside the cluster) | Compare FIC issuer, subject, and audience | SA or namespace name mismatch, or issuer changed |
For the interactive troubleshooting flow, see Module 8 → Troubleshooting → Decision tree.
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)
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.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)
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
# 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.
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
kubectl apply -f ~/k8s-h5/m8/limitrange.yaml -f ~/k8s-h5/m8/quota.yaml kubectl -n shop describe quota shop-compute | head -20
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}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.kind delete cluster --name lab.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.
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.
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.
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.
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.
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.
| Topic | Verification result | Source (page date / access date) |
|---|---|---|
| Kubernetes version | 1.37.1 (2026-09-15) is the latest patch; 1.37 was released on 2026-08-26 | kubernetes.io/releases · v1.37 release blog (accessed 2026-11-15) |
| Pod Certificates / ClusterTrustBundle | v1.37 Stable (KEP-4317, KEP-3257); used through a podCertificate projected volume with signerName | v1.37 release blog (2026-08-26) |
| Manifest-based admission control | v1.36 Alpha, v1.37 Beta enabled by default; staticManifestsDir; object name suffix .static.k8s.io; feature gate ManifestBasedAdmissionControlConfig | Manifest-Based Admission Control · v1.36 blog (2026-05-04) |
| MutatingAdmissionPolicy | Stable since v1.36, enabled by default, admissionregistration.k8s.io/v1 | Mutating Admission Policy (accessed 2026-11-15) |
| Structured authentication configuration | AuthenticationConfiguration (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 → groups | Authenticating (accessed 2026-11-15) |
| User Namespaces | Stable 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) |
| SELinuxMount | v1.37 Stable and enabled by default; seLinuxChangePolicy: Recursive keeps the old behavior | v1.37 release blog |
| Pod Security Standards / Admission | Baseline 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 latest | Pod Security Standards · Pod Security Admission (accessed 2026-11-15) |
| Kubelet fine-grained API authorization | v1.36 GA (replaces the broad permissions of nodes/proxy) | Kubernetes Blog (article title dated 2026-04-24) |
| AKS Workload ID | Commands: --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.0 | Deploy and configure (2026-07-31) · Overview (2026-10-06) |
| AKS KMS | legacy 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 KMSPMKPreview | legacy 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-provider | CSI identity access (2026-09-02) |
| Tool versions | External 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 user | The Dockerfile creates non-root user app and sets USER app (non-numeric), so an explicit runAsUser is required | podinfo Dockerfile (accessed 2026-11-15) |
| nginx unprivileged image | nginxinc/nginx-unprivileged:1.29-alpine exists (last updated 2026-05-11), listens on 8080, UID 101 | Docker Hub (accessed 2026-11-15) |
| kind auditing | Official examples: audit.k8s.io/v1 Policy, kubeadmConfigPatches + extraMounts | kind: Auditing (accessed 2026-11-15) |
| KMS v2, VAP, PSA, and AppArmor fields | KMS v2 GA in v1.29; VAP GA in v1.30; PSA GA in v1.25 (PSP removed); appArmorProfile GA in v1.30 | Course standard §3 verified facts + the matching kubernetes.io docs |
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.
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.
/etc/kubernetes/pki/ directory. This is a lab shortcut, not a production practice.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.keyType, credentialBundlePath, etc.) are illustrative only. Follow the v1.37 official docs. You must deploy the signer controller yourself.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.kubectl auth can-i.