Learning Kubernetes RBAC the hands-on way: a complete local lab on Ubuntu
Eleven stages, one disposable cluster, and a regression suite that proves every permission boundary. Audience: anyone who has some Kubernetes basics but finds RBAC abstract, confusing, or intimidating – and wants to feel how it works instead of just reading about it. What you'll build A disposable rbac-lab cluster on your own Ubuntu machine, walk […]

Audience: anyone who has some Kubernetes basics but finds RBAC abstract, confusing, or intimidating – and wants to feel how it works instead of just reading about it.
A disposable rbac-lab cluster on your own Ubuntu machine, walk through 11 stages from “ServiceAccount with zero permissions” all the way to policy-as-code admission control, and validate every single stage with an automated test suite. By the end, you’ll have a repeatable lab that takes you from nothing to a hardened, fully-tested cluster with one command.
Linux (I use Ubuntu) and a willingness to run commands in your own terminal. Everything else will be installed along the way with instructions provided in the article or from their official links.
1. Why a local lab – and why these tools are ideal for learning
I did a lot of practicing with Kubernetes before taking my KCNA exam some time ago because I believe the best way to learn something is to play with it a lot. Make something, try some ideas out and then break it to see if I can fix it somehow to make it work again – Make Shake and Break as I call it. This is my goal for experimenting and playing with ideas as I try to learn something. In this article I will share one of many practice sessions as an article form that is hopefully easy to follow along. I also need it as a souvenir. 🙂
Kubernetes RBAC is one of those topics that feels simple in a diagram and painful in production because RBAC is also almost uniquely silent in how it breaks. A typo in your apiGroups or a missing list verb does not produce a loud failure – it produces a quiet no. There’s no compiler warning, and the API server is perfectly happy to accept a Role that grants access to a resource type that does not exist. That is precisely why RBAC is worth learning by doing on a throwaway cluster rather than by reading, and why the tool choices below matter so much.
Here’s why each tool is not just convenient, but genuinely great for learning:
k3d – real clusters you can destroy without fear
k3d runs k3s (a lightweight, CNCF-certified Kubernetes distribution) inside Docker containers. The API server you’ll talk to is a real Kubernetes API server – RBAC, ServiceAccounts, certificates, admission controllers, all of it behaves exactly as it does in production. What k3d adds is that the whole cluster lives in a couple of containers, so:
- Create time is seconds, not minutes.
k3d cluster delete rbac-labwipes everything – mistakes have literally zero cost, which is the single most important property for learning.- RAM usage is modest (a few GB), so it runs happily on a laptop alongside an editor.
The freedom to destroy and rebuild is the whole pedagogical trick: you can afford to break things deliberately.
kubectl – the canonical interface and the most important probe
kubectl has the auth subcommand which is the star of this course. kubectl auth can-i <verb> <resource> --as=<identity> -n <namespace> asks the API server “can this identity do this thing here?” and prints a clean yes or no. That single probe turns RBAC from something you read about into something you measure, which is the difference between guessing and knowing.
k9s – instant, live inspection in the terminal
k9s is a terminal UI for Kubernetes, and it is the fastest way to check Roles, RoleBindings, ClusterRoles, and ServiceAccounts without writing ten kubectl get ... -o yaml commands. Two things make it great for this lab specifically:
- You can type
:role,:rolebinding,:clusterrole,:saand dive into any object with Enter. - You can launch k9s as a restricted user (pointing at a locked-down kubeconfig). Suddenly the UI itself starts refusing to show you
secrets– you feel least privilege from the inside instead of just reading about it.
Freelens – the visual graph that builds intuition
Freelens (a community fork of the Lens Kubernetes IDE) shows the relationship ServiceAccount -> RoleBinding -> Role as a clickable graph. When you have three or four bindings, raw YAML is fine; when you have a dozen, the graph is what saves you. For a learner, the value is that it converts RBAC from “tokens in YAML” into a picture in your head – which is exactly the mental model you’ll carry into production.
bats – turning every stage into a regression suite
Here’s the insight that upgrades this from “tutorial” to “training”: every RBAC check you can do by hand, you can also assert automatically. kubectl auth can-i returns exit code 0 for yes and 1 for no, which is exactly the shape of a unit test. bats-core is a Bash testing framework built for “run a command, assert on its output and exit code” – and that’s all RBAC validation is.
The payoff is threefold:
- Each stage of the course becomes a
.batsfile withsetup_file(apply manifests) -> test cases (allowed and denied checks) ->teardown_file(delete manifests). - The k3d cluster lifecycle maps cleanly onto bats’ setup/teardown hooks, so your tests can spin up a fresh cluster per run.
- You end up with a regression suite: tweak a Role later and rerun the suite to see instantly whether a permission boundary broke. This is genuinely how RBAC gets validated in production pipeline, so it is not a toy – it is the real skill.
kubectl-who-can (via krew) – auditing in the reverse direction
auth can-i asks “can this subject do X?” kubectl-who-can asks the opposite: “who can do X on Y?” A krew plugin, it lists every binding that grants a given verb/resource – the tool you’ll reach for when you inherit a cluster and ask “who on earth can delete secrets here?”
openssl – because Kubernetes has no User objects
One of the most eye-opening facts in this course: Kubernetes has no User API object. Human identity is whatever your client certificate (or token) says it is. Generating real certs with openssl – signing them with the cluster’s own CA and authenticating for real over TLS – transforms an abstract sentence into something you’ve done with your own hands.
Tool setup
Some of the tools like freelens, k9s, can be installed by downloading the `.deb` file from the release page on the github repo and running a command like:
sudo dpkg -i [filename].deb
Others have their setup instructions linked here: kubectl, Docker Engine, k3d, k9s
2. The course at a glance
| Stage | Topic | What you’ll prove |
|---|---|---|
| 0 | Environment sanity check + bats scaffolding | Tools wired up; test harness works |
| 1 | RBAC mental model | Understand Roles/Bindings before touching the cluster |
| 2 | ServiceAccounts + default deny | A fresh identity can do almost nothing |
| 3 | Roles + RoleBindings (namespace-scoped) | Read-only Pod access in one namespace only |
| 4 | ClusterRoles, both binding styles | Cluster-wide vs. namespace-scoped grants, same Role |
| 5 | Real users via client certificates | A hand-rolled cert authenticates as a real user |
| 6 | Groups + aggregated ClusterRoles | Group-based grants; how edit is actually assembled |
| 7 | Least-privilege auditing | Tighten an over-permissive setup with audit tools |
| 8 | Debugging drills | Diagnose 5 notoriously silent RBAC failures |
| 9 | Full automation | One command: create -> test -> tear down |
Every stage from 2 onward ends with a bats file you run until it is green. Green is the definition of “you’ve got it.”
3. Stage 0 – Build the sandbox
3.1 Create the cluster and verify the toolchain
k3d version
k3d cluster create rbac-lab --wait
# you can add something like
# --image rancher/k3s:v1.36.4-k3s1
# to choose a version of k3s from https://hub.docker.com/r/rancher/k3s/tags
# that matches your kubectl version
kubectl cluster-info
kubectl get nodes
You should see one node in Ready state. This is your disposable lab.
k3d auto-merges a context into your kubeconfig, but confirm you’re on the right context before doing anything RBAC-related – running RBAC experiments against the wrong cluster is a classic, embarrassing mistake:
kubectl config current-context # should show: k3d-rbac-lab
kubectl config use-context k3d-rbac-lab
3.2 Verify k9s and Freelens
k9s version
k9s --context k3d-rbac-lab
Inside k9s, type :ns and confirm you can see default, kube-system, etc. Quit with :q.
Then open Freelens, add the k3d-rbac-lab context from its cluster list, and confirm it connects. Leave it open – you’ll use it visually in every stage.
3.3 Install krew + kubectl-who-can
Based on https://krew.sigs.k8s.io/docs/user-guide/setup/install/
Instructions below assume you are using Zsh. If using Bash, replace .zshrc with ./bashrc
# krew (if not already installed)
(
set -x; cd "$(mktemp -d)" &&
OS="$(uname | tr '[:upper:]' '[:lower:]')" &&
ARCH="$(uname -m | sed -e 's/x86_64/amd64/' -e 's/\(arm\)\(64\)\?.*/\1\2/' -e 's/aarch64$/arm64/')" &&
KREW="krew-${OS}_${ARCH}" &&
curl -fsSLO "https://github.com/kubernetes-sigs/krew/releases/latest/download/${KREW}.tar.gz" &&
tar zxvf "${KREW}.tar.gz" &&
./"${KREW}" install krew
)
echo 'export PATH="${KREW_ROOT:-$HOME/.krew}/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
kubectl krew install who-can
kubectl who-can list pods
3.4 Install bats-core and scaffold the project
sudo apt update
sudo apt install -y bats git
bats --version
Then the project layout. Every stage’s manifests go in its own directory; every stage’s tests in theirs:
mkdir -p rbac-lab/{clusters,manifests,tests}
cd rbac-lab
git init
mkdir -p tests/test_helper
git submodule add https://github.com/bats-core/bats-support.git tests/test_helper/bats-support
git submodule add https://github.com/bats-core/bats-assert.git tests/test_helper/bats-assert
3.5 The sanity test
Before writing a single RBAC assertion, prove the harness itself works. You want to catch “my test framework is misconfigured” separately from “my RBAC is misconfigured”:
cat > tests/stage0_sanity.bats << 'EOF'
#!/usr/bin/env bats
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
@test "kubectl can reach the k3d-rbac-lab cluster" {
run kubectl cluster-info --context k3d-rbac-lab
assert_success
}
@test "cluster has at least one Ready node" {
run kubectl get nodes --context k3d-rbac-lab --no-headers
assert_success
assert_output --partial "Ready"
}
EOF
bats tests/stage0_sanity.bats
Two green checks mean: cluster live, kubectl/k9s/Freelens wired, krew working, bats working – a clean baseline for everything that follows.
4. Stage 1 – The RBAC mental model
Before touching the cluster, get the shape right – it is four object types and two axes:
| Namespace-scoped | Cluster-scoped | |
|---|---|---|
| Permission definition | Role |
ClusterRole |
| Grant to a subject | RoleBinding |
ClusterRoleBinding |
A RoleBinding can reference a ClusterRole – that’s how you reuse one ClusterRole (like the built-in view) but scope its grant to a single namespace. A ClusterRoleBinding can only reference a ClusterRole, never a Role. We’ll prove this live in Stage 4.
The three kinds of subjects
- User – there is no API object. Identity comes entirely from the client certificate (or token) presented. That’s why Stage 5 generates a cert by hand.
- Group – also not an object. Derived from the certificate’s
O=(Organization) field or an identity provider claim. Stage 6. - ServiceAccount – the one subject that is a real API object (
kubectl get sa), normally used by workloads rather than humans. We start with SAs in Stage 2 because it is the easiest to create and test.
Verbs and resources
Standard verbs: get, list, watch, create, update, patch, delete, deletecollection. Resources are named by their API resources – pods, deployments, secrets – and are referenced together with their apiGroups. Here’s the first landmine: pods are a core resource whose apiGroup is the empty string, "" – not "core". deployments live under apiGroups: ["apps"]. This one-character distinction is a classic silent failure (Stage 8, Bug 1).
Explore the built-in ClusterRoles
Every cluster ships with view, edit, admin, and cluster-admin – the best real-world reference for writing your own:
kubectl get clusterroles
kubectl describe clusterrole view
kubectl describe clusterrole edit
kubectl describe clusterrole admin
kubectl describe clusterrole cluster-admin
What to notice:
view– read-only across most resources, but deliberately excludessecrets. Reading Secrets is treated as strictly more sensitive than other reads. Keep this in your back pocket; it matters in Stage 6.edit– write verbs on most resources, but still can’t touch RBAC objects or resource quotas.admin– full control within a namespace, including managing Roles/RoleBindings inside that namespace – but nothing cluster-scoped.cluster-admin–*verbs on*resources in*apiGroups. The nuclear option.
One more peek – this is where the aggregation preview lives:
kubectl get clusterrole edit -o yaml | head -20
You’ll see an aggregationRule with a clusterRoleSelectors matching a label like rbac.authorization.k8s.io/aggregate-to-edit: "true". edit‘s actual permission list is assembled from other ClusterRoles carrying that label – not hardcoded. That’s Stage 6 material.
The secure-by-default baseline
kubectl auth can-i --list --as=system:serviceaccount:default:default
That is the default ServiceAccount every pod gets automatically. Notice how little it can do – that near-empty list is the “secure by default” baseline. Every later stage builds on top of it.
5. Stage 2 – ServiceAccounts and the default-deny baseline
5.1 Create the lab namespace and a bare ServiceAccount
kubectl create namespace rbac-lab
mkdir -p manifests/stage2
cat > manifests/stage2/serviceaccount.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: lab-reader
namespace: rbac-lab
EOF
kubectl apply -f manifests/stage2/serviceaccount.yaml
kubectl get sa -n rbac-lab
lab-reader exists but has no Role or RoleBinding attached. That’s the whole point of this stage.
5.2 Prove it can do almost nothing
kubectl auth can-i list pods \
--as=system:serviceaccount:rbac-lab:lab-reader \
-n rbac-lab
kubectl auth can-i --list \
--as=system:serviceaccount:rbac-lab:lab-reader \
-n rbac-lab
The first prints no. The second dumps the full (near-empty) permission list. An unbound ServiceAccount has essentially zero access.
5.3 See it in k9s and Freelens
- k9s:
:sa, selectlab-reader, press Enter to describe – no associated bindings. - Freelens: Access Control -> Service Accounts ->
lab-reader– empty permissions/bindings panel.
5.4 The bats suite – asserting the absence of permissions
cat > tests/stage2_serviceaccount.bats << 'EOF'
#!/usr/bin/env bats
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
SA="system:serviceaccount:rbac-lab:lab-reader"
setup_file() {
kubectl create namespace rbac-lab --dry-run=client -o yaml | kubectl apply -f -
kubectl apply -f manifests/stage2/serviceaccount.yaml
}
@test "lab-reader ServiceAccount exists" {
run kubectl get sa lab-reader -n rbac-lab
assert_success
}
@test "lab-reader cannot list pods (no binding yet)" {
run kubectl auth can-i list pods --as="$SA" -n rbac-lab
assert_output "no"
}
@test "lab-reader cannot list secrets" {
run kubectl auth can-i list secrets --as="$SA" -n rbac-lab
assert_output "no"
}
@test "lab-reader cannot do anything cluster-scoped" {
run kubectl auth can-i list nodes --as="$SA"
assert_line "no"
}
EOF
bats tests/stage2_serviceaccount.bats
All four green. Asserting the absence of permissions is just as important a regression check as asserting presence – this is exactly the test that catches someone later accidentally attaching cluster-admin to this ServiceAccount.
6. Stage 3 – Roles and RoleBindings
This is the pattern that covers ~80% of real-world RBAC: a namespaced Role + a namespaced RoleBinding. Everything after this is variations on it.
6.1 Write the Role
mkdir -p manifests/stage3
cat > manifests/stage3/role.yaml << 'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: pod-reader
namespace: rbac-lab
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
EOF
apiGroups: [""] – pods are a core resource, empty group. Internalize this now; Stage 8 will deliberately break it.
6.2 Write the RoleBinding
cat > manifests/stage3/rolebinding.yaml << 'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: lab-reader-binding
namespace: rbac-lab
subjects:
- kind: ServiceAccount
name: lab-reader
namespace: rbac-lab
roleRef:
kind: Role
name: pod-reader
apiGroup: rbac.authorization.k8s.io
EOF
The RoleBinding itself lives in rbac-lab (metadata.namespace) – that’s what scopes the grant to this namespace, regardless of where the subject “lives.”
6.3 Apply and verify
kubectl apply -f manifests/stage3/role.yaml
kubectl apply -f manifests/stage3/rolebinding.yaml
kubectl auth can-i list pods \
--as=system:serviceaccount:rbac-lab:lab-reader -n rbac-lab
# should now be: yes
kubectl auth can-i list pods \
--as=system:serviceaccount:rbac-lab:lab-reader -n default
# should still be: no - different namespace, no binding there
kubectl auth can-i delete pods \
--as=system:serviceaccount:rbac-lab:lab-reader -n rbac-lab
# should be: no - Role only grants get/list/watch, not delete
6.4 Inspect in k9s and Freelens
- k9s:
:role->pod-reader-> EnterDfor Describe to see the rule and notice the Verbs[get list watch];:rolebinding->lab-reader-binding-> EnterDfor Describe to see it linking Role -> ServiceAccount. - Freelens: Access Control -> Roles / Role Bindings – click through the subject/role graph showing
lab-reader -> pod-reader. This visual graph is exactly what gets harder to track the moment you have a dozen bindings.
6.5 The bats suite
cat > tests/stage3_role_rolebinding.bats << 'EOF'
#!/usr/bin/env bats
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
SA="system:serviceaccount:rbac-lab:lab-reader"
setup_file() {
kubectl apply -f manifests/stage3/role.yaml
kubectl apply -f manifests/stage3/rolebinding.yaml
}
teardown_file() {
kubectl delete -f manifests/stage3/rolebinding.yaml --ignore-not-found
kubectl delete -f manifests/stage3/role.yaml --ignore-not-found
}
@test "lab-reader can list pods in rbac-lab" {
run kubectl auth can-i list pods --as="$SA" -n rbac-lab
assert_output "yes"
}
@test "lab-reader can get pods in rbac-lab" {
run kubectl auth can-i get pods --as="$SA" -n rbac-lab
assert_output "yes"
}
@test "lab-reader cannot list pods in default namespace" {
run kubectl auth can-i list pods --as="$SA" -n default
assert_output "no"
}
@test "lab-reader cannot delete pods in rbac-lab" {
run kubectl auth can-i delete pods --as="$SA" -n rbac-lab
assert_output "no"
}
@test "lab-reader cannot list secrets in rbac-lab" {
run kubectl auth can-i list secrets --as="$SA" -n rbac-lab
assert_output "no"
}
EOF
bats tests/stage3_role_rolebinding.bats
Notice teardown_file removes the Role/RoleBinding – unlike Stage 2, these tests run against a clean before/after state. This stage is the one to sit with: it is the pattern, and the allowed/denied pairs are the shape of every suite that follows.
7. Stage 4 – ClusterRoles and the two ways to bind them
Two parts: (A) true cluster-wide access via ClusterRoleBinding, and (B) the trick that confuses everyone – a namespaced RoleBinding that references a ClusterRole, scoping the grant down.
7.1 Write a ClusterRole
mkdir -p manifests/stage4
cat > manifests/stage4/clusterrole.yaml << 'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: pod-reader-cluster
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
EOF
kubectl apply -f manifests/stage4/clusterrole.yaml
Notice: no namespace field – ClusterRoles are always cluster-scoped objects, regardless of how they get bound.
7.2A Bind it cluster-wide
Create a second ServiceAccount so you don’t muddy Stage 3’s results:
cat > manifests/stage4/serviceaccount-cluster.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: lab-cluster-reader
namespace: rbac-lab
EOF
cat > manifests/stage4/clusterrolebinding.yaml << 'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: lab-cluster-reader-binding
subjects:
- kind: ServiceAccount
name: lab-cluster-reader
namespace: rbac-lab
roleRef:
kind: ClusterRole
name: pod-reader-cluster
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f manifests/stage4/serviceaccount-cluster.yaml
kubectl apply -f manifests/stage4/clusterrolebinding.yaml
Verify it is genuinely cluster-wide – same identity, every namespace, still yes:
kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:lab-cluster-reader -n rbac-lab # yes
kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:lab-cluster-reader -n default # yes
kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:lab-cluster-reader -n kube-system # yes
7.2B Bind the same ClusterRole with a namespaced RoleBinding
This is the real-world pattern: reuse a shared ClusterRole definition, scope per-team via RoleBinding.
cat > manifests/stage4/serviceaccount-scoped.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: lab-scoped-reader
namespace: rbac-lab
EOF
cat > manifests/stage4/rolebinding-to-clusterrole.yaml << 'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: lab-scoped-reader-binding
namespace: rbac-lab
subjects:
- kind: ServiceAccount
name: lab-scoped-reader
namespace: rbac-lab
roleRef:
kind: ClusterRole
name: pod-reader-cluster
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f manifests/stage4/serviceaccount-scoped.yaml
kubectl apply -f manifests/stage4/rolebinding-to-clusterrole.yaml
kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:lab-scoped-reader -n rbac-lab # yes
kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:lab-scoped-reader -n default # no
That contrast is the whole lesson of this stage: identical ClusterRole, different binding, different scope.
7.3 Visual inspection
- k9s:
:clusterrole->pod-reader-cluster;:clusterrolebinding->lab-cluster-reader-binding(note: no namespace column – it is cluster-scoped);:rolebindinginrbac-lab->lab-scoped-reader-bindingand describe –roleRef.kind: ClusterRoleis the visual tell that this binding borrows a cluster-scoped definition. - Freelens: compare the two binding types side by side – the
roleRefpointing at a ClusterRole is usually rendered with a different icon than Stage 3’s.
7.4 The bats suite
cat > tests/stage4_clusterrole.bats << 'EOF'
#!/usr/bin/env bats
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
CLUSTER_SA="system:serviceaccount:rbac-lab:lab-cluster-reader"
SCOPED_SA="system:serviceaccount:rbac-lab:lab-scoped-reader"
setup_file() {
kubectl apply -f manifests/stage4/clusterrole.yaml
kubectl apply -f manifests/stage4/serviceaccount-cluster.yaml
kubectl apply -f manifests/stage4/clusterrolebinding.yaml
kubectl apply -f manifests/stage4/serviceaccount-scoped.yaml
kubectl apply -f manifests/stage4/rolebinding-to-clusterrole.yaml
}
teardown_file() {
kubectl delete -f manifests/stage4/rolebinding-to-clusterrole.yaml --ignore-not-found
kubectl delete -f manifests/stage4/clusterrolebinding.yaml --ignore-not-found
kubectl delete -f manifests/stage4/serviceaccount-scoped.yaml --ignore-not-found
kubectl delete -f manifests/stage4/serviceaccount-cluster.yaml --ignore-not-found
kubectl delete -f manifests/stage4/clusterrole.yaml --ignore-not-found
}
@test "ClusterRoleBinding grants access in rbac-lab" {
run kubectl auth can-i list pods --as="$CLUSTER_SA" -n rbac-lab
assert_output "yes"
}
@test "ClusterRoleBinding grants access in default namespace too" {
run kubectl auth can-i list pods --as="$CLUSTER_SA" -n default
assert_output "yes"
}
@test "ClusterRoleBinding grants access in kube-system too" {
run kubectl auth can-i list pods --as="$CLUSTER_SA" -n kube-system
assert_output "yes"
}
@test "namespaced RoleBinding to ClusterRole grants access in rbac-lab" {
run kubectl auth can-i list pods --as="$SCOPED_SA" -n rbac-lab
assert_output "yes"
}
@test "namespaced RoleBinding to ClusterRole does NOT grant access in default" {
run kubectl auth can-i list pods --as="$SCOPED_SA" -n default
assert_output "no"
}
EOF
bats tests/stage4_clusterrole.bats
That last pair (yes in rbac-lab, no in default, same ClusterRole) locks in the concept. Get it backwards in a later manifest, and this test catches it immediately.
8. Stage 5 – Real human users via client certificates
Until now we’ve impersonated identities with --as. Time for the real thing: a human user whose identity is a certificate we generated ourselves.
8.1 Get the cluster’s client CA
k3d clusters run as Docker containers, and k3s stores its CA inside the server container. Find it and pull out the client CA (the one that signs client certs – not server-ca, which signs the API server’s own TLS cert):
docker ps --filter "name=k3d-rbac-lab-server" --format "{{.Names}}"
# note the name, e.g. k3d-rbac-lab-server-0
# k3d-rbac-lab-serverlb
# k3d-rbac-lab-server-0
mkdir -p certs
docker cp k3d-rbac-lab-server-0:/var/lib/rancher/k3s/server/tls/client-ca.crt certs/
docker cp k3d-rbac-lab-server-0:/var/lib/rancher/k3s/server/tls/client-ca.key certs/
8.2 Generate a key and CSR for alice
cd certs
openssl genrsa -out alice.key 2048
openssl req -new -key alice.key -out alice.csr -subj "/CN=alice"
CN=alice is the User identity in Kubernetes. (Groups would be /CN=alice/O=<group> – that’s Stage 6.)
8.3 Sign with the cluster’s client CA
openssl x509 -req -in alice.csr \
-CA client-ca.crt -CAkey client-ca.key -CAcreateserial \
-out alice.crt -days 365
cd ..
You now hold a certificate the cluster genuinely trusts as alice.
8.4 Build alice’s kubeconfig
CLUSTER_SERVER=$(kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}')
CLUSTER_CA=$(kubectl config view --minify --raw -o jsonpath='{.clusters[0].cluster.certificate-authority-data}')
kubectl config set-cluster rbac-lab-cluster \
--server="$CLUSTER_SERVER" \
--certificate-authority=<(echo "$CLUSTER_CA" | base64 -d) \
--embed-certs=true \
--kubeconfig=certs/alice.kubeconfig
kubectl config set-credentials alice \
--client-certificate=certs/alice.crt \
--client-key=certs/alice.key \
--embed-certs=true \
--kubeconfig=certs/alice.kubeconfig
kubectl config set-context alice-context \
--cluster=rbac-lab-cluster --user=alice --namespace=rbac-lab \
--kubeconfig=certs/alice.kubeconfig
kubectl config use-context alice-context --kubeconfig=certs/alice.kubeconfig
8.5 Alice starts with nothing
kubectl --kubeconfig=certs/alice.kubeconfig get pods
Expect a Forbidden error – a fresh User identity starts with zero access, exactly like the fresh ServiceAccount in Stage 2.
8.6 Grant alice a Role
mkdir -p manifests/stage5
cat > manifests/stage5/role-user.yaml << 'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: alice-pod-reader
namespace: rbac-lab
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
EOF
cat > manifests/stage5/rolebinding-user.yaml << 'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: alice-binding
namespace: rbac-lab
subjects:
- kind: User
name: alice
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: Role
name: alice-pod-reader
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f manifests/stage5/role-user.yaml
kubectl apply -f manifests/stage5/rolebinding-user.yaml
Note kind: User in the subject – unlike ServiceAccounts, there’s nothing to kubectl get; the binding references the CN string directly.
8.7 Test as alice, for real
kubectl --kubeconfig=certs/alice.kubeconfig get pods -n rbac-lab
# should succeed (an empty list is fine - access, not data, is what we're testing)
kubectl --kubeconfig=certs/alice.kubeconfig get pods -n default
# Forbidden - same behavior as Stage 3's SA, different identity mechanism
kubectl --kubeconfig=certs/alice.kubeconfig delete pod some-pod -n rbac-lab
# Forbidden - Role only grants get/list/watch
This is a stronger proof than --as impersonation: you’re going through actual TLS client-cert auth, end to end.
8.8 Feel least privilege from the inside
k9s --kubeconfig certs/alice.kubeconfig --context alice-context
k9s itself is now constrained by alice’s permissions – try :secrets or :sa and you’ll get access errors right in the UI. That’s what least privilege feels like from the client side. Freelens shows the same if you add certs/alice.kubeconfig as an additional kubeconfig.
8.9 The bats suite
cat > tests/stage5_user_cert.bats << 'EOF'
#!/usr/bin/env bats
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
KCFG="certs/alice.kubeconfig"
setup_file() {
kubectl apply -f manifests/stage5/role-user.yaml
kubectl apply -f manifests/stage5/rolebinding-user.yaml
}
teardown_file() {
kubectl delete -f manifests/stage5/rolebinding-user.yaml --ignore-not-found
kubectl delete -f manifests/stage5/role-user.yaml --ignore-not-found
}
@test "alice cert is trusted by the API server" {
run kubectl --kubeconfig="$KCFG" auth can-i get pods -n rbac-lab
refute_output --partial "Unable to connect"
}
@test "alice can list pods in rbac-lab" {
run kubectl --kubeconfig="$KCFG" get pods -n rbac-lab
assert_success
}
@test "alice cannot list pods in default" {
run kubectl --kubeconfig="$KCFG" get pods -n default
assert_failure
assert_output --partial "forbidden"
}
@test "alice cannot delete pods in rbac-lab" {
run kubectl --kubeconfig="$KCFG" auth can-i delete pods -n rbac-lab
assert_output "no"
}
EOF
mkdir -p tests
bats tests/stage5_user_cert.bats
certs/alice.key is a real private key. Fine for a throwaway lab cluster – but make sure certs/ lands in .gitignore before this repo ever gets pushed anywhere.
echo 'certs/' >> .gitignore
Private keys generated during Stages 5/6 shouldn’t end up in version control, even for a throwaway lab. Good habit to carry into real projects.
9. Stage 6 – Groups and aggregated ClusterRoles
Two independent concepts: (A) simulating group membership via certificates, and (B) how edit is actually assembled from smaller pieces.
Part A – group membership via certs
9.1 Generate bob, who belongs to a group
cd certs
openssl genrsa -out bob.key 2048
openssl req -new -key bob.key -out bob.csr -subj "/CN=bob/O=rbac-lab-viewers"
openssl x509 -req -in bob.csr \
-CA client-ca.crt -CAkey client-ca.key -CAcreateserial \
-out bob.crt -days 365
cd ..
Every O= entry in the cert subject is group membership – a cert can carry multiple O= fields for multiple groups.
9.2 Build bob’s kubeconfig
kubectl config set-cluster rbac-lab-cluster \
--server="$CLUSTER_SERVER" \
--certificate-authority=<(echo "$CLUSTER_CA" | base64 -d) \
--embed-certs=true \
--kubeconfig=certs/bob.kubeconfig
kubectl config set-credentials bob \
--client-certificate=certs/bob.crt \
--client-key=certs/bob.key \
--embed-certs=true \
--kubeconfig=certs/bob.kubeconfig
kubectl config set-context bob-context \
--cluster=rbac-lab-cluster --user=bob --namespace=rbac-lab \
--kubeconfig=certs/bob.kubeconfig
kubectl config use-context bob-context --kubeconfig=certs/bob.kubeconfig
9.3 Bind the group, not bob
mkdir -p manifests/stage6
cat > manifests/stage6/rolebinding-group.yaml << 'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: viewers-binding
namespace: rbac-lab
subjects:
- kind: Group
name: rbac-lab-viewers
apiGroup: rbac.authorization.k8s.io
roleRef:
kind: ClusterRole
name: view
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f manifests/stage6/rolebinding-group.yaml
Notice this reuses the built-in view ClusterRole from Stage 1, bound namespaced – the Stage 4B pattern again – and the subject is kind: Group matching the O= value, not any individual username.
9.4 Verify
kubectl --kubeconfig=certs/bob.kubeconfig get pods -n rbac-lab
# succeeds - bob was never named anywhere, only his group was
kubectl --kubeconfig=certs/bob.kubeconfig get secrets -n rbac-lab
# Forbidden - recall that `view` deliberately excludes secrets
kubectl --kubeconfig=certs/bob.kubeconfig get pods -n default
# Forbidden - the RoleBinding is namespaced to rbac-lab only
The real lesson: create a second user “carol” with the same O=rbac-lab-viewers and she inherits identical access with zero new RBAC objects. This is why binding groups instead of individuals is standard practice at any real scale.
Part B – how aggregationRule composes permissions
9.5 Look at how edit is built
kubectl get clusterrole edit -o yaml
You’ll find:
aggregationRule:
clusterRoleSelectors:
- matchLabels:
rbac.authorization.k8s.io/aggregate-to-edit: "true"
The rules: block underneath is computed, not authored – the API server watches for any ClusterRole carrying that label and merges its rules automatically.
9.6 Prove it live
cat > manifests/stage6/aggregated-base.yaml << 'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: rbac-lab-aggregate-base
labels:
rbac.authorization.k8s.io/aggregate-to-edit: "true"
rules:
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get", "list", "watch", "create"]
EOF
kubectl apply -f manifests/stage6/aggregated-base.yaml
Now check edit again:
kubectl get clusterrole edit -o yaml | grep -A5 configmaps
Your configmaps rule is now merged into edit‘s computed rules – you extended a built-in role without ever editing it. This is exactly how CRD-installing Helm charts (cert-manager, Prometheus Operator, …) automatically grant edit/admin users access to their new custom resources.
9.7 The bats suite
cat > tests/stage6_groups_aggregation.bats << 'EOF'
#!/usr/bin/env bats
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
BOB_KCFG="certs/bob.kubeconfig"
setup_file() {
kubectl apply -f manifests/stage6/rolebinding-group.yaml
kubectl apply -f manifests/stage6/aggregated-base.yaml
}
teardown_file() {
kubectl delete -f manifests/stage6/rolebinding-group.yaml --ignore-not-found
kubectl delete -f manifests/stage6/aggregated-base.yaml --ignore-not-found
}
@test "bob (via group) can list pods in rbac-lab" {
run kubectl --kubeconfig="$BOB_KCFG" get pods -n rbac-lab
assert_success
}
@test "bob (via group, view role) cannot list secrets" {
run kubectl --kubeconfig="$BOB_KCFG" auth can-i list secrets -n rbac-lab
assert_output "no"
}
@test "bob cannot access outside rbac-lab" {
run kubectl --kubeconfig="$BOB_KCFG" get pods -n default
assert_failure
}
@test "custom aggregate-to-edit label merges into built-in edit ClusterRole" {
run kubectl get clusterrole edit -o jsonpath='{.rules[?(@.resources[0]=="configmaps")].verbs}'
assert_output --partial "create"
}
EOF
bats tests/stage6_groups_aggregation.bats
That last test asserts on a computed object rather than something you applied directly – a good habit for validating aggregation-based extension patterns in real clusters too.
10. Stage 7 – Auditing down to least privilege
Now flip the workflow: start over-permissive and use audit tools to find and strip what shouldn’t be there.
10.1 Create a deliberately sloppy setup
mkdir -p manifests/stage7
cat > manifests/stage7/overpermissive.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: lab-app
namespace: rbac-lab
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: lab-app-role
rules:
- apiGroups: [""]
resources: ["pods", "secrets", "configmaps", "services", "persistentvolumeclaims"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["apps"]
resources: ["deployments", "replicasets"]
verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
- apiGroups: ["rbac.authorization.k8s.io"]
resources: ["roles", "rolebindings"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: lab-app-binding
subjects:
- kind: ServiceAccount
name: lab-app
namespace: rbac-lab
roleRef:
kind: ClusterRole
name: lab-app-role
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f manifests/stage7/overpermissive.yaml
A realistic “someone copy-pasted edit-ish permissions and bound it cluster-wide” scenario: full CRUD on Secrets, cluster-wide scope, and read access to the RBAC objects themselves. The premise: this ServiceAccount actually only needs to read Pods and read/write ConfigMaps in rbac-lab.
10.2 Audit from the subject side
SA="system:serviceaccount:rbac-lab:lab-app"
kubectl auth can-i --list --as="$SA" -n rbac-lab
Read through every row and ask: does lab-app actually need this? Flag anything touching secrets, deployments, pvc, or anything cluster-scoped.
10.3 Audit from the resource side with kubectl-who-can
The reverse direction – “who can do X on Y?”:
kubectl who-can delete secrets
kubectl who-can list secrets -n rbac-lab
kubectl who-can '*' '*'
That last one is worth running on any real cluster you inherit – it surfaces every binding granting blanket access, which is exactly the kind of thing that accumulates silently over time.
10.4 Tighten it
Replace the ClusterRole/ClusterRoleBinding with a scoped Role/RoleBinding:
cat > manifests/stage7/tightened.yaml << 'EOF'
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: lab-app-role-tight
namespace: rbac-lab
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources: ["configmaps"]
verbs: ["get", "list", "watch", "create", "update", "patch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: lab-app-binding-tight
namespace: rbac-lab
subjects:
- kind: ServiceAccount
name: lab-app
namespace: rbac-lab
roleRef:
kind: Role
name: lab-app-role-tight
apiGroup: rbac.authorization.k8s.io
EOF
# Remove only the over-broad role and binding - keep the ServiceAccount itself
kubectl delete clusterrole lab-app-role
kubectl delete clusterrolebinding lab-app-binding
kubectl apply -f manifests/stage7/tightened.yaml
10.5 Re-audit
kubectl auth can-i --list --as="$SA" -n rbac-lab
kubectl who-can delete secrets -n rbac-lab
# lab-app should no longer appear
kubectl auth can-i get deployments --as="$SA" -n rbac-lab
# no
10.6 The bats suite – asserting absence
cat > tests/stage7_least_privilege.bats << 'EOF'
#!/usr/bin/env bats
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
SA="system:serviceaccount:rbac-lab:lab-app"
setup_file() {
kubectl apply -f manifests/stage7/tightened.yaml
}
teardown_file() {
kubectl delete -f manifests/stage7/tightened.yaml --ignore-not-found
}
@test "lab-app can still read pods (needed permission preserved)" {
run kubectl auth can-i get pods --as="$SA" -n rbac-lab
assert_output "yes"
}
@test "lab-app can manage configmaps (needed permission preserved)" {
run kubectl auth can-i create configmaps --as="$SA" -n rbac-lab
assert_output "yes"
}
@test "lab-app CANNOT touch secrets" {
run kubectl auth can-i get secrets --as="$SA" -n rbac-lab
assert_output "no"
}
@test "lab-app CANNOT touch deployments" {
run kubectl auth can-i delete deployments --as="$SA" -n rbac-lab
assert_output "no"
}
@test "lab-app CANNOT read RBAC objects" {
run kubectl auth can-i list roles --as="$SA" -n rbac-lab
assert_output "no"
}
@test "lab-app has no cluster-wide access" {
run kubectl auth can-i get pods --as="$SA" -n default
assert_output "no"
}
EOF
bats tests/stage7_least_privilege.bats
This positive + negative pairing – assert what’s still allowed and what’s now denied – is the shape every least-privilege regression test should take. A tightening pass that breaks the app is just as much a bug as one that leaves a hole open.
11. Stage 8 – Debugging drills
RBAC has almost no compile-time safety net: apiGroups, resources, and roleRef.name are all just strings, validated only when something tries to actually use them. That silence is why these drills matter – diagnosing a Forbidden error quickly is the real-world skill this stage builds.
Five broken manifests below. For each: apply it, run the “expected to work” command, and diagnose before reading the explanation that follows each one. Use kubectl describe role/rolebinding and kubectl get events -n rbac-lab alongside auth can-i.
mkdir -p manifests/stage8
Bug 1
cat > manifests/stage8/bug1.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: debug1
namespace: rbac-lab
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: bug1-role
namespace: rbac-lab
rules:
- apiGroups: ["core"]
resources: ["pods"]
verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: bug1-binding
namespace: rbac-lab
subjects:
- kind: ServiceAccount
name: debug1
namespace: rbac-lab
roleRef:
kind: Role
name: bug1-role
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f manifests/stage8/bug1.yaml
kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:debug1 -n rbac-lab
Diagnosis: Wrong apiGroup "core" is simply not a valid apiGroup string. Kubernetes has exactly one way to reference the core group: the empty string "". There is no group literally named "core" anywhere in the API, so apiGroups: ["core"] matches zero resources. The Role technically applies – it just grants access to a group that doesn’t exist, which is functionally granting nothing. Fix: apiGroups: [""].
Bug 2
cat > manifests/stage8/bug2.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: debug2
namespace: rbac-lab
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: bug2-binding
namespace: rbac-lab
subjects:
- kind: ServiceAccount
name: debug2
namespace: rbac-lab
roleRef:
kind: ClusterRole
name: bug2-role
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f manifests/stage8/bug2.yaml
kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:debug2 -n rbac-lab
Run kubectl get clusterrole bug2-role – what do you see, and what’s missing?
Diagnosis: roleRef points at something that does not exist roleRef.kind: ClusterRole, name: bug2-role points at a ClusterRole that was never created – only the RoleBinding and ServiceAccount exist in this manifest. RoleBindings don’t validate that their roleRef target exists at apply time: the binding happily applies while pointing at nothing, so it grants nothing. Sneaky, precisely because kubectl apply gives you no error at all.
Bug 3
cat > manifests/stage8/bug3.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: debug3
namespace: default
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: bug3-role
namespace: rbac-lab
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: bug3-binding
namespace: rbac-lab
subjects:
- kind: ServiceAccount
name: debug3
namespace: rbac-lab
roleRef:
kind: Role
name: bug3-role
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f manifests/stage8/bug3.yaml
kubectl auth can-i list pods --as=system:serviceaccount:default:debug3 -n rbac-lab
Diagnosis: namespace mismatch on the SA subject the SA exists, the Role exists, the binding applied fine – still no. The subjects[0].namespace: rbac-lab in the binding doesn’t describe where the binding lives; it identifies which ServiceAccount is being referenced (SAs are namespaced objects). The actual debug3 was created in default, so the binding references a rbac-lab/debug3 that doesn’t exist – and the real identity system:serviceaccount:default:debug3 was never granted anything.
Bug 4
cat > manifests/stage8/bug4.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: debug4
namespace: rbac-lab
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: bug4-role
namespace: rbac-lab
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: bug4-binding
namespace: rbac-lab
subjects:
- kind: ServiceAccount
name: debug4
namespace: rbac-lab
roleRef:
kind: Role
name: bug4-role
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f manifests/stage8/bug4.yaml
kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:debug4 -n rbac-lab
no – but kubectl auth can-i get pods --as=... -n rbac-lab returns yes. What’s the lesson?
Diagnosis: missing verb get and list are separate, independent verbs – they don’t imply each other. “I can read it” is a mental shortcut that Kubernetes doesn’t share: every verb is its own explicit grant. watch is the same story, often needed alongside list for anything streaming updates (like kubectl get -w or most controllers).
Bug 5
cat > manifests/stage8/bug5.yaml << 'EOF'
apiVersion: v1
kind: ServiceAccount
metadata:
name: debug5
namespace: rbac-lab
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: bug5-role
namespace: rbac-lab
rules:
- apiGroups: [""]
resources: ["pod"]
verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: bug5-binding
namespace: rbac-lab
subjects:
- kind: ServiceAccount
name: debug5
namespace: rbac-lab
roleRef:
kind: Role
name: bug5-role
apiGroup: rbac.authorization.k8s.io
EOF
kubectl apply -f manifests/stage8/bug5.yaml
kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:debug5 -n rbac-lab
Diagnosis: resource name typo resources: ["pod"] – singular, should be "pods" (plural, matching the actual API resource name). Same failure mode as Bug 2: the API server performs no validation that "pod" corresponds to a real resource – RBAC rules are just arbitrary strings from its point of view. The Role applies cleanly, describes cleanly, and grants access to a resource type that doesn’t exist. Arguably the nastiest of the five, because nothing flags it except a permission test.
The lesson across all five
Kubernetes RBAC has almost no compile-time safety – apiGroups, resources, and roleRef.name are all just strings, validated only at the moment something tries to actually use them. Which is exactly why the bats regression suite matters more here than in almost any other area of Kubernetes config.
The bats suite – known-broken states, documented
cat > tests/stage8_debugging.bats << 'EOF'
#!/usr/bin/env bats
load 'test_helper/bats-support/load'
load 'test_helper/bats-assert/load'
setup_file() {
for f in manifests/stage8/bug*.yaml; do
kubectl apply -f "$f"
done
}
teardown_file() {
for f in manifests/stage8/bug*.yaml; do
kubectl delete -f "$f" --ignore-not-found
done
}
@test "bug1: wrong apiGroup ('core' instead of '') denies access" {
run kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:debug1 -n rbac-lab
assert_output "no"
}
@test "bug2: roleRef to nonexistent ClusterRole denies access" {
run kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:debug2 -n rbac-lab
assert_regex "no - RBAC: clusterrole.rbac.authorization.k8s.io .* not found"
}
@test "bug2: the referenced ClusterRole genuinely does not exist" {
run kubectl get clusterrole bug2-role
assert_failure
}
@test "bug3: SA namespace mismatch denies access to the real SA" {
run kubectl auth can-i list pods --as=system:serviceaccount:default:debug3 -n rbac-lab
assert_output "no"
}
@test "bug4: 'get' verb does not imply 'list'" {
run kubectl auth can-i get pods --as=system:serviceaccount:rbac-lab:debug4 -n rbac-lab
assert_output "yes"
run kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:debug4 -n rbac-lab
assert_output "no"
}
@test "bug5: singular 'pod' resource name grants nothing" {
run kubectl auth can-i list pods --as=system:serviceaccount:rbac-lab:debug5 -n rbac-lab
assert_output "no"
}
EOF
bats tests/stage8_debugging.bats
This suite asserts that known traps stay broken in a specific, understood way – it documents “here’s exactly why these are traps,” so future-you or a teammate hits the failure with the explanation already attached.
12. Stage 9 – One-command automation
Time to wire the whole lab together: ./run-lab.sh from nothing -> fully validated cluster -> clean teardown.
12.1 The run script
cat > run-lab.sh << 'EOF'
#!/usr/bin/env bash
set -euo pipefail
CLUSTER_NAME="rbac-lab"
CONTEXT="k3d-${CLUSTER_NAME}"
KEEP_CLUSTER=false
usage() {
echo "Usage: $0 [--keep]"
echo " --keep don't delete the cluster after tests run (default: tear down)"
exit 1
}
for arg in "$@"; do
case "$arg" in
--keep) KEEP_CLUSTER=true ;;
-h|--help) usage ;;
esac
done
cleanup() {
if [ "$KEEP_CLUSTER" = false ]; then
echo "==> Tearing down cluster ${CLUSTER_NAME}"
k3d cluster delete "${CLUSTER_NAME}" || true
else
echo "==> --keep passed, leaving cluster ${CLUSTER_NAME} running"
fi
}
trap cleanup EXIT
echo "==> Creating fresh k3d cluster: ${CLUSTER_NAME}"
k3d cluster delete "${CLUSTER_NAME}" 2>/dev/null || true
k3d cluster create "${CLUSTER_NAME}" --wait
kubectl config use-context "${CONTEXT}"
echo "==> Waiting for node Ready"
kubectl wait --for=condition=Ready node --all --timeout=60s
echo "==> Creating rbac-lab namespace"
kubectl create namespace rbac-lab --dry-run=client -o yaml | kubectl apply -f -
echo "==> Extracting client CA for cert-based user tests (Stage 5/6)"
SERVER_CONTAINER=$(docker ps --filter "name=${CLUSTER_NAME}-server" --format "{{.Names}}" | head -1)
if [ -n "$SERVER_CONTAINER" ]; then
docker cp "${SERVER_CONTAINER}:/var/lib/rancher/k3s/server/tls/client-ca.crt" certs/client-ca.crt
docker cp "${SERVER_CONTAINER}:/var/lib/rancher/k3s/server/tls/client-ca.key" certs/client-ca.key
else
echo "WARNING: could not find server container, skipping CA extraction"
fi
echo "==> Generating alice + bob certs and kubeconfigs (Stage 5/6 prerequisites)"
bash scripts/generate-user-certs.sh
echo "==> Running full bats suite, stage by stage"
FAILED=0
for f in tests/stage*.bats; do
echo ""
echo "---- $f ----"
bats "$f" || FAILED=1
done
if [ "$FAILED" -ne 0 ]; then
echo ""
echo "==> One or more stages FAILED. See output above."
exit 1
fi
echo ""
echo "==> All stages passed."
EOF
chmod +x run-lab.sh
12.2 Extract the cert-generation into a reusable script
mkdir -p scripts
cat > scripts/generate-user-certs.sh << 'EOF'
#!/usr/bin/env bash
set -euo pipefail
cd certs
CLUSTER_SERVER=$(kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}')
CLUSTER_CA_DATA=$(kubectl config view --minify --raw -o jsonpath='{.clusters[0].cluster.certificate-authority-data}')
gen_user() {
local name="$1" subj="$2"
[ -f "${name}.key" ] || openssl genrsa -out "${name}.key" 2048
openssl req -new -key "${name}.key" -out "${name}.csr" -subj "$subj"
openssl x509 -req -in "${name}.csr" \
-CA client-ca.crt -CAkey client-ca.key -CAcreateserial \
-out "${name}.crt" -days 365
kubectl config set-cluster rbac-lab-cluster \
--server="$CLUSTER_SERVER" \
--certificate-authority=<(echo "$CLUSTER_CA_DATA" | base64 -d) \
--embed-certs=true --kubeconfig="${name}.kubeconfig"
kubectl config set-credentials "$name" \
--client-certificate="${name}.crt" --client-key="${name}.key" \
--embed-certs=true --kubeconfig="${name}.kubeconfig"
kubectl config set-context "${name}-context" \
--cluster=rbac-lab-cluster --user="$name" --namespace=rbac-lab \
--kubeconfig="${name}.kubeconfig"
kubectl config use-context "${name}-context" --kubeconfig="${name}.kubeconfig"
}
gen_user alice "/CN=alice"
gen_user bob "/CN=bob/O=rbac-lab-viewers"
cd ..
EOF
chmod +x scripts/generate-user-certs.sh
12.3 Run it
./run-lab.sh
That’s the entire course in one command: fresh cluster -> CA extracted -> alice/bob certs generated -> every stage’s bats file run in order -> full teardown, with a clean pass/fail summary. The cluster is deleted automatically at the end unless you pass --keep:
./run-lab.sh --keep # leaves the cluster up so you can poke around in k9s/Freelens afterward
Iterate on a single stage anytime with e.g. bats tests/stage5_user_cert.bats while the --keep cluster is up.
The finished layout
rbac-lab/
├── certs/
├── clusters/
├── manifests/
│ ├── stage2/ stage3/ stage4/ stage5/ stage6/ stage7/ stage8/
├── scripts/
│ └── generate-user-certs.sh
├── tests/
│ ├── test_helper/{bats-support,bats-assert}/
│ ├── stage0_sanity.bats ... stage8_debugging.bats
└── run-lab.sh
13. What you walk away with
If you ran every stage until green, you now have:
- A working mental model of Subjects -> Bindings -> Roles -> Verbs on Resources, namespace-scoped vs. cluster-scoped, proven live rather than memorized.
- Real muscle memory for the
can-iprobe, cert-based identities, groups, and aggregation – including the fact that Kubernetes has no User objects, and what that means. - A least-privilege workflow – audit with
auth can-i --listandkubectl who-can, tighten, and re-audit. - Intimate knowledge of the five silent failure modes of RBAC and how to diagnose each one.
- A regression suite (bats) that encodes every “allowed” and “denied” boundary – the same validation class used in production pipelines.
- A one-command, fully repeatable lab:
./run-lab.shtakes you from zero to a hardened, fully-tested cluster and back to zero.
And one more practical bonus: this exact rbac-lab/ structure is genuinely reusable if you ever want to prototype RBAC changes for a real cluster before applying them for real. Just point kubectl at a different context and skip the k3d cluster create step – the bats suites run identically, which is the whole point of having built them.
Go break something. That’s what the lab is for – and now you can do it, catch it, fix it, and prove the fix, all in the space of a few minutes and one disposable cluster.