diff --git a/src/http/HTTPContext.rs b/src/http/HTTPContext.rs index 6d2d912f02e5..1f8d44bb0dce 100644 --- a/src/http/HTTPContext.rs +++ b/src/http/HTTPContext.rs @@ -494,7 +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 => { - InitError::FailedToOpenSocket + crate::error::take_boringssl_error() + .map(|p| InitError::ClientTLSSetup(p.get())) + .unwrap_or(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..4ec4c27bfe60 100644 --- a/src/http/InitError.rs +++ b/src/http/InitError.rs @@ -10,4 +10,7 @@ pub enum InitError { InvalidCA, #[error("InvalidCRL")] InvalidCRL, + /// 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 698ce01f3bae..567e42919327 100644 --- a/src/http/ProxyTunnel.rs +++ b/src/http/ProxyTunnel.rs @@ -627,10 +627,11 @@ impl ProxyTunnel { if e == InitError::OutOfMemory { bun_core::out_of_memory(); } - - // invalid TLS Options + 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::(crate::Error::ConnectionRefused, socket); + this.close_and_fail::(fail, socket); return; } } diff --git a/src/http/error.rs b/src/http/error.rs index b7edb71da82a..43527e141575 100644 --- a/src/http/error.rs +++ b/src/http/error.rs @@ -93,6 +93,9 @@ pub enum Error { HTTP3ContentLengthMismatch, #[error("FailedToOpenSocket")] FailedToOpenSocket, + /// Packed BoringSSL error from [`take_boringssl_error`]; surfaces as `ERR_OSSL_*`. + #[error("ClientTLSSetup")] + ClientTLSSetup(u32), #[error("InvalidCRL")] InvalidCRL, #[error("UnsupportedProxyProtocol")] @@ -256,6 +259,14 @@ pub enum CertError { UNKNOWN_CERTIFICATE_VERIFICATION_ERROR, } +/// 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)?; + bun_boringssl_sys::ERR_clear_error(); + Some(packed) +} + impl Error { #[allow(clippy::trivially_copy_pass_by_ref)] pub fn name(&self) -> &'static str { @@ -306,6 +317,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..ff2e27b092b9 100644 --- a/src/runtime/crypto/boringssl_jsc.rs +++ b/src/runtime/crypto/boringssl_jsc.rs @@ -52,23 +52,39 @@ fn static_cstr<'a>(ptr: *const core::ffi::c_char) -> Option<&'a [u8]> { if bytes.is_empty() { None } else { Some(bytes) } } -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[..]; +fn build_err_ossl_code(err_code: u32, reason: &[u8]) -> Vec { + 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 +} - // SAFETY: message_buf is a valid writable buffer of message_buf.len() bytes. +/// 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. unsafe { boring::ERR_error_string_n( err_code, - message_buf.as_mut_ptr().cast::(), - message_buf.len(), + outbuf.as_mut_ptr().cast::(), + outbuf.len(), ); } + let message = bun_core::slice_to_nul(&outbuf[..]).to_vec(); + + let code = static_cstr(boring::ERR_reason_error_string(err_code)) + .map(|reason| build_err_ossl_code(err_code, reason)) + .unwrap_or_default(); - let error_message: &[u8] = bun_core::slice_to_nul(&outbuf[..]); + (code, message) +} + +pub fn err_to_js(global: &JSGlobalObject, err_code: u32) -> JSValue { + let (code, error_message) = err_code_and_message(err_code); if error_message.is_empty() { return global .err( @@ -78,12 +94,8 @@ 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). - // 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); + // 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)) { err.put(global, b"library", ZigString::init(library).to_js(global)); @@ -93,15 +105,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/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..2d23c43e5423 100644 --- a/test/js/web/fetch/fetch.tls.test.ts +++ b/test/js/web/fetch/fetch.tls.test.ts @@ -1,5 +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"; @@ -202,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 @@ -699,3 +708,76 @@ 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); + }); + + // 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.on("error", () => {}); + 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(); + } + }); +});