Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 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
4 changes: 3 additions & 1 deletion src/http/HTTPContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,9 @@ impl<const SSL: bool> HTTPContext<SSL> {
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)
}
});
}
Expand Down
3 changes: 2 additions & 1 deletion src/http/HTTPThread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}
Expand Down Expand Up @@ -543,6 +543,7 @@ impl HttpThread {

return Err(match err {
InitError::InvalidCRL => crate::Error::InvalidCRL,
InitError::ClientTLSSetup(code) => crate::Error::ClientTLSSetup(code),
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
InitError::FailedToOpenSocket
| InitError::InvalidCA
| InitError::InvalidCAFile
Expand Down
3 changes: 3 additions & 0 deletions src/http/InitError.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,7 @@ pub enum InitError {
InvalidCA,
#[error("InvalidCRL")]
InvalidCRL,
/// Packed BoringSSL error from [`crate::error::take_boringssl_error`].
#[error("ClientTLSSetup")]
ClientTLSSetup(u32),
}
7 changes: 4 additions & 3 deletions src/http/ProxyTunnel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Comment thread
robobun marked this conversation as resolved.
Resolved
proxy_tunnel_ref.detach_and_deref();
this.close_and_fail::<IS_SSL>(crate::Error::ConnectionRefused, socket);
this.close_and_fail::<IS_SSL>(fail, socket);
return;
}
}
Expand Down
12 changes: 12 additions & 0 deletions src/http/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")]
Expand Down Expand Up @@ -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<core::num::NonZeroU32> {
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 {
Expand Down Expand Up @@ -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),
Expand Down
2 changes: 1 addition & 1 deletion src/install/PackageManager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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", ());
}
}
Expand Down
55 changes: 30 additions & 25 deletions src/runtime/crypto/boringssl_jsc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8> {
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<u8>, Vec<u8>) {
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::<core::ffi::c_char>(),
message_buf.len(),
outbuf.as_mut_ptr().cast::<core::ffi::c_char>(),
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)
}
Comment thread
claude[bot] marked this conversation as resolved.
Resolved

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(
Expand All @@ -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_<LIB>_<REASON> (or ERR_SSL_<REASON> 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));
Expand All @@ -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));
}

Expand Down
20 changes: 20 additions & 0 deletions src/runtime/webcore/fetch/FetchTasklet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
76 changes: 76 additions & 0 deletions test/js/web/fetch/fetch.tls.test.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -699,3 +702,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");
});
});
Comment thread
robobun marked this conversation as resolved.
Resolved
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();
}
});
});
Loading