Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install iam-helper-for-policy-simulator@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin iam-helper-for-policy-simulator v1.0.0 follows the Agent Plugins spec.
gh skills-hub install iam-helper-for-policy-simulator Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/iam-helper-for-policy-simulator/ Extract the ZIP to .github/skills/ in your repo. The folder name must match iam-helper-for-policy-simulator for Copilot to auto-discover it.
Skill Files (3)
SKILL.md 6.0 KB
---
name: iam-helper-for-policy-simulator
description: >-
Safely simulates and applies Identity and Access Management (IAM) v1 (Allow)
policy changes on Google Cloud.
Uses the Policy Simulator to replay historical access logs against proposed policies
to prevent breaking active workloads before applying the changes. Use when
simulating or applying IAM v1 allow policies across Projects, Folders, or Organizations.
Don't use for analyzing IAM v2 deny policies, VPC Service Controls, or performing
general policy troubleshooting.
metadata:
version: "1.0.2"
category: Security
---
# IAM Policy Simulator (v1 Allow)
You are an advanced security assistant helping users safely modify IAM
policies. You must NEVER apply a modifying policy change without first
running a Policy Simulation to ensure existing workloads are not disrupted. You
must only use standard public gcloud commands.
## 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).
## Core Concepts & Prerequisites
* **IAM v1 (Allow Policies)**: Specifies who has access (a role) to a
resource.
* **Policy Simulator**: Replays the last 90 days of access logs against a
proposed policy to verify if any historical access would be blocked by the
change.
* **Required Permissions**: The execution environment must have
`roles/policysimulator.admin`, `roles/cloudasset.viewer`, and the
appropriate IAM Admin roles for the target resource.
* **Resource Scope**: Changes can target Projects, Folders, or Organizations.
## Execution Workflow: Plan, Simulate, Analyze, Apply
### Step 1: Retrieve Current Policy (Plan)
Fetch the baseline IAM v1 policy for the target resource (Project, Folder, or
Organization) and save it to the `/tmp/` directory:
**For Projects:**
```bash
gcloud projects get-iam-policy TARGET_PROJECT_ID --format=json > /tmp/current_policy.json
```
**For Folders:**
```bash
gcloud resource-manager folders get-iam-policy TARGET_FOLDER_ID --format=json > /tmp/current_policy.json
```
**For Organizations:**
```bash
gcloud organizations get-iam-policy TARGET_ORG_ID --format=json > /tmp/current_policy.json
```
**CRUCIAL SAFETY GATE:** Verify that the policy was successfully retrieved. If
the command fails or the resulting JSON is empty, you MUST terminate the
workflow immediately and inform the user. Do not proceed to prepare or simulate
an empty or partial policy.
### Step 2: Prepare Proposed Policy
Create a `/tmp/proposed_policy.json` file. Modify `/tmp/current_policy.json` by
adding or removing role bindings in the `bindings` array to match the requested
change.
**CRUCIAL NO-OP CHECK:** Compare the proposed policy to the current policy. If
no changes were actually made (e.g., you are trying to remove a role the user
doesn't hold, or add a role they already have), you MUST inform the user that no
changes are necessary and **terminate the workflow immediately**. Do not run a
simulation.
### Step 3: Run Policy Simulation
Run the simulator to replay the last 90 days of access logs against the proposed
policy change. Execute the exact command for your resource type:
**For Projects:**
```bash
gcloud iam simulator replay-recent-access //cloudresourcemanager.googleapis.com/projects/TARGET_PROJECT_ID /tmp/proposed_policy.json --project=TARGET_PROJECT_ID --format=json > /tmp/simulation_results.json
```
**For Folders:**
```bash
gcloud iam simulator replay-recent-access //cloudresourcemanager.googleapis.com/folders/TARGET_FOLDER_ID /tmp/proposed_policy.json --format=json > /tmp/simulation_results.json
```
**For Organizations:**
```bash
gcloud iam simulator replay-recent-access //cloudresourcemanager.googleapis.com/organizations/TARGET_ORG_ID /tmp/proposed_policy.json --format=json > /tmp/simulation_results.json
```
*(Note: If the Policy Simulator API is not enabled, it will prompt you to enable
it. Select Yes. Do not use placeholders verbatim; replace TARGET_PROJECT_ID,
TARGET_FOLDER_ID, or TARGET_ORG_ID with the actual resource ID).*
**CRUCIAL SAFETY GATE:** Verify the command exited successfully. If the
simulator command crashes, times out, or returns a non-zero exit code, you MUST
NOT treat the failure as a "safe" result. Terminate the workflow immediately and
report the simulator failure to the user.
### Step 4: Analyze Simulation Results
Analyze the contents of `/tmp/simulation_results.json` using the provided helper
script. Do not write custom scripts on the fly. You MUST execute the following
command:
```bash
python3 scripts/analyze_simulation.py
```
* **SAFE (No Breakage):** If the script outputs `REVOKED_COUNT=0`, the change
is safe.
* **UNSAFE (Breakage):** If the script outputs `REVOKED_COUNT` > 0 (meaning
the logs contain `ACCESS_REVOKED` or `ACCESS_MAYBE_REVOKED`):
* Identify the `principal`, `permission`, and `fullResourceName` from the
printed JSON.
* **Do NOT apply the policy.**
* The change will break an active workload. Inform the user of the
specific disrupted accesses.
### Step 5: Apply Policy (Only if Safe)
If and only if the simulation in Step 4 was SAFE (No Breakage), prompt the user:
*"The simulation showed no disrupted access. Do you want to apply this policy
change? (Yes/No)"*.
* **If Yes:** Apply the policy using the correct command for the resource
type:
**For Projects:**
```bash
gcloud projects set-iam-policy TARGET_PROJECT_ID /tmp/proposed_policy.json
```
**For Folders:**
```bash
gcloud resource-manager folders set-iam-policy TARGET_FOLDER_ID /tmp/proposed_policy.json
```
**For Organizations:**
```bash
gcloud organizations set-iam-policy TARGET_ORG_ID /tmp/proposed_policy.json
```
* **If No:** Terminate the workflow.
### Step 6: Cleanup (Always Run)
After applying the policy, declining the prompt, or terminating early due to a
NO-OP/failure, always delete the temporary files to prevent cross-contamination
in future runs:
```bash
rm -f /tmp/current_policy.json /tmp/proposed_policy.json /tmp/simulation_results.json
```
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-policy-simulator)" \
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-policy-simulator)`
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-policy-simulator)
```
- **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.
analyze_simulation.py 1.3 KB
#!/usr/bin/env python3
"""Analyzes IAM policy simulation results and identifies access revocations."""
import json
import os
import sys
def main():
results_file = "/tmp/simulation_results.json"
if not os.path.exists(results_file):
print(f"PARSE_ERROR: File {results_file} not found.")
sys.exit(1)
try:
with open(results_file, "r") as f:
data = json.load(f)
results = (
data
if isinstance(data, list)
else data.get("results", data.get("replayResults", []))
)
revoked = []
for item in results:
if not isinstance(item, dict):
continue
# Safely navigate the deeply nested JSON structure
diff = item.get("diff", {}).get("accessDiff", {})
change = diff.get("accessChange")
# Fallbacks just in case the API structure flattens
if not change:
change = item.get("accessChange")
if not change:
change = item.get("accessTuple", {}).get("accessChange")
if change in ["ACCESS_REVOKED", "ACCESS_MAYBE_REVOKED"]:
revoked.append(item)
print(f"REVOKED_COUNT={len(revoked)}")
if revoked:
print(json.dumps(revoked, indent=2))
except Exception as e: # pylint: disable=broad-exception-caught
print(f"PARSE_ERROR: {e}")
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