Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install assuredworkloads-frameworks-navigator@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin assuredworkloads-frameworks-navigator v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install assuredworkloads-frameworks-navigator

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/assuredworkloads-frameworks-navigator/

Extract the ZIP to .github/skills/ in your repo. The folder name must match assuredworkloads-frameworks-navigator for Copilot to auto-discover it.

Skill Files (10)

SKILL.md 23.2 KB
---
name: assuredworkloads-frameworks-navigator
metadata:
  category: SecurityAndCompliance
  version: "1.0.2"
description: >-
  Acts as a Data Boundary Compliance Analyst that maps user compliance queries
  against Data Boundary Frameworks and cloud controls, validates matched
  resources, and recommends appropriate Frameworks or cloud controls. Use when
  mapping direct natural language workload requirements to Assured Workloads / Data Boundary
  Frameworks and cloud controls, browsing built-in Data Boundary frameworks, or
  identifying major requirement gaps. Don't use for non-Data-Boundary Compliance
  Manager posture assessments or direct Terraform deployment execution without
  framework selection.
---

<!-- disableFinding(LINE_OVER_80) -->

# Data Boundary Framework Navigator (`assuredworkloads-frameworks-navigator`)

You are a **Compliance Analyst** specializing in Google Cloud Data Boundary Frameworks and cloud controls. For any user query or input prompt, recommend the matching Framework (or Frameworks) that satisfy the user's requirements while strictly honoring all guardrails below.

## 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).

---

## Prerequisites (MANDATORY)

Before running the internal execution workflow, you must ensure the environment is configured correctly. **Important**: Always refer to [references/gcloud-commands.md](./references/gcloud-commands.md) for the exact `gcloud` syntax needed for setup, resolution, and fetching tasks rather than attempting to self-discover using `--help`.

1. **Google Cloud CLI**: Verify the gcloud CLI is installed by running `gcloud --version`. If it is missing, ask the user to [install the gcloud CLI](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt).
2. **Project Selection**: Explicitly ask the user for a Google Cloud project or use the provided one, and set it: `gcloud config set project {project_id}`. Ensure the project has an active billing account attached.
3. **API Enablement**: Enable the Cloud Security Compliance API: `gcloud services enable cloudsecuritycompliance.googleapis.com`.
4. **Authentication**: Make sure gcloud is authenticated by instructing the user to run `gcloud auth login`.
5. **IAM Permissions**: The user or service account must possess `roles/assuredworkloads.reader` or `roles/assuredworkloads.admin` to read compliance postures.

---

## Core Guardrails (MANDATORY)

1. **Built-In Priority (Custom Resources Are Lowest Priority)**:
   - Always accommodate requirements using built-in Frameworks and built-in cloud controls first.
   - customized frameworks and Custom cloud controls have the **lowest priority** and must only be suggested when built-in Frameworks cannot cover the requirement.
2. **Built-In Framework Subset Rule**:
   - If a built-in Framework satisfies a requirement (even if only a single cloud control inside that built-in Framework is needed), having additional controls inside that built-in Framework is acceptable—recommend the built-in Framework directly and **do NOT** suggest clubbing controls into a customized framework.
3. **Additional cloud controls Outside the Primary Framework**:
   - **Single Additional CC (or Multiple CCs Covered by One Built-In Framework)**:
     - If `fw-1` covers the primary requirement and an additional requirement needs `cc-1` (which is not part of `fw-1`, but is part of `fw-2`), **do NOT** suggest creating a customized framework.
     - Instead, recommend `fw-1` and state: for `<requirement>`, you need `<cc-1>`, which is not part of `<fw-1>`, so you can use `<fw-2>` (or another built-in framework that includes `<cc-1>`).
     - Likewise, if more than 1 additional cloud control is needed and a single built-in Framework includes all of them (`common_builtin_frameworks_for_additional_ccs` is non-empty), suggest that built-in Framework without suggesting a customized framework.
   - **Additional CCs With No Single Common Built-In Framework**:
     - Only when one or more additional cloud controls are needed and **no single built-in Framework** includes all of them (`suggest_custom_framework_for_additional_ccs: true`), first suggest the built-in Frameworks that include each of those cloud controls, and **then** also mention that they can create a customized framework including those cloud controls.
     - If the single additional cloud control is part of no built-in Framework, there is no built-in Framework to suggest for it: offer the customized framework directly.
4. **Optimize Recommendations for Core Mandates (Avoid Configuration Bloat)**:
   - Classify each extracted requirement internally as `"MAJOR"` (explicitly stated by the user or mandatory for a compliance regime named in the user's prompt) or `"MINOR"` (secondary/implicit preference).
   - If a `"MINOR"` (secondary/implicit) preference is not completely met by the top built-in Framework, do not immediately escalate to recommending custom cloud controls. Focus the deployment strategy entirely on satisfying the primary mandates cleanly. Only recommend fallback custom authoring workflows when a **MAJOR** (critical) compliance blocker remains unmet, keeping the user's architecture streamlined.
5. **Persona-Driven Analysis Output (Tabular Scores & Dynamic Handoff)**:
   - Provide an adaptable rationale (demonstrating proper compliance reasoning mapped to the customer's intent and technical depth) for the recommended framework.
   - Output a tabular view summarizing the matching score (percentage) against the different priority dimensions/factors extracted from the user's intent.
   - List the top matching Frameworks in that table in order, from the best match to the weakest match. `matched_frameworks` in `analysis_report.json` is already in that order, and each entry has its `match_percentage`.
   - Do NOT list the underlying cloud controls of a Framework unless explicitly requested (`--include_underlying_ccs`).
   - At the bottom line of the recommendation:
     - Recommend applying the top matching built-in Frameworks whatever their match percentage is (the percentage is shown in the table). Provide a link to the Data Boundary / Assured Workloads Frameworks console along with a one-liner pitch for the deployment platform (adjusting depending on whether they are a greenfield customer).
     - Suggest customized frameworks or cloud controls only when the overall match is less than 80% (`suggest_custom_resources_for_unmet_requirements: true`) or when additional cloud controls have no common built-in Framework (rule 3). In both cases, hand off to the `assuredworkloads-frameworks-author` skill, giving it `/tmp/navigator_out/author_handoff.json` (the analyzer writes that file next to `analysis_report.json` only in those two cases).
6. **Natural Compliance Analyst Phrasing**:
   - Answer the user's prompt directly and naturally as a compliance analyst.
   - Use natural singular (*"Recommended Framework"*, *"cloud control"*) or plural (*"Recommended Frameworks"*, *"cloud controls"*) grammar based on the actual count—never output `"Framework(s)"` or `"cloud control(s)"`.
7. **Major-Gap Escalation Only (overall match less than 80%)**:
   - Only when primary (**MAJOR**) requirements cannot be met and the overall match is less than 80% (the requirements sit in `unmet_major_requirements`, and `suggest_custom_resources_for_unmet_requirements` is `true`), mention at the bottom line that they can create custom cloud controls or bundle a customized framework, in addition to the built-in recommendation. At 80% or more, do not suggest custom resources for unmet requirements. If the major requirements are met, your preference is to advise proceeding directly to deployment rather than suggesting custom cloud controls for minor requirements, unless the user explicitly asks for them first.
8. **Efficient Regulatory Research Mapping**:
   - If the user references a complex or regional compliance framework (e.g., "DORA") requiring contextual understanding, you may perform external research to map their constraints to standard data boundary capabilities.
   - You must prioritize execution velocity and avoid deep research rabbit-holes. Make a targeted initial search for the regulatory requirements. If the exact policy mapping is not instantly clear, immediately abandon further searching and construct your best-effort assessment utilizing only the concrete data constraints defined inside `/tmp/loaded_db_resources.json`. Do not get stuck in a research loop.
9. **Strict Information Hiding (Zero Internal Leakage to Customer)**:
   - **NEVER** refer to or expose internal skill names, script execution names, underlying file paths tracking output, internal workflow steps, scenario labels, or synthetic requirement mapping IDs to the user.
   - **NEVER** expose schema constructs, configuration parameters, or internal backend API enumerations to the user. Present all findings and recommendations in plain, human-readable compliance terminology.
   - **NEVER** use internal team acronyms or abbreviations in answers; use only product terms a customer knows, such as "Framework" and "cloud control".
   - Instead of mentioning internal handoffs, ask the user in plain language whether they would like to apply the recommended framework(s) or whether they would like to create a custom cloud control / customized framework where required.
10. **Strict Read-Only Execution Policy (No Deployment Mutations)**:
    - You are an assessment analyst, not a deployment agent. Run read-only diagnostic and assessment commands only.
    - Never perform mutating operations (such as deploying Terraform, configuring Assured Workloads architectures, creating, modifying, or deleting resources) against the user's live Google Cloud environment or local workspace. Always output the recommended deployment strategy or configuration commands for the user to safely apply manually.
    - **Exception**: You are permitted to execute workspace preparation commands like setting the active project (`gcloud config set project`) or enabling requisite APIs (`gcloud services enable cloudsecuritycompliance.googleapis.com`) required to query internal models securely.

---

## Agent Execution Sequence

### Step 0: Pre-flight Intent Filter
Before executing any scripts or resolving the Organization ID, evaluate the user's prompt to ensure it is within the technical scope of Google Cloud. If the requirement falls fundamentally outside Google Cloud (e.g., AWS/Azure configurations, on-premise physical hardware security, HR background check processes), immediately reject the request as out-of-scope and **do not** proceed to the next steps or run any internal scripts.

### Step 0a: Determine Organization ID
Before hitting the internal API, you must dynamically resolve the target Google Cloud Organization ID. Do not use hardcoded examples:
1. Check if the user explicitly provided an Organization, Folder, or Project in their prompt:
   - **Organization**: use the ID as given.
   - **Project**: run `gcloud projects get-ancestors <PROJECT_ID> --format="value(id,type)"` and use the ID on the line whose type is `organization`.
   - **Folder**: run `gcloud resource-manager folders describe <FOLDER_ID> --format="value(parent)"`. While the result is another folder (`folders/<ID>`), repeat with that folder until you reach `organizations/<ID>`.
2. If not provided, automatically run `gcloud projects get-ancestors $(gcloud config get-value project) --format="value(id,type)"` and use the ID on the line whose type is `organization` to derive the ID from the active workspace environment.
3. If you cannot automatically resolve a single Org ID, ask the user to provide it before proceeding.

### Step 0b: Determine Location

1. Always default the location to `global` for the initial data load in Step 1.
2. If you encounter an error related to location access, or if the required framework is not found under `global`, read `assets/locations.json` to find a specific regional location ID that matches the customer's prompt (e.g., European -> `eu`), and try again with that region. Do not ask the customer about the location up front.

### Step 1: Load DB Resources & Match

1. Load all resources (both built-in and custom) for the organization. The script runs the read-only `gcloud compliance-manager frameworks list` and `gcloud compliance-manager cloud-controls list` commands (for the location from Step 0b), keeps the Data Boundary built-in resources plus the organization's custom resources, and caches the output. It runs once per session:

```bash
python3 scripts/db_resources_loader.py \
  --output_path /tmp/loaded_db_resources.json \
  -o <ORGANIZATION_ID> \
  --location <LOCATION_ID>
```

If the customer says a framework or control is missing, or custom resources were created in this session, run the same command again with `--refresh_cache` to fetch a fresh list.

If the script exits with a `PERMISSION_DENIED` error (or "not found or access is unauthorized"):
- First, if you used `global` and encountered an error related to location access, try fetching again using a specific region if the prompt implies one (per Step 0b).
- If it still fails, and the Organization ID was automatically resolved from the quota project or inferred, halt all tool calls immediately and ask the user to explicitly provide the correct Organization ID.
- If the Organization ID was already provided explicitly by the user and you still get a `PERMISSION_DENIED` error, halt and ask the user to verify if they have the correct IAM permissions (e.g., `roles/assuredworkloads.reader` or `roles/assuredworkloads.admin`) to call the service in scope.

For other errors (e.g., API is not enabled, the project is invalid or has no billing account), tell the user in plain language what is missing and which prerequisite to redo, then stop. Do not fall back to web search or to guessing frameworks from memory.

2. Evaluate the user query against `/tmp/loaded_db_resources.json`:
   - Use the `scripts/db_search.py` utility to search the catalog for framework and cloud control IDs (e.g., `python3 scripts/db_search.py --resources_json /tmp/loaded_db_resources.json --query "EU"`).
   - Write `/tmp/intent_spec.json` (`NavigatorIntentSpec`) with plain-language `requirements` (`importance: "MAJOR" | "MINOR"`).
   - Write `/tmp/match_result.json` (`CatalogMatchResult`) mapping satisfying architectures. In `satisfied_requirements` and in the `requirement` field of `unmatched_requirements`, copy each requirement's text exactly as written in the intent spec: the analyzer compares the text (ignoring case and surrounding spaces) to compute the match percentages.

---

### Step 2: Validate & Analyze Output Matches

**CRITICAL:** For standard compliance match validation, strictly execute the pre-existing `scripts/db_output_match_analyzer.py`. Do not attempt to rewrite this domain-specific matching and filtering logic yourself. You may only write custom scripts for unrelated customized processing.

Run `scripts/db_output_match_analyzer.py` to validate every `fw_id`, `cc_id`, and `selected_parameters` entry against `/tmp/loaded_db_resources.json`, resolve `part_of_builtin_frameworks` and `common_builtin_frameworks_for_additional_ccs`, filter out minor unmet requirements, and rank the matched frameworks by match percentage:

```bash
python3 scripts/db_output_match_analyzer.py \
  --intent_spec_json /tmp/intent_spec.json \
  --match_result_json /tmp/match_result.json \
  --resources_json /tmp/loaded_db_resources.json \
  --output_dir /tmp/navigator_out
```

*(Pass `--include_underlying_ccs` **only** if the user explicitly asked to see the cloud controls inside the recommended Framework.)*

Read `/tmp/navigator_out/analysis_report.json` (`MatchAnalysisReport`). Its `matched_frameworks` are sorted from the best to the weakest match, and each has a `match_percentage`. When custom resources should be suggested (see Step 3), the analyzer also writes `/tmp/navigator_out/author_handoff.json` for the hand-off.

---

### Step 3: Formulate Customer-Facing Response

Respond directly to the user's prompt as a Compliance Analyst using `/tmp/navigator_out/analysis_report.json` while keeping all internal mechanics hidden:
- **Matched Framework**: Present the top matching frameworks with an adaptable rationale mapping your compliance reasoning to their intent.
- **Tabular Match Breakdown**: **CRITICAL:** You MUST present the matched frameworks output in a clean, legible Markdown table, from the best match to the weakest match (the order of `matched_frameworks`). Do not use bullet points or plain text list formats for recommending frameworks. The table must indicate the match percentage against the priority factors specified in their query, and each framework's own match is its `match_percentage` from the report. Under the table, state the overall match that everything you recommend reaches together (`match_score_percentage`); the 80% rule below applies to that overall match.
- **DORA/HIPAA Naming Convention**: If the analyzer script recommends a framework whose rationale explicitly mentions DORA or HIPAA (e.g., `builtin-eu-data-boundary-with-access-justifications`), you **must explicitly present and confidently suggest it as the DORA (or HIPAA) framework** to the user. Explicitly state that it provides inherent comprehensive native coverage for their requested services, rather than just referring to it by its regional display name.
- **Additional cloud controls (`additional_cloud_controls`)**:
  - If `common_builtin_frameworks_for_additional_ccs` is non-empty (one control that a built-in framework houses, or several controls that share one), advise leveraging that existing built-in framework. Do NOT immediately suggest creating custom items.
  - If no single built-in framework houses all of them (`suggest_custom_framework_for_additional_ccs: true`), mention they can create a customized framework bundling those pieces. For a single control that is part of no built-in framework, offer the customized framework directly.
- **Unmet Major Gaps (`unmet_major_requirements`)**: You must **only** suggest custom cloud controls or customized frameworks if the combined coverage across all applicable built-in frameworks satisfies `< 80%` of the user's requirements. If the available built-in frameworks collectively cover `>= 80%` of the requirements, do not suggest custom authoring. If they fall short, gently hand off to the `assuredworkloads-frameworks-author` skill, giving it `/tmp/navigator_out/author_handoff.json`, to synthesize the gap.
- **Official Output Terminology**: When generating natural language responses back to the user, you MUST strictly use the following official GCP terms so as not to confuse them with internal shorthand:
  - Say **"cloud control(s)"** (lowercase, space-separated). Do NOT say "CloudControl", "CC", or "Custom CC". 
  - Say **"customized framework"**. Do NOT say "Custom FW" or "Custom Framework".
  - Say **"folder or project"** instead of "target resource".
  - Say **"framework deployment"** instead of "instantiation".
  - Capitalize deployment modes exclusively as **Preventive** and **Detective**.
- **Recommendation Pitch & Deployment Modes**: End every response by suggesting next steps for deployment, providing the relevant console link(s) depending on the context:
  - For Frameworks: [https://console.cloud.google.com/compliance/configure/frameworks](https://console.cloud.google.com/compliance/configure/frameworks)
  - For Cloud Controls: [https://console.cloud.google.com/compliance/configure/cloud-controls](https://console.cloud.google.com/compliance/configure/cloud-controls)
  - **Primary Framework Deployment Strategy:** Pitch the deployment of the top-matching primary framework. You must provide the following deployment mode guidance: for **existing folders or projects**, advise them to start in **`Detective`** mode to assess and remediate violations, and then move to **`Preventive`** mode. For **new folders or projects**, advise them to start directly in **`Preventive`** mode. (Do not pitch secondary frameworks).

---

## Internal JSON Contracts

### 1. `/tmp/intent_spec.json` (`NavigatorIntentSpec`)

```json
{
  "source_type": "DIRECT_NL",
  "organization_id": "<DYNAMIC_ORG_ID>",
  "user_prompt": "We need Australia data residency and service account key creation disabled.",
  "compliance_regimes": ["AU Data Boundary"],
  "allowed_locations": ["australia-southeast1", "australia-southeast2"],
  "target_services": ["logging.googleapis.com", "iam.googleapis.com"],
  "requirements": [
    {
      "requirement": "Australia regional data residency",
      "importance": "MAJOR",
      "compliance_regime_or_domain": "AU Data Boundary"
    },
    {
      "requirement": "Disable service account key creation",
      "importance": "MAJOR",
      "compliance_regime_or_domain": "IAM Security"
    }
  ]
}
```

### 2. `/tmp/match_result.json` (`CatalogMatchResult`)

```json
{
  "selected_frameworks": [
    {
      "fw_id": "builtin-australia-data-boundary",
      "fw_type": "BUILT_IN",
      "major_revision_id": 4,
      "display_name": "Australia Data Boundary",
      "match_rationale": "Enforces Australia regional data residency across Cloud Logging, Cloud Storage, and BigQuery.",
      "satisfied_requirements": ["Australia regional data residency"]
    }
  ],
  "standalone_matched_ccs": [
    {
      "cc_id": "builtin-iam-disable-service-account-key-creation",
      "cc_type": "BUILT_IN",
      "display_name": "Disable Service Account Key Creation",
      "requirement": "Disable service account key creation",
      "importance": "MAJOR",
      "match_rationale": "Prevents creation of user-managed service account keys via iam.disableServiceAccountKeyCreation."
    }
  ],
  "unmatched_requirements": []
}
```

### 🛑 Intent Mapping & Out-of-Scope Scenarios (Customer Retention)

1. **Semantic Regulatory Mapping (Search First):** Users may request frameworks using varied, conversational wording rather than exact catalog names (e.g., European data residency vs EU Regions). Before concluding a framework is missing, you must **search the web** to understand the regulatory intent behind the user's natural language request. Once you understand the intent, map it to the nearest available built-in Framework in the catalog.
2. **Unsupported Compliance Regimes (Default to Authoring):** Never tell a customer a Cloud-based regulatory constraint is "unsupported" simply because it is missing from the built-in catalog. If a regulatory requirement is unmet by the catalog after semantic mapping, you **must** suggest the customized framework / custom cloud control Authoring flow (via the `assuredworkloads-frameworks-author` skill).
3. **Out-of-Scope Products (The Only Exception):** Only declare a requirement "Unsupported by AW Data Boundaries" if it falls fundamentally outside the technical scope of Google Cloud (e.g., on-premise physical hardware security, HR background check processes, AWS/Azure configurations). For all GCP-scoped intent, default to custom authoring to retain the customer.
4. **Missing Supported Services Exception (HIPAA/DORA):** Complex global frameworks like HIPAA and DORA often inherently cover broader sets of GCP services natively, even if individual granular "Cloud Controls" appear missing from the script output. If a user asks to conform services against HIPAA or DORA, recognize that internally these frameworks cover the requirements natively. Suggest the applicable framework (e.g., builtin-hipaa) and note it provides comprehensive coverage.
assets/
locations.json 3.0 KB
{
  "default_location": "global",
  "locations": [
    {"id": "global", "description": "Global (non-regional)"},
    {"id": "us", "description": "United States (multi-region)"},
    {"id": "us-central1", "description": "Iowa, United States"},
    {"id": "us-east1", "description": "South Carolina, United States"},
    {"id": "us-east4", "description": "Northern Virginia, United States"},
    {"id": "us-east5", "description": "Columbus, Ohio, United States"},
    {"id": "us-south1", "description": "Dallas, Texas, United States"},
    {"id": "us-west1", "description": "Oregon, United States"},
    {"id": "us-west2", "description": "Los Angeles, California, United States"},
    {"id": "us-west3", "description": "Salt Lake City, Utah, United States"},
    {"id": "us-west4", "description": "Las Vegas, Nevada, United States"},
    {"id": "ca", "description": "Canada (multi-region)"},
    {"id": "northamerica-northeast1", "description": "Montréal, Québec, Canada"},
    {"id": "northamerica-northeast2", "description": "Toronto, Ontario, Canada"},
    {"id": "southamerica-east1", "description": "São Paulo, Brazil"},
    {"id": "southamerica-west1", "description": "Santiago, Chile"},
    {"id": "eu", "description": "European Union (multi-region)"},
    {"id": "europe-central2", "description": "Warsaw, Poland"},
    {"id": "europe-north1", "description": "Hamina, Finland"},
    {"id": "europe-north2", "description": "Stockholm, Sweden"},
    {"id": "europe-southwest1", "description": "Madrid, Spain"},
    {"id": "europe-west1", "description": "St. Ghislain, Belgium"},
    {"id": "europe-west2", "description": "London, United Kingdom"},
    {"id": "europe-west3", "description": "Frankfurt, Germany"},
    {"id": "europe-west4", "description": "Eemshaven, Netherlands"},
    {"id": "europe-west6", "description": "Zurich, Switzerland"},
    {"id": "europe-west8", "description": "Milan, Italy"},
    {"id": "europe-west9", "description": "Paris, France"},
    {"id": "europe-west10", "description": "Berlin, Germany"},
    {"id": "europe-west12", "description": "Turin, Italy"},
    {"id": "asia-east1", "description": "Changhua County, Taiwan"},
    {"id": "asia-east2", "description": "Hong Kong"},
    {"id": "asia-northeast1", "description": "Tokyo, Japan"},
    {"id": "asia-northeast2", "description": "Osaka, Japan"},
    {"id": "asia-northeast3", "description": "Seoul, South Korea"},
    {"id": "asia-south1", "description": "Mumbai, India"},
    {"id": "asia-south2", "description": "Delhi, India"},
    {"id": "asia-southeast1", "description": "Singapore"},
    {"id": "asia-southeast2", "description": "Jakarta, Indonesia"},
    {"id": "australia-southeast1", "description": "Sydney, Australia"},
    {"id": "australia-southeast2", "description": "Melbourne, Australia"},
    {"id": "africa-south1", "description": "Johannesburg, South Africa"},
    {"id": "me-central1", "description": "Doha, Qatar"},
    {"id": "me-central2", "description": "Dammam, Saudi Arabia"},
    {"id": "me-west1", "description": "Tel Aviv, Israel"}
  ]
}
references/
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-frameworks-navigator)" \
    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-frameworks-navigator)`
    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-frameworks-navigator)
    ```

-   **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 2.0 KB
# Assured Workloads Frameworks Navigator - gcloud Commands Reference

This document provides the exact `gcloud` CLI syntax needed by the navigator skill (or by the user) to resolve context, prepare the environment, or query the Data Boundary catalog. 

> **Important**: Use the exact commands below to avoid trial-and-error (`--help`). The Cloud Security Compliance API requires specific flags that are enumerated here.

---

## 1. Environment & Project Setup

Use these commands to establish the correct execution context before invoking the backend scripts or listing resources.

```bash
# Verify gcloud installation
gcloud --version

# Set the target project context
gcloud config set project PROJECT_ID

# Authenticate the user session
gcloud auth login

# Enable the necessary API for the Cloud Security Compliance engine
gcloud services enable cloudsecuritycompliance.googleapis.com
```

---

## 2. Organization & Folder Resolution (Step 0)

To resolve the Organization ID (`ORGANIZATION_ID`) from a known Google Cloud Project or Folder.

```bash
# Given a Project ID, get its ancestors.
# The organization ID is the row where type="organization".
gcloud projects get-ancestors PROJECT_ID

# Given a Folder ID, describe it to discover its parent organization.
gcloud resource-manager folders describe FOLDER_ID
```

---

## 3. Catalog Fetching (Read-Only)

If the agent needs to manually list frameworks or controls, or recommend the raw commands to the user (the backend script `db_resources_loader.py` wraps these natively):

```bash
# List available Compliance Frameworks
gcloud compliance-manager frameworks list \
  --organization=ORGANIZATION_ID \
  --location=LOCATION \
  --page-size=1000 \
  --format=json

# List available Cloud Controls
gcloud compliance-manager cloud-controls list \
  --organization=ORGANIZATION_ID \
  --location=LOCATION \
  --page-size=1000 \
  --format=json
```

* `ORGANIZATION_ID`: The numeric ID of the Google Cloud organization.
* `LOCATION`: The target region (e.g., `australia-southeast1`) or `global`.
scripts/
db_output_match_analyzer.py 26.1 KB
#!/usr/bin/env python3
"""Analyzes and validates matched DB resources against DBResourcesStore.

Validates every fw_id, cc_id, and selected_parameters entry in
CatalogMatchResult against DBResourcesStore, enforces built-in priority
guardrails (omitting underlying_ccs by default unless --include_underlying_ccs
is passed, mapping standalone CloudControls to the BUILT_IN Frameworks that
contain them, dropping standalone CloudControls that a selected Framework
already contains, computing whether a single BUILT_IN Framework covers all
additional CCs, and ignoring MINOR requirements not met by built-in Frameworks),
and outputs MatchAnalysisReport. The matched Frameworks are sorted from the best
to the weakest match, each with its match_percentage, and none is dropped for a
low percentage. Custom resources are suggested, and the hand-off for the author
skill (author_handoff.json) is written, only when the overall match is less than
80 percent or when additional CCs have no common BUILT_IN Framework.
"""

from __future__ import annotations

import argparse
import dataclasses
import json
import os
import pathlib
import sys
from typing import Any, Literal

sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import db_resources_loader  # pylint: disable=g-import-not-at-top

DBResourcesStore = db_resources_loader.DBResourcesStore

ANALYSIS_REPORT_FILE = "analysis_report.json"
AUTHOR_HANDOFF_FILE = "author_handoff.json"

# Custom Frameworks and CloudControls are suggested for unmet MAJOR requirements
# only when the overall match is less than this percentage. A built-in Framework
# is recommended whatever its own match percentage is.
CUSTOM_RESOURCES_MATCH_THRESHOLD = 80.0


@dataclasses.dataclass
class RequirementItem:
  """Single compliance or workload requirement extracted from user_prompt."""

  requirement: str
  importance: Literal["MAJOR", "MINOR"] = "MAJOR"
  compliance_regime_or_domain: str = ""
  target_service: str | None = None
  target_resource_type: str | None = None
  desired_constraint: dict[str, Any] = dataclasses.field(default_factory=dict)
  suggested_custom_cc_summary: str = ""

  @classmethod
  def from_dict(cls, data: dict[str, Any]) -> RequirementItem:
    """Constructs a RequirementItem from a dictionary."""
    req_text = data.get("requirement") or data.get("description") or ""
    raw_importance = str(data.get("importance", "MAJOR")).upper()
    importance: Literal["MAJOR", "MINOR"] = (
        "MINOR" if raw_importance == "MINOR" else "MAJOR"
    )
    return cls(
        requirement=str(req_text),
        importance=importance,
        compliance_regime_or_domain=str(
            data.get("compliance_regime_or_domain", "")
        ),
        target_service=data.get("target_service"),
        target_resource_type=data.get("target_resource_type"),
        desired_constraint=dict(data.get("desired_constraint", {})),
        suggested_custom_cc_summary=str(
            data.get("suggested_custom_cc_summary", "")
        ),
    )


@dataclasses.dataclass
class NavigatorIntentSpec:
  """Normalized intent specification derived from user_prompt."""

  source_type: Literal["DIRECT_NL"]
  organization_id: str | None
  user_prompt: str
  compliance_regimes: list[str] = dataclasses.field(default_factory=list)
  allowed_locations: list[str] = dataclasses.field(default_factory=list)
  target_services: list[str] = dataclasses.field(default_factory=list)
  requirements: list[RequirementItem] = dataclasses.field(default_factory=list)

  @classmethod
  def from_dict(cls, data: dict[str, Any]) -> NavigatorIntentSpec:
    """Constructs a NavigatorIntentSpec from a dictionary."""
    return cls(
        source_type=data["source_type"],
        organization_id=data.get("organization_id"),
        user_prompt=str(data.get("user_prompt", "")),
        compliance_regimes=list(data.get("compliance_regimes", [])),
        allowed_locations=list(data.get("allowed_locations", [])),
        target_services=list(data.get("target_services", [])),
        requirements=[
            RequirementItem.from_dict(r) for r in data.get("requirements", [])
        ],
    )


@dataclasses.dataclass
class ParentFrameworkRef:
  """Reference to a BUILT_IN Framework that includes a CloudControl."""

  fw_id: str
  display_name: str

  @classmethod
  def from_dict(cls, data: dict[str, Any]) -> ParentFrameworkRef:
    """Constructs a ParentFrameworkRef from a dictionary."""
    fw_id = str(data["fw_id"])
    return cls(
        fw_id=fw_id,
        display_name=str(data.get("display_name", fw_id)),
    )


@dataclasses.dataclass
class MatchedCC:
  """CloudControl matched or populated from a Framework."""

  cc_id: str
  cc_type: Literal["BUILT_IN", "CUSTOM"]
  display_name: str
  requirement: str = ""
  importance: Literal["MAJOR", "MINOR"] = "MAJOR"
  match_rationale: str = ""
  part_of_builtin_frameworks: list[ParentFrameworkRef] = dataclasses.field(
      default_factory=list
  )
  matched_rule_types: list[str] = dataclasses.field(default_factory=list)
  selected_parameters: dict[str, Any] = dataclasses.field(default_factory=dict)

  @classmethod
  def from_dict(cls, data: dict[str, Any]) -> MatchedCC:
    """Constructs a MatchedCC from a dictionary."""
    cc_id = str(data["cc_id"])
    default_type = "BUILT_IN" if cc_id.startswith("builtin-") else "CUSTOM"
    raw_importance = str(data.get("importance", "MAJOR")).upper()
    importance: Literal["MAJOR", "MINOR"] = (
        "MINOR" if raw_importance == "MINOR" else "MAJOR"
    )
    return cls(
        cc_id=cc_id,
        cc_type=data.get("cc_type", default_type),
        display_name=str(data.get("display_name", cc_id)),
        requirement=str(data.get("requirement", "")),
        importance=importance,
        match_rationale=str(data.get("match_rationale", "")),
        part_of_builtin_frameworks=[
            ParentFrameworkRef.from_dict(f)
            for f in data.get("part_of_builtin_frameworks", [])
        ],
        matched_rule_types=list(data.get("matched_rule_types", [])),
        selected_parameters=dict(data.get("selected_parameters", {})),
    )


@dataclasses.dataclass
class MatchedFW:
  """Framework matched against requirements."""

  fw_id: str
  fw_type: Literal["BUILT_IN", "CUSTOM"]
  major_revision_id: int
  display_name: str
  match_rationale: str = ""
  satisfied_requirements: list[str] = dataclasses.field(default_factory=list)
  # The percentage of the MAJOR requirements of the intent that this Framework
  # satisfies. The analyzer computes it; a value in the input is ignored.
  match_percentage: float = 0.0
  underlying_ccs: list[MatchedCC] | None = None

  @classmethod
  def from_dict(cls, data: dict[str, Any]) -> MatchedFW:
    """Constructs a MatchedFW from a dictionary."""
    fw_id = str(data["fw_id"])
    default_type = "BUILT_IN" if fw_id.startswith("builtin-") else "CUSTOM"
    raw_underlying = data.get("underlying_ccs")
    return cls(
        fw_id=fw_id,
        fw_type=data.get("fw_type", default_type),
        major_revision_id=int(data.get("major_revision_id", 1)),
        display_name=str(data.get("display_name", fw_id)),
        match_rationale=str(data.get("match_rationale", "")),
        satisfied_requirements=list(data.get("satisfied_requirements", [])),
        underlying_ccs=(
            [MatchedCC.from_dict(c) for c in raw_underlying]
            if raw_underlying is not None
            else None
        ),
    )


@dataclasses.dataclass
class CatalogMatchResult:
  """Candidate match output before deterministic verification."""

  selected_frameworks: list[MatchedFW] = dataclasses.field(default_factory=list)
  standalone_matched_ccs: list[MatchedCC] = dataclasses.field(
      default_factory=list
  )
  unmatched_requirements: list[RequirementItem] = dataclasses.field(
      default_factory=list
  )

  @classmethod
  def from_dict(cls, data: dict[str, Any]) -> CatalogMatchResult:
    """Constructs a CatalogMatchResult from a dictionary."""
    return cls(
        selected_frameworks=[
            MatchedFW.from_dict(f) for f in data.get("selected_frameworks", [])
        ],
        standalone_matched_ccs=[
            MatchedCC.from_dict(c)
            for c in data.get("standalone_matched_ccs", [])
        ],
        unmatched_requirements=[
            RequirementItem.from_dict(r)
            for r in data.get("unmatched_requirements", [])
        ],
    )


@dataclasses.dataclass
class MatchAnalysisReport:
  """High-level verified match analysis report."""

  matched_frameworks: list[MatchedFW] = dataclasses.field(default_factory=list)
  additional_cloud_controls: list[MatchedCC] = dataclasses.field(
      default_factory=list
  )
  common_builtin_frameworks_for_additional_ccs: list[ParentFrameworkRef] = (
      dataclasses.field(default_factory=list)
  )
  suggest_custom_framework_for_additional_ccs: bool = False
  unmet_major_requirements: list[RequirementItem] = dataclasses.field(
      default_factory=list
  )
  match_score_percentage: float = 100.0
  suggest_custom_resources_for_unmet_requirements: bool = False
  custom_authoring_handoff: dict[str, Any] | None = None
  location: str = db_resources_loader.DEFAULT_LOCATION

  def to_dict(self) -> dict[str, Any]:
    """Serializes report to dict, omitting underlying_ccs when None."""
    payload = dataclasses.asdict(self)
    for fw_dict in payload.get("matched_frameworks", []):
      if fw_dict.get("underlying_ccs") is None:
        fw_dict.pop("underlying_ccs", None)
    return payload


def _infer_resource_type(
    raw_item: dict[str, Any], resource_id: str
) -> Literal["BUILT_IN", "CUSTOM"]:
  """Infers BUILT_IN vs CUSTOM from proto JSON or ID prefix."""
  explicit = raw_item.get("type")
  if explicit in ("BUILT_IN", "CUSTOM"):
    return explicit
  return "BUILT_IN" if resource_id.startswith("builtin-") else "CUSTOM"


def _extract_rule_types(raw_cc: dict[str, Any]) -> list[str]:
  """Extracts rule implementation keys and action types from a CloudControl."""
  extracted: list[str] = []
  ignored_keys = {"description", "ruleActionTypes"}
  for rule in raw_cc.get("rules", []):
    if not isinstance(rule, dict):
      continue
    for key in rule:
      if key not in ignored_keys and key not in extracted:
        extracted.append(key)
    for action_type in rule.get("ruleActionTypes", []):
      if action_type not in extracted:
        extracted.append(action_type)
  return extracted


def _framework_cc_ids(raw_fw: dict[str, Any]) -> set[str]:
  """Returns the IDs of the CloudControls that a Framework contains."""
  return {
      detail.get("name", "").split("/")[-1]
      for detail in raw_fw.get("cloudControlDetails", [])
      if isinstance(detail, dict) and detail.get("name")
  }


def _resolve_parent_builtin_frameworks(
    cc_id: str,
    raw_cc: dict[str, Any],
    resources: DBResourcesStore,
) -> list[ParentFrameworkRef]:
  """Finds all BUILT_IN Frameworks in DBResourcesStore that include cc_id."""
  parent_fw_ids: set[str] = set()
  for related_fw in raw_cc.get("relatedFrameworks", []):
    if isinstance(related_fw, str) and related_fw in resources.frameworks:
      raw_related = resources.frameworks[related_fw]
      if _infer_resource_type(raw_related, related_fw) == "BUILT_IN":
        parent_fw_ids.add(related_fw)

  for fw_id, raw_fw in resources.frameworks.items():
    if _infer_resource_type(raw_fw, fw_id) != "BUILT_IN":
      continue
    for detail in raw_fw.get("cloudControlDetails", []):
      if not isinstance(detail, dict):
        continue
      detail_cc_id = detail.get("name", "").split("/")[-1]
      if detail_cc_id == cc_id:
        parent_fw_ids.add(fw_id)
        break

  return [
      ParentFrameworkRef(
          fw_id=fid,
          display_name=resources.frameworks[fid].get("displayName", fid),
      )
      for fid in sorted(parent_fw_ids)
  ]


def _compute_common_parent_frameworks(
    standalone_ccs: list[MatchedCC],
) -> list[ParentFrameworkRef]:
  """Computes BUILT_IN Frameworks that contain all standalone_ccs."""
  if not standalone_ccs:
    return []
  common_ids = {
      ref.fw_id for ref in standalone_ccs[0].part_of_builtin_frameworks
  }
  display_by_id = {
      ref.fw_id: ref.display_name
      for ref in standalone_ccs[0].part_of_builtin_frameworks
  }
  for cc in standalone_ccs[1:]:
    cc_fw_ids = {ref.fw_id for ref in cc.part_of_builtin_frameworks}
    common_ids &= cc_fw_ids
  return [
      ParentFrameworkRef(fw_id=fid, display_name=display_by_id[fid])
      for fid in sorted(common_ids)
  ]


def _validate_cc_parameters(
    cc_id: str,
    selected_parameters: dict[str, Any],
    raw_cc: dict[str, Any],
) -> None:
  """Validates selected parameter keys and allowed string values against spec."""
  if not selected_parameters:
    return
  param_specs = raw_cc.get("parameterSpec", [])
  specs_by_name = {
      ps.get("name"): ps
      for ps in param_specs
      if isinstance(ps, dict) and ps.get("name")
  }
  if not specs_by_name:
    raise ValueError(
        f"CloudControl '{cc_id}' does not accept parameters, but got:"
        f" {list(selected_parameters.keys())}"
    )

  for param_key, param_val in selected_parameters.items():
    if param_key not in specs_by_name:
      raise ValueError(
          f"Invalid parameter '{param_key}' for CloudControl '{cc_id}'."
          f" Allowed parameters: {sorted(specs_by_name.keys())}"
      )
    spec = specs_by_name[param_key]
    allowed_entries = (
        spec.get("validation", {}).get("allowedValues", {}).get("values", [])
    )
    allowed_strings = {
        entry.get("stringValue")
        for entry in allowed_entries
        if isinstance(entry, dict) and "stringValue" in entry
    }
    if allowed_strings:
      candidate_str = (
          param_val.get("stringValue")
          if isinstance(param_val, dict)
          else (param_val if isinstance(param_val, str) else None)
      )
      if candidate_str is not None and candidate_str not in allowed_strings:
        raise ValueError(
            f"Invalid value '{candidate_str}' for parameter '{param_key}' on"
            f" CloudControl '{cc_id}'. Allowed values:"
            f" {sorted(allowed_strings)}"
        )


def _match_percentage(
    satisfied_requirements: list[str], major_requirement_keys: list[str]
) -> float:
  """Returns the percentage of the MAJOR requirements that are satisfied.

  Args:
    satisfied_requirements: The requirements that a Framework satisfies.
    major_requirement_keys: The text of each MAJOR requirement of the intent,
      stripped and in lower case.

  Returns:
    The percentage, rounded to 2 decimals. It is 100.0 when the intent has no
    MAJOR requirement, the same as the overall match score.
  """
  if not major_requirement_keys:
    return 100.0
  satisfied_keys = {r.strip().lower() for r in satisfied_requirements}
  met = sum(1 for key in major_requirement_keys if key in satisfied_keys)
  return round(met / len(major_requirement_keys) * 100.0, 2)


def analyze_output_matches(
    intent: NavigatorIntentSpec,
    match_result: CatalogMatchResult,
    resources: DBResourcesStore,
    include_underlying_ccs: bool = False,
) -> MatchAnalysisReport:
  """Validates matched FWs/CCs, enforces built-in priority, and builds report.

  Args:
    intent: Normalized NavigatorIntentSpec from the user prompt.
    match_result: Candidate frameworks, standalone CCs, and unmatched reqs.
    resources: Loaded DBResourcesStore containing active FWs and CCs.
    include_underlying_ccs: Whether to populate underlying_ccs on matched FWs
      (False by default; set True only when the user explicitly asks for CCs).

  Returns:
    A verified MatchAnalysisReport, with the matched Frameworks sorted from the
    best to the weakest match.

  Raises:
    ValueError: If any fw_id, cc_id, or parameter name/value is invalid.
  """
  req_importance_by_text = {
      r.requirement.strip().lower(): r.importance for r in intent.requirements
  }
  major_requirement_keys = [
      r.requirement.strip().lower()
      for r in intent.requirements
      if r.importance == "MAJOR"
  ]

  verified_fws: list[MatchedFW] = []
  has_builtin_fw = False
  selected_fw_cc_ids: set[str] = set()
  for fw in match_result.selected_frameworks:
    raw_fw = resources.frameworks.get(fw.fw_id)
    if not raw_fw:
      raise ValueError(f"Unknown framework ID in match_result: {fw.fw_id}")

    fw_type = _infer_resource_type(raw_fw, fw.fw_id)
    if fw_type == "BUILT_IN":
      has_builtin_fw = True
    selected_fw_cc_ids |= _framework_cc_ids(raw_fw)

    populated_ccs: list[MatchedCC] | None = None
    if include_underlying_ccs:
      overrides_by_cc = {c.cc_id: c for c in fw.underlying_ccs or []}
      populated_ccs = []
      for ref in raw_fw.get("cloudControlDetails", []):
        cid = ref.get("name", "").split("/")[-1]
        if not cid:
          continue
        raw_cc = resources.cloud_controls.get(cid, {})
        bound_params = {
            p.get("name"): p.get("parameterValue", {})
            for p in ref.get("parameters", [])
            if isinstance(p, dict) and p.get("name")
        }
        override_cc = overrides_by_cc.get(cid)
        if override_cc and override_cc.selected_parameters:
          _validate_cc_parameters(cid, override_cc.selected_parameters, raw_cc)
          bound_params.update(override_cc.selected_parameters)

        populated_ccs.append(
            MatchedCC(
                cc_id=cid,
                cc_type=_infer_resource_type(raw_cc, cid),
                display_name=raw_cc.get(
                    "displayName",
                    override_cc.display_name if override_cc else cid,
                ),
                match_rationale=(
                    override_cc.match_rationale
                    if override_cc and override_cc.match_rationale
                    else raw_cc.get("description", "")
                ),
                matched_rule_types=(
                    _extract_rule_types(raw_cc)
                    or (override_cc.matched_rule_types if override_cc else [])
                ),
                selected_parameters=bound_params,
            )
        )

    verified_fws.append(
        MatchedFW(
            fw_id=fw.fw_id,
            fw_type=fw_type,
            major_revision_id=int(
                raw_fw.get("majorRevisionId", fw.major_revision_id)
            ),
            display_name=raw_fw.get("displayName", fw.display_name),
            match_rationale=(
                fw.match_rationale or raw_fw.get("description", "")
            ),
            satisfied_requirements=list(fw.satisfied_requirements),
            match_percentage=_match_percentage(
                fw.satisfied_requirements, major_requirement_keys
            ),
            underlying_ccs=populated_ccs,
        )
    )

  # Best match first. The sort is stable, so Frameworks with the same
  # percentage keep the order in which they were selected.
  verified_fws.sort(key=lambda fw: fw.match_percentage, reverse=True)

  verified_standalone_ccs: list[MatchedCC] = []
  for cc in match_result.standalone_matched_ccs:
    raw_cc = resources.cloud_controls.get(cc.cc_id)
    if not raw_cc:
      raise ValueError(f"Unknown CloudControl ID in match_result: {cc.cc_id}")
    _validate_cc_parameters(cc.cc_id, cc.selected_parameters, raw_cc)

    # Guardrail: A selected Framework already contains this CloudControl, so it
    # is not an additional one. Matched by ID only; the parameter values that
    # the Framework binds are not compared.
    if cc.cc_id in selected_fw_cc_ids:
      continue

    effective_importance = cc.importance
    if cc.requirement:
      effective_importance = req_importance_by_text.get(
          cc.requirement.strip().lower(), cc.importance
      )

    # Guardrail: If a requirement is minor and not met by the matched built-in
    # framework, ignore recommending extra CCs for it.
    if has_builtin_fw and effective_importance == "MINOR":
      continue

    parent_fws = _resolve_parent_builtin_frameworks(cc.cc_id, raw_cc, resources)
    verified_standalone_ccs.append(
        MatchedCC(
            cc_id=cc.cc_id,
            cc_type=_infer_resource_type(raw_cc, cc.cc_id),
            display_name=raw_cc.get("displayName", cc.display_name),
            requirement=cc.requirement,
            importance=effective_importance,
            match_rationale=(
                cc.match_rationale or raw_cc.get("description", "")
            ),
            part_of_builtin_frameworks=parent_fws,
            matched_rule_types=(
                _extract_rule_types(raw_cc) or list(cc.matched_rule_types)
            ),
            selected_parameters=dict(cc.selected_parameters),
        )
    )

  common_builtin_fws = _compute_common_parent_frameworks(
      verified_standalone_ccs
  )
  # Guardrail: If 1+ additional CCs are all covered by at least one single
  # built-in framework, do NOT suggest clubbing them into a custom framework.
  # Only suggest creating a custom framework for additional CCs when no single
  # built-in framework covers them (e.g. >1 CCs belonging to disjoint built-in
  # frameworks, or an additional CC not in any built-in framework).
  suggest_custom_fw_for_additional_ccs = bool(
      verified_standalone_ccs and not common_builtin_fws
  )

  # Compute unmet MAJOR requirements (ignoring MINOR unmet requirements).
  covered_reqs_lower: set[str] = set()
  for fw in verified_fws:
    for req_str in fw.satisfied_requirements:
      covered_reqs_lower.add(req_str.strip().lower())
  for cc in match_result.standalone_matched_ccs:
    if cc.requirement:
      covered_reqs_lower.add(cc.requirement.strip().lower())

  unmet_major_by_text: dict[str, RequirementItem] = {}
  for req in match_result.unmatched_requirements:
    key = req.requirement.strip().lower()
    effective_imp = req_importance_by_text.get(key, req.importance)
    if effective_imp == "MAJOR" and key:
      req.importance = "MAJOR"
      unmet_major_by_text[key] = req

  for req in intent.requirements:
    key = req.requirement.strip().lower()
    if (
        req.importance == "MAJOR"
        and key
        and key not in covered_reqs_lower
        and key not in unmet_major_by_text
    ):
      unmet_major_by_text[key] = req

  unmet_major_requirements = list(unmet_major_by_text.values())

  total_major_reqs = len(major_requirement_keys)
  match_score_percentage = 100.0
  if total_major_reqs > 0:
    # Count only unmet requirements that are in the intent. The agent can put
    # any text into `unmatched_requirements`, and a requirement that the
    # customer never stated must not lower the score.
    unmet_intent_major_reqs = sum(
        1 for key in major_requirement_keys if key in unmet_major_by_text
    )
    met_major_reqs = total_major_reqs - unmet_intent_major_reqs
    match_score_percentage = (met_major_reqs / total_major_reqs) * 100.0
  match_score_percentage = round(
      max(0.0, min(100.0, match_score_percentage)), 2
  )

  # Guardrail: A built-in Framework is recommended whatever its match percentage
  # is. Custom resources for unmet MAJOR requirements are suggested only when
  # the overall match is less than the threshold.
  suggest_custom_for_unmet_requirements = bool(
      unmet_major_requirements
      and match_score_percentage < CUSTOM_RESOURCES_MATCH_THRESHOLD
  )

  custom_handoff: dict[str, Any] | None = None
  if (
      suggest_custom_for_unmet_requirements
      or suggest_custom_fw_for_additional_ccs
  ):
    custom_handoff = {
        "organization_id": intent.organization_id,
        "location": resources.location,
        "base_frameworks": [f.fw_id for f in verified_fws],
        "additional_existing_ccs_to_bundle": [
            {"cc_id": c.cc_id, "selected_parameters": c.selected_parameters}
            for c in verified_standalone_ccs
        ],
        "unmet_major_requirements_needing_custom_ccs": [
            dataclasses.asdict(r) for r in unmet_major_requirements
        ],
    }

  return MatchAnalysisReport(
      matched_frameworks=verified_fws,
      additional_cloud_controls=verified_standalone_ccs,
      common_builtin_frameworks_for_additional_ccs=common_builtin_fws,
      suggest_custom_framework_for_additional_ccs=(
          suggest_custom_fw_for_additional_ccs
      ),
      unmet_major_requirements=unmet_major_requirements,
      match_score_percentage=match_score_percentage,
      suggest_custom_resources_for_unmet_requirements=(
          suggest_custom_for_unmet_requirements
      ),
      custom_authoring_handoff=custom_handoff,
      location=resources.location,
  )


def write_outputs(
    report: MatchAnalysisReport, output_dir: pathlib.Path
) -> None:
  """Writes the analysis report and, when needed, the author hand-off file.

  `author_handoff.json` is written next to `analysis_report.json` only when the
  report has a hand-off. A file left by an earlier run is removed otherwise, so
  it cannot be mistaken for the hand-off of this run.

  Args:
    report: The verified MatchAnalysisReport.
    output_dir: The directory to write into; it is created if missing.
  """
  output_dir.mkdir(parents=True, exist_ok=True)
  (output_dir / ANALYSIS_REPORT_FILE).write_text(
      json.dumps(report.to_dict(), indent=2)
  )
  handoff_path = output_dir / AUTHOR_HANDOFF_FILE
  if report.custom_authoring_handoff is None:
    handoff_path.unlink(missing_ok=True)
  else:
    handoff_path.write_text(
        json.dumps(report.custom_authoring_handoff, indent=2)
    )


def main() -> None:
  """CLI entry point for validating matches and producing analysis_report.json."""
  parser = argparse.ArgumentParser(
      description="Validates matched DB resources and produces analysis report."
  )
  parser.add_argument("--intent_spec_json", required=True)
  parser.add_argument("--match_result_json", required=True)
  parser.add_argument("--resources_json", required=True)
  parser.add_argument("--output_dir", required=True)
  parser.add_argument(
      "--include_underlying_ccs",
      action="store_true",
      help="Include underlying CloudControls inside matched Frameworks.",
  )
  args = parser.parse_args()

  intent = NavigatorIntentSpec.from_dict(
      json.loads(pathlib.Path(args.intent_spec_json).read_text())
  )
  match_res = CatalogMatchResult.from_dict(
      json.loads(pathlib.Path(args.match_result_json).read_text())
  )
  resources = DBResourcesStore.from_dict(
      json.loads(pathlib.Path(args.resources_json).read_text())
  )
  report = analyze_output_matches(
      intent,
      match_res,
      resources,
      include_underlying_ccs=args.include_underlying_ccs,
  )

  write_outputs(report, pathlib.Path(args.output_dir))


if __name__ == "__main__":
  main()
db_output_match_analyzer_test.py 38.4 KB
#!/usr/bin/env python3
"""Unit tests for db_output_match_analyzer."""

from __future__ import annotations

import contextlib
import io
import json
import os
import pathlib
import sys
import tempfile
import unittest
from unittest import mock

sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import db_output_match_analyzer  # pylint: disable=g-import-not-at-top
import db_resources_loader  # pylint: disable=g-import-not-at-top


def _fw_name(fw_id: str) -> str:
  return f"organizations/123/locations/global/frameworks/{fw_id}"


def _cc_name(cc_id: str) -> str:
  return f"organizations/123/locations/global/cloudControls/{cc_id}"


_REGULATORY_FRAMEWORK_PARAMETER_SPEC = {
    "name": "framework",
    "valueType": "STRING",
    "isRequired": True,
    "validation": {
        "allowedValues": {
            "values": [
                {"stringValue": "DATA_BOUNDARY_FOR_FEDRAMP_HIGH"},
                {"stringValue": "DATA_BOUNDARY_FOR_IL4"},
            ]
        }
    },
}


def _make_sample_resources() -> db_resources_loader.DBResourcesStore:
  return db_resources_loader.DBResourcesStore(
      last_synced_epoch=1_790_000_000.0,
      frameworks={
          "builtin-australia-data-boundary": {
              "name": _fw_name("builtin-australia-data-boundary"),
              "displayName": "Australia Data Boundary",
              "description": "Enforces Australia regional data residency.",
              "majorRevisionId": "4",
              "cloudControlDetails": [
                  {
                      "name": _cc_name(
                          "builtin-cloud-logging-storage-locations"
                      ),
                      "majorRevisionId": "3",
                      "parameters": [{
                          "name": "cloudLoggingStorageLocations",
                          "parameterValue": {
                              "stringListValue": {
                                  "values": [
                                      "australia-southeast1",
                                      "australia-southeast2",
                                  ]
                              }
                          },
                      }],
                  },
                  {
                      "name": _cc_name("builtin-require-cmek"),
                      "majorRevisionId": "2",
                  },
              ],
          },
          "builtin-il4": {
              "name": _fw_name("builtin-il4"),
              "displayName": "Impact Level 4 (IL4)",
              "majorRevisionId": "2",
              "cloudControlDetails": [{
                  "name": _cc_name(
                      "builtin-gemini-enterprise-regulatory-settings"
                  ),
                  "majorRevisionId": "2",
              }],
          },
          "builtin-il5": {
              "name": _fw_name("builtin-il5"),
              "displayName": "Impact Level 5 (IL5)",
              "majorRevisionId": "2",
              "cloudControlDetails": [
                  {
                      "name": _cc_name(
                          "builtin-iam-disable-service-account-key-creation"
                      ),
                      "majorRevisionId": "3",
                  },
                  {
                      "name": _cc_name(
                          "builtin-gemini-enterprise-regulatory-settings"
                      ),
                      "majorRevisionId": "2",
                  },
              ],
          },
          "builtin-japan-data-boundary": {
              "name": _fw_name("builtin-japan-data-boundary"),
              "displayName": "Japan Data Boundary",
              "majorRevisionId": "1",
              "cloudControlDetails": [{
                  "name": _cc_name("builtin-only-in-japan"),
                  "majorRevisionId": "1",
              }],
          },
      },
      cloud_controls={
          "builtin-cloud-logging-storage-locations": {
              "name": _cc_name("builtin-cloud-logging-storage-locations"),
              "displayName": "Cloud Logging Storage Locations",
              "parameterSpec": [{
                  "name": "cloudLoggingStorageLocations",
                  "valueType": "STRINGLIST",
                  "isRequired": True,
              }],
              "rules": [{
                  "ruleActionTypes": ["RULE_ACTION_TYPE_PREVENTIVE"],
              }],
          },
          "builtin-require-cmek": {
              "name": _cc_name("builtin-require-cmek"),
              "displayName": "Require CMEK",
              "rules": [{
                  "celExpression": {"expression": "has(resource.kmsKey)"},
                  "ruleActionTypes": ["RULE_ACTION_TYPE_DETECTIVE"],
              }],
          },
          "builtin-iam-disable-service-account-key-creation": {
              "name": _cc_name(
                  "builtin-iam-disable-service-account-key-creation"
              ),
              "displayName": "Disable Service Account Key Creation",
              "description": (
                  "Prevents creation of user-managed service account keys."
              ),
              "relatedFrameworks": ["builtin-il5"],
              "rules": [
                  {"ruleActionTypes": ["RULE_ACTION_TYPE_PREVENTIVE"]},
              ],
          },
          "builtin-gemini-enterprise-regulatory-settings": {
              "name": _cc_name("builtin-gemini-enterprise-regulatory-settings"),
              "displayName": "Regulatory Framework",
              "relatedFrameworks": ["builtin-il4", "builtin-il5"],
              "parameterSpec": [_REGULATORY_FRAMEWORK_PARAMETER_SPEC],
              "rules": [
                  {"ruleActionTypes": ["RULE_ACTION_TYPE_PREVENTIVE"]},
              ],
          },
          "builtin-only-in-japan": {
              "name": _cc_name("builtin-only-in-japan"),
              "displayName": "Japan Specific Control",
              "relatedFrameworks": ["builtin-japan-data-boundary"],
              "rules": [
                  {"ruleActionTypes": ["RULE_ACTION_TYPE_PREVENTIVE"]},
              ],
          },
          # Not part of any framework in this sample.
          "builtin-in-no-framework": {
              "name": _cc_name("builtin-in-no-framework"),
              "displayName": "Control In No Framework",
              "rules": [
                  {"ruleActionTypes": ["RULE_ACTION_TYPE_DETECTIVE"]},
              ],
          },
      },
  )


def _intent(*requirements) -> db_output_match_analyzer.NavigatorIntentSpec:
  return db_output_match_analyzer.NavigatorIntentSpec(
      source_type="DIRECT_NL",
      organization_id="123",
      user_prompt="test",
      requirements=list(requirements),
  )


def _req(
    text: str, importance: str = "MAJOR"
) -> db_output_match_analyzer.RequirementItem:
  return db_output_match_analyzer.RequirementItem(
      requirement=text, importance=importance
  )


def _fw(fw_id: str, *satisfied: str) -> db_output_match_analyzer.MatchedFW:
  return db_output_match_analyzer.MatchedFW(
      fw_id=fw_id,
      fw_type="BUILT_IN",
      major_revision_id=1,
      display_name=fw_id,
      satisfied_requirements=list(satisfied),
  )


def _cc(
    cc_id: str, requirement: str = "", importance: str = "MAJOR"
) -> db_output_match_analyzer.MatchedCC:
  return db_output_match_analyzer.MatchedCC(
      cc_id=cc_id,
      cc_type="BUILT_IN",
      display_name=cc_id,
      requirement=requirement,
      importance=importance,
  )


class DBOutputMatchAnalyzerTest(unittest.TestCase):

  def test_omits_underlying_ccs_by_default_and_includes_when_requested(self):
    resources = _make_sample_resources()
    intent = db_output_match_analyzer.NavigatorIntentSpec(
        source_type="DIRECT_NL",
        organization_id="123",
        user_prompt="Australia data residency with CMEK",
        requirements=[
            db_output_match_analyzer.RequirementItem(
                requirement="Store logs in Australia regions",
                importance="MAJOR",
            ),
            db_output_match_analyzer.RequirementItem(
                requirement="Enforce CMEK encryption",
                importance="MAJOR",
            ),
        ],
    )
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            db_output_match_analyzer.MatchedFW(
                fw_id="builtin-australia-data-boundary",
                fw_type="BUILT_IN",
                major_revision_id=1,
                display_name="Australia Data Boundary",
                match_rationale=(
                    "Enforces Australia regional data residency and CMEK."
                ),
                satisfied_requirements=[
                    "Store logs in Australia regions",
                    "Enforce CMEK encryption",
                ],
            )
        ]
    )

    default_report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )
    self.assertIsNone(default_report.matched_frameworks[0].underlying_ccs)
    self.assertNotIn(
        "underlying_ccs", default_report.to_dict()["matched_frameworks"][0]
    )
    self.assertIsNone(default_report.custom_authoring_handoff)

    expanded_report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources, include_underlying_ccs=True
    )
    fw = expanded_report.matched_frameworks[0]
    self.assertIsNotNone(fw.underlying_ccs)
    self.assertEqual(
        [c.cc_id for c in fw.underlying_ccs or []],
        [
            "builtin-cloud-logging-storage-locations",
            "builtin-require-cmek",
        ],
    )

  def test_multiple_ccs_sharing_common_builtin_fw_do_not_suggest_custom_fw(
      self,
  ):
    resources = _make_sample_resources()
    intent = db_output_match_analyzer.NavigatorIntentSpec(
        source_type="DIRECT_NL",
        organization_id="123",
        user_prompt=(
            "AU data boundary + SA key creation disabled + Gemini settings"
        ),
        requirements=[
            db_output_match_analyzer.RequirementItem(
                requirement="Australia regional data residency",
                importance="MAJOR",
            ),
            db_output_match_analyzer.RequirementItem(
                requirement="Disable service account key creation",
                importance="MAJOR",
            ),
            db_output_match_analyzer.RequirementItem(
                requirement="Gemini regulatory settings",
                importance="MAJOR",
            ),
        ],
    )
    # Both standalone CCs are in builtin-il5 -> common_builtin_frameworks has
    # builtin-il5, so suggest_custom_framework_for_additional_ccs is False.
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            db_output_match_analyzer.MatchedFW(
                fw_id="builtin-australia-data-boundary",
                fw_type="BUILT_IN",
                major_revision_id=4,
                display_name="Australia Data Boundary",
                satisfied_requirements=["Australia regional data residency"],
            )
        ],
        standalone_matched_ccs=[
            db_output_match_analyzer.MatchedCC(
                cc_id="builtin-iam-disable-service-account-key-creation",
                cc_type="BUILT_IN",
                display_name="Disable Service Account Key Creation",
                requirement="Disable service account key creation",
                importance="MAJOR",
            ),
            db_output_match_analyzer.MatchedCC(
                cc_id="builtin-gemini-enterprise-regulatory-settings",
                cc_type="BUILT_IN",
                display_name="Regulatory Framework",
                requirement="Gemini regulatory settings",
                importance="MAJOR",
                selected_parameters={"framework": "DATA_BOUNDARY_FOR_IL4"},
            ),
        ],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )
    self.assertEqual(
        [f.fw_id for f in report.common_builtin_frameworks_for_additional_ccs],
        ["builtin-il5"],
    )
    self.assertFalse(report.suggest_custom_framework_for_additional_ccs)
    self.assertIsNone(report.custom_authoring_handoff)

  def test_disjoint_multiple_ccs_with_no_common_builtin_fw_suggests_custom_fw(
      self,
  ):
    resources = _make_sample_resources()
    intent = db_output_match_analyzer.NavigatorIntentSpec(
        source_type="DIRECT_NL",
        organization_id="123",
        user_prompt=(
            "AU data boundary + SA key creation disabled + Japan control"
        ),
        requirements=[
            db_output_match_analyzer.RequirementItem(
                requirement="Australia regional data residency",
                importance="MAJOR",
            ),
            db_output_match_analyzer.RequirementItem(
                requirement="Disable service account key creation",
                importance="MAJOR",
            ),
            db_output_match_analyzer.RequirementItem(
                requirement="Japan specific control",
                importance="MAJOR",
            ),
        ],
    )
    # One CC is only in builtin-il5, the other is only in
    # builtin-japan-data-boundary. No single built-in FW contains both ->
    # suggest_custom_framework_for_additional_ccs is True.
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            db_output_match_analyzer.MatchedFW(
                fw_id="builtin-australia-data-boundary",
                fw_type="BUILT_IN",
                major_revision_id=4,
                display_name="Australia Data Boundary",
                satisfied_requirements=["Australia regional data residency"],
            )
        ],
        standalone_matched_ccs=[
            db_output_match_analyzer.MatchedCC(
                cc_id="builtin-iam-disable-service-account-key-creation",
                cc_type="BUILT_IN",
                display_name="Disable Service Account Key Creation",
                requirement="Disable service account key creation",
                importance="MAJOR",
            ),
            db_output_match_analyzer.MatchedCC(
                cc_id="builtin-only-in-japan",
                cc_type="BUILT_IN",
                display_name="Japan Specific Control",
                requirement="Japan specific control",
                importance="MAJOR",
            ),
        ],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )
    self.assertEqual(report.common_builtin_frameworks_for_additional_ccs, [])
    self.assertTrue(report.suggest_custom_framework_for_additional_ccs)
    self.assertIsNotNone(report.custom_authoring_handoff)

  def test_single_additional_cc_in_no_builtin_fw_suggests_custom_fw(self):
    resources = _make_sample_resources()
    intent = _intent(
        _req("Australia regional data residency"),
        _req("Detect the control that no built-in framework has"),
    )
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            _fw(
                "builtin-australia-data-boundary",
                "Australia regional data residency",
            )
        ],
        standalone_matched_ccs=[
            _cc(
                "builtin-in-no-framework",
                requirement="Detect the control that no built-in framework has",
            )
        ],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )

    self.assertEqual(
        [c.cc_id for c in report.additional_cloud_controls],
        ["builtin-in-no-framework"],
    )
    self.assertEqual(
        report.additional_cloud_controls[0].part_of_builtin_frameworks, []
    )
    self.assertEqual(report.common_builtin_frameworks_for_additional_ccs, [])
    self.assertTrue(report.suggest_custom_framework_for_additional_ccs)
    # The match is 100 percent, so only the additional control asks for it.
    self.assertEqual(report.match_score_percentage, 100.0)
    self.assertFalse(report.suggest_custom_resources_for_unmet_requirements)
    handoff = report.custom_authoring_handoff
    self.assertIsNotNone(handoff)
    self.assertEqual(
        [c["cc_id"] for c in handoff["additional_existing_ccs_to_bundle"]],
        ["builtin-in-no-framework"],
    )

  def test_single_additional_cc_in_a_builtin_fw_does_not_suggest_custom_fw(
      self,
  ):
    resources = _make_sample_resources()
    intent = _intent(
        _req("Australia regional data residency"),
        _req("Japan specific control"),
    )
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            _fw(
                "builtin-australia-data-boundary",
                "Australia regional data residency",
            )
        ],
        standalone_matched_ccs=[
            _cc("builtin-only-in-japan", requirement="Japan specific control")
        ],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )

    self.assertEqual(
        [f.fw_id for f in report.common_builtin_frameworks_for_additional_ccs],
        ["builtin-japan-data-boundary"],
    )
    self.assertFalse(report.suggest_custom_framework_for_additional_ccs)
    self.assertIsNone(report.custom_authoring_handoff)

  def test_standalone_cc_already_in_a_selected_fw_is_dropped(self):
    resources = _make_sample_resources()
    intent = _intent(
        _req("Impact Level 5 compliance"),
        _req("Disable service account key creation"),
    )
    # The control is in builtin-il5, which is selected, so it is not an
    # additional one, and its requirement counts as met.
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[_fw("builtin-il5", "Impact Level 5 compliance")],
        standalone_matched_ccs=[
            _cc(
                "builtin-iam-disable-service-account-key-creation",
                requirement="Disable service account key creation",
            )
        ],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )

    self.assertEqual(report.additional_cloud_controls, [])
    self.assertEqual(report.common_builtin_frameworks_for_additional_ccs, [])
    self.assertFalse(report.suggest_custom_framework_for_additional_ccs)
    self.assertEqual(report.unmet_major_requirements, [])
    self.assertEqual(report.match_score_percentage, 100.0)
    self.assertIsNone(report.custom_authoring_handoff)

  def test_standalone_cc_is_still_validated_before_it_is_dropped(self):
    resources = _make_sample_resources()
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[_fw("builtin-il5")],
        standalone_matched_ccs=[
            db_output_match_analyzer.MatchedCC(
                cc_id="builtin-gemini-enterprise-regulatory-settings",
                cc_type="BUILT_IN",
                display_name="Regulatory Framework",
                selected_parameters={"framework": "INVALID_ENUM_VALUE"},
            )
        ],
    )

    with self.assertRaisesRegex(
        ValueError, "Invalid value 'INVALID_ENUM_VALUE'"
    ):
      db_output_match_analyzer.analyze_output_matches(
          _intent(), match_result, resources
      )

  def test_ignores_minor_unmet_and_minor_standalone_ccs_when_builtin_fw_matched(
      self,
  ):
    resources = _make_sample_resources()
    intent = db_output_match_analyzer.NavigatorIntentSpec(
        source_type="DIRECT_NL",
        organization_id="123",
        user_prompt="AU data residency with minor preferences",
        requirements=[
            db_output_match_analyzer.RequirementItem(
                requirement="Australia regional data residency",
                importance="MAJOR",
            ),
            db_output_match_analyzer.RequirementItem(
                requirement="Optional SA key rotation preference",
                importance="MINOR",
            ),
            db_output_match_analyzer.RequirementItem(
                requirement="Optional custom audit label",
                importance="MINOR",
            ),
        ],
    )
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            db_output_match_analyzer.MatchedFW(
                fw_id="builtin-australia-data-boundary",
                fw_type="BUILT_IN",
                major_revision_id=4,
                display_name="Australia Data Boundary",
                satisfied_requirements=["Australia regional data residency"],
            )
        ],
        standalone_matched_ccs=[
            db_output_match_analyzer.MatchedCC(
                cc_id="builtin-iam-disable-service-account-key-creation",
                cc_type="BUILT_IN",
                display_name="Disable Service Account Key Creation",
                requirement="Optional SA key rotation preference",
                importance="MINOR",
            )
        ],
        unmatched_requirements=[
            db_output_match_analyzer.RequirementItem(
                requirement="Optional custom audit label",
                importance="MINOR",
            )
        ],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )
    self.assertEqual(len(report.additional_cloud_controls), 0)
    self.assertEqual(len(report.unmet_major_requirements), 0)
    self.assertIsNone(report.custom_authoring_handoff)

  def test_surfaces_unmet_major_requirement_and_builds_custom_handoff(self):
    resources = _make_sample_resources()
    intent = db_output_match_analyzer.NavigatorIntentSpec(
        source_type="DIRECT_NL",
        organization_id="123",
        user_prompt="AU data boundary + custom AlloyDB port 5433",
        requirements=[
            db_output_match_analyzer.RequirementItem(
                requirement="Australia regional data residency",
                importance="MAJOR",
            ),
            db_output_match_analyzer.RequirementItem(
                requirement="Restrict AlloyDB to custom non-default port 5433",
                importance="MAJOR",
                suggested_custom_cc_summary=(
                    "Enforce port 5433 on alloydb.googleapis.com/Cluster."
                ),
            ),
        ],
    )
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            db_output_match_analyzer.MatchedFW(
                fw_id="builtin-australia-data-boundary",
                fw_type="BUILT_IN",
                major_revision_id=4,
                display_name="Australia Data Boundary",
                satisfied_requirements=["Australia regional data residency"],
            )
        ]
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )
    self.assertEqual(
        [r.requirement for r in report.unmet_major_requirements],
        ["Restrict AlloyDB to custom non-default port 5433"],
    )
    self.assertIsNotNone(report.custom_authoring_handoff)
    self.assertEqual(report.match_score_percentage, 50.0)

  def test_score_ignores_unmet_requirements_that_are_not_in_the_intent(self):
    resources = _make_sample_resources()
    intent = _intent(_req("Requirement one"), _req("Requirement two"))
    # The agent put three requirements that the customer never stated into
    # `unmatched_requirements`; they must not push the score below 100.
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            _fw("builtin-il4", "Requirement one", "Requirement two")
        ],
        unmatched_requirements=[
            _req("Invented requirement A"),
            _req("Invented requirement B"),
            _req("Invented requirement C"),
        ],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )

    self.assertEqual(report.match_score_percentage, 100.0)
    # They stay in the unmet list, but the match is still 100 percent, so no
    # custom resources are suggested and there is no hand-off.
    self.assertEqual(len(report.unmet_major_requirements), 3)
    self.assertFalse(report.suggest_custom_resources_for_unmet_requirements)
    self.assertIsNone(report.custom_authoring_handoff)

  def test_score_is_between_zero_and_one_hundred(self):
    resources = _make_sample_resources()
    intent = _intent(_req("Requirement one"), _req("Requirement two"))
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[_fw("builtin-il4", "Requirement two")],
        unmatched_requirements=[_req("Requirement one")],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )
    self.assertEqual(report.match_score_percentage, 50.0)

    nothing_met = db_output_match_analyzer.analyze_output_matches(
        intent, db_output_match_analyzer.CatalogMatchResult(), resources
    )
    self.assertEqual(nothing_met.match_score_percentage, 0.0)

  def test_matched_frameworks_are_sorted_from_best_to_weakest_match(self):
    resources = _make_sample_resources()
    intent = _intent(
        _req("Requirement one"),
        _req("Requirement two"),
        _req("Requirement three"),
        _req("Requirement four"),
    )
    # The agent lists the Frameworks in another order than their match.
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            _fw("builtin-il4", "Requirement one"),
            _fw(
                "builtin-il5",
                "Requirement one",
                "Requirement two",
                "Requirement three",
            ),
            _fw(
                "builtin-japan-data-boundary",
                "Requirement one",
                "Requirement two",
            ),
        ],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )

    self.assertEqual(
        [f.fw_id for f in report.matched_frameworks],
        ["builtin-il5", "builtin-japan-data-boundary", "builtin-il4"],
    )
    self.assertEqual(
        [f.match_percentage for f in report.matched_frameworks],
        [75.0, 50.0, 25.0],
    )
    self.assertEqual(
        [f["match_percentage"] for f in report.to_dict()["matched_frameworks"]],
        [75.0, 50.0, 25.0],
    )
    # The hand-off lists the base Frameworks in the same order.
    self.assertEqual(
        report.custom_authoring_handoff["base_frameworks"],
        ["builtin-il5", "builtin-japan-data-boundary", "builtin-il4"],
    )

  def test_frameworks_with_the_same_match_keep_their_selection_order(self):
    resources = _make_sample_resources()
    intent = _intent(_req("Requirement one"), _req("Requirement two"))
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            _fw("builtin-il5", "Requirement one"),
            _fw("builtin-il4", "Requirement two"),
            _fw(
                "builtin-japan-data-boundary",
                "Requirement one",
                "Requirement two",
            ),
        ],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )

    self.assertEqual(
        [f.fw_id for f in report.matched_frameworks],
        ["builtin-japan-data-boundary", "builtin-il5", "builtin-il4"],
    )

  def test_framework_percentage_ignores_requirements_outside_the_intent(self):
    resources = _make_sample_resources()
    intent = _intent(
        _req("Requirement one"),
        _req("Requirement two"),
        _req("Optional preference", importance="MINOR"),
    )
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            # The text of the second requirement differs in case and spaces
            # only. The MINOR requirement and the unknown text do not count.
            _fw(
                "builtin-il4",
                "Requirement one",
                "  REQUIREMENT TWO ",
                "Optional preference",
                "Text the customer never stated",
            ),
            _fw("builtin-il5", "Requirement one"),
        ],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )

    self.assertEqual(
        [(f.fw_id, f.match_percentage) for f in report.matched_frameworks],
        [("builtin-il4", 100.0), ("builtin-il5", 50.0)],
    )

  def test_framework_percentage_is_100_when_the_intent_has_no_major(self):
    resources = _make_sample_resources()
    intent = _intent(_req("Optional preference", importance="MINOR"))
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[_fw("builtin-il4")],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )

    self.assertEqual(report.matched_frameworks[0].match_percentage, 100.0)
    self.assertEqual(report.match_score_percentage, 100.0)

  def test_a_framework_is_kept_whatever_its_match_percentage(self):
    resources = _make_sample_resources()
    intent = _intent(
        _req("Requirement one"),
        _req("Requirement two"),
        _req("Requirement three"),
        _req("Requirement four"),
        _req("Requirement five"),
    )
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            _fw("builtin-il5"),
            _fw("builtin-il4", "Requirement one"),
        ],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )

    # Neither Framework is dropped, not even the one with 0 percent.
    self.assertEqual(
        [(f.fw_id, f.match_percentage) for f in report.matched_frameworks],
        [("builtin-il4", 20.0), ("builtin-il5", 0.0)],
    )
    # Custom resources are offered in addition to them.
    self.assertTrue(report.suggest_custom_resources_for_unmet_requirements)

  def test_a_match_percentage_in_the_input_is_ignored(self):
    resources = _make_sample_resources()
    match_result = db_output_match_analyzer.CatalogMatchResult.from_dict({
        "selected_frameworks": [{
            "fw_id": "builtin-il4",
            "satisfied_requirements": ["Requirement one"],
            "match_percentage": 99.0,
        }]
    })

    report = db_output_match_analyzer.analyze_output_matches(
        _intent(_req("Requirement one"), _req("Requirement two")),
        match_result,
        resources,
    )

    self.assertEqual(report.matched_frameworks[0].match_percentage, 50.0)

  def test_custom_resources_are_suggested_only_below_eighty_percent(self):
    resources = _make_sample_resources()
    # (MAJOR requirements in the intent, how many the Framework satisfies,
    # the expected overall match, whether custom resources are suggested)
    cases = [
        (10, 10, 100.0, False),
        (10, 9, 90.0, False),
        (5, 4, 80.0, False),
        (24, 19, 79.17, True),
        (4, 3, 75.0, True),
        (5, 3, 60.0, True),
        (3, 0, 0.0, True),
    ]
    for total, met, expected_match, expected_suggestion in cases:
      with self.subTest(total=total, met=met):
        texts = [f"Requirement {i}" for i in range(total)]
        match_result = db_output_match_analyzer.CatalogMatchResult(
            selected_frameworks=[_fw("builtin-il4", *texts[:met])],
        )

        report = db_output_match_analyzer.analyze_output_matches(
            _intent(*[_req(text) for text in texts]), match_result, resources
        )

        self.assertEqual(report.match_score_percentage, expected_match)
        self.assertEqual(
            report.suggest_custom_resources_for_unmet_requirements,
            expected_suggestion,
        )
        # The Framework is recommended in every case.
        self.assertEqual(
            [f.fw_id for f in report.matched_frameworks], ["builtin-il4"]
        )
        # The unmet requirements are always reported; only the suggestion
        # and the hand-off depend on the threshold.
        self.assertEqual(len(report.unmet_major_requirements), total - met)
        self.assertEqual(
            report.custom_authoring_handoff is not None, expected_suggestion
        )

  def test_report_and_handoff_carry_the_location_of_the_catalog(self):
    resources = _make_sample_resources()
    resources.location = "europe-west1"
    intent = _intent(_req("Requirement one"))
    match_result = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[_fw("builtin-il4")],
        unmatched_requirements=[_req("Requirement one")],
    )

    report = db_output_match_analyzer.analyze_output_matches(
        intent, match_result, resources
    )

    handoff = report.custom_authoring_handoff
    self.assertEqual(report.location, "europe-west1")
    self.assertEqual(report.to_dict()["location"], "europe-west1")
    self.assertEqual(handoff["location"], "europe-west1")

  def test_location_defaults_to_global(self):
    report = db_output_match_analyzer.analyze_output_matches(
        _intent(),
        db_output_match_analyzer.CatalogMatchResult(),
        _make_sample_resources(),
    )

    self.assertEqual(report.location, "global")

  def test_rejects_hallucinated_ids_and_invalid_parameters(self):
    resources = _make_sample_resources()
    intent = db_output_match_analyzer.NavigatorIntentSpec(
        source_type="DIRECT_NL",
        organization_id="123",
        user_prompt="Test validation",
    )

    bad_fw_match = db_output_match_analyzer.CatalogMatchResult(
        selected_frameworks=[
            db_output_match_analyzer.MatchedFW(
                fw_id="builtin-nonexistent-fw",
                fw_type="BUILT_IN",
                major_revision_id=1,
                display_name="Fake",
            )
        ]
    )
    with self.assertRaisesRegex(ValueError, "Unknown framework ID"):
      db_output_match_analyzer.analyze_output_matches(
          intent, bad_fw_match, resources
      )

    bad_param_val_match = db_output_match_analyzer.CatalogMatchResult(
        standalone_matched_ccs=[
            db_output_match_analyzer.MatchedCC(
                cc_id="builtin-gemini-enterprise-regulatory-settings",
                cc_type="BUILT_IN",
                display_name="Regulatory Framework",
                selected_parameters={"framework": "INVALID_ENUM_VALUE"},
            )
        ]
    )
    with self.assertRaisesRegex(
        ValueError, "Invalid value 'INVALID_ENUM_VALUE'"
    ):
      db_output_match_analyzer.analyze_output_matches(
          intent, bad_param_val_match, resources
      )


class MainTest(unittest.TestCase):
  """Runs the command line entry point on files in a temporary directory."""

  def _run_main(self, tmp_dir, match_result, requirement_texts):
    tmp = pathlib.Path(tmp_dir)
    (tmp / "intent.json").write_text(
        json.dumps({
            "source_type": "DIRECT_NL",
            "organization_id": "123",
            "user_prompt": "test",
            "requirements": [
                {"requirement": text, "importance": "MAJOR"}
                for text in requirement_texts
            ],
        })
    )
    (tmp / "match.json").write_text(json.dumps(match_result))
    (tmp / "resources.json").write_text(_make_sample_resources().to_json())
    argv = [
        "db_output_match_analyzer.py",
        "--intent_spec_json",
        str(tmp / "intent.json"),
        "--match_result_json",
        str(tmp / "match.json"),
        "--resources_json",
        str(tmp / "resources.json"),
        "--output_dir",
        str(tmp / "out"),
    ]
    with mock.patch.object(sys, "argv", argv):
      with contextlib.redirect_stdout(io.StringIO()):
        db_output_match_analyzer.main()
    return tmp / "out"

  def test_writes_the_author_handoff_next_to_the_report(self):
    match_result = {
        "selected_frameworks": [{"fw_id": "builtin-il4"}],
        "unmatched_requirements": [{"requirement": "Custom port rule"}],
    }

    with tempfile.TemporaryDirectory() as tmp_dir:
      out_dir = self._run_main(tmp_dir, match_result, ["Custom port rule"])

      report = json.loads((out_dir / "analysis_report.json").read_text())
      handoff = json.loads((out_dir / "author_handoff.json").read_text())

    self.assertEqual(handoff, report["custom_authoring_handoff"])
    self.assertEqual(handoff["organization_id"], "123")
    self.assertEqual(handoff["location"], "global")
    self.assertEqual(handoff["base_frameworks"], ["builtin-il4"])
    self.assertEqual(
        [
            r["requirement"]
            for r in handoff["unmet_major_requirements_needing_custom_ccs"]
        ],
        ["Custom port rule"],
    )

  def test_writes_no_handoff_when_none_is_needed(self):
    match_result = {
        "selected_frameworks": [
            {"fw_id": "builtin-il4", "satisfied_requirements": ["IL4"]}
        ]
    }

    with tempfile.TemporaryDirectory() as tmp_dir:
      out_dir = self._run_main(tmp_dir, match_result, ["IL4"])

      self.assertTrue((out_dir / "analysis_report.json").exists())
      self.assertFalse((out_dir / "author_handoff.json").exists())
      report = json.loads((out_dir / "analysis_report.json").read_text())
    self.assertIsNone(report["custom_authoring_handoff"])

  def test_removes_the_handoff_of_an_earlier_run(self):
    match_result = {
        "selected_frameworks": [
            {"fw_id": "builtin-il4", "satisfied_requirements": ["IL4"]}
        ]
    }

    with tempfile.TemporaryDirectory() as tmp_dir:
      stale = pathlib.Path(tmp_dir, "out", "author_handoff.json")
      stale.parent.mkdir()
      stale.write_text('{"stale": true}')

      out_dir = self._run_main(tmp_dir, match_result, ["IL4"])

      self.assertFalse((out_dir / "author_handoff.json").exists())

  def test_writes_the_handoff_only_below_eighty_percent(self):
    texts = [f"Requirement {i}" for i in range(5)]
    for met, expect_handoff in [(5, False), (4, False), (3, True)]:
      with self.subTest(met=met):
        match_result = {
            "selected_frameworks": [
                {"fw_id": "builtin-il4", "satisfied_requirements": texts[:met]}
            ],
            "unmatched_requirements": [
                {"requirement": text} for text in texts[met:]
            ],
        }

        with tempfile.TemporaryDirectory() as tmp_dir:
          out_dir = self._run_main(tmp_dir, match_result, texts)

          self.assertEqual(
              (out_dir / "author_handoff.json").exists(), expect_handoff
          )
          report = json.loads((out_dir / "analysis_report.json").read_text())
        self.assertEqual(report["match_score_percentage"], met * 20.0)
        self.assertEqual(
            report["matched_frameworks"][0]["match_percentage"], met * 20.0
        )
        self.assertEqual(
            report["suggest_custom_resources_for_unmet_requirements"],
            expect_handoff,
        )


if __name__ == "__main__":
  unittest.main()
db_resources_loader.py 11.4 KB
"""Loads Data Boundary BUILT_IN and org CUSTOM resources via the gcloud CLI.

Runs the read-only `gcloud compliance-manager frameworks list` and
`gcloud compliance-manager cloud-controls list` commands for an organization
and a location, and caches the filtered result for the session.
"""

from __future__ import annotations

import argparse
import dataclasses
import json
import os
import pathlib
import re
import subprocess
import sys
import tempfile
import time
from typing import Any, Literal

DEFAULT_CACHE_DIR = os.path.join(
    tempfile.gettempdir(),
    "db_framework_navigator",
)
# The location used when the customer names none.
DEFAULT_LOCATION = "global"
# The supported location IDs, each with a plain-words description. The path is
# not resolved through symbolic links: a build system can link each file on its
# own, and following the link would lose the neighbouring `assets/` directory.
LOCATIONS_FILE = (
    pathlib.Path(os.path.abspath(__file__)).parent.parent
    / "assets"
    / "locations.json"
)
GCLOUD_TIMEOUT_SECONDS = 120
# gcloud's default page size returned incomplete lists for this API, so ask for
# one large page.
GCLOUD_PAGE_SIZE = 1000
# Built-in frameworks that are kept although they lack the ASSURED_WORKLOADS
# category.
_EXTRA_BUILTIN_FRAMEWORK_IDS = frozenset({"builtin-hipaa"})
_MAX_ERROR_CHARS = 800
_ORGANIZATION_ID_RE = re.compile(r"[0-9]+")


class GcloudError(Exception):
  """Raised when a gcloud invocation fails or returns unusable output."""


@dataclasses.dataclass
class DBResourcesStore:
  """Container for active Data Boundary BUILT_IN and org CUSTOM resources."""

  last_synced_epoch: float
  organization_id: str = ""
  frameworks: dict[str, dict[str, Any]] = dataclasses.field(
      default_factory=dict
  )
  cloud_controls: dict[str, dict[str, Any]] = dataclasses.field(
      default_factory=dict
  )
  location: str = DEFAULT_LOCATION

  def to_json(self) -> str:
    return json.dumps(dataclasses.asdict(self), indent=2)

  @classmethod
  def from_dict(cls, data: dict[str, Any]) -> DBResourcesStore:
    epoch = data.get("last_synced_epoch", data.get("last_compiled_epoch", 0.0))
    return cls(
        last_synced_epoch=float(epoch),
        organization_id=str(data.get("organization_id", "")),
        frameworks=dict(data.get("frameworks", {})),
        cloud_controls=dict(data.get("cloud_controls", {})),
        # A cache file written before locations existed counts as `global`.
        location=str(data.get("location", DEFAULT_LOCATION)),
    )


def normalize_organization_id(raw: str) -> str:
  """Returns the numeric organization ID; accepts `organizations/<ID>` too."""
  org_id = raw.strip()
  if org_id.startswith("organizations/"):
    org_id = org_id[len("organizations/") :]
  if not _ORGANIZATION_ID_RE.fullmatch(org_id):
    raise ValueError(
        f"Invalid organization ID {raw!r}: expected the numeric organization"
        " ID."
    )
  return org_id


def load_locations(path: pathlib.Path = LOCATIONS_FILE) -> dict[str, str]:
  """Returns the supported locations as a map from location ID to description.

  Args:
    path: The JSON file that lists the supported locations.

  Raises:
    ValueError: If the file is missing or does not have the expected shape.
  """
  try:
    data = json.loads(path.read_text(encoding="utf-8"))
    return {entry["id"]: entry["description"] for entry in data["locations"]}
  except (OSError, ValueError, KeyError, TypeError) as e:
    raise ValueError(
        f"Could not read the supported locations from {path.name}: {e!r}"
    ) from e


def normalize_location(raw: str) -> str:
  """Returns the location ID if it is one of the supported locations.

  The match is exact: no case folding, no prefix handling, no guessing.

  Args:
    raw: The location ID as given on the command line.

  Raises:
    ValueError: If the ID is not in the list of supported locations.
  """
  location = raw.strip()
  if location not in load_locations():
    raise ValueError(
        f"Unknown location {raw!r}: use one of the location IDs in"
        f" {LOCATIONS_FILE.name} (default: {DEFAULT_LOCATION})."
    )
  return location


def _summarize_stderr(stderr: str) -> str:
  """Returns the actionable part of gcloud's stderr.

  gcloud can append very large debug traces to its `ERROR:` line, and prints
  informational lines such as "Parsed [location] resource" even on success. The
  `ERROR:` prefix is dropped because the caller adds its own.

  Args:
    stderr: The raw stderr of a failed gcloud invocation.
  """
  lines = [line.strip() for line in stderr.splitlines() if line.strip()]
  for line in lines:
    if line.startswith("ERROR:"):
      return line[len("ERROR:") :].strip()[:_MAX_ERROR_CHARS]
  return " ".join(lines[:3])[:_MAX_ERROR_CHARS]


def run_gcloud_list(
    resource_kind: Literal["frameworks", "cloud-controls"],
    organization_id: str,
    location: str = DEFAULT_LOCATION,
) -> list[dict[str, Any]]:
  """Lists every framework or cloud control of an organization via gcloud.

  Asks for pages of `GCLOUD_PAGE_SIZE` items, because gcloud's default page size
  returned incomplete lists for this API. A list of exactly one full page may
  still be incomplete, so the function warns on stderr in that case.

  Args:
    resource_kind: The `gcloud compliance-manager` command group to list.
    organization_id: The numeric Google Cloud organization ID.
    location: The location ID to list in.

  Returns:
    The parsed `--format=json` output: one dict per resource.

  Raises:
    GcloudError: If gcloud is missing, times out, exits non-zero, or prints
      something other than a JSON list.
  """
  command = [
      "gcloud",
      "compliance-manager",
      resource_kind,
      "list",
      f"--organization={organization_id}",
      f"--location={location}",
      f"--page-size={GCLOUD_PAGE_SIZE}",
      "--format=json",
      "--quiet",
  ]
  description = f"`gcloud compliance-manager {resource_kind} list`"
  try:
    result = subprocess.run(
        command,
        capture_output=True,
        encoding="utf-8",
        errors="replace",
        check=False,
        stdin=subprocess.DEVNULL,
        timeout=GCLOUD_TIMEOUT_SECONDS,
    )
  except FileNotFoundError as e:
    raise GcloudError(
        "The gcloud CLI was not found on PATH. Install the gcloud CLI and run"
        " `gcloud auth login`."
    ) from e
  except OSError as e:
    # For example PermissionError when gcloud exists but cannot be executed.
    raise GcloudError(f"Could not run the gcloud CLI: {e}") from e
  except subprocess.TimeoutExpired as e:
    raise GcloudError(
        f"{description} timed out after {GCLOUD_TIMEOUT_SECONDS} seconds."
    ) from e

  if result.returncode != 0:
    raise GcloudError(
        f"{description} failed (exit code {result.returncode}):"
        f" {_summarize_stderr(result.stderr)}"
    )
  try:
    items = json.loads(result.stdout)
  except json.JSONDecodeError as e:
    raise GcloudError(f"{description} did not return valid JSON.") from e
  if not isinstance(items, list):
    raise GcloudError(f"{description} did not return a JSON list.")
  if len(items) == GCLOUD_PAGE_SIZE:
    print(
        f"WARNING: {description} returned exactly {GCLOUD_PAGE_SIZE} items,"
        " one full page, so the list may be incomplete.",
        file=sys.stderr,
    )
  return items


def fetch_and_filter_db_resources(
    organization_id: str, location: str = DEFAULT_LOCATION
) -> DBResourcesStore:
  """Fetches all FWs & CCs in one pass, filtering BUILT_IN and keeping CUSTOM."""
  raw_fws = run_gcloud_list("frameworks", organization_id, location)
  raw_ccs = run_gcloud_list("cloud-controls", organization_id, location)

  frameworks_by_id: dict[str, dict[str, Any]] = {}
  underlying_db_cc_ids: set[str] = set()

  for fw in raw_fws:
    fw_id = fw.get("name", "").split("/")[-1]
    if not fw_id:
      continue
    is_builtin = fw_id.startswith("builtin-")
    fw_item = dict(fw)

    if is_builtin:
      categories = fw_item.get("category", [])
      if (
          "ASSURED_WORKLOADS" not in categories
          and fw_id not in _EXTRA_BUILTIN_FRAMEWORK_IDS
      ):
        continue
      for cc_ref in fw_item.get("cloudControlDetails", []):
        ref_id = cc_ref.get("name", "").split("/")[-1]
        if ref_id:
          underlying_db_cc_ids.add(ref_id)
    else:
      # Keep all Organization Custom Frameworks
      pass

    frameworks_by_id[fw_id] = fw_item

  cloud_controls_by_id: dict[str, dict[str, Any]] = {}
  for cc in raw_ccs:
    cc_id = cc.get("name", "").split("/")[-1]
    if not cc_id:
      continue
    is_builtin = cc_id.startswith("builtin-")
    cc_item = dict(cc)

    if is_builtin and cc_id not in underlying_db_cc_ids:
      continue

    cloud_controls_by_id[cc_id] = cc_item

  return DBResourcesStore(
      last_synced_epoch=time.time(),
      organization_id=organization_id,
      frameworks=frameworks_by_id,
      cloud_controls=cloud_controls_by_id,
      location=location,
  )


def _cache_file_name(organization_id: str, location: str) -> str:
  """Returns the cache file name; `global` keeps the name without a suffix."""
  if location == DEFAULT_LOCATION:
    return f"db_resources_cache_{organization_id}.json"
  return f"db_resources_cache_{organization_id}_{location}.json"


def load_db_resources(
    organization_id: str,
    cache_dir: str = DEFAULT_CACHE_DIR,
    refresh_cache: bool = False,
    location: str = DEFAULT_LOCATION,
) -> DBResourcesStore:
  """Loads DB BUILT_IN + org CUSTOM resources from the session cache or gcloud."""
  organization_id = normalize_organization_id(organization_id)
  location = normalize_location(location)
  cache_file = pathlib.Path(cache_dir) / _cache_file_name(
      organization_id, location
  )

  if not refresh_cache and cache_file.exists():
    loaded = DBResourcesStore.from_dict(json.loads(cache_file.read_text()))
    if (
        loaded.location == location
        and loaded.frameworks
        and loaded.cloud_controls
    ):
      return loaded

  store = fetch_and_filter_db_resources(organization_id, location)
  cache_file.parent.mkdir(parents=True, exist_ok=True)
  cache_file.write_text(store.to_json())
  return store


def main() -> None:
  parser = argparse.ArgumentParser(description="Load Data Boundary Resources")
  parser.add_argument(
      "-o", "--organization_id", required=True, help="GCP Organization ID"
  )
  parser.add_argument(
      "--output_path",
      required=True,
      help=(
          "Path to save the loaded database of DB frameworks and cloud"
          " controls."
      ),
  )
  parser.add_argument(
      "--location",
      default=DEFAULT_LOCATION,
      help=(
          "Location ID from the list of supported locations (default:"
          f" {DEFAULT_LOCATION})."
      ),
  )
  parser.add_argument(
      "--cache_dir",
      default=DEFAULT_CACHE_DIR,
      help="Directory to store per-session caches.",
  )
  parser.add_argument(
      "--refresh_cache",
      action="store_true",
      help="Force a refresh from gcloud even if a cache file exists.",
  )
  args = parser.parse_args()

  try:
    store = load_db_resources(
        args.organization_id, args.cache_dir, args.refresh_cache, args.location
    )
  except (GcloudError, ValueError) as e:
    print(f"ERROR: {e}", file=sys.stderr)
    sys.exit(1)

  out_path = pathlib.Path(args.output_path)
  out_path.parent.mkdir(parents=True, exist_ok=True)
  out_path.write_text(store.to_json())
  print(
      f"Successfully loaded and saved {len(store.frameworks)} frameworks and"
      f" {len(store.cloud_controls)} cloud controls to {args.output_path}"
  )


if __name__ == "__main__":
  main()
db_resources_loader_test.py 27.1 KB
#!/usr/bin/env python3
"""Unit tests for the gcloud-backed db_resources_loader."""

from __future__ import annotations

import contextlib
import importlib.util
import io
import json
import os
import pathlib
import subprocess
import sys
import tempfile
import time
import unittest
from unittest import mock

sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import db_resources_loader  # pylint: disable=g-import-not-at-top


def _completed(
    stdout: str = "", stderr: str = "", returncode: int = 0
) -> subprocess.CompletedProcess[str]:
  return subprocess.CompletedProcess(
      args=["gcloud"], returncode=returncode, stdout=stdout, stderr=stderr
  )


_FRAMEWORKS = [
    # Builtin AW
    {
        "name": "organizations/123/locations/global/frameworks/builtin-fw-aw",
        "category": ["ASSURED_WORKLOADS", "XYZ"],
        "cloudControlDetails": [{
            "name": (
                "organizations/123/locations/global/cloudControls/"
                "builtin-cc-aw-1"
            )
        }],
    },
    # Builtin Not-AW
    {
        "name": (
            "organizations/123/locations/global/frameworks/builtin-fw-notaw"
        ),
        "category": ["OTHER"],
    },
    # Custom Framework
    {"name": "organizations/123/locations/global/frameworks/custom-fw-1"},
]
_CLOUD_CONTROLS = [
    # Builtin referenced in AW framework
    {
        "name": (
            "organizations/123/locations/global/cloudControls/builtin-cc-aw-1"
        )
    },
    # Builtin NOT referenced in AW framework
    {
        "name": (
            "organizations/123/locations/global/cloudControls/builtin-cc-not-aw"
        )
    },
    # Custom CC
    {"name": "organizations/123/locations/global/cloudControls/custom-cc-1"},
]


def _fake_gcloud(command, **unused_kwargs):
  """Stands in for `subprocess.run` with canned `gcloud ... list` output."""
  kind = command[2]
  payload = {"frameworks": _FRAMEWORKS, "cloud-controls": _CLOUD_CONTROLS}[kind]
  return _completed(stdout=json.dumps(payload))


class RunGcloudListTest(unittest.TestCase):

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_runs_expected_gcloud_command_and_parses_json(self, mock_run):
    mock_run.return_value = _completed(
        stdout=json.dumps([{"name": "fw-1"}, {"name": "fw-2"}])
    )

    res = db_resources_loader.run_gcloud_list("frameworks", "123")

    self.assertEqual(res, [{"name": "fw-1"}, {"name": "fw-2"}])
    mock_run.assert_called_once()
    self.assertEqual(
        mock_run.call_args.args[0],
        [
            "gcloud",
            "compliance-manager",
            "frameworks",
            "list",
            "--organization=123",
            "--location=global",
            "--page-size=1000",
            "--format=json",
            "--quiet",
        ],
    )
    kwargs = mock_run.call_args.kwargs
    self.assertIs(kwargs["stdin"], subprocess.DEVNULL)
    self.assertTrue(kwargs["capture_output"])
    self.assertFalse(kwargs["check"])
    self.assertEqual(
        kwargs["timeout"], db_resources_loader.GCLOUD_TIMEOUT_SECONDS
    )

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_passes_the_requested_location(self, mock_run):
    mock_run.return_value = _completed(stdout="[]")

    db_resources_loader.run_gcloud_list("frameworks", "123", "europe-west1")

    command = mock_run.call_args.args[0]
    self.assertIn("--location=europe-west1", command)
    self.assertNotIn("--location=global", command)

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_warns_when_a_list_is_exactly_one_full_page(self, mock_run):
    page = db_resources_loader.GCLOUD_PAGE_SIZE
    for count, expect_warning in ((page - 1, False), (page, True)):
      with self.subTest(count=count):
        mock_run.return_value = _completed(
            stdout=json.dumps([{"name": f"cc-{i}"} for i in range(count)])
        )
        stderr = io.StringIO()

        with contextlib.redirect_stderr(stderr):
          items = db_resources_loader.run_gcloud_list("cloud-controls", "123")

        self.assertEqual(len(items), count)
        self.assertEqual("WARNING" in stderr.getvalue(), expect_warning)
        if expect_warning:
          self.assertIn("may be incomplete", stderr.getvalue())

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_cloud_controls_use_the_kebab_case_command_group(self, mock_run):
    mock_run.return_value = _completed(stdout="[]")

    self.assertEqual(
        db_resources_loader.run_gcloud_list("cloud-controls", "123"), []
    )

    self.assertEqual(
        mock_run.call_args.args[0][:4],
        ["gcloud", "compliance-manager", "cloud-controls", "list"],
    )

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_nonzero_exit_reports_only_the_error_line(self, mock_run):
    mock_run.return_value = _completed(
        returncode=1,
        stderr=(
            "Parsed [location] resource: organizations/123/locations/global\n"
            "ERROR: (gcloud.compliance-manager.frameworks.list)"
            " PERMISSION_DENIED: caller lacks permission\n"
            "- '@type': type.googleapis.com/google.rpc.DebugInfo\n"
            '  detail: "[ORIGINAL ERROR] generic::permission_denied: stack"\n'
        ),
    )

    with self.assertRaises(db_resources_loader.GcloudError) as ctx:
      db_resources_loader.run_gcloud_list("frameworks", "123")

    message = str(ctx.exception)
    self.assertIn("`gcloud compliance-manager frameworks list` failed", message)
    self.assertIn("exit code 1", message)
    self.assertIn("PERMISSION_DENIED: caller lacks permission", message)
    self.assertNotIn("ERROR:", message)
    self.assertNotIn("DebugInfo", message)
    self.assertNotIn("Parsed [location]", message)

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_nonzero_exit_without_error_line_uses_first_lines(self, mock_run):
    mock_run.return_value = _completed(
        returncode=2, stderr="one\ntwo\nthree\nfour\n"
    )

    with self.assertRaises(db_resources_loader.GcloudError) as ctx:
      db_resources_loader.run_gcloud_list("frameworks", "123")

    self.assertIn("one two three", str(ctx.exception))
    self.assertNotIn("four", str(ctx.exception))

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_long_error_line_is_truncated(self, mock_run):
    mock_run.return_value = _completed(
        returncode=1, stderr="ERROR: " + "x" * 5000
    )

    with self.assertRaises(db_resources_loader.GcloudError) as ctx:
      db_resources_loader.run_gcloud_list("frameworks", "123")

    self.assertLess(len(str(ctx.exception)), 1200)

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_missing_gcloud_cli(self, mock_run):
    mock_run.side_effect = FileNotFoundError("gcloud")

    with self.assertRaisesRegex(
        db_resources_loader.GcloudError, "gcloud CLI was not found"
    ):
      db_resources_loader.run_gcloud_list("frameworks", "123")

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_gcloud_that_cannot_be_executed(self, mock_run):
    mock_run.side_effect = PermissionError(13, "Permission denied", "gcloud")

    with self.assertRaisesRegex(
        db_resources_loader.GcloudError,
        "Could not run the gcloud CLI: .*Permission denied",
    ):
      db_resources_loader.run_gcloud_list("frameworks", "123")

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_timeout(self, mock_run):
    mock_run.side_effect = subprocess.TimeoutExpired(cmd="gcloud", timeout=1)

    with self.assertRaisesRegex(db_resources_loader.GcloudError, "timed out"):
      db_resources_loader.run_gcloud_list("cloud-controls", "123")

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_invalid_json(self, mock_run):
    mock_run.return_value = _completed(stdout="not json")

    with self.assertRaisesRegex(
        db_resources_loader.GcloudError, "did not return valid JSON"
    ):
      db_resources_loader.run_gcloud_list("frameworks", "123")

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_json_that_is_not_a_list(self, mock_run):
    mock_run.return_value = _completed(stdout='{"frameworks": []}')

    with self.assertRaisesRegex(
        db_resources_loader.GcloudError, "did not return a JSON list"
    ):
      db_resources_loader.run_gcloud_list("frameworks", "123")


class NormalizeOrganizationIdTest(unittest.TestCase):

  def test_accepts_digits_and_resource_name_form(self):
    for raw in ("123", " 123\n", "organizations/123"):
      with self.subTest(raw=raw):
        self.assertEqual(
            db_resources_loader.normalize_organization_id(raw), "123"
        )

  def test_rejects_anything_that_is_not_a_numeric_id(self):
    for raw in (
        "",
        "abc",
        "organizations/",
        "organizations/abc",
        "12 3",
        "123 --project=other",
        "--organization=123",
        "123/../../etc",
        "folders/123",
    ):
      with self.subTest(raw=raw):
        with self.assertRaises(ValueError):
          db_resources_loader.normalize_organization_id(raw)


class LocationsTest(unittest.TestCase):

  def test_shipped_file_is_well_formed(self):
    data = json.loads(
        db_resources_loader.LOCATIONS_FILE.read_text(encoding="utf-8")
    )
    entries = data["locations"]
    ids = [entry["id"] for entry in entries]

    self.assertEqual(
        data["default_location"], db_resources_loader.DEFAULT_LOCATION
    )
    self.assertIn(db_resources_loader.DEFAULT_LOCATION, ids)
    self.assertEqual(len(ids), len(set(ids)))
    for entry in entries:
      with self.subTest(location=entry["id"]):
        self.assertRegex(entry["id"], r"^[a-z][a-z0-9-]*$")
        # `prod-*` names are backend environment names that the API rejects.
        self.assertFalse(entry["id"].startswith("prod-"))
        self.assertTrue(entry["description"].strip())

  def test_load_locations_maps_every_id_to_its_description(self):
    data = json.loads(
        db_resources_loader.LOCATIONS_FILE.read_text(encoding="utf-8")
    )

    locations = db_resources_loader.load_locations()

    self.assertEqual(
        locations, {e["id"]: e["description"] for e in data["locations"]}
    )
    self.assertIn("australia-southeast1", locations)

  def test_load_locations_rejects_unusable_files(self):
    with tempfile.TemporaryDirectory() as tmp_dir:
      missing = pathlib.Path(tmp_dir, "missing.json")
      invalid = pathlib.Path(tmp_dir, "invalid.json")
      invalid.write_text("not json")
      wrong_shape = pathlib.Path(tmp_dir, "wrong_shape.json")
      wrong_shape.write_text(json.dumps({"locations": [{"id": "global"}]}))

      for path in (missing, invalid, wrong_shape):
        with self.subTest(path=path.name):
          with self.assertRaisesRegex(
              ValueError, "Could not read the supported locations"
          ):
            db_resources_loader.load_locations(path)

  def test_locations_file_is_found_next_to_a_linked_script(self):
    # A build system can link each script file on its own: the path the module
    # reports is then a link, and the real file is in another directory.
    with tempfile.TemporaryDirectory() as tmp_dir:
      real_dir = pathlib.Path(tmp_dir, "store")
      skill_dir = pathlib.Path(tmp_dir, "skill")
      real_dir.mkdir()
      (skill_dir / "scripts").mkdir(parents=True)
      (skill_dir / "assets").mkdir()
      real_script = real_dir / "db_resources_loader.py"
      real_script.write_bytes(
          pathlib.Path(db_resources_loader.__file__).read_bytes()
      )
      linked_script = skill_dir / "scripts" / "db_resources_loader.py"
      linked_script.symlink_to(real_script)
      spec = importlib.util.spec_from_file_location(
          "linked_db_resources_loader", linked_script
      )
      module = importlib.util.module_from_spec(spec)
      with mock.patch.dict(sys.modules, {spec.name: module}):
        spec.loader.exec_module(module)

      self.assertEqual(
          module.LOCATIONS_FILE, skill_dir / "assets" / "locations.json"
      )

  def test_normalize_location_accepts_exact_ids(self):
    for raw, expected in (
        ("global", "global"),
        (" us-east1\n", "us-east1"),
        ("europe-west1", "europe-west1"),
    ):
      with self.subTest(raw=raw):
        self.assertEqual(db_resources_loader.normalize_location(raw), expected)

  def test_normalize_location_rejects_everything_else(self):
    for raw in (
        "",
        "GLOBAL",
        "prod-us-central1",
        "us-east",
        "Sydney",
        "us-east1 --project=other",
        "europe-west1/../x",
    ):
      with self.subTest(raw=raw):
        with self.assertRaisesRegex(ValueError, "Unknown location"):
          db_resources_loader.normalize_location(raw)


class FetchAndFilterTest(unittest.TestCase):

  @mock.patch.object(db_resources_loader, "run_gcloud_list")
  def test_filters_builtin_resources_and_keeps_custom(self, mock_list):
    mock_list.side_effect = lambda kind, org, location: {
        "frameworks": _FRAMEWORKS,
        "cloud-controls": _CLOUD_CONTROLS,
    }[kind]

    store = db_resources_loader.fetch_and_filter_db_resources("123")

    self.assertEqual(
        [c.args for c in mock_list.call_args_list],
        [("frameworks", "123", "global"), ("cloud-controls", "123", "global")],
    )
    self.assertEqual(store.organization_id, "123")
    self.assertEqual(store.location, "global")
    self.assertIn("builtin-fw-aw", store.frameworks)
    self.assertNotIn("builtin-fw-notaw", store.frameworks)
    self.assertIn("custom-fw-1", store.frameworks)

    self.assertIn("builtin-cc-aw-1", store.cloud_controls)
    self.assertNotIn("builtin-cc-not-aw", store.cloud_controls)
    self.assertIn("custom-cc-1", store.cloud_controls)

  @mock.patch.object(db_resources_loader, "run_gcloud_list")
  def test_keeps_builtin_hipaa_but_no_other_non_assured_workloads_builtin(
      self, mock_list
  ):
    hipaa = {
        "name": "organizations/123/locations/global/frameworks/builtin-hipaa",
        "category": ["INDUSTRY_DEFINED_STANDARD"],
    }
    other = {
        "name": (
            "organizations/123/locations/global/frameworks/"
            "builtin-other-standard"
        ),
        "category": ["INDUSTRY_DEFINED_STANDARD"],
    }
    mock_list.side_effect = lambda kind, org, location: {
        "frameworks": [hipaa, other],
        "cloud-controls": [],
    }[kind]

    store = db_resources_loader.fetch_and_filter_db_resources("123")

    # HIPAA has no `cloudControlDetails`: it loads without underlying controls.
    self.assertEqual(sorted(store.frameworks), ["builtin-hipaa"])
    self.assertEqual(store.cloud_controls, {})

  @mock.patch.object(db_resources_loader, "run_gcloud_list")
  def test_forwards_and_records_the_location(self, mock_list):
    mock_list.return_value = []

    store = db_resources_loader.fetch_and_filter_db_resources("123", "us-east1")

    self.assertEqual(store.location, "us-east1")
    self.assertEqual(
        [c.args for c in mock_list.call_args_list],
        [
            ("frameworks", "123", "us-east1"),
            ("cloud-controls", "123", "us-east1"),
        ],
    )

  @mock.patch.object(db_resources_loader, "run_gcloud_list")
  def test_gcloud_failure_propagates(self, mock_list):
    mock_list.side_effect = db_resources_loader.GcloudError("boom")

    with self.assertRaisesRegex(db_resources_loader.GcloudError, "boom"):
      db_resources_loader.fetch_and_filter_db_resources("123")


class LoadDBResourcesTest(unittest.TestCase):

  @mock.patch.object(db_resources_loader, "fetch_and_filter_db_resources")
  def test_uses_cache_unless_refresh_requested(self, mock_fetch):
    now = time.time()
    valid_store = db_resources_loader.DBResourcesStore(
        last_synced_epoch=now - 3600.0,
        organization_id="123",
        frameworks={"builtin-fw": {"type": "BUILT_IN"}},
        cloud_controls={"builtin-cc": {"type": "BUILT_IN"}},
    )

    with tempfile.TemporaryDirectory() as tmp_dir:
      cache_path = os.path.join(tmp_dir, "db_resources_cache_123.json")
      # Write a valid cache
      pathlib.Path(cache_path).write_text(valid_store.to_json())

      loaded = db_resources_loader.load_db_resources(
          organization_id="123", cache_dir=tmp_dir, refresh_cache=False
      )
      self.assertEqual(loaded.frameworks, valid_store.frameworks)
      mock_fetch.assert_not_called()

      # Now force refresh
      mock_fetch.return_value = db_resources_loader.DBResourcesStore(
          last_synced_epoch=now,
          organization_id="123",
          frameworks={"builtin-fw2": {"type": "BUILT_IN"}},
          cloud_controls={"builtin-cc2": {"type": "BUILT_IN"}},
      )
      loaded2 = db_resources_loader.load_db_resources(
          organization_id="123", cache_dir=tmp_dir, refresh_cache=True
      )
      self.assertIn("builtin-fw2", loaded2.frameworks)
      mock_fetch.assert_called_once_with("123", "global")

  @mock.patch.object(db_resources_loader, "fetch_and_filter_db_resources")
  def test_incomplete_cache_is_refetched(self, mock_fetch):
    mock_fetch.return_value = db_resources_loader.DBResourcesStore(
        last_synced_epoch=time.time(),
        organization_id="123",
        frameworks={"builtin-fw": {}},
        cloud_controls={"builtin-cc": {}},
    )

    with tempfile.TemporaryDirectory() as tmp_dir:
      incomplete = db_resources_loader.DBResourcesStore(
          last_synced_epoch=time.time(), organization_id="123"
      )
      pathlib.Path(tmp_dir, "db_resources_cache_123.json").write_text(
          incomplete.to_json()
      )

      loaded = db_resources_loader.load_db_resources("123", cache_dir=tmp_dir)

    self.assertIn("builtin-fw", loaded.frameworks)
    mock_fetch.assert_called_once_with("123", "global")

  @mock.patch.object(db_resources_loader, "fetch_and_filter_db_resources")
  def test_non_global_location_uses_its_own_cache_file(self, mock_fetch):
    mock_fetch.return_value = db_resources_loader.DBResourcesStore(
        last_synced_epoch=time.time(),
        organization_id="123",
        frameworks={"custom-fw": {}},
        cloud_controls={"custom-cc": {}},
        location="europe-west1",
    )

    with tempfile.TemporaryDirectory() as tmp_dir:
      store = db_resources_loader.load_db_resources(
          "123", cache_dir=tmp_dir, location="europe-west1"
      )

      self.assertEqual(store.location, "europe-west1")
      self.assertEqual(
          os.listdir(tmp_dir), ["db_resources_cache_123_europe-west1.json"]
      )
      mock_fetch.assert_called_once_with("123", "europe-west1")

      # A second call is served from that file.
      again = db_resources_loader.load_db_resources(
          "123", cache_dir=tmp_dir, location="europe-west1"
      )
      self.assertEqual(again.location, "europe-west1")
      mock_fetch.assert_called_once()

  @mock.patch.object(db_resources_loader, "fetch_and_filter_db_resources")
  def test_cache_file_without_a_location_counts_as_global(self, mock_fetch):
    legacy = {
        "last_synced_epoch": 1.0,
        "organization_id": "123",
        "frameworks": {"fw": {}},
        "cloud_controls": {"cc": {}},
    }

    with tempfile.TemporaryDirectory() as tmp_dir:
      pathlib.Path(tmp_dir, "db_resources_cache_123.json").write_text(
          json.dumps(legacy)
      )

      loaded = db_resources_loader.load_db_resources("123", cache_dir=tmp_dir)

    self.assertEqual(loaded.location, "global")
    self.assertIn("fw", loaded.frameworks)
    mock_fetch.assert_not_called()

  @mock.patch.object(db_resources_loader, "fetch_and_filter_db_resources")
  def test_cache_of_another_location_is_not_reused(self, mock_fetch):
    mock_fetch.return_value = db_resources_loader.DBResourcesStore(
        last_synced_epoch=time.time(),
        organization_id="123",
        frameworks={"fw-global": {}},
        cloud_controls={"cc-global": {}},
    )

    with tempfile.TemporaryDirectory() as tmp_dir:
      # The file with the `global` name holds the catalog of another location.
      other = db_resources_loader.DBResourcesStore(
          last_synced_epoch=time.time(),
          organization_id="123",
          frameworks={"fw-us": {}},
          cloud_controls={"cc-us": {}},
          location="us",
      )
      pathlib.Path(tmp_dir, "db_resources_cache_123.json").write_text(
          other.to_json()
      )

      loaded = db_resources_loader.load_db_resources("123", cache_dir=tmp_dir)

    self.assertEqual(loaded.location, "global")
    self.assertIn("fw-global", loaded.frameworks)
    mock_fetch.assert_called_once_with("123", "global")

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_fetches_through_gcloud_and_writes_cache(self, mock_run):
    mock_run.side_effect = _fake_gcloud

    with tempfile.TemporaryDirectory() as tmp_dir:
      store = db_resources_loader.load_db_resources(
          "organizations/123", cache_dir=tmp_dir
      )

      self.assertEqual(
          [c.args[0][2] for c in mock_run.call_args_list],
          ["frameworks", "cloud-controls"],
      )
      self.assertEqual(
          sorted(store.frameworks), ["builtin-fw-aw", "custom-fw-1"]
      )
      self.assertEqual(
          sorted(store.cloud_controls), ["builtin-cc-aw-1", "custom-cc-1"]
      )
      cache_file = pathlib.Path(tmp_dir, "db_resources_cache_123.json")
      self.assertTrue(cache_file.exists())

      # A second call is served from the cache without invoking gcloud.
      mock_run.reset_mock()
      again = db_resources_loader.load_db_resources("123", cache_dir=tmp_dir)
      mock_run.assert_not_called()
      self.assertEqual(again.frameworks, store.frameworks)

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_invalid_organization_id_never_reaches_gcloud(self, mock_run):
    with tempfile.TemporaryDirectory() as tmp_dir:
      with self.assertRaises(ValueError):
        db_resources_loader.load_db_resources("../../x", cache_dir=tmp_dir)

    mock_run.assert_not_called()

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_unknown_location_never_reaches_gcloud(self, mock_run):
    with tempfile.TemporaryDirectory() as tmp_dir:
      with self.assertRaisesRegex(ValueError, "Unknown location"):
        db_resources_loader.load_db_resources(
            "123", cache_dir=tmp_dir, location="prod-us-central1"
        )

    mock_run.assert_not_called()


class MainTest(unittest.TestCase):

  def _run_main(self, argv):
    stdout, stderr = io.StringIO(), io.StringIO()
    with mock.patch.object(sys, "argv", ["db_resources_loader.py", *argv]):
      with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(
          stderr
      ):
        try:
          db_resources_loader.main()
          exit_code = 0
        except SystemExit as e:
          exit_code = e.code
    return exit_code, stdout.getvalue(), stderr.getvalue()

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_writes_output_file(self, mock_run):
    mock_run.side_effect = _fake_gcloud

    with tempfile.TemporaryDirectory() as tmp_dir:
      out_path = os.path.join(tmp_dir, "out", "loaded.json")
      exit_code, stdout, _ = self._run_main([
          "-o",
          "123",
          "--output_path",
          out_path,
          "--cache_dir",
          os.path.join(tmp_dir, "cache"),
      ])

      self.assertEqual(exit_code, 0)
      self.assertIn("Successfully loaded and saved 2 frameworks", stdout)
      written = json.loads(pathlib.Path(out_path).read_text())
      self.assertEqual(written["organization_id"], "123")
      self.assertEqual(written["location"], "global")
      self.assertIn("builtin-fw-aw", written["frameworks"])
      self.assertIn("builtin-cc-aw-1", written["cloud_controls"])

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_location_flag_selects_the_location(self, mock_run):
    mock_run.side_effect = _fake_gcloud

    with tempfile.TemporaryDirectory() as tmp_dir:
      out_path = os.path.join(tmp_dir, "loaded.json")
      exit_code, _, _ = self._run_main([
          "-o",
          "123",
          "--output_path",
          out_path,
          "--cache_dir",
          os.path.join(tmp_dir, "cache"),
          "--location",
          "us-east1",
      ])

      self.assertEqual(exit_code, 0)
      written = json.loads(pathlib.Path(out_path).read_text())
      self.assertEqual(written["location"], "us-east1")
      self.assertEqual(
          os.listdir(os.path.join(tmp_dir, "cache")),
          ["db_resources_cache_123_us-east1.json"],
      )

    self.assertEqual(mock_run.call_count, 2)
    for call in mock_run.call_args_list:
      self.assertIn("--location=us-east1", call.args[0])

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_gcloud_failure_exits_nonzero_with_message(self, mock_run):
    mock_run.return_value = _completed(
        returncode=1, stderr="ERROR: (gcloud) API not enabled"
    )

    with tempfile.TemporaryDirectory() as tmp_dir:
      out_path = os.path.join(tmp_dir, "loaded.json")
      exit_code, stdout, stderr = self._run_main([
          "-o",
          "123",
          "--output_path",
          out_path,
          "--cache_dir",
          tmp_dir,
      ])

      self.assertEqual(exit_code, 1)
      self.assertEqual(stdout, "")
      self.assertIn("ERROR: ", stderr)
      self.assertIn("API not enabled", stderr)
      self.assertNotIn("Traceback", stderr)
      self.assertFalse(os.path.exists(out_path))

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_location_rejected_by_the_api_is_reported_by_name(self, mock_run):
    mock_run.return_value = _completed(
        returncode=1,
        stderr=(
            "ERROR: (gcloud.compliance-manager.frameworks.list)"
            " PERMISSION_DENIED: Location eu is not found or access is"
            " unauthorized.\n"
        ),
    )

    with tempfile.TemporaryDirectory() as tmp_dir:
      out_path = os.path.join(tmp_dir, "loaded.json")
      exit_code, stdout, stderr = self._run_main([
          "-o",
          "123",
          "--output_path",
          out_path,
          "--cache_dir",
          tmp_dir,
          "--location",
          "eu",
      ])

      self.assertEqual(exit_code, 1)
      self.assertEqual(stdout, "")
      self.assertIn("Location eu is not found", stderr)
      self.assertNotIn("Traceback", stderr)
      # Neither an output file nor a cache file is left behind.
      self.assertEqual(os.listdir(tmp_dir), [])

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_location_that_is_not_in_the_list_exits_nonzero(self, mock_run):
    with tempfile.TemporaryDirectory() as tmp_dir:
      exit_code, _, stderr = self._run_main([
          "-o",
          "123",
          "--output_path",
          os.path.join(tmp_dir, "loaded.json"),
          "--cache_dir",
          tmp_dir,
          "--location",
          "prod-us-central1",
      ])

    self.assertEqual(exit_code, 1)
    self.assertIn("Unknown location 'prod-us-central1'", stderr)
    self.assertNotIn("Traceback", stderr)
    mock_run.assert_not_called()

  @mock.patch.object(db_resources_loader.subprocess, "run")
  def test_invalid_organization_id_exits_nonzero(self, mock_run):
    with tempfile.TemporaryDirectory() as tmp_dir:
      exit_code, _, stderr = self._run_main([
          "-o",
          "not-an-org",
          "--output_path",
          os.path.join(tmp_dir, "loaded.json"),
          "--cache_dir",
          tmp_dir,
      ])

    self.assertEqual(exit_code, 1)
    self.assertIn("Invalid organization ID", stderr)
    mock_run.assert_not_called()


if __name__ == "__main__":
  unittest.main()
db_search.py 1.8 KB
#!/usr/bin/env python3
import argparse
import json
import sys


def main():
  parser = argparse.ArgumentParser(
      description=(
          "Search the loaded DB resources for matching frameworks and cloud"
          " controls."
      )
  )
  parser.add_argument(
      "--resources_json", required=True, help="Path to loaded_db_resources.json"
  )
  parser.add_argument(
      "--query", required=True, help="Keyword to search for (case-insensitive)"
  )
  args = parser.parse_args()

  try:
    with open(args.resources_json, "r") as f:
      data = json.load(f)
  except PermissionError as e:
    print(f"ERROR: PERMISSION_DENIED: {e}", file=sys.stderr)
    sys.exit(1)
  except Exception as e:
    print(f"ERROR: Could not read {args.resources_json}: {e}", file=sys.stderr)
    sys.exit(1)

  query = args.query.lower()

  print(f"--- Search Results for '{args.query}' ---")

  frameworks = data.get("frameworks", {})
  matched_fws = []
  for fw_id, fw in frameworks.items():
    search_text = (
        f"{fw_id} {fw.get('displayName', '')} {fw.get('description', '')}"
        .lower()
    )
    if query in search_text:
      matched_fws.append((fw_id, fw.get("displayName", "")))

  print(f"\nFrameworks found ({len(matched_fws)}):")
  for fw_id, name in matched_fws:
    print(f" - ID: {fw_id} | Name: {name}")

  cloud_controls = data.get("cloud_controls", {})
  matched_ccs = []
  for cc_id, cc in cloud_controls.items():
    search_text = (
        f"{cc_id} {cc.get('displayName', '')} {cc.get('description', '')}"
        .lower()
    )
    if query in search_text:
      matched_ccs.append((cc_id, cc.get("displayName", "")))

  print(f"\nCloud Controls found ({len(matched_ccs)}):")
  for cc_id, name in matched_ccs:
    print(f" - ID: {cc_id} | Name: {name}")


if __name__ == "__main__":
  main()
db_search_test.py 3.8 KB
#!/usr/bin/env python3
"""Tests for db_search.py."""

import io
import json
import os
import sys
import tempfile
import unittest
from unittest import mock

sys.dont_write_bytecode = True
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import db_search  # pylint: disable=g-import-not-at-top


class DbSearchTest(unittest.TestCase):

  def setUp(self):
    super().setUp()
    self.test_data = {
        "frameworks": {
            "builtin-fw1": {
                "displayName": "Framework One",
                "description": "This is the first framework",
            },
            "builtin-hipaa": {
                "displayName": "HIPAA",
                "description": (
                    "Health Insurance Portability and Accountability Act"
                ),
            },
        },
        "cloud_controls": {
            "cc1": {
                "displayName": "Control One",
                "description": "First control",
            },
            "cc-health": {
                "displayName": "Health Control",
                "description": "Control for health data",
            },
        },
    }

    self.temp_dir = tempfile.TemporaryDirectory()
    self.json_path = os.path.join(self.temp_dir.name, "test_resources.json")
    with open(self.json_path, "w") as f:
      json.dump(self.test_data, f)

  def tearDown(self):
    self.temp_dir.cleanup()
    super().tearDown()

  def test_search_finds_matches(self):
    test_args = [
        "db_search.py",
        "--resources_json",
        self.json_path,
        "--query",
        "health",
    ]
    with mock.patch.object(sys, "argv", test_args):
      with mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
        db_search.main()
        output = mock_stdout.getvalue()

    self.assertIn("Search Results for 'health'", output)
    self.assertIn("ID: builtin-hipaa | Name: HIPAA", output)
    self.assertIn("ID: cc-health | Name: Health Control", output)
    self.assertNotIn("builtin-fw1", output)
    self.assertNotIn("cc1", output)

  def test_search_case_insensitive(self):
    test_args = [
        "db_search.py",
        "--resources_json",
        self.json_path,
        "--query",
        "HIPAA",
    ]
    with mock.patch.object(sys, "argv", test_args):
      with mock.patch("sys.stdout", new_callable=io.StringIO) as mock_stdout:
        db_search.main()
        output = mock_stdout.getvalue()

    self.assertIn("Search Results for 'HIPAA'", output)
    self.assertIn("ID: builtin-hipaa | Name: HIPAA", output)
    self.assertNotIn("builtin-fw1", output)
    self.assertNotIn("cc1", output)

  def test_search_missing_file(self):
    test_args = [
        "db_search.py",
        "--resources_json",
        "non_existent.json",
        "--query",
        "health",
    ]
    with mock.patch.object(sys, "argv", test_args):
      with mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr:
        with self.assertRaises(SystemExit) as cm:
          db_search.main()

        self.assertEqual(cm.exception.code, 1)
        output = mock_stderr.getvalue()
        self.assertIn("ERROR: Could not read non_existent.json", output)

  @mock.patch("builtins.open")
  def test_search_permission_error(self, mock_open):
    mock_open.side_effect = PermissionError("Permission denied")
    test_args = [
        "db_search.py",
        "--resources_json",
        self.json_path,
        "--query",
        "health",
    ]
    with mock.patch.object(sys, "argv", test_args):
      with mock.patch("sys.stderr", new_callable=io.StringIO) as mock_stderr:
        with self.assertRaises(SystemExit) as cm:
          db_search.main()

        self.assertEqual(cm.exception.code, 1)
        output = mock_stderr.getvalue()
        self.assertIn("ERROR: PERMISSION_DENIED", output)


if __name__ == "__main__":
  unittest.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