|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const { test } = require('tap') |
| 4 | +const { createServer } = require('http') |
| 5 | +const { createHash } = require('crypto') |
| 6 | +const { gzipSync } = require('zlib') |
| 7 | +const { fetch, setGlobalDispatcher, Agent } = require('../..') |
| 8 | + |
| 9 | +setGlobalDispatcher(new Agent({ |
| 10 | + keepAliveTimeout: 1, |
| 11 | + keepAliveMaxTimeout: 1 |
| 12 | +})) |
| 13 | + |
| 14 | +test('request with correct integrity checksum', (t) => { |
| 15 | + const body = 'Hello world!' |
| 16 | + const hash = createHash('sha256').update(body).digest('hex') |
| 17 | + |
| 18 | + const server = createServer((req, res) => { |
| 19 | + res.end(body) |
| 20 | + }) |
| 21 | + |
| 22 | + t.teardown(server.close.bind(server)) |
| 23 | + |
| 24 | + server.listen(0, async () => { |
| 25 | + const response = await fetch(`http://localhost:${server.address().port}`, { |
| 26 | + integrity: `sha256-${hash}` |
| 27 | + }) |
| 28 | + t.strictSame(body, await response.text()) |
| 29 | + t.end() |
| 30 | + }) |
| 31 | +}) |
| 32 | + |
| 33 | +test('request with wrong integrity checksum', (t) => { |
| 34 | + const body = 'Hello world!' |
| 35 | + const hash = 'c0535e4be2b79ffd93291305436bf889314e4a3faec05ecffcbb7df31ad9e51b' |
| 36 | + |
| 37 | + const server = createServer((req, res) => { |
| 38 | + res.end(body) |
| 39 | + }) |
| 40 | + |
| 41 | + t.teardown(server.close.bind(server)) |
| 42 | + |
| 43 | + server.listen(0, () => { |
| 44 | + fetch(`http://localhost:${server.address().port}`, { |
| 45 | + integrity: `sha256-${hash}` |
| 46 | + }).then(response => { |
| 47 | + t.fail('fetch did not fail') |
| 48 | + }).catch((err) => { |
| 49 | + t.equal(err.cause.message, 'integrity mismatch') |
| 50 | + }).finally(() => { |
| 51 | + t.end() |
| 52 | + }) |
| 53 | + }) |
| 54 | +}) |
| 55 | + |
| 56 | +test('request with integrity checksum on encoded body', (t) => { |
| 57 | + const body = 'Hello world!' |
| 58 | + const hash = createHash('sha256').update(body).digest('hex') |
| 59 | + |
| 60 | + const server = createServer((req, res) => { |
| 61 | + res.setHeader('content-encoding', 'gzip') |
| 62 | + res.end(gzipSync(body)) |
| 63 | + }) |
| 64 | + |
| 65 | + t.teardown(server.close.bind(server)) |
| 66 | + |
| 67 | + server.listen(0, async () => { |
| 68 | + const response = await fetch(`http://localhost:${server.address().port}`, { |
| 69 | + integrity: `sha256-${hash}` |
| 70 | + }) |
| 71 | + t.strictSame(body, await response.text()) |
| 72 | + t.end() |
| 73 | + }) |
| 74 | +}) |
0 commit comments