Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install assuredworkloads-environment-assessor@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin assuredworkloads-environment-assessor v1.0.0 follows the Agent Plugins spec.
gh skills-hub install assuredworkloads-environment-assessor Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/assuredworkloads-environment-assessor/ Extract the ZIP to .github/skills/ in your repo. The folder name must match assuredworkloads-environment-assessor for Copilot to auto-discover it.
Skill Files (5)
SKILL.md 28.0 KB
---
name: assuredworkloads-environment-assessor
metadata:
version: "1.0.2"
category: SecurityAndCompliance
description: >-
Discover Google Cloud resource telemetry and effective Org Policies, evaluate brownfield workloads against
sovereign data boundary and compliance standards (EU Data Boundary with Support, FedRAMP Moderate/High, DoD IL4/IL5,
ITAR, CJIS, US/EU Regional Data Boundaries), and recommend the optimal Assured Workloads Framework. Use
when asked to: "assess my environment for compliance", "which Assured Workloads framework
should I use?", "check if my folder is ready for EU sovereignty", "evaluate compliance
posture for folders/123 or projects/xyz", or "discover compliance gaps before deployment".
Do NOT use for live mutating policy deployments, generating deep audit reports via Cloud Audit Manager,
generating remediation scripts, or authoring custom Assured Workloads frameworks.
---
# Compliance Environment Assessor Skill
This skill performs zero-risk, non-mutating compliance discovery, physical telemetry profiling, and data boundary framework recommendation across Google Cloud Folders (`folders/{folder_id}`) and Projects (`projects/{project_id}`).
## 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).
## Safety & Execution Tier (CRITICAL)
* **Tier R (Strictly Read-Only)**:
All discovery operations execute read-only queries
(`gcloud asset search-all-resources`,
`gcloud compliance-manager frameworks list`,
`gcloud compliance-manager cloud-controls describe`, and
`gcloud org-policies describe --effective`).
You MUST NEVER execute mutating commands (`gcloud compliance-manager framework-deployments create`,
`gcloud org-policies set-policy`, or `gcloud resource-manager ...`).
---
## Grounding Guardrails: Google Cloud & Assured Workloads Precedence (CRITICAL)
To prevent hallucinations, incorrect compliance assessments, and false blockers derived from generic LLM pre-training, the agent is governed by strict **Grounding Guardrails**:
1. **Strict Prohibition on Generic LLM Pre-Training Priors**:
* You MUST NOT derive compliance rules, API semantics, or deployment constraints from generic web pre-training (e.g., generic NIST/FedRAMP certification audit checklists, AWS/Azure architectures, or legacy on-prem IT auditor mindsets).
* In traditional IT audits, non-compliance is a binary go/no-go gate that
blocks deployment. In Google Cloud Assured Workloads, deploying in
**Monitoring (`Detective`) mode** enables detective controls without
mutating existing Organization Policies, allowing continuous observability
without halting Day 0 rollout. You MUST NOT confuse these paradigms.
2. **Authoritative Assured Workloads Scope & Deployment Grounding**:
* Assured Workloads binds compliance frameworks directly to existing or new
Google Cloud folders (`folders/...`) and projects (`projects/...`).
* **Existing Workloads (Folders or Projects)**: Recommend deploying in
**Monitoring (`Detective`) mode** first to assess and remediate findings
safely without mutating existing Organization Policies, and then
transitioning to **Preventive** mode.
* **New Workloads (Folders or Projects)**: Recommend starting in
**Preventive** mode or **Monitoring (`Detective`) mode**.
* **Google Cloud Console Deployment**: Always guide the user to deploy the
recommended framework via the **Assured Workloads Frameworks tab in Google
Cloud Console**
(`https://console.cloud.google.com/compliance/configure/frameworks?organizationId=ORGANIZATION_ID`).
Do NOT recommend `gcloud assured workloads create` (which only provisions
new greenfield folders using legacy regime enums and cannot bind frameworks
to existing folders or projects).
3. **Client-Side Org Policy Readiness vs. Server-Side CES Boundary**:
* **Client-Side Scope**: Pre-flight evaluation via
`scripts/evaluate_control_rules.py` assesses **ONLY the 3 high-confidence
Organization Policy parameter sets** bound in
`Framework.cloudControlDetails[].parameters`:
1. Resource Locations (`builtin-restrict-resource-locations` /
`constraints/gcp.resourceLocations`)
2. Service Usage Restrictions / SUR
(`builtin-enforce-service-usage-restrictions` /
`constraints/gcp.restrictServiceUsage`)
3. CMEK Encryption Requirements (`builtin-require-cmek` /
`constraints/gcp.restrictNonCmekServices`)
* **Server-Side CES Scope**: Complex Continuous Evaluation Service
(`ces_rule`) and REST API rules (`rest_api_measurement`) are evaluated
**server-side by the Continuous Evaluation Service (CES)** after the
framework is deployed.
* **Terminology Invariant**: You MUST frame client-side findings as
**Pre-Flight Org Policy Readiness Recommendations / Potential Drift
Indicators** (`orgPolicyDriftIndicators`), NEVER as definitive compliance
"violations" or "deployment blockers" that could contradict an actual
post-deployment CES run.
4. **Static Built-In Catalog, Session Caching, Support Routing & KAJ Flow**:
* Built-in Frameworks (`type: BUILT_IN`) returned by
`gcloud compliance-manager frameworks list` are static configurations
uniform across organizations. Fetch `frameworks.json` once per session and
reuse the cached file across all candidate evaluations and follow-up
queries.
* **Personnel Support Model**: Determine whether a framework requires a
**Paid Sovereign/Regulated Support Subscription** or uses **Standard
Commercial Support** ($0 support uplift) from the framework's public
`displayName` and `description` in `frameworks.json`:
- **Paid Sovereign/Regulated Support Subscription**: Frameworks whose
`description` specifies support personnel access controls (e.g.,
`"Support access controls are set to ..."`, `-and-support` variants
such as `builtin-eu-data-boundary-and-support` and
`builtin-us-data-boundary-and-support`, or regulated standards such as
`builtin-il4`, `builtin-il5`, `builtin-itar`, `builtin-fedramp-high`,
`builtin-cjis`).
- **Standard Commercial Support ($0 support uplift)**: Regional-only Data
Boundary frameworks whose `description` sets data location controls only
without a support access controls clause (e.g.,
`builtin-us-data-boundary`, `builtin-eu-data-boundary`,
`builtin-uk-data-boundary`, `builtin-japan-data-boundary`).
- **Important**: Do NOT use the mere presence of
`builtin-restrict-technical-support-services` in `cloudControlDetails`
as a discriminator, because both regional-only and paid-support Data
Boundary frameworks include that control.
* **Key Access Justifications (KAJ) & EKM**: Recommend
`-with-access-justifications` framework variants only when the customer
**explicitly requests KAJ/EKM**, or when disambiguating between matching
regional variants in `frameworks.json`.
5. **Deterministic Tool Gating**:
* You MUST NOT guess compatibility scores ($$S_{\text{composite}}$$) or resource inventories.
* You MUST execute `scripts/evaluate_control_rules.py` with `--frameworks-file=frameworks.json`.
## Prerequisites
Before executing environment assessment, ensure your local or Cloud Shell environment meets the following prerequisites:
1. **Google Cloud SDK**:
* Install and initialize the latest Google Cloud CLI (`gcloud`): https://docs.cloud.google.com/sdk/docs/install.md.txt
2. **Project Setup & Target Selection**:
* Select or configure an administrative project for running assessment queries:
```bash
gcloud config set project PROJECT_ID
```
3. **Region Configuration & Availability**:
* Configure a well-supported default region (e.g. `us-central1`):
```bash
gcloud config set compute/region us-central1
```
* Consult official region availability documentation: [Google Cloud Locations](https://cloud.google.com/about/locations).
4. **Required API Enablement**:
* Enable the required Google Cloud APIs on the administrative project:
```bash
gcloud services enable \
cloudasset.googleapis.com \
orgpolicy.googleapis.com \
assuredworkloads.googleapis.com \
cloudsecuritycompliance.googleapis.com
```
5. **Authentication Setup**:
* Authenticate your user or service account identity and establish application default credentials:
```bash
gcloud auth login
gcloud auth application-default login
```
6. **Billing & Quota Project Setup (Zero Billing Impact)**:
* **Zero-Cost Assessment Guarantee**: Running this assessment incurs **$0 in
Google Cloud infrastructure and API billing charges**. All discovery
operations (`gcloud asset search-all-resources`,
`gcloud compliance-manager frameworks list`, and
`gcloud org-policies describe --effective`) are free read-only metadata
queries.
* **Quota Project Requirement**: Google Cloud Service Infrastructure requires an administrative project with an active Cloud Billing account attached to allocate API rate limits and meter service usage (sent via the `X-Goog-User-Project` header), even for free APIs.
* **Pre-Flight Verification**:
```bash
# 1. Verify active Cloud Billing account is attached to administrative project
gcloud billing projects describe PROJECT_ID --format="value(billingEnabled)"
# 2. If using a shared project, ensure your user identity has permission to consume project quota
gcloud projects add-iam-policy-binding PROJECT_ID \
--member="user:USER_EMAIL" \
--role="roles/serviceusage.serviceUsageConsumer"
# 3. Synchronize Application Default Credentials quota project
gcloud auth application-default set-quota-project PROJECT_ID
```
7. **Commands & Payloads Reference**:
* Consult the [Google Cloud CLI Commands Reference](references/gcloud-commands.md) for full server-side projection masks, field filters, and API payload definitions.
---
## Step-by-Step Operating Workflow
### Step 1: Ingest Scope & Resolve Organization ID
1. Accept or prompt for the target scope (`folders/{folder_id}` or `projects/{project_id}`). If the user provides an open-ended scope without stating a regulatory regime, DO NOT block on broad questionnaires. Proceed immediately to ingest telemetry.
2. Automatically resolve the parent Organization ID from the scope to drive downstream catalog queries:
* **For Folders**:
```bash
gcloud resource-manager folders describe FOLDER_ID --format="value(parent)"
```
*(If the parent is another folder, traverse up ancestors until `organizations/{org_id}` is found)*
* **For Projects**:
```bash
gcloud projects get-ancestors PROJECT_ID --format="value(id,type)"
```
### Step 2: Ingest Asset Telemetry & Effective Org Policies via Two-Pass Telescoping Protocol
To guarantee 100% coverage across the scope hierarchy while keeping payloads compact, telemetry ingestion executes in two telescoping passes (see [Google Cloud CLI Commands Reference](references/gcloud-commands.md)):
1. **Pass 1: Macro Footprint & API Enumeration (100% Scope Coverage)**:
```bash
gcloud asset search-all-resources \
--scope="folders/FOLDER_ID" \
--page-size=500 \
--format="json(name,assetType,location)" > macro_telemetry.json
```
* *Pagination & Scope Semantics*: `--page-size=500` fetches 500 cloud assets
per HTTP API page (the maximum batch size permitted by Cloud Asset
Inventory), automatically paginating through all assets strictly inside
`folders/FOLDER_ID` and its descendant projects.
* *Full Location & SUR Coverage*: `macro_telemetry.json` captures 100% of
active `location` and `assetType` values required to evaluate both
`builtin-restrict-resource-locations` (`allowedLocations`) and
`builtin-enforce-service-usage-restrictions` (`allowedServices` / SUR).
* If `PERMISSION_DENIED` is returned:
- If the error states `USER_PROJECT_DENIED` or references `roles/serviceusage.serviceUsageConsumer`, the error is on the **administrative quota project** (it lacks an attached billing account or caller lacks `serviceUsageConsumer`). Follow the Quota Project Recovery playbook and stop running further commands.
- If the error references the target scope (`folders/...` or `projects/...`), HALT ALL TOOL CALLS IMMEDIATELY (do not run Step 2.2, Step 3, or any further commands) and inform the user they require `roles/cloudasset.viewer` and `roles/orgpolicy.policyViewer` on that scope.
* If 0 resources are returned, inform the user the target scope is empty.
2. **Inspect Effective Universal Org Policies on Scope (`38/38` Frameworks)**:
```bash
gcloud org-policies describe gcp.resourceLocations \
--folder=FOLDER_ID \
--effective \
--format="json(name,spec.rules)" > effective_locations.json
gcloud org-policies describe gcp.restrictServiceUsage \
--folder=FOLDER_ID \
--effective \
--format="json(name,spec.rules)" > effective_services.json
gcloud org-policies describe gcp.restrictTLSVersion \
--folder=FOLDER_ID \
--effective \
--format="json(name,spec.rules)" > effective_tls.json
```
### Step 3: Fetch & Cache Built-In Framework Catalog and Filter by Location + SUR
1. **Fetch & Cache Built-In Framework Catalog (with Bound Parameters)**:
```bash
if [ ! -s frameworks.json ]; then
gcloud compliance-manager frameworks list \
--organization=ORGANIZATION_ID \
--location=global \
--filter="category:ASSURED_WORKLOADS" \
--format="json(name,majorRevisionId,displayName,description,category,cloudControlDetails)" > frameworks.json
fi
```
* *Session Caching*: Because built-in `ASSURED_WORKLOADS` frameworks are
static definitions uniform across organizations, cache the output in
`frameworks.json` and reuse it for all candidate evaluations and follow-up
questions.
2. **Filter Candidates by Location + SUR Footprint & Clarify Intent**:
* Exclude location-less control-plane management metadata
(`cloudresourcemanager.googleapis.com/*`, `orgpolicy.googleapis.com/*`,
`cloudasset.googleapis.com/*`, `accesscontextmanager.googleapis.com/*`, and
`location: "global"` hierarchy nodes) from data-plane location checks.
* Match active data-plane regions (`location`) and active service prefixes
(`assetType`) from `macro_telemetry.json` against each framework's
`builtin-restrict-resource-locations` (`allowedLocations`) and
`builtin-enforce-service-usage-restrictions` (`allowedServices` / SUR)
parameters in `frameworks.json`:
* **US-Only Regions (`us-central1`, `us-east4`)**: Candidates include DoD
IL5 (`builtin-il5`, adjudicated support), ITAR (`builtin-itar`, US
persons support), FedRAMP High/Moderate, or US Regional Data Boundary
(`builtin-us-data-boundary`, standard commercial support).
* **EU-Only Regions (`europe-west3`, `europe-west1`)**: Candidates include
EU Data Boundary and Support (`builtin-eu-data-boundary-and-support`) vs.
standard EU Regional Boundary (`builtin-eu-data-boundary`).
* **Targeted Disambiguation**:
* If multiple frameworks match the physical footprint and user regulatory
intent is unstated (e.g., an open-ended request with no regime specified),
DO NOT finalize a single primary recommendation yet — present the matching
candidate frameworks and STOP to ask the user a targeted clarifying
question about their regulatory intent (e.g., EU Sovereignty, US
FedRAMP/IL5) and personnel support model (Standard Commercial Support vs.
Paid Sovereign/Regulated Support).
* Recommend `-with-access-justifications` (KAJ/EKM) framework variants only
if the customer explicitly asks for KAJ/EKM or when disambiguating
between matching regional variants.
* **Out-of-Scope / Non-Catalog Compliance Standards (e.g., CMMC, UK
GDPR)**:
If the user asks to evaluate a compliance standard or legal certification
that is not present as a built-in `ASSURED_WORKLOADS` framework in
`frameworks.json` (such as CMMC, UK GDPR, SOC 2, or PCI-DSS), DO NOT
fabricate or pass non-existent framework IDs (e.g., `builtin-cmmc` or
`builtin-uk-gdpr`) to `evaluate_control_rules.py`. Explicitly state that
the requested standard is not a standalone Assured Workloads Data
Boundary framework, explain the catalog scope boundary (Data Boundary
enforces regional data residency, SUR, CMEK, and sovereign support
routing rather than legal privacy or third-party certification audits),
and offer the closest adjacent `ASSURED_WORKLOADS` frameworks from
`frameworks.json` that match their active regional footprint (e.g.,
`builtin-il5` or `builtin-fedramp-high` for US defense/CUI workloads, or
`builtin-eu-data-boundary-and-support` / `builtin-eu-data-boundary` /
`builtin-uk-data-boundary` for European/UK regional residency).
### Step 4: Conditional Pass 2 CMEK Ingestion & Org Policy Evaluation
1. **Pass 2: Conditional Targeted Deep Ingestion for CMEK Resource Types**:
Derive `TARGET_TYPES` (the intersection of active CAI `assetType`s in
`macro_telemetry.json` and CMEK-governed services in `builtin-require-cmek`
from `frameworks.json`). Only 6 of the 38 Data Boundary frameworks include
`builtin-require-cmek`; if `TARGET_TYPES` is non-empty, fetch `kmsKeys`:
```bash
TARGET_TYPES=$(python3 scripts/evaluate_control_rules.py \
--get-target-asset-types \
--framework=FRAMEWORK_ID \
--telemetry-file=macro_telemetry.json \
--frameworks-file=frameworks.json)
if [ -n "${TARGET_TYPES}" ]; then
gcloud asset search-all-resources \
--scope="folders/FOLDER_ID" \
--asset-types="${TARGET_TYPES}" \
--page-size=500 \
--format="json(name,assetType,location,kmsKeys)" > deep_telemetry.json
fi
```
2. **Execute High-Confidence Org Policy Evaluator**:
Run `scripts/evaluate_control_rules.py` over `macro_telemetry.json` (and
optional `deep_telemetry.json`) with `frameworks.json` to compute the 3
quantitative scores (`locationScore`, `serviceScore`, `cmekScore`,
`compositeScore`) and `orgPolicyDriftIndicators` (when `cmekRequired` is
`false`, always display the CMEK Readiness column as `N/A` in the scorecard):
```bash
python3 scripts/evaluate_control_rules.py \
--telemetry-file=macro_telemetry.json \
--deep-telemetry-file=deep_telemetry.json \
--framework=FRAMEWORK_ID \
--frameworks-file=frameworks.json
```
3. **Evaluate Operational & Governance Impact**:
* Review `cloudControlDetails` in `frameworks.json` for parameterized and
operational controls (`builtin-restrict-kms-protection-levels`,
`builtin-enforce-allowed-cmek-crypto-key-projects`,
`builtin-restrict-cloud-function-generations`,
`builtin-restrict-cloudstorage-auth-types`,
`builtin-iam-disable-service-account-key-creation`,
`builtin-disable-ssh-in-browser`, `builtin-enable-axt`, and
`*-regulatory-settings` controls like
`builtin-cloud-logging-regulatory-settings`) and summarize their workflow
impact in the final report.
### Step 5: Render Executive Assessment Report (Minto Pyramid Structure)
Present an executive report structured around the **Minto Pyramid Principle**
(Bottom Line Up Front -> Core Value Pillars -> Supporting Evidence -> Action
Plan):
```markdown
# Compliance Environment Assessment Report: [Scope URI]
## 1. Executive Conclusion & Recommendation (Bottom Line Up Front)
* **Primary Recommendation**: [Framework Name] (`organizations/{org_id}/locations/global/frameworks/{framework_id}`)
* **Org Policy Readiness Alignment**: [Composite Fit %]
* **Recommended Deployment Mode**:
* **Existing Workloads (Folders or Projects)**: Deploy in **Monitoring (`Detective`) mode** first, then transition to **Preventive** mode after remediating findings.
* **New Workloads (Folders or Projects)**: Start in **Preventive** mode or **Monitoring (`Detective`) mode**.
* **Zero Production Outage Risk**: Monitoring (`Detective`) mode mutates zero Organization Policies on Day 0.
* **Continuous Server-Side CES Observability**: Activates real-time Continuous Evaluation Service (CES) monitoring across all framework controls.
* **No Migration Required**: Protects existing folders and projects in-place without migrating resources.
---
## 2. Core Value Drivers: Why Assured Workloads Fits This Scope
1. **Residency & Boundary Alignment (`gcp.resourceLocations`)**: Active regional workloads are evaluated against allowed regions ([e.g. 100% US-contained]).
2. **Service & API Compatibility (`gcp.restrictServiceUsage` / SUR)**: Active service APIs are evaluated against accredited service allowlists ([e.g. 100% approved services]).
3. **Non-Disruptive Posture Hardening**: Enrolling existing workloads in Monitoring (`Detective`) mode provides server-side CES posture evaluation while allowing your team to triage Org Policy readiness safely before moving to Preventive mode.
---
## 3. Objective Assessment Scorecard & Org Policy Readiness Triage
### Quantitative Org Policy Readiness Scorecard
| Candidate Framework | Location Residency (`locationScore`) | Service Usage / SUR (`serviceScore`) | CMEK Readiness (`cmekScore`) | Composite Alignment | Personnel Support Model |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **[Framework 1]** | [XX%] | [XX%] | [XX% or N/A] | **[XX%]** | [Support Model] |
| **[Framework 2]** | [XX%] | [XX%] | [XX% or N/A] | **[XX%]** | [Support Model] |
### Active Resource & Effective Org Policy Baseline
* **Discovered Inventory**: [Total Assets count] across [Active resource types and regions].
* **Effective Org Policy Baseline**: [Effective `gcp.resourceLocations`, `gcp.restrictServiceUsage`, and `gcp.restrictTLSVersion` posture].
### Pre-Flight Org Policy Readiness Recommendations (Prior to Preventive Mode)
*Pre-flight drift indicators do NOT block Day 0 deployment in Monitoring (`Detective`) mode. Address these prior to enabling Preventive policy enforcement (authoritative CES and REST control evaluations run server-side after deployment):*
* **[Priority 1]**: [e.g. Configure CMEK keys on unencrypted resources before toggling `builtin-require-cmek` to `PREVENTIVE`].
* **[Priority 2]**: [e.g. Operational impact of bound controls such as `builtin-restrict-kms-protection-levels` or `builtin-cloud-logging-regulatory-settings`].
---
## 4. Deployment Action Plan & Commercial Advisory
### Deploy via Google Cloud Console — Assured Workloads Frameworks Tab (Recommended)
Review and deploy the recommended framework directly in the Google Cloud Console **Assured Workloads -> Frameworks** tab:
👉 **[Open Assured Workloads Frameworks Console](https://console.cloud.google.com/compliance/configure/frameworks?organizationId=ORGANIZATION_ID)**
* **Existing Workloads (Folders or Projects)**: Deploy in **Monitoring (`Detective`) mode** to evaluate posture and remediate findings with zero Day 0 Organization Policy mutations, then transition to **Preventive** mode.
* **New Workloads (Folders or Projects)**: Start directly in **Preventive** mode or in **Monitoring (`Detective`) mode**.
### Commercial & Licensing Advisory
* Assured Workloads compliance regimes may carry support routing or licensing entitlements depending on whether the framework enforces regional data location controls only (standard commercial support, $0 support uplift) or specifies support personnel access controls in its `displayName` and `description` (paid sovereign/regulated support).
* Review full pricing details and entitlement tiers at: https://cloud.google.com/assured-workloads/pricing
```
### Step 6: Handling Customer Follow-Up Questions on Specific Services
When a customer follows up with a specific question about how a recommended or
candidate framework affects a particular Google Cloud service (e.g., Cloud Run,
Cloud Storage, Spanner, GKE, Cloud SQL, Vertex AI, Cloud Logging):
1. **Inspect Cached `frameworks.json` Locally (or Fetch via Step 3 `frameworks list` if Not Cached)**:
* If `frameworks.json` is not yet present in the current working directory, run the Step 3 `gcloud compliance-manager frameworks list` command first to populate `frameworks.json`.
* Check whether `<service>.googleapis.com` is permitted in
`builtin-enforce-service-usage-restrictions` (`allowedServices`) and
whether CMEK is required in `builtin-require-cmek` (`services`).
* Identify all service-specific `cloudControlDetails[].name` entries bound in
that framework (e.g., `builtin-run-disable-ephemeral-disk`,
`builtin-restrict-cloudstorage-auth-types`,
`builtin-disable-spanner-multi-region`,
`builtin-cloud-logging-regulatory-settings`) and any bound `parameters`.
2. **Fetch Authoritative Control Details On Demand**:
* Because `Framework.cloudControlDetails` omits control descriptions,
enforcement modes, and remediation steps, run `cloud-controls describe` for
the relevant control ID(s):
```bash
gcloud compliance-manager cloud-controls describe CONTROL_ID \
--organization=ORGANIZATION_ID \
--location=global \
--format="json(name,displayName,description,supportedEnforcementModes,remediationSteps,parameterSpec)"
```
* Extract the exact underlying Organization Policy constraint (e.g.,
`run.managed.disableEphemeralDisk`, `storage.restrictAuthTypes`),
`supportedEnforcementModes` (`PREVENTIVE` vs. `DETECTIVE`), and
`remediationSteps` from the response.
3. **Check Effective Folder/Project Policy If Requested**:
* If the customer asks whether their folder already enforces that
service-specific Org Policy constraint, run:
```bash
gcloud org-policies describe CONSTRAINT_NAME \
--folder=FOLDER_ID \
--effective \
--format="json(name,spec.rules)"
```
---
## Failure Modes & Error Recovery Playbook
| Error Condition | Immediate Action | User Recovery Guidance |
| :--- | :--- | :--- |
| **`USER_PROJECT_DENIED` or `serviceusage.serviceUsageConsumer`** | HALT discovery. Do not confuse with target scope permissions. Check administrative project billing status and caller quota permissions. | *"The administrative project `PROJECT_ID` cannot be used for API quota. 1) Verify a Cloud Billing account is attached (`gcloud billing projects describe PROJECT_ID`), 2) Grant `roles/serviceusage.serviceUsageConsumer` on `PROJECT_ID` to your identity, or 3) Switch to a project you own: `gcloud config set project <PROJECT_ID>`."* |
| **`PERMISSION_DENIED` on CAIS** | HALT discovery immediately. Do not speculate or guess resources. | *"To analyze this environment, grant `roles/cloudasset.viewer` on `folders/123` to your active identity."* |
| **`PERMISSION_DENIED` on Org Policies** | HALT policy inspection. Do not guess effective constraints. | *"To inspect effective organization policies, grant `roles/orgpolicy.policyViewer` on `folders/123`."* |
| **Empty Scope (0 Resources)** | HALT evaluation. Inform user the scope contains no active assets. | *"No active resources found in `folders/123`. Provision resources or select an active scope."* |
| **Conflicting Regulatory Intent** | Engage user in focused clarification probe. | Present distinct requirements (e.g. DoD IL5 Adjudicated Support vs. ITAR US Persons) and ask for business requirement. |
| **Zero Catalog Match** | Detail multi-regional drift indicator. | Explain why single-region sovereign data boundary frameworks were ruled out (e.g. multi-continental resource footprint spanning unapproved regions). |
| **Out-of-Scope / Non-Catalog Standard (e.g., CMMC, UK GDPR)** | Do not invent framework IDs (`builtin-cmmc`, `builtin-uk-gdpr`). Explain catalog boundary and map to adjacent `ASSURED_WORKLOADS` candidates. | *"Assured Workloads does not include a standalone `[CMMC / UK GDPR]` framework in `frameworks.json`. However, based on your active resources, we can evaluate an adjacent Assured Workloads Data Boundary framework such as `builtin-il5` / `builtin-fedramp-high` (for US defense/federal workloads) or `builtin-eu-data-boundary-and-support` / `builtin-uk-data-boundary` (for European/UK regional residency)."* |
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:assuredworkloads-environment-assessor)" \
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:assuredworkloads-environment-assessor)`
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:assuredworkloads-environment-assessor)
```
- **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.
gcloud-commands.md 4.5 KB
# Google Cloud CLI Commands Reference for Compliance Environment Assessment
This reference documents the read-only Google Cloud CLI (`gcloud`) commands and server-side field projection masks utilized by the `assuredworkloads-environment-assessor` skill.
## Table of Contents
* [1. Scope Resolution & Ancestry](#1-scope-resolution-ancestry)
* [2. Resource Telemetry Ingestion (Cloud Asset Inventory)](#2-resource-telemetry-ingestion-cloud-asset-inventory)
* [3. Assured Workloads Framework & Control Discovery](#3-assured-workloads-framework-control-discovery)
* [4. Organization Policy Inspection](#4-organization-policy-inspection)
* [5. Framework Deployment via Google Cloud Console](#5-framework-deployment-via-google-cloud-console)
---
## 1. Scope Resolution & Ancestry
### Resolve Folder Parent & Organization
```bash
# Check direct parent of folder
gcloud resource-manager folders describe FOLDER_ID --format="value(parent)"
```
*If the parent is `folders/...`, recursively inspect until `organizations/{org_id}` is found.*
### Resolve Project Ancestry
```bash
# List all ancestors from project up to root Organization
gcloud projects get-ancestors PROJECT_ID --format="value(id,type)"
```
---
## 2. Resource Telemetry Ingestion (Cloud Asset Inventory)
### Pass 1: Macro Footprint & API Enumeration (100% Coverage Across Scope)
```bash
gcloud asset search-all-resources \
--scope="folders/123456" \
--page-size=500 \
--format="json(name,assetType,location)" > macro_telemetry.json
```
### Pass 2: Conditional Targeted Deep Ingestion for CMEK Readiness (`kmsKeys`)
```bash
gcloud asset search-all-resources \
--scope="folders/123456" \
--asset-types="${TARGET_TYPES}" \
--page-size=500 \
--format="json(name,assetType,location,kmsKeys)" > deep_telemetry.json
```
*Note: `search-all-resources` is free of charge ($0 billing impact), but Google Cloud requires an administrative project with an active Cloud Billing account attached to allocate API rate limits (`gcloud config set project PROJECT_ID`).*
### Key Field Extraction
* **`name`**: Cloud resource URI (e.g. `//compute.googleapis.com/projects/.../instances/...`).
* **`assetType`**: Google Cloud resource type (e.g. `compute.googleapis.com/Instance`, `storage.googleapis.com/Bucket`).
* **`location`**: Region or zone string (e.g. `us-central1`, `europe-west3`, `us-east4-a`).
* **`kmsKeys`**: Customer-Managed Encryption Key (CMEK) URIs bound to the resource.
---
## 3. Assured Workloads Framework & Control Discovery
### List & Cache Built-in Assured Workloads Frameworks (Including Bound Parameters)
```bash
if [ ! -s frameworks.json ]; then
gcloud compliance-manager frameworks list \
--organization=ORGANIZATION_ID \
--location=global \
--filter="category:ASSURED_WORKLOADS" \
--format="json(name,majorRevisionId,displayName,description,category,cloudControlDetails)" > frameworks.json
fi
```
### On-Demand Service Follow-Up: Describe a Specific Cloud Control
```bash
gcloud compliance-manager cloud-controls describe CONTROL_ID \
--organization=ORGANIZATION_ID \
--location=global \
--format="json(name,displayName,description,supportedEnforcementModes,remediationSteps,parameterSpec)"
```
---
## 4. Organization Policy Inspection
### Describe Effective Universal Constraints on Scope (`38/38` Frameworks)
```bash
# Check effective resource locations constraint
gcloud org-policies describe gcp.resourceLocations \
--folder=FOLDER_ID \
--effective \
--format="json(name,spec.rules)"
# Check effective service usage restriction (SUR) constraint
gcloud org-policies describe gcp.restrictServiceUsage \
--folder=FOLDER_ID \
--effective \
--format="json(name,spec.rules)"
# Check effective TLS version restriction constraint
gcloud org-policies describe gcp.restrictTLSVersion \
--folder=FOLDER_ID \
--effective \
--format="json(name,spec.rules)"
```
---
## 5. Framework Deployment via Google Cloud Console
After completing the read-only compliance assessment, guide the customer or
cloud administrator to deploy the recommended framework in the Google Cloud
Console **Assured Workloads -> Frameworks** tab:
```
https://console.cloud.google.com/compliance/configure/frameworks?organizationId=ORGANIZATION_ID
```
### Recommended Deployment Modes
* **Existing Workloads (Folders or Projects)**: Deploy in
**Monitoring (`Detective`) mode** first to assess posture and remediate
findings with zero Day 0 Organization Policy mutations, and then transition
to **Preventive** mode.
* **New Workloads (Folders or Projects)**: Start directly in **Preventive**
mode or in **Monitoring (`Detective`) mode**.
evaluate_control_rules.py 18.2 KB
#!/usr/bin/env python3
r"""Hermetic CLI utility for evaluating CAIS telemetry against Org Policy specs.
Evaluates the 3 deterministic Organization Policy parameter sets bound in
`google.cloud.cloudsecuritycompliance.v1.Framework.cloudControlDetails`:
1. Resource Locations (`builtin-restrict-resource-locations`)
2. Service Usage Restrictions / SUR
(`builtin-enforce-service-usage-restrictions`)
3. CMEK Encryption Requirements (`builtin-require-cmek`)
Usage:
python3 scripts/evaluate_control_rules.py \
--telemetry-file=macro_telemetry.json \
--deep-telemetry-file=deep_telemetry.json \
--framework=builtin-il5 \
--frameworks-file=frameworks.json
"""
import argparse
import json
import sys
import types
from typing import Any
CONTROL_PLANE_SERVICE_PREFIXES: frozenset[str] = frozenset({
"cloudresourcemanager.googleapis.com",
"orgpolicy.googleapis.com",
"cloudasset.googleapis.com",
"accesscontextmanager.googleapis.com",
})
CONTROL_PLANE_ASSET_TYPES: frozenset[str] = frozenset({
"cloudresourcemanager.googleapis.com/Organization",
"cloudresourcemanager.googleapis.com/Folder",
"cloudresourcemanager.googleapis.com/Project",
"orgpolicy.googleapis.com/Policy",
"cloudasset.googleapis.com/Feed",
"logging.googleapis.com/BillingAccountSettings",
"logging.googleapis.com/OrganizationSettings",
"logging.googleapis.com/FolderSettings",
})
# Standard CAI data-plane asset types associated with CMEK-governed services
# when get_target_asset_types is invoked without Pass 1 active_resources.
DEFAULT_CMEK_SERVICE_ASSET_TYPES: types.MappingProxyType[
str, tuple[str, ...]
] = types.MappingProxyType({
"compute.googleapis.com": (
"compute.googleapis.com/Instance",
"compute.googleapis.com/Disk",
),
"storage.googleapis.com": ("storage.googleapis.com/Bucket",),
"sqladmin.googleapis.com": ("sqladmin.googleapis.com/Instance",),
"container.googleapis.com": ("container.googleapis.com/Cluster",),
"bigquery.googleapis.com": (
"bigquery.googleapis.com/Dataset",
"bigquery.googleapis.com/Table",
),
"pubsub.googleapis.com": ("pubsub.googleapis.com/Topic",),
"secretmanager.googleapis.com": ("secretmanager.googleapis.com/Secret",),
"spanner.googleapis.com": ("spanner.googleapis.com/Instance",),
"run.googleapis.com": ("run.googleapis.com/Service",),
"artifactregistry.googleapis.com": (
"artifactregistry.googleapis.com/Repository",
),
"aiplatform.googleapis.com": ("aiplatform.googleapis.com/Dataset",),
})
# Location value groups used by constraints/gcp.resourceLocations in csclibrary
LOCATION_GROUP_PREFIXES: types.MappingProxyType[str, tuple[str, ...]] = (
types.MappingProxyType({
"us-locations": ("us-", "us"),
"in:us-locations": ("us-", "us"),
"eu-locations": ("europe-", "eu"),
"in:eu-locations": ("europe-", "eu"),
})
)
LOCATION_GROUP_EXACT_REGIONS: types.MappingProxyType[str, frozenset[str]] = (
types.MappingProxyType({
"canada-locations": frozenset(
{"northamerica-northeast1", "northamerica-northeast2"}
),
"in:canada-locations": frozenset(
{"northamerica-northeast1", "northamerica-northeast2"}
),
"australia-locations": frozenset(
{"australia-southeast1", "australia-southeast2"}
),
"in:australia-locations": frozenset(
{"australia-southeast1", "australia-southeast2"}
),
"india-locations": frozenset({"asia-south1", "asia-south2"}),
"in:india-locations": frozenset({"asia-south1", "asia-south2"}),
"japan-locations": frozenset({"asia-northeast1", "asia-northeast2"}),
"in:japan-locations": frozenset({"asia-northeast1", "asia-northeast2"}),
"israel-locations": frozenset({"me-west1"}),
"in:israel-locations": frozenset({"me-west1"}),
"ksa-locations": frozenset({"me-central2"}),
"in:ksa-locations": frozenset({"me-central2"}),
"switzerland-locations": frozenset({"europe-west6"}),
"in:switzerland-locations": frozenset({"europe-west6"}),
"uk-locations": frozenset({"europe-west2"}),
"in:uk-locations": frozenset({"europe-west2"}),
})
)
def is_control_plane_metadata(resource: dict[str, Any]) -> bool:
"""Identifies control-plane metadata to exclude from workload evaluation."""
asset_type = resource.get("assetType", "")
prefix = asset_type.split("/")[0] if "/" in asset_type else asset_type
return (
prefix in CONTROL_PLANE_SERVICE_PREFIXES
or asset_type in CONTROL_PLANE_ASSET_TYPES
)
def _extract_string_list_from_param_value(
param_val: dict[str, Any],
) -> list[str]:
"""Extracts a list of strings from a v1.ParamValue protobuf JSON structure."""
if not isinstance(param_val, dict):
return []
if "stringListValue" in param_val:
values = param_val["stringListValue"].get("values", [])
return [str(val) for val in values if val]
if "stringValue" in param_val and param_val["stringValue"]:
return [str(param_val["stringValue"])]
if "oneofValue" in param_val and isinstance(param_val["oneofValue"], dict):
nested_param_val = param_val["oneofValue"].get("parameterValue", {})
return _extract_string_list_from_param_value(nested_param_val)
return []
def parse_framework_org_policy_spec(
frameworks: list[dict[str, Any]], framework_id: str
) -> dict[str, Any]:
"""Extracts the 3 quantitative Org Policy parameter sets from a Framework."""
if not frameworks:
raise ValueError(
"Empty frameworks list provided. Assured Workloads Frameworks Library"
" export is empty."
)
clean_framework_id = framework_id.split("/")[-1].strip()
matched_framework: dict[str, Any] | None = None
for framework in frameworks:
framework_name = framework.get("name", "")
candidate_id = framework_name.split("/")[-1] if framework_name else ""
if candidate_id == clean_framework_id or candidate_id.replace(
"_", "-"
) == clean_framework_id.replace("_", "-"):
matched_framework = framework
break
if matched_framework is None:
raise ValueError(
f"Framework '{clean_framework_id}' not found in frameworks.json export."
" Ensure 'gcloud compliance-manager frameworks list' output includes"
" this framework."
)
allowed_locations: set[str] = set()
allowed_services: set[str] = set()
cmek_services: set[str] = set()
cmek_required = False
for control in matched_framework.get("cloudControlDetails", []):
control_name = control.get("name", "")
control_id = control_name.split("/")[-1] if control_name else ""
params = control.get("parameters", [])
if control_id == "builtin-restrict-resource-locations":
for param in params:
if param.get("name") in ("locations", "allowedLocations"):
allowed_locations.update(
_extract_string_list_from_param_value(
param.get("parameterValue", {})
)
)
elif control_id == "builtin-enforce-service-usage-restrictions":
for param in params:
if param.get("name") in ("serviceUsage", "allowedServices"):
allowed_services.update(
_extract_string_list_from_param_value(
param.get("parameterValue", {})
)
)
elif control_id == "builtin-require-cmek":
cmek_required = True
for param in params:
if param.get("name") == "services":
cmek_services.update(
_extract_string_list_from_param_value(
param.get("parameterValue", {})
)
)
return {
"framework_id": clean_framework_id,
"allowed_locations": allowed_locations,
"allowed_services": allowed_services,
"cmek_services": cmek_services,
"cmek_required": cmek_required,
}
def is_location_allowed(location: str, allowed_locations: set[str]) -> bool:
"""Checks whether a CAIS resource location satisfies resourceLocations."""
if not allowed_locations:
return True
loc = location.strip().lower()
region = "-".join(loc.split("-")[:2]) if "-" in loc else loc
normalized_allowed = {
allowed_loc.strip().lower() for allowed_loc in allowed_locations
}
if (
loc in normalized_allowed
or region in normalized_allowed
or f"in:{loc}-locations" in normalized_allowed
or f"in:{region}-locations" in normalized_allowed
):
return True
for group_token, prefixes in LOCATION_GROUP_PREFIXES.items():
if group_token in normalized_allowed:
if any(
loc == prefix
or loc.startswith(prefix)
or region == prefix
or region.startswith(prefix)
for prefix in prefixes
):
return True
for group_token, exact_regions in LOCATION_GROUP_EXACT_REGIONS.items():
if group_token in normalized_allowed:
if loc in exact_regions or region in exact_regions:
return True
return False
def get_target_asset_types(
framework_id: str,
frameworks: list[dict[str, Any]],
active_resources: list[dict[str, Any]] | None = None,
) -> list[str]:
"""Derives the CAIS asset types requiring Pass 2 CMEK inspection (`kmsKeys`).
Only the 6/38 Data Boundary frameworks that include `builtin-require-cmek`
require Pass 2 CMEK ingestion; for the remaining 32/38 frameworks, this
returns an empty list so Pass 2 is skipped.
Args:
framework_id: Target framework identifier (e.g. 'builtin-il5').
frameworks: Parsed list of v1.Framework objects from frameworks.json.
active_resources: Optional Pass 1 CAIS resource list to intersect against.
Returns:
Sorted list of CAIS assetType strings requiring Pass 2 CMEK inspection.
"""
spec = parse_framework_org_policy_spec(frameworks, framework_id)
if not spec["cmek_required"] or not spec["cmek_services"]:
return []
cmek_services: set[str] = spec["cmek_services"]
if active_resources is not None:
targets: set[str] = set()
for resource in active_resources:
if is_control_plane_metadata(resource):
continue
asset_type = resource.get("assetType", "")
if "/" not in asset_type:
continue
service_prefix = asset_type.split("/")[0]
if service_prefix in cmek_services:
targets.add(asset_type)
return sorted(targets)
default_targets: set[str] = set()
for service_name in cmek_services:
for asset_type in DEFAULT_CMEK_SERVICE_ASSET_TYPES.get(service_name, ()):
default_targets.add(asset_type)
return sorted(default_targets)
def _extract_kms_keys(resource: dict[str, Any]) -> list[str]:
"""Extracts kmsKeys from CAIS ResourceSearchResult or additionalAttributes."""
top_keys = resource.get("kmsKeys")
if isinstance(top_keys, list) and top_keys:
return [str(key) for key in top_keys if key]
if isinstance(top_keys, str) and top_keys:
return [top_keys]
attrs = resource.get("additionalAttributes", {})
if isinstance(attrs, dict):
attr_keys = attrs.get("kmsKeys", [])
if isinstance(attr_keys, list) and attr_keys:
return [str(key) for key in attr_keys if key]
return []
def evaluate_telemetry(
resources: list[dict[str, Any]],
framework_id: str,
frameworks: list[dict[str, Any]],
deep_resources: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""Evaluates CAIS telemetry against the 3 deterministic Org Policy specs."""
spec = parse_framework_org_policy_spec(frameworks, framework_id)
cmek_required: bool = spec["cmek_required"]
# Index Pass 2 deep telemetry kmsKeys by resource name so Pass 1 telemetry
# remains the full-scope source of truth for Location and SUR.
deep_kms_by_name: dict[str, list[str]] = {}
if deep_resources:
for deep_resource in deep_resources:
resource_name = deep_resource.get("name")
if resource_name:
deep_kms_by_name[resource_name] = _extract_kms_keys(deep_resource)
workload_resources = [
resource
for resource in resources
if not is_control_plane_metadata(resource)
]
total_assets = len(workload_resources)
evaluation_note = (
"Pre-flight readiness indicators evaluate high-confidence Organization"
" Policy parameters (location, service usage, CMEK) over CAIS metadata."
" Authoritative CES and REST control evaluations run server-side via the"
" Continuous Evaluation Service (CES) after framework deployment."
)
if total_assets == 0:
return {
"frameworkId": framework_id,
"totalAssets": 0,
"cmekRequired": cmek_required,
"scores": {
"locationScore": 1.0,
"serviceScore": 1.0,
"cmekScore": 1.0,
"compositeScore": 1.0,
},
"orgPolicyDriftIndicators": {
"outOfBoundaryLocations": [],
"unapprovedServices": [],
"missingCmekAssets": [],
},
"evaluationNote": evaluation_note,
}
# 1. Location Org Policy Check (constraints/gcp.resourceLocations)
allowed_locations: set[str] = spec["allowed_locations"]
loc_targets = [
resource
for resource in workload_resources
if resource.get("location") and resource.get("location") != "global"
]
compliant_loc_count = 0
out_of_boundary_locations: list[dict[str, Any]] = []
for resource in loc_targets:
loc = resource.get("location", "")
if is_location_allowed(loc, allowed_locations):
compliant_loc_count += 1
else:
out_of_boundary_locations.append(
{"name": resource.get("name"), "location": loc}
)
total_loc_assets = len(loc_targets)
location_score = (
compliant_loc_count / total_loc_assets if total_loc_assets else 1.0
)
# 2. Service Usage Restriction Check (constraints/gcp.restrictServiceUsage)
allowed_services: set[str] = spec["allowed_services"]
compliant_svc_count = 0
unapproved_services: list[dict[str, Any]] = []
for resource in workload_resources:
asset_type = resource.get("assetType", "")
prefix = asset_type.split("/")[0] if "/" in asset_type else asset_type
if not allowed_services or prefix in allowed_services:
compliant_svc_count += 1
else:
unapproved_services.append(
{"name": resource.get("name"), "assetType": asset_type}
)
service_score = compliant_svc_count / total_assets if total_assets else 1.0
# 3. CMEK Org Policy Check (constraints/gcp.restrictNonCmekServices)
cmek_services: set[str] = spec["cmek_services"]
missing_cmek_assets: list[str] = []
if cmek_required and cmek_services:
cmek_targets = [
resource
for resource in workload_resources
if (
resource.get("assetType", "").split("/")[0]
if "/" in resource.get("assetType", "")
else resource.get("assetType", "")
)
in cmek_services
]
for resource in cmek_targets:
resource_name = resource.get("name", "")
kms_keys = _extract_kms_keys(resource) or deep_kms_by_name.get(
resource_name, []
)
if not kms_keys:
missing_cmek_assets.append(resource_name)
cmek_score = (
1.0 - (len(missing_cmek_assets) / len(cmek_targets))
if cmek_targets
else 1.0
)
else:
cmek_score = 1.0
if cmek_required:
composite_score = round(
0.40 * location_score + 0.35 * service_score + 0.25 * cmek_score, 4
)
else:
composite_score = round(
(0.40 / 0.75) * location_score + (0.35 / 0.75) * service_score, 4
)
return {
"frameworkId": framework_id,
"totalAssets": total_assets,
"cmekRequired": cmek_required,
"scores": {
"locationScore": round(location_score, 4),
"serviceScore": round(service_score, 4),
"cmekScore": round(cmek_score, 4),
"compositeScore": composite_score,
},
"orgPolicyDriftIndicators": {
"outOfBoundaryLocations": out_of_boundary_locations,
"unapprovedServices": unapproved_services,
"missingCmekAssets": missing_cmek_assets,
},
"evaluationNote": evaluation_note,
}
def main() -> None:
parser = argparse.ArgumentParser(
description=(
"Evaluate CAIS telemetry against Assured Workloads Organization"
" Policy parameters from frameworks.json."
)
)
parser.add_argument(
"--framework", required=True, help="Framework ID (e.g. builtin-il5)"
)
parser.add_argument(
"--telemetry-file",
required=False,
help="Path to Pass 1 CAIS macro telemetry JSON export",
)
parser.add_argument(
"--deep-telemetry-file",
required=False,
help="Optional path to Pass 2 CAIS deep telemetry JSON export (kmsKeys)",
)
parser.add_argument(
"--frameworks-file",
required=True,
help=(
"Path to frameworks JSON export from 'gcloud compliance-manager"
" frameworks list' (authoritative SOT)"
),
)
parser.add_argument(
"--get-target-asset-types",
action="store_true",
help=(
"Derive and print CMEK-governed CAIS asset types for Pass 2"
" inspection"
),
)
args = parser.parse_args()
try:
with open(args.frameworks_file, "r", encoding="utf-8") as f:
frameworks = json.load(f)
if args.get_target_asset_types:
active_resources = None
if args.telemetry_file:
with open(args.telemetry_file, "r", encoding="utf-8") as f:
active_resources = json.load(f)
target_types = get_target_asset_types(
args.framework, frameworks, active_resources
)
print(",".join(target_types))
return
if not args.telemetry_file:
sys.stderr.write(
"EVALUATION_ERROR: --telemetry-file is required for rule"
" evaluation.\n"
)
sys.exit(1)
with open(args.telemetry_file, "r", encoding="utf-8") as f:
resources = json.load(f)
deep_resources = None
if args.deep_telemetry_file:
try:
with open(args.deep_telemetry_file, "r", encoding="utf-8") as f:
deep_resources = json.load(f)
except FileNotFoundError:
deep_resources = None
result = evaluate_telemetry(
resources, args.framework, frameworks, deep_resources=deep_resources
)
print(json.dumps(result, indent=2))
except (ValueError, OSError, KeyError, TypeError) as e:
sys.stderr.write(f"EVALUATION_ERROR: {str(e)}\n")
sys.exit(1)
if __name__ == "__main__":
main()
validate_workload_payload.py 11.1 KB
#!/usr/bin/env python3
r"""Hermetic CLI utility for validating Assured Workloads request payloads.
Requires dynamic ingestion of Data Boundary frameworks directly from Assured
Workloads Frameworks Library via --frameworks-file:
python3 scripts/validate_workload_payload.py \
--payload-json='{"displayName":"Enclave","complianceRegime":"FEDRAMP_HIGH"}' \
--org-id=123456789 \
--frameworks-file=frameworks.json
Assured Workloads Frameworks Library (gcloud compliance-manager frameworks list)
is the authoritative Source of Truth (SOT). No static fallback lists are used.
"""
import argparse
import json
import re
import sys
from typing import Any
VALID_ENFORCEMENT_MODES: frozenset[str] = frozenset({
"PREVENTIVE",
"DETECTIVE",
"AUDIT",
})
_BUILTIN_PREFIX_RE = re.compile(r"^builtin[-_]")
_FOLDER_RE = re.compile(r"folders/\d+")
_PROJECT_RE = re.compile(r"projects/[a-z0-9-]+")
_FRAMEWORK_NAME_RE = re.compile(
r"organizations/(\d+)/locations/([^/]+)/frameworks/([^/]+)"
)
def load_allowed_frameworks_and_regimes(
frameworks_data: list[dict[str, Any]],
) -> tuple[set[str], set[str]]:
"""Extracts valid framework IDs and compliance regimes from v1.Framework."""
if not frameworks_data:
raise ValueError(
"Empty frameworks list provided. Assured Workloads Frameworks Library"
" export is empty."
)
allowed_frameworks: set[str] = set()
allowed_regimes: set[str] = set()
for framework in frameworks_data:
# Filter by public v1.Framework.category = ASSURED_WORKLOADS
category = framework.get("category", [])
if isinstance(category, list):
category_matches = any(
"ASSURED_WORKLOADS" in str(cat).upper() for cat in category
)
else:
category_matches = "ASSURED_WORKLOADS" in str(category).upper()
if category and not category_matches:
continue
# Extract framework ID from public v1.Framework.name
name = framework.get("name", "")
framework_id = name.split("/")[-1] if name else ""
if framework_id:
allowed_frameworks.add(framework_id)
allowed_frameworks.add(framework_id.replace("_", "-"))
allowed_frameworks.add(framework_id.replace("-", "_"))
# Extract compliance regimes from public v1.CloudControlDetails.parameters
for control in framework.get("cloudControlDetails", []):
for param in control.get("parameters", []):
param_value = param.get("parameterValue", {})
if isinstance(param_value, dict):
string_value = str(param_value.get("stringValue", "")).strip().upper()
if string_value.startswith("COMPLIANCE_REGIME_"):
clean_regime = string_value.replace("COMPLIANCE_REGIME_", "")
allowed_regimes.add(string_value)
allowed_regimes.add(clean_regime)
# Derive standard regime token from framework resource ID
if framework_id:
normalized_regime = (
_BUILTIN_PREFIX_RE.sub("", framework_id).upper().replace("-", "_")
)
allowed_regimes.add(normalized_regime)
if normalized_regime == "EU_DATA_BOUNDARY_AND_SUPPORT":
allowed_regimes.add("EU_REGIONS_AND_SUPPORT")
elif normalized_regime == "US_DATA_BOUNDARY":
allowed_regimes.add("US_REGIONAL_DATA_BOUNDARY")
elif normalized_regime == "AUSTRALIA_DATA_BOUNDARY":
allowed_regimes.add("AU_REGIONS_AND_SUPPORT")
elif normalized_regime == "JAPAN_DATA_BOUNDARY":
allowed_regimes.add("JP_REGIONS_AND_SUPPORT")
elif normalized_regime == "ISRAEL_DATA_BOUNDARY":
allowed_regimes.add("ISR_REGIONS_AND_SUPPORT")
if not allowed_frameworks:
raise ValueError(
"No Assured Workloads frameworks found in frameworks.json export."
" Ensure the catalog contains frameworks with category"
" ASSURED_WORKLOADS."
)
return allowed_frameworks, allowed_regimes
def validate_v1_workload_payload(
payload: dict[str, Any],
org_id: str,
location: str,
allowed_regimes: set[str],
) -> dict[str, Any]:
"""Validates payload against Assured Workloads v1 GA schema."""
display_name = payload.get("displayName")
if not display_name or not isinstance(display_name, str):
raise ValueError("Missing or invalid 'displayName' in v1 workload payload.")
regime = payload.get("complianceRegime")
if not regime or not isinstance(regime, str):
raise ValueError("Missing 'complianceRegime' in v1 workload payload.")
regime_upper = regime.upper().strip()
if regime_upper not in allowed_regimes and not any(
regime_upper == candidate
or f"COMPLIANCE_REGIME_{regime_upper}" == candidate
for candidate in allowed_regimes
):
raise ValueError(
f"Invalid complianceRegime '{regime}'. Allowed Data Boundary regimes"
" derived dynamically from Assured Workloads Frameworks Library SOT:"
f" {sorted(allowed_regimes)}"
)
if "resourceSettings" in payload:
for setting in payload.get("resourceSettings", []):
resource_id = setting.get("resourceId", "")
if str(resource_id).startswith("folders/") or str(resource_id).startswith(
"projects/"
):
raise ValueError(
f"Invalid resourceSettings: resourceId '{resource_id}'. Assured"
" Workloads v1 creates a NEW folder and does not support adopting"
" existing folders or projects. Use Assured Workloads v2"
" (resourceConfig) for brownfield adoption."
)
clean_org = org_id.replace("organizations/", "").strip()
clean_loc = location.strip() or "us-central1"
endpoint_path = (
"POST https://assuredworkloads.googleapis.com/v1/"
f"organizations/{clean_org}/locations/{clean_loc}/workloads"
)
console_url = f"https://console.cloud.google.com/compliance/assuredworkloads?organizationId={clean_org}"
return {
"apiVersion": "v1 (GA)",
"consoleUrl": console_url,
"restEndpoint": endpoint_path,
"requestBody": payload,
}
def validate_v2_workload_payload(
payload: dict[str, Any],
org_id: str,
location: str,
allowed_frameworks: set[str],
) -> dict[str, Any]:
"""Validates payload against Assured Workloads v2 preview schema."""
# 1. Validate Target Resource Config
resource_config = payload.get("resourceConfig")
if not resource_config or not isinstance(resource_config, dict):
raise ValueError(
"Missing required 'resourceConfig' object in workload payload."
)
has_target = False
if "existingFolder" in resource_config:
folder = resource_config["existingFolder"]
if not _FOLDER_RE.fullmatch(folder):
raise ValueError(
f"Invalid 'existingFolder' format: {folder}. Expected"
" 'folders/{id}'."
)
has_target = True
elif "existingProject" in resource_config:
project = resource_config["existingProject"]
if not _PROJECT_RE.fullmatch(project):
raise ValueError(f"Invalid 'existingProject' format: {project}.")
has_target = True
if not has_target:
raise ValueError(
"resourceConfig must specify 'existingFolder' or 'existingProject'."
)
# 2. Validate Framework Reference
framework_ref = payload.get("framework")
if (
not framework_ref
or not isinstance(framework_ref, dict)
or "framework" not in framework_ref
):
raise ValueError(
"Missing required 'framework.framework' resource reference in workload"
" payload."
)
framework_name = framework_ref["framework"]
framework_match = _FRAMEWORK_NAME_RE.fullmatch(framework_name)
if not framework_match:
raise ValueError(
f"Invalid framework resource path: {framework_name}. Expected"
" 'organizations/{org}/locations/{loc}/frameworks/{framework_id}'."
)
framework_id = framework_match.group(3)
if framework_id not in allowed_frameworks:
raise ValueError(
f"Unsupported framework ID '{framework_id}'. Allowed Data Boundary"
" frameworks derived dynamically from Assured Workloads Frameworks"
f" Library SOT: {sorted(allowed_frameworks)}"
)
# 3. Validate Cloud Control Configs (if provided)
control_configs = payload.get("cloudControlConfigs", [])
for idx, control in enumerate(control_configs):
mode = control.get("enforcementMode")
if mode not in VALID_ENFORCEMENT_MODES:
raise ValueError(
f"Control index {idx} has invalid enforcementMode '{mode}'. Valid"
f" modes: {VALID_ENFORCEMENT_MODES}"
)
# 4. Construct REST Endpoint URL & Google Cloud Console URL
clean_org = org_id.replace("organizations/", "").strip()
clean_loc = location.strip() or "global"
endpoint_path = (
"POST https://assuredworkloads.googleapis.com/v2/"
f"organizations/{clean_org}/locations/{clean_loc}/workloads"
)
console_url = f"https://console.cloud.google.com/compliance/assuredworkloads?organizationId={clean_org}"
return {
"apiVersion": "v2 (Preview)",
"consoleUrl": console_url,
"restEndpoint": endpoint_path,
"requestBody": payload,
}
def validate_workload_payload(
payload: dict[str, Any],
org_id: str,
location: str,
frameworks_data: list[dict[str, Any]],
) -> dict[str, Any]:
"""Dispatches validation to v1 GA or v2 Preview schema."""
allowed_frameworks, allowed_regimes = load_allowed_frameworks_and_regimes(
frameworks_data
)
# If complianceRegime is present, validate as GA v1 schema
if "complianceRegime" in payload or (
"resourceConfig" not in payload and "framework" not in payload
):
v1_loc = "us-central1" if location == "global" else location
return validate_v1_workload_payload(
payload, org_id, v1_loc, allowed_regimes
)
# Otherwise validate as v2 preview schema
return validate_v2_workload_payload(
payload, org_id, location, allowed_frameworks
)
def main() -> None:
parser = argparse.ArgumentParser(
description=(
"Validate Assured Workloads request payload against dynamic Assured"
" Workloads Frameworks Library frameworks."
)
)
parser.add_argument(
"--payload-json",
required=True,
help="Raw JSON string or path to JSON payload",
)
parser.add_argument(
"--org-id", required=True, help="Organization ID (e.g. 123456789)"
)
parser.add_argument(
"--location",
default="global",
help="Location (e.g. global, us-central1, europe-west3)",
)
parser.add_argument(
"--frameworks-file",
required=True,
help=(
"Path to Assured Workloads Frameworks Library frameworks JSON export"
" (authoritative SOT)"
),
)
args = parser.parse_args()
try:
if args.payload_json.startswith("{"):
payload = json.loads(args.payload_json)
else:
with open(args.payload_json, "r", encoding="utf-8") as f:
payload = json.load(f)
with open(args.frameworks_file, "r", encoding="utf-8") as f:
frameworks_data = json.load(f)
output = validate_workload_payload(
payload, args.org_id, args.location, frameworks_data=frameworks_data
)
print(json.dumps(output, indent=2))
except (ValueError, OSError, KeyError, TypeError) as e:
sys.stderr.write(f"VALIDATION_ERROR: {str(e)}\n")
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