-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtestserver.js
4308 lines (4166 loc) · 260 KB
/
testserver.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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// *** TEST SELECTION ***
var dale = require ('dale');
var teishi = require ('teishi');
var noAuth = dale.stop (process.argv, true, function (v) {return v === 'noAuth'});
var noUpload = dale.stop (process.argv, true, function (v) {return v === 'noUpload'});
var noManual = dale.stop (process.argv, true, function (v) {return v === 'noManual'});
var debuggingMode = dale.stop (process.argv, true, function (v) {return v === 'debug'});
var toRun = process.argv [2];
process.argv [2] = undefined;
if (teishi.inc (['noAuth', 'noUpload', 'noManual', 'debug'], toRun)) toRun = undefined;
// *** SETUP ***
var CONFIG = require ('./config.js');
var SECRET = require ('./secret.js');
var Path = require ('path');
var hash = require ('murmurhash').v3;
var mime = require ('mime');
var cicek = require ('cicek');
var redis = require ('redis').createClient ({db: CONFIG.redisdb});
var h = require ('hitit');
var a = require ('./assets/astack.js');
var fs = require ('fs');
var type = teishi.type, clog = teishi.clog, eq = teishi.eq, last = teishi.last, inc = teishi.inc;
// *** TEST CONSTANTS ***
var tk = {
pivPath: 'test/',
pivDataPath: 'test/pivdata.json',
users: {
user1: {username: 'user1', password: 'foobar', firstName: 'name1', email: '[email protected]', timezone: 240},
user2: {username: 'user2', password: Math.random () + '', firstName: 'name2', email: '[email protected]', timezone: -240},
user3: {username: 'user3', password: Math.random () + '', firstName: 'name3', email: '[email protected]', timezone: 0},
}
}
// *** HELPER FUNCTIONS ***
var k = function (s) {
var command = [].slice.call (arguments, 1);
var output = {stdout: '', stderr: '', command: command};
var options = {};
var commands = dale.fil (command.slice (1), undefined, function (command) {
if (type (command) !== 'object' || ! command.env) return command;
options.env = command.env;
});
var proc = require ('child_process').spawn (command [0], commands, options);
var wait = 3;
var done = function () {
if (--wait > 0) return;
if (output.code === 0) s.next (output);
else s.next (0, output);
}
dale.go (['stdout', 'stderr'], function (v) {
proc [v].on ('data', function (chunk) {
if (debuggingMode) process.stdout.write (chunk);
output [v] += chunk;
});
proc [v].on ('end', done);
});
proc.on ('error', function (error) {
output.err += error + ' ' + error.stack;
done ();
});
proc.on ('exit', function (code, signal) {
output.code = code;
output.signal = signal;
done ();
});
if (commands [0] === 'server') H.server = proc;
}
var H = {
setCredentials: function (s, rq, rs) {
s.headers = {cookie: rs.headers ['set-cookie'] [0].split (';') [0]};
s.csrf = rs.body.csrf;
return true;
},
runServer: function () {
var requiresGeo = ! toRun || toRun === 'geo';
a.seq ([
[a.stop, [
[a.make (fs.readFile), tk.pivDataPath],
function (s) {
tk.pivs = JSON.parse (s.last);
s.next ();
}
], H.loadPivData],
[k, 'redis-cli', '-n', CONFIG.redisdb, 'flushdb'],
[k, 'node', 'server', 'local'],
function (s) {
process.exit (0);
}
]);
},
tryTimeout: function (interval, times, fn, cb) {
var retry = function (error, data, breakingError) {
if (breakingError) return cb (breakingError);
if (! error) return cb ();
if (! --times) return cb (error);
setTimeout (function () {
fn (retry);
}, interval);
}
fn (retry);
},
// The apres function in test, if present, must return true or false (it cannot be itself async).
testTimeout: function (interval, times, test) {
var apres = test.apres || function () {return true};
var tryTimeoutSet;
test.apres = function (s, rq, rs, next) {
if (apres (s, rq, rs, next)) return true;
if (tryTimeoutSet) return false;
tryTimeoutSet = true;
H.tryTimeout (interval, times, function (cb) {h.one (s, test, cb)}, next);
}
return test;
},
stop: function (label, result, value) {
if (eq (result, value)) return false;
if (teishi.complex (result) && teishi.complex (value)) {
var differentField = dale.stopNot (result, undefined, function (v, k) {if (! eq (v, value [k])) return k});
if (differentField === undefined) differentField = dale.stopNot (value, undefined, function (v, k) {if (! eq (v, result [k])) return k});
clog ('Invalid ' + label + ', expecting', value, 'got', result, 'in field', differentField);
}
else clog ('Invalid ' + label + ', expecting', value, 'got', result);
return true;
},
cBody: function (value) {
return function (s, rq, rs) {
return ! H.stop ('body', rs.body, type (value) === 'function' ? value (s) : value);
}
},
dateFromName: function (name) {
// Date example: 20220308
if (name.match (/(19|20)\d{6}/)) {
var date = name.match (/(19|20)\d{6}/g) [0];
date = [date.slice (0, 4), date.slice (4, 6), date.slice (6)].join ('-');
// Date with time acceptable format: date + 0 or more non digits + 1-2 digits (hour) + 0 or more non digits + 2 digits (minutes) + 0 or more non digits + optional two digits (seconds) + zero or more non letters plus optional am|AM|pm|PM
var time = name.match (/(19|20)\d{6}[^\d]*(\d{1,2})[^\d]*(\d{2})[^\d]*(\d{2})?[^a-zA-Z]*(am|AM|pm|PM)?/);
}
// Date example: 2022-03-08
else if (name.match (/(19|20)\d\d-\d\d-\d\d/)) {
var date = name.match (/(19|20)\d\d-\d\d-\d\d/g) [0];
date = [date.slice (0, 4), date.slice (5, 7), date.slice (8)].join ('-');
// Date with time acceptable format: date + 0 or more non digits + 1-2 digits (hour) + 0 or more non digits + 2 digits (minutes) + 0 or more non digits + optional two digits (seconds) + zero or more non letters plus optional am|AM|pm|PM
var time = name.match (/(19|20)\d\d-\d\d-\d\d[^\d]*(\d{1,2})[^\d]*(\d{2})[^\d]*(\d{2})?[^a-zA-Z]*(am|AM|pm|PM)?/);
}
else return -1;
// Attempt to get the time from the date. If it fails, just return the date with no time.
if (time && time [2] !== undefined && time [3] !== undefined) {
var hour = parseInt (time [2]);
if (time [5] && time [5].match (/pm/i) && hour > 0 && hour < 12) hour += 12;
hour += '';
var dateWithTime = date + 'T' + (hour.length === 1 ? '0' : '') + hour + ':' + time [3] + ':' + (time [4] || '00') + '.000Z';
dateWithTime = H.parseDate (dateWithTime);
if (dateWithTime !== -1) return dateWithTime;
}
return H.parseDate (date);
},
parseDate: function (date) {
if (! date) return -1;
// Range is years 1970-2100
var minDate = 0, maxDate = 4133980799999;
var d = new Date (date), ms = d.getTime ();
if (! isNaN (ms) && ms >= minDate && ms <= maxDate) return ms;
d = new Date (date.replace (':', '-').replace (':', '-'));
ms = d.getTime ();
if (! isNaN (ms) && ms >= minDate && ms <= maxDate) return ms;
return -1;
},
// Returns an output of the shape: {isVid: UNDEFINED|true, mimetype: STRING, dimw: INT, dimh: INT, format: STRING, deg: UNDEFINED|90|180|-90, dates: {...}, date: INTEGER, dateSource: STRING, loc: UNDEFINED|[INT, INT]}
// If onlyLocation flag is passed, output will only have the `loc` field.
getMetadata: function (s, path, onlyLocation, lastModified, name) {
var output = {};
a.seq (s, [
[k, 'exiftool', path],
function (s) {
dale.stop ((s.last || s.error).stdout.split ('\n'), true, function (line) {
if (! line.match (/^GPS Position\s+:/)) return;
var originalLine = line;
line = (line.split (':') [1]).split (',');
var lat = line [0].replace ('deg', '').replace ('\'', '').replace ('"', '').split (/\s+/);
var lon = line [1].replace ('deg', '').replace ('\'', '').replace ('"', '').split (/\s+/);
lat = (lat [4] === 'S' ? -1 : 1) * (parseFloat (lat [1]) + parseFloat (lat [2]) / 60 + parseFloat (lat [3]) / 3600);
lon = (lon [4] === 'W' ? -1 : 1) * (parseFloat (lon [1]) + parseFloat (lon [2]) / 60 + parseFloat (lon [3]) / 3600);
if (isNaN (lat) || lat < -90 || lat > 90) lat = undefined;
if (isNaN (lon) || lon < -180 || lon > 180) lon = undefined;
// We set location only if both latitude and longitude are valid
if (lat && lon) output.loc = [lat, lon];
return true;
});
if (onlyLocation) s.next ();
else s.next ((s.last || s.error).stdout.split ('\n'));
},
function (s) {
if (onlyLocation) return s.next ();
output.dates = {};
// We first detect the mimetype to ascertain whether this is a vid or a pic
dale.stopNot (s.last, undefined, function (line) {
if (! line.match (/^MIME Type\s+:/)) return;
output.mimetype = line.split (':') [1].trim ();
if (line.match (/^MIME Type\s+:\s+video\//)) output.isVid = true;
return true;
});
var error = dale.stopNot (s.last, undefined, function (line) {
if (line.match (/^Warning\s+:/)) {
var exceptions = new RegExp (['minor', 'Invalid EXIF text encoding', 'Bad IFD1 directory', 'Bad length ICC_Profile', 'Invalid CanonCameraSettings data', 'Truncated'].join ('|'));
if (line.match (exceptions)) return;
return line;
}
else if (line.match (/^Error\s+:/)) return line;
else if (line.match (/date/i)) {
var key = line.split (':') [0].trim ();
if (! key.match (/\bdate\b/i)) return;
if (key.match (/gps|profile|manufacture|extension|firmware/i)) return;
// Ignore metadata fields related to the newly created file itself, because they have the same date as the upload itself and they are irrelevant for dating the piv
if (inc (['File Modification Date/Time', 'File Access Date/Time', 'File Inode Change Date/Time'], key)) return;
var value = line.split (':').slice (1).join (':').trim ();
// If value doesn't start with a number or only contains zeroes, we ignore it.
if (! value.match (/^\d/) || ! value.match (/[1-9]/)) return;
output.dates [key] = value;
}
else if (line.match (/^File Type\s+:/)) {
output.format = line.split (':') [1].trim ().toLowerCase ();
if (output.format === 'extended webp') output.format = 'webp';
}
else if (! output.isVid && line.match (/^Image Width\s+:/)) output.dimw = parseInt (line.split (':') [1].trim ());
else if (! output.isVid && line.match (/^Image Height\s+:/)) output.dimh = parseInt (line.split (':') [1].trim ());
else if ((! output.isVid && line.match (/^Orientation\s+:/)) || (output.isVid && line.match (/Rotation\s+:/))) {
if (line.match ('270')) output.deg = -90;
if (line.match ('90')) output.deg = 90;
if (line.match ('180')) output.deg = 180;
}
});
if (error) return s.next (null, {error: error});
if (! output.isVid) return s.next ();
a.seq (s, [
[k, 'ffprobe', '-i', path, '-show_streams'],
function (s) {
var ffprobeMetadata = (s.last.stdout + '\n' + s.last.stderr).split ('\n');
var formats = [];
// ffprobe metadata is only used to detect width, height and the names of the codecs of the video & audio streams
dale.go (ffprobeMetadata, function (line) {
if (line.match (/^width=\d+$/)) output.dimw = parseInt (line.split ('=') [1]);
if (line.match (/^height=\d+$/)) output.dimh = parseInt (line.split ('=') [1]);
if (line.match (/^codec_name=/)) {
var format = line.split ('=') [1];
if (format !== 'unknown') formats.push (format);
}
});
if (formats.length) output.format += ':' + formats.sort ().join ('/');
s.next ();
}
]);
},
function (s) {
if (onlyLocation) return s.next (output);
// Despite our trust in exiftool and ffprobe, we make sure that the required output fields are present
if (type (output.dimw) !== 'integer' || output.dimw < 1) return s.next (null, {error: 'Invalid width: ' + output.dimw});
if (type (output.dimh) !== 'integer' || output.dimh < 1) return s.next (null, {error: 'Invalid height: ' + output.dimh});
if (! output.format) return s.next (null, {error: 'Missing format'});
if (! output.mimetype) return s.next (null, {error: 'Missing mimetype'});
// All dates are considered to be UTC, unless they explicitly specify a timezone.
// The underlying server must be in UTC to not add a timezone offset to dates that specify no timezone.
// The client also ignores timezones, except for applying a timezone offset for the `last modified` metadata of the piv in the filesystem when it is uploaded.
output.dates ['upload:lastModified'] = lastModified;
if (H.dateFromName (name) !== -1) output.dates ['upload:fromName'] = name;
var validDates = dale.obj (output.dates, function (date, key) {
var parsed = key.match ('fromName') ? H.dateFromName (date) : H.parseDate (date);
// We ignore invalid dates (-1) or dates before the Unix epoch (< 0).
if (parsed > -1) return [key, parsed];
});
// We first try to find a valid Date/Time Original, if it's the case, then we will use that date.
if (validDates ['Date/Time Original']) {
output.date = validDates ['Date/Time Original'];
output.dateSource = 'Date/Time Original';
}
// Otherwise, of all the valid dates, we will set the oldest one.
else {
dale.go (validDates, function (date, key) {
if (output.date && output.date <= date) return;
output.date = date;
output.dateSource = key;
});
}
// If the date source is upload:fromName and there's another valid date entry on the same date (but a later time), we use the latest one of them. This avoids files with a name that contains a date without time to override the date + time combination of another metadata tag.
if (output.dateSource === 'upload:fromName') {
var adjustedDate;
dale.go (validDates, function (date, key) {
if (date - output.date < 1000 * 60 * 60 * 24) {
if (! adjustedDate) adjustedDate = [key, date];
else {
if (date < adjustedDate [1]) adjustedDate = [key, date];
}
}
});
if (adjustedDate) {
output.dateSource = adjustedDate [0];
output.date = adjustedDate [1];
}
}
s.next (output);
}
]);
},
loadPivData: function (s) {
var invalid = ['empty.jpg', 'invalid.jpg', 'invalidvid.mp4'];
// medium-nometa.jpg has no metadata; small-meta.png has an extra metadata field for date
var repeated = ['medium-nometa.jpg', 'small-meta.png'];
var unsupported = ['location.svg'];
var pivs = dale.obj (fs.readdirSync (tk.pivPath).sort (), function (file) {
var stat = fs.statSync (Path.join (tk.pivPath, file));
// Ignore vim swap files
if (file.match (/.swp$/)) return;
var data = {name: file, path: Path.join (tk.pivPath, file), size: stat.size, mtime: new Date (stat.mtime).getTime (), invalid: inc (invalid, file) || undefined, repeated: inc (repeated, file) || undefined, unsupported: inc (unsupported, file) || undefined};
return [data.name.split ('.') [0], data];
});
a.seq (s, [
[a.fork, pivs, function (piv) {
if (piv.invalid || piv.unsupported) return [];
return [
[H.getMetadata, piv.path, false, piv.mtime, piv.name],
function (s) {
dale.go (s.last, function (v, k) {
piv [k] = v;
});
// humanReadableDate is there just for manual checking purposes, to see that the date indeed makes sense at a glance compared to the dates contained in the metadata
piv.humanReadableDate = new Date (piv.date).toISOString ();
piv.dateTags = ['d::' + new Date (piv.date).getUTCFullYear (), 'd::M' + (new Date (piv.date).getUTCMonth () + 1)];
s.next ();
},
function (s) {
fs.readFile (piv.path, function (error, file) {
if (error) return s.next (null, error);
piv.hash = hash (file) + ':' + piv.size;
// We remove the reference to the buffer to free memory.
file = null;
s.next ();
});
}
];
}],
function (s) {
a.make (fs.writeFile) (s, tk.pivDataPath, JSON.stringify (pivs, null, ' '), 'utf8');
tk.pivs = pivs;
}
]);
},
invalidTestMaker: function (label, Path, rules) {
var error = function (error) {
throw new Error (error);
}
if (type (rules) !== 'array') return error ('Rules must be an array.');
var types = {
string: function () {return Math.random () + ''},
integer: function () {return Math.round (Math.random () + Math.random ())},
float: function () {return Math.random ()},
object: function () {return {}},
array: function () {return []},
null: function () {return null},
boolean: function () {return Math.random > 0.5},
undefined: function () {},
}
var stringMaker = function (length) {
return dale.go (dale.times (length), function () {
return (Math.random () + '') [2];
}).join ('');
}
var get = function (target, path) {
return dale.stop (path, false, function (v, k) {
if (k < path.length - 1 && teishi.simple (target [v])) return false;
target = target [v];
}) === false ? undefined : target;
}
var updateValid = function (path, value) {
if (path.length === 0) valid = value;
else get (valid, path.slice (0, -1)) [last (path)] = value;
}
var addTest = function (label, path, value, checkError) {
var body;
if (path.length === 0) body = value;
else {
body = teishi.copy (valid);
get (body, path.slice (0, -1)) [last (path)] = value;
}
tests.push ([label + ' ' + (path.length === 0 ? 'root object' : path.join ('.')), body, function (s, rq, rs) {
return checkError (rs.body);
}]);
}
// keep track/copy of last valid object so you can add incrementally
var valid, tests = [];
var runOne = function (rule) {
// Type constraint
if (rule.length === 2 || rule [1] === 'type') {
if (rule [1] === 'type') rule = [rule [0]].concat (rule.slice (2));
// If more than one desired type, default to the first one
var sdesired = type (rule [1]) === 'array' ? ('one of ' + cicek.escape (teishi.str (rule [1]))) : rule [1];
dale.go (types, function (maker, type) {
var valid = teishi.type (rule [1]) === 'array' ? inc (rule [1], type) : rule [1] === type;
if (valid) {
if (type !== 'undefined') updateValid (rule [0], maker ());
}
else addTest ('type ' + type, rule [0], maker (), function (body) {
if (rule [0].length === 0 && ! inc (['array', 'object'], type)) return body === 'All post requests must be multipart/form-data, application/x-www-urlencoded or application/json!';
var match = new RegExp ((last (rule [0]) !== undefined ? last (rule [0]) : 'body') + ' should have as type ' + sdesired + ' but (one of .+|instead) is .+ with type ' + type);
var customMatch;
if (rule [2]) customMatch = new RegExp (rule [2]);
return body && teishi.type (body.error) === 'string' && (customMatch ? body.error.match (customMatch) : body.error.match (match));
});
});
}
// This constraint doesn't update the valid payload
else if (rule [1] === 'keys') {
dale.go (types, function (maker, type) {
if (type === 'undefined') return;
addTest ('invalid key with type ' + type, rule [0].concat (types.string ()), maker (), function (body) {
var match = new RegExp ('each of the keys of .+ should be equal to one of ' + cicek.escape (teishi.str (rule [2])) + ' but one of .+ is');
return body && teishi.type (body.error) === 'string' && body.error.match (match);
});
});
}
// This constraint doesn't update the valid payload
else if (rule [1] === 'invalidKeys') {
dale.go (rule [2], function (invalid, k) {
addTest ('invalid key #' + (k + 1), rule [0].concat (invalid), types.string (), function (body) {
var match = new RegExp ('each of the keys of .+ should be equal to one of .+ but one of .+ is ' + cicek.escape (invalid));
return body && teishi.type (body.error) === 'string' && body.error.match (match);
});
});
}
// Values takes an array of possible values and defaults to the first one
// This constraint doesn't generate tests, only updates the valid payload
// TODO: make it so that every variant is tested in a full run of the test suite, by creating a NxN list of combinations.
else if (rule [1] === 'values') {
updateValid (rule [0], rule [2] [0]);
}
// This constraint doesn't update the valid payload
else if (rule [1] === 'invalidValues') {
dale.go (rule [2], function (invalid, k) {
addTest ('invalid value #' + (k + 1), rule [0], invalid, function (body) {
var regexMatch = new RegExp (last (rule [0]) + ' should match .+ but instead is ' + invalid);
var equalMatch = new RegExp (last (rule [0]) + ' should be (equal to|) one of .+ but instead is ' + invalid);
var customMatch;
if (rule [3]) customMatch = new RegExp (rule [3]);
return body && teishi.type (body.error) === 'string' && (customMatch ? body.error.match (customMatch) : (body.error.match (regexMatch) || body.error.match (equalMatch)));
});
});
}
// This constraint only works for generating strings
else if (rule [1] === 'length') {
dale.go (rule [2], function (v, k) {
updateValid (rule [0], stringMaker (v));
var invalidValue = v + (k === 'min' ? -1 : 1);
addTest ('invalid length - ' + k + ': ' + v, rule [0], stringMaker (invalidValue), function (body) {
var match = new RegExp (last (rule [0]) + ' length should be in range ' + cicek.escape (teishi.str (rule [2])) + ' but instead is ' + invalidValue);
var customMatch;
if (rule [3]) customMatch = new RegExp (rule [3]);
return body && teishi.type (body.error) === 'string' && (customMatch ? body.error.match (customMatch) : body.error.match (match));
});
});
}
else if (rule [1] === 'range') {
dale.go (rule [2], function (v, k) {
updateValid (rule [0], v);
var invalidValue = v + (k === 'min' ? -1 : 1);
addTest ('invalid range - ' + k + ': ' + v, rule [0], invalidValue, function (body) {
var match = new RegExp (last (rule [0]) + ' should be in range ' + cicek.escape (teishi.str (rule [2])) + ' but instead is ' + invalidValue);
return body && teishi.type (body.error) === 'string' && body.error.match (match);
});
});
}
else return error ('Invalid rule type: ' + rule [1]);
}
var parseRules = function (list) {
var invalid = dale.stopNot (list, undefined, function (ruleOrList) {
if (type (ruleOrList) !== 'array' || (type (ruleOrList [0]) !== 'array' && ruleOrList.length)) return ['Invalid rule or list of rules', ruleOrList, 'with type', type (ruleOrList)];
if (ruleOrList.length === 0) return;
if (type (ruleOrList [0] [0]) === 'array') return parseRules (ruleOrList);
runOne (ruleOrList);
});
if (invalid) return clog (invalid);
}
parseRules (rules);
return dale.go (tests, function (test) {
return ['Invalid payload - ' + label + ' - ' + test [0], 'post', Path, {}, test [1], 400, function (s, rq, rs) {
if (test [2]) return test [2] (s, rq, rs);
return true;
}];
});
}
}
var split = function (n) {
return n.toString ().replace (/\B(?=(\d{3})+(?!\d))/g, ',');
}
// *** TEST SUITES ***
var suites = {};
suites.auth = {
login: function (user) {
return ['login ' + user.username, 'post', 'auth/login', {}, function () {return {username: user.username, password: user.password, timezone: user.timezone}}, 200, H.setCredentials]
},
in: function (user) {
return [
['signup ' + user.username, 'post', 'auth/signup', {}, function (s) {
return {username: user.username, password: user.password, email: user.email};
}, 200, function (s, rq, rs) {
s.validationToken = rs.body.token;
if (rs.headers ['set-cookie']) return clog ('Signup should not log you in.');
return true;
}],
['verify ' + user.username, 'get', function (s) {return 'auth/verify/' + s.validationToken}, {}, '', 302],
suites.auth.login (user),
];
},
out: function (user) {
return [
suites.auth.login (user),
['delete account', 'post', 'auth/delete', {}, {}, 200, function (s, rq, rs) {
delete s.headers.cookie;
return true;
}],
];
},
full: function () {
if (noAuth) return [];
var user = tk.users.user1;
return [
H.invalidTestMaker ('signup', 'auth/signup', [
[[], 'object'],
[[], 'keys', ['username', 'password', 'email']],
dale.go (['username', 'password', 'email'], function (key) {
return [[key], 'string']
}),
[['email'], 'values', [tk.users.user1.email]],
[['username'], 'invalidValues', ['a@a', 'a:a']],
[['username'], 'invalidValues', ['aa', '\taa\n', ' '], 'Trimmed username is less than three characters long.'],
[['username'], 'invalidValues', ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', ' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa '], 'Trimmed username is more than forty characters long.'],
[['password'], 'length', {min: 6}],
// Taken from https://help.xmatters.com/ondemand/trial/valid_email_format.htm
[['email'], 'invalidValues', ['[email protected]', '[email protected]', '[email protected]', 'abc#[email protected]', '[email protected]', 'abc.def@mail#archive.com ', 'abc.def@mail', '[email protected]']],
]),
H.invalidTestMaker ('login', 'auth/login', [
[[], 'object'],
[[], 'keys', ['username', 'password', 'timezone']],
[['username'], 'string'],
[['password'], 'string'],
[['timezone'], 'integer'],
[['timezone'], 'range', {min: -840, max: 720}]
]),
H.invalidTestMaker ('recover', 'auth/recover', [
[[], 'object'],
[[], 'keys', ['username']],
[['username'], 'string'],
]),
H.invalidTestMaker ('reset', 'auth/reset', [
[[], 'object'],
[[], 'keys', ['username', 'password', 'token']],
[['username'], 'string'],
[['password'], 'string'],
[['token'], 'string'],
]),
['signup', 'post', 'auth/signup', {}, function (s) {
return {username: user.username, password: user.password, email: user.email};
}, 200, function (s, rq, rs) {
if (! rs.body.token) return clog ('No token returned after signup', rs.body);
s.verificationToken = rs.body.token;
return true;
}],
['try to signup with existing username', 'post', 'auth/signup', {}, function (s) {
return {username: user.username, password: user.password, email: user.email + 'foo'};
}, 403, H.cBody ({error: 'username'})],
['try to signup with existing email', 'post', 'auth/signup', {}, function (s) {
return {username: user.username + 'foo', password: user.password, email: user.email};
}, 403, H.cBody ({error: 'email'})],
['login with invalid password', 'post', 'auth/login', {}, {username: user.username, password: user.password + 'foo', timezone: user.timezone}, 403, H.cBody ({error: 'auth'})],
['login with invalid username', 'post', 'auth/login', {}, {username: user.username, password: user.password + 'foo', timezone: user.timezone}, 403, H.cBody ({error: 'auth'})],
['login before verification', 'post', 'auth/login', {}, function (s) {
return {username: user.username, password: user.password, timezone: user.timezone};
}, 403, H.cBody ({error: 'verify'})],
['verify user with invalid token', 'get', function (s) {return 'auth/verify/' + s.verificationToken + 'foo'}, {}, '', 302, function (s, rq, rs) {
if (H.stop ('location header', rs.headers.location, CONFIG.domain + '#/login/badtoken')) return false;
return true;
}],
['verify user', 'get', function (s) {return 'auth/verify/' + s.verificationToken}, {}, '', 302, function (s, rq, rs) {
if (H.stop ('location header', rs.headers.location, CONFIG.domain + '#/login/verified')) return false;
return true;
}],
['verify user again', 'get', function (s) {return 'auth/verify/' + s.verificationToken}, {}, '', 302, function (s, rq, rs) {
if (H.stop ('location header', rs.headers.location, CONFIG.domain + '#/login/verified')) return false;
return true;
}],
['login after verification', 'post', 'auth/login', {}, {username: user.username, password: user.password, timezone: user.timezone}, 200, function (s, rq, rs) {
if (! rs.headers ['set-cookie'] || rs.headers ['set-cookie'].length !== 1) return clog ('Invalid cookie header', rs.headers ['set-cookie']);
var cookie = rs.headers ['set-cookie'] [0];
if (! cookie.match ('HttpOnly')) return clog ('No HttpOnly flag');
if (type (rs.body) !== 'object' || type (rs.body.csrf) !== 'string') return clog ('Invalid CSRF token', rs.body);
H.setCredentials (s, rq, rs);
return true;
}],
['get account at the beginning of the test cycle', 'get', 'account', {}, '', 200, function (s, rq, rs) {
if (H.stop ('type of body', type (rs.body), 'object')) return false;
if (H.stop ('type of logs', type (rs.body.logs), 'array')) return false;
delete rs.body.logs;
if (type (rs.body.created) !== 'integer' || Math.abs (Date.now () - rs.body.created) > 5000) return clog ('Invalid created field', rs.body.created);
delete rs.body.created;
if (H.stop ('body', rs.body, {username: user.username, email: user.email, usage: {limit: CONFIG.freeSpace, byfs: 0, bys3: 0}, geo: true, suggestSelection: true, onboarding: true})) return false;
return true;
}],
['get CSRF token without being logged in', 'get', 'auth/csrf', {cookie: ''}, '', 403, H.cBody ({error: 'nocookie'})],
['get CSRF token with tampered cookie', 'get', 'auth/csrf', {cookie: CONFIG.cookieName + '=foo'}, '', 403, H.cBody ({error: 'tampered'})],
['get CSRF token with extraneous cookie', 'get', 'auth/csrf', {cookie: 'foo=bar'}, '', 403, H.cBody ({error: 'nocookie'})],
['get CSRF', 'get', 'auth/csrf', {}, '', 200, function (s, rq, rs) {
if (H.stop ('body', rs.body, {csrf: s.csrf})) return false;
return true;
}],
{tag: 'query pivs without csrf token', method: 'post', path: 'query', code: 403, body: {tags: ['a::'], sort: 'newest', from: 1, to: 10}, apres: H.cBody ({error: 'csrf'})},
{tag: 'query pivs with invalid csrf token', method: 'post', path: 'query', code: 403, body: {csrf: 'foobar', tags: ['a::'], sort: 'newest', from: 1, to: 10}, apres: H.cBody ({error: 'csrf'})},
['logout', 'post', 'auth/logout', {}, {}, 200, function (s, rq, rs) {
if (! rs.headers ['set-cookie'] || ! rs.headers ['set-cookie'] [0].match (/max-age=0/i)) return clog ('Invalid set-cookie header', res.headers ['set-cookie']);
return true;
}],
['get CSRF token with deleted cookie', 'get', 'auth/csrf', {}, '', 403, H.cBody ({error: 'session'})],
['logout again', 'post', 'auth/logout', {}, {}, 403, H.cBody ({error: 'session'})],
['delete account without being logged in', 'get', 'auth/delete', {}, '', 403],
['logout with no credentials', 'post', 'auth/logout', {cookie: ''}, {}, 403, H.cBody ({error: 'nocookie'})],
['login with email', 'post', 'auth/login', {}, function () {return {username: user.email, password: user.password, timezone: user.timezone}}, 200, H.setCredentials],
dale.go (['\t', ' ', ' \t '], function (space) {
return dale.go ([user.email + space, space + user.email, space + user.email + space, user.username + space, space + user.username, space + user.username + space, user.email.toUpperCase (), user.username.toUpperCase ()], function (spacedUsername) {
return ['login with username with spaces', 'post', 'auth/login', {}, function () {return {username: spacedUsername, password: user.password, timezone: user.timezone}}, 200];
});
}),
H.invalidTestMaker ('change password', 'auth/changePassword', [
[[], 'object'],
[[], 'keys', ['old', 'new']],
[['old'], 'string'],
[['new'], 'string'],
[['new'], 'length', {min: 6}, 'password should be in range {"min":6} but instead is 5'],
]),
['change password with invalid old password', 'post', 'auth/changePassword', {}, function (s) {return {old: user.password + 'foo', new: user.password + 'foo'}}, 403],
['change password', 'post', 'auth/changePassword', {}, function (s) {return {old: user.password, new: user.password + 'foo'}}, 200],
['login after password change with old password', 'post', 'auth/login', {}, function () {return {username: user.username, password: user.password, timezone: user.timezone}}, 403],
['login after password change with new password', 'post', 'auth/login', {}, function () {return {username: user.username, password: user.password + 'foo', timezone: user.timezone}}, 200, H.setCredentials],
['recover password with invalid username', 'post', 'auth/recover', {}, {username: user.username + 'foo'}, 403],
['recover password with valid username', 'post', 'auth/recover', {}, {username: user.username}, 200],
['recover password with valid email', 'post', 'auth/recover', {}, {username: user.username}, 200],
dale.go (['\t', ' ', ' \t '], function (space) {
return dale.go ([user.email + space, space + user.email, space + user.email + space, user.username + space, space + user.username, space + user.username + space, user.email.toUpperCase (), user.username.toUpperCase ()], function (spacedUsername) {
return ['recover password with username/email with spaces', 'post', 'auth/recover', {}, function () {return {username: spacedUsername}}, 200];
});
}),
['recover password', 'post', 'auth/recover', {}, {username: user.username}, 200, function (s, rq, rs) {
if (H.stop ('auth token', type (rs.body.token), 'string')) return false;
s.recoveryToken1 = rs.body.token;
return true;
}],
['recover password again with email to generate a new token', 'post', 'auth/recover', {}, {username: user.email}, 200, function (s, rq, rs) {
s.recoveryToken2 = rs.body.token;
return true;
}],
['reset password for invalid username', 'post', 'auth/reset', {}, function (s) {return {username: user.username + 'foo', password: user.password, token: s.recoveryToken2}}, 403, H.cBody ({error: 'token'})],
['reset password with invalid token', 'post', 'auth/reset', {}, function (s) {return {username: user.username, password: user.password, token: s.recoveryToken2 + 'foo'}}, 403],
['reset password with invaliidated token', 'post', 'auth/reset', {}, function (s) {return {username: user.username, password: user.password, token: s.recoveryToken1}}, 403],
['reset password', 'post', 'auth/reset', {}, function (s) {return {username: user.username, password: user.password + 'bar', token: s.recoveryToken2}}, 200],
['login after password reset', 'post', 'auth/login', {}, function () {return {username: user.username, password: user.password + 'bar', timezone: user.timezone}}, 200, H.setCredentials],
['get auth logs', 'get', 'account', {}, '', 200, function (s, rq, rs) {
var sequence = ['signup', 'verify', 'login', 'logout', 'login'];
dale.go (dale.times (24), function () {sequence.push ('login')});
sequence = sequence.concat ('passwordChange', 'login', 'recover', 'recover');
dale.go (dale.times (24), function () {sequence.push ('recover')});
sequence = sequence.concat ('recover', 'recover', 'reset', 'login');
if (H.stop ('log length', rs.body.logs.length, sequence.length)) return false;
if (dale.stop (rs.body.logs, false, function (log, k) {
if (H.stop ('log.ev', log.ev, 'auth')) return false;
if (H.stop ('log.type', log.type, sequence [k])) return false;
if (H.stop ('log.t type', type (log.t), 'integer')) return false;
if (H.stop ('log.ip', log.ip, '::ffff:127.0.0.1')) return false;
if (log.type === 'login' && H.stop ('log.timezone', log.timezone, user.timezone)) return false;
}) === false) return false;
return true;
}],
// /feedback is not really part of auth, but it goes here for lack of a better place to put it
H.invalidTestMaker ('feedback', 'feedback', [
[[], 'object'],
[[], 'keys', ['message']],
[['message'], 'string'],
]),
['send feedback', 'post', 'feedback', {}, {message: 'La radio está buenísima.'}, 200],
['login again to create a separate session', 'post', 'auth/login', {}, {username: tk.users.user1.username, password: tk.users.user1.password + 'bar', timezone: 0}, 200, function (s, rq, rs) {
s.alternativeSession = rs.headers ['set-cookie'] [0].split (';') [0];
return true;
}],
['delete account', 'post', 'auth/delete', {}, {}, 200, function (s, rq, rs) {
if (! rs.headers ['set-cookie'] || ! rs.headers ['set-cookie'] [0].match (/max-age=0/i)) return clog ('Invalid set-cookie header', res.headers ['set-cookie']);
return true;
}],
['get CSRF token after account deletion', 'get', 'auth/csrf', {}, '', 403, H.cBody ({error: 'session'})],
['get CSRF token after account deletion with alternative session', 'get', 'auth/csrf', function (s) {return {cookie: s.alternativeSession}}, '', 403, H.cBody ({error: 'session'})],
['logout after account deletion', 'post', 'auth/logout', {}, {}, 403, H.cBody ({error: 'session'})],
['login after account deletion', 'post', 'auth/login', {}, function () {return {username: user.username, password: user.password + 'bar', timezone: user.timezone}}, 403, function (s) {
s.headers = {};
return true;
}],
['signup again to verify deleted user', 'post', 'auth/signup', {}, function (s) {
return {username: user.username, password: user.password, email: user.email};
}, 200, function (s, rq, rs) {
s.verificationToken = rs.body.token;
return true;
}],
['verify user', 'get', function (s) {return 'auth/verify/' + s.verificationToken}, {}, '', 302],
['login again to create a separate session', 'post', 'auth/login', {}, {username: tk.users.user1.username, password: tk.users.user1.password, timezone: 0}, 200, H.setCredentials],
['delete account', 'post', 'auth/delete', {}, {}, 200, function (s, rq, rs) {
delete s.headers.cookie;
return true;
}],
['verify deleted user', 'get', function (s) {return 'auth/verify/' + s.verificationToken}, {}, '', 403, H.cBody ({error: 'auth'})],
];
}
}
suites.oauth = function () {
if (noManual) return [];
return [
H.invalidTestMaker ('google mobile signin', 'auth/signin/mobile/google', [
[[], 'object'],
[[], 'keys', ['token', 'platform', 'testToken']],
[['token'], 'string'],
[['platform'], 'values', ['android', 'ios']],
[['testToken'], 'object'],
]),
['get oauth client ids', 'get', 'auth/signin/credentials/google', {}, '', 200, H.cBody ({
android: SECRET.google.oauth.login.androidClientId,
ios: SECRET.google.oauth.login.iosClientId,
web: SECRET.google.oauth.login.webClientId,
})],
['dummy request before starting OAuth flow requiring manual input', 'get', '/', {}, '', 200, function (s, rq, rs, next) {
var googleClientId = '764404427753-v129e6ckia1eebpra59bmv648pidtjma.apps.googleusercontent.com';
var googleRedirectURI = CONFIG.domain + 'auth/signin/web/google';
var googleURI = 'https://accounts.google.com/o/oauth2/v2/auth?client_id=' + googleClientId + '&redirect_uri=' + googleRedirectURI + '&response_type=code&scope=openid%20email%20profile';
clog ('LOGIN NOW INTO GOOGLE', googleURI);
// Try for 20 seconds every second to see if the oauth flow is complete
H.tryTimeout (10, 2000, function (cb) {
redis.get ('oauth-token', function (error, user) {
if (error) return cb (null, null, error);
if (! user) return cb ('No user yet');
s.oauthToken = JSON.parse (user);
redis.get ('oauth-cookie', function (error, cookie) {
if (error) return cb (null, null, error);
if (! cookie) return cb ('No cookie yet');
s.headers = {cookie: cookie};
redis.get ('oauth-csrf', function (error, csrf) {
if (error) return cb (null, null, error);
if (! csrf) return cb ('No csrf token yet');
s.csrf = csrf;
var multi = redis.multi ();
// Cleanup test keys
multi.del ('oauth-token', 'oauth-cookie', 'oauth-csrf');
multi.exec (function (error) {
if (error) return cb (null, null, error);
cb ();
});
});
});
});
}, next);
}],
// Note: we haven't add tests that send a malformed token, or a tampered one.
['get account after creating user with oauth', 'get', 'account', {}, '', 200, function (s, rq, rs) {
if (H.stop ('type of body', type (rs.body), 'object')) return false;
if (H.stop ('type of logs', type (rs.body.logs), 'array')) return false;
if (type (rs.body.created) !== 'integer' || Math.abs (Date.now () - rs.body.created) > 5000) return clog ('Invalid created field', rs.body.created);
var error = dale.stopNot (['username', 'email', 'firstName', 'lastName', 'googleId'], undefined, function (field) {
if (type (rs.body [field]) !== 'string') return 'Invalid ' + field + ' field, must be string', rs.body [field];
});
if (error) return clog (error);
error = dale.stopNot (['geo', 'suggestSelection', 'onboarding'], undefined, function (field) {
if (rs.body [field] !== true) return 'Invalid ' + field + ' field, must be true', rs.body [field];
});
if (error) return clog (error);
if (H.stop ('type of body.logs', type (rs.body.logs), 'array')) return false;
if (H.stop ('body.logs length', rs.body.logs.length, 1)) return false;
if (H.stop ('body.logs [0].type', rs.body.logs [0].type, 'signup')) return false;
delete rs.body.logs;
s.oauthUser = rs.body;
s.headers = {};
return true;
}],
['recover password as user that already did oauth login', 'post', 'auth/recover', {}, function (s) {return {username: s.oauthUser.email}}, 200, function (s, rq, rs) {
s.recoveryToken = rs.body.token;
return true;
}],
['reset password', 'post', 'auth/reset', {}, function (s) {return {username: s.oauthUser.email, password: 'foobar', token: s.recoveryToken}}, 200],
['login with username and password for the first time with user that was created through oauth', 'post', 'auth/login', {}, function (s) {return {username: s.oauthUser.email, password: 'foobar', timezone: 0}}, 200, H.setCredentials],
['get account after logging in with username & password and check that it is the same user than the one created by oauth', 'get', 'account', {}, '', 200, function (s, rq, rs) {
if (H.stop ('type of body', type (rs.body), 'object')) return false;
if (H.stop ('type of logs', type (rs.body.logs), 'array')) return false;
if (type (rs.body.created) !== 'integer' || Math.abs (Date.now () - rs.body.created) > 5000) return clog ('Invalid created field', rs.body.created);
if (H.stop ('body.logs length', rs.body.logs.length, 4)) return false;
if (H.stop ('body.logs [0].type', rs.body.logs [0].type, 'signup')) return false;
if (H.stop ('body.logs [1].type', rs.body.logs [1].type, 'recover')) return false;
if (H.stop ('body.logs [2].type', rs.body.logs [2].type, 'reset')) return false;
if (H.stop ('body.logs [3].type', rs.body.logs [3].type, 'login')) return false;
delete rs.body.logs;
if (H.stop ('body', rs.body, s.oauthUser)) return false;
return true;
}],
['delete account', 'post', 'auth/delete', {}, {}, 200, function (s, rq, rs) {
delete s.headers.cookie;
return true;
}],
// Lack of abstraction doesn't allow me here to user suites.auth.in passing as email `s.oauthToken.email`
['create user anew using email from oauth but just using email/password', 'post', 'auth/signup', {}, function (s) {return {username: 'pacodelucia', email: s.oauthToken.email, password: 'foobar'}}, 200, function (s, rq, rs) {
s.validationToken = rs.body.token;
return true;
}],
['verify new user', 'get', function (s) {return 'auth/verify/' + s.validationToken}, {}, '', 302],
['login with username and password with user that was created through email', 'post', 'auth/login', {}, function (s) {return {username: s.oauthToken.email, password: 'foobar', timezone: 0}}, 200, H.setCredentials],
['get account after creating user with username/password', 'get', 'account', {}, '', 200, function (s, rq, rs) {
delete rs.body.logs;
s.emailUser = rs.body;
return true;
}],
['login with oauth using token', 'post', 'auth/signin/mobile/google', {}, function (s) {return {token: 'DUMMY', testToken: s.oauthToken, platform: 'android'}}, 200, H.setCredentials],
['get account after logging in with oauth to previously existing user', 'get', 'account', {}, '', 200, function (s, rq, rs) {
if (H.stop ('body.logs length', rs.body.logs.length, 4)) return false;
if (H.stop ('body.logs [0].type', rs.body.logs [0].type, 'signup')) return false;
if (H.stop ('body.logs [1].type', rs.body.logs [1].type, 'verify')) return false;
if (H.stop ('body.logs [2].type', rs.body.logs [2].type, 'login')) return false;
if (H.stop ('body.logs [5].type', rs.body.logs [3].type, 'login')) return false;
delete rs.body.logs;
// Add firstName and lastName to email user, as the server should have done after the login with oauth
s.emailUser.firstName = s.oauthToken.given_name;
s.emailUser.lastName = s.oauthToken.family_name;
// Add googleId
s.emailUser.googleId = s.oauthToken.sub;
if (H.stop ('body', rs.body, s.emailUser)) return false;
// Change email in token to trigger an email change on the next login
s.changedOAuthToken = teishi.copy (s.oauthToken);
s.changedOAuthToken.email = '[email protected]';
return true;
}],
['login with oauth using token with different email', 'post', 'auth/signin/mobile/google', {}, function (s) {return {token: 'DUMMY', testToken: s.changedOAuthToken, platform: 'android'}}, 200, H.setCredentials],
['get account after having logged in with oauth with different email, check that email was indeed changed on the same user', 'get', 'account', {}, '', 200, function (s, rq, rs) {
delete rs.body.logs;
delete rs.body.usage;
s.emailUser.email = '[email protected]';
delete s.emailUser.usage;
if (H.stop ('body', rs.body, s.emailUser)) return false;
return true;
}],
['login with new email and check that it associates to the existing account', 'post', 'auth/login', {}, function (s) {return {username: s.changedOAuthToken.email, password: 'foobar', timezone: 0}}, 200, H.setCredentials],
['get account after having logged in with changed email to see if the account is still the same', 'get', 'account', {}, '', 200, function (s, rq, rs) {
delete rs.body.logs;
delete rs.body.usage;
if (H.stop ('body', rs.body, s.emailUser)) return false;
return true;
}],
['signup with username/password using the email that is no longer used, to prove that the email was changed and freed up', 'post', 'auth/signup', {}, function (s) {return {username: 'another', email: s.oauthToken.email, password: 'foobar2'}}, 200, function (s, rq, rs) {
s.validationToken = rs.body.token;
return true;
}],
['verify new user', 'get', function (s) {return 'auth/verify/' + s.validationToken}, {}, '', 302],
['login with username and password with user that was created through email freed up by changing the email in the older user', 'post', 'auth/login', {}, function (s) {return {username: 'another', password: 'foobar2', timezone: 0}}, 200, H.setCredentials],
['attempt to login with token that uses an email that doesn\'t belong to it yet, but it is already taken', 'post', 'auth/signin/mobile/google', {}, function (s) {return {token: 'DUMMY', testToken: s.oauthToken, platform: 'android'}}, 409, H.cBody ({error: 'Another user already exists with that email'})],
['delete account with email but no oauth', 'post', 'auth/delete', {}, {}, 200],
['login to account with email & oauth', 'post', 'auth/login', {}, function (s) {return {username: s.changedOAuthToken.email, password: 'foobar', timezone: 0}}, 200, H.setCredentials],
['delete account with email & oauth', 'post', 'auth/delete', {}, {}, 200, function (s, rq, rs, next) {
delete s.headers.cookie;
redis.del ('oauth-token', 'oauth-cookie', 'oauth-csrf', function (error) {
if (error) return next (error);
next ();
});
}],
];
}
suites.public = function () {
return [
['get head /stats', 'head', 'stats', {}, '', 200],
dale.go ([['favicon.ico', 'assets/img/favicon.ico'], ['img/logo.svg', 'markup/img/logo.svg'], ['assets/gotoB.min.js', 'node_modules/gotob/gotoB.min.js'], ['client.js'], ['admin.js']], function (v) {
return {tag: 'get ' + v [0], method: 'get', path: v [0], code: 200, raw: true, apres: function (s, rq, rs) {
if (Buffer.compare (Buffer.from (rs.body, 'binary'), fs.readFileSync (v [1] || v [0])) !== 0) return clog ('Mismatch between original and uploaded file');
return true;
}};
}),
['get app root', 'get', '/', {}, '', 200],
['get admin root', 'get', 'admin', {}, '', 200],
['submit error (array)', 'post', 'error', {}, [1], 200, H.cBody ({priority: 'critical', type: 'client error in browser', ip: '::ffff:127.0.0.1', user: 'PUBLIC', error: [1]})],
['submit error (object)', 'post', 'error', {}, {sin: 'sobresaltos'}, 200, H.cBody ({priority: 'critical', type: 'client error in browser', ip: '::ffff:127.0.0.1', user: 'PUBLIC', error: {sin: 'sobresaltos'}})],
suites.auth.in (tk.users.user1),
['submit error as logged in user', 'post', 'error', {}, {sin: 'sobresaltos'}, 200, H.cBody ({priority: 'critical', type: 'client error in browser', ip: '::ffff:127.0.0.1', user: 'user1', error: {sin: 'sobresaltos'}})],
suites.auth.out (tk.users.user1),
['get public stats', 'get', 'stats', {}, '', 200, H.cBody ({byfs: '0', bys3: '0', pics: '0', vids: '0', pivs: '0', thumbS: '0', thumbM: '0', users: '0'})],
['check that regular user cannot reach the admin', 'get', 'admin/users', {}, '', 403],
];
}
suites.upload = {};
suites.upload.upload = function () {
return [
suites.auth.in (tk.users.user1),
['get uploads at the beginning', 'get', 'uploads', {}, '', 200, H.cBody ([])],
dale.go (['start', 'complete', 'cancel', 'wait', 'error'], function (op) {
var keys = ['op', 'provider'], invalidKeys;
if (op === 'error') {
keys = keys.concat ('id', 'error');
invalidKeys = ['tags', 'total', 'tooLarge', 'unsupported', 'alreadyImported'];
}
else if (op === 'start') {
keys = keys.concat ('tags', 'total', 'tooLarge', 'unsupported', 'alreadyImported');
invalidKeys = ['id', 'error'];
}
else {
keys = keys.concat ('id');
invalidKeys = ['tags', 'total', 'tooLarge', 'unsupported', 'alreadyImported'].concat ('error');
}
return H.invalidTestMaker ('upload ' + op, 'upload', [
[[], 'object'],
[['op'], 'values', [op]],
[[], 'keys', keys],
[[], 'invalidKeys', invalidKeys],
[['provider'], 'values', [undefined, 'google', 'dropbox']],
[['provider'], 'invalidValues', ['foo']],
op === 'start' ? [
['tags', 'tooLarge', 'unsupported'].map (function (key) {
return [
[[key], ['undefined', 'array']],
[[key, 0], 'type', 'string', 'each of the body.' + key + ' should have as type string but one of .+ is .+ with type'],
];
}),
[['total'], 'integer'],
[['total'], 'range', {min: 0}],
[['alreadyImported'], ['integer', 'undefined']],
[['alreadyImported'], 'range', {min: 1}],
[['tags'], 'invalidValues', [['a::', ' a::', 'a:: ']], 'invalid tag'],
[['tags'], 'invalidValues', [['ok', '\nu::']], 'invalid tag'],
] : [['id'], 'integer'],
op !== 'error' ? [] : [['error'], 'object']
]);
}),