Kubernetes rbac

From paulpas/agent-skill-router · View interactive version

Kubernetes rbac is an AI agent skill from the GitHub repository paulpas/agent-skill-router. Implements rbac.authorization.k8s.io/v1 Role, ClusterRole, RoleBinding, and ClusterRoleBinding manifests with least privilege access control for Kubernetes resources.

How to use this skill

Skill file

Kubernetes RBAC Manager

Implements rbac.authorization.k8s.io/v1 Role, ClusterRole, RoleBinding, and ClusterRoleBinding manifests to enforce least-privilege access control for Kubernetes API resources. When loaded, the model generates production-grade RBAC policies with scoped permissions, service account binding, and audit-ready role definitions.

TL;DR Checklist


When to Use

Use this skill when:


When NOT to Use

Avoid this skill for:


Core Workflow

  1. Identify the Service Account — Determine which service account needs access and what resources it must interact with. Checkpoint: Each workload should have its own dedicated service account — never use the default service account.
  1. Define Namespace-Scoped Role — Create a Role with specific resources, verbs, and subresources. Checkpoint: List every resource and verb explicitly — never use wildcards (*).
  1. Create RoleBinding — Bind the Role to the service account within the namespace. Checkpoint: Ensure the roleRef.apiGroup is rbac.authorization.k8s.io, roleRef.kind matches the Role kind, and roleRef.name matches the Role name.
  1. Escalate to ClusterRole if Needed — For resources that exist cluster-wide (Nodes, PersistentVolumes, StorageClasses), create a ClusterRole and ClusterRoleBinding. Checkpoint: ClusterRoles should be used sparingly and only when cross-namespace access is genuinely required.
  1. Apply and Verify — Apply the RBAC manifests and verify access using kubectl auth can-i. Checkpoint: Test both allowed and denied operations to confirm the policy is precise.
  1. Audit Access Periodically — Review RBAC policies quarterly and remove unused permissions. Checkpoint: Run kubectl auth can-i --list --as=system:serviceaccount:<ns>:<sa> to audit existing permissions.

Implementation Patterns

Pattern 1: Namespace-Scoped Role and Binding for an Application

A production-grade RBAC setup for a deployment automation service account.

# Role: Deployment automation can manage Deployments, Services, ConfigMaps, and Secrets
# within the production namespace only.
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: deployment-manager
  namespace: production
rules:
  # Manage deployments and their associated pods
  - apiGroups: ["apps"]
    resources: ["deployments"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
  # Manage pods (read-only — deployments manage pod creation)
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get", "list", "watch"]
  # Manage services for load balancing
  - apiGroups: [""]
    resources: ["services"]
    verbs: ["get", "list", "watch", "create", "update", "patch", "delete"]
  # Read configuration
  - apiGroups: [""]
    resources: ["configmaps"]
    verbs: ["get", "list", "watch"]
  # Manage application secrets (create/update only — never list/delete)
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "create", "update", "patch"]
---
# Bind the Role to the deployment-manager service account
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: deployment-manager-binding
  namespace: production
subjects:
  - kind: ServiceAccount
    name: deployment-manager
    namespace: production
roleRef:
  kind: Role
  name: deployment-manager
  apiGroup: rbac.authorization.k8s.io
---
# The service account that the deployment manager uses
apiVersion: v1
kind: ServiceAccount
metadata:
  name: deployment-manager
  namespace: production

Pattern 2: ClusterRole and Least Privilege (BAD vs GOOD)

Overly permissive RBAC is the most common security misconfiguration in Kubernetes clusters.

# ❌ BAD: Wildcard permissions — this grants full cluster-admin equivalent access
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: overprivileged-role
rules:
  - apiGroups: ["*"]       # ← All API groups
    resources: ["*"]       # ← All resources
    verbs: ["*"]           # ← All verbs (including delete, impersonate, escalate)

# ❌ BAD: Binding to the default service account — every pod in the namespace
# inherits these permissions, massively expanding the attack surface
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: default-binding
  namespace: production
subjects:
  - kind: ServiceAccount
    name: default          # ← Wildcard: grants to ALL pods
    namespace: production
roleRef:
  kind: Role
  name: deployment-manager
  apiGroup: rbac.authorization.k8s.io

# ❌ BAD: Granting access to sensitive resources without justification
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: dangerous-role
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "list", "watch", "create", "update", "delete"]  # ← Full CRUD on all secrets cluster-wide
  - apiGroups: ["rbac.authorization.k8s.io"]
    resources: ["roles", "rolebindings"]
    verbs: ["*"]  # ← Can modify RBAC itself — privilege escalation risk

# ✅ GOOD: Least privilege — deployment manager gets exactly what it needs
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: ci-pipeline-runner
rules:
  # Read-only access to all namespaces for discovery
  - apiGroups: ["apps"]
    resources: ["deployments", "replicasets"]
    verbs: ["get", "list", "watch"]
  # Create/patch pods in any namespace (for job runner pods)
  - apiGroups: [""]
    resources: ["pods", "pods/log"]
    verbs: ["get", "list", "watch", "create", "delete"]
  # Read service accounts to generate token references
  - apiGroups: [""]
    resources: ["serviceaccounts"]
    verbs: ["get", "list"]

# ✅ GOOD: Bind to a specific service account, not the default
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: ci-pipeline-runner-binding
subjects:
  - kind: ServiceAccount
    name: ci-pipeline
    namespace: ci-tools
roleRef:
  kind: ClusterRole
  name: ci-pipeline-runner
  apiGroup: rbac.authorization.k8s.io

Pattern 3: RBAC Access Verification and Audit

def generate_rbac_commands(role_name: str, namespace: str, sa_name: str = "") -> list[str]:
    """Generate kubectl commands to verify and audit an RBAC policy.

    Useful for confirming that a RoleBinding grants the expected permissions
    and for auditing existing access.

    Args:
        role_name: The Role or ClusterRole name to audit.
        namespace: The namespace context.
        sa_name: Optional service account name to check specifically.

    Returns:
        List of kubectl commands for verification and audit.
    """
    commands = [
        f"kubectl describe role {role_name} -n {namespace}",
        f"kubectl describe rolebinding {role_name}-binding -n {namespace}",
        f"kubectl auth can-i create deployments --as=system:serviceaccount:{namespace}:{sa_name or 'default'} -n {namespace}",
        f"kubectl auth can-i delete deployments --as=system:serviceaccount:{namespace}:{sa_name or 'default'} -n {namespace}",
    ]
    return commands


def verify_role_binding(binding: dict) -> list[str]:
    """Verify a RoleBinding or ClusterRoleBinding has correct structure.

    Checks that roleRef fields are consistent and subjects are properly defined.

    Args:
        binding: A parsed RoleBinding or ClusterRoleBinding manifest dict.

    Returns:
        List of validation error messages. Empty means binding is valid.
    """
    errors: list[str] = []
    metadata = binding.get("metadata", {})
    spec = binding.get("spec", {})

    api_group = spec.get("roleRef", {}).get("apiGroup", "")
    role_kind = spec.get("roleRef", {}).get("kind", "")
    role_name = spec.get("roleRef", {}).get("name", "")

    if api_group != "rbac.authorization.k8s.io":
        errors.append(f"roleRef.apiGroup must be 'rbac.authorization.k8s.io', got '{api_group}'")
    if not role_kind:
        errors.append("roleRef.kind is required (Role or ClusterRole)")
    if not role_name:
        errors.append("roleRef.name is required")

    subjects = spec.get("subjects", [])
    if not subjects:
        errors.append("subjects list is empty — no one is granted this role")

    for subject in subjects:
        if subject.get("kind") not in ("User", "Group", "ServiceAccount"):
            errors.append(f"Invalid subject kind: '{subject.get('kind')}' — must be User, Group, or ServiceAccount")
        if not subject.get("name"):
            errors.append(f"Subject is missing 'name' field")

    return errors

Constraints

MUST DO

MUST NOT DO


Output Template

When implementing Kubernetes RBAC policies, produce the following:

  1. Role or ClusterRole YAML — Complete role definition with specific resources, verbs, and apiGroups.
  2. RoleBinding or ClusterRoleBinding YAML — Binding that connects the role to the target service account or user.
  3. ServiceAccount YAML (if needed) — The dedicated service account that receives the role binding.
  4. Access Verification Commands — kubectl auth can-i commands to verify the policy grants the expected permissions.

Related Skills

| Skill | Purpose |

|---|---|

| kubernetes-deployment | Reference the RBAC service account in Deployment pod specs via serviceAccountName |

| cncf/kyverno-pod-security-baseline | Enforce pod security standards alongside RBAC for defense-in-depth |

| cncf/open-policy-agent-opa | Apply admission-time policy enforcement for RBAC compliance validation |

| cncf/keycloak | Integrate Kubernetes with external identity providers for user authentication |


Live References

Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.