11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ciconst common = require('../common');
31cb0ef41Sopenharmony_ciconst fixtures = require('../common/fixtures');
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ci// Adding a CA certificate to contextWithCert should not also add it to
61cb0ef41Sopenharmony_ci// contextWithoutCert. This is tested by trying to connect to a server that
71cb0ef41Sopenharmony_ci// depends on that CA using contextWithoutCert.
81cb0ef41Sopenharmony_ci
91cb0ef41Sopenharmony_ciconst {
101cb0ef41Sopenharmony_ci  assert, connect, keys, tls
111cb0ef41Sopenharmony_ci} = require(fixtures.path('tls-connect'));
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_ciconst contextWithoutCert = tls.createSecureContext({});
141cb0ef41Sopenharmony_ciconst contextWithCert = tls.createSecureContext({});
151cb0ef41Sopenharmony_cicontextWithCert.context.addCACert(keys.agent1.ca);
161cb0ef41Sopenharmony_ci
171cb0ef41Sopenharmony_ciconst serverOptions = {
181cb0ef41Sopenharmony_ci  key: keys.agent1.key,
191cb0ef41Sopenharmony_ci  cert: keys.agent1.cert,
201cb0ef41Sopenharmony_ci};
211cb0ef41Sopenharmony_ci
221cb0ef41Sopenharmony_ciconst clientOptions = {
231cb0ef41Sopenharmony_ci  ca: [keys.agent1.ca],
241cb0ef41Sopenharmony_ci  servername: 'agent1',
251cb0ef41Sopenharmony_ci  rejectUnauthorized: true,
261cb0ef41Sopenharmony_ci};
271cb0ef41Sopenharmony_ci
281cb0ef41Sopenharmony_ci// This client should fail to connect because it doesn't trust the CA
291cb0ef41Sopenharmony_ci// certificate.
301cb0ef41Sopenharmony_ciclientOptions.secureContext = contextWithoutCert;
311cb0ef41Sopenharmony_ci
321cb0ef41Sopenharmony_ciconnect({
331cb0ef41Sopenharmony_ci  client: clientOptions,
341cb0ef41Sopenharmony_ci  server: serverOptions,
351cb0ef41Sopenharmony_ci}, common.mustCall((err, pair, cleanup) => {
361cb0ef41Sopenharmony_ci  assert(err);
371cb0ef41Sopenharmony_ci  assert.strictEqual(err.message, 'unable to verify the first certificate');
381cb0ef41Sopenharmony_ci  cleanup();
391cb0ef41Sopenharmony_ci
401cb0ef41Sopenharmony_ci  // This time it should connect because contextWithCert includes the needed CA
411cb0ef41Sopenharmony_ci  // certificate.
421cb0ef41Sopenharmony_ci  clientOptions.secureContext = contextWithCert;
431cb0ef41Sopenharmony_ci  connect({
441cb0ef41Sopenharmony_ci    client: clientOptions,
451cb0ef41Sopenharmony_ci    server: serverOptions,
461cb0ef41Sopenharmony_ci  }, common.mustSucceed((pair, cleanup) => {
471cb0ef41Sopenharmony_ci    cleanup();
481cb0ef41Sopenharmony_ci  }));
491cb0ef41Sopenharmony_ci}));
50