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

概要

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

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

ACL の設定

コンソール

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

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

  3. オブジェクトに関連付けられた [その他の操作] メニュー()から [アクセス権を編集] をクリックします。

    次のような権限ダイアログが表示されます。

    この ACL には次の 4 つのエントリが含まれています。

    • 最初のエントリは、特定のプロジェクト(プロジェクト番号が 867489140601 のプロジェクト)のすべてのオーナーに、このオブジェクトに対する「オーナー」アクセス権を付与します。
    • 2 番目のエントリは、特定のプロジェクト(プロジェクト番号が 867489140601 のプロジェクト)のすべての編集者にも、このオブジェクトに対する「オーナー」アクセス権を付与します。
    • 3 番目のエントリは、特定のプロジェクト(プロジェクト番号が 867489140601 のプロジェクト)のすべての閲覧者に、このオブジェクトに対する「読み取り」アクセス権を付与します。
    • 4 番目のエントリは、オブジェクトをアップロードしたユーザーに、オブジェクトに対する「オーナー」アクセス権を付与します。オブジェクトをアップロードしたユーザーは、常に「オーナー」として設定され、削除できません。
  4. [項目を追加] をクリックします。

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

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

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

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

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

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

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

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

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

gsutil

gsutil acl を使用して ACL を指定します。

  • 個々の権限を指定するには:

    gsutil acl ch -u USER_EMAIL:PERMISSION gs://BUCKET_NAME

  • ACL テンプレートを指定するには:

    gsutil acl set CANNED_ACL_NAME gs://BUCKET_NAME

  • JSON 形式で ACL を指定するには:

    gsutil acl set JSON_FILE gs://BUCKET_NAME

    ただし、JSON_FILE には、JSON 形式で指定された ACL が含まれます。

クライアント ライブラリ

C++

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

以下は、バケットに ACL を追加する例です。

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& entity) {
  StatusOr<gcs::BucketAccessControl> patched_acl =
      client.PatchBucketAcl(bucket_name, entity,
                            gcs::BucketAccessControlPatchBuilder().set_role(
                                gcs::BucketAccessControl::ROLE_OWNER()));
  if (!patched_acl) throw std::move(patched_acl).status();
  std::cout << "ACL entry for " << patched_acl->entity() << " 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::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";
}

C#

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

以下は、バケットに ACL を追加する例です。


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

public class AddBucketOwnerSample
{
    public Bucket AddBucketOwner(
        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.Acl ??= new List<BucketAccessControl>();

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

以下は、オブジェクトに 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;
    }
}

Go

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

以下は、バケットに ACL を追加する例です。

import (
	"context"
	"fmt"

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

// addBucketOwner adds ACL to the specified bucket.
func addBucketOwner(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: %v", err)
	}
	defer client.Close()

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

以下は、オブジェクトに 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: %v", 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: %v", err)
	}
	return nil
}

Java

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

以下は、バケットに 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 AddBucketOwner {

  public static void addBucketOwner(String projectId, String bucketName, String userEmail) {
    // 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 an owner
    // String userEmail = "someuser@domain.com"

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

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

以下は、オブジェクトに 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 AddFileOwner {

  public static void addFileOwner(
      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 file "
            + blobName
            + " in bucket "
            + bucketName);
  }
}

Node.js

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

以下は、バケットに 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 addBucketOwner() {
  // Makes the user an owner 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.owners.addUser(userEmail);

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

addBucketOwner().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 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);

PHP

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

以下は、バケットに ACL を追加する例です。

use Google\Cloud\Storage\StorageClient;

/**
 * Add an entity and role to a bucket's 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_acl(string $bucketName, string $entity, string $role): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->acl();
    $acl->add($entity, $role);
    printf('Added %s (%s) to gs://%s ACL' . PHP_EOL, $entity, $role, $bucketName);
}

以下は、オブジェクトに 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);
}

Python

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

以下は、バケットに ACL を追加する例です。

from google.cloud import storage

def add_bucket_owner(bucket_name, user_email):
    """Adds a user as an owner on the given bucket."""
    # 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.acl.user(user_email).grant_owner()
    bucket.acl.save()

    print(
        f"Added user {user_email} as an owner on bucket {bucket_name}."
    )

以下は、オブジェクトに 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
        )
    )

Ruby

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

以下は、バケットに 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.acl.add_owner email

puts "Added OWNER permission for #{email} to #{bucket_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.add_owner email

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

JSON API

バケットを作成するとき、insert リクエストに acl[] プロパティを指定できます。既存のバケットに対しては、patch リクエストまたは update リクエストに acl[] プロパティを指定します。

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

バケット ACL とオブジェクトの ACL プロパティの定義については、それぞれ BucketAccessControlsObjectAccessControls リソースをご覧ください。

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

"acl": [
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/project-owners-123412341234",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/project-owners-123412341234",
"bucket": "example-bucket",
"entity": "project-owners-123412341234",
"role": "OWNER",
"projectTeam": {
       "projectNumber": "123412341234",
       "team": "owners"
},
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/project-editors-123412341234",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/project-editors-123412341234",
"bucket": "example-bucket",
"entity": "project-editors-123412341234",
"role": "OWNER",
"projectTeam": {
     "projectNumber": "123412341234",
     "team": "editors"
},
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/project-viewers-123412341234",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/project-viewers-123412341234",
"bucket": "example-bucket",
"entity": "project-viewers-123412341234",
"role": "READER",
"projectTeam": {
     "projectNumber": "123412341234",
     "team": "viewers"
},
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/group-gs-announce@googlegroups.com",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/group-gs-announce@googlegroups.com",
"bucket": "example-bucket",
"entity": "group-gs-announce@googlegroups.com",
"role": "READER",
"email": "gs-announce@googlegroups.com",
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/user-jane@gmail.com",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/user-jane@gmail.com",
"bucket": "example-bucket",
"entity": "user-jane@gmail.com",
"role": "READER",
"email": "jane@gmail.com",
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/allUsers",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/allUsers",
"bucket": "example-bucket",
"entity": "allUsers",
"role": "READER",
"etag": "CDk="
},
{
"kind": "storage#bucketAccessControl",
"id": "example-bucket/allAuthenticatedUsers",
"selfLink": "https://www.googleapis.com/storage/v1/b/example-bucket/acl/allAuthenticatedUsers",
"bucket": "example-bucket",
"entity": "allAuthenticatedUsers",
"role": "READER",
"etag": "CDk="
}
]

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 を変更します。

XML API に次の ACL 構文を使用します。

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

Amazon Simple Storage Service™ および Amazon S3™ は、米国およびその他の国における Amazon.com, Inc. またはその関連会社の商標です。
ID バケット オーナーの Google Cloud Storage ID。
DisplayName 現在は実装されていません。この値は常に空の文字列です。
Entries ゼロ個以上の Entry 要素のコンテナ。
Entry Scope 要素と Permission 要素のコンテナ。Entry に含めるのは 1 つの Scope と 1 つの Permission 要素だけにする必要があります。
Scope ACL のスコープを定義する IDEmailAddressDomain 要素のコンテナ。この要素は次のいずれかの値を格納する type 属性を持っている必要があります。UserByIDUserByEmailGroupByIDGroupByEmailGroupByDomainAllUsersAllAuthenticatedUsers
ID 権限エントリが ID で指定される場合の、利用者の ID。
EmailAddress 権限エントリがメールで指定される場合の利用者のメール識別子。
Domain 権限エントリがメールで指定される場合の利用者のドメイン識別子。
Name 指定できるオプション要素、またはスコープが UserByEmail または GroupByEmail の場合に自動的に追加できるオプション要素。
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="GroupById">
        <ID>00b4903a9723...</ID>
      </Scope>
      <Permission>FULL_CONTROL</Permission>
    </Entry>
    <Entry>
      <Scope type="GroupById">
        <ID>00b4903a9724...</ID>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="GroupByDomain">
        <Domain>example.com</Domain>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="GroupByEmail">
        <EmailAddress>gs-announce@googlegroups.com</EmailAddress>
      </Scope>
      <Permission>READ</Permission>
    </Entry>
    <Entry>
      <Scope type="UserByEmail">
        <EmailAddress>jane@gmail.com</EmailAddress>
        <Name>jane</Name>
      </Scope>
      <Permission>READ</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>jane@gmail.com</EmailAddress>
      <Name>Jane</Name>
    </Scope>
    <Permission>FULL_CONTROL</Permission>
</Entry>

オプションであるこれらの <Name> 要素は、次の 2 つの状況下で追加されます。

  1. バケットまたはオブジェクトの ACL に要素として <Name> が含まれている場合

    ACL を設定するとき、ACL エントリに <Name> 要素を含めることができます。<Name> 要素にはいずれの値も指定できます。指定した値は、ACL が削除または置換されるまで Cloud Storage に保存されます。この方法は、Google Cloud Storage ID など、簡単に識別できない識別子を使用している場合に便利です。

  2. UserByEmail または GroupByEmail のスコープに Google 公開プロフィールが含まれている場合

    これらのスコープのどちらかを使用していて、<Name> 要素を指定していない場合、Cloud Storage は、メールアドレスに関連付けられているユーザーまたはメールの Google グループに、公開名を含む Google 公開プロフィールが設定されているかどうかをチェックします。Google 公開プロフィールが設定されている場合は、Cloud Storage によりその公開名が <Name> 要素に自動的に追加されます。

定義済み ACL を適用する

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

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

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

コンソール

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

gsutil

事前定義された ACL を適用するには、gsutil cp コマンドで -a オプションを使用します。

gsutil cp -a PREDEFINED_ACL OBJECT gs://BUCKET_NAME

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

gsutil cp -a bucket-owner-read paris.jpg gs://example-travel-maps

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 ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
"https://storage.googleapis.com/upload/storage/v1/b/example-travel-maps/o?name=paris.jpg&predefinedAcl=bucketOwnerRead"

リクエストは次の例のようになります。

POST /upload/storage/v1/b/example-travel-maps/o?name=paris.jpg&amppredefinedAcl=bucketOwnerRead HTTP/1.1
Host: www.googleapis.com
Content-Type: image/jpeg
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
Content-Length: 12345
Date: Fri, 10 Oct 2014 00:02:38 GMT

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 ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
https://storage.googleapis.com/example-travel-maps/paris.jpg

リクエストは次の例のようになります。

PUT /paris.jpg HTTP/1.1
Host: example-travel-maps.storage.googleapis.com
Date: Thu, 09 Oct 2014 23:06:08 GMT
Content-Length: 12345
Content-Type: image/jpg
x-goog-acl: bucket-owner-read
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
 
12345 bytes in entity body

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

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

コンソール

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

gsutil

事前定義された ACL を適用するには、gsutil acl set コマンドを使用します。

gsutil acl set PREDEFINED_ACL gs://BUCKET_NAME/OBJECT_NAME

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

gsutil acl set private gs://example-travel-maps/paris.jpg

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 ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
https://storage.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg?predefinedAcl=private

リクエストは次の例のようになります。

PATCH /storage/v1/b/example-travel-maps/o/paris.jpg?predefinedAcl=private HTTP/1.1
Host: www.googleapis.com
Content-Type: application/json
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
Content-Length: 11
Date: Fri, 10 Oct 2014 18:57:59 GMT

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 ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
-H "x-goog-acl: private" https://storage.googleapis.com/example-travel-maps/paris.jpg?acl

リクエストは次の例のようになります。

PUT /paris.jpg?acl HTTP/1.1
Host: example-travel-maps.storage.googleapis.com
Date: Thu, 09 Oct 2014 23:14:59 GMT
Content-Length: 0
x-goog-acl: private
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
 
empty entity body

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

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

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

コンソール

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

gsutil

  1. gsutil defacl を使用してデフォルト オブジェクト ACL を取得します。

    gsutil defacl get gs://BUCKET_NAME

  2. gsutil defacl ch または gsutil defacl set を使用してデフォルト オブジェクト ACL を変更します。

    たとえば、次のコマンドラインでは、jane@gmail.com がバケット example-travel-maps のデフォルト オブジェクト ACL に追加されます。

    gsutil defacl ch -u jane@gmail.com:READER gs://example-travel-maps

    デフォルト オブジェクト ACL をファイルから指定することもできます。詳細については、gsutil defacl のヘルプをご覧ください。

クライアント ライブラリ

C++

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

以下は、デフォルト オブジェクト 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 のリファレンス ドキュメントをご覧ください。

以下は、バケットのデフォルト オブジェクト 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 のリファレンス ドキュメントをご覧ください。

以下は、デフォルト オブジェクト 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: %v", err)
	}
	defer client.Close()

	acl := client.Bucket(bucket).DefaultObjectACL()
	if err := acl.Set(ctx, entity, role); err != nil {
		return fmt.Errorf("ACLHandle.Set: %v", 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: %v", err)
	}
	defer client.Close()

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

Java

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

以下は、デフォルト オブジェクト 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 のリファレンス ドキュメントをご覧ください。

以下は、デフォルト オブジェクト 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 のリファレンス ドキュメントをご覧ください。

以下は、デフォルト オブジェクト 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 のリファレンス ドキュメントをご覧ください。

以下は、デフォルト オブジェクト 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 のリファレンス ドキュメントをご覧ください。

以下は、デフォルト オブジェクト 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}"

JSON API

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

    curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" 
    https://storage.googleapis.com/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 OAUTH2_TOKEN" 
    https://storage.googleapis.com/storage/v1/b/example-travel-maps

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

    {
    "defaultObjectAcl": [
    {
    "email": "jane@gmail.com",
    "entity": "user-jane@gmail.com",
    "role": "READER"
    }
    ]
    }

XML API

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

    curl -X GET -H "Authorization: Bearer OAUTH2_TOKEN" 
    https://storage.googleapis.com/BUCKET_NAME?defaultObjectAcl

  2. バケットをスコープに設定して PUT リクエストを使用します。?defaultObjectAcl パラメータを使用して、acls.xml に指定されている ACL に、デフォルト オブジェクト ACL を置き換えます。例:

    curl -X PUT --data-binary @acls.xml -H "Authorization: Bearer OAUTH2_TOKEN" 
    http://storage.googleapis.com/BUCKET_NAME?defaultObjectAcl

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

    <AccessControlList>
    <Entries>
    <Entry>
    <Permission>FULL_CONTROL</Permission>
    <Scope type="GroupByEmail">
    <EmailAddress>travel-companions@googlegroups.com</EmailAddress>
    </Scope>
    </Entry>
    </Entries>
    </AccessControlList>

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

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

コンソール

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

gsutil

事前定義された ACL の名前を指定して、gsutil defacl コマンドを使用します。

たとえば、バケット example-travel-mapsproject-privateにデフォルト オブジェクト ACL を設定するには、次のコマンドを実行します。

gsutil defacl set project-private gs://example-travel-maps

JSON API

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

例:

curl -X PUT -H "Content-Length: 0" -H "Authorization: Bearer OAUTH2_TOKEN" 
https://storage.googleapis.com/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 OAUTH2_TOKEN" 
http://storage.googleapis.com/BUCKET_NAME?defaultObjectAcl

新たに作成されたバケットのデフォルト オブジェクト ACL

新たに作成されたバケットのデフォルト オブジェクト ACL を以下に示します。バケットのデフォルト オブジェクト ACL とこれらの ACL を比較して、バケット デフォルト オブジェクト ACL が変更されていないかを確認します。

コンソール

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

gsutil

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

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

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. Google Cloud コンソールで、Cloud Storage ブラウザに移動します。
    Cloud Storage ブラウザに移動

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

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

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

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

gsutil

gsutil acl get を使用してオブジェクトの ACL を返します。

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

gsutil acl get gs://example-travel-maps/paris.jpg

レスポンスの例:

[
{
    "entity": "project-owners-123412341234",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "owners"
    },
    "role": "OWNER"
},
{
    "entity": "project-editors-123412341234",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "editors"
    },
    "role": "OWNER"
},
{
    "entity": "project-viewers-123412341234",
    "projectTeam": {
      "projectNumber": "123412341234",
      "team": "viewers"
    },
    "role": "READER"
},
{
    "email": "gs-announce@googlegroups.com",
    "entity": "group-gs-announce@googlegroups.com",
    "role": "READER"
},
{
    "email": "jane@gmail.com",
    "entity": "user-jane@gmail.com",
    "role": "READER"
},
{
    "entity": "allUsers",
    "role": "READER"
},
{
    "entity": "allAuthenticatedUsers",
    "role": "READER"
}
]

バケットの ACL を返すには:

gsutil acl get gs://BUCKET_NAME

gsutil acl get を使って gsutil でバケットとオブジェクトの ACL を 返す場合、その形式は ACL 設定時に使用する JSON 形式と同じです。JSON 形式の ACL は entityrole などの JSON API プロパティ名を使用します。

出力の解釈方法や gsutil help acls の実行方法については、JSON API の構文を参照してください。

クライアント ライブラリ

C++

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

以下は、バケットの ACL を取得する例です。

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

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

以下は、オブジェクトの 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 のリファレンス ドキュメントをご覧ください。

以下は、バケットの ACL を取得する例です。


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

public class PrintBucketAclSample
{
    public IEnumerable<BucketAccessControl> PrintBucketAcl(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.Acl)
        {
            Console.WriteLine($"{acl.Role}:{acl.Entity}");
        }

        return bucket.Acl;
    }
}

以下は、オブジェクトの 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 のリファレンス ドキュメントをご覧ください。

以下は、バケットの ACL を取得する例です。

import (
	"context"
	"fmt"
	"io"

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

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

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

以下は、オブジェクトの 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: %v", err)
	}
	defer client.Close()

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

Java

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

以下は、バケットの ACL を取得する例です。


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

public class PrintBucketAcl {

  public static void printBucketAcl(String projectId, String bucketName) {
    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    Bucket bucket = storage.get(bucketName);
    List<Acl> bucketAcls = bucket.getAcl();

    for (Acl acl : bucketAcls) {

      // 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);
    }
  }
}

以下は、オブジェクトの 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 PrintFileAcl {

  public static void printFileAcl(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 のリファレンス ドキュメントをご覧ください。

以下は、バケットの ACL を取得する例です。

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

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

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

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

  acls.forEach(acl => {
    console.log(`${acl.role}: ${acl.entity}`);
  });
}
printBucketAcl().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';

// 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 のリファレンス ドキュメントをご覧ください。

以下は、バケットの ACL を取得する例です。

use Google\Cloud\Storage\StorageClient;

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

以下は、オブジェクトの 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 のリファレンス ドキュメントをご覧ください。

以下は、バケットの ACL を取得する例です。

from google.cloud import storage

def print_bucket_acl(bucket_name):
    """Prints out a bucket's access control list."""

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

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

以下は、オブジェクトの 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 のリファレンス ドキュメントをご覧ください。

以下は、バケットの ACL を取得する例です。

# The ID of your GCS bucket
# bucket_name = "your-unique-bucket-name"

require "google/cloud/storage"

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

puts "ACL for #{bucket_name}:"

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

bucket.acl.writers.each do |writer|
  puts "WRITER #{writer}"
end

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

以下は、オブジェクトの 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

JSON API

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

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

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

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

curl -X GET -H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" 
https://storage.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg?projection=full

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

{
"kind": "storage#object",
"id": "example-travel-maps/paris.jpg/1412805837131000",
"selfLink": "https://www.googleapis.com/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-jane@gmail.com",
"role": "OWNER",
"email": "jane@gmail.com",
...
},
{
...
"entity": "group-gs-announce@googlegroups.com",
"role": "READER",
"email": "gs-announce@googlegroups.com",
...
}
],
"owner": {
"entity": "user-jane@gmail.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 ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg" 
https://storage.googleapis.com/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>jane@gmail.com</EmailAddress>
    <Name>Jane</Name>
  </Scope>
  <Permission>FULL_CONTROL</Permission>
</Entry>
<Entry>
  <Scope type="GroupByEmail">
    <EmailAddress>gs-announce@googlegroups.com</EmailAddress>
  </Scope>
  <Permission>READ</Permission>
</Entry>
</Entries>
</AccessControlList>

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

ACL の変更

既存のオブジェクトまたはバケットの ACL を変更するには:

コンソール

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

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

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

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

次の例は、jane@gmail.com ユーザーにオブジェクト paris.jpg に対する OWNER 権限を付与し、gs-announce グループのメンバーに READER 権限を付与する方法を示しています。

オブジェクト paris.jpg に対する ACL の設定

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

gsutil

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

  2. ACL ファイルを gsutil acl set に渡し、ACL を設定するオブジェクトを指定します。

たとえば、ファイル acls.txt から、バケット example-travel-maps 内の paris.jpg という名前のオブジェクトに ACL を適用するには、次のようにします。

gsutil acl set acl.txt gs://example-travel-maps/paris.jpg

acl.txt の内容は次のとおりです:これらの ACL は、プロジェクト 867489160491 のオーナーとユーザー jane@gmail.com にオブジェクト paris.jpg に対する OWNER 権限を付与し、gs-announce グループのメンバーにこのオブジェクトに対する READER 権限を付与します。

[
{
"entity": "project-owners-867489160491",
"role": "OWNER",
"projectTeam": {
    "projectNumber": "867489160491",
    "team": "owners"
},
},
{
"entity": "user-jane@gmail.com",
"email": "jane@gmail.com",
"role": "OWNER"
},
{
"entity": "group-gs-announce@googlegroups.com",
"email": "gs-announce@googlegroups.com",
"role": "READER"
}
]

このオブジェクトに対し、個別の許可を使って同じ ACL を設定することもできます。 たとえば、jane@gmail.com ユーザーに READER アクセス権に付与するには、次のようにします

gsutil acl ch -u jane@gmail.com:READ gs://example-travel-maps/paris.jpg
.

クライアント ライブラリ

C++

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

以下は、ACL をバケットから削除する例です。

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

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

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

  gcs::BucketAccessControl owner = *it;
  google::cloud::Status status =
      client.DeleteBucketAcl(bucket_name, owner.entity());

  if (!status.ok()) throw std::runtime_error(status.message());
  std::cout << "Deleted ACL entry for " << owner.entity() << " in bucket "
            << bucket_name << "\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 のリファレンス ドキュメントをご覧ください。

以下は、ACL をバケットから削除する例です。


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

public class RemoveBucketOwnerSample
{
    public void RemoveBucketOwner(
        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 });
        if (bucket.Acl == null)
        {
            Console.WriteLine("No owner to remove");
        }
        else
        {
            bucket.Acl = bucket.Acl.Where(acl => !(acl.Entity == $"user-{userEmail}" && acl.Role == "OWNER")).ToList();
            var updatedBucket = storage.UpdateBucket(bucket);
            Console.WriteLine($"Removed user {userEmail} from bucket {bucketName}.");
        }
    }
}

以下は、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 のリファレンス ドキュメントをご覧ください。

以下は、ACL をバケットから削除する例です。

import (
	"context"
	"fmt"

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

// removeBucketOwner removes ACL from a bucket.
func removeBucketOwner(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: %v", err)
	}
	defer client.Close()

	acl := client.Bucket(bucket).ACL()
	if err := acl.Delete(ctx, entity); err != nil {
		return fmt.Errorf("ACLHandle.Delete: %v", 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: %v", err)
	}
	defer client.Close()

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

Java

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

以下は、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 RemoveBucketOwner {

  public static void removeBucketOwner(String projectId, String bucketName, String userEmail) {

    // 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 an owner
    // String userEmail = "someuser@domain.com"

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

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

以下は、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 RemoveFileOwner {

  public static void removeFileOwner(
      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 のリファレンス ドキュメントをご覧ください。

以下は、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 removeBucketOwner() {
  // 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.owners.deleteUser(userEmail);

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

removeBucketOwner().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 のリファレンス ドキュメントをご覧ください。

以下は、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_acl(string $bucketName, string $entity): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $acl = $bucket->acl();
    $acl->delete($entity);
    printf('Deleted %s from gs://%s ACL' . PHP_EOL, $entity, $bucketName);
}

以下は、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 のリファレンス ドキュメントをご覧ください。

以下は、ACL をバケットから削除する例です。

from google.cloud import storage

def remove_bucket_owner(bucket_name, user_email):
    """Removes a user from the access control list of the given bucket."""
    # 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.acl.user(user_email).revoke_read()
    bucket.acl.user(user_email).revoke_write()
    bucket.acl.user(user_email).revoke_owner()
    bucket.acl.save()

    print(f"Removed user {user_email} from bucket {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 のリファレンス ドキュメントをご覧ください。

以下は、ACL をバケットから削除する例です。

# project_id  = "Your Google Cloud project ID"
# 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.acl.delete email

puts "Removed ACL permissions for #{email} from #{bucket_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}"

JSON API

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

  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 ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
https://storage.googleapis.com/storage/v1/b/example-travel-maps/o/paris.jpg

ACL がプロジェクト 867489160491 のオーナーとユーザー jane@gmail.comOWNER 権限を付与し、gs-announce グループのメンバーに READER 権限を付与する場合、リクエストは次のようになります。

PATCH /storage/v1/b/example-travel-maps/o/paris.jpg HTTP/1.1
Host: www.googleapis.com
Content-Type: application/json
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
Content-Length: 597
Date: Wed, 08 Oct 2014 22:37:58 GMT
{
"acl": [
{
"entity": "project-owners-867489160491",
"role": "OWNER",
"projectTeam": {
    "projectNumber": "867489160491",
    "team": "owners"
},
{
"entity": "user-jane@gmail.com",
"role": "OWNER",
"email": "jane@gmail.com"
},
{
"entity": "group-gs-announce@googlegroups.com",
"role": "READER",
"email": "gs-announce@googlegroups.com"
}
]
}

XML API

  1. ACL を XML ドキュメント内に定義します。

  2. acl クエリ文字列パラメータと、それに対応する XML ドキュメントを使用して、PUT Object リクエストを送信します。

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

curl -X PUT --data-binary @acls.xml 
-H "Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg"
https://storage.googleapis.com/example-travel-maps/paris.jpg?acl

ACL が jane@gmail.com ユーザーに FULL_CONTROL 権限を付与し、gs-announce グループのメンバーに READ 権限を付与する場合、リクエストは次のようになります。

PUT /paris.jpg?acl HTTP/1.1
Host: example-travel-maps.storage.googleapis.com
Date: Sat, 20 Feb 2010 08:31:08 GMT
Content-Length: 589
Content-Type=application/xml
Authorization: Bearer ya29.AHES6ZRVmB7fkLtd1XTmq6mo0S1wqZZi3-Lh_s-6Uw7p8vtgSwg
 
<?xml version='1.0' encoding='utf-8'?>
<AccessControlList>
<Owner>
<ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
</Owner>
<Entries>
<Entry>
<Permission>FULL_CONTROL</Permission>
<Scope type="UserById">
  <ID>84fac329bceSAMPLE777d5d22b8SAMPLE77d85ac2SAMPLE2dfcf7c4adf34da46</ID>
</Scope>
</Entry>
<Entry>
<Scope type="UserByEmail">
  <EmailAddress>jane@gmail.com</EmailAddress>
  <Name>Jane</Name>
</Scope>
<Permission>FULL_CONTROL</Permission>
</Entry>
<Entry>
<Scope type="GroupByEmail">
  <EmailAddress>gs-announce@googlegroups.com</EmailAddress>
</Scope>
<Permission>READ</Permission>
</Entry>
</Entries>
</AccessControlList>

次のステップ