Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
26 changes: 8 additions & 18 deletions src/js/node/tls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ const { Server: NetServer, Socket: NetSocket } = net;
const { kArmHandshakeTimeout, kPreHandshakeWrite, kSecureConnectDone, kVerifyError } = require("internal/net/symbols");

const getBundledRootCertificates = $newCppFunction("NodeTLS.cpp", "getBundledRootCertificates", 1);
const loadExtraCACertificates = $newCppFunction("NodeTLS.cpp", "loadExtraCACertificates", 0);
const getExtraCACertificates = $newCppFunction("NodeTLS.cpp", "getExtraCACertificates", 1);
const getSystemCACertificates = $newCppFunction("NodeTLS.cpp", "getSystemCACertificates", 1);
const canonicalizeIP = $newCppFunction("NodeTLS.cpp", "Bun__canonicalizeIP", 1);
Expand Down Expand Up @@ -1747,30 +1748,19 @@ function cacheExtraCACertificates(): string[] {
return extraCACertificates;
}

let warnedAboutExtraCACerts = false;
let loadedExtraCACerts = false;
/**
* Match Node's crypto_context.cc: a NODE_EXTRA_CA_CERTS file that cannot be
* loaded is ignored with a one-time warning on stderr - emitted when the
* first secure context is created, not at startup - rather than failing the
* process. The reason text mirrors the strerror()-derived string Node prints.
* process. The native loader prints that warning, once per process, because
* fetch() and Bun.connect() reach it without this module. So run the load
* here instead of leaving it to the first handshake that verifies a peer.
Comment thread
robobun marked this conversation as resolved.
Resolved
*/
function maybeWarnAboutExtraCACerts() {
if (warnedAboutExtraCACerts) return;
warnedAboutExtraCACerts = true;
const extraPath = process.env.NODE_EXTRA_CA_CERTS;
if (!extraPath) return;
try {
require("node:fs").accessSync(extraPath);
} catch (err: any) {
// Node prints this with a raw fprintf(stderr, ...) from
// crypto_context.cc, not through process.emitWarning - no pid prefix and
// no colorization.
process.stderr.write(
`Warning: Ignoring extra certs from \`${extraPath}\`, load failed: ${
err?.code === "ENOENT" ? "No such file or directory" : err?.message
}\n`,
);
}
if (loadedExtraCACerts) return;
loadedExtraCACerts = true;
loadExtraCACertificates();
}

// Runtime override for the "default" CA certificate set, installed by
Expand Down
8 changes: 8 additions & 0 deletions src/jsc/bindings/NodeTLS.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,14 @@ JSC_DEFINE_HOST_FUNCTION(getBundledRootCertificates, (JSC::JSGlobalObject * glob
RELEASE_AND_RETURN(scope, JSValue::encode(JSC::objectConstructorFreeze(globalObject, rootCertificates)));
}

// Runs the once-per-process NODE_EXTRA_CA_CERTS load, which warns on stderr if it fails, without building the PEM
// list getExtraCACertificates returns.
Comment thread
robobun marked this conversation as resolved.
Resolved
JSC_DEFINE_HOST_FUNCTION(loadExtraCACertificates, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
us_get_root_extra_cert_instances();
return JSValue::encode(jsUndefined());
}

JSC_DEFINE_HOST_FUNCTION(getExtraCACertificates, (JSC::JSGlobalObject * globalObject, JSC::CallFrame* callFrame))
{
auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
Expand Down
1 change: 1 addition & 0 deletions src/jsc/bindings/NodeTLS.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ namespace Bun {

BUN_DECLARE_HOST_FUNCTION(Bun__canonicalizeIP);
JSC_DECLARE_HOST_FUNCTION(getBundledRootCertificates);
JSC_DECLARE_HOST_FUNCTION(loadExtraCACertificates);
JSC_DECLARE_HOST_FUNCTION(getExtraCACertificates);
JSC_DECLARE_HOST_FUNCTION(getSystemCACertificates);
JSC_DECLARE_HOST_FUNCTION(parseCACertificates);
Expand Down
9 changes: 7 additions & 2 deletions src/uws/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,9 @@ pub struct SocketAddress {

pub use bun_uws_sys::loop_::free_thread_loop;

/// The only `NODE_EXTRA_CA_CERTS` warning, worded as Node's crypto_context.cc words it. The load that reports here
/// runs once per process (`us_get_root_extra_cert_instances`), on whichever thread first needs the list.
///
Comment thread
robobun marked this conversation as resolved.
Resolved
/// # Safety
/// `filename` and `error_msg` must be valid NUL-terminated C strings.
#[unsafe(no_mangle)]
Expand All @@ -116,11 +119,13 @@ unsafe extern "C" fn BUN__warn__extra_ca_load_failed(
let filename = unsafe { bun_core::ffi::cstr(filename) };
// SAFETY: caller contract guarantees valid NUL-terminated strings.
let error_msg = unsafe { bun_core::ffi::cstr(error_msg) };
bun_core::warn!(
"ignoring extra certs from {}, load failed: {}",
bun_core::pretty_errorln!(
"Warning: Ignoring extra certs from `{}`, load failed: {}",
bstr::BStr::new(filename.to_bytes()),
bstr::BStr::new(error_msg.to_bytes()),
);
// Output buffers stderr per thread: the main thread can hold this line until exit, and a Worker can drop it.
bun_core::Output::flush();
}

pub use bun_uws_sys::LIBUS_SOCKET_DESCRIPTOR;
Expand Down
2 changes: 1 addition & 1 deletion test/js/node/tls/node-tls-cert.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -683,7 +683,7 @@ it("tls.connect should ignore NODE_EXTRA_CA_CERTS if it contains invalid cert",
);

for (const { stderr, exitCode } of results) {
expect(stderr).toContain("ignoring extra certs");
expect(stderr).toContain("Warning: Ignoring extra certs from");
expect(exitCode).toBe(1);
}
});
Expand Down
92 changes: 92 additions & 0 deletions test/js/node/tls/test-node-extra-ca-certs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,98 @@ aWRnaXRzIFB0eSBMdGQwHhcNMTgwNDEwMDgwNzQ4WhcNMjgwNDA3MDgwNzQ4WjBF
expect(exitCode).toBe(0);
expect(stdout.trim()).toBe("OK");
});

// One failed load is one warning, worded as Node words it, whichever API needs the extra CA list first.
describe("a file that cannot be loaded warns once", () => {
const missingWarning = "Warning: Ignoring extra certs from `missing.pem`, load failed: No such file or directory\n";

// Accepts one connection, drops it and closes, so a TLS client fails its handshake without leaving the process.
const deadEnd = `
function deadEnd(connect) {
const server = require("node:net").createServer(socket => {
socket.destroy();
server.close();
});
server.listen(0, "127.0.0.1", () => connect(server.address().port));
}
`;
const users = {
"tls.connect": `${deadEnd}
deadEnd(port => require("node:tls").connect(port, "127.0.0.1").on("error", () => {}));`,
"tls.createSecureContext": `require("node:tls").createSecureContext();`,
"tls.createServer": `require("node:tls").createServer({});`,
"tls.getCACertificates": `require("node:tls").getCACertificates("extra");`,
"fetch": `${deadEnd}
deadEnd(port => fetch("https://127.0.0.1:" + port).catch(() => {}));`,
"fetch, then node:tls": `${deadEnd}
deadEnd(async port => {
await fetch("https://127.0.0.1:" + port).catch(() => {});
require("node:tls").createSecureContext();
});`,
"Bun.connect": `${deadEnd}
deadEnd(port =>
Bun.connect({ hostname: "127.0.0.1", port, tls: true, socket: { data() {}, error() {}, connectError() {} } })
.catch(() => {}),
);`,
"node:tls on two threads": `
require("node:tls").createSecureContext();
new (require("node:worker_threads").Worker)('require("node:tls").createSecureContext()', { eval: true });`,
"node:tls in a Worker only": `
new (require("node:worker_threads").Worker)('require("node:tls").createSecureContext()', { eval: true });`,
};

// NODE_EXTRA_CA_CERTS is relative to `cwd`, so the warning names the same path on every platform.
function spawnWith(extraCACerts: string, cwd: string, code: string) {
return spawn({
cmd: [bunExe(), "-e", code],
env: { ...bunEnv, NODE_EXTRA_CA_CERTS: extraCACerts },
cwd,
stdout: "ignore",
stderr: "pipe",
});
}

async function run(extraCACerts: string, files: Record<string, string>, code: string) {
using dir = tempDir("extra-ca-warning", files);
await using proc = spawnWith(extraCACerts, String(dir), code);
const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]);
return { stderr, exitCode };
}

for (const [user, code] of Object.entries(users)) {
test.concurrent(user, async () => {
expect(await run("missing.pem", {}, code)).toEqual({ stderr: missingWarning, exitCode: 0 });
});
}

// Node warns for this file too. The reason is the TLS library's error string, which BoringSSL words differently.
test.concurrent("a certificate that does not parse", async () => {
const files = {
"malformed.pem": "-----BEGIN CERTIFICATE-----\nbm90IGEgY2VydGlmaWNhdGU=\n-----END CERTIFICATE-----\n",
};
expect(await run("malformed.pem", files, users["tls.createSecureContext"])).toEqual({
stderr: expect.stringMatching(
/^Warning: Ignoring extra certs from `malformed\.pem`, load failed: error:[^\n]+\n$/,
),
exitCode: 0,
});
});

test.concurrent("when the load fails, not when the process exits", async () => {
using dir = tempDir("extra-ca-warning", {});
// This process never exits by itself: the line has to arrive before the kill on dispose.
const code = `${users["Bun.connect"]} setInterval(() => {}, 1000);`;
await using proc = spawnWith("missing.pem", String(dir), code);
const decoder = new TextDecoder();
let stderr = "";
for await (const chunk of proc.stderr) {
stderr += decoder.decode(chunk, { stream: true });
if (stderr.includes("\n")) break;
}

expect(stderr).toBe(missingWarning);
});
});
});

test("explicit ca option replaces the default trust store instead of appending to it", async () => {
Expand Down
2 changes: 1 addition & 1 deletion test/js/web/fetch/fetch.tls.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1327,7 +1327,7 @@ describe.concurrent("fetch-tls", () => {
expect(await proc.exited).toBe(1);
const stderr = await proc.stderr.text();
expect(stderr).toContain("DEPTH_ZERO_SELF_SIGNED_CERT");
expect(stderr).toContain("ignoring extra certs");
expect(stderr).toContain("Warning: Ignoring extra certs from");
}
});
});
Loading