Skip to content

Commit 161b003

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: #25170, #9386
1 parent 7196946 commit 161b003

File tree

2 files changed

+56
-2
lines changed

2 files changed

+56
-2
lines changed

lib/https.js

+15-2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ const {
3030
FunctionPrototypeCall,
3131
JSONStringify,
3232
ObjectAssign,
33+
ObjectDefineProperty,
3334
ObjectSetPrototypeOf,
3435
ReflectApply,
3536
ReflectConstruct,
@@ -350,7 +351,7 @@ Agent.prototype._evictSession = function _evictSession(key) {
350351
delete this._sessionCache.map[key];
351352
};
352353

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

355356
/**
356357
* Makes a request to a secure web server.
@@ -415,9 +416,21 @@ function get(input, options, cb) {
415416

416417
module.exports = {
417418
Agent,
418-
globalAgent,
419419
Server,
420420
createServer,
421421
get,
422422
request,
423423
};
424+
425+
// Make https.globalAgent overridable also under ECMAScript Modules
426+
ObjectDefineProperty(module.exports, 'globalAgent', {
427+
__proto__: null,
428+
configurable: true,
429+
enumerable: true,
430+
get() {
431+
return globalAgent;
432+
},
433+
set(value) {
434+
globalAgent = value;
435+
},
436+
});
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)