Access Control

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

  1. Overview
  2. Permissions and Roles
    1. Required Permissions
    2. Roles
  3. Access Control via the GCP Console
  4. Access Control via the 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

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

In 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 Cloud Pub/Sub resources within a project to a group of developers.

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

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

Permissions and Roles

This section summarizes the permissions and roles 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. Note that for creating a subscription in Project A on a Topic T in Project B, the appropriate permissions must be granted on both Project A and on Topic T.
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 Cloud Pub/Sub Cloud IAM roles with a corresponding list of all the permissions each role includes. Note that every permission is applicable to a particular resource type.

These preconfigured roles address many typical use cases. However, you might need a role that includes a custom set of permissions. For instance, you may wish to create a role that allows a user to create a subscription in a project, without letting them delete or update existing topics or subscriptions in the project. In those cases, you may be able to create an Cloud IAM custom role that meets your needs.

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 GCP Console

You can use the GCP 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 GCP Console, select your 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 Cloud Pub/Sub IAM API

The 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 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 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()) {
  ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(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.

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const subscriptionName = 'your-subscription';

// Retrieves the IAM policy for the subscription
pubsub
  .subscription(subscriptionName)
  .iam.getPolicy()
  .then(results => {
    const policy = results[0];
    console.log(`Policy for subscription: %j.`, policy.bindings);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

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.

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.

# project_id        = "Your Google Cloud Project ID"
# subscription_name = "Your Pubsub subscription name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

subscription = pubsub.subscription subscription_name
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()) {
  ProjectTopicName topicName = ProjectTopicName.of(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.

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const topicName = 'your-topic';

// Retrieves the IAM policy for the topic
pubsub
  .topic(topicName)
  .iam.getPolicy()
  .then(results => {
    const policy = results[0];
    console.log(`Policy for topic: %j.`, policy.bindings);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

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.

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.

# project_id = "Your Google Cloud Project ID"
# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topic  = pubsub.topic topic_name
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()) {
  ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(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.

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const subscriptionName = 'your-subscription';

// 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
pubsub
  .subscription(subscriptionName)
  .iam.setPolicy(newPolicy)
  .then(results => {
    const updatedPolicy = results[0];
    console.log(
      `Updated policy for subscription: %j`,
      updatedPolicy.bindings
    );
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

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.

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.

# project_id        = "Your Google Cloud Project ID"
# subscription_name = "Your Pubsub subscription name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

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

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 = ProjectTopicName.format(projectId, topicId);
  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.

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const topicName = 'your-topic';

// 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
pubsub
  .topic(topicName)
  .iam.setPolicy(newPolicy)
  .then(results => {
    const updatedPolicy = results[0];
    console.log(`Updated policy for topic: %j`, updatedPolicy.bindings);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

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.

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.

# project_id = "Your Google Cloud Project ID"
# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topic = pubsub.topic topic_name
topic.policy do |policy|
  policy.add "roles/pubsub.publisher",
    "serviceAccount:account_name@project_name.iam.gserviceaccount.com"
end

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 SubscriptionName(_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");
  ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(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.

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const subscriptionName = 'your-subscription';

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

// Tests the IAM policy for the specified subscription
pubsub
  .subscription(subscriptionName)
  .iam.testPermissions(permissionsToTest)
  .then(results => {
    const permissions = results[0];
    console.log(`Tested permissions for subscription: %j`, permissions);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

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.

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.

# project_id        = "Your Google Cloud Project ID"
# subscription_name = "Your Pubsub subscription name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

subscription = pubsub.subscription subscription_name
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"

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");
  ProjectTopicName topicName = ProjectTopicName.of(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.

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

// Creates a client
const pubsub = new PubSub();

/**
 * TODO(developer): Uncomment the following line to run the sample.
 */
// const topicName = 'your-topic';

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

// Tests the IAM policy for the specified topic
pubsub
  .topic(topicName)
  .iam.testPermissions(permissionsToTest)
  .then(results => {
    const permissions = results[0];
    console.log(`Tested permissions for topic: %j`, permissions);
  })
  .catch(err => {
    console.error('ERROR:', err);
  });

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.

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.

# project_id = "Your Google Cloud Project ID"
# topic_name = "Your Pubsub topic name"
require "google/cloud/pubsub"

pubsub = Google::Cloud::Pubsub.new project: project_id

topic       = pubsub.topic topic_name
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"

Sample Use Case: Cross-Project Communication

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

Authorization checks depend on the IAM subsystem. In order to offer consistently low response latency for data operations (publishing and message consumption), the system may fall back on cached IAM policies. A cached IAM policy expires after at most an hour.

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Pub/Sub Documentation