forked from nodejs/undici
/
integrity.js
74 lines (60 loc) · 1.89 KB
/
integrity.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
'use strict'
const { test } = require('tap')
const { createServer } = require('http')
const { createHash } = require('crypto')
const { gzipSync } = require('zlib')
const { fetch, setGlobalDispatcher, Agent } = require('../..')
setGlobalDispatcher(new Agent({
keepAliveTimeout: 1,
keepAliveMaxTimeout: 1
}))
test('request with correct integrity checksum', (t) => {
const body = 'Hello world!'
const hash = createHash('sha256').update(body).digest('hex')
const server = createServer((req, res) => {
res.end(body)
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const response = await fetch(`http://localhost:${server.address().port}`, {
integrity: `sha256-${hash}`
})
t.strictSame(body, await response.text())
t.end()
})
})
test('request with wrong integrity checksum', (t) => {
const body = 'Hello world!'
const hash = 'c0535e4be2b79ffd93291305436bf889314e4a3faec05ecffcbb7df31ad9e51b'
const server = createServer((req, res) => {
res.end(body)
})
t.teardown(server.close.bind(server))
server.listen(0, () => {
fetch(`http://localhost:${server.address().port}`, {
integrity: `sha256-${hash}`
}).then(response => {
t.fail('fetch did not fail')
}).catch((err) => {
t.equal(err.cause.message, 'integrity mismatch')
}).finally(() => {
t.end()
})
})
})
test('request with integrity checksum on encoded body', (t) => {
const body = 'Hello world!'
const hash = createHash('sha256').update(body).digest('hex')
const server = createServer((req, res) => {
res.setHeader('content-encoding', 'gzip')
res.end(gzipSync(body))
})
t.teardown(server.close.bind(server))
server.listen(0, async () => {
const response = await fetch(`http://localhost:${server.address().port}`, {
integrity: `sha256-${hash}`
})
t.strictSame(body, await response.text())
t.end()
})
})