Gerenciar o acesso a secrets regionais

Esta página descreve como gerenciar o acesso a um secret regional, incluindo o material do secret. Para saber mais sobre controles e permissões de acesso, consulte Controle de acesso com o IAM.

Funções exigidas

Para receber as permissões necessárias para gerenciar o acesso a secrets, peça ao administrador para conceder a você o Administrador do Gerenciador de segredos (roles/secretmanager.admin) do IAM no secret, projeto, pasta ou organização. Para mais informações sobre a concessão de papéis, consulte Gerenciar o acesso a projetos, pastas e organizações.

Também é possível conseguir as permissões necessárias por meio de papéis personalizados ou de outros papéis predefinidos.

Conceder acesso

Para conceder acesso a um secret, use um dos seguintes métodos:

Console

  1. Acesse a página do Secret Manager no console do Google Cloud:

    Acessar o Secret Manager

  2. Acesse a guia Secrets regionais. Para selecionar um secret, marque a caixa de seleção ao lado do nome dele.

  3. Se ela ainda não estiver aberta, clique em Mostrar painel de informações para abrir o painel.

  4. No painel de informações, clique em Adicionar participante.

  5. No campo Novos participantes, insira os endereços de e-mail dos membros que você quer adicionar.

  6. Na lista Selecionar um papel, escolha Secret Manager e, em seguida, selecione Acessador de secrets do Secret Manager.

gcloud

Antes de usar os dados do comando abaixo, faça estas substituições:

  • SECRET_ID: o ID do secret ou do identificador totalmente qualificado
  • LOCATION: o local do Google Cloud do segredo
  • MEMBER: o membro do IAM, como um usuário, grupo ou conta de serviço

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

ggcloud secrets add-iam-policy-binding SECRET_ID --location=LOCATION \
    --member="MEMBER" \
    --role="roles/secretmanager.secretAccessor"

Windows (PowerShell)

ggcloud secrets add-iam-policy-binding SECRET_ID --location=LOCATION `
    --member="MEMBER" `
    --role="roles/secretmanager.secretAccessor"

Windows (cmd.exe)

ggcloud secrets add-iam-policy-binding SECRET_ID --location=LOCATION ^
    --member="MEMBER" ^
    --role="roles/secretmanager.secretAccessor"

REST

Observação: diferentemente dos outros exemplos, isso substitui toda a política do IAM.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • LOCATION: o local do Google Cloud do segredo
  • PROJECT_ID: o projeto do Google Cloud que contém o segredo
  • SECRET_ID: o ID do secret ou do identificador totalmente qualificado
  • MEMBER: o membro do IAM, como um usuário, grupo ou conta de serviço

Método HTTP e URL:

POST https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID:setIamPolicy

Corpo JSON da solicitação:

{"policy": {"bindings": [{"members": ["MEMBER"], "role": "roles/secretmanager.secretAccessor"}]}}

Para enviar a solicitação, escolha uma destas opções:

curl

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID:setIamPolicy"

PowerShell

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID:setIamPolicy" | Select-Object -Expand Content

Você receberá uma resposta JSON semelhante a esta:

{
  "version": 1,
  "etag": "BwYhOrAmWFQ=",
  "bindings": [
    {
      "role": "roles/secretmanager.secretAccessor",
      "members": [
        "user:username@google.com"
      ]
    }
  ]
}

Go

Para executar esse código, primeiro configure um ambiente de desenvolvimento do Go e instale o SDK do Go do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do cloud-platform.

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"google.golang.org/api/option"
)

// iamGrantAccess grants the given member access to the secret.
func IamGrantAccessWithRegionalSecret(w io.Writer, projectId, locationId, secretId, member string) error {
	// name := "projects/my-project/locations/my-location/secrets/my-secret"
	// member := "user:foo@example.com"

	// Create the client.
	ctx := context.Background()
	//Endpoint to send the request to regional server
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationId)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))

	if err != nil {
		return fmt.Errorf("failed to create regional secretmanager client: %w", err)
	}
	defer client.Close()

	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s", projectId, locationId, secretId)
	// Get the current IAM policy.
	handle := client.IAM(name)
	policy, err := handle.Policy(ctx)
	if err != nil {
		return fmt.Errorf("failed to get policy: %w", err)
	}

	// Grant the member access permissions.
	policy.Add(member, "roles/secretmanager.secretAccessor")
	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

Para executar esse código, primeiro configure um ambiente de desenvolvimento do Java e instale o SDK do Java do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do cloud-platform.

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import java.io.IOException;

public class IamGrantAccessWithRegionalSecret {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Your GCP project ID.
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // Resource ID of the secret to grant access to.
    String secretId = "your-secret-id";
    // IAM member, such as a user group or service account you want to grant access.
    String member = "user:foo@example.com";
    iamGrantAccessWithRegionalSecret(projectId, locationId, secretId, member);
  }

  // Grant a member access to a particular secret.
  public static Policy iamGrantAccessWithRegionalSecret(
      String projectId, String locationId, String secretId, String member)
      throws IOException {

    // Endpoint to call the regional secret manager sever
    String apiEndpoint = String.format("secretmanager.%s.rep.googleapis.com:443", locationId);
    SecretManagerServiceSettings secretManagerServiceSettings =
        SecretManagerServiceSettings.newBuilder().setEndpoint(apiEndpoint).build();

    // Initialize the client that will be used to send requests. This client only needs to be
    // created once, and can be reused for multiple requests.
    try (SecretManagerServiceClient client = 
        SecretManagerServiceClient.create(secretManagerServiceSettings)) {
      // Build the name from the version.
      SecretName secretName = 
          SecretName.ofProjectLocationSecretName(projectId, locationId, secretId);

      // Request the current IAM policy.
      Policy currentPolicy =
          client.getIamPolicy(
              GetIamPolicyRequest.newBuilder().setResource(secretName.toString()).build());

      // Build the new binding.
      Binding binding =
          Binding.newBuilder()
              .setRole("roles/secretmanager.secretAccessor")
              .addMembers(member)
              .build();

      // Create a new IAM policy from the current policy, adding the binding.
      Policy newPolicy = Policy.newBuilder().mergeFrom(currentPolicy).addBindings(binding).build();

      // Save the updated IAM policy.
      Policy updatedPolicy = client.setIamPolicy(
          SetIamPolicyRequest.newBuilder()
              .setResource(secretName.toString())
              .setPolicy(newPolicy)
              .build());

      System.out.printf("Updated IAM policy for %s\n", secretId);

      return updatedPolicy;
    }
  }
}

Node.js

Para executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Node.js do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do cloud-platform.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'my-location';
// const secretId = 'my-secret';
// const member = 'user:you@example.com';
//
// NOTE: Each member must be prefixed with its type. See the IAM documentation
// for more information: https://cloud.google.com/iam/docs/overview.

const name = `projects/${projectId}/locations/${locationId}/secrets/${secretId}`;

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Adding the endpoint to call the regional secret manager sever
const options = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;

// Instantiates a client
const client = new SecretManagerServiceClient(options);

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

  // Add the user with accessor permissions to the bindings list.
  policy.bindings.push({
    role: 'roles/secretmanager.secretAccessor',
    members: [member],
  });

  // Save the updated IAM policy.
  await client.setIamPolicy({
    resource: name,
    policy: policy,
  });

  console.log(`Updated IAM policy for ${name}`);
}

grantAccessRegionalSecret();

Python

Para executar esse código, primeiro configure um ambiente de desenvolvimento do Python e instale o SDK do Python do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do cloud-platform.

# Import the Secret Manager client library.
from google import iam
from google.cloud import secretmanager_v1


def iam_grant_access_with_regional_secret(
    project_id: str,
    location_id: str,
    secret_id: str,
    member: str,
) -> iam.v1.iam_policy_pb2.SetIamPolicyRequest:
    """
    Grants the given member access to a secret.
    """

    # Endpoint to call the regional secret manager sever.
    api_endpoint = f"secretmanager.{location_id}.rep.googleapis.com"

    # Create the Secret Manager client.
    client = secretmanager_v1.SecretManagerServiceClient(
        client_options={"api_endpoint": api_endpoint},
    )

    # Build the resource name of the secret.
    name = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}"

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

    # Add the given member with access permissions.
    policy.bindings.add(role="roles/secretmanager.secretAccessor", members=[member])

    # Update the IAM Policy.
    new_policy = client.set_iam_policy(request={"resource": name, "policy": policy})

    # Print data about the secret.
    print(f"Updated IAM policy on {secret_id}")

    return new_policy

Revogação do acesso

Para revogar o acesso a um secret, use um dos seguintes métodos:

Console

  1. Acesse a página do Secret Manager no console do Google Cloud:

    Acessar o Secret Manager

  2. Acesse a guia Secrets regionais. Para selecionar um secret, marque a caixa de seleção ao lado do nome dele.

  3. Se ela ainda não estiver aberta, clique em Mostrar painel de informações para abrir o painel.

  4. No painel de informações, clique na seta de expansão ao lado do função do usuário para conferir uma lista dos usuários ou das contas de serviço com acesso a esse papel.

  5. Para remover a conta de usuário ou de serviço, clique em Excluir ao lado da conta de serviço ou do ID do usuário.

  6. Na caixa de diálogo de confirmação que aparece, clique em Remover.

gcloud

Antes de usar os dados do comando abaixo, faça estas substituições:

  • SECRET_ID: o ID do secret ou do identificador totalmente qualificado
  • LOCATION: o local do Google Cloud do segredo
  • MEMBER: o membro do IAM, como um usuário, grupo ou conta de serviço

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

gcloud secrets remove-iam-policy-binding SECRET_ID --location=LOCATION \
    --member="MEMBER" \
    --role="roles/secretmanager.secretAccessor"

Windows (PowerShell)

gcloud secrets remove-iam-policy-binding SECRET_ID --location=LOCATION `
    --member="MEMBER" `
    --role="roles/secretmanager.secretAccessor"

Windows (cmd.exe)

gcloud secrets remove-iam-policy-binding SECRET_ID --location=LOCATION ^
    --member="MEMBER" ^
    --role="roles/secretmanager.secretAccessor"

REST

Observação: diferentemente dos outros exemplos, isso substitui toda a política do IAM.

Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:

  • LOCATION: o local do Google Cloud do segredo
  • PROJECT_ID: o ID do projeto do Google Cloud
  • SECRET_ID: o ID do secret ou do identificador totalmente qualificado

Método HTTP e URL:

POST https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID:setIamPolicy

Corpo JSON da solicitação:

{"policy": {"bindings": []}}

Para enviar a solicitação, escolha uma destas opções:

curl

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID:setIamPolicy"

PowerShell

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID:setIamPolicy" | Select-Object -Expand Content

Você receberá uma resposta JSON semelhante a esta:

{
  "version": 1,
  "etag": "BwYhOtzsOBk="
}

Go

Para executar esse código, primeiro configure um ambiente de desenvolvimento do Go e instale o SDK do Go do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do cloud-platform.

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"google.golang.org/api/option"
)

// iamRevokeAccess revokes the given member's access on the secret.
func IamRevokeAccessWithRegionalSecret(w io.Writer, projectId, locationId, secretId, member string) error {
	// name := "projects/my-project/locations/my-location/secrets/my-secret"
	// member := "user:foo@example.com"

	// Create the client.
	ctx := context.Background()
	//Endpoint to send the request to regional server
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationId)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))

	if err != nil {
		return fmt.Errorf("failed to create regional secretmanager client: %w", err)
	}
	defer client.Close()

	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s", projectId, locationId, secretId)

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

	// Grant the member access permissions.
	policy.Remove(member, "roles/secretmanager.secretAccessor")
	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

Para executar esse código, primeiro configure um ambiente de desenvolvimento do Java e instale o SDK do Java do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do cloud-platform.

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import java.io.IOException;

public class IamRevokeAccessWithRegionalSecret {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Your GCP project ID.
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // Resource ID of the secret to revoke access to.
    String secretId = "your-secret-id";
    // IAM member, such as a user group or service account you want to revoke access.
    String member = "user:foo@example.com";
    iamRevokeAccessWithRegionalSecret(projectId, locationId, secretId, member);
  }

  // Revoke a member access to a particular secret.
  public static Policy iamRevokeAccessWithRegionalSecret(
      String projectId, String locationId, String secretId, String member)
      throws IOException {

    // Endpoint to call the regional secret manager sever
    String apiEndpoint = String.format("secretmanager.%s.rep.googleapis.com:443", locationId);
    SecretManagerServiceSettings secretManagerServiceSettings =
        SecretManagerServiceSettings.newBuilder().setEndpoint(apiEndpoint).build();

    // Initialize the client that will be used to send requests. This client only needs to be
    // created once, and can be reused for multiple requests.
    try (SecretManagerServiceClient client = 
        SecretManagerServiceClient.create(secretManagerServiceSettings)) {
      // Build the name from the version.
      SecretName secretName = 
          SecretName.ofProjectLocationSecretName(projectId, locationId, secretId);

      // Request the current IAM policy.
      Policy policy =
          client.getIamPolicy(
              GetIamPolicyRequest.newBuilder().setResource(secretName.toString()).build());

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

      // Save the updated IAM policy.
      Policy updatedPolicy = client.setIamPolicy(
          SetIamPolicyRequest.newBuilder()
              .setResource(secretName.toString())
              .setPolicy(policy)
              .build());

      System.out.printf("Updated IAM policy for %s\n", secretId);

      return updatedPolicy;
    }
  }
}

Node.js

Para executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Node.js do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do cloud-platform.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'my-location';
// const secretId = 'my-secret';
// const versionId = 'my-version';
// const member = 'user:you@example.com';
//
// NOTE: Each member must be prefixed with its type. See the IAM documentation
// for more information: https://cloud.google.com/iam/docs/overview.

const name = `projects/${projectId}/locations/${locationId}/secrets/${secretId}`;

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Adding the endpoint to call the regional secret manager sever
const options = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;

// Instantiates a client
const client = new SecretManagerServiceClient(options);

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

  // 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/secretmanager.secretAccessor') {
      continue;
    }

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

  // Save the updated IAM policy.
  await client.setIamPolicy({
    resource: name,
    policy: policy,
  });

  console.log(`Updated IAM policy for ${name}`);
}

grantAccessRegionalSecret();

Python

Para executar esse código, primeiro configure um ambiente de desenvolvimento do Python e instale o SDK do Python do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do cloud-platform.

# Import the Secret Manager client library.
from google import iam
from google.cloud import secretmanager_v1


def iam_revoke_access_with_regional_secret(
    project_id: str,
    location_id: str,
    secret_id: str,
    member: str,
) -> iam.v1.iam_policy_pb2.SetIamPolicyRequest:
    """
    Revokes the given member access to a secret.
    """

    # Endpoint to call the regional secret manager sever.
    api_endpoint = f"secretmanager.{location_id}.rep.googleapis.com"

    # Create the Secret Manager client.
    client = secretmanager_v1.SecretManagerServiceClient(
        client_options={"api_endpoint": api_endpoint},
    )

    # Build the resource name of the secret.
    name = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}"

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

    # Remove the given member's access permissions.
    accessRole = "roles/secretmanager.secretAccessor"
    for b in list(policy.bindings):
        if b.role == accessRole and member in b.members:
            b.members.remove(member)

    # Update the IAM Policy.
    new_policy = client.set_iam_policy(request={"resource": name, "policy": policy})

    # Print data about the secret.
    print(f"Updated IAM policy on {secret_id}")

    return new_policy

A seguir