1'use strict';
2const common = require('../common');
3
4if (!common.hasCrypto)
5  common.skip('missing crypto');
6
7// This test verifies the behavior of the tls setSecureContext() method.
8// It also verifies that existing connections are not disrupted when the
9// secure context is changed.
10
11const assert = require('assert');
12const events = require('events');
13const https = require('https');
14const timers = require('timers/promises');
15const fixtures = require('../common/fixtures');
16const credentialOptions = [
17  {
18    key: fixtures.readKey('agent1-key.pem'),
19    cert: fixtures.readKey('agent1-cert.pem'),
20    ca: fixtures.readKey('ca1-cert.pem')
21  },
22  {
23    key: fixtures.readKey('agent2-key.pem'),
24    cert: fixtures.readKey('agent2-cert.pem'),
25    ca: fixtures.readKey('ca2-cert.pem')
26  },
27];
28let firstResponse;
29
30const server = https.createServer(credentialOptions[0], (req, res) => {
31  const id = +req.headers.id;
32
33  if (id === 1) {
34    firstResponse = res;
35    firstResponse.write('multi-');
36    return;
37  } else if (id === 4) {
38    firstResponse.write('success-');
39  }
40
41  res.end('success');
42});
43
44server.listen(0, common.mustCall(() => {
45  const { port } = server.address();
46  const firstRequest = makeRequest(port, 1);
47
48  (async function makeRemainingRequests() {
49    // Wait until the first request is guaranteed to have been handled.
50    while (!firstResponse) {
51      await timers.setImmediate();
52    }
53
54    assert.strictEqual(await makeRequest(port, 2), 'success');
55
56    server.setSecureContext(credentialOptions[1]);
57    firstResponse.write('request-');
58    const errorMessageRegex = common.hasOpenSSL3 ?
59      /^Error: self-signed certificate$/ :
60      /^Error: self signed certificate$/;
61    await assert.rejects(makeRequest(port, 3), errorMessageRegex);
62
63    server.setSecureContext(credentialOptions[0]);
64    assert.strictEqual(await makeRequest(port, 4), 'success');
65
66    server.setSecureContext(credentialOptions[1]);
67    firstResponse.end('fun!');
68    await assert.rejects(makeRequest(port, 5), errorMessageRegex);
69
70    assert.strictEqual(await firstRequest, 'multi-request-success-fun!');
71    server.close();
72  })().then(common.mustCall());
73}));
74
75async function makeRequest(port, id) {
76  const options = {
77    rejectUnauthorized: true,
78    ca: credentialOptions[0].ca,
79    servername: 'agent1',
80    headers: { id },
81    agent: new https.Agent()
82  };
83
84  const req = https.get(`https://localhost:${port}`, options);
85
86  let errored = false;
87  req.on('error', () => errored = true);
88  req.on('finish', () => assert.strictEqual(errored, false));
89
90  const [res] = await events.once(req, 'response');
91  res.setEncoding('utf8');
92  let response = '';
93  for await (const chunk of res) response += chunk;
94  return response;
95}
96