Skip to content

Commit 54579fb

Browse files
committed
https: make https.globalAgent overridable also under ECMAScript Modules
Under ECMAScript modules when you do "import * as https from 'https'" you get a new object with properties copied from https module exports. So if this is a regular data property, you will just override a copy, but if this would be a accessor property, we can still access the actual https.globalAgent. Refs: nodejs#25170, nodejs#9386
1 parent 7196946 commit 54579fb

File tree

2 files changed

+55
-2
lines changed

2 files changed

+55
-2
lines changed

lib/https.js

+14-2
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,7 @@ Agent.prototype._evictSession = function _evictSession(key) {
350350
delete this._sessionCache.map[key];
351351
};
352352

353-
const globalAgent = new Agent({ keepAlive: true, scheduling: 'lifo', timeout: 5000 });
353+
let globalAgent = new Agent({ keepAlive: true, scheduling: 'lifo', timeout: 5000 });
354354

355355
/**
356356
* Makes a request to a secure web server.
@@ -415,9 +415,21 @@ function get(input, options, cb) {
415415

416416
module.exports = {
417417
Agent,
418-
globalAgent,
419418
Server,
420419
createServer,
421420
get,
422421
request,
423422
};
423+
424+
// make https.globalAgent overridable also under ECMAScript Modules
425+
ObjectDefineProperty(module.exports, 'globalAgent', {
426+
__proto__: null,
427+
configurable: true,
428+
enumerable: true,
429+
get() {
430+
return globalAgent;
431+
},
432+
set(value) {
433+
globalAgent = value;
434+
},
435+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { hasCrypto, skip, mustCall } from '../common';
2+
if (!hasCrypto) skip('missing crypto');
3+
import { readKey } from '../common/fixtures';
4+
import assert from 'assert';
5+
// to override https.globalAgent we need to use namespace import
6+
import * as https from 'https';
7+
8+
// Disable strict server certificate validation by the client
9+
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
10+
11+
const options = {
12+
key: readKey('agent1-key.pem'),
13+
cert: readKey('agent1-cert.pem'),
14+
};
15+
16+
const server = https.Server(
17+
options,
18+
mustCall((req, res) => {
19+
res.writeHead(200);
20+
res.end('Hello, World!');
21+
})
22+
);
23+
24+
server.listen(
25+
0,
26+
mustCall(() => {
27+
const agent = new https.Agent();
28+
const name = agent.getName({ port: server.address().port });
29+
https.globalAgent = agent;
30+
31+
makeRequest();
32+
assert(name in agent.sockets); // Agent has indeed been used
33+
})
34+
);
35+
36+
function makeRequest() {
37+
const req = https.get({
38+
port: server.address().port,
39+
});
40+
req.on('close', () => server.close());
41+
}

0 commit comments

Comments
 (0)