Skip to content
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

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
12 changes: 12 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,17 @@ function prepareExecution(options) {
return mainEntry;
}

function setupHttpProxy() {
if (process.env.NODE_USE_ENV_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): handle http/https global agents and perhaps Agent constructor
// behaviors.
}
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
4 changes: 4 additions & 0 deletions test/fixtures/fetch-and-log.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const address = process.env.SERVER_ADDRESS;
const response = await fetch(address);
const body = await response.text();
console.log(body);
22 changes: 22 additions & 0 deletions test/fixtures/proxy-handler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const net = require('net');

exports.onConnect = function (req, clientSocket, head) {
const [hostname, port] = req.url.split(':');

const serverSocket = net.connect(port, hostname, () => {
clientSocket.write(
'HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n'
);
serverSocket.write(head);
clientSocket.pipe(serverSocket);
serverSocket.pipe(clientSocket);
});

serverSocket.on('error', (err) => {
console.error('Error on CONNECT tunnel:', err.message);
clientSocket.write('HTTP/1.1 500 Connection Error\r\n\r\n');
clientSocket.end();
});
};
64 changes: 64 additions & 0 deletions test/parallel/test-http-proxy-fetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use strict';

const common = require('../common');
const fixtures = require('../common/fixtures');
const assert = require('assert');
const { spawn } = require('child_process');
const http = require('http');
const { onConnect } = require('../fixtures/proxy-handler');

// Start a server to process the final request.
const server = http.createServer((req, res) => {
res.end('Hello world');
});
server.on('error', (err) => { console.log('Server error', err); });

server.listen(0, common.mustCall(() => {
// Start a proxy server to tunnel the request.
const proxy = http.createServer();
// If the request does not go through the proxy server, common.mustCall fails.
proxy.on('connect', common.mustCall((req, clientSocket, head) => {
console.log('Proxying CONNECT', req.url, req.headers);
assert.strictEqual(req.url, `localhost:${server.address().port}`);
onConnect(req, clientSocket, head);
}));
proxy.on('error', (err) => { console.log('Proxy error', err); });

proxy.listen(0, common.mustCall(() => {
const proxyAddress = `http://localhost:${proxy.address().port}`;
const serverAddress = `http://localhost:${server.address().port}`;
const child = spawn(process.execPath,
[fixtures.path('fetch-and-log.mjs')],
{
env: {
...process.env,
HTTP_PROXY: proxyAddress,
NODE_USE_ENV_PROXY: true,
SERVER_ADDRESS: serverAddress,
},
});

const stderr = [];
const stdout = [];
child.stderr.on('data', (chunk) => {
stderr.push(chunk);
});
child.stdout.on('data', (chunk) => {
stdout.push(chunk);
});

child.on('exit', common.mustCall(function(code, signal) {
proxy.close();
server.close();

console.log('--- stderr ---');
Copy link
Member

Choose a reason for hiding this comment

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

Nit: are the console.log statements part of the test or just diagnostic output? If the former, can you add a comment indicating so; and if the latter, are they strictly necessary? Can they be removed?

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.

They are just debugging outputs, I personally find logs like these helpful when a test involving servers start to fail - especially due to timeout - in the CI.

console.log(Buffer.concat(stderr).toString());
console.log('--- stdout ---');
const stdoutStr = Buffer.concat(stdout).toString();
console.log(stdoutStr);
assert.strictEqual(stdoutStr.trim(), 'Hello world');
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
}));
}));
}));