Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
70 changes: 70 additions & 0 deletions src/http/HTTPThread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,12 @@ pub struct HttpThread {
pub queued_shutdowns: Vec<ShutdownMessage>,
pub queued_writes: Vec<WriteMessage>,
pub queued_response_body_drains: Vec<DrainMessage>,
pub queued_cert_check_resumes: Vec<CertCheckResumeMessage>,

pub queued_shutdowns_lock: Mutex,
pub queued_writes_lock: Mutex,
pub queued_response_body_drains_lock: Mutex,
pub queued_cert_check_resumes_lock: Mutex,

pub queued_threadlocal_proxy_derefs: Vec<*mut ProxyTunnel>,

Expand Down Expand Up @@ -179,9 +181,11 @@ impl HttpThread {
queued_shutdowns: Vec::new(),
queued_writes: Vec::new(),
queued_response_body_drains: Vec::new(),
queued_cert_check_resumes: Vec::new(),
queued_shutdowns_lock: Mutex::new(),
queued_writes_lock: Mutex::new(),
queued_response_body_drains_lock: Mutex::new(),
queued_cert_check_resumes_lock: Mutex::new(),
queued_threadlocal_proxy_derefs: Vec::new(),
has_awoken: AtomicBool::new(false),
timer: Instant::now(),
Expand Down Expand Up @@ -278,6 +282,12 @@ pub struct ShutdownMessage {
pub async_http_id: u32,
}

/// The JS thread's `checkServerIdentity` callback approved the peer
/// certificate; un-park the connection so the request is written.
pub struct CertCheckResumeMessage {
pub async_http_id: u32,
}

pub struct LibdeflateState {
pub decompressor: *mut bun_libdeflate_sys::libdeflate::Decompressor,
pub shared_buffer: [u8; 512 * 1024],
Expand Down Expand Up @@ -776,6 +786,51 @@ impl HttpThread {
}
}

fn drain_queued_cert_check_resumes(&mut self) {
loop {
let queued_cert_check_resumes = {
let _guard = self.queued_cert_check_resumes_lock.lock_guard();
core::mem::take(&mut self.queued_cert_check_resumes)
};
for resume in &queued_cert_check_resumes {
// Both arms are required: an HTTPS target behind a plaintext
// proxy parks behind a SocketTcp tracker entry.
if let Some(socket_ptr) = abort_tracker().get(&resume.async_http_id) {
match *socket_ptr {
uws::AnySocket::SocketTls(socket) => {
if socket.is_closed() || socket.is_shutdown() {
continue;
}
let tagged = HTTPContext::<true>::get_tagged_from_socket(socket);
if let Some(client) = tagged.client_mut() {
// May synchronously reach close_and_fail →
// dispatch_result_and_reset; do not touch
// `client` after this call.
client.resume_after_cert_check::<true>(socket);
}
}
uws::AnySocket::SocketTcp(socket) => {
if socket.is_closed() || socket.is_shutdown() {
continue;
}
let tagged = HTTPContext::<false>::get_tagged_from_socket(socket);
if let Some(client) = tagged.client_mut() {
// See Tls arm.
client.resume_after_cert_check::<false>(socket);
}
}
}
}
}
let len = queued_cert_check_resumes.len();
drop(queued_cert_check_resumes);
if len == 0 {
break;
}
bun_core::scoped_log!(HTTPThread, "drained {} queued cert check resumes", len);
}
}

fn drain_queued_http_response_body_drains(&mut self) {
loop {
// socket.close() can potentially be slow
Expand Down Expand Up @@ -823,6 +878,10 @@ impl HttpThread {
self.drain_queued_http_response_body_drains();
self.drain_queued_writes();
self.drain_queued_shutdowns();
// After shutdowns: an abort or cert-rejection scheduled in the same JS
// turn removes the abort-tracker entry first, so the resume becomes a
// no-op and the request is never transmitted after a same-tick abort.
self.drain_queued_cert_check_resumes();
h3::PendingConnect::drain_resolved();

for http in self.queued_threadlocal_proxy_derefs.drain(..) {
Expand Down Expand Up @@ -938,6 +997,17 @@ impl HttpThread {
self.wakeup();
}

pub fn schedule_cert_check_resume(&mut self, http: &AsyncHttp) {
bun_core::scoped_log!(HTTPThread, "scheduleCertCheckResume {}", http.async_http_id);
{
let _guard = self.queued_cert_check_resumes_lock.lock_guard();
self.queued_cert_check_resumes.push(CertCheckResumeMessage {
async_http_id: http.async_http_id,
});
}
self.wakeup();
}

pub fn schedule_request_write(&mut self, http: &AsyncHttp, kind: WriteMessageType) {
{
let _guard = self.queued_writes_lock.lock_guard();
Expand Down
10 changes: 10 additions & 0 deletions src/http/InternalState.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,15 @@ pub struct InternalStateFlags {
/// pool/close decision — that decision needs `hostname` still set to know
/// the handshake was verified against an override.
pub clear_hostname_on_redirect: bool,
/// Set when the TLS handshake completed but the user-supplied JS
/// `checkServerIdentity` callback has not yet approved the peer
/// certificate. While set, `on_writable` must not write any HTTP
/// application data to the socket and `on_data` must treat incoming
/// application data as unexpected. Cleared by
/// `HTTPClient::resume_after_cert_check` once the JS thread reports the
/// check passed (and implicitly by `InternalState::reset()` on every
/// redirect hop / failure, so each hop re-parks independently).
pub is_waiting_for_cert_check: bool,
}

impl InternalStateFlags {
Expand All @@ -81,6 +90,7 @@ impl InternalStateFlags {
is_libdeflate_fast_path_disabled: false,
resend_request_body_on_redirect: false,
clear_hostname_on_redirect: false,
is_waiting_for_cert_check: false,
}
}
}
Expand Down
10 changes: 10 additions & 0 deletions src/http/ProxyTunnel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,16 @@ fn on_data(ctx: *mut HTTPClient, decoded_data: &[u8]) {
return;
};
let _guard = ProxyTunnel::ref_scope(proxy_nn);
// While parked waiting for the JS `checkServerIdentity` verdict no request
// has been written through the tunnel, so any decrypted application data
// arriving here is unexpected.
if this.state.flags.is_waiting_for_cert_check {
scoped_log!(http_proxy_tunnel, "ProxyTunnel onData while parked");
this.state.pending_response = None;
// SAFETY: `this` dead (NLL); reenter via raw ptr.
ProxyTunnel::close_from_callback(proxy_nn, err!(UnexpectedData));
return;
}
match this.state.response_stage {
HTTPStage::Body => {
scoped_log!(http_proxy_tunnel, "ProxyTunnel onData body");
Expand Down
73 changes: 72 additions & 1 deletion src/http/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1466,7 +1466,13 @@ impl<'a> HTTPClient<'a> {

// check if we need to report the error (probably to `checkServerIdentity` was informed from JS side)
// this is the slow path
if self.signals.get(signals::Field::CertErrors) {
//
// The JS callback only applies to the *target's* certificate
// (Node semantics). For the HTTPS proxy's own handshake, use
// the native SAN check — a pinning callback written for the
// target would reject the proxy's certificate.
let is_proxy_certificate = allow_proxy_url && self.http_proxy.is_some();
if !is_proxy_certificate && self.signals.get(signals::Field::CertErrors) {
// clone the relevant data
// SAFETY: x509 is a live *mut X509 borrowed from cert_chain; null out-ptr requests size-only
let cert_size =
Expand All @@ -1485,6 +1491,14 @@ impl<'a> HTTPClient<'a> {
cert_error,
});

// Park the connection until the JS-side
// `checkServerIdentity` callback approves this
// certificate (gates `on_writable`/`on_data`; see the
// flag's doc comment). The JS thread resumes via
// `HTTPThread::schedule_cert_check_resume` on success,
// or schedules a shutdown on failure.
self.state.flags.is_waiting_for_cert_check = true;

// we inform the user that the cert is invalid
let ctx = self.get_ssl_ctx::<IS_SSL>();
self.progress_update::<IS_SSL>(ctx, socket);
Expand Down Expand Up @@ -1633,6 +1647,12 @@ impl<'a> HTTPClient<'a> {
/// `BUN_FEATURE_FLAG_EXPERIMENTAL_HTTP2_CLIENT` env var, or
/// `protocol: "http2"` on the fetch options.
pub fn can_offer_h2(&self) -> bool {
// The h2 session transmits from `attach()` without consulting the
// `is_waiting_for_cert_check` park gate, so requests with a JS
// `checkServerIdentity` callback stay on HTTP/1.1.
if self.signals.get(signals::Field::CertErrors) {
return false;
}
if self.flags.force_http1 {
return false;
}
Expand Down Expand Up @@ -1674,6 +1694,11 @@ impl<'a> HTTPClient<'a> {
/// specific protocol). When true, `start_()` consults `H3.AltSvc.lookup`
/// before opening TCP.
pub fn can_try_h3_alt_svc(&self) -> bool {
// The h3 client never routes through `check_server_identity`, so a JS
// `checkServerIdentity` callback could never run; stay on TCP.
if self.signals.get(signals::Field::CertErrors) {
return false;
}
if self.flags.force_http1 || self.flags.force_http2 {
return false;
}
Expand Down Expand Up @@ -2452,7 +2477,23 @@ impl<'a> HTTPClient<'a> {
}
}

// `can_offer_h2` refuses to advertise h2 when a JS `checkServerIdentity`
// callback is set, so `protocol: "http2"` + callback would handshake and
// then fail in `first_call` anyway. Fail up front instead.
if self.flags.force_http2 && self.signals.get(signals::Field::CertErrors) {
self.fail(err!(HTTP2Unsupported));
self.complete_connecting_process();
return;
}

if self.flags.force_http3 {
// h3 never routes through `check_server_identity`; refuse the
// combination instead of silently skipping the JS callback.
if self.signals.get(signals::Field::CertErrors) {
self.fail(err!(HTTP3Unsupported));
self.complete_connecting_process();
return;
}
if !IS_SSL {
self.fail(err!(HTTP3Unsupported));
self.complete_connecting_process();
Expand Down Expand Up @@ -2779,6 +2820,13 @@ impl<'a> HTTPClient<'a> {
proxy.on_writable::<IS_SSL>(socket);
}

// Parked until the JS `checkServerIdentity` callback approves the peer
// certificate: write no HTTP data. Kept below the tunnel flush so the
// handshake's final flight still reaches the wire while parked.
if self.state.flags.is_waiting_for_cert_check {
return;
}

match self.state.request_stage {
RequestStage::Pending | RequestStage::Headers | RequestStage::Opened => {
bun_core::scoped_log!(fetch, "sendInitialRequestPayload");
Expand Down Expand Up @@ -3018,6 +3066,19 @@ impl<'a> HTTPClient<'a> {
}
}

/// The JS-side `checkServerIdentity` callback approved the peer
/// certificate: clear the park flag and write the request that
/// `on_writable` has been holding back since the handshake completed.
pub fn resume_after_cert_check<const IS_SSL: bool>(&mut self, socket: HttpSocket<IS_SSL>) {
if !self.state.flags.is_waiting_for_cert_check {
// Never parked, or already resumed/reset by a redirect or failure.
return;
}
bun_core::scoped_log!(fetch, "resumeAfterCertCheck");
self.state.flags.is_waiting_for_cert_check = false;
self.on_writable::<true, IS_SSL>(socket);
}

pub fn close_and_fail<const IS_SSL: bool>(
&mut self,
err: bun_core::Error,
Expand Down Expand Up @@ -3293,6 +3354,16 @@ impl<'a> HTTPClient<'a> {
return;
}

// While parked waiting for the JS `checkServerIdentity` verdict, no
// request has been written, so any data is unexpected. Must stay below
// the proxy_tunnel dispatch above: a tunneled target's raw inner-TLS
// records must keep reaching the SSLWrapper while parked.
if self.state.flags.is_waiting_for_cert_check {
self.state.pending_response = None;
self.close_and_fail::<IS_SSL>(err!(UnexpectedData), socket);
return;
}

match self.state.response_stage {
ResponseStage::Pending | ResponseStage::Headers => {
self.handle_on_data_headers::<IS_SSL>(incoming_data, ctx, socket);
Expand Down
Loading
Loading