Access Control

This document describes the access control options available to you in Google Cloud Pub/Sub.

  1. Overview
  2. Permissions and Roles
    1. Required Permissions
    2. Roles
  3. Access Control via the Cloud Platform Console
  4. Access Control via the Google Cloud Pub/Sub IAM API
    1. Get a Policy
    2. Set a Policy
    3. Test Permissions
  5. Sample Use Case: Cross-Project Communication
  6. Partial Availability Behavior

Overview

Google Cloud Pub/Sub uses Google Cloud Identity and Access Management (IAM) for access control.

In Google Cloud Pub/Sub, access control can be configured at the project level and at the individual resource level. For example:

  • Grant access on a per-topic or per-subscription basis, rather than for the whole Cloud project.
  • Grant access with limited capabilities, such as to only publish messages to a topic, or to only consume messages from a subscription, but not to delete the topic or subscription.
  • Grant access to all Google Cloud Pub/Sub resources within a project to a group of developers.

For a detailed description of IAM and its features, see the Google Cloud Identity and Access Management developer's guide. In particular, see its Managing IAM Policies section.

Every Google Cloud Pub/Sub method requires the caller to have the necessary permissions. For a list of the permissions and roles Google Cloud Pub/Sub IAM supports, see the following section.

Permissions and Roles

This section summarizes the permissions and roles Google Cloud Pub/Sub IAM supports.

Required Permissions

The following table lists the permissions that the caller must have to call each method:

Method Required Permission(s)
projects.subscriptions.acknowledge pubsub.subscriptions.consume on the requested subscription.
projects.subscriptions.create pubsub.subscriptions.create on the containing Cloud project, and pubsub.topics.attachSubscription on the requested topic.
projects.subscriptions.delete pubsub.subscriptions.delete on the requested subscription.
projects.subscriptions.get pubsub.subscriptions.get on the requested subscription.
projects.subscriptions.getIamPolicy pubsub.subscriptions.getIamPolicy on the requested subscription.
projects.subscriptions.list pubsub.subscriptions.list on the requested Cloud project.
projects.subscriptions.modifyAckDeadline pubsub.subscriptions.consume on the requested subscription.
projects.subscriptions.modifyPushConfig pubsub.subscriptions.update on the requested subscription.
projects.subscriptions.pull pubsub.subscriptions.consume on the requested subscription.
projects.subscriptions.setIamPolicy pubsub.subscriptions.setIamPolicy on the requested subscription.
projects.subscriptions.testIamPermissions None.
projects.topics.create pubsub.topics.create on the containing Cloud project.
projects.topics.delete pubsub.topics.delete on the requested topic.
projects.topics.get pubsub.topics.get on the requested topic.
projects.topics.getIamPolicy pubsub.topics.getIamPolicy on the requested topic.
projects.topics.list pubsub.topics.list on the requested Cloud project.
projects.topics.publish pubsub.topics.publish on the requested topic.
projects.topics.setIamPolicy pubsub.topics.setIamPolicy on the requested topic.
projects.topics.testIamPermissions None.
projects.topics.subscriptions.list pubsub.topics.get on the requested topic.

Roles

The following table lists the Google Cloud Pub/Sub IAM roles with a corresponding list of all the permissions each role includes. Note that every permission is applicable to a particular resource type.

Role includes permission(s): for resource type:
roles/pubsub.publisher pubsub.topics.publish Topic
roles/pubsub.subscriber
pubsub.subscriptions.consume Subscription
pubsub.topics.attachSubscription Topic
roles/pubsub.viewer or
roles/viewer
pubsub.topics.list Project
pubsub.topics.get Topic
pubsub.subscriptions.list Project
pubsub.subscriptions.get Subscription
roles/pubsub.editor or
roles/editor
All of the above, as well as:
pubsub.topics.create Project
pubsub.topics.delete Topic
pubsub.topics.update Topic
pubsub.subscriptions.create Project
pubsub.subscriptions.delete Subscription
pubsub.subscriptions.update Subscription
roles/pubsub.admin or
roles/owner
All of the above, as well as:
pubsub.topics.getIamPolicy Topic
pubsub.topics.setIamPolicy Topic
pubsub.subscriptions.getIamPolicy Subscription
pubsub.subscriptions.setIamPolicy Subscription
Note that the roles roles/owner, roles/editor, and roles/viewer include permissions for other Google Cloud Platform services as well.

Access Control via the Cloud Platform Console

You can use the Cloud Platform Console to manage access control for your topics and projects.

To set access controls at the project level:

  1. Open the IAM page in the Google Cloud Platform Console.
  2. Select your project, and click Continue.
  3. Click ADD MEMBER.
  4. Enter the email address of a new member to whom you have not granted any IAM role previously.
  5. Select the desired role from the drop-down menu.
  6. Click Add.
  7. Verify that the member is listed under the role that you granted.

To set access controls for topics and subscriptions:

  1. Navigate to the Pub/Sub topics page in the Cloud Platform Console, select your Google Cloud Pub/Sub-enabled project.
  2. Select the topic or subscription for which you want to set permissions.

    You can set permissions for multiple topics at one time. To set permissions for a topic's subscription, expand the topic and click the subscription to open it in its own page.

  3. Click Permissions. A Permissions pane appears on the side of the screen.
  4. Type in a member name or names, select a role from the righthand drop down menu, and click Add.

Access Control via the Google Cloud Pub/Sub IAM API

The Google Cloud Pub/Sub IAM API lets you set and get policies on individual topics and subscriptions in a project, and test a user's permissions for a given resource. As with the regular Google Cloud Pub/Sub methods, you can invoke the IAM methods via the client libraries, or the API Explorer, or directly over HTTP.

Note that you cannot use the Google Cloud Pub/Sub IAM API to manage policies at the Cloud Project level.

The following sections give examples for how to set and get a policy, and how to test what permissions a caller has for a given resource.

Get a Policy

The method getIamPolicy() allows you to get a policy that was previously set. This method returns a JSON object containing the policy associated with the resource.

Here is some sample code to get a policy for a subscription:

Protocol

Request:

GET https://pubsub.googleapis.com/v1/projects/myproject/subscriptions/mysubscription:getIamPolicy?key={YOUR_API_KEY}

Response:

200 OK
{
  "etag": "AxxxxxxY/c=",
  "bindings": [
    {
      "role": "roles/pubsub.admin",
      "members": [
        "user:minka@example.com"
      ]
    },
    {
      "role": "roles/pubsub.editor",
      "members": [
        "user:trevor@example.com",
        "user:nate@example.com"
      ]
    }
  ]
}

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
Policy policy = publisher.GetIamPolicy(subscriptionName.ToString());
Console.WriteLine($"Subscription IAM Policy found for {subscriptionId}:");
Console.WriteLine(policy.Bindings);

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

policy, err := c.Subscription(subName).IAM().Policy(ctx)
if err != nil {
	return nil, err
}
for _, role := range policy.Roles() {
	log.Printf("%q: %q", role, policy.Members(role))
}

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
  Policy policy = subscriptionAdminClient.getIamPolicy(subscriptionName.toString());
  if (policy == null) {
    // subscription was not found
  }
  return policy;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function getSubscriptionPolicy (subscriptionName) {
  // Instantiates a client
  const pubsub = PubSub();

  // References an existing subscription, e.g. "my-subscription"
  const subscription = pubsub.subscription(subscriptionName);

  // Retrieves the IAM policy for the subscription
  return subscription.iam.getPolicy()
    .then((results) => {
      const policy = results[0];

      console.log(`Policy for subscription: %j.`, policy.bindings);

      return policy;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

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

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def get_subscription_policy(project, subscription_name):
    """Prints the IAM policy for the given subscription."""
    client = pubsub_v1.SubscriberClient()
    subscription_path = client.subscription_path(project, subscription_name)

    policy = client.get_iam_policy(subscription_path)

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

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub       = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
subscription = pubsub.subscription "my-subscription"

policy = subscription.policy

puts "Subscription policy:"
puts policy.roles

Here is some sample code to get a policy for a topic:

Protocol

Request:

GET https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic:getIamPolicy?key={YOUR_API_KEY}

Response:

200 OK
{
  "etag": "Awxxxxxxxxc=",
  "bindings": [
    {
      "role": "roles/viewer",
      "members": [
        "user:touki@example.com"
      ]
    }
  ]
}

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

TopicName topicName = new TopicName(projectId, topicId);
Policy policy = publisher.GetIamPolicy(topicName.ToString());
Console.WriteLine($"Topic IAM Policy found for {topicId}:");
Console.WriteLine(policy.Bindings);

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

policy, err := c.Topic(topicName).IAM().Policy(ctx)
if err != nil {
	return nil, err
}
for _, role := range policy.Roles() {
	log.Print(policy.Members(role))
}

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  TopicName topicName = TopicName.create(projectId, topicId);
  Policy policy = topicAdminClient.getIamPolicy(topicName.toString());
  if (policy == null) {
    // topic iam policy was not found
  }
  return policy;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function getTopicPolicy (topicName) {
  // Instantiates a client
  const pubsub = PubSub();

  // References an existing topic, e.g. "my-topic"
  const topic = pubsub.topic(topicName);

  // Retrieves the IAM policy for the topic
  return topic.iam.getPolicy()
    .then((results) => {
      const policy = results[0];

      console.log(`Policy for topic: %j.`, policy.bindings);

      return policy;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

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

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def get_topic_policy(project, topic_name):
    """Prints the IAM policy for the given topic."""
    client = pubsub_v1.PublisherClient()
    topic_path = client.topic_path(project, topic_name)

    policy = client.get_iam_policy(topic_path)

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

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
topic  = pubsub.topic "my-topic"

policy = topic.policy

puts "Topic policy:"
puts policy.roles

Set a Policy

The setIamPolicy() method lets you attach a policy to a resource. The setIamPolicy() method takes a SetIamPolicyRequest, which contains the policy to be set and the resource to which the policy is attached. It returns the resulting policy.

Here is some sample code to set a policy for a subscription:

Protocol

Request:

POST https://pubsub.googleapis.com/v1/projects/myproject/subscriptions/mysubscription:setIamPolicy?key={YOUR_API_KEY}
{
  "policy": {
    "bindings": [
      {
        "role": "roles/pubsub.admin",
        "members": [
          "user:rowan@example.com"
        ]
      },
      {
        "role": "roles/pubsub.editor",
        "members": [
          "user:trevor@example.com",
          "user:nate@example.com"
        ]
      }
    ]
  }
}

Response:

200 OK
{
  "etag": "Awxxxxxxxxc=",
  "bindings": [
    {
      "role": "roles/pubsub.admin",
      "members": [
        "user:rowan@example.com"
      ]
    },
    {
      "role": "roles/pubsub.editor",
      "members": [
        "user:trevor@example.com",
        "user:nate@example.com"
      ]
    }
  ]
}

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

Policy policy = new Policy
{
    Bindings =
    {
        new Binding { Role = roleToBeAddedToPolicy,
            Members = { member } }
    }
};
SetIamPolicyRequest request = new SetIamPolicyRequest
{
    Resource = new SubscriptionName(projectId, subscriptionId).ToString(),
    Policy = policy
};
Policy response = publisher.SetIamPolicy(request);
Console.WriteLine($"Subscription IAM Policy updated: {response}");

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

sub := c.Subscription(subName)
policy, err := sub.IAM().Policy(ctx)
if err != nil {
	return 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 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.

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
  SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
  Policy policy = subscriptionAdminClient.getIamPolicy(subscriptionName.toString());
  // Create a role => members binding
  Binding binding =
      Binding.newBuilder()
          .setRole(Role.viewer().toString())
          .addMembers(Identity.allAuthenticatedUsers().toString())
          .build();
  //Update policy
  Policy updatedPolicy = policy.toBuilder().addBindings(binding).build();

  updatedPolicy = subscriptionAdminClient.setIamPolicy(subscriptionName.toString(), updatedPolicy);
  return updatedPolicy;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function setSubscriptionPolicy (subscriptionName) {
  // Instantiates a client
  const pubsub = PubSub();

  // References an existing subscription, e.g. "my-subscription"
  const subscription = pubsub.subscription(subscriptionName);

  // 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
  return subscription.iam.setPolicy(newPolicy)
    .then((results) => {
      const updatedPolicy = results[0];

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

      return updatedPolicy;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

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

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def set_subscription_policy(project, subscription_name):
    """Sets the IAM policy for a topic."""
    client = pubsub_v1.SubscriberClient()
    subscription_path = client.subscription_path(project, subscription_name)

    policy = client.get_iam_policy(subscription_path)

    # Add all users as viewers.
    policy.bindings.add(
        role='roles/pubsub.viewer',
        members=['allUsers'])

    # 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(subscription_path, policy)

    print('IAM policy for subscription {} set: {}'.format(
        subscription_name, policy))

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub       = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
subscription = pubsub.subscription "my-subscription"

policy = subscription.policy do |p|
  p.add "roles/pubsub.subscriber",
        "serviceAccount:account-name@other-project.iam.gserviceaccount.com"
end

puts subscription.policy.roles

Here is some sample code to set a policy for a topic:

Protocol

Request:

POST https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic:setIamPolicy?key={YOUR_API_KEY}
{
  "policy": {
    "bindings": [
      {
        "role": "roles/pubsub.admin",
        "members": [
          "user:lindy@example.com"
        ]
      },
      {
        "role": "roles/pubsub.viewer",
        "members": [
          "user:penny@example.com"
        ]
      }
    ]
  }
}

Response:

200 OK
{
  "etag": "Axxxxxxz+pc=",
  "bindings": [
    {
      "role": "roles/pubsub.admin",
        "members": [
        "user:lindy@example.com"
      ]
    },
    {
      "role": "roles/pubsub.viewer",
        "members": [
        "user:penny@example.com"
      ]
    }
  ]
}

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

Policy policy = new Policy
{
    Bindings =
        {
            new Binding { Role = roleToBeAddedToPolicy,
                Members = { member } }
        }
};
SetIamPolicyRequest request = new SetIamPolicyRequest
{
    Resource = new TopicName(projectId, topicId).ToString(),
    Policy = policy
};
Policy response = publisher.SetIamPolicy(request);
Console.WriteLine($"Topic IAM Policy updated: {response}");

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

topic := c.Topic(topicName)
policy, err := topic.IAM().Policy(ctx)
if err != nil {
	return 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 {
	log.Fatalf("SetPolicy: %v", 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.

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  String topicName = TopicName.create(projectId, topicId).toString();
  Policy policy = topicAdminClient.getIamPolicy(topicName);
  // add role -> members binding
  Binding binding =
      Binding.newBuilder()
          .setRole(Role.viewer().toString())
          .addMembers(Identity.allAuthenticatedUsers().toString())
          .build();
  // create updated policy
  Policy updatedPolicy = Policy.newBuilder(policy).addBindings(binding).build();
  updatedPolicy = topicAdminClient.setIamPolicy(topicName, updatedPolicy);
  return updatedPolicy;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function setTopicPolicy (topicName) {
  // Instantiates a client
  const pubsub = PubSub();

  // References an existing topic, e.g. "my-topic"
  const topic = pubsub.topic(topicName);

  // 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
  return topic.iam.setPolicy(newPolicy)
    .then((results) => {
      const updatedPolicy = results[0];

      console.log(`Updated policy for topic: %j`, updatedPolicy.bindings);

      return updatedPolicy;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

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

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def set_topic_policy(project, topic_name):
    """Sets the IAM policy for a topic."""
    client = pubsub_v1.PublisherClient()
    topic_path = client.topic_path(project, topic_name)

    policy = client.get_iam_policy(topic_path)

    # Add all users as viewers.
    policy.bindings.add(
        role='roles/pubsub.viewer',
        members=['allUsers'])

    # 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(topic_path, policy)

    print('IAM policy for topic {} set: {}'.format(
        topic_name, policy))

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
topic  = pubsub.topic "my-topic"

policy = topic.policy do |p|
  p.add "roles/pubsub.publisher",
        "serviceAccount:account-name@other-project.iam.gserviceaccount.com"
end

puts topic.policy.roles

Test Permissions

You can use the testIamPermissions() method to check which of the given permissions the caller has for the given resource. It takes as parameters a resource name and a set of permissions, and returns the subset of permissions that the caller has.

Here is some sample code to test permissions for a subscription:

Protocol

Request:

POST https://pubsub.googleapis.com/v1/projects/myproject/subscriptions/mysubscription:testIamPermissions?key={YOUR_API_KEY}
{
  "permissions": [
    "pubsub.subscriptions.consume",
    "pubsub.subscriptions.update"
  ]
}

Response:

200 OK
{
  "permissions": [
    "pubsub.subscriptions.consume"
  ]
}

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

List<string> permissions = new List<string>();
permissions.Add("pubsub.subscriptions.get");
permissions.Add("pubsub.subscriptions.update");
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
    Resource = new TopicName(_projectId, subscriptionId).ToString(),
    Permissions = { permissions }
};
TestIamPermissionsResponse response = publisher.TestIamPermissions(request);
return response;

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

sub := c.Subscription(subName)
perms, err := sub.IAM().TestPermissions(ctx, []string{
	"pubsub.subscriptions.consume",
	"pubsub.subscriptions.update",
})
if err != nil {
	return nil, err
}
for _, perm := range perms {
	log.Printf("Allowed: %v", perm)
}

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  List<String> permissions = new LinkedList<>();
  permissions.add("pubsub.subscriptions.get");
  SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
  TestIamPermissionsResponse testedPermissions =
      topicAdminClient.testIamPermissions(subscriptionName.toString(), permissions);
  return testedPermissions;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function testSubscriptionPermissions (subscriptionName) {
  // Instantiates a client
  const pubsub = PubSub();

  // References an existing subscription, e.g. "my-subscription"
  const subscription = pubsub.subscription(subscriptionName);

  const permissionsToTest = [
    `pubsub.subscriptions.consume`,
    `pubsub.subscriptions.update`
  ];

  // Tests the IAM policy for the specified subscription
  subscription.iam.testPermissions(permissionsToTest)
    .then((results) => {
      const permissions = results[0];

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

      return permissions;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

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

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def check_subscription_permissions(project, subscription_name):
    """Checks to which permissions are available on the given subscription."""
    client = pubsub_v1.SubscriberClient()
    subscription_path = client.subscription_path(project, subscription_name)

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

    allowed_permissions = client.test_iam_permissions(
        subscription_path, permissions_to_check)

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

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub       = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
subscription = pubsub.subscription "my-subscription"

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

puts permissions.include? "pubsub.subscriptions.consume"
puts permissions.include? "pubsub.subscriptions.update"

Here is some sample code to test permissions for a topic:

Protocol

Request:

POST https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic:testIamPermissions?key={YOUR_API_KEY}
{
  "permissions": [
    "pubsub.topics.get",
    "pubsub.topics.update"
  ]
}

Response:

200 OK
{
  "permissions": [
    "pubsub.topics.get"
  ]
}

C#

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

List<string> permissions = new List<string>();
permissions.Add("pubsub.topics.get");
permissions.Add("pubsub.topics.update");
TestIamPermissionsRequest request = new TestIamPermissionsRequest
{
    Resource = new TopicName(_projectId, topicId).ToString(),
    Permissions = { permissions }
};
TestIamPermissionsResponse response = publisher.TestIamPermissions(request);
return response;

Go

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

topic := c.Topic(topicName)
perms, err := topic.IAM().TestPermissions(ctx, []string{
	"pubsub.topics.publish",
	"pubsub.topics.update",
})
if err != nil {
	return nil, err
}
for _, perm := range perms {
	log.Printf("Allowed: %v", perm)
}

Java

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
  List<String> permissions = new LinkedList<>();
  permissions.add("pubsub.topics.get");
  TopicName topicName = TopicName.create(projectId, topicId);
  TestIamPermissionsResponse testedPermissions =
      topicAdminClient.testIamPermissions(topicName.toString(), permissions);
  return testedPermissions;
}

Node.js

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

function testTopicPermissions (topicName) {
  // Instantiates a client
  const pubsub = PubSub();

  // References an existing topic, e.g. "my-topic"
  const topic = pubsub.topic(topicName);

  const permissionsToTest = [
    `pubsub.topics.attachSubscription`,
    `pubsub.topics.publish`,
    `pubsub.topics.update`
  ];

  // Tests the IAM policy for the specified topic
  return topic.iam.testPermissions(permissionsToTest)
    .then((results) => {
      const permissions = results[0];

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

      return permissions;
    });
}

PHP

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

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

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

def check_topic_permissions(project, topic_name):
    """Checks to which permissions are available on the given topic."""
    client = pubsub_v1.PublisherClient()
    topic_path = client.topic_path(project, topic_name)

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

    allowed_permissions = client.test_iam_permissions(
        topic_path, permissions_to_check)

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

Ruby

For more on installing and creating a Cloud Pub/Sub client, refer to Cloud Pub/Sub Client Libraries.

pubsub = Google::Cloud::Pubsub.new project: "my-gcp-project-id"
topic  = pubsub.topic "my-topic"

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

puts permissions.include? "pubsub.topics.attachSubscription"
puts permissions.include? "pubsub.topics.publish"
puts permissions.include? "pubsub.topics.update"

Sample Use Case: Cross-Project Communication

Google Cloud Pub/Sub IAM is useful for fine-tuning access in cross-project communication. For example, suppose a service account in Cloud Project A wants to publish messages to a topic in Cloud Project B. You could accomplish this by granting the service account Edit permission in Cloud Project B. However, this approach is often too coarse. You can use the IAM API to achieve a more fine-grained level of access.

For example, this snippet uses the setIamPolicy() method to grant the service account foobar@appspot.gserviceaccount.com the publisher role on the topic projects/myproject/topics/mytopic:

POST https://pubsub.googleapis.com/v1/projects/myproject/topics/mytopic:setIamPolicy?key={YOUR_API_KEY}
{
  "policy": {
    "bindings": [
      {
        "members": [
          "serviceAccount:foobar@appspot.gserviceaccount.com"
        ],
        "role": "roles/pubsub.publisher"
      }
    ]
  }
}

Partial Availability Behavior

Performing authorization checks depends on the IAM subsystem. As with any distributed system, there is a small chance that this system may become unavailable. If this unlikely event occurs, Google Cloud Pub/Sub employs a fallback mechanism to reduce the impact of IAM unavailability. The goal of the fallback behavior is simply to keep messages flowing through Google Cloud Pub/Sub; thus, fallback is used only for reading the pubsub.topics.publish and pubsub.subscriptions.consume permissions. Google Cloud Pub/Sub remembers the last successful result from the IAM service and uses it. If the server ever enters the fallback state, Google Cloud Pub/Sub will post a notification in the Google Cloud Platform status dashboard, and will record the duration of the incident.

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Cloud Pub/Sub Documentation