IAM を使用したアクセス制御

このトピックでは、Cloud KMS リソースへのアクセスを管理する方法について説明します。

概要

鍵やキーリングなどの Cloud KMS リソースへのアクセスを管理するには、Identity and Access Management(IAM)ロールを付与します。鍵のローテーションやデータの暗号化など、特定の暗号オペレーションの実行権限を付与または制限できます。次のとおり、IAM のロールを付与できます。

  • 鍵に直接
  • その鍵リング内のすべての鍵によって継承される鍵リング
  • プロジェクトのすべての鍵によって継承される Google Cloud プロジェクト
  • フォルダ内のすべてのプロジェクトのすべての鍵によって継承される Google Cloud フォルダ
  • 組織内のフォルダ内のすべての鍵によって継承される Google Cloud 組織

Cloud KMS のアクションおよび IAM のロールと権限の一覧については、権限とロールをご覧ください。Cloud KMS リソースとリソース間の関係については、Cloud KMS リソースをご覧ください。

始める前に

これらのタスクを完了するには、Google Cloud プロジェクトの Cloud KMS リソースを管理する権限が必要です。Cloud KMS 管理者のロール(roles/cloudkms.admin)には、必要な権限が含まれています。

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the required API.

    Enable the API

  5. Install the Google Cloud CLI.
  6. To initialize the gcloud CLI, run the following command:

    gcloud init
  7. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  8. Make sure that billing is enabled for your Google Cloud project.

  9. Enable the required API.

    Enable the API

  10. Install the Google Cloud CLI.
  11. To initialize the gcloud CLI, run the following command:

    gcloud init
  12. キーリングなどのリソースを作成します。
  13. 作成されたリソース(キーリング、鍵、鍵バージョンなど)のリソース IDを取得します。

Cloud KMS リソースへのアクセス権を付与または取り消すことができるのは、オーナー(roles/owner)または Cloud KMS 管理者(roles/cloudkms.admin)のロールを持つ IAM プリンシパルのみです。

リソースに対するロールの付与

次の例では、Cloud KMS 鍵へのアクセスを提供するロールを付与します。

gcloud

コマンドラインで Cloud KMS を使用するには、まず Google Cloud CLI の最新バージョンをインストールまたはアップグレードします

gcloud kms keys add-iam-policy-binding key \
    --keyring key-ring \
    --location location \
    --member principal-type:principal-email \
    --role roles/role

key を鍵の名前に置き換えます。key-ring は、鍵が配置されている鍵リングの名前に置き換えます。location を鍵リングの Cloud KMS の場所に置き換えます。principal-typeprincipal-email は、プリンシパルの種類とプリンシパルのメールアドレスに置き換えます。role は、追加するロールの名前に置き換えます。

C#

このコードを実行するには、まず C# 開発環境を設定し、Cloud KMS C# SDK をインストールします。


using Google.Cloud.Iam.V1;
using Google.Cloud.Kms.V1;

public class IamAddMemberSample
{
    public Policy IamAddMember(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key",
      string member = "user:foo@example.com")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the resource name.
        CryptoKeyName resourceName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // The resource name could also be a key ring.
        // var resourceName = new KeyRingName(projectId, locationId, keyRingId);

        // Get the current IAM policy.
        Policy policy = client.IAMPolicyClient.GetIamPolicy(
            new GetIamPolicyRequest
            { 
                ResourceAsResourceName = resourceName
            });

        // Add the member to the policy.
        policy.AddRoleMember("roles/cloudkms.cryptoKeyEncrypterDecrypter", member);

        // Save the updated IAM policy.
        Policy result = client.IAMPolicyClient.SetIamPolicy(
            new SetIamPolicyRequest
            {
                ResourceAsResourceName = resourceName,
                Policy = policy
            });

        // Return the resulting policy.
        return result;
    }
}

Go

このコードを実行するには、まず Go 開発環境を設定し、Cloud KMS Go SDK をインストールします。

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
)

// iamAddMember adds a new IAM member to the Cloud KMS key
func iamAddMember(w io.Writer, name, member string) error {
	// NOTE: The resource name can be either a key or a key ring. If IAM
	// permissions are granted on the key ring, the permissions apply to all keys
	// in the key ring.
	//
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"
	// member := "user:foo@example.com"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Get the current IAM policy.
	handle := client.ResourceIAM(name)
	policy, err := handle.Policy(ctx)
	if err != nil {
		return fmt.Errorf("failed to get IAM policy: %w", err)
	}

	// Grant the member permissions. This example grants permission to use the key
	// to encrypt data.
	policy.Add(member, "roles/cloudkms.cryptoKeyEncrypterDecrypter")
	if err := handle.SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("failed to save policy: %w", err)
	}

	fmt.Fprintf(w, "Updated IAM policy for %s\n", name)
	return nil
}

Java

このコードを実行するには、まず Java 開発環境を設定し、Cloud KMS Java SDK をインストールします。

import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import java.io.IOException;

public class IamAddMember {

  public void iamAddMember() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    String member = "user:foo@example.com";
    iamAddMember(projectId, locationId, keyRingId, keyId, member);
  }

  // Add the given IAM member to the key.
  public void iamAddMember(
      String projectId, String locationId, String keyRingId, String keyId, String member)
      throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyName resourceName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // The resource name could also be a key ring.
      // KeyRingName resourceName = KeyRingName.of(projectId, locationId, keyRingId);

      // Get the current policy.
      Policy policy = client.getIamPolicy(resourceName);

      // Create a new IAM binding for the member and role.
      Binding binding =
          Binding.newBuilder()
              .setRole("roles/cloudkms.cryptoKeyEncrypterDecrypter")
              .addMembers(member)
              .build();

      // Add the binding to the policy.
      Policy newPolicy = policy.toBuilder().addBindings(binding).build();

      client.setIamPolicy(resourceName, newPolicy);
      System.out.printf("Updated IAM policy for %s%n", resourceName.toString());
    }
  }
}

Node.js

このコードを実行するには、まず Node.js 開発環境を設定し、Cloud KMS Node.js SDK をインストールします。

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';
// const member = 'user:foo@example.com';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the resource name
const resourceName = client.cryptoKeyPath(
  projectId,
  locationId,
  keyRingId,
  keyId
);

// The resource name could also be a key ring.
// const resourceName = client.keyRingPath(projectId, locationId, keyRingId);

async function iamAddMember() {
  // Get the current IAM policy.
  const [policy] = await client.getIamPolicy({
    resource: resourceName,
  });

  // Add the member to the policy.
  policy.bindings.push({
    role: 'roles/cloudkms.cryptoKeyEncrypterDecrypter',
    members: [member],
  });

  // Save the updated policy.
  const [updatedPolicy] = await client.setIamPolicy({
    resource: resourceName,
    policy: policy,
  });

  console.log('Updated policy');
  return updatedPolicy;
}

return iamAddMember();

PHP

このコードを実行するには、まず Google Cloud での PHP の使用について学び、Cloud KMS PHP SDK をインストールします。

use Google\Cloud\Iam\V1\Binding;
use Google\Cloud\Iam\V1\GetIamPolicyRequest;
use Google\Cloud\Iam\V1\SetIamPolicyRequest;
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;

function iam_add_member(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key',
    string $member = 'user:foo@example.com'
) {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the resource name.
    $resourceName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // The resource name could also be a key ring.
    // $resourceName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Get the current IAM policy.
    $getIamPolicyRequest = (new GetIamPolicyRequest())
        ->setResource($resourceName);
    $policy = $client->getIamPolicy($getIamPolicyRequest);

    // Add the member to the policy.
    $bindings = $policy->getBindings();
    $bindings[] = (new Binding())
        ->setRole('roles/cloudkms.cryptoKeyEncrypterDecrypter')
        ->setMembers([$member]);
    $policy->setBindings($bindings);

    // Save the updated IAM policy.
    $setIamPolicyRequest = (new SetIamPolicyRequest())
        ->setResource($resourceName)
        ->setPolicy($policy);
    $updatedPolicy = $client->setIamPolicy($setIamPolicyRequest);
    printf('Added %s' . PHP_EOL, $member);

    return $updatedPolicy;
}

Python

このコードを実行するには、まず Python 開発環境を設定し、Cloud KMS Python SDK をインストールします。

from google.cloud import kms
from google.iam.v1 import policy_pb2 as iam_policy


def iam_add_member(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, member: str
) -> iam_policy.Policy:
    """
    Add an IAM member to a resource.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').
        member (string): Member to add (e.g. 'user:foo@example.com')

    Returns:
        Policy: Updated Cloud IAM policy.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the resource name.
    resource_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    # The resource name could also be a key ring.
    # resource_name = client.key_ring_path(project_id, location_id, key_ring_id);

    # Get the current policy.
    policy = client.get_iam_policy(request={"resource": resource_name})

    # Add the member to the policy.
    policy.bindings.add(
        role="roles/cloudkms.cryptoKeyEncrypterDecrypter", members=[member]
    )

    # Save the updated IAM policy.
    request = {"resource": resource_name, "policy": policy}

    updated_policy = client.set_iam_policy(request=request)
    print(f"Added {member} to {resource_name}")
    return updated_policy

Ruby

このコードを実行するには、まず Ruby 開発環境を設定し、Cloud KMS Ruby SDK をインストールします。

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"
# member      = "user:foo@example.com"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the resource name.
resource_name = client.crypto_key_path project:    project_id,
                                       location:   location_id,
                                       key_ring:   key_ring_id,
                                       crypto_key: key_id

# The resource name could also be a key ring.
# resource_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Create the IAM client.
iam_client = Google::Cloud::Kms::V1::IAMPolicy::Client.new

# Get the current IAM policy.
policy = iam_client.get_iam_policy resource: resource_name

# Add the member to the policy.
policy.bindings << Google::Iam::V1::Binding.new(
  members: [member],
  role:    "roles/cloudkms.cryptoKeyEncrypterDecrypter"
)

# Save the updated policy.
updated_policy = iam_client.set_iam_policy resource: resource_name, policy: policy
puts "Added #{member}"

リソースへのアクセスの取り消し

Cloud KMS 鍵に対するプリンシパルのアクセス権を削除するには、以下の操作を行います。

gcloud

コマンドラインで Cloud KMS を使用するには、まず Google Cloud CLI の最新バージョンをインストールまたはアップグレードします

gcloud kms keys remove-iam-policy-binding key \
    --keyring key-ring \
    --location location \
    --member principal-type:principal-email \
    --role roles/role-name

key を鍵の名前に置き換えます。key-ring は、鍵が配置されている鍵リングの名前に置き換えます。location を鍵リングの Cloud KMS の場所に置き換えます。principal-typeprincipal-email は、プリンシパルの種類とプリンシパルのメールアドレスに置き換えます。role-name は、削除するロールの名前に置き換えます。

すべてのフラグと有効な値については、--help フラグを指定してコマンドを実行してください。

C#

このコードを実行するには、まず C# 開発環境を設定し、Cloud KMS C# SDK をインストールします。


using Google.Cloud.Iam.V1;
using Google.Cloud.Kms.V1;

public class IamRemoveMemberSample
{
    public Policy IamRemoveMember(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key",
      string member = "user:foo@example.com")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the resource name.
        CryptoKeyName resourceName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // The resource name could also be a key ring.
        // var resourceName = new KeyRingName(projectId, locationId, keyRingId);

        // Get the current IAM policy.
        Policy policy = client.IAMPolicyClient.GetIamPolicy(
            new GetIamPolicyRequest
            {
                ResourceAsResourceName = resourceName
            });

        // Add the member to the policy.
        policy.RemoveRoleMember("roles/cloudkms.cryptoKeyEncrypterDecrypter", member);

        // Save the updated IAM policy.
        Policy result = client.IAMPolicyClient.SetIamPolicy(
            new SetIamPolicyRequest
            {
                ResourceAsResourceName = resourceName,
                Policy = policy
            });

        // Return the resulting policy.
        return result;
    }
}

Go

このコードを実行するには、まず Go 開発環境を設定し、Cloud KMS Go SDK をインストールします。

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
)

// iamRemoveMember removes the IAM member from the Cloud KMS key, if they exist.
func iamRemoveMember(w io.Writer, name, member string) error {
	// NOTE: The resource name can be either a key or a key ring.
	//
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"
	// member := "user:foo@example.com"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Get the current IAM policy.
	handle := client.ResourceIAM(name)
	policy, err := handle.Policy(ctx)
	if err != nil {
		return fmt.Errorf("failed to get IAM policy: %w", err)
	}

	// Grant the member permissions. This example grants permission to use the key
	// to encrypt data.
	policy.Remove(member, "roles/cloudkms.cryptoKeyEncrypterDecrypter")
	if err := handle.SetPolicy(ctx, policy); err != nil {
		return fmt.Errorf("failed to save policy: %w", err)
	}

	fmt.Fprintf(w, "Updated IAM policy for %s\n", name)
	return nil
}

Java

このコードを実行するには、まず Java 開発環境を設定し、Cloud KMS Java SDK をインストールします。

import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import java.io.IOException;

public class IamRemoveMember {

  public void iamRemoveMember() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    String member = "user:foo@example.com";
    iamRemoveMember(projectId, locationId, keyRingId, keyId, member);
  }

  // Remove the given IAM membership on the resource, if it exists.
  public void iamRemoveMember(
      String projectId, String locationId, String keyRingId, String keyId, String member)
      throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyName resourceName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // The resource name could also be a key ring.
      // KeyRingName resourceName = KeyRingName.of(projectId, locationId, keyRingId);

      // Get the current policy.
      Policy policy = client.getIamPolicy(resourceName);

      // Search through the bindings and remove matches.
      String roleToFind = "roles/cloudkms.cryptoKeyEncrypterDecrypter";
      for (Binding binding : policy.getBindingsList()) {
        if (binding.getRole().equals(roleToFind) && binding.getMembersList().contains(member)) {
          binding.getMembersList().remove(member);
        }
      }

      client.setIamPolicy(resourceName, policy);
      System.out.printf("Updated IAM policy for %s%n", resourceName.toString());
    }
  }
}

Node.js

このコードを実行するには、まず Node.js 開発環境を設定し、Cloud KMS Node.js SDK をインストールします。

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';
// const member = 'user:foo@example.com';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the resource name
const resourceName = client.cryptoKeyPath(
  projectId,
  locationId,
  keyRingId,
  keyId
);

// The resource name could also be a key ring.
// const resourceName = client.keyRingPath(projectId, locationId, keyRingId);

async function iamRemoveMember() {
  // Get the current IAM policy.
  const [policy] = await client.getIamPolicy({
    resource: resourceName,
  });

  // Build a new list of policy bindings with the user excluded.
  for (const i in policy.bindings) {
    const binding = policy.bindings[i];
    if (binding.role !== 'roles/cloudkms.cryptoKeyEncrypterDecrypter') {
      continue;
    }

    const idx = binding.members.indexOf(member);
    if (idx !== -1) {
      binding.members.splice(idx, 1);
    }
  }

  // Save the updated IAM policy.
  const [updatedPolicy] = await client.setIamPolicy({
    resource: resourceName,
    policy: policy,
  });

  console.log('Updated policy');
  return updatedPolicy;
}

return iamRemoveMember();

PHP

このコードを実行するには、まず Google Cloud での PHP の使用について学び、Cloud KMS PHP SDK をインストールします。

use Google\Cloud\Iam\V1\Binding;
use Google\Cloud\Iam\V1\GetIamPolicyRequest;
use Google\Cloud\Iam\V1\Policy;
use Google\Cloud\Iam\V1\SetIamPolicyRequest;
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;

function iam_remove_member(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key',
    string $member = 'user:foo@example.com'
): Policy {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the resource name.
    $resourceName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // The resource name could also be a key ring.
    // $resourceName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Get the current IAM policy.
    $getIamPolicyRequest = (new GetIamPolicyRequest())
        ->setResource($resourceName);
    $policy = $client->getIamPolicy($getIamPolicyRequest);

    // Remove the member from the policy by creating a new policy with everyone
    // but the member to remove.
    $newPolicy = new Policy();
    foreach ($policy->getBindings() as $binding) {
        if ($binding->getRole() !== 'roles/cloudkms.cryptoKeyEncrypterDecrypter') {
            $newPolicy->getBindings()[] = $binding;
        } else {
            $newBinding = (new Binding())
              ->setRole($binding->getRole());

            $newMembers = [];
            foreach ($binding->getMembers() as $existingMember) {
                if ($member !== $existingMember) {
                    $newMembers[] = $existingMember;
                }
            }

            $newPolicy->getBindings()[] = (new Binding())
              ->setRole($binding->getRole())
              ->setMembers($newMembers);
        }
    }

    // Save the updated IAM policy.
    $setIamPolicyRequest = (new SetIamPolicyRequest())
        ->setResource($resourceName)
        ->setPolicy($newPolicy);
    $updatedPolicy = $client->setIamPolicy($setIamPolicyRequest);
    printf('Removed %s' . PHP_EOL, $member);

    return $updatedPolicy;
}

Python

このコードを実行するには、まず Python 開発環境を設定し、Cloud KMS Python SDK をインストールします。

from google.cloud import kms
from google.iam.v1 import policy_pb2 as iam_policy


def iam_remove_member(
    project_id: str, location_id: str, key_ring_id: str, key_id: str, member: str
) -> iam_policy.Policy:
    """
    Remove an IAM member from a resource.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').
        member (string): Member to remove (e.g. 'user:foo@example.com')

    Returns:
        Policy: Updated Cloud IAM policy.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the resource name.
    resource_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    # The resource name could also be a key ring.
    # resource_name = client.key_ring_path(project_id, location_id, key_ring_id);

    # Get the current policy.
    policy = client.get_iam_policy(request={"resource": resource_name})

    # Remove the member from the policy.
    for binding in policy.bindings:
        if binding.role == "roles/cloudkms.cryptoKeyEncrypterDecrypter":
            if member in binding.members:
                binding.members.remove(member)

    # Save the updated IAM policy.
    request = {"resource": resource_name, "policy": policy}
    updated_policy = client.set_iam_policy(request=request)
    print(f"Removed {member} from {resource_name}")
    return updated_policy

Ruby

このコードを実行するには、まず Ruby 開発環境を設定し、Cloud KMS Ruby SDK をインストールします。

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"
# member      = "user:foo@example.com"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the resource name.
resource_name = client.crypto_key_path project:    project_id,
                                       location:   location_id,
                                       key_ring:   key_ring_id,
                                       crypto_key: key_id

# The resource name could also be a key ring.
# resource_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Create the IAM client.
iam_client = Google::Cloud::Kms::V1::IAMPolicy::Client.new

# Get the current IAM policy.
policy = iam_client.get_iam_policy resource: resource_name

# Remove the member from the current bindings
policy.bindings.each do |bind|
  if bind.role == "roles/cloudkms.cryptoKeyEncrypterDecrypter"
    bind.members.delete member
  end
end

# Save the updated policy.
updated_policy = iam_client.set_iam_policy resource: resource_name, policy: policy
puts "Removed #{member}"

リソースに対する権限を表示する

Cloud KMS 鍵の IAM ポリシーを表示するには:

gcloud

コマンドラインで Cloud KMS を使用するには、まず Google Cloud CLI の最新バージョンをインストールまたはアップグレードします

gcloud kms keys get-iam-policy key \
    --keyring key-ring \
    --location location

key を鍵の名前に置き換えます。key-ring は、鍵が配置されている鍵リングの名前に置き換えます。location を鍵リングの Cloud KMS の場所に置き換えます。

すべてのフラグと有効な値については、--help フラグを指定してコマンドを実行してください。

C#

このコードを実行するには、まず C# 開発環境を設定し、Cloud KMS C# SDK をインストールします。


using Google.Cloud.Iam.V1;
using Google.Cloud.Kms.V1;
using System;

public class IamGetPolicySample
{
    public Policy IamGetPolicy(
      string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the resource name.
        CryptoKeyName resourceName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // The resource name could also be a key ring.
        // var resourceName = new KeyRingName(projectId, locationId, keyRingId);

        // Get the current IAM policy.
        Policy policy = client.IAMPolicyClient.GetIamPolicy(
            new GetIamPolicyRequest
            {
                ResourceAsResourceName = resourceName
            });

        // Print the policy.
        foreach (Binding b in policy.Bindings)
        {
            String role = b.Role;

            foreach (String member in b.Members)
            {
                // ...
            }
        }

        // Return the policy.
        return policy;
    }
}

Go

このコードを実行するには、まず Go 開発環境を設定し、Cloud KMS Go SDK をインストールします。

import (
	"context"
	"fmt"
	"io"

	kms "cloud.google.com/go/kms/apiv1"
)

// iamGetPolicy retrieves and prints the Cloud IAM policy associated with the
// Cloud KMS key.
func iamGetPolicy(w io.Writer, name string) error {
	// NOTE: The resource name can be either a key or a key ring.
	//
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key"
	// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring"

	// Create the client.
	ctx := context.Background()
	client, err := kms.NewKeyManagementClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create kms client: %w", err)
	}
	defer client.Close()

	// Get the current policy.
	policy, err := client.ResourceIAM(name).Policy(ctx)
	if err != nil {
		return fmt.Errorf("failed to get IAM policy: %w", err)
	}

	// Print the policy members.
	for _, role := range policy.Roles() {
		fmt.Fprintf(w, "%s\n", role)
		for _, member := range policy.Members(role) {
			fmt.Fprintf(w, "- %s\n", member)
		}
		fmt.Fprintf(w, "\n")
	}
	return nil
}

Java

このコードを実行するには、まず Java 開発環境を設定し、Cloud KMS Java SDK をインストールします。

import com.google.cloud.kms.v1.CryptoKeyName;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import java.io.IOException;

public class IamGetPolicy {

  public void iamGetPolicy() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String locationId = "us-east1";
    String keyRingId = "my-key-ring";
    String keyId = "my-key";
    iamGetPolicy(projectId, locationId, keyRingId, keyId);
  }

  // Get the IAM policy for the given key.
  public void iamGetPolicy(String projectId, String locationId, String keyRingId, String keyId)
      throws IOException {
    // Initialize client that will be used to send requests. This client only
    // needs to be created once, and can be reused for multiple requests. After
    // completing all of your requests, call the "close" method on the client to
    // safely clean up any remaining background resources.
    try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
      // Build the key version name from the project, location, key ring, key,
      // and key version.
      CryptoKeyName resourceName = CryptoKeyName.of(projectId, locationId, keyRingId, keyId);

      // The resource name could also be a key ring.
      // KeyRingName resourceName = KeyRingName.of(projectId, locationId, keyRingId);

      // Get the current policy.
      Policy policy = client.getIamPolicy(resourceName);

      // Print the policy.
      System.out.printf("IAM policy:%n");
      for (Binding binding : policy.getBindingsList()) {
        System.out.printf("%s%n", binding.getRole());
        for (String member : binding.getMembersList()) {
          System.out.printf("- %s%n", member);
        }
      }
    }
  }
}

Node.js

このコードを実行するには、まず Node.js 開発環境を設定し、Cloud KMS Node.js SDK をインストールします。

//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const keyId = 'my-key';
// const member = 'user:foo@example.com';

// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');

// Instantiates a client
const client = new KeyManagementServiceClient();

// Build the resource name
const resourceName = client.cryptoKeyPath(
  projectId,
  locationId,
  keyRingId,
  keyId
);

// The resource name could also be a key ring.
// const resourceName = client.keyRingPath(projectId, locationId, keyRingId);

async function iamGetPolicy() {
  const [policy] = await client.getIamPolicy({
    resource: resourceName,
  });

  for (const binding of policy.bindings) {
    console.log(`Role: ${binding.role}`);
    for (const member of binding.members) {
      console.log(`  - ${member}`);
    }
  }

  return policy;
}

return iamGetPolicy();

PHP

このコードを実行するには、まず Google Cloud での PHP の使用について学び、Cloud KMS PHP SDK をインストールします。

use Google\Cloud\Iam\V1\GetIamPolicyRequest;
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;

function iam_get_policy(
    string $projectId = 'my-project',
    string $locationId = 'us-east1',
    string $keyRingId = 'my-key-ring',
    string $keyId = 'my-key'
) {
    // Create the Cloud KMS client.
    $client = new KeyManagementServiceClient();

    // Build the resource name.
    $resourceName = $client->cryptoKeyName($projectId, $locationId, $keyRingId, $keyId);

    // The resource name could also be a key ring.
    // $resourceName = $client->keyRingName($projectId, $locationId, $keyRingId);

    // Get the current IAM policy.
    $getIamPolicyRequest = (new GetIamPolicyRequest())
        ->setResource($resourceName);
    $policy = $client->getIamPolicy($getIamPolicyRequest);

    // Print the policy.
    printf('IAM policy for %s' . PHP_EOL, $resourceName);
    foreach ($policy->getBindings() as $binding) {
        printf('%s' . PHP_EOL, $binding->getRole());

        foreach ($binding->getMembers() as $member) {
            printf('- %s' . PHP_EOL, $member);
        }
    }

    return $policy;
}

Python

このコードを実行するには、まず Python 開発環境を設定し、Cloud KMS Python SDK をインストールします。

from google.cloud import kms
from google.iam.v1 import policy_pb2 as iam_policy


def iam_get_policy(
    project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> iam_policy.Policy:
    """
    Get the IAM policy for a resource.

    Args:
        project_id (string): Google Cloud project ID (e.g. 'my-project').
        location_id (string): Cloud KMS location (e.g. 'us-east1').
        key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
        key_id (string): ID of the key to use (e.g. 'my-key').

    Returns:
        Policy: Cloud IAM policy.

    """

    # Create the client.
    client = kms.KeyManagementServiceClient()

    # Build the resource name.
    resource_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)

    # The resource name could also be a key ring.
    # resource_name = client.key_ring_path(project_id, location_id, key_ring_id);

    # Get the current policy.
    policy = client.get_iam_policy(request={"resource": resource_name})

    # Print the policy
    print(f"IAM policy for {resource_name}")
    for binding in policy.bindings:
        print(binding.role)
        for member in binding.members:
            print(f"- {member}")

    return policy

Ruby

このコードを実行するには、まず Ruby 開発環境を設定し、Cloud KMS Ruby SDK をインストールします。

# TODO(developer): uncomment these values before running the sample.
# project_id  = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# key_id      = "my-key"

# Require the library.
require "google/cloud/kms"

# Create the client.
client = Google::Cloud::Kms.key_management_service

# Build the resource name.
resource_name = client.crypto_key_path project:    project_id,
                                       location:   location_id,
                                       key_ring:   key_ring_id,
                                       crypto_key: key_id

# The resource name could also be a key ring.
# resource_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id

# Create the IAM client.
iam_client = Google::Cloud::Kms::V1::IAMPolicy::Client.new

# Get the current IAM policy.
policy = iam_client.get_iam_policy resource: resource_name

# Print the policy.
puts "Policy for #{resource_name}"
policy.bindings.each do |bind|
  puts bind.role
  bind.members.each do |member|
    puts "- #{member}"
  end
end

最小権限の原則

最小権限の原則を実践するには、最も狭い権限セットをリソース階層内の最下位オブジェクトに付与します。

  • データを暗号化する権限をプリンシパルに付与するには(復号は不可)、鍵に対する roles/cloudkms.cryptoKeyEncrypter ロールを付与します。

  • データの暗号化と復号の権限をプリンシパルに付与するには、鍵に対する roles/cloudkms.cryptoKeyEncrypterDecrypter ロールを付与します。

  • データを検証する権限をプリンシパルに付与するには(署名は不可)、鍵に対する roles/cloudkms.publicKeyViewer ロールを付与します。

  • データの署名と検証の権限をプリンシパルに付与するには、鍵に対する roles/cloudkms.signerVerifier ロールを付与します。

  • 鍵を管理する権限をプリンシパルに付与するには、鍵に対する roles/cloudkms.admin ロールを付与します。

他にもいろいろな使い方があります。権限とロールの完全なリストについては、Cloud KMS の権限とロールをご覧ください。

階層と継承

ポリシー バインディングは、プロジェクト、鍵リング、鍵、インポート ジョブ、その他の Cloud KMS リソースで指定できます。

鍵は鍵リングに属し、鍵リングはプロジェクトに属するため、その階層の上位レベルで特定のロールまたは権限を持つプリンシパルは、子リソースに対して同じ権限を継承します。つまり、あるプロジェクトに対して owner ロールを持つユーザーは、そのプロジェクトのすべての鍵リングおよび鍵に対しても owner になります。同様に、あるユーザーに鍵リングの cloudkms.admin ロールが付与されている場合、その鍵リングに含まれるすべての鍵についても関連する権限が付与されます。

その逆は当てはまりません。つまり、鍵に対する権限はあっても、親キーリングに対する権限がないユーザーには、そのキーリングに対する権限はありません。

次のステップ