-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
249 lines (225 loc) · 7.95 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
'use strict';
/**
* serverless-kms-secrets
* - a plugin for for encrypting secrets using KMS with Serverless Framework
*/
const fse = require('fs-extra');
const BbPromise = require('bluebird');
const yaml = require('yamljs');
function readFile(filePath) {
return new BbPromise((resolve, reject) => {
if (!fse.existsSync(filePath)) {
reject(`No file ${filePath}`);
}
const kmsSecrets = yaml.load(filePath);
return resolve(kmsSecrets.secrets);
});
}
class kmsSecretsPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
encrypt: {
usage: 'Encrypt variables to file',
lifecycleEvents: [
'kmsEncrypt',
],
options: {
name: {
usage: 'Name of variable',
shortcut: 'n',
required: true,
},
value: {
usage: 'Value of variable',
shortcut: 'v',
required: true,
},
keyid: {
usage: 'KMS key Id',
shortcut: 'k',
required: false,
},
},
},
decrypt: {
usage: 'Decrypt variables from file',
lifecycleEvents: [
'kmsDecrypt',
],
options: {
name: {
usage: 'Name of variable',
shortcut: 'n',
required: false,
},
},
},
};
this.hooks = {
'encrypt:kmsEncrypt': this.encryptVariable.bind(this),
'decrypt:kmsDecrypt': this.decryptVariable.bind(this),
};
}
decrypt(secret, region, stage) {
const myModule = this;
return new Promise((success, failure) => {
myModule.serverless.getProvider('aws')
.request('KMS',
'decrypt',
{
CiphertextBlob: Buffer.from(secret, 'base64'), // eslint-disable-line new-cap
}, region, stage)
.then((data) => {
success(String(data.Plaintext));
}, failure);
});
}
encryptVariable() {
return new Promise((resolve, reject) => {
const myModule = this;
let stage = this.options.stage;
let region = this.options.region;
const parts = this.options.name.split(':');
const varname = parts[0];
const subvarname = parts[1];
let value = this.options.value;
this.serverless.service.load({
stage,
region,
})
.then((inited) => {
myModule.serverless.environment = inited.environment;
const vars = new myModule.serverless.classes.Variables(myModule.serverless);
return vars.populateService(this.options).then(() => inited);
})
.then((inited) => {
const moduleConfig = inited.custom['serverless-kms-secrets'] || {};
region = this.options.region || inited.provider.region;
stage = this.options.stage || inited.provider.stage;
const configFile =
moduleConfig.secretsFile
|| `kms-secrets.${stage}.${region}.yml`;
let kmsSecrets = {
secrets: {},
};
let keyId = this.options.keyid;
if (fse.existsSync(configFile)) {
kmsSecrets = yaml.load(configFile);
if (!keyId) {
keyId = kmsSecrets.keyArn.replace(/.*\//, '');
myModule.serverless.cli.log(`Encrypting using key ${keyId} found in ${configFile}`);
}
} else if (!this.options.keyid) {
myModule.serverless.cli.log(`No config file ${configFile} and no keyid specified`);
reject('No keyId in serverless.yml');
}
function preEncrypt() {
return new Promise((succeed) => {
if (subvarname) {
if (kmsSecrets &&
kmsSecrets.secrets &&
kmsSecrets.secrets[varname]) {
myModule.decrypt(kmsSecrets.secrets[varname], region, stage)
.then((valtext) => {
succeed(JSON.parse(valtext));
});
} else {
succeed({});
}
} else {
succeed({});
}
});
}
return preEncrypt()
.then((valstruct) => {
if (subvarname) {
const newStruct = valstruct;
newStruct[subvarname] = value;
value = JSON.stringify(newStruct);
}
myModule.serverless.getProvider('aws')
.request('KMS',
'encrypt',
{
KeyId: keyId, // The identifier of the CMK to use for encryption.
// You can use the key ID or Amazon Resource Name (ARN) of the CMK,
// or the name or ARN of an alias that refers to the CMK.
Plaintext: Buffer.from(String(value)), // eslint-disable-line new-cap
}, region, stage)
.then((data) => {
kmsSecrets.secrets[varname] = data.CiphertextBlob.toString('base64');
kmsSecrets.keyArn = data.KeyId;
fse.writeFileSync(configFile, yaml.stringify(kmsSecrets, 2));
myModule.serverless.cli.log(`Updated ${varname} to ${configFile}`);
resolve();
}, (error) => {
myModule.serverless.cli.log(error);
reject(error);
});
});
}, (error) => {
myModule.serverless.cli.log(error);
reject(error);
});
});
}
// Decrypt a variable defined in the options
decryptVariable() {
return new Promise((resolve, reject) => {
const myModule = this;
let stage = this.options.stage;
let region = this.options.region;
this.serverless.service.load({
stage,
region,
})
.then((inited) => {
myModule.serverless.environment = inited.environment;
const vars = new myModule.serverless.classes.Variables(myModule.serverless);
return vars.populateService(this.options).then(() => inited);
})
.then((inited) => {
const moduleConfig = inited.custom['serverless-kms-secrets'] || {};
stage = this.options.stage || inited.provider.stage;
region = this.options.region || inited.provider.region;
const configFile =
moduleConfig.secretsFile
|| `kms-secrets.${stage}.${region}.yml`;
myModule.serverless.cli.log(`Decrypting secrets from ${configFile}`);
readFile(configFile)
.then((secrets) => {
const names = this.options.name ? [this.options.name] : Object.keys(secrets);
names.forEach((varName) => {
const parts = varName.split(':');
const mainVarName = parts[0];
const subVarName = parts[1];
if (secrets[mainVarName]) {
myModule.decrypt(secrets[mainVarName], region, stage)
.then((secret) => {
if (subVarName) {
let varStruct = {};
if (secret) {
varStruct = JSON.parse(secret);
}
myModule.serverless.cli.log(`${varName} = ${varStruct[subVarName] || ''}`);
} else {
myModule.serverless.cli.log(`${varName} = ${secret}`);
}
}, (error) => {
myModule.serverless.cli.log(`KMS error ${error}`);
reject(error);
});
} else {
myModule.serverless.cli.log(`No secret with name ${varName}`);
resolve();
}
});
}, error => myModule.serverless.cli.log(error));
}, error => myModule.serverless.cli.log(error));
});
}
}
module.exports = kmsSecretsPlugin;