Skip to content

Chapter 08: Security, RBAC & Service Accounts

- :material-school: **Topic Focus** • ServiceAccounts, Roles, ClusterRoles, SecurityContext, and PSS - :material-api: **Primary APIs** • `rbac.authorization.k8s.io/v1`, `v1` • `Role`, `ClusterRole`, `RoleBinding`, `ServiceAccount` - :material-rocket-launch: [**Launch Playground in Wasm →**](../playground/index.html?chapter=8){ .md-button .md-button--primary }

1. Architectural Overview & Control Plane Mechanics

In Kubernetes, Security, RBAC & Service Accounts is reconciled through declarative state loops managed by the control plane and node daemons:

flowchart LR
    subgraph ClientAuth["1. Authentication (AuthN)"]
        REQ["API Request (curl/kubectl)"]
        AUTHN{"AuthN Engine<br/><i>X.509 Certs, OIDC Bearer, ServiceAccount Tokens</i>"}
        REQ --> AUTHN
    end

    subgraph RBACAuthz["2. Authorization (AuthZ)"]
        AUTHZ{"RBAC Engine<br/><i>API Groups, Resources, Verbs</i>"}
        CRB["ClusterRoleBinding / RoleBinding"]
        CR["ClusterRole / Role Rules<br/><code>verbs: [get, list, watch]</code>"]
        AUTHN -->|Authenticated User/Group| AUTHZ
        CRB --> AUTHZ
        CR --> CRB
    end

    subgraph AdmissionControl["3. Admission & Policy"]
        ADM{"Admission Controllers<br/><i>PodSecurity Standards (Restricted), Mutating/Validating</i>"}
        AUTHZ -->|Authorized| ADM
    end

    subgraph ClusterPersistence["4. Execution"]
        ETCD[("etcd Storage")]
        ADM -->|Allowed| ETCD
    end

1.1 Architectural Flow & Lifecycle Walkthrough

  1. Authentication (AuthN): A client initiates an HTTPS request to kube-apiserver. The server passes the request through configured authentication handlers in sequence:
  2. X.509 Client Certificates: Validates client certificate signatures against the cluster CA; extracts the Common Name (CN) as the Username and Organizational Units (O) as Groups.
  3. OIDC Bearer Tokens: Validates JSON Web Tokens (JWT) signed by an external identity provider (Okta, Keycloak, Dex) via public JWKS keys.
  4. ServiceAccount Tokens: Validates signed JWT service account tokens (sub: system:serviceaccount:namespace:sa-name) using RSA/ECDSA public keys.
  5. Authorization (AuthZ): The authenticated subject (User, Group, or ServiceAccount) is evaluated by the RBAC Authorization Engine. The engine performs an in-memory lookup across:
  6. Roles & RoleBindings (scoped to specific namespaces).
  7. ClusterRoles & ClusterRoleBindings (cluster-wide or across all namespaces). The engine matches the request API Group, Resource, Subresource, and Verb (get, list, watch, create, delete). If any rule matches, authorization is granted; if no rules match, the request is rejected with 403 Forbidden.
  8. Admission Control & Security Standards: Authorized requests pass through Mutating and Validating Admission Webhooks and built-in Admission Controllers, including the Pod Security Standards engine (Privileged, Baseline, Restricted).
  9. etcd Transaction: If all validation and policy checks pass, the API server commits the state change to etcd.

1.2 Serialization, Protocols & Communication Pathways

  • JWT (JSON Web Signature RFC 7515): Projected ServiceAccount tokens and OIDC tokens are base64url-encoded signed JSON payloads containing standard claims (iss, sub, aud, exp, nbf).
  • SubjectAccessReview JSON/Protobuf API: Kubernetes API enabling external proxies to delegate authorization decisions by posting authorization.k8s.io/v1 SubjectAccessReview payloads to the API server.
  • X.509 ASN.1 DER Encoding: TLS transport client certificates encoded in standard ASN.1 Distinguished Encoding Rules format.

1.3 Deep-Dive Component Breakdown

  • AuthN Authenticator Pipeline: Chain of pluggable Go authenticators (x509, Webhook, OIDC, TokenFile, ServiceAccountToken).
  • RBAC Authorizer: In-memory rule index indexing role rules by verb and resource group for sub-microsecond permission checks.
  • Pod Security Admission (PSA): Built-in admission controller replacing legacy PSPs, evaluating Pod specifications against privileged, baseline, and restricted security profiles enforced via namespace labels.
  • Projected Token Volume Driver: Kubelet driver responsible for refreshing and rotating signed ServiceAccount JWT tokens mounted into /var/run/secrets/kubernetes.io/serviceaccount/token before expiration.

1.4 Under-The-Hood Mechanics & Failure Modes

  • Silent Token Expiration in Long-Running Daemons: Legacy applications that cache the ServiceAccount token in memory on startup will encounter 401 Unauthorized errors after the projected token rotates on disk (default 1-hour expiration) unless they re-read /var/run/secrets/kubernetes.io/serviceaccount/token dynamically.
  • Privilege Escalation Prevention: The RBAC engine blocks users from creating or updating Roles with permissions they do not personally possess, preventing unauthorized privilege escalation unless the user holds the explicit escalate verb.
  • Over-Permissioned Wildcard Roles (*): Granting apiGroups: ["*"] and resources: ["*"] with verbs: ["*"] violates least privilege and exposes the entire cluster control plane to compromise if a single workload service account is leaked.

2. Annotated Production YAML Anatomy & Field Reference

Below is a production-grade declarative manifest demonstrating field definitions and operational patterns:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: deployment-manager
  namespace: production
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: deployment-operator
  namespace: production
rules:
- apiGroups: ["apps"]
  resources: ["deployments", "replicasets"]
  verbs: ["get", "list", "watch", "create", "update", "patch"]
- apiGroups: [""]
  resources: ["pods"]
  verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: bind-deployment-operator
  namespace: production
subjects:
- kind: ServiceAccount
  name: deployment-manager
  namespace: production
roleRef:
  kind: Role
  name: deployment-operator
  apiGroup: rbac.authorization.k8s.io

Key Field Schema Reference

Field Type Description
rules[*].apiGroups Array Target API group ("" for core v1, "apps", "networking.k8s.io").
rules[*].resources Array Kubernetes resource nouns (pods, deployments, configmaps).
rules[*].verbs Array Permitted operations (get, list, watch, create, update, patch, delete).

3. Real-World Architectural Patterns

ClusterRole for Cross-Namespace Read-Only Audit

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: cluster-viewer
rules:
- apiGroups: ["", "apps", "batch", "networking.k8s.io"]
  resources: ["*"]
  verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: bind-cluster-viewer
subjects:
- kind: ServiceAccount
  name: auditor
  namespace: security-tools
roleRef:
  kind: ClusterRole
  name: cluster-viewer
  apiGroup: rbac.authorization.k8s.io

Pod Security Standard Restricted SecurityContext

apiVersion: v1
kind: Pod
metadata:
  name: hardened-secure-pod
spec:
  securityContext:
    runAsNonRoot: true
    runAsUser: 10001
    runAsGroup: 10001
    fsGroup: 10001
    seccompProfile:
      type: RuntimeDefault
  containers:
  - name: secure-app
    image: alpine:3.20
    command: ["sleep", "3600"]
    securityContext:
      allowPrivilegeEscalation: false
      readOnlyRootFilesystem: true
      capabilities:
        drop:
        - ALL

4. Production Hardening & Operational Governance

  • Follow the Principle of Least Privilege: never grant wildcard * permissions in production RoleBindings.
  • Disable automatic ServiceAccount token mounting with automountServiceAccountToken: false on pods that do not interact with the API Server.
  • Enforce Pod Security Standards (pod-security.kubernetes.io/enforce: restricted) at the Namespace level.

5. Failure Modes & Diagnostic Triage Tree

API Request 403 Forbidden

Root Cause: ServiceAccount lacks RBAC verb or resource permission.

Diagnostic Triage Sequence: 1. Test authorization: kubectl auth can-i create deployments --as=system:serviceaccount:production:deployment-manager -n production 2. Inspect RoleBinding subjects and roleRef matching.


6. Interactive Practice Matrix

Practice concepts from this chapter directly in the interactive WebAssembly sandbox:

Exercise ID Challenge Description Direct Link Action
rbac01 ServiceAccounts & Token Management ../playground/index.html?exercise=rbac01 ⚡ Solve rbac01 in Playground →
rbac02 Roles & RoleBindings ../playground/index.html?exercise=rbac02 ⚡ Solve rbac02 in Playground →
rbac03 ClusterRoles & ClusterRoleBindings ../playground/index.html?exercise=rbac03 ⚡ Solve rbac03 in Playground →
rbac04 Pod & Container SecurityContext ../playground/index.html?exercise=rbac04 ⚡ Solve rbac04 in Playground →
rbac05 Pod Security Standards (PSS/PSA) ../playground/index.html?exercise=rbac05 ⚡ Solve rbac05 in Playground →