const AWS = require('aws-sdk')
var axios = require('axios');
var aws4 = require('aws4');
var crypto = require('crypto-js');
const REGION = process.env.REGION || 'eu-west-1';
const ASSUME_ROLE_ARN = process.env.ASSUME_ROLE_ARN || '';
const API_ID_PARAMETER = process.env._API_ID_PARAMETER ;
exports.handler = async(event) => {
var mappedbody = event.body;
console.log('mappedbody : ' + mappedbody);
var sts = new AWS.STS({
region: REGION
});
console.log('sts success')
const getCrossAccountCredentials = async() => {
return new Promise((resolve, reject) => {
const timestamp = (new Date()).getTime();
const params = {
RoleArn: ASSUME_ROLE_ARN,
RoleSessionName: `tewt-${timestamp}`,
DurationSeconds: 3600
};
console.log('RoleSessionName : ' + params.RoleSessionName)
sts.assumeRole(params, (err, data) => {
if (err)
reject(err);
else {
resolve({
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken,
});
}
});
});
}
try {
const tempdata = await getCrossAccountCredentials();
var data = JSON.parse(JSON.stringify(tempdata));
console.log(data);
console.log(data.accessKeyId);
console.log(data.secretAccessKey);
const creds = {
accessKeyId: data.accessKeyId,
secretAccessKey: data.secretAccessKey,
sessionToken: data.sessionToken
};
console.log('AWS.SSM start')
var ssm = new AWS.SSM({
apiVersion: '2014-11-06',
region: REGION,
credentials: creds
});
console.log('AWS.SSM end')
const {
Parameter
} = await ssm
.getParameter({
Name: API_ID_PARAMETER
})
.promise();
console.log(Parameter.Value)
var hashedPayload = crypto.SHA256(mappedbody).toString();
let request = {
service: 'execute-api',
host: `${Parameter.Value}.execute-api.${REGION}.amazonaws.com`,
method: 'POST',
url: `https://${Parameter.Value}.execute-api.${REGION}.amazonaws.com/dev/insert`,
path: '/dev/insert',
data: mappedbody, // object describing the mappedbody
body: JSON.stringify(mappedbody),
headers: {
'Content-Type': 'application/json',
'X-Amz-Content-Sha256': hashedPayload,
}
};
console.log('request: ' + request);
let signedRequest = aws4.sign(request, creds);
console.log('signedReguest : ' + JSON.stringify(signedRequest));
delete signedRequest.headers['Host'];
delete signedRequest.headers['Content-Length'];
delete signedRequest.headers['Content-Type'];
const res = await axios(signedRequest);
console.log('Data:', res.data);
console.log('StatusCode:', res.statusCode);
var responseBody = '';
var response = '';
if (res.statusCode === '200') {
responseBody = {
Code: 202,
Description: "The request was successfully accepted"
};
response = {
"statusCode": 202,
"body": JSON.stringify(responseBody),
"isBase64Encoded": false
};
}
return response
} catch (err) {
console.log('Error:', err);
var responseBody = '';
var response = '';
responseBody = {
Code: 500,
Description: "Service unavailable"
};
response = {
"statusCode": 500,
"body": JSON.stringify(responseBody),
"isBase64Encoded": false
};
return response
}
};