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
|
// The environment variable HOST_DIR must be defined for the tests to
// work. Mocking exit gives a more descriptive error.
const exit = jest
.spyOn(process, "exit")
.mockImplementation(() => undefined as never);
import _request, { SuperTest, Test } from "supertest";
import express from "express";
import dotenv from "dotenv";
import fs from "fs";
import path from "path";
import { Writable } from "stream";
import winston from "winston";
dotenv.config();
test("Environment variable HOST_DIR must be defined", () => {
expect(process.env.HOST_DIR).not.toBeUndefined();
});
test("HOST_DIR must be readable and writable", () => {
expect(() =>
fs.accessSync(
process.env.HOST_DIR ?? "",
fs.constants.W_OK | fs.constants.R_OK
)
).not.toThrowError();
});
let output = "";
jest.mock("./util/logger", () => {
const stream = new Writable();
stream._write = (chunk, _encoding, next) => {
output = output += chunk.toString();
next();
};
const streamTransport = new winston.transports.Stream({ stream });
return {
__esModule: true,
default: () => ({
format: winston.format.combine(
winston.format.splat(),
winston.format.simple()
),
transports: [streamTransport],
}),
};
});
import { configOrError, persistTemplate } from "./config";
import loggerConfig from "./util/logger";
import routes from "./routes";
import Metadata, { EnvConfig } from "./metadata";
import { Template } from "./templates";
import { Db } from "mongodb";
import { badgen } from "badgen";
import { BranchNotFoundError } from "./errors";
type MetadataMockType = {
logger: winston.Logger;
database: Db;
config: EnvConfig;
getHeadCommit: jest.Mock;
getToken: jest.Mock;
getUploadLimit: jest.Mock;
getHostDir: jest.Mock;
getPublicDir: jest.Mock;
getGradientStyle: jest.Mock;
updateBranch: jest.Mock;
createRepository: jest.Mock;
};
const logger = winston.createLogger(loggerConfig("TEST", "debug"));
const config = {
token: "THISISCORRECT",
// should be just larger than the example report used
uploadLimit: Number(40000),
hostDir: configOrError("HOST_DIR", logger),
publicDir: path.join(__dirname, "..", "public"),
stage1: 95,
stage2: 80,
bindAddress: "localhost",
targetUrl: "http://localhost:3000/",
port: 3000,
dbName: "ao-coverage",
dbUri: "localhost",
logLevel: "debug",
};
const mock = (
headCommit: jest.Mock = jest.fn(
() =>
new Promise((solv) => solv({ commit: "testcommit", format: "tarpaulin" }))
),
updateBranch: jest.Mock = jest.fn(() => new Promise((solv) => solv(true)))
): MetadataMockType => ({
logger,
database: {} as Db,
config: config,
getToken: jest.fn(() => config.token),
getUploadLimit: jest.fn(() => config.uploadLimit),
getHostDir: jest.fn(() => config.hostDir),
getPublicDir: jest.fn(() => config.publicDir),
getGradientStyle: jest.fn(() => ({
stage1: config.stage1,
stage2: config.stage2,
})),
getHeadCommit: headCommit,
updateBranch: updateBranch,
createRepository: jest.fn(),
});
const request = async (
mockMeta: MetadataMockType = mock()
): Promise<SuperTest<Test>> => {
const app = express();
app.use(routes(mockMeta as Metadata));
return _request(app);
};
const HOST_DIR = configOrError("HOST_DIR", logger);
const TARGET_URL = "https://localhost:3000";
describe("templates", () => {
describe("GET /sh", () => {
it("should return the sh file containing the curl command", async () => {
await persistTemplate(
{
inputFile: path.join(
__dirname,
"..",
"public",
"templates",
"sh.tmpl"
),
outputFile: path.join(HOST_DIR, "sh"),
context: { TARGET_URL },
} as Template,
logger
);
const res = await (await request()).get("/sh").expect(200);
expect(exit).not.toHaveBeenCalled();
expect(res.text).toMatch("curl -X POST");
expect(res.text).toMatch(`url="${TARGET_URL}"`);
});
});
describe("GET /", () => {
it("should return the index HTML file containing the bash command", async () => {
await persistTemplate(
{
inputFile: path.join(
__dirname,
"..",
"public",
"templates",
"index.html.tmpl"
),
outputFile: path.join(HOST_DIR, "index.html"),
context: { TARGET_URL, CURL_HTTPS: "--https " },
} as Template,
logger
);
const res = await (await request())
.get("/")
.expect("Content-Type", /html/)
.expect(200);
expect(exit).not.toHaveBeenCalled();
expect(res.text).toMatch(`curl --https -sSf ${TARGET_URL}/sh | sh`);
});
});
});
describe("Static files", () => {
const staticRoot = path.join(__dirname, "..", "public", "static");
it("should return favicon.ico at GET /favicon.ico", async () => {
const buffer = await fs.promises.readFile(
path.join(staticRoot, "favicon.ico")
);
await (await request())
.get("/favicon.ico")
.expect("Content-Type", /icon/)
.expect(buffer)
.expect(200);
});
it("should return index.css at GET /static/index.css", async () => {
const buffer = await fs.promises.readFile(
path.join(staticRoot, "index.css")
);
const res = await (await request()).get("/static/index.css").expect(200);
expect(res.text).toEqual(buffer.toString("utf-8"));
});
it("should return 404.html at unhandled endpoints", async () => {
const buffer = await fs.promises.readFile(
path.join(staticRoot, "404.html")
);
const res = await (await request()).get("/thisisnotanendpoint").expect(404);
expect(res.text).toEqual(buffer.toString("utf-8"));
});
});
describe("Badges and reports", () => {
const reportPath = path.join(
HOST_DIR,
"testorg",
"testrepo",
"testbranch",
"testcommit"
);
const tarpaulinReport = path.join(
__dirname,
"..",
"example_reports",
"tarpaulin-report.html"
);
const coberturaReport = path.join(
__dirname,
"..",
"example_reports",
"cobertura-report.xml"
);
const fakeBadge = badgen({
label: "coverage",
status: "120%",
color: "#E1C",
});
beforeAll(async () => {
// place test files on HOST_DIR
await fs.promises.mkdir(reportPath, { recursive: true });
await fs.promises.copyFile(
tarpaulinReport,
path.join(reportPath, "index.html")
);
await fs.promises.copyFile(
coberturaReport,
path.join(reportPath, "index.xml")
);
await fs.promises.writeFile(path.join(reportPath, "badge.svg"), fakeBadge);
});
describe("GET /v1/:org/:repo/:branch/:commit.html", () => {
it("should retrieve the stored report file", async () => {
const res = await (await request())
.get("/v1/testorg/testrepo/testbranch/testcommit.html")
.expect("Content-Type", /html/)
.expect(200);
const buffer = await fs.promises.readFile(tarpaulinReport);
expect(res.text).toEqual(buffer.toString("utf-8"));
});
it("should return 404 if file does not exist", async () => {
await (await request())
.get("/v1/neorg/nerepo/nebranch/necommit.html")
.expect(404);
});
});
describe("GET /v1/:org/:repo/:branch/:commit.xml", () => {
it("should retrieve the stored report file", async () => {
const res = await (await request())
.get("/v1/testorg/testrepo/testbranch/testcommit.xml")
.expect("Content-Type", /xml/)
.expect(200);
const buffer = await fs.promises.readFile(coberturaReport);
expect(res.text).toEqual(buffer.toString("utf-8"));
});
it("should return 404 if file does not exist", async () => {
await (await request())
.get("/v1/neorg/nerepo/nebranch/necommit.xml")
.expect(404);
});
});
describe("GET /v1/:org/:repo/:branch.html", () => {
it("should retrieve the stored report file with the associated head commit", async () => {
const mockMeta = mock();
const res = await (await request(mockMeta))
.get("/v1/testorg/testrepo/testbranch.html")
.expect("Content-Type", /html/)
.expect(200);
const buffer = await fs.promises.readFile(tarpaulinReport);
expect(mockMeta.getHeadCommit).toHaveBeenCalledTimes(1);
expect(res.text).toEqual(buffer.toString("utf-8"));
});
it("should retrieve the marked format as stored in metadata", async () => {
const head = jest.fn(
() =>
new Promise((solv) =>
solv({ commit: "testcommit", format: "cobertura" })
)
);
const mockMeta = mock(head);
// request HTML, get XML
const res = await (await request(mockMeta))
.get("/v1/testorg/testrepo/testbranch.html")
.expect("Content-Type", /xml/)
.expect(200);
const buffer = await fs.promises.readFile(coberturaReport);
expect(mockMeta.getHeadCommit).toHaveBeenCalledTimes(1);
expect(res.text).toEqual(buffer.toString("utf-8"));
});
it("should return 404 if file does not exist", async () => {
await (await request()).get("/v1/neorg/nerepo/nebranch.html").expect(404);
});
it("should return 404 if head commit not found", async () => {
const head = jest.fn(
() => new Promise((solv) => solv(new BranchNotFoundError()))
);
await (await request(mock(head)))
.get("/v1/testorg/testrepo/testbranch.html")
.expect(404);
});
it("should return 500 if promise is rejected", async () => {
const head = jest.fn(() => new Promise((_, rej) => rej("fooey")));
await (await request(mock(head)))
.get("/v1/testorg/testrepo/testbranch.html")
.expect(500);
});
});
describe("GET /v1/:org/:repo/:branch.xml", () => {
it("should retrieve the stored report file with the associated head commit", async () => {
const head = jest.fn(
() =>
new Promise((solv) =>
solv({ commit: "testcommit", format: "cobertura" })
)
);
const mockMeta = mock(head);
const res = await (await request(mockMeta))
.get("/v1/testorg/testrepo/testbranch.xml")
.expect("Content-Type", /xml/)
.expect(200);
const buffer = await fs.promises.readFile(coberturaReport);
expect(mockMeta.getHeadCommit).toHaveBeenCalledTimes(1);
expect(res.text).toEqual(buffer.toString("utf-8"));
});
it("should retrieve the marked format as stored in metadata", async () => {
const head = jest.fn(
() =>
new Promise((solv) =>
solv({ commit: "testcommit", format: "tarpaulin" })
)
);
const mockMeta = mock(head);
// request XML, get HTML
const res = await (await request(mockMeta))
.get("/v1/testorg/testrepo/testbranch.xml")
.expect("Content-Type", /html/)
.expect(200);
const buffer = await fs.promises.readFile(tarpaulinReport);
expect(mockMeta.getHeadCommit).toHaveBeenCalledTimes(1);
expect(res.text).toEqual(buffer.toString("utf-8"));
});
it("should return 404 if file does not exist", async () => {
await (await request()).get("/v1/neorg/nerepo/nebranch.xml").expect(404);
});
it("should return 404 if head commit not found", async () => {
const head = jest.fn(
() => new Promise((solv) => solv(new BranchNotFoundError()))
);
await (await request(mock(head)))
.get("/v1/testorg/testrepo/testbranch.xml")
.expect(404);
});
it("should return 500 if promise is rejected", async () => {
const head = jest.fn(() => new Promise((_, rej) => rej("fooey")));
await (await request(mock(head)))
.get("/v1/testorg/testrepo/testbranch.xml")
.expect(500);
});
});
describe("GET /v1/:org/:repo/:branch/:commit.svg", () => {
it("should retrieve the stored report badge", async () => {
const res = await (await request())
.get("/v1/testorg/testrepo/testbranch/testcommit.svg")
.expect("Content-Type", /svg/)
.expect(200);
expect(res.body.toString("utf-8")).toEqual(fakeBadge);
});
it("should return 404 if file does not exist", async () => {
await (await request())
.get("/v1/neorg/nerepo/nebranch/necommit.svg")
.expect(404);
});
});
describe("GET /v1/:org/:repo/:branch.svg", () => {
it("should retrieve the stored report badge with the associated head commit", async () => {
const mockMeta = mock();
const res = await (await request(mockMeta))
.get("/v1/testorg/testrepo/testbranch.svg")
.expect("Content-Type", /svg/)
.expect(200);
expect(mockMeta.getHeadCommit).toHaveBeenCalledTimes(1);
expect(res.body.toString("utf-8")).toEqual(fakeBadge);
});
it("should return 404 if file does not exist", async () => {
await (await request()).get("/v1/neorg/nerepo/nebranch.svg").expect(404);
});
it("should return 404 if head commit not found", async () => {
const head = jest.fn(
() => new Promise((solv) => solv(new BranchNotFoundError()))
);
await (await request(mock(head)))
.get("/v1/testorg/testrepo/testbranch.svg")
.expect(404);
});
it("should return 500 if promise is rejected", async () => {
const head = jest.fn(() => new Promise((_, rej) => rej("fooey")));
await (await request(mock(head)))
.get("/v1/testorg/testrepo/testbranch.svg")
.expect(500);
});
});
});
describe("Uploads", () => {
const reportPath = path.join(
HOST_DIR,
"testorg",
"testrepo",
"newthis",
"newthat"
);
beforeEach(async () => {
try {
await fs.promises.rmdir(reportPath);
} catch (err) {
// ignore failures for rmdir
}
});
describe("GET /v1/health-check", () => {
it("should return 200 OK", async () => {
await (await request()).get(`/v1/health-check`).send().expect(200);
});
});
describe("POST /v1/:org/:repo/:branch/:commit.html", () => {
const data = fs.promises.readFile(
path.join(__dirname, "..", "example_reports", "tarpaulin-report.html")
);
it("should upload the report and generate a badge", async () => {
const mockMeta = mock();
await (
await request(mockMeta)
)
.post(
`/v1/testorg/testrepo/newthis/newthat.html?token=${config.token}&format=tarpaulin`
)
.send(await data)
.expect(200);
expect(mockMeta.updateBranch).toBeCalledWith({
organization: "testorg",
repository: "testrepo",
branch: "newthis",
head: { commit: "newthat", format: "tarpaulin" },
});
expect(mockMeta.updateBranch).toHaveBeenCalledTimes(1);
await fs.promises.access(
path.join(reportPath, "index.html"),
fs.constants.R_OK
);
await fs.promises.access(
path.join(reportPath, "badge.svg"),
fs.constants.R_OK
);
});
it("should return 401 when token is not correct", async () => {
await (
await request()
)
.post(
`/v1/testorg/testrepo/newthis/newthat.html?token=wrong&format=tarpaulin`
)
.send(await data)
.expect(401);
});
it("should return 406 with an invalid format", async () => {
await (
await request()
)
.post(
`/v1/testorg/testrepo/newthis/newthat.html?token=${config.token}&format=pepperoni`
)
.send(await data)
.expect(406);
});
it("should return 400 when request body is not the appropriate format", async () => {
await (await request())
.post(
`/v1/testorg/testrepo/newthis/newthat.html?token=${config.token}&format=tarpaulin`
)
.send("This is not a file")
.expect(400);
});
it("should return 413 when request body is not the appropriate format", async () => {
const file = await data;
let bigData = file;
while (bigData.length <= config.uploadLimit) {
bigData = Buffer.concat([bigData, file]);
}
await (await request())
.post(
`/v1/testorg/testrepo/newthis/newthat.html?token=${config.token}&format=tarpaulin`
)
.send(bigData)
.expect(413);
});
it("should return 500 when Metadata does not create branch", async () => {
const update = jest.fn(() => new Promise((solv) => solv(false)));
await (
await request(mock(jest.fn(), update))
)
.post(
`/v1/testorg/testrepo/newthis/newthat.html?token=${config.token}&format=tarpaulin`
)
.send(await data)
.expect(500);
});
it("should return 500 when promise chain is rejected", async () => {
const update = jest.fn(() => new Promise((_, rej) => rej("fooey 2")));
await (
await request(mock(jest.fn(), update))
)
.post(
`/v1/testorg/testrepo/newthis/newthat.html?token=${config.token}&format=tarpaulin`
)
.send(await data)
.expect(500);
});
});
describe("POST /v1/:org/:repo/:branch/:commit.xml", () => {
const data = fs.promises.readFile(
path.join(__dirname, "..", "example_reports", "cobertura-report.xml")
);
it("should upload the report and generate a badge", async () => {
const mockMeta = mock();
await (
await request(mockMeta)
)
.post(
`/v1/testorg/testrepo/newthis/newthat.xml?token=${config.token}&format=cobertura`
)
.send(await data)
.expect(200);
expect(mockMeta.updateBranch).toBeCalledWith({
organization: "testorg",
repository: "testrepo",
branch: "newthis",
head: { commit: "newthat", format: "cobertura" },
});
expect(mockMeta.updateBranch).toHaveBeenCalledTimes(1);
await fs.promises.access(
path.join(reportPath, "index.xml"),
fs.constants.R_OK
);
await fs.promises.access(
path.join(reportPath, "badge.svg"),
fs.constants.R_OK
);
});
it("should return 401 when token is not correct", async () => {
await (
await request()
)
.post(
`/v1/testorg/testrepo/newthis/newthat.xml?token=wrong&format=cobertura`
)
.send(await data)
.expect(401);
});
it("should return 406 with an invalid format", async () => {
await (
await request()
)
.post(
`/v1/testorg/testrepo/newthis/newthat.xml?token=${config.token}&format=pepperoni`
)
.send(await data)
.expect(406);
});
it("should return 400 when request body is not the appropriate format", async () => {
await (await request())
.post(
`/v1/testorg/testrepo/newthis/newthat.xml?token=${config.token}&format=cobertura`
)
.send("This is not a file")
.expect(400);
});
it("should return 413 when request body is not the appropriate format", async () => {
const file = await data;
let bigData = file;
while (bigData.length <= config.uploadLimit) {
bigData = Buffer.concat([bigData, file]);
}
await (await request())
.post(
`/v1/testorg/testrepo/newthis/newthat.xml?token=${config.token}&format=cobertura`
)
.send(bigData)
.expect(413);
});
it("should return 500 when Metadata does not create branch", async () => {
const update = jest.fn(() => new Promise((solv) => solv(false)));
await (
await request(mock(jest.fn(), update))
)
.post(
`/v1/testorg/testrepo/newthis/newthat.xml?token=${config.token}&format=cobertura`
)
.send(await data)
.expect(500);
});
it("should return 500 when promise chain is rejected", async () => {
const update = jest.fn(() => new Promise((_, rej) => rej("fooey 2")));
await (
await request(mock(jest.fn(), update))
)
.post(
`/v1/testorg/testrepo/newthis/newthat.xml?token=${config.token}&format=cobertura`
)
.send(await data)
.expect(500);
});
});
});
|