Query testable permissions

Demonstrates listing the permissions that are valid for a resource.

Explore further

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

Code sample

C++

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM C++ API reference documentation.

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

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& resource) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::QueryTestablePermissionsRequest request;
  request.set_full_resource_name(resource);
  int count = 0;
  for (auto& permission : client.QueryTestablePermissions(request)) {
    if (!permission) throw std::move(permission).status();
    std::cout << "Permission successfully retrieved: " << permission->name()
              << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No testable permissions found in resource: " << resource
              << "\n";
  }
}

C#

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM C# API reference documentation.

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


using System;
using System.Collections.Generic;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class CustomRoles
{
    public static IList<Permission> QueryTestablePermissions(
        string fullResourceName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new QueryTestablePermissionsRequest
        {
            FullResourceName = fullResourceName
        };
        var response = service.Permissions.QueryTestablePermissions(request)
            .Execute();
        foreach (var p in response.Permissions)
        {
            Console.WriteLine(p.Name);
        }
        return response.Permissions;
    }
}

Go

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Go API reference documentation.

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

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// queryTestablePermissions lists testable permissions on a resource.
func queryTestablePermissions(w io.Writer, fullResourceName string) ([]*iam.Permission, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	request := &iam.QueryTestablePermissionsRequest{
		FullResourceName: fullResourceName,
	}
	response, err := service.Permissions.QueryTestablePermissions(request).Do()
	if err != nil {
		return nil, fmt.Errorf("Permissions.QueryTestablePermissions: %w", err)
	}
	for _, p := range response.Permissions {
		fmt.Fprintf(w, "Found permissions: %v", p.Name)
	}
	return response.Permissions, nil
}

Java

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Java API reference documentation.

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


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.cloud.iam.admin.v1.IAMClient.QueryTestablePermissionsPagedResponse;
import com.google.iam.admin.v1.QueryTestablePermissionsRequest;
import java.io.IOException;

/** View available permissions in a project. */
public class QueryTestablePermissions {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variable before running the sample.
    // Full resource names can take one of the following forms:
    // cloudresourcemanager.googleapis.com/projects/PROJECT_ID
    // cloudresourcemanager.googleapis.com/organizations/NUMERIC_ID
    String fullResourceName = "your-full-resource-name";

    queryTestablePermissions(fullResourceName);
  }

  public static void queryTestablePermissions(String fullResourceName) throws IOException {
    QueryTestablePermissionsRequest queryTestablePermissionsRequest =
        QueryTestablePermissionsRequest.newBuilder().setFullResourceName(fullResourceName).build();

    try (IAMClient iamClient = IAMClient.create()) {
      QueryTestablePermissionsPagedResponse queryTestablePermissionsPagedResponse =
          iamClient.queryTestablePermissions(queryTestablePermissionsRequest);
      queryTestablePermissionsPagedResponse
          .iterateAll()
          .forEach(permission -> System.out.println(permission.getName()));
    }
  }
}

Python

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Python API reference documentation.

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

def query_testable_permissions(resource: str) -> None:
    """Lists valid permissions for a resource."""

    # pylint: disable=no-member
    permissions = (
        service.permissions()
        .queryTestablePermissions(body={"fullResourceName": resource})
        .execute()["permissions"]
    )
    for p in permissions:
        print(p["name"])

What's next

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