【问题标题】:Global scope variable initialization in google cloud function谷歌云函数中的全局范围变量初始化
【发布时间】:2019-02-20 11:12:15
【问题描述】:

我想使用 Google Cloud KMS 存储密钥并在 Google Cloud Function 中使用它。首先,我将加密我的密钥并将其存储在环境变量中

如果我像link 这样解密我的密钥,它会返回 Promise。 当我的函数被部署和调用时,我的变量是否保证完成初始化?

【问题讨论】:

    标签: node.js google-cloud-platform google-cloud-functions google-cloud-kms


    【解决方案1】:

    我是该代码 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 是一种异步语言,因此无法保证变量 usernamepassword 在函数调用之前完全初始化。在那个 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 2013-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多