|
| 1 | +'use strict' |
| 2 | + |
| 3 | +const { tspl } = require('@matteo.collina/tspl') |
| 4 | +const { test, after } = require('node:test') |
| 5 | +const { createServer } = require('node:http') |
| 6 | +const { once } = require('node:events') |
| 7 | +const { request } = require('..') |
| 8 | +const { ProxyConnectionError } = require('../lib/core/errors') |
| 9 | +const ProxyAgent = require('../lib/dispatcher/proxy-agent') |
| 10 | + |
| 11 | +// Regression test for https://github.com/nodejs/undici/issues/3897 |
| 12 | +// |
| 13 | +// When the proxy tears down the socket while the CONNECT tunnel is being |
| 14 | +// established, the inner client rejects with UND_ERR_SOCKET. client.js#onError |
| 15 | +// treats UND_ERR_SOCKET as a recoverable error on an established connection and |
| 16 | +// leaves the request queued, so connect() is retried forever - the proxy gets |
| 17 | +// hammered with CONNECT attempts and the request never settles. The fix surfaces |
| 18 | +// a tunnel-establishment socket failure as a non-recoverable ProxyConnectionError |
| 19 | +// so the request fails after a single attempt. |
| 20 | +test('a proxy that drops the CONNECT tunnel fails the request instead of looping', { timeout: 5000 }, async (t) => { |
| 21 | + t = tspl(t, { plan: 3 }) |
| 22 | + |
| 23 | + let connectAttempts = 0 |
| 24 | + const proxy = createServer() |
| 25 | + proxy.on('connect', (req, socket) => { |
| 26 | + connectAttempts++ |
| 27 | + // Tear the tunnel down before it is established, like a proxy that does not |
| 28 | + // implement CONNECT or rejects the upstream. |
| 29 | + socket.destroy() |
| 30 | + }) |
| 31 | + |
| 32 | + proxy.listen(0) |
| 33 | + await once(proxy, 'listening') |
| 34 | + |
| 35 | + const proxyUrl = `http://127.0.0.1:${proxy.address().port}` |
| 36 | + const proxyAgent = new ProxyAgent(proxyUrl) |
| 37 | + |
| 38 | + after(async () => { |
| 39 | + await proxyAgent.close() |
| 40 | + proxy.close() |
| 41 | + }) |
| 42 | + |
| 43 | + await t.rejects( |
| 44 | + request('http://localhost/', { dispatcher: proxyAgent }), |
| 45 | + (err) => { |
| 46 | + t.ok(err instanceof ProxyConnectionError) |
| 47 | + t.strictEqual(connectAttempts, 1) |
| 48 | + return true |
| 49 | + } |
| 50 | + ) |
| 51 | + |
| 52 | + await t.completed |
| 53 | +}) |
0 commit comments