Test permissions for subscription

Tests IAM permissions for a subscription.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C++

Before trying this sample, follow the C++ setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub C++ API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

namespace iam = google::cloud::iam;
namespace pubsub = google::cloud::pubsub;
[](std::string project_id, std::string subscription_id) {
  auto const subscription =
      pubsub::Subscription(std::move(project_id), std::move(subscription_id));
  auto client = iam::IAMPolicyClient(
      iam::MakeIAMPolicyConnection(pubsub::IAMPolicyOptions()));
  google::iam::v1::TestIamPermissionsRequest request;
  request.set_resource(subscription.FullName());
  request.add_permissions("pubsub.subscriptions.consume");
  request.add_permissions("pubsub.subscriptions.update");

  auto response = client.TestIamPermissions(request);
  if (!response) throw std::move(response).status();
  std::cout << "Allowed permissions for subscription "
            << subscription.FullName() << ":";
  for (auto const& permission : response->permissions()) {
    std::cout << " " << permission;
  }
  std::cout << "\n";
}

C#

Before trying this sample, follow the C# setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub C# API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

Go

Before trying this sample, follow the Go setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub Go API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

Before trying this sample, follow the Java setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub Java API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

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

Node.js

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

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

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

async function testSubscriptionPermissions(subscriptionNameOrId: string) {
  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

Before trying this sample, follow the PHP setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub PHP API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

Before trying this sample, follow the Python setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub Python API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

Before trying this sample, follow the Ruby setup instructions in the Pub/Sub quickstart using client libraries. For more information, see the Pub/Sub Ruby API reference documentation.

To authenticate to Pub/Sub, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

# 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"

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.