限制对 Google 云函数的访问

Restrict access to Google Cloud Function

我已经成功部署了一个 Cloud Function,它对某些数据执行一些基本 pre-processing 并将其上传到 gSheet。
现在,触发器 url 接受外部未经身份验证的调用,如果 url 落入坏人之手,会导致账单过多的风险。

我想知道是否有任何方法可以在 IAM 中限制对 Cloud Scheduler 的调用,从而完全阻止对服务的外部调用。
阅读它似乎在请求中包含一些 header 并在函数中检查它可能是强制执行真正基本身份验证的基本方法。

如果您想限制最终用户请求对您的 Google Cloud Functions 的访问,您可以将 Google 登录与 Cloud IAM 集成或实施 Firebase 身份验证

Cloud Functions: Authenticating Developers, Functions, and End-users:

Most applications handle requests from end-users, and it's a best practice to restrict access to only allowed end users. In order to accomplish this, you can integrate Google Sign-In and grant users the roles/cloudfunctions.invoker IAM role, or implement Firebase Authentication and manually validate their credentials.

为了防止外部未经身份验证的调用,您可以将函数设置为私有。很容易做到,使用 --no-allow-unauthenticated 参数

部署它
gcloud functions deploy my-function --no-allow-unauthenticated --trigger... -- region... --runtime...

但是现在,调度程序无法调用它。现在你必须做两件事

  • 创建一个具有正确角色的服务帐户。您可以通过 GUI 或命令行来完成
# Create the service account
gcloud iam service-accounts create your-service-account-name

# Grant the role for calling the function
gcloud functions add-iam-policy-binding \
  --member=serviceAccount:your-service-account-name@YOUR_PROJECT_ID.iam.gserviceaccount.com \
  --role=roles/cloudfunctions.invoker your-function-name

使用 GUI,如果您在项目级别授予角色 cloudfunctions.invoker,您的服务帐户将能够访问项目中的所有功能。在我的命令行中,我只授予特定功能的角色。您可以通过控制台完成此操作,方法是转到函数列表,select 一个函数(复选框)并单击 show info panel。这里有一个权限选项卡

  • 然后使用服务帐户创建调度程序
gcloud scheduler jobs create http your-job name --schedule="0 0 * * *" \
  --uri=your-function-URI \
  --oidc-service-account-email=your-service-account-name@YOUR_PROJECT_ID.iam.gserviceaccount.com

如果不起作用,那是因为您的云调度程序服务代理未授权使用服务帐户生成令牌。

gcloud projects add-iam-policy-binding YOUR_PROJECT_ID \
  --member=serviceAccount:service-[project-number]@gcp-sa-cloudscheduler.iam.gserviceaccount.com \
  --role roles/cloudscheduler.serviceAgent