-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp-request.test.mts
More file actions
2266 lines (1925 loc) · 73.8 KB
/
http-request.test.mts
File metadata and controls
2266 lines (1925 loc) · 73.8 KB
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
/**
* @fileoverview Unit tests for HTTP/HTTPS request utilities.
*
* Tests HTTP client utilities with local test server:
* - httpRequest() low-level HTTP request function
* - httpText() fetches and returns text content
* - httpJson() fetches and parses JSON responses
* - httpDownload() downloads files to disk
* - Redirect following, timeout handling, error cases
* - Custom headers, user agent, retry logic
* Used by Socket tools for API communication (registry, GitHub, GHSA).
*/
import { createHash } from 'node:crypto'
import { promises as fs } from 'node:fs'
import http from 'node:http'
import path from 'node:path'
import { Writable } from 'node:stream'
import {
enrichErrorMessage,
fetchChecksums,
httpDownload,
httpJson,
httpRequest,
httpText,
parseChecksums,
readIncomingResponse,
} from '@socketsecurity/lib/http-request'
import type {
HttpHookRequestInfo,
HttpHookResponseInfo,
IncomingRequest,
IncomingResponse,
} from '@socketsecurity/lib/http-request'
import { Logger } from '@socketsecurity/lib/logger'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { runWithTempDir } from './utils/temp-file-helper'
// Test server setup
let httpServer: http.Server
let httpPort: number
let httpBaseUrl: string
beforeAll(async () => {
// Create HTTP test server
await new Promise<void>(resolve => {
httpServer = http.createServer((req, res) => {
const url = req.url || ''
// Handle different test endpoints
if (url === '/json') {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ message: 'Hello, World!', status: 'success' }))
} else if (url === '/text') {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Plain text response')
} else if (url === '/redirect') {
res.writeHead(302, { Location: '/text' })
res.end()
} else if (url === '/redirect-absolute') {
res.writeHead(302, { Location: `${httpBaseUrl}/text` })
res.end()
} else if (url === '/redirect-loop-1') {
res.writeHead(302, { Location: '/redirect-loop-2' })
res.end()
} else if (url === '/redirect-loop-2') {
res.writeHead(302, { Location: '/redirect-loop-3' })
res.end()
} else if (url === '/redirect-loop-3') {
res.writeHead(302, { Location: '/redirect-loop-4' })
res.end()
} else if (url === '/redirect-loop-4') {
res.writeHead(302, { Location: '/redirect-loop-5' })
res.end()
} else if (url === '/redirect-loop-5') {
res.writeHead(302, { Location: '/redirect-loop-6' })
res.end()
} else if (url === '/redirect-loop-6') {
res.writeHead(302, { Location: '/text' })
res.end()
} else if (url === '/not-found') {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.end('Not Found')
} else if (url === '/server-error') {
res.writeHead(500, { 'Content-Type': 'text/plain' })
res.end('Internal Server Error')
} else if (url === '/timeout') {
// Don't respond - simulate timeout
return
} else if (url === '/slow') {
// Respond after delay
setTimeout(() => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Slow response')
}, 100)
} else if (url === '/echo-method') {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end(req.method)
} else if (url === '/echo-body') {
let body = ''
req.on('data', chunk => {
body += chunk.toString()
})
req.on('end', () => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end(body)
})
} else if (url === '/echo-headers') {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(req.headers))
} else if (url === '/binary') {
res.writeHead(200, { 'Content-Type': 'application/octet-stream' })
const buffer = Buffer.from([0x00, 0x01, 0x02, 0x03, 0xff, 0xfe, 0xfd])
res.end(buffer)
} else if (url === '/download') {
const content = 'Download test content'
res.writeHead(200, {
'Content-Length': String(content.length),
'Content-Type': 'text/plain',
})
// Send data in chunks to test progress
const chunk1 = content.slice(0, 10)
const chunk2 = content.slice(10)
res.write(chunk1)
setTimeout(() => {
res.end(chunk2)
}, 10)
} else if (url === '/large-download') {
const content = 'X'.repeat(1000)
res.writeHead(200, {
'Content-Length': String(content.length),
'Content-Type': 'text/plain',
})
res.end(content)
} else if (url === '/download-no-length') {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('No content length')
} else if (url === '/invalid-json') {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end('not valid json{')
} else if (url === '/checksum-file') {
// File with known content for checksum testing.
const content = 'Test content for checksum verification'
res.writeHead(200, {
'Content-Length': String(content.length),
'Content-Type': 'text/plain',
})
res.end(content)
} else if (url === '/checksums.txt') {
// Checksums file in standard format: "hash filename".
const content = 'Test content for checksum verification'
const hash = createHash('sha256').update(content).digest('hex')
const checksums = `${hash} checksum-file\nabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890 other-file\n`
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end(checksums)
} else if (url === '/checksums-single-space.txt') {
// Checksums file with single space separator.
const content = 'Test content for checksum verification'
const hash = createHash('sha256').update(content).digest('hex')
const checksums = `${hash} checksum-file\n`
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end(checksums)
} else if (url === '/checksums-missing.txt') {
// Checksums file without our target file.
const checksums =
'abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890 other-file\n'
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end(checksums)
} else if (url === '/checksums-empty.txt') {
// Empty checksums file (only comments).
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('# This file has no checksums\n\n')
} else if (url === '/large-body') {
const content = 'X'.repeat(10_000)
res.writeHead(200, {
'Content-Length': String(content.length),
'Content-Type': 'text/plain',
})
res.end(content)
} else if (url === '/post-success') {
if (req.method === 'POST') {
res.writeHead(201, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ created: true }))
} else {
res.writeHead(405)
res.end()
}
} else if (url === '/no-redirect') {
res.writeHead(301, { Location: '/text' })
res.end()
} else {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('OK')
}
})
httpServer.listen(0, () => {
const address = httpServer.address()
if (address && typeof address === 'object') {
httpPort = address.port
httpBaseUrl = `http://localhost:${httpPort}`
}
resolve()
})
})
// Create HTTPS test server (self-signed)
await new Promise<void>(resolve => {
// For testing, we'll skip HTTPS server as it requires certificates
// In production tests, you would set up proper certificates
resolve()
})
})
afterAll(async () => {
await new Promise<void>(resolve => {
httpServer.close(() => resolve())
})
})
function makeRawRequest(url: string): Promise<http.IncomingMessage> {
return new Promise((resolve, reject) => {
http.get(url, resolve).on('error', reject)
})
}
describe('http-request', () => {
describe('httpRequest', () => {
it('should make a simple GET request', async () => {
const response = await httpRequest(`${httpBaseUrl}/text`)
expect(response.status).toBe(200)
expect(response.ok).toBe(true)
expect(response.statusText).toBe('OK')
expect(response.text()).toBe('Plain text response')
})
it('should parse JSON response', async () => {
const response = await httpRequest(`${httpBaseUrl}/json`)
expect(response.status).toBe(200)
expect(response.ok).toBe(true)
const data = response.json<{ message: string; status: string }>()
expect(data.message).toBe('Hello, World!')
expect(data.status).toBe('success')
})
it('should handle 404 errors', async () => {
const response = await httpRequest(`${httpBaseUrl}/not-found`)
expect(response.status).toBe(404)
expect(response.ok).toBe(false)
expect(response.statusText).toBe('Not Found')
expect(response.text()).toBe('Not Found')
})
it('should handle 500 errors', async () => {
const response = await httpRequest(`${httpBaseUrl}/server-error`)
expect(response.status).toBe(500)
expect(response.ok).toBe(false)
expect(response.text()).toBe('Internal Server Error')
})
it('should follow redirects by default', async () => {
const response = await httpRequest(`${httpBaseUrl}/redirect`)
expect(response.status).toBe(200)
expect(response.text()).toBe('Plain text response')
})
it('should follow absolute URL redirects', async () => {
const response = await httpRequest(`${httpBaseUrl}/redirect-absolute`)
expect(response.status).toBe(200)
expect(response.text()).toBe('Plain text response')
})
it('should not follow redirects when followRedirects is false', async () => {
const response = await httpRequest(`${httpBaseUrl}/no-redirect`, {
followRedirects: false,
})
expect(response.status).toBe(301)
expect(response.ok).toBe(false)
expect(response.headers.location).toBe('/text')
})
it('should handle too many redirects', async () => {
await expect(
httpRequest(`${httpBaseUrl}/redirect-loop-1`, { maxRedirects: 3 }),
).rejects.toThrow(/Too many redirects/)
})
it('should make POST request', async () => {
const response = await httpRequest(`${httpBaseUrl}/post-success`, {
method: 'POST',
})
expect(response.status).toBe(201)
expect(response.json<{ created: boolean }>().created).toBe(true)
})
it('should send request body as string', async () => {
const body = JSON.stringify({ test: 'data' })
const response = await httpRequest(`${httpBaseUrl}/echo-body`, {
body,
method: 'POST',
})
expect(response.text()).toBe(body)
})
it('should send request body as Buffer', async () => {
const buffer = Buffer.from('binary data')
const response = await httpRequest(`${httpBaseUrl}/echo-body`, {
body: buffer,
method: 'POST',
})
expect(response.text()).toBe('binary data')
})
it('should send custom headers', async () => {
const response = await httpRequest(`${httpBaseUrl}/echo-headers`, {
headers: {
'X-Custom-Header': 'custom-value',
},
})
const headers = response.json<Record<string, string>>()
expect(headers['x-custom-header']).toBe('custom-value')
expect(headers['user-agent']).toBe('socket-registry/1.0')
})
it('should handle custom User-Agent', async () => {
const response = await httpRequest(`${httpBaseUrl}/echo-headers`, {
headers: {
'User-Agent': 'my-custom-agent',
},
})
const headers = response.json<Record<string, string>>()
expect(headers['user-agent']).toBe('my-custom-agent')
})
it('should support different HTTP methods', async () => {
const methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']
const results = await Promise.all(
methods.map(async method => {
const response = await httpRequest(`${httpBaseUrl}/echo-method`, {
method,
})
return { method, text: response.text() }
}),
)
for (const result of results) {
expect(result.text).toBe(result.method)
}
})
it('should get arrayBuffer from response', async () => {
const response = await httpRequest(`${httpBaseUrl}/binary`)
const arrayBuffer = response.arrayBuffer()
const view = new Uint8Array(arrayBuffer)
expect(Array.from(view)).toEqual([
0x00, 0x01, 0x02, 0x03, 0xff, 0xfe, 0xfd,
])
})
it('should expose body as Buffer', async () => {
const response = await httpRequest(`${httpBaseUrl}/binary`)
expect(Buffer.isBuffer(response.body)).toBe(true)
expect(Array.from(response.body)).toEqual([
0x00, 0x01, 0x02, 0x03, 0xff, 0xfe, 0xfd,
])
})
it('should handle timeout', async () => {
await expect(
httpRequest(`${httpBaseUrl}/timeout`, { timeout: 100 }),
).rejects.toThrow(/timed out after 100ms/)
})
it('should complete before timeout', async () => {
const response = await httpRequest(`${httpBaseUrl}/slow`, {
timeout: 2000,
})
expect(response.text()).toBe('Slow response')
})
it('should retry on failure', async () => {
let attemptCount = 0
const testServer = http.createServer((req, res) => {
attemptCount++
if (attemptCount < 3) {
// Fail first 2 attempts
req.socket.destroy()
} else {
// Succeed on 3rd attempt
res.writeHead(200)
res.end('Success after retries')
}
})
await new Promise<void>(resolve => {
testServer.listen(0, () => resolve())
})
const address = testServer.address()
const testPort = address && typeof address === 'object' ? address.port : 0
try {
const response = await httpRequest(`http://localhost:${testPort}/`, {
retries: 3,
retryDelay: 10,
})
expect(response.text()).toBe('Success after retries')
expect(attemptCount).toBe(3)
} finally {
await new Promise<void>(resolve => {
testServer.close(() => resolve())
})
}
})
it('should fail after all retries exhausted', async () => {
let attemptCount = 0
const testServer = http.createServer((req, _res) => {
attemptCount++
req.socket.destroy()
})
await new Promise<void>(resolve => {
testServer.listen(0, () => resolve())
})
const address = testServer.address()
const testPort = address && typeof address === 'object' ? address.port : 0
try {
await expect(
httpRequest(`http://localhost:${testPort}/`, {
retries: 2,
retryDelay: 10,
}),
).rejects.toThrow(/request failed/)
expect(attemptCount).toBe(3) // Initial attempt + 2 retries
} finally {
await new Promise<void>(resolve => {
testServer.close(() => resolve())
})
}
})
it('should handle network errors', async () => {
await expect(
httpRequest('http://localhost:1/nonexistent', { timeout: 100 }),
).rejects.toThrow(/request failed/)
})
it('should handle invalid URLs gracefully', async () => {
await expect(httpRequest('not-a-url')).rejects.toThrow()
})
it('should use exponential backoff for retries', async () => {
const startTime = Date.now()
let attemptCount = 0
const testServer = http.createServer((req, _res) => {
attemptCount++
req.socket.destroy()
})
await new Promise<void>(resolve => {
testServer.listen(0, () => resolve())
})
const address = testServer.address()
const testPort = address && typeof address === 'object' ? address.port : 0
try {
await httpRequest(`http://localhost:${testPort}/`, {
retries: 2,
retryDelay: 100,
}).catch(() => {
// Expected to fail
})
const elapsed = Date.now() - startTime
// Should wait at least 100ms + 200ms = 300ms for exponential backoff
expect(elapsed).toBeGreaterThanOrEqual(200)
expect(attemptCount).toBe(3)
} finally {
await new Promise<void>(resolve => {
testServer.close(() => resolve())
})
}
})
it('should handle connection close without response', async () => {
const testServer = http.createServer((_req, _res) => {
// Close connection without sending response
_res.socket?.destroy()
})
await new Promise<void>(resolve => {
testServer.listen(0, () => resolve())
})
const address = testServer.address()
const testPort = address && typeof address === 'object' ? address.port : 0
try {
await expect(
httpRequest(`http://localhost:${testPort}/`),
).rejects.toThrow(/request failed/)
} finally {
await new Promise<void>(resolve => {
testServer.close(() => resolve())
})
}
})
})
describe('httpDownload', () => {
it('should download file to disk', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'download.txt')
const result = await httpDownload(`${httpBaseUrl}/download`, destPath)
expect(result.path).toBe(destPath)
expect(result.size).toBeGreaterThan(0)
const content = await fs.readFile(destPath, 'utf8')
expect(content).toBe('Download test content')
}, 'httpDownload-basic-')
})
it('should track download progress', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'progress.txt')
const progressUpdates: Array<{ downloaded: number; total: number }> = []
await httpDownload(`${httpBaseUrl}/large-download`, destPath, {
onProgress: (downloaded, total) => {
progressUpdates.push({ downloaded, total })
},
})
expect(progressUpdates.length).toBeGreaterThan(0)
// Last update should have full size
const lastUpdate = progressUpdates[progressUpdates.length - 1]
expect(lastUpdate.downloaded).toBe(lastUpdate.total)
expect(lastUpdate.total).toBe(1000)
}, 'httpDownload-progress-')
})
it('should not call progress callback when no content-length', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'no-length.txt')
let progressCalled = false
await httpDownload(`${httpBaseUrl}/download-no-length`, destPath, {
onProgress: () => {
progressCalled = true
},
})
expect(progressCalled).toBe(false)
const content = await fs.readFile(destPath, 'utf8')
expect(content).toBe('No content length')
}, 'httpDownload-no-length-')
})
it('should handle download errors', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'error.txt')
await expect(
httpDownload(`${httpBaseUrl}/not-found`, destPath),
).rejects.toThrow(/Download failed: HTTP 404/)
}, 'httpDownload-error-')
})
it('should handle download timeout', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'timeout.txt')
await expect(
httpDownload(`${httpBaseUrl}/timeout`, destPath, { timeout: 100 }),
).rejects.toThrow(/timed out after 100ms/)
}, 'httpDownload-timeout-')
})
it('should retry download on failure', async () => {
let attemptCount = 0
const testServer = http.createServer((req, res) => {
attemptCount++
if (attemptCount < 3) {
req.socket.destroy()
} else {
res.writeHead(200, { 'Content-Length': '7' })
res.end('Success')
}
})
await new Promise<void>(resolve => {
testServer.listen(0, () => resolve())
})
const address = testServer.address()
const testPort = address && typeof address === 'object' ? address.port : 0
try {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'retry.txt')
const result = await httpDownload(
`http://localhost:${testPort}/`,
destPath,
{
retries: 3,
retryDelay: 10,
},
)
expect(result.size).toBe(7)
expect(attemptCount).toBe(3)
const content = await fs.readFile(destPath, 'utf8')
expect(content).toBe('Success')
}, 'httpDownload-retry-')
} finally {
await new Promise<void>(resolve => {
testServer.close(() => resolve())
})
}
})
it('should fail after all download retries exhausted', async () => {
let attemptCount = 0
const testServer = http.createServer((req, _res) => {
attemptCount++
req.socket.destroy()
})
await new Promise<void>(resolve => {
testServer.listen(0, () => resolve())
})
const address = testServer.address()
const testPort = address && typeof address === 'object' ? address.port : 0
try {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'fail.txt')
await expect(
httpDownload(`http://localhost:${testPort}/`, destPath, {
retries: 2,
retryDelay: 10,
}),
).rejects.toThrow(/HTTP download failed/)
expect(attemptCount).toBe(3)
}, 'httpDownload-fail-')
} finally {
await new Promise<void>(resolve => {
testServer.close(() => resolve())
})
}
})
it('should send custom headers in download', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'headers.txt')
// Use main test server - headers are already checked by echo-headers endpoint
await httpDownload(`${httpBaseUrl}/download`, destPath, {
headers: { 'X-Custom-Header': 'test-value' },
})
const content = await fs.readFile(destPath, 'utf8')
expect(content).toBe('Download test content')
}, 'httpDownload-headers-')
})
it('should handle file write errors', async () => {
await runWithTempDir(async tmpDir => {
// Try to write to an invalid path
const destPath = path.join(tmpDir, 'nonexistent', 'nested', 'file.txt')
await expect(
httpDownload(`${httpBaseUrl}/download`, destPath),
).rejects.toThrow(/Failed to write file/)
}, 'httpDownload-write-error-')
})
it('should handle response errors during download', async () => {
const testServer = http.createServer((_req, _res) => {
_res.writeHead(200, { 'Content-Length': '100' })
_res.write('partial')
// Simulate error during transmission
setTimeout(() => {
_res.destroy()
}, 10)
})
await new Promise<void>(resolve => {
testServer.listen(0, () => resolve())
})
const address = testServer.address()
const testPort = address && typeof address === 'object' ? address.port : 0
try {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'error.txt')
await expect(
httpDownload(`http://localhost:${testPort}/`, destPath),
).rejects.toThrow()
}, 'httpDownload-response-error-')
} finally {
await new Promise<void>(resolve => {
testServer.close(() => resolve())
})
}
})
it('should use default timeout of 120 seconds', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'default-timeout.txt')
// This should succeed quickly with default timeout
const result = await httpDownload(`${httpBaseUrl}/download`, destPath)
expect(result.size).toBeGreaterThan(0)
}, 'httpDownload-default-timeout-')
})
it('should log progress with logger option', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'logger.txt')
const logMessages: string[] = []
const stdout = new Writable({
write(chunk, _encoding, callback) {
logMessages.push(chunk.toString())
callback()
},
})
const logger = new Logger({ stdout })
await httpDownload(`${httpBaseUrl}/large-download`, destPath, {
logger,
progressInterval: 25, // Log every 25%
})
// Should have logged progress at 25%, 50%, 75%, 100%
expect(logMessages.length).toBeGreaterThan(0)
expect(logMessages.some(msg => msg.includes('Progress:'))).toBe(true)
expect(logMessages.some(msg => msg.includes('MB'))).toBe(true)
const content = await fs.readFile(destPath, 'utf8')
expect(content).toBe('X'.repeat(1000))
}, 'httpDownload-logger-')
})
it('should use default progressInterval of 10%', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'logger-default.txt')
const logMessages: string[] = []
const stdout = new Writable({
write(chunk, _encoding, callback) {
logMessages.push(chunk.toString())
callback()
},
})
const logger = new Logger({ stdout })
await httpDownload(`${httpBaseUrl}/large-download`, destPath, {
logger,
// No progressInterval specified - should default to 10%
})
expect(logMessages.length).toBeGreaterThan(0)
expect(logMessages.some(msg => msg.includes('Progress:'))).toBe(true)
}, 'httpDownload-logger-default-')
})
it('should prefer onProgress callback over logger', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'logger-precedence.txt')
const logMessages: string[] = []
let onProgressCalled = false
const stdout = new Writable({
write(chunk, _encoding, callback) {
logMessages.push(chunk.toString())
callback()
},
})
const logger = new Logger({ stdout })
await httpDownload(`${httpBaseUrl}/large-download`, destPath, {
logger,
onProgress: () => {
onProgressCalled = true
},
progressInterval: 25,
})
// onProgress should have been called
expect(onProgressCalled).toBe(true)
// Logger should NOT have been used
expect(logMessages.length).toBe(0)
}, 'httpDownload-logger-precedence-')
})
it('should format progress with MB units correctly', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'logger-format.txt')
const logMessages: string[] = []
const stdout = new Writable({
write(chunk, _encoding, callback) {
logMessages.push(chunk.toString())
callback()
},
})
const logger = new Logger({ stdout })
await httpDownload(`${httpBaseUrl}/large-download`, destPath, {
logger,
progressInterval: 50,
})
// Check format: " Progress: XX% (Y.Y MB / Z.Z MB)"
expect(logMessages.length).toBeGreaterThan(0)
const progressMsg = logMessages.find(msg => msg.includes('Progress:'))
expect(progressMsg).toBeDefined()
expect(progressMsg).toMatch(
/Progress: \d+% \(\d+\.\d+ MB \/ \d+\.\d+ MB\)/,
)
}, 'httpDownload-logger-format-')
})
it('should not log progress with logger when no content-length', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'logger-no-length.txt')
const logMessages: string[] = []
const stdout = new Writable({
write(chunk, _encoding, callback) {
logMessages.push(chunk.toString())
callback()
},
})
const logger = new Logger({ stdout })
await httpDownload(`${httpBaseUrl}/download-no-length`, destPath, {
logger,
})
// Should not have logged any progress (no content-length header)
expect(logMessages.length).toBe(0)
const content = await fs.readFile(destPath, 'utf8')
expect(content).toBe('No content length')
}, 'httpDownload-logger-no-length-')
})
it('should verify sha256 checksum when provided', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'checksum.txt')
const content = 'Test content for checksum verification'
const expectedHash = createHash('sha256').update(content).digest('hex')
const result = await httpDownload(
`${httpBaseUrl}/checksum-file`,
destPath,
{ sha256: expectedHash },
)
expect(result.path).toBe(destPath)
const downloadedContent = await fs.readFile(destPath, 'utf8')
expect(downloadedContent).toBe(content)
}, 'httpDownload-sha256-')
})
it('should fail when sha256 checksum does not match', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'checksum-fail.txt')
const wrongHash =
'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
await expect(
httpDownload(`${httpBaseUrl}/checksum-file`, destPath, {
sha256: wrongHash,
}),
).rejects.toThrow(/Checksum verification failed/)
// File should not exist after failed verification.
const exists = await fs
.access(destPath)
.then(() => true)
.catch(() => false)
expect(exists).toBe(false)
}, 'httpDownload-sha256-fail-')
})
it('should verify checksum using fetchChecksums', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'checksum-url.txt')
// Fetch checksums first, then use the hash.
const checksums = await fetchChecksums(`${httpBaseUrl}/checksums.txt`)
expect(checksums['checksum-file']).toBeDefined()
const result = await httpDownload(
`${httpBaseUrl}/checksum-file`,
destPath,
{ sha256: checksums['checksum-file'] },
)
expect(result.path).toBe(destPath)
const content = await fs.readFile(destPath, 'utf8')
expect(content).toBe('Test content for checksum verification')
}, 'httpDownload-checksums-url-')
})
it('should accept uppercase sha256 hash', async () => {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'checksum-upper.txt')
const content = 'Test content for checksum verification'
const expectedHash = createHash('sha256')
.update(content)
.digest('hex')
.toUpperCase()
const result = await httpDownload(
`${httpBaseUrl}/checksum-file`,
destPath,
{ sha256: expectedHash },
)
expect(result.path).toBe(destPath)
}, 'httpDownload-sha256-uppercase-')
})
it('should verify checksum after successful retry', async () => {
let attemptCount = 0
const content = 'Retry checksum content'
const expectedHash = createHash('sha256').update(content).digest('hex')
const testServer = http.createServer((req, res) => {
attemptCount++
if (attemptCount < 2) {
req.socket.destroy()
} else {
res.writeHead(200, { 'Content-Length': String(content.length) })
res.end(content)
}
})
await new Promise<void>(resolve => {
testServer.listen(0, () => resolve())
})
const address = testServer.address()
const testPort = address && typeof address === 'object' ? address.port : 0
try {
await runWithTempDir(async tmpDir => {
const destPath = path.join(tmpDir, 'retry-checksum.txt')
const result = await httpDownload(
`http://localhost:${testPort}/`,
destPath,
{
retries: 2,
retryDelay: 10,
sha256: expectedHash,
},
)
expect(result.size).toBe(content.length)
expect(attemptCount).toBe(2)
const downloaded = await fs.readFile(destPath, 'utf8')