-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathPermissions.js
54 lines (46 loc) · 1.93 KB
/
Permissions.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
'use strict';
class LambdaPermissions {
constructor(options, provider) {
this.options = options;
this.provider = provider;
}
getId(functionName,bucketName) {
const aliasName = this.options.alias ? `-${this.options.alias}` : '';
const id = `exS3-v2-${functionName}${aliasName}-${bucketName.replace(/[\.\:\*]/g,'')}`;
if (id.length < 100) { return id }
return id.substring(0,68) + require('crypto').createHash('md5').update(id).digest("hex")
}
createPolicy(functionName,bucketName,passthrough){
let region = (this.provider.sdk && this.provider.sdk.config && this.provider.sdk.config.region) || undefined;
const payload = {
Action: "lambda:InvokeFunction",
FunctionName: functionName,
Principal: 's3.amazonaws.com',
StatementId: this.getId(functionName,bucketName),
SourceArn: `arn:${(region && /^cn\-/.test(region)) ? 'aws-cn' : 'aws'}:s3:::${bucketName}`
};
if (this.options.alias) {
payload['Qualifier'] = this.options.alias;
}
return this.provider.request('Lambda', 'addPermission', payload)
.then( () => this.getPolicy(functionName, passthrough) )
}
getPolicy(functionName,passthrough) {
const payload = {FunctionName: functionName};
if (this.options.alias) {
payload['Qualifier'] = this.options.alias;
}
return this.provider.request('Lambda', 'getPolicy', payload)
.then( results => Object.assign({},{ statement: this.getStatement(this.asJson(results.Policy),passthrough), passthrough }) )
.catch( error => Object.assign({}, { error:error.message, passthrough } ) );
}
getStatement(policy,event) {
const policyId = this.getId(event.name, event.existingS3.bucket);
console.log("policyId",policyId);
return policy.Statement.find( statement => statement.Sid === policyId );
}
asJson(value){
return typeof value === 'string' ? JSON.parse(value) : value
}
}
module.exports.Lambda = LambdaPermissions;