Skip to content

http: support HTTP[S]_PROXY environment variables in fetch #57165

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -3545,6 +3545,21 @@ If `value` equals `'0'`, certificate validation is disabled for TLS connections.
This makes TLS, and HTTPS by extension, insecure. The use of this environment
variable is strongly discouraged.

### `NODE_USE_ENV_PROXY=1`

<!-- YAML
added: REPLACEME
-->

> Stability: 1.1 - Active Development
When enabled, Node.js parses the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY`
environment variables during startup, and tunnels requests over the
specified proxy.

This currently only affects requests sent over `fetch()`. Support for other
built-in `http` and `https` methods is under way.

### `NODE_V8_COVERAGE=dir`

When set, Node.js will begin outputting [V8 JavaScript code coverage][] and
Expand Down
16 changes: 16 additions & 0 deletions lib/internal/process/pre_execution.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ function prepareExecution(options) {
initializeConfigFileSupport();

require('internal/dns/utils').initializeDns();
setupHttpProxy();

if (isMainThread) {
assert(internalBinding('worker').isMainThread);
Expand Down Expand Up @@ -154,6 +155,21 @@ function prepareExecution(options) {
return mainEntry;
}

function setupHttpProxy() {
if (process.env.NODE_USE_ENV_PROXY &&
(process.env.HTTP_PROXY || process.env.HTTPS_PROXY ||
process.env.http_proxy || process.env.https_proxy)) {
const { setGlobalDispatcher, EnvHttpProxyAgent } = require('internal/deps/undici/undici');
const envHttpProxyAgent = new EnvHttpProxyAgent();
setGlobalDispatcher(envHttpProxyAgent);
// TODO(joyeecheung): This currently only affects fetch. Implement handling in the
// http/https Agent constructor too.
// TODO(joyeecheung): This is currently guarded with NODE_USE_ENV_PROXY. Investigate whether
// it's possible to enable it by default without stepping on other existing libraries that
// sets the global dispatcher or monkey patches the global agent.
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of curiosity... What does the error look like if the proxy is misconfigured? That is, if I set HTTP_PROXY to an invalid value and the dispatcher is not able to actually make the connection? It would be helpful to ensure that the error gives enough indication for the user to know that the issue is the proxy config.

Copy link
Member Author

@joyeecheung joyeecheung Mar 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It depends on how invalid the value is - typically this just times out, just like what happens if you send the request to an invalid server. Or if the domain name is invalid then you get a DNS error, etc. I am not sure if it makes sense to pre-emptively check for anything, however. Sending requests to an invalid proxy server is not too different from sending requests without proxy to an invalid server, in essence. As far as I know, other command line tools that support these environment variables would not really check the validity of the proxy - if the checking process is not part of the typical protocol (in the case of HTTP proxies, I don't think there is one), then performing a separate check can also lead to a TOCTOU problem. The proxy server being invalid during process startup does not mean that it won't be valid when the application actually makes the request.

}

function setupUserModules(forceDefaultLoader = false) {
initializeCJSLoader();
initializeESMLoader(forceDefaultLoader);
Expand Down
100 changes: 100 additions & 0 deletions test/common/proxy-server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
'use strict';

const net = require('net');
const http = require('http');
const assert = require('assert');

function logRequest(logs, req) {
logs.push({
method: req.method,
url: req.url,
headers: { ...req.headers },
});
}

// This creates a minimal proxy server that logs the requests it gets
// to an array before performing proxying.
exports.createProxyServer = function() {
const logs = [];

const proxy = http.createServer();
proxy.on('request', (req, res) => {
logRequest(logs, req);
const [hostname, port] = req.headers.host.split(':');
const targetPort = port || 80;

const options = {
hostname: hostname,
port: targetPort,
path: req.url,
method: req.method,
headers: req.headers,
};

const proxyReq = http.request(options, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res, { end: true });
});

proxyReq.on('error', (err) => {
logs.push({ error: err, source: 'proxy request' });
res.writeHead(500);
res.end('Proxy error: ' + err.message);
});

req.pipe(proxyReq, { end: true });
});

proxy.on('connect', (req, res, head) => {
logRequest(logs, req);

const [hostname, port] = req.url.split(':');
const proxyReq = net.connect(port, hostname, () => {
res.write(
'HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n',
);
proxyReq.write(head);
res.pipe(proxyReq);
proxyReq.pipe(res);
});

proxyReq.on('error', (err) => {
logs.push({ error: err, source: 'proxy request' });
res.write('HTTP/1.1 500 Connection Error\r\n\r\n');
res.end('Proxy error: ' + err.message);
});
});

proxy.on('error', (err) => {
logs.push({ error: err, source: 'proxy server' });
});

return { proxy, logs };
};

exports.checkProxiedRequest = async function(envExtension, expectation) {
const { spawnPromisified } = require('./');
const fixtures = require('./fixtures');
const { code, signal, stdout, stderr } = await spawnPromisified(
process.execPath,
[fixtures.path('fetch-and-log.mjs')], {
env: {
...process.env,
...envExtension,
},
});

assert.deepStrictEqual({
stderr: stderr.trim(),
stdout: stdout.trim(),
code,
signal,
}, {
stderr: '',
code: 0,
signal: null,
...expectation,
});
};
3 changes: 3 additions & 0 deletions test/fixtures/fetch-and-log.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const response = await fetch(process.env.FETCH_URL);
const body = await response.text();
console.log(body);
61 changes: 61 additions & 0 deletions test/parallel/test-http-proxy-fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
'use strict';

const common = require('../common');
const assert = require('assert');
const { once } = require('events');
const http = require('http');
const { createProxyServer, checkProxiedRequest } = require('../common/proxy-server');

(async () => {
// Start a server to process the final request.
const server = http.createServer(common.mustCall((req, res) => {
res.end('Hello world');
}, 2));
server.on('error', common.mustNotCall((err) => { console.error('Server error', err); }));
server.listen(0);
await once(server, 'listening');

// Start a minimal proxy server.
const { proxy, logs } = createProxyServer();
proxy.listen(0);
await once(proxy, 'listening');

const serverHost = `localhost:${server.address().port}`;

// FIXME(undici:4083): undici currently always tunnels the request over
// CONNECT, no matter it's HTTP traffic or not, which is different from e.g.
// how curl behaves.
const expectedLogs = [{
method: 'CONNECT',
url: serverHost,
headers: {
// FIXME(undici:4086): this should be keep-alive.
connection: 'close',
host: serverHost
}
}];

// Check upper-cased HTTPS_PROXY environment variable.
await checkProxiedRequest({
NODE_USE_ENV_PROXY: 1,
FETCH_URL: `http://${serverHost}/test`,
HTTP_PROXY: `http://localhost:${proxy.address().port}`,
}, {
stdout: 'Hello world',
});
assert.deepStrictEqual(logs, expectedLogs);

// Check lower-cased https_proxy environment variable.
logs.splice(0, logs.length);
await checkProxiedRequest({
NODE_USE_ENV_PROXY: 1,
FETCH_URL: `http://${serverHost}/test`,
http_proxy: `http://localhost:${proxy.address().port}`,
}, {
stdout: 'Hello world',
});
assert.deepStrictEqual(logs, expectedLogs);

proxy.close();
server.close();
})().then(common.mustCall());
67 changes: 67 additions & 0 deletions test/parallel/test-https-proxy-fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
'use strict';

const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');

const fixtures = require('../common/fixtures');
const assert = require('assert');
const https = require('https');
const { once } = require('events');
const { createProxyServer, checkProxiedRequest } = require('../common/proxy-server');

(async () => {
// Start a server to process the final request.
const server = https.createServer({
cert: fixtures.readKey('agent8-cert.pem'),
key: fixtures.readKey('agent8-key.pem'),
}, common.mustCall((req, res) => {
res.end('Hello world');
}, 2));
server.on('error', common.mustNotCall((err) => { console.error('Server error', err); }));
server.listen(0);
await once(server, 'listening');

// Start a minimal proxy server.
const { proxy, logs } = createProxyServer();
proxy.listen(0);
await once(proxy, 'listening');

const serverHost = `localhost:${server.address().port}`;

const expectedLogs = [{
method: 'CONNECT',
url: serverHost,
headers: {
// FIXME(undici:4086): this should be keep-alive.
connection: 'close',
host: serverHost
}
}];

// Check upper-cased HTTPS_PROXY environment variable.
await checkProxiedRequest({
NODE_USE_ENV_PROXY: 1,
FETCH_URL: `https://${serverHost}/test`,
HTTPS_PROXY: `http://localhost:${proxy.address().port}`,
NODE_EXTRA_CA_CERTS: fixtures.path('keys', 'fake-startcom-root-cert.pem'),
}, {
stdout: 'Hello world',
});
assert.deepStrictEqual(logs, expectedLogs);

// Check lower-cased https_proxy environment variable.
logs.splice(0, logs.length);
await checkProxiedRequest({
NODE_USE_ENV_PROXY: 1,
FETCH_URL: `https://${serverHost}/test`,
https_proxy: `http://localhost:${proxy.address().port}`,
NODE_EXTRA_CA_CERTS: fixtures.path('keys', 'fake-startcom-root-cert.pem'),
}, {
stdout: 'Hello world',
});
assert.deepStrictEqual(logs, expectedLogs);

proxy.close();
server.close();
})().then(common.mustCall());
Loading