我是该代码 sn-p 和 corresponding blog post 的作者。对于帖子历史记录,这是 OP 所指的完整 sn-p:
const cryptoKeyID = process.env.KMS_CRYPTO_KEY_ID;
const kms = require('@google-cloud/kms');
const client = new kms.v1.KeyManagementServiceClient();
let username;
client.decrypt({
name: cryptoKeyID,
ciphertext: process.env.DB_USER,
}).then(res => {
username = res[0].plaintext.toString().trim();
}).catch(err => {
console.error(err);
});
let password;
client.decrypt({
name: cryptoKeyID,
ciphertext: process.env.DB_PASS,
}).then(res => {
password = res[0].plaintext.toString().trim();
}).catch(err => {
console.error(err);
});
exports.F = (req, res) => {
res.send(`${username}:${password}`)
}
由于 Node 是一种异步语言,因此无法保证变量 username 和 password 在函数调用之前完全初始化。在那个 sn-p 中,我优化了“在函数启动时解密,因此每个函数调用都在恒定时间内运行”。在您的示例中,您希望针对“函数在调用前完全初始化”进行优化,这需要对代码进行一些重新组织。
一种可能的解决方案是将查找移动到调用 GCF 函数时调用的 Node 函数中。例如:
const cryptoKeyID = process.env.KMS_CRYPTO_KEY_ID;
const kms = require('@google-cloud/kms');
const client = new kms.v1.KeyManagementServiceClient();
let cache = {};
const decrypt = async (ciphertext) => {
if (!cache[ciphertext]) {
const [result] = await client.decrypt({
name: cryptoKeyID,
ciphertext: ciphertext,
});
cache[ciphertext] = result.plaintext;
}
return cache[ciphertext];
}
exports.F = async (req, res) => {
const username = await decrypt(process.env.DB_USER);
const password = await decrypt(process.env.DB_PASS);
res.send(`${username}:${password}`)
}
请注意,我在这里添加了一个缓存层,因为您可能不想在每次调用函数时解密加密的 blob。