//! DEDUP(D202): the `SSLConfig` struct, its `Clone`/`Drop`/`Default`/hash/ //! equality/registry impls, and `as_usockets*`/`for_client_verification` were //! duplicated (here and in `bun_http::ssl_config`). The lower-tier //! `bun_http` copy is canonical (JSC-free, nullable NUL-terminated C-string //! field layout); this module now re-exports it and keeps ONLY the //! JSC-dependent constructors (`from_js` / `from_generated` / blob+path //! readers) plus the WebSocket C-ABI exports, which need `bun_jsc` / //! `webcore::Blob` / `node_fs` (tier-6). //! //! `from_js`/`from_generated` cannot be inherent `impl SSLConfig` (orphan //! rule on a foreign type), so they're provided via the [`SSLConfigFromJs`] //! extension trait. Import that trait to call `SSLConfig::from_js(..)`. use core::ffi::c_char; use bun_jsc::virtual_machine::VirtualMachine; use bun_jsc::{self as jsc, JSGlobalObject, JSValue, JsError, JsResult, SysErrorJsc}; use crate::generated_bindgen::ssl_config as generated; use crate::node::fs as node_fs; use crate::webcore::Blob; use crate::webcore::blob::store::Data as StoreData; // ────────────────────────────────────────────────────────────────────────── // Canonical re-exports (struct + registry live in bun_http now) // ────────────────────────────────────────────────────────────────────────── pub(crate) use bun_http::ssl_config::SSLConfig; // ────────────────────────────────────────────────────────────────────────── // ReadFromBlobError // ────────────────────────────────────────────────────────────────────────── // Cannot derive `thiserror::Error` because `JsError` is not // `std::error::Error`/`Display`. Manual `From` instead. #[derive(Debug)] pub(crate) enum ReadFromBlobError { Js(JsError), NullStore, NotAFile, EmptyFile, } impl From for ReadFromBlobError { #[inline] fn from(e: JsError) -> Self { ReadFromBlobError::Js(e) } } // ────────────────────────────────────────────────────────────────────────── // Allocation helpers // // Every owned C-string field on `bun_http::SSLConfig` is freed via // `bun_core::free_sensitive` (the default-allocator free after secure-zero). // Allocate via `bun_core::dupe_z` (the matching default-allocator alloc) so the // pairing is exact. Do NOT leak a `Box<[u8]>` here: under `cfg(bun_asan)` the // process-global `#[global_allocator]` is `std::alloc::System`, not mimalloc, // so `free_sensitive` would not pair with `Box`-owned memory. // ────────────────────────────────────────────────────────────────────────── /// `ZBox` is global-allocator memory; re-allocate via `dupe_z` so `mi_free` can free it. #[inline] fn zbox_into_raw(z: &bun_core::ZBox) -> *const c_char { bun_core::dupe_z(z.as_bytes()) } /// `dupeZ` a byte slice into a fresh mimalloc allocation. #[inline] fn dupe_z(bytes: &[u8]) -> *const c_char { bun_core::dupe_z(bytes) } type CStrSlice = Option>; fn read_from_blob( global: &JSGlobalObject, blob: &Blob, ) -> Result<*const c_char, ReadFromBlobError> { let store = blob .store .get() .as_ref() .ok_or(ReadFromBlobError::NullStore)?; let file = match &store.data { StoreData::File(f) => f, _ => return Err(ReadFromBlobError::NotAFile), }; let mut fs = node_fs::NodeFS::default(); // `ReadFile` has a `Drop` impl (releases its `signal` ref), so functional // record update from `..Default::default()` would partially move out of a // `Drop` type. Mutate-after-default instead. let mut read_args = node_fs::args::ReadFile::default(); read_args.path = file.pathlike.clone(); let maybe = fs.read_file_with_options( &read_args, node_fs::Flavor::Sync, node_fs::ReadFileStringType::NullTerminated, ); let result = match maybe { Ok(result) => result, Err(err) => { return Err(global.throw_value(err.to_js(global)).into()); } }; // `read_file_with_options(NullTerminated)` transfers ownership of the // returned buffer to the caller, so we can return it directly without // duplicating. let node_fs::ret::ReadFileWithOptions::NullTerminated(zbox) = result else { unreachable!("ReadFileStringType::NullTerminated always yields the NullTerminated variant"); }; if zbox.is_empty() { return Err(ReadFromBlobError::EmptyFile); } Ok(zbox_into_raw(&zbox)) } // ────────────────────────────────────────────────────────────────────────── // fromJS / fromGenerated — extension trait (orphan-rule workaround) // ────────────────────────────────────────────────────────────────────────── /// JSC-dependent constructors for the canonical `bun_http::SSLConfig`. /// Import this trait to call `SSLConfig::from_js(..)` / `::from_generated(..)`. /// An unset `rejectUnauthorized` is `true` for a server and `NODE_TLS_REJECT_UNAUTHORIZED` for a client, as in Node.js. pub(crate) trait SSLConfigFromJs: Sized { fn from_js( vm: &VirtualMachine, global: &JSGlobalObject, value: JSValue, is_server: bool, ) -> JsResult>; fn from_generated( vm: &VirtualMachine, global: &JSGlobalObject, generated: &generated::TLSOptions, is_server: bool, ) -> JsResult>; } impl SSLConfigFromJs for SSLConfig { fn from_js( vm: &VirtualMachine, global: &JSGlobalObject, value: JSValue, is_server: bool, ) -> JsResult> { let generated = generated::TLSOptions::from_js(global, value)?; Self::from_generated(vm, global, &generated, is_server) } fn from_generated( vm: &VirtualMachine, global: &JSGlobalObject, generated: &generated::TLSOptions, is_server: bool, ) -> JsResult> { let mut result = SSLConfig::zero(); // `result` cleanup handled by Drop on error-path `?` let mut any = false; if let Some(passphrase) = generated.passphrase.as_ref() { result.passphrase = zbox_into_raw(&passphrase.to_owned_slice_z()); any = true; } if let Some(dh_params_file) = generated.dh_params_file.as_ref() { result.dh_params_file_name = handle_path(global, "dhParamsFile", dh_params_file)?; any = true; } if let Some(server_name) = generated.server_name.as_ref() { let server_name = server_name.to_owned_slice_z(); // `server_name` is a C string: SNI and the certificate check would see the name up to the NUL. if bun_core::strings::contains_char(server_name.as_bytes(), 0) { return Err(global.throw_invalid_arguments(format_args!( "\"serverName\" must not contain null bytes" ))); } result.server_name = zbox_into_raw(&server_name); result.requires_custom_request_ctx = true; } result.low_memory_mode = generated.low_memory_mode; result.reject_unauthorized = generated .reject_unauthorized .unwrap_or_else(|| is_server || vm.get_tls_reject_unauthorized()) as i32; result.request_cert = generated.request_cert as i32; result.secure_options = generated.secure_options; result.ssl_min_version = generated.ssl_min_version; result.ssl_max_version = generated.ssl_max_version; result.session_timeout = generated.session_timeout; result.allow_partial_trust_chain = generated.allow_partial_trust_chain; if let Some(sigalgs) = generated.sigalgs.as_ref() { result.sigalgs = zbox_into_raw(&sigalgs.to_owned_slice_z()); any = true; } if let Some(ecdh_curve) = generated.ecdh_curve.as_ref() { let bytes = ecdh_curve.to_owned_slice_z(); // Node treats `ecdhCurve: 'auto'` (the documented default) as // "use the library's default group list", i.e. skip the // SSL_CTX_set1_groups_list call entirely. if bytes.as_bytes() != b"auto" { result.ecdh_curve = zbox_into_raw(&bytes); any = true; } } any = any || result.low_memory_mode || generated.reject_unauthorized.is_some() || generated.request_cert || result.secure_options != 0 || result.ssl_min_version != 0 || result.ssl_max_version != 0 || result.session_timeout != 0 || result.allow_partial_trust_chain; result.ca = handle_file_for_field(global, "ca", &generated.ca)?; result.cert = handle_file_for_field(global, "cert", &generated.cert)?; result.key = handle_file_for_field(global, "key", &generated.key)?; result.crl = handle_file_for_field(global, "crl", &generated.crl)?; result.requires_custom_request_ctx = result.requires_custom_request_ctx || result.ca.is_some() || result.cert.is_some() || result.key.is_some() || result.crl.is_some() || result.secure_options != 0 || result.ssl_min_version != 0 || result.ssl_max_version != 0 || !result.sigalgs.is_null() || !result.ecdh_curve.is_null() || result.session_timeout != 0 || result.allow_partial_trust_chain; if let Some(key_file) = generated.key_file.as_ref() { result.key_file_name = handle_path(global, "keyFile", key_file)?; result.requires_custom_request_ctx = true; } if let Some(cert_file) = generated.cert_file.as_ref() { result.cert_file_name = handle_path(global, "certFile", cert_file)?; result.requires_custom_request_ctx = true; } if let Some(ca_file) = generated.ca_file.as_ref() { result.ca_file_name = handle_path(global, "caFile", ca_file)?; result.requires_custom_request_ctx = true; } let protocols: *const c_char = match &generated.alpn_protocols { generated::ALPNProtocols::None => core::ptr::null(), generated::ALPNProtocols::String(val) => zbox_into_raw(&val.to_owned_slice_z()), generated::ALPNProtocols::Buffer(val) => { // SAFETY: `generated` holds a ref on the buffer, and nothing else borrows it here. let buffer: jsc::ArrayBuffer = unsafe { (*val.get()).as_array_buffer() }; dupe_z(buffer.byte_slice()) } }; if !protocols.is_null() { result.protos = protocols; result.requires_custom_request_ctx = true; } if let Some(ciphers) = generated.ciphers.as_ref() { result.ssl_ciphers = zbox_into_raw(&ciphers.to_owned_slice_z()); result.is_using_default_ciphers = false; result.requires_custom_request_ctx = true; } result.client_renegotiation_limit = generated.client_renegotiation_limit; result.client_renegotiation_window = generated.client_renegotiation_window; any = any || result.requires_custom_request_ctx || result.client_renegotiation_limit != 0 || generated.client_renegotiation_window != 0; if !any { return Ok(None); } // After `any`: the fallback does not make `tls: {}` a TLS configuration. if generated.ciphers.is_none() { apply_default_ciphers(vm, &mut result); } Ok(Some(result)) } } /// The `SSLConfig` for the `tls: true` shorthand: every option at its /// documented default, unlike `SSLConfig::zero()`. pub(crate) fn tls_true_defaults(vm: &VirtualMachine, is_server: bool) -> SSLConfig { let mut cfg = SSLConfig::zero(); cfg.reject_unauthorized = (is_server || vm.get_tls_reject_unauthorized()) as i32; apply_default_ciphers(vm, &mut cfg); cfg } /// For a request without TLS options: its default context is built on the HTTP thread, which does not see `tls.DEFAULT_CIPHERS`. pub(crate) fn http_client_defaults(vm: &VirtualMachine) -> Option { vm.tls_default_ciphers()?; Some(bun_http::ssl_config::global_registry::intern( tls_true_defaults(vm, false), )) } /// No `ciphers` option means `tls.DEFAULT_CIPHERS`, as in Node's `configSecureContext`. fn apply_default_ciphers(vm: &VirtualMachine, cfg: &mut SSLConfig) { if let Some(ciphers) = vm.tls_default_ciphers() { cfg.set_default_ciphers(ciphers); } } /// Whether a new TLS socket must enforce `rejectUnauthorized`: close the /// connection when the peer certificate fails verification. pub(crate) fn resolve_reject_unauthorized( vm: &VirtualMachine, cfg: Option<&SSLConfig>, is_server: bool, ) -> bool { match cfg { Some(cfg) => (!is_server || cfg.request_cert != 0) && cfg.reject_unauthorized != 0, None => !is_server && vm.get_tls_reject_unauthorized(), } } // ── handlePath / handleFile helpers ────────────────────────────────── // `field` is a runtime &'static str (not monomorphized) since it is only // used in a cold error message. fn handle_path( global: &JSGlobalObject, field: &'static str, string: &bun_core::String, ) -> JsResult<*const c_char> { let name = string.to_utf8(); let name = name.slice(); if bun_core::strings::contains_char(name, 0) { return Err(global .err( jsc::ErrorCode::INVALID_ARG_VALUE, format_args!("TLSOptions.{field} must be a path without null bytes"), ) .throw()); } // Opened later (for fetch, on the HTTP thread), and the SSL_CTX caches key on this string. let mut path = if cfg!(windows) || !bun_paths::is_absolute_posix(name) { bun_paths::AutoAbsPathChecked::init_top_level_dir() } else { bun_paths::AutoAbsPathChecked::init() }; // The kernel resolves `..` through symlinks, so it is left in. Win32 resolves it as `join` does, which also knows `C:foo` and `\foo`. let pinned = if cfg!(windows) { path.join(&[name]) } else { path.append(name) }; // `append` drops a trailing slash, with which no file opens. if name.is_empty() || (cfg!(not(windows)) && name.ends_with(b"/")) || pinned.is_err() || bun_sys::access(path.slice_z(), bun_sys::posix::F_OK).is_err() { return Err(global.throw_invalid_arguments(format_args!("Unable to access {field} path"))); } // BoringSSL's fopen is narrow on Windows: a non-ASCII cwd must not be baked into the path. if cfg!(windows) && !bun_core::strings::is_all_ascii(path.slice()) { return Ok(dupe_z(name)); } Ok(dupe_z(path.slice())) } fn handle_file_for_field( global: &JSGlobalObject, field: &'static str, file: &generated::TLSOptionsFile, ) -> JsResult { match handle_file(global, file) { Ok(v) => Ok(v), Err(ReadFromBlobError::Js(e)) => Err(e), Err(ReadFromBlobError::EmptyFile) => { Err(global .throw_invalid_arguments(format_args!("TLSOptions.{} is an empty file", field))) } Err(ReadFromBlobError::NullStore) | Err(ReadFromBlobError::NotAFile) => Err(global .throw_invalid_arguments(format_args!( "TLSOptions.{} is not a valid BunFile (non-BunFile `Blob`s are not supported)", field ))), } } fn handle_file( global: &JSGlobalObject, file: &generated::TLSOptionsFile, ) -> Result { let single = handle_single_file( global, match file { generated::TLSOptionsFile::None => return Ok(None), generated::TLSOptionsFile::String(val) => SingleFile::String(val), generated::TLSOptionsFile::Buffer(val) => { // SAFETY: `file` holds a ref on the buffer, and nothing else borrows it here. SingleFile::Buffer(unsafe { &mut *val.get() }) } generated::TLSOptionsFile::File(val) => { // SAFETY: as above, for the `Blob`. SingleFile::File(unsafe { &mut *val.get() }) } generated::TLSOptionsFile::Array(list) => { return handle_file_array(global, list); } }, )?; // The only fallible op below is alloc, and Rust aborts on OOM, so no // error-path zeroing is needed. Ok(Some(vec![single].into_boxed_slice())) } fn handle_file_array( global: &JSGlobalObject, elements: &[generated::TLSOptionsSingleFile], ) -> Result { if elements.is_empty() { return Ok(None); } let mut result: Vec<*const c_char> = Vec::with_capacity(elements.len()); // Error path: free_sensitive each, then drop result — need zeroing on error: let mut guard = scopeguard::guard(&mut result, |r| { for p in r.drain(..) { // SAFETY: every pushed `p` came from `handle_single_file` → // `zbox_into_raw`, a `default_alloc::malloc`-backed NUL-terminated buffer. unsafe { bun_core::free_sensitive(p) }; } }); for elem in elements { guard.push(handle_single_file( global, match elem { generated::TLSOptionsSingleFile::String(val) => SingleFile::String(val), generated::TLSOptionsSingleFile::Buffer(val) => { // SAFETY: see `handle_file`. SingleFile::Buffer(unsafe { &mut *val.get() }) } generated::TLSOptionsSingleFile::File(val) => { // SAFETY: see `handle_file`. SingleFile::File(unsafe { &mut *val.get() }) } }, )?); } let result = scopeguard::ScopeGuard::into_inner(guard); Ok(Some(core::mem::take(result).into_boxed_slice())) } enum SingleFile<'a> { String(&'a bun_core::String), Buffer(&'a mut jsc::JSCArrayBuffer), File(&'a mut crate::webcore::Blob), } fn handle_single_file( global: &JSGlobalObject, file: SingleFile<'_>, ) -> Result<*const c_char, ReadFromBlobError> { match file { SingleFile::String(string) => Ok(zbox_into_raw(&string.to_owned_slice_z())), SingleFile::Buffer(jsc_buffer) => { let buffer: jsc::ArrayBuffer = jsc_buffer.as_array_buffer(); Ok(dupe_z(buffer.byte_slice())) } SingleFile::File(blob) => read_from_blob(global, blob), } } // ────────────────────────────────────────────────────────────────────────── // WebSocket C-ABI exports (parseSSLConfig / freeSSLConfig) // // LAYERING: the consumer is `src/http_jsc/websocket_client/ // WebSocketUpgradeClient.rs`, but `SSLConfig::from_js` // dereferences Blob / JSCArrayBuffer / node_fs values (tier-6) and lives in // this crate. `bun_runtime → bun_http_jsc`, so hosting the export here breaks // the cycle without an opaque stub. The boxed payload is the canonical // `bun_http::ssl_config::SSLConfig` (what `HTTPClient::connect` consumes). // C++ (JSWebSocket.cpp) links by symbol name only. // ────────────────────────────────────────────────────────────────────────── /// Parse SSLConfig from a JavaScript TLS options object. /// This function is exported for C++ to call from JSWebSocket.cpp. /// Returns null if parsing fails (an exception will be set on globalThis). /// The returned SSLConfig is heap-allocated and ownership is transferred to the caller. #[unsafe(no_mangle)] extern "C" fn Bun__WebSocket__parseSSLConfig( global_this: &JSGlobalObject, tls_value: JSValue, ) -> Option> { // SAFETY: `bun_vm()` returns the live VM for this global; the WebSocket // constructor only runs on the JS thread with an initialized VM. let vm = global_this.bun_vm(); // Use SSLConfig::from_js for clean and safe parsing let config_opt = match SSLConfig::from_js(vm, global_this, tls_value, false) { Ok(c) => c, // Exception is already set on globalThis Err(_) => return None, }; // No TLS options provided or all defaults → null let config = config_opt?; // Allocate on heap and return pointer (ownership transferred to caller). Some(Box::new(config)) } /// Free an SSLConfig previously returned by `parseSSLConfig`. /// Exported for C++ so error/early-return paths in JSWebSocket.cpp and /// WebSocket.cpp can release ownership without leaking the heap allocation /// (and all duped cert/key/CA strings inside it) when `connect()` never /// hands the pointer off to an upgrade client. /// /// # Safety /// `config` must be null or a pointer previously returned by /// `Bun__WebSocket__parseSSLConfig` whose ownership the caller is transferring /// back (i.e. not already freed or handed to an upgrade client). #[unsafe(no_mangle)] unsafe extern "C" fn Bun__WebSocket__freeSSLConfig(config: *mut bun_http::ssl_config::SSLConfig) { // SAFETY: caller upholds the `# Safety` contract above — `config` is null // or a live pointer from `Bun__WebSocket__parseSSLConfig` whose ownership // is being transferred back. `heap::take` handles the null case. drop(unsafe { bun_core::heap::take(config) }); }