Overview of the AWS CloudTrail Analytics Dashboard
46 |
This dashboard and its associated solution provide a mechanism for collecting, analyzing, and displaying AWS account activity in real time. The solution logs events for your AWS account using AWS CloudTrail which include actions taken through the AWS Management Console, AWS SDKs, command line tools, and other AWS services. That data is captured and analyzed by Amazon Kinesis to produce important metrics in real time and persist them to DynamoDB. The processed data is visualized using a custom dashboard you see below using a website hosted on Amazon S3. All raw and processed data is archived in Amazon S3.
47 |
48 |
Many events are processed in real time but some events take up to 15 minutes to arrive from AWS CloudTrail. The dashboard loads new data from DynamoDB into line graphs every 10 seconds and bar charts every 1 minute. The past 15 minutes of data are updated every 1 minute to capture events that arrive late from AWS CloudTrail.
49 |
Use of Amazon Cognito
50 |
This solution uses Amazon Cognito for authentication. The solution asks for a user name and email address when it is launched. Durning deployoment, an Amazon Cognito User Pool and user are created for you. The user ID and temporary password are emailed to the provided email address. Additional users can be added to the dashboard by using the Amazon Cognito console and adding additional users.
51 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/source/helper/lib/metrics-helper.js:
--------------------------------------------------------------------------------
1 | /*********************************************************************************************************************
2 | * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. *
3 | * *
4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance *
5 | * with the License. A copy of the License is located at *
6 | * *
7 | * http://www.apache.org/licenses/LICENSE-2.0 *
8 | * *
9 | * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES *
10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions *
11 | * and limitations under the License. *
12 | *********************************************************************************************************************/
13 |
14 | /**
15 | * @author Solution Builders
16 | */
17 |
18 | 'use strict';
19 |
20 | let moment = require('moment');
21 | let https = require('https');
22 |
23 | /**
24 | * Helper function to send anonymous data from cfn custom resource.
25 | *
26 | * @class metricsHelper
27 | */
28 | let metricsHelper = (function() {
29 |
30 | /**
31 | * @class metricsHelper
32 | * @constructor
33 | */
34 | let metricsHelper = function() {};
35 |
36 | /**
37 | * Sends opt-in, anonymous metric.
38 | * @param {json} metric - metric to send to opt-in, anonymous collection.
39 | * @param {sendAnonymousMetric~requestCallback} cb - The callback that handles the response.
40 | */
41 | metricsHelper.prototype.sendAnonymousMetric = function(metric, cb) {
42 |
43 | let _options = {
44 | hostname: 'metrics.awssolutionsbuilder.com',
45 | port: 443,
46 | path: '/generic',
47 | method: 'POST',
48 | headers: {
49 | 'Content-Type': 'application/json'
50 | }
51 | };
52 |
53 | let request = https.request(_options, function(response) {
54 | // data is streamed in chunks from the server
55 | // so we have to handle the "data" event
56 | let buffer;
57 | let data;
58 | let route;
59 |
60 | response.on('data', function(chunk) {
61 | buffer += chunk;
62 | });
63 |
64 | response.on('end', function(err) {
65 | data = buffer;
66 | cb(null, data);
67 | });
68 | });
69 |
70 | if (metric) {
71 | request.write(JSON.stringify(metric));
72 | }
73 |
74 | request.end();
75 |
76 | request.on('error', (e) => {
77 | console.error(e);
78 | cb(['Error occurred when sending metric request.', JSON.stringify(_payload)].join(' '), null);
79 | });
80 | };
81 |
82 | return metricsHelper;
83 |
84 | })();
85 |
86 | module.exports = metricsHelper;
87 |
--------------------------------------------------------------------------------
/deployment/manifest-generator/app.js:
--------------------------------------------------------------------------------
1 | /*********************************************************************************************************************
2 | * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. *
3 | * *
4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance *
5 | * with the License. A copy of the License is located at *
6 | * *
7 | * http://www.apache.org/licenses/LICENSE-2.0 *
8 | * *
9 | * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES *
10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions *
11 | * and limitations under the License. *
12 | *********************************************************************************************************************/
13 |
14 | /**
15 | * @author Solution Builders
16 | */
17 |
18 | 'use strict';
19 |
20 | const fs = require('fs');
21 | const path = require('path');
22 | const args = require('minimist')(process.argv.slice(2));
23 |
24 | let getFileList = function(path) {
25 | let fileInfo;
26 | let filesFound;
27 | let fileList = [];
28 |
29 | filesFound = fs.readdirSync(path);
30 | for (let i = 0; i < filesFound.length; i++) {
31 | fileInfo = fs.lstatSync([path, filesFound[i]].join('/'));
32 | if (fileInfo.isFile()) {
33 | fileList.push(filesFound[i]);
34 | }
35 |
36 | if (fileInfo.isDirectory()) {
37 | console.log([path, filesFound[i]].join('/'));
38 | }
39 | }
40 |
41 | return fileList;
42 | };
43 |
44 | // List all files in a directory in Node.js recursively in a synchronous fashion
45 | let walkSync = function(dir, filelist) {
46 | // let filelist = []; //getFileList('./temp/site');
47 | let files = fs.readdirSync(dir);
48 | filelist = filelist || [];
49 | files.forEach(function(file) {
50 | if (fs.statSync(path.join(dir, file)).isDirectory()) {
51 | filelist = walkSync(path.join(dir, file), filelist);
52 | } else {
53 | filelist.push(path.join(dir, file));
54 | }
55 | });
56 |
57 | return filelist;
58 | };
59 |
60 | let _filelist = [];
61 | let _manifest = {
62 | files: []
63 | };
64 |
65 | if (!args.hasOwnProperty('target')) {
66 | console.log('--target parameter missing. This should be the target directory containing content for the manifest.');
67 | process.exit(1);
68 | }
69 |
70 | if (!args.hasOwnProperty('output')) {
71 | console.log('--ouput parameter missing. This should be the out directory where the manifest file will be generated.');
72 | process.exit(1);
73 | }
74 |
75 | console.log(`Generating a manifest file ${args.output} for directory ${args.target}`);
76 |
77 | walkSync(args.target, _filelist);
78 |
79 | for (let i = 0; i < _filelist.length; i++) {
80 | _manifest.files.push(_filelist[i].replace(`${args.target}/`, ''));
81 | };
82 |
83 | fs.writeFileSync(args.output, JSON.stringify(_manifest, null, 4));
84 | console.log(`Manifest file ${args.output} generated.`);
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
4 | documentation, we greatly value feedback and contributions from our community.
5 |
6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
7 | information to effectively respond to your bug report or contribution.
8 |
9 |
10 | ## Reporting Bugs/Feature Requests
11 |
12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features.
13 |
14 | When filing an issue, please check [existing open](https://github.com/awslabs/real-time-iot-device-monitoring-with-kinesis/issues), or [recently closed](https://github.com/awslabs/real-time-iot-device-monitoring-with-kinesis/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already
15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:
16 |
17 | * A reproducible test case or series of steps
18 | * The version of our code being used
19 | * Any modifications you've made relevant to the bug
20 | * Anything unusual about your environment or deployment
21 |
22 |
23 | ## Contributing via Pull Requests
24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:
25 |
26 | 1. You are working against the latest source on the *master* branch.
27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted.
29 |
30 | To send us a pull request, please:
31 |
32 | 1. Fork the repository.
33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
34 | 3. Ensure local tests pass.
35 | 4. Commit to your fork using clear commit messages.
36 | 5. Send us a pull request, answering any default questions in the pull request interface.
37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.
38 |
39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/).
41 |
42 |
43 | ## Finding contributions to work on
44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/awslabs/real-time-iot-device-monitoring-with-kinesis/labels/help%20wanted) issues is a great place to start.
45 |
46 |
47 | ## Code of Conduct
48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
50 | opensource-codeofconduct@amazon.com with any additional questions or comments.
51 |
52 |
53 | ## Security issue notifications
54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.
55 |
56 |
57 | ## Licensing
58 |
59 | See the [LICENSE](https://github.com/awslabs/real-time-iot-device-monitoring-with-kinesis/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
60 |
61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes.
--------------------------------------------------------------------------------
/deployment/build-s3-dist.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | #
3 | # This assumes all of the OS-level configuration has been completed and git repo has already been cloned
4 | #
5 | # This script should be run from the repo's deployment directory
6 | # cd deployment
7 | # ./build-s3-dist.sh source-bucket-base-name trademarked-solution-name version-code
8 | #
9 | # Paramenters:
10 | # - source-bucket-base-name: Name for the S3 bucket location where the template will source the Lambda
11 | # code from. The template will append '-[region_name]' to this bucket name.
12 | # For example: ./build-s3-dist.sh solutions my-solution v1.0.0
13 | # The template will then expect the source code to be located in the solutions-[region_name] bucket
14 | #
15 | # - trademarked-solution-name: name of the solution for consistency
16 | #
17 | # - version-code: version of the package
18 |
19 | # Check to see if input has been provided:
20 | if [ -z "$1" ] || [ -z "$2" ] || [ -z "$3" ]; then
21 | echo "Please provide the base source bucket name (where the lambda code will eventually reside), trademark approved solution name and version."
22 | echo "For example: ./build-s3-dist.sh solutions trademarked-solution-name v1.0.0"
23 | exit 1
24 | fi
25 |
26 | # Get reference for all important folders
27 | template_dir="$PWD"
28 | template_dist_dir="$template_dir/global-s3-assets"
29 | build_dist_dir="$template_dir/regional-s3-assets"
30 | source_dir="$template_dir/../source"
31 |
32 | echo "------------------------------------------------------------------------------"
33 | echo "[Init] Clean old dist, node_modules and bower_components folders"
34 | echo "------------------------------------------------------------------------------"
35 | rm -rf $template_dist_dir
36 | mkdir -p $template_dist_dir
37 | rm -rf $build_dist_dir
38 | mkdir -p $build_dist_dir
39 |
40 | echo "------------------------------------------------------------------------------"
41 | echo "[Packing] Templates"
42 | echo "------------------------------------------------------------------------------"
43 | cp $template_dir/real-time-insights-account-activity.template $template_dist_dir/
44 |
45 | replace="s/%%BUCKET_NAME%%/$1/g"
46 | sed -i '' -e $replace $template_dist_dir/real-time-insights-account-activity.template
47 | replace="s/%%SOLUTION_NAME%%/$2/g"
48 | sed -i '' -e $replace $template_dist_dir/real-time-insights-account-activity.template
49 | replace="s/%%VERSION%%/$3/g"
50 | sed -i '' -e $replace $template_dist_dir/real-time-insights-account-activity.template
51 |
52 | echo "------------------------------------------------------------------------------"
53 | echo "[Build] Custom resource helper Lambda function"
54 | echo "------------------------------------------------------------------------------"
55 | cd $source_dir/helper
56 | npm install
57 | npm run build
58 | npm run zip
59 | cp ./dist/custom-resource-helper.zip $build_dist_dir/custom-resource-helper.zip
60 | rm -rf dist
61 | rm -rf node_modules
62 |
63 | echo "------------------------------------------------------------------------------"
64 | echo "[Build] Lambda function to update DDB from Kinesis stream"
65 | echo "------------------------------------------------------------------------------"
66 | cd $source_dir/update_ddb_from_stream
67 | rm -rf ./dist && mkdir ./dist
68 | cp update_ddb_from_stream.py ./dist
69 | cd dist
70 | zip -r update_ddb_from_stream.zip .
71 | cp ./update_ddb_from_stream.zip $build_dist_dir/update_ddb_from_stream.zip
72 |
73 | echo "------------------------------------------------------------------------------"
74 | echo "[Build] Copying web site content"
75 | echo "------------------------------------------------------------------------------"
76 | cp -r $source_dir/web_site $build_dist_dir/
77 |
78 | echo "------------------------------------------------------------------------------"
79 | echo "[Build] Generating web site manifest"
80 | echo "------------------------------------------------------------------------------"
81 | cd "$template_dir/manifest-generator" || exit
82 | npm install
83 | node app.js --target "$build_dist_dir/web_site" --output "$build_dist_dir/web-site-manifest.json"
84 |
85 | echo "------------------------------------------------------------------------------"
86 | echo "S3 Packaging Complete"
87 | echo "------------------------------------------------------------------------------"
88 |
--------------------------------------------------------------------------------
/source/helper/lib/kinesisapp-helper.js:
--------------------------------------------------------------------------------
1 | /*********************************************************************************************************************
2 | * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. *
3 | * *
4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance *
5 | * with the License. A copy of the License is located at *
6 | * *
7 | * http://www.apache.org/licenses/LICENSE-2.0 *
8 | * *
9 | * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES *
10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions *
11 | * and limitations under the License. *
12 | *********************************************************************************************************************/
13 |
14 | /**
15 | * @author Solution Builders
16 | */
17 |
18 | 'use strict';
19 |
20 | let AWS = require('aws-sdk');
21 | let ka = new AWS.KinesisAnalytics();
22 |
23 | /**
24 | * Helper function to turn on a Kinesis Analytics app cfn custom resource.
25 | *
26 | * @class bucketEncryptionHelper
27 | */
28 | let kinesisAnalyticsAppHelper = (function() {
29 |
30 | /**
31 | * @class bucketEncryptionHelper
32 | * @constructor
33 | */
34 | let kinesisAnalyticsAppHelper = function() {};
35 |
36 | /**
37 | * Starts a Kinesis Data Analytics application.
38 | * @param {string} ApplicationName - Name of the Kinesis Data Analytics application.
39 | * @param {copyWebSiteAssets~requestCallback} cb - The callback that handles the response.
40 | */
41 | kinesisAnalyticsAppHelper.prototype.startApplication = function(ApplicationName, cb) {
42 | console.log(['Looking up Kinesis Data Analytics application:', ApplicationName].join(' '));
43 | var params = {
44 | ApplicationName: ApplicationName
45 | };
46 | ka.describeApplication(params, function(err, app_description) {
47 | if (app_description == null) {
48 | console.log(['Could not find application:', ApplicationName].join(' '));
49 | return cb(['Kinesis Data Analytics application,', ApplicationName, ', could not be found!'].join(' '), null);
50 | }
51 | console.log('app status: ',app_description.ApplicationDetail.ApplicationStatus);
52 | if (err) {
53 | console.log(['Failed to describe application:', err].join(' '));
54 | return cb(err, null);
55 | } else {
56 | if (app_description.ApplicationDetail.ApplicationStatus === 'READY') {
57 | //Start App
58 | params = {
59 | ApplicationName: ApplicationName,
60 | InputConfigurations: [
61 | {
62 | 'Id': '1.1',
63 | 'InputStartingPositionConfiguration': {
64 | 'InputStartingPosition': 'NOW'
65 | }
66 | }
67 | ]
68 | };
69 | console.log("Starting application");
70 | ka.startApplication(params, function(err, response) {
71 | if (err) {
72 | console.log(['Failed to start application', item.ApplicationName, ': ', err].join(' '));
73 | return cb(err, null);
74 | } else {
75 | return cb(null, "SUCCESS");
76 | }
77 | });
78 | } else {
79 | return cb(['Kinesis Data Analytics Application was not in READY state (app status === ', app_description.ApplicationDetail.ApplicationStatus,')'].join(''), null);
80 | }
81 | }
82 | });
83 | };
84 |
85 | return kinesisAnalyticsAppHelper;
86 |
87 | })();
88 |
89 | module.exports = kinesisAnalyticsAppHelper;
90 |
--------------------------------------------------------------------------------
/source/helper/index.js:
--------------------------------------------------------------------------------
1 | /*********************************************************************************************************************
2 | * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. *
3 | * *
4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance *
5 | * with the License. A copy of the License is located at *
6 | * *
7 | * http://www.apache.org/licenses/LICENSE-2.0 *
8 | * *
9 | * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES *
10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions *
11 | * and limitations under the License. *
12 | *********************************************************************************************************************/
13 |
14 | /**
15 | * @author Solution Builders
16 | */
17 |
18 | 'use strict';
19 |
20 | console.log('Loading function');
21 |
22 | const AWS = require('aws-sdk');
23 | const https = require('https');
24 | const url = require('url');
25 | const moment = require('moment');
26 | const WebsiteHelper = require('./lib/website-helper.js');
27 | const MetricsHelper = require('./lib/metrics-helper.js');
28 | const KinesisAppHelper = require('./lib/kinesisapp-helper.js');
29 | const UUID = require('node-uuid');
30 |
31 | /**
32 | * Request handler.
33 | */
34 | exports.handler = (event, context, callback) => {
35 | console.log('Received event:', JSON.stringify(event, null, 2));
36 |
37 | let responseStatus = 'FAILED';
38 | let responseData = {};
39 |
40 | if (event.RequestType === 'Delete') {
41 | if (event.ResourceProperties.customAction === 'sendMetric') {
42 | responseStatus = 'SUCCESS';
43 |
44 | let _metricsHelper = new MetricsHelper();
45 |
46 | let _metric = {
47 | Solution: event.ResourceProperties.solutionId,
48 | UUID: event.ResourceProperties.UUID,
49 | TimeStamp: moment().utc().format('YYYY-MM-DD HH:mm:ss.S'),
50 | Data: {
51 | Version: event.ResourceProperties.version,
52 | RequestType: event.RequestType
53 | }
54 | };
55 |
56 | _metricsHelper.sendAnonymousMetric(_metric, function(err, data) {
57 | if (err) {
58 | responseData = {
59 | Error: 'Sending metrics helper delete failed'
60 | };
61 | console.log([responseData.Error, ':\n', err].join(''));
62 | }
63 | sendResponse(event, callback, context.logStreamName, 'SUCCESS');
64 | });
65 | } else {
66 | sendResponse(event, callback, context.logStreamName, 'SUCCESS');
67 | }
68 | }
69 |
70 | if (event.RequestType === 'Create') {
71 | if (event.ResourceProperties.customAction === 'configureWebsite') {
72 | let _websiteHelper = new WebsiteHelper();
73 | //BUGFIX removed hardcoded table names:: analyticsTable &\ ipTable
74 | _websiteHelper.copyWebSiteAssets(event.ResourceProperties.sourceS3Bucket,
75 | event.ResourceProperties.sourceS3key, event.ResourceProperties.sourceManifest, event.ResourceProperties.destS3Bucket,
76 | event.ResourceProperties.userPoolId, event.ResourceProperties.userPoolClientId,
77 | event.ResourceProperties.identityPoolId, event.ResourceProperties.region,
78 | event.ResourceProperties.UUID, event.ResourceProperties.anonymousData,event.ResourceProperties.analyticsTable, event.ResourceProperties.ipTable,
79 | function(err, data) {
80 | if (err) {
81 | responseData = {
82 | Error: 'Copy of website assets failed'
83 | };
84 | console.log([responseData.Error, ':\n', err].join(''));
85 | } else {
86 | responseStatus = 'SUCCESS';
87 | responseData = {};
88 | }
89 |
90 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData);
91 | });
92 |
93 | } else if (event.ResourceProperties.customAction === 'startKinesisApplication') {
94 | let _kinesisAppHelper = new KinesisAppHelper();
95 |
96 | _kinesisAppHelper.startApplication(event.ResourceProperties.ApplicationName,
97 | function(err, data) {
98 | if (err) {
99 | responseData = {
100 | Error: 'Starting kinesis application failed'
101 | };
102 | console.log([responseData.Error, ':\n', err].join(''));
103 | } else {
104 | responseStatus = 'SUCCESS';
105 | responseData = {};
106 | }
107 |
108 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData);
109 | });
110 |
111 | } else if (event.ResourceProperties.customAction === 'createUuid') {
112 | responseStatus = 'SUCCESS';
113 | responseData = {
114 | UUID: UUID.v4()
115 | };
116 | sendResponse(event, callback, context.logStreamName, responseStatus, responseData);
117 |
118 | } else if (event.ResourceProperties.customAction === 'sendMetric') {
119 | let _metricsHelper = new MetricsHelper();
120 |
121 | let _metric = {
122 | Solution: event.ResourceProperties.solutionId,
123 | UUID: event.ResourceProperties.UUID,
124 | TimeStamp: moment().utc().format('YYYY-MM-DD HH:mm:ss.S'),
125 | Data: {
126 | Version: event.ResourceProperties.version,
127 | SendAnonymousData: event.ResourceProperties.anonymousData,
128 | RequestType: event.RequestType
129 | }
130 | };
131 |
132 | _metricsHelper.sendAnonymousMetric(_metric, function(err, data) {
133 | if (err) {
134 | responseData = {
135 | Error: 'Sending anonymous launch metric failed'
136 | };
137 | console.log([responseData.Error, ':\n', err].join(''));
138 | } else {
139 | responseStatus = 'SUCCESS';
140 | responseData = {};
141 | }
142 | });
143 | sendResponse(event, callback, context.logStreamName, 'SUCCESS');
144 | }
145 |
146 | }
147 |
148 | };
149 |
150 | /**
151 | * Sends a response to the pre-signed S3 URL
152 | */
153 | let sendResponse = function(event, callback, logStreamName, responseStatus, responseData) {
154 | const responseBody = JSON.stringify({
155 | Status: responseStatus,
156 | Reason: `See the details in CloudWatch Log Stream: ${logStreamName}`,
157 | PhysicalResourceId: logStreamName,
158 | StackId: event.StackId,
159 | RequestId: event.RequestId,
160 | LogicalResourceId: event.LogicalResourceId,
161 | Data: responseData,
162 | });
163 |
164 | console.log('RESPONSE BODY:\n', responseBody);
165 | const parsedUrl = url.parse(event.ResponseURL);
166 | const options = {
167 | hostname: parsedUrl.hostname,
168 | port: 443,
169 | path: parsedUrl.path,
170 | method: 'PUT',
171 | headers: {
172 | 'Content-Type': '',
173 | 'Content-Length': responseBody.length,
174 | }
175 | };
176 |
177 | const req = https.request(options, (res) => {
178 | console.log('STATUS:', res.statusCode);
179 | console.log('HEADERS:', JSON.stringify(res.headers));
180 | callback(null, 'Successfully sent stack response!');
181 | });
182 |
183 | req.on('error', (err) => {
184 | console.log('sendResponse Error:\n', err);
185 | callback(err);
186 | });
187 |
188 | req.write(responseBody);
189 | req.end();
190 | };
191 |
--------------------------------------------------------------------------------
/source/update_ddb_from_stream/update_ddb_from_stream.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # -*- coding: utf-8 -*-
3 |
4 | # #####################################################################################################################
5 | # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
6 | # #
7 | # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance #
8 | # with the License. A copy of the License is located at #
9 | # #
10 | # http://www.apache.org/licenses/LICENSE-2.0 #
11 | # #
12 | # or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES #
13 | # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions #
14 | # and limitations under the License. #
15 | #######################################################################################################################
16 |
17 | # @author Solution Builders
18 |
19 | from itertools import groupby
20 | import boto3
21 | import botocore
22 | import base64
23 | import os
24 | import logging
25 | import urllib.request
26 | import urllib.parse
27 | from json import loads,dumps
28 | from collections import OrderedDict
29 | from operator import itemgetter
30 | from random import randint
31 | from sys import maxsize
32 | from time import sleep
33 |
34 | log_level = str(os.environ.get('LOG_LEVEL')).upper()
35 | if log_level not in ['DEBUG', 'INFO','WARNING', 'ERROR','CRITICAL']:
36 | log_level = 'ERROR'
37 | log = logging.getLogger()
38 | log.setLevel(log_level)
39 |
40 | send_anonymous_data = str(os.environ.get('SEND_ANONYMOUS_DATA')).upper()
41 | ip_table_name = os.environ.get('IP_TABLE')
42 | table_name = os.environ.get('TABLE')
43 | calls_per_ip="CallsPerUniqueIp"
44 | successful_calls = "NumberOfSuccessfulCalls"
45 | anomaly_score = "AnomalyScore"
46 | max_retry_attempts = 5
47 | client = boto3.client('dynamodb')
48 |
49 | def update_dynamodb(record_data):
50 | ddb_record = client.get_item(TableName=table_name,
51 | Key={'MetricType': {'S':metric_type},
52 | 'EventTime':{'S':event_time} },
53 | ConsistentRead=True)
54 |
55 | ddb_data = loads(ddb_record['Item']['Data']['S'])
56 | concurrency_token = int(ddb_record['Item']['ConcurrencyToken']['N'])
57 | merged_data = { k : record_data.get(k,0) + ddb_data.get(k,0) for k in set(record_data) | set(ddb_data) }
58 | record_data = OrderedDict(sorted(merged_data.items(), key=itemgetter(1), reverse=True))
59 | put_record(metric_type, event_time, record_data, concurrency_token)
60 |
61 | def put_record_with_retry(metric_type, event_time, record_data, merged_data, concurrency_token, attempt=0):
62 | log.info("Retry: {0} {1} {2}".format(metric_type, event_time, str(attempt)))
63 | if attempt > max_retry_attempts: return
64 | try:
65 | put_record(metric_type, event_time, merged_data, concurrency_token)
66 | except botocore.exceptions.ClientError as e:
67 | if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
68 | sleep(randint(0,5))
69 | ddb_record = client.get_item(TableName=table_name,
70 | Key={'MetricType': {'S':metric_type},
71 | 'EventTime':{'S':event_time} },
72 | ConsistentRead=True)
73 | merged_data = merge_record_with_ddb(record_data, ddb_record)
74 | put_record_with_retry(metric_type, event_time, record_data, merged_data, concurrency_token, attempt+1)
75 | else: raise
76 |
77 | def put_record(metric_type, event_time, data, concurrency_token=None):
78 | item = {'MetricType': {'S':metric_type},
79 | 'EventTime':{'S':event_time},
80 | 'Data':{'S':dumps(data)},
81 | 'ConcurrencyToken':{'N':str(randint(0,maxsize))}}
82 | if concurrency_token:
83 | client.put_item(TableName=table_name, Item=item,
84 | ConditionExpression='ConcurrencyToken = :concurrency_token',
85 | ExpressionAttributeValues={':concurrency_token':{'N':str(concurrency_token)}})
86 | else:
87 | client.put_item(TableName=table_name, Item=item)
88 |
89 | def merge_record_with_ddb(record_data, ddb_record):
90 | ddb_data = loads(ddb_record['Item']['Data']['S'])
91 | concurrency_token = int(ddb_record['Item']['ConcurrencyToken']['N'])
92 | merged_data = { k : record_data.get(k,0) + ddb_data.get(k,0) for k in set(record_data) | set(ddb_data) }
93 | merged_data = OrderedDict(sorted(merged_data.items(), key=itemgetter(1), reverse=True))
94 | return merged_data
95 |
96 | def merge_record_values(metric_key, grouped_rows):
97 | if 'AnomalyScore' in metric_key:
98 | return sum(float(key[5]) for key in grouped_rows)
99 | else:
100 | return sum(int(key[5]) for key in grouped_rows)
101 |
102 | #This function sends anonymous usage data, if enabled
103 | def sendAnonymousData(event_time,dataDict):
104 | log.debug("Sending Anonymous Data")
105 | postDict = {}
106 | postDict['Data'] = dataDict
107 | postDict['TimeStamp'] = event_time
108 | postDict['Solution'] = 'SO0037'
109 | postDict['UUID'] = os.environ.get('UUID')
110 |
111 | # API Gateway URL to make HTTP POST call
112 | url = 'https://metrics.awssolutionsbuilder.com/generic'
113 | data = urllib.parse.urlencode(postDict).encode()
114 | log.debug(data)
115 |
116 | headers = {'content-type': 'application/json'}
117 | req = urllib.request.Request(url, data, headers)
118 | rsp = urllib.request.urlopen(req)
119 | rspcode = rsp.getcode()
120 | content = rsp.read()
121 | log.debug("Response from APIGateway: %s, %s", rspcode, content)
122 |
123 | def lambda_handler(event, context):
124 | payload = event['Records']
125 | output = {}
126 |
127 | data = [base64.b64decode(record['kinesis']['data']).decode().strip().split(',') for record in payload]
128 | data = filter(lambda x: x[2]!="null", data)
129 | log.info(data)
130 |
131 | for metric_key,metric_group in groupby(data, key=lambda x:"{0}|{1}".format(x[0],x[1])):
132 | grouped_metric = list(metric_group)
133 | for category_key,grouped_rows in groupby(grouped_metric, key=lambda x: "{0}|{1}".format(x[2],x[3])):
134 | output.setdefault(metric_key, {})[category_key] = merge_record_values(metric_key, list(grouped_rows))
135 |
136 | for record_key in output:
137 | event_time,metric_type = record_key.split('|')
138 | record_data = OrderedDict(sorted(output[record_key].items(), key=itemgetter(1), reverse=True))
139 |
140 | ddb_record = client.get_item(TableName=table_name,
141 | Key={'MetricType': {'S':metric_type},
142 | 'EventTime':{'S':event_time} },
143 | ConsistentRead=True)
144 |
145 | if 'Item' not in ddb_record:
146 | put_record(metric_type,event_time, record_data)
147 | else:
148 | merged_data = merge_record_with_ddb(record_data, ddb_record)
149 | put_record_with_retry(metric_type, event_time, record_data, merged_data, int(ddb_record['Item']['ConcurrencyToken']['N']))
150 | if metric_type == calls_per_ip:
151 | max_ip = next(iter(record_data))
152 | max_ip_count = record_data[max_ip]
153 |
154 | max_ip = max_ip.split('|')[0]
155 | hour,minute,_ = event_time.split(':')
156 |
157 | ddb_max_ip = client.get_item(TableName=ip_table_name,
158 | Key={'Hour': {'S': hour},
159 | 'Minute':{'S':minute} },
160 | ConsistentRead=True)
161 |
162 | if 'Item' not in ddb_max_ip or max_ip_count > int(ddb_max_ip['Item']['MaxCount']['N']):
163 | client.put_item(TableName=ip_table_name,
164 | Item={'Hour': {'S':hour},
165 | 'Minute':{'S':minute},
166 | 'IP':{'S':max_ip},
167 | 'MaxCount':{'N': str(max_ip_count)}} )
168 | if send_anonymous_data == "YES":
169 | try:
170 | unique_keys = list(set(output))
171 | for record_key in unique_keys:
172 | event_time,metric_type = record_key.split('|')
173 | if metric_type == successful_calls or metric_type == anomaly_score:
174 | ddb_record = client.get_item(TableName=table_name,
175 | Key={'MetricType': {'S':metric_type},
176 | 'EventTime':{'S':event_time} },
177 | ConsistentRead=True)
178 | del ddb_record["Item"]["ConcurrencyToken"]
179 | del ddb_record["Item"]["EventTime"]
180 | metric_data= {}
181 | metric_data['MetricType'] = ddb_record['Item']['MetricType']['S']
182 | if metric_type == successful_calls:
183 | services, num_calls = ddb_record['Item']['Data']['S'].split(',')[0].split(':')
184 | metric_data['NumberOfSuccessfulCalls'] = num_calls.replace('}','').replace(' ', '')
185 | if metric_type == anomaly_score:
186 | num_calls,anomaly_data = ddb_record['Item']['Data']['S'].split(',')[0].split(':')
187 | metric_data['NumberOfSuccessfulCalls'] = num_calls.replace('{', '').replace('"', '').split('|')[0]
188 | metric_data['AnamonlyScore'] = anomaly_data.replace('}', '')
189 | sendAnonymousData(event_time,metric_data)
190 | except Exception as error:
191 | log.error(error)
192 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2019 - 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/source/helper/lib/website-helper.js:
--------------------------------------------------------------------------------
1 | /*********************************************************************************************************************
2 | * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. *
3 | * *
4 | * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance *
5 | * with the License. A copy of the License is located at *
6 | * *
7 | * http://www.apache.org/licenses/LICENSE-2.0 *
8 | * *
9 | * or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES *
10 | * OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions *
11 | * and limitations under the License. *
12 | *********************************************************************************************************************/
13 |
14 | /**
15 | * @author Solution Builders
16 | */
17 |
18 | 'use strict';
19 |
20 | let AWS = require('aws-sdk');
21 | let s3 = new AWS.S3();
22 | const fs = require('fs');
23 | const _downloadLocation = '/tmp/web-site-manifest.json';
24 |
25 | /**
26 | * Helper function to interact with s3 hosted website for cfn custom resource.
27 | *
28 | * @class websiteHelper
29 | */
30 | let websiteHelper = (function() {
31 |
32 | /**
33 | * @class websiteHelper
34 | * @constructor
35 | */
36 | let websiteHelper = function() {};
37 |
38 | /**
39 | * Provisions the web site UI at deployment.
40 | * @param {string} sourceS3Bucket - Bucket containing the web site files to be copied.
41 | * @param {string} sourceS3prefix - S3 prefix to prepend to the web site manifest file names to be copied.
42 | * @param {string} destS3Bucket - S3 destination bucket to copy website content into
43 | * @param {string} userPoolId - Cognito User Pool Id for web site configuration
44 | * @param {string} userPoolClientId - Cognito User Pool Client Id for web site configuration
45 | * @param {string} identityPoolId - Cognito Identity Pool ID
46 | * @param {string} region - Region of destination S3 bucket
47 | * @param {string} uuid - UUID for this instance of the solution
48 | * @param {string} dashboard_usage - Enable or disable dashaboard use tracking
49 | * @param {copyWebSiteAssets~requestCallback} cb - The callback that handles the response.
50 | */
51 | websiteHelper.prototype.copyWebSiteAssets = function(sourceS3Bucket, sourceS3prefix, sourceManifest, destS3Bucket,
52 | userPoolId, userPoolClientId, identityPoolId, region, uuid, dashboard_usage,metrics_table,ip_table, cb) {
53 | console.log("Copying UI web site");
54 | console.log(['source bucket:', sourceS3Bucket].join(' '));
55 | console.log(['source prefix:', sourceS3prefix].join(' '));
56 | console.log(['destination bucket:', destS3Bucket].join(' '));
57 | console.log(['user pool:', userPoolId].join(' '));
58 | console.log(['user pool client:', userPoolClientId].join(' '));
59 | console.log(['identity pool:', identityPoolId].join(' '));
60 | console.log(['region:', region].join(' '));
61 |
62 | downloadWebisteManifest(sourceS3Bucket, sourceManifest, _downloadLocation, function(err, data) {
63 | if (err) {
64 | console.log(err);
65 | return cb(err, null);
66 | }
67 |
68 | fs.readFile(_downloadLocation, 'utf8', function(err, data) {
69 | if (err) {
70 | console.log(err);
71 | return cb(err, null);
72 | }
73 |
74 | console.log(data);
75 | let _manifest = validateJSON(data);
76 |
77 | if (!_manifest) {
78 | return cb('Unable to validate downloaded manifest file JSON', null);
79 | } else {
80 | uploadFile(_manifest.files, 0, destS3Bucket, [sourceS3Bucket, sourceS3prefix]
81 | .join('/'),
82 | function(err, result) {
83 | if (err) {
84 | return cb(err, null);
85 | }
86 |
87 | console.log(result);
88 |
89 | createAppVariables(userPoolId, userPoolClientId, identityPoolId, region, destS3Bucket, uuid, dashboard_usage, metrics_table, ip_table,
90 | function(err, createResult) {
91 | if (err) {
92 | return cb(err, null);
93 | }
94 |
95 | return cb(null, result);
96 | });
97 | });
98 | }
99 |
100 | });
101 |
102 | });
103 |
104 | };
105 |
106 | /**
107 | * Helper function to validate the JSON structure of contents of an import manifest file.
108 | * @param {string} body - JSON object stringify-ed.
109 | * @returns {JSON} - The JSON parsed string or null if string parsing failed
110 | */
111 | let validateJSON = function(body) {
112 | try {
113 | let data = JSON.parse(body);
114 | console.log(data);
115 | return data;
116 | } catch (e) {
117 | // failed to parse
118 | console.log('Manifest file contains invalid JSON.');
119 | return null;
120 | }
121 | };
122 |
123 | let createAppVariables = function(userPoolId, userPoolClientId, identityPoolId, region, destS3Bucket, uuid, dashboard_usage, metrics_table,ip_table, cb) {
124 | console.log("Creating AppVariables");
125 | console.log(['destination bucket:', destS3Bucket].join(' '));
126 | console.log(['user pool:', userPoolId].join(' '));
127 | console.log(['user pool client:', userPoolClientId].join(' '));
128 | console.log(['identity pool:', identityPoolId].join(' '));
129 | console.log(['region:', region].join(' '));
130 | console.log(['destS3Bucket:', destS3Bucket].join(' '));
131 | console.log(['uuid:', uuid].join(' '));
132 | console.log(['dashboard_usage:', dashboard_usage].join(' '));
133 | console.log(['metrics_table:', metrics_table].join(' '));
134 | console.log(['ip_table:', ip_table].join(' '));
135 |
136 | var _content = [
137 | ['localStorage.setItem(\'upid\', \'', userPoolId, '\');'].join(''),
138 | ['localStorage.setItem(\'cid\', \'', userPoolClientId, '\');'].join(''),
139 | ['localStorage.setItem(\'ipid\', \'', identityPoolId, '\');'].join(''),
140 | ['localStorage.setItem(\'r\', \'', region, '\');'].join(''),
141 | ['var _dashboard_usage = \'', dashboard_usage, '\';'].join(''),
142 | ['var metrics_table = \'', metrics_table, '\';'].join(''),
143 | ['var ip_table = \'', ip_table, '\';'].join(''),
144 | ['var _hit_data = {'],
145 | [' \'Solution\': \'SO0037\','],
146 | [' \'UUID\': \'',uuid,'\','].join(''),
147 | [' \'TimeStamp\': moment().utc().format(\'YYYY-MM-DD HH:mm:ss.S\'),'],
148 | [' \'Data\': {'],
149 | [' \'dashboard\': 1,'],
150 | [' \'region\': \'',region,'\''].join(''),
151 | [' }'],
152 | ['};']
153 | ].join('\n');
154 | console.log(_content);
155 | let params = {
156 | Bucket: destS3Bucket,
157 | Key: 'js/app-variables.js',
158 | Body: _content
159 | };
160 |
161 | s3.putObject(params, function(err, data) {
162 | if (err) {
163 | console.log(err);
164 | return cb('error creating js/app-variables.js file for website UI', null);
165 | }
166 |
167 | console.log(data);
168 | return cb(null, data);
169 | });
170 |
171 | };
172 |
173 | let uploadFile = function(filelist, index, destS3Bucket, sourceS3prefix, cb) {
174 | if (filelist.length > index) {
175 | let params = {
176 | Bucket: destS3Bucket,
177 | Key: filelist[index],
178 | CopySource: [sourceS3prefix, filelist[index]].join('/'),
179 | };
180 | if (filelist[index].endsWith('.htm') || filelist[index].endsWith('.html')) {
181 | params.ContentType = "text/html";
182 | params.MetadataDirective = "REPLACE";
183 | } else if (filelist[index].endsWith('.css')) {
184 | params.ContentType = "text/css";
185 | params.MetadataDirective = "REPLACE";
186 | } else if (filelist[index].endsWith('.js')) {
187 | params.ContentType = "application/javascript";
188 | params.MetadataDirective = "REPLACE";
189 | } else if (filelist[index].endsWith('.png')) {
190 | params.ContentType = "image/png";
191 | params.MetadataDirective = "REPLACE";
192 | } else if (filelist[index].endsWith('.jpg') || filelist[index].endsWith('.jpeg')) {
193 | params.ContentType = "image/jpeg";
194 | params.MetadataDirective = "REPLACE";
195 | } else if (filelist[index].endsWith('.gif')) {
196 | params.ContentType = "image/gif";
197 | params.MetadataDirective = "REPLACE";
198 | };
199 |
200 | s3.copyObject(params, function(err, data) {
201 | if (err) {
202 | return cb(['error copying ', [sourceS3prefix, filelist[index]].join('/'), '\n', err]
203 | .join(
204 | ''),
205 | null);
206 | }
207 |
208 | console.log([
209 | [sourceS3prefix, filelist[index]].join('/'), 'uploaded successfully'
210 | ].join(' '));
211 | let _next = index + 1;
212 | uploadFile(filelist, _next, destS3Bucket, sourceS3prefix, function(err, resp) {
213 | if (err) {
214 | return cb(err, null);
215 | }
216 |
217 | cb(null, resp);
218 | });
219 | });
220 | } else {
221 | cb(null, [index, 'files copied'].join(' '));
222 | }
223 |
224 | };
225 |
226 | /**
227 | * Helper function to download the website manifest to local storage for processing.
228 | * @param {string} s3_bucket - Amazon S3 bucket of the website manifest to download.
229 | * @param {string} s3_key - Amazon S3 key of the website manifest to download.
230 | * @param {string} downloadLocation - Local storage location to download the Amazon S3 object.
231 | * @param {downloadManifest~requestCallback} cb - The callback that handles the response.
232 | */
233 | let downloadWebisteManifest = function(s3Bucket, sourceManifest, downloadLocation, cb) {
234 | let params = {
235 | Bucket: s3Bucket,
236 | Key: sourceManifest
237 | };
238 |
239 | console.log(params);
240 |
241 | // check to see if the manifest file exists
242 | s3.headObject(params, function(err, metadata) {
243 | if (err) {
244 | console.log(err);
245 | }
246 |
247 | if (err && err.code === 'NotFound') {
248 | // Handle no object on cloud here
249 | console.log('file doesnt exist');
250 | return cb('Manifest file was not found.', null);
251 | } else {
252 | console.log('file exists');
253 | console.log(metadata);
254 | let file = require('fs').createWriteStream(downloadLocation);
255 |
256 | s3.getObject(params).
257 | on('httpData', function(chunk) {
258 | file.write(chunk);
259 | }).
260 | on('httpDone', function() {
261 | file.end();
262 | console.log('website manifest downloaded for processing...');
263 | return cb(null, 'success');
264 | }).
265 | send();
266 | }
267 | });
268 | };
269 |
270 | return websiteHelper;
271 |
272 | })();
273 |
274 | module.exports = websiteHelper;
275 |
--------------------------------------------------------------------------------
/source/web_site/dash.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | CloudTrail Analytics Dashboard
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
74 |
75 |
76 |
77 |
78 |
AWS CloudTrail Analytics Dashboard
79 |
Sign in to get started. This dashboard uses Amazon Cognito for authentication. See
80 | help for more information.
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
91 |
Configuration
92 |
93 |
94 |
95 | The Dashboard is not configured correctly. Please ensure these values are set and are accurate.
96 |
97 |
98 |
99 | These values are used by the Dashboard to validate users in your Cognito User Pool. Don't change these values unless you
100 | know what you're doing!
101 |
102 |
103 |
122 |
123 |
124 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
140 |
Create New Password
141 |
142 |
143 |
144 | The passwords you entered do not match!
145 |
146 |
147 | The password you entered does not meet the following complexity requirements:
148 |
149 |
8 or more characters
150 |
Upper case character
151 |
Lower case character
152 |
Number
153 |
154 |
155 |
156 |
157 |
158 | Your temporary password must be changed! Please create a new password (8 or more characters, one of which must be
159 | uppercase, lowercase, and a number).
160 |
161 |
162 |
172 |
173 |
174 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
Overview of the dashboard
186 |
This dashboard demo and its associated solution provide a mechanism for collecting, analyzing, and displaying
187 | AWS account activity in real time. Amazon Kinesis Data Analytics
188 | is used to compute real-time metrics from AWS CloudTrail
189 | including top IP addresses, services, and API calls by request count. We encourage you to take this Amazon Kinesis
190 | Data Analytics solution and customize it for your own needs. Visit
191 | Real-Time Insights into AWS Account Activity
192 | to learn more about this solution.
193 |
194 |
195 | For more information, including processing and delivery times, please see help.
196 |
197 |
198 |
199 |
200 |
201 |
202 |
Total number of API calls over the last 10 minutes