如何在 Google Cloud Run 中生成 Blob 签名 url?

sww*_*314 3 python google-cloud-storage google-iam google-cloud-run

在 Google Cloud Run 下,您可以选择容器正在运行的服务帐户。使用默认计算服务帐户无法生成签名 url。

此处列出的解决方法适用于 Google Cloud Compute - 如果您允许服务帐户的所有范围。在 Cloud Run 中似乎没有办法做到这一点(我找不到)。

https://github.com/googleapis/google-auth-library-python/issues/50

我尝试过的事情:

  1. 为服务帐号分配角色: roles/iam.serviceAccountTokenCreator
  2. 在虚拟机(vs Cloud Run)中验证了同一个 GCP 项目中的解决方法
  3. 使用从私钥(通过 json 文件)加载的服务帐户验证代码在容器中本地工作。
from google.cloud import storage
client = storage.Client()
bucket = client.get_bucket('EXAMPLE_BUCKET')
blob = bucket.get_blob('libraries/image_1.png')
expires = datetime.now() + timedelta(seconds=86400)
blob.generate_signed_url(expiration=expires)
Run Code Online (Sandbox Code Playgroud)

失败:

you need a private key to sign credentials.the credentials you are currently using <class 'google.auth.compute_engine.credentials.Credentials'> just contains a token. see https://googleapis.dev/python/google-api-core/latest/auth.html#setting-up-a-service-account for more details.
/usr/local/lib/python3.8/site-packages/google/cloud/storage/_signing.py, line 51, in ensure_signed_credentials
Run Code Online (Sandbox Code Playgroud)

尝试添加解决方法,

Error calling the IAM signBytes API: 
{  "error": {  "code": 400,

    "message": "Request contains an invalid argument.",
    "status": "INVALID_ARGUMENT"  }
}
Exception Location: /usr/local/lib/python3.8/site-packages/google/auth/iam.py, line 81, in _make_signing_request
Run Code Online (Sandbox Code Playgroud)

Github问题中提到的解决方法代码:

from google.cloud import storage
from google.auth.transport import requests
from google.auth import compute_engine
from datetime import datetime, timedelta

def get_signing_creds(credentials):
    auth_request = requests.Request()
    print(credentials.service_account_email)
    signing_credentials = compute_engine.IDTokenCredentials(auth_request, "", service_account_email=credentials.ser
vice_account_email)
    return signing_credentials


client = storage.Client()
bucket = client.get_bucket('EXAMPLE_BUCKET')
blob = bucket.get_blob('libraries/image_1.png')
expires = datetime.now() + timedelta(seconds=86400)
signing_creds = get_signing_creds(client._credentials)
url = blob.generate_signed_url(expiration=expires, credentials=signing_creds)
print(url)
Run Code Online (Sandbox Code Playgroud)

如何在 Google Cloud Run 下生成签名网址?在这一点上,似乎我可能必须挂载我想避免的服务帐户密钥。

编辑:为了尝试澄清,服务帐户具有正确的权限 - 它在 GCE 和本地 JSON 私钥中工作。

gui*_*ere 8

是的,你可以,但我必须深入研究才能找到方法(如果你不关心细节,请跳到最后)

如果你进入_signing.py file, line 623,你可以看到这个

if access_token and service_account_email:
   signature = _sign_message(string_to_sign, access_token, service_account_email)
...
Run Code Online (Sandbox Code Playgroud)

如果您提供access_tokenservice_account_email,则可以使用该_sign_message方法。此方法在此行使用IAM 服务 SignBlob API

这很重要,因为您现在可以在没有本地私钥的情况下对 blob 进行签名!!所以,这解决了问题,以下代码适用于 Cloud Run(我确定适用于 Cloud Function)

def sign_url():
    from google.cloud import storage
    from datetime import datetime, timedelta

    import google.auth
    credentials, project_id = google.auth.default()

    # Perform a refresh request to get the access token of the current credentials (Else, it's None)
    from google.auth.transport import requests
    r = requests.Request()
    credentials.refresh(r)

    client = storage.Client()
    bucket = client.get_bucket('EXAMPLE_BUCKET')
    blob = bucket.get_blob('libraries/image_1.png')
    expires = datetime.now() + timedelta(seconds=86400)

    # In case of user credential use, define manually the service account to use (for development purpose only)
    service_account_email = "YOUR DEV SERVICE ACCOUNT"
    # If you use a service account credential, you can use the embedded email
    if hasattr(credentials, "service_account_email"):
        service_account_email = credentials.service_account_email

    url = blob.generate_signed_url(expiration=expires,service_account_email=service_account_email, access_token=credentials.token)
    return url, 200
Run Code Online (Sandbox Code Playgroud)

如果不清楚,请告诉我

  • 不幸的是,这似乎无法使用云功能内的默认应用程序引擎服务帐户。它引发了一个异常:`AttributeError:您需要私钥来签署凭据。您当前使用的凭据 &lt;class 'google.auth.compute_engine.credentials.Credentials'&gt; 仅包含一个令牌。有关更多详细信息,请参阅 https://googleapis.dev/python/google-api-core/latest/auth.html#setting-up-a-service-account。 (2认同)