In this lesson, you will learn how to harden your Kubernetes environment by stripping away excessive permissions from your application's ServiceAccount to ensure it only possesses the capabilities required to function.
The Problem with "Default" Permissions
When deploying operators or applications, it is tempting to use broad ClusterRole permissions to avoid "permission denied" errors. However, if a pod is compromised, an attacker can use the attached ServiceAccount token to move laterally through your cluster. If that token has access to list secrets or delete deployments globally, the blast radius of a security breach is maximized.
Auditing and Restricting
Applying the Principle of Least Privilege means moving from "what can my app do?" to "what must my app do?".
- Audit via Verbose Logs: Temporarily set your controller or application log level to
debug. Run your integration tests (usingenvtest) and observe which Kubernetes resources the application actually interacts with. - Restrict via Granular RBAC: Once you identify the necessary operations, construct your
RoleorClusterRoleto define exactly which verbs (get,list,patch, etc.) are permitted on specific resources.
Consider this example of a restricted Role for a controller that only needs to manage its own custom resources:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: controller-minimal-role
rules:
- apiGroups: ["my.api.group"]
resources: ["myresources"]
verbs: ["get", "list", "watch", "update", "patch"]
# Explicitly omit 'delete' or 'create' if not required by your reconciliation loop
The Continuous Refinement Cycle
The Principle of Least Privilege is not a "set and forget" task. As you implement new features—such as adding status subresources or finalizers—your ServiceAccount requirements will change. Every time you extend your operator’s logic, revisit the Role definition to ensure you aren't adding unnecessary broad permissions (like * for all verbs). By enforcing granular access at the ServiceAccount level, you ensure that even if one component is compromised, the integrity of the rest of your cluster remains intact.
Key Takeaway: Never grant administrative or cluster-wide permissions to an application by default; explicitly map your ServiceAccount roles to the absolute minimum set of verbs and resources required for the specific task at hand.