awsApiController.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. var debug = require('debug')('ylt:server');
  2. var Q = require('q');
  3. var AWS = require('aws-sdk');
  4. var ylt = require('../../index');
  5. var ScreenshotHandler = require('../../screenshotHandler');
  6. var RunsQueue = require('../datastores/runsQueue');
  7. var RunsDatastore = require('../datastores/runsDatastore');
  8. var serverSettings = (process.env.IS_TEST) ? require('../../../test/fixtures/settings.json') : require('../../../server_config/settings.json');
  9. var ResultsDatastore = (serverSettings.awsHosting) ? require('../datastores/awsResultsDatastore') : require('../datastores/resultsDatastore');
  10. var ApiController = function(app) {
  11. 'use strict';
  12. var queue = new RunsQueue();
  13. var runsDatastore = new RunsDatastore();
  14. var resultsDatastore = new ResultsDatastore();
  15. // Increase AWS Lambda timeout
  16. AWS.config.update({httpOptions: {timeout: 300000}});
  17. // Create a new run
  18. app.post('/api/runs', function(req, res) {
  19. // Add http to the test URL
  20. if (req.body.url && req.body.url.toLowerCase().indexOf('http://') !== 0 && req.body.url.toLowerCase().indexOf('https://') !== 0) {
  21. req.body.url = 'http://' + req.body.url;
  22. }
  23. // Block requests to unwanted websites (=spam)
  24. if (req.body.url && isBlocked(req.body.url)) {
  25. console.error('Test blocked for URL: %s', req.body.url);
  26. res.status(403).send('Forbidden');
  27. return;
  28. }
  29. // Grab the test parameters and generate a random run ID
  30. var run = {
  31. runId: (Date.now()*1000 + Math.round(Math.random()*1000)).toString(36),
  32. params: {
  33. url: req.body.url,
  34. waitForResponse: req.body.waitForResponse === true || req.body.waitForResponse === 'true' || req.body.waitForResponse === 1,
  35. partialResult: req.body.partialResult || null,
  36. screenshot: req.body.screenshot || false,
  37. device: req.body.device || 'desktop',
  38. proxy: req.body.proxy || null,
  39. waitForSelector: req.body.waitForSelector || null,
  40. cookie: req.body.cookie || null,
  41. authUser: req.body.authUser || null,
  42. authPass: req.body.authPass || null,
  43. blockDomain: req.body.blockDomain || null,
  44. allowDomain: req.body.allowDomain || null,
  45. noExternals: req.body.noExternals || false
  46. }
  47. };
  48. // Add test to the testQueue
  49. debug('Adding test %s to the queue', run.runId);
  50. var queuePromise = queue.push(run.runId);
  51. // Save the run to the datastore
  52. //runsDatastore.add(run, queuePromise.startingPosition);
  53. runsDatastore.add(run, 0);
  54. // Let's start the run
  55. queuePromise.then(function() {
  56. runsDatastore.updatePosition(run.runId, 0);
  57. console.log('Launching test ' + run.runId + ' on ' + run.params.url);
  58. var runOptions = {
  59. screenshot: run.params.screenshot ? ScreenshotHandler.getTmpFileRelativePath() : false,
  60. device: run.params.device,
  61. proxy: run.params.proxy,
  62. waitForSelector: run.params.waitForSelector,
  63. cookie: run.params.cookie,
  64. authUser: run.params.authUser,
  65. authPass: run.params.authPass,
  66. blockDomain: run.params.blockDomain,
  67. allowDomain: run.params.allowDomain,
  68. noExternals: run.params.noExternals
  69. };
  70. const {region, arn} = chooseLambdaRegionByGeoIP(req.headers);
  71. const lambda = new AWS.Lambda({region: region});
  72. return lambda.invoke({
  73. FunctionName: arn,
  74. InvocationType: 'RequestResponse',
  75. Payload: JSON.stringify({url: run.params.url, id: run.runId, options: runOptions})
  76. }).promise();
  77. })
  78. .then(function(response) {
  79. debug('We\'ve got a response from AWS Lambda');
  80. debug('StatusCode = %d', response.StatusCode);
  81. debug('Payload = %s', response.Payload);
  82. if (response.StatusCode === 200 && response.Payload && response.Payload !== 'null') {
  83. const payload = JSON.parse(response.Payload);
  84. if (payload.errorType) {
  85. runsDatastore.markAsFailed(run.runId, payload.errorMessage);
  86. } else {
  87. debug('Success!');
  88. runsDatastore.markAsComplete(run.runId);
  89. }
  90. } else {
  91. debug('Empty response from the lambda agent');
  92. runsDatastore.markAsFailed(run.runId, "Empty response from the agent");
  93. }
  94. })
  95. .catch(function(err) {
  96. debug('Error from AWS Lambda:');
  97. debug(err);
  98. runsDatastore.markAsFailed(run.runId, err.toString());
  99. });
  100. // The user doesn't want to wait for the response, sending the run ID only
  101. debug('Sending response without waiting.');
  102. res.setHeader('Content-Type', 'application/json');
  103. res.send(JSON.stringify({runId: run.runId}));
  104. });
  105. // Reads the Geoip_Continent_Code header and chooses the right region from the settings
  106. function chooseLambdaRegionByGeoIP(headers) {
  107. // The settings can be configured like this in server_config/settings.json:
  108. //
  109. // "awsHosting": {
  110. // "lambda": {
  111. // "regionByContinent": {
  112. // "AF": "eu-west-3",
  113. // "AS": "ap-southeast-1",
  114. // "EU": "eu-west-3",
  115. // "NA": "us-east-1",
  116. // "OC": "ap-southeast-1",
  117. // "SA": "us-east-1",
  118. // "default": "eu-west-3"
  119. // },
  120. // "arnByRegion": {
  121. // "us-east-1": "arn:aws:lambda:us-east-1:xxx:function:xxx",
  122. // "eu-west-3": "arn:aws:lambda:eu-west-3:xxx:function:xxx",
  123. // "ap-southeast-1": "arn:aws:lambda:ap-southeast-1:xxx:function:xxx"
  124. // }
  125. // }
  126. // },
  127. const header = headers.geoip_continent_code;
  128. debug('Value of the Geoip_Continent_Code header: %s', header);
  129. const continent = header || 'default';
  130. const region = serverSettings.awsHosting.lambda.regionByContinent[continent];
  131. const arn = serverSettings.awsHosting.lambda.arnByRegion[region];
  132. debug('The chosen AWS Lambda is: %s', arn);
  133. return {region, arn};
  134. }
  135. // Retrive one run by id
  136. app.get('/api/runs/:id', function(req, res) {
  137. var runId = req.params.id;
  138. var run = runsDatastore.get(runId);
  139. if (run) {
  140. res.setHeader('Content-Type', 'application/json');
  141. res.send(JSON.stringify(run, null, 2));
  142. } else {
  143. res.status(404).send('Not found');
  144. }
  145. });
  146. // Counts all pending runs
  147. app.get('/api/runs', function(req, res) {
  148. res.setHeader('Content-Type', 'application/json');
  149. res.send(JSON.stringify({
  150. pendingRuns: queue.length(),
  151. timeSinceLastTestStarted: queue.timeSinceLastTestStarted()
  152. }, null, 2));
  153. });
  154. // Delete one run by id
  155. /*app.delete('/api/runs/:id', function(req, res) {
  156. deleteRun()
  157. });*/
  158. // Delete all
  159. /*app.delete('/api/runs', function(req, res) {
  160. purgeRuns()
  161. });
  162. // List all
  163. app.get('/api/runs', function(req, res) {
  164. listRuns()
  165. });
  166. // Exists
  167. app.head('/api/runs/:id', function(req, res) {
  168. existsX();
  169. // Returns 200 if the result exists or 404 if not
  170. });
  171. */
  172. // Retrive one result by id
  173. app.get('/api/results/:id', function(req, res) {
  174. getPartialResults(req.params.id, res, function(data) {
  175. // Some fields can be excluded from the response, this way:
  176. // /api/results/:id?exclude=field1,field2
  177. if (req.query.exclude && typeof req.query.exclude === 'string') {
  178. var excludedFields = req.query.exclude.split(',');
  179. excludedFields.forEach(function(fieldName) {
  180. if (data[fieldName]) {
  181. delete data[fieldName];
  182. }
  183. });
  184. }
  185. return data;
  186. });
  187. });
  188. // Retrieve one result and return only the generalScores part of the response
  189. app.get('/api/results/:id/generalScores', function(req, res) {
  190. getPartialResults(req.params.id, res, function(data) {
  191. return data.scoreProfiles.generic;
  192. });
  193. });
  194. app.get('/api/results/:id/generalScores/:scoreProfile', function(req, res) {
  195. getPartialResults(req.params.id, res, function(data) {
  196. return data.scoreProfiles[req.params.scoreProfile];
  197. });
  198. });
  199. app.get('/api/results/:id/rules', function(req, res) {
  200. getPartialResults(req.params.id, res, function(data) {
  201. return data.rules;
  202. });
  203. });
  204. app.get('/api/results/:id/javascriptExecutionTree', function(req, res) {
  205. getPartialResults(req.params.id, res, function(data) {
  206. return data.javascriptExecutionTree;
  207. });
  208. });
  209. app.get('/api/results/:id/toolsResults/phantomas', function(req, res) {
  210. getPartialResults(req.params.id, res, function(data) {
  211. return data.toolsResults.phantomas;
  212. });
  213. });
  214. function getPartialResults(runId, res, partialGetterFn) {
  215. resultsDatastore.getResult(runId)
  216. .then(function(data) {
  217. var results = partialGetterFn(data);
  218. if (typeof results === 'undefined') {
  219. res.status(404).send('Not found');
  220. return;
  221. }
  222. // TODO: Reverse quick fix
  223. results.screenshotUrl = '/api/results/' + runId + '/screenshot.jpg';
  224. res.setHeader('Content-Type', 'application/json');
  225. res.send(JSON.stringify(results, null, 2));
  226. }).fail(function() {
  227. res.status(404).send('Not found');
  228. });
  229. }
  230. // Retrive one result by id
  231. app.get('/api/results/:id/screenshot.jpg', function(req, res) {
  232. var runId = req.params.id;
  233. resultsDatastore.getScreenshot(runId)
  234. .then(function(screenshotBuffer) {
  235. res.setHeader('Content-Type', 'image/jpeg');
  236. res.send(screenshotBuffer);
  237. }).fail(function() {
  238. res.status(404).send('Not found');
  239. });
  240. });
  241. function isBlocked(url) {
  242. if (!serverSettings.blockedUrls) {
  243. return false;
  244. }
  245. return serverSettings.blockedUrls.some(function(blockedUrl) {
  246. return (url.indexOf(blockedUrl) === 0);
  247. });
  248. }
  249. };
  250. module.exports = ApiController;