Inferensys

Prompt

Kubernetes RBAC Access Denied Repair Prompt

A practical prompt playbook for cluster operators and platform engineers using AI to repair Kubernetes RBAC authorization failures from audit logs and existing manifests.
ML engineer managing model training cluster on laptop, GPU utilization visible, technical deep learning setup.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the exact scenario, required inputs, and boundaries for the Kubernetes RBAC repair prompt.

This prompt is designed for cluster operators and SRE teams who need to resolve Kubernetes RBAC authorization failures that result in HTTP 403 Forbidden errors. The core job-to-be-done is to consume a denied request audit log entry alongside the existing RBAC manifests—Roles, ClusterRoles, RoleBindings, and ClusterRoleBindings—and propose a corrected binding or role that grants the minimal necessary permissions. The ideal user is an operator who has access to the audit log event describing the denied verb, resource, subresource, API group, and namespace, and who can retrieve the current RBAC configuration for the affected subject (user or service account).

To use this prompt effectively, you must provide two concrete inputs: the raw audit log entry for the denied request and the YAML or JSON representation of the existing RBAC manifests that apply to the subject. The prompt will analyze the gap between the requested action and the granted permissions, then output a corrected Role or ClusterRole and a corresponding RoleBinding or ClusterRoleBinding that adds only the missing permissions. The output must preserve existing permissions, respect namespace isolation boundaries, and follow the principle of least privilege. The prompt includes placeholders for [AUDIT_LOG_ENTRY], [EXISTING_RBAC_MANIFESTS], and [SUBJECT_IDENTIFIER] to make the template adaptable across clusters and subjects.

Do not use this prompt for failures that originate outside the RBAC authorization layer. Network policy violations, admission controller rejections (such as OPA/Gatekeeper or Kyverno denials), pod security standard enforcement, and image pull authentication errors require different diagnostic inputs and recovery logic. Using this prompt for those scenarios will produce irrelevant or misleading suggestions because the prompt reasons exclusively about RBAC verbs, resources, and API groups. If the audit log shows a non-RBAC error or the subject already has the required permissions, escalate to a human operator for deeper investigation rather than forcing a binding change.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and the operational prerequisites for safe deployment in production Kubernetes environments.

01

Good Fit: Audit-Driven Repair

Use when: You have a structured audit log entry (e.g., kubectl auth can-i failure or API server rejection) and the existing RBAC manifests. The prompt excels at correlating the denied resource/verb with the subject's current bindings to propose a minimal fix. Guardrail: Always validate the proposed Role/ClusterRole against the principle of least privilege before applying.

02

Bad Fit: Network Policy or Pod Security

Avoid when: The access denial stems from NetworkPolicies, Pod Security Standards (PSS), or OPA/Gatekeeper constraints. This prompt reasons about RBAC subjects and bindings, not network-level enforcement or admission control. Guardrail: Route access-denied errors through a classifier first to confirm the failure domain is strictly RBAC before invoking this prompt.

03

Required Inputs

Risk: Incomplete input leads to overly permissive or incorrect bindings. The prompt requires the raw audit log line, the subject's current RoleBindings/ClusterRoleBindings, and the target namespace context. Guardrail: Implement a pre-flight check in the harness that verifies all three input fields are non-empty and the namespace exists before sending the prompt.

04

Operational Risk: Privilege Escalation

Risk: A hallucinated or poorly constrained repair could grant cluster-admin or broad wildcard permissions. Guardrail: Post-process the model's output with a static policy validator that rejects any proposed Role containing * verbs on * resources or bindings to the cluster-admin ClusterRole. Escalate to human review if detected.

05

Operational Risk: Cross-Namespace Leakage

Risk: The prompt might incorrectly suggest a ClusterRole when a namespaced Role is sufficient, breaking namespace isolation. Guardrail: Add a constraint in the prompt's [CONSTRAINTS] block that defaults to namespaced Roles unless the audit log explicitly shows a cluster-scoped resource. Validate the output's scope before applying.

06

Retry Budget Integration

Risk: Repeated repair failures can loop, generating multiple invalid RBAC manifests. Guardrail: Integrate this prompt into a retry harness with a maximum of 2 attempts. If the second proposed manifest also fails kubectl auth can-i --validate or dry-run apply, escalate to the on-call SRE with the full audit trail and both rejected proposals.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt template for diagnosing and repairing Kubernetes RBAC access denied errors using audit logs and existing RBAC manifests.

This prompt template is designed for cluster operators and SRE teams who need to resolve authorization failures in Kubernetes. It consumes the denied request audit log and existing RBAC manifests to propose a corrected Role or ClusterRole binding. The prompt is structured to enforce subject-scope validation and namespace isolation checks, ensuring that the proposed fix adheres to the principle of least privilege. Before using this template, ensure you have gathered the relevant audit log entry for the denied request and the current RBAC configuration (Role, ClusterRole, RoleBinding, or ClusterRoleBinding) that should have permitted the action.

text
You are a Kubernetes RBAC repair assistant. Your task is to analyze an access denied error and propose a minimal, secure correction to the existing RBAC configuration.

## INPUT
- Audit Log Entry: [AUDIT_LOG_ENTRY]
- Existing RBAC Manifest: [EXISTING_RBAC_MANIFEST]
- Target Namespace (if applicable): [TARGET_NAMESPACE]

## CONSTRAINTS
- Apply the principle of least privilege. Grant only the specific verbs and resources required by the denied request.
- If the request is namespace-scoped, the fix must be scoped to [TARGET_NAMESPACE]. Do not propose a ClusterRoleBinding unless the request is for a cluster-scoped resource.
- Validate that the subject (User, Group, or ServiceAccount) from the audit log is correctly referenced in the proposed binding.
- Do not modify existing rules that are unrelated to the denied request.
- Output must be a valid Kubernetes manifest.

## OUTPUT_SCHEMA
Provide your response as a JSON object with the following fields:
{
  "diagnosis": "A one-sentence summary of why the request was denied.",
  "corrected_manifest": "The full, corrected Kubernetes manifest (Role, ClusterRole, RoleBinding, or ClusterRoleBinding) as a multi-line string.",
  "explanation": "A step-by-step explanation of the changes made and why they resolve the issue.",
  "validation_checks": ["A list of manual checks the operator should perform before applying, e.g., 'Verify the ServiceAccount exists in the target namespace.'"]
}

## RISK_LEVEL
[HIGH] - Incorrect RBAC changes can grant excessive permissions. Human review is mandatory before applying the corrected manifest.

To adapt this template, replace the placeholders with real data from your cluster. The [AUDIT_LOG_ENTRY] should be the full JSON object from your audit log for the denied request, including the user, verb, resource, and namespace fields. The [EXISTING_RBAC_MANIFEST] is the YAML or JSON of the Role/ClusterRole and its binding that you expected to authorize the request. The [TARGET_NAMESPACE] is required for namespace-scoped resources to enforce isolation. After receiving the model's output, always validate the corrected_manifest with kubectl auth can-i --as=[user] [verb] [resource] -n [namespace] before applying it to the cluster. This prompt is a starting point; for production use, integrate it into a harness that automatically extracts audit log entries and fetches the relevant RBAC manifests before calling the model.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Kubernetes RBAC Access Denied Repair Prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Missing or malformed inputs will cause the repair logic to fail or produce insecure bindings.

PlaceholderPurposeExampleValidation Notes

[AUDIT_LOG_ENTRY]

The raw audit log line or event describing the denied API request, including user, verb, resource, namespace, and timestamp.

{"kind":"Event","user":{"username":"app-sa"},"verb":"list","objectRef":{"resource":"pods","namespace":"prod"},"responseStatus":{"code":403}}

Must be valid JSON. Check for presence of user.username, verb, objectRef.resource, and objectRef.namespace fields. Reject if responseStatus.code is not 403.

[EXISTING_ROLE_YAML]

The current Role or ClusterRole manifest that should grant access but is failing. Include the full YAML document.

apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: name: pod-reader namespace: prod rules:

  • apiGroups: [""] resources: ["pods"] verbs: ["get", "watch"]

Must parse as valid Kubernetes RBAC YAML. Validate kind is Role or ClusterRole. Reject if apiVersion is not recognized. Check for at least one rule block.

[EXISTING_BINDING_YAML]

The RoleBinding or ClusterRoleBinding that links the denied subject to the role. Include the full YAML document.

apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: read-pods namespace: prod subjects:

  • kind: ServiceAccount name: app-sa namespace: prod roleRef: kind: Role name: pod-reader

Must parse as valid Kubernetes RBAC YAML. Validate kind is RoleBinding or ClusterRoleBinding. Check that subjects array is non-empty and roleRef.name matches a known role. Reject if namespace does not match audit log namespace.

[SUBJECT_IDENTIFIER]

The fully qualified name of the user, group, or service account that was denied. Extracted from the audit log.

system:serviceaccount:prod:app-sa

Must match the subject in the binding. For service accounts, validate format system:serviceaccount:<namespace>:<name>. For users, validate against expected user prefix. For groups, validate against expected group prefix.

[TARGET_NAMESPACE]

The Kubernetes namespace where the denied request occurred. Used to scope the repair to the correct namespace.

prod

Must be a valid Kubernetes namespace name (RFC 1123 DNS label). Must match the namespace in the audit log and the namespace of the Role and RoleBinding. Reject if empty or set to 'default' without explicit confirmation.

[REQUESTED_VERB]

The specific API verb that was denied, such as get, list, watch, create, update, patch, or delete.

list

Must be one of the standard Kubernetes API verbs: get, list, watch, create, update, patch, delete, deletecollection. Reject if verb is escalate, bind, or impersonate without explicit security review flag.

[REQUESTED_RESOURCE]

The Kubernetes resource type that was denied, such as pods, services, deployments, or secrets.

pods

Must be a valid Kubernetes resource name. Validate against a known resource list or allow any string matching RFC 1123 subdomain. Reject if resource is secrets, configmaps, or serviceaccounts/token without explicit security review flag.

[API_GROUP]

The API group of the denied resource. Empty string for core resources, or a named group like apps, networking.k8s.io, or rbac.authorization.k8s.io.

""

Must be a valid Kubernetes API group string. Use empty string for core resources. Validate format as DNS subdomain or empty. Reject if group is rbac.authorization.k8s.io or certificates.k8s.io without explicit security review flag.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Kubernetes RBAC Access Denied Repair Prompt into an operator workflow with validation, safety checks, and retry logic.

This prompt is designed to sit inside a remediation pipeline, not a chat window. The primary integration point is a cluster operator's debugging workflow or an automated controller that detects Forbidden (403) errors from the Kubernetes API audit log. The harness must extract three inputs before calling the model: the raw audit log line or full error message from kubectl, the current RBAC manifest (Role, ClusterRole, and their bindings) for the subject in question, and the namespace scope where the access was denied. Without all three, the model lacks the context to propose a minimal, correct fix.

The harness should enforce a strict validation layer after the model returns its proposed manifest. First, parse the output to isolate the YAML block. Validate it against the target cluster's API version schema using kubectl --dry-run=server or an equivalent schema validator. Second, run a subject-scope check: confirm the binding only grants permissions to the specific user, group, or service account that experienced the denial. Third, enforce namespace isolation: if the original denial occurred in a specific namespace, the proposed fix must not expand permissions to other namespaces unless explicitly requested. If any validation fails, the harness should feed the validation error back into the prompt as a retry with the original context, not silently apply a broken manifest.

For production use, never apply the model's output directly. Route all proposed RBAC changes through a human approval queue or a policy-as-code gate (e.g., OPA/Kyverno) that enforces least-privilege rules. Log every invocation with the input error, the proposed diff, validation results, and the final approval decision. This audit trail is critical for compliance and post-incident review. Model choice matters here: prefer a model with strong code and YAML generation performance, and set a low temperature (0.0–0.2) to maximize deterministic, repeatable output. If the model proposes a wildcard (*) resource or verb where a specific one was denied, flag it as a policy violation and escalate immediately.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the Kubernetes RBAC repair response. Use this contract to parse, validate, and integrate the model output into your remediation harness.

Field or ElementType or FormatRequiredValidation Rule

repair_type

enum: Role | ClusterRole | RoleBinding | ClusterRoleBinding

Must exactly match one of the four enum values. Reject any other string.

manifest

string (YAML)

Must parse as valid YAML. Must contain apiVersion, kind, and metadata.name. Kind must match repair_type.

explanation

string

Must be non-empty. Must reference the specific error from [ERROR_LOG] and the specific RBAC rule that was missing or misconfigured.

subject_scope_check

object

Must contain 'subject_kind' (string), 'subject_name' (string), and 'namespace' (string or null). If repair_type is ClusterRoleBinding, namespace must be null.

namespace_isolation

boolean

Must be true if the repair is scoped to a single namespace. Must be false if repair_type is ClusterRole or ClusterRoleBinding. Validate against repair_type.

diff_from_original

string (YAML diff)

If present, must be a valid unified diff or structured patch showing only the changed lines from [CURRENT_MANIFEST]. Null allowed when no original manifest was provided.

least_privilege_justification

string

Must list the exact API groups, resources, and verbs granted. Must not include wildcard verbs or resources unless explicitly present in the denied request audit log.

validation_warnings

array of strings

If present, each string must describe a non-blocking concern (e.g., broad resource pattern, missing resourceNames). Null or empty array allowed when no warnings apply.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using AI to repair Kubernetes RBAC access denied errors, and how to guard against it.

01

Privilege Escalation via Overly Broad Rules

What to watch: The model proposes a ClusterRole or wildcard resource permissions (*, *.*) instead of a scoped Role with specific verbs and resources. This grants the subject more access than needed to resolve the original denial. Guardrail: Post-process the proposed manifest with a least-privilege validator that rejects any rule containing * in resources or verbs unless explicitly allowed by a human-approved exception list.

02

Namespace Boundary Violation

What to watch: The model suggests a ClusterRoleBinding for a subject that only needs access within a single namespace, or proposes a RoleBinding that references a service account from a different namespace without proper trust configuration. Guardrail: Enforce a namespace isolation check in the harness. If the original denied request was namespace-scoped, reject any output that proposes a ClusterRoleBinding. Validate that the subject and the Role exist in the same namespace.

03

Subject Misidentification from Audit Logs

What to watch: The model misparses the user, group, or serviceaccount field from the audit log, especially when the subject name contains special characters, system prefixes (system:), or when the log format differs across Kubernetes distributions. Guardrail: Extract and normalize the subject identity in the application layer before passing it to the prompt. Use a regex validator to confirm the subject matches the system:serviceaccount:<ns>:<name> or known user/group patterns before applying any binding.

04

Ignoring Existing Effective Permissions

What to watch: The model proposes a new binding without considering that the subject already has the required permission through another RoleBinding or a wildcard ClusterRole. This creates redundant, confusing RBAC state. Guardrail: Run an access check (kubectl auth can-i --as=<subject>) before generating the repair prompt. If the subject already has the required access, the failure is not RBAC-related, and the prompt should not be invoked. Log this as a false-positive trigger.

05

YAML Syntax Errors in Generated Manifests

What to watch: The model produces a manifest with incorrect indentation, missing apiVersion fields, or invalid metadata structure that causes kubectl apply to fail with a parse error, creating a new failure instead of fixing the original one. Guardrail: Pipe the generated output through kubectl --dry-run=client apply -f - in the harness. If the dry run fails, feed the parse error back into a single retry loop before surfacing the output to the operator.

06

Hallucinated API Groups or Resource Names

What to watch: The model invents non-existent API groups (e.g., apps/v2), resource names (e.g., podlogs), or sub-resources that don't exist on the target cluster version, causing the repaired binding to be syntactically valid but semantically broken. Guardrail: Validate every apiGroups and resources entry in the proposed Role against the cluster's live API discovery endpoint (/apis and /api/v1) before applying. Reject any rule containing resources not present in the discovery response.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality and safety of the Kubernetes RBAC Access Denied Repair Prompt before shipping to production. Each criterion targets a specific failure mode common to authorization repair workflows.

CriterionPass StandardFailure SignalTest Method

Subject Scope Validation

Proposed binding references only the subject from [DENIED_SUBJECT] and does not grant permissions to additional users, groups, or service accounts.

Output contains a subjects list with entries not present in the original denied request audit log.

Parse the proposed manifest and diff the subjects field against the input [DENIED_SUBJECT]. Fail if any new subject is introduced.

Namespace Isolation

Proposed RoleBinding is scoped to the namespace in [DENIED_NAMESPACE]. ClusterRoleBinding is proposed only when the denied resource is cluster-scoped.

A ClusterRoleBinding is proposed for a namespaced resource, or a RoleBinding references a namespace different from the denied request.

Inspect the kind field of the proposed binding. If the denied resource is namespaced and kind is ClusterRoleBinding, fail. If namespace metadata differs from [DENIED_NAMESPACE], fail.

Least-Privilege Permission Addition

Proposed Role or ClusterRole adds only the specific API group, resource, and verb that were denied. No wildcard verbs or resources are introduced unless already present in [EXISTING_MANIFESTS].

Output contains a rule with '*' in verbs, resources, or apiGroups that was not present in the existing authorized manifest.

Parse the rules array of the proposed role. Flag any rule where verbs, resources, or apiGroups contain '*' and that exact wildcard rule is absent from [EXISTING_MANIFESTS].

Manifest Syntactic Validity

Proposed YAML parses successfully and contains valid apiVersion, kind, metadata, and spec fields for a Kubernetes RBAC object.

YAML parser throws an error, or the parsed object is missing required fields such as metadata.name or roleRef.

Run a strict YAML parser on the output. Validate the parsed object against the Kubernetes RBAC v1 schema. Fail on any parsing error or missing required field.

Error-Context Alignment

The explanation references the specific error code or message from [DENIED_ERROR_LOG] and maps it to the proposed fix.

The explanation is generic, does not mention the specific error, or proposes a fix unrelated to the error message.

Check that the explanation string contains a substring from [DENIED_ERROR_LOG] or a direct paraphrase of the denial reason. Fail if no alignment is found.

No Over-Permission via Aggregation

Proposed role does not include an aggregationRule that would pull in broader permissions than the denied request requires.

Output includes an aggregationRule field that was not present in [EXISTING_MANIFESTS] and would expand permissions beyond the denied verb.

Parse the output for the presence of an aggregationRule. If found, compare the clusterRoleSelectors against existing cluster roles. Fail if the aggregated permissions exceed the denied verb and resource.

Resource Name Restriction Preservation

If [DENIED_ERROR_LOG] indicates a resourceNames restriction failure, the proposed role includes resourceNames matching the denied request.

The proposed role omits resourceNames when the error log shows a denial for a specific named resource, or adds incorrect resource names.

Extract the resource name from [DENIED_ERROR_LOG]. Verify the proposed role's rule for the denied resource includes a resourceNames array containing that exact name. Fail if missing or mismatched.

Diff-Only Output Isolation

Output contains only the corrected manifest and explanation. No extraneous commentary, markdown fences outside the YAML block, or conversational filler.

Output includes phrases like 'Here you go', 'I hope this helps', or multiple YAML alternatives with commentary.

Check the output string for conversational preamble or sign-off patterns. Fail if the output is not strictly the corrected YAML block and a single explanation paragraph.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add strict output schema, namespace isolation validation, subject-scope checks, and diff-only output. Require the model to explain which specific rule change fixes the denial and why existing rules are insufficient.

code
You are a Kubernetes RBAC repair assistant. Given:
- [AUDIT_LOG_ENTRY]: the denied request from the API audit log
- [CURRENT_RBAC_MANIFESTS]: all Role, ClusterRole, RoleBinding, and ClusterRoleBinding objects in the affected namespace
- [SUBJECT_DETAILS]: the user, group, or service account that was denied

Output a JSON object with:
- "diagnosis": why the denial occurred, referencing specific missing verbs or resources
- "corrected_manifest": the minimal changed Role or ClusterRole YAML (diff-only)
- "binding_check": whether the subject is correctly bound to the role
- "namespace_isolation": confirmation the fix does not grant cross-namespace access unless a ClusterRole is explicitly required

Do not modify existing rules that are not related to the denial.

Watch for

  • Silent format drift in the JSON output
  • Missing binding_check when the Role exists but the binding is broken
  • ClusterRole suggestions when a namespaced Role would suffice
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.