Configuration, secrets, storage and access · 6 MIN READ
RBAC: ServiceAccounts, Roles and bindings for least-privilege API access
Tell authentication from authorization, grant a ServiceAccount exactly the verbs it needs with a Role and RoleBinding, verify the result with kubectl auth can-i, and call the API from Go with the pod's own identity.
Every request to the API server, from kubectl or from a controller running in a pod, is first authenticated to an identity and then authorized against rules. Role-based access control (RBAC) is how you write those rules. Done well, a compromised pod or a leaked kubeconfig can do little; done badly, everything quietly runs as cluster-admin.
kubernetes · A MAP OF THE IDEA
- One ServiceAccount per workload
- Role with only needed verbs
- RoleBinding in its namespace
- Verify with auth can-i --as
Useful when
- A leaked token can do only what its Role lists.
- auth can-i turns permissions into testable checks.
Watch out
- list on secrets, pod create and exec reveal Secrets.
- ClusterRoleBindings grant rights in every namespace.
Implementation & operation cost: A ServiceAccount, Role and RoleBinding per workload, reviewed whenever the code starts calling a new API.
Authentication, then authorization
Authentication answers who is calling. Kubernetes has no User object: people arrive with a client certificate, whose CN is the user name and whose O fields are groups, or with an OIDC token from an identity provider. kind writes a certificate for kubernetes-admin into your kubeconfig, and kubectl auth whoami shows it. Workloads use ServiceAccounts, namespaced objects the API server does store; a pod runs as one, default unless serviceAccountName says otherwise, and receives a short-lived, audience-bound token under /var/run/secrets/kubernetes.io/serviceaccount that the kubelet refreshes. Its user name is system:serviceaccount:NAMESPACE:NAME. Authorization then decides whether that identity may perform this verb on this resource; in kind the Node and RBAC authorizers decide, and admission control runs only after a request is authorized.
Roles: verbs on resources
A Role holds rules for one namespace; a ClusterRole has the same shape but is cluster-scoped, so it can cover nodes and other cluster-wide kinds or be reused in many namespaces. Each rule names apiGroups ("" is the core group with pods, services and secrets; apps holds deployments), resources including subresources such as pods/log and pods/exec, optional resourceNames, and verbs: get, list, watch, create, update, patch, delete and deletecollection. Rules only add permissions; there is no deny, so anything not granted is refused. Some grants are stronger than they look: list on secrets returns their values, create on pods lets a user run any image as any ServiceAccount of the namespace, and the escalate, bind and impersonate verbs let a subject climb past its own rights.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: pod-reader
namespace: shop
rules:
- apiGroups: [""]
resources: ["pods", "pods/log"]
verbs: ["get", "list", "watch"]
- apiGroups: ["apps"]
resources: ["deployments"]
resourceNames: ["inventory"]
verbs: ["get"]The first rule lets the subject read pods and their logs in shop, including watch, which client-go informers need. The second allows get on the one Deployment named inventory and on nothing else. Names cannot restrict create or deletecollection, and they restrict list or watch only when the request filters on metadata.name.
Bindings connect subjects to roles
A RoleBinding grants a Role, or a ClusterRole, to subjects inside its own namespace; binding a ClusterRole this way is how one definition, such as the built-in view or edit role, is reused namespace by namespace. A ClusterRoleBinding grants a ClusterRole in every namespace and on cluster-scoped resources, which an application rarely needs. Subjects are users, groups or ServiceAccounts, and a ServiceAccount subject must name its namespace. roleRef cannot be changed after creation, so you delete and recreate a binding to point it elsewhere. Changes take effect on the next request; nothing has to restart.
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: inventory-pod-reader
namespace: shop
subjects:
- kind: ServiceAccount
name: inventory
namespace: shop
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: pod-readerThe binding lives in shop, so it grants permissions only there, even if roleRef named a ClusterRole. Its subject is the inventory ServiceAccount of shop. kubectl create rolebinding inventory-pod-reader --role=pod-reader --serviceaccount=shop:inventory -n shop creates the same object.
Least privilege, checked with kubectl auth can-i
Give each workload its own ServiceAccount with no permissions, then add only the verbs its code calls. kubectl auth can-i asks the authorizer directly and exits with status 0 for yes and 1 for no, so it works in scripts and CI. --as=system:serviceaccount:shop:inventory impersonates the ServiceAccount, which needs the impersonate permission cluster admins have. A missing verb shows up in the application as a 403: pods is forbidden: User "system:serviceaccount:shop:inventory" cannot list resource "pods" in API group "" in the namespace "orders". Pods that never call the API should set automountServiceAccountToken: false, so a compromised container has no token to steal. Never grant to broad groups such as system:authenticated or system:serviceaccounts, and review who holds cluster-admin, secrets access and pods/exec.
A Go service with its ServiceAccount
Inside a pod, client-go's rest.InClusterConfig builds a configuration from the KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT variables, the mounted CA certificate and the token file, which it rereads so that rotated tokens keep working. The program then has exactly the rights of its ServiceAccount, set with serviceAccountName in the pod template. Read the pod's namespace from the mounted namespace file instead of hard-coding it, and treat a 403 as a deployment error that deserves a clear log line: it means the Role lacks a verb, not that the cluster is down, and retrying will not help.
import (
"context"
"fmt"
"log/slog"
"os"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
const nsFile = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
func listPods(ctx context.Context) error {
cfg, err := rest.InClusterConfig() // token, CA and API address of this pod
if err != nil {
return err // not running in a pod
}
cs, err := kubernetes.NewForConfig(cfg)
if err != nil {
return err
}
ns, err := os.ReadFile(nsFile)
if err != nil {
return err
}
pods, err := cs.CoreV1().Pods(string(ns)).List(ctx, metav1.ListOptions{})
if apierrors.IsForbidden(err) {
return fmt.Errorf("ServiceAccount may not list pods: %w", err)
}
if err != nil {
return err
}
for _, p := range pods.Items {
slog.Info("pod", "name", p.Name, "phase", p.Status.Phase)
}
return nil
}InClusterConfig fails outside a cluster, the signal to fall back to a kubeconfig during local development. The List call is exactly what the pod-reader Role allows, so it succeeds in shop. apierrors.IsForbidden separates an RBAC problem from network or server errors, so the log names the missing permission instead of the program retrying forever.
Try it in the lab terminal
Check which identity your kubeconfig uses, create a ServiceAccount that has no permissions, and ask the authorizer about it with kubectl auth can-i --as. Grant it get and list on pods in its own namespace with a Role and a RoleBinding, then ask again about listing, deleting, another namespace and Secrets. Finally run a Deployment whose pods use that ServiceAccount, the identity a client-go program inside them would have.
kind create cluster
kubectl auth whoami
kubectl create namespace shop
kubectl create serviceaccount inventory -n shop
kubectl auth can-i list pods -n shop --as=system:serviceaccount:shop:inventory
kubectl create role pod-reader --verb=get,list --resource=pods -n shop
kubectl create rolebinding inventory-pod-reader --role=pod-reader --serviceaccount=shop:inventory -n shop
kubectl get role pod-reader -n shop -o yaml
kubectl auth can-i list pods -n shop --as=system:serviceaccount:shop:inventory
kubectl auth can-i delete pods -n shop --as=system:serviceaccount:shop:inventory
kubectl auth can-i list pods -n default --as=system:serviceaccount:shop:inventory
kubectl auth can-i get secrets -n shop --as=system:serviceaccount:shop:inventory
cat > inventory.yaml <<'EOF'
apiVersion: apps/v1
kind: Deployment
metadata:
name: inventory
namespace: shop
spec:
replicas: 1
selector:
matchLabels:
app: inventory
template:
metadata:
labels:
app: inventory
spec:
serviceAccountName: inventory
containers:
- name: inventory
image: busybox
command: ["sleep", "3600"]
EOF
kubectl apply -f inventory.yaml
kubectl get pods -n shop -o custom-columns=NAME:.metadata.name,SERVICEACCOUNT:.spec.serviceAccountNameauth whoami prints Username kubernetes-admin, the certificate identity kind created for you. The new ServiceAccount starts with no rights, so the first can-i prints no and exits with status 1. The Role's YAML shows one rule: apiGroups "", resources pods, verbs get and list. can-i then prints yes for list pods in shop, and no for delete pods, for list pods in default and for get secrets in shop. The pod inventory-<hash>-<id> shows SERVICEACCOUNT inventory, so a client-go program inside it would get exactly these answers.
TAKE THIS WITH YOU
Authentication establishes who is calling; RBAC decides what that identity may do, through additive rules bound per namespace. Give each workload its own ServiceAccount, grant only the verbs its code uses, and prove it with kubectl auth can-i --as.
Check your understanding
A controller running as ServiceAccount shop:inventory gets "forbidden" listing pods in namespace orders, though its RoleBinding in shop grants list on pods. Why?
Go to the source
Progress stays in this browser. No account needed.