Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install iam-helper-for-troubleshooting@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin iam-helper-for-troubleshooting v1.0.0 follows the Agent Plugins spec.
gh skills-hub install iam-helper-for-troubleshooting Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/iam-helper-for-troubleshooting/ Extract the ZIP to .github/skills/ in your repo. The folder name must match iam-helper-for-troubleshooting for Copilot to auto-discover it.
Skill Files (8)
SKILL.md 5.4 KB
---
name: iam-helper-for-troubleshooting
metadata:
version: "1.0.4"
category: Security
description: >-
Diagnoses, remediates, and manages Identity and Access Management (IAM)
access issues on Google Cloud. Supports two distinct operational modes: (1)
Requester Flow for developers encountering access denials (capturing error
context, self-service PAM JIT activations, elevated developer
self-remediation, or logging structured tickets), and (2) Resolver Flow for
privileged administrators (authoritative Policy Troubleshooter analysis, deny
policy exemptions, least-privilege role discovery, and PAM/IAM provisioning).
---
# IAM Access Troubleshooter & Remediation Orchestrator on Google Cloud
You are an expert Google Cloud Security and IAM assistant. You diagnose access denial errors and orchestrate the appropriate resolution path depending on the caller's persona and privileges.
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Mode Selection Guide
Identify the caller's context to select the appropriate operational mode:
| Mode | Target Persona / Context | Primary Actions | Reference Guide |
| :--- | :--- | :--- | :--- |
| **Mode 1: Requester Flow** | Developer, Service Account, or requester blocked by an access denial | Captures Error ID, runs self-diagnosis, self-activates PAM JIT grants, self-remediates (if elevated), or logs structured tickets. | [`references/requester.md`](references/requester.md) |
| **Mode 2: Resolver Flow** | Security Admin, Cloud IAM Admin, or agent handling an escalated access ticket | Authoritatively evaluates allow/deny policies, creates deny exemptions, discovers minimal roles, and provisions PAM/IAM access. | [`references/resolver.md`](references/resolver.md) |
### Routing Rules
1. **Follow Mode 1 (Requester Flow) if:**
* You are executing an end-user development task, encounter a 403 / Error ID, and need to perform self-service PAM activation or produce an internal escalation ticket for an administrator.
* 📖 **Reference Guide:** Read and follow [`references/requester.md`](references/requester.md) for detailed execution steps.
2. **Follow Mode 2 (Resolver Flow) if:**
* The user asks you to troubleshoot access, investigate a missing permission, find candidate roles, or resolve an access denial on a Google Cloud resource.
* 📖 **Reference Guide:** Read and follow [`references/resolver.md`](references/resolver.md) for detailed execution steps.
3. **Default Behavior:**
* Default to **Mode 2 (Resolver Flow)** for troubleshooting access denials and missing permissions across Google Cloud resources. Read and follow [`references/resolver.md`](references/resolver.md) for detailed execution steps.
---
## Safety Guardrails & Approval Policy
All access modifications and role provisioning operations are governed by the approval tiers and safety boundaries defined in [`references/guardrails.md`](references/guardrails.md):
* **Human-in-the-Loop (HITL):** All role provisioning operations (read-only, mutating, and administrative roles) require explicit human approval before execution. High-risk administrative roles require an explicit high-risk warning.
* **Access Already Granted Rule:** When policy evaluation determines `accessState: GRANTED` (or access is already granted via inherited allow policies), inform the user that the IAM permission configuration is correct and **terminate the troubleshooting flow immediately**. Do NOT search for roles, suggest role queries, or propose role bindings.
* **Role Discovery Gating:** Always ask the user for confirmation before executing queries to list or search candidate roles. Only list roles after receiving user confirmation in a subsequent turn.
* **Unknown Access State / Group Expansion Rule:** When policy evaluation returns `accessState: UNKNOWN` or `UNKNOWN_INFO` (due to missing permissions to expand group memberships like `roles/browser`), explain that access is unknown due to missing group expansion permissions (`roles/browser`), and **terminate the troubleshooting flow immediately**. Do NOT run secondary queries or probe alternative policies.
* **Anti-Loop & Permission Denied:** If troubleshooting commands encounter `PERMISSION_DENIED` on the caller's identity (HTTP 403), stop immediately without querying roles or running alternative commands. If the user requested replying with "Permission Denied" or the role name, reply immediately with "Permission Denied".
> [!NOTE]
> Organizations cloning this skill should customize [`references/guardrails.md`](references/guardrails.md) to define their specific approval tiers and policies.
---
## Supporting Links & Resources
* [Requester Flow Reference](references/requester.md): Developer and access requester self-service & triage playbook
* [Resolver Flow Reference](references/resolver.md): Administrator and security resolver authoritative playbook
* [Guardrails & Approval Policy](references/guardrails.md): Human-in-the-loop approval tiers and security boundaries
* [MCP Usage Reference](references/mcp-usage.md): Using the Policy Troubleshooter remote MCP server
* [Policy Troubleshooter Overview](https://docs.cloud.google.com/policy-intelligence/docs/troubleshoot-access.md.txt)
* [Understanding IAM Predefined Roles](https://docs.cloud.google.com/iam/docs/roles-permissions.md.txt)
* [gcloud SDK iam roles list CLI Reference](https://cloud.google.com/sdk/gcloud/reference/iam/roles/list)
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:iam-helper-for-troubleshooting)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:iam-helper-for-troubleshooting)`
in the `User-Agent` header. If a `User-Agent` header is already specified,
append this string to the end of it rather than overwriting existing
`User-Agent` data — the collection pipeline parses the
`agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:iam-helper-for-troubleshooting)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
guardrails.md 3.4 KB
# Access Provisioning Guardrails & Approval Policy
This reference defines the safety boundaries and Human-in-the-Loop (HITL) approval policy for access resolution and role provisioning in the **Resolver Flow**.
> [!TIP]
> **Customization Notice for Organizations:**
> When adopting or cloning this skill for your organization, **customize this file** (`references/guardrails.md`) to define your specific security policies, trusted role tiers, sensitive role denylists, and approval workflows.
---
## 1. Role Approval Tiers
Before applying any IAM policy binding or creating a PAM entitlement, evaluate the target `ROLE_NAME` against the following approval tiers:
| Tier | Classification | Matching Criteria / Examples | Execution Mode |
| :--- | :--- | :--- | :--- |
| **Read-Only (Low Risk)** | Viewer, Reader, Read-only access | Role names ending in `Viewer` or `Reader`, or roles containing only read-only permissions (`*.get`, `*.list`). Examples: `roles/viewer`, `roles/bigquery.dataViewer`, `roles/storage.objectViewer`, `roles/browser`. | **Human-in-the-Loop (HITL)** (Requires explicit confirmation prompt or ticket approval before execution). |
| **Mutating / Write (Medium Risk)** | Creator, Writer, Editor access | Roles containing create, update, or write permissions (`*.create`, `*.update`, `*.write`, `*.publish`). Examples: `roles/bigquery.dataEditor`, `roles/storage.objectUser`, `roles/pubsub.publisher`. | **Human-in-the-Loop (HITL)** (Requires explicit confirmation prompt or ticket approval before execution). |
| **Destructive / Admin (High Risk)** | Admin, Deletion, Security, IAM | Roles with delete permissions (`*.delete`), administrative authority (`roles/*.admin`, `roles/owner`), or IAM/security controls (`roles/resourcemanager.*Admin`, `roles/iam.*`, `*.setIamPolicy`). | **Human-in-the-Loop (HITL)** (Requires explicit confirmation with high-risk warning). |
---
## 2. Human-in-the-Loop (HITL) Execution Protocol
When a candidate role is selected:
1. **Do NOT apply the binding or entitlement automatically.**
2. **Present the Planned Change to the Human Operator:**
```
[APPROVAL REQUIRED]: Role 'ROLE_NAME' grants permissions for 'PRINCIPAL_EMAIL' on 'RESOURCE_URI'.
- Role scope: Read-Only / Write / Admin
- Resource: RESOURCE_URI
- Target Principal: PRINCIPAL_EMAIL
Do you approve granting this access? (Yes/No)
```
3. **If Approved ('Yes'):** Proceed with the role binding or PAM entitlement creation.
4. **If Rejected ('No'):** Terminate the provisioning flow and record the rejection in the resolution summary.
---
## 3. General Safety Rules
* **Standard Roles Preferred:** Prioritize standard service-level roles (for example, `roles/compute.admin`) over hyper-granular least-privileged roles, while avoiding overly broad basic roles like `roles/editor` or `roles/owner`.
* **Deny Overrides Allow:** An IAM v2 deny policy unconditionally overrides any allow policy or PAM grant. If a deny policy blocks access, granting a role in an allow policy will not work until a deny exemption is applied under `exceptionPrincipals`.
* **No Task Usurpation (Resolver Guardrail):** When operating in Resolver mode, only resolve the permission barrier. In human-in-the-loop flows, advise the user to retry the task. In autonomous agent flows, simply retry the task.
* **Anti-Looping:** If an API call or binding command fails due to invalid parameters or permission errors, halt immediately and report the error instead of repeatedly retrying in a loop.
mcp-usage.md 3.0 KB
# Policy Troubleshooter MCP Usage
Policy Troubleshooter is supported by a remote Model Context Protocol (MCP)
server that provides a set of tools for automated Identity and Access Management
(IAM) access analysis and troubleshooting.
## MCP Tools for Policy Troubleshooter
- **`troubleshoot_access`**: Troubleshoots an IAM access check for a specific
principal, resource, and permission. It analyzes Allow, Deny, and Principal
Access Boundary (PAB) policies to explain why access was granted or denied.
- **`troubleshoot_iam_error_id`**: Troubleshoots an IAM access denied error
using the unique error ID (`error_info_id`) reported in Google Cloud Console
error messages or API error details.
## Setup Instructions
The Policy Troubleshooter remote MCP server is available at the following URL:
```
https://policytroubleshooter.googleapis.com/mcp
```
To connect an MCP client (such as Claude Desktop, Gemini CLI, or custom agents)
to the Policy Troubleshooter remote MCP server, configure your client to connect
via Server-Sent Events (SSE) or HTTP to the server URL, passing an OAuth 2.0
Bearer token in the `Authorization` header.
To connect to the Policy Troubleshooter MCP server, see
[Configure a client connection](https://cloud.google.com/policy-intelligence/docs/use-policy-troubleshooter-mcp).
### Example: Client Configuration
Add the following configuration to your client configuration (for example,
`claude_desktop_config.json`). This configuration uses the `gcloud` CLI to
dynamically fetch a valid access token:
```json
{
"mcpServers": {
"policy_troubleshooter": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-sse-client",
"https://policytroubleshooter.googleapis.com/mcp"
],
"env": {
"AUTHORIZATION": "Bearer $(gcloud auth print-access-token)"
}
}
}
}
```
## Supported Operations
Agents using the Policy Troubleshooter remote MCP server can perform tasks such
as:
- **Diagnose permission denied errors**: Paste an error ID (`error_info_id`)
or specify a user, resource, and permission to immediately understand which
policy blocked access.
- **Analyze IAM policy hierarchies**: Explain how allow policies, deny rules,
and Principal Access Boundary (PAB) policies interact across organizations,
folders, and projects.
- **Automate remediation suggestions**: Determine whether a missing role
binding, an explicit deny policy, or a PAB boundary is causing an access
failure.
For more information about the Policy Troubleshooter MCP server, visit:
[Use Policy Troubleshooter with MCP](https://cloud.google.com/policy-intelligence/docs/use-policy-troubleshooter-mcp).
For detailed tool schemas and parameter descriptions, see the
[Policy Troubleshooter MCP tools reference](https://cloud.google.com/policy-intelligence/docs/reference/policytroubleshooter/mcp).
For general IAM access troubleshooting concepts, see
[Troubleshooting access with Policy Troubleshooter](https://cloud.google.com/policy-intelligence/docs/troubleshoot-access).
requester.md 6.5 KB
# Developer & Access Requester Flow
This guide details how developers and access requesters handle IAM access denials, ranging from self-service just-in-time (JIT) elevations and local project remediation to logging structured tickets.
---
## Step 1: Capture Error Context
Extract the necessary parameters from the failed operation:
* **Option A (Error ID - Preferred):** Extract the base64-encoded `error_info_id` / `ERROR_ID` (for example, `ZGVuaWVkX2J5X2RlbmlhbF9wb2xpY3k...`) from the 403 API error response.
* **Option B (Manual Parameters):**
* `PRINCIPAL_EMAIL`: The identity executing the task.
* `IAM_PERMISSION`: The exact missing permission (for example, `bigquery.datasets.create`).
* `RESOURCE_URI`: The target resource URI (for example, `//cloudresourcemanager.googleapis.com/projects/PROJECT_ID`).
---
## Step 2: Diagnostic Check (Attempt Self-Diagnosis)
Attempt to verify why access was denied using available tools:
1. Call the Policy Troubleshooter MCP tool (`troubleshoot_access` or `troubleshoot_iam_error_id`) to analyze the full Resource Manager hierarchy.
* **Fallback:** If MCP tools are unavailable, use the fallback scripts or `gcloud` CLI:
* For Error IDs: `ERROR_ID="YOUR_ERROR_ID" python3 scripts/troubleshooting_error_id.py`
* For manual checks: Extract the project ID from `RESOURCE_URI` (if available) and pass `--billing-project` and `--format=json`:
```bash
gcloud policy-troubleshoot iam //RESOURCE_URI \
--principal-email="PRINCIPAL_EMAIL" \
--permission="IAM_PERMISSION" \
--billing-project="PROJECT_ID" \
--format=json
```
2. **If troubleshooting returns `PERMISSION_DENIED`:**
* The identity lacks the required viewer rights (for example, missing `resourcemanager.projects.getIamPolicy`). Recognize that troubleshooting failed due to caller permissions. Proceed directly to **Step 5 (Log Bug / Escalate to Admin)** to escalate the permission error to an administrator using the captured error context.
3. **If troubleshooting succeeds:**
* **CASE A (`accessState: GRANTED`):** Access is correctly configured and granted (including via inherited organization or folder allow policies). Conclude that access is already granted and the IAM permission configuration is correct. **Terminate the flow immediately.** Do NOT search for roles, suggest role queries, or propose role bindings.
* **CASE B (`accessState` or `bindingState` is `UNKNOWN` or `UNKNOWN_INFO`):** Access evaluation returned unknown/inconclusive information (typically due to missing permissions to expand group memberships, which requires `roles/browser`). Inform the user that access could not be fully confirmed because of missing permissions to expand group memberships (`roles/browser`).
* **CASE C (`accessState: NOT_GRANTED`):** Access is absent or blocked. Check `denyPolicyExplanation` for explicitly blocked access, Principal Access Boundary policy evaluations, and `allowPolicyExplanation` for absent allow bindings.
---
## Step 3: Self-Service & Elevated Developer Checks
Evaluate the diagnosis against your available permissions:
### Branch A: Blocked by an IAM deny policy
* Modifying deny policies requires organization-level `roles/iam.denyAdmin`.
* Developers cannot self-remediate deny policies. Advise contacting the Security or Organization Administrator and proceed directly to **Step 5 (Log Bug / Escalate to Admin)**, including the blocking `POLICY_ID`.
### Branch B: Missing allow policy (No deny policy blocking)
Evaluate the following tiers in order:
* **Tier 1: Self-Service PAM Entitlement Grants (Pre-approved Entitlement Exists)**
1. Check if an active PAM entitlement covers this permission (`gcloud pam entitlements list`).
2. If found, request a time-bound PAM entitlement grant:
```bash
gcloud pam grants create \
--entitlement=ENTITLEMENT_ID \
--location=global \
--project=PROJECT_ID \
--requested-duration="1h"
```
3. Once the grant is active, proceed to **Step 4 (Retry Troubleshooter Check)**.
* **Tier 2: Elevated Developer (Local Project IAM Admin Rights)**
1. If no PAM entitlement exists, check if you hold `roles/resourcemanager.projectIamAdmin` on the target project.
2. If permitted, explain the findings to the user and **prompt the user for permission** before running any role queries or discovery scripts:
> *"There is no allow policy granting permission 'IAM_PERMISSION', and no deny policy blocking access. Would you like me to find candidate roles granting this permission? (Yes/No)"*
3. **Only after receiving user confirmation**, search for candidate roles using `gcloud iam roles list --filter="includedPermissions:IAM_PERMISSION"` or [`scripts/least_privileged_role.py`](../scripts/least_privileged_role.py).
4. Evaluate the returned `ROLE_NAME` against the guardrails in [`references/guardrails.md`](guardrails.md). **Prompt the user for approval** before applying the project-level IAM binding:
```bash
gcloud projects add-iam-policy-binding PROJECT_ID \
--member="user:PRINCIPAL_EMAIL" \
--role="ROLE_NAME"
```
5. Proceed to **Step 4 (Retry Troubleshooter Check)**.
* **Tier 3: Unprivileged Developer (No PAM Entitlement & No Local Admin Rights)**
* Proceed to **Step 5 (Log Bug / Escalate to Admin)**.
---
## Step 4: Retry Troubleshooter Check
Whenever access is granted (via PAM entitlement activation or local role binding), **immediately re-run the policy troubleshooter check** to confirm access before advising any task retries.
---
## Step 5: Log Bug / Escalate to Admin
When self-remediation is not possible, construct a structured escalation report or ticket:
### Ticket / Escalation Template
```text
Title: [Access Request] Missing permission <IAM_PERMISSION> on <RESOURCE_URI>
Principal: <PRINCIPAL_EMAIL>
Target Resource: <RESOURCE_URI>
Missing Permission: <IAM_PERMISSION>
Error ID: <ERROR_ID>
Diagnostic Details:
- Deny policy blocking: [Yes: <POLICY_ID> / None]
- Principal Access Boundary policy blocking: [Yes / No]
- Allow policy missing: [Yes / No]
- Suggested least-privileged role: <ROLE_NAME> (if diagnosed)
Resolution Options for Admin:
- If deny policy is blocking: Add exemption for <PRINCIPAL_EMAIL> on <POLICY_ID>.
- If allow policy is missing: Create a time-bound PAM entitlement or grant role binding <ROLE_NAME>.
- Reference: See https://docs.cloud.google.com/iam/docs/resolve-permission-errors for more comprehensive information.
```
**Agent Instruction:** (In multi-agent setups, output the summary above and escalate to a human administrator).
resolver.md 14.1 KB
# Administrator & Security Resolver Flow
This guide details how privileged administrators and security agents intake
access requests, resolve blocking deny policies, and provision least-privileged
access.
### Prerequisites & Required Roles
To successfully troubleshoot and remediate access, the caller must possess the
following roles:
* **Troubleshooting:** `roles/policyintelligence.policyTroubleshooterViewer`
(or `roles/iam.securityReviewer`), `roles/iam.principalAccessBoundaryViewer`
(to view PAB policies), and `roles/serviceusage.serviceUsageConsumer` (to
run gcloud commands).
* **Expanding Memberships:** Expanding group memberships requires Google
Workspace Admin access. Expanding group memberships for service account
principal sets requires `roles/browser`.
* **Remediation:** `roles/resourcemanager.projectIamAdmin` (for local
bindings) or `roles/iam.denyAdmin` (for deny policies).
* *Note: Basic roles like `roles/owner` or `roles/editor` inherently provide
most of these permissions.*
--------------------------------------------------------------------------------
## Step 1: Intake & Authoritative Diagnosis
1. Retrieve the `ERROR_ID` (for example, an alphanumeric base64-encoded string
like `ZGVuaWVkX2J5X2RlbmlhbF9wb2xpY3k...`) or (`PRINCIPAL_EMAIL`,
`IAM_PERMISSION`, `RESOURCE_URI`) from the ticket or escalation payload.
2. Invoke the Policy Troubleshooter MCP tool (`troubleshoot_access` or
`troubleshoot_iam_error_id`) to analyze the full CRM hierarchy (Organization
-> Folder -> Project).
* **Fallback:** If MCP tools are unavailable, use the fallback scripts or
`gcloud` CLI:
* For Error IDs: `ERROR_ID="YOUR_ERROR_ID" python3
scripts/troubleshooting_error_id.py`
* For manual checks: Always use `gcloud policy-troubleshoot iam` with
`--format=json` and pass `--billing-project` (extracting
`PROJECT_ID` from `RESOURCE_URI` if present):
```bash
gcloud policy-troubleshoot iam //RESOURCE_URI \
--principal-email="PRINCIPAL_EMAIL" \
--permission="IAM_PERMISSION" \
--billing-project="PROJECT_ID" \
--format=json
```
3. Evaluate the results:
* **CASE A (`accessState: GRANTED` or Inherited Org/Folder Allow
Policy):** Access is correctly configured and already granted (including
via inherited organization or folder allow policies, or
domain-wide/group bindings). When checking access on a resource where
parent organization policy (`organizations/...` in `explainedPolicies`)
grants an allow binding such as `roles/viewer` or
`roles/resourcemanager.organizationViewer`, conclude and state that
access is **GRANTED via an allow policy inherited at the Organization
level** and the IAM permission configuration is correct. **Terminate the
flow immediately.** Do NOT search for roles, do NOT suggest querying
roles, and do NOT propose or apply any role bindings.
* **CASE B (`accessState` or `bindingState` is `UNKNOWN` or
`UNKNOWN_INFO`):** Access evaluation returned unknown/inconclusive
information (typically due to missing permissions to expand group
memberships, which requires `roles/browser` or directory viewer
permissions, or missing `resourcemanager.projects.getIamPolicy` on
ancestors). Conclude and inform the user that access could not be fully
confirmed because of missing permissions to expand group memberships
(`roles/browser`). **Terminate the troubleshooting flow immediately.**
Do NOT run secondary queries (such as `get-iam-policy` or `iam policies
list`), do NOT query groups, and do NOT diagnose as a definitive missing
allow binding.
* **CASE C (`accessState: NOT_GRANTED`):** Access is absent or blocked:
* If `denyPolicyExplanation` shows access is blocked by an explicit
IAM deny policy, explain that an explicit IAM deny policy blocks
access, advise contacting the Security/Organization Administrator,
and proceed to Step 2.
* If `pabPolicyExplanation` indicates a Principal Access Boundary
policy block, proceed to Step 3.
* If `allowPolicyExplanation` shows no allow policy grants the
permission and no deny policies block access, proceed to Step 4.
* **Caller Permission Denied / Anti-Loop Rule:** If invoking the Policy
Troubleshooter tool/API or `gcloud policy-troubleshoot` returns
`PERMISSION_DENIED` (HTTP 403 / insufficient caller permissions to
troubleshoot the resource), the caller lacks the necessary diagnostic
permissions (`roles/policyintelligence.policyTroubleshooterViewer` or
`roles/iam.securityReviewer`). Halt immediately and do NOT search for
roles, do NOT query project IAM policies, and do NOT retry alternative
commands. If the user asked for "Permission Denied" or the role name,
reply immediately with "Permission Denied".
--------------------------------------------------------------------------------
## Step 2: Remediate Blocking Deny Policies
If one or more IAM v2 deny policies block access, then do the following:
1. For each blocking policy (`POLICY_ID`), present the admin with the following
options to avoid dangerous permission escalations (Require a HITL prompt
before execution):
* **Option A: Add the principal to `exceptionPrincipals` (exempt
principal).**
* Update the deny rule definition file to add
`principal://goog/subject/PRINCIPAL_EMAIL` under
`denyRule.exceptionPrincipals`, then run the following command:
```bash
gcloud iam policies update POLICY_ID \
--attachment-point=ATTACHMENT_POINT \
--kind=denypolicies \
--policy-file=policy.json
```
* **Option B: Remove the permission from the deny rule.**
* Update the deny rule definition file to remove `IAM_PERMISSION` from
`denyRule.deniedPermissions` (or add it under
`denyRule.exceptionPermissions`), then run the following command:
```bash
gcloud iam policies update POLICY_ID \
--attachment-point=ATTACHMENT_POINT \
--kind=denypolicies \
--policy-file=policy.json
```
* **Option C: Exclude the resource from the deny policy scope.**
* Update the deny rule condition in the policy file (for example,
adding `!resource.matchTag(...)` or narrowing the rule scope so the
target `RESOURCE_URI` is excluded), then run the following command:
```bash
gcloud iam policies update POLICY_ID \
--attachment-point=ATTACHMENT_POINT \
--kind=denypolicies \
--policy-file=policy.json
```
2. If human approval is granted for the chosen option, apply the policy update.
3. Wait 60 seconds for policy changes to propagate.
4. If the troubleshooting response also indicated a missing allow policy,
proceed to Step 4. Otherwise, proceed to Step 6.
--------------------------------------------------------------------------------
## Step 3: Remediate Blocking Principal Access Boundary (PAB) Policies
If `pabPolicyExplanation` indicates access is blocked by a Principal Access
Boundary policy, then do the following:
1. Present the admin with remediation options (Require HITL approval before
execution):
* **Option A: Update the PAB Policy Resources.** Add the target resource
or its parent folder/project to the list of allowed resources defined in
the PAB policy:
```bash
gcloud iam principal-access-boundary-policies update PAB_POLICY_ID \
--location=global \
--organization=ORGANIZATION_ID \
--add-details-rules=description="Allow target resource",effect=ALLOW,resources=//cloudresourcemanager.googleapis.com/projects/PROJECT_ID
```
* **Option B: Modify Principal Sets.** Update the PAB binding or modify
user group membership so the principal is no longer subject to the
restrictive boundary. For example, to remove a restrictive PAB binding,
run the following command:
```bash
gcloud iam policy-bindings delete BINDING_ID \
--location=global \
--organization=ORGANIZATION_ID
```
For more specific steps on modifying bindings, refer to the
[Principal Access Boundary documentation](https://cloud.google.com/iam/docs/principal-access-boundary-policies-create).
2. Wait 60 seconds for policy changes to propagate, then re-evaluate access.
--------------------------------------------------------------------------------
## Step 4: Discover Least-Privileged Role
If access is missing due to an absent allow policy, then do the following:
1. First, explain the diagnostic findings: confirm that no allow policy grants
`IAM_PERMISSION` and there are no blocking deny policies.
2. **Prompt User for Confirmation Before Querying Roles (Turn Control):** If
the user has not already confirmed finding candidate roles, ask the user
whether they want to find candidate roles granting the permission: > *"There
is no allow policy granting permission 'IAM_PERMISSION', and no deny policy
blocking access. Would you like me to find candidate roles (including
predefined and project custom roles) that provide this permission?
(Yes/No)"*
3. **Execute Role Query (After Receiving User Confirmation):** Run the automated
least-privileged role finder script (preferred, as it evaluates both predefined
and project custom roles and returns a single optimal role, avoiding long lists):
```bash
IAM_PERMISSION="YOUR_IAM_PERMISSION" \
TARGET_PROJECT_ID="YOUR_PROJECT_ID" \
python3 scripts/least_privileged_role.py
```
*Fallback (Manual CLI queries):* If the script cannot be executed, search for matching predefined and project custom roles using `gcloud iam roles list`:
```bash
# Predefined roles matching permission:
gcloud iam roles list --filter="includedPermissions:IAM_PERMISSION" --format="table(name,title)"
# Project custom roles matching permission:
gcloud iam roles list --project=TARGET_PROJECT_ID --filter="includedPermissions:IAM_PERMISSION" --format="table(name,title)"
```
Select the role returned with the least privilege (`ROLE_NAME`). Never
assign broad basic roles such as `roles/owner`, `roles/editor`,
`roles/viewer`, `roles/admin`, or `roles/writer`.
4. Proceed to Step 5 to prompt the user for approval before provisioning
access.
--------------------------------------------------------------------------------
## Step 5: Provision Access (Subject to Guardrails)
When prompting the human for HITL approval, explicitly state the target resource
(e.g., the `RESOURCE_URI` or, if that resource does not accept allow policies,
the resource's parent project) where the role would be granted.
If creating a new role grant, evaluate `ROLE_NAME` against the approval tiers
defined in the organization's customized guardrails:
* **Standard Roles (HITL Protocol):** If `ROLE_NAME` is a standard role
granting read/view or write/mutating permissions (for example,
`roles/*.viewer`, `roles/*.editor`, `roles/writer`), follow HITL protocol
and prompt for user confirmation, stating the target resource.
* **Admin / Destructive Roles (HITL):** If `ROLE_NAME` grants destructive,
deletion, or administrative privileges (for example, `roles/*.admin`,
`roles/owner`, `roles/resourcemanager.*Admin`, `roles/iam.*`), follow HITL
protocol with an explicit high-risk warning, stating the target resource.
Prompt the user to choose between temporary PAM access (Path A) and permanent
bindings (Path B).
### Provisioning Paths:
#### Path A: Privileged Access Manager (PAM Entitlement - Preferred)
Ask the user if PAM is enabled, or check for existing PAM entitlements using
`gcloud pam entitlements list`. If the organization uses PAM for time-bound,
audited access, delegate the provisioning to
`@skill:iam-helper-for-privileged-access-management`:
1. **If an entitlement already exists** for `ROLE_NAME` covering
`PRINCIPAL_EMAIL`: Delegate to
`@skill:iam-helper-for-privileged-access-management` to request a grant
against the existing entitlement.
2. **If an entitlement does not exist**: Delegate to
`@skill:iam-helper-for-privileged-access-management` to create a new
standing PAM entitlement for `ROLE_NAME` allowing `PRINCIPAL_EMAIL` to
request access, and then request the grant.
#### Path B: Permanent IAM Role Binding (Direct Grant)
If permanent standing access is approved, then run one of the following commands, based on the resource that they need access on:
* **For Projects:**
```bash
gcloud projects add-iam-policy-binding PROJECT_ID \
--member="user:PRINCIPAL_EMAIL" \
--role="ROLE_NAME"
```
* **For Folders:**
```bash
gcloud resource-manager folders add-iam-policy-binding FOLDER_ID \
--member="user:PRINCIPAL_EMAIL" \
--role="ROLE_NAME"
```
* **For Organizations:**
```bash
gcloud organizations add-iam-policy-binding ORGANIZATION_ID \
--member="user:PRINCIPAL_EMAIL" \
--role="ROLE_NAME"
```
--------------------------------------------------------------------------------
## Step 6: Verification & Handoff
1. Verify that the binding or PAM grant is active by re-running the policy
troubleshooter check.
2. Provide a structured resolution summary:
* **Root Cause:** Deny policy / PAB policy / Missing allow policy.
* **Remediation Applied:** Added deny exemption for `POLICY_ID` / Updated
PAB policy `PAB_POLICY_ID` / Granted role `ROLE_NAME` via PAM
entitlement `ENTITLEMENT_ID` / Granted permanent role `ROLE_NAME`.
* **Target Principal:** `PRINCIPAL_EMAIL`
3. **Notify Developer / Transfer Back:**
* Inform the requester that the permission barrier is resolved.
* Instruct the admin to direct the original developer to retry their
underlying task.
least_privileged_role.py 4.9 KB
#!/usr/bin/env python3
"""Finds the candidate IAM role with least privilege granting a specific permission."""
import json
import os
import subprocess
import sys
from typing import List, Optional, Tuple
def get_default_project() -> str:
"""Retrieves the default project ID from gcloud config."""
try:
return subprocess.check_output(
["gcloud", "config", "get-value", "project"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
except (subprocess.SubprocessError, OSError):
return ""
def list_roles(
filter_perm: Optional[str] = None,
extra_args: Optional[List[str]] = None,
) -> List[str]:
"""Lists role names using gcloud iam roles list, optionally filtered by permission."""
cmd = ["gcloud", "iam", "roles", "list", "--format=value(name)"]
if filter_perm:
cmd.append(f"--filter=includedPermissions:{filter_perm}")
if extra_args:
cmd.extend(extra_args)
try:
output = subprocess.check_output(
cmd, text=True, stderr=subprocess.DEVNULL
).strip()
return [line.strip() for line in output.splitlines() if line.strip()]
except (subprocess.SubprocessError, OSError):
return []
def describe_role(
role_id: str, extra_args: Optional[List[str]] = None
) -> Optional[dict]:
"""Describes a role using gcloud iam roles describe and returns parsed JSON."""
cmd = ["gcloud", "iam", "roles", "describe", role_id, "--format=json"]
if extra_args:
cmd.extend(extra_args)
try:
output = subprocess.check_output(
cmd, text=True, stderr=subprocess.DEVNULL
).strip()
if output:
return json.loads(output)
except (subprocess.SubprocessError, OSError, json.JSONDecodeError):
pass
return None
def find_least_privileged_role(
permission: str,
project: Optional[str] = None,
org: Optional[str] = None,
) -> Optional[str]:
"""Finds the role with the fewest permissions that includes the given permission."""
candidates: List[Tuple[str, Optional[List[str]]]] = []
# Predefined roles (filtered by permission, excluding overly broad basic roles)
for role_name in list_roles(filter_perm=permission):
if role_name not in [
"roles/owner",
"roles/editor",
"roles/viewer",
"roles/reader",
"roles/writer",
"roles/admin",
]:
candidates.append((role_name, None))
# Project-level custom roles
if project:
for role_name in list_roles(
filter_perm=permission, extra_args=[f"--project={project}"]
):
short_id = role_name.split("/")[-1]
candidates.append((short_id, [f"--project={project}"]))
# Organization-level custom roles
if org:
for role_name in list_roles(
filter_perm=permission, extra_args=[f"--organization={org}"]
):
short_id = role_name.split("/")[-1]
candidates.append((short_id, [f"--organization={org}"]))
valid_roles = []
for role_id, extra_args in candidates:
role_data = describe_role(role_id, extra_args)
if not role_data:
continue
included_perms = role_data.get("includedPermissions", [])
if permission in included_perms:
role_name = role_data.get("name", role_id)
role_name_lower = role_name.lower()
# Identify service-level standard roles (for example, roles/compute.admin), avoiding basic overly broad roles
is_service_level_standard = role_name.startswith("roles/") and (
role_name_lower.endswith("admin")
or role_name_lower.endswith("editor")
or role_name_lower.endswith("viewer")
or role_name_lower.endswith("reader")
or role_name_lower.endswith("writer")
)
valid_roles.append({
"name": role_name,
"perm_count": len(included_perms),
"is_service_level_standard": is_service_level_standard,
"is_predefined": role_name.startswith("roles/"),
})
if not valid_roles:
return None
# Updated sorting logic: surface service-level standard roles first, then predefined roles, then by minimum permissions
valid_roles.sort(
key=lambda x: (
not x["is_service_level_standard"],
not x["is_predefined"],
x["perm_count"],
)
)
return valid_roles[0]["name"]
def main() -> None:
permission = os.environ.get("IAM_PERMISSION", "")
if not permission and len(sys.argv) > 1:
permission = sys.argv[1]
if not permission:
print(
"Error: IAM_PERMISSION environment variable or argument must be"
" provided.",
file=sys.stderr,
)
sys.exit(1)
project = os.environ.get("TARGET_PROJECT_ID", "")
if not project:
project = get_default_project()
org = os.environ.get("TARGET_ORGANIZATION_ID", "")
best_role = find_least_privileged_role(permission, project=project, org=org)
if best_role:
print(best_role)
else:
print(
"Warning: No candidate IAM role found that includes permission"
f" '{permission}'.",
file=sys.stderr,
)
if __name__ == "__main__":
main()
troubleshooting_error_id.py 4.7 KB
#!/usr/bin/env python3
"""Troubleshoots IAM errors using the Policy Troubleshooter API.
Uses a base64 encoded error ID to query the API.
"""
import base64
import binascii
import json
import os
import re
import subprocess
import sys
from typing import Any, Dict
import urllib.error
import urllib.request
def extract_project_id(error_id: str) -> str:
"""Best-effort extraction of a project ID from a base64 error_info_id.
Args:
error_id: The base64 error info ID string.
Returns:
Extracted project ID string, or "" if error_id isn't valid base64 or
contains no projects/<id> segment.
"""
try:
decoded = base64.b64decode(error_id).decode("utf-8", errors="ignore")
except (binascii.Error, ValueError):
return ""
match = re.search(r"projects/([^\s\x00-\x1f\"]+)", decoded)
return match.group(1) if match else ""
def build_summary(data: Dict[str, Any]) -> Dict[str, Any]:
"""Projects raw troubleshootError API response down to decision tree fields.
Args:
data: Raw response dict from troubleshootError API.
Returns:
Dict containing projected fields for decision tree consumption.
"""
return {
"overallAccessState": data.get(
"overallAccessState", data.get("accessState")
),
"accessContext": data.get("accessContext", data.get("accessTuple", {})),
"allowPolicyExplanation": data.get(
"allowPolicyExplanation", data.get("explainedPolicies", [])
),
"denyPolicyExplanation": data.get("denyPolicyExplanation", {}),
"pabPolicyExplanation": data.get("pabPolicyExplanation", {}),
"errors": data.get("errors", []),
}
def enable_service(target_project_id: str) -> None:
"""Enables the Policy Troubleshooter API for the target project."""
if target_project_id:
subprocess.run(
[
"gcloud",
"services",
"enable",
"policytroubleshooter.googleapis.com",
f"--project={target_project_id}",
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
def get_access_token() -> str:
"""Retrieves an access token using gcloud."""
try:
return subprocess.check_output(
["gcloud", "auth", "application-default", "print-access-token"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
except (subprocess.SubprocessError, OSError):
try:
return subprocess.check_output(
["gcloud", "auth", "print-access-token"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
except (subprocess.SubprocessError, OSError) as e:
print(
"Error: Failed to obtain access token from gcloud. Please ensure"
" you are authenticated (e.g. `gcloud auth application-default login`"
f" or `gcloud auth login`). Details: {e}",
file=sys.stderr,
)
sys.exit(1)
def main() -> None:
"""Queries Policy Troubleshooter for a specified IAM error ID."""
error_id = os.environ.get("ERROR_ID", "")
if not error_id and len(sys.argv) > 1:
error_id = sys.argv[1]
if not error_id:
print(
"Error: ERROR_ID environment variable or argument must be provided.",
file=sys.stderr,
)
sys.exit(1)
target_project_id = os.environ.get("TARGET_PROJECT_ID", "")
if not target_project_id and error_id:
target_project_id = extract_project_id(error_id)
if not target_project_id:
try:
target_project_id = subprocess.check_output(
["gcloud", "config", "get-value", "project"],
text=True,
stderr=subprocess.DEVNULL,
).strip()
except (subprocess.SubprocessError, OSError):
pass
enable_service(target_project_id)
token = get_access_token()
url = (
"https://policytroubleshooter.googleapis.com/v3beta/iam:troubleshootError"
)
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
if target_project_id:
headers["X-Goog-User-Project"] = target_project_id
req = urllib.request.Request(
url,
data=json.dumps({"error_info_id": error_id}).encode("utf-8"),
headers=headers,
method="POST",
)
try:
with urllib.request.urlopen(req) as resp:
data = json.loads(resp.read().decode("utf-8"))
print(json.dumps(build_summary(data), indent=2))
except urllib.error.HTTPError as e:
body = e.read().decode("utf-8", errors="ignore")
print(
f"Error calling Policy Troubleshooter API: HTTP {e.code}"
f" {e.reason}\n{body}",
file=sys.stderr,
)
sys.exit(1)
except (urllib.error.URLError, OSError, ValueError, KeyError) as e:
print(f"Error calling Policy Troubleshooter API: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE