Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cloud-storage-bucket-architect@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin google-cloud-storage-bucket-architect v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install google-cloud-storage-bucket-architect

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

Download and extract to your repository:

.github/skills/google-cloud-storage-bucket-architect/

Extract the ZIP to .github/skills/ in your repo. The folder name must match google-cloud-storage-bucket-architect for Copilot to auto-discover it.

Skill Files (20)

SKILL.md 12.5 KB
---
name: google-cloud-storage-bucket-architect
description: >-
  Creates Cloud Storage on Google Cloud (also known colloquially as GCS)
  buckets. Analyzes the workload (sensitive data, media hosting, ingestion,
  web hosting, archiving, backup, logging, analytics, AI/ML, or
  general-purpose), validates
  project-level security settings, and designs a secure-by-default,
  cost-effective configuration (location, storage class, uniform bucket-level
  access, public access prevention, soft delete, lifecycle) before creating it.
  Use whenever a user wants to create, make, set up, provision, or spin up a
  bucket, or needs object storage for an app, service, pipeline, or dataset —
  even a "simple" or "default" bucket, or when bucket creation is one step in a
  larger workflow. Outputs or executes the creation via gcloud, the JSON/REST
  API, Terraform, or SDK client libraries (C++, Java, Python, Go). Don't use for
  anything other than creating new buckets — for uploads, downloads, access
  changes, or reconfiguring existing buckets, use google-cloud-storage-basics.
license: Apache-2.0
metadata:
  version: "1.1.0"
  publisher: google
  tags: "gcs, storage, architect, bucket-creation"
  category: Storage
  support_tier: primary
---

# Cloud Storage Bucket Architect

You are a Use-Case Driven Cloud Storage Bucket Architect agent on Google Cloud.
You analyze the user's workload, validate baseline project security settings,
draft a tailored secure-by-default architecture plan (UBLA enabled, CSEK
restricted, soft delete enabled, PAP enforced unless public access is required),
and output or execute the configuration in the user's preferred format.

> [!CAUTION]
>
> **CRITICAL: Never execute mutating commands, including bucket
> creation/update/deletion (e.g., `gcloud`, REST API calls), without first
> presenting the exact configuration/command and obtaining explicit confirmation
> from the user.** For Cloud Storage location questions, refer to
> [Storage Locations](https://cloud.google.com/storage/docs/locations).

## Attribution

Tag every Cloud Storage command you run or provide to the user. The tag
identifies only the skill and its version; it carries no user data. Do not use
attribution for SDK or Terraform snippets, and do not use `gcloud config set`:

*   **gcloud**: Prefix every `gcloud` invocation you execute or output
    (including project checks, bucket name checks, creation/update commands, and
    auxiliary `gcloud` commands—except `gcloud auth print-access-token` inside a
    REST `curl` command) inline with this exact append form:

    ```bash
    CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
    gcloud <command> [flags]
    ```

*   **REST (cURL)**: Set the `User-Agent` header verbatim:
    `User-Agent: gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)`

## Phase Summary Table

Phase                              | Inputs                 | Outputs                                              | Reference
:--------------------------------- | :--------------------- | :--------------------------------------------------- | :--------
**1. Preflight/Project Checks**    | Project ID             | Project security posture assessment                  | `references/phase_project_checks.md`
**2. Draft Bucket Create Plan**    | Use case, requirements | Bucket configuration plan & name availability status | `references/phase_draft_plan.md`
**3. Output Based on User Intent** | Plan, preferred format | Command or code snippet for bucket creation          | `references/phase_output.md`

## Workflow Execution

> [!IMPORTANT]
>
> **Present every applicable phase in one response, and DO NOT read reference
> files across separate tool-call rounds**: Even when the user asks for ONLY the
> final code/commands or forbids running `gcloud` commands, you **MUST** read
> all needed reference files in full in **one parallel batch** (all tool calls
> in one assistant message) in **Step 2** (never read Phase 1, Phase 2, Phase 3,
> or format files one round at a time). Then, in **Step 3**, present Phase 1,
> then Phase 2 (unless the user only asked to check project security settings),
> then Phase 3 if the user explicitly requested the final commands or code in
> their prompt, all in one response.

Follow this exact 3-step execution sequence for minimal round and token usage:

*   **Step 1**: Read `SKILL.md` in full.
*   **Step 2 (One Parallel Tool-Call Batch — All Reference File Reads + One
    Read-Only Shell Command, Unless Commands Are Explicitly Forbidden)**:

    1.  **Read All Needed Reference Files in Full in One Parallel Batch (No Line
        Ranges or Pagination)**: In this single batch, read every reference file
        needed for the entire response:
        *   `references/phase_project_checks.md` and
            `references/phase_draft_plan.md` (if the user only asks to check
            project security settings, read only
            `references/phase_project_checks.md`).
        *   The single primary `references/<use_case>.md` file that best matches
            the workload by default (read two use-case files only if the user
            explicitly asks to combine two distinct use cases; for a
            **general-purpose** bucket with no specialized workload, do **not**
            read any `<use_case>.md` file).
        *   If the prompt specifies an output format (`gcloud`, `REST`/`curl`,
            `Terraform`, or an SDK) or asks for commands/code, you **MUST** also
            read `references/phase_output.md` **AND** the format reference
            (`references/gcloud.md`, `references/rest.md`,
            `references/terraform.md`, or `references/sdk.md` +
            `references/sdk_<lang>.md`—never read `sdk.md` for
            `gcloud`/`REST`/`Terraform` tasks) in this **same batch**.
    2.  **Run the Read-Only Pre-Flight Checks as One Shell Command in the Same
        Batch**: If the user explicitly forbade running `gcloud`/all commands,
        run none of the 5 checks. Otherwise (note: *"Do not execute bucket
        creation or modification commands"* still requires running read-only
        checks!), run all 5 read-only Phase 1 & Phase 2 checks in **that same
        batch** as a single shell command, but skip the 4 project checks if no
        project ID was given. If no bucket name was given, invent
        `<project-id>-<use-case>-<6-char-hex>` now (drop `<project-id>-` if no
        project ID was given) and use it in your output (and in the 5th command
        when the checks run). **No project ID (any path):** never run a command
        against a guessed, placeholder (including `<PROJECT_ID>`), or
        `gcloud config` default project, and use `<PROJECT_ID>` in any commands
        or code you output; report the 4 project checks as `⚠️ Undetermined` (no
        project ID) and ask for the ID; unless the user explicitly forbade
        running commands, run the 4 checks once the user provides it, before
        executing anything in that project. Write each command on a single line
        so quotes are never split:

        ```bash
        echo "=== TLS 1.2 ==="; CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" gcloud org-policies describe constraints/gcp.restrictTLSVersion --project=<PROJECT_ID> --effective --format=json 2>&1 || true
        echo "=== HTTPS Only ==="; CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" gcloud org-policies describe constraints/storage.secureHttpTransport --project=<PROJECT_ID> --effective --format=json 2>&1 || true
        echo "=== Restrict HMAC ==="; CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" gcloud org-policies describe constraints/storage.restrictAuthTypes --project=<PROJECT_ID> --effective --format=json 2>&1 || true
        echo "=== Project Liens ==="; CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" gcloud alpha resource-manager liens list --project=<PROJECT_ID> --format=json 2>&1 || true
        echo "=== Bucket Name ==="; CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" gcloud storage buckets describe gs://<BUCKET_NAME> --format=json 2>&1 || true
        ```

*   **Step 3 (One Response Containing Every Applicable Phase)**:

    1.  **Phase 1 (Preflight/Project Checks)**: Present the 4 project security
        checks per `references/phase_project_checks.md`.
    2.  **Phase 2 (Draft Bucket Create Plan)**: Draft the configuration plan per
        `references/phase_draft_plan.md` (including bucket name availability).
        Skip Phase 2 (and Phase 3) if the user only asked to check project
        security settings. If the user did not explicitly request the final
        commands or code in their prompt, end your response with the plan's
        confirmation question (also ask for their preferred output format if
        they named none), and continue to Phase 3 only after they confirm.
    3.  **Phase 3 (Output Based on User Intent)**: Generate the final output per
        `references/phase_output.md` without executing any commands (for
        `gcloud`/`REST`, offer to execute, and execute only after explicit,
        affirmative confirmation; for `Terraform`/`SDK`, display the snippet for
        integration).

## Error Handling

Problem                                    | Cause                    | Fix
:----------------------------------------- | :----------------------- | :--
Execution failure during creation          | Network/permission error | Report error details and suggest manual execution with the generated command.
Creation fails with 409 / "already exists" | Bucket name taken        | Propose a different name, verify availability, and regenerate the output.

## References

### Phases

*   [Preflight / Project Checks](references/phase_project_checks.md):
    Project-level security verification and status mapping.
*   [Draft Bucket Create Plan](references/phase_draft_plan.md): Workload
    assessment, secure defaults, and architecture plan generation.
*   [Output Based on User Intent](references/phase_output.md): Final
    command/code generation and execution confirmation workflows.

### Bucket Use Cases (Read Only the Primary Matching File by Default; None for General-Purpose Buckets)

*   [Sensitive Data & Compliance](references/sensitive_data.md): Regulated data
    (PII, HIPAA, finance) with CMEK, restricted CSEK, and IP filtering.
*   [Media Hosting & CDN](references/media_hosting.md): Public or
    application-gated video/media asset hosting (including hosting
    user-generated video content), live streaming, VOD, and CDN origin config.
*   [Direct UGC Ingestion](references/ugc_ingestion.md): Browser/client-side
    direct uploads via `PUT` Signed URLs, CORS for uploads, and ingestion
    buckets.
*   [Static Website Hosting](references/static_website.md): Website hosting,
    public read access, and index/error page handling.
*   [Long-Term Archive & Compliance](references/archiving_compliance.md):
    Multi-year regulatory retention (including multi-year financial/compliance
    audit logs), WORM (Object Lock), Bucket Lock, and `ARCHIVE` storage.
*   [Backup & Disaster Recovery](references/backup_dr.md): Immutable database/VM
    backups, snapshots, regional + STS replication, and soft delete.
*   [Log Storage](references/log_storage.md): Operational application, audit,
    and VPC flow logs, tiering/lifecycle management, and monitoring/inventory.
*   [AI & Machine Learning](references/storage_for_ai.md): High-throughput
    training/checkpointing/streaming, Rapid Cache, and zonal `RAPID` buckets.

### Provisioning & Output Formats

*   [gcloud CLI Reference](references/gcloud.md): `gcloud storage` commands.
*   [REST API Reference](references/rest.md): JSON API payloads and `curl`.
*   [Terraform Reference](references/terraform.md): `google_storage_bucket` HCL.
*   [SDK Client Libraries Overview](references/sdk.md): Shared SDK concepts and
    version gates (read together with one language guide:
    [C++](references/sdk_cpp.md), [Go](references/sdk_go.md),
    [Java](references/sdk_java.md), or [Python](references/sdk_python.md)).
references/
archiving_compliance.md 6.2 KB
# Long-Term Archive & Regulatory Compliance

This reference document outlines the secure-by-default, cost-effective
configuration mapping and architecture recommendation for Cloud Storage buckets
optimized for long-term archiving and regulatory compliance mandates.

## Description

The user is retaining data (such as financial statements, medical records, tax
documents, or corporate legal logs) for legal or regulatory requirements
(typically 7-10+ years). The data is accessed very infrequently, but its
integrity must be guaranteed, and it must be protected against accidental or
premature deletion (immutability).

## Bucket Configuration Plan Mapping

The following table maps the Long-Term Archive & Compliance use case to specific
Cloud Storage features and details their recommendation status. See
[Official Documentation References](#official-documentation-references) below
for feature links if further reference is needed (do not fetch routinely).

Cloud Storage Feature / Setting        | Status             | Recommendations & Implementation Details
:------------------------------------- | :----------------- | :---------------------------------------
**Storage Class**                      | Highly Recommended | **Coldline** or **Archive** Storage Class.<br><br>Archive storage offers the lowest cost per gigabyte, ideal for data kept as a legal requirement that may never be read. Beware of high retrieval and early deletion fees (e.g. minimum 365 days retention for Archive).
**Bucket Type**                        | Highly Recommended | **Regional** or **Dual-Regional** bucket configuration. Multi-regional configurations should be avoided if national laws mandate physical data residency boundaries.
**Signed URLs**                        | Good to Have       | Gated write access only; restrict public URLs entirely.
**Uniform Bucket-Level Access (UBLA)** | **Required**       | **Must be enabled.** Standardizes administrative access control across the bucket.
**Public Access Prevention (PAP)**     | **Required**       | **Must be enforced.** Disallows public read permissions.
**Encryption (CMEK)**                  | Highly Recommended | **CMEK via KMS** is standard for compliance workloads. Use KMS Autokey for automated keys, or prompt the user for key paths.
**IP Filtering**                       | Good to Have       | Limit bucket administration endpoints exclusively to verified corporate office IPs or secure VPN ranges.
**Retention Policy (WORM)**            | Good to Have       | Configure Cloud Storage **Bucket Lock** or **Object Lock** to enforce immutability (Write Once, Read Many).<br><br>**Warning: Locking the retention policy is irreversible. Objects cannot be deleted by anyone, including owners or Google Cloud Support, until the retention period expires.**
**Object Lifecycle Management (OLM)**  | Highly Recommended | Configure lifecycle rules to automatically purge expired archive records (e.g. delete after 7 years / 2555 days) to mitigate liability and storage costs.
**Labels & Tagging**                   | Highly Recommended | Apply governance metadata tags (e.g. `{"compliance-type": "hipaa"}` or `{"retention-period": "7-years"}`) for cost-center and policy tracking.
**Storage Intelligence**               | Good to Have       | Use Storage Insights Inventory Reports to track record age, verify compliance counts, and manage data wipes.
**Regional Endpoints**                 | Highly Recommended | Enforce localized control planes to satisfy sovereignty requirements where data operations must stay within regional borders.
**Storage Transfer Service (STS)**     | Good to Have       | Use STS for inter-regional migrations, backup, or ITAR compliance transfers.
**SFTP**                               | Good to Have       | Implement secure SFTP transfers if legacy compliance networks or mainframes upload transaction logs directly.
**Cloud Logging**                      | Highly Recommended | Enable Cloud Storage Audit Logs (Data Access & Admin Activity) to maintain a complete, audit-safe record of data reads, writes, and config updates.
**Cloud Monitoring**                   | Good to Have       | Monitor capacity trends and set alert systems to fire if unexpected large drops in object count or volume occur.

## Key Pre-Deployment Questions to Ask:

1.  **What specific compliance standard governs this data (e.g., HIPAA, SEC Rule
    17a-4, GDPR)?**
2.  **Do you require an irreversible compliance lock (Bucket/Object Lock)?**
    *   *If Yes*: Explain that once locked, even the Project Administrator
        cannot shorten the policy or delete the data. Confirm if they wish to
        proceed with "Locked" or "Unlocked" status.
3.  **What is the exact data retention duration (e.g., 7 years)?**

## Official Documentation References

Feature / Topic             | Documentation Link
:-------------------------- | :-----------------
Storage Classes             | https://cloud.google.com/storage/docs/storage-classes
Locations                   | https://cloud.google.com/storage/docs/locations
Signed URLs                 | https://cloud.google.com/storage/docs/access-control/signed-urls
Uniform Bucket-Level Access | https://cloud.google.com/storage/docs/uniform-bucket-level-access
Public Access Prevention    | https://cloud.google.com/storage/docs/public-access-prevention
CMEK                        | https://cloud.google.com/storage/docs/encryption/customer-managed-keys
Bucket IP Filtering         | https://cloud.google.com/storage/docs/ip-filtering-overview
Bucket Lock                 | https://cloud.google.com/storage/docs/bucket-lock
Object Lock                 | https://cloud.google.com/storage/docs/object-lock
Lifecycle Management        | https://cloud.google.com/storage/docs/lifecycle
Bucket Labels               | https://cloud.google.com/storage/docs/using-bucket-labels
Inventory Reports           | https://cloud.google.com/storage/docs/insights/inventory-reports
Storage Transfer Service    | https://cloud.google.com/storage-transfer/docs/overview
SFTP Gateway (SFTP)         | https://cloud.google.com/integration-connectors/docs/connectors/sftp/configure
Cloud Audit Logging         | https://cloud.google.com/storage/docs/audit-logging
Cloud Monitoring            | https://cloud.google.com/storage/docs/monitoring
backup_dr.md 6.8 KB
# Backup and Disaster Recovery

This reference document outlines the secure-by-default, highly durable
configuration mapping and architecture recommendation for Cloud Storage buckets
serving as the storage backend for database dumps, virtual machine snapshots,
and system backups.

## Description

The user is storing mission-critical backups and disaster recovery data. This
workload requires high durability, protection against ransomware and accidental
deletion (WORM/Soft Delete), and automated cross-region replication to maintain
recovery objectives (RTO/RPO). Backups are typically written once and read
infrequently, but require rapid access when a restore is triggered.

## Bucket Configuration Plan Mapping

The following table maps the Backup and Disaster Recovery to specific Cloud
Storage features and details their recommendation status. See
[Official Documentation References](#official-documentation-references) below
for feature links if further reference is needed (do not fetch routinely).

Cloud Storage Feature / Setting        | Status             | Recommendations & Implementation Details
:------------------------------------- | :----------------- | :---------------------------------------
**Storage Class**                      | Highly Recommended | **Nearline**, **Coldline**, or **Archive** Storage Class.<br><br>Choose based on retention duration and restore probability. Nearline is ideal for daily/weekly backups (30-day minimum), Coldline for monthly archives (90-day minimum), and Archive for annual backups (365-day minimum).
**Bucket Type**                        | Highly Recommended | **Regional** bucket type. Combine with cross-bucket replication using Storage Transfer Service (STS) to replicate to a disaster recovery region.<br><br>*Note: Dual-Region or Multi-Region buckets are not recommended for backups due to higher cost and lack of flexibility. If the user requests dual-region (e.g. nam4), explicitly advise against it and recommend Regional + STS instead.*
**Signed URLs**                        | Not Recommended    | Typically not required for backup workloads.
**CORS**                               | Not Recommended    | Typically not required for backup workloads.
**Uniform Bucket-Level Access (UBLA)** | **Required**       | **Must be enabled.** Standardizes IAM permissions across the bucket, disabling legacy ACLs.
**Public Access Prevention (PAP)**     | **Required**       | **Must be enforced.** Disallows public access.
**Encryption (CMEK)**                  | Highly Recommended | **Customer-Managed Encryption Keys (CMEK)** via Cloud KMS.<br><br>Use KMS Autokey for automated provisioning, or guide the user to assign a key.
**Soft Delete**                        | Highly Recommended | **Enabled (default 7 days).** Essential baseline defense to recover from accidental deletions by scripts or administrative errors.
**Object Versioning**                  | Good to Have       | Suggest as an alternative to Soft Delete for recovery.
**Data Retention (WORM)**              | Good to Have       | Prompt the user to configure a Retention Policy (Bucket Lock or Object Lock) if immutability is required for ransomware protection or compliance.<br><br>**Warning: Lock mode is permanent and irreversible.**
**IP Filtering**                       | Good to Have       | Restrict access exclusively to trusted corporate data center IPs or secure office perimeters.
**Object Lifecycle Management (OLM)**  | Not Recommended    | Start with the correct storage class. OLM is generally not recommended for transitioning backups unless specific lifecycle needs exist.
**Labels & Tagging**                   | Highly Recommended | **Mandatory** bucket-level tagging (e.g., `{"environment": "production"}` and `{"app": "core-db-backup"}`) to map and audit storage spend.
**Storage Intelligence**               | Good to Have       | Use Storage Insights to monitor backup volume growth and security status.
**Storage Transfer Service (STS)**     | Highly Recommended | Use STS for automated, secure cross-bucket replication to a secondary DR region to simplify disaster recovery.
**Cloud Logging**                      | Highly Recommended | Enable Cloud Logging for troubleshooting network timeouts or throughput bottlenecks during massive backup transfers.
**Cloud Monitoring**                   | Highly Recommended | Track API call counts and storage limits. Configure alerts to fire if a backup bucket registers zero write activity within 24 hours.

## Project-Level Security Checks & Recommendations

Before bucket creation, verify the following project-level configurations:

1.  **Restrict Sharing Org Policy**: Ensure
    `constraints/iam.allowedPolicyMemberDomains` is configured to restrict
    sharing outside of authorized organizational domains.
2.  **Access Transparency**: Ensure Access Transparency is enabled on the
    project to audit Google administrator access.
3.  **Location Org Policy**: Check `constraints/gcp.resourceLocations` to ensure
    bucket creation conforms to the organization's regional residency
    guidelines.
4.  **Cloud Audit Logging**: Ensure Cloud Audit Logging is enabled for the
    project to maintain an audit trail.

## Official Documentation References

Feature / Topic             | Documentation Link
:-------------------------- | :-----------------
Storage Classes             | https://cloud.google.com/storage/docs/storage-classes
Locations                   | https://cloud.google.com/storage/docs/locations
Signed URLs                 | https://cloud.google.com/storage/docs/access-control/signed-urls
CORS                        | https://cloud.google.com/storage/docs/using-cors
Uniform Bucket-Level Access | https://cloud.google.com/storage/docs/uniform-bucket-level-access
Public Access Prevention    | https://cloud.google.com/storage/docs/public-access-prevention
CMEK                        | https://cloud.google.com/storage/docs/encryption/customer-managed-keys
KMS Autokey                 | https://cloud.google.com/kms/docs/autokey-overview
Soft Delete                 | https://cloud.google.com/storage/docs/soft-delete
Object Versioning           | https://cloud.google.com/storage/docs/object-versioning
Bucket Lock                 | https://cloud.google.com/storage/docs/bucket-lock
Object Lock                 | https://cloud.google.com/storage/docs/object-lock
Bucket IP Filtering         | https://cloud.google.com/storage/docs/ip-filtering-overview
Lifecycle Management        | https://cloud.google.com/storage/docs/lifecycle
Bucket Labels               | https://cloud.google.com/storage/docs/using-bucket-labels
Storage Insights            | https://cloud.google.com/storage/docs/insights/inventory-reports
Storage Transfer Service    | https://cloud.google.com/storage-transfer/docs/overview
Cloud Audit Logging         | https://cloud.google.com/storage/docs/audit-logging
Cloud Monitoring            | https://cloud.google.com/storage/docs/monitoring
gcloud.md 17.9 KB
# gcloud Command Generation Guide

> [!IMPORTANT]
>
> **DO NOT EXECUTE THESE COMMANDS AUTOMATICALLY.** Present generated commands to
> the user for confirmation and execute them in Phase 3 only if explicit
> confirmation is granted by the user.

This guide translates a **Draft Bucket Creation Plan** (Phase 2) into
`gcloud storage` commands.

## Official Documentation References

*   [gcloud storage buckets create](https://cloud.google.com/sdk/gcloud/reference/storage/buckets/create)
*   [gcloud storage buckets update](https://cloud.google.com/sdk/gcloud/reference/storage/buckets/update)
*   [gcloud storage buckets add-iam-policy-binding](https://cloud.google.com/sdk/gcloud/reference/storage/buckets/add-iam-policy-binding)
*   [gcloud storage objects update](https://cloud.google.com/sdk/gcloud/reference/storage/objects/update)
*   [gcloud storage cp](https://cloud.google.com/sdk/gcloud/reference/storage/cp)
*   [gcloud storage buckets notifications create](https://cloud.google.com/sdk/gcloud/reference/storage/buckets/notifications/create)
*   [gcloud storage buckets anywhere-caches create](https://cloud.google.com/sdk/gcloud/reference/storage/buckets/anywhere-caches/create)
*   [Create zonal buckets](https://cloud.google.com/storage/docs/rapid/create-zonal-buckets)
*   [Domain-named bucket verification](https://cloud.google.com/storage/docs/domain-name-verification)
*   [Host a static website](https://cloud.google.com/storage/docs/hosting-static-website)

--------------------------------------------------------------------------------

> [!CAUTION]
>
> **DO NOT HALLUCINATE GCLOUD FLAGS.** Ground all `gcloud storage` commands and
> flags strictly in the **Translation Mapping Table** and **Helper Configuration
> Templates** below—do **not** run `gcloud ... --help` or documentation searches
> for any feature already covered in this guide. Never guess or invent flag
> names (e.g., use `--versioning`, not `--enable-versioning`). Only if the user
> explicitly requests a specialized Cloud Storage CLI setting absent from the
> table below (and has not forbidden running commands), verify the exact flag
> via `--help` or the official documentation linked above before presenting it.

## Translation Mapping Table

Prefer combining supported creation flags into a single
`gcloud storage buckets create` command, and combining `update`-only settings
(labels, versioning, CORS, website config, usage logging, or retention lock)
into a single `gcloud storage buckets update` command.

Draft Plan Field / Setting         | gcloud CLI Flag / Subcommand           | Notes / Full Command Syntax
:--------------------------------- | :------------------------------------- | :--------------------------
**Attribution**                    | `CLOUDSDK_METRICS_ENVIRONMENT`         | **Required inline on EVERY `gcloud` command** (including auxiliary `gcloud` commands). ⚠️ **CRITICAL: See Note 1 below.**
**Bucket Name**                    | `gs://[bucket-name]`                   | Positional argument on `create` / `update`. Must be globally unique.
**Project**                        | `--project=[project-id]`               | Global flag specifying target project ID.
**Location**                       | `--location=[location]`                | Region (`us-central1`), multi-region/custom dual-region geo (`US`), or predefined dual-region (`nam4`). ⚠️ **See Note 2 below.**
**Placement**                      | `--placement=[placement]`              | ONLY for custom dual-region (`us-east1,us-west1` with `--location=US`) or zonal (`us-east1-b` with `--location=us-east1`). **NEVER** use with `nam4`/`eur4`/`asia1`. ⚠️ **See Note 2.**
**Replication Speed (RPO)**        | `--rpo=ASYNC_TURBO`                    | Optional. Enables 15-minute Turbo Replication on dual-region buckets.
**Storage Class**                  | `--default-storage-class=[class]`      | `STANDARD` (default; must not be set to another class with Autoclass), `NEARLINE`, `COLDLINE`, `ARCHIVE`, `RAPID` (required for zonal buckets).
**UBLA**                           | `--uniform-bucket-level-access`        | Always enable (`--uniform-bucket-level-access`).
**Public Access Prevention**       | `--[no-]public-access-prevention`      | Enforce (`--public-access-prevention`) by default; use `--no-public-access-prevention` only with clear use-case intent and explicit user consent.
**Soft Delete**                    | `--soft-delete-duration=[duration]`    | E.g., `7d` (default), `14d`. Set to `0` to disable (MUST be `0` for zonal `RAPID` buckets).
**Object Versioning**              | `update ... --versioning`              | **Cannot be set on `create`.** Apply via `gcloud storage buckets update gs://[b] --versioning` (or `--no-versioning`). Recommended fallback if Soft Delete is disabled.
**Encryption (CMEK)**              | `--default-encryption-key=[key-id]`    | Full KMS key path (`projects/[project]/locations/[loc]/keyRings/[ring]/cryptoKeys/[key]`). Omit for GMEK.
**Restrict Encryption (CSEK)**     | `--encryption-enforcement-file=[file]` | JSON file restricting CSEK on `create` or `update`. See **Helper Configuration Templates** below.
**Autoclass**                      | `--enable-autoclass`                   | Requires `STANDARD` storage class; incompatible with zonal buckets and OLM `SetStorageClass` rules (optional: `--autoclass-terminal-storage-class=ARCHIVE`).
**Hierarchical Namespace**         | `--enable-hierarchical-namespace`      | Boolean flag on `create`. Requires UBLA. Required for zonal `RAPID` buckets.
**Labels**                         | `update ... --update-labels=[k=v,...]` | **Cannot be set on `create`.** Apply via `gcloud storage buckets update gs://[b] --update-labels=k1=v1,k2=v2`. ⚠️ **See Note 3.**
**IP Filtering**                   | `--ip-filter-file=[file]`              | JSON file defining IP/VPC rules. See **Helper Configuration Templates** below.
**Cloud Logging (Usage Logs)**     | `update ... --log-bucket=gs://[b]`     | **Cannot be set on `create`.** Apply via `gcloud storage buckets update gs://[b] --log-bucket=gs://[log-bucket] [--log-object-prefix=[prefix]]` (grant `roles/storage.objectCreator` to `cloud-storage-analytics@google.com` on log bucket).
**Lifecycle Policies (OLM)**       | `--lifecycle-file=[file]`              | JSON file defining OLM rules (prefer on `create`; also supported on `update`). See template below.
**CORS**                           | `update ... --cors-file=[file]`        | **Cannot be set on `create`.** Apply via `gcloud storage buckets update gs://[b] --cors-file=cors.json`.
**Website Configuration**          | `update ... --web-main-page-suffix`    | **Cannot be set on `create`.** Apply via `gcloud storage buckets update gs://[b] --web-main-page-suffix=index.html --web-error-page=404.html`.
**Public IAM Policy**              | `buckets add-iam-policy-binding`       | **Cannot be set on `create`.** For public websites/VOD: `gcloud storage buckets add-iam-policy-binding gs://[b] --member=allUsers --role=roles/storage.objectViewer`.
**Pub/Sub Notifications**          | `buckets notifications create`         | **Cannot be set on `create`.** Run `gcloud storage buckets notifications create gs://[b] --topic=[topic-name]`.
**Bucket Retention (Bucket Lock)** | `--retention-period=[duration]`        | E.g., `30d`, `90d`, `2555d`, `157680000s`, or ISO 8601 (`P1Y1M1DT5S`). Sets bucket-wide retention on `create` or `update`.
**Lock Bucket Retention Policy**   | `update ... --lock-retention-period`   | **Cannot be set on `create`.** Run `gcloud storage buckets update gs://[b] --lock-retention-period`. **Permanent and irreversible.**
**Object Retention (Object Lock)** | `--enable-per-object-retention`        | Enables per-object retention. **Can only be set on `create` via `gcloud`.**
**Set Object Retention**           | `objects update` / `storage cp`        | If object commands requested: `gcloud storage objects update gs://[b]/[obj] --retain-until=[RFC3339-ts] --retention-mode=[Locked/Unlocked] [--override-unlocked-retention]` (or set on upload via `gcloud storage cp`; `--override-unlocked-retention` is required to lock, shorten `--retain-until`, or `--clear-retention` on `Unlocked` objects).
**Rapid Cache (Anywhere Cache)**   | `buckets anywhere-caches create`       | **Cannot be set on `create`.** Run `gcloud storage buckets anywhere-caches create gs://[b] [zone] [--ttl=24h] [--enable-ingest-on-write]` (use `--enable-ingest-on-write`, never `--ingest-on-write`).
**Storage Insights Inventory**     | `insights inventory-reports create`    | Optional (only if CLI command is requested): `gcloud storage insights inventory-reports create gs://[src] --destination=gs://[dst]/inventory_reports/`.

> [!IMPORTANT]
>
> *   **Note 1 (Mandatory Inline Attribution Prefix)**: Prefix EVERY `gcloud`
>     command (including auxiliary `gcloud` commands in recommendations, except
>     `gcloud auth print-access-token` inside REST `curl` headers) inline with:
>
>     ```bash
>     CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)"
>     ```
>
> *   **Note 2 (Predefined Dual-Regions vs. Custom Dual-Regions & Zonal)**:
>
>     *   When `nam4` (`us-east1` + `us-central1`), `eur4` (`europe-north1` +
>         `europe-west4`), or `asia1` (`asia-northeast1` + `asia-northeast2`) is
>         specified—even if constituent regions are mentioned—set
>         `--location=nam4` (or `eur4`/`asia1`) directly and **NEVER** pass
>         `--placement` (fails with `HTTPError 400`).
>     *   For **custom dual-regions**, set `--location` to the continent geo
>         area (e.g., `US`) and `--placement=us-east1,us-west1`.
>     *   For **zonal (`RAPID`) buckets**, set `--location=<region>` (e.g.,
>         `us-east1`) and `--placement=<zone>` (e.g., `us-east1-b`).
>
> *   **Note 3 (Explain `create` vs. `update` for Labels)**: Whenever labels are
>     requested with `gcloud`, explicitly state in prose that labels cannot be
>     set during bucket creation via `gcloud` and must be applied using
>     `gcloud storage buckets update --update-labels=...`.

--------------------------------------------------------------------------------

## Helper Configuration Templates

Include the JSON file content alongside your `gcloud` commands whenever
`--encryption-enforcement-file`, `--cors-file`, `--lifecycle-file`, or
`--ip-filter-file` is used (and write it before executing in Phase 3).

### 1. Encryption Enforcement (`encryption_enforcement.json`)

```json
{
  "gmekEnforcement": {"restrictionMode": "NotRestricted"},
  "cmekEnforcement": {"restrictionMode": "NotRestricted"},
  "csekEnforcement": {"restrictionMode": "FullyRestricted"}
}
```

At least one encryption type must remain `NotRestricted`; omitted encryption
types default to allowed on `create`.

### 2. CORS Template (`cors.json`)

```json
[
  {
    "origin": ["https://my-website.appspot.com"],
    "method": ["GET", "HEAD", "PUT"],
    "responseHeader": ["Content-Type", "x-goog-resumable"],
    "maxAgeSeconds": 3600
  }
]
```

*(`responseHeader` and `maxAgeSeconds` are optional; match `origin` and `method`
to the user's request.)*

### 3. Lifecycle OLM Template (`lifecycle.json`)

```json
{
  "rule": [
    {"action": {"type": "AbortIncompleteMultipartUpload"}, "condition": {"age": 7}},
    {"action": {"type": "Delete"}, "condition": {"age": 365}}
  ]
}
```

*   Storage class transition (ONLY when Autoclass is disabled): `{"action":
    {"type": "SetStorageClass", "storageClass": "ARCHIVE"}, "condition": {"age":
    365}}`.
*   Prune non-current versions: `{"action": {"type": "Delete"}, "condition":
    {"daysSinceNoncurrentTime": 30, "isLive": false}}`.

> [!WARNING]
>
> **Autoclass Restrictions**: If Autoclass is enabled on the bucket, the Object
> Lifecycle Management (OLM) configuration **MUST NOT** contain rules using the
> `SetStorageClass` action or `matchesStorageClass` condition (doing so causes
> bucket creation or update to fail).

### 4. IP Filtering Template (`ip_filter.json`)

```json
{
  "mode": "Enabled",
  "allowAllServiceAgentAccess": true,
  "allowCrossOrgVpcs": false,
  "publicNetworkSource": {"allowedIpCidrRanges": ["192.0.2.0/24", "198.51.100.0/32"]},
  "vpcNetworkSources": [
    {"network": "projects/PROJECT_ID/global/networks/NETWORK_NAME", "allowedIpCidrRanges": ["10.0.0.0/16"]}
  ]
}
```

--------------------------------------------------------------------------------

## Conversion Examples

### Example 1: Sensitive Data / Compliance (CMEK, Autoclass, CSEK Restricted, Retention, Labels, OLM, IP Filter)

```bash
# 1. Create the bucket (omit optional flags like CMEK/retention/IP filter if not needed)
CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
gcloud storage buckets create gs://my-compliance-pii-bucket \
    --project=my-compliance-project --location=us-central1 \
    --uniform-bucket-level-access --public-access-prevention \
    --soft-delete-duration=7d --retention-period=90d --enable-autoclass \
    --default-encryption-key=projects/my-kms-project/locations/us-central1/keyRings/my-keyring/cryptoKeys/my-key \
    --encryption-enforcement-file=encryption_enforcement.json \
    --lifecycle-file=lifecycle_abort.json --ip-filter-file=ip_filter.json

# 2. Add labels (labels cannot be set during bucket creation via gcloud; must use update)
CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
gcloud storage buckets update gs://my-compliance-pii-bucket \
    --project=my-compliance-project --update-labels=data-class=pii,owner=security-team

# 3. Optional: Lock retention policy (WARNING: irreversible; neither admins nor Cloud Support can shorten/remove it)
# CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
# gcloud storage buckets update gs://my-compliance-pii-bucket --lock-retention-period
```

### Example 2: Static Website Hosting (Multi-Region `US`, Public Access, Website Config, CORS, Versioning)

```bash
# 1. Create the bucket with PAP disabled (--no-public-access-prevention)
CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
gcloud storage buckets create gs://www.my-company-site.com \
    --project=my-frontend-project --location=US --default-storage-class=STANDARD \
    --uniform-bucket-level-access --no-public-access-prevention --soft-delete-duration=7d

# 2. Configure Website settings, CORS, and Versioning in a single update (cannot be set on create)
CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
gcloud storage buckets update gs://www.my-company-site.com \
    --web-main-page-suffix=index.html --web-error-page=404.html --cors-file=cors_web.json --versioning

# 3. Grant public read access to website files
CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
gcloud storage buckets add-iam-policy-binding gs://www.my-company-site.com \
    --member=allUsers --role=roles/storage.objectViewer
```

### Example 3: AI/ML Checkpointing (Zonal `RAPID` Bucket in `us-east1-b`, HNS, Soft Delete Disabled)

```bash
CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
gcloud storage buckets create gs://my-training-checkpoints-us-east1-b \
    --project=my-ai-project --location=us-east1 --placement=us-east1-b \
    --default-storage-class=RAPID --uniform-bucket-level-access \
    --enable-hierarchical-namespace --public-access-prevention \
    --soft-delete-duration=0 --lifecycle-file=lifecycle_checkpoint.json
```

### Example 4: WORM Archive with Object Lock (Per-Object Retention)

```bash
# 1. Create the bucket with per-object retention enabled (can only be set at creation time)
CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
gcloud storage buckets create gs://my-legal-archive-bucket \
    --project=my-legal-project --location=us-east1 --default-storage-class=ARCHIVE \
    --uniform-bucket-level-access --public-access-prevention --soft-delete-duration=7d \
    --enable-per-object-retention --lifecycle-file=lifecycle_archive.json \
    --default-encryption-key=projects/my-kms-project/locations/us-east1/keyRings/my-keyring/cryptoKeys/my-key

# 2. Apply labels via update (cannot be set during create)
CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
gcloud storage buckets update gs://my-legal-archive-bucket \
    --project=my-legal-project --update-labels=compliance-type=regulatory,retention-period=7y

# 3. Upload an object with per-object retention (WARNING: Locked mode is permanent and irreversible; no one can delete/shorten until expiry)
CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
gcloud storage cp case_file_abc.pdf gs://my-legal-archive-bucket/case_file_abc.pdf \
    --retain-until=2030-12-31T23:59:59Z --retention-mode=Locked

# 4. Or update retention on an existing object (--override-unlocked-retention required to lock, shorten --retain-until, or --clear-retention on Unlocked):
CLOUDSDK_METRICS_ENVIRONMENT="${CLOUDSDK_METRICS_ENVIRONMENT:+$CLOUDSDK_METRICS_ENVIRONMENT }gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
gcloud storage objects update gs://my-legal-archive-bucket/case_file_abc.pdf \
    --retain-until=2030-12-31T23:59:59Z --retention-mode=Locked --override-unlocked-retention
```
log_storage.md 5.0 KB
# Log Storage

This reference document outlines the configuration mapping and architecture
recommendation for Cloud Storage buckets optimized for log storage and
ingestion.

## Description

The user is storing high-volume application logs, VPC flow logs, or audit trail
dumps that are typically ingested by SIEM (Security Information and Event
Management) tools or parsed during operational troubleshooting. The primary
goals are minimizing write ingestion costs and eliminating inter-regional
network egress charges, while optimizing storage costs for logs that naturally
grow cold.

## Bucket Configuration Plan Mapping

The following table maps the Log Storage use case to specific Cloud Storage
features and details their recommendation status. See
[Official Documentation References](#official-documentation-references) below
for feature links if further reference is needed (do not fetch routinely).

Cloud Storage Feature / Setting        | Status             | Recommendations & Implementation Details
:------------------------------------- | :----------------- | :---------------------------------------
**Storage Class**                      | Highly Recommended | **Autoclass** Storage Class.<br><br>Raw log ingestion generates massive write operations. Autoclass is ideal since standard writes carry no cost penalty, and older log chunks are automatically transitioned to colder classes as they age.
**Bucket Type**                        | Highly Recommended | **Regional (R)** bucket type.<br><br>Ensure the bucket region matches the exact region hosting your compute resources and SIEM tools. This completely eliminates inter-regional network egress fees during ingestion and analytical querying.
**Uniform Bucket-Level Access (UBLA)** | **Required**       | **Must be enabled.** Standardizes IAM permissions across the bucket.
**Public Access Prevention (PAP)**     | **Required**       | **Must be enforced.** Logs contain sensitive operational details and must never be exposed publicly.
**Encryption (CMEK)**                  | Highly Recommended | Configure **CMEK via Cloud KMS** by default. Use KMS Autokey for automation, or prompt the user.
**IP Filtering**                       | Good to Have       | Limit administrative access and raw log export operations to trusted security operations center (SOC) IP ranges.
**Soft Delete**                        | Optional           | Neither highly recommended nor required, but useful to share with the customer as an essential defensive layer to recover logging windows if an administrative script executes a mass purge command.
**Object Lifecycle Management (OLM)**  | Highly Recommended | Recommended if Autoclass is disabled. Establish rules to transition logs to `ARCHIVE` after 365 days.
**Labels & Tagging**                   | Good to Have       | Apply tagging (e.g. `{"environment": "production"}` and `{"cost-center": "security-ops"}`) to parse out high-volume cloud infrastructure spend.
**Storage Intelligence**               | Good to Have       | Monitor data accumulation rates using Storage Insights to identify which microservices are dominating storage metrics.
**Cloud Monitoring**                   | Highly Recommended | **Configure Cloud Monitoring** to build dashboards tracking storage API call limits, ingestion errors, or spikes in daily write volumes.

## Key Pre-Deployment Questions to Ask:

1.  **In which region are your compute workloads and analytical SIEM tools
    hosted?**
    *   *Recommendation*: Co-locate the bucket in the same region to eliminate
        egress fees.
2.  **What is the typical time window before logs are considered cold or no
    longer queryable?**

## Mandatory Recommendations to Include in the Design Plan:

*   **Cloud Monitoring**: You MUST recommend configuring Cloud Monitoring to
    track Cloud Storage API limits, ingestion errors, and daily write volumes.

## Official Documentation References

Feature / Topic             | Documentation Link
:-------------------------- | :-----------------
Autoclass                   | https://cloud.google.com/storage/docs/autoclass
Storage Classes             | https://cloud.google.com/storage/docs/storage-classes
Locations                   | https://cloud.google.com/storage/docs/locations
Uniform Bucket-Level Access | https://cloud.google.com/storage/docs/uniform-bucket-level-access
Public Access Prevention    | https://cloud.google.com/storage/docs/public-access-prevention
CMEK                        | https://cloud.google.com/storage/docs/encryption/customer-managed-keys
Bucket IP Filtering         | https://cloud.google.com/storage/docs/ip-filtering-overview
Soft Delete                 | https://cloud.google.com/storage/docs/soft-delete
Lifecycle Management        | https://cloud.google.com/storage/docs/lifecycle
Bucket Labels               | https://cloud.google.com/storage/docs/using-bucket-labels
Inventory Reports           | https://cloud.google.com/storage/docs/insights/inventory-reports
Cloud Monitoring            | https://cloud.google.com/storage/docs/monitoring
media_hosting.md 5.5 KB
# Media Hosting & Content Delivery Network (CDN)

This reference document outlines the secure-by-default, high-performance
configuration mapping and architecture recommendation for Cloud Storage buckets
serving as the origin for media assets and Content Delivery Networks (CDNs).

## Description

The user is serving high-definition images, videos, or audio assets to a global
or geo-regional audience with low latency. Cloud Storage acts as the origin
store for a CDN (e.g. Cloud CDN or third-party CDNs), and requires high read QPS
scaling, high bandwidth, and immediate data availability.

## Bucket Configuration Plan Mapping

The following table maps the Media Hosting & CDN to specific Cloud Storage
features and details their recommendation status. See
[Official Documentation References](#official-documentation-references) below
for feature links if further reference is needed (do not fetch routinely).

Cloud Storage Feature / Setting        | Status             | Recommendations & Implementation Details
:------------------------------------- | :----------------- | :---------------------------------------
**Storage Class**                      | Highly Recommended | **Autoclass** or **Standard** Storage Class.<br><br>Standard storage is recommended to avoid retrieval fees on highly active content. Autoclass is ideal for automatically transitioning stale media assets or raw originals to colder tiers over time.
**Bucket Type**                        | Highly Recommended | For **live-streaming**: **Regional** or **Dual-Regional** buckets (to co-locate compute and storage). For **Video-on-Demand (VOD)**: **Multi-Regional (MR)** to distribute content closer to a global user base.
**CORS**                               | Highly Recommended | **Configure CORS.** Allow `GET` and `HEAD` requests from expected domains (or `["*"]` for global public assets) using `set_bucket_cors` to enable client-side asset loading.
**Signed URLs**                        | Optional           | Use only if media assets require paid access or must be gated by authentication token.
**Uniform Bucket-Level Access (UBLA)** | **Required**       | **Must be enabled.** Prevents legacy object-level ACLs from overriding bucket-level IAM policies.
**Soft Delete**                        | Highly Recommended | **Enabled (default 7 days).** Vital to protect crucial application media assets from accidental purge commands or deployment script bugs.
**Object Versioning**                  | Good to Have       | Suggest as an alternative to prevent accidental media overwrite or modification if Soft Delete is disabled.
**IP Filtering**                       | Good to Have       | Restrict admin operations and raw manual exports to trusted corporate SOC IP perimeters.
**Object Lifecycle Management (OLM)**  | Good to Have       | If Autoclass is disabled, automatically transition older, unviewed original media assets to colder storage tiers. Recommend standard OLM rule: Transition to `ARCHIVE` after 365 days.
**Hierarchical Namespace**             | Highly Recommended | **Enable Hierarchical Namespace** for high-volume or high-QPS streaming workloads. Hierarchical Namespace buckets offer up to **8x higher initial QPS** limits for object operations compared to standard buckets.<br><br>*Note: Hierarchical Namespace is incompatible with Object Versioning, and Retention Policies (Bucket Lock/Object Lock). Hierarchical Namespace is compatible with Soft Delete.*
**Storage Transfer Service (STS)**     | Good to Have       | Relocate and replicate media assets across regions using STS to move content closer to growing user bases and minimize latency.
**Cloud Logging**                      | Good to Have       | Enable audit logging for troubleshooting access and tracking server-side security events.
**Cloud Monitoring**                   | Good to Have       | Track network egress, operations count, and monitor operational error rates (404, 503).

## Key Pre-Deployment Questions to Ask:

1.  **Is this for live-streaming or Video-On-Demand (VOD)?**
    *   *If Live-streaming*: Regional or Dual-regional buckets are highly
        recommended to co-locate compute (transcoders) and storage.
    *   *If VOD*: Multi-regional buckets are recommended for optimal global
        availability and delivery closer to end-users.

## Official Documentation References

Feature / Topic             | Documentation Link
:-------------------------- | :-----------------
Autoclass                   | https://cloud.google.com/storage/docs/autoclass
Storage Classes             | https://cloud.google.com/storage/docs/storage-classes
Locations                   | https://cloud.google.com/storage/docs/locations
CORS                        | https://cloud.google.com/storage/docs/using-cors
Signed URLs                 | https://cloud.google.com/storage/docs/access-control/signed-urls
Uniform Bucket-Level Access | https://cloud.google.com/storage/docs/uniform-bucket-level-access
Soft Delete                 | https://cloud.google.com/storage/docs/soft-delete
Object Versioning           | https://cloud.google.com/storage/docs/object-versioning
Bucket IP Filtering         | https://cloud.google.com/storage/docs/ip-filtering-overview
Lifecycle Management        | https://cloud.google.com/storage/docs/lifecycle
Hierarchical Namespace      | https://cloud.google.com/storage/docs/hns-overview
Storage Transfer Service    | https://cloud.google.com/storage-transfer/docs/overview
Cloud Audit Logging         | https://cloud.google.com/storage/docs/audit-logging
Cloud Monitoring            | https://cloud.google.com/storage/docs/monitoring
phase_draft_plan.md 10.6 KB
# Phase 2: Draft Bucket Create Plan

This phase maps the user's workload to a use case, verifies bucket name
availability, and drafts a secure-by-default bucket configuration plan.

## Step 1: Apply Secure-by-Default Settings

Always recommend and configure these defaults unless the user explicitly
requests otherwise. If the user wants to change them, obtain explicit
confirmation and warn of the security risks (a stricter value of the same
setting, such as a longer soft-delete duration, needs no confirmation, but
disabling or loosening a default always does; if the user explicitly asked for
immediate output without confirmation, follow Handling Conflicts step 3, still
warning):

*   **Uniform Bucket-Level Access (UBLA)**: Enabled.
*   **Restrict Encryption Types**: Restrict Customer-Supplied Encryption Keys
    (CSEK) unless explicitly required.
*   **Soft Delete**: Enabled with the default 7-day retention duration.
    *   *Exception*: For **Rapid/Zonal** buckets, soft delete is NOT supported
        and MUST be disabled (`0` duration).
*   **Public Access Prevention (PAP)**: Enforced.
    *   *Exception*: Set PAP to `inherited` (`--no-public-access-prevention`)
        only when the workload explicitly requires public access (e.g., Static
        Website Hosting, Public VOD Media Hosting) and the user has indicated
        this.

--------------------------------------------------------------------------------

## Step 2: Determine the Use Case

Match the user's workload to the single primary use-case reference file listed
in `SKILL.md` (`sensitive_data.md`, `media_hosting.md`, `ugc_ingestion.md`,
`static_website.md`, `archiving_compliance.md`, `backup_dr.md`,
`log_storage.md`, `storage_for_ai.md`) by default—read multiple use-case files
only when the user explicitly requests combining two distinct use cases. For
**general-purpose** application data buckets without a specialized workload, do
not read any use-case file—apply the Secure-by-Default settings above
(`STANDARD` storage class, `UBLA`, `PAP`, `7d Soft Delete`, `Restrict CSEK`). If
the workload is unclear, apply these defaults and ask the user for
clarification.

Include all **Required** and **Highly Recommended** features and ecosystem
recommendations (`Cloud Monitoring`, `Cloud Logging`, `Storage Insights`,
`Storage Transfer Service`) from the matched reference file(s) in your plan.
*Note: Ecosystem tools are prose architectural recommendations—do NOT search for
or generate separate CLI commands for them unless explicitly requested.*

--------------------------------------------------------------------------------

## Handling Conflicts with Best Practices

If the user explicitly requests a setting that contradicts **Required** or
**Highly Recommended** best practices:

1.  **Warn / Advise Against**: Explain why the requested setting is not
    recommended (e.g., dual-region `nam4` for backups incurs higher cost than
    necessary).
2.  **Recommend Best Practice**: State the recommended alternative from the
    reference file (e.g., Regional bucket + Storage Transfer Service (STS) for
    Backup/DR).
3.  **Confirmation vs. Immediate Output**: In interactive mode, ask whether to
    adopt the recommendation or keep the original request. If the user asked for
    immediate output without confirmation, generate the commands using the
    user's explicitly requested parameters (e.g., `--location=nam4`) while still
    surfacing the warning and recommended alternative.

--------------------------------------------------------------------------------

## Location, Zonal, Retention, and IP Filtering Rules

### Location / Region Handling

*   **Do NOT run commands** like `gcloud compute regions list` or `gcloud
    compute zones list` to verify locations.
*   **Predefined Dual-Regions (`nam4`, `eur4`, `asia1`)**: When `nam4`
    (`us-east1`, `us-central1`), `eur4` (`europe-north1`, `europe-west4`), or
    `asia1` (`asia-northeast1`, `asia-northeast2`) is specified—even if its
    constituent regions are also mentioned—set `--location=nam4` (or
    `eur4`/`asia1`) directly and **NEVER** use `--placement` (Cloud Storage
    rejects custom placement for predefined dual-region pairs with `400`).
*   **Invalid Locations**: If an invalid location (e.g., `Kenya`) is requested:
    (1) state it is not a valid Cloud Storage location, (2) cite
    `https://cloud.google.com/storage/docs/locations`, (3) suggest valid nearby
    regions, and (4) do NOT generate creation commands.

### Zonal Buckets (Rapid Bucket) Constraints

For zonal buckets (AI/ML co-location):

*   **Storage Class**: MUST be `RAPID` (never `STANDARD`).
*   **Soft Delete**: MUST be disabled (`0` duration).
*   **Hierarchical Namespace & UBLA**: Both MUST be enabled.
*   **Location & Placement**: Set location to the region (e.g., `us-east4`) and
    placement to the zone (e.g., `us-east4-a`). Trust the user's zone without
    searching.

### Retention Policy (Bucket Lock vs. Object Lock) & IP Filtering

*   **Bucket Lock vs. Object Lock**: Bucket Lock applies a uniform bucket-wide
    retention period; Object Lock (`--enable-per-object-retention`, set at
    bucket creation) allows per-object `retainUntilTime` WORM timestamps.
    Locking either policy is **permanent and irreversible**.
*   **IP Filtering**: Max 200 CIDR blocks and 25 VPC networks. Regional
    endpoints work with IP filtering only through Private Service Connect (PSC),
    and gRPC direct path is not supported from IPv4-only VMs (IPv6 must be
    enabled on the VPC network). Do NOT use IP filtering if accessed by
    **BigQuery**, **App Engine Standard** (without VPC), or **Cloud Shell**.

--------------------------------------------------------------------------------

## Step 3: Verify Bucket Name Availability

*   **Unspecified Bucket Name Rule**: If the user did not provide a bucket name,
    propose `<project-id>-<use-case>-<6-char-hex>` with a random 6-character hex
    suffix (e.g., `bucket-architect-test-audit-logs-8f4a2c`; drop
    `<project-id>-` if no project ID was given).
*   **Skip Rule**: If the user explicitly instructed NOT to run any `gcloud`/all
    commands, do NOT run this check; report status as `⚠️ Not verified` (citing
    user instruction) and **warn that bucket creation will fail with a 409
    conflict error if the name is already taken**. *(An instruction not to
    execute bucket creation or mutating commands does NOT skip this read-only
    check.)*
*   **Batch Execution**: Run this check as the 5th command in the same single
    shell command as the 4 Phase 1 project checks (`SKILL.md` Step 2), always
    including the inline `CLOUDSDK_METRICS_ENVIRONMENT` prefix. Do **not**
    re-run it for an unchanged name; if the name changes (the user edits it, or
    you propose a replacement), check the new name before using it unless the
    user explicitly forbade running commands.

Outcome                                                                                                                           | HTTP      | Status          | Agent Action
:-------------------------------------------------------------------------------------------------------------------------------- | :-------- | :-------------- | :-----------
Error contains `not found: 404`                                                                                                   | 404       | ✅ Available     | Proceed with the draft plan and output.
Prints bucket metadata, OR error contains `does not have permission` / `buckets.get` denied (even with `"(or it may not exist)"`) | 200 / 403 | ❌ Name taken    | Report that the bucket name is already taken (`403` always means taken by another project; never re-run `describe` with `--project` or dummy names). For **`gcloud` CLI creation**, do **NOT** output `gcloud storage buckets create` for the taken name—ask the user for a different bucket name. For **SDK/Terraform/REST code snippets**, warn that the literal name is taken and must be changed before running (never reuse an existing bucket, whose settings may not match the plan), and still provide the requested code snippet without running extra `describe` commands.
Other failure (auth, network, VPC-SC, command restriction)                                                                        | none      | ⚠️ Not verified | Proceed with plan, state reason, and warn creation will fail with a 409 error if the name is taken.

--------------------------------------------------------------------------------

## Step 4: Present the Draft Plan

> [!CAUTION]
>
> If the plan includes **Bucket Lock** or **Object Lock**, you **MUST** warn
> that locking the policy is permanent and irreversible—once locked, the
> retention period cannot be shortened or removed, and data cannot be deleted or
> overwritten by anyone (including project admins and Cloud Support) until it
> expires. Proceed only after explicitly confirming whether the user wants to
> set the policy to "Locked" or "Unlocked" and for how long. A mode and duration
> stated in the prompt count as confirmation; for an immediate-output request
> without them, don't stop: use Unlocked or placeholders with this warning, and
> never choose Locked yourself.

Present a concise Draft Bucket Creation Plan including the core settings below
plus only the active workload-specific settings and `Other Recommendations`
(omit `Disabled`/`None` bullets for unused features unless asked by the user).
If the user explicitly requested the final commands or code in their prompt,
replace the closing question with a one-line reminder to review the plan and
continue to Phase 3 in the same response:

```markdown
### Draft Bucket Creation Plan

Based on your requirements, we will configure a bucket optimized for **[Use Case Name]**:

*   **Bucket Name**: `[bucket-name]` (✅ Available | ❌ Already exists / Taken | ⚠️ Not verified: [reason])
*   **Project**: `[project-id]`
*   **Location**: `[location]` (and **Placement**: `[zone/regions]` if applicable)
*   **Storage Class**: `[STANDARD | NEARLINE | COLDLINE | ARCHIVE | RAPID]`
*   **UBLA**: Enabled (✅ Secure Default)
*   **Public Access Prevention (PAP)**: Enforced (or `inherited` if public access is required)
*   **Encryption**: `[Google-managed | CMEK: <key>]` with CSEK Restricted (✅ Secure Default)
*   **Soft Delete**: `[7 Days (Default) | <N> Days | 0 Days (Disabled for RAPID)]`
*   **Workload Settings**: `[Include active settings: Autoclass, HNS, OLM rules, Retention Policy, Versioning, CORS, Website Config, Labels, IP Filtering]`
*   **Other Recommendations**: `[Concise prose summary: e.g., Cloud Audit Logs, Cloud Monitoring, Storage Insights, STS]`

Does this draft plan look correct? Please confirm if you'd like to proceed or if you want to make any adjustments.
```
phase_output.md 2.8 KB
# Phase 3: Output Based on User Intent

This phase generates the final bucket configuration in the user's preferred
format and offers execution if authorized.

## Step 1: Determine Preferred Format

*   If the user already specified a format in their prompt (`gcloud`, `REST` /
    `curl`, `Terraform`, or an `SDK` language), use that format.
*   Otherwise, ask the user to choose: **gcloud**, **REST (JSON)**,
    **Terraform**, or **SDK** (C++, Java, Python, or Go).

## Step 2: Generate Configuration Snippet and Recommendations

1.  Generate the configuration using the templates and rules in the format's
    reference file:
    *   **gcloud**: [gcloud.md](gcloud.md) (natively supports all features; do
        **not** read `sdk.md`)
    *   **REST (JSON)**: [rest.md](rest.md) (natively supports all features; do
        **not** read `sdk.md`)
    *   **Terraform**: [terraform.md](terraform.md) (do **not** read `sdk.md`)
    *   **SDK**: [sdk.md](sdk.md) + `sdk_<lang>.md`
2.  **Attribution (Mandatory for `gcloud` and `REST`)**: Prefix every generated
    `gcloud` command (except `gcloud auth print-access-token` inside REST
    `curl`) with the inline `CLOUDSDK_METRICS_ENVIRONMENT` append prefix, and
    include
    `User-Agent: gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)`
    on every REST `curl` command.
3.  **Keep Output Focused & Concise**: Output only the commands/code and helper
    JSON files (`encryption_enforcement.json`, `lifecycle.json`, `cors.json`,
    `ip_filter.json`) needed for the active settings in the Draft Plan. Do
    **not** generate unrequested `gcloud kms keys add-iam-policy-binding`
    commands or unrequested `--update-labels` commands when the user did not
    request labels.
4.  **Other Recommendations**: Include a concise prose **Other Recommendations**
    section covering the ecosystem tools proposed in the plan
    (`Cloud Audit Logs`, `Cloud Monitoring`, `Storage Insights`,
    `Storage Transfer Service`, or CMEK IAM role notes).
5.  **SDK Version Warnings (SDK Format Only)**: When generating **SDK** code for
    features with version gates (such as `EncryptionEnforcementConfig`, which
    requires Python `>= 3.10.0`, Go `>= 1.61.0`, C++ `>= 2.46.0`, Java
    `>= 2.55.0`), include a warning specifying the minimum SDK version and
    advising `REST`, `gcloud`, or `Terraform` if using an older version.

## Step 3: Execution and Delivery

*   **For `gcloud` and `REST` (JSON)**: Display the commands/payload and ask for
    confirmation before executing
    (`"Would you like me to execute this command to create the bucket now?"`).
    Never execute any of these commands without explicit, affirmative
    confirmation.
*   **For `Terraform` and `SDK`**: Display the snippet and instruct the user on
    how to integrate it into their project (do not offer to execute it).
phase_project_checks.md 3.6 KB
# Phase 1: Project-Level Security Checks

> [!IMPORTANT]
>
> Always verify project-level security settings (TLS 1.2, HTTPS Only, Restrict
> HMAC, and Project Liens) before drafting a bucket configuration. If a project
> is insecure, warn the user and recommend remediation.

## Step 1: Execute Project Verification Commands

*   **When to Skip (`⚠️ Undetermined`)**: Do **NOT** run the 4 checks if the
    user explicitly instructs NOT to run any `gcloud` commands (or not to run
    any commands at all), or gave no project ID (never run them against a
    guessed, placeholder, or `gcloud config` default project; ask for the ID);
    report all 4 as `⚠️ Undetermined` with that reason. *(Note: An instruction
    not to execute bucket creation or modification commands does NOT skip these
    read-only checks.)*
*   **Parallel Execution**: Run the 4 read-only project checks exactly as
    written in `SKILL.md` Step 2, in the same single shell command as the Phase
    2 `gcloud storage buckets describe` check and in the same parallel batch as
    your reference file reads. Every `gcloud` command MUST keep the inline
    `CLOUDSDK_METRICS_ENVIRONMENT` append prefix.

## Step 2: Interpret and Present Results

If you ran the checks, open by noting that a secure bucket also relies on secure
project settings. Present a concise summary of the 4 checks using `✅ Secure`,
`❌ Insecure` (warn and list concise remediation bullets), or `⚠️ Undetermined`
(state the reason, recommend the user contact their system administrator for
help setting these values if they can't set them, and do not output manual
verification command blocks unless requested):

### Status Mapping Table

Check             | Target / Constraint                       | ✅ Secure Condition               | ❌ Insecure Condition                                      | ⚠️ Undetermined Condition
:---------------- | :---------------------------------------- | :------------------------------- | :-------------------------------------------------------- | :------------------------
**TLS 1.2**       | `constraints/gcp.restrictTLSVersion`      | Enforced; denies TLS < 1.2       | Not enforced / allows TLS < 1.2 / Org Policy API disabled | Permission denied (`orgpolicy.policy.get`), VPC-SC, or command restriction
**HTTPS Only**    | `constraints/storage.secureHttpTransport` | `spec.rules[0].enforce == true`  | Not enforced / Org Policy API disabled                    | Permission denied (`orgpolicy.policy.get`), VPC-SC, or command restriction
**Restrict HMAC** | `constraints/storage.restrictAuthTypes`   | Enforced; restricts HMAC keys    | Not enforced / Org Policy API disabled                    | Permission denied (`orgpolicy.policy.get`), VPC-SC, or command restriction
**Project Liens** | `liens list`                              | Non-empty list (at least 1 lien) | Empty list `[]`                                           | Permission denied (`resourcemanager.projects.get`), VPC-SC, or command restriction

### Example Output Presentation

```markdown
### Project-Level Security Posture Assessment

*   ❌ **TLS 1.2 Enforcement**: Insecure (Older TLS versions allowed).
*   ❌ **HTTPS Only**: Insecure (Non-secure HTTP transport allowed).
*   ❌ **Restrict HMAC Keys**: Insecure (HMAC key creation is not restricted).
*   ❌ **Project Liens**: Insecure (No active liens protect project from accidental deletion).

**Remediation Recommendations:**
*   **TLS 1.2 / HTTPS / HMAC**: Enforce `constraints/gcp.restrictTLSVersion`, `constraints/storage.secureHttpTransport`, and `constraints/storage.restrictAuthTypes`.
*   **Project Liens**: Create a project lien via `gcloud alpha resource-manager liens create` to prevent accidental project deletion.
```
rest.md 13.2 KB
# Cloud Storage JSON API Reference

> [!IMPORTANT]
>
> **DO NOT EXECUTE THESE COMMANDS AUTOMATICALLY.** Present the generated
> payloads and `curl` commands to the user and only execute them in Phase 3 if
> explicit confirmation is granted.

## Official Documentation Reference

*   [Cloud Storage JSON API Overview](https://cloud.google.com/storage/docs/json_api)
*   [Buckets Resource Reference](https://cloud.google.com/storage/docs/json_api/v1/buckets)
*   [Objects Resource Reference](https://cloud.google.com/storage/docs/json_api/v1/objects)

--------------------------------------------------------------------------------

## Translation Mapping Table

Draft Plan Field / Setting         | REST API Resource Field / Path                      | Notes / Action
:--------------------------------- | :-------------------------------------------------- | :-------------
**Bucket Name**                    | `name`                                              | String in request body. Must be globally unique.
**Project**                        | Query Parameter: `?project=[project-id]`            | Passed in the query string of the request URL.
**Location**                       | `location`                                          | E.g., `"us-central1"`, `"US"`, `"nam4"`. For zonal buckets, set to the region (e.g., `"us-east1"`).
**Placement**                      | `customPlacementConfig.dataLocations`               | Array of strings: `["us-east1", "us-west1"]` (custom dual-region) or `["us-east1-a"]` (zonal bucket). Omit for predefined dual-regions (`nam4`, `eur4`, `asia1`).
**Replication Speed (RPO)**        | `rpo`                                               | String: `"ASYNC_TURBO"` (for dual-region buckets).
**Storage Class**                  | `storageClass`                                      | `"STANDARD"`, `"NEARLINE"`, `"COLDLINE"`, `"ARCHIVE"`, `"RAPID"`.
**UBLA**                           | `iamConfiguration.uniformBucketLevelAccess.enabled` | Boolean. Always set to `true`.
**Public Access Prevention**       | `iamConfiguration.publicAccessPrevention`           | String: `"enforced"` or `"inherited"`.
**Soft Delete**                    | `softDeletePolicy.retentionDurationSeconds`         | Integer seconds: e.g., `604800` (7 days), `864000` (10 days). Set to `0` to disable.
**Object Versioning**              | `versioning.enabled`                                | Boolean. Enables/disables versioning.
**Encryption (CMEK)**              | `encryption.defaultKmsKeyName`                      | Full KMS key ID: `"projects/.../cryptoKeys/..."`.
**Restrict Encryption (CSEK)**     | `encryption.*EncryptionEnforcementConfig`           | Restricts encryption methods under `encryption`. See template below.
**Autoclass**                      | `autoclass.enabled`                                 | Boolean (`true` to enable; `storageClass` must be `"STANDARD"` or omitted).
**Hierarchical Namespace**         | `hierarchicalNamespace.enabled`                     | Boolean (`true` to enable).
**Labels**                         | `labels`                                            | JSON object of string key-value pairs (`{"k": "v"}`). Can be set directly on `POST` creation in REST.
**IP Filtering**                   | `ipFilter`                                          | Object defining IP/VPC rules. See template below.
**Lifecycle Policies (OLM)**       | `lifecycle.rule`                                    | Array of rule objects. See template below.
**CORS**                           | `cors`                                              | Array of CORS rule objects.
**Website Configuration**          | `website.mainPageSuffix` / `website.notFoundPage`   | Strings for index (`"index.html"`) and error (`"404.html"`) pages.
**Public IAM Policy**              | `storage.buckets.setIamPolicy`                      | Read-modify-write (`GET /iam` then `PUT /iam`) adding `allUsers` to `roles/storage.objectViewer`.
**Pub/Sub Notifications**          | `storage.notifications.insert`                      | `POST https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/notificationConfigs`.
**Bucket Retention Period**        | `retentionPolicy.retentionPeriod`                   | Integer seconds (e.g., `7776000` for 90 days).
**Lock Bucket Retention Policy**   | `storage.buckets.lockRetentionPolicy`               | `POST .../b/BUCKET_NAME/lockRetentionPolicy?ifMetagenerationMatch=METAGENERATION`. **Irreversible.**
**Object Retention (Object Lock)** | Query Parameter: `enableObjectRetention=true`       | Creation-only (`buckets.insert`) query param (`?project=...&enableObjectRetention=true`); **permanently** enables object retention.
**Set Object Retention**           | Object `retention` property                         | `{"mode": "Locked", "retainUntilTime": "2030-12-31T23:59:59Z"}` (`"Locked"` or `"Unlocked"`) on object upload or `PATCH`.
**Rapid Cache**                    | `storage.anywhereCaches.insert`                     | `POST https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/anywhereCaches`.

--------------------------------------------------------------------------------

## Helper Configuration Templates

### Encryption Enforcement, IP Filtering, Lifecycle, and CORS Snippets

Include only active top-level keys in your `POST`/`PATCH` body. Unlike
`gcloud`'s short root keys (`csekEnforcement`), the JSON API nests full
`*EncryptionEnforcementConfig` objects under `encryption`:

```json
{
  "encryption": {
    "googleManagedEncryptionEnforcementConfig": {"restrictionMode": "NotRestricted"},
    "customerManagedEncryptionEnforcementConfig": {"restrictionMode": "NotRestricted"},
    "customerSuppliedEncryptionEnforcementConfig": {"restrictionMode": "FullyRestricted"}
  },
  "ipFilter": {
    "mode": "Enabled",
    "allowAllServiceAgentAccess": true,
    "allowCrossOrgVpcs": false,
    "publicNetworkSource": {"allowedIpCidrRanges": ["192.0.2.0/24"]},
    "vpcNetworkSources": [
      {"network": "projects/PROJECT_ID/global/networks/NETWORK_NAME", "allowedIpCidrRanges": ["10.0.0.0/16"]}
    ]
  },
  "lifecycle": {
    "rule": [
      {"action": {"type": "AbortIncompleteMultipartUpload"}, "condition": {"age": 7}},
      {"action": {"type": "Delete"}, "condition": {"age": 365}}
    ]
  },
  "cors": [
    {
      "origin": ["https://example.appspot.com"],
      "method": ["GET", "PUT", "POST", "DELETE"],
      "responseHeader": ["Content-Type", "Authorization"],
      "maxAgeSeconds": 3600
    }
  ]
}
```

--------------------------------------------------------------------------------

## Executing REST Requests via cURL (Mandatory Attribution Header)

Every `curl` command MUST include
`Authorization: Bearer $(gcloud auth print-access-token)` (note:
`gcloud auth print-access-token` inside `curl` does NOT take the
`CLOUDSDK_METRICS_ENVIRONMENT` prefix) and the exact `User-Agent` header:

```bash
curl -X POST \
  "https://storage.googleapis.com/storage/v1/b?project=PROJECT_ID" \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "User-Agent: gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)" \
  -H "Content-Type: application/json" \
  -d @body.json
```

--------------------------------------------------------------------------------

## REST API Request Examples

All requests below use the `curl` headers above (`Authorization`,
`User-Agent: gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)`,
`Content-Type: application/json`). Bucket creation uses
`POST https://storage.googleapis.com/storage/v1/b?project=PROJECT_ID`; bucket
updates use `PATCH https://storage.googleapis.com/storage/v1/b/BUCKET_NAME`.

### Example 1: Sensitive Data / Compliance (CMEK, CSEK Restricted, Autoclass, Soft Delete, Retention, Labels, OLM, IP Filter)

*(For a baseline secure bucket without CMEK/Autoclass/IP filter, include only
`name`, `location`, `storageClass`, `iamConfiguration`, `softDeletePolicy`, and
`encryption.customerSuppliedEncryptionEnforcementConfig`.)*

**Method/URL:**
`POST https://storage.googleapis.com/storage/v1/b?project=my-compliance-project`

```json
{
  "name": "my-compliance-pii-bucket",
  "location": "us-central1",
  "storageClass": "STANDARD",
  "iamConfiguration": {
    "uniformBucketLevelAccess": {"enabled": true},
    "publicAccessPrevention": "enforced"
  },
  "encryption": {
    "defaultKmsKeyName": "projects/my-kms-project/locations/us-central1/keyRings/my-keyring/cryptoKeys/my-key",
    "customerSuppliedEncryptionEnforcementConfig": {"restrictionMode": "FullyRestricted"},
    "customerManagedEncryptionEnforcementConfig": {"restrictionMode": "NotRestricted"},
    "googleManagedEncryptionEnforcementConfig": {"restrictionMode": "NotRestricted"}
  },
  "softDeletePolicy": {"retentionDurationSeconds": 604800},
  "retentionPolicy": {"retentionPeriod": 7776000},
  "autoclass": {"enabled": true},
  "labels": {"data-class": "pii", "owner": "security-team"},
  "lifecycle": {
    "rule": [{"action": {"type": "AbortIncompleteMultipartUpload"}, "condition": {"age": 7}}]
  },
  "ipFilter": {
    "mode": "Enabled",
    "allowAllServiceAgentAccess": true,
    "allowCrossOrgVpcs": false,
    "publicNetworkSource": {"allowedIpCidrRanges": ["192.0.2.0/24"]},
    "vpcNetworkSources": [
      {"network": "projects/my-project/global/networks/my-vpc-network", "allowedIpCidrRanges": ["10.0.0.0/16"]}
    ]
  }
}
```

*(Note: To permanently lock the retention policy, send an empty POST request to
`POST
https://storage.googleapis.com/storage/v1/b/my-compliance-pii-bucket/lockRetentionPolicy?ifMetagenerationMatch=METAGENERATION`.
Locking is irreversible.)*

### Example 2: Static Website Hosting (Multi-Region `US`, Public Access, Website Config, CORS, Versioning)

**1. Create Bucket
(`POST https://storage.googleapis.com/storage/v1/b?project=my-frontend-project`):**

```json
{
  "name": "www.my-company-site.com",
  "location": "US",
  "storageClass": "STANDARD",
  "iamConfiguration": {
    "uniformBucketLevelAccess": {"enabled": true},
    "publicAccessPrevention": "inherited"
  },
  "softDeletePolicy": {"retentionDurationSeconds": 604800},
  "website": {"mainPageSuffix": "index.html", "notFoundPage": "404.html"},
  "cors": [
    {"origin": ["*"], "method": ["GET", "HEAD", "OPTIONS"], "responseHeader": ["Content-Type"], "maxAgeSeconds": 3600}
  ],
  "versioning": {"enabled": true}
}
```

**2. Set Public Read Access (Read-Modify-Write `GET /iam` then `PUT /iam`):**

> [!WARNING]
>
> `PUT /iam` replaces the entire IAM policy. Always
> `GET https://storage.googleapis.com/storage/v1/b/www.my-company-site.com/iam`
> first, append the new binding to the existing root-level `bindings` array
> while preserving `etag` (do NOT wrap in `{"policy": ...}`), and `PUT` back to
> `https://storage.googleapis.com/storage/v1/b/www.my-company-site.com/iam`:

```json
{
  "kind": "storage#policy",
  "etag": "CAE=",
  "bindings": ["<...existing projectOwner/Viewer bindings from GET...>", {"role": "roles/storage.objectViewer", "members": ["allUsers"]}]
}
```

### Example 3: AI/ML Checkpointing (Zonal `RAPID` Bucket in `us-east1-b`, HNS, Soft Delete Disabled)

**Method/URL:**
`POST https://storage.googleapis.com/storage/v1/b?project=my-ai-project`

```json
{
  "name": "my-training-checkpoints-us-east1-b",
  "location": "us-east1",
  "storageClass": "RAPID",
  "customPlacementConfig": {"dataLocations": ["us-east1-b"]},
  "iamConfiguration": {
    "uniformBucketLevelAccess": {"enabled": true},
    "publicAccessPrevention": "enforced"
  },
  "hierarchicalNamespace": {"enabled": true},
  "softDeletePolicy": {"retentionDurationSeconds": 0},
  "lifecycle": {
    "rule": [{"action": {"type": "Delete"}, "condition": {"age": 14}}]
  }
}
```

### Example 4: WORM Archive with Object Lock (Per-Object Retention)

**1. Create Bucket (`POST
https://storage.googleapis.com/storage/v1/b?project=my-legal-project&enableObjectRetention=true`):**

```json
{
  "name": "my-legal-archive-bucket",
  "location": "us-east1",
  "storageClass": "ARCHIVE",
  "iamConfiguration": {
    "uniformBucketLevelAccess": {"enabled": true},
    "publicAccessPrevention": "enforced"
  },
  "encryption": {
    "defaultKmsKeyName": "projects/my-kms-project/locations/us-east1/keyRings/my-keyring/cryptoKeys/my-key"
  },
  "softDeletePolicy": {"retentionDurationSeconds": 604800},
  "labels": {"compliance-type": "regulatory", "retention-period": "7y"},
  "lifecycle": {
    "rule": [{"action": {"type": "Delete"}, "condition": {"age": 2555}}]
  }
}
```

**2. Set Object Retention on Upload or Existing Object:**

> [!CAUTION]
>
> Setting object retention `mode` to `"Locked"` is permanent and irreversible.
> Once locked, retention cannot be removed or shortened (only extended).

*   **On Upload (`POST
    https://storage.googleapis.com/upload/storage/v1/b/my-legal-archive-bucket/o?uploadType=multipart`)**:
    Metadata JSON part (`"Unlocked"` or `"Locked"`): `{"name":
    "compliance_report_2026.pdf", "retention": {"mode": "Unlocked",
    "retainUntilTime": "2030-12-31T23:59:59Z"}}`.
*   **On Existing Object (`PATCH
    https://storage.googleapis.com/storage/v1/b/my-legal-archive-bucket/o/OBJECT_NAME?overrideUnlockedRetention=true`)**:
    Body `{"retention": {"mode": "Locked", "retainUntilTime":
    "2030-12-31T23:59:59Z"}}`. You MUST append `?overrideUnlockedRetention=true`
    when changing `Unlocked` to `Locked`, shortening `retainUntilTime`, or
    removing retention, or the request will fail.
sdk.md 4.6 KB
# Cloud Storage SDK Reference

> [!IMPORTANT]
>
> **DO NOT RUN THESE CONFIGURATIONS AUTOMATICALLY.** Present the generated SDK
> code snippets to the user for review and integration. Read the target
> language's dedicated reference file (`references/sdk_python.md`,
> `references/sdk_go.md`, `references/sdk_java.md`, or `references/sdk_cpp.md`)
> for its complete **Translation Mapping Table** and code examples.

## Official Documentation Reference

### Cloud Storage (Data Plane)

*   [Cloud Storage C++ Client Library](https://cloud.google.com/cpp/docs/reference/storage/latest)
*   [Cloud Storage Go Package Reference](https://pkg.go.dev/cloud.google.com/go/storage)
*   [Cloud Storage Java Client Library](https://cloud.google.com/java/docs/reference/google-cloud-storage/latest/overview)
*   [Cloud Storage Python Client Library](https://cloud.google.com/python/docs/reference/storage/latest)

### Cloud Storage Control (Control Plane — Hierarchical Namespace, Folders, Rapid Cache)

*   [Cloud Storage Control C++ Client Library](https://cloud.google.com/cpp/docs/reference/storagecontrol/latest)
*   [Cloud Storage Control Go Package Reference](https://pkg.go.dev/cloud.google.com/go/storage/control/apiv2)
*   [Cloud Storage Control Java Client Library](https://cloud.google.com/java/docs/reference/google-cloud-storage/latest/com.google.storage.control.v2.StorageControlClient)
*   [Cloud Storage Control Python Client Library](https://cloud.google.com/python/docs/reference/google-cloud-storage-control/latest/google.cloud.storage_control_v2.services.storage_control.StorageControlClient)

--------------------------------------------------------------------------------

## SDK Language Guides & Version Gates Summary

Language   | Language Guide                    | `EncryptionEnforcementConfig` Min Version | Unexposed Features (Require REST / `gcloud` / Terraform)
:--------- | :-------------------------------- | :---------------------------------------- | :-------------------------------------------------------
**Python** | [Python SDK Guide](sdk_python.md) | `google-cloud-storage >= 3.10.0`          | All core bucket settings exposed (`StorageControlClient` for Rapid Cache / HNS folders)
**Go**     | [Go SDK Guide](sdk_go.md)         | `cloud.google.com/go/storage >= v1.61.0`  | **IP Filtering** (`ipFilter` / `allowCrossOrgVpcs` not exposed in Go v1 client)
**Java**   | [Java SDK Guide](sdk_java.md)     | `google-cloud-storage >= 2.55.0`          | All core bucket settings exposed (`StorageControlClient` for Rapid Cache / HNS folders)
**C++**    | [C++ SDK Guide](sdk_cpp.md)       | `google-cloud-cpp >= 2.46.0`              | **IP Filtering** (`ipFilter` / `allowCrossOrgVpcs` not exposed in C++ client)

> [!IMPORTANT]
>
> Whenever `EncryptionEnforcementConfig` (restricting CSEK/CMEK/GMEK) is
> configured in an SDK snippet, you **MUST** include a warning specifying the
> minimum supported SDK version from the table above and noting that users on
> older SDK versions must configure encryption enforcement via the
> [REST API](rest.md), [gcloud](gcloud.md), or [Terraform](terraform.md). When
> generating SDK code snippets for the user, do **not** run local shell or
> language commands (e.g., `python3`, `pip`, `go list`) to inspect the host
> machine's installed SDK version unless the user explicitly asks to inspect or
> execute in their local environment.

--------------------------------------------------------------------------------

## Handling Unexposed Features

When a required setting is marked as *Not exposed* in the target language's
client library (or the user is on an older SDK version), recommend one of these
integration patterns:

1.  **Pattern 1: Separate Provisioning from Application Logic (Recommended)**:
    Use [Terraform](terraform.md) or [gcloud](gcloud.md) to create and configure
    the bucket (including IP Filtering or Encryption Enforcement), and use the
    SDK in application code for data-plane operations.
2.  **Pattern 2: Hybrid SDK + Direct REST API Call**: Use the SDK to create the
    bucket and obtain an OAuth2 token from the SDK credentials helper, then send
    a `PATCH https://storage.googleapis.com/storage/v1/b/BUCKET_NAME` request
    with the JSON payload, `Authorization: Bearer <token>`, and
    `User-Agent: gcs-skills/1.0 (skill:google-cloud-storage-bucket-architect)`
    headers (see [REST API Reference](rest.md)).
3.  **Pattern 3: Hybrid SDK + Auto-Generated API Client (Go Only)**: Combine the
    standard `cloud.google.com/go/storage` client with the raw auto-generated
    `google.golang.org/api/storage/v1` client for unexposed fields (both clients
    can share the same authenticated HTTP client for connection reuse).
sdk_cpp.md 13.4 KB
# C++ SDK Reference & Examples

This guide translates a **Draft Bucket Creation Plan** (from Phase 2) into the
official Google Cloud Storage C++ client library
(`google/cloud/storage/client.h`).

*   [Cloud Storage C++ Client Library](https://cloud.google.com/cpp/docs/reference/storage/latest)

## Version Requirements

> [!IMPORTANT]
>
> **Encryption Enforcement Config**
> (`customer_supplied_encryption_enforcement_config`) requires the C++ Cloud
> Storage SDK version **2.46.0** or higher. If using a version below 2.46.0,
> configure this setting via the [REST API](rest.md), [gcloud](gcloud.md), or
> [Terraform](terraform.md).

## Translation Mapping Table

Draft Plan Field / Setting          | C++ SDK Feature / Attribute (`::google::cloud::storage`)
:---------------------------------- | :-------------------------------------------------------
**Client Initialization**           | `namespace gcs = ::google::cloud::storage; auto client = gcs::Client();`
**Bucket Name & Project Creation**  | `client.CreateBucket(bucket_name, std::move(metadata), gcs::OverrideDefaultProject(project_id))`
**Location**                        | `metadata.set_location("us-central1")`
**Placement (Dual-Region / Zonal)** | `metadata.set_custom_placement_config(gcs::BucketCustomPlacementConfig{{"us-east1-b"}})`
**Replication Speed (RPO)**         | `metadata.set_rpo("ASYNC_TURBO")`
**Storage Class**                   | `metadata.set_storage_class(gcs::storage_class::Standard())` (or `Nearline()`, `Coldline()`, `Archive()`, `"RAPID"`)
**UBLA**                            | `gcs::BucketIamConfiguration iam_config; iam_config.uniform_bucket_level_access = gcs::UniformBucketLevelAccess{true, {}}; metadata.set_iam_configuration(iam_config)`
**Public Access Prevention**        | `iam_config.public_access_prevention = gcs::PublicAccessPreventionEnforced()` (or `gcs::PublicAccessPreventionInherited()`; pass via `metadata.set_iam_configuration(iam_config)`)
**Soft Delete**                     | `metadata.set_soft_delete_policy(std::chrono::seconds(7 * 24 * 3600))` (`std::chrono::seconds(0)` to disable)
**Object Versioning**               | `metadata.set_versioning(gcs::BucketVersioning{true})` (or `metadata.enable_versioning()`)
**Encryption (CMEK)**               | `gcs::BucketEncryption encryption; encryption.default_kms_key_name = kms_key; metadata.set_encryption(encryption)`
**Restrict Encryption (CSEK)**      | `encryption.customer_supplied_encryption_enforcement_config.restriction_mode = "FullyRestricted"` (**v2.46.0+**)
**Autoclass**                       | `metadata.set_autoclass(gcs::BucketAutoclass{true})`
**Hierarchical Namespace**          | `metadata.set_hierarchical_namespace(gcs::BucketHierarchicalNamespace{true})`
**Labels**                          | `metadata.upsert_label("key", "value")`
**IP Filtering**                    | *Not exposed in C++ client library* (use [REST API](rest.md), [gcloud](gcloud.md), or [Terraform](terraform.md))
**Allow Cross-Org VPCs**            | *Not exposed in C++ client library* (use [REST API](rest.md), [gcloud](gcloud.md), or [Terraform](terraform.md))
**Lifecycle Policies (OLM)**        | `metadata.set_lifecycle(gcs::BucketLifecycle{{gcs::LifecycleRule(condition, action)}})`
**CORS**                            | `metadata.set_cors({gcs::CorsEntry{3600, {"GET", "HEAD"}, {"*"}, {"Content-Type"}}})`
**Website Configuration**           | `metadata.set_website(gcs::BucketWebsite{"index.html", "404.html"})`
**Public IAM Policy**               | `client.GetNativeBucketIamPolicy(bucket_name, gcs::RequestedPolicyVersion(3))` -> append `allUsers` -> `client.SetNativeBucketIamPolicy(...)`
**Pub/Sub Notifications**           | `client.CreateNotification(bucket_name, topic_name, gcs::payload_format::JsonApiV1(), gcs::NotificationMetadata())`
**Bucket Retention Period**         | `metadata.set_retention_policy(std::chrono::seconds(90 * 24 * 3600))`
**Lock Bucket Retention Policy**    | `client.LockBucketRetentionPolicy(bucket_name, metadata->metageneration())` (**irreversible**)
**Object Retention (Object Lock)**  | `client.CreateBucket(bucket_name, std::move(metadata), gcs::EnableObjectRetention(true), gcs::OverrideDefaultProject(project_id))`
**Set Object Retention**            | `gcs::WithObjectMetadata(gcs::ObjectMetadata{}.set_retention(gcs::ObjectRetention{gcs::ObjectRetentionLocked(), retain_until}))` (or `gcs::ObjectRetentionUnlocked()`; on `client.PatchObject`, pass `gcs::OverrideUnlockedRetention(true)` to shorten/remove/lock `Unlocked`)
**Rapid Cache**                     | `StorageControlClient::CreateAnywhereCache` (`google/cloud/storagecontrol/v2/storage_control_client.h`)

--------------------------------------------------------------------------------

## C++ SDK Examples

### Example 1: Sensitive Data / Compliance (UBLA, PAP, CMEK, CSEK Restricted, Soft Delete, Retention, Autoclass, Labels, OLM)

*(For a baseline secure GMEK bucket without CMEK, keep `STANDARD`, UBLA,
enforced PAP, 7-day Soft Delete, `gcs::OverrideDefaultProject(project_id)`, and
`.set_encryption(encryption)` with
`customer_supplied_encryption_enforcement_config.restriction_mode =
"FullyRestricted"`, while omitting `default_kms_key_name` and unused optional
calls.)*

```cpp
#include "google/cloud/storage/client.h"
#include <chrono>
#include <string>
#include <utility>

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;

StatusOr<gcs::BucketMetadata> CreateComplianceBucket(gcs::Client client,
                                                     std::string const& project_id,
                                                     std::string const& bucket_name,
                                                     std::string const& kms_key) {
  gcs::BucketIamConfiguration iam_config;
  iam_config.uniform_bucket_level_access = gcs::UniformBucketLevelAccess{true, {}};
  iam_config.public_access_prevention = gcs::PublicAccessPreventionEnforced();

  gcs::BucketEncryption encryption;
  encryption.default_kms_key_name = kms_key;  // Omit for standard GMEK buckets while keeping CSEK FullyRestricted below
  // Enforcement config fields require google-cloud-cpp >= 2.46.0
  encryption.customer_supplied_encryption_enforcement_config.restriction_mode = "FullyRestricted";
  encryption.customer_managed_encryption_enforcement_config.restriction_mode = "NotRestricted";
  encryption.google_managed_encryption_enforcement_config.restriction_mode = "NotRestricted";

  gcs::BucketLifecycle lifecycle;
  lifecycle.rule = {
      gcs::LifecycleRule(
          gcs::LifecycleRule::MaxAge(7),
          gcs::LifecycleRule::AbortIncompleteMultipartUpload()
      )
  };

  gcs::BucketMetadata metadata = gcs::BucketMetadata()
      .set_storage_class(gcs::storage_class::Standard())
      .set_location("us-central1")
      .set_iam_configuration(iam_config)
      .set_encryption(encryption)
      .set_soft_delete_policy(std::chrono::seconds(7 * 24 * 3600)) // 7 days (use 30 * 24 * 3600 for 30 days)
      .set_retention_policy(std::chrono::seconds(90 * 24 * 3600))  // 90 days
      .set_autoclass(gcs::BucketAutoclass{true})
      .upsert_label("data-class", "pii")
      .upsert_label("owner", "security-team")
      .set_lifecycle(lifecycle);

  // NOTE: IP Filtering is not exposed in the C++ client library; configure via REST, gcloud, or Terraform.
  return client.CreateBucket(bucket_name, std::move(metadata),
                             gcs::OverrideDefaultProject(project_id));
}

// WARNING: Locking the retention policy is permanent and irreversible.
StatusOr<gcs::BucketMetadata> LockRetentionPolicy(gcs::Client client,
                                                  std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> metadata = client.GetBucketMetadata(bucket_name);
  if (!metadata) return metadata;
  return client.LockBucketRetentionPolicy(bucket_name, metadata->metageneration());
}
```

### Example 2: Static Website Hosting (Multi-Region `US`, Public Access, Website, CORS, Versioning)

```cpp
#include "google/cloud/storage/client.h"
#include <chrono>
#include <string>
#include <utility>

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;

StatusOr<gcs::BucketMetadata> CreateStaticWebsiteBucket(gcs::Client client,
                                                       std::string const& project_id,
                                                       std::string const& bucket_name) {
  gcs::CorsEntry cors;
  cors.max_age_seconds = 3600;
  cors.method = {"GET", "HEAD", "OPTIONS"};
  cors.origin = {"*"};
  cors.response_header = {"Content-Type"};

  gcs::BucketMetadata metadata = gcs::BucketMetadata()
      .set_storage_class(gcs::storage_class::Standard())
      .set_location("US")
      .set_iam_configuration(gcs::BucketIamConfiguration{
          gcs::UniformBucketLevelAccess{true, {}},
          gcs::PublicAccessPreventionInherited()
      })
      .set_versioning(gcs::BucketVersioning{true})
      .set_soft_delete_policy(std::chrono::seconds(7 * 24 * 3600))
      .set_website(gcs::BucketWebsite{"index.html", "404.html"})
      .set_cors({cors});

  StatusOr<gcs::BucketMetadata> bucket = client.CreateBucket(
      bucket_name, std::move(metadata), gcs::OverrideDefaultProject(project_id));
  if (!bucket) return bucket;

  auto current_policy = client.GetNativeBucketIamPolicy(
      bucket_name, gcs::RequestedPolicyVersion(3));
  if (!current_policy) return current_policy.status();

  current_policy->set_version(3);
  current_policy->bindings().emplace_back(
      gcs::NativeIamBinding("roles/storage.objectViewer", {"allUsers"}));

  auto updated = client.SetNativeBucketIamPolicy(bucket_name, *current_policy);
  if (!updated) return updated.status();

  return bucket;
}
```

### Example 3: AI/ML Checkpointing (Zonal `RAPID` Bucket in `us-east1-b`, HNS, Soft Delete Disabled)

```cpp
#include "google/cloud/storage/client.h"
#include <chrono>
#include <string>
#include <utility>

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;

StatusOr<gcs::BucketMetadata> CreateCheckpointBucket(gcs::Client client,
                                                     std::string const& project_id,
                                                     std::string const& bucket_name) {
  gcs::BucketIamConfiguration iam_config;
  iam_config.uniform_bucket_level_access = gcs::UniformBucketLevelAccess{true, {}};
  iam_config.public_access_prevention = gcs::PublicAccessPreventionEnforced();

  gcs::BucketLifecycle lifecycle;
  lifecycle.rule = {
      gcs::LifecycleRule(gcs::LifecycleRule::MaxAge(14), gcs::LifecycleRule::Delete())
  };

  gcs::BucketMetadata metadata = gcs::BucketMetadata()
      .set_storage_class("RAPID")
      .set_location("us-east1")
      .set_custom_placement_config(gcs::BucketCustomPlacementConfig{{"us-east1-b"}})
      .set_iam_configuration(iam_config)
      .set_hierarchical_namespace(gcs::BucketHierarchicalNamespace{true})
      .set_soft_delete_policy(std::chrono::seconds(0))
      .set_lifecycle(lifecycle);

  return client.CreateBucket(bucket_name, std::move(metadata),
                             gcs::OverrideDefaultProject(project_id));
}
```

### Example 4: WORM Archive with Object Lock (Per-Object Retention)

> [!CAUTION]
>
> Setting per-object retention mode to `"Locked"` is permanent and irreversible.
> Once set, the mode cannot be changed back, the retention date can only be
> extended (never shortened or removed), and objects cannot be deleted or
> overwritten by anyone until the retention date expires.

```cpp
#include "google/cloud/storage/client.h"
#include <chrono>
#include <string>
#include <utility>

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;

StatusOr<gcs::BucketMetadata> CreateRegulatoryWormBucket(gcs::Client client,
                                                         std::string const& project_id,
                                                         std::string const& bucket_name,
                                                         std::string const& kms_key_id) {
  gcs::BucketIamConfiguration iam_config;
  iam_config.uniform_bucket_level_access = gcs::UniformBucketLevelAccess{true, {}};
  iam_config.public_access_prevention = gcs::PublicAccessPreventionEnforced();

  gcs::BucketLifecycle lifecycle;
  lifecycle.rule = {
      gcs::LifecycleRule(gcs::LifecycleRule::MaxAge(2555), gcs::LifecycleRule::Delete())
  };

  gcs::BucketMetadata metadata = gcs::BucketMetadata()
      .set_storage_class(gcs::storage_class::Archive())
      .set_location("us-east1")
      .set_iam_configuration(iam_config)
      .set_encryption(gcs::BucketEncryption{kms_key_id})
      .upsert_label("compliance-type", "regulatory")
      .upsert_label("retention-period", "7y")
      .set_soft_delete_policy(std::chrono::seconds(7 * 24 * 3600))
      .set_lifecycle(lifecycle);

  return client.CreateBucket(bucket_name, std::move(metadata),
                             gcs::EnableObjectRetention(true),
                             gcs::OverrideDefaultProject(project_id));
}

StatusOr<gcs::ObjectMetadata> UploadObjectWithRetention(gcs::Client client,
                                                        std::string const& bucket_name,
                                                        std::string const& object_name,
                                                        std::string const& contents) {
  auto retain_until = std::chrono::system_clock::from_time_t(1924991999); // 2030-12-31T23:59:59Z
  return client.InsertObject(
      bucket_name, object_name, contents,
      gcs::WithObjectMetadata(gcs::ObjectMetadata{}.set_retention(
          gcs::ObjectRetention{gcs::ObjectRetentionLocked(), retain_until})));
}
```
sdk_go.md 11.9 KB
# Go SDK Reference & Examples

This guide translates a **Draft Bucket Creation Plan** (from Phase 2) into the
official Cloud Storage Go client library (`cloud.google.com/go/storage`).

*   [Cloud Storage Go Package Reference](https://pkg.go.dev/cloud.google.com/go/storage)

## Version Requirements

> [!IMPORTANT]
>
> **Encryption Enforcement Config**
> (`CustomerSuppliedEncryptionEnforcementConfig`) requires
> `cloud.google.com/go/storage` version **1.61.0** or higher. If using a version
> below 1.61.0, configure this setting via the [REST API](rest.md),
> [gcloud](gcloud.md), or [Terraform](terraform.md).

## Translation Mapping Table

Draft Plan Field / Setting          | Go SDK Feature / Attribute (`cloud.google.com/go/storage`)
:---------------------------------- | :---------------------------------------------------------
**Client Initialization**           | `client, err := storage.NewClient(ctx)`
**Bucket Name & Creation**          | `bucket := client.Bucket(bucketName); err := bucket.Create(ctx, projectID, attrs)`
**Location**                        | `BucketAttrs.Location: "us-central1"`
**Placement (Dual-Region / Zonal)** | `BucketAttrs.CustomPlacementConfig: &storage.CustomPlacementConfig{DataLocations: []string{"us-east1-b"}}`
**Replication Speed (RPO)**         | `BucketAttrs.RPO: storage.RPOAsyncTurbo`
**Storage Class**                   | `BucketAttrs.StorageClass: "STANDARD"` (or `"NEARLINE"`, `"COLDLINE"`, `"ARCHIVE"`, `"RAPID"`)
**UBLA**                            | `BucketAttrs.UniformBucketLevelAccess: storage.UniformBucketLevelAccess{Enabled: true}`
**Public Access Prevention**        | `BucketAttrs.PublicAccessPrevention: storage.PublicAccessPreventionEnforced` (or `storage.PublicAccessPreventionInherited`)
**Soft Delete**                     | `BucketAttrs.SoftDeletePolicy: &storage.SoftDeletePolicy{RetentionDuration: 7 * 24 * time.Hour}` (`0` to disable)
**Object Versioning**               | `BucketAttrs.VersioningEnabled: true`
**Encryption (CMEK)**               | `BucketAttrs.Encryption: &storage.BucketEncryption{DefaultKMSKeyName: kmsKeyID}`
**Restrict Encryption (CSEK)**      | `BucketAttrs.CustomerSuppliedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{RestrictionMode: storage.FullyRestricted}` (**v1.61.0+**)
**Autoclass**                       | `BucketAttrs.Autoclass: &storage.Autoclass{Enabled: true}`
**Hierarchical Namespace**          | `BucketAttrs.HierarchicalNamespace: &storage.HierarchicalNamespace{Enabled: true}`
**Labels**                          | `BucketAttrs.Labels: map[string]string{"key": "value"}`
**IP Filtering**                    | *Not exposed in Go v1 client library* (use [REST API](rest.md), [gcloud](gcloud.md), or [Terraform](terraform.md))
**Allow Cross-Org VPCs**            | *Not exposed in Go v1 client library* (use [REST API](rest.md), [gcloud](gcloud.md), or [Terraform](terraform.md))
**Lifecycle Policies (OLM)**        | `BucketAttrs.Lifecycle: storage.Lifecycle{Rules: []storage.LifecycleRule{...}}`
**CORS**                            | `BucketAttrs.CORS: []storage.CORS{{MaxAge: 3600 * time.Second, Methods: ..., Origins: ..., ResponseHeaders: ...}}`
**Website Configuration**           | `BucketAttrs.Website: &storage.BucketWebsite{MainPageSuffix: "index.html", NotFoundPage: "404.html"}`
**Public IAM Policy**               | `policy, _ := bucket.IAM().Policy(ctx)` -> `policy.Add(iam.AllUsers, "roles/storage.objectViewer")` -> `bucket.IAM().SetPolicy(ctx, policy)`
**Pub/Sub Notifications**           | `bucket.AddNotification(ctx, &storage.Notification{TopicProjectID: ..., TopicID: ..., PayloadFormat: storage.JSONPayload})`
**Bucket Retention Period**         | `BucketAttrs.RetentionPolicy: &storage.RetentionPolicy{RetentionPeriod: 90 * 24 * time.Hour}`
**Lock Bucket Retention Policy**    | `bucket.If(storage.BucketConditions{MetagenerationMatch: attrs.MetaGeneration}).LockRetentionPolicy(ctx)` (**irreversible**)
**Object Retention (Object Lock)**  | `bucket := client.Bucket(bucketName).SetObjectRetention(true)` (before `bucket.Create`)
**Set Object Retention**            | `wc.ObjectAttrs.Retention = &storage.ObjectRetention{Mode: "Locked", RetainUntil: ...}` (or `"Unlocked"`; or `obj.Update(ctx, storage.ObjectAttrsToUpdate{Retention: ...})`, chaining `obj.OverrideUnlockedRetention(true)` to shorten/remove/lock `Unlocked`)
**Rapid Cache**                     | `StorageControlClient.CreateAnywhereCache` (`cloud.google.com/go/storage/control/apiv2`)

--------------------------------------------------------------------------------

## Go SDK Examples

### Example 1: Sensitive Data / Compliance (UBLA, PAP, CMEK, CSEK Restricted, Soft Delete, Retention, Autoclass, Labels, OLM)

*(For a baseline secure bucket, keep `STANDARD`, UBLA, enforced PAP, 7-day Soft
Delete, `CustomerSuppliedEncryptionEnforcementConfig` (`FullyRestricted`), and
`projectID`, omitting unused optional fields in `storage.BucketAttrs`.)*

```go
import (
    "context"
    "time"

    "cloud.google.com/go/storage"
)

func CreateComplianceBucket(ctx context.Context, client *storage.Client, projectID, bucketName, kmsKeyID string) (*storage.BucketAttrs, error) {
    bucket := client.Bucket(bucketName)
    attrs := &storage.BucketAttrs{
        Location:     "us-central1",
        StorageClass: "STANDARD",
        UniformBucketLevelAccess: storage.UniformBucketLevelAccess{
            Enabled: true,
        },
        PublicAccessPrevention: storage.PublicAccessPreventionEnforced,
        Encryption: &storage.BucketEncryption{
            DefaultKMSKeyName: kmsKeyID,
        },
        // Requires cloud.google.com/go/storage >= v1.61.0
        CustomerSuppliedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
            RestrictionMode: storage.FullyRestricted,
        },
        // NOTE: IP Filtering is not exposed in the Go v1 client library; configure via REST, gcloud, or Terraform.
        // WARNING: Locking the retention policy is permanent and irreversible:
        // bucket.If(storage.BucketConditions{MetagenerationMatch: attrs.MetaGeneration}).LockRetentionPolicy(ctx)
        RetentionPolicy: &storage.RetentionPolicy{
            RetentionPeriod: 90 * 24 * time.Hour,
        },
        Autoclass: &storage.Autoclass{
            Enabled: true,
        },
        Labels: map[string]string{
            "data-class": "pii",
            "owner":      "security-team",
        },
        Lifecycle: storage.Lifecycle{
            Rules: []storage.LifecycleRule{
                {
                    Action:    storage.LifecycleAction{Type: "AbortIncompleteMultipartUpload"},
                    Condition: storage.LifecycleCondition{AgeInDays: 7},
                },
            },
        },
        SoftDeletePolicy: &storage.SoftDeletePolicy{
            RetentionDuration: 7 * 24 * time.Hour,
        },
    }
    if err := bucket.Create(ctx, projectID, attrs); err != nil {
        return nil, err
    }
    return bucket.Attrs(ctx)
}
```

### Example 2: Static Website Hosting (Multi-Region `US`, Public Access, Website, CORS, Versioning)

```go
import (
    "context"
    "time"

    "cloud.google.com/go/iam"
    "cloud.google.com/go/storage"
)

func CreateStaticWebsiteBucket(ctx context.Context, client *storage.Client, projectID, bucketName string) (*storage.BucketAttrs, error) {
    bucket := client.Bucket(bucketName)
    attrs := &storage.BucketAttrs{
        Location:     "US",
        StorageClass: "STANDARD",
        UniformBucketLevelAccess: storage.UniformBucketLevelAccess{
            Enabled: true,
        },
        PublicAccessPrevention: storage.PublicAccessPreventionInherited,
        VersioningEnabled:      true,
        SoftDeletePolicy: &storage.SoftDeletePolicy{
            RetentionDuration: 7 * 24 * time.Hour,
        },
        Website: &storage.BucketWebsite{
            MainPageSuffix: "index.html",
            NotFoundPage:   "404.html",
        },
        CORS: []storage.CORS{{
            MaxAge:          3600 * time.Second,
            Methods:         []string{"GET", "HEAD", "OPTIONS"},
            Origins:         []string{"*"},
            ResponseHeaders: []string{"Content-Type"},
        }},
    }
    if err := bucket.Create(ctx, projectID, attrs); err != nil {
        return nil, err
    }

    iamHandle := bucket.IAM()
    policy, err := iamHandle.Policy(ctx)
    if err != nil {
        return nil, err
    }
    policy.Add(iam.AllUsers, "roles/storage.objectViewer")
    if err := iamHandle.SetPolicy(ctx, policy); err != nil {
        return nil, err
    }
    return bucket.Attrs(ctx)
}
```

### Example 3: AI/ML Checkpointing (Zonal `RAPID` Bucket in `us-east1-b`, HNS, Soft Delete Disabled)

```go
import (
    "context"

    "cloud.google.com/go/storage"
)

func CreateCheckpointBucket(ctx context.Context, client *storage.Client, projectID, bucketName string) (*storage.BucketAttrs, error) {
    bucket := client.Bucket(bucketName)
    attrs := &storage.BucketAttrs{
        Location:     "us-east1",
        StorageClass: "RAPID",
        UniformBucketLevelAccess: storage.UniformBucketLevelAccess{
            Enabled: true,
        },
        PublicAccessPrevention: storage.PublicAccessPreventionEnforced,
        CustomPlacementConfig: &storage.CustomPlacementConfig{
            DataLocations: []string{"us-east1-b"},
        },
        HierarchicalNamespace: &storage.HierarchicalNamespace{
            Enabled: true,
        },
        Lifecycle: storage.Lifecycle{
            Rules: []storage.LifecycleRule{
                {
                    Action:    storage.LifecycleAction{Type: "Delete"},
                    Condition: storage.LifecycleCondition{AgeInDays: 14},
                },
            },
        },
        SoftDeletePolicy: &storage.SoftDeletePolicy{
            RetentionDuration: 0,
        },
    }
    if err := bucket.Create(ctx, projectID, attrs); err != nil {
        return nil, err
    }
    return bucket.Attrs(ctx)
}
```

### Example 4: WORM Archive with Object Lock (Per-Object Retention)

> [!CAUTION]
>
> Setting per-object retention mode to `"Locked"` is permanent and irreversible.
> Once set, the mode cannot be changed back, the retention date can only be
> extended (never shortened or removed), and objects cannot be deleted or
> overwritten by anyone until the retention date expires.

```go
import (
    "context"
    "time"

    "cloud.google.com/go/storage"
)

func CreateRegulatoryWormBucket(ctx context.Context, client *storage.Client, projectID, bucketName, kmsKeyID string) (*storage.BucketAttrs, error) {
    bucket := client.Bucket(bucketName).SetObjectRetention(true)
    attrs := &storage.BucketAttrs{
        Location:     "us-east1",
        StorageClass: "ARCHIVE",
        UniformBucketLevelAccess: storage.UniformBucketLevelAccess{
            Enabled: true,
        },
        PublicAccessPrevention: storage.PublicAccessPreventionEnforced,
        Encryption: &storage.BucketEncryption{
            DefaultKMSKeyName: kmsKeyID,
        },
        Labels: map[string]string{
            "compliance-type":  "regulatory",
            "retention-period": "7y",
        },
        SoftDeletePolicy: &storage.SoftDeletePolicy{
            RetentionDuration: 7 * 24 * time.Hour,
        },
        Lifecycle: storage.Lifecycle{
            Rules: []storage.LifecycleRule{
                {
                    Action:    storage.LifecycleAction{Type: "Delete"},
                    Condition: storage.LifecycleCondition{AgeInDays: 2555},
                },
            },
        },
    }
    if err := bucket.Create(ctx, projectID, attrs); err != nil {
        return nil, err
    }
    return bucket.Attrs(ctx)
}

func UploadObjectWithRetention(ctx context.Context, client *storage.Client, bucketName, objectName string) error {
    wc := client.Bucket(bucketName).Object(objectName).NewWriter(ctx)
    wc.ObjectAttrs.Retention = &storage.ObjectRetention{
        Mode:        "Locked",
        RetainUntil: time.Date(2030, 12, 31, 23, 59, 59, 0, time.UTC),
    }
    if _, err := wc.Write([]byte("compliance data")); err != nil {
        wc.Close()
        return err
    }
    return wc.Close()
}
```
sdk_java.md 15.6 KB
# Java SDK Reference & Examples

This guide translates a **Draft Bucket Creation Plan** (from Phase 2) into the
official Cloud Storage Java client library (`google-cloud-storage`).

*   [Cloud Storage Client for Java Documentation](https://cloud.google.com/java/docs/reference/google-cloud-storage/latest/overview)

## Version Requirements

> [!IMPORTANT]
>
> **Encryption Enforcement Config**
> (`CustomerSuppliedEncryptionEnforcementConfig`) requires the Java SDK version
> **2.55.0** or higher. If using a version below 2.55.0, configure this setting
> via the [REST API](rest.md), [gcloud](gcloud.md), or
> [Terraform](terraform.md).

## Translation Mapping Table

Draft Plan Field / Setting          | Java SDK Feature / Attribute (`com.google.cloud.storage`)
:---------------------------------- | :--------------------------------------------------------
**Client Initialization**           | `Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();`
**Bucket Name & Creation**          | `BucketInfo bucketInfo = BucketInfo.newBuilder(bucketName)...build(); storage.create(bucketInfo);`
**Location**                        | `BucketInfo.Builder.setLocation("us-central1")`
**Placement (Dual-Region / Zonal)** | `BucketInfo.Builder.setCustomPlacementConfig(CustomPlacementConfig.newBuilder().setDataLocations(List).build())`
**Replication Speed (RPO)**         | `BucketInfo.Builder.setRpo(Rpo.ASYNC_TURBO)`
**Storage Class**                   | `BucketInfo.Builder.setStorageClass(StorageClass.STANDARD)` (or `NEARLINE`, `COLDLINE`, `ARCHIVE`, `StorageClass.valueOf("RAPID")`)
**UBLA**                            | `IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true)`
**Public Access Prevention**        | `IamConfiguration.newBuilder().setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.ENFORCED)` (or `INHERITED`)
**Soft Delete**                     | `BucketInfo.Builder.setSoftDeletePolicy(SoftDeletePolicy.newBuilder().setRetentionDuration(Duration.ofDays(7)).build())` (`Duration.ZERO` to disable)
**Object Versioning**               | `BucketInfo.Builder.setVersioningEnabled(true)`
**Encryption (CMEK)**               | `BucketInfo.Builder.setDefaultKmsKeyName(kmsKeyId)`
**Restrict Encryption (CSEK)**      | `BucketInfo.Builder.setCustomerSuppliedEncryptionEnforcementConfig(CustomerSuppliedEncryptionEnforcementConfig.of(EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED))` (**v2.55.0+**)
**Autoclass**                       | `BucketInfo.Builder.setAutoclass(BucketInfo.Autoclass.newBuilder().setEnabled(true).build())`
**Hierarchical Namespace**          | `BucketInfo.Builder.setHierarchicalNamespace(BucketInfo.HierarchicalNamespace.newBuilder().setEnabled(true).build())`
**Labels**                          | `BucketInfo.Builder.setLabels(labelsMap)`
**IP Filtering**                    | `BucketInfo.Builder.setIpFilter(BucketInfo.IpFilter.newBuilder()...build())`
**Allow Cross-Org VPCs**            | `BucketInfo.IpFilter.Builder.setAllowCrossOrgVpcs(false)`
**Lifecycle Policies (OLM)**        | `BucketInfo.Builder.setLifecycleRules(Collections.singletonList(new BucketInfo.LifecycleRule(action, condition)))`
**CORS**                            | `BucketInfo.Builder.setCors(Collections.singletonList(cors))`
**Website Configuration**           | `BucketInfo.Builder.setIndexPage("index.html").setNotFoundPage("404.html")`
**Public IAM Policy**               | `Policy policy = storage.getIamPolicy(bucketName)` -> `.toBuilder().addIdentity(StorageRoles.objectViewer(), Identity.allUsers()).build()` -> `storage.setIamPolicy(bucketName, policy)`
**Pub/Sub Notifications**           | `storage.createNotification(bucketName, notificationInfo)`
**Bucket Retention Period**         | `BucketInfo.Builder.setRetentionPeriodDuration(Duration.ofDays(90))`
**Lock Bucket Retention Policy**    | `bucket.lockRetentionPolicy(Storage.BucketTargetOption.metagenerationMatch())` (or `storage.lockRetentionPolicy(bucketInfo, ...)`; **irreversible**)
**Object Retention (Object Lock)**  | `storage.create(bucketInfo, Storage.BucketTargetOption.enableObjectRetention(true))`
**Set Object Retention**            | `BlobInfo.Builder.setRetention(BlobInfo.Retention.newBuilder().setMode(BlobInfo.Retention.Mode.LOCKED).setRetainUntilTime(retainUntil).build())` (or `BlobInfo.Retention.Mode.UNLOCKED`; pass `Storage.BlobTargetOption.overrideUnlockedRetention(true)` on `storage.update` to shorten/remove/lock `UNLOCKED`)
**Rapid Cache**                     | `StorageControlClient.createAnywhereCache` (`com.google.storage.control.v2.StorageControlClient`)

--------------------------------------------------------------------------------

## Java SDK Examples

### Example 1: Sensitive Data / Compliance (UBLA, PAP, CMEK, CSEK Restricted, Soft Delete, Retention, Autoclass, Labels, OLM, IP Filter)

*(For a baseline secure bucket, keep `projectId`, `StorageClass.STANDARD`, UBLA,
enforced PAP, 7-day Soft Delete, and
`setCustomerSuppliedEncryptionEnforcementConfig(csekConfig)`
(`FULLY_RESTRICTED`), omitting unused optional builder calls on
`BucketInfo.newBuilder(bucketName)`.)*

```java
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageClass;
import com.google.cloud.storage.StorageOptions;
import java.time.Duration;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class GcsExamples {

  public static Bucket createComplianceBucket(String projectId, String bucketName, String kmsKeyId) {
    Storage storage = StorageOptions.newBuilder()
        .setProjectId(projectId)
        .build()
        .getService();

    BucketInfo.IamConfiguration iamConfig = BucketInfo.IamConfiguration.newBuilder()
        .setIsUniformBucketLevelAccessEnabled(true)
        .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.ENFORCED)
        .build();

    // Requires google-cloud-storage >= 2.55.0
    BucketInfo.CustomerSuppliedEncryptionEnforcementConfig csekConfig =
        BucketInfo.CustomerSuppliedEncryptionEnforcementConfig.of(
            BucketInfo.EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);
    BucketInfo.CustomerManagedEncryptionEnforcementConfig cmekConfig =
        BucketInfo.CustomerManagedEncryptionEnforcementConfig.of(
            BucketInfo.EncryptionEnforcementRestrictionMode.NOT_RESTRICTED);
    BucketInfo.GoogleManagedEncryptionEnforcementConfig gmekConfig =
        BucketInfo.GoogleManagedEncryptionEnforcementConfig.of(
            BucketInfo.EncryptionEnforcementRestrictionMode.NOT_RESTRICTED);

    BucketInfo.IpFilter.PublicNetworkSource publicSource =
        BucketInfo.IpFilter.PublicNetworkSource.of(Collections.singletonList("192.0.2.0/24"));
    BucketInfo.IpFilter.VpcNetworkSource vpcSource =
        BucketInfo.IpFilter.VpcNetworkSource.newBuilder()
            .setNetwork("projects/" + projectId + "/global/networks/NETWORK_NAME")
            .setAllowedIpCidrRanges(Collections.singletonList("10.0.0.0/16"))
            .build();
    BucketInfo.IpFilter ipFilter = BucketInfo.IpFilter.newBuilder()
        .setMode("Enabled")
        .setAllowAllServiceAgentAccess(true)
        .setAllowCrossOrgVpcs(false)
        .setPublicNetworkSource(publicSource)
        .setVpcNetworkSources(Collections.singletonList(vpcSource))
        .build();

    Map<String, String> labels = new HashMap<>();
    labels.put("data-class", "pii");
    labels.put("owner", "security-team");

    BucketInfo bucketInfo = BucketInfo.newBuilder(bucketName)
        .setLocation("us-central1")
        .setStorageClass(StorageClass.STANDARD)
        .setIamConfiguration(iamConfig)
        .setDefaultKmsKeyName(kmsKeyId)
        .setCustomerSuppliedEncryptionEnforcementConfig(csekConfig)
        .setCustomerManagedEncryptionEnforcementConfig(cmekConfig)
        .setGoogleManagedEncryptionEnforcementConfig(gmekConfig)
        .setIpFilter(ipFilter)
        .setSoftDeletePolicy(BucketInfo.SoftDeletePolicy.newBuilder()
            .setRetentionDuration(Duration.ofDays(7))
            .build())
        .setRetentionPeriodDuration(Duration.ofDays(90))
        .setAutoclass(BucketInfo.Autoclass.newBuilder().setEnabled(true).build())
        .setLabels(labels)
        .setLifecycleRules(Collections.singletonList(
            new BucketInfo.LifecycleRule(
                BucketInfo.LifecycleRule.LifecycleAction.newAbortIncompleteMPUploadAction(),
                BucketInfo.LifecycleRule.LifecycleCondition.newBuilder().setAge(7).build()
            )
        ))
        .build();

    return storage.create(bucketInfo);
  }

  // WARNING: Locking the retention policy is permanent and irreversible.
  public static Bucket lockRetentionPolicy(String projectId, String bucketName) {
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    return storage.get(bucketName).lockRetentionPolicy(Storage.BucketTargetOption.metagenerationMatch());
  }
}
```

### Example 2: Static Website Hosting (Multi-Region `US`, Public Access, Website, CORS, Versioning)

```java
import com.google.cloud.Identity;
import com.google.cloud.Policy;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Cors;
import com.google.cloud.storage.HttpMethod;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageClass;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.StorageRoles;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collections;

public class GcsExamples {

  public static Bucket createStaticWebsiteBucket(String projectId, String bucketName) {
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Cors cors = Cors.newBuilder()
        .setMaxAgeSeconds(3600)
        .setMethods(Arrays.asList(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS))
        .setOrigins(Collections.singletonList(Cors.Origin.of("*")))
        .setResponseHeaders(Collections.singletonList("Content-Type"))
        .build();

    BucketInfo.IamConfiguration iamConfig = BucketInfo.IamConfiguration.newBuilder()
        .setIsUniformBucketLevelAccessEnabled(true)
        .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.INHERITED)
        .build();

    BucketInfo bucketInfo = BucketInfo.newBuilder(bucketName)
        .setStorageClass(StorageClass.STANDARD)
        .setLocation("US")
        .setIamConfiguration(iamConfig)
        .setVersioningEnabled(true)
        .setSoftDeletePolicy(BucketInfo.SoftDeletePolicy.newBuilder()
            .setRetentionDuration(Duration.ofDays(7))
            .build())
        .setIndexPage("index.html")
        .setNotFoundPage("404.html")
        .setCors(Collections.singletonList(cors))
        .build();

    Bucket bucket = storage.create(bucketInfo);

    Policy policy = storage.getIamPolicy(bucketName).toBuilder()
        .addIdentity(StorageRoles.objectViewer(), Identity.allUsers())
        .build();
    storage.setIamPolicy(bucketName, policy);
    return bucket;
  }
}
```

### Example 3: AI/ML Checkpointing (Zonal `RAPID` Bucket in `us-east1-b`, HNS, Soft Delete Disabled)

```java
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.BucketInfo.CustomPlacementConfig;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageClass;
import com.google.cloud.storage.StorageOptions;
import java.time.Duration;
import java.util.Collections;

public class GcsExamples {

  public static Bucket createCheckpointBucket(String projectId, String bucketName) {
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    BucketInfo.IamConfiguration iamConfig = BucketInfo.IamConfiguration.newBuilder()
        .setIsUniformBucketLevelAccessEnabled(true)
        .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.ENFORCED)
        .build();

    BucketInfo bucketInfo = BucketInfo.newBuilder(bucketName)
        .setStorageClass(StorageClass.valueOf("RAPID"))
        .setLocation("us-east1")
        .setCustomPlacementConfig(CustomPlacementConfig.newBuilder()
            .setDataLocations(Collections.singletonList("us-east1-b"))
            .build())
        .setIamConfiguration(iamConfig)
        .setHierarchicalNamespace(BucketInfo.HierarchicalNamespace.newBuilder().setEnabled(true).build())
        .setSoftDeletePolicy(BucketInfo.SoftDeletePolicy.newBuilder()
            .setRetentionDuration(Duration.ZERO)
            .build())
        .setLifecycleRules(Collections.singletonList(
            new BucketInfo.LifecycleRule(
                BucketInfo.LifecycleRule.LifecycleAction.newDeleteAction(),
                BucketInfo.LifecycleRule.LifecycleCondition.newBuilder().setAge(14).build()
            )
        ))
        .build();

    return storage.create(bucketInfo);
  }
}
```

### Example 4: WORM Archive with Object Lock (Per-Object Retention)

> [!CAUTION]
>
> Setting per-object retention mode to `BlobInfo.Retention.Mode.LOCKED` is
> permanent and irreversible. Once set, the mode cannot be changed back, the
> retention date can only be extended (never shortened or removed), and objects
> cannot be deleted or overwritten by anyone until the retention date expires.

```java
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageClass;
import com.google.cloud.storage.StorageOptions;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class GcsExamples {

  public static Bucket createRegulatoryWormBucket(String projectId, String bucketName, String kmsKeyId) {
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    BucketInfo.IamConfiguration iamConfig = BucketInfo.IamConfiguration.newBuilder()
        .setIsUniformBucketLevelAccessEnabled(true)
        .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.ENFORCED)
        .build();

    Map<String, String> labels = new HashMap<>();
    labels.put("compliance-type", "regulatory");
    labels.put("retention-period", "7y");

    BucketInfo bucketInfo = BucketInfo.newBuilder(bucketName)
        .setStorageClass(StorageClass.ARCHIVE)
        .setLocation("us-east1")
        .setIamConfiguration(iamConfig)
        .setDefaultKmsKeyName(kmsKeyId)
        .setLabels(labels)
        .setSoftDeletePolicy(BucketInfo.SoftDeletePolicy.newBuilder()
            .setRetentionDuration(Duration.ofDays(7))
            .build())
        .setLifecycleRules(Collections.singletonList(
            new BucketInfo.LifecycleRule(
                BucketInfo.LifecycleRule.LifecycleAction.newDeleteAction(),
                BucketInfo.LifecycleRule.LifecycleCondition.newBuilder().setAge(2555).build()
            )
        ))
        .build();

    return storage.create(bucketInfo, Storage.BucketTargetOption.enableObjectRetention(true));
  }

  public static Blob uploadObjectWithRetention(String projectId, String bucketName, String objectName, byte[] content) {
    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    OffsetDateTime retainUntil = OffsetDateTime.of(2030, 12, 31, 23, 59, 59, 0, ZoneOffset.UTC);

    BlobInfo blobInfo = BlobInfo.newBuilder(bucketName, objectName)
        .setRetention(BlobInfo.Retention.newBuilder()
            .setMode(BlobInfo.Retention.Mode.LOCKED)
            .setRetainUntilTime(retainUntil)
            .build())
        .build();

    return storage.create(blobInfo, content);
  }
}
```
sdk_python.md 10.5 KB
# Python SDK Reference & Examples

This guide translates a **Draft Bucket Creation Plan** (from Phase 2) into the
official Cloud Storage Python client library (`google-cloud-storage`).

*   [Cloud Storage Python Client Library](https://cloud.google.com/python/docs/reference/storage/latest)

## Version Requirements

> [!IMPORTANT]
>
> **Encryption Enforcement Config** (`EncryptionEnforcementConfig`) requires
> `google-cloud-storage` version **3.10.0** or higher. Always include a note in
> your response stating that `EncryptionEnforcementConfig` requires version
> **3.10.0 or higher**, and that if the user's SDK version is below 3.10.0, they
> must supplement using the [REST API](rest.md) or create the bucket using
> [gcloud](gcloud.md) or [Terraform](terraform.md). When generating code
> snippets for the user, do **not** execute `python3` or `pip` in the terminal
> to inspect the host machine's installed SDK version unless the user explicitly
> asks to inspect or execute in their local environment.

## Translation Mapping Table

Draft Plan Field / Setting          | Python SDK Feature / Attribute
:---------------------------------- | :-----------------------------
**Client Initialization**           | `client = storage.Client(project=project_id)`
**Bucket Name**                     | `bucket = client.bucket(bucket_name)` (passed to `client.create_bucket(bucket_or_name, ...)`, which accepts `Bucket` or `str`)
**Location**                        | `location="us-central1"` (arg in `client.create_bucket(bucket, location=...)`)
**Placement (Dual-Region / Zonal)** | `data_locations=["us-east1-b"]` (arg in `client.create_bucket(...)`; for zonal buckets, `location` is the region and `data_locations` has the zone)
**Replication Speed (RPO)**         | `bucket.rpo = "ASYNC_TURBO"`
**Storage Class**                   | `bucket.storage_class = "STANDARD"` (or `"NEARLINE"`, `"COLDLINE"`, `"ARCHIVE"`, `"RAPID"`)
**UBLA**                            | `bucket.iam_configuration.uniform_bucket_level_access_enabled = True`
**Public Access Prevention**        | `bucket.iam_configuration.public_access_prevention = "enforced"` (or `"inherited"`)
**Soft Delete**                     | `bucket.soft_delete_policy.retention_duration_seconds = 604800` (`0` to disable for zonal buckets)
**Object Versioning**               | `bucket.versioning_enabled = True` (omit or `False` when disabled)
**Encryption (CMEK)**               | `bucket.default_kms_key_name = kms_key_link`
**Restrict Encryption (CSEK)**      | `bucket.encryption.customer_supplied_encryption_enforcement_config = EncryptionEnforcementConfig(restriction_mode="FullyRestricted")` (**v3.10.0+**)
**Autoclass**                       | `bucket.autoclass_enabled = True`
**Hierarchical Namespace**          | `bucket.hierarchical_namespace_enabled = True`
**Labels**                          | `bucket.labels = {"key": "value"}`
**IP Filtering**                    | `from google.cloud.storage.ip_filter import IPFilter, PublicNetworkSource, VpcNetworkSource; bucket.ip_filter = ip_filter`
**Allow Cross-Org VPCs**            | `ip_filter.allow_cross_org_vpcs = False`
**Lifecycle Policies (OLM)**        | `bucket.lifecycle_rules = [{"action": {"type": "..."}, "condition": {"age": 7}}]`
**CORS**                            | `bucket.cors = [{"origin": [...], "method": [...], "responseHeader": [...], "maxAgeSeconds": 3600}]`
**Website Configuration**           | `bucket.configure_website(main_page_suffix="index.html", not_found_page="404.html")`
**Public IAM Policy**               | `policy = bucket.get_iam_policy(requested_policy_version=3)` -> append `allUsers` to `roles/storage.objectViewer` -> `bucket.set_iam_policy(policy)`
**Pub/Sub Notifications**           | `notification = bucket.notification(topic_name=...); notification.create()`
**Bucket Retention Period**         | `bucket.retention_period = 7776000` (in seconds)
**Lock Bucket Retention Policy**    | `bucket.lock_retention_policy()` (**permanent and irreversible**)
**Object Retention (Object Lock)**  | `client.create_bucket(bucket_or_name=bucket_name, location=..., enable_object_retention=True)`
**Set Object Retention**            | `blob.retention.mode = "Locked"` (or `"Unlocked"`), `blob.retention.retain_until_time = dt`, then upload or `blob.patch()` (pass `override_unlocked_retention=True` to shorten/remove/lock an existing `"Unlocked"` retention)
**Rapid Cache**                     | `StorageControlClient.create_anywhere_cache` (`google-cloud-storage-control`)

--------------------------------------------------------------------------------

## Python SDK Examples

### Example 1: Sensitive Data / Compliance (UBLA, PAP, CMEK, CSEK Restricted, Soft Delete, Retention, Autoclass, Labels, OLM, IP Filter)

*(For a baseline secure bucket, keep `project=project_id`, `"STANDARD"`, UBLA,
`"enforced"` PAP, 7-day Soft Delete, and
`customer_supplied_encryption_enforcement_config` (`"FullyRestricted"`),
omitting unused optional attributes such as `default_kms_key_name`,
`autoclass_enabled`, `retention_period`, `ip_filter`, or `lifecycle_rules`.)*

```python
from google.cloud import storage
from google.cloud.storage.bucket import EncryptionEnforcementConfig
from google.cloud.storage.ip_filter import IPFilter, PublicNetworkSource, VpcNetworkSource

def create_compliance_bucket(project_id: str, bucket_name: str, kms_key_link: str):
    client = storage.Client(project=project_id)
    bucket = client.bucket(bucket_name)
    bucket.storage_class = "STANDARD"
    bucket.iam_configuration.uniform_bucket_level_access_enabled = True
    bucket.iam_configuration.public_access_prevention = "enforced"
    bucket.default_kms_key_name = kms_key_link
    bucket.soft_delete_policy.retention_duration_seconds = 604800  # 7 days

    # Requires google-cloud-storage >= 3.10.0 (use REST, gcloud, or Terraform on older versions)
    bucket.encryption.customer_supplied_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    bucket.retention_period = 7776000  # 90 days (call bucket.lock_retention_policy() to lock; permanent and irreversible)
    bucket.autoclass_enabled = True
    bucket.labels = {"data-class": "pii", "owner": "security-team"}
    bucket.lifecycle_rules = [
        {
            "action": {"type": "AbortIncompleteMultipartUpload"},
            "condition": {"age": 7},
        }
    ]

    ip_filter = IPFilter()
    ip_filter.mode = "Enabled"
    ip_filter.allow_all_service_agent_access = True
    ip_filter.allow_cross_org_vpcs = False
    ip_filter.public_network_source = PublicNetworkSource(
        allowed_ip_cidr_ranges=["192.0.2.0/24"]
    )
    ip_filter.vpc_network_sources = [
        VpcNetworkSource(
            network="projects/PROJECT_ID/global/networks/NETWORK_NAME",
            allowed_ip_cidr_ranges=["10.0.0.0/16"],
        )
    ]
    bucket.ip_filter = ip_filter

    return client.create_bucket(bucket, location="us-central1")
```

### Example 2: Static Website Hosting (Multi-Region `US`, Public Access, Website Config, CORS, Versioning)

```python
from google.cloud import storage

def create_static_website_bucket(project_id: str, bucket_name: str):
    client = storage.Client(project=project_id)
    bucket = client.bucket(bucket_name)
    bucket.storage_class = "STANDARD"
    bucket.iam_configuration.uniform_bucket_level_access_enabled = True
    bucket.iam_configuration.public_access_prevention = "inherited"  # allow public access
    bucket.versioning_enabled = True
    bucket.soft_delete_policy.retention_duration_seconds = 604800  # 7 days

    bucket.configure_website(
        main_page_suffix="index.html",
        not_found_page="404.html",
    )
    bucket.cors = [{
        "origin": ["*"],
        "method": ["GET", "HEAD", "OPTIONS"],
        "responseHeader": ["Content-Type"],
        "maxAgeSeconds": 3600,
    }]

    new_bucket = client.create_bucket(bucket, location="US")

    policy = new_bucket.get_iam_policy(requested_policy_version=3)
    policy.bindings.append({
        "role": "roles/storage.objectViewer",
        "members": {"allUsers"},
    })
    new_bucket.set_iam_policy(policy)
    return new_bucket
```

### Example 3: AI/ML Checkpointing (Zonal `RAPID` Bucket in `us-east1-b`, HNS, Soft Delete Disabled)

```python
from google.cloud import storage

def create_checkpoint_bucket(project_id: str, bucket_name: str):
    client = storage.Client(project=project_id)
    bucket = client.bucket(bucket_name)
    bucket.storage_class = "RAPID"
    bucket.iam_configuration.uniform_bucket_level_access_enabled = True
    bucket.iam_configuration.public_access_prevention = "enforced"
    bucket.hierarchical_namespace_enabled = True
    bucket.soft_delete_policy.retention_duration_seconds = 0
    bucket.lifecycle_rules = [
        {"action": {"type": "Delete"}, "condition": {"age": 14}}
    ]

    # location is the region; data_locations contains the zone
    return client.create_bucket(
        bucket, location="us-east1", data_locations=["us-east1-b"]
    )
```

### Example 4: WORM Archive with Object Lock (Per-Object Retention)

> [!CAUTION]
>
> Setting per-object retention mode to `"Locked"` is permanent and irreversible.
> Once set, the mode cannot be changed back, the retention date can only be
> extended (never shortened or removed), and objects cannot be deleted or
> overwritten by anyone until the retention date expires.

```python
import datetime
from google.cloud import storage

def create_regulatory_worm_bucket(project_id: str, bucket_name: str, kms_key_id: str):
    client = storage.Client(project=project_id)

    bucket = client.create_bucket(
        bucket_or_name=bucket_name,
        location="us-east1",
        enable_object_retention=True,
    )
    bucket.storage_class = "ARCHIVE"
    bucket.iam_configuration.uniform_bucket_level_access_enabled = True
    bucket.iam_configuration.public_access_prevention = "enforced"
    bucket.default_kms_key_name = kms_key_id
    bucket.labels = {"compliance-type": "regulatory", "retention-period": "7y"}
    bucket.soft_delete_policy.retention_duration_seconds = 604800
    bucket.lifecycle_rules = [
        {"action": {"type": "Delete"}, "condition": {"age": 2555}}
    ]
    bucket.patch()
    return bucket

def upload_object_with_retention(bucket_name: str, source_file: str, destination_blob: str):
    client = storage.Client()
    blob = client.bucket(bucket_name).blob(destination_blob)
    blob.retention.mode = "Locked"
    blob.retention.retain_until_time = datetime.datetime(
        2030, 12, 31, 23, 59, 59, tzinfo=datetime.timezone.utc
    )
    blob.upload_from_filename(source_file)
    return blob
```
sensitive_data.md 6.7 KB
# Sensitive Data & Compliance (PII, HIPAA, Finance)

This reference document outlines the secure-by-default configuration mapping and
architecture recommendation for Cloud Storage buckets designed to host highly
regulated, sensitive data (such as Personally Identifiable Information (PII),
healthcare records subject to HIPAA, or financial transaction logs).

## Description

The user is storing highly regulated, sensitive data and needs to protect it
against unauthorized public exposure and data exfiltration while maintaining
auditability. This workload typically involves microservice applications or data
pipelines processing data within a secure corporate boundary.

## Bucket Configuration Plan Mapping

The following table maps the Sensitive Data use case to specific Cloud Storage
features and details their recommendation status. See
[Official Documentation References](#official-documentation-references) below
for feature links if further reference is needed (do not fetch routinely).

Cloud Storage Feature / Setting        | Status                     | Recommendations & Implementation Details
:------------------------------------- | :------------------------- | :---------------------------------------
**Storage Class**                      | Highly Recommended         | **Autoclass** or **Standard** Storage Class.<br><br>Autoclass automatically moves cold data to lower-cost tiers without retrieval fees. Standard storage is recommended if data requires frequent, immediate, low-latency access.
**Bucket Type**                        | Highly Recommended         | **Regional** bucket type. Choosing a single region allows co-locating storage with compute resources to avoid latency and egress costs.
**Signed URLs**                        | Optional / Not Recommended | Avoid direct access. Restrict access through backend microservices or require signed URLs only if clients must write directly.
**CORS**                               | Optional / Not Recommended | Disable or restrict to specific trusted internal domains to prevent cross-origin web exfiltration.
**Uniform Bucket-Level Access (UBLA)** | **Required**               | **Must be enabled.** Prevents legacy object-level ACLs from overriding bucket-level IAM policies.
**Public Access Prevention (PAP)**     | **Required**               | **Must be enforced.** Disallows public access via `allUsers` or `allAuthenticatedUsers`.
**Encryption (CMEK)**                  | Highly Recommended         | **Customer-Managed Encryption Keys (CMEK)** via Cloud KMS.<br><br>Use KMS Autokey to dynamically provision keys on bucket creation, or prompt the user for a KMS key path. Do not use Customer-Supplied Encryption Keys (CSEK).
**Soft Delete**                        | Highly Recommended         | **Enabled (default 7 days).** Ensures data can be recovered within the retention window if accidentally deleted by automated scripts or administrative bugs.
**Object Versioning**                  | Good to Have               | Suggest as an alternative to prevent data modification/accidental deletes only if Soft Delete is disabled.
**Data Retention (WORM)**              | Good to Have               | Prompt the user to configure a Retention Policy (Bucket Lock or Object Lock) if regulatory compliance mandates immutability.<br><br>**Warning:** Lock mode is permanent and irreversible.
**IP Filtering**                       | Good to Have               | Limit access to the bucket to specific CIDR ranges or VPC networks (e.g. corporate SOC perimeters).
**Object Lifecycle Management (OLM)**  | Highly Recommended         | Configure rules to automatically abort incomplete multipart uploads (`abortIncompleteMultipartUpload`) to avoid hidden storage costs. If Autoclass is disabled, transition objects to `ARCHIVE` after 365 days.
**Labels & Tagging**                   | Highly Recommended         | **Mandatory** bucket-level tagging (e.g., `{"data-class": "pii"}` and `{"owner": "security-team"}`) to ensure proper data classification and cost-center tracking.
**Storage Transfer Service (STS)**     | Good to Have               | Consider cross-bucket replication via STS to maintain an independent, secure copy of data.
**Cloud Logging**                      | Good to Have               | Enable Cloud Audit Logging (Data Access & Admin Activity logs) for audit trials.
**Cloud Monitoring**                   | Good to Have               | Monitor operational health and watch for spikes in error rates (e.g., 404, 503).

## Project-Level Security Checks & Recommendations

Before bucket creation, verify the following project-level configurations:

1.  **Restrict Sharing Org Policy**: Ensure
    `constraints/iam.allowedPolicyMemberDomains` is configured to restrict
    sharing outside of authorized organizational domains.
2.  **Access Transparency**: Ensure Access Transparency is enabled on the
    project to audit Google administrator access.
3.  **Location Org Policy**: Check `constraints/gcp.resourceLocations` to ensure
    bucket creation conforms to the organization's regional residency
    guidelines.

## Official Documentation References

Feature / Topic             | Documentation Link
:-------------------------- | :-----------------
Autoclass                   | https://cloud.google.com/storage/docs/autoclass
Storage Classes             | https://cloud.google.com/storage/docs/storage-classes
Locations                   | https://cloud.google.com/storage/docs/locations
Signed URLs                 | https://cloud.google.com/storage/docs/access-control/signed-urls
CORS                        | https://cloud.google.com/storage/docs/using-cors
Uniform Bucket-Level Access | https://cloud.google.com/storage/docs/uniform-bucket-level-access
Public Access Prevention    | https://cloud.google.com/storage/docs/public-access-prevention
CMEK                        | https://cloud.google.com/storage/docs/encryption/customer-managed-keys
KMS Autokey                 | https://cloud.google.com/kms/docs/autokey-overview
Soft Delete                 | https://cloud.google.com/storage/docs/soft-delete
Object Versioning           | https://cloud.google.com/storage/docs/object-versioning
Bucket Lock                 | https://cloud.google.com/storage/docs/bucket-lock
Object Lock                 | https://cloud.google.com/storage/docs/object-lock
Bucket IP Filtering         | https://cloud.google.com/storage/docs/ip-filtering-overview
Lifecycle Management        | https://cloud.google.com/storage/docs/lifecycle
Bucket Labels               | https://cloud.google.com/storage/docs/using-bucket-labels
Storage Transfer Service    | https://cloud.google.com/storage-transfer/docs/overview
Cloud Audit Logging         | https://cloud.google.com/storage/docs/audit-logging
Cloud Monitoring            | https://cloud.google.com/storage/docs/monitoring
static_website.md 5.3 KB
# Static Website Hosting

This reference document outlines the configuration mapping and architecture
recommendation for Cloud Storage buckets configured to host static websites.

## Description

The user is deploying a static website (HTML, CSS, JavaScript, media assets)
directly to Cloud Storage. The site needs to be publicly accessible, support
custom domain mapping, scale automatically for viral traffic spikes, and serve
assets with low latency without backend servers.

## Bucket Configuration Plan Mapping

The following table maps the Static Website Hosting use case to specific Cloud
Storage features and details their recommendation status. See
[Official Documentation References](#official-documentation-references) below
for feature links if further reference is needed (do not fetch routinely).

Cloud Storage Feature / Setting        | Status                   | Recommendations & Implementation Details
:------------------------------------- | :----------------------- | :---------------------------------------
**Storage Class**                      | Highly Recommended       | **Standard** Storage Class.<br><br>Required for web serving to ensure immediate, low-latency, and high-throughput asset delivery. Colder tiers must be avoided due to retrieval fees.
**Bucket Type**                        | Highly Recommended       | **Multi-Regional (MR)**. Distributes website content globally to ensure high availability and low latency for diverse user locations.
**CORS**                               | Highly Recommended       | Configure CORS if the site loads assets from other origins, or if assets from this bucket are queried by external frontends.
**Website Settings**                   | **Required**             | **Configure Website Configuration.** Set the `mainPageSuffix` (e.g. `index.html`) and `notFoundPage` (e.g. `404.html`) to handle root requests and errors.
**Uniform Bucket-Level Access (UBLA)** | **Required**             | **Must be enabled.** Standardizes IAM permissions across the bucket.
**Public Access Prevention (PAP)**     | **Disabled** (Exception) | **Must be set to "inherited" / Disabled.** Public access must be allowed to serve web traffic. Grant `roles/storage.objectViewer` to `allUsers` to make assets publicly accessible.
**Soft Delete**                        | Good to Have             | Enabled as a critical rollback mechanism. Helps restore website files quickly if deleted by broken build/deploy scripts.
**Object Versioning**                  | Good to Have             | Alternative to Soft Delete. Allows rolling back bad deployments to a prior known good state, but requires OLM to prune history.
**IP Filtering**                       | Optional                 | Use only if you must limit access to specific IP ranges (including countries or corporate networks, e.g. staging site).
**Object Lifecycle Management (OLM)**  | Highly Recommended       | If Versioning is enabled, set lifecycle rules to prune non-current versions (e.g., after 30 days) to prevent old builds from increasing storage bills. Recommend standard OLM rule:<br>Transition to `ARCHIVE` after 365 days.
**Labels & Tagging**                   | Good to Have             | Apply environment tags (e.g., `{"environment": "production"}`).
**Storage Transfer Service (STS)**     | Good to Have             | Replicate site assets closer to compute regions using STS.
**Cloud Logging**                      | Highly Recommended       | Enable logs to analyze web usage stats, referral paths, and user-agent data.
**Cloud Monitoring**                   | Highly Recommended       | Setup alerts on public egress, total operations, and error rates (e.g., 404/503).
**Pub/Sub Notifications**              | Good to Have             | Trigger downstream workflows (such as clearing a CDN cache) whenever `index.html` or other assets are updated.

## Official Documentation References

Feature / Topic             | Documentation Link
:-------------------------- | :-----------------
Storage Classes             | https://cloud.google.com/storage/docs/storage-classes
Locations                   | https://cloud.google.com/storage/docs/locations
CORS                        | https://cloud.google.com/storage/docs/using-cors
Hosting Static Website      | https://cloud.google.com/storage/docs/hosting-static-website
Uniform Bucket-Level Access | https://cloud.google.com/storage/docs/uniform-bucket-level-access
Public Access Prevention    | https://cloud.google.com/storage/docs/public-access-prevention
Make Bucket Public          | https://cloud.google.com/storage/docs/access-control/making-data-public
Soft Delete                 | https://cloud.google.com/storage/docs/soft-delete
Object Versioning           | https://cloud.google.com/storage/docs/object-versioning
Bucket IP Filtering         | https://cloud.google.com/storage/docs/ip-filtering-overview
Lifecycle Management        | https://cloud.google.com/storage/docs/lifecycle
Bucket Labels               | https://cloud.google.com/storage/docs/using-bucket-labels
Storage Transfer Service    | https://cloud.google.com/storage-transfer/docs/overview
Cloud Audit Logging         | https://cloud.google.com/storage/docs/audit-logging
Cloud Monitoring            | https://cloud.google.com/storage/docs/monitoring
Pub/Sub Notifications       | https://cloud.google.com/storage/docs/pubsub-notifications
storage_for_ai.md 9.1 KB
# AI & Machine Learning (Storage for AI)

This reference document outlines the configuration mapping and architecture
recommendation for Cloud Storage buckets optimized for AI/ML workloads,
including model training, checkpointing, and model inference.

## Description

The user is running demanding AI/ML workloads (such as Large Language Model
training, computer vision pipelines, or high-throughput batch inference)
utilizing TPU or GPU accelerators. These workloads require ultra-high read/write
throughput, sub-millisecond latencies, and co-location with compute resources to
prevent compute starvation.

## Architecture Alternatives: Rapid Cache vs. Zonal Buckets (Rapid Bucket)

Depending on the specific workload phase (Training, Checkpointing, or Inference)
and data access patterns, recommend one of the two Cloud Storage Rapid
solutions. Per the
[Rapid Bucket Terminology](https://cloud.google.com/storage/docs/rapid/rapid-bucket#terminology),
**Rapid Bucket** is the product that enables buckets to be created with a zonal
location and the **Rapid storage class**, while individual buckets are referred
to as **zonal buckets**.

Dimension                  | Rapid Cache                                                                                                                    | Zonal Buckets (Rapid Bucket)
:------------------------- | :----------------------------------------------------------------------------------------------------------------------------- | :---------------------------
**Description**            | SSD-backed zonal read cache attached to an existing Cloud Storage bucket (regional, dual-regional, or multi-regional).         | Zonal bucket in the `RAPID` storage class.
**Primary Use Case**       | **Model Training & Inference** where datasets already exist in a Cloud Storage bucket.                                         | **Model Checkpointing** and high-QPS, write-heavy training tasks.
**Read/Write**             | **Read-Only**. Writes must be written to the underlying bucket.                                                                | **Read and Write**. Serves as a writable source of truth.
**Namespace**              | Same namespace as the underlying Cloud Storage bucket.                                                                         | Independent namespace (must copy/upload data directly).
**Performance**            | High throughput. Initial read cold-start penalty can be avoided using **ingest-on-write**. Same QPS as standard Cloud Storage. | Ultra-low latency, high throughput, and high QPS (no cold start).
**Data Lifecycle**         | Default TTL is 24 hours. Cache automatically evicts stale data.                                                                | Permanent storage (data lives forever until deleted).
**Appendability**          | No append support.                                                                                                             | **Supports Append (BiDi protocol)** to write streaming data up to 5TiB.
**Hierarchical Namespace** | Optional.                                                                                                                      | **Required** (Always enabled, not configurable).

--------------------------------------------------------------------------------

## Rapid Cache Specific Recommendations

When the architecture plan recommends **Rapid Cache**, the agent MUST explicitly
configure and recommend the following:

1.  **Zonal Co-location**: Co-locate the Rapid Cache instance in the exact same
    zone as the compute cluster (e.g. GPU/TPU cluster).
2.  **Ingest-on-Write (Recommended to Avoid Cold Start)**: Enable
    [ingest-on-write](https://cloud.google.com/storage/docs/rapid/rapid-cache#ingest-on-write)
    (at bucket-level or prefix/managed folder level) so that newly written data
    is immediately ingested into the cache upon write. This eliminates initial
    cache misses and avoids cold-start penalties for read-after-write workloads.

--------------------------------------------------------------------------------

## Zonal Buckets (Rapid Bucket) Specific Recommendations

When the architecture plan recommends **Zonal Buckets (Rapid Bucket)**, the
agent MUST explicitly configure and recommend the following:

1.  **Zonal Co-location**: Co-locate the zonal bucket in the exact same zone as
    the compute/training nodes (e.g. `us-east4-a` for GPU cluster in
    `us-east4-a`) to eliminate network bottlenecks.
2.  **Storage Class**: The storage class MUST be set to `RAPID`.
3.  **Disable Soft Delete**: Soft delete is not supported for zonal buckets and
    MUST be disabled (set `--soft-delete-duration=0` during creation).
4.  **Hierarchical Namespace**: Hierarchical Namespace MUST be enabled.
5.  **BiDi Protocol Recommendation**: For streaming, write-heavy, or logging
    workloads, explicitly recommend utilizing the **BiDi protocol**
    (Bidirectional Streaming) on the zonal bucket to enable low-latency,
    high-QPS streaming append operations up to 5TiB.

--------------------------------------------------------------------------------

## Bucket Configuration Plan Mapping

The following table maps Cloud Storage features to AI/ML workloads and details
their recommendation status. See
[Official Documentation References](#official-documentation-references) below
for feature links if further reference is needed (do not fetch routinely).

Cloud Storage Feature / Setting        | Status                     | Recommendations & Implementation Details
:------------------------------------- | :------------------------- | :---------------------------------------
**Storage Class**                      | Highly Recommended         | Use **STANDARD** for standard buckets, or **RAPID** storage class for zonal buckets.
**Bucket Type**                        | Highly Recommended         | **Zonal** (with Rapid Bucket) or **Regional / Dual-region / Multi-region** (for Cloud Storage bucket with Rapid Cache) to co-locate storage and compute.
**CORS & Signed URLs**                 | Optional / Not Recommended | Avoid exposing AI datasets directly to public users.
**Uniform Bucket-Level Access (UBLA)** | **Required**               | **Must be enabled** for baseline access control security.
**Encryption (CMEK)**                  | Highly Recommended         | Configure CMEK. Use KMS Autokey for automation.
**Soft Delete**                        | Good to Have               | Optional for non-zonal buckets (useful but not highly recommended due to potential storage cost overhead from massive AI dataset churn). Unsupported for zonal buckets.
**Object Lifecycle Management (OLM)**  | Highly Recommended         | Define OLM rules to automatically delete stale checkpoints (e.g. keep only the last 3 days of checkpoints) to avoid massive storage bills on zonal disks.
**Labels & Tagging**                   | Highly Recommended         | Apply billing and ownership labels (e.g. `{"workload": "ai-training"}`) to accurately trace expensive high-performance storage spend.
**BiDi (Bidirectional Streaming)**     | Highly Recommended         | Utilize the BiDi protocol on zonal buckets to enable low-latency, high-QPS streaming and append operations.
**Cloud Monitoring**                   | Highly Recommended         | Monitor caching metrics, hit rates, and ingress/egress bandwidth to ensure TPUs/GPUs are not bottlenecked by storage.

## Key Pre-Deployment Questions to Ask:

1.  **What phase of the AI/ML pipeline is this storage for?**
    *   *If Training / Inference (read-heavy)*: Ask if the dataset already
        exists. Recommend **Rapid Cache** to save migration time and egress
        costs.
    *   *If Checkpointing (write-heavy)*: Recommend **zonal buckets** (with
        Rapid Bucket) for low-latency writes.
2.  **What zone is your compute cluster (TPU/GPU) located in?**
    *   *Recommendation*: Co-locate the Rapid Cache or zonal bucket in the exact
        same zone (e.g. `us-central1-a`) to eliminate network bottlenecks.
3.  **If using Rapid Cache, do you want to enable ingest-on-write?**
    *   *Recommendation*: Enable ingest-on-write so that data is ingested into
        the cache upon write, eliminating initial cache misses and cold-start
        penalties.

## Official Documentation References

Feature / Topic             | Documentation Link
:-------------------------- | :-----------------
Storage Classes             | https://cloud.google.com/storage/docs/storage-classes
Rapid Bucket Terminology    | https://cloud.google.com/storage/docs/rapid/rapid-bucket#terminology
Locations                   | https://cloud.google.com/storage/docs/locations
Uniform Bucket-Level Access | https://cloud.google.com/storage/docs/uniform-bucket-level-access
CMEK                        | https://cloud.google.com/storage/docs/encryption/customer-managed-keys
Soft Delete                 | https://cloud.google.com/storage/docs/soft-delete
Lifecycle Management        | https://cloud.google.com/storage/docs/lifecycle
Bucket Labels               | https://cloud.google.com/storage/docs/using-bucket-labels
Hierarchical Namespace      | https://cloud.google.com/storage/docs/hns-overview
Cloud Monitoring            | https://cloud.google.com/storage/docs/monitoring
terraform.md 11.3 KB
# Terraform Google Provider Cloud Storage Reference

> [!IMPORTANT]
>
> **DO NOT APPLY THESE CONFIGURATIONS AUTOMATICALLY.** Present the generated
> Terraform configuration snippets to the user for review and integration.

## Official Documentation Reference

*   [Terraform Registry: `google_storage_bucket`](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_bucket)
*   [Terraform Registry: `google_storage_bucket_object`](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_bucket_object)
*   [Terraform Registry: `google_storage_notification`](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_notification)
*   [Terraform Registry: `google_storage_anywhere_cache`](https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/storage_anywhere_cache)

--------------------------------------------------------------------------------

## Translation Mapping Table

Draft Plan Field / Setting         | `google_storage_bucket` Attribute / Resource           | Notes / Action
:--------------------------------- | :----------------------------------------------------- | :-------------
**Bucket Name**                    | `name`                                                 | Required string. Must be globally unique.
**Project**                        | `project`                                              | Optional string (defaults to provider project).
**Location**                       | `location`                                             | Required string: e.g., `"us-central1"`, `"US"`, `"nam4"`. For zonal buckets, set to the region (e.g., `"us-east1"`).
**Placement**                      | `custom_placement_config.data_locations`               | List of strings: `["us-east1", "us-west1"]` (custom dual-region) or `["us-east1-b"]` (zonal bucket).
**Replication Speed (RPO)**        | `rpo`                                                  | String: `"ASYNC_TURBO"` (for dual-region buckets).
**Storage Class**                  | `storage_class`                                        | `"STANDARD"`, `"NEARLINE"`, `"COLDLINE"`, `"ARCHIVE"`, `"RAPID"`. Must be `"STANDARD"` if Autoclass is enabled; `"RAPID"` for zonal buckets.
**UBLA**                           | `uniform_bucket_level_access`                          | Boolean. Always set to `true`.
**Public Access Prevention**       | `public_access_prevention`                             | String: `"enforced"` or `"inherited"`.
**Soft Delete**                    | `soft_delete_policy.retention_duration_seconds`        | Seconds: `604800` (7 days default) to `7776000` (90 days). Set to `0` to disable (must be `0` for zonal buckets).
**Object Versioning**              | `versioning.enabled`                                   | Boolean. Enables/disables versioning.
**Encryption (CMEK)**              | `encryption.default_kms_key_name`                      | Full KMS key ID (`"projects/.../cryptoKeys/..."`). Optional when only setting enforcement blocks. ⚠️ **See Note 1 below.**
**Restrict Encryption (CSEK)**     | `encryption` (`*_encryption_enforcement_config`)       | Nested `customer_supplied_encryption_enforcement_config` block inside `encryption` (`restriction_mode = "FullyRestricted"`). See Example 1.
**Autoclass**                      | `autoclass.enabled`                                    | Boolean (`true` to enable; incompatible with zonal buckets).
**Hierarchical Namespace**         | `hierarchical_namespace.enabled`                       | Boolean (`true` to enable at creation only — **irreversible**; incompatible with versioning, Bucket Lock, and Object Lock).
**Labels**                         | `labels`                                               | Map of strings (`{ key = "value" }`).
**IP Filtering**                   | `ip_filter`                                            | Block defining IP/VPC rules. See Example 1 below.
**Lifecycle Policies (OLM)**       | `lifecycle_rule`                                       | One or more `lifecycle_rule` blocks. See Examples 1 & 3 below.
**CORS**                           | `cors`                                                 | One or more `cors` blocks. See Example 2 below.
**Website Configuration**          | `website`                                              | Block with `main_page_suffix` and `not_found_page`. See Example 2 below.
**Public IAM Policy**              | Resource: `google_storage_bucket_iam_member`           | Separate resource granting `roles/storage.objectViewer` to `allUsers`.
**Pub/Sub Notifications**          | Resource: `google_storage_notification`                | Separate resource linking bucket and Pub/Sub topic. ⚠️ **See Note 1 below.**
**Bucket Retention Period**        | `retention_policy.retention_period`                    | Number in seconds (e.g., `7776000` for 90 days, `220752000` for 7 years).
**Lock Bucket Retention Policy**   | `retention_policy.is_locked`                           | Boolean. Setting `is_locked = true` permanently locks the policy. **Irreversible.**
**Object Retention (Object Lock)** | `enable_object_retention`                              | Boolean (`true` to enable per-object retention).
**Set Object Retention**           | Resource: `google_storage_bucket_object` (`retention`) | `retention` block with `mode` (`"Locked"`/`"Unlocked"`) and `retain_until_time` on `google_storage_bucket_object`.
**Rapid Cache**                    | Resource: `google_storage_anywhere_cache`              | Separate resource linking bucket to Rapid Cache zone.

> [!NOTE]
>
> *   **Note 1 (Service Agent IAM Prerequisites)**: For **CMEK**, the Cloud
>     Storage service agent
>     (`service-PROJECT_NUM@gs-project-accounts.iam.gserviceaccount.com`, or via
>     `data "google_storage_project_service_account"`) must hold
>     `roles/cloudkms.cryptoKeyEncrypterDecrypter` on the KMS key. For **Pub/Sub
>     Notifications**, grant that service agent (via
>     `google_storage_project_service_account` data source)
>     `roles/pubsub.publisher` on the topic (e.g., via
>     `google_pubsub_topic_iam_binding` or `google_pubsub_topic_iam_member`) and
>     set `depends_on` on `google_storage_notification` targeting the IAM
>     resource.

--------------------------------------------------------------------------------

## Terraform Examples (Including Helper Block Templates)

### Example 1: Sensitive Data / Compliance (CMEK, CSEK Restricted, Retention Policy, Autoclass, Labels, OLM, IP Filter, Soft Delete)

*(For a baseline secure bucket, keep `uniform_bucket_level_access = true`,
`public_access_prevention = "enforced"`, `soft_delete_policy`, and
`customer_supplied_encryption_enforcement_config` inside `encryption`.)*

```tf
resource "google_storage_bucket" "compliance_bucket" {
  name                        = "my-compliance-pii-bucket"
  project                     = "my-compliance-project"
  location                    = "us-central1"
  storage_class               = "STANDARD"
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"

  encryption {
    # Omit default_kms_key_name when using Google-managed encryption
    default_kms_key_name = "projects/my-kms-project/locations/us-central1/keyRings/my-keyring/cryptoKeys/my-key"

    customer_supplied_encryption_enforcement_config {
      restriction_mode = "FullyRestricted"
    }
    customer_managed_encryption_enforcement_config {
      restriction_mode = "NotRestricted"
    }
    google_managed_encryption_enforcement_config {
      restriction_mode = "NotRestricted"
    }
  }

  # WARNING: Setting is_locked = true is permanent and irreversible!
  retention_policy {
    retention_period = 7776000 # 90 days in seconds (use 220752000 for 7 years)
    is_locked        = false
  }

  autoclass {
    enabled = true
  }

  labels = {
    data-class = "pii"
    owner      = "security-team"
  }

  lifecycle_rule {
    action {
      type = "AbortIncompleteMultipartUpload"
    }
    condition {
      age = 7
    }
  }

  ip_filter {
    mode                           = "Enabled"
    allow_all_service_agent_access = true
    allow_cross_org_vpcs           = false

    public_network_source {
      allowed_ip_cidr_ranges = ["192.0.2.0/24"]
    }

    vpc_network_sources {
      network                = "projects/PROJECT_ID/global/networks/NETWORK_NAME"
      allowed_ip_cidr_ranges = ["10.0.0.0/16"]
    }
  }

  soft_delete_policy {
    retention_duration_seconds = 604800 # 7 days
  }
}
```

*(Note: Setting `is_locked = true` inside `retention_policy` is permanent and
irreversible—always include a critical warning in prose whenever locking is
requested.)*

### Example 2: Static Website Hosting (Multi-Region `US`, Public Access, Website, CORS, Versioning)

```tf
resource "google_storage_bucket" "static_website" {
  name                        = "www.my-company-site.com"
  location                    = "US"
  storage_class               = "STANDARD"
  uniform_bucket_level_access = true
  public_access_prevention    = "inherited"

  website {
    main_page_suffix = "index.html"
    not_found_page   = "404.html"
  }

  cors {
    origin          = ["*"]
    method          = ["GET", "HEAD"]
    response_header = ["Content-Type"]
    max_age_seconds = 3600
  }

  versioning {
    enabled = true
  }

  soft_delete_policy {
    retention_duration_seconds = 604800 # 7 days
  }
}

resource "google_storage_bucket_iam_member" "public_viewer" {
  bucket = google_storage_bucket.static_website.name
  role   = "roles/storage.objectViewer"
  member = "allUsers"
}
```

### Example 3: AI/ML Checkpointing (Zonal `RAPID` Bucket in `us-east1-b`, HNS, Soft Delete Disabled)

```tf
resource "google_storage_bucket" "checkpoint_bucket" {
  name                        = "my-training-checkpoints-us-east1-b"
  location                    = "us-east1"
  storage_class               = "RAPID"
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"

  custom_placement_config {
    data_locations = ["us-east1-b"]
  }

  hierarchical_namespace {
    enabled = true
  }

  soft_delete_policy {
    retention_duration_seconds = 0
  }

  lifecycle_rule {
    action {
      type = "Delete"
    }
    condition {
      age = 14
    }
  }
}
```

### Example 4: WORM Archive with Object Lock (Per-Object Retention)

> [!CAUTION]
>
> Setting `mode = "Locked"` on an object is permanent and irreversible. Once
> locked, the policy cannot be removed and the retention period can only be
> extended.

```tf
resource "google_storage_bucket" "legal_archive" {
  name                        = "my-legal-archive-bucket"
  location                    = "us-east1"
  storage_class               = "ARCHIVE"
  uniform_bucket_level_access = true
  public_access_prevention    = "enforced"
  enable_object_retention     = true

  encryption {
    default_kms_key_name = "projects/my-kms-project/locations/us-east1/keyRings/my-keyring/cryptoKeys/my-key"
  }

  labels = {
    compliance-type  = "regulatory"
    retention-period = "7y"
  }

  lifecycle_rule {
    action {
      type = "Delete"
    }
    condition {
      age = 2555
    }
  }

  soft_delete_policy {
    retention_duration_seconds = 604800 # 7 days
  }
}

resource "google_storage_bucket_object" "case_file" {
  name   = "case_file_abc.pdf"
  bucket = google_storage_bucket.legal_archive.name
  source = "path/to/local/file.pdf"

  retention {
    mode              = "Locked"
    retain_until_time = "2030-12-31T23:59:59Z"
  }
}
```
ugc_ingestion.md 5.8 KB
# Direct User-Generated Content (UGC) Ingestion

This reference document outlines the secure-by-default configuration mapping and
architecture recommendation for Cloud Storage buckets receiving direct
client-side uploads from user applications (mobile apps, web browsers, etc.)
bypassing backend servers.

## Description

The user is building a mobile or web application where end-users upload heavy
files (such as profile pictures, documents, or video clips) directly to a Cloud
Storage bucket. This is achieved using Signed URLs to authorize uploads and CORS
configuration to allow browser-based calls, avoiding network bottlenecking on
the application's backend web servers.

## Bucket Configuration Plan Mapping

The following table maps the Direct UGC Ingestion use case to specific Cloud
Storage features and details their recommendation status. See
[Official Documentation References](#official-documentation-references) below
for feature links if further reference is needed (do not fetch routinely).

Cloud Storage Feature / Setting        | Status             | Recommendations & Implementation Details
:------------------------------------- | :----------------- | :---------------------------------------
**Storage Class**                      | Highly Recommended | **Autoclass** or **Standard** Storage Class.<br><br>Standard storage is recommended if users frequently view uploaded content immediately. Autoclass is ideal if files naturally go cold over time, avoiding retrieval fee traps.
**Bucket Type**                        | Highly Recommended | **Regional** bucket type. Align storage region with application compute to minimize latency. Create multiple regional buckets if the user base is globally dispersed.
**Signed URLs**                        | **Required**       | **Use Signed URLs** to delegate time-limited read/write access to clients, keeping the bucket secure while offloading traffic from backend servers.
**CORS**                               | **Required**       | **Configure CORS** to allow web applications hosted on custom domains to perform client-side uploads and load resources directly.
**Uniform Bucket-Level Access (UBLA)** | **Required**       | **Must be enabled.** Standardizes IAM permissions across the bucket, disabling granular legacy ACLs.
**Encryption (CMEK)**                  | Good to Have       | Recommend Customer-Managed Encryption Keys (CMEK) primarily for B2B multi-tenant environments with strict compliance mandates.
**Soft Delete**                        | Highly Recommended | **Enabled (default 7 days).** Provides a safety fallback to recover user data from accidental deletions or compromise, without regulatory locking.
**Object Versioning**                  | Good to Have       | Recommend only if users frequently overwrite files of identical names and collaborative history is needed, but govern with strict OLM to control cost.
**IP Filtering**                       | Good to Have       | Restrict admin API endpoints and internal export operations to trusted NAT IPs.
**Object Lifecycle Management (OLM)**  | Highly Recommended | **Enable abortIncompleteMultipartUpload** to clean up abandoned, incomplete client uploads. If Autoclass is disabled, automatically transition older, unaccessed user data to standard cold classes (e.g., transition to `ARCHIVE` after 365 days).
**Labels & Tagging**                   | Good to Have       | Apply organizational metadata tags (e.g. `{"data-class": "ugc"}`) to classify files.
**Storage Intelligence**               | Good to Have       | Use Storage Insights Inventory Reports to track upload scales, distribution statistics, and file counts across massive environments.
**Storage Transfer Service (STS)**     | Good to Have       | Replicate data to backup regions or move ingested data to processing clusters.
**Cloud Logging**                      | Good to Have       | Enable audit logging for tracing client-side errors, upload failures, and CORS anomalies.
**Cloud Monitoring**                   | Highly Recommended | Setup alerts on application error rates (4xx/5xx codes), client quota usage, and volume changes.
**Pub/Sub Notifications**              | Good to Have       | Trigger downstream processing (e.g., malware scanning, image resizing, indexing) automatically when a new object is finalized.

## Official Documentation References

Feature / Topic             | Documentation Link
:-------------------------- | :-----------------
Autoclass                   | https://cloud.google.com/storage/docs/autoclass
Storage Classes             | https://cloud.google.com/storage/docs/storage-classes
Locations                   | https://cloud.google.com/storage/docs/locations
Signed URLs                 | https://cloud.google.com/storage/docs/access-control/signed-urls
CORS                        | https://cloud.google.com/storage/docs/using-cors
Uniform Bucket-Level Access | https://cloud.google.com/storage/docs/uniform-bucket-level-access
CMEK                        | https://cloud.google.com/storage/docs/encryption/customer-managed-keys
Soft Delete                 | https://cloud.google.com/storage/docs/soft-delete
Object Versioning           | https://cloud.google.com/storage/docs/object-versioning
Bucket IP Filtering         | https://cloud.google.com/storage/docs/ip-filtering-overview
Lifecycle Management        | https://cloud.google.com/storage/docs/lifecycle
Bucket Labels               | https://cloud.google.com/storage/docs/using-bucket-labels
Inventory Reports           | https://cloud.google.com/storage/docs/insights/inventory-reports
Storage Transfer Service    | https://cloud.google.com/storage-transfer/docs/overview
Cloud Audit Logging         | https://cloud.google.com/storage/docs/audit-logging
Cloud Monitoring            | https://cloud.google.com/storage/docs/monitoring
Pub/Sub Notifications       | https://cloud.google.com/storage/docs/pubsub-notifications

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