如何管理 Google 本地开发的云凭据

How to manage Google Cloud credentials for local development

我搜索了很多如何 authenticate/authorize Google 的客户端库,似乎没有人同意如何去做。

有些人说我应该创建一个服务帐户,从中创建一个密钥,然后将该密钥提供给每个想要充当此服务帐户的开发人员。我讨厌这个解决方案,因为它会将服务帐户的身份泄露给多个人。

其他人提到您只需通过以下操作使用 Cloud SDK 和 ADC(应用程序默认凭据)登录:

$ gcloud auth application-default login

然后,像 google-cloud-storage 这样的库将从 ADC 加载与我的用户相关联的凭据。 它更好,但对我来说仍然不好,因为这需要转到 IAM 并向每个开发人员(或组)授予应用程序所需的权限 运行。此外,如果开发人员 运行 在本地有许多应用程序用于测试目的(例如微服务),则所需的权限列表可能会很长。也很难理解为什么我们在一段时间后授予这样的权限。

我遇到的最后一种方法是服务帐户模拟。这解决了将私钥暴露给开发人员的事实,让我们定义应用程序所需的权限,假设 A 一次,将它们关联到服务帐户并说:

Hey, let Julien act as the service account used for application A.

以下是如何模拟校长的片段:

from google.auth import impersonated_credentials
from google.auth import default

from google.cloud import storage

target_scopes = ['https://www.googleapis.com/auth/devstorage.read_only']

credentials, project = default(scopes=target_scopes)

final_credentials = impersonated_credentials.Credentials(
    source_credentials=credentials,
    target_principal="foo@bar-271618.iam.gserviceaccount.com",
    target_scopes=target_scopes
)

client = storage.Client(credentials=final_credentials)

print(next(client.list_buckets()))

If you want to try this yourself, you need to create the service account you want to impersonate (here foo@bar-271618.iam.gserviceaccount.com) and grant your user the role Service Account Token Creator from the service account permission tab.

我唯一担心的是,它需要我 wrap 所有 Google 我想使用的云客户端库,用于检查我是否 运行在本地安装我的应用程序:

from google.auth import impersonated_credentials
from google.auth import default

from google.cloud import storage

target_scopes = ['https://www.googleapis.com/auth/devstorage.read_only']

credentials, project = default(scopes=target_scopes)
if env := os.getenv("RUNNING_ENVIRONMENT") == "local":
    credentials = impersonated_credentials.Credentials(
        source_credentials=credentials,
        target_principal=os.environ["TARGET_PRINCIPAL"],
        target_scopes=target_scopes
    )

client = storage.Client(credentials=credentials)
print(next(client.list_buckets()))

此外,我必须定义范围(我认为这是 oauth2 访问范围?)我正在使用,这很烦人。

我的问题是:我的方向是否正确?我是否想得太多了?有没有更简单的方法来实现所有这些?

这是我使用的一些来源:

更新 1

讨论了这个话题here

我提出了第一个提议 here 来支持此增强功能。

更新 2

该功能已实现!有关详细信息,请参阅 here

您可以使用新的 gcloud 功能并像这样模拟您的本地凭据:

gcloud auth application-default login --impersonate-service-account=<SA email>

这是一项新功能。作为 Java 和 Golang 开发人员,我检查并测试了 Java 客户端库,它已经支持这种身份验证模式。然而,在 Go 中还不是这样。我提交了一个 pull request 将其添加到 go 客户端库中。

我很快签入了 Python,它 seems implemented。试用最新版本之一(2021 年 8 月 3 日后发布)并告诉我!!

注意:一些人知道您的用例。我很高兴在这种情况下不孤单:)