aboutsummaryrefslogtreecommitdiffhomepage
path: root/lib
diff options
context:
space:
mode:
authorMark Steele <mark.steele@autodesk.com>2018-04-17 16:41:11 -0400
committerMark Steele <mark.steele@autodesk.com>2018-04-17 16:41:11 -0400
commit80b6050c258f8504b04d59c5db67ddadc3403721 (patch)
treee9047bbe3dd483b788694d0b78ed23177f75ee07 /lib
downloadnetlify-serverless-oauth2-backend-80b6050c258f8504b04d59c5db67ddadc3403721.tar.gz
netlify-serverless-oauth2-backend-80b6050c258f8504b04d59c5db67ddadc3403721.tar.zst
netlify-serverless-oauth2-backend-80b6050c258f8504b04d59c5db67ddadc3403721.zip
Initial import
Diffstat (limited to 'lib')
-rw-r--r--lib/secrets.js62
1 files changed, 62 insertions, 0 deletions
diff --git a/lib/secrets.js b/lib/secrets.js
new file mode 100644
index 0000000..9559a47
--- /dev/null
+++ b/lib/secrets.js
@@ -0,0 +1,62 @@
1/* eslint-disable import/no-extraneous-dependencies */
2/* eslint-disable class-methods-use-this */
3const AWS = require('aws-sdk');
4
5const MAX_SSM_PARAMETERS_PER_REQUEST = 10;
6
7class Secrets {
8 constructor(secretList) {
9 this.secretList = secretList;
10 Object.keys(secretList).forEach((secret) => {
11 this[secret] = secretList[secret];
12 });
13 }
14
15 flattenParameters(params) {
16 const flat = {};
17 params.forEach((param) => {
18 flat[param.Name.replace(/^.+\/(.+)$/, '$1')] = param.Value;
19 });
20 return flat;
21 }
22
23 init() {
24 if (this.initPromise === undefined) {
25 this.initPromise = new Promise((resolve, reject) => {
26 const shouldLoadSecretsFromSsm = !process.env.IS_OFFLINE || process.env.IS_TEST;
27 if (shouldLoadSecretsFromSsm) {
28 this.loadSecrets().then(resolve, reject);
29 } else {
30 resolve();
31 }
32 });
33 }
34 return this.initPromise;
35 }
36
37 loadSecrets() {
38 const ssm = new AWS.SSM();
39 const secretNames = Object.keys(this.secretList).map(secret => process.env[secret]);
40
41 // Create an array of promises of SSM getparameters requests.
42 // Max 10 per call.
43 const promises = [];
44 while (secretNames.length > 0) {
45 const subSet = secretNames.splice(0, MAX_SSM_PARAMETERS_PER_REQUEST);
46 promises.push(ssm.getParameters({ Names: subSet, WithDecryption: true }).promise());
47 }
48 return Promise.all(promises)
49 .then((secrets) => {
50 const settingsArray = [];
51 secrets.forEach((secretSet) => {
52 settingsArray.push(...secretSet.Parameters);
53 });
54 const settings = this.flattenParameters(settingsArray);
55 Object.keys(settings).forEach((setting) => {
56 this[setting] = settings[setting];
57 });
58 });
59 }
60}
61
62module.exports = Secrets;