google-cloud-platform - Cloud Functions 调用另一个 Cloud Functions 面临“访问被禁止”
问题描述
我正在尝试从另一个调用云函数,为此,我正在关注此文档。
我创建了两个函数。这是调用另一个函数的代码:
const {get} = require('axios');
// TODO(developer): set these values
const REGION = 'us-central1';
const PROJECT_ID = 'my-project-######';
const RECEIVING_FUNCTION = 'hello-world';
// Constants for setting up metadata server request
// See https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature
const functionURL = `https://${REGION}-${PROJECT_ID}.cloudfunctions.net/${RECEIVING_FUNCTION}`;
const metadataServerURL =
'http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=';
const tokenUrl = metadataServerURL + functionURL;
exports.proxy = async (req, res) => {
// Fetch the token
const tokenResponse = await get(tokenUrl, {
headers: {
'Metadata-Flavor': 'Google',
},
});
const token = tokenResponse.data;
console.log(`Token: ${token}`);
// Provide the token in the request to the receiving function
try {
console.log(`Calling: ${functionURL}`);
const functionResponse = await get(functionURL, {
headers: {Authorization: `bearer ${token}`},
});
res.status(200).send(functionResponse.data);
} catch (err) {
console.error(JSON.stringify(err));
res.status(500).send('An error occurred! See logs for more details.');
}
};
它与文档中提出的几乎相同。我刚刚添加了一些日志,并且在记录错误之前将其字符串化。按照该页面上的说明,我还在我的函数中添加了服务帐户拥有该角色hello-world
的权限:my-project-######@appspot.gserviceaccount.com
roles/cloudfunctions.invoker
$ gcloud functions add-iam-policy-binding hello-world \
> --member='serviceAccount:my-project-######@appspot.gserviceaccount.com' \
> --role='roles/cloudfunctions.invoker'
bindings:
- members:
- allUsers
- serviceAccount:my-project--######@appspot.gserviceaccount.com
role: roles/cloudfunctions.invoker
etag: ############
version: 1
但是,当我调用上面的代码时,我得到403 Access is forbidden
. 我确定这是由hello-world
函数返回的,因为我可以从代码中看到日志。我可以看到令牌,并且可以hello-world
在日志中看到该函数的正确 URL。另外,我可以hello-world
直接从 GCP 控制台调用该函数。这两个函数都是Trigger type: HTTP
且唯一的hello-world
函数是Ingress settings: Allow internal traffic only
。另一个,Ingress settings: Allow all traffic
。
有人可以帮我理解有什么问题吗?
解决方案
如果您的Hello world
功能处于Allow internal only
模式,这意味着:
仅允许来自同一项目中的 VPC 网络或 VPC Service Controls 边界的请求。所有其他请求都被拒绝。
要使用这些功能,您必须通过您的 VPC 调用它。为了这,
- 在函数的同一区域创建无服务器 VPC 连接器(请注意,无服务器 VPC 连接器并非在所有区域都可用!!)
- 将其添加到您的第二个功能中
- 将所有流量路由到无服务器 VPC 连接器(我不确定您是否仅路由有效的内部流量)
推荐阅读
- node.js - 如何对 MongoDB 中数组内的字段值进行分组?
- sql - SQL存储过程中按日期分组以计算收入
- python-3.x - pyswmm可以改变Raingage的来源吗
- python - 图/二叉树编码问题 - 找出可以支付晚餐的人数(连接组件?)
- vaadin - 全新项目的 Vaadin 14 与 Vaadin 20
- java - 在使用 https post rest 客户端时获取 401
- android - 删除 jetpack compose 文本字段上的默认填充
- directed-acyclic-graphs - Airflow DAG:何时创建新的 dag?
- javascript - 如何在不使用 jwt 的情况下在 vue.js 中进行会话?
- scala - Spark RDD join-operation end with stackOverFlow