From a6bd22171e18889f9f9c28139cd975376e947d19 Mon Sep 17 00:00:00 2001 From: Ian McCurdy Date: Fri, 27 Sep 2024 11:27:36 -0400 Subject: [PATCH] Add optional ca fallback to tls.rootCertificates --- lib/protocol/tcp.js | 5 +++++ test/lib.tcp.js | 47 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/lib/protocol/tcp.js b/lib/protocol/tcp.js index 28c9d09..1a5c592 100644 --- a/lib/protocol/tcp.js +++ b/lib/protocol/tcp.js @@ -28,6 +28,11 @@ exports.connect = function connect(options, cb) { if (!('servername' in options)) { options.servername = options.host; } + if (!('sslUseDefaultTrustStore' in options) || (options.sslUseDefaultTrustStore === true)) { + if ('ca' in options) { + options.ca = [].concat(options.ca, tls.rootCertificates); + } + } } else { createSocket = exports.createSocket; } diff --git a/test/lib.tcp.js b/test/lib.tcp.js index c4ee682..c2a0ada 100644 --- a/test/lib.tcp.js +++ b/test/lib.tcp.js @@ -14,6 +14,7 @@ 'use strict'; var tcp = require('../lib/protocol/tcp'); +var tls = require('tls'); var createSocket = tcp.createSocket; var createSecureSocket = tcp.createSecureSocket; var socket = { @@ -66,5 +67,51 @@ describe('Lib', function () { tcp.connect({}, done).should.equal(socket); }); + it('should fallback to default trusted CAs', function (done) { + var testCase = 0; + tcp.createSecureSocket = function tlsConnect(options, cb) { + switch (testCase) { + case 0: + (options.ca === undefined).should.equal(true); + break; + case 1: + options.ca[0].should.equal("DummyCert"); + options.ca.length.should.equal(tls.rootCertificates.length + 1); + for(var i = 0; i < tls.rootCertificates.length; ++i) { + options.ca[i+1].should.equal(tls.rootCertificates[i]); + } + break; + case 2: + options.ca[0].should.equal("DummyCert"); + options.ca[1].should.equal("DummyCert2"); + options.ca.length.should.equal(tls.rootCertificates.length + 2); + for(var i = 0; i < tls.rootCertificates.length; ++i) { + options.ca[i+2].should.equal(tls.rootCertificates[i]); + } + break; + case 3: + options.ca.should.equal("DummyCert"); + break; + default: + break; + } + process.nextTick(cb); + return socket; + } + tcp.connect({useTLS: true}, () => { + ++testCase; // 1 + tcp.connect({ca: "DummyCert"}, () => { + ++testCase; // 2 + tcp.connect({ca: ["DummyCert", "DummyCert2"], sslUseDefaultTrustStore: true}, () => { + ++testCase; // 3 + tcp.connect({ca: "DummyCert", sslUseDefaultTrustStore: false}, () => { + tcp.createSecureSocket = createSecureSocket; + done(); + }).should.equal(socket); + }).should.equal(socket); + }).should.equal(socket); + }); + }); + }); });