TExcelTAD
Home › Kubernetes › RBAC

RBAC

Every request to the API server goes through three gates:

  1. Authentication: who are you? (client certificate, bearer token, OIDC login, ServiceAccount token)
  2. Authorization: are you allowed to do this? Usually RBAC (role-based access control)
  3. Admission: is this object acceptable? (quotas, Pod Security, policy engines)

RBAC is deny by default and purely additive: there are no "deny" rules. A request is allowed if any rule bound to the user allows it.

The four RBAC objects

Object Scope Contains
Role One namespace Rules: which verbs on which resources
ClusterRole Cluster-wide Same, plus cluster-scoped resources (nodes, PVs) and non-resource URLs
RoleBinding One namespace Grants a Role or ClusterRole to subjects, within that namespace
ClusterRoleBinding Cluster-wide Grants a ClusterRole to subjects in all namespaces

Subjects are User, Group or ServiceAccount. Kubernetes has no user objects: users and groups are just names asserted by the authenticator (e.g. from your company's OIDC provider).

yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: deployer
  namespace: shop
rules:
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "list", "watch", "update", "patch"]
  - apiGroups: [""]                    # "" = the core group (pods, services, ...)
    resources: ["pods", "pods/log"]
    verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: ci-deployer
  namespace: shop
subjects:
  - kind: ServiceAccount
    name: ci
    namespace: ci-system
  - kind: Group
    name: shop-developers
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: Role
  name: deployer
  apiGroup: rbac.authorization.k8s.io

Verbs map to HTTP methods: get, list, watch (reading), create, update, patch, delete, deletecollection. Subresources such as pods/log, pods/exec and deployments/scale are listed separately.

An RBAC evaluator

This model parses Roles and bindings from YAML and answers "can subject X do verb V on resource R in namespace N?", following the real rules: bindings in the namespace plus cluster-wide bindings, wildcards *, and a RoleBinding to a ClusterRole only granting within its own namespace:

python · try it yourself
import yaml

objects = list(yaml.safe_load_all("""
kind: Role
metadata: {name: deployer, namespace: shop}
rules:
  - {apiGroups: [apps], resources: [deployments], verbs: [get, list, update, patch]}
  - {apiGroups: [""], resources: [pods, pods/log], verbs: [get, list]}
---
kind: ClusterRole
metadata: {name: view-secrets}
rules:
  - {apiGroups: [""], resources: [secrets], verbs: [get, list]}
---
kind: ClusterRole
metadata: {name: cluster-admin}
rules:
  - {apiGroups: ["*"], resources: ["*"], verbs: ["*"]}
---
kind: RoleBinding
metadata: {name: dev-deployer, namespace: shop}
subjects: [{kind: Group, name: shop-devs}]
roleRef: {kind: Role, name: deployer}
---
kind: RoleBinding
metadata: {name: dev-secrets, namespace: shop}
subjects: [{kind: User, name: alice}]
roleRef: {kind: ClusterRole, name: view-secrets}
---
kind: ClusterRoleBinding
metadata: {name: admins}
subjects: [{kind: User, name: root-ops}]
roleRef: {kind: ClusterRole, name: cluster-admin}
"""))

def find_role(kind, name, namespace=None):
    for o in objects:
        if o["kind"] == kind and o["metadata"]["name"] == name and o["metadata"].get("namespace") == namespace:
            return o

def rule_allows(rule, verb, group, resource):
    return ((verb in rule["verbs"] or "*" in rule["verbs"]) and
            (group in rule["apiGroups"] or "*" in rule["apiGroups"]) and
            (resource in rule["resources"] or "*" in rule["resources"]))

def can(user, groups, verb, group, resource, namespace):
    for b in objects:
        if b["kind"] not in ("RoleBinding", "ClusterRoleBinding"):
            continue
        if b["kind"] == "RoleBinding" and b["metadata"]["namespace"] != namespace:
            continue
        if not any((s["kind"] == "User" and s["name"] == user) or (s["kind"] == "Group" and s["name"] in groups)
                   for s in b["subjects"]):
            continue
        ref = b["roleRef"]
        role = find_role(ref["kind"], ref["name"], b["metadata"]["namespace"] if ref["kind"] == "Role" else None)
        if role and any(rule_allows(r, verb, group, resource) for r in role["rules"]):
            return f"yes (via {b['kind']} {b['metadata']['name']})"
    return "no"

checks = [
    ("bob", ["shop-devs"], "patch", "apps", "deployments", "shop"),
    ("bob", ["shop-devs"], "delete", "apps", "deployments", "shop"),
    ("bob", ["shop-devs"], "get", "", "pods/log", "shop"),
    ("bob", ["shop-devs"], "get", "", "pods", "billing"),
    ("alice", [], "get", "", "secrets", "shop"),
    ("alice", [], "get", "", "secrets", "billing"),
    ("root-ops", [], "delete", "", "nodes", None),
]
for user, groups, verb, group, resource, ns in checks:
    where = ns or "(cluster)"
    print(f"{user:8} {verb:6} {resource:11} in {where:9} -> {can(user, groups, verb, group, resource, ns)}")
bob      patch  deployments in shop      -> yes (via RoleBinding dev-deployer)
bob      delete deployments in shop      -> no
bob      get    pods/log    in shop      -> yes (via RoleBinding dev-deployer)
bob      get    pods        in billing   -> no
alice    get    secrets     in shop      -> yes (via RoleBinding dev-secrets)
alice    get    secrets     in billing   -> no
root-ops delete nodes       in (cluster) -> yes (via ClusterRoleBinding admins)

Alice can read Secrets in shop but not in billing: the ClusterRole is reusable, but the RoleBinding limits it to its namespace.

Checking permissions for real

bash
kubectl auth can-i create deployments -n shop
kubectl auth can-i delete pods -n shop --as=bob --as-group=shop-devs
kubectl auth can-i --list -n shop --as=system:serviceaccount:ci-system:ci

Sample output:

text
yes
no
Resources                          Non-Resource URLs   Resource Names   Verbs
deployments.apps                   []                  []               [get list watch update patch]
pods                               []                  []               [get list watch]
pods/log                           []                  []               [get list watch]

Built-in ClusterRoles

ClusterRole Grants
cluster-admin Everything
admin Full control within a namespace (when bound with a RoleBinding), incl. Roles
edit Read/write most objects, but not Roles/RoleBindings
view Read-only, excluding Secrets

Least privilege

Grant the minimum: specific verbs on specific resources in specific namespaces. Some permissions are more powerful than they look. A quick audit helper that flags risky rules:

python · try it yourself
RISKY = {
    ("*", "*"): "wildcard: full access",
    ("secrets", "get"): "can read every Secret",
    ("secrets", "list"): "list returns Secret contents too",
    ("pods", "create"): "can run any image and mount any Secret in the namespace",
    ("pods/exec", "create"): "shell into running containers",
    ("rolebindings", "create"): "can grant permissions (escalation)",
    ("serviceaccounts/token", "create"): "can mint tokens for other identities",
}

rules = [
    {"resources": ["deployments"], "verbs": ["get", "patch"]},
    {"resources": ["secrets"], "verbs": ["list"]},
    {"resources": ["pods", "pods/exec"], "verbs": ["create", "get"]},
    {"resources": ["*"], "verbs": ["*"]},
]
for i, rule in enumerate(rules):
    findings = [msg for r in rule["resources"] for v in rule["verbs"]
                for (res, verb), msg in RISKY.items() if (res, verb) == (r, v)]
    print(f"rule {i}: {rule['resources']} {rule['verbs']}")
    for f in findings or ["ok"]:
        print("   -", f)
rule 0: ['deployments'] ['get', 'patch']
   - ok
rule 1: ['secrets'] ['list']
   - list returns Secret contents too
rule 2: ['pods', 'pods/exec'] ['create', 'get']
   - can run any image and mount any Secret in the namespace
   - shell into running containers
rule 3: ['*'] ['*']
   - wildcard: full access

Go further: RBAC Review: Who Can Do What finds the permissions that are worth more than they look.

Test yourself

A RoleBinding in namespace dev references a ClusterRole. Where do the permissions apply?

  1. All namespaces
  2. Only in dev
  3. Only to cluster-scoped resources
  4. Nowhere, that's invalid

How do you deny a specific action in RBAC?

  1. Add a rule with verbs: [deny]
  2. You can't; RBAC is additive, so don't grant it
  3. Use a ClusterRoleBinding with deny: true
  4. Use a negative label

Which built-in role is read-only and cannot see Secrets?

  1. admin
  2. edit
  3. view
  4. cluster-admin