-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (53 loc) · 1.75 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
'use strict';
const AWS = require('aws-sdk');
const crypto = require('crypto');
const Promise = require('bluebird');
const VARIABLE_PREFIX = 'stsCallerId';
const sts = new AWS.STS();
function sha1(data) {
return crypto.createHash('sha1').update(data).digest('hex');
}
class Plugin {
constructor(serverless, options) {
this.callerId = undefined;
const delegate = serverless.variables.getValueFromSource.bind(serverless.variables);
serverless.variables.getValueFromSource = (variableString) => {
if (variableString.startsWith(VARIABLE_PREFIX)) {
if (this.callerId !== undefined) {
return Promise.resolve(this.callerId)
}
return sts.getCallerIdentity()
.promise()
.then(data => {
const callerId = data.UserId;
if (variableString == VARIABLE_PREFIX) {
return callerId;
}
let variableParts = variableString.split(`${VARIABLE_PREFIX}:`);
if (variableParts.length > 1) {
variableParts = variableParts[1].split(':');
const suffix = variableParts[0];
if (suffix == 'hashed') {
const hashedCallerId = sha1(callerId);
if (variableParts.length === 2) {
const hashLength = parseInt(variableParts[1]);
if (hashLength) {
return hashedCallerId.slice(0, hashLength);
}
}
return hashedCallerId;
}
}
})
.then((res) => {
if (!res) {
return delegate(variableString);
}
return res;
});
}
return delegate(variableString);
}
}
}
module.exports = Plugin;