node/test/parallel/test-tls-set-default-ca-certificates-append-fetch.mjs
Joyee Cheung edd66d0130
crypto: add tls.setDefaultCACertificates()
This API allows dynamically configuring CA certificates that
will be used by the Node.js TLS clients by default.

Once called, the provided certificates will become the default CA
certificate list returned by `tls.getCACertificates('default')` and
used by TLS connections that don't specify their own CA certificates.

This function only affects the current Node.js thread.

PR-URL: https://github.com/nodejs/node/pull/58822
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Tim Perry <pimterry@gmail.com>
Reviewed-By: Ethan Arrowood <ethan@arrowood.dev>
2025-07-18 19:57:53 +00:00

54 lines
1.6 KiB
JavaScript

// Flags: --no-use-system-ca
// This tests appending certificates to existing defaults should work correctly
// with fetch.
import * as common from '../common/index.mjs';
import { once } from 'node:events';
import * as fixtures from '../common/fixtures.mjs';
import assert from 'node:assert';
if (!common.hasCrypto) common.skip('missing crypto');
const { includesCert } = await import('../common/tls.js');
const { default: https } = await import('node:https');
const { default: tls } = await import('node:tls');
const bundledCerts = tls.getCACertificates('bundled');
const fixtureCert = fixtures.readKey('fake-startcom-root-cert.pem');
if (includesCert(bundledCerts, fixtureCert)) {
common.skip('fake-startcom-root-cert is already in bundled certificates, skipping test');
}
// Test HTTPS connection fails with bundled CA, succeeds after adding custom CA
const server = https.createServer({
cert: fixtures.readKey('agent8-cert.pem'),
key: fixtures.readKey('agent8-key.pem'),
}, common.mustCall((req, res) => {
res.writeHead(200);
res.end('hello world');
}, 1));
server.listen(0);
await once(server, 'listening');
const url = `https://localhost:${server.address().port}/hello-world`;
// First attempt should fail without custom CA.
await assert.rejects(
fetch(url),
(err) => {
assert.strictEqual(err.cause.code, 'UNABLE_TO_VERIFY_LEAF_SIGNATURE');
return true;
},
);
// Now enable custom CA certificate.
tls.setDefaultCACertificates([fixtureCert]);
// Second attempt should succeed.
const response = await fetch(url);
assert.strictEqual(response.status, 200);
const text = await response.text();
assert.strictEqual(text, 'hello world');
server.close();