アクセス制御リスト(ACL)の作成と管理

概要

このページでは、アクセス制御リスト(ACL)を使用してバケットとオブジェクトへのアクセスを制御する方法について説明します。ACL は、バケットとオブジェクトへのアクセス権を持つユーザーと各ユーザーのアクセスレベルを定義するために使用できるメカニズムです。

リソースへのアクセス制御に ACL を使用する必要があるかどうかについては、ACL の概要をご覧ください。

必要なロール

ACL の作成と管理に必要な権限を取得するには、ACL の作成と管理を行うオブジェクトが含まれているバケットに対するストレージ管理者(roles/storage.admin)IAM ロールを付与するよう管理者に依頼してください。

この事前定義ロールには、ACL の作成と管理に必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

  • storage.buckets.get
  • storage.buckets.list
    • この権限は、 Cloud de Confiance コンソールを使用してこのページのタスクを実行する場合にのみ必要です。
  • storage.buckets.setIamPolicy
  • storage.buckets.update
  • storage.objects.get
  • storage.objects.getIamPolicy
  • storage.objects.setIamPolicy
  • storage.objects.update

カスタムロールを使用して、これらの権限を取得することもできます。

バケットに対するロールの付与については、バケットでの IAM ポリシーの設定と管理をご覧ください。

ACL の設定または変更

コンソール

  1. Cloud de Confiance コンソールで Cloud Storage ブラウザに移動します。
    Cloud Storage ブラウザに移動

  2. バケットのリストで、ACL を変更するオブジェクトが存在するバケットの名前をクリックします。

  3. ACL を設定または変更するオブジェクトの名前をクリックします。

  4. [アクセス権を編集] をクリックします。

    権限ダイアログが開き、オブジェクトの現在の ACL が表示されます。

  5. [+ エントリを追加] をクリックします。

  6. アクセス権を付与するエンティティの種類を選択します。

    [エンティティ] は、権限を付与する対象の種類(ユーザーやグループなど)を指定します。[エンティティ] に指定できる値の一覧については、アクセス制御のスコープをご覧ください。

  7. [名前] に値を入力します。

    [名前] は、特定のユーザー、グループ、その他のエンティティ タイプを識別します。[名前] に指定できる値の一覧については、アクセス制御のスコープをご覧ください。

    [エンティティ] と [名前] の組み合わせにより、権限の適用対象が定義されます。

  8. [アクセス権] の値を選択します。

    [アクセス権] は、オブジェクトに設定する権限を定義します。[アクセス権] に指定できる値の一覧については、アクセス制御の権限をご覧ください。

  9. [保存] をクリックします。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Cloud de Confiance コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

オブジェクトに対する個別の権限付与を追加、変更、削除するには、目的のフラグを指定して objects update コマンドを使用します。

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME FLAG

ここで

  • BUCKET_NAME は、変更が適用されるオブジェクトを含むバケットの名前です。例: example-travel-maps

  • OBJECT_NAME は、変更が適用されるオブジェクトの名前です。例: paris.jpg

  • FLAG は、次のいずれかです。

    • --add-acl-grantと、追加または変更に必要な権限。例: --add-acl-grant=entity=user-example-service-account@example-project.s3ns.iam.gserviceaccount.com,role=READER

    • --remove-acl-grant と、アクセス権を削除するエンティティ。例: --remove-acl-grant=user-example-service-account@example-project.s3ns.iam.gserviceaccount.com

オブジェクトのすべての ACL を置き換えるには:

  1. JSON 形式または YAML 形式のファイルで ACL を定義します。

    たとえば、次の ACL は、プロジェクト 867489160491 のオーナーとユーザー example-service-account@example-project.s3ns.iam.gserviceaccount.com にオブジェクト paris.jpg に対する OWNER 権限を付与し、gs-announce グループのメンバーに paris.jpg に対する READER 権限を付与します。

    [
    {
      "entity": "project-owners-867489160491",
      "role": "OWNER",
      "projectTeam": {
        "projectNumber": "867489160491",
        "team": "owners"
      },
    },
    {
      "entity": "user-example-service-account@example-project.s3ns.iam.gserviceaccount.com",
      "email": "example-service-account@example-project.s3ns.iam.gserviceaccount.com",
      "role": "OWNER"
    },
    {
      "entity": "group-gs-announce@googlegroups.com",
      "email": "gs-announce@googlegroups.com",
      "role": "READER"
    }
    ]
    
  2. objects update コマンドを使用し、--acl-file フラグを指定します。

    gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME --acl-file=FILE_LOCATION

    ここで

    • BUCKET_NAME は、ACL が適用されるオブジェクトを含むバケットの名前です。例: example-travel-maps

    • OBJECT_NAME は、ACL が適用されるオブジェクトの名前です。例: paris.jpg

    • FILE_LOCATION は、定義した ACL を含むファイルのローカルパスです。例: Desktop/acls.json

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトに ACL を追加する例です。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& entity) {
  StatusOr<gcs::ObjectAccessControl> patched_acl =
      client.CreateObjectAcl(bucket_name, object_name, entity,
                             gcs::ObjectAccessControl::ROLE_OWNER());

  if (!patched_acl) throw std::move(patched_acl).status();
  std::cout << "ACL entry for " << patched_acl->entity() << " in object "
            << patched_acl->object() << " in bucket " << patched_acl->bucket()
            << " is now " << *patched_acl << "\n";
}

以下は、ACL をオブジェクトから削除する例です。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& entity) {
  StatusOr<gcs::ObjectMetadata> original_metadata = client.GetObjectMetadata(
      bucket_name, object_name, gcs::Projection::Full());
  if (!original_metadata) throw std::move(original_metadata).status();

  std::vector<gcs::ObjectAccessControl> original_acl =
      original_metadata->acl();
  auto it = std::find_if(original_acl.begin(), original_acl.end(),
                         [entity](gcs::ObjectAccessControl const& entry) {
                           return entry.entity() == entity &&
                                  entry.role() ==
                                      gcs::ObjectAccessControl::ROLE_OWNER();
                         });

  if (it == original_acl.end()) {
    std::cout << "Could not find entity " << entity << " for file "
              << object_name << " with role OWNER in bucket " << bucket_name
              << "\n";
    return;
  }

  gcs::ObjectAccessControl owner = *it;
  google::cloud::Status status =
      client.DeleteObjectAcl(bucket_name, object_name, owner.entity());

  if (!status.ok()) throw std::runtime_error(status.message());
  std::cout << "Deleted ACL entry for " << owner.entity() << " for file "
            << object_name << " in bucket " << bucket_name << "\n";
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトに ACL を追加する例です。


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

public class AddFileOwnerSample
{
    public Google.Apis.Storage.v1.Data.Object AddFileOwner(
        string bucketName = "your-unique-bucket-name",
        string objectName = "my-file-name",
        string userEmail = "dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName, new GetObjectOptions
        {
            Projection = Projection.Full
        });

        storageObject.Acl.Add(new ObjectAccessControl
        {
            Bucket = bucketName,
            Entity = $"user-{userEmail}",
            Role = "OWNER",
        });
        var updatedObject = storage.UpdateObject(storageObject);
        Console.WriteLine($"Added user { userEmail} as an owner on file { objectName}.");
        return updatedObject;
    }
}

以下は、ACL をオブジェクトから削除する例です。


using Google.Cloud.Storage.V1;
using System;
using System.Linq;

public class RemoveFileOwnerSample
{
    public void RemoveFileOwner(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name",
        string userEmail = "dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName, new GetObjectOptions { Projection = Projection.Full });
        if (storageObject.Acl == null)
        {
            Console.WriteLine("No owner to remove");
        }
        else
        {
            storageObject.Acl = storageObject.Acl.Where((acl) => !(acl.Entity == $"user-{userEmail}" && acl.Role == "OWNER")).ToList();
            var updatedObject = storage.UpdateObject(storageObject);
            Console.WriteLine($"Removed user {userEmail} from file {objectName}.");
        }
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトに ACL を追加する例です。

import (
	"context"
	"fmt"

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

// addFileOwner adds ACL to the specified object.
func addFileOwner(bucket, object string, entity storage.ACLEntity) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// entity := storage.AllUsers
	role := storage.RoleOwner

	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	acl := client.Bucket(bucket).Object(object).ACL()
	if err := acl.Set(ctx, entity, role); err != nil {
		return fmt.Errorf("ACLHandle.Set: %w", err)
	}
	return nil
}

以下は、ACL をオブジェクトから削除する例です。

import (
	"context"
	"fmt"

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

// removeFileOwner removes default ACL from the given object.
func removeFileOwner(bucket, object string, entity storage.ACLEntity) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// entity := storage.AllUsers
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	acl := client.Bucket(bucket).Object(object).ACL()
	if err := acl.Delete(ctx, entity); err != nil {
		return fmt.Errorf("ACLHandle.Delete: %w", err)
	}
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトに ACL を追加する例です。


import com.google.cloud.storage.Acl;
import com.google.cloud.storage.Acl.Role;
import com.google.cloud.storage.Acl.User;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class AddBlobOwner {

  public static void addBlobOwner(
      String projectId, String bucketName, String userEmail, String blobName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

    // Email of the user you wish to add as a file owner
    // String userEmail = "someuser@domain.com"

    // The name of the blob/file that you wish to modify permissions on
    // String blobName = "your-blob-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Blob blob = storage.get(BlobId.of(bucketName, blobName));
    Acl newOwner = Acl.of(new User(userEmail), Role.OWNER);

    blob.createAcl(newOwner);
    System.out.println(
        "Added user "
            + userEmail
            + " as an owner on blob "
            + blobName
            + " in bucket "
            + bucketName);
  }
}

以下は、ACL をオブジェクトから削除する例です。


import com.google.cloud.storage.Acl.User;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class RemoveBlobOwner {

  public static void removeBlobOwner(
      String projectId, String bucketName, String userEmail, String blobName) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

    // Email of the user you wish to remove as a file owner
    // String userEmail = "someuser@domain.com"

    // The name of the blob/file that you wish to modify permissions on
    // String blobName = "your-blob-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Blob blob = storage.get(BlobId.of(bucketName, blobName));
    User ownerToRemove = new User(userEmail);

    boolean success = blob.deleteAcl(ownerToRemove);
    if (success) {
      System.out.println(
          "Removed user "
              + userEmail
              + " as an owner on file "
              + blobName
              + " in bucket "
              + bucketName);
    } else {
      System.out.println("User " + userEmail + " was not found");
    }
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトに ACL を追加する例です。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The name of the file to access
// const fileName = 'file.txt';

// The email address of the user to add
// const userEmail = 'user-email-to-add';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function addFileOwner() {
  await storage
    .bucket(bucketName)
    .file(fileName)
    .acl.owners.addUser(userEmail);

  console.log(`Added user ${userEmail} as an owner on file ${fileName}.`);
}

addFileOwner().catch(console.error);

以下は、ACL をオブジェクトから削除する例です。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

// The email address of the user to remove
// const userEmail = 'user-email-to-remove';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function removeFileOwner() {
  // Removes the user from the access control list of the file. You can use
  // deleteAllUsers(), deleteDomain(), deleteProject(), deleteGroup(), and
  // deleteAllAuthenticatedUsers() to remove access for different types of entities.
  await storage
    .bucket(bucketName)
    .file(fileName)
    .acl.owners.deleteUser(userEmail);

  console.log(`Removed user ${userEmail} from file ${fileName}.`);
}

removeFileOwner().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトに ACL を追加する例です。

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to an object's ACL.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $entity The entity for which to update access controls.
 *        (e.g. 'user-example@domain.com')
 * @param string $role The permissions to add for the specified entity.
 *        (e.g. 'OWNER')
 */
function add_object_acl(string $bucketName, string $objectName, string $entity, string $role): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    $acl->add($entity, $role);
    printf('Added %s (%s) to gs://%s/%s ACL' . PHP_EOL, $entity, $role, $bucketName, $objectName);
}

以下は、ACL をオブジェクトから削除する例です。

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an entity from an object's ACL.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $entity The entity for which to update access controls.
 *        (e.g. 'user-example@domain.com')
 */
function delete_object_acl(string $bucketName, string $objectName, string $entity): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    $acl->delete($entity);
    printf('Deleted %s from gs://%s/%s ACL' . PHP_EOL, $entity, $bucketName, $objectName);
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトに ACL を追加する例です。

from google.cloud import storage


def add_blob_owner(bucket_name, blob_name, user_email):
    """Adds a user as an owner on the given blob."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"
    # user_email = "name@example.com"

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

    # Reload fetches the current ACL from Cloud Storage.
    blob.acl.reload()

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # grant access to different types of entities. You can also use
    # `grant_read` or `grant_write` to grant different roles.
    blob.acl.user(user_email).grant_owner()
    blob.acl.save()

    print(
        "Added user {} as an owner on blob {} in bucket {}.".format(
            user_email, blob_name, bucket_name
        )
    )

以下は、ACL をオブジェクトから削除する例です。

from google.cloud import storage


def remove_blob_owner(bucket_name, blob_name, user_email):
    """Removes a user from the access control list of the given blob in the
    given bucket."""
    # bucket_name = "your-bucket-name"
    # blob_name = "your-object-name"
    # user_email = "name@example.com"

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

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # remove access for different types of entities.
    blob.acl.user(user_email).revoke_read()
    blob.acl.user(user_email).revoke_write()
    blob.acl.user(user_email).revoke_owner()
    blob.acl.save()

    print(
        f"Removed user {user_email} from blob {blob_name} in bucket {bucket_name}."
    )

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトに ACL を追加する例です。

# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# file_name   = "Name of a file in the Storage bucket"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

file.acl.add_owner email

puts "Added OWNER permission for #{email} to #{file_name}"

以下は、ACL をオブジェクトから削除する例です。

# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# file_name   = "Name of a file in the Storage bucket"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

file.acl.delete email

puts "Removed ACL permissions for #{email} from #{file_name}"

REST API

JSON API

オブジェクトを作成するとき、リクエストの本文に acl[] プロパティを指定するか、insertリクエストに predefinedAcl クエリ パラメータを指定できます。既存のオブジェクトに対しては、patch リクエストまたはupdateリクエストに acl[] プロパティまたは predefinedAcl クエリ パラメータを指定します。

オブジェクトの ACL プロパティの定義については、ObjectAccessControls リソースをご覧ください。

  1. ACL を JSON ファイル内に定義します。

    たとえば、ACL がプロジェクト 867489160491 のオーナーとユーザー example-service-account@example-project.s3ns.iam.gserviceaccount.comOWNER 権限を付与し、gs-announce グループのメンバーに READER を付与するとします。この場合、次のコンテンツを含む acls.json という名前のファイルを作成できます。

    {
    "acl": [
      {
        "entity": "project-owners-867489160491",
        "role": "OWNER",
        "projectTeam": {
          "projectNumber": "867489160491",
          "team": "owners"
        }
      },
      {
        "entity": "user-example-service-account@example-project.s3ns.iam.gserviceaccount.com",
        "role": "OWNER",
        "email": "example-service-account@example-project.s3ns.iam.gserviceaccount.com"
      },
      {
        "entity": "group-gs-announce@googlegroups.com",
        "role": "READER",
        "email": "gs-announce@googlegroups.com"
      }
    ]
    }
    
  2. JSON ファイルを含む patch リクエストを送信し、ACL を設定するオブジェクトを指定します。

たとえば、次の curl コマンドは、ドキュメント acls.json の JSON ペイロードをバケット example-travel-maps 内の paris.jpg というオブジェクトに適用します。

curl -X PATCH --data @acls.json -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://storage.s3nsapis.fr/storage/v1/b/example-travel-maps/o/paris.jpg

XML API

XML API では、ACL を XML 形式で扱います。バケットとオブジェクトの ACL を変更するには、XML ドキュメントをリクエストの本文に添付する必要があります。バケットとオブジェクトの ACL を取得すると、XML ドキュメントが返されます。XML ドキュメントには、バケットまたはオブジェクトの個々の ACL エントリが格納されています。

  • PUT Bucket リクエストを使ってバケットを作成した後、?acl パラメータ付きでもう一度 PUT Bucket リクエストを使用し、バケットの ACL を変更します。

  • PUT Object リクエストを使用してオブジェクトをアップロードした後、?acl パラメータまたは x-googl-acl リクエスト ヘッダー付きでもう一度 PUT リクエストを使用し、ACL を変更します。

たとえば、次の curl コマンドは、ドキュメント acls.xml の XML ペイロードをバケット example-travel-maps 内の paris.jpg というオブジェクトに適用します。

curl -X PUT --data-binary @acls.xml \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://storage.s3nsapis.fr/example-travel-maps/paris.jpg?acl

XML ドキュメントに次の ACL 構文を使用します。

要素 説明
AccessControlList Entries 要素と Owner 要素のコンテナ。
Owner DisplayName 要素と ID 要素のコンテナ。オブジェクトは、それをアップロードしたユーザーが常に所有するため、この要素はオブジェクトには不要です。この要素は、Amazon S3 ACL 構文を移行シナリオで使う場合に使用します。

Amazon Simple Storage Service™ および Amazon S3™ は、米国およびその他の国における Amazon.com, Inc. またはその関連会社の商標です。
ID バケット所有者の Cloud Storage ID。
DisplayName 実装なし。この値は常に空の文字列です。
Entries ゼロ個以上の Entry 要素のコンテナ。
Entry Scope 要素と Permission 要素のコンテナ。Entry に含めるのは 1 つの Scope と 1 つの Permission 要素だけにする必要があります。
Scope ACL のスコープを定義する IDEmailAddressDomain 要素のコンテナ。この要素は次のいずれかの値を格納する type 属性を持っている必要があります。UserByIDUserByEmailGroupByIDGroupByDomainAllUsersAllAuthenticatedUsers
ID 権限エントリが ID で指定される場合の利用者の ID。
EmailAddress 権限エントリがメールで指定される場合の利用者のメール識別子。
Domain 権限エントリがドメインで指定される場合の利用者のドメイン識別子。
Name 指定できるオプション要素。
Permission 付与される権限 READWRITEFULL_CONTROL

XML API を使って ACL の作業を行う場合には、以下の点に注意してください。

  • 前述の XML 形式のみを使用できます。
  • 重複するスコープは設定できません。

    ACL XML には複数のエントリを指定できますが。スコープが重複するエントリを設定することはできません。たとえば、同じスコープ要素 jane@example.com を持つ 2 個のエントリを設定することはできません。

さまざまなバケット ACL エントリの例を以下に示します。

<?xml version="1.0" encoding="UTF-8"?>
<AccessControlList>
  <Owner>
    <ID>00b4903a9721...</ID>
  </Owner>
  <Entries>
    <Entry>
      <Scope type="GroupById">
        <ID>00b4903a9722...</ID>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="UserByEmail">
        <EmailAddress>example-service-account@example-project.s3ns.iam.gserviceaccount.com</EmailAddress>
        <Name>Jefferson</Name>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="AllUsers"/>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="AllAuthenticatedUsers"/>
      <Permission>READ</Permission>
    </Entry>
  </Entries>
</AccessControlList>

ACL XML で Name 要素を設定する

バケットまたはオブジェクトから ACL を取得すると、<Name> 要素が一部のエントリに追加されている場合があります。たとえば、エントリが次のようになっている場合があります:

<Entry>
  <Scope type="UserByEmail">
    <EmailAddress>example-service-account@example-project.s3ns.iam.gserviceaccount.com</EmailAddress>
    <Name>Jefferson</Name>
  </Scope>
  <Permission>FULL_CONTROL</Permission>
</Entry>

これらのオプションの <Name> 要素は、バケットまたはオブジェクトの ACL に要素として <Name> が含まれている場合に入力されます。ACL を設定するときに、ACL エントリに <Name> 要素を含めることができます。<Name> 要素にはいずれの値も指定できます。指定した値は、ACL が削除または置換されるまで Cloud Storage に保存されます。この方法は、簡単に識別できない識別子を使用している場合に便利です。

定義済み ACL を適用する

ACL 全体を設定する際は、前述のようにエントリを一度に 1 個ずつ指定することもできますが、定義済み ACL を使用することで、特定のシナリオ向けにカスタマイズされた複数のエントリを自動的に適用できます。定義済み ACL をバケットまたはオブジェクトに適用するには、Google Cloud CLI、JSON API、XML API のいずれかを使用します。

新しいオブジェクトの場合

定義済み ACL を、オブジェクトのアップロード時にオブジェクトに適用するには:

コンソール

Cloud de Confiance コンソールでは、定義済み ACL を適用することはできません。代わりに gcloud storage を使用してください。

コマンドライン

gcloud storage cp コマンドを使用し、--predefined-acl フラグを指定します。

gcloud storage cp OBJECT gs://BUCKET_NAME --predefined-acl=PREDEFINED_ACL

たとえば、オブジェクト paris.jpg をバケット example-travel-maps にアップロードするときに定義済み ACL bucketOwnerRead を適用するには、次のようにします。

gcloud storage cp paris.jpg gs://example-travel-maps --predefined-acl=bucketOwnerRead

REST API

JSON API

事前定義された ACL を適用するには、insert リクエストに predefinedAcl クエリ文字列パラメータを使用します。

たとえば、オブジェクト paris.jpg をバケット example-travel-maps にアップロードするときに定義済み ACL bucketOwnerRead を適用するには、次のようにします。

curl -X POST --data-binary @paris.jpg -H "Content-Type: image/jpeg" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)"  \
    "https://storage.s3nsapis.fr/upload/storage/v1/b/example-travel-maps/o?name=paris.jpg&predefinedAcl=bucketOwnerRead"

XML API

事前定義された ACL を適用するには、Put Object リクエストで x-goog-acl ヘッダーを使用します。

たとえば、オブジェクト paris.jpg をバケット example-travel-maps にアップロードするときに定義済み ACL bucket-owner-read を適用するには、次のようにします。

curl -X PUT --upload-file paris.jpg -H "x-goog-acl: bucket-owner-read" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)"  \
    https://storage.s3nsapis.fr/example-travel-maps/paris.jpg

既存のバケットまたはオブジェクトの場合

既存のバケットやオブジェクトに定義済み ACL を適用することもできます。これは、定義済み ACL を別のものに変更したい場合や、カスタム ACL を定義済み ACL に更新したい場合に便利です。

コンソール

Cloud de Confiance コンソールでは、定義済み ACL を適用することはできません。代わりに gcloud storage を使用してください。

コマンドライン

objects update コマンドを使用し、--predefined-acl フラグを指定します。

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME --predefined-acl=PREDEFINED_ACL_NAME

たとえば、定義済み ACL private をバケット example-travel-maps のオブジェクト paris.jpg に適用するには、次のようにします。

gcloud storage objects update gs://example-travel-maps/paris.jpg --predefined-acl=private

REST API

JSON API

事前定義された ACL を適用するには、patch リクエストに predefinedAcl クエリ文字列パラメータを使用し、空の acl プロパティを指定します。

たとえば、定義済み ACL private をバケット example-travel-maps のオブジェクト paris.jpg に適用するには、次のようにします。

curl -X PATCH --data '{"acl": []}'  -H "Content-Type: application/json" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)"  \
    https://storage.s3nsapis.fr/storage/v1/b/example-travel-maps/o/paris.jpg?predefinedAcl=private

XML API

PUT Object リクエストで x-goog-acl ヘッダーを使用して acl クエリ文字列パラメータを指定します。ただし、発行するリクエストでは XML ドキュメントを指定しないでください。

たとえば、定義済み ACL private をバケット example-travel-maps のオブジェクト paris.jpg に適用するには、次のようにします。

curl -X PUT -H "Content-Length: 0" \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "x-goog-acl: private" \
    https://storage.s3nsapis.fr/example-travel-maps/paris.jpg?acl

デフォルト オブジェクト ACL を設定する

新しいオブジェクトを作成するたびに ACL を設定しなくても済むように、バケットにデフォルト オブジェクト ACL を設定できます。その後は、そのバケットに追加される、ACL が明示的に指定されていないすべての新しいオブジェクトについて、デフォルトが適用されます。たとえば、あるユーザー グループのみが特定のバケット内のほとんどのオブジェクトへのアクセス権を所有するように指定するとします。デフォルト オブジェクト ACL を変更して、オブジェクトをバケットに追加できます。これらの追加されたオブジェクトには、指定したデフォルト オブジェクト ACL が自動的に適用されます。ただし、特定のオブジェクトに異なる ACL を指定することもできます。その場合はデフォルト ACL が適用されません。

バケットのデフォルト オブジェクト ACL を表示、変更するには:

コンソール

Cloud de Confiance コンソールでは、デフォルト オブジェクト ACL を設定することはできません。代わりに gcloud storage を使用してください。

コマンドライン

  1. buckets describe コマンドを --format フラグとともに使用して、バケットのデフォルト オブジェクト ACL を取得します。

    gcloud storage buckets describe gs://BUCKET_NAME --format="default(default_acl)"

    ここで、BUCKET_NAME は、デフォルトのオブジェクト ACL を表示するバケットの名前です。例: my-bucket

  2. 目的のフラグを指定して buckets update コマンドを実行し、バケットのデフォルト オブジェクト ACL を変更します。

    gcloud storage buckets update gs://BUCKET_NAME FLAG

    ここで

    • BUCKET_NAME は、デフォルト オブジェクト ACL を変更するバケットの名前です。例: my-bucket

    • FLAG は、次のいずれかです。

      • --add-default-object-acl-grant と、バケットの全体的なデフォルト オブジェクト ACL に追加する権限。

      • --default-object-acl-file と、バケットの新しいデフォルト オブジェクト ACL を定義するローカル ファイルのパス。

      • --predefined-default-object-acl と、バケットの既存のデフォルト オブジェクト ACL を置き換える事前定義オブジェクト ACL の名前。

      • --remove-default-object-acl-grant とバケットのデフォルト オブジェクト ACL 全体から削除するエンティティ。

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、デフォルト オブジェクト ACL をバケットに追加する例です。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& entity, std::string const& role) {
  StatusOr<gcs::ObjectAccessControl> default_object_acl =
      client.CreateDefaultObjectAcl(bucket_name, entity, role);
  if (!default_object_acl) throw std::move(default_object_acl).status();

  std::cout << "Role " << default_object_acl->role()
            << " will be granted default to " << default_object_acl->entity()
            << " on any new object created on bucket "
            << default_object_acl->bucket() << "\n"
            << "Full attributes: " << *default_object_acl << "\n";
}

以下は、デフォルト オブジェクト ACL をバケットから削除する例です。

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& entity) {
  google::cloud::Status status =
      client.DeleteDefaultObjectAcl(bucket_name, entity);

  if (!status.ok()) throw std::runtime_error(status.message());
  std::cout << "Deleted ACL entry for " << entity << " in bucket "
            << bucket_name << "\n";
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、バケットのデフォルト オブジェクト ACL を出力する例です。


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

public class PrintBucketDefaultAclSample
{
    public IEnumerable<ObjectAccessControl> PrintBucketDefaultAcl(string bucketName = "your-unique-bucket-name")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });

        foreach (var acl in bucket.DefaultObjectAcl)
        {
            Console.WriteLine($"{acl.Role}:{acl.Entity}");
        }

        return bucket.DefaultObjectAcl;
    }
}

以下は、デフォルト オブジェクト ACL をバケットに追加する例です。


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

public class AddBucketDefaultOwnerSample
{
    public Bucket AddBucketDefaultOwner(
        string bucketName = "your-unique-bucket-name",
        string userEmail = "dev@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });

        bucket.DefaultObjectAcl.Add(new ObjectAccessControl
        {
            Bucket = bucketName,
            Entity = $"user-{userEmail}",
            Role = "OWNER",
        });
        var updatedBucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"Added user {userEmail} as a default owner on bucket {bucketName}.");
        return updatedBucket;
    }
}

以下は、デフォルト オブジェクト ACL をバケットから削除する例です。


using Google.Cloud.Storage.V1;
using System;
using System.Linq;

public class RemoveBucketDefaultOwnerSample
{
    public void RemoveBucketDefaultOwner(
        string bucketName = "your-unique-bucket-name",
        string userEmail = "user@iam.gserviceaccount.com")
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName, new GetBucketOptions { Projection = Projection.Full });
        if (bucket.DefaultObjectAcl == null)
        {
            Console.WriteLine("No default owner to remove");
        }
        else
        {
            bucket.DefaultObjectAcl = bucket.DefaultObjectAcl.Where(acl => !(acl.Entity == $"user-{userEmail}" && acl.Role == "OWNER")).ToList();
            var updatedBucket = storage.UpdateBucket(bucket);
            Console.WriteLine($"Removed user {userEmail} from bucket {bucketName}.");
        }
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、デフォルト オブジェクト ACL をバケットに追加する例です。

import (
	"context"
	"fmt"

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

// addBucketDefaultOwner adds default ACL to the specified bucket.
func addBucketDefaultOwner(bucket string, entity storage.ACLEntity) error {
	// bucket := "bucket-name"
	// entity := storage.AllUsers
	role := storage.RoleOwner

	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	acl := client.Bucket(bucket).DefaultObjectACL()
	if err := acl.Set(ctx, entity, role); err != nil {
		return fmt.Errorf("ACLHandle.Set: %w", err)
	}
	return nil
}

以下は、デフォルト オブジェクト ACL をバケットから削除する例です。

import (
	"context"
	"fmt"

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

// deleteDefaultBucketACL removes default ACL from a bucket.
func removeBucketDefaultOwner(bucket string, entity storage.ACLEntity) error {
	// bucket := "bucket-name"
	// entity := storage.AllUsers
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	acl := client.Bucket(bucket).DefaultObjectACL()
	if err := acl.Delete(ctx, entity); err != nil {
		return fmt.Errorf("ACLHandle.Delete: %w", err)
	}
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、デフォルト オブジェクト ACL をバケットに追加する例です。


import com.google.cloud.storage.Acl;
import com.google.cloud.storage.Acl.Role;
import com.google.cloud.storage.Acl.User;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class AddBucketDefaultOwner {

  public static void addBucketDefaultOwner(String bucketName, String userEmail) {

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

    // The email of the user you wish to add as a default owner
    // String userEmail = "someuser@domain.com"

    Storage storage = StorageOptions.newBuilder().build().getService();
    Bucket bucket = storage.get(bucketName);
    Acl newDefaultOwner = Acl.of(new User(userEmail), Role.OWNER);

    bucket.createDefaultAcl(newDefaultOwner);
    System.out.println("Added user " + userEmail + " as an owner on " + bucketName);
  }
}

以下は、デフォルト オブジェクト ACL をバケットから削除する例です。


import com.google.cloud.storage.Acl.User;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class RemoveBucketDefaultOwner {

  public static void removeBucketDefaultOwner(String bucketName, String userEmail) {

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

    // The email of the user you wish to remove as a default owner
    // String userEmail = "someuser@domain.com"

    Storage storage = StorageOptions.newBuilder().build().getService();
    Bucket bucket = storage.get(bucketName);
    User userToRemove = new User(userEmail);

    boolean success = bucket.deleteDefaultAcl(userToRemove);
    if (success) {
      System.out.println("Removed user " + userEmail + " as an owner on " + bucketName);
    } else {
      System.out.println("User " + userEmail + " was not found");
    }
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、デフォルト オブジェクト ACL をバケットに追加する例です。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The email address of the user to add
// const userEmail = 'user-email-to-add';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function addBucketDefaultOwner() {
  // Makes the user an owner in the default ACL of the bucket. You can use
  // addAllUsers(), addDomain(), addProject(), addGroup(), and
  // addAllAuthenticatedUsers() to grant access to different types of entities.
  // You can also use "readers" and "writers" to grant different roles.
  await storage.bucket(bucketName).acl.default.owners.addUser(userEmail);

  console.log(`Added user ${userEmail} as an owner on bucket ${bucketName}.`);
}

addBucketDefaultOwner().catch(console.error);

以下は、デフォルト オブジェクト ACL をバケットから削除する例です。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The email address of the user to remove
// const userEmail = 'user-email-to-remove';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function removeBucketDefaultOwner() {
  // Removes the user from the access control list of the bucket. You can use
  // deleteAllUsers(), deleteDomain(), deleteProject(), deleteGroup(), and
  // deleteAllAuthenticatedUsers() to remove access for different types of entities.
  await storage.bucket(bucketName).acl.default.owners.deleteUser(userEmail);

  console.log(`Removed user ${userEmail} from bucket ${bucketName}.`);
}

removeBucketDefaultOwner().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、デフォルト オブジェクト ACL をバケットに追加する例です。

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to a bucket's default ACL.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $entity The entity for which to update access controls.
 *        (e.g. 'user-example@domain.com')
 * @param string $role The permissions to add for the specified entity.
 *        (e.g. 'OWNER')
 */
function add_bucket_default_acl(string $bucketName, string $entity, string $role): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->defaultAcl();
    $acl->add($entity, $role);
    printf('Added %s (%s) to gs://%s default ACL' . PHP_EOL, $entity, $role, $bucketName);
}

以下は、デフォルト オブジェクト ACL をバケットから削除する例です。

use Google\Cloud\Storage\StorageClient;

/**
 * Delete an entity from a bucket's default ACL.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $entity The entity for which to update access controls.
 *        (e.g. 'user-example@domain.com')
 */
function delete_bucket_default_acl(string $bucketName, string $entity): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->defaultAcl();
    $acl->delete($entity);
    printf('Deleted %s from gs://%s default ACL' . PHP_EOL, $entity, $bucketName);
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、デフォルト オブジェクト ACL をバケットに追加する例です。

from google.cloud import storage


def add_bucket_default_owner(bucket_name, user_email):
    """Adds a user as an owner in the given bucket's default object access
    control list."""
    # bucket_name = "your-bucket-name"
    # user_email = "name@example.com"

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

    # Reload fetches the current ACL from Cloud Storage.
    bucket.acl.reload()

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # grant access to different types of entities. You can also use
    # `grant_read` or `grant_write` to grant different roles.
    bucket.default_object_acl.user(user_email).grant_owner()
    bucket.default_object_acl.save()

    print(
        "Added user {} as an owner in the default acl on bucket {}.".format(
            user_email, bucket_name
        )
    )

以下は、デフォルト オブジェクト ACL をバケットから削除する例です。

from google.cloud import storage


def remove_bucket_default_owner(bucket_name, user_email):
    """Removes a user from the access control list of the given bucket's
    default object access control list."""
    # bucket_name = "your-bucket-name"
    # user_email = "name@example.com"

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

    # Reload fetches the current ACL from Cloud Storage.
    bucket.acl.reload()

    # You can also use `group`, `domain`, `all_authenticated` and `all` to
    # remove access for different types of entities.
    bucket.default_object_acl.user(user_email).revoke_read()
    bucket.default_object_acl.user(user_email).revoke_write()
    bucket.default_object_acl.user(user_email).revoke_owner()
    bucket.default_object_acl.save()

    print(
        f"Removed user {user_email} from the default acl of bucket {bucket_name}."
    )

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、デフォルト オブジェクト ACL をバケットに追加する例です。

# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name

bucket.default_acl.add_owner email

puts "Added default OWNER permission for #{email} to #{bucket_name}"

以下は、デフォルト オブジェクト ACL をバケットから削除する例です。

# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name

bucket.default_acl.delete email

puts "Removed default ACL permissions for #{email} from #{bucket_name}"

REST API

JSON API

  1. GET リクエストを使ってデフォルト オブジェクト ACL を取得します。例:

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        https://storage.s3nsapis.fr/storage/v1/b/BUCKET_NAME?projection=full
    
  2. patch リクエストを使用して、デフォルト オブジェクト ACL を置き換えます。たとえば、次のリクエストでは、バケット example-travel-maps のデフォルト オブジェクト ACL が、defacls.json で指定した ACL に置き換えられます。

    curl -X PATCH --data @defacls.json -H "Content-Type: application/json" -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        https://storage.s3nsapis.fr/storage/v1/b/example-travel-maps
    

    以下に defacls.json の例を示します。

    {
    "defaultObjectAcl": [
      {
        "email": "example-service-account@example-project.s3ns.iam.gserviceaccount.com",
        "entity": "user-example-service-account@example-project.s3ns.iam.gserviceaccount.com",
        "role": "READER"
      }
    ]
    }
    

XML API

  1. GET リクエストを使用して、デフォルト オブジェクト ACL を取得します。リクエストのスコープはバケットと ?defaultObjectAcl パラメータです。次に例を示します。

    curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
        https://storage.s3nsapis.fr/BUCKET_NAME?defaultObjectAcl
    
  2. バケットをスコープに設定して PUT リクエストを使用します。?defaultObjectAcl パラメータを使用して、acls.xml に指定されている ACL に、デフォルト オブジェクト ACL を置き換えます。次に例を示します。

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

    以下に acls.xml の例を示します。

    <AccessControlList>
      <Entries>
        <Entry>
          <Permission>FULL_CONTROL</Permission>
          <Scope type="UserByEmail">
            <EmailAddress>example-service-account@example-project.s3ns.iam.gserviceaccount.com</EmailAddress>
          </Scope>
        </Entry>
      </Entries>
    </AccessControlList>
    

ACL の構文については、ACL の設定をご覧ください。定義済み ACL をデフォルト オブジェクト ACL として指定することもできます。

バケットのデフォルト オブジェクト ACL を定義済み ACL に設定するには:

コンソール

Cloud de Confiance コンソールでは、デフォルト オブジェクト ACL を設定することはできません。代わりに gcloud storage を使用してください。

コマンドライン

buckets update コマンドを使用し、--predefined-default-object-acl フラグを指定します。

gcloud storage buckets update gs://BUCKET_NAME --predefined-default-object-acl=PREDEFINED_ACL

ここで

  • BUCKET_NAME は、デフォルト オブジェクト ACL を変更するバケットの名前です。例: my-bucket

  • PREDEFINED_ACL は、有効な定義済み ACL の名前です。例: projectPrivate

REST API

JSON API

PUT リクエストと predefinedAcl パラメータを使用します。

次に例を示します。

curl -X PUT -H "Content-Length: 0" -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://storage.s3nsapis.fr/storage/v1/b/BUCKET_NAME?predefinedAcl=private

XML API

バケットをスコープに設定して ?defaultObjectAcl パラメータと x-goog-acl ヘッダーを設定し、PUT リクエストを使用します。

次に例を示します。

curl -X PUT -H "x-goog-acl: project-private" -H "Content-Length: 0" -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    http://storage.s3nsapis.fr/BUCKET_NAME?defaultObjectAcl

新しく作成したバケットのデフォルト オブジェクト ACL

次の例は、リクエストの一部として独自のデフォルト オブジェクト ACL を指定していない場合に、新しく作成したバケットに自動的に適用されるデフォルト オブジェクト ACL を示しています。バケットのデフォルト オブジェクト ACL が変更されたかどうかを確認するには、バケットの現在のデフォルト オブジェクト ACL を次の例と比較してください。

コンソール

Cloud de Confiance コンソールでは、デフォルト オブジェクト ACL を操作できません。代わりに gcloud storage を使用してください。

コマンドライン

次の例で、プロジェクト ID は "123412341234" です。実際のプロジェクト ID は違ったものになります。

defaultObjectAcl:
– entity: project-owners-123412341234
  etag: CAE=
  kind: storage#objectAccessControl
  projectTeam:
    projectNumber: '123412341234'
    team: owners
  role: OWNER
– entity: project-editors-123412341234
  etag: CAE=
  kind: storage#objectAccessControl
  projectTeam:
    projectNumber: '123412341234'
    team: editors
  role: OWNER
– entity: project-viewers-123412341234
  etag: CAE=
  kind: storage#objectAccessControl
  projectTeam:
    projectNumber: '123412341234'
    team: viewers
  role: READER

REST API

JSON API

次の例で、プロジェクト ID は "123412341234" です。実際のプロジェクト ID は違ったものになります。

"defaultObjectAcl": [
  {
    "kind": "storage#objectAccessControl",
    "entity": "project-owners-123412341234",
    "role": "OWNER",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "owners"
    }
  },
  {
    "kind": "storage#objectAccessControl",
    "entity": "project-editors-123412341234",
    "role": "OWNER",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "editors"
    }
  },
  {
    "kind": "storage#objectAccessControl",
    "entity": "project-viewers-123412341234",
    "role": "READER",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "viewers"
    }
  }
]

XML API

次の例で、プロジェクトの役割 ID は「00b4903a97...」で始まっています。実際のプロジェクト ID は違ったものになります。

<?xml version='1.0' encoding='UTF-8'?>
<AccessControlList>
  <Entries>
    <Entry>
      <Scope type='GroupById'>
        <ID>00b4903a9721...</ID>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type='GroupById'>
        <ID>00b4903a9722...</ID>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type='GroupById'>
        <ID>00b4903a9723...</ID>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
  </Entries>
</AccessControlList>

新たに作成したバケットのデフォルト オブジェクト ACL は定義済みの projectPrivate ACL と同等であるので注意してください。

ACL の取得

既存のリソースの ACL を取得するには:

コンソール

  1. Cloud de Confiance コンソールで Cloud Storage ブラウザに移動します。
    Cloud Storage ブラウザに移動

  2. ACL を表示する対象のオブジェクトに移動します。

  3. オブジェクトのプルダウン メニューから [アクセス権を編集] を選択します。

    権限ダイアログにオブジェクトの権限が表示されます。

失敗した Cloud Storage オペレーションの詳細なエラー情報を Cloud de Confiance コンソールで確認する方法については、トラブルシューティングをご覧ください。

コマンドライン

  1. オブジェクトの ACL を取得するには、--format フラグを指定して objects describe コマンドを使用します。

    gcloud storage objects describe gs://BUCKET_NAME/OBJECT_NAME --format="default(acl)"

    ここで

    • BUCKET_NAME は、ACL を表示するオブジェクトが含まれるバケットの名前です。例: my-bucket

    • OBJECT_NAME は、ACL を表示するオブジェクトの名前です。例: paris.jpg

クライアント ライブラリ

C++

詳細については、Cloud Storage C++ API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトの ACL を取得する例です。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name) {
  StatusOr<std::vector<gcs::ObjectAccessControl>> items =
      client.ListObjectAcl(bucket_name, object_name);

  if (!items) throw std::move(items).status();
  std::cout << "ACLs for object=" << object_name << " in bucket "
            << bucket_name << "\n";
  for (gcs::ObjectAccessControl const& acl : *items) {
    std::cout << acl.role() << ":" << acl.entity() << "\n";
  }
}

C#

詳細については、Cloud Storage C# API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトの ACL を取得する例です。


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

public class PrintFileAclSample
{
    public IEnumerable<ObjectAccessControl> PrintObjectAcl(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name")
    {
        var storage = StorageClient.Create();
        var storageObject = storage.GetObject(bucketName, objectName, new GetObjectOptions
        {
            Projection = Projection.Full
        });

        foreach (var acl in storageObject.Acl)
        {
            Console.WriteLine($"{acl.Role}:{acl.Entity}");
        }

        return storageObject.Acl;
    }
}

Go

詳細については、Cloud Storage Go API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトの ACL を取得する例です。

import (
	"context"
	"fmt"
	"io"

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

// printFileACL lists ACL of the specified object.
func printFileACL(w io.Writer, bucket, object string) error {
	// bucket := "bucket-name"
	// object := "object-name"
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	rules, err := client.Bucket(bucket).Object(object).ACL().List(ctx)
	if err != nil {
		return fmt.Errorf("ACLHandle.List: %w", err)
	}
	for _, rule := range rules {
		fmt.Fprintf(w, "ACL rule: %v\n", rule)
	}
	return nil
}

Java

詳細については、Cloud Storage Java API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトの ACL を取得する例です。


import com.google.cloud.storage.Acl;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.util.List;

public class PrintBlobAcl {

  public static void printBlobAcl(String bucketName, String blobName) {

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

    // The name of the blob/file that you wish to view Acls of
    // String blobName = "your-blob-name";

    Storage storage = StorageOptions.newBuilder().build().getService();
    Blob blob = storage.get(BlobId.of(bucketName, blobName));
    List<Acl> blobAcls = blob.getAcl();

    for (Acl acl : blobAcls) {

      // This will give you the role.
      // See https://cloud.google.com/storage/docs/access-control/lists#permissions
      String role = acl.getRole().name();

      // This will give you the Entity type (i.e. User, Group, Project etc.)
      // See https://cloud.google.com/storage/docs/access-control/lists#scopes
      String entityType = acl.getEntity().getType().name();

      System.out.printf("%s: %s %n", role, entityType);
    }
  }
}

Node.js

詳細については、Cloud Storage Node.js API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトの ACL を取得する例です。

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function printFileAcl() {
  // Gets the ACL for the file
  const [acls] = await storage.bucket(bucketName).file(fileName).acl.get();

  acls.forEach(acl => {
    console.log(`${acl.role}: ${acl.entity}`);
  });
}

printFileAcl().catch(console.error);

PHP

詳細については、Cloud Storage PHP API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトの ACL を取得する例です。

use Google\Cloud\Storage\StorageClient;

/**
 * Print all entities and roles for an object's ACL.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 */
function get_object_acl(string $bucketName, string $objectName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $acl = $object->acl();
    foreach ($acl->get() as $item) {
        printf('%s: %s' . PHP_EOL, $item['entity'], $item['role']);
    }
}

Python

詳細については、Cloud Storage Python API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトの ACL を取得する例です。

from google.cloud import storage


def print_blob_acl(bucket_name, blob_name):
    """Prints out a blob's access control list."""

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

    for entry in blob.acl:
        print(f"{entry['role']}: {entry['entity']}")

Ruby

詳細については、Cloud Storage Ruby API のリファレンス ドキュメントをご覧ください。

Cloud Storage に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

コードサンプルを実行する前に、GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境変数を s3nsapis.fr に設定します。

以下は、オブジェクトの ACL を取得する例です。

# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"
# file_name   = "Name of a file in the Storage bucket"
# email       = "Google Cloud Storage ACL Entity email"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name
file    = bucket.file file_name

puts "ACL for #{file_name} in #{bucket_name}:"

file.acl.owners.each do |owner|
  puts "OWNER #{owner}"
end

file.acl.readers.each do |reader|
  puts "READER #{reader}"
end

REST API

JSON API

  1. オブジェクトに対する OWNER 権限があることを確認します。

  2. GET リクエストを使用してオブジェクトの ACL を取得します。

    オブジェクトの ACL が JSON 形式で返され、レスポンスの本文に添付されます。

たとえば、バケット example-travel-maps 内のオブジェクト paris.jpg の ACL を返すには、次のように使用します。

curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://storage.s3nsapis.fr/storage/v1/b/example-travel-maps/o/paris.jpg?projection=full

次のようなレスポンスが表示されます。

{
  "kind": "storage#object",
  "id": "example-travel-maps/paris.jpg/1412805837131000",
  "selfLink": "https://www.s3nsapis.fr/storage/v1/b/example-travel-maps/o/paris.jpg",
  "name": "paris.jpg",
    "bucket": "example-travel-maps",
  ...
  "acl": [
    {
      ...
      "entity": "project-owners-867489160491",
      "role": "OWNER",
      "projectTeam": {
        "projectNumber": "867489160491",
        "team": "owners"
      },
      ...
    },
    {
      ...
      "entity": "user-example-service-account@example-project.s3ns.iam.gserviceaccount.com",
      "role": "OWNER",
      "email": "example-service-account@example-project.s3ns.iam.gserviceaccount.com",
      ...
    },
    {
      ...
      "entity": "group-gs-announce@googlegroups.com",
      "role": "READER",
      "email": "gs-announce@googlegroups.com",
      ...
    }
    ],
  "owner": {
    "entity": "user-example-service-account@example-project.s3ns.iam.gserviceaccount.com"
  },
  ...
}

objectAccessControls リソースの GET メソッドを使用してオブジェクトの ACL の個々のエントリを返すこともできます。

XML API

  1. バケットまたはオブジェクトに対する FULL_CONTROL 権限を持っていることを確認します。

  2. GET Object リクエストで acl クエリ文字列パラメータを使用して、バケットまたはオブジェクトの ACL を取得します。

ACL は XML で記述され、レスポンスの本文に添付されます。

たとえば、バケット example-travel-maps 内のオブジェクト paris.jpg の ACL を返すには、次のように使用します。

curl -X GET -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    https://storage.s3nsapis.fr/example-travel-maps/paris.jpg?acl

次のようなレスポンスが表示されます。

<?xml version="1.0" encoding="UTF-8"?>
<AccessControlList>
  <Owner>
    <ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
    <Name>Owner Name</Name>
  </Owner>
  <Entries>
    <Entry>
      <Scope type="UserById">
        <ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
        <Name>Name</Name>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="UserByEmail">
        <EmailAddress>example-service-account@example-project.s3ns.iam.gserviceaccount.com</EmailAddress>
        <Name>Jefferson</Name>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
  </Entries>
</AccessControlList>

また、ObjectAccessControls リソースの JSON GET メソッドを使用してオブジェクトの特定の ACL エントリを返すこともできます。

次のステップ