IAM 権限をテストする

検出結果を作成するための IAM 権限の確認方法を説明します。

もっと見る

このコードサンプルを含む詳細なドキュメントについては、以下をご覧ください。

コードサンプル

Go

Security Command Center で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

import (
	"context"
	"fmt"
	"io"

	securitycenter "cloud.google.com/go/securitycenter/apiv1"
	iam "google.golang.org/genproto/googleapis/iam/v1"
)

// testIam demonstrates how to determine if your service user has appropriate
// access to create and update findings, it writes permissions to w.
// sourceName is the full resource name of the source to test for permissions.
func testIam(w io.Writer, sourceName string) error {
	// sourceName := "organizations/111122222444/sources/1234"
	// Instantiate a context and a security service client to make API calls.
	ctx := context.Background()
	client, err := securitycenter.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("securitycenter.NewClient: %w", err)
	}
	defer client.Close() // Closing the client safely cleans up background resources.
	// Check for create/update Permissions.
	req := &iam.TestIamPermissionsRequest{
		Resource:    sourceName,
		Permissions: []string{"securitycenter.findings.update"},
	}

	policy, err := client.TestIamPermissions(ctx, req)
	if err != nil {
		return fmt.Errorf("Error getting IAM policy: %w", err)
	}
	fmt.Fprintf(w, "Permision to create/update findings? %t",
		len(policy.Permissions) > 0)

	// Check for updating state Permissions
	req = &iam.TestIamPermissionsRequest{
		Resource:    sourceName,
		Permissions: []string{"securitycenter.findings.setState"},
	}

	policy, err = client.TestIamPermissions(ctx, req)
	if err != nil {
		return fmt.Errorf("Error getting IAM policy: %w", err)
	}
	fmt.Fprintf(w, "Permision to update state? %t",
		len(policy.Permissions) > 0)

	return nil
}

Java

Security Command Center で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

static TestIamPermissionsResponse testIamPermissions(SourceName sourceName) {
  try (SecurityCenterClient client = SecurityCenterClient.create()) {
    // SourceName sourceName = SourceName.of(/*organizationId=*/"123234324",
    // /*sourceId=*/"423432321");

    // Iam permission to test.
    List<String> permissionsToTest = new ArrayList<>();
    permissionsToTest.add("securitycenter.findings.update");

    // Call the API.
    TestIamPermissionsResponse response =
        client.testIamPermissions(sourceName.toString(), permissionsToTest);
    System.out.println("IAM Permission:");
    System.out.println(response);

    return response;
  } catch (IOException e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}

Node.js

Security Command Center で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

// Imports the Google Cloud client library.
const {SecurityCenterClient} = require('@google-cloud/security-center');

// Creates a new client.
const client = new SecurityCenterClient();

// sourceName is the full resource name of the source to test for permissions.
/*
 * TODO(developer): Uncomment the following lines
 */
// const sourceName = "organizations/111122222444/sources/1234";
async function testIam() {
  {
    const [policy] = await client.testIamPermissions({
      resource: sourceName,
      permissions: ['securitycenter.findings.update'],
    });
    console.log(
      `Permissions to create/update findings? ${
        policy.permissions.length > 0
      }`
    );
  }
  {
    const [policy] = await client.testIamPermissions({
      resource: sourceName,
      permissions: ['securitycenter.findings.setState'],
    });
    console.log(
      `Permissions to update state? ${policy.permissions.length > 0}`
    );
  }
}
testIam();

Python

Security Command Center で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

from google.cloud import securitycenter

# Create a client.
client = securitycenter.SecurityCenterClient()
# 'source_name' is the resource path for a source that has been
# created previously (you can use list_sources to find a specific one).
# Its format is:
# source_name = "organizations/{organization_id}/sources/{source_id}"
# e.g.:
# source_name = "organizations/111122222444/sources/1234"

# Check for permssions to call create_finding or update_finding.
permission_response = client.test_iam_permissions(
    request={
        "resource": source_name,
        "permissions": ["securitycenter.findings.update"],
    }
)

print(
    "Permision to create or update findings? {}".format(
        len(permission_response.permissions) > 0
    )
)
# Check for permissions necessary to call set_finding_state.
permission_response = client.test_iam_permissions(
    request={
        "resource": source_name,
        "permissions": ["securitycenter.findings.setState"],
    }
)
print(f"Permision to update state? {len(permission_response.permissions) > 0}")

次のステップ

他の Google Cloud プロダクトに関連するコードサンプルの検索およびフィルタ検索を行うには、Google Cloud のサンプルをご覧ください。