Skip to content
Merged
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
74 changes: 74 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,14 @@ pub struct ShutdownMessage {
pub async_http_id: u32,
}

/// The JS thread's `checkServerIdentity` callback approved the peer
/// certificate for this request; un-park the connection so the request is
/// finally written. Looked up through the abort tracker — a missing entry
/// means the connection already closed/failed and the resume is a no-op.
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 +788,53 @@ 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 {
// A missing tracker entry means the connection already
// closed, failed, or completed — the resume is a no-op.
// 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 +882,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 +1001,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
13 changes: 13 additions & 0 deletions src/http/ProxyTunnel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,19 @@ fn on_data(ctx: *mut HTTPClient, decoded_data: &[u8]) {
return;
};
let _guard = ProxyTunnel::ref_scope(proxy_nn);
// Defense in depth: this callback only ever sees *decrypted application
// data* (TLS handshake-layer records such as NewSessionTicket are consumed
// inside the SSL state machine and never reach here). While the connection
// is parked waiting for the JS `checkServerIdentity` verdict no request
// has been written through the tunnel, so the target has nothing
// legitimate to say.
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
115 changes: 114 additions & 1 deletion src/http/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1466,7 +1466,18 @@ 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 ever applies to the *target's*
// certificate (Node semantics: `checkServerIdentity` is a
// property of the destination TLS socket). When this is
// the outer handshake of an HTTPS proxy, `hostname` above
// is the proxy's hostname — fall through to the native
// SAN check against the proxy hostname instead of
// invoking the user callback with the proxy's certificate
// (a pinning callback written for the target would reject
// it and fail the whole fetch).
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 +1496,27 @@ impl<'a> HTTPClient<'a> {
cert_error,
});

// Park the connection until the JS-side
// `checkServerIdentity` callback approves this
// certificate. The flag gates `on_writable` (so the
// request line / headers / body are never written to
// an unverified peer) and `on_data` (so a server that
// speaks before being spoken to is rejected). The JS
// thread resumes the connection via
// `HTTPThread::schedule_cert_check_resume` on
// success, or schedules a shutdown on failure.
//
// Requests carrying a JS callback are pinned to
// HTTP/1.1: `can_offer_h2`, `can_try_h3_alt_svc`, and
// the `force_http3` branch of `start_` all bail out
// when the CertErrors signal is set, because the h2/h3
// session objects transmit without consulting this
// park gate. Pooled keep-alive sockets skip the
// handshake, so they never re-park; their certificate
// was validated (native SAN or JS callback) by
// whichever request first established the connection.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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 +1665,16 @@ 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 {
// A JS `checkServerIdentity` callback must run before any request
// bytes reach the wire. The h2 session transmits the preface and
// request frames from `attach()` without consulting the
// `is_waiting_for_cert_check` park gate, so keep such requests on
// HTTP/1.1 where the gate is enforced. This also blocks adopting or
// coalescing onto an existing h2 session, since both paths are gated
// on `can_offer_h2`.
if self.signals.get(signals::Field::CertErrors) {
return false;
}
Comment thread
Jarred-Sumner marked this conversation as resolved.
Resolved
if self.flags.force_http1 {
return false;
}
Expand Down Expand Up @@ -1674,6 +1716,13 @@ 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 performs its own QUIC handshake and never routes
// through `check_server_identity`, so a JS `checkServerIdentity`
// callback could never run before the request is transmitted. Stay on
// TCP for such requests.
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 +2501,30 @@ impl<'a> HTTPClient<'a> {
}
}

// `protocol: "http2"` combined with a JS `checkServerIdentity`
// callback can never succeed: `can_offer_h2` refuses to advertise h2
// when the CertErrors signal is set (the h2 session transmits without
// consulting the cert-check park gate), so the connection would
// complete a full TCP+TLS handshake, invoke the callback, and then
// fail in `first_call` anyway. Fail up front instead, mirroring the
// `force_http3` guard below.
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 {
// The h3 client performs its own QUIC handshake and never routes
// through `check_server_identity`, so a JS `checkServerIdentity`
// callback could never run before the request is transmitted.
// Refuse the combination instead of silently skipping the
// 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 +2851,16 @@ impl<'a> HTTPClient<'a> {
proxy.on_writable::<IS_SSL>(socket);
}

// The TLS handshake completed but the JS `checkServerIdentity`
// callback has not approved the peer certificate yet. Do not write any
// HTTP application data (request line, headers, body) until
// `resume_after_cert_check` clears the flag. The tunnel flush above
// still runs so already-encrypted TLS-layer bytes (the handshake's
// final flight) reach 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 +3100,24 @@ 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.
/// `on_writable`'s first statement is the Aborted check, and its
/// `request_stage` match handles both the direct (Pending/Opened) and
/// tunneled (ProxyHeaders) park points. ALPN/h2 resolution already ran in
/// `first_call` at handshake time, so it is not repeated here.
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). Nothing to do.
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 +3393,19 @@ impl<'a> HTTPClient<'a> {
return;
}

// Defense in depth: while parked waiting for the JS
// `checkServerIdentity` verdict, no request has been written, so a
// direct server has nothing legitimate to say. (This gate must stay
// BELOW the proxy_tunnel dispatch above — for a tunneled target the
// outer socket carries raw inner-TLS records that must keep reaching
// the SSLWrapper while parked; the tunnel's own decrypted-data
// callback has the equivalent gate.)
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