A implantação de uma função com uma CMEK protege os dados associados a ela usando
uma chave de criptografia que está em seu controle total. Esse tipo de criptografia permite
que você atenda a requisitos de conformidade em determinados setores, como
serviços financeiros. Como a chave CMEK pertence a você e não é controlada pelo Google,
ninguém (incluindo você) pode acessar os dados protegidos por essas chaves de criptografia
quando as chaves são desativadas ou destruídas.
Os seguintes tipos de dados do Cloud Run functions são criptografados ao usar uma
CMEK:
Código-fonte da função enviado para implantação e armazenado pelo Google no
Cloud Storage, usado no processo de compilação.
Os resultados do processo de criação da função, incluindo:
A imagem do contêiner criada a partir do código-fonte da função.
Cada instância da função que está implantada.
Dados em repouso para canais de transporte de eventos internos.
O processo de compilação da função em si é protegido por uma chave temporária gerada
exclusivamente para cada compilação. Consulte
Conformidade com CMEK no Cloud Build para mais
informações. Além disso:
Os metadados do arquivo, como caminhos de sistema de arquivos ou carimbos de data/hora de modificação,
não são criptografados.
Se uma chave for desativada, a imagem do contêiner não poderá ser implantada e novas
instâncias não poderão ser iniciadas.
A proteção de CMEK do Cloud Run functions se aplica apenas aos recursos do Cloud Run functions gerenciados pelo Google. Você é responsável por proteger dados e recursos gerenciados por você, como os repositórios de código-fonte ou quaisquer serviços usados pelas funções.
A configuração de CMEK para o Cloud Run functions envolve o seguinte:
Conceder às contas de serviço necessárias acesso à chave:
Para todas as funções, é preciso conceder acesso à chave às contas de serviço do Cloud Run functions,
Artifact Registry e Cloud Storage.
Como criar um repositório do Artifact Registry protegido por CMEK para armazenar
as imagens de função.
Como conceder acesso à chave para as contas de serviço
Para todas as funções, conceda às seguintes contas de serviço acesso à chave:
Agente de serviço de funções do Cloud Run (service-PROJECT_NUMBER@gcf-admin-robot.iam.gserviceaccount.com)
Agente de serviço do Artifact Registry (service-PROJECT_NUMBER@gcp-sa-artifactregistry.iam.gserviceaccount.com)
Agente de serviço do Cloud Storage (service-PROJECT_NUMBER@gs-project-accounts.iam.gserviceaccount.com)
Para conceder a essas contas de serviço acesso à chave, adicione cada conta de serviço como um
principal da chave e conceda a ela o
papel Cloud KMS CryptoKey Encrypter/Decrypter.
Clique no nome do keyring que contém a chave escolhida.
Clique no nome da chave para visualizar os detalhes dela.
Na guia Permissões, clique em Conceder acesso.
No campo Novos participantes, insira os endereços de e-mail das três
contas de serviço mostrado anteriormente para atribuir permissões às três contas de uma só vez.
No menu suspenso Selecionar um papel, escolha Criptografador/descriptografador
do Cloud KMS CryptoKey.
Clique em Salvar.
gcloud
Para cada conta de serviço discutida anteriormente, execute o seguinte comando:
KEY_RING: o nome do keyring. Por exemplo, my-keyring.
LOCATION: a localização da chave. Por exemplo, us-central1.
SERVICE_AGENT_EMAIL: o endereço de e-mail da
conta de serviço.
a ele.
Como ativar CMEK para uma função
Depois de configurar um repositório do Artifact Registry com CMEK ativada e conceder
ao Cloud Run functions acesso à sua chave, você estará pronto para ativar
a CMEK para sua função.
FUNCTION: o nome da função para ativar
CMEK. Por exemplo, cmek-function.
KEY: o nome da chave totalmente qualificada no seguinte
formato:
projects/PROJECT_NAME/locations/LOCATION/keyRings/KEYRING_NAME/cryptoKeys/KEY_NAME.
REPOSITORY: o nome do repositório do Artifact Registry
totalmente qualificado, no seguinte formato:
projects/PROJECT_NAME/locations/LOCATION/repositories/REPOSITORY.
YOUR_SOURCE_LOCATION: ao ativar a CMEK para uma
função preexistente, verifique se o código-fonte pretendido está sendo
reimplantado especificando explicitamente esse parâmetro.
FLAGS...: sinalizações adicionais que podem ser necessárias para implantar a função, especialmente para criar implantações. Para detalhes, consulte Implantar um Cloud Run function.
CMEK está ativada para a função.
O Cloud Run functions sempre usa a versão primária de uma chave para proteção CMEK. Não é possível especificar uma versão de chave específica para usar ao ativar
o CMEK para suas funções.
Se uma chave for destruída ou
desativada ou as permissões necessárias forem
revogadas, as instâncias ativas das funções protegidas por ela não serão encerradas.
As execuções de funções em andamento vão continuar sendo executadas, mas as novas execuções
vão falhar se o Cloud Run functions não tiver acesso à chave.
Como testar a proteção CMEK
Para verificar se a proteção de CMEK está funcionando, desative a chave usada
para ativá-la em uma função e, em seguida, tente acionar a função:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-04-23 UTC."],[[["\u003cp\u003eCloud Run functions (1st gen) can be protected using Cloud Key Management Service customer-managed encryption keys (CMEK), giving users full control over encryption keys for sensitive data.\u003c/p\u003e\n"],["\u003cp\u003eCMEK protection applies to function source code, container images, deployed instances, and at-rest data for internal event transport channels within Cloud Run functions.\u003c/p\u003e\n"],["\u003cp\u003eEnabling CMEK for Cloud Run functions requires granting key access to Cloud Run functions, Artifact Registry, and Cloud Storage service accounts, along with creating a CMEK-protected Artifact Registry repository.\u003c/p\u003e\n"],["\u003cp\u003eDisabling or destroying the CMEK key will prevent new function executions and deployments, though existing active instances will continue until completion.\u003c/p\u003e\n"],["\u003cp\u003eVerifying CMEK protection can be done by disabling the key and ensuring that attempts to access the functions source code or trigger it fails.\u003c/p\u003e\n"]]],[],null,["# Protect your data with CMEK (1st gen)\n=====================================\n\nYou can use Cloud Key Management Service\n[customer-managed encryption keys (CMEK)](/kms/docs/cmek) to protect\nCloud Run functions and related\n[data at rest](https://en.wikipedia.org/wiki/Data_at_rest). Such keys are\ncreated and managed through Cloud KMS and stored as software keys, in\nan [HSM cluster](/kms/docs/hsm), or [externally](/kms/docs/ekm).\n\nDeploying a function with a CMEK protects the data associated with it by using\nan encryption key that is in your full control. This type of encryption lets you\nmeet compliance requirements in certain industries, such as financial\nservices. Because the key is owned by you and is not controlled by Google,\nno one (including you) can access the data protected by these encryption keys\nwhen the keys are disabled or destroyed.\n\nThe following types of Cloud Run functions data are encrypted when using a\nCMEK:\n\n- Function source code uploaded for deployment and stored by Google in Cloud Storage, used in the build process.\n- The results of the function build process, including:\n - The container image built from your function source code.\n - Each instance of the function that is deployed.\n- At-rest data for internal event transport channels.\n\nThe function build process itself is protected by an ephemeral key uniquely\ngenerated for each build. See\n[CMEK compliance in Cloud Build](/build/docs/securing-builds/cmek) for more\ninformation. Additionally, note the following:\n\n- File metadata, such as filesystem paths or modification timestamps,\n is not encrypted.\n\n- If a key is disabled, the container image cannot be deployed and new\n instances cannot start.\n\n- Cloud Run functions CMEK protection only applies to Google-managed\n Cloud Run functions resources; you are responsible for protecting data and\n resources managed by you, such as your source code repositories, or any\n services used by your functions.\n\nSetting up CMEK for Cloud Run functions entails the following:\n\n- Granting the necessary service accounts access to the key:\n\n - For all functions, you need to grant the Cloud Run functions, Artifact Registry, and Cloud Storage service accounts access to the key.\n- Creating a CMEK-protected Artifact Registry repository to store your\n function images.\n\n- Enabling CMEK on your function.\n\n- Optionally, enable [CMEK organization policies](/kms/docs/cmek-org-policy) to\n enforce all new functions to be CMEK compliant.\n\nThese steps are described in more detail below.\n\nBefore you begin\n----------------\n\n1. Create a single-region key to use to encrypt your functions. To learn how to\n create a key, see\n [Creating symmetric encryption keys](/kms/docs/creating-keys).\n\n2. [Create an Artifact Registry repository](/artifact-registry/docs/manage-repos#create)\n that has [CMEK enabled](/artifact-registry/docs/cmek). You must use the same\n key for the Artifact Registry repository as you do when enabling CMEK for a\n function.\n\nGranting service accounts access to the key\n-------------------------------------------\n\nFor all functions, you must grant the following service accounts access to the key:\n\n- Cloud Run functions service agent (`service-`\u003cvar translate=\"no\"\u003ePROJECT_NUMBER\u003c/var\u003e`@gcf-admin-robot.iam.gserviceaccount.com`)\n\n- Artifact Registry service agent (`service-`\u003cvar translate=\"no\"\u003ePROJECT_NUMBER\u003c/var\u003e`@gcp-sa-artifactregistry.iam.gserviceaccount.com`)\n\n- Cloud Storage service agent (`service-`\u003cvar translate=\"no\"\u003ePROJECT_NUMBER\u003c/var\u003e`@gs-project-accounts.iam.gserviceaccount.com`)\n\nTo grant these service accounts access to the key, add each service account as a\nprincipal of the key and then grant the service account the\n`Cloud KMS CryptoKey Encrypter/Decrypter` role: \n\n### Console\n\n1. Go to the Cloud Key Management Service page in the Google Cloud console: \n\n [Go to the Cloud KMS page](https://console.cloud.google.com/security/kms)\n\n2. Click the name of the key ring that contains the chosen key.\n\n3. Click the name of the key to view the key details.\n\n4. In the **Permissions** tab, click **Grant access**.\n\n5. In the **New principals** field, enter the email addresses of all three\n service accounts shown earlier to assign permissions to all three accounts\n at once.\n\n6. In the **Select a role** drop-down, select **Cloud KMS CryptoKey\n Encrypter/Decrypter**.\n\n7. Click **Save**.\n\n### gcloud\n\nFor each service account discussed earlier, run the following command: \n\n```bash\ngcloud kms keys add-iam-policy-binding KEY \\\n--keyring KEY_RING \\\n--location LOCATION \\\n--member serviceAccount:SERVICE_AGENT_EMAIL \\\n--role roles/cloudkms.cryptoKeyEncrypterDecrypter\n```\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003eKEY\u003c/var\u003e: The name of the key. For example, `my-key`.\n\n- \u003cvar translate=\"no\"\u003eKEY_RING\u003c/var\u003e: The name of the key ring. For example,\n `my-keyring`.\n\n- \u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e: The location of the key. For example,\n `us-central1`.\n\n- \u003cvar translate=\"no\"\u003eSERVICE_AGENT_EMAIL\u003c/var\u003e: The email address of the\n service account.\n\n| **Important:** Some service agents, such as the Cloud Storage service agent (including its email address), are not initially available when you create a project. Instead, they are activated the first time you access them. For example, to activate the Cloud Storage service agent, you can [retrieve its email address](/storage/docs/getting-service-agent). The service agent must be activated prior to assigning permissions to it.\n\nEnabling CMEK for a function\n----------------------------\n\nAfter setting up an Artifact Registry repository with CMEK enabled and\ngranting Cloud Run functions access to your key, you're ready to enable\nCMEK for your function.\n\nTo enable CMEK for a function: \n\n### Console\n\n1. Go to the Cloud Run functions page in the Google Cloud console: \n\n [Go to the Cloud Run functions page](https://console.cloud.google.com/functions)\n\n2. Click the name of the function you want to enable CMEK on.\n\n3. Click **Edit**.\n\n4. Click **Runtime, build...** to expand the\n advanced configuration options.\n\n5. Select the **Security and image repo** tab.\n\n6. In the **Encryption** section, select\n **Customer-managed encryption key (CMEK)**.\n\n7. Select your chosen key from the dropdown.\n\n8. Under **Container location** , select\n **Customer-managed Artifact Registry**.\n\n9. In the **Artifact registry** dropdown, select the CMEK-protected\n repository.\n\n10. Click **Next**.\n\n11. Click **Deploy**.\n\n### gcloud\n\nRun the following command. \n\n```bash\ngcloud functions deploy FUNCTION \\\n--no-gen2 \\\n--kms-key=KEY \\\n--docker-repository=REPOSITORY \\\n--source=YOUR_SOURCE_LOCATION\nFLAGS...\n```\n\nReplace the following:\n\n- \u003cvar translate=\"no\"\u003eFUNCTION\u003c/var\u003e: The name of the function to enable CMEK\n on. For example, `cmek-function`.\n\n- \u003cvar translate=\"no\"\u003eKEY\u003c/var\u003e: The fully qualified key name, in the following\n format:\n `projects/`\u003cvar translate=\"no\"\u003ePROJECT_NAME\u003c/var\u003e`/locations/`\u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e`/keyRings/`\u003cvar translate=\"no\"\u003eKEYRING_NAME\u003c/var\u003e`/cryptoKeys/`\u003cvar translate=\"no\"\u003eKEY_NAME\u003c/var\u003e.\n\n- \u003cvar translate=\"no\"\u003eREPOSITORY\u003c/var\u003e: The fully qualified Artifact Registry\n repository name, in the following format:\n `projects/`\u003cvar translate=\"no\"\u003ePROJECT_NAME\u003c/var\u003e`/locations/`\u003cvar translate=\"no\"\u003eLOCATION\u003c/var\u003e`/repositories/`\u003cvar translate=\"no\"\u003eREPOSITORY\u003c/var\u003e.\n\n- \u003cvar translate=\"no\"\u003eYOUR_SOURCE_LOCATION\u003c/var\u003e: When enabling CMEK for a\n pre-existing function, make sure that the intended source code is being\n re-deployed by specifying this parameter explicitly.\n\n- \u003cvar translate=\"no\"\u003eFLAGS\u003c/var\u003e`...`: Additional flags that may be\n required to deploy your function, particularly for create deployments. For\n details, see\n [Deploy a Cloud Run function](/functions/1stgendocs/deploy#basics).\n\nCMEK is enabled for the function.\n| **Note:** First-time function deployments with CMEK enabled might fail due to IAM propagation delays. If you encounter an error upon deployment, ensure the permissions are set correctly and try again after a short period.\n\nNote that Cloud Run functions always uses the primary version of a key for CMEK\nprotection. You cannot specify a particular key version to use when enabling\nCMEK for your functions.\n\nIf a key is [destroyed](/kms/docs/destroy-restore) or\n[disabled](/kms/docs/enable-disable), or the requisite permissions on it are\nrevoked, active instances of functions protected by that key are not shut down.\nFunction executions already in progress will continue to run, but new executions\nwill fail as long as Cloud Run functions does not have access to the key.\n\nTesting CMEK protection\n-----------------------\n\nTo verify that CMEK protection is working, you can disable the key you used\nto enable CMEK for a function, then try to trigger your function:\n\n1. [Disable the key](/kms/docs/enable-disable#disable) used to protect\n your function.\n\n | **Note:** It may take up to three hours for the changes to propagate.\n2. Attempt to view the source code associated with this function. The attempt\n should fail.\n\n3. Attempt to [trigger the CMEK-protected function](/functions/1stgendocs/calling).\n The attempt should fail.\n\n4. After you have verified that CMEK protection is working,\n [enable the key](/kms/docs/enable-disable#enable).\n\nThe function's CMEK protection is now confirmed.\n\nWhat's next\n-----------\n\n- Learn how to [rotate your keys](/kms/docs/rotating-keys).\n- Learn more about [Google default encryption](/security/encryption/default-encryption).\n- Learn [more about CMEK](/kms/docs/cmek).\n- Learn more about [CMEK organization policies](/kms/docs/cmek-org-policy)."]]