/
applications.js
648 lines (541 loc) · 20.1 KB
/
applications.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
import test from 'ava';
import events from 'events';
import httpMocks from 'node-mocks-http';
import moment from 'moment';
import nock from 'nock';
import config from 'config';
import _ from 'lodash';
import isInt from 'validator/lib/isInt';
import application from './fixtures/app';
import applications from '../lib/applications';
import init from '../lib/applications/init';
import database from '../lib/database';
import merged from './fixtures/applications/objects/model-merged.js';
import dbmocks from './fixtures/applications/objects/database-mocks.js';
const EventEmitter = events.EventEmitter;
const next = application.next;
/**
* Form body response
* @type {Object}
*/
const body = {
'name--text': 'Bar',
'live-endpoint--url': 'http://bar.com/live',
'updated-endpoint--url': 'http://bar.com/updated',
'sunset-endpoint--url': 'http://bar.com/sunset',
'submit': 'save',
};
/**
* Express Request Object
* @type {Object}
*/
const reqObj = application.request({
url: '/application',
app: {
'applications-apps': dbmocks.rows,
'applications-merged': merged,
},
session: {
form: {
applications: {
save: {},
edit: {},
},
},
},
});
/**
* Request options
* @type {Object}
*/
const reqOptions = {
url: 'https://punchcard.io',
method: 'POST',
json: {
id: 1234,
secret: 5678,
},
};
// set up nock locations from data
dbmocks.rows.forEach(app => {
const endpoints = ['live', 'updated', 'sunset'];
endpoints.forEach(endpoint => {
if (app[`${endpoint}-endpoint`]) {
nock(app[`${endpoint}-endpoint`])
.post('')
.reply(200);
}
});
});
test.cb.before(t => {
database.init().then(() => {
database('applications').del().then(() => {
database('applications').insert(dbmocks.rows).then(() => {
// auto-increment set past added entries
database.schema.raw('select setval(\'applications_id_seq\', 20, true)').then(() => {
t.end();
});
});
});
}).catch(e => {
t.fail(e.message);
});
});
test.cb.after.always(t => {
database('applications').select('*').del().then(() => {
t.end();
}).catch(e => {
t.fail(e.message);
});
});
test('Applications functions', t => {
t.is(typeof applications.model, 'function', '`model` exists and is a function');
t.is(typeof applications.model.structure, 'object', '`structure` exists and is an object');
t.is(typeof applications.routes, 'object', '`routes` exists and is an object');
t.is(typeof applications.routes.all, 'function', '`all` exists and is a function');
t.is(typeof applications.routes.add, 'function', '`new` exists and is a function');
t.is(typeof applications.routes.one, 'function', '`one` exists and is a function');
t.is(typeof applications.routes.secret, 'function', '`secret` exists and is a function');
t.is(typeof applications.routes.save, 'function', '`save` exists and is a function');
t.is(typeof applications.send.endpoints, 'function', '`send` exists and is a function');
});
//////////////////////////////
// Applications object structure
//////////////////////////////
test('Applications structure object', t => {
const structure = applications.model.structure;
t.is(typeof structure, 'object', 'Structure is an object');
t.is(structure.name, 'Applications', 'Structure has name');
t.is(structure.description, 'Contains webhook applications', 'Structure has description');
t.is(structure.id, 'applications', 'Structure has id');
t.true(Array.isArray(structure.attributes), 'attributes is an array');
t.deepEqual(reqObj.app['applications-merged'], merged, 'merged model is part of request object fixture');
});
//////////////////////////////
// Applications - model
//////////////////////////////
test('Applications model', t => {
return applications.model().then(model => {
t.true(model[0].hasOwnProperty('name'), 'Should have a workflow attribute');
t.is(model[0].name, 'Applications', 'Structure has name');
});
});
test('Workflow model from config', t => {
const structure = _.cloneDeep(applications.model.structure);
structure.name = 'Other';
return applications.model(structure).then(model => {
t.true(model[0].hasOwnProperty('name'), 'Should have a workflow attribute');
t.is(model[0].name, 'Other', 'Structure has name');
});
});
//////////////////////////////
// Applications init
//////////////////////////////
test('Grab applications model-merged and all apps', t => {
return init().then(result => {
t.is(typeof result, 'object', 'Returns an object');
t.is(typeof result.merged, 'object', 'Returns merged object');
t.true(Array.isArray(result.apps), 'Returns applications in an array');
t.true(result.apps.length <= 5, 'has no more than five applications');
});
});
//////////////////////////////
// Send: endpoints
//////////////////////////////
test('Endpoint Request options', t => {
const options = {
trigger: 'live',
apps: dbmocks.rows,
};
return applications.send.endpoints(options).then(res => {
t.true(Array.isArray(res.endpoints), 'Should return an array');
t.is(res.endpoints.length, 4, 'Should return four objects because id:2 has no `live` endpoint');
const point = dbmocks.rows.find((end) => {
return end.id === 1;
});
const app = res.endpoints.find((ap) => {
return ap.id === 1;
});
t.is(app.id, 1, 'Should be first app');
t.is(_.get(app, 'options.url', null), 'http://foo.com/live', 'includes live endpoint');
t.is(_.get(app, 'options.method', null), 'POST', 'includes method');
t.is(_.get(app, 'options.json.id', null), point['client-id'], 'includes client id');
t.is(_.get(app, 'options.json.secret', null), point['client-secret'], 'includes client secret');
});
});
test('Endpoint Request options', t => {
const options = {
trigger: 'live',
apps: null,
};
return applications.send.endpoints(options).catch(err => {
t.is(err, 'Apps must be an array', 'Should require apps to be an array');
});
});
//////////////////////////////
// Send: request
//////////////////////////////
test('Request wrapper - good', t => {
nock('https://punchcard.io')
.post('/')
.reply(200);
return applications.send.request(reqOptions).then(res => {
t.is(typeof res, 'object', 'Should return an object');
t.is(res.response, 200, 'Should return 200 status');
t.true(_.isDate(new Date(res.timestamp)), 'includes a timestamp which is a date');
});
});
test('Request wrapper - bad', t => {
const badOptions = _.cloneDeep(reqOptions);
badOptions.url = 'https://punchcard.io/bad';
nock('https://punchcard.io')
.post('/bad')
.reply(500);
return applications.send.request(badOptions).then(res => {
t.is(typeof res, 'object', 'Should return an object');
t.is(res.response, 500, 'Should return 500 status');
t.true(_.isDate(new Date(res.timestamp)), 'includes a timestamp which is a date');
});
});
//////////////////////////////
// Send: save
//////////////////////////////
test('Save responses to DB', t => {
const response = {
response: 200,
timestamp: moment().unix(),
};
const options = {
trigger: 'live',
apps: dbmocks.rows,
endpoints: [
{
id: 1,
options: reqOptions,
response,
},
{
id: 2,
options: reqOptions,
response,
},
],
};
return applications.send.save(options).then(res => {
const app = res[0][0];
t.true(Array.isArray(res), 'Should return an array');
t.true(Array.isArray(app.responses.live), 'includes live responses, which is an array');
t.is(app.responses.live[0].response, 200, 'includes endpoint response');
});
});
test('Save responses to DB when zero responses', t => {
const response = {
response: 200,
timestamp: moment().unix(),
};
const options = {
trigger: 'live',
apps: dbmocks.rows,
endpoints: [
{
id: 3,
options: reqOptions,
response,
},
],
};
return applications.send.save(options).then(res => {
const app = res.find(ap => {
return ap[0].name === 'Bar Third Application';
});
t.true(Array.isArray(res), 'Should return an array');
t.true(Array.isArray(app[0].responses.live), 'includes live responses, which is an array');
t.is(app[0].responses.live[app[0].responses.live.length - 1].response, 200, 'includes endpoint response');
});
});
//////////////////////////////
// Send: SEND
//////////////////////////////
test('Send', t => {
const options = {
trigger: 'live',
apps: dbmocks.rows,
};
return applications.send(options).then(res => {
const app = res[0][0];
t.true(Array.isArray(res), 'Should return an array');
t.true(Array.isArray(app.responses.live), 'includes live responses, which is an array');
t.is(app.responses.live[app.responses.live.length - 1].response, 200, 'includes endpoint response');
});
});
test('Send - sunset', t => {
const options = {
trigger: 'sunset',
apps: dbmocks.rows,
};
return applications.send(options).then(res => {
const app = res.map(ap => {
return ap[0];
}).find((ap) => {
return ap.name === 'Foo First Application';
});
t.true(Array.isArray(res), 'Should return an array');
t.true(Array.isArray(app.responses.sunset), 'includes live responses, which is an array');
t.is(app.responses.sunset[0].response, 200, 'includes endpoint response');
});
});
test('Send - bad urls', t => {
const rows = dbmocks.rows;
const bad = rows.map(rw => {
const row = rw;
row['sunset-endpoint'] = 'http://a bad url.com';
return row;
});
const options = {
trigger: 'sunset',
apps: bad,
};
return applications.send(options).then(res => {
const app = res.map(ap => {
return ap[0];
}).find((ap) => {
return ap.name === 'Foo First Application';
});
t.true(Array.isArray(res), 'Should return an array');
t.true(Array.isArray(app.responses.sunset), 'includes live responses, which is an array');
const sorted = _.sortBy(app.responses.sunset, 'timestamp');
t.is(sorted[sorted.length - 1].response, 500, 'includes endpoint response'); // Failing for me locally with a 400, but Travis wants it to be a 500
});
});
//////////////////////////////
// Routes - Applications landing
//////////////////////////////
test('All applications route', t => {
const request = httpMocks.createRequest(reqObj);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
applications.routes.all(request, response);
response.render();
const data = response._getRenderData();
const app = data.applications.find((ap) => {
return ap.name === 'Foo First Application';
});
t.is(response.statusCode, 200, 'Should be a 200 response');
t.is(app.name, 'Foo First Application', 'includes form with inputs');
t.is(_.get(app, 'responses.live[0].response', null), 200, 'includes live response');
t.true(_.isDate(new Date(_.get(app, 'responses.live[0].timestamp', null))), 'includes live timestamp which is a date');
t.is(_.get(app, 'responses.updated[0].response', null), 200, 'includes updated response');
t.true(_.isDate(new Date(_.get(app, 'responses.updated[0].timestamp', null))), 'includes updated timestamp which is a date');
t.is(_.get(app, 'responses.sunset[0].response', null), 200, 'includes sunset response');
t.true(_.isDate(new Date(_.get(app, 'responses.sunset[0].timestamp', null))), 'includes sunset timestamp which is a date');
});
//////////////////////////////
// Routes - New Application
//////////////////////////////
test('New application route', t => {
const req = _.cloneDeep(reqObj);
req.url = '/applications/add';
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
const resp = applications.routes.add(request, response);
response.render();
return resp.then(() => {
const data = response._getRenderData();
t.is(response.statusCode, 200, 'Should be a 200 response');
t.true(_.includes(data.form.html, 'name="sunset-endpoint--url"'), 'includes form with inputs');
});
});
//////////////////////////////
// Routes - Single application
//////////////////////////////
test('Single application route', t => {
const req = _.cloneDeep(reqObj);
req.url = '/applications/1';
req.params.id = 1;
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
const resp = applications.routes.one(request, response);
response.render();
return resp.then(() => {
const data = response._getRenderData();
t.is(response.statusCode, 200, 'Should be a 200 response');
// form is populated
t.true(_.includes(data.form.html, 'value=\"Foo First Application\"'), 'includes form with name value');
t.true(_.includes(data.form.html, 'value=\"http://foo.com/live\"'), 'includes form with live-endpoint value');
t.true(_.includes(data.form.html, 'value=\"http://foo.com/updated\"'), 'includes form with updated-endpoint value');
t.true(_.includes(data.form.html, 'value=\"http://foo.com/sunset\"'), 'includes form with sunset-endpoint value');
t.true(_.includes(data.action, '/applications/save'), 'includes `save` for form action');
t.is(data.config.toString(), config.applications.toString(), 'includes config for applications');
t.is(data.app.name, 'Foo First Application', 'includes data from database');
t.is(data.button, 'update', 'includes `update` as text for button');
});
});
test.cb('Single application route - bad id', t => {
const req = _.cloneDeep(reqObj);
req.url = '/applications/1000';
req.params.id = 1000;
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
const resp = applications.routes.one(request, response, next);
response.on('end', () => {
t.is(response.statusCode, 200, 'Should be a 200 response');
return resp.then(res => {
t.is(res.status, 404, 'should have 404 status');
t.end();
});
});
response.render();
});
test('Single application route - error on save', t => {
const req = _.cloneDeep(reqObj);
req.url = '/applications/3';
req.params.id = 3;
req.session.form.applications.edit.id = 3;
req.session.form.applications.save.errors = {
'name--text': 'Field is required to be saved!',
};
req.session.form.applications.save.content = {
'name': { text: { value: '' } },
'live-endpoint': { url: { value: 'http://bar.com/live' } },
'updated-endpoint': { url: { value: 'http://bar.com/updated' } },
'sunset-endpoint': { url: { value: 'http://bar.com/sunset' } },
};
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
const resp = applications.routes.one(request, response);
response.render();
return resp.then(() => {
const data = response._getRenderData();
t.is(response.statusCode, 200, 'Should be a 200 response');
// form shows error
t.regex(data.form.html, /<p class="form--alert" role="alert" for="([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})">Field is required to be saved!<\/p>/g, 'includes form alert');
});
});
//////////////////////////////
// Routes - Secret
//////////////////////////////
test('Create new secret', t => {
const req = _.cloneDeep(reqObj);
req.method = 'POST';
req.headers.referrer = '/applications/1';
req.session.form.applications.edit.id = 1;
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
const resp = applications.routes.secret(request, response, next);
response.render();
return response.on('end', () => {
t.is(response.statusCode, 302, 'Should be a 302 response');
t.is(response._getRedirectUrl(), '/applications/1', 'should redirect to edit url');
return resp.then(res => {
t.not(res, dbmocks.rows[0]['client-secret'], 'should be a new client secret');
});
});
});
test('Create new secret - bad id kills db', t => {
const req = _.cloneDeep(reqObj);
req.method = 'POST';
req.headers.referrer = '/applications/break';
req.session.form.applications.edit.id = 'break';
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
const resp = applications.routes.secret(request, response, next);
return resp.then(res => {
t.true(_.includes(res.message, 'update "applications" set "client-secret"'), 'postgres error');
});
});
test.cb('Create new secret - bad referrer', t => {
const req = _.cloneDeep(reqObj);
req.method = 'POST';
req.headers.referrer = '/applications/add';
req.session.form.applications.edit.id = 1;
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
const resp = applications.routes.secret(request, response, next);
if (resp.message) {
t.is(resp.message, 'Secret can only be changed from the application edit screen', 'should error with message when bad referrer');
t.is(resp.safe, '/applications', 'should error with safe url when bad referrer');
t.is(resp.status, 500, 'should error with status message when bad referrer');
t.end();
}
else {
t.fail('should get secret warning message');
}
});
//////////////////////////////
// Routes - Save application
//////////////////////////////
test('Save new app: name required', t => {
const req = _.cloneDeep(reqObj);
req.method = 'POST';
req.session.referrer = '/applications/add';
req.url = '/applications/save';
req.body = _.cloneDeep(body);
req.body['name--text'] = '';
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
applications.routes.save(request, response);
response.render();
t.is(response.statusCode, 302, 'Should be a 302 response');
t.is(response._getRedirectUrl(), '/applications/add');
});
test('Save existing app: name required', t => {
const req = _.cloneDeep(reqObj);
req.method = 'POST';
req.session.referrer = '/applications/123';
req.url = '/applications/save';
req.body = _.cloneDeep(body);
req.body['name--text'] = '';
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
applications.routes.save(request, response);
t.is(response.statusCode, 302, 'Should be a 302 response');
t.is(response._getRedirectUrl(), '/applications/123');
});
test.cb('Delete existing application', t => {
const req = _.cloneDeep(reqObj);
req.method = 'POST';
req.session.referrer = '/applications/4';
req.session.form.applications.edit.id = 4;
req.url = '/applications/save';
req.body = _.cloneDeep(body);
req.body.submit = 'delete';
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
applications.routes.save(request, response);
response.on('end', () => {
t.is(response._getRedirectUrl(), '/applications');
t.end();
});
});
test.cb('Update existing application', t => {
const req = _.cloneDeep(reqObj);
req.method = 'POST';
req.session.referrer = '/applications/2';
req.session.form.applications.edit.id = 2;
req.url = '/applications/save';
req.body = _.cloneDeep(body);
req.body.submit = 'update';
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
applications.routes.save(request, response);
response.on('end', () => {
t.is(response._getRedirectUrl(), '/applications');
t.end();
});
});
test.cb('Save new application', t => {
const req = _.cloneDeep(reqObj);
req.method = 'POST';
req.session.referrer = '/applications/add';
req.url = '/applications/save';
req.body = _.cloneDeep(body);
const request = httpMocks.createRequest(req);
const response = httpMocks.createResponse({ eventEmitter: EventEmitter });
applications.routes.save(request, response);
response.on('end', () => {
const redir = response._getRedirectUrl();
const parts = redir.split('/');
t.is(parts[1], 'applications', 'Should have applications base');
t.true(isInt(parts[2]), 'Should have last application id');
t.end();
});
});