IAM を使用したアクセス制御

このドキュメントでは、Pub/Sub で使用可能なアクセス制御オプションについて説明します。

概要

Pub/Sub は、Identity and Access Management(IAM)を使用してアクセス制御を行います。

Pub/Sub では、アクセス制御をプロジェクト レベルと個々のリソースレベルで構成できます。次に例を示します。

  • Cloud プロジェクト全体ではなく、トピックごと、またはサブスクリプションごとにアクセス権を付与します。

    単一のトピックまたはサブスクリプションに対する表示専用アクセス権がある場合、Google Cloud コンソールを使用してそのトピックまたはサブスクリプションを表示することはできません。代わりに、Google Cloud CLI を使用できます。

  • 機能が限定されたアクセス権を付与します。たとえば、トピックにメッセージをパブリッシュするのみのアクセス権、サブスクリプションからのメッセージを使用するのみで、トピックやサブスクリプションを削除できないアクセス権などです。

  • プロジェクト内のすべての Pub/Sub リソースに対するアクセス権限を、デベロッパーのグループに付与します。

IAM とその機能の詳細については、IAM のドキュメントをご覧ください。特に、リソースへのアクセス権の付与、変更、取り消しをご覧ください。

各 Pub/Sub メソッドでは、必要な権限が必要となります。Pub/Sub IAM でサポートされる権限とロールのリストについては、次のロールセクションをご覧ください。

権限とロール

このセクションでは、Pub/Sub IAM でサポートされる権限とロールを簡単に説明します。

必要な権限

次の表に、各メソッドを呼び出すのに必要な権限を示します。

REST メソッド 必要な権限
projects.snapshots.create 含まれている Cloud プロジェクトに対する pubsub.snapshots.create 権限と、ソース サブスクリプションに対する pubsub.subscriptions.consume 権限。
projects.snapshots.delete リクエストされたスナップショットに対する pubsub.snapshots.delete
projects.snapshots.getIamPolicy リクエストされたスナップショットに対する pubsub.snapshots.getIamPolicy
projects.snapshots.list リクエストされた Cloud プロジェクトに対する pubsub.snapshots.list
projects.snapshots.patch リクエストされたスナップショットに対する pubsub.snapshots.update
projects.snapshots.setIamPolicy リクエストされたスナップショットに対する pubsub.snapshots.setIamPolicy
projects.snapshots.testIamPermissions なし
projects.subscriptions.acknowledge リクエストされたサブスクリプションに対する pubsub.subscriptions.consume
projects.subscriptions.create 含まれている Cloud プロジェクトに対する pubsub.subscriptions.create と、リクエストされたトピックに対する pubsub.topics.attachSubscription。プロジェクト A 内で、プロジェクト B のトピック T に対するサブスクリプションを作成するには、プロジェクト A とトピック T の両方に対する適切な権限が付与されている必要があります。この場合、ユーザー ID 情報はプロジェクト B の監査ログに記録できます。
projects.subscriptions.delete リクエストされたサブスクリプションに対する pubsub.subscriptions.delete
projects.subscriptions.get リクエストされたサブスクリプションに対する pubsub.subscriptions.get
projects.subscriptions.getIamPolicy リクエストされたサブスクリプションに対する pubsub.subscriptions.getIamPolicy
projects.subscriptions.list リクエストされた Cloud プロジェクトに対する pubsub.subscriptions.list
projects.subscriptions.modifyAckDeadline リクエストされたサブスクリプションに対する pubsub.subscriptions.consume
projects.subscriptions.modifyPushConfig リクエストされたサブスクリプションに対する pubsub.subscriptions.update
projects.subscriptions.patch リクエストされたサブスクリプションに対する pubsub.subscriptions.update
projects.subscriptions.pull リクエストされたサブスクリプションに対する pubsub.subscriptions.consume
projects.subscriptions.seek リクエストされたサブスクリプションに対する pubsub.subscriptions.consume と、リクエストされたスナップショット(存在する場合)に対する pubsub.snapshots.seek
projects.subscriptions.setIamPolicy リクエストされたサブスクリプションに対する pubsub.subscriptions.setIamPolicy
projects.subscriptions.testIamPermissions なし
projects.topics.create 含まれている Cloud プロジェクトに対する pubsub.topics.create
projects.topics.delete リクエストされたトピックに対する pubsub.topics.delete
projects.topics.detachSubscription リクエストされたトピックに対する pubsub.topics.detachSubscription
projects.topics.get リクエストされたトピックに対する pubsub.topics.get
projects.topics.getIamPolicy リクエストされたトピックに対する pubsub.topics.getIamPolicy
projects.topics.list リクエストされた Cloud プロジェクトに対する pubsub.topics.list
projects.topics.patch リクエストされたトピックに対する pubsub.topics.update
projects.topics.publish リクエストされたトピックに対する pubsub.topics.publish
projects.topics.setIamPolicy リクエストされたトピックに対する pubsub.topics.setIamPolicy
projects.topics.subscriptions.list リクエストされたトピックに対する pubsub.topics.get
projects.topics.testIamPermissions なし

ロール

次の表に、すべての Pub/Sub のロールと、各ロールに関連付けられている権限を示します。

Role Permissions

(roles/pubsub.admin)

Provides full access to topics and subscriptions.

Lowest-level resources where you can grant this role:

  • Schema
  • Snapshot
  • Subscription
  • Topic

pubsub.*

  • pubsub.schemas.attach
  • pubsub.schemas.commit
  • pubsub.schemas.create
  • pubsub.schemas.delete
  • pubsub.schemas.get
  • pubsub.schemas.getIamPolicy
  • pubsub.schemas.list
  • pubsub.schemas.listRevisions
  • pubsub.schemas.rollback
  • pubsub.schemas.setIamPolicy
  • pubsub.schemas.validate
  • pubsub.snapshots.create
  • pubsub.snapshots.delete
  • pubsub.snapshots.get
  • pubsub.snapshots.getIamPolicy
  • pubsub.snapshots.list
  • pubsub.snapshots.seek
  • pubsub.snapshots.setIamPolicy
  • pubsub.snapshots.update
  • pubsub.subscriptions.consume
  • pubsub.subscriptions.create
  • pubsub.subscriptions.delete
  • pubsub.subscriptions.get
  • pubsub.subscriptions.getIamPolicy
  • pubsub.subscriptions.list
  • pubsub.subscriptions.setIamPolicy
  • pubsub.subscriptions.update
  • pubsub.topics.attachSubscription
  • pubsub.topics.create
  • pubsub.topics.delete
  • pubsub.topics.detachSubscription
  • pubsub.topics.get
  • pubsub.topics.getIamPolicy
  • pubsub.topics.list
  • pubsub.topics.publish
  • pubsub.topics.setIamPolicy
  • pubsub.topics.update
  • pubsub.topics.updateTag

resourcemanager.projects.get

serviceusage.quotas.get

serviceusage.services.get

serviceusage.services.list

(roles/pubsub.editor)

Provides access to modify topics and subscriptions, and access to publish and consume messages.

Lowest-level resources where you can grant this role:

  • Schema
  • Snapshot
  • Subscription
  • Topic

pubsub.schemas.attach

pubsub.schemas.commit

pubsub.schemas.create

pubsub.schemas.delete

pubsub.schemas.get

pubsub.schemas.list

pubsub.schemas.listRevisions

pubsub.schemas.rollback

pubsub.schemas.validate

pubsub.snapshots.create

pubsub.snapshots.delete

pubsub.snapshots.get

pubsub.snapshots.list

pubsub.snapshots.seek

pubsub.snapshots.update

pubsub.subscriptions.consume

pubsub.subscriptions.create

pubsub.subscriptions.delete

pubsub.subscriptions.get

pubsub.subscriptions.list

pubsub.subscriptions.update

pubsub.topics.attachSubscription

pubsub.topics.create

pubsub.topics.delete

pubsub.topics.detachSubscription

pubsub.topics.get

pubsub.topics.list

pubsub.topics.publish

pubsub.topics.update

pubsub.topics.updateTag

resourcemanager.projects.get

serviceusage.quotas.get

serviceusage.services.get

serviceusage.services.list

(roles/pubsub.publisher)

Provides access to publish messages to a topic.

Lowest-level resources where you can grant this role:

  • Topic

pubsub.topics.publish

(roles/pubsub.subscriber)

Provides access to consume messages from a subscription and to attach subscriptions to a topic.

Lowest-level resources where you can grant this role:

  • Snapshot
  • Subscription
  • Topic

pubsub.snapshots.seek

pubsub.subscriptions.consume

pubsub.topics.attachSubscription

(roles/pubsub.viewer)

Provides access to view topics and subscriptions.

Lowest-level resources where you can grant this role:

  • Schema
  • Snapshot
  • Subscription
  • Topic

pubsub.schemas.get

pubsub.schemas.list

pubsub.schemas.listRevisions

pubsub.schemas.validate

pubsub.snapshots.get

pubsub.snapshots.list

pubsub.subscriptions.get

pubsub.subscriptions.list

pubsub.topics.get

pubsub.topics.list

resourcemanager.projects.get

serviceusage.quotas.get

serviceusage.services.get

serviceusage.services.list

Google Cloud コンソールによるアクセス制御

Google Cloud Console を使用して、トピックやプロジェクトのアクセス制御を管理できます。

プロジェクト レベルでアクセス制御を設定するには、次の手順に沿って操作します。

  1. Google Cloud コンソールの [IAM] ページに移動します。

    [IAM] に移動

  2. プロジェクトを選択します。

  3. [追加] をクリックします。

  4. 1 つ以上のプリンシパル名を入力します。

  5. [ロールを選択] リストで、付与するロールを選択します。

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

  7. 付与したロールにそのプリンシパルがリストされているかを確認します。

トピックとサブスクリプションに対するアクセス制御を設定するには、次の手順に沿って操作します。

  1. Google Cloud コンソールで、Pub/Sub の [トピック] リストに移動します。

    トピックに移動

  2. 必要に応じて、Pub/Sub が有効なプロジェクトを選択します。

  3. 次のいずれかの手順に沿って操作します。

    • 1 つ以上のトピックにロールを設定するには、トピックを選択します。

    • トピックに関連付けられたサブスクリプションのロールを設定するには、トピック ID をクリックします。[トピックの詳細] ページで、サブスクリプション ID をクリックします。[サブスクリプションの詳細] ページが表示されます。

  4. 情報パネルが表示されていない場合は、[情報パネルを表示] をクリックします。

  5. [権限] タブで、[ プリンシパルを追加] をクリックします。

  6. 1 つ以上のプリンシパル名を入力します。

  7. [ロールを選択] リストで、付与するロールを選択します。

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

IAM API によるアクセス制御

Pub/Sub IAM API を使用して、プロジェクト内の個々のトピックとサブスクリプションに対し、ポリシーを設定および取得して、所定のリソースに対するユーザーの権限をテストできます。通常の Pub/Sub メソッドと同様に、IAM API のメソッドはクライアント ライブラリや API Explorer を使用するか、または HTTP を介して直接呼び出すことができます。

Pub/Sub IAM API を使用して、Google Cloud プロジェクト レベルでポリシーを管理することはできません。

次のセクションでは、ポリシーの設定および取得方法、所定のリソースに対して呼び出し元がどの権限を持っているかをテストする方法について説明します。

ポリシーの取得

getIamPolicy()メソッドを使用すると、既存のポリシーを取得できます。このメソッドでは、リソースに関連付けられたポリシーを含む JSON オブジェクトが返されます。

サブスクリプションのポリシーを取得するするためのサンプルコードを以下に示します。

C#

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の C# の設定手順を実施してください。詳細については、Pub/Sub C# API のリファレンス ドキュメントをご覧ください。


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class GetSubscriptionIamPolicySample
{
    public Policy GetSubscriptionIamPolicy(string projectId, string subscriptionId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        Policy policy = publisher.IAMPolicyClient.GetIamPolicy(new GetIamPolicyRequest
        {
            ResourceAsResourceName = subscriptionName
        });
        return policy;
    }
}

gcloud

サブスクリプション ポリシーを取得します。

gcloud pubsub subscriptions get-iam-policy \
   projects/${PROJECT}/subscriptions/${SUBSCRIPTION} \
   --format json

出力:

   {
     "etag": "BwUjMhCsNvY=",
     "bindings": [
       {
         "role": "roles/pubsub.admin",
         "members": [
           "user:user-1@gmail.com"
         ]
       },
       {
         "role": "roles/pubsub.editor",
         "members": [
           "serviceAccount:service-account-2@appspot.gserviceaccount.com",
           "user:user-3@gmail.com"
       }
     ]
   }

Go

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Go の設定手順を実施してください。詳細については、Pub/Sub Go API のリファレンス ドキュメントをご覧ください。

import (
	"context"
	"fmt"
	"io"

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

func policy(w io.Writer, projectID, subID string) (*iam.Policy, error) {
	// projectID := "my-project-id"
	// subID := "my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	policy, err := client.Subscription(subID).IAM().Policy(ctx)
	if err != nil {
		return nil, fmt.Errorf("Subscription: %w", err)
	}
	for _, role := range policy.Roles() {
		fmt.Fprintf(w, "%q: %q\n", role, policy.Members(role))
	}
	return policy, nil
}

Java

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Java の設定手順を実施してください。詳細については、Pub/Sub Java API のリファレンス ドキュメントをご覧ください。


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.pubsub.v1.ProjectSubscriptionName;
import java.io.IOException;

public class GetSubscriptionPolicyExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";

    getSubscriptionPolicyExample(projectId, subscriptionId);
  }

  public static void getSubscriptionPolicyExample(String projectId, String subscriptionId)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      GetIamPolicyRequest getIamPolicyRequest =
          GetIamPolicyRequest.newBuilder().setResource(subscriptionName.toString()).build();
      Policy policy = subscriptionAdminClient.getIamPolicy(getIamPolicyRequest);
      System.out.println("Subscription policy: " + policy);
    }
  }
}

Node.js

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。詳細については、Pub/Sub Node.js API のリファレンス ドキュメントをご覧ください。

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function getSubscriptionPolicy(subscriptionNameOrId) {
  // Retrieves the IAM policy for the subscription
  const [policy] = await pubSubClient
    .subscription(subscriptionNameOrId)
    .iam.getPolicy();

  console.log(`Policy for subscription: ${JSON.stringify(policy.bindings)}.`);
}

Node.js

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。詳細については、Pub/Sub Node.js API のリファレンス ドキュメントをご覧ください。

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

// Imports the Google Cloud client library
import {PubSub, Policy} from '@google-cloud/pubsub';

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function getSubscriptionPolicy(subscriptionNameOrId: string) {
  // Retrieves the IAM policy for the subscription
  const [policy]: [Policy] = await pubSubClient
    .subscription(subscriptionNameOrId)
    .iam.getPolicy();

  console.log(`Policy for subscription: ${JSON.stringify(policy.bindings)}.`);
}

PHP

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の PHP の設定手順を実施してください。詳細については、Pub/Sub PHP API のリファレンス ドキュメントをご覧ください。

use Google\Cloud\PubSub\PubSubClient;

/**
 * Prints the policy for a PubSub subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 */
function get_subscription_policy($projectId, $subscriptionName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $subscription = $pubsub->subscription($subscriptionName);
    $policy = $subscription->iam()->policy();
    print_r($policy);
}

Python

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Python の設定手順を実施してください。詳細については、Pub/Sub Python API のリファレンス ドキュメントをご覧ください。

from google.cloud import pubsub_v1

# TODO(developer): Choose an existing subscription.
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

client = pubsub_v1.SubscriberClient()
subscription_path = client.subscription_path(project_id, subscription_id)

policy = client.get_iam_policy(request={"resource": subscription_path})

print("Policy for subscription {}:".format(subscription_path))
for binding in policy.bindings:
    print("Role: {}, Members: {}".format(binding.role, binding.members))

client.close()

Ruby

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Ruby の設定手順を実施してください。詳細については、Pub/Sub Ruby API のリファレンス ドキュメントをご覧ください。

# subscription_id = "your-subscription-id"

pubsub = Google::Cloud::Pubsub.new

subscription = pubsub.subscription subscription_id
policy       = subscription.policy

puts "Subscription policy:"
puts policy.roles
トピックのポリシーを取得するためのサンプルコードを以下に示します。

C#

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の C# の設定手順を実施してください。詳細については、Pub/Sub C# API のリファレンス ドキュメントをご覧ください。


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class GetTopicIamPolicySample
{
    public Policy GetTopicIamPolicy(string projectId, string topicId)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        Policy policy = publisher.IAMPolicyClient.GetIamPolicy(new GetIamPolicyRequest
        {
            ResourceAsResourceName = topicName
        });
        return policy;
    }
}

gcloud

トピックのポリシーを取得するには、次のコマンドを実行します。

gcloud pubsub topics get-iam-policy \
    projects/${PROJECT}/topics/${TOPIC} \
    --format json

出力:

{
  "etag": "BwUjMhCsNvY=",
  "bindings": [
    {
      "role":" roles/pubsub.viewer",
      "members": [
        "user:user-1@gmail.com"
      ]
    }
  ]
}

Go

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Go の設定手順を実施してください。詳細については、Pub/Sub Go API のリファレンス ドキュメントをご覧ください。

import (
	"context"
	"fmt"
	"io"

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

func policy(w io.Writer, projectID, topicID string) (*iam.Policy, error) {
	// projectID := "my-project-id"
	// topicID := "my-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	policy, err := client.Topic(topicID).IAM().Policy(ctx)
	if err != nil {
		return nil, fmt.Errorf("Policy: %w", err)
	}
	for _, role := range policy.Roles() {
		fmt.Fprint(w, policy.Members(role))
	}
	return policy, nil
}

Java

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Java の設定手順を実施してください。詳細については、Pub/Sub Java API のリファレンス ドキュメントをご覧ください。


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class GetTopicPolicyExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    getTopicPolicyExample(projectId, topicId);
  }

  public static void getTopicPolicyExample(String projectId, String topicId) throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      GetIamPolicyRequest getIamPolicyRequest =
          GetIamPolicyRequest.newBuilder().setResource(topicName.toString()).build();
      Policy policy = topicAdminClient.getIamPolicy(getIamPolicyRequest);
      System.out.println("Topic policy: " + policy);
    }
  }
}

Node.js

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。詳細については、Pub/Sub Node.js API のリファレンス ドキュメントをご覧ください。

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function getTopicPolicy(topicNameOrId) {
  // Retrieves the IAM policy for the topic
  const [policy] = await pubSubClient.topic(topicNameOrId).iam.getPolicy();
  console.log('Policy for topic: %j.', policy.bindings);
}

PHP

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の PHP の設定手順を実施してください。詳細については、Pub/Sub PHP API のリファレンス ドキュメントをご覧ください。

use Google\Cloud\PubSub\PubSubClient;

/**
 * Prints the policy for a Pub/Sub topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 */
function get_topic_policy($projectId, $topicName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $policy = $topic->iam()->policy();
    print_r($policy);
}

Python

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Python の設定手順を実施してください。詳細については、Pub/Sub Python API のリファレンス ドキュメントをご覧ください。

from google.cloud import pubsub_v1

# TODO(developer): Choose an existing topic.
# project_id = "your-project-id"
# topic_id = "your-topic-id"

client = pubsub_v1.PublisherClient()
topic_path = client.topic_path(project_id, topic_id)

policy = client.get_iam_policy(request={"resource": topic_path})

print("Policy for topic {}:".format(topic_path))
for binding in policy.bindings:
    print("Role: {}, Members: {}".format(binding.role, binding.members))

Ruby

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Ruby の設定手順を実施してください。詳細については、Pub/Sub Ruby API のリファレンス ドキュメントをご覧ください。

# topic_id = "your-topic-id"

pubsub = Google::Cloud::Pubsub.new

topic  = pubsub.topic topic_id
policy = topic.policy

puts "Topic policy:"
puts policy.roles

ポリシーの設定

setIamPolicy() メソッドを使用すると、ポリシーをリソースに接続できます。setIamPolicy() メソッドは SetIamPolicyRequest を受け取ります。ここには、設定されるポリシーと、ポリシーが接続されるリソースが含まれています。これにより、結果のポリシーが返されます。

サブスクリプションにポリシーを設定するためのサンプルコードを以下に示します。

C#

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の C# の設定手順を実施してください。詳細については、Pub/Sub C# API のリファレンス ドキュメントをご覧ください。


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class SetSubscriptionIamPolicySample
{
    public Policy SetSubscriptionIamPolicy(string projectId, string subscriptionId, string role, string member)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        string roleToBeAddedToPolicy = $"roles/{role}";

        Policy policy = new Policy
        {
            Bindings = {
                new Binding
                {
                    Role = roleToBeAddedToPolicy,
                    Members = { member }
                }
            }
        };
        SetIamPolicyRequest request = new SetIamPolicyRequest
        {
            ResourceAsResourceName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId),
            Policy = policy
        };
        Policy response = publisher.IAMPolicyClient.SetIamPolicy(request);
        return response;
    }
}

gcloud

1. サブスクリプションのポリシーを保存します。

gcloud pubsub subscriptions get-iam-policy \
   projects/${PROJECT}/subscriptions/${SUBSCRIPTION} \
   --format json > subscription_policy.json

2. subscription_policy.json を開き、適切なプリンシパルに適切なロールを与えてバインディングを更新します。subscription_policy.json ファイルの操作の詳細については、IAM ドキュメントのポリシーをご覧ください。

   {
     "etag": "BwUjMhCsNvY=",
     "bindings": [
       {
         "role": "roles/pubsub.admin",
         "members": [
           "user:user-1@gmail.com"
         ]
       },
       {
         "role": "roles/pubsub.editor",
         "members": [
           "serviceAccount:service-account-2@appspot.gserviceaccount.com"
       }
     ]
   }

3. 新しいサブスクリプション ポリシーを適用します。

gcloud pubsub subscriptions set-iam-policy \
  projects/${PROJECT}/subscriptions/${SUBSCRIPTION} \
  subscription_policy.json

Go

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Go の設定手順を実施してください。詳細については、Pub/Sub Go API のリファレンス ドキュメントをご覧ください。

import (
	"context"
	"fmt"

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

// addUsers adds all IAM users to a subscription.
func addUsers(projectID, subID string) error {
	// projectID := "my-project-id"
	// subID := "my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	sub := client.Subscription(subID)
	policy, err := sub.IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("err getting IAM Policy: %w", err)
	}
	// Other valid prefixes are "serviceAccount:", "user:"
	// See the documentation for more values.
	policy.Add(iam.AllUsers, iam.Viewer)
	policy.Add("group:cloud-logs@google.com", iam.Editor)
	if err := sub.IAM().SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("SetPolicy: %w", err)
	}
	// NOTE: It may be necessary to retry this operation if IAM policies are
	// being modified concurrently. SetPolicy will return an error if the policy
	// was modified since it was retrieved.
	return nil
}

Java

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Java の設定手順を実施してください。詳細については、Pub/Sub Java API のリファレンス ドキュメントをご覧ください。


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.pubsub.v1.ProjectSubscriptionName;
import java.io.IOException;

public class SetSubscriptionPolicyExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";

    setSubscriptionPolicyExample(projectId, subscriptionId);
  }

  public static void setSubscriptionPolicyExample(String projectId, String subscriptionId)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);
      GetIamPolicyRequest getIamPolicyRequest =
          GetIamPolicyRequest.newBuilder().setResource(subscriptionName.toString()).build();
      Policy oldPolicy = subscriptionAdminClient.getIamPolicy(getIamPolicyRequest);

      // Create new role -> members binding
      Binding binding =
          Binding.newBuilder()
              .setRole("roles/pubsub.editor")
              .addMembers("domain:google.com")
              .build();

      // Add new binding to updated policy
      Policy updatedPolicy = Policy.newBuilder(oldPolicy).addBindings(binding).build();

      SetIamPolicyRequest setIamPolicyRequest =
          SetIamPolicyRequest.newBuilder()
              .setResource(subscriptionName.toString())
              .setPolicy(updatedPolicy)
              .build();
      Policy newPolicy = subscriptionAdminClient.setIamPolicy(setIamPolicyRequest);
      System.out.println("New subscription policy: " + newPolicy);
    }
  }
}

Node.js

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。詳細については、Pub/Sub Node.js API のリファレンス ドキュメントをご覧ください。

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function setSubscriptionPolicy(subscriptionNameOrId) {
  // The new IAM policy
  const newPolicy = {
    bindings: [
      {
        // Add a group as editors
        role: 'roles/pubsub.editor',
        members: ['group:cloud-logs@google.com'],
      },
      {
        // Add all users as viewers
        role: 'roles/pubsub.viewer',
        members: ['allUsers'],
      },
    ],
  };

  // Updates the IAM policy for the subscription
  const [updatedPolicy] = await pubSubClient
    .subscription(subscriptionNameOrId)
    .iam.setPolicy(newPolicy);

  console.log('Updated policy for subscription: %j', updatedPolicy.bindings);
}

PHP

use Google\Cloud\PubSub\PubSubClient;

/**
 * Adds a user to the policy for a Pub/Sub subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 * @param string $userEmail  The user email to add to the policy.
 */
function set_subscription_policy($projectId, $subscriptionName, $userEmail)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $subscription = $pubsub->subscription($subscriptionName);
    $policy = $subscription->iam()->policy();
    $policy['bindings'][] = [
        'role' => 'roles/pubsub.subscriber',
        'members' => ['user:' . $userEmail]
    ];
    $subscription->iam()->setPolicy($policy);

    printf(
        'User %s added to policy for %s' . PHP_EOL,
        $userEmail,
        $subscriptionName
    );
}

Python

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Python の設定手順を実施してください。詳細については、Pub/Sub Python API のリファレンス ドキュメントをご覧ください。

from google.cloud import pubsub_v1

# TODO(developer): Choose an existing subscription.
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

client = pubsub_v1.SubscriberClient()
subscription_path = client.subscription_path(project_id, subscription_id)

policy = client.get_iam_policy(request={"resource": subscription_path})

# Add all users as viewers.
policy.bindings.add(role="roles/pubsub.viewer", members=["domain:google.com"])

# Add a group as an editor.
policy.bindings.add(role="roles/editor", members=["group:cloud-logs@google.com"])

# Set the policy
policy = client.set_iam_policy(
    request={"resource": subscription_path, "policy": policy}
)

print("IAM policy for subscription {} set: {}".format(subscription_id, policy))

client.close()

Ruby

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Ruby の設定手順を実施してください。詳細については、Pub/Sub Ruby API のリファレンス ドキュメントをご覧ください。

# subscription_id       = "your-subscription-id"
# role                  = "roles/pubsub.publisher"
# service_account_email = "serviceAccount:account_name@project_name.iam.gserviceaccount.com"

pubsub = Google::Cloud::Pubsub.new

subscription = pubsub.subscription subscription_id
subscription.policy do |policy|
  policy.add role, service_account_email
end

トピックにポリシーを設定するためのサンプルコードを以下に示します。

C#

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の C# の設定手順を実施してください。詳細については、Pub/Sub C# API のリファレンス ドキュメントをご覧ください。


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class SetTopicIamPolicySample
{
    public Policy SetTopicIamPolicy(string projectId, string topicId, string role, string member)
    {
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        string roleToBeAddedToPolicy = $"roles/{role}";

        Policy policy = new Policy
        {
            Bindings = {
                new Binding
                {
                    Role = roleToBeAddedToPolicy,
                    Members = { member }
                }
            }
        };
        SetIamPolicyRequest request = new SetIamPolicyRequest
        {
            ResourceAsResourceName = TopicName.FromProjectTopic(projectId, topicId),
            Policy = policy
        };
        Policy response = publisher.IAMPolicyClient.SetIamPolicy(request);
        return response;
    }
}

gcloud

1. トピックのポリシーを保存します。

gcloud pubsub topics get-iam-policy \
   projects/${PROJECT}/topics/${TOPIC} \
   --format json > topic_policy.json

2. topic_policy.json を開き、適切なプリンシパルに適切なロールを与えてバインディングを更新します。subscription_policy.json ファイルの操作の詳細については、IAM ドキュメントのポリシーをご覧ください。

   {
     "etag": "BwUjMhCsNvY=",
     "bindings": [
       {
         "role": "roles/pubsub.editor",
         "members": [
           "user:user-1@gmail.com",
           "user:user-2@gmail.com"
         ]
       }
     ]
   }

3. 新しいトピックのポリシーを適用します。

gcloud pubsub topics set-iam-policy  \
   projects/${PROJECT}/topics/${TOPIC}     \
   topic_policy.json

Go

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Go の設定手順を実施してください。詳細については、Pub/Sub Go API のリファレンス ドキュメントをご覧ください。

import (
	"context"
	"fmt"

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

func addUsers(projectID, topicID string) error {
	// projectID := "my-project-id"
	// topicID := "my-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("pubsub.NewClient: %w", err)
	}
	defer client.Close()

	topic := client.Topic(topicID)
	policy, err := topic.IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("Policy: %w", err)
	}
	// Other valid prefixes are "serviceAccount:", "user:"
	// See the documentation for more values.
	policy.Add(iam.AllUsers, iam.Viewer)
	policy.Add("group:cloud-logs@google.com", iam.Editor)
	if err := topic.IAM().SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("SetPolicy: %w", err)
	}
	// NOTE: It may be necessary to retry this operation if IAM policies are
	// being modified concurrently. SetPolicy will return an error if the policy
	// was modified since it was retrieved.
	return nil
}

Java

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Java の設定手順を実施してください。詳細については、Pub/Sub Java API のリファレンス ドキュメントをご覧ください。


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.pubsub.v1.TopicName;
import java.io.IOException;

public class SetTopicPolicyExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    setTopicPolicyExample(projectId, topicId);
  }

  public static void setTopicPolicyExample(String projectId, String topicId) throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      TopicName topicName = TopicName.of(projectId, topicId);
      GetIamPolicyRequest getIamPolicyRequest =
          GetIamPolicyRequest.newBuilder().setResource(topicName.toString()).build();
      Policy oldPolicy = topicAdminClient.getIamPolicy(getIamPolicyRequest);

      // Create new role -> members binding
      Binding binding =
          Binding.newBuilder()
              .setRole("roles/pubsub.editor")
              .addMembers("domain:google.com")
              .build();

      // Add new binding to updated policy
      Policy updatedPolicy = Policy.newBuilder(oldPolicy).addBindings(binding).build();

      SetIamPolicyRequest setIamPolicyRequest =
          SetIamPolicyRequest.newBuilder()
              .setResource(topicName.toString())
              .setPolicy(updatedPolicy)
              .build();
      Policy newPolicy = topicAdminClient.setIamPolicy(setIamPolicyRequest);
      System.out.println("New topic policy: " + newPolicy);
    }
  }
}

Node.js

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。詳細については、Pub/Sub Node.js API のリファレンス ドキュメントをご覧ください。

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function setTopicPolicy(topicNameOrId) {
  // The new IAM policy
  const newPolicy = {
    bindings: [
      {
        // Add a group as editors
        role: 'roles/pubsub.editor',
        members: ['group:cloud-logs@google.com'],
      },
      {
        // Add all users as viewers
        role: 'roles/pubsub.viewer',
        members: ['allUsers'],
      },
    ],
  };

  // Updates the IAM policy for the topic
  const [updatedPolicy] = await pubSubClient
    .topic(topicNameOrId)
    .iam.setPolicy(newPolicy);
  console.log('Updated policy for topic: %j', updatedPolicy.bindings);
}

PHP

use Google\Cloud\PubSub\PubSubClient;

/**
 * Adds a user to the policy for a Pub/Sub topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 * @param string $userEmail  The user email to add to the policy.
 */
function set_topic_policy($projectId, $topicName, $userEmail)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $policy = $topic->iam()->policy();
    $policy['bindings'][] = [
        'role' => 'roles/pubsub.publisher',
        'members' => ['user:' . $userEmail]
    ];
    $topic->iam()->setPolicy($policy);

    printf(
        'User %s added to policy for %s' . PHP_EOL,
        $userEmail,
        $topicName
    );
}

Python

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Python の設定手順を実施してください。詳細については、Pub/Sub Python API のリファレンス ドキュメントをご覧ください。

from google.cloud import pubsub_v1

# TODO(developer): Choose an existing topic.
# project_id = "your-project-id"
# topic_id = "your-topic-id"

client = pubsub_v1.PublisherClient()
topic_path = client.topic_path(project_id, topic_id)

policy = client.get_iam_policy(request={"resource": topic_path})

# Add all users as viewers.
policy.bindings.add(role="roles/pubsub.viewer", members=["domain:google.com"])

# Add a group as a publisher.
policy.bindings.add(
    role="roles/pubsub.publisher", members=["group:cloud-logs@google.com"]
)

# Set the policy
policy = client.set_iam_policy(request={"resource": topic_path, "policy": policy})

print("IAM policy for topic {} set: {}".format(topic_id, policy))

Ruby

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Ruby の設定手順を実施してください。詳細については、Pub/Sub Ruby API のリファレンス ドキュメントをご覧ください。

# topic_id              = "your-topic-id"
# role                  = "roles/pubsub.publisher"
# service_account_email = "serviceAccount:account_name@project_name.iam.gserviceaccount.com"

pubsub = Google::Cloud::Pubsub.new

topic = pubsub.topic topic_id
topic.policy do |policy|
  policy.add role, service_account_email
end

権限のテスト

testIamPermissions() メソッドを使用して、特定の権限を追加または削除できます。これはパラメータとしてリソース名と一連の権限を取得し、権限のサブセットを返します。

サブスクリプションに対する権限をテストするためのサンプルコードを以下に示します。

C#

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の C# の設定手順を実施してください。詳細については、Pub/Sub C# API のリファレンス ドキュメントをご覧ください。


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class TestSubscriptionIamPermissionsSample
{
    public TestIamPermissionsResponse TestSubscriptionIamPermissionsResponse(string projectId, string subscriptionId)
    {
        TestIamPermissionsRequest request = new TestIamPermissionsRequest
        {
            ResourceAsResourceName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId),
            Permissions = { "pubsub.subscriptions.get", "pubsub.subscriptions.update" }
        };
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        TestIamPermissionsResponse response = publisher.IAMPolicyClient.TestIamPermissions(request);
        return response;
    }
}

gcloud

gcloud iam list-testable-permissions \
   https://pubsub.googleapis.com/v1/projects/${PROJECT}/subscriptions/${SUBSCRIPTION} \
   --format json

出力:

 [
    {
     "name": "pubsub.subscriptions.consume",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.delete",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.get",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.getIamPolicy",
     "stage": "GA"
    },
   {
     "name": "pubsub.subscriptions.setIamPolicy",
     "stage": "GA"
   },
   {
     "name": "pubsub.subscriptions.update",
     "stage": "GA"
   }
 ]

Go

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Go の設定手順を実施してください。詳細については、Pub/Sub Go API のリファレンス ドキュメントをご覧ください。

import (
	"context"
	"fmt"
	"io"

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

func testPermissions(w io.Writer, projectID, subID string) ([]string, error) {
	// projectID := "my-project-id"
	// subID := "my-sub"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %w", err)
	}

	sub := client.Subscription(subID)
	perms, err := sub.IAM().TestPermissions(ctx, []string{
		"pubsub.subscriptions.consume",
		"pubsub.subscriptions.update",
	})
	if err != nil {
		return nil, fmt.Errorf("TestPermissions: %w", err)
	}
	for _, perm := range perms {
		fmt.Fprintf(w, "Allowed: %v\n", perm)
	}

Java

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Java の設定手順を実施してください。詳細については、Pub/Sub Java API のリファレンス ドキュメントをご覧ください。


import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.pubsub.v1.ProjectSubscriptionName;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class TestSubscriptionPermissionsExample {
  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String subscriptionId = "your-subscription-id";

    testSubscriptionPermissionsExample(projectId, subscriptionId);
  }

  public static void testSubscriptionPermissionsExample(String projectId, String subscriptionId)
      throws IOException {
    try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
      ProjectSubscriptionName subscriptionName =
          ProjectSubscriptionName.of(projectId, subscriptionId);

      List<String> permissions = new LinkedList<>();
      permissions.add("pubsub.subscriptions.consume");
      permissions.add("pubsub.subscriptions.update");

      TestIamPermissionsRequest testIamPermissionsRequest =
          TestIamPermissionsRequest.newBuilder()
              .setResource(subscriptionName.toString())
              .addAllPermissions(permissions)
              .build();

      TestIamPermissionsResponse testedPermissionsResponse =
          subscriptionAdminClient.testIamPermissions(testIamPermissionsRequest);

      System.out.println("Tested:\n" + testedPermissionsResponse);
    }
  }
}

Node.js

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。詳細については、Pub/Sub Node.js API のリファレンス ドキュメントをご覧ください。

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const subscriptionNameOrId = 'YOUR_SUBSCRIPTION_NAME_OR_ID';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function testSubscriptionPermissions(subscriptionNameOrId) {
  const permissionsToTest = [
    'pubsub.subscriptions.consume',
    'pubsub.subscriptions.update',
  ];

  // Tests the IAM policy for the specified subscription
  const [permissions] = await pubSubClient
    .subscription(subscriptionNameOrId)
    .iam.testPermissions(permissionsToTest);

  console.log('Tested permissions for subscription: %j', permissions);
}

PHP

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の PHP の設定手順を実施してください。詳細については、Pub/Sub PHP API のリファレンス ドキュメントをご覧ください。

use Google\Cloud\PubSub\PubSubClient;

/**
 * Prints the permissions of a subscription.
 *
 * @param string $projectId  The Google project ID.
 * @param string $subscriptionName  The Pub/Sub subscription name.
 */
function test_subscription_permissions($projectId, $subscriptionName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $subscription = $pubsub->subscription($subscriptionName);
    $permissions = $subscription->iam()->testPermissions([
        'pubsub.subscriptions.consume',
        'pubsub.subscriptions.update'
    ]);
    foreach ($permissions as $permission) {
        printf('Permission: %s' . PHP_EOL, $permission);
    }
}

Python

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Python の設定手順を実施してください。詳細については、Pub/Sub Python API のリファレンス ドキュメントをご覧ください。

from google.cloud import pubsub_v1

# TODO(developer): Choose an existing subscription.
# project_id = "your-project-id"
# subscription_id = "your-subscription-id"

client = pubsub_v1.SubscriberClient()
subscription_path = client.subscription_path(project_id, subscription_id)

permissions_to_check = [
    "pubsub.subscriptions.consume",
    "pubsub.subscriptions.update",
]

allowed_permissions = client.test_iam_permissions(
    request={"resource": subscription_path, "permissions": permissions_to_check}
)

print(
    "Allowed permissions for subscription {}: {}".format(
        subscription_path, allowed_permissions
    )
)

client.close()

Ruby

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Ruby の設定手順を実施してください。詳細については、Pub/Sub Ruby API のリファレンス ドキュメントをご覧ください。

# subscription_id = "your-subscription-id"

pubsub = Google::Cloud::Pubsub.new

subscription = pubsub.subscription subscription_id
permissions  = subscription.test_permissions "pubsub.subscriptions.consume",
                                             "pubsub.subscriptions.update"

puts "Permission to consume" if permissions.include? "pubsub.subscriptions.consume"
puts "Permission to update" if permissions.include? "pubsub.subscriptions.update"

トピックに対する権限をテストするためのサンプルコードを以下に示します。

C#

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の C# の設定手順を実施してください。詳細については、Pub/Sub C# API のリファレンス ドキュメントをご覧ください。


using Google.Cloud.Iam.V1;
using Google.Cloud.PubSub.V1;

public class TestTopicIamPermissionsSample
{
    public TestIamPermissionsResponse TestTopicIamPermissions(string projectId, string topicId)
    {
        TestIamPermissionsRequest request = new TestIamPermissionsRequest
        {
            ResourceAsResourceName = TopicName.FromProjectTopic(projectId, topicId),
            Permissions = { "pubsub.topics.get", "pubsub.topics.update" }
        };
        PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
        TestIamPermissionsResponse response = publisher.IAMPolicyClient.TestIamPermissions(request);
        return response;
    }
}

gcloud

gcloud iam list-testable-permissions \
   https://pubsub.googleapis.com/v1/projects/${PROJECT}/topics/${TOPIC} \
   --format json

出力

 [
   {
     "name": "pubsub.topics.attachSubscription",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.delete",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.detachSubscription",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.get",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.getIamPolicy",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.publish",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.setIamPolicy",
     "stage": "GA"
   },
   {
     "name": "pubsub.topics.update",
     "stage": "GA"
   }
 ]

Go

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Go の設定手順を実施してください。詳細については、Pub/Sub Go API のリファレンス ドキュメントをご覧ください。

import (
	"context"
	"fmt"
	"io"

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

func testPermissions(w io.Writer, projectID, topicID string) ([]string, error) {
	// projectID := "my-project-id"
	// topicID := "my-topic"
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, projectID)
	if err != nil {
		return nil, fmt.Errorf("pubsub.NewClient: %w", err)
	}

	topic := client.Topic(topicID)
	perms, err := topic.IAM().TestPermissions(ctx, []string{
		"pubsub.topics.publish",
		"pubsub.topics.update",
	})
	if err != nil {
		return nil, fmt.Errorf("TestPermissions: %w", err)
	}
	for _, perm := range perms {
		fmt.Fprintf(w, "Allowed: %v\n", perm)
	}
	return perms, nil
}

Java

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Java の設定手順を実施してください。詳細については、Pub/Sub Java API のリファレンス ドキュメントをご覧ください。


import com.google.cloud.pubsub.v1.TopicAdminClient;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.pubsub.v1.ProjectTopicName;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class TestTopicPermissionsExample {

  public static void main(String... args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String topicId = "your-topic-id";

    testTopicPermissionsExample(projectId, topicId);
  }

  public static void testTopicPermissionsExample(String projectId, String topicId)
      throws IOException {
    try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
      ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);

      List<String> permissions = new LinkedList<>();
      permissions.add("pubsub.topics.attachSubscription");
      permissions.add("pubsub.topics.publish");
      permissions.add("pubsub.topics.update");

      TestIamPermissionsRequest testIamPermissionsRequest =
          TestIamPermissionsRequest.newBuilder()
              .setResource(topicName.toString())
              .addAllPermissions(permissions)
              .build();

      TestIamPermissionsResponse testedPermissionsResponse =
          topicAdminClient.testIamPermissions(testIamPermissionsRequest);

      System.out.println("Tested:\n" + testedPermissionsResponse);
    }
  }
}

Node.js

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Node.js の設定手順を実施してください。詳細については、Pub/Sub Node.js API のリファレンス ドキュメントをご覧ください。

/**
 * TODO(developer): Uncomment this variable before running the sample.
 */
// const topicNameOrId = 'YOUR_TOPIC_NAME_OR_ID';

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

// Creates a client; cache this for further use
const pubSubClient = new PubSub();

async function testTopicPermissions(topicNameOrId) {
  const permissionsToTest = [
    'pubsub.topics.attachSubscription',
    'pubsub.topics.publish',
    'pubsub.topics.update',
  ];

  // Tests the IAM policy for the specified topic
  const [permissions] = await pubSubClient
    .topic(topicNameOrId)
    .iam.testPermissions(permissionsToTest);

  console.log('Tested permissions for topic: %j', permissions);
}

PHP

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の PHP の設定手順を実施してください。詳細については、Pub/Sub PHP API のリファレンス ドキュメントをご覧ください。

use Google\Cloud\PubSub\PubSubClient;

/**
 * Prints the permissions of a topic.
 *
 * @param string $projectId  The Google project ID.
 * @param string $topicName  The Pub/Sub topic name.
 */
function test_topic_permissions($projectId, $topicName)
{
    $pubsub = new PubSubClient([
        'projectId' => $projectId,
    ]);
    $topic = $pubsub->topic($topicName);
    $permissions = $topic->iam()->testPermissions([
        'pubsub.topics.attachSubscription',
        'pubsub.topics.publish',
        'pubsub.topics.update'
    ]);
    foreach ($permissions as $permission) {
        printf('Permission: %s' . PHP_EOL, $permission);
    }
}

Python

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Python の設定手順を実施してください。詳細については、Pub/Sub Python API のリファレンス ドキュメントをご覧ください。

from google.cloud import pubsub_v1

# TODO(developer): Choose an existing topic.
# project_id = "your-project-id"
# topic_id = "your-topic-id"

client = pubsub_v1.PublisherClient()
topic_path = client.topic_path(project_id, topic_id)

permissions_to_check = ["pubsub.topics.publish", "pubsub.topics.update"]

allowed_permissions = client.test_iam_permissions(
    request={"resource": topic_path, "permissions": permissions_to_check}
)

print(
    "Allowed permissions for topic {}: {}".format(topic_path, allowed_permissions)
)

Ruby

このサンプルを試す前に、クイックスタート: クライアント ライブラリの使用の Ruby の設定手順を実施してください。詳細については、Pub/Sub Ruby API のリファレンス ドキュメントをご覧ください。

# topic_id = "your-topic-id"

pubsub = Google::Cloud::Pubsub.new

topic       = pubsub.topic topic_id
permissions = topic.test_permissions "pubsub.topics.attachSubscription",
                                     "pubsub.topics.publish", "pubsub.topics.update"

puts "Permission to attach subscription" if permissions.include? "pubsub.topics.attachSubscription"
puts "Permission to publish" if permissions.include? "pubsub.topics.publish"
puts "Permission to update" if permissions.include? "pubsub.topics.update"

サンプル ユースケース: プロジェクト間通信

Pub/Sub IAM は、プロジェクト間の通信でアクセス権を適切に調整するのに便利です。

Cloud Project A のサービス アカウントで Cloud Project B のトピックにメッセージをパブリッシュする必要があるとします。まず、Project A で Pub/Sub API を有効にします。

次に、Cloud Project B でサービス アカウントに編集権限を付与します。ただし、このアプローチでは大まかすぎることがよくあります。IAM API を使用すれば、アクセスレベルをより詳細に調整できます。

プロジェクト間の通信

たとえば、次のスニペットでは、project-bsetIamPolicy() メソッドと用意されている topic_policy.json ファイを使用して、トピック projects/project-b/topics/topic-b でのパブリッシャーのロールを project-a のサービス アカウント foobar@project-a.iam.gserviceaccount.com に付与します。

gcloud pubsub topics set-iam-policy \
    projects/project-b/topics/topic-b \
    topic_policy.json
出力:
Updated IAM policy for topic topic-b.
bindings:
- members:
  - serviceAccount:foobar@project-a.iam.gserviceaccount.com
  role: roles/pubsub.publisher
etag: BwWGrQYX6R4=

部分的に可用性を維持する動作

承認チェックは IAM サブシステムによって異なります。データ オペレーション(公開、メッセージの使用)のレスポンス レイテンシを低くするため、システムがキャッシュ内の IAM ポリシーにフォールバックする場合があります。変更が有効になるタイミングについては IAM のドキュメントをご覧ください。