Test IAM permissions

Test IAM permissions.

Code sample

Go

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

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

import (
	"context"
	"fmt"
	"io"
	"strings"

	datacatalog "cloud.google.com/go/datacatalog/apiv1beta1"
	iampb "google.golang.org/genproto/googleapis/iam/v1"
)

// testIAMPermissions demonstrates a caller probing what permissions they hold on a given taxonomy
// or policy tag resource.
func testIAMPermissions(w io.Writer, resourceID string, permissions []string) error {
	// permissions := []string{"datacatalog.categories.fineGrainedGet"}
	ctx := context.Background()
	policyClient, err := datacatalog.NewPolicyTagManagerClient(ctx)
	if err != nil {
		return fmt.Errorf("datacatalog.NewPolicyTagManagerClient: %w", err)
	}
	defer policyClient.Close()

	req := &iampb.TestIamPermissionsRequest{
		Resource:    resourceID,
		Permissions: permissions,
	}
	resp, err := policyClient.TestIamPermissions(ctx, req)
	if err != nil {
		return fmt.Errorf("TestIamPermissions: %w", err)
	}
	fmt.Fprintf(w, "Testing the permissions on %s, of the %d permissions probed, caller has %d permissions", resourceID, len(permissions), len(resp.Permissions))
	if len(resp.Permissions) > 0 {
		fmt.Fprintf(w, ": %s", strings.Join(resp.Permissions, ", "))
	}
	fmt.Fprintln(w)
	return nil
}

What's next

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