0

我已经坚持了好几天了,感觉无论我如何构建它,aws 秘密管理器调用总是在应用程序初始化后返回。npm run start 触发 app.js 文件,这会触发 knex 并且一切都按顺序运行,但是在一切都已经初始化之后,带有用户名/密码的秘密响应似乎又回来了。

knex.js:

console.log("knex.js")
const environment = process.env.APP_ENV || 'development'
const config = require('../knexfile.js')[environment];
const knex = require('knex')(config);

module.exports = knex

knexfile.js:

require('dotenv').config();
const path = require('path')
const pathToCert = path.resolve(__dirname, 'root.cert'); // where to save a file

console.log("knexfile.js")

var AWS = require('aws-sdk');
region = 'us-east-2'
secretName = 'blah'
var client = new AWS.SecretsManager({
  region: region
});
async function getConfig() {
  console.log("in get config")
  return await new Promise((resolve, reject) => {
    client.getSecretValue({ SecretId: secretName }, function (
      err,
      data
    ) {
      let secret = JSON.parse(data.SecretString);
      console.log("returning it***************" + secret.password + " " + secret.username + " " + pathToCert)
      let connectionString = `postgresql://${secret.username}:${secret.password}@some-host:1234/defaultdb?sslmode=verify-full&sslrootcert=${pathToCert}&options=--cluster`
      resolve(connectionString)
      return

    })
  })
}
const config = {
  development: {
    client: 'pg',
    version: 7.2,
    connection: getConfig(),
    migrations: {
      directory: './knex/migrations',
    },
    seeds: {
      directory: './knex/seeds'
    }
  }

}
console.log("exporting module")
module.exports = config

控制台返回:

knex.js
knexfile.js
in get config
exporting module
Listening on: 3000
returning it***************pass username C:\project-webservice\root.cert

有谁看到我做错了什么?

4

1 回答 1

0

当然,在我发布后我就知道了:)

从 knex 文档中,我根据以下代码片段调整了我的 knexfile.js:

const knex = require('knex')({
  client: 'postgres',
  connection: async () => {
    const { token, tokenExpiration } = await someCallToGetTheToken();
    return {
      host : 'your_host',
      port : 3306,
      user : 'your_database_user',
      password : token,
      database : 'myapp_test',
      expirationChecker: () => {
        return tokenExpiration <= Date.now();
      }
    };
  }
});

具体来说:

 async () => {
    const { token, tokenExpiration } = await someCallToGetTheToken();
    return {
      host : 'your_host',
      port : 3306,
      user : 'your_database_user',
      password : token,
      database : 'myapp_test',
      expirationChecker: () => {
        return tokenExpiration <= Date.now();
      }
    };
于 2021-11-26T03:44:23.330 回答