如何获取Cloud Functions发送POST请求时的发送方FQDN?
问题描述
我在Node.js环境的Cloud Functions中运行以下代码,向设备发送POST请求:
const postDevice = (user, device) => { const options = { host: user.host, //URL port: device.port, //PORT method: 'POST', ContentType: 'text/plain', //在头部设置指令内容 headers: { email: 'test@test.jp', device: 'TV', action: 'ON', }, }; const req = http.request(options, (res) => { res.setEncoding('utf8'); res.on('data', (chunk) => { console.log('BODY:', chunk); }); res.on('end', () => {}); }); req.end(); };
我需要获取Cloud Functions发送该POST请求时的发送方FQDN,但接收请求的设备无法验证这个FQDN。
解决方案
核心说明
Cloud Functions本身没有固定的发送方FQDN,它使用Google Cloud的动态出口IP池,每次请求的出口IP可能变化,因此无法通过固定FQDN验证请求来源。可以通过以下替代方案实现请求合法性验证:
基于IP范围的验证
Google会公开Cloud Functions所在区域的出口IP范围,你可以在接收设备上配置防火墙规则,只允许来自这些IP段的请求。需定期同步Google发布的对应区域IP范围列表。自定义请求签名验证
在Cloud Functions的请求头中添加基于密钥生成的签名,接收设备通过相同的密钥和算法验证签名,确认请求来自你的服务。示例代码调整如下:const crypto = require('crypto'); const SECRET_KEY = process.env.SIGN_SECRET; // 建议用环境变量存储密钥,避免硬编码 const postDevice = (user, device) => { const timestamp = Date.now().toString(); // 结合请求关键参数生成签名,防止篡改 const signature = crypto.createHmac('sha256', SECRET_KEY) .update(`${timestamp}:${device.device}:${device.action}`) .digest('hex'); const options = { host: user.host, port: device.port, method: 'POST', ContentType: 'text/plain', headers: { email: 'test@test.jp', device: 'TV', action: 'ON', 'X-Request-Timestamp': timestamp, 'X-Request-Signature': signature }, }; const req = http.request(options, (res) => { res.setEncoding('utf8'); res.on('data', (chunk) => { console.log('BODY:', chunk); }); res.on('end', () => {}); }); req.end(); };接收设备端需提取请求头中的时间戳和签名,用相同密钥重新计算签名并对比,同时验证时间戳有效期,防止重放攻击。
改用Cloud Run获取固定FQDN
如果必须依赖固定FQDN验证,可将函数部署到Cloud Run。Cloud Run支持分配固定的自定义域名或默认Cloud Run域名,发送请求时的发送方FQDN固定,接收设备可直接验证该FQDN。
内容的提问来源于stack exchange,提问作者Goto
相关产品推荐
相关产品推荐

