云任务未执行云功能

时间:2021-06-28 07:20:13

标签: google-cloud-platform google-cloud-functions google-iam google-tasks-api

我想为我的 Cloud Functions 添加安全性,因此我删除了调用它的 allUsers 访问权限 - 因此我只能从 GCP 中的服务帐户调用它。

所以我遵循了 GCP docs exactly 中的教程:

云功能

async function createTask(taskName, functionToFire, payload, fireAt){
    const tasksClient = new CloudTasksClient()
    const projectId = JSON.parse(process.env.FIREBASE_CONFIG).projectId
    console.log(`${taskName} will fire ${functionToFire} at ${fireAt}...`)
    const location = 'us-central1'
    const queuePath = tasksClient.queuePath(projectId, location, taskName)
    const url = `https://us-central1-${PROJECT_ID}.cloudfunctions.net/task/${functionToFire}`
    const serviceAccountEmail = 'cloud-tasks@${PROJECT_ID}.iam.gserviceaccount.com';
    // const sendAt = Date.now() / 1000 + 10 // plus 10 seconds of current epoch
    const task = {
        httpRequest: {
          httpMethod: 'POST',
          url,
          oidcToken: {
            serviceAccountEmail
          },
          body: Buffer.from(JSON.stringify(payload)).toString('base64'),
          headers: {
            'Content-Type': 'application/json',
          },
        },
        scheduleTime: {
          seconds: (fireAt / 1000) // Convert millis to seconds
        }
    }
    await tasksClient.createTask({ parent: queuePath, task })
    return 200;
}

云功能权限

服务帐户已被授予对这个名为 task 的特定函数的以下权限:

  • 云函数管理员
  • 云函数调用程序
  • Cloud Functions 服务代理

enter image description here

但是当任务实际触发时,它会出现此错误:

PERMISSION_DENIED(7): HTTP status code 403

我也遇到了以下错误:

UNAUTHENTICATED(16): HTTP status code 401

我已经使用 2 个服务帐户进行了测试 - 推荐的一个使用文档(如上所示)以及我专门为此创建的一个名为 cloud-tasks@${PROJECT_ID}.iam.gserviceaccount.com 的服务帐户。

我还访问了通用 IAM 页面并检查了这些服务帐户的权限:

  1. 默认服务帐号:

enter image description here

  1. 我创建的服务帐户:

enter image description here

当函数触发时,两者都返回上面显示的 PERMISSION_DENIEDUNAUTHENTICATED 错误:

enter image description here

知道是什么问题吗?我几乎什么都试过了。

1 个答案:

答案 0 :(得分:1)

您忘记将受众放入您的 OIDC 令牌定义中。您可以在 nodeJS documentation

中找到对象定义
...
...
 const task = {
        httpRequest: {
          httpMethod: 'POST',
          url,
          oidcToken: {
            serviceAccountEmail: serviceAccountEmail
            //Audience is the raw URL, without extra path or query parameter
            audience: https://us-central1-${PROJECT_ID}.cloudfunctions.net/task           },
...
...