Usa IAM con Cloud KMS

Las claves y los llaveros de claves son recursos de Google Cloud Platform y se les pueden configurar políticas de IAM como a cualquier otro recurso. Las políticas de IAM no se pueden configurar en versiones individuales. Las acciones de Cloud KMS tienen un permiso correspondiente para determinar quién tiene acceso. Consulta Permisos y funciones para ver una lista completa de las acciones y los permisos.

Modifica los permisos de IAM

Cambiar los permisos de IAM requiere que un usuario tenga el permiso para configurar la política de IAM. Según el gráfico en Permisos y funciones, actualmente, eso solo es posible para las cuentas de usuario o servicio con la función owner o cloudkms.admin.

Línea de comandos

Agrega un usuario USER_EMAIL a la función ROLE_NAME del proyecto PROJECT_NAME.

gcloud projects add-iam-policy-binding PROJECT_NAME \
  --member user:USER_EMAIL --role roles/ROLE_NAME

Windows cmd.exe

Agrega un usuario USER_EMAIL a la función ROLE_NAME del proyecto PROJECT_NAME.

gcloud projects add-iam-policy-binding PROJECT_NAME ^
  --member user:USER_EMAIL --role roles/ROLE_NAME

PowerShell

Agrega un usuario USER_EMAIL a la función ROLE_NAME del proyecto PROJECT_NAME.
gcloud projects add-iam-policy-binding PROJECT_NAME `
  --member user:USER_EMAIL --role roles/ROLE_NAME

Línea de comandos

Quita un usuario USER_EMAIL de la función ROLE_NAME del proyecto PROJECT_NAME.

gcloud projects remove-iam-policy-binding PROJECT_NAME \
  --member user:USER_EMAIL --role roles/ROLE_NAME

Windows cmd.exe

Quita un usuario USER_EMAIL de la función ROLE_NAME del proyecto PROJECT_NAME.

gcloud projects remove-iam-policy-binding PROJECT_NAME ^
  --member user:USER_EMAIL --role roles/ROLE_NAME

PowerShell

Quita un usuario USER_EMAIL de la función ROLE_NAME del proyecto PROJECT_NAME.

gcloud projects remove-iam-policy-binding PROJECT_NAME `
  --member user:USER_EMAIL --role roles/ROLE_NAME

En nuestra documentación de IAM hay instrucciones adicionales disponibles sobre cómo usar la herramienta de línea de comandos de gcloud para las políticas de IAM.

Jerarquía y herencia

Las vinculaciones de políticas se pueden especificar a nivel de proyecto, como se demuestra anteriormente, pero también se pueden especificar en las claves y los llaveros de claves. Los miembros siguen el formato user:USER_EMAIL para los usuarios y el formato serviceAccount:SERVICE_ACCOUNT_EMAIL para las cuentas de servicio. Las funciones siguen el formato roles/ROLE_NAME. El siguiente ejemplo agrega un miembro a una clave de una función específica:

Línea de comandos

gcloud kms keys add-iam-policy-binding [KEY] --location [LOCATION] \
  --keyring [KEYRING] --member user:USER_EMAIL --role roles/ROLE_NAME

C#

      public static object AddMemberToCryptoKeyPolicy(string projectId, string locationId,
          string keyRingId, string cryptoKeyId, string role, string member)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for updating the crypto key IAM policy.
          var parent = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}/cryptoKeys/{cryptoKeyId}";
          SetIamPolicyRequest setIamPolicyRequest = new SetIamPolicyRequest();
          var result = cloudKms.Projects.Locations.KeyRings.CryptoKeys.GetIamPolicy(parent).Execute();
          if (result.Bindings != null)
          {
              // Policy already exists, so add a new Binding to it.
              Binding bindingToAdd = new Binding();
              bindingToAdd.Role = role;
              string[] testMembers = { member };
              bindingToAdd.Members = testMembers;
              result.Bindings.Add(bindingToAdd);
              setIamPolicyRequest.Policy = result;
          }
          else
          {
              // Policy does not yet exist, so create a new one.
              Policy newPolicy = new Policy();
              newPolicy.Bindings = new List<Binding>();
              Binding bindingToAdd = new Binding();
              bindingToAdd.Role = role;
              string[] testMembers = { member };
              bindingToAdd.Members = testMembers;
              newPolicy.Bindings.Add(bindingToAdd);
              setIamPolicyRequest.Policy = newPolicy;
          }
          var request = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource
              .SetIamPolicyRequest(cloudKms, setIamPolicyRequest, parent);
          var setIamPolicyResult = request.Execute();
          var updateResult = cloudKms.Projects.Locations.KeyRings.CryptoKeys.GetIamPolicy(parent).Execute();
          updateResult.Bindings.ToList().ForEach(response =>
          {
              Console.WriteLine($"Role: {response.Role}");
              response.Members.ToList().ForEach(memberFound =>
              {
                  Console.WriteLine($"  Member: {memberFound}");
              });
          });
          return 0;
      }

Go

func addMemberCryptoKeyPolicy(project, keyRing, key, role, member string) error {
	ctx := context.Background()
	authedClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return err
	}
	client, err := cloudkms.New(authedClient)
	if err != nil {
		return err
	}
	location := "global"
	parent := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeyVersions/%s",
		project, location, keyRing, key)

	policy, err := client.Projects.Locations.KeyRings.CryptoKeys.GetIamPolicy(parent).Do()
	if err != nil {
		return err
	}
	policy.Bindings = append(policy.Bindings, &cloudkms.Binding{
		Role:    role,
		Members: []string{member},
	})
	if err != nil {
		return err
	}

	_, err = client.Projects.Locations.KeyRings.CryptoKeys.SetIamPolicy(
		parent, &cloudkms.SetIamPolicyRequest{
			Policy: policy,
		}).Do()
	if err != nil {
		return err
	}

	return nil
}

Java

/**
 * Adds the given member to the given key, with the given role.
 *
 * @param projectId The id of the project.
 * @param locationId The location id of the key.
 * @param keyRingId The id of the keyring.
 * @param cryptoKeyId The id of the crypto key.
 * @param member The member to add. Must be in the proper format, eg:
 *
 * allUsers user:$userEmail serviceAccount:$serviceAccountEmail
 *
 * See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
 * @param role Must be in one of the following formats: roles/[role]
 * organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
 *
 * See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
 */
public static Policy addMemberToCryptoKeyPolicy(
    String projectId, String locationId, String keyRingId, String cryptoKeyId, String member,
    String role)
    throws IOException {
  // Create the Cloud KMS client.
  CloudKMS kms = createAuthorizedClient();

  // The resource name of the cryptoKey version
  String cryptoKey = String.format(
      "projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
      projectId, locationId, keyRingId, cryptoKeyId);

  // Get the current IAM policy
  Policy iamPolicy = getCryptoKeyPolicy(projectId, locationId, keyRingId, cryptoKeyId);

  // Add the new account to it.
  Binding newBinding = new Binding()
      .setRole(role)
      .setMembers(Collections.singletonList(member));
  List<Binding> bindings = iamPolicy.getBindings();
  if (null == bindings) {
    bindings = Collections.singletonList(newBinding);
  } else {
    bindings.add(newBinding);
  }
  iamPolicy.setBindings(bindings);

  // Set the new IAM Policy.
  Policy newIamPolicy = kms.projects().locations().keyRings()
      .cryptoKeys()
      .setIamPolicy(cryptoKey, new SetIamPolicyRequest().setPolicy(iamPolicy))
      .execute();

  System.out.println("Response: " + newIamPolicy);
  return newIamPolicy;
}

Node.js

async function addMemberToCryptoKeyPolicy(
  projectId = 'your-project-id', // Your GCP Project Id
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  cryptoKeyId = 'my-key', // Name of the crypto key
  member = 'user:dev@example.com', // Member to add to the crypto key
  role = 'roles/viewer' // Role to give the member
) {
  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the crypto key's key ring
  const locationId = 'global';

  // Get the full path to the crypto key
  const resource = client.cryptoKeyPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId
  );

  // Gets the IAM policy of a crypto key
  const [result] = await client.getIamPolicy({resource});
  let policy = Object.assign({bindings: []}, result);
  const index = policy.bindings.findIndex(binding => binding.role === role);

  // Add the role/member combo to the policy
  const members = [];
  const binding = Object.assign({role, members}, policy.bindings[index]);
  if (index === -1) {
    policy.bindings.push(binding);
  }
  if (!binding.members.includes(member)) {
    binding.members.push(member);
  }

  // Adds the member/role combo to the policy of the crypto key
  [policy] = await client.setIamPolicy({resource, policy});
  console.log(
    `${member}/${role} combo added to policy for crypto key ${cryptoKeyId}.`
  );
  if (policy.bindings) {
    policy.bindings.forEach(binding => {
      if (binding.members && binding.members.length) {
        console.log(`${binding.role}:`);
        binding.members.forEach(member => {
          console.log(`  ${member}`);
        });
      }
    });
  } else {
    console.log(`Policy for crypto key ${cryptoKeyId} is empty.`);
  }
}

PHP

/**
 * Add a member to a CryptoKey IAM policy.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $cryptoKeyId
 * @param string $member Must be in the format "user:$userEmail" or
 *        "serviceAccount:$serviceAccountEmail"
 * @param string $role Must be in the format "roles/$role",
 *        "organizations/$organizationId/roles/$role", or "projects/$projectId/roles/$role"
 * @param string $locationId
 * @return null
 */
function add_member_to_cryptokey_policy($projectId, $keyRingId, $cryptoKeyId, $member, $role, $locationId)
{
    // Instantiate the client, authenticate, and add scopes.
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');

    // Create the Cloud KMS client.
    $kms = new Google_Service_CloudKMS($client);

    // The resource name of the CryptoKey.
    $parent = sprintf('projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s',
        $projectId,
        $locationId,
        $keyRingId,
        $cryptoKeyId
    );

    // Get the current IAM policy and add the new account to it.
    $policy = $kms->projects_locations_keyRings_cryptoKeys->getIamPolicy($parent);
    $bindings = $policy->getBindings();
    $bindings[] = new Google_Service_CloudKMS_Binding([
        'members' => [$member],
        'role' => $role,
    ]);
    $policy->setBindings($bindings);

    // Set the new IAM Policy.
    $request = new Google_Service_CloudKMS_SetIamPolicyRequest(['policy' => $policy]);
    $kms->projects_locations_keyRings_cryptoKeys->setIamPolicy(
        $parent,
        $request
    );

    printf('Member %s added to policy for cryptoKey %s in keyRing %s' . PHP_EOL, $member, $cryptoKeyId, $keyRingId);
}

Python

def add_member_to_crypto_key_policy(
        project_id, location_id, key_ring_id, crypto_key_id, member, role):
    """Adds a member with a given role to the Identity and Access Management
    (IAM) policy for a given CryptoKey associated with a KeyRing."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the CryptoKey.
    parent = 'projects/{}/locations/{}/keyRings/{}/cryptoKeys/{}'.format(
        project_id, location_id, key_ring_id, crypto_key_id)

    # Get the current IAM policy and add the new member to it.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    policy_request = crypto_keys.getIamPolicy(resource=parent)
    policy_response = policy_request.execute()
    bindings = []
    if 'bindings' in policy_response.keys():
        bindings = policy_response['bindings']
    members = []
    members.append(member)
    new_binding = dict()
    new_binding['role'] = role
    new_binding['members'] = members
    bindings.append(new_binding)
    policy_response['bindings'] = bindings

    # Set the new IAM Policy.
    crypto_keys = kms_client.projects().locations().keyRings().cryptoKeys()
    request = crypto_keys.setIamPolicy(
        resource=parent, body={'policy': policy_response})
    request.execute()

    print_msg = (
        'Member {} added with role {} to policy for CryptoKey {} in KeyRing {}'
        .format(member, role, crypto_key_id, key_ring_id))
    print(print_msg)

Ruby

# project_id    = "Your Google Cloud project ID"
# location_id   = "The location of the key ring"
# key_ring_id   = "The ID of the key ring"
# crypto_key_id = "The ID of the crypto key"
# member        = "Member to add to the crypto key policy"
# role          = "Role assignment for new member"

require "google/apis/cloudkms_v1"

# Initialize the client and authenticate with the specified scope
Cloudkms = Google::Apis::CloudkmsV1
kms_client = Cloudkms::CloudKMSService.new
kms_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the crypto key
resource = "projects/#{project_id}/locations/#{location_id}/" +
           "keyRings/#{key_ring_id}/cryptoKeys/#{crypto_key_id}"

# Get the current IAM policy
policy = kms_client.get_project_location_key_ring_crypto_key_iam_policy resource

# Add new member to current bindings
policy.bindings ||= []
policy.bindings << Cloudkms::Binding.new(members: [member], role: role)

# Update IAM policy
policy_request = Cloudkms::SetIamPolicyRequest.new policy: policy
kms_client.set_crypto_key_iam_policy resource, policy_request

puts "Member #{member} added to policy for " +
     "crypto key #{crypto_key_id} in key ring #{key_ring_id}"

Para agregar una vinculación de política a nivel del llavero de claves, haz lo siguiente:

Línea de comandos

gcloud kms keyrings add-iam-policy-binding [KEYRING] --location [LOCATION] \
  --member user:USER_EMAIL --role roles/ROLE_NAME

C#

      public static object AddMemberToKeyRingPolicy(string projectId, string locationId,
          string keyRingId, string role, string member)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for updating the key ring IAM policy.
          var parent = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}";
          SetIamPolicyRequest setIamPolicyRequest = new SetIamPolicyRequest();
          var result = cloudKms.Projects.Locations.KeyRings.GetIamPolicy(parent).Execute();
          if (result.Bindings != null)
          {
              // Policy already exists, so add a new Binding to it.
              Binding bindingToAdd = new Binding();
              bindingToAdd.Role = role;
              string[] testMembers = { member };
              bindingToAdd.Members = testMembers;
              result.Bindings.Add(bindingToAdd);
              setIamPolicyRequest.Policy = result;
          }
          else
          {
              // Policy does not yet exist, so create a new one
              Policy newPolicy = new Policy();
              newPolicy.Bindings = new List<Binding>();
              Binding bindingToAdd = new Binding();
              bindingToAdd.Role = role;
              string[] testMembers = { member };
              bindingToAdd.Members = testMembers;
              newPolicy.Bindings.Add(bindingToAdd);
              setIamPolicyRequest.Policy = newPolicy;
          }
          var request = new ProjectsResource.LocationsResource.KeyRingsResource
              .SetIamPolicyRequest(cloudKms, setIamPolicyRequest, parent);
          var setIamPolicyResult = request.Execute();
          var updateResult = cloudKms.Projects.Locations.KeyRings.GetIamPolicy(parent).Execute();
          updateResult.Bindings.ToList().ForEach(response =>
          {
              Console.WriteLine($"Role: {response.Role}");
              response.Members.ToList().ForEach(memberFound =>
              {
                  Console.WriteLine($"  Member: {memberFound}");
              });
          });
          return 0;
      }

Go

func addMemberRingPolicy(project, location, keyRing, role, member string) error {
	ctx := context.Background()
	authedClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return err
	}
	client, err := cloudkms.New(authedClient)
	if err != nil {
		return err
	}

	parent := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s",
		project, location, keyRing)

	policy, err := client.Projects.Locations.KeyRings.GetIamPolicy(parent).Do()
	if err != nil {
		return err
	}
	policy.Bindings = append(policy.Bindings, &cloudkms.Binding{
		Role:    role,
		Members: []string{member},
	})
	if err != nil {
		return err
	}

	_, err = client.Projects.Locations.KeyRings.SetIamPolicy(
		parent, &cloudkms.SetIamPolicyRequest{
			Policy: policy,
		}).Do()
	if err != nil {
		return err
	}

	return nil
}

Java

/**
 * Adds the given member to the given keyring, with the given role.
 *
 * @param projectId The id of the project.
 * @param locationId The location id of the key.
 * @param keyRingId The id of the keyring.
 * @param member The member to add. Must be in the proper format, eg:
 *
 * allUsers user:$userEmail serviceAccount:$serviceAccountEmail
 *
 * See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
 * @param role Must be in one of the following formats: roles/[role]
 * organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
 *
 * See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
 */
public static Policy addMemberToKeyRingPolicy(
    String projectId, String locationId, String keyRingId, String member, String role)
    throws IOException {
  // Create the Cloud KMS client.
  CloudKMS kms = createAuthorizedClient();

  // The resource name of the keyring version
  String keyring = String.format(
      "projects/%s/locations/%s/keyRings/%s",
      projectId, locationId, keyRingId);

  // Get the current IAM policy
  Policy iamPolicy = getKeyRingPolicy(projectId, locationId, keyRingId);

  // Add the new account to it.
  Binding newBinding = new Binding()
      .setRole(role)
      .setMembers(Collections.singletonList(member));
  List<Binding> bindings = iamPolicy.getBindings();
  if (null == bindings) {
    bindings = Collections.singletonList(newBinding);
  } else {
    bindings.add(newBinding);
  }
  iamPolicy.setBindings(bindings);

  // Set the new IAM Policy.
  Policy newIamPolicy = kms.projects().locations()
      .keyRings()
      .setIamPolicy(keyring, new SetIamPolicyRequest().setPolicy(iamPolicy))
      .execute();

  System.out.println("Response: " + newIamPolicy);
  return newIamPolicy;
}

Node.js

async function addMemberToKeyRingPolicy(
  projectId = 'your-project-id', // Your GCP projectId
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  member = 'user:dev@example.com', // Member to add to the crypto key
  role = 'roles/viewer' // Role to give the member
) {
  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the key ring, e.g. "global"
  const locationId = 'global';

  // Get the full path to the keyring
  const resource = client.keyRingPath(projectId, locationId, keyRingId);

  // Gets the IAM policy of a key ring
  let [policy] = await client.getIamPolicy({resource});
  policy.bindings = policy.bindings || [];

  // find the index of the binding matching the requested role
  const index = policy.bindings.findIndex(binding => binding.role === role);

  // Add the role/member combo to the policy
  const members = [];
  const binding = Object.assign({role}, {members}, policy.bindings[index]);
  if (index === -1) {
    policy.bindings.push(binding);
  }
  if (!binding.members.includes(member)) {
    binding.members.push(member);
  }

  // Adds the member/role combo to the policy of the key ring
  [policy] = await client.setIamPolicy({resource, policy});
  console.log(
    `${member}/${role} combo added to policy for key ring ${keyRingId}.`
  );
  if (policy.bindings) {
    policy.bindings.forEach(binding => {
      if (binding.members && binding.members.length) {
        console.log(`${binding.role}:`);
        binding.members.forEach(member => {
          console.log(`  ${member}`);
        });
      }
    });
  } else {
    console.log(`Policy for key ring ${keyRingId} is empty.`);
  }
}

PHP

/**
 * Add a member to a KeyRing IAM policy.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $member Must be in the format "user:$userEmail" or
 *        "serviceAccount:$serviceAccountEmail"
 * @param string $role Must be in the format "roles/$role",
 *        "organizations/$organizationId/roles/$role", or "projects/$projectId/roles/$role"
 * @param string $locationId [optional]
 * @return null
 */
function add_member_to_keyring_policy($projectId, $keyRingId, $member, $role, $locationId = 'global')
{
    // Instantiate the client, authenticate, and add scopes.
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');

    // Create the Cloud KMS client.
    $kms = new Google_Service_CloudKMS($client);

    // The resource name of the KeyRing.
    $parent = sprintf('projects/%s/locations/%s/keyRings/%s',
        $projectId,
        $locationId,
        $keyRingId
    );

    // Get the current IAM policy and add the new account to it.
    $policy = $kms->projects_locations_keyRings->getIamPolicy($parent);
    $bindings = $policy->getBindings();
    $bindings[] = new Google_Service_CloudKMS_Binding([
        'members' => [$member],
        'role' => $role,
    ]);
    $policy->setBindings($bindings);

    // Set the new IAM Policy.
    $request = new Google_Service_CloudKMS_SetIamPolicyRequest(['policy' => $policy]);
    $kms->projects_locations_keyRings->setIamPolicy(
        $parent,
        $request
    );

    printf('Member %s added to policy for keyRing %s' . PHP_EOL, $member, $keyRingId);
}

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The location of the key ring"
# key_ring_id = "The ID of the key ring"
# member      = "Member to add to the key ring policy"
# role        = "Role assignment for new member"

require "google/apis/cloudkms_v1"

# Initialize the client and authenticate with the specified scope
Cloudkms = Google::Apis::CloudkmsV1
kms_client = Cloudkms::CloudKMSService.new
kms_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the key ring
resource = "projects/#{project_id}/locations/#{location_id}/" +
           "keyRings/#{key_ring_id}"

# Get the current IAM policy
policy = kms_client.get_project_location_key_ring_iam_policy resource

# Add new member to current bindings
policy.bindings ||= []
policy.bindings << Cloudkms::Binding.new(members: [member], role: role)

# Update IAM policy
policy_request = Cloudkms::SetIamPolicyRequest.new policy: policy
kms_client.set_key_ring_iam_policy resource, policy_request

puts "Member #{member} added to policy for " +
     "key ring #{key_ring_id}"

Debido a que las claves pertenecen a llaveros de claves y estos, a su vez, pertenecen a proyectos, un usuario con una función o un permiso específico en el nivel más alto de esa jerarquía hereda los mismos permisos en los recursos secundarios. En otras palabras, un usuario que tiene la función de owner en un proyecto también es un owner en todos los llaveros de claves y las claves de ese proyecto. De manera similar, si un usuario recibe la función de cloudkms.admin en un llavero de claves, tiene los permisos asociados para las claves de ese llavero de claves.

Lo inverso no ocurre, es decir, un usuario con un permiso para una clave a quien no se le otorgó un permiso en el llavero de claves superior no tiene permisos para ese llavero.

Si es necesario, se puede quitar a un miembro y una función de una política de clave o llavero de claves, como se muestra a continuación:

Línea de comandos

gcloud kms keys remove-iam-policy-binding [KEY] --location [LOCATION] \
  --keyring [KEYRING] --member user:USER_EMAIL --role roles/ROLE_NAME

C#

      public static object RemoveMemberFromCryptoKeyPolicy(string projectId, string locationId,
          string keyRingId, string cryptoKeyId, string role, string member)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for updating the crypto key IAM policy.
          var parent = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}/cryptoKeys/{cryptoKeyId}";
          var result = cloudKms.Projects.Locations.KeyRings.CryptoKeys.GetIamPolicy(parent).Execute();
          if (result.Bindings != null)
          {
              result.Bindings.ToList().ForEach(response =>
              {
                  if (response.Role == role)
                  {
                      // Remove the role/member combo from the crypto key IAM policy.
                      response.Members = response.Members.Where(m => m != member).ToList();
                  }
              });
              // Set the modified crypto key IAM policy to be the cryto key's current IAM policy.
              SetIamPolicyRequest setIamPolicyRequest = new SetIamPolicyRequest();
              setIamPolicyRequest.Policy = result;
              var request = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource
                  .SetIamPolicyRequest(cloudKms, setIamPolicyRequest, parent);
              var setIamPolicyResult = request.Execute();
              // Get and display the modified crypto key IAM policy.
              var resultAfterUpdate = cloudKms.Projects.Locations.KeyRings.CryptoKeys.GetIamPolicy(parent).Execute();
              if (resultAfterUpdate.Bindings != null)
              {
                  Console.WriteLine($"Policy Bindings: {resultAfterUpdate.Bindings}");
                  resultAfterUpdate.Bindings.ToList().ForEach(response =>
                  {
                      Console.WriteLine($"Role: {response.Role}");
                      response.Members.ToList().ForEach(memberAfterUpdate =>
                      {
                          Console.WriteLine($"  Member: {memberAfterUpdate}");
                      });
                  });
              }
              else
              {
                  Console.WriteLine($"Empty IAM policy found for CryptoKey: {parent}");
              }
          }
          else
          {
              Console.WriteLine($"Empty IAM policy found for CryptoKey: {parent}");
          }
          return 0;
      }

Go

func getCryptoKeyPolicy(project, keyRing, key string) error {
	ctx := context.Background()
	authedClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return err
	}
	client, err := cloudkms.New(authedClient)
	if err != nil {
		return err
	}
	location := "global"
	parent := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeyVersions/%s",
		project, location, keyRing, key)

	policy, err := client.Projects.Locations.KeyRings.CryptoKeys.GetIamPolicy(parent).Do()
	if err != nil {
		return err
	}
	for _, binding := range policy.Bindings {
		log.Printf("Role: %s\n", binding.Role)
		log.Printf("Members: %v\n", binding.Members)
	}

	return nil
}

Java

/**
 * Removes the given member from the given policy.
 */
public static Policy removeMemberFromCryptoKeyPolicy(
    String projectId, String locationId, String keyRingId, String cryptoKeyId, String member,
    String role)
    throws IOException {
  // Create the Cloud KMS client.
  CloudKMS kms = createAuthorizedClient();

  // The resource name of the cryptoKey
  String cryptoKey = String.format(
      "projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s",
      projectId, locationId, keyRingId, cryptoKeyId);

  // Get the current IAM policy and add the new account to it.
  Policy iamPolicy = getCryptoKeyPolicy(projectId, locationId, keyRingId, cryptoKeyId);

  if (null == iamPolicy.getBindings()) {
    // Nothing to remove
    return null;
  }

  // Filter out the given member
  for (Binding b : iamPolicy.getBindings()) {
    if (role.equals(b.getRole()) && b.getMembers().contains(member)) {
      b.getMembers().removeAll(Collections.singletonList(member));
      break;
    }
  }

  // Set the new IAM Policy.
  Policy newIamPolicy = kms.projects().locations().keyRings()
      .cryptoKeys()
      .setIamPolicy(cryptoKey, new SetIamPolicyRequest().setPolicy(iamPolicy))
      .execute();

  System.out.println("Response: " + newIamPolicy);
  return newIamPolicy;
}

Node.js

async function removeMemberFromCryptoKeyPolicy(
  projectId = 'your-project-id', // Your GCP projectId
  keyRingId = 'my-key-ring', // Name of the crypto key's key ring
  cryptoKeyId = 'my-key', // Name of the crypto key, e.g. "my-key"
  member = 'user:dev@example.com', // Member to add to the crypto key
  role = 'roles/viewer' // Role to give the member
) {
  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the crypto key's key ring, e.g. "global"
  const locationId = 'global';

  // Get the full path to the crypto key
  const resource = client.cryptoKeyPath(
    projectId,
    locationId,
    keyRingId,
    cryptoKeyId
  );

  // Gets the IAM policy of a crypto key
  const [result] = await client.getIamPolicy({resource});
  let policy = Object.assign({bindings: []}, result);
  const index = policy.bindings.findIndex(binding => binding.role === role);
  const members = [];
  const binding = Object.assign({role, members}, policy.bindings[index]);
  if (index === -1) {
    return;
  }
  if (!binding.members.includes(member)) {
    return;
  }

  // Remove the role/member combo from the policy
  binding.members.splice(binding.members.indexOf(member), 1);

  const request = {resource, policy};
  console.log(JSON.stringify(request, null, 2));

  // Removes the member/role combo from the policy of the crypto key
  [policy] = await client.setIamPolicy(request);
  console.log(
    `${member}/${role} combo removed from policy for crypto key ${cryptoKeyId}.`
  );
  if (policy.bindings) {
    policy.bindings.forEach(binding => {
      if (binding.members && binding.members.length) {
        console.log(`${binding.role}:`);
        binding.members.forEach(member => {
          console.log(`  ${member}`);
        });
      }
    });
  } else {
    console.log(`Policy for crypto key ${cryptoKeyId} is empty.`);
  }
}

PHP

/**
 * Remove a member from a CryptoKey IAM policy.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $cryptoKeyId
 * @param string $member Must be in the format "user:$userEmail" or
 *        "serviceAccount:$serviceAccountEmail"
 * @param string $role Must be in the format "roles/$role",
 *        "organizations/$organizationId/roles/$role", or "projects/$projectId/roles/$role"
 * @param string $locationId [optional]
 * @return null
 */
function remove_member_from_cryptokey_policy($projectId, $keyRingId, $cryptoKeyId, $member, $role, $locationId = 'global')
{
    // Instantiate the client, authenticate, and add scopes.
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');

    // Create the Cloud KMS client.
    $kms = new Google_Service_CloudKMS($client);

    // The resource name of the KeyRing associated with the CryptoKey.
    $parent = sprintf('projects/%s/locations/%s/keyRings/%s/cryptoKeys/%s',
        $projectId,
        $locationId,
        $keyRingId,
        $cryptoKeyId
    );

    // Get the current IAM policy and remove the member from it.
    $policy = $kms->projects_locations_keyRings_cryptoKeys->getIamPolicy($parent);
    foreach ($policy->getBindings() as $binding) {
        if ($binding->getRole() == $role) {
            $members = $binding->getMembers();
            if (false !== $i = array_search($member, $members)) {
                unset($members[$i]);
                $binding->setMembers($members);
                break;
            }
        }
    }

    // Set the new IAM Policy.
    $request = new Google_Service_CloudKMS_SetIamPolicyRequest(['policy' => $policy]);
    $kms->projects_locations_keyRings_cryptoKeys->setIamPolicy(
        $parent,
        $request
    );

    printf('Member %s removed from policy for cryptoKey %s in keyRing %s' . PHP_EOL,
        $member,
        $cryptoKeyId,
        $keyRingId);
}

Ruby

# project_id    = "Your Google Cloud project ID"
# location_id   = "The location of the key ring"
# key_ring_id   = "The ID of the key ring"
# crypto_key_id = "The ID of the crypto key"
# member        = "Member to remove to the crypto key policy"
# role          = "Role assignment for the member"

require "google/apis/cloudkms_v1"

# Initialize the client and authenticate with the specified scope
Cloudkms = Google::Apis::CloudkmsV1
kms_client = Cloudkms::CloudKMSService.new
kms_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the crypto key
resource = "projects/#{project_id}/locations/#{location_id}/" +
           "keyRings/#{key_ring_id}/cryptoKeys/#{crypto_key_id}"

# Get the current IAM policy
policy = kms_client.get_project_location_key_ring_crypto_key_iam_policy resource

# Remove a member to current bindings
if policy.bindings
  policy.bindings.delete_if do |binding|
    binding.role.include?(role) && binding.members.include?(member)
  end
end

# Update IAM policy
policy_request = Cloudkms::SetIamPolicyRequest.new policy: policy
kms_client.set_crypto_key_iam_policy resource, policy_request

puts "Member #{member} removed from policy for " +
     "crypto key #{crypto_key_id} in key ring #{key_ring_id}"

Otorga permisos para usar las claves

A fin de permitirle a una cuenta de usuario o servicio usar una clave para encriptar o desencriptar con una clave particular, debe tener una función de owner, cloudkms.cryptoKeyEncrypterDecrypter, cloudkms.cryptoKeyEncrypter o cloudkms.cryptoKeyDecrypter de acuerdo con el gráfico que aparece en Permisos y funciones.

Con Cloud KMS, lo más probable es que uses cuentas de servicio para realizar operaciones de clave como encriptar y desencriptar contenido. Generalmente, el correo electrónico de la cuenta de servicio se deriva del nombre de esa cuenta, en el siguiente formato:

SERVICE_ACCOUNT_NAME@PROJECT_NAME.iam.gserviceaccount.com

Línea de comandos

Por ejemplo, si accedes a Cloud KMS desde una instancia de Google Cloud Platform y creaste una cuenta de servicio my-service-account@my-project.iam.gserviceaccount.com, puedes usar la herramienta de línea de comandos de gcloud a fin de otorgarle a esa cuenta de servicio el permiso para usar la clave golden-egg en el llavero de claves golden-goose desde la ubicación global como sigue:

gcloud kms keys add-iam-policy-binding \
  golden-egg --location global --keyring golden-goose \
  --member serviceAccount:my-service-account@my-project.iam.gserviceaccount.com \
  --role roles/cloudkms.cryptoKeyEncrypterDecrypter

Windows cmd.exe

Por ejemplo, si accedes a Cloud KMS desde una instancia de Google Cloud Platform y creaste una cuenta de servicio my-service-account@my-project.iam.gserviceaccount.com, puedes usar la herramienta de línea de comandos de gcloud a fin de otorgarle a esa cuenta de servicio el permiso para usar la clave golden-egg en el llavero de claves golden-goose desde la ubicación global como sigue:

gcloud kms keys add-iam-policy-binding ^
  golden-egg --location global --keyring golden-goose ^
  --member serviceAccount:my-service-account@my-project.iam.gserviceaccount.com ^
  --role roles/cloudkms.cryptoKeyEncrypterDecrypter

PowerShell

Por ejemplo, si accedes a Cloud KMS desde una instancia de Google Cloud Platform y creaste una cuenta de servicio my-service-account@my-project.iam.gserviceaccount.com, puedes usar la herramienta de línea de comandos de gcloud a fin de otorgarle a esa cuenta de servicio el permiso para usar la clave golden-egg en el llavero de claves golden-goose desde la ubicación global como sigue:
gcloud kms keys add-iam-policy-binding `
  golden-egg --location global --keyring golden-goose `
  --member serviceAccount:my-service-account@my-project.iam.gserviceaccount.com `
  --role roles/cloudkms.cryptoKeyEncrypterDecrypter

Se pueden otorgar permisos a los usuarios para que usen la clave. En este caso, el miembro es user:USER_EMAIL en lugar de serviceAccount:SERVICE_ACCOUNT_EMAIL como se muestra a continuación:

Línea de comandos

gcloud kms keys add-iam-policy-binding \
  golden-egg --location global --keyring golden-goose \
  --member user:sillygoose@gmail.com \
  --role roles/cloudkms.cryptoKeyEncrypterDecrypter

Windows cmd.exe

gcloud kms keys add-iam-policy-binding ^
  golden-egg --location global --keyring golden-goose ^
  --member user:sillygoose@gmail.com ^
  --role roles/cloudkms.cryptoKeyEncrypterDecrypter

PowerShell

gcloud kms keys add-iam-policy-binding `
  golden-egg --location global --keyring golden-goose `
  --member user:sillygoose@gmail.com `
  --role roles/cloudkms.cryptoKeyEncrypterDecrypter

Otorga permisos para administrar claves

Para permitir que una cuenta de usuario o servicio cree o actualice las claves existentes, es necesario que tenga al menos la función de editor, de acuerdo con el gráfico anterior. La función cloudkms.admin también le permite destruir claves y configurar políticas de IAM. La función owner puede hacer todo esto y, además, puede encriptar o desencriptar contenido con una clave.

Línea de comandos

El siguiente ejemplo le da a un usuario sillygoose@gmail.com la función cloudkms.admin para la clave golden-egg en el llavero de claves golden-goose:

gcloud kms keys add-iam-policy-binding \
  golden-egg --location global --keyring golden-goose \
  --member user:sillygoose@gmail.com \
  --role roles/cloudkms.admin

Windows cmd.exe

El siguiente ejemplo le da a un usuario sillygoose@gmail.com la función cloudkms.admin para la clave golden-egg en el llavero de claves golden-goose:

gcloud kms keys add-iam-policy-binding ^
  golden-egg --location global --keyring golden-goose ^
  --member user:sillygoose@gmail.com ^
  --role roles/cloudkms.admin

PowerShell

El siguiente ejemplo le da a un usuario sillygoose@gmail.com la función cloudkms.admin para la clave golden-egg en el llavero de claves golden-goose:
gcloud kms keys add-iam-policy-binding `
  golden-egg --location global --keyring golden-goose `
  --member user:sillygoose@gmail.com `
  --role roles/cloudkms.admin

Obtén permisos existentes

Un usuario con las funciones viewer,editor, cloudkms.admin u owner puede ver la política de IAM para una clave.

Línea de comandos

Por ejemplo, para obtener la política de IAM de la clave bird en el llavero de claves hand:

gcloud kms keys get-iam-policy bird --location global \
  --keyring hand

C#

      public static object GetKeyRingIamPolicy(string projectId, string locationId, string keyRingId)
      {
          var cloudKms = CreateAuthorizedClient();
          // Generate the full path of the parent to use for getting the key ring IAM policy.
          var parent = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}";
          var result = cloudKms.Projects.Locations.KeyRings.GetIamPolicy(parent).Execute();
          if (result.Bindings != null)
          {
              Console.WriteLine($"Policy Bindings: {result.Bindings}");
              result.Bindings.ToList().ForEach(response =>
              {
                  Console.WriteLine($"Role: {response.Role}");

                  response.Members.ToList().ForEach(member =>
                  {
                      Console.WriteLine($"  Member: {member}");
                  });
              });
          }
          else
          {
              Console.WriteLine($"Empty IAM policy found for KeyRing: {parent}");
          }
          return 0;
      }

Go

func getCryptoKeyPolicy(project, keyRing, key string) error {
	ctx := context.Background()
	authedClient, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
	if err != nil {
		return err
	}
	client, err := cloudkms.New(authedClient)
	if err != nil {
		return err
	}
	location := "global"
	parent := fmt.Sprintf("projects/%s/locations/%s/keyRings/%s/cryptoKeyVersions/%s",
		project, location, keyRing, key)

	policy, err := client.Projects.Locations.KeyRings.CryptoKeys.GetIamPolicy(parent).Do()
	if err != nil {
		return err
	}
	for _, binding := range policy.Bindings {
		log.Printf("Role: %s\n", binding.Role)
		log.Printf("Members: %v\n", binding.Members)
	}

	return nil
}

Java

/**
 * Retrieves the IAM policy for the given crypto key.
 */
public static Policy getKeyRingPolicy(String projectId, String locationId, String keyRingId)
    throws IOException {
  // Create the Cloud KMS client.
  CloudKMS kms = createAuthorizedClient();

  // The resource name of the keyring
  String keyring = String.format(
      "projects/%s/locations/%s/keyRings/%s",
      projectId, locationId, keyRingId);

  // Get the current IAM policy and add the new account to it.
  Policy iamPolicy = kms.projects().locations().keyRings()
      .getIamPolicy(keyring)
      .execute();

  System.out.println(iamPolicy.getBindings());
  return iamPolicy;
}

Node.js

async function getKeyRingIamPolicy(
  projectId = 'your-project-id', // Your GCP projectId
  keyRingId = 'my-key-ring' // Name of the crypto key's key ring
) {
  // Import the library and create a client
  const kms = require('@google-cloud/kms');
  const client = new kms.KeyManagementServiceClient();

  // The location of the key ring, e.g. "global"
  const locationId = 'global';

  // Get the full path to the keyring
  const resource = client.keyRingPath(projectId, locationId, keyRingId);

  // Gets the IAM policy of a key ring
  const [policy] = await client.getIamPolicy({resource});
  if (policy.bindings && policy.bindings.length > 0) {
    policy.bindings.forEach(binding => {
      if (binding.members && binding.members.length) {
        console.log(`${binding.role}:`);
        binding.members.forEach(member => {
          console.log(`  ${member}`);
        });
      }
    });
  } else {
    console.log(`Policy for key ring ${keyRingId} is empty.`);
  }
}

PHP

/**
 * Get the IAM policy for a KeyRing.
 *
 * @param string $projectId
 * @param string $keyRingId
 * @param string $locationId [optional]
 * @return null
 */
function get_keyring_policy($projectId, $keyRingId, $locationId = 'global')
{
    // Instantiate the client, authenticate, and add scopes.
    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope('https://www.googleapis.com/auth/cloud-platform');

    // Create the Cloud KMS client.
    $kms = new Google_Service_CloudKMS($client);

    // The resource name of the location associated with the key rings.
    $parent = sprintf('projects/%s/locations/%s/keyRings/%s',
        $projectId,
        $locationId,
        $keyRingId
    );

    // Get the current IAM policy and print it.
    $policy = $kms->projects_locations_keyRings->getIamPolicy($parent);
    foreach ($policy->getBindings() as $binding) {
        printf("Role: %s\nMembers:\n%s\n",
            $binding->getRole(),
            implode("\n", $binding->getMembers())
        );
    }
}

Python

def get_key_ring_policy(project_id, location_id, key_ring_id):
    """Gets the Identity and Access Management (IAM) policy for a given KeyRing
    and prints out roles and the members assigned to those roles."""

    # Creates an API client for the KMS API.
    kms_client = googleapiclient.discovery.build('cloudkms', 'v1')

    # The resource name of the KeyRing.
    parent = 'projects/{}/locations/{}/keyRings/{}'.format(
        project_id, location_id, key_ring_id)

    # Get the current IAM policy.
    request = kms_client.projects().locations().keyRings().getIamPolicy(
        resource=parent)
    response = request.execute()

    if 'bindings' in response.keys():
        print('Printing IAM policy for resource {}:'.format(parent))
        for binding in response['bindings']:
            print('')
            print('Role: {}'.format(binding['role']))
            print('Members:')
            for member in binding['members']:
                print(member)
        print('')
    else:
        print('No roles found for resource {}.'.format(parent))

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The location of the key ring"
# key_ring_id = "The ID of the key ring"

require "google/apis/cloudkms_v1"

# Initialize the client and authenticate with the specified scope
Cloudkms = Google::Apis::CloudkmsV1
kms_client = Cloudkms::CloudKMSService.new
kms_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the key ring
resource = "projects/#{project_id}/locations/#{location_id}/" +
           "keyRings/#{key_ring_id}"

# Get the current IAM policy
policy = kms_client.get_project_location_key_ring_iam_policy resource

# Print role and associated members
if policy.bindings
  policy.bindings.each do |binding|
    puts "Role: #{binding.role} Members: #{binding.members}"
  end
else
  puts "No members"
end

¿Te sirvió esta página? Envíanos tu opinión:

Enviar comentarios sobre…

Documentación de Cloud KMS