Skip to content

crypto: add tls.useSystemCA() #58822

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions doc/api/tls.md
Original file line number Diff line number Diff line change
Expand Up @@ -2260,6 +2260,25 @@ openssl pkcs12 -certpbe AES-256-CBC -export -out client-cert.pem \
The server can be tested by connecting to it using the example client from
[`tls.connect()`][].

## `tls.useSystemCA()`

<!-- YAML
added: REPLACEME
-->

Enables system CA certificates to be used by the Node.js TLS clients by default.
This is equivalent to enabling the [`--use-system-ca`][] flag, but can be done
programmatically at runtime.

Once called, the system CA certificates will be included in the default CA
certificate list returned by [`tls.getCACertificates()`][] and used by TLS
connections that don't specify their own CA certificates.

Subsequent calls to this function are no-ops. The system CA certificates are
loaded and cached on the first call.

This function only affects the current Node.js thread.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I'd much prefer this to be set as an option on an individual connection rather than programmatically impacting all connections. A cli flag is one thing because it's set by the individual running the app. This API could be set by dependencies impacting global state without the application being aware of it. Setting it per connection seems the safest.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, I'm not sure introducing more mutable global state here is worthwhile I'm afraid.

I'd much prefer this to be set as an option on an individual connection rather than programmatically impacting all connections.

I think that's already possible with the other recent improvements around this:

{
  ca: tls.getCACertificates('system')
}

AFAICT, adding that to TLS options anywhere should be equivalent to this change, but scoped to the single context.

I think with the current global CLI flag plus easy per-connection configuration, that should cover most use cases.

Copy link
Member Author

@joyeecheung joyeecheung Jun 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As explained, the per-connection option already exists.

This API serves a different use case, where another party (e.g. corporate infra packages) would need to allow system certificates to be enabled when they are only to be loaded by application developers (who can start tls connections themselves, or use a third-party library that does it) and have no control over the command line.

This API could be set by dependencies impacting global state without the application being aware of it.

This is already possible by monkey patching tls or the global HTTPS agent - for example, see https://www.npmjs.com/package/syswide-cas. If both the ca option and NODE_EXTRA_CA_CERTS exist but a package like this still gets 14K+ weekly downloads, that means the existing API surfaces are not enough to cover them. I am fairly certain there are applications/packages that would just go a nuclear route and use rejectUnauthorized: false in the monkey-patched option bag when the woes they are having can't be fixed with existing options, considering how often it shows up on the Internet and on even public GitHub. Providing an option to allow using system certificates dynamically is at least a lot safer than what people are already doing, since the system certificates tend to be managed in a much more secure fashion. I can put that into the PR description, if it's not clear.

Copy link
Member Author

@joyeecheung joyeecheung Jun 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually there are more packages monkey patching tls/https agent to do this..(sigh):

https://www.npmjs.com/package/win-ca
https://www.npmjs.com/package/ssl-root-cas

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I won't block but I'm still unconvinced this is a good thing to add.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This API serves a different use case

@joyeecheung That corporate infra use case makes sense. I don't think the library argument is that strong (they all predate the other new improvements you'd made here to cover this, and could easily be a symptom of lack of awareness of new APIs and/or inertia) but it makes sense to include this (runtime global CA configuration) if somebody concrete is asking for it despite the other new APIs.

This API feels like a strange state change though: it's a one-way toggle, that can easily be switched invisibly & unexpectedly in dependencies, which only supports one type of runtime change, and which doesn't act like any other APIs we have (AFAIK). It's not normal global mutable state - it's a runtime-activated CLI flag.

What do you think about an alternative more along the lines of http.globalAgent? A writable property to globally control the TLS defaults.

The easiest direct solution in that vein would be to make tls.rootCertificates directly configurable. I think ESM means it's awkward to make that writable directly, but an API like tls.setDefaultCACertificates(tls.getCACertificates('system')) would be workable. That seems more idiomatic & well-behaved to me, achieves the same result, and is more flexible to allow for globally configuring CAs in other ways too (e.g. adding a single extra CA at runtime - which likely has plenty of overlap in corporate use cases). Is there a reason that's not possible?

We could even do that more generally for all TLS defaults... A tls.setDefaultOptions() method to configure a default used by all secure contexts has other interesting use cases (globally set minimum TLS version, OpenSSL options, TLS timeouts, etc) and would cover this neatly too. Or we could stick with just root certs separately if that's too bold/complicated for now.

Copy link
Member Author

@joyeecheung joyeecheung Jun 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The easiest direct solution in that vein would be to make tls.rootCertificates directly configurable. I think ESM means it's awkward to make that writable directly, but an API like tls.setDefaultCACertificates(tls.getCACertificates('system'))

That is a good idea, I think I'll need to look into it a bit further to confirm this is implementable & safe in async operations, but it sounds better than the current API to me.

Copy link
Member Author

@joyeecheung joyeecheung Jun 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or we could stick with just root certs separately if that's too bold/complicated for now.

Personally I'd be more comfortable to just stick to root certs considering the option bags are cherry-picked and copied into various instances, with everything being monkey-patchable and visible to user land, so it seems tricky to ensure consistency. The root cert store lives completely in C++ land so is safer from user tampering.


## `tls.getCACertificates([type])`

<!-- YAML
Expand Down
19 changes: 18 additions & 1 deletion lib/tls.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const {
getBundledRootCertificates,
getExtraCACertificates,
getSystemCACertificates,
useSystemCA: useSystemCABinding,
getSSLCiphers,
} = internalBinding('crypto');
const { Buffer } = require('buffer');
Expand Down Expand Up @@ -122,6 +123,21 @@ function cacheSystemCACertificates() {
}

let defaultCACertificates;
let enabledSystemCACertificates = false;
function useSystemCA() {
if (enabledSystemCACertificates) {
// Already enabled. It's a no-op.
return;
}

useSystemCABinding();
enabledSystemCACertificates = true;
// Invalidate the cached values so that they will be
// recalculated the next time tls.getCACertificates() is called.
systemCACertificates = undefined;
defaultCACertificates = undefined;
}

function cacheDefaultCACertificates() {
if (defaultCACertificates) { return defaultCACertificates; }
defaultCACertificates = [];
Expand All @@ -131,7 +147,7 @@ function cacheDefaultCACertificates() {
for (let i = 0; i < bundled.length; ++i) {
ArrayPrototypePush(defaultCACertificates, bundled[i]);
}
if (getOptionValue('--use-system-ca')) {
if (getOptionValue('--use-system-ca') || enabledSystemCACertificates) {
const system = cacheSystemCACertificates();
for (let i = 0; i < system.length; ++i) {

Expand Down Expand Up @@ -170,6 +186,7 @@ function getCACertificates(type = 'default') {
}
}
exports.getCACertificates = getCACertificates;
exports.useSystemCA = useSystemCA;

// Convert protocols array into valid OpenSSL protocols list
// ("\x06spdy/2\x08http/1.1\x08http/1.0")
Expand Down
28 changes: 23 additions & 5 deletions src/crypto/crypto_context.cc
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,15 @@ static std::string extra_root_certs_file; // NOLINT(runtime/string)
static std::atomic<bool> has_cached_bundled_root_certs{false};
static std::atomic<bool> has_cached_system_root_certs{false};
static std::atomic<bool> has_cached_extra_root_certs{false};

// Per-thread root cert store.
static thread_local X509_STORE* root_cert_store = nullptr;
static bool use_system_ca_in_root_cert_store = false;
X509_STORE* GetOrCreateRootCertStore() {
// Guaranteed thread-safe by standard, just don't use -fno-threadsafe-statics.
static X509_STORE* store = NewRootCertStore();
return store;
if (root_cert_store != nullptr) {
return root_cert_store;
}
root_cert_store = NewRootCertStore();
return root_cert_store;
}

// Takes a string or buffer and loads it into a BIO.
Expand Down Expand Up @@ -851,7 +855,8 @@ X509_STORE* NewRootCertStore() {
for (X509* cert : GetBundledRootCertificates()) {
CHECK_EQ(1, X509_STORE_add_cert(store, cert));
}
if (per_process::cli_options->use_system_ca) {
if (per_process::cli_options->use_system_ca ||
use_system_ca_in_root_cert_store) {
for (X509* cert : GetSystemStoreCACertificates()) {
CHECK_EQ(1, X509_STORE_add_cert(store, cert));
}
Expand Down Expand Up @@ -935,6 +940,17 @@ MaybeLocal<Array> X509sToArrayOfStrings(Environment* env,
return scope.Escape(Array::New(env->isolate(), result.data(), result.size()));
}

void UseSystemCA(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
use_system_ca_in_root_cert_store = true;
X509_STORE* store = GetOrCreateRootCertStore();
for (X509* cert : GetSystemStoreCACertificates()) {
if (!X509_STORE_add_cert(store, cert)) {
return ThrowCryptoError(env, ERR_get_error(), "X509_STORE_add_cert");
}
}
}

void GetSystemCACertificates(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Local<Array> results;
Expand Down Expand Up @@ -1046,6 +1062,7 @@ void SecureContext::Initialize(Environment* env, Local<Object> target) {
context, target, "getSystemCACertificates", GetSystemCACertificates);
SetMethodNoSideEffect(
context, target, "getExtraCACertificates", GetExtraCACertificates);
SetMethodNoSideEffect(context, target, "useSystemCA", UseSystemCA);
}

void SecureContext::RegisterExternalReferences(
Expand Down Expand Up @@ -1088,6 +1105,7 @@ void SecureContext::RegisterExternalReferences(
registry->Register(GetBundledRootCertificates);
registry->Register(GetSystemCACertificates);
registry->Register(GetExtraCACertificates);
registry->Register(UseSystemCA);
}

SecureContext* SecureContext::Create(Environment* env) {
Expand Down
39 changes: 39 additions & 0 deletions test/parallel/test-tls-use-system-ca-certificates-with-flag.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';
// Flags: --use-system-ca

// This tests that tls.useSystemCA() is a no-op when
// --use-system-ca flag is already set.

const common = require('../common');
if (!common.hasCrypto) common.skip('missing crypto');

const assert = require('assert');
const tls = require('tls');

// Get initial state when --use-system-ca is already set
const initialDefaultCerts = tls.getCACertificates('default');
const systemCerts = tls.getCACertificates('system');

assert(Array.isArray(systemCerts));

// With --use-system-ca, default should already include system certs
const initialSystemSet = new Set(systemCerts);
const initialDefaultSet = new Set(initialDefaultCerts);
assert.deepStrictEqual(initialDefaultSet.intersection(initialSystemSet), initialSystemSet);

// Enable system CA certificates (should be a no-op)
tls.useSystemCA();

// Get certificates after calling useSystemCA
const newDefaultCerts = tls.getCACertificates('default');
const newSystemCerts = tls.getCACertificates('system');

// Everything should have the same content.
assert.deepStrictEqual(initialDefaultCerts, newDefaultCerts);
assert.deepStrictEqual(systemCerts, newSystemCerts);

// Multiple calls should still be no-ops
tls.useSystemCA();
tls.useSystemCA();
const stillSameDefaultCerts = tls.getCACertificates('default');
assert.deepStrictEqual(newDefaultCerts, stillSameDefaultCerts);
54 changes: 54 additions & 0 deletions test/parallel/test-tls-use-system-ca-certificates.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
'use strict';

// Flags: --no-use-system-ca
// This tests that tls.useSystemCA() works correctly.

const common = require('../common');
if (!common.hasCrypto) common.skip('missing crypto');

const assert = require('assert');
const tls = require('tls');

// Get initial state
const initialDefaultCerts = tls.getCACertificates('default');
const systemCerts = tls.getCACertificates('system');

assert(Array.isArray(systemCerts));

// Check that system certs are not included by default (without --use-system-ca)
const initialSystemSet = new Set(systemCerts);
const initialDefaultSet = new Set(initialDefaultCerts);
const initialIntersection = initialDefaultSet.intersection(initialSystemSet);

// The initial default should not contain all system certs
// if there are system certs installed.
if (systemCerts.length > 0) {
assert(initialIntersection.size < systemCerts.length);
}

// Enable system CA certificates.
tls.useSystemCA();

// Get certificates after enabling system CAs
const newDefaultCerts = tls.getCACertificates('default');
const newSystemCerts = tls.getCACertificates('system');

// System certificates should have the same content
assert.deepStrictEqual(systemCerts, newSystemCerts);

// Default certificates behavior depends on whether system certs exist
if (systemCerts.length > 0) {
// The new default should be old default plus system certs
const newDefaultSet = new Set(newDefaultCerts);
const newSystemSet = new Set(systemCerts);
assert.deepStrictEqual(newDefaultSet.intersection(initialDefaultSet), initialDefaultSet);
assert.deepStrictEqual(newDefaultSet.intersection(newSystemSet), newSystemSet);
} else {
// If no system certs, default certs should remain the same
assert.deepStrictEqual(initialDefaultCerts, newDefaultCerts);
}

// Calling useSystemCA again should be a no-op
tls.useSystemCA();
const sameDefaultCerts = tls.getCACertificates('default');
assert.deepStrictEqual(newDefaultCerts, sameDefaultCerts);
64 changes: 64 additions & 0 deletions test/system-ca/test-use-system-ca-certificates.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
'use strict';

// Flags: --no-use-system-ca

// This tests that tls.useSystemCA() works correctly
// when the certificates from the README are installed on the system.
// To run this test, install the certificates as described in README.md

const common = require('../common');
if (!common.hasCrypto) common.skip('missing crypto');

const assert = require('assert');
const tls = require('tls');
const { assertIsCAArray } = require('../common/tls');
const fixtures = require('../common/fixtures');

// Read the expected certificates that should be installed
const startcomRootCert = fixtures.readKey('fake-startcom-root-cert.pem', 'utf8');

// Get initial state.
const initialDefaultCerts = tls.getCACertificates('default');
const systemCerts = tls.getCACertificates('system');

// System certs should be a valid CA array and should contain our test certificates
assertIsCAArray(systemCerts);
assert(systemCerts.length > 0, 'System certificates should be available when test certs are installed');

assert(systemCerts.includes(startcomRootCert));
assert(!initialDefaultCerts.includes(startcomRootCert));

// Check that system certs are not included by default (without --use-system-ca)
const initialSystemSet = new Set(systemCerts);
const initialDefaultSet = new Set(initialDefaultCerts);
const initialIntersection = initialDefaultSet.intersection(initialSystemSet);

// The initial default should not contain all system certs
assert(initialIntersection.size < systemCerts.length, 'Default certs should not include all system certs initially');

// Enable system CA certificates
tls.useSystemCA();

// Get certificates after enabling system CAs
const newDefaultCerts = tls.getCACertificates('default');
const newSystemCerts = tls.getCACertificates('system');

// System certificates should have the same content
assert.deepStrictEqual(systemCerts, newSystemCerts);

// Default certificates should now include the system certificates
assert.notStrictEqual(initialDefaultCerts, newDefaultCerts, 'Default certs should change after enabling system CAs');

// The new default should be a superset of system certificates
assert(newDefaultCerts.length >= systemCerts.length, 'New default should include all system certs');
const newDefaultSet = new Set(newDefaultCerts);
const newSystemSet = new Set(systemCerts);
assert.deepStrictEqual(newDefaultSet.intersection(newSystemSet), newSystemSet);

// Verify that our test certificates are now in the default certs
assert(newDefaultCerts.includes(startcomRootCert));

// Calling useSystemCA again should be a no-op
tls.useSystemCA();
const sameDefaultCerts = tls.getCACertificates('default');
assert.deepStrictEqual(newDefaultCerts, sameDefaultCerts);
74 changes: 74 additions & 0 deletions test/system-ca/test-use-system-ca-dynamic.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Flags: --no-use-system-ca

// This tests that tls.useSystemCA() dynamically enables
// system certificates, allowing connections that would otherwise fail.
// To run this test, install the certificates as described in README.md

import * as common from '../common/index.mjs';
import assert from 'node:assert/strict';
import https from 'node:https';
import tls from 'node:tls';
import fixtures from '../common/fixtures.js';
import { it, beforeEach, afterEach, describe } from 'node:test';
import { once } from 'events';

if (!common.hasCrypto) {
common.skip('requires crypto');
}

const handleRequest = (req, res) => {
const path = req.url;
switch (path) {
case '/hello-world':
res.writeHead(200);
res.end('hello world\n');
break;
default:
assert(false, `Unexpected path: ${path}`);
}
};

describe('enable-system-ca-dynamic', function() {
async function setupServer(key, cert) {
const theServer = https.createServer({
key: fixtures.readKey(key),
cert: fixtures.readKey(cert),
}, handleRequest);
theServer.listen(0);
await once(theServer, 'listening');

return theServer;
}

let server;

beforeEach(async function() {
server = await setupServer('agent8-key.pem', 'agent8-cert.pem');
});

it('fails before enabling system CA, succeeds after', async function() {
const url = `https://localhost:${server.address().port}/hello-world`;

// First attempt should fail without system certificates.
await assert.rejects(
fetch(url),
(err) => {
assert.strictEqual(err.cause.code, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE');
return true;
},
);

// Now enable system CA certificates
tls.useSystemCA();

// Second attempt should succeed.
const response = await fetch(url);
assert.strictEqual(response.status, 200);
const text = await response.text();
assert.strictEqual(text, 'hello world\n');
});

afterEach(async function() {
server?.close();
});
});
Loading