Enforce or restrict the encryption types for a bucket

This document describes how to configure which encryption methods are allowed or restricted for new objects in a Cloud Storage bucket. You can configure a bucket to enforce or restrict the use of standard encryption (Google default encryption), customer-managed encryption keys (CMEK), or customer-supplied encryption keys (CSEK) for any new objects that are created within the bucket.

For example, to help protect against ransomware attacks, you can require that all new objects are encrypted with either standard encryption or CMEK, and restrict the use of customer-supplied encryption keys.

For more information about the encryption methods that are available, see Data encryption options.

Cloud Storage enforces the encryption configuration for all actions that create a new object, such as uploading an object, copying an object, composing objects, and restoring a soft-deleted object.

Before you begin

To get the permissions that you need to configure encryption enforcement for a bucket, ask your administrator to grant you the Storage Admin (roles/storage.admin) IAM role on bucket. For more information about granting roles, see Manage access to projects, folders, and organizations.

This predefined role contains the permissions required to configure encryption enforcement for a bucket. To see the exact permissions that are required, expand the Required permissions section:

Required permissions

The following permissions are required to configure encryption enforcement for a bucket:

  • Set the configuration when creating a new bucket: storage.buckets.create
  • Update the configuration for an existing bucket: storage.buckets.update

You might also be able to get these permissions with custom roles or other predefined roles.

Create a bucket that enforces encryption types

You can specify the encryption methods that are allowed or restricted for the objects in a bucket when you create a new bucket.

If you set a default Cloud KMS key for the bucket, then you must also allow encryption using CMEKs or customer-supplied encryption keys.

gcloud

  1. Create a JSON file that contains the following information:

    {
      "gmekEnforcement": {"restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"},
      "cmekEnforcement": {"restrictionMode": "CMEK_RESTRICTION_MODE"},
      "csekEnforcement": {"restrictionMode": "CSEK_RESTRICTION_MODE"}
    }

    Replace the following:

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: Whether encryption using standard encryption (Google default encryption) is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use standard encryption.
      • FullyRestricted: new objects can't use standard encryption.
    • CMEK_RESTRICTION_MODE: Whether encryption using CMEKs is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use CMEKs.
      • FullyRestricted: new objects can't use CMEKs.
    • CSEK_RESTRICTION_MODE: Whether encryption using customer-supplied encryption keys is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use customer-supplied encryption keys.
      • FullyRestricted: new objects can't use customer-supplied encryption keys.

    You must allow at least one encryption type. If you omit the enforcement configuration for a specific encryption type, then that encryption type is allowed by default.

  2. Use the gcloud storage buckets create command with the --encryption-enforcement-file flag:

    gcloud storage buckets create gs://BUCKET_NAME \
      --encryption-enforcement-file=ENCRYPTION_ENFORCEMENT_FILE

    Replace the following:

    • BUCKET_NAME: the name of the bucket.
    • ENCRYPTION_ENFORCEMENT_FILE: the path to the JSON file that you created in the previous step.

Client libraries

C#

For more information, see the Cloud Storage C# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class BucketSetEncryptionEnforcementConfigSample
{
    /// <summary>
    /// Set the encryption enforcement configuration for a bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <param name="kmsKeyName">
    /// The full resource name of the Cloud KMS key (CMEK). 
    /// Required if <paramref name="enforceCmek"/> is true.
    /// </param>
    /// <param name="enforceCmek">If true, enforces Customer-Managed Encryption Key.</param>
    /// <param name="enforceGmek">If true, enforces Google-Managed Encryption Key.</param>
    /// <param name="enforceCsek">If true, enforces Customer-Supplied Encryption Key.</param>
    public Bucket.EncryptionData SetBucketEncryptionEnforcementConfig(
        string bucketName = "your-unique-bucket-name",
        string kmsKeyName = null,
        bool enforceCmek = false,
        bool enforceGmek = false,
        bool enforceCsek = false)
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        if (bucket.Encryption == null)
        {
            bucket.Encryption = new Bucket.EncryptionData();
        }

        if (!string.IsNullOrEmpty(kmsKeyName))
        {
            bucket.Encryption.DefaultKmsKeyName = kmsKeyName;
            Console.WriteLine($"Default Key Set: {kmsKeyName}");
        }
        else
        {
            bucket.Encryption.DefaultKmsKeyName = null;
            Console.WriteLine("Default Key Set: None");
        }

        string cmek = (enforceGmek || enforceCsek) ? "FullyRestricted" : "NotRestricted";
        string gmek = (enforceCmek || enforceCsek) ? "FullyRestricted" : "NotRestricted";
        string csek = (enforceCmek || enforceGmek) ? "FullyRestricted" : "NotRestricted";

        string message = enforceCmek ? "CMEK-only enforcement policy"
            : enforceGmek ? "GMEK-only enforcement policy"
            : enforceCsek ? "CSEK-only enforcement policy"
            : "no encryption enforcement policy";

        bucket.Encryption.CustomerManagedEncryptionEnforcementConfig = new Bucket.EncryptionData.CustomerManagedEncryptionEnforcementConfigData { RestrictionMode = cmek };
        bucket.Encryption.CustomerSuppliedEncryptionEnforcementConfig = new Bucket.EncryptionData.CustomerSuppliedEncryptionEnforcementConfigData { RestrictionMode = csek };
        bucket.Encryption.GoogleManagedEncryptionEnforcementConfig = new Bucket.EncryptionData.GoogleManagedEncryptionEnforcementConfigData { RestrictionMode = gmek };

        if (message != null)
        {
            Console.WriteLine($"Bucket {bucketName} updated with {message}");
        }

        var updatedBucket = storage.UpdateBucket(bucket);
        return updatedBucket.Encryption;
    }
}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

import (
	"context"
	"fmt"
	"io"
	"time"

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

// setBucketEncryptionEnforcementConfig sets a bucket's encryption enforcement configuration.
func setBucketEncryptionEnforcementConfig(w io.Writer, projectID, bucketName string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	bucket := client.Bucket(bucketName)
	if err := bucket.Create(ctx, projectID, &storage.BucketAttrs{
		GoogleManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
		CustomerManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.NotRestricted,
		},
		CustomerSuppliedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
	}); err != nil {
		return fmt.Errorf("Bucket(%q).Create: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Bucket %v encryption enforcement policies set.\n", bucketName)
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.BucketInfo.CustomerManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.CustomerSuppliedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.EncryptionEnforcementRestrictionMode;
import com.google.cloud.storage.BucketInfo.GoogleManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetBucketEncryptionEnforcementConfig {
  public static void setBucketEncryptionEnforcementConfig(String projectId, String bucketName)
      throws Exception {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    try (Storage storage =
        StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {

      // Example 1: Enforce GMEK Only
      setGmekEnforcedPolicy(storage, "g-" + bucketName);

      // Example 2: Enforce CMEK Only
      setCmekEnforcedPolicy(storage, "c-" + bucketName);

      // Example 3: Restrict CSEK (Ransomware Protection)
      restrictCsekPolicy(storage, "rc-" + bucketName);
    }
  }

  public static void setGmekEnforcedPolicy(Storage storage, String bucketName) {
    GoogleManagedEncryptionEnforcementConfig gmekConfig =
        GoogleManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.NOT_RESTRICTED);
    CustomerManagedEncryptionEnforcementConfig cmekConfig =
        CustomerManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);
    CustomerSuppliedEncryptionEnforcementConfig csekConfig =
        CustomerSuppliedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

    BucketInfo bucketInfo =
        BucketInfo.newBuilder(bucketName)
            .setGoogleManagedEncryptionEnforcementConfig(gmekConfig)
            .setCustomerManagedEncryptionEnforcementConfig(cmekConfig)
            .setCustomerSuppliedEncryptionEnforcementConfig(csekConfig)
            .build();

    Bucket bucket = storage.create(bucketInfo);
    System.out.println(
        "Bucket " + bucket.getName() + " created with GMEK-only enforcement policy.");
  }

  public static void setCmekEnforcedPolicy(Storage storage, String bucketName) {
    GoogleManagedEncryptionEnforcementConfig gmekConfig =
        GoogleManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);
    CustomerManagedEncryptionEnforcementConfig cmekConfig =
        CustomerManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.NOT_RESTRICTED);
    CustomerSuppliedEncryptionEnforcementConfig csekConfig =
        CustomerSuppliedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

    BucketInfo bucketInfo =
        BucketInfo.newBuilder(bucketName)
            .setGoogleManagedEncryptionEnforcementConfig(gmekConfig)
            .setCustomerManagedEncryptionEnforcementConfig(cmekConfig)
            .setCustomerSuppliedEncryptionEnforcementConfig(csekConfig)
            .build();

    Bucket bucket = storage.create(bucketInfo);
    System.out.println(
        "Bucket " + bucket.getName() + " created with CMEK-only enforcement policy.");
  }

  public static void restrictCsekPolicy(Storage storage, String bucketName) {
    CustomerSuppliedEncryptionEnforcementConfig csekConfig =
        CustomerSuppliedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

    BucketInfo bucketInfo =
        BucketInfo.newBuilder(bucketName)
            .setCustomerSuppliedEncryptionEnforcementConfig(csekConfig)
            .build();

    Bucket bucket = storage.create(bucketInfo);
    System.out.println("Bucket " + bucket.getName() + " created with a policy to restrict CSEK.");
  }
}

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

use Google\Cloud\Storage\StorageClient;

/**
 * Creates a bucket with specific encryption enforcement (e.g., CMEK-only).
 *
 * @param string $bucketName The ID of your GCS bucket (e.g. "my-bucket").
 * @param string $kmsKeyName The name of the KMS key to be used as the default (e.g. "projects/my-project/...").
 */
function set_bucket_encryption_enforcement_config(string $bucketName, string $kmsKeyName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    // This configuration enforces that all objects uploaded to the bucket
    // must use Customer Managed Encryption Keys (CMEK).
    $options = [
        'encryption' => [
            'defaultKmsKeyName' => $kmsKeyName,
            'googleManagedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'FullyRestricted',
            ],
            'customerSuppliedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'FullyRestricted',
            ],
            'customerManagedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'NotRestricted',
            ],
        ],
    ];
    $storage->createBucket($bucketName, $options);

    printf('Bucket %s created with encryption enforcement configuration.' . PHP_EOL, $bucketName);
}

Python

For more information, see the Cloud Storage Python API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

from google.cloud import storage
from google.cloud.storage.bucket import EncryptionEnforcementConfig


def set_bucket_encryption_enforcement_config(bucket_name):
    """Creates a bucket with encryption enforcement configuration."""
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    # Setting restriction_mode to "FullyRestricted" for Google-managed encryption (GMEK)
    # means objects cannot be created using the default Google-managed keys.
    bucket.encryption.google_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    # Setting restriction_mode to "NotRestricted" for Customer-managed encryption (CMEK)
    # ensures that objects ARE permitted to be created using Cloud KMS keys.
    bucket.encryption.customer_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="NotRestricted")
    )

    # Setting restriction_mode to "FullyRestricted" for Customer-supplied encryption (CSEK)
    # prevents objects from being created using raw, client-side provided keys.
    bucket.encryption.customer_supplied_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    bucket.create()

    print(f"Created bucket {bucket.name} with Encryption Enforcement Config.")

REST APIs

JSON API

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  2. Create a JSON file that contains the settings for the bucket. For a complete list of settings, see the Buckets: Insert documentation. The following settings define only the bucket name and encryption:

    {
      "name": "BUCKET_NAME",
      "encryption": {
        "googleManagedEncryptionEnforcementConfig": {
          "restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"
        },
        "customerManagedEncryptionEnforcementConfig": {
          "restrictionMode": "CMEK_RESTRICTION_MODE"
        },
        "customerSuppliedEncryptionEnforcementConfig": {
          "restrictionMode": "CSEK_RESTRICTION_MODE"
        }
      }
    }

    Replace the following:

    • BUCKET_NAME: The name of the bucket.
    • STANDARD_ENCRYPTION_RESTRICTION_MODE: Whether encryption using standard encryption (Google default encryption) is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use standard encryption.
      • FullyRestricted: new objects can't use standard encryption.
    • CMEK_RESTRICTION_MODE: Whether encryption using CMEKs is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use CMEKs.
      • FullyRestricted: new objects can't use CMEKs.
    • CSEK_RESTRICTION_MODE: Whether encryption using customer-supplied encryption keys is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use customer-supplied encryption keys.
      • FullyRestricted: new objects can't use customer-supplied encryption keys.

    You must allow at least one encryption type. If you omit the enforcement configuration for a specific encryption type, then that encryption type is allowed by default.

  3. Use cURL to call the JSON API with a POST Bucket request:

    curl -X POST --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.s3nsapis.fr/storage/v1/b?project=PROJECT_ID"

    Replace the following:

    • JSON_FILE_NAME: the path to the JSON file that you created in the previous step.
    • PROJECT_ID: the ID or number of the project for your bucket.

XML API

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  2. Create an XML file that contains the settings for the bucket. For a complete list of settings, see the XML: Create a bucket documentation. The following settings define only the encryption enforcement:

    <CreateBucketConfiguration>
      <EncryptionConfiguration>
        <GoogleManagedEncryptionEnforcement>
          <RestrictionMode>STANDARD_ENCRYPTION_RESTRICTION_MODE</RestrictionMode>
        </GoogleManagedEncryptionEnforcement>
        <CustomerManagedEncryptionEnforcement>
          <RestrictionMode>CMEK_RESTRICTION_MODE</RestrictionMode>
        </CustomerManagedEncryptionEnforcement>
        <CustomerSuppliedEncryptionEnforcement>
          <RestrictionMode>CSEK_RESTRICTION_MODE</RestrictionMode>
        </CustomerSuppliedEncryptionEnforcement>
      </EncryptionConfiguration>
    </CreateBucketConfiguration>

    Replace the following:

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: Whether encryption using standard encryption (Google default encryption) is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use standard encryption.
      • FullyRestricted: new objects can't use standard encryption.
    • CMEK_RESTRICTION_MODE: Whether encryption using CMEKs is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use CMEKs.
      • FullyRestricted: new objects can't use CMEKs.
    • CSEK_RESTRICTION_MODE: Whether encryption using customer-supplied encryption keys is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use customer-supplied encryption keys.
      • FullyRestricted: new objects can't use customer-supplied encryption keys.

    You must allow at least one encryption type. If you omit the enforcement configuration for a specific encryption type, then that encryption type is allowed by default.

  3. Use cURL to call the XML API with a PUT Bucket request:

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "x-goog-project-id: PROJECT_ID" \
      "https://storage.s3nsapis.fr/BUCKET_NAME"

    Replace the following:

    • XML_FILE_NAME: the path to the XML file that you created in the previous step.
    • PROJECT_ID: the ID or number of the project for your bucket.
    • BUCKET_NAME: the name of the bucket.

Update the encryption types that are allowed for a bucket

To update which encryption methods are allowed for new objects in an existing bucket, complete the following steps.

If the bucket has a default KMS key set, then you can't restrict both CMEK and customer-supplied encryption keys because that would prevent new objects from being created. Either allow CMEK or CSEK on such a bucket, or remove the default Cloud KMS key from the bucket.

gcloud

  1. Create a JSON file that contains the following information:

    {
      "gmekEnforcement": {"restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"},
      "cmekEnforcement": {"restrictionMode": "CMEK_RESTRICTION_MODE"},
      "csekEnforcement": {"restrictionMode": "CSEK_RESTRICTION_MODE"}
    }

    Replace the following:

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: Whether encryption using standard encryption (Google default encryption) is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use standard encryption.
      • FullyRestricted: new objects can't use standard encryption.
    • CMEK_RESTRICTION_MODE: Whether encryption using CMEKs is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use CMEKs.
      • FullyRestricted: new objects can't use CMEKs.
    • CSEK_RESTRICTION_MODE: Whether encryption using customer-supplied encryption keys is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use customer-supplied encryption keys.
      • FullyRestricted: new objects can't use customer-supplied encryption keys.

    You must allow at least one encryption type. If you omit an encryption type, the existing configuration is retained.

  2. Use the gcloud storage buckets update command with the --encryption-enforcement-file flag:

    gcloud storage buckets update gs://BUCKET_NAME \
      --encryption-enforcement-file=ENCRYPTION_ENFORCEMENT_FILE

    Replace the following:

    • BUCKET_NAME: the name of the bucket.
    • ENCRYPTION_ENFORCEMENT_FILE: the path to the JSON file that you created in the previous step.

    It might take up to two minutes for the updated configuration to take effect.

Client libraries

C#

For more information, see the Cloud Storage C# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class BucketUpdateEncryptionEnforcementConfigSample
{
    /// <summary>
    /// Updates the encryption enforcement configuration of the bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <param name="encryptionData">The encryption configuration for the bucket.</param>
    public Bucket.EncryptionData BucketUpdateEncryptionEnforcementConfig(string bucketName = "your-unique-bucket-name", Bucket.EncryptionData encryptionData = null)
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        if (bucket.Encryption is null
            || (bucket.Encryption.CustomerManagedEncryptionEnforcementConfig is null
                && bucket.Encryption.CustomerSuppliedEncryptionEnforcementConfig is null
                && bucket.Encryption.GoogleManagedEncryptionEnforcementConfig is null))
        {
            Console.WriteLine($"No Encryption Enforcement Configuration found for bucket {bucketName}");
            return bucket.Encryption;
        }

        bucket.Encryption = encryptionData;
        bucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"The Encryption Enforcement Configuration has been updated for the bucket {bucketName}");
        return bucket.Encryption;
    }
}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

import (
	"context"
	"fmt"
	"io"
	"time"

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

// updateBucketEncryptionEnforcementConfig updates a bucket's encryption enforcement configuration.
func updateBucketEncryptionEnforcementConfig(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*30)
	defer cancel()

	bucket := client.Bucket(bucketName)
	if _, err := bucket.Update(ctx, storage.BucketAttrsToUpdate{
		GoogleManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.NotRestricted,
		},
		CustomerManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
		CustomerSuppliedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
	}); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Bucket %v encryption enforcement policies updated.\n", bucketName)
	return nil
}

Java

For more information, see the Cloud Storage Java API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo.CustomerManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.CustomerSuppliedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.EncryptionEnforcementRestrictionMode;
import com.google.cloud.storage.BucketInfo.GoogleManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class UpdateBucketEncryptionEnforcementConfig {
  public static void updateBucketEncryptionEnforcementConfig(String projectId, String bucketName)
      throws Exception {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket with CMEK and CSEK restricted
    // String bucketName = "your-unique-bucket-name";

    try (Storage storage =
        StorageOptions.newBuilder().setProjectId(projectId).build().getService()) {

      Bucket bucket = storage.get(bucketName);
      if (bucket == null) {
        System.out.println("Bucket " + bucketName + " not found.");
        return;
      }

      // 1. Update a specific type (e.g., change GMEK to FULLY_RESTRICTED)
      GoogleManagedEncryptionEnforcementConfig newGmekConfig =
          GoogleManagedEncryptionEnforcementConfig.of(
              EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

      // 2. Remove a specific type (e.g., remove CMEK enforcement)
      CustomerManagedEncryptionEnforcementConfig newCmekConfig =
          CustomerManagedEncryptionEnforcementConfig.of(
              EncryptionEnforcementRestrictionMode.NOT_RESTRICTED);

      // For the update, need to specify all three configs, so keeping this same as before
      CustomerSuppliedEncryptionEnforcementConfig sameCsekConfig =
          CustomerSuppliedEncryptionEnforcementConfig.of(
              EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

      bucket.toBuilder()
          .setGoogleManagedEncryptionEnforcementConfig(newGmekConfig)
          .setCustomerManagedEncryptionEnforcementConfig(newCmekConfig)
          .setCustomerSuppliedEncryptionEnforcementConfig(sameCsekConfig)
          .build()
          .update();

      System.out.println("Encryption enforcement policy updated for bucket " + bucketName);
      System.out.println("GMEK is now fully restricted, and CMEK enforcement has been removed.");
    }
  }
}

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

use Google\Cloud\Storage\StorageClient;

/**
 * Updates or removes encryption enforcement configurations from a bucket.
 *
 * @param string $bucketName The ID of your GCS bucket (e.g. "my-bucket").
 */
function update_bucket_encryption_enforcement_config(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    // Update a specific encryption type's restriction mode
    // This partial update preserves other existing encryption settings.
    $updateOptions = [
        'encryption' => [
            'googleManagedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'FullyRestricted'
            ]
        ]
    ];
    $bucket->update($updateOptions);
    printf('Google-managed encryption enforcement set to FullyRestricted for %s.' . PHP_EOL, $bucketName);

    // Remove all encryption enforcement configurations altogether
    // Setting these values to null removes the policies from the bucket metadata.
    $clearOptions = [
        'encryption' => [
            'defaultKmsKeyName' => null,
            'googleManagedEncryptionEnforcementConfig' => null,
            'customerSuppliedEncryptionEnforcementConfig' => null,
            'customerManagedEncryptionEnforcementConfig' => null,
        ],
    ];

    $bucket->update($clearOptions);
    printf('All encryption enforcement configurations removed from bucket %s.' . PHP_EOL, $bucketName);
}

Python

For more information, see the Cloud Storage Python API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for client libraries.

Before running code samples, set the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable to s3nsapis.fr.

from google.cloud import storage
from google.cloud.storage.bucket import EncryptionEnforcementConfig


def update_bucket_encryption_enforcement_config(bucket_name):
    """Updates the encryption enforcement policy for a bucket."""
    # The ID of your GCS bucket with GMEK and CSEK restricted
    # bucket_name = "your-unique-bucket-name"

    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)

    # Update a specific type (e.g., change GMEK to NotRestricted)
    bucket.encryption.google_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="NotRestricted")
    )

    # Update another type (e.g., change CMEK to FullyRestricted)
    bucket.encryption.customer_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    # Keeping CSEK unchanged
    bucket.encryption.customer_supplied_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    bucket.patch()

    print(f"Encryption enforcement policy updated for bucket {bucket.name}.")

    gmek = bucket.encryption.google_managed_encryption_enforcement_config
    cmek = bucket.encryption.customer_managed_encryption_enforcement_config
    csek = bucket.encryption.customer_supplied_encryption_enforcement_config

    print(f"GMEK restriction mode: {gmek.restriction_mode if gmek else 'None'}")
    print(f"CMEK restriction mode: {cmek.restriction_mode if cmek else 'None'}")
    print(f"CSEK restriction mode: {csek.restriction_mode if csek else 'None'}")

REST APIs

JSON API

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  2. Create a JSON file that contains the following information:

    {
      "encryption": {
        "googleManagedEncryptionEnforcementConfig": {
          "restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"
        },
        "customerManagedEncryptionEnforcementConfig": {
          "restrictionMode": "CMEK_RESTRICTION_MODE"
        },
        "customerSuppliedEncryptionEnforcementConfig": {
          "restrictionMode": "CSEK_RESTRICTION_MODE"
        }
      }
    }

    Replace the following:

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: Whether encryption using standard encryption (Google default encryption) is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use standard encryption.
      • FullyRestricted: new objects can't use standard encryption.
    • CMEK_RESTRICTION_MODE: Whether encryption using CMEKs is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use CMEKs.
      • FullyRestricted: new objects can't use CMEKs.
    • CSEK_RESTRICTION_MODE: Whether encryption using customer-supplied encryption keys is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use customer-supplied encryption keys.
      • FullyRestricted: new objects can't use customer-supplied encryption keys.

    You must allow at least one encryption type. If you omit an encryption type, the existing configuration is retained.

  3. Use cURL to call the JSON API with a PATCH Bucket request:

    curl -X PATCH --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.s3nsapis.fr/storage/v1/b/BUCKET_NAME?fields=encryption"

    Replace the following:

    • JSON_FILE_NAME: the path to the JSON file that you created in the previous step.
    • BUCKET_NAME: the name of the bucket.

    It might take up to two minutes for the updated configuration to take effect.

XML API

  1. Have gcloud CLI installed and initialized, which lets you generate an access token for the Authorization header.

  2. Create an XML file that contains the encryption settings for the bucket. The following settings define only the encryption enforcement configuration.

    <EncryptionConfiguration>
      <GoogleManagedEncryptionEnforcement>
        <RestrictionMode>STANDARD_ENCRYPTION_RESTRICTION_MODE</RestrictionMode>
      </GoogleManagedEncryptionEnforcement>
      <CustomerManagedEncryptionEnforcement>
        <RestrictionMode>CMEK_RESTRICTION_MODE</RestrictionMode>
      </CustomerManagedEncryptionEnforcement>
      <CustomerSuppliedEncryptionEnforcement>
        <RestrictionMode>CSEK_RESTRICTION_MODE</RestrictionMode>
      </CustomerSuppliedEncryptionEnforcement>
    </EncryptionConfiguration>

    Replace the following:

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: Whether encryption using standard encryption (Google default encryption) is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use standard encryption.
      • FullyRestricted: new objects can't use standard encryption.
    • CMEK_RESTRICTION_MODE: Whether encryption using CMEKs is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use CMEKs.
      • FullyRestricted: new objects can't use CMEKs.
    • CSEK_RESTRICTION_MODE: Whether encryption using customer-supplied encryption keys is allowed when creating objects in this bucket. The following values are supported:
      • NotRestricted: new objects can use customer-supplied encryption keys.
      • FullyRestricted: new objects can't use customer-supplied encryption keys.

    You must allow at least one encryption type.

  3. Use cURL to call the XML API with a PUT Bucket request scoped to ?encryptionConfig:

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.s3nsapis.fr/BUCKET_NAME?encryptionConfig"

    Replace the following:

    • XML_FILE_NAME: the path to the XML file that you created in the previous step.
    • BUCKET_NAME: the name of the bucket.

    It might take up to two minutes for the updated configuration to take effect.

View the encryption settings for a bucket

For steps to view which encryption methods are allowed for a bucket, see Get bucket metadata.

What's next