From 37f76b2f81064d0be0aa49acd3b16343ead58a01 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 27 Jul 2026 22:11:44 +0000 Subject: [PATCH 1/7] fetch(tls): surface ERR_OSSL_* for bad client cert/key instead of FailedToOpenSocket fetch(url, {tls: {cert, key, passphrase}}) collapsed every client certificate/key load failure (cert/key mismatch, wrong or missing passphrase for an encrypted key, non-PEM input) into a generic FailedToOpenSocket "Was there a typo in the url or port?" error. node:https in the same process already reports the real BoringSSL codes (ERR_OSSL_X509_KEY_VALUES_MISMATCH, ERR_OSSL_BAD_DECRYPT, ERR_OSSL_PEM_NO_START_LINE) via SecureContext. us_ssl_ctx_build_raw returns NULL with *err left at CREATE_BUN_SOCKET_ERROR_NONE for cert/key/passphrase failures; the real cause is only on the calling thread's BoringSSL error queue. The fetch-client SSL_CTX is built on the HTTP thread, and HTTPContext::init_with_opts mapped (None, err == none) to InitError::FailedToOpenSocket without reading the queue. Capture ERR_get_error() in init_with_opts (same thread as the failed SSL_CTX_* calls), carry the packed u32 across in a new InitError::ClientTLSSetup / http::Error::ClientTLSSetup variant, and format it on the JS thread in FetchTasklet::on_reject using the same ERR_OSSL__ composition SecureContext uses. The resulting error carries .code (ERR_OSSL_*), .message (ERR_error_string_n output) and .path (the request URL). --- src/http/HTTPContext.rs | 14 +++++++- src/http/HTTPThread.rs | 3 +- src/http/InitError.rs | 5 +++ src/http/error.rs | 6 ++++ src/install/PackageManager.rs | 2 +- src/runtime/crypto/boringssl_jsc.rs | 33 ++++++++++++++++++ src/runtime/webcore/fetch/FetchTasklet.rs | 20 +++++++++++ test/js/web/fetch/fetch.tls.test.ts | 42 +++++++++++++++++++++++ 8 files changed, 122 insertions(+), 3 deletions(-) diff --git a/src/http/HTTPContext.rs b/src/http/HTTPContext.rs index 6d2d912f02e5..7abaebed8703 100644 --- a/src/http/HTTPContext.rs +++ b/src/http/HTTPContext.rs @@ -494,7 +494,19 @@ impl HTTPContext { uws::create_bun_socket_error_t::none | uws::create_bun_socket_error_t::invalid_ciphers | uws::create_bun_socket_error_t::invalid_ecdh_curve => { - InitError::FailedToOpenSocket + // us_ssl_ctx_build_raw returns NULL with *err left at + // .none for client cert/key/passphrase failures; the + // real cause is only on this thread's BoringSSL error + // queue. Capture it here (same thread as the failed + // SSL_CTX_* calls) so the JS thread can surface + // ERR_OSSL_* instead of a generic FailedToOpenSocket. + let packed = bun_boringssl_sys::ERR_get_error(); + if packed != 0 { + bun_boringssl_sys::ERR_clear_error(); + InitError::ClientTLSSetup(packed) + } else { + InitError::FailedToOpenSocket + } } }); } diff --git a/src/http/HTTPThread.rs b/src/http/HTTPThread.rs index 6c090309ed1c..3155b78e0f7f 100644 --- a/src/http/HTTPThread.rs +++ b/src/http/HTTPThread.rs @@ -370,7 +370,7 @@ fn on_init_error_noop(err: InitError, opts: &InitOpts) -> ! { InitError::InvalidCRL => { Output::err("HTTPThread", "the provided CRL is invalid", ()); } - InitError::FailedToOpenSocket => { + InitError::FailedToOpenSocket | InitError::ClientTLSSetup(_) => { bun_core::err_generic!("failed to start HTTP client thread"); } } @@ -543,6 +543,7 @@ impl HttpThread { return Err(match err { InitError::InvalidCRL => crate::Error::InvalidCRL, + InitError::ClientTLSSetup(code) => crate::Error::ClientTLSSetup(code), InitError::FailedToOpenSocket | InitError::InvalidCA | InitError::InvalidCAFile diff --git a/src/http/InitError.rs b/src/http/InitError.rs index 2c6505a3b274..c81f4019e62d 100644 --- a/src/http/InitError.rs +++ b/src/http/InitError.rs @@ -10,4 +10,9 @@ pub enum InitError { InvalidCA, #[error("InvalidCRL")] InvalidCRL, + /// SSL_CTX construction failed while loading client cert/key material. + /// Carries the packed BoringSSL error (from `ERR_get_error()`), captured on + /// the thread that built the context so the JS thread can format it later. + #[error("ClientTLSSetup")] + ClientTLSSetup(u32), } diff --git a/src/http/error.rs b/src/http/error.rs index b7edb71da82a..13b075adeba0 100644 --- a/src/http/error.rs +++ b/src/http/error.rs @@ -93,6 +93,11 @@ pub enum Error { HTTP3ContentLengthMismatch, #[error("FailedToOpenSocket")] FailedToOpenSocket, + /// Loading the client TLS certificate/key into the SSL_CTX failed. Carries + /// the packed BoringSSL error code so the consumer can produce Node's + /// `ERR_OSSL_*` shape. + #[error("ClientTLSSetup")] + ClientTLSSetup(u32), #[error("InvalidCRL")] InvalidCRL, #[error("UnsupportedProxyProtocol")] @@ -306,6 +311,7 @@ impl Error { Self::HTTP3StreamReset => "HTTP3StreamReset", Self::HTTP3ContentLengthMismatch => "HTTP3ContentLengthMismatch", Self::FailedToOpenSocket => "FailedToOpenSocket", + Self::ClientTLSSetup(_) => "ClientTLSSetup", Self::InvalidCRL => "InvalidCRL", Self::UnsupportedProxyProtocol => "UnsupportedProxyProtocol", Self::Cert(e) => <&'static str>::from(e), diff --git a/src/install/PackageManager.rs b/src/install/PackageManager.rs index 402f2fb25326..98b51ffb30d9 100644 --- a/src/install/PackageManager.rs +++ b/src/install/PackageManager.rs @@ -1275,7 +1275,7 @@ fn http_thread_on_init_error(err: http::InitError, opts: &http::http_thread::Ini http::InitError::InvalidCRL => { Output::err("HTTPThread", "the CRL is invalid", ()); } - http::InitError::FailedToOpenSocket => { + http::InitError::FailedToOpenSocket | http::InitError::ClientTLSSetup(_) => { Output::err_generic("failed to start HTTP client thread", ()); } } diff --git a/src/runtime/crypto/boringssl_jsc.rs b/src/runtime/crypto/boringssl_jsc.rs index 034cd99b50f1..49d9c263451e 100644 --- a/src/runtime/crypto/boringssl_jsc.rs +++ b/src/runtime/crypto/boringssl_jsc.rs @@ -52,6 +52,39 @@ fn static_cstr<'a>(ptr: *const core::ffi::c_char) -> Option<&'a [u8]> { if bytes.is_empty() { None } else { Some(bytes) } } +/// Format a packed BoringSSL error into `(code, message)` strings without +/// touching JSC. `code` is Node's `ERR_OSSL__` (or `ERR_SSL_*` for +/// the SSL library); `message` is the raw `ERR_error_string_n` output. Both +/// lookups are pure table reads keyed on the `u32`, so the thread that calls +/// this need not be the thread that produced the error. +pub fn err_code_and_message(err_code: u32) -> (Vec, Vec) { + let mut outbuf = [0u8; 128 + 1]; + // SAFETY: outbuf is a valid writable buffer of outbuf.len() bytes. + unsafe { + boring::ERR_error_string_n( + err_code, + outbuf.as_mut_ptr().cast::(), + outbuf.len(), + ); + } + let message = bun_core::slice_to_nul(&outbuf[..]).to_vec(); + + let code = if let Some(reason) = static_cstr(boring::ERR_reason_error_string(err_code)) { + let lib = lib_short_name((err_code >> 24) & 0xff); + let prefix = if lib == "SSL_" { "" } else { "OSSL_" }; + let mut code = Vec::with_capacity(4 + prefix.len() + lib.len() + reason.len()); + code.extend_from_slice(b"ERR_"); + code.extend_from_slice(prefix.as_bytes()); + code.extend_from_slice(lib.as_bytes()); + code.extend_from_slice(reason); + code + } else { + Vec::new() + }; + + (code, message) +} + pub fn err_to_js(global: &JSGlobalObject, err_code: u32) -> JSValue { // The message is the raw ERR_error_string output // ("error:0b000074:X.509 certificate routines:OPENSSL_internal:..."), diff --git a/src/runtime/webcore/fetch/FetchTasklet.rs b/src/runtime/webcore/fetch/FetchTasklet.rs index 9bff5a530a83..b3ceefd55c70 100644 --- a/src/runtime/webcore/fetch/FetchTasklet.rs +++ b/src/runtime/webcore/fetch/FetchTasklet.rs @@ -1326,6 +1326,26 @@ impl FetchTasklet { } } + if let http::Error::ClientTLSSetup(packed) = fail { + let (ossl_code, ossl_msg) = crate::crypto::boringssl_jsc::err_code_and_message(packed); + let code = if ossl_code.is_empty() { + BunString::static_(fail.name()) + } else { + BunString::clone_utf8(&ossl_code) + }; + let message = if ossl_msg.is_empty() { + BunString::static_("Failed to load client TLS certificate or key") + } else { + BunString::clone_utf8(&ossl_msg) + }; + return BodyValueError::SystemError(jsc::SystemError { + code: code.into(), + message: message.into(), + path: path.into(), + ..Default::default() + }); + } + let code = if fail == http::Error::ConnectionClosed { BunString::static_("ECONNRESET") } else { diff --git a/test/js/web/fetch/fetch.tls.test.ts b/test/js/web/fetch/fetch.tls.test.ts index 6082427fdb5e..3d7fd04db9da 100644 --- a/test/js/web/fetch/fetch.tls.test.ts +++ b/test/js/web/fetch/fetch.tls.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "bun:test"; import { bunEnv, bunExe, isASAN, tmpdirSync } from "harness"; +import { readFileSync } from "node:fs"; import { join } from "node:path"; import tls from "node:tls"; @@ -699,3 +700,44 @@ describe.concurrent("fetch-tls", () => { } }); }); + +// When client cert/key material fails to load into the SSL_CTX, fetch used to +// surface a generic FailedToOpenSocket "Was there a typo in the url or port?" +// even though the same misconfiguration via node:https reports the real +// BoringSSL error (ERR_OSSL_X509_KEY_VALUES_MISMATCH, ERR_OSSL_BAD_DECRYPT, +// ERR_OSSL_PEM_NO_START_LINE). +describe.concurrent("fetch tls: client cert/key load errors surface the OpenSSL code", () => { + const nodeTlsFixture = (f: string) => + readFileSync(join(import.meta.dir, "..", "..", "node", "tls", "fixtures", f), "utf8"); + const rsaCert = nodeTlsFixture("rsa_cert.crt"); + const rsaEncryptedKey = nodeTlsFixture("rsa_private_encrypted.pem"); + + const cases: [string, { cert: string; key: string; passphrase?: string }, RegExp][] = [ + ["cert/key mismatch", { cert: validTls.cert, key: expiredTls.key }, /^ERR_OSSL_X509_KEY_VALUES_MISMATCH$/], + ["encrypted key, wrong passphrase", { cert: rsaCert, key: rsaEncryptedKey, passphrase: "wrong" }, /^ERR_OSSL_/], + ["encrypted key, no passphrase", { cert: rsaCert, key: rsaEncryptedKey }, /^ERR_OSSL_/], + ["non-PEM cert string", { cert: "not a pem", key: validTls.key }, /^ERR_OSSL_PEM_NO_START_LINE$/], + ["non-PEM key string", { cert: validTls.cert, key: "not a pem" }, /^ERR_OSSL_PEM_NO_START_LINE$/], + ]; + + it.each(cases)("%s", async (_name, clientTls, codePattern) => { + using server = Bun.serve({ + port: 0, + tls: validTls, + fetch: () => new Response("ok"), + }); + + let err: any; + try { + await fetch(server.url, { tls: { ca: validTls.cert, ...clientTls } }); + } catch (e) { + err = e; + } + expect(err).toBeDefined(); + expect(err.code).toMatch(codePattern); + expect(err.code).not.toBe("FailedToOpenSocket"); + expect(err.message).not.toContain("typo in the url"); + // The failing URL is attached like every other fetch rejection. + expect(err.path).toBe(server.url.href); + }); +}); From ae8459c55a06a06194a80b32d5b73a50a48ccba4 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 27 Jul 2026 22:38:38 +0000 Subject: [PATCH 2/7] fetch(tls): cover the http-proxy CONNECT path and dedupe err_to_js ProxyTunnel::start builds the inner-TLS SSL_CTX for the http-proxy -> https-target CONNECT tunnel via SSLWrapper::init_from_options; on bad cert/key that site returned InitError::InvalidOptions and was mapped to ConnectionRefused without reading the BoringSSL queue. Capture ERR_get_error() there too (same thread as the failed SSL_CTX_* calls) and surface Error::ClientTLSSetup(packed) so the proxy path reports the same ERR_OSSL_* code as the direct path. Also fold the ERR_OSSL__ code composition into a shared build_err_ossl_code helper and have err_to_js call err_code_and_message for its (code, message), so the fetch and node:https paths cannot drift. --- src/http/ProxyTunnel.rs | 14 ++++++- src/runtime/crypto/boringssl_jsc.rs | 60 +++++++++++------------------ test/js/web/fetch/fetch.tls.test.ts | 33 ++++++++++++++++ 3 files changed, 68 insertions(+), 39 deletions(-) diff --git a/src/http/ProxyTunnel.rs b/src/http/ProxyTunnel.rs index 698ce01f3bae..3fba0aaf5688 100644 --- a/src/http/ProxyTunnel.rs +++ b/src/http/ProxyTunnel.rs @@ -628,9 +628,19 @@ impl ProxyTunnel { bun_core::out_of_memory(); } - // invalid TLS Options + // invalid TLS Options: create_ssl_context leaves the detail + // on this thread's BoringSSL error queue (same thread as the + // failed SSL_CTX_* calls). Surface it the way the direct + // (non-proxy) path does instead of a generic ConnectionRefused. + let packed = bun_boringssl_sys::ERR_get_error(); + let fail = if packed != 0 { + bun_boringssl_sys::ERR_clear_error(); + crate::Error::ClientTLSSetup(packed) + } else { + crate::Error::ConnectionRefused + }; proxy_tunnel_ref.detach_and_deref(); - this.close_and_fail::(crate::Error::ConnectionRefused, socket); + this.close_and_fail::(fail, socket); return; } } diff --git a/src/runtime/crypto/boringssl_jsc.rs b/src/runtime/crypto/boringssl_jsc.rs index 49d9c263451e..b3d1a953361f 100644 --- a/src/runtime/crypto/boringssl_jsc.rs +++ b/src/runtime/crypto/boringssl_jsc.rs @@ -52,6 +52,22 @@ fn static_cstr<'a>(ptr: *const core::ffi::c_char) -> Option<&'a [u8]> { if bytes.is_empty() { None } else { Some(bytes) } } +/// Compose Node's `ERR_OSSL__` code (or `ERR_SSL_` for the +/// SSL library) from a packed BoringSSL error's library number and reason +/// string. Shared by [`err_code_and_message`] and [`err_to_js`] so the two +/// paths cannot drift. +fn build_err_ossl_code(err_code: u32, reason: &[u8]) -> Vec { + let lib = lib_short_name((err_code >> 24) & 0xff); + // Don't generate codes like "ERR_OSSL_SSL_". + let prefix = if lib == "SSL_" { "" } else { "OSSL_" }; + let mut code = Vec::with_capacity(4 + prefix.len() + lib.len() + reason.len()); + code.extend_from_slice(b"ERR_"); + code.extend_from_slice(prefix.as_bytes()); + code.extend_from_slice(lib.as_bytes()); + code.extend_from_slice(reason); + code +} + /// Format a packed BoringSSL error into `(code, message)` strings without /// touching JSC. `code` is Node's `ERR_OSSL__` (or `ERR_SSL_*` for /// the SSL library); `message` is the raw `ERR_error_string_n` output. Both @@ -69,18 +85,9 @@ pub fn err_code_and_message(err_code: u32) -> (Vec, Vec) { } let message = bun_core::slice_to_nul(&outbuf[..]).to_vec(); - let code = if let Some(reason) = static_cstr(boring::ERR_reason_error_string(err_code)) { - let lib = lib_short_name((err_code >> 24) & 0xff); - let prefix = if lib == "SSL_" { "" } else { "OSSL_" }; - let mut code = Vec::with_capacity(4 + prefix.len() + lib.len() + reason.len()); - code.extend_from_slice(b"ERR_"); - code.extend_from_slice(prefix.as_bytes()); - code.extend_from_slice(lib.as_bytes()); - code.extend_from_slice(reason); - code - } else { - Vec::new() - }; + let code = static_cstr(boring::ERR_reason_error_string(err_code)) + .map(|reason| build_err_ossl_code(err_code, reason)) + .unwrap_or_default(); (code, message) } @@ -89,19 +96,7 @@ pub fn err_to_js(global: &JSGlobalObject, err_code: u32) -> JSValue { // The message is the raw ERR_error_string output // ("error:0b000074:X.509 certificate routines:OPENSSL_internal:..."), // exactly what Node built against BoringSSL produces - no prefix. - let mut outbuf = [0u8; 128 + 1]; - let message_buf = &mut outbuf[..]; - - // SAFETY: message_buf is a valid writable buffer of message_buf.len() bytes. - unsafe { - boring::ERR_error_string_n( - err_code, - message_buf.as_mut_ptr().cast::(), - message_buf.len(), - ); - } - - let error_message: &[u8] = bun_core::slice_to_nul(&outbuf[..]); + let (code, error_message) = err_code_and_message(err_code); if error_message.is_empty() { return global .err( @@ -114,9 +109,7 @@ pub fn err_to_js(global: &JSGlobalObject, err_code: u32) -> JSValue { // A plain Error carrying Node's library/function/reason/code decomposition // of the OpenSSL error, the way ThrowCryptoError builds it: the code is // ERR_OSSL__ (or ERR_SSL_ for the SSL library). - // The message must own its bytes - `outbuf` is a stack buffer and the - // error instance outlives this frame. - let err = BunString::clone_utf8(error_message).to_error_instance(global); + let err = BunString::clone_utf8(&error_message).to_error_instance(global); if let Some(library) = static_cstr(boring::ERR_lib_error_string(err_code)) { err.put(global, b"library", ZigString::init(library).to_js(global)); @@ -126,15 +119,8 @@ pub fn err_to_js(global: &JSGlobalObject, err_code: u32) -> JSValue { } if let Some(reason) = static_cstr(boring::ERR_reason_error_string(err_code)) { err.put(global, b"reason", ZigString::init(reason).to_js(global)); - - let lib = lib_short_name((err_code >> 24) & 0xff); - // Don't generate codes like "ERR_OSSL_SSL_". - let prefix = if lib == "SSL_" { "" } else { "OSSL_" }; - let mut code = Vec::with_capacity(4 + prefix.len() + lib.len() + reason.len()); - code.extend_from_slice(b"ERR_"); - code.extend_from_slice(prefix.as_bytes()); - code.extend_from_slice(lib.as_bytes()); - code.extend_from_slice(reason); + } + if !code.is_empty() { err.put(global, b"code", ZigString::init(&code).to_js(global)); } diff --git a/test/js/web/fetch/fetch.tls.test.ts b/test/js/web/fetch/fetch.tls.test.ts index 3d7fd04db9da..916482bd16e5 100644 --- a/test/js/web/fetch/fetch.tls.test.ts +++ b/test/js/web/fetch/fetch.tls.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from "bun:test"; import { bunEnv, bunExe, isASAN, tmpdirSync } from "harness"; +import { once } from "node:events"; import { readFileSync } from "node:fs"; +import net from "node:net"; import { join } from "node:path"; import tls from "node:tls"; @@ -740,4 +742,35 @@ describe.concurrent("fetch tls: client cert/key load errors surface the OpenSSL // The failing URL is attached like every other fetch rejection. expect(err.path).toBe(server.url.href); }); + + // The http-proxy -> https-target CONNECT-tunnel path builds the client + // SSL_CTX at ProxyTunnel::start, after the proxy replies 200; that site must + // surface the same ERR_OSSL_* code instead of a generic ConnectionRefused. + it.each(cases)("via http CONNECT proxy: %s", async (_name, clientTls, codePattern) => { + const proxy = net.createServer(client => { + client.once("data", () => { + client.write("HTTP/1.1 200 Connection established\r\n\r\n"); + }); + }); + proxy.listen(0, "127.0.0.1"); + await once(proxy, "listening"); + const proxyPort = (proxy.address() as net.AddressInfo).port; + try { + let err: any; + try { + await fetch(`https://127.0.0.1:1/`, { + proxy: `http://127.0.0.1:${proxyPort}`, + tls: { rejectUnauthorized: false, ...clientTls }, + }); + } catch (e) { + err = e; + } + expect(err).toBeDefined(); + expect(err.code).toMatch(codePattern); + expect(err.code).not.toBe("ConnectionRefused"); + expect(err.code).not.toBe("FailedToOpenSocket"); + } finally { + proxy.close(); + } + }); }); From 142c64557192a9f9ea731a71d2a56cafbf982110 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 27 Jul 2026 22:43:34 +0000 Subject: [PATCH 3/7] extract take_boringssl_error helper and trim comments The ERR_get_error/ERR_clear_error pattern now has a single named helper in http::error that both HTTPContext and ProxyTunnel call, so the thread-local-queue invariant is documented once and the call sites are self-explanatory. --- src/http/HTTPContext.rs | 16 +++------------- src/http/InitError.rs | 5 ++--- src/http/ProxyTunnel.rs | 15 +++------------ src/http/error.rs | 14 +++++++++++--- src/runtime/crypto/boringssl_jsc.rs | 19 ++++--------------- 5 files changed, 23 insertions(+), 46 deletions(-) diff --git a/src/http/HTTPContext.rs b/src/http/HTTPContext.rs index 7abaebed8703..1f8d44bb0dce 100644 --- a/src/http/HTTPContext.rs +++ b/src/http/HTTPContext.rs @@ -494,19 +494,9 @@ impl HTTPContext { uws::create_bun_socket_error_t::none | uws::create_bun_socket_error_t::invalid_ciphers | uws::create_bun_socket_error_t::invalid_ecdh_curve => { - // us_ssl_ctx_build_raw returns NULL with *err left at - // .none for client cert/key/passphrase failures; the - // real cause is only on this thread's BoringSSL error - // queue. Capture it here (same thread as the failed - // SSL_CTX_* calls) so the JS thread can surface - // ERR_OSSL_* instead of a generic FailedToOpenSocket. - let packed = bun_boringssl_sys::ERR_get_error(); - if packed != 0 { - bun_boringssl_sys::ERR_clear_error(); - InitError::ClientTLSSetup(packed) - } else { - InitError::FailedToOpenSocket - } + crate::error::take_boringssl_error() + .map(|p| InitError::ClientTLSSetup(p.get())) + .unwrap_or(InitError::FailedToOpenSocket) } }); } diff --git a/src/http/InitError.rs b/src/http/InitError.rs index c81f4019e62d..52a5ef93e250 100644 --- a/src/http/InitError.rs +++ b/src/http/InitError.rs @@ -10,9 +10,8 @@ pub enum InitError { InvalidCA, #[error("InvalidCRL")] InvalidCRL, - /// SSL_CTX construction failed while loading client cert/key material. - /// Carries the packed BoringSSL error (from `ERR_get_error()`), captured on - /// the thread that built the context so the JS thread can format it later. + /// Client cert/key failed to load into the SSL_CTX; payload is the packed + /// BoringSSL error from [`crate::error::take_boringssl_error`]. #[error("ClientTLSSetup")] ClientTLSSetup(u32), } diff --git a/src/http/ProxyTunnel.rs b/src/http/ProxyTunnel.rs index 3fba0aaf5688..567e42919327 100644 --- a/src/http/ProxyTunnel.rs +++ b/src/http/ProxyTunnel.rs @@ -627,18 +627,9 @@ impl ProxyTunnel { if e == InitError::OutOfMemory { bun_core::out_of_memory(); } - - // invalid TLS Options: create_ssl_context leaves the detail - // on this thread's BoringSSL error queue (same thread as the - // failed SSL_CTX_* calls). Surface it the way the direct - // (non-proxy) path does instead of a generic ConnectionRefused. - let packed = bun_boringssl_sys::ERR_get_error(); - let fail = if packed != 0 { - bun_boringssl_sys::ERR_clear_error(); - crate::Error::ClientTLSSetup(packed) - } else { - crate::Error::ConnectionRefused - }; + let fail = crate::error::take_boringssl_error() + .map(|p| crate::Error::ClientTLSSetup(p.get())) + .unwrap_or(crate::Error::ConnectionRefused); proxy_tunnel_ref.detach_and_deref(); this.close_and_fail::(fail, socket); return; diff --git a/src/http/error.rs b/src/http/error.rs index 13b075adeba0..e8505eb2a7ac 100644 --- a/src/http/error.rs +++ b/src/http/error.rs @@ -93,9 +93,8 @@ pub enum Error { HTTP3ContentLengthMismatch, #[error("FailedToOpenSocket")] FailedToOpenSocket, - /// Loading the client TLS certificate/key into the SSL_CTX failed. Carries - /// the packed BoringSSL error code so the consumer can produce Node's - /// `ERR_OSSL_*` shape. + /// Client cert/key failed to load into the SSL_CTX; payload is the packed + /// BoringSSL error that becomes `ERR_OSSL_*` at the JS boundary. #[error("ClientTLSSetup")] ClientTLSSetup(u32), #[error("InvalidCRL")] @@ -261,6 +260,15 @@ pub enum CertError { UNKNOWN_CERTIFICATE_VERIFICATION_ERROR, } +/// Pop + drain this thread's BoringSSL error queue. Call immediately after a +/// failed `create_ssl_context` on the same thread (the queue is thread-local). +pub fn take_boringssl_error() -> Option { + let packed = bun_boringssl_sys::ERR_get_error(); + let packed = core::num::NonZeroU32::new(packed)?; + bun_boringssl_sys::ERR_clear_error(); + Some(packed) +} + impl Error { #[allow(clippy::trivially_copy_pass_by_ref)] pub fn name(&self) -> &'static str { diff --git a/src/runtime/crypto/boringssl_jsc.rs b/src/runtime/crypto/boringssl_jsc.rs index b3d1a953361f..25a9dcaa3d39 100644 --- a/src/runtime/crypto/boringssl_jsc.rs +++ b/src/runtime/crypto/boringssl_jsc.rs @@ -52,10 +52,7 @@ fn static_cstr<'a>(ptr: *const core::ffi::c_char) -> Option<&'a [u8]> { if bytes.is_empty() { None } else { Some(bytes) } } -/// Compose Node's `ERR_OSSL__` code (or `ERR_SSL_` for the -/// SSL library) from a packed BoringSSL error's library number and reason -/// string. Shared by [`err_code_and_message`] and [`err_to_js`] so the two -/// paths cannot drift. +/// Node's `ERR_OSSL__` (or `ERR_SSL_`) code string. fn build_err_ossl_code(err_code: u32, reason: &[u8]) -> Vec { let lib = lib_short_name((err_code >> 24) & 0xff); // Don't generate codes like "ERR_OSSL_SSL_". @@ -68,11 +65,8 @@ fn build_err_ossl_code(err_code: u32, reason: &[u8]) -> Vec { code } -/// Format a packed BoringSSL error into `(code, message)` strings without -/// touching JSC. `code` is Node's `ERR_OSSL__` (or `ERR_SSL_*` for -/// the SSL library); `message` is the raw `ERR_error_string_n` output. Both -/// lookups are pure table reads keyed on the `u32`, so the thread that calls -/// this need not be the thread that produced the error. +/// JSC-free `(code, message)` formatter for a packed BoringSSL error. Pure +/// table lookups on the `u32`, so callable from any thread. pub fn err_code_and_message(err_code: u32) -> (Vec, Vec) { let mut outbuf = [0u8; 128 + 1]; // SAFETY: outbuf is a valid writable buffer of outbuf.len() bytes. @@ -93,9 +87,6 @@ pub fn err_code_and_message(err_code: u32) -> (Vec, Vec) { } pub fn err_to_js(global: &JSGlobalObject, err_code: u32) -> JSValue { - // The message is the raw ERR_error_string output - // ("error:0b000074:X.509 certificate routines:OPENSSL_internal:..."), - // exactly what Node built against BoringSSL produces - no prefix. let (code, error_message) = err_code_and_message(err_code); if error_message.is_empty() { return global @@ -106,9 +97,7 @@ pub fn err_to_js(global: &JSGlobalObject, err_code: u32) -> JSValue { .to_js(); } - // A plain Error carrying Node's library/function/reason/code decomposition - // of the OpenSSL error, the way ThrowCryptoError builds it: the code is - // ERR_OSSL__ (or ERR_SSL_ for the SSL library). + // Node's ThrowCryptoError shape: .message/.library/.function/.reason/.code. let err = BunString::clone_utf8(&error_message).to_error_instance(global); if let Some(library) = static_cstr(boring::ERR_lib_error_string(err_code)) { From 931451576d290b67488e77848db988bfbb4c0d6a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 27 Jul 2026 22:46:09 +0000 Subject: [PATCH 4/7] trim doc comments to single lines --- src/http/InitError.rs | 3 +-- src/http/error.rs | 6 ++---- src/runtime/crypto/boringssl_jsc.rs | 5 +---- 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/src/http/InitError.rs b/src/http/InitError.rs index 52a5ef93e250..4ec4c27bfe60 100644 --- a/src/http/InitError.rs +++ b/src/http/InitError.rs @@ -10,8 +10,7 @@ pub enum InitError { InvalidCA, #[error("InvalidCRL")] InvalidCRL, - /// Client cert/key failed to load into the SSL_CTX; payload is the packed - /// BoringSSL error from [`crate::error::take_boringssl_error`]. + /// Packed BoringSSL error from [`crate::error::take_boringssl_error`]. #[error("ClientTLSSetup")] ClientTLSSetup(u32), } diff --git a/src/http/error.rs b/src/http/error.rs index e8505eb2a7ac..43527e141575 100644 --- a/src/http/error.rs +++ b/src/http/error.rs @@ -93,8 +93,7 @@ pub enum Error { HTTP3ContentLengthMismatch, #[error("FailedToOpenSocket")] FailedToOpenSocket, - /// Client cert/key failed to load into the SSL_CTX; payload is the packed - /// BoringSSL error that becomes `ERR_OSSL_*` at the JS boundary. + /// Packed BoringSSL error from [`take_boringssl_error`]; surfaces as `ERR_OSSL_*`. #[error("ClientTLSSetup")] ClientTLSSetup(u32), #[error("InvalidCRL")] @@ -260,8 +259,7 @@ pub enum CertError { UNKNOWN_CERTIFICATE_VERIFICATION_ERROR, } -/// Pop + drain this thread's BoringSSL error queue. Call immediately after a -/// failed `create_ssl_context` on the same thread (the queue is thread-local). +/// Pop+drain the thread-local BoringSSL error queue right after a failed `create_ssl_context`. pub fn take_boringssl_error() -> Option { let packed = bun_boringssl_sys::ERR_get_error(); let packed = core::num::NonZeroU32::new(packed)?; diff --git a/src/runtime/crypto/boringssl_jsc.rs b/src/runtime/crypto/boringssl_jsc.rs index 25a9dcaa3d39..ff2e27b092b9 100644 --- a/src/runtime/crypto/boringssl_jsc.rs +++ b/src/runtime/crypto/boringssl_jsc.rs @@ -52,10 +52,8 @@ fn static_cstr<'a>(ptr: *const core::ffi::c_char) -> Option<&'a [u8]> { if bytes.is_empty() { None } else { Some(bytes) } } -/// Node's `ERR_OSSL__` (or `ERR_SSL_`) code string. fn build_err_ossl_code(err_code: u32, reason: &[u8]) -> Vec { let lib = lib_short_name((err_code >> 24) & 0xff); - // Don't generate codes like "ERR_OSSL_SSL_". let prefix = if lib == "SSL_" { "" } else { "OSSL_" }; let mut code = Vec::with_capacity(4 + prefix.len() + lib.len() + reason.len()); code.extend_from_slice(b"ERR_"); @@ -65,8 +63,7 @@ fn build_err_ossl_code(err_code: u32, reason: &[u8]) -> Vec { code } -/// JSC-free `(code, message)` formatter for a packed BoringSSL error. Pure -/// table lookups on the `u32`, so callable from any thread. +/// JSC-free `(ERR_OSSL_* code, message)` for a packed BoringSSL error; thread-agnostic lookup. pub fn err_code_and_message(err_code: u32) -> (Vec, Vec) { let mut outbuf = [0u8; 128 + 1]; // SAFETY: outbuf is a valid writable buffer of outbuf.len() bytes. From e09a13773afacb18f2ad0fdfc8987962da1f0ec7 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 27 Jul 2026 22:50:57 +0000 Subject: [PATCH 5/7] test: swallow ECONNRESET on the proxy's accepted socket --- test/js/web/fetch/fetch.tls.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/test/js/web/fetch/fetch.tls.test.ts b/test/js/web/fetch/fetch.tls.test.ts index 916482bd16e5..b0c09409c671 100644 --- a/test/js/web/fetch/fetch.tls.test.ts +++ b/test/js/web/fetch/fetch.tls.test.ts @@ -748,6 +748,7 @@ describe.concurrent("fetch tls: client cert/key load errors surface the OpenSSL // surface the same ERR_OSSL_* code instead of a generic ConnectionRefused. it.each(cases)("via http CONNECT proxy: %s", async (_name, clientTls, codePattern) => { const proxy = net.createServer(client => { + client.on("error", () => {}); client.once("data", () => { client.write("HTTP/1.1 200 Connection established\r\n\r\n"); }); From ed7988cfaeafdf8fdf43e4d61bb14d1298f36aaa Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 27 Jul 2026 23:19:55 +0000 Subject: [PATCH 6/7] test: give the cert-mismatch-churn fixture headroom under ASAN The fixture spawns a debug+ASAN bun subprocess that drives hundreds of TLS handshakes; on main with no other changes it already ran at ~4.2-5.5s against the 5s default timeout and flaked ~1 in 5 runs. Give it an explicit isASAN-gated timeout. --- test/js/web/fetch/fetch.tls.test.ts | 40 +++++++++++++++++------------ 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/test/js/web/fetch/fetch.tls.test.ts b/test/js/web/fetch/fetch.tls.test.ts index b0c09409c671..2d23c43e5423 100644 --- a/test/js/web/fetch/fetch.tls.test.ts +++ b/test/js/web/fetch/fetch.tls.test.ts @@ -205,23 +205,29 @@ describe.concurrent("fetch-tls", () => { // read the freed AsyncHTTP clone and called through a null callback pointer. // The fixture drives that exact traffic shape and exits non-zero on any // unexpected outcome; every failure must surface as a catchable error. - it("rejects a trusted cert with a mismatched hostname cleanly under abort/timeout/keepalive churn", async () => { - await using proc = Bun.spawn({ - cmd: [bunExe(), join(import.meta.dir, "fetch.tls.cert-mismatch-churn.fixture.ts")], - env: { ...bunEnv, BUN_CONFIG_HTTP_IDLE_TIMEOUT: "1" }, - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); - // Check stderr for sanitizer reports first (and unconditionally): a - // recovered ASAN report can leave exit code 0, and on an abort this - // surfaces the actual report instead of a bare exit-code mismatch. - // Don't assert emptiness: debug builds emit benign startup noise. - expect(stderr).not.toMatch(/AddressSanitizer|ERROR: (Leak|Thread)Sanitizer/); - // Fixture reports unexpected outcomes on stdout. - expect(stdout).toStartWith("OK "); - expect(exitCode).toBe(0); - }); + it( + "rejects a trusted cert with a mismatched hostname cleanly under abort/timeout/keepalive churn", + async () => { + await using proc = Bun.spawn({ + cmd: [bunExe(), join(import.meta.dir, "fetch.tls.cert-mismatch-churn.fixture.ts")], + env: { ...bunEnv, BUN_CONFIG_HTTP_IDLE_TIMEOUT: "1" }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + // Check stderr for sanitizer reports first (and unconditionally): a + // recovered ASAN report can leave exit code 0, and on an abort this + // surfaces the actual report instead of a bare exit-code mismatch. + // Don't assert emptiness: debug builds emit benign startup noise. + expect(stderr).not.toMatch(/AddressSanitizer|ERROR: (Leak|Thread)Sanitizer/); + // Fixture reports unexpected outcomes on stdout. + expect(stdout).toStartWith("OK "); + expect(exitCode).toBe(0); + }, + // The fixture is a debug+ASAN subprocess driving hundreds of TLS + // handshakes; on main it already ran at ~4.2-5.0s against the 5s default. + isASAN ? 20000 : 10000, + ); // When checkServerIdentity is provided, the HTTP thread sends an intermediate // progress update carrying the server certificate before response headers From 96c737581f4d6faeded91ee254c59ed3d680b692 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Mon, 27 Jul 2026 23:36:30 +0000 Subject: [PATCH 7/7] ci: retrigger