Course contents · Lesson 16 of 22

Kubernetes Namespaces and RBAC for Beginners

Kubernetes Concepts · Lesson 16 of 22 · 11 min Engineer

Your team shares one Kubernetes cluster. Someone testing in dev deletes a Deployment called web, and it was production's. Elsewhere, an app needs to read its own pods, so it gets admin rights over the whole cluster. This lesson shows how namespaces and RBAC prevent both: namespaces divide a cluster into named sections, and role-based access control decides who may do what in each.

Namespaces: separate floors in one cluster

A namespace is a named section of one cluster, the "named group of objects" from lesson 8. It is not the Linux namespace from lesson 1, the kernel feature that walls off one container; only the word is shared.

Names need to be unique only within a namespace, so dev and prod can each have a Service called web. As lesson 11 showed, a pod in dev reaches its own as web and prod's as web.prod.

Many settings attach to a namespace. A ResourceQuota can cap the total its pods may request, such as 4 CPUs; once a quota covers CPU or memory, pods there must set requests or limits for it (lesson 15) or may be rejected.

In the diagram, notice that each namespace has its own web Service and quota, while nodes and PersistentVolumes belong to no namespace.

A cluster box holding three namespaces, dev, staging and prod. Each has its own Service named web, reachable as web.dev, web.staging and web.prod, two pods behind it, and its own CPU request quota of 2, 4 and 16, which are illustrative. Below, a strip of cluster-wide objects in no namespace: Nodes, PersistentVolumes, ClusterRoles and Namespaces. Footer: by default, pods can still reach other namespaces
The name web exists three times without a clash, because a name only has to be unique within its namespace.

Every cluster starts with four: default for what you create without naming a namespace, kube-system for the cluster's own parts, kube-public, readable even without logging in, and kube-node-lease for node heartbeats. Names starting with kube- are reserved.

You create a cluster in lesson 17, so read along for now. Create a namespace called dev, then list every namespace in the cluster:

kubectl create namespace dev
kubectl get namespaces

On a kind cluster you should see this; kind adds local-path-storage for its storage provisioner, and your ages will differ:

namespace/dev created
NAME                 STATUS   AGE
default              Active   20m
dev                  Active   5s
kube-node-lease      Active   20m
kube-public          Active   20m
kube-system          Active   20m
local-path-storage   Active   20m

To work in a namespace, add -n dev to a kubectl command. Without it, kubectl uses your current namespace, normally default: the usual cause of a surprising No resources found. kubectl config set-context --current --namespace=dev changes it. Careful: kubectl delete namespace deletes everything inside.

What a namespace does not do

A namespace separates names and settings, not machines or networks. Pods from different namespaces can run on the same node, sharing its kernel, and by default a pod accepts connections from any other pod, so one in dev can reach web.prod.

To block that, add a NetworkPolicy, a namespaced object listing which pods may connect to which. It works only if the cluster's network plugin enforces it; otherwise it has no effect.

So treat a namespace as a floor plan, not a vault: combine it with RBAC and network policies, and use separate clusters for strong isolation.

How the API server checks every request

Every kubectl command or app call to Kubernetes is a request to lesson 8's kube-apiserver, which runs three checks in turn.

Authentication asks "who are you?", usually from a client certificate or a token. Kubernetes stores no user accounts: a user or group is just a name that a certificate or an outside identity provider vouches for. Failing gives 401 Unauthorized.

Authorization asks "may you do this?". Kubernetes supports several modes; this lesson covers RBAC, role-based access control. It looks for a rule, in any role bound to you, that matches the verb, the resource with its API group, and the namespace. If nothing allows the request, it gets 403 Forbidden.

Admission checks run last and skip plain reads. They can change or reject a request, such as a pod that would break its namespace's quota. Then the object is saved in etcd. In the flowchart, notice that nothing has to forbid a request: without a matching rule, it is refused.

Flowchart. A request, create a pod in dev, reaches the API server. Step 1, authentication: who are you, from a client certificate or a token? No: 401 Unauthorized. Yes: step 2, RBAC: does any rule in a role bound to you match the verb, resource and namespace? No: 403 Forbidden, nothing allows it. Yes: step 3, admission checks, skipped for reads, such as ResourceQuota. Fails: rejected, for example over quota. Passes: saved in etcd. Footer: RBAC has no deny rules, so no match means no
A request must pass all three checks in order, and one that no rule allows is refused by default.

Roles, bindings and subjects

RBAC uses four objects. A role lists what may be done; a binding grants a role to subjects: users, groups or ServiceAccounts, the pod identities covered next.

ObjectScopeWhat it does
RoleOne namespacePermissions in that namespace
ClusterRoleClusterPermissions on cluster-wide objects, or reusable in any namespace
RoleBindingOne namespaceGrants a Role or ClusterRole in its namespace
ClusterRoleBindingClusterGrants a ClusterRole everywhere

Built-in ClusterRoles include view, which reads most objects but not Secrets; edit, which reads and writes most objects, Secrets included; and cluster-admin, which may do anything.

Reading a Role

Here is the Role example from the Kubernetes documentation. apiGroups names the resources' API group: "" is the core group of pods, Services and Secrets, while Deployments are in apps, as in the apps/v1 from lesson 10.

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: pod-reader
rules:
- apiGroups: [""] # "" indicates the core API group
  resources: ["pods"]
  verbs: ["get", "watch", "list"]

resources takes lowercase plurals. verbs are actions: get reads one object by name, list reads them all and watch streams changes; others include create, update and delete. Subresources, parts of an object such as a pod's logs, need their own rule: reading logs needs get on pods/log.

RBAC only adds: there are no deny rules, so the grants from all your bindings add up. A Role grants nothing until a binding uses it, and a binding's roleRef cannot be changed; you delete and recreate the binding.

In the diagram of the next section's example, notice that only the RoleBinding links the subject and the Role.

Three objects in the namespace dev. In the middle, the RoleBinding web-reads-pods. Its subjects field points to the ServiceAccount web, which could also be a User or a Group. Its roleRef field points to the Role pod-reader, which grants get, list and watch on pods in the core group. Below the Role: allowed in dev, get, list and watch on pods only. Beside it: not granted, so denied, create or delete pods, pods/log, and anything in other namespaces. Footer: roles only add permissions, and anything not listed is denied
Delete the RoleBinding and the subject loses the access, though the Role still exists.

ServiceAccounts and least privilege

A ServiceAccount is a non-human identity for software in pods. Every namespace gets one named default, given to any pod that names no other, and its token is mounted at /var/run/secrets/kubernetes.io/serviceaccount/token for calling the API server. With RBAC, default has no permissions beyond API discovery.

Least privilege means each app gets only the verbs and resources it needs, only in its namespace. Suppose an app in dev must list pods. Give it a ServiceAccount, a Role and a RoleBinding:

kubectl create serviceaccount web -n dev
kubectl create role pod-reader --verb=get,list,watch --resource=pods -n dev
kubectl create rolebinding web-reads-pods --role=pod-reader --serviceaccount=dev:web -n dev

You should see one line per command:

serviceaccount/web created
role.rbac.authorization.k8s.io/pod-reader created
rolebinding.rbac.authorization.k8s.io/web-reads-pods created

--serviceaccount takes namespace:name; plain web fails with error: serviceaccount must be <namespace>:<name>. Then set serviceAccountName: web in the pod template's spec; a running pod's ServiceAccount cannot change, so the Deployment replaces its pods. An app that never calls the API should set automountServiceAccountToken: false, leaving no token to steal.

Check with kubectl auth can-i, which asks the API server whether an action is allowed. --as asks for another identity, written system:serviceaccount:<namespace>:<name> for a ServiceAccount:

kubectl auth can-i list pods -n dev --as=system:serviceaccount:dev:web
kubectl auth can-i delete pods -n dev --as=system:serviceaccount:dev:web
kubectl auth can-i list pods -n default --as=system:serviceaccount:dev:web

You should see this, because the Role allows listing but not deleting, and only in dev:

yes
no
no

--as needs impersonation rights, which cluster administrators have. If the app itself is refused, the error names what is missing: pods is forbidden: User "system:serviceaccount:dev:web" cannot list resource "pods" in API group "" in the namespace "default".

Check yourself

Teams in the namespaces shop and billing each create a Service called api. Do the names clash, and can a shop pod call the billing one?

No clash, because names are unique only within a namespace. And yes, it can call api.billing: namespaces do not separate the network, so only an enforced NetworkPolicy would block it.

You want a user to do everything in dev except delete Secrets. Can you add a rule that denies just that?

No: RBAC has no deny rules. Grant a Role listing what they need and leave out delete on Secrets; anything not granted is refused.

You bind the ClusterRole view to a user with a RoleBinding in dev. Can they read pods in prod?

No. A RoleBinding grants only in its own namespace, even when it refers to a ClusterRole. A ClusterRoleBinding, or a RoleBinding in prod, would be needed.