本地开发时如何正确管理Google Cloud凭证?
我搜索了大量Google客户端库身份认证/授权的相关方案,目前业内尚未形成统一的落地标准。
部分方案建议创建service account,生成其密钥后分发给所有需要使用该服务账号权限的开发人员。我不认可该方案,因为会导致service account的身份信息泄露给多人。
另一部分方案提出可以直接通过Cloud SDK使用ADC(Application Default Credentials)登录,执行命令如下:
$ gcloud auth application-default login
后续google-cloud-storage这类客户端库会自动从ADC加载当前用户绑定的凭证。该方案相对更优但仍存在缺陷:需要进入IAM为每个开发人员(或对应的用户组)配置应用运行所需的全部权限;如果开发人员本地运行多个测试应用(比如微服务),所需的权限列表会非常冗长,后期也很难追溯当时授予这些权限的原因。
我了解到的最后一种方案是service account impersonation,该方案解决了向开发人员泄露私钥的问题,我们可以一次性定义某应用A所需的全部权限,将其绑定到对应service account后,仅需配置允许开发人员模拟该应用使用的service account即可,例如:
允许Julien模拟应用A所使用的service account。
以下是模拟principal的代码片段:
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()))
如果要自行测试该方案,你需要先创建待模拟的service account(本例为foo@bar-271618.iam.gserviceaccount.com),并在该service account的权限配置页为你的用户授予
Service Account Token Creator角色。
我目前的顾虑是:需要对所有用到的Google Cloud客户端库做封装,增加运行环境判断逻辑,判断应用是否在本地运行:
from google.auth import impersonated_credentials from google.auth import default import os from google.cloud import storage target_scopes = ['https://www.googleapis.com/auth/devstorage.read_only'] credentials, project = default(scopes=target_scopes) if 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()))
另外我还需要手动声明使用的scopes(我推测是oauth2访问scopes),使用体验较差。
我的疑问是:我当前的选型方向是否正确?是否存在考虑过度的情况?有没有更简便的实现方式?
我参考的相关资料如下:
- https://readthedocs.org/projects/google-auth/downloads/pdf/latest/
- https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials
- https://cloud.google.com/docs/authentication/production
- https://youtu.be/IYGkbDXDR9I?t=822
更新1
该议题已在google-auth-library-python代码仓库的相关issue中讨论,我已提交PR提议支持该功能优化。
更新2
该功能已正式实现,可参考对应代码仓库的说明文档使用。
内容的提问来源于stack exchange,提问作者MadJlzz

