1use std::{
2 any::Any,
3 error::Error,
4 fmt, io,
5 net::SocketAddr,
6 sync::{
7 atomic::{AtomicU64, Ordering as AtomicOrdering},
8 Arc,
9 },
10 time::{Duration, Instant},
11};
12
13use subc_transport::{
14 authenticate_server, AuthError, AuthStage, DAEMON_ID_LEN, WATCHDOG_CLIENT_ROLE,
15};
16use tokio::{
17 io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufReader, BufWriter},
18 net::TcpListener,
19 sync::{mpsc, Semaphore},
20 task::{JoinHandle, JoinSet},
21 time::timeout,
22};
23use tracing::{debug, info, warn};
24
25use crate::{
26 forwarding::{CloseReason, ConnectionCloseReceiver},
27 observability::ConnectedClients,
28 read_frame,
29 router::{FrameSink, RouteCtx, Router},
30 write_frame, FrameIoError, RouterError,
31};
32
33pub const CONNECTION_EGRESS_BYTE_BUDGET: usize = subc_protocol::MAX_DELIVERED_FRAME_LEN;
52pub const CONNECTION_EGRESS_STALL_GRACE: Duration = Duration::from_millis(250);
59pub const CONNECTION_EGRESS_FRAME_CAP: usize = 32 * 1024;
68pub const MAX_PENDING_ROUTE_OPENS_PER_CONNECTION: usize = 8;
74pub(crate) const MAX_PENDING_ROUTE_BINDS_PER_TARGET: usize =
78 MAX_PENDING_ROUTE_OPENS_PER_CONNECTION * 2;
79pub const DEFAULT_AUTH_DEADLINE: Duration = Duration::from_secs(2);
80pub const DEFAULT_MAX_UNAUTHENTICATED_CONNECTIONS: usize = 256;
85const CLOSE_DRAIN_GRACE: Duration = Duration::from_secs(2);
86const PRE_AUTH_REJECT_LOG_INTERVAL: Duration = Duration::from_secs(1);
87
88struct ClientDeliveryGuard(FrameSink);
91
92impl Drop for ClientDeliveryGuard {
93 fn drop(&mut self) {
94 self.0.close_client_delivery();
95 }
96}
97
98#[derive(Clone, Copy, Debug)]
99enum PreAuthRejectStage {
100 WaitingForHandshakeSlot,
101 HandshakeDeadline,
102 InvalidProof,
103 MalformedMessage,
104 PeerClosed,
105 OtherAuthenticationFailure,
106}
107
108impl PreAuthRejectStage {
109 const fn index(self) -> usize {
110 match self {
111 Self::WaitingForHandshakeSlot => 0,
112 Self::HandshakeDeadline => 1,
113 Self::InvalidProof => 2,
114 Self::MalformedMessage => 3,
115 Self::PeerClosed => 4,
116 Self::OtherAuthenticationFailure => 5,
117 }
118 }
119
120 const fn stage(self) -> &'static str {
121 match self {
122 Self::WaitingForHandshakeSlot => "waiting_for_handshake_slot",
123 Self::HandshakeDeadline => "handshake_deadline",
124 Self::InvalidProof => "client_authentication",
125 Self::MalformedMessage => "malformed_message",
126 Self::PeerClosed => "peer_closed",
127 Self::OtherAuthenticationFailure => "authentication",
128 }
129 }
130
131 const fn reason(self) -> &'static str {
132 match self {
133 Self::WaitingForHandshakeSlot => "capacity_wait_timed_out",
134 Self::HandshakeDeadline => "handshake_deadline_expired",
135 Self::InvalidProof => "client_proof_mismatch",
136 Self::MalformedMessage => "malformed_or_oversized_message",
137 Self::PeerClosed => "peer_closed_before_authentication_completed",
138 Self::OtherAuthenticationFailure => "authentication_failed_before_routing",
139 }
140 }
141}
142
143#[derive(Debug)]
144struct PreAuthRejectRateLimit {
145 next_allowed_ns: AtomicU64,
146 suppressed: AtomicU64,
147}
148
149impl PreAuthRejectRateLimit {
150 const fn new() -> Self {
151 Self {
152 next_allowed_ns: AtomicU64::new(0),
153 suppressed: AtomicU64::new(0),
154 }
155 }
156}
157
158#[derive(Debug)]
161struct PreAuthRejectLog {
162 epoch: Instant,
163 limiter: PreAuthRejectLimiter,
164}
165
166impl PreAuthRejectLog {
167 fn new() -> Self {
168 Self {
169 epoch: Instant::now(),
170 limiter: PreAuthRejectLimiter::new(),
171 }
172 }
173}
174
175#[derive(Debug)]
177struct PreAuthRejectLimiter {
178 stages: [PreAuthRejectRateLimit; 6],
179}
180
181impl PreAuthRejectLimiter {
182 fn new() -> Self {
183 Self {
184 stages: std::array::from_fn(|_| PreAuthRejectRateLimit::new()),
185 }
186 }
187
188 fn allow_at(&self, stage: PreAuthRejectStage, now: Duration) -> Option<u64> {
189 let slot = &self.stages[stage.index()];
190 let now_ns = now.as_nanos().min(u64::MAX as u128) as u64;
191 let interval_ns = PRE_AUTH_REJECT_LOG_INTERVAL.as_nanos() as u64;
192 let mut next_allowed_ns = slot.next_allowed_ns.load(AtomicOrdering::Relaxed);
193
194 loop {
195 if now_ns < next_allowed_ns {
196 slot.suppressed.fetch_add(1, AtomicOrdering::Relaxed);
197 return None;
198 }
199
200 match slot.next_allowed_ns.compare_exchange_weak(
201 next_allowed_ns,
202 now_ns.saturating_add(interval_ns),
203 AtomicOrdering::Relaxed,
204 AtomicOrdering::Relaxed,
205 ) {
206 Ok(_) => return Some(slot.suppressed.swap(0, AtomicOrdering::Relaxed)),
207 Err(actual) => next_allowed_ns = actual,
208 }
209 }
210 }
211}
212
213fn log_pre_auth_rejection(
214 error: &ConnectionError,
215 peer_addr: SocketAddr,
216 elapsed: Duration,
217 now: Duration,
218 limiter: &PreAuthRejectLimiter,
219) {
220 let Some(stage) = error.pre_auth_reject_stage() else {
221 return;
222 };
223 let Some(suppressed_since_last) = limiter.allow_at(stage, now) else {
224 return;
225 };
226 let elapsed_ms = elapsed.as_millis().min(u64::MAX as u128) as u64;
227
228 info!(
229 peer_addr = %peer_addr,
230 elapsed_ms,
231 stage = stage.stage(),
232 reason = stage.reason(),
233 auth_stage = ?error.auth_stage(),
234 suppressed_since_last,
235 error = %error,
236 "subc TCP connection rejected before routing"
237 );
238}
239
240async fn handle_accepted_connection<S>(
241 stream: S,
242 router: Arc<Router>,
243 auth: ServerAuth,
244 peer_addr: SocketAddr,
245 accepted_at: Instant,
246) -> Result<(), ConnectionError>
247where
248 S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
249{
250 let reject_log = Arc::clone(&auth.pre_auth_reject_log);
251 let result = handle_connection(stream, router, auth).await;
252 if let Err(error) = &result {
253 if error.is_quiet_reject() {
254 log_pre_auth_rejection(
255 error,
256 peer_addr,
257 accepted_at.elapsed(),
258 reject_log.epoch.elapsed(),
259 &reject_log.limiter,
260 );
261 } else {
262 warn!(?peer_addr, error = %error, "subc connection ended with error");
263 }
264 }
265 result
266}
267
268#[derive(Clone)]
271pub struct ServerAuth {
272 key: Arc<[u8]>,
273 daemon_id: [u8; DAEMON_ID_LEN],
274 daemon_ver: Arc<str>,
275 deadline: Duration,
276 unauthenticated: Arc<Semaphore>,
277 connected_clients: ConnectedClients,
278 pre_auth_reject_log: Arc<PreAuthRejectLog>,
279}
280
281impl ServerAuth {
282 pub fn new(
283 key: Vec<u8>,
284 daemon_id: [u8; DAEMON_ID_LEN],
285 daemon_ver: impl Into<String>,
286 ) -> Self {
287 Self::with_limits(
288 key,
289 daemon_id,
290 daemon_ver,
291 DEFAULT_AUTH_DEADLINE,
292 DEFAULT_MAX_UNAUTHENTICATED_CONNECTIONS,
293 )
294 }
295
296 pub fn with_limits(
298 key: Vec<u8>,
299 daemon_id: [u8; DAEMON_ID_LEN],
300 daemon_ver: impl Into<String>,
301 deadline: Duration,
302 max_unauthenticated: usize,
303 ) -> Self {
304 Self {
305 key: Arc::from(key),
306 daemon_id,
307 daemon_ver: Arc::from(daemon_ver.into()),
308 deadline,
309 unauthenticated: Arc::new(Semaphore::new(max_unauthenticated.max(1))),
310 connected_clients: ConnectedClients::new(),
311 pre_auth_reject_log: Arc::new(PreAuthRejectLog::new()),
312 }
313 }
314
315 pub fn with_connected_clients(mut self, connected_clients: ConnectedClients) -> Self {
316 self.connected_clients = connected_clients;
317 self
318 }
319}
320
321impl fmt::Debug for ServerAuth {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 f.debug_struct("ServerAuth")
324 .field("key", &"<redacted>")
325 .field("daemon_id", &self.daemon_id)
326 .field("daemon_ver", &self.daemon_ver)
327 .field("deadline", &self.deadline)
328 .finish_non_exhaustive()
329 }
330}
331
332pub async fn serve_listener(
335 listener: TcpListener,
336 router: Arc<Router>,
337 auth: ServerAuth,
338) -> Result<(), ServerError> {
339 serve_listener_on(&listener, router, auth).await
340}
341
342async fn serve_listener_on(
343 listener: &TcpListener,
344 router: Arc<Router>,
345 auth: ServerAuth,
346) -> Result<(), ServerError> {
347 serve_listener_with_accept(listener.local_addr().ok(), router, auth, || {
348 listener.accept()
349 })
350 .await
351}
352
353async fn serve_listener_with_accept<A, F>(
354 local_addr: Option<SocketAddr>,
355 router: Arc<Router>,
356 auth: ServerAuth,
357 mut accept: A,
358) -> Result<(), ServerError>
359where
360 A: FnMut() -> F,
361 F: std::future::Future<Output = io::Result<(tokio::net::TcpStream, SocketAddr)>>,
362{
363 let mut admission = router.forwarding().upgrade_admission.subscribe();
364 loop {
365 let (stream, peer_addr) = match accept_when_unpaused(&mut admission, &mut accept).await {
366 Ok(accepted) => accepted,
367 Err(source) => {
368 let kind = source.kind();
369 let exhausted = accept_resource_exhausted(&source);
373 if matches!(
374 kind,
375 io::ErrorKind::ConnectionAborted
376 | io::ErrorKind::ConnectionReset
377 | io::ErrorKind::Interrupted
378 ) || exhausted
379 {
380 warn!(?local_addr, error = %source, "temporary TCP accept failure");
381 if exhausted {
382 tokio::time::sleep(Duration::from_millis(75)).await;
383 }
384 continue;
385 }
386 return Err(ServerError::Accept { local_addr, source });
387 }
388 };
389 let accepted_at = Instant::now();
390 if let Err(source) = stream.set_nodelay(true) {
406 warn!(?peer_addr, error = %source, "could not disable Nagle on accepted connection");
407 }
408 debug!(?peer_addr, ?local_addr, "accepted subc TCP connection");
409 let router = Arc::clone(&router);
410 let auth = auth.clone();
411 tokio::spawn(async move {
412 let _ = handle_accepted_connection(stream, router, auth, peer_addr, accepted_at).await;
413 });
414 }
415}
416
417#[cfg_attr(not(unix), allow(dead_code))]
418fn temporary_accept_failure(source: &io::Error) -> bool {
419 matches!(
420 source.kind(),
421 io::ErrorKind::ConnectionAborted
422 | io::ErrorKind::ConnectionReset
423 | io::ErrorKind::Interrupted
424 ) || accept_resource_exhausted(source)
425}
426
427fn accept_resource_exhausted(error: &io::Error) -> bool {
428 #[cfg(unix)]
433 {
434 use rustix::io::Errno;
435 let exhausted = [Errno::NFILE, Errno::MFILE, Errno::NOBUFS];
436 error
437 .raw_os_error()
438 .is_some_and(|code| exhausted.iter().any(|e| e.raw_os_error() == code))
439 }
440 #[cfg(windows)]
441 {
442 matches!(error.raw_os_error(), Some(10024 | 10055))
443 }
444 #[cfg(not(any(unix, windows)))]
445 {
446 let _ = error;
447 false
448 }
449}
450
451pub async fn serve_local_listener(
458 bound: crate::local_listener::BoundLocalListener,
459 router: Arc<Router>,
460 auth: ServerAuth,
461) -> Result<(), ServerError> {
462 match bound {
463 #[cfg(unix)]
464 crate::local_listener::BoundLocalListener::Unix { listener, path } => {
465 serve_unix_local(listener, path, router, auth).await
466 }
467 #[cfg(windows)]
468 crate::local_listener::BoundLocalListener::Windows {
469 pipe_name,
470 first_instance,
471 } => serve_pipe_local(pipe_name, first_instance, router, auth).await,
472 #[allow(unreachable_patterns)]
474 _ => Err(ServerError::NoListeners),
475 }
476}
477
478#[cfg(unix)]
479async fn serve_unix_local(
480 listener: std::os::unix::net::UnixListener,
481 path: std::path::PathBuf,
482 router: Arc<Router>,
483 auth: ServerAuth,
484) -> Result<(), ServerError> {
485 serve_unix_local_with_start(listener, path, router, auth, None::<fn()>).await
486}
487
488#[cfg(any(target_os = "linux", target_os = "macos"))]
489pub(crate) async fn serve_resumed_local_listener(
490 bound: crate::local_listener::BoundLocalListener,
491 router: Arc<Router>,
492 auth: ServerAuth,
493 on_accepting: impl FnOnce() + Send,
494) -> Result<(), ServerError> {
495 match bound {
496 crate::local_listener::BoundLocalListener::Unix { listener, path } => {
497 serve_unix_local_with_start(listener, path, router, auth, Some(on_accepting)).await
498 }
499 }
500}
501
502#[cfg(unix)]
503async fn serve_unix_local_with_start(
504 listener: std::os::unix::net::UnixListener,
505 path: std::path::PathBuf,
506 router: Arc<Router>,
507 auth: ServerAuth,
508 on_accepting: Option<impl FnOnce() + Send>,
509) -> Result<(), ServerError> {
510 let _release = SocketFileRelease(path.clone());
513 listener
514 .set_nonblocking(true)
515 .map_err(|source| local_accept_error(&path, source))?;
516 let listener = tokio::net::UnixListener::from_std(listener)
517 .map_err(|source| local_accept_error(&path, source))?;
518 let mut admission = router.forwarding().upgrade_admission.subscribe();
519 if let Some(on_accepting) = on_accepting {
522 on_accepting();
523 }
524 loop {
525 let (stream, _addr) = match accept_when_unpaused(&mut admission, || listener.accept()).await
526 {
527 Ok(accepted) => accepted,
528 Err(source) if temporary_accept_failure(&source) => {
529 warn!(error = %source, "temporary local-socket accept failure");
530 if accept_resource_exhausted(&source) {
531 tokio::time::sleep(Duration::from_millis(75)).await;
532 }
533 continue;
534 }
535 Err(source) => return Err(local_accept_error(&path, source)),
536 };
537 let (peer, diagnostic_pid) =
538 subc_os::local_peer::capture_unix_peer_with_diagnostic_pid(&stream);
539 let opener = diagnostic_pid.map(subc_os::local_peer::DiagnosticProcess::capture);
540 let router = Arc::clone(&router);
541 let auth = auth.clone();
542 tokio::spawn(async move {
543 let _ = handle_accepted_local_connection(stream, router, auth, peer, opener).await;
544 });
545 }
546}
547
548#[cfg(unix)]
549fn local_accept_error(endpoint: &std::path::Path, source: io::Error) -> ServerError {
550 ServerError::LocalAccept {
551 endpoint: endpoint.display().to_string(),
552 source,
553 }
554}
555
556#[cfg(unix)]
557struct SocketFileRelease(std::path::PathBuf);
558
559#[cfg(unix)]
560impl Drop for SocketFileRelease {
561 fn drop(&mut self) {
562 crate::local_listener::remove_unix_socket(&self.0);
563 }
564}
565
566#[cfg(windows)]
567async fn serve_pipe_local(
568 pipe_name: String,
569 first_instance: Option<tokio::net::windows::named_pipe::NamedPipeServer>,
570 router: Arc<Router>,
571 auth: ServerAuth,
572) -> Result<(), ServerError> {
573 let mut free = first_instance;
577 loop {
578 let server = match free.take() {
579 Some(server) => server,
580 None => create_pipe_instance(&pipe_name)?,
581 };
582 if let Err(source) = server.connect().await {
587 if temporary_accept_failure(&source) {
588 continue;
589 }
590 return Err(ServerError::LocalAccept {
591 endpoint: pipe_name.clone(),
592 source,
593 });
594 }
595 free = Some(create_pipe_instance(&pipe_name)?);
598 let router = Arc::clone(&router);
599 let auth = auth.clone();
600 let (peer, diagnostic_pid) =
603 match subc_os::local_peer::capture_pipe_client_with_diagnostic_pid(&server) {
604 Ok(capture) => capture,
605 Err(error) => {
606 warn!(%error, "refused a non-local named-pipe client on the local endpoint");
607 continue;
608 }
609 };
610 let opener = Some(subc_os::local_peer::DiagnosticProcess::capture(
611 diagnostic_pid,
612 ));
613 tokio::spawn(async move {
614 let _ = handle_accepted_local_connection(server, router, auth, peer, opener).await;
615 });
616 }
617}
618
619#[cfg(windows)]
620fn create_pipe_instance(
621 pipe_name: &str,
622) -> Result<tokio::net::windows::named_pipe::NamedPipeServer, ServerError> {
623 crate::local_listener::create_named_pipe_end(pipe_name).map_err(|source| {
624 ServerError::LocalAccept {
625 endpoint: pipe_name.to_owned(),
626 source,
627 }
628 })
629}
630
631async fn handle_accepted_local_connection<S>(
633 stream: S,
634 router: Arc<Router>,
635 auth: ServerAuth,
636 peer: subc_os::local_peer::CapturedPeer,
637 opener: Option<subc_os::local_peer::DiagnosticProcess>,
638) -> Result<(), ConnectionError>
639where
640 S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
641{
642 let result =
643 handle_connection_with_peer(stream, router, auth, LocalOrigin::Local, Some(peer), opener)
644 .await;
645 if let Err(error) = &result {
646 debug!(error = %error, "local-endpoint connection ended");
647 }
648 result
649}
650
651#[derive(Debug, Clone)]
654pub(crate) enum LocalOrigin {
655 Tcp,
656 Local,
657 RegistrationChannel(Arc<crate::supervise::RegistrationSpawn>),
658}
659
660pub async fn serve_listeners(
662 listeners: Vec<TcpListener>,
663 router: Arc<Router>,
664 auth: ServerAuth,
665) -> Result<(), ServerError> {
666 serve_shared_listeners(listeners.into_iter().map(Arc::new).collect(), router, auth).await
667}
668
669pub(crate) async fn serve_shared_listeners(
670 listeners: Vec<Arc<TcpListener>>,
671 router: Arc<Router>,
672 auth: ServerAuth,
673) -> Result<(), ServerError> {
674 if listeners.is_empty() {
675 return Err(ServerError::NoListeners);
676 }
677 router.install_registration_service(auth.clone());
678
679 let (tx, mut rx) = mpsc::channel(listeners.len());
680 let mut accept_tasks = AbortTasksOnDrop::default();
681 for listener in listeners {
682 let router = Arc::clone(&router);
683 let auth = auth.clone();
684 let tx = tx.clone();
685 accept_tasks.push(tokio::spawn(async move {
686 let result = serve_listener_on(&listener, router, auth).await;
687 let _ = tx.send(result).await;
688 }));
689 }
690 drop(tx);
691
692 rx.recv().await.unwrap_or(Ok(()))
693}
694
695#[derive(Default)]
696struct AbortTasksOnDrop {
697 handles: Vec<JoinHandle<()>>,
698}
699
700impl AbortTasksOnDrop {
701 fn push(&mut self, handle: JoinHandle<()>) {
702 self.handles.push(handle);
703 }
704}
705
706impl Drop for AbortTasksOnDrop {
707 fn drop(&mut self) {
708 for handle in &self.handles {
709 if !handle.is_finished() {
710 handle.abort();
711 }
712 }
713 }
714}
715
716#[derive(Debug)]
717enum ConnectionLoopExit {
718 PeerClosed,
719 CloseRequested(CloseReason),
720}
721
722#[derive(Default)]
723struct ConnectionTasks {
724 routes: JoinSet<Result<(), RouterError>>,
725 privileged: JoinSet<Result<(), RouterError>>,
726 activity: JoinSet<Result<(), RouterError>>,
727 #[cfg(test)]
728 refusal_before_send: Option<(
729 tokio::sync::oneshot::Sender<()>,
730 tokio::sync::oneshot::Receiver<()>,
731 )>,
732}
733
734impl ConnectionTasks {
735 async fn shutdown(&mut self) {
736 self.activity.abort_all();
737 self.routes.shutdown().await;
738 self.privileged.shutdown().await;
739 self.activity.shutdown().await;
741 }
742}
743
744pub async fn handle_connection<S>(
753 stream: S,
754 router: Arc<Router>,
755 auth: ServerAuth,
756) -> Result<(), ConnectionError>
757where
758 S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
759{
760 handle_connection_with_origin(stream, router, auth, LocalOrigin::Tcp).await
761}
762
763pub(crate) async fn handle_connection_with_origin<S>(
766 stream: S,
767 router: Arc<Router>,
768 auth: ServerAuth,
769 origin: LocalOrigin,
770) -> Result<(), ConnectionError>
771where
772 S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
773{
774 handle_connection_with_peer(stream, router, auth, origin, None, None).await
775}
776
777fn clone_tcp_socket(stream: &tokio::net::TcpStream) -> io::Result<std::net::TcpStream> {
778 #[cfg(unix)]
779 let socket = {
780 use std::os::fd::AsFd;
781 stream.as_fd().try_clone_to_owned()?
782 };
783 #[cfg(windows)]
784 let socket = {
785 use std::os::windows::io::AsSocket;
786 stream.as_socket().try_clone_to_owned()?
787 };
788 Ok(socket.into())
789}
790
791struct ShutdownTcpOnDrop(std::net::TcpStream);
792
793impl Drop for ShutdownTcpOnDrop {
794 fn drop(&mut self) {
795 let _ = self.0.shutdown(std::net::Shutdown::Both);
798 }
799}
800
801async fn handle_connection_with_peer<S>(
802 mut stream: S,
803 router: Arc<Router>,
804 auth: ServerAuth,
805 origin: LocalOrigin,
806 peer: Option<subc_os::local_peer::CapturedPeer>,
807 opener: Option<subc_os::local_peer::DiagnosticProcess>,
808) -> Result<(), ConnectionError>
809where
810 S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
811{
812 let channel_spawn = match &origin {
813 LocalOrigin::RegistrationChannel(spawn) => Some(spawn.clone()),
814 _ => None,
815 };
816 let mut upgrade_admission = router.forwarding().upgrade_admission.subscribe();
817 struct RetireRegistration(Option<Arc<crate::supervise::RegistrationSpawn>>);
818 impl Drop for RetireRegistration {
819 fn drop(&mut self) {
820 if let Some(spawn) = &self.0 {
821 spawn.retire_registration_channel();
822 }
823 }
824 }
825 let _registration_lifetime = RetireRegistration(channel_spawn.clone());
826 let channel_closed = async {
827 match &channel_spawn {
828 Some(spawn) => spawn.wait_closed().await,
829 None => std::future::pending().await,
830 }
831 };
832 tokio::pin!(channel_closed);
833 let endpoints = (&stream as &dyn Any)
836 .downcast_ref::<tokio::net::TcpStream>()
837 .and_then(|tcp| tcp.local_addr().ok().zip(tcp.peer_addr().ok()));
838 let permit = if channel_spawn.is_some() {
860 None
861 } else {
862 Some(tokio::select! {
863 biased;
864 _ = wait_for_upgrade_listener_pause(&mut upgrade_admission) => return Ok(()),
865 _ = &mut channel_closed => return Ok(()),
866 result = tokio::time::timeout(auth.deadline, auth.unauthenticated.clone().acquire_owned()) => match result {
867 Ok(Ok(permit)) => permit,
868 Ok(Err(_)) | Err(_) => {
869 let _ = stream.shutdown().await;
870 return Err(ConnectionError::UnauthenticatedCapacity);
871 }
872 }
873 })
874 };
875 let handshake_budget = channel_spawn.as_ref().map_or(auth.deadline, |spawn| {
876 spawn
877 .deadline()
878 .saturating_duration_since(tokio::time::Instant::now())
879 });
880 let authenticated = tokio::select! {
881 biased;
882 _ = wait_for_upgrade_listener_pause(&mut upgrade_admission) => return Ok(()),
883 _ = &mut channel_closed => { let _ = stream.shutdown().await; return Ok(()); },
884 result = authenticate_server(
885 &mut stream,
886 auth.key.as_ref(),
887 &auth.daemon_id,
888 auth.daemon_ver.as_ref(),
889 handshake_budget,
890 ) => result.map_err(ConnectionError::Auth)?,
891 };
892 drop(permit);
893
894 let _tcp_shutdown = (&stream as &dyn Any)
897 .downcast_ref::<tokio::net::TcpStream>()
898 .map(|tcp| clone_tcp_socket(tcp).map(ShutdownTcpOnDrop))
899 .transpose()
900 .map_err(|err| ConnectionError::FrameIo(FrameIoError::Io(err)))?;
901
902 let mut connection = router.begin_connection();
903 let connection_id = connection.id();
904 if let LocalOrigin::RegistrationChannel(spawn) = &origin {
905 spawn.bind(connection_id);
906 }
907 router.record_caller_endpoints(connection_id, endpoints);
908 use crate::control::RouteOpenerConnection;
909 match &origin {
910 LocalOrigin::Local => {
911 router.record_local_connection(connection_id);
912 router.record_route_opener(connection_id, RouteOpenerConnection::Local(opener));
913 }
914 LocalOrigin::Tcp => router.record_route_opener(connection_id, RouteOpenerConnection::Tcp),
915 LocalOrigin::RegistrationChannel(_) => {}
916 }
917 if let Some(peer) = peer {
918 router.record_captured_peer(connection_id, peer);
919 }
920 let _connected_client = (authenticated.role != WATCHDOG_CLIENT_ROLE)
935 .then(|| auth.connected_clients.open(connection_id));
936 let close_receiver = connection.take_close_receiver();
937 debug!(
938 connection_id = connection_id.get(),
939 "subc authenticated connection opened"
940 );
941
942 let (read_half, write_half) = tokio::io::split(stream);
943 let mut read_half = BufReader::new(read_half);
947 let (egress, rx) = connection_egress();
948 let delivery_guard = ClientDeliveryGuard(egress.clone());
949 let writer = tokio::spawn(drain_writer(write_half, rx));
950
951 let ctx = RouteCtx {
952 connection_id,
953 egress: egress.clone(),
954 };
955
956 let mut tasks = ConnectionTasks::default();
957 let registration_expired = async {
958 match &channel_spawn {
959 Some(spawn) => spawn.registration_expired().await,
960 None => std::future::pending().await,
961 }
962 };
963 let loop_result = tokio::select! {
964 _ = registration_expired => Ok(ConnectionLoopExit::CloseRequested(CloseReason::new("registration_timeout", "module did not complete HELLO before its spawn deadline"))),
965 _ = &mut channel_closed => Ok(ConnectionLoopExit::CloseRequested(CloseReason::new("registration_channel_closed", "the supervised launch ended"))),
966 result = connection_loop(
967 &mut read_half,
968 Arc::clone(&router),
969 ctx.clone(),
970 close_receiver,
971 &mut tasks,
972 origin,
973 ) => result,
974 };
975
976 if let Some(spawn) = &channel_spawn {
981 spawn.retire_registration_channel();
982 }
983 drop(delivery_guard);
984 tasks.shutdown().await;
994
995 drop(ctx);
996 drop(egress);
997 drop(connection);
998
999 let close_reason = match &loop_result {
1000 Ok(ConnectionLoopExit::CloseRequested(reason)) => Some(reason.to_string()),
1001 Ok(ConnectionLoopExit::PeerClosed) | Err(_) => None,
1002 };
1003 let writer_result = finish_connection_writer(writer, connection_id.get()).await;
1004
1005 let result = if let Some(reason) = close_reason.as_deref() {
1006 match writer_result {
1007 Some(Ok(Ok(()))) | None => Ok(()),
1008 Some(Ok(Err(writer_err))) => {
1009 debug!(
1010 connection_id = connection_id.get(),
1011 close_reason = reason,
1012 writer_error = %writer_err,
1013 "writer failed after requested connection close"
1014 );
1015 Ok(())
1016 }
1017 Some(Err(join_err)) => {
1018 warn!(
1019 connection_id = connection_id.get(),
1020 close_reason = reason,
1021 join_error = %join_err,
1022 "writer task join failed after requested connection close"
1023 );
1024 Ok(())
1025 }
1026 }
1027 } else {
1028 match (loop_result, writer_result) {
1029 (Err(loop_err), Some(Ok(Ok(()))) | None) => Err(loop_err),
1030 (Err(loop_err), Some(Ok(Err(writer_err)))) => {
1031 warn!(
1032 connection_id = connection_id.get(),
1033 writer_error = %writer_err,
1034 "writer failed while closing after connection error"
1035 );
1036 Err(loop_err)
1037 }
1038 (Err(loop_err), Some(Err(join_err))) => {
1039 warn!(
1040 connection_id = connection_id.get(),
1041 join_error = %join_err,
1042 "writer task join failed while closing after connection error"
1043 );
1044 Err(loop_err)
1045 }
1046 (Ok(ConnectionLoopExit::PeerClosed), Some(Ok(Ok(()))) | None) => Ok(()),
1047 (Ok(ConnectionLoopExit::PeerClosed), Some(Ok(Err(writer_err)))) => {
1048 Err(ConnectionError::FrameIo(writer_err))
1049 }
1050 (Ok(ConnectionLoopExit::PeerClosed), Some(Err(join_err))) => Err(join_err),
1051 (Ok(ConnectionLoopExit::CloseRequested(_)), _) => {
1052 unreachable!("close requests are handled before normal writer result matching")
1053 }
1054 }
1055 };
1056
1057 match &result {
1058 Ok(()) => {
1059 if let Some(reason) = close_reason.as_deref() {
1060 debug!(
1061 connection_id = connection_id.get(),
1062 close_reason = reason,
1063 "subc connection closed by request"
1064 );
1065 } else {
1066 debug!(
1067 connection_id = connection_id.get(),
1068 "subc connection closed"
1069 );
1070 }
1071 }
1072 Err(err) => debug!(
1073 connection_id = connection_id.get(),
1074 error = %err,
1075 "subc connection exited with error"
1076 ),
1077 }
1078
1079 result
1080}
1081
1082async fn finish_connection_writer(
1083 mut writer: JoinHandle<Result<(), FrameIoError>>,
1084 connection_id: u64,
1085) -> Option<Result<Result<(), FrameIoError>, ConnectionError>> {
1086 match timeout(CLOSE_DRAIN_GRACE, &mut writer).await {
1089 Ok(result) => Some(result.map_err(ConnectionError::WriterTask)),
1090 Err(_) => {
1091 warn!(
1092 connection_id,
1093 grace = ?CLOSE_DRAIN_GRACE,
1094 "connection writer did not drain during teardown; aborting writer task"
1095 );
1096 writer.abort();
1097 let _ = writer.await;
1098 None
1099 }
1100 }
1101}
1102
1103#[cfg(all(test, unix))]
1104pub(crate) fn config_test_connection_loop(
1105 router: Arc<Router>,
1106) -> (
1107 crate::ConnectionId,
1108 tokio::io::DuplexStream,
1109 JoinHandle<Result<(), ConnectionError>>,
1110) {
1111 let mut connection = router.begin_connection();
1112 let id = connection.id();
1113 let close = connection.take_close_receiver();
1114 router.record_local_connection(id);
1115 let (client, server) = tokio::io::duplex(64 * 1024);
1116 let (mut read, mut write) = tokio::io::split(server);
1117 let (sender, mut outgoing) = tokio::sync::mpsc::channel::<crate::router::OutboundFrame>(8);
1118 let ctx = RouteCtx {
1119 connection_id: id,
1120 egress: crate::FrameSink::new(sender),
1121 };
1122 let writer = tokio::spawn(async move {
1123 while let Some(mut outbound) = outgoing.recv().await {
1124 if crate::write_frame(&mut write, &outbound.frame)
1125 .await
1126 .is_err()
1127 || tokio::io::AsyncWriteExt::flush(&mut write).await.is_err()
1128 {
1129 break;
1130 }
1131 if let Some(flushed) = outbound.flushed.take() {
1132 let _ = flushed.send(());
1133 }
1134 }
1135 });
1136 let task = tokio::spawn(async move {
1137 let mut tasks = ConnectionTasks::default();
1138 let result = connection_loop(
1139 &mut read,
1140 router,
1141 ctx.clone(),
1142 close,
1143 &mut tasks,
1144 LocalOrigin::Local,
1145 )
1146 .await;
1147 tasks.shutdown().await;
1148 drop(ctx);
1149 drop(connection);
1150 writer.abort();
1151 let _ = writer.await;
1152 result.map(|_| ())
1153 });
1154 (id, client, task)
1155}
1156
1157async fn connection_loop<R>(
1158 read_half: &mut R,
1159 router: Arc<Router>,
1160 ctx: RouteCtx,
1161 mut close_receiver: ConnectionCloseReceiver,
1162 tasks: &mut ConnectionTasks,
1163 origin: LocalOrigin,
1164) -> Result<ConnectionLoopExit, ConnectionError>
1165where
1166 R: AsyncRead + Unpin,
1167{
1168 #[cfg(test)]
1169 let mut refusal_before_send = tasks.refusal_before_send.take();
1170 let ConnectionTasks {
1171 routes: route_open_tasks,
1172 privileged: privileged_tasks,
1173 activity: activity_tasks,
1174 ..
1175 } = tasks;
1176 let forwarding = router.forwarding();
1177 let mut upgrade_admission = forwarding.upgrade_admission.subscribe();
1178 let (phase, _live_reader) = forwarding.start_upgrade_reader(ctx.connection_id);
1179 close_receiver.initialize_phase(phase);
1180 loop {
1181 while let Some(result) = activity_tasks.try_join_next() {
1182 finish_route_open_task(result)?;
1183 }
1184 while let Some(result) = privileged_tasks.try_join_next() {
1185 finish_route_open_task(result)?;
1186 }
1187 while let Some(result) = route_open_tasks.try_join_next() {
1188 finish_route_open_task(result)?;
1189 }
1190
1191 let read = read_frame(&mut *read_half);
1194 tokio::pin!(read);
1195 close_receiver.acknowledge_reader();
1196 let frame = loop {
1197 let can_read = !close_receiver.phase().clients_frozen();
1198 tokio::select! {
1199 biased;
1200 signal = close_receiver.next_signal() => {
1201 match signal {
1202 Ok(None) => close_receiver.acknowledge_reader(),
1203 Ok(Some(reason)) => return Ok(ConnectionLoopExit::CloseRequested(reason)),
1204 Err(error) => return Ok(ConnectionLoopExit::CloseRequested(close_reason(Err(error)))),
1205 }
1206 }
1207 _ = wait_for_upgrade_listener_pause(&mut upgrade_admission), if matches!(&origin, LocalOrigin::RegistrationChannel(spawn) if !spawn.registered()) => {
1208 return Ok(ConnectionLoopExit::PeerClosed);
1209 }
1210 result = route_open_tasks.join_next(), if !route_open_tasks.is_empty() => {
1211 finish_route_open_task(
1212 result.expect("a non-empty route.open JoinSet has a next task")
1213 )?;
1214 }
1215 result = activity_tasks.join_next(), if !activity_tasks.is_empty() => {
1216 finish_route_open_task(result.expect("non-empty activity task set"))?;
1217 }
1218 result = privileged_tasks.join_next(), if !privileged_tasks.is_empty() => {
1219 finish_route_open_task(result.expect("non-empty privileged task set"))?;
1220 }
1221 result = &mut read, if can_read => {
1222 break match result.map_err(ConnectionError::FrameIo)? {
1223 Some(frame) => frame,
1224 None => return Ok(ConnectionLoopExit::PeerClosed),
1225 };
1226 }
1227 }
1228 };
1229
1230 if ctx.egress.ingress_terminal() {
1233 return Ok(ConnectionLoopExit::PeerClosed);
1234 }
1235 let first = ctx.egress.first_ingress_frame();
1236 let hello = frame.header.ty == subc_protocol::FrameType::Hello;
1237 if hello && upgrade_admission.borrow().listeners_paused() {
1238 return Ok(ConnectionLoopExit::PeerClosed);
1239 }
1240 if frame.header.channel == 0 && frame.header.ty == subc_protocol::FrameType::Goodbye {
1241 activity_tasks.shutdown().await;
1242 }
1243 if let Some((code, message)) = hello_transport_refusal(&origin, &frame) {
1244 ctx.egress.terminate_ingress();
1245 let refusal = crate::control::control_error_frame(&frame, code, message)
1246 .map_err(ConnectionError::Router)?;
1247 let send_result = tokio::select! {
1251 close = &mut close_receiver => {
1252 return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1253 }
1254 result = router.observe_connection_wait(&ctx, "reply_egress", send_refusal(&ctx.egress, refusal)) => result,
1255 };
1256 send_result.map_err(ConnectionError::Router)?;
1257 return Ok(ConnectionLoopExit::PeerClosed);
1258 }
1259
1260 if let LocalOrigin::RegistrationChannel(spawn) = &origin {
1261 let hello = frame.header.ty == subc_protocol::FrameType::Hello;
1262 if (!spawn.registered() && !hello) || (spawn.registered() && hello) {
1263 ctx.egress.terminate_ingress();
1264 spawn.retire_registration_channel();
1265 return Ok(ConnectionLoopExit::PeerClosed);
1266 }
1267 }
1268
1269 let control_dispatch = ControlDispatch::of(&frame);
1270 if control_dispatch == ControlDispatch::Activity {
1271 if activity_tasks.len() >= 128 {
1274 let response = crate::control::control_error_frame(
1275 &frame,
1276 subc_control::ACTIVITY_UNAVAILABLE,
1277 "activity queue full",
1278 )
1279 .map_err(ConnectionError::Router)?;
1280 let send_result = tokio::select! {
1281 close = &mut close_receiver => {
1282 return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1283 }
1284 result = router.observe_connection_wait(&ctx, "reply_egress", ctx.egress.send(response)) => result,
1285 };
1286 send_result.map_err(ConnectionError::Router)?;
1287 } else {
1288 let reservation = router.reserve_activity_subscription(&ctx, &frame);
1291 let task_router = Arc::clone(&router);
1292 let task_ctx = ctx.clone();
1293 activity_tasks.spawn(async move {
1294 let _reservation = reservation;
1295 route_open_tail(&task_router, task_ctx, frame, Instant::now(), first).await
1296 });
1297 }
1298 continue;
1299 }
1300
1301 if let Some(target_module_id) = (control_dispatch == ControlDispatch::RouteOpen)
1302 .then(|| router.route_open_target(&frame))
1303 .flatten()
1304 {
1305 while let Some(result) = route_open_tasks.try_join_next() {
1309 finish_route_open_task(result)?;
1310 }
1311
1312 if route_open_tasks.len() >= MAX_PENDING_ROUTE_OPENS_PER_CONNECTION {
1313 let refusal = router
1316 .route_open_capacity_refusal(
1317 &ctx,
1318 &frame,
1319 &target_module_id,
1320 route_open_tasks.len(),
1321 MAX_PENDING_ROUTE_OPENS_PER_CONNECTION,
1322 )
1323 .map_err(ConnectionError::Router)?;
1324 let send_result = tokio::select! {
1325 close = &mut close_receiver => {
1326 return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1327 }
1328 result = router.observe_connection_wait(&ctx, "reply_egress", ctx.egress.send(refusal)) => result,
1329 };
1330 send_result.map_err(ConnectionError::Router)?;
1331 continue;
1332 }
1333
1334 let task_router = router.clone().track_cutover_task();
1335 let task_ctx = ctx.clone();
1336 let dispatch_started_at = Instant::now();
1339 route_open_tasks.spawn(async move {
1340 route_open_tail(
1341 task_router.owner(),
1342 task_ctx,
1343 frame,
1344 dispatch_started_at,
1345 first,
1346 )
1347 .await
1348 });
1349 continue;
1350 }
1351
1352 if router.defers_config_approval(&frame) || router.defers_privileged_control(&ctx, &frame) {
1353 let reservation = match router.reserve_config_approval(&ctx, &frame) {
1354 Ok(reservation) => reservation,
1355 Err(error) => {
1356 ctx.egress
1357 .send(
1358 crate::control::control_error_body_frame(
1359 &frame,
1360 subc_protocol::ErrorBody {
1361 code: error.code,
1362 message: error.detail,
1363 detail: None,
1364 },
1365 )
1366 .map_err(ConnectionError::Router)?,
1367 )
1368 .await
1369 .map_err(ConnectionError::Router)?;
1370 continue;
1371 }
1372 };
1373 let task_router = Arc::clone(&router);
1376 let task_ctx = ctx.clone();
1377 let started = Instant::now();
1378 privileged_tasks.spawn(async move {
1379 let _reservation = reservation;
1382 route_open_tail(&task_router, task_ctx, frame, started, first).await
1383 });
1384 continue;
1385 }
1386
1387 let route_result = tokio::select! {
1390 biased;
1391 _ = wait_for_upgrade_listener_pause(&mut upgrade_admission), if hello => {
1392 return Ok(ConnectionLoopExit::PeerClosed);
1393 }
1394 close = &mut close_receiver => {
1395 return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1396 }
1397 result = router.route_for_connection_ingress(&ctx, frame, None, first) => result,
1398 };
1399
1400 if let Err(err) = route_result {
1401 if let Some(reply) = router.prepare_routed_error(&err) {
1402 #[cfg(test)]
1403 if let Some((built, release)) = refusal_before_send.take() {
1404 let _ = built.send(());
1405 let _ = release.await;
1406 }
1407 warn!(
1408 connection_id = ctx.connection_id.get(),
1409 error = %err,
1410 "routing failure recovered with ERROR frame"
1411 );
1412 let send_result = tokio::select! {
1413 biased;
1414 close = &mut close_receiver => {
1415 return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1416 }
1417 result = router.observe_connection_wait(&ctx, "reply_egress", reply.send(&ctx.egress)) => result,
1418 };
1419 send_result.map_err(ConnectionError::Router)?;
1420 } else {
1421 debug!(
1422 connection_id = ctx.connection_id.get(),
1423 error = %err,
1424 "fatal routing failure"
1425 );
1426 return Err(ConnectionError::Router(err));
1427 }
1428 }
1429 }
1430}
1431
1432async fn accept_when_unpaused<F, T>(
1433 admission: &mut tokio::sync::watch::Receiver<crate::control::upgrade_in_place::Admission>,
1434 mut accept: impl FnMut() -> F,
1435) -> T
1436where
1437 F: std::future::Future<Output = T>,
1438{
1439 loop {
1440 let _ = admission.wait_for(|phase| !phase.listeners_paused()).await;
1441 tokio::select! {
1442 biased;
1443 _ = wait_for_upgrade_listener_pause(admission) => {},
1444 accepted = accept() => {
1445 let _ = admission.wait_for(|phase| !phase.listeners_paused()).await;
1448 return accepted;
1449 }
1450 }
1451 }
1452}
1453
1454async fn wait_for_upgrade_listener_pause(
1455 admission: &mut tokio::sync::watch::Receiver<crate::control::upgrade_in_place::Admission>,
1456) {
1457 let _ = admission.wait_for(|phase| phase.listeners_paused()).await;
1458}
1459
1460fn hello_transport_refusal(
1461 origin: &LocalOrigin,
1462 frame: &crate::Frame,
1463) -> Option<(&'static str, &'static str)> {
1464 use crate::supervise::resume_hello;
1465 if frame.header.ty != subc_protocol::FrameType::Hello {
1466 return None;
1467 }
1468 let local = matches!(origin, LocalOrigin::Local);
1469 let value = serde_json::from_slice::<serde_json::Value>(&frame.body).ok();
1470 if let Some(value) = value
1471 .as_ref()
1472 .filter(|value| resume_hello::has_resume_token(value))
1473 {
1474 if !local
1475 || !cfg!(any(target_os = "macos", target_os = "linux"))
1476 || frame.header.channel != 0
1477 || resume_hello::parse_resume_hash(value).is_none()
1478 {
1479 return Some((resume_hello::REFUSED, resume_hello::REFUSAL_MESSAGE));
1480 }
1481 } else if local {
1482 return Some((
1483 crate::local_listener::LOCAL_ENDPOINT_CLIENTS_ONLY,
1484 "the local endpoint serves clients only; modules register over TCP",
1485 ));
1486 }
1487 None
1488}
1489
1490async fn send_refusal(sink: &FrameSink, frame: crate::Frame) -> Result<(), RouterError> {
1493 #[cfg(unix)]
1494 {
1495 sink.send_flushed(frame).await
1496 }
1497 #[cfg(not(unix))]
1498 {
1499 sink.send(frame).await
1500 }
1501}
1502
1503#[derive(Clone, Copy, PartialEq, Eq)]
1504enum ControlDispatch {
1505 Activity,
1506 RouteOpen,
1507 Other,
1508}
1509
1510impl ControlDispatch {
1511 fn of(frame: &crate::Frame) -> Self {
1512 if frame.header.channel != 0 || frame.header.ty != subc_protocol::FrameType::Request {
1513 return Self::Other;
1514 }
1515 #[derive(serde::Deserialize)]
1516 struct Op<'a> {
1517 #[serde(borrow)]
1518 op: std::borrow::Cow<'a, str>,
1519 }
1520 let Ok(op) = serde_json::from_slice::<Op<'_>>(&frame.body) else {
1521 return Self::Other;
1522 };
1523 match op.op.as_ref() {
1524 subc_control::ops::ACTIVITY_RECORD
1525 | subc_control::ops::ACTIVITY_QUERY
1526 | subc_control::ops::ACTIVITY_SUBSCRIBE => Self::Activity,
1527 subc_control::ops::ROUTE_OPEN => Self::RouteOpen,
1528 _ => Self::Other,
1529 }
1530 }
1531}
1532
1533async fn route_open_tail(
1534 router: &Router,
1535 ctx: RouteCtx,
1536 frame: crate::Frame,
1537 dispatch_started_at: Instant,
1538 first: bool,
1539) -> Result<(), RouterError> {
1540 match router
1541 .route_for_connection_ingress(&ctx, frame, Some(dispatch_started_at), first)
1542 .await
1543 {
1544 Ok(()) => Ok(()),
1545 Err(err) => {
1546 let Some(reply) = router.prepare_routed_error(&err) else {
1547 return Err(err);
1548 };
1549 warn!(
1550 connection_id = ctx.connection_id.get(),
1551 error = %err,
1552 "routing failure recovered with ERROR frame"
1553 );
1554 router
1555 .observe_connection_wait(&ctx, "reply_egress", reply.send(&ctx.egress))
1556 .await
1557 }
1558 }
1559}
1560
1561fn finish_route_open_task(
1562 result: Result<Result<(), RouterError>, tokio::task::JoinError>,
1563) -> Result<(), ConnectionError> {
1564 match result {
1565 Ok(Ok(())) => Ok(()),
1566 Ok(Err(err)) => Err(ConnectionError::Router(err)),
1567 Err(err) => Err(ConnectionError::Router(RouterError::backend(
1568 0,
1569 0,
1570 format!("route.open task failed: {err}"),
1571 ))),
1572 }
1573}
1574
1575fn close_reason(
1576 result: Result<CloseReason, tokio::sync::oneshot::error::RecvError>,
1577) -> CloseReason {
1578 result.unwrap_or_else(|_| {
1579 CloseReason::new(
1580 "close_registry_dropped",
1581 "connection close registration was dropped without a reason",
1582 )
1583 })
1584}
1585
1586pub(crate) fn connection_egress() -> (FrameSink, mpsc::Receiver<crate::router::OutboundFrame>) {
1590 let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(CONNECTION_EGRESS_FRAME_CAP);
1591 (
1592 FrameSink::with_byte_budget(tx, CONNECTION_EGRESS_BYTE_BUDGET),
1593 rx,
1594 )
1595}
1596
1597pub(crate) async fn drain_writer<W>(
1598 write_half: W,
1599 mut rx: mpsc::Receiver<crate::router::OutboundFrame>,
1600) -> Result<(), FrameIoError>
1601where
1602 W: AsyncWrite + Unpin,
1603{
1604 let mut writer = BufWriter::new(write_half);
1605 while let Some(outbound) = rx.recv().await {
1606 write_outbound(&mut writer, outbound).await?;
1607 while let Ok(outbound) = rx.try_recv() {
1608 write_outbound(&mut writer, outbound).await?;
1609 }
1610 writer.flush().await.map_err(FrameIoError::Io)?;
1611 }
1612 writer.flush().await.map_err(FrameIoError::Io)?;
1613 Ok(())
1614}
1615
1616async fn write_outbound<W>(
1623 writer: &mut BufWriter<W>,
1624 outbound: crate::router::OutboundFrame,
1625) -> Result<(), FrameIoError>
1626where
1627 W: AsyncWrite + Unpin,
1628{
1629 const SLOW_REPLY_QUEUE: Duration = Duration::from_millis(1000);
1630 let queued = outbound.enqueued_at.elapsed();
1631 let charge = outbound.charge;
1634 if let Some(charge) = &charge {
1635 charge.taken_by_writer();
1636 }
1637 let frame = outbound.frame;
1638 #[cfg(all(
1639 feature = "test-support",
1640 any(target_os = "linux", target_os = "macos")
1641 ))]
1642 if let Some(gate) = outbound.fixture_flush_gate {
1643 crate::control::upgrade_in_place::wait_at_gate(&gate, 3)
1644 .await
1645 .map_err(FrameIoError::Io)?;
1646 }
1647 if frame.header.channel == 0 && queued >= SLOW_REPLY_QUEUE {
1648 let write_started = std::time::Instant::now();
1649 let result = write_frame(writer, &frame).await;
1650 tracing::warn!(
1651 corr = frame.header.corr,
1652 queued_ms = queued.as_millis() as u64,
1653 write_ms = write_started.elapsed().as_millis() as u64,
1654 "slow control reply write"
1655 );
1656 result?;
1657 } else {
1658 write_frame(writer, &frame).await?;
1659 }
1660 if let Some(flushed) = outbound.flushed {
1661 writer.flush().await.map_err(FrameIoError::Io)?;
1665 let _ = flushed.send(());
1666 }
1667 Ok(())
1668}
1669
1670#[cfg(all(test, unix))]
1671#[tokio::test]
1672async fn shutdown_notice_ack_waits_for_socket_flush() {
1673 let (socket, mut peer) = tokio::io::duplex(1);
1674 let (tx, rx) = mpsc::channel(1);
1675 let sink = FrameSink::new(tx);
1676 let writer = tokio::spawn(drain_writer(socket, rx));
1677 let frame = crate::Frame::build(
1678 subc_protocol::FrameType::Push,
1679 subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
1680 0,
1681 0,
1682 0,
1683 b"notice".to_vec(),
1684 )
1685 .unwrap();
1686 let send = sink.send_flushed(frame);
1687 tokio::pin!(send);
1688 assert!(
1689 timeout(Duration::from_millis(20), &mut send).await.is_err(),
1690 "queueing bytes is not a socket flush acknowledgement"
1691 );
1692 let (sent, received) = timeout(Duration::from_secs(1), async {
1693 tokio::join!(&mut send, read_frame(&mut peer))
1694 })
1695 .await
1696 .unwrap();
1697 sent.unwrap();
1698 assert_eq!(received.unwrap().unwrap().body, b"notice");
1699 writer.abort();
1700}
1701
1702#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
1703#[tokio::test]
1704async fn close_requested_reader_stays_counted_while_its_request_is_parked() {
1705 closing_reader_accounts_for_dropped_request(false).await;
1706}
1707
1708#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
1709#[tokio::test]
1710async fn closing_reader_accounts_for_a_refusal_built_before_close() {
1711 closing_reader_accounts_for_dropped_request(true).await;
1712}
1713
1714#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
1715async fn closing_reader_accounts_for_dropped_request(already_built_refusal: bool) {
1716 use crate::{
1717 forwarding::{DataRoute, DataRouteState, RouteBindRelayOutcome},
1718 ConnectionId,
1719 };
1720 use subc_protocol::{
1721 manifest::Concurrency, Flags, Frame, FrameType, Priority, PROTOCOL_VERSION,
1722 };
1723
1724 let router = Arc::new(Router::default());
1725 let forwarding = router.forwarding();
1726 let mut connection = router.begin_connection();
1727 let (reader_sink, mut reader_replies) = connection_egress();
1728 let ctx = RouteCtx {
1729 connection_id: connection.id(),
1730 egress: reader_sink,
1731 };
1732 let (module_tx, mut module_rx) = mpsc::channel(1);
1733 let sink = FrameSink::new(module_tx);
1734 let module = ConnectionId::new(15_000);
1735 forwarding
1736 .register_module_connection(
1737 module,
1738 "blocked-module".into(),
1739 PROTOCOL_VERSION,
1740 Concurrency::ModuleManaged,
1741 sink.clone(),
1742 )
1743 .unwrap();
1744 let (client_sink, mut client_rx) = connection_egress();
1745 let route = forwarding
1746 .begin_route_bind_relay_for_test(ctx.connection_id, client_sink, 80, "blocked-module")
1747 .unwrap();
1748 forwarding
1749 .complete_pending_relay(module, route.corr, RouteBindRelayOutcome::Accepted)
1750 .unwrap();
1751 assert_eq!(client_rx.try_recv().unwrap().header.corr, 80);
1752 let flags = Flags::new(false, Priority::Passive, false);
1753 sink.try_send(Frame::build(FrameType::Push, flags, 0, 0, 81, vec![]).unwrap())
1754 .unwrap();
1755 let (mut peer, mut reader) = tokio::io::duplex(4096);
1756 let request = Frame::build(
1757 FrameType::Request,
1758 flags,
1759 route.client_channel,
1760 route.client_epoch,
1761 82,
1762 vec![],
1763 )
1764 .unwrap();
1765 crate::write_frame(&mut peer, &request).await.unwrap();
1766
1767 let mut tasks = ConnectionTasks::default();
1768 let refusal_pause = already_built_refusal.then(|| {
1769 let (built, seen) = tokio::sync::oneshot::channel();
1770 let (resume, wait) = tokio::sync::oneshot::channel();
1771 tasks.refusal_before_send = Some((built, wait));
1772 (seen, resume)
1773 });
1774 let loop_future = connection_loop(
1775 &mut reader,
1776 router,
1777 ctx.clone(),
1778 connection.take_close_receiver(),
1779 &mut tasks,
1780 LocalOrigin::Tcp,
1781 );
1782 tokio::pin!(loop_future);
1783 std::future::poll_fn(|cx| {
1784 assert!(std::future::Future::poll(loop_future.as_mut(), cx).is_pending());
1785 std::task::Poll::Ready(())
1786 })
1787 .await;
1788 let DataRoute::Client(DataRouteState::Bound(binding)) = forwarding
1789 .lookup_data_route(ctx.connection_id, route.client_channel, route.client_epoch)
1790 .unwrap()
1791 else {
1792 panic!("expected bound route");
1793 };
1794 assert_eq!(
1795 binding.flow.in_flight(),
1796 1,
1797 "the reader decoded the request and took credit before blocking on the writer"
1798 );
1799
1800 forwarding.upgrade_refusals.begin();
1801 let resume = if let Some((mut seen, resume)) = refusal_pause {
1802 forwarding.set_upgrade_admission(crate::control::upgrade_in_place::Admission::Fenced);
1803 std::future::poll_fn(|cx| {
1804 assert!(std::future::Future::poll(loop_future.as_mut(), cx).is_pending());
1805 std::task::Poll::Ready(())
1806 })
1807 .await;
1808 seen.try_recv()
1809 .expect("the reader already built its upgrade refusal");
1810 Some(resume)
1811 } else {
1812 None
1813 };
1814 assert!(forwarding.request_connection_close(
1815 ctx.connection_id,
1816 CloseReason::new("test_close", "reader is still dispatching")
1817 ));
1818 let readers = forwarding.freeze_upgrade_readers();
1820 let remaining = readers.subscribe();
1821 assert_eq!(
1822 *remaining.borrow(),
1823 1,
1824 "requesting close does not acknowledge the reader's current frame"
1825 );
1826 if let Some(resume) = resume {
1827 resume.send(()).unwrap();
1828 }
1829 assert!(matches!(
1830 loop_future.await.unwrap(),
1831 ConnectionLoopExit::CloseRequested(_)
1832 ));
1833 assert_eq!(
1834 *remaining.borrow(),
1835 0,
1836 "the reader has returned and no longer owns its frame"
1837 );
1838 assert_eq!(module_rx.try_recv().unwrap().header.corr, 81);
1839 assert!(module_rx.try_recv().is_err());
1840 assert!(reader_replies.try_recv().is_err());
1841 let tracked = usize::from(already_built_refusal);
1842 assert_eq!(
1843 forwarding.upgrade_refusals.receipt_for_test(&readers).await,
1844 (tracked, tracked, true),
1845 "only a daemon fence refusal already built before the close is counted"
1846 );
1847}
1848
1849#[cfg(all(test, unix))]
1850#[tokio::test]
1851async fn activity_and_other_control_ops_skip_the_typed_route_open_probe() {
1852 use subc_protocol::{Flags, Frame, FrameType, Priority};
1853 let router = Arc::new(Router::default());
1854 let (_id, mut client, server) = config_test_connection_loop(router.clone());
1855 let request = |corr, body: serde_json::Value| {
1856 Frame::build(
1857 FrameType::Request,
1858 Flags::new(false, Priority::Passive, false),
1859 0,
1860 0,
1861 corr,
1862 serde_json::to_vec(&body).unwrap(),
1863 )
1864 .unwrap()
1865 };
1866 for (i, op) in [
1867 "activity.query",
1868 "activity.record",
1869 "activity.subscribe",
1870 "server.describe",
1871 ]
1872 .into_iter()
1873 .enumerate()
1874 {
1875 let corr = 100 + i as u64;
1876 crate::write_frame(&mut client, &request(corr, serde_json::json!({"op":op})))
1877 .await
1878 .unwrap();
1879 assert_eq!(
1880 timeout(Duration::from_secs(2), read_frame(&mut client))
1881 .await
1882 .unwrap()
1883 .unwrap()
1884 .unwrap()
1885 .header
1886 .corr,
1887 corr
1888 );
1889 assert_eq!(
1890 router.route_open_probes_for_test(),
1891 0,
1892 "{op} must not reach the typed route.open probe"
1893 );
1894 }
1895 crate::write_frame(
1896 &mut client,
1897 &request(
1898 200,
1899 serde_json::json!({
1900 "op":"route.open",
1901 "target":subc_protocol::RouteTarget::ToolProvider { module_id: "no-module".into() },
1902 "identity":subc_protocol::BindIdentity::new("probe-fixture", "route"),
1903 }),
1904 ),
1905 )
1906 .await
1907 .unwrap();
1908 assert_eq!(
1909 timeout(Duration::from_secs(2), read_frame(&mut client))
1910 .await
1911 .unwrap()
1912 .unwrap()
1913 .unwrap()
1914 .header
1915 .corr,
1916 200
1917 );
1918 assert_eq!(router.route_open_probes_for_test(), 1);
1919 drop(client);
1920 server.await.unwrap().unwrap();
1921}
1922
1923#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
1924#[tokio::test]
1925async fn relayed_health_error_with_upgrade_body_does_not_enter_refusal_accounting() {
1926 use crate::{ConnectionId, ControlHandler, ForwardingTable, Registry};
1927 use subc_protocol::{
1928 manifest::{Concurrency, ModuleManifest},
1929 ErrorBody, Flags, Frame, FrameType, Priority, PROTOCOL_VERSION,
1930 };
1931 let registry = Arc::new(Registry::default());
1932 let forwarding = Arc::new(ForwardingTable::default());
1933 let router = Arc::new(Router::with_control_handler(Arc::new(
1934 ControlHandler::with_forwarding(registry.clone(), forwarding.clone()),
1935 )));
1936 let module_id = "receipt-probe";
1937 let module_connection = ConnectionId::new(400);
1938 let (module_sink, mut module_reader) = connection_egress();
1939 registry
1940 .register_with_control_ops(
1941 ModuleManifest::builder(module_id, "1.0.0").build(),
1942 PROTOCOL_VERSION,
1943 module_connection,
1944 vec!["health.check".into()],
1945 )
1946 .unwrap();
1947 forwarding
1948 .register_module_connection(
1949 module_connection,
1950 module_id.into(),
1951 PROTOCOL_VERSION,
1952 Concurrency::ModuleManaged,
1953 module_sink.clone(),
1954 )
1955 .unwrap();
1956 let (client_sink, mut replies) = connection_egress();
1957 let flags = Flags::new(false, Priority::Passive, false);
1958 let make = |ty, corr, body| Frame::build(ty, flags, 0, 0, corr, body).unwrap();
1959 let health = make(
1960 FrameType::Request,
1961 501,
1962 serde_json::to_vec(
1963 &serde_json::json!({"op":"supervisor.health_probe","module_id":module_id}),
1964 )
1965 .unwrap(),
1966 );
1967 let active = tokio::spawn({
1968 let router = router.clone();
1969 async move {
1970 router
1971 .route_for_connection(
1972 &RouteCtx {
1973 connection_id: ConnectionId::new(401),
1974 egress: client_sink,
1975 },
1976 health,
1977 )
1978 .await
1979 }
1980 });
1981 let probe = timeout(Duration::from_secs(2), module_reader.recv())
1982 .await
1983 .unwrap()
1984 .unwrap();
1985 forwarding.upgrade_refusals.begin();
1986 forwarding.set_upgrade_admission(crate::control::upgrade_in_place::Admission::Fenced);
1987 let error = ErrorBody::module_reloading_for_daemon_upgrade("module-authored error");
1988 router
1989 .route_for_connection(
1990 &RouteCtx {
1991 connection_id: module_connection,
1992 egress: module_sink,
1993 },
1994 make(
1995 FrameType::Error,
1996 probe.header.corr,
1997 serde_json::to_vec(&error).unwrap(),
1998 ),
1999 )
2000 .await
2001 .unwrap();
2002 active.await.unwrap().unwrap();
2003 let reply = replies.try_recv().unwrap();
2004 assert_eq!(reply.header.corr, 501);
2005 assert_eq!(
2006 serde_json::from_slice::<ErrorBody>(&reply.body).unwrap(),
2007 error
2008 );
2009 assert!(
2010 reply.flushed.is_none(),
2011 "a module-authored error is not a tracked fence refusal"
2012 );
2013 assert_eq!(
2014 forwarding
2015 .upgrade_refusals
2016 .receipt_for_test(&Default::default())
2017 .await,
2018 (0, 0, true)
2019 );
2020}
2021
2022#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
2023#[tokio::test]
2024async fn upgrade_fence_refuses_health_and_flushes_queued_request_before_goodbye() {
2025 use crate::control::upgrade_in_place::Admission;
2026 use crate::{ControlHandler, ForwardingTable, Registry};
2027 use subc_protocol::{Flags, Frame, FrameType, Priority};
2028
2029 let (socket, mut peer) = tokio::io::duplex(1);
2030 let (sink, queued) = connection_egress();
2031 let writer = tokio::spawn(drain_writer(socket, queued));
2032 let frame = |ty, channel, corr, body| {
2033 Frame::build(
2034 ty,
2035 Flags::new(false, Priority::Passive, false),
2036 channel,
2037 0,
2038 corr,
2039 body,
2040 )
2041 .unwrap()
2042 };
2043 sink.try_send(frame(FrameType::Request, 1, 33, b"request".to_vec()))
2044 .unwrap();
2045
2046 let forwarding = Arc::new(ForwardingTable::default());
2047 forwarding.set_upgrade_admission(Admission::Fenced);
2048 let control = ControlHandler::with_forwarding(Arc::new(Registry::default()), forwarding);
2049 let (egress, _replies) = connection_egress();
2050 let probe = frame(
2051 FrameType::Request,
2052 0,
2053 44,
2054 serde_json::to_vec(
2055 &serde_json::json!({"op":"supervisor.health_probe", "module_id":"module"}),
2056 )
2057 .unwrap(),
2058 );
2059 let replies = control
2060 .handle_control_frame_timed(
2061 &RouteCtx {
2062 connection_id: crate::ConnectionId::new(15),
2063 egress,
2064 },
2065 probe,
2066 None,
2067 )
2068 .await
2069 .unwrap();
2070 let refused: subc_protocol::ErrorBody = serde_json::from_slice(&replies[0].body).unwrap();
2071 assert_eq!(refused.code, "upgrade_busy");
2072
2073 let notices = async {
2074 sink.send_flushed(frame(FrameType::Push, 0, 0, b"upgrading".to_vec()))
2075 .await
2076 .unwrap();
2077 sink.send_flushed(frame(FrameType::Goodbye, 0, 0, vec![]))
2078 .await
2079 .unwrap();
2080 };
2081 tokio::pin!(notices);
2082 std::future::poll_fn(|cx| {
2083 assert!(std::future::Future::poll(notices.as_mut(), cx).is_pending());
2084 std::task::Poll::Ready(())
2085 })
2086 .await;
2087 let (_, ()) = timeout(Duration::from_secs(2), async {
2088 tokio::join!(
2089 async {
2090 for expected in [FrameType::Request, FrameType::Push, FrameType::Goodbye] {
2091 assert_eq!(
2092 read_frame(&mut peer).await.unwrap().unwrap().header.ty,
2093 expected
2094 );
2095 }
2096 },
2097 &mut notices
2098 )
2099 })
2100 .await
2101 .unwrap();
2102 writer.abort();
2103}
2104
2105#[derive(Debug)]
2106pub enum ServerError {
2107 NoListeners,
2108 Accept {
2109 local_addr: Option<SocketAddr>,
2110 source: io::Error,
2111 },
2112 LocalAccept {
2115 endpoint: String,
2116 source: io::Error,
2117 },
2118}
2119
2120impl fmt::Display for ServerError {
2121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2122 match self {
2123 Self::NoListeners => write!(f, "no TCP listeners were provided"),
2124 Self::Accept { local_addr, source } => match local_addr {
2125 Some(addr) => write!(f, "failed to accept TCP connection on {addr}: {source}"),
2126 None => write!(f, "failed to accept TCP connection: {source}"),
2127 },
2128 Self::LocalAccept { endpoint, source } => {
2129 write!(f, "local endpoint {endpoint} failed: {source}")
2130 }
2131 }
2132 }
2133}
2134
2135impl Error for ServerError {
2136 fn source(&self) -> Option<&(dyn Error + 'static)> {
2137 match self {
2138 Self::Accept { source, .. } | Self::LocalAccept { source, .. } => Some(source),
2139 Self::NoListeners => None,
2140 }
2141 }
2142}
2143
2144#[derive(Debug)]
2145pub enum ConnectionError {
2146 Auth(AuthError),
2147 UnauthenticatedCapacity,
2148 FrameIo(FrameIoError),
2149 Router(RouterError),
2150 WriterTask(tokio::task::JoinError),
2151}
2152
2153impl ConnectionError {
2154 fn is_quiet_reject(&self) -> bool {
2155 matches!(self, Self::Auth(_) | Self::UnauthenticatedCapacity)
2156 }
2157
2158 fn pre_auth_reject_stage(&self) -> Option<PreAuthRejectStage> {
2159 match self {
2160 Self::UnauthenticatedCapacity => Some(PreAuthRejectStage::WaitingForHandshakeSlot),
2161 Self::Auth(AuthError::Timeout { .. }) => Some(PreAuthRejectStage::HandshakeDeadline),
2162 Self::Auth(
2163 AuthError::InvalidClientAuth
2164 | AuthError::InvalidServerProof
2165 | AuthError::DaemonIdMismatch,
2166 ) => Some(PreAuthRejectStage::InvalidProof),
2167 Self::Auth(AuthError::MessageTooLarge { .. } | AuthError::JsonDecode { .. }) => {
2168 Some(PreAuthRejectStage::MalformedMessage)
2169 }
2170 Self::Auth(AuthError::UnexpectedEof { .. }) => Some(PreAuthRejectStage::PeerClosed),
2171 Self::Auth(AuthError::Io { source, .. })
2172 if matches!(
2173 source.kind(),
2174 io::ErrorKind::BrokenPipe
2175 | io::ErrorKind::ConnectionAborted
2176 | io::ErrorKind::ConnectionReset
2177 | io::ErrorKind::UnexpectedEof
2178 ) =>
2179 {
2180 Some(PreAuthRejectStage::PeerClosed)
2181 }
2182 Self::Auth(_) => Some(PreAuthRejectStage::OtherAuthenticationFailure),
2183 Self::FrameIo(_) | Self::Router(_) | Self::WriterTask(_) => None,
2184 }
2185 }
2186
2187 fn auth_stage(&self) -> Option<AuthStage> {
2188 match self {
2189 Self::Auth(
2190 AuthError::Io { stage, .. }
2191 | AuthError::Timeout { stage, .. }
2192 | AuthError::UnexpectedEof { stage, .. }
2193 | AuthError::MessageTooLarge { stage, .. }
2194 | AuthError::JsonEncode { stage, .. }
2195 | AuthError::JsonDecode { stage, .. },
2196 ) => Some(*stage),
2197 Self::Auth(
2198 AuthError::Random(_)
2199 | AuthError::KeyTooShort { .. }
2200 | AuthError::InvalidServerProof
2201 | AuthError::DaemonIdMismatch
2202 | AuthError::InvalidClientAuth,
2203 )
2204 | Self::UnauthenticatedCapacity
2205 | Self::FrameIo(_)
2206 | Self::Router(_)
2207 | Self::WriterTask(_) => None,
2208 }
2209 }
2210}
2211
2212impl fmt::Display for ConnectionError {
2213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2214 match self {
2215 Self::Auth(err) => write!(f, "connection auth failed: {err}"),
2216 Self::UnauthenticatedCapacity => write!(
2217 f,
2218 "too many concurrent unauthenticated subc TCP connections"
2219 ),
2220 Self::FrameIo(err) => write!(f, "frame connection error: {err}"),
2221 Self::Router(err) => write!(f, "router connection error: {err}"),
2222 Self::WriterTask(err) => write!(f, "connection writer task failed: {err}"),
2223 }
2224 }
2225}
2226
2227impl Error for ConnectionError {
2228 fn source(&self) -> Option<&(dyn Error + 'static)> {
2229 match self {
2230 Self::Auth(err) => Some(err),
2231 Self::FrameIo(err) => Some(err),
2232 Self::Router(err) => Some(err),
2233 Self::WriterTask(err) => Some(err),
2234 Self::UnauthenticatedCapacity => None,
2235 }
2236 }
2237}
2238
2239#[cfg(all(test, unix))]
2240#[path = "server/peer_liveness_test.rs"]
2241mod peer_liveness_test;
2242
2243#[cfg(test)]
2244mod tests {
2245 use std::{
2246 future::Future,
2247 pin::Pin,
2248 sync::atomic::{AtomicUsize, Ordering},
2249 task::{Context, Poll},
2250 };
2251
2252 use super::*;
2253 use serde::{de::DeserializeOwned, Serialize};
2254 use subc_protocol::{
2255 DecodeError, ErrorBody, Flags, FrameType, Priority, HEADER_LEN, PROTOCOL_VERSION,
2256 };
2257 use tokio::io::{duplex, AsyncReadExt, AsyncWriteExt, ReadBuf};
2258
2259 use subc_transport::{
2260 authenticate_client, compute_proof, ClientAuth, ClientHello, ConnectionInfo, Endpoint,
2261 ServerProof, CLIENT_AUTH_DOMAIN, NONCE_LEN, SCHEMA_VERSION,
2262 };
2263
2264 use crate::{ControlHandler, EchoBackend, Frame, ReadStage, Registry};
2265
2266 const TEST_DEADLINE: Duration = Duration::from_secs(2);
2267 const TEST_DAEMON_VER: &str = "test-subc-server";
2268
2269 #[test]
2270 fn null_resume_token_is_an_ordinary_hello() {
2271 let frame = Frame::build(
2272 FrameType::Hello,
2273 Flags::new(false, Priority::Interactive, false),
2274 0,
2275 0,
2276 1,
2277 serde_json::to_vec(&serde_json::json!({
2278 "protocol_ver": PROTOCOL_VERSION,
2279 "manifest": subc_protocol::manifest::ModuleManifest::builder("fresh", "1.0.0")
2280 .build(),
2281 "resume_token": null,
2282 }))
2283 .unwrap(),
2284 )
2285 .unwrap();
2286 assert_eq!(hello_transport_refusal(&LocalOrigin::Tcp, &frame), None);
2287 assert_eq!(
2288 hello_transport_refusal(&LocalOrigin::Local, &frame)
2289 .unwrap()
2290 .0,
2291 crate::local_listener::LOCAL_ENDPOINT_CLIENTS_ONLY
2292 );
2293 let control = ControlHandler::new(Arc::new(Registry::default()));
2294 let replies = control
2295 .handle_control(crate::ConnectionId::new(1), frame)
2296 .unwrap();
2297 assert_eq!(replies[0].header.ty, FrameType::HelloAck);
2298 }
2299
2300 #[test]
2304 fn egress_budget_is_the_published_delivered_frame_limit() {
2305 assert_eq!(
2306 CONNECTION_EGRESS_BYTE_BUDGET,
2307 subc_protocol::MAX_DELIVERED_FRAME_LEN
2308 );
2309 }
2310
2311 struct ObservedStream {
2312 inner: tokio::io::DuplexStream,
2313 write_blocked: Arc<tokio::sync::Notify>,
2314 dropped: Arc<AtomicUsize>,
2315 read_error: Option<tokio::sync::oneshot::Receiver<()>>,
2316 }
2317
2318 impl AsyncRead for ObservedStream {
2319 fn poll_read(
2320 mut self: Pin<&mut Self>,
2321 cx: &mut Context<'_>,
2322 buf: &mut ReadBuf<'_>,
2323 ) -> Poll<io::Result<()>> {
2324 if let Some(receiver) = self.read_error.as_mut() {
2325 match Pin::new(receiver).poll(cx) {
2326 Poll::Ready(Ok(())) => {
2327 self.read_error = None;
2328 return Poll::Ready(Err(io::ErrorKind::ConnectionReset.into()));
2329 }
2330 Poll::Ready(Err(_)) => self.read_error = None,
2331 Poll::Pending => {}
2332 }
2333 }
2334 Pin::new(&mut self.inner).poll_read(cx, buf)
2335 }
2336 }
2337
2338 impl AsyncWrite for ObservedStream {
2339 fn poll_write(
2340 mut self: Pin<&mut Self>,
2341 cx: &mut Context<'_>,
2342 buf: &[u8],
2343 ) -> Poll<io::Result<usize>> {
2344 let result = Pin::new(&mut self.inner).poll_write(cx, buf);
2345 if result.is_pending() {
2346 self.write_blocked.notify_one();
2347 }
2348 result
2349 }
2350
2351 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
2352 Pin::new(&mut self.inner).poll_flush(cx)
2353 }
2354
2355 fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
2356 Pin::new(&mut self.inner).poll_shutdown(cx)
2357 }
2358 }
2359
2360 impl Drop for ObservedStream {
2361 fn drop(&mut self) {
2362 self.dropped.fetch_add(1, Ordering::SeqCst);
2363 }
2364 }
2365
2366 struct BlockedWriterConnection {
2367 client: tokio::io::DuplexStream,
2368 server: JoinHandle<Result<(), ConnectionError>>,
2369 stream_dropped: Arc<AtomicUsize>,
2370 read_error: Option<tokio::sync::oneshot::Sender<()>>,
2371 router: Arc<Router>,
2372 }
2373
2374 impl BlockedWriterConnection {
2375 async fn new() -> Self {
2376 let (mut client, inner) = duplex(256);
2377 let write_blocked = Arc::new(tokio::sync::Notify::new());
2378 let stream_dropped = Arc::new(AtomicUsize::new(0));
2379 let (read_error, receiver) = tokio::sync::oneshot::channel();
2380 let stream = ObservedStream {
2381 inner,
2382 write_blocked: Arc::clone(&write_blocked),
2383 dropped: Arc::clone(&stream_dropped),
2384 read_error: Some(receiver),
2385 };
2386 let (auth, conn) = test_auth();
2387 let router = echo_router();
2388 let server = tokio::spawn(handle_connection(stream, Arc::clone(&router), auth));
2389 authenticate(&mut client, &conn).await;
2390
2391 let _ = timeout(Duration::ZERO, write_blocked.notified()).await;
2394 write_frame(&mut client, &request(7, 1, &[b'x'; 1024]))
2395 .await
2396 .unwrap();
2397 timeout(TEST_DEADLINE, write_blocked.notified())
2398 .await
2399 .expect("writer should block on the unread echo reply");
2400 assert!(!server.is_finished());
2401 assert_eq!(stream_dropped.load(Ordering::SeqCst), 0);
2402 Self {
2403 client,
2404 server,
2405 stream_dropped,
2406 read_error: Some(read_error),
2407 router,
2408 }
2409 }
2410
2411 async fn finish(&mut self) -> Result<(), ConnectionError> {
2412 let started = tokio::time::Instant::now();
2413 let result = timeout(CLOSE_DRAIN_GRACE + Duration::from_secs(1), &mut self.server)
2414 .await
2415 .expect("connection teardown exceeded writer drain grace plus margin")
2416 .expect("connection task should not panic");
2417 assert!(started.elapsed() >= CLOSE_DRAIN_GRACE);
2418 assert_eq!(
2419 self.stream_dropped.load(Ordering::SeqCst),
2420 1,
2421 "writer must release its stream half before teardown completes"
2422 );
2423 result
2424 }
2425
2426 fn request_close(&self) {
2427 assert!(self.router.forwarding().request_connection_close(
2429 crate::registry::ConnectionId::new(1),
2430 CloseReason::new("test_close", "test requested close"),
2431 ));
2432 }
2433 }
2434
2435 #[tokio::test(start_paused = true)]
2436 async fn peer_eof_bounds_blocked_writer_teardown() {
2437 let mut connection = BlockedWriterConnection::new().await;
2438 connection.client.shutdown().await.unwrap();
2441 connection.finish().await.unwrap();
2442 }
2443
2444 #[tokio::test]
2445 async fn tcp_teardown_sends_eof_while_another_endpoint_copy_is_open() {
2446 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2447 let mut peer = tokio::net::TcpStream::connect(listener.local_addr().unwrap())
2448 .await
2449 .unwrap();
2450 let (stream, _) = listener.accept().await.unwrap();
2451 let inherited_copy = clone_tcp_socket(&stream).unwrap();
2454 let (auth, conn) = test_auth();
2455 let router = echo_router();
2456 let server = tokio::spawn(handle_connection(stream, Arc::clone(&router), auth));
2457 authenticate(&mut peer, &conn).await;
2458 write_frame(&mut peer, &request(7, 1, b"ready"))
2459 .await
2460 .unwrap();
2461 read_frame(&mut peer).await.unwrap().unwrap();
2462 assert!(router.forwarding().request_connection_close(
2463 crate::registry::ConnectionId::new(1),
2464 CloseReason::new("test_close", "test requested close"),
2465 ));
2466 timeout(TEST_DEADLINE, server)
2467 .await
2468 .unwrap()
2469 .unwrap()
2470 .unwrap();
2471 let mut byte = [0];
2472 assert_eq!(
2473 timeout(TEST_DEADLINE, peer.read(&mut byte))
2474 .await
2475 .expect("teardown must send EOF without waiting for inherited descriptors")
2476 .unwrap(),
2477 0,
2478 );
2479 drop(inherited_copy);
2480 }
2481
2482 #[tokio::test(start_paused = true)]
2483 async fn read_error_bounds_blocked_writer_teardown() {
2484 let mut connection = BlockedWriterConnection::new().await;
2485 connection.read_error.take().unwrap().send(()).unwrap();
2486 let error = connection.finish().await.unwrap_err();
2487 assert!(matches!(
2488 error,
2489 ConnectionError::FrameIo(FrameIoError::Io(error))
2490 if error.kind() == io::ErrorKind::ConnectionReset
2491 ));
2492 }
2493
2494 #[tokio::test(start_paused = true)]
2495 async fn close_requested_bounds_blocked_writer_teardown() {
2496 let mut connection = BlockedWriterConnection::new().await;
2497 connection.request_close();
2498 connection.finish().await.unwrap();
2499 }
2500
2501 #[tokio::test(start_paused = true)]
2502 async fn close_requested_flushes_queued_reply_before_grace() {
2503 let mut connection = BlockedWriterConnection::new().await;
2504 connection.request_close();
2505 let started = tokio::time::Instant::now();
2506 let reply = timeout(CLOSE_DRAIN_GRACE, read_frame(&mut connection.client))
2507 .await
2508 .expect("queued reply should flush before the grace expires")
2509 .unwrap()
2510 .unwrap();
2511 assert_eq!(reply.body, vec![b'x'; 1024]);
2512 timeout(CLOSE_DRAIN_GRACE, &mut connection.server)
2513 .await
2514 .unwrap()
2515 .unwrap()
2516 .unwrap();
2517 assert!(started.elapsed() < CLOSE_DRAIN_GRACE);
2518 assert_eq!(connection.stream_dropped.load(Ordering::SeqCst), 1);
2519 }
2520
2521 #[tokio::test]
2526 async fn stale_queued_control_reply_logs_slow_reply_write() {
2527 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
2528 let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(4);
2529 let reply = Frame::build_with_version(
2530 PROTOCOL_VERSION,
2531 FrameType::Error,
2532 Flags::new(false, Priority::Interactive, false),
2533 0,
2534 0,
2535 7,
2536 serde_json::to_vec(&ErrorBody {
2537 code: "test".into(),
2538 message: "reply".into(),
2539 detail: None,
2540 })
2541 .expect("body encodes"),
2542 )
2543 .expect("frame builds");
2544 tx.send(crate::router::OutboundFrame {
2545 frame: reply,
2546 enqueued_at: std::time::Instant::now() - Duration::from_millis(1500),
2547 flushed: None,
2548 #[cfg(all(
2549 feature = "test-support",
2550 any(target_os = "linux", target_os = "macos")
2551 ))]
2552 fixture_flush_gate: None,
2553 charge: None,
2554 })
2555 .await
2556 .expect("queued");
2557 drop(tx);
2558 let (write_half, mut read_half) = duplex(64 * 1024);
2559 drain_writer(write_half, rx).await.expect("writer drains");
2560 let mut sink = Vec::new();
2561 read_half.read_to_end(&mut sink).await.expect("read");
2562 assert!(!sink.is_empty(), "frame reached the socket");
2563 let captured = crate::router::test_log::captured_logs(&logs);
2564 assert!(
2565 captured.contains("slow control reply write") && captured.contains("corr=7"),
2566 "expected slow reply WARN naming corr, got: {captured}"
2567 );
2568 let queued_ms: u64 = captured
2569 .split("queued_ms=")
2570 .nth(1)
2571 .and_then(|s| s.split_whitespace().next())
2572 .and_then(|s| s.parse().ok())
2573 .expect("queued_ms present");
2574 assert!(
2575 queued_ms >= 1500,
2576 "queued_ms reflects residency: {queued_ms}"
2577 );
2578 }
2579
2580 #[tokio::test]
2584 async fn fresh_control_and_stale_data_frames_log_nothing() {
2585 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
2586 let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(4);
2587 let control = Frame::build_with_version(
2588 PROTOCOL_VERSION,
2589 FrameType::Error,
2590 Flags::new(false, Priority::Interactive, false),
2591 0,
2592 0,
2593 8,
2594 serde_json::to_vec(&ErrorBody {
2595 code: "test".into(),
2596 message: "fresh".into(),
2597 detail: None,
2598 })
2599 .expect("body encodes"),
2600 )
2601 .expect("frame builds");
2602 tx.send(crate::router::OutboundFrame {
2603 frame: control,
2604 enqueued_at: std::time::Instant::now(),
2605 flushed: None,
2606 #[cfg(all(
2607 feature = "test-support",
2608 any(target_os = "linux", target_os = "macos")
2609 ))]
2610 fixture_flush_gate: None,
2611 charge: None,
2612 })
2613 .await
2614 .expect("queued");
2615 let data = Frame::build_with_version(
2616 PROTOCOL_VERSION,
2617 FrameType::Error,
2618 Flags::new(false, Priority::Interactive, false),
2619 9,
2620 1,
2621 9,
2622 serde_json::to_vec(&ErrorBody {
2623 code: "test".into(),
2624 message: "data".into(),
2625 detail: None,
2626 })
2627 .expect("body encodes"),
2628 )
2629 .expect("frame builds");
2630 tx.send(crate::router::OutboundFrame {
2631 frame: data,
2632 enqueued_at: std::time::Instant::now() - Duration::from_millis(5000),
2633 flushed: None,
2634 #[cfg(all(
2635 feature = "test-support",
2636 any(target_os = "linux", target_os = "macos")
2637 ))]
2638 fixture_flush_gate: None,
2639 charge: None,
2640 })
2641 .await
2642 .expect("queued");
2643 drop(tx);
2644 let (write_half, _read_half) = duplex(64 * 1024);
2645 drain_writer(write_half, rx).await.expect("writer drains");
2646 let captured = crate::router::test_log::captured_logs(&logs);
2647 assert!(
2648 !captured.contains("slow control reply write"),
2649 "no WARN for fresh control or stale data frames, got: {captured}"
2650 );
2651 }
2652
2653 struct CountingReader {
2654 bytes: Vec<u8>,
2655 offset: usize,
2656 first_read_end: Option<usize>,
2657 reads: Arc<AtomicUsize>,
2658 }
2659
2660 impl CountingReader {
2661 fn new(bytes: Vec<u8>, first_read_end: Option<usize>) -> (Self, Arc<AtomicUsize>) {
2662 let reads = Arc::new(AtomicUsize::new(0));
2663 (
2664 Self {
2665 bytes,
2666 offset: 0,
2667 first_read_end,
2668 reads: Arc::clone(&reads),
2669 },
2670 reads,
2671 )
2672 }
2673 }
2674
2675 impl AsyncRead for CountingReader {
2676 fn poll_read(
2677 mut self: Pin<&mut Self>,
2678 _cx: &mut Context<'_>,
2679 buf: &mut ReadBuf<'_>,
2680 ) -> Poll<io::Result<()>> {
2681 self.reads.fetch_add(1, Ordering::Relaxed);
2682 let available = self.bytes.len().saturating_sub(self.offset);
2683 let first_read_remaining = self
2684 .first_read_end
2685 .filter(|end| self.offset < *end)
2686 .map_or(available, |end| end - self.offset);
2687 let count = available.min(first_read_remaining).min(buf.remaining());
2688 let end = self.offset + count;
2689 buf.put_slice(&self.bytes[self.offset..end]);
2690 self.offset = end;
2691 Poll::Ready(Ok(()))
2692 }
2693 }
2694
2695 fn encode_frames(frames: &[Frame]) -> Vec<u8> {
2696 let mut bytes = Vec::new();
2697 for frame in frames {
2698 bytes.extend_from_slice(&frame.header.encode());
2699 bytes.extend_from_slice(&frame.body);
2700 }
2701 bytes
2702 }
2703
2704 async fn read_frames<R>(reader: &mut R, count: usize) -> Vec<Frame>
2705 where
2706 R: AsyncRead + Unpin,
2707 {
2708 let mut frames = Vec::with_capacity(count);
2709 for _ in 0..count {
2710 frames.push(read_frame(reader).await.unwrap().unwrap());
2711 }
2712 frames
2713 }
2714
2715 fn request(channel: u16, corr: u64, body: &[u8]) -> Frame {
2716 Frame::build(
2717 FrameType::Request,
2718 Flags::new(true, Priority::Interactive, false),
2719 channel,
2720 0,
2721 corr,
2722 body.to_vec(),
2723 )
2724 .unwrap()
2725 }
2726
2727 fn echo_router() -> Arc<Router> {
2728 let mut router = Router::with_default_self_handler();
2729 router.register_backend(7, EchoBackend).unwrap();
2730 router.register_backend(9, EchoBackend).unwrap();
2731 Arc::new(router)
2732 }
2733
2734 fn test_auth() -> (ServerAuth, ConnectionInfo) {
2735 test_auth_with_limit(4)
2736 }
2737
2738 fn test_auth_with_limit(max_unauthenticated: usize) -> (ServerAuth, ConnectionInfo) {
2739 test_auth_with_deadline_and_limit(TEST_DEADLINE, max_unauthenticated)
2740 }
2741
2742 fn test_auth_with_deadline_and_limit(
2743 deadline: Duration,
2744 max_unauthenticated: usize,
2745 ) -> (ServerAuth, ConnectionInfo) {
2746 let key = vec![0x42; 32];
2747 let daemon_id = [0x24; 16];
2748 let conn = ConnectionInfo {
2749 schema: SCHEMA_VERSION,
2750 wire_version: None,
2751 endpoints: vec![Endpoint {
2752 host: "127.0.0.1".to_owned(),
2753 port: 1,
2754 }],
2755 key: key.clone(),
2756 daemon_id,
2757 pid: std::process::id(),
2758 daemon_ver: TEST_DAEMON_VER.to_owned(),
2759 };
2760 (
2761 ServerAuth::with_limits(
2762 key,
2763 daemon_id,
2764 TEST_DAEMON_VER,
2765 deadline,
2766 max_unauthenticated,
2767 ),
2768 conn,
2769 )
2770 }
2771
2772 async fn authenticate<S>(stream: &mut S, conn: &ConnectionInfo)
2773 where
2774 S: AsyncRead + AsyncWrite + Unpin,
2775 {
2776 authenticate_client(stream, conn, TEST_DEADLINE)
2777 .await
2778 .expect("test client should authenticate")
2779 }
2780
2781 async fn write_auth_message<S, T>(stream: &mut S, value: &T)
2782 where
2783 S: AsyncWrite + Unpin,
2784 T: Serialize,
2785 {
2786 let body = serde_json::to_vec(value).expect("auth message encodes");
2787 stream
2788 .write_all(&(body.len() as u32).to_le_bytes())
2789 .await
2790 .expect("auth message length writes");
2791 stream
2792 .write_all(&body)
2793 .await
2794 .expect("auth message body writes");
2795 }
2796
2797 async fn read_auth_message<S, T>(stream: &mut S) -> T
2798 where
2799 S: AsyncRead + Unpin,
2800 T: DeserializeOwned,
2801 {
2802 let mut length = [0; 4];
2803 stream
2804 .read_exact(&mut length)
2805 .await
2806 .expect("auth message length reads");
2807 let mut body = vec![0; u32::from_le_bytes(length) as usize];
2808 stream
2809 .read_exact(&mut body)
2810 .await
2811 .expect("auth message body reads");
2812 serde_json::from_slice(&body).expect("auth message decodes")
2813 }
2814
2815 async fn send_wrong_key_client_auth<S>(stream: &mut S, conn: &ConnectionInfo)
2816 where
2817 S: AsyncRead + AsyncWrite + Unpin,
2818 {
2819 let hello = ClientHello {
2820 client_nonce: [0x57; NONCE_LEN],
2821 role: "client".to_owned(),
2822 };
2823 write_auth_message(stream, &hello).await;
2824 let proof: ServerProof = read_auth_message(stream).await;
2825 let mut wrong_key = conn.key.clone();
2826 wrong_key[0] ^= 0xff;
2827 let client_auth = ClientAuth {
2828 client_auth: compute_proof(
2829 &wrong_key,
2830 CLIENT_AUTH_DOMAIN,
2831 &hello.client_nonce,
2832 &proof.server_nonce,
2833 &conn.daemon_id,
2834 ),
2835 };
2836 write_auth_message(stream, &client_auth).await;
2837 }
2838
2839 fn assert_pre_auth_log(logs: &Arc<std::sync::Mutex<Vec<u8>>>, stage: &str, port: u16) {
2840 let captured = crate::router::test_log::captured_logs(logs);
2841 assert!(
2842 captured.contains(&format!("stage=\"{stage}\"")),
2843 "expected rejection stage {stage}, got: {captured}"
2844 );
2845 assert!(
2846 captured.contains(&format!("peer_addr=127.0.0.1:{port}")),
2847 "expected peer address, got: {captured}"
2848 );
2849 assert!(
2850 captured.contains("elapsed_ms=") && captured.contains("suppressed_since_last="),
2851 "expected elapsed time and suppression count, got: {captured}"
2852 );
2853 assert!(
2854 !captured.contains("WARN"),
2855 "pre-auth rejection must not be logged as a warning: {captured}"
2856 );
2857 }
2858
2859 #[tokio::test]
2860 async fn logs_handshake_deadline_pre_auth_rejection() {
2861 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2862 let deadline = Duration::from_millis(60);
2863 let (auth, _) = test_auth_with_deadline_and_limit(deadline, 4);
2864 let (client, server_stream) = duplex(512);
2865 let port = 41001;
2866 let server = handle_accepted_connection(
2867 server_stream,
2868 echo_router(),
2869 auth,
2870 SocketAddr::from(([127, 0, 0, 1], port)),
2871 Instant::now(),
2872 );
2873
2874 let error = tokio::time::timeout(deadline * 3, server)
2875 .await
2876 .expect("idle handshake should end at its deadline")
2877 .expect_err("idle handshake must be rejected");
2878 drop(client);
2879 assert!(matches!(
2880 error,
2881 ConnectionError::Auth(AuthError::Timeout {
2882 stage: AuthStage::ClientHello,
2883 ..
2884 })
2885 ));
2886 let captured = crate::router::test_log::captured_logs(&logs);
2887 assert!(
2888 captured.contains("reason=\"handshake_deadline_expired\""),
2889 "{captured}"
2890 );
2891 assert_pre_auth_log(&logs, "handshake_deadline", port);
2892 }
2893
2894 #[tokio::test]
2895 async fn logs_invalid_client_proof_pre_auth_rejection() {
2896 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2897 let (auth, conn) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2898 let (mut client, server_stream) = duplex(512);
2899 let port = 41002;
2900 let server = handle_accepted_connection(
2901 server_stream,
2902 echo_router(),
2903 auth,
2904 SocketAddr::from(([127, 0, 0, 1], port)),
2905 Instant::now(),
2906 );
2907
2908 let (error, ()) = tokio::join!(server, send_wrong_key_client_auth(&mut client, &conn));
2909 assert!(matches!(
2910 error,
2911 Err(ConnectionError::Auth(AuthError::InvalidClientAuth))
2912 ));
2913 let captured = crate::router::test_log::captured_logs(&logs);
2914 assert!(
2915 captured.contains("reason=\"client_proof_mismatch\""),
2916 "{captured}"
2917 );
2918 assert_pre_auth_log(&logs, "client_authentication", port);
2919 }
2920
2921 #[tokio::test]
2922 async fn logs_malformed_pre_auth_message() {
2923 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2924 let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2925 let (mut client, server_stream) = duplex(512);
2926 let port = 41003;
2927 let server = handle_accepted_connection(
2928 server_stream,
2929 echo_router(),
2930 auth,
2931 SocketAddr::from(([127, 0, 0, 1], port)),
2932 Instant::now(),
2933 );
2934 let send_malformed_message = async {
2935 let body = b"{";
2936 client
2937 .write_all(&(body.len() as u32).to_le_bytes())
2938 .await
2939 .expect("message length writes");
2940 client.write_all(body).await.expect("message body writes");
2941 };
2942
2943 let (error, ()) = tokio::join!(server, send_malformed_message);
2944 assert!(matches!(
2945 error,
2946 Err(ConnectionError::Auth(AuthError::JsonDecode {
2947 stage: AuthStage::ClientHello,
2948 ..
2949 }))
2950 ));
2951 let captured = crate::router::test_log::captured_logs(&logs);
2952 assert!(
2953 captured.contains("reason=\"malformed_or_oversized_message\""),
2954 "{captured}"
2955 );
2956 assert_pre_auth_log(&logs, "malformed_message", port);
2957 }
2958
2959 #[tokio::test]
2960 async fn logs_peer_close_during_handshake() {
2961 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2962 let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2963 let (client, server_stream) = duplex(512);
2964 let port = 41004;
2965 drop(client);
2966
2967 let error = handle_accepted_connection(
2968 server_stream,
2969 echo_router(),
2970 auth,
2971 SocketAddr::from(([127, 0, 0, 1], port)),
2972 Instant::now(),
2973 )
2974 .await
2975 .expect_err("closed peer must be rejected");
2976 assert!(matches!(
2977 error,
2978 ConnectionError::Auth(AuthError::UnexpectedEof {
2979 stage: AuthStage::ClientHello,
2980 actual: 0,
2981 ..
2982 })
2983 ));
2984 let captured = crate::router::test_log::captured_logs(&logs);
2985 assert!(
2986 captured.contains("reason=\"peer_closed_before_authentication_completed\""),
2987 "{captured}"
2988 );
2989 assert_pre_auth_log(&logs, "peer_closed", port);
2990 }
2991
2992 #[tokio::test]
2996 async fn each_listener_rate_limits_its_own_rejection_logs() {
2997 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2998 for port in [41011, 41012] {
2999 let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
3000 let (client, server_stream) = duplex(512);
3001 drop(client);
3002 handle_accepted_connection(
3003 server_stream,
3004 echo_router(),
3005 auth,
3006 SocketAddr::from(([127, 0, 0, 1], port)),
3007 Instant::now(),
3008 )
3009 .await
3010 .expect_err("closed peer must be rejected");
3011 }
3012 let captured = crate::router::test_log::captured_logs(&logs);
3013 for port in [41011, 41012] {
3014 assert!(
3015 captured.contains(&format!("127.0.0.1:{port}")),
3016 "listener on port {port} logged nothing: {captured}"
3017 );
3018 }
3019 }
3020
3021 #[tokio::test]
3022 async fn logs_unauthenticated_capacity_rejection() {
3023 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
3024 let deadline = Duration::from_millis(60);
3025 let (auth, _) = test_auth_with_deadline_and_limit(deadline, 1);
3026 let held_slot = auth
3027 .unauthenticated
3028 .clone()
3029 .try_acquire_owned()
3030 .expect("the only pre-auth slot is available");
3031 let (client, server_stream) = duplex(512);
3032 let port = 41005;
3033 let server = handle_accepted_connection(
3034 server_stream,
3035 echo_router(),
3036 auth,
3037 SocketAddr::from(([127, 0, 0, 1], port)),
3038 Instant::now(),
3039 );
3040
3041 let error = tokio::time::timeout(deadline * 3, server)
3042 .await
3043 .expect("queued connection should end at the capacity deadline")
3044 .expect_err("connection without a free slot must be rejected");
3045 drop(held_slot);
3046 drop(client);
3047 assert!(matches!(error, ConnectionError::UnauthenticatedCapacity));
3048 let captured = crate::router::test_log::captured_logs(&logs);
3049 assert!(
3050 captured.contains("reason=\"capacity_wait_timed_out\""),
3051 "{captured}"
3052 );
3053 assert_pre_auth_log(&logs, "waiting_for_handshake_slot", port);
3054 }
3055
3056 #[test]
3057 fn pre_auth_rejection_limiter_suppresses_bursts_and_reports_count() {
3058 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
3059 let limiter = PreAuthRejectLimiter::new();
3060 let capacity = ConnectionError::UnauthenticatedCapacity;
3061 let handshake_timeout = ConnectionError::Auth(AuthError::Timeout {
3062 stage: AuthStage::ClientHello,
3063 deadline: Duration::from_millis(200),
3064 });
3065 let peer_addr = SocketAddr::from(([127, 0, 0, 1], 41006));
3066
3067 log_pre_auth_rejection(
3068 &capacity,
3069 peer_addr,
3070 Duration::from_millis(1),
3071 Duration::ZERO,
3072 &limiter,
3073 );
3074 for _ in 0..4 {
3075 log_pre_auth_rejection(
3076 &capacity,
3077 peer_addr,
3078 Duration::from_millis(2),
3079 Duration::from_millis(100),
3080 &limiter,
3081 );
3082 }
3083 log_pre_auth_rejection(
3084 &handshake_timeout,
3085 peer_addr,
3086 Duration::from_millis(3),
3087 Duration::from_millis(100),
3088 &limiter,
3089 );
3090 log_pre_auth_rejection(
3091 &capacity,
3092 peer_addr,
3093 Duration::from_millis(4),
3094 Duration::from_secs(1),
3095 &limiter,
3096 );
3097
3098 let captured = crate::router::test_log::captured_logs(&logs);
3099 assert_eq!(
3100 captured
3101 .matches("subc TCP connection rejected before routing")
3102 .count(),
3103 3,
3104 "one line per stage in a burst, then a later capacity line: {captured}"
3105 );
3106 assert!(
3107 captured.contains("suppressed_since_last=4"),
3108 "later capacity line should report the four hidden rejects: {captured}"
3109 );
3110 assert!(
3111 captured.contains("stage=\"handshake_deadline\""),
3112 "{captured}"
3113 );
3114 }
3115
3116 #[tokio::test]
3117 async fn buffered_frame_reader_coalesces_reads_and_preserves_short_reads() {
3118 let frames = vec![
3119 request(7, 1, b"first"),
3120 request(9, 2, b"second"),
3121 request(7, 3, b"third"),
3122 request(9, 4, b"fourth"),
3123 ];
3124 let bytes = encode_frames(&frames);
3125
3126 let (mut direct, direct_reads) = CountingReader::new(bytes.clone(), None);
3127 assert_eq!(read_frames(&mut direct, frames.len()).await, frames);
3128 assert_eq!(direct_reads.load(Ordering::Relaxed), frames.len() * 3);
3129
3130 let (buffered_source, buffered_reads) = CountingReader::new(bytes, None);
3131 let mut buffered = BufReader::new(buffered_source);
3132 assert_eq!(read_frames(&mut buffered, frames.len()).await, frames);
3133 assert_eq!(buffered_reads.load(Ordering::Relaxed), 1);
3134
3135 let split_frame = request(7, 5, b"split-body");
3136 let split_bytes = encode_frames(std::slice::from_ref(&split_frame));
3137 let (split_source, split_reads) = CountingReader::new(split_bytes, Some(10));
3138 let mut split_reader = BufReader::new(split_source);
3139 assert_eq!(
3140 read_frame(&mut split_reader).await.unwrap(),
3141 Some(split_frame)
3142 );
3143 assert_eq!(split_reads.load(Ordering::Relaxed), 2);
3144 }
3145
3146 #[tokio::test]
3147 async fn interleaved_channels_on_one_stream_demux_byte_identically_after_auth() {
3148 let (mut client, server_stream) = duplex(4096);
3149 let (auth, conn) = test_auth();
3150 let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
3151 authenticate(&mut client, &conn).await;
3152 let frames = [
3153 request(7, 1, b"chan7-first\0opaque"),
3154 request(9, 2, b"chan9-middle-{json?}"),
3155 request(7, 3, b"chan7-second\xffbytes"),
3156 ];
3157
3158 for frame in &frames {
3159 crate::write_frame(&mut client, frame).await.unwrap();
3160 }
3161
3162 for expected in &frames {
3163 let response = crate::read_frame(&mut client).await.unwrap().unwrap();
3164 assert_eq!(response.header.ty, FrameType::Response);
3165 assert_eq!(response.header.channel, expected.header.channel);
3166 assert_eq!(response.header.corr, expected.header.corr);
3167 assert_eq!(response.body, expected.body);
3168 }
3169
3170 drop(client);
3171 server.await.unwrap().unwrap();
3172 }
3173
3174 #[tokio::test]
3175 async fn channel_zero_goes_to_subc_self_handler_after_auth() {
3176 let (mut client, server_stream) = duplex(512);
3177 let (auth, conn) = test_auth();
3178 let server = tokio::spawn(handle_connection(
3179 server_stream,
3180 Arc::new(Router::with_default_self_handler()),
3181 auth,
3182 ));
3183 authenticate(&mut client, &conn).await;
3184 let ping = Frame::build(
3185 FrameType::Ping,
3186 Flags::new(false, Priority::Passive, false),
3187 0,
3188 0,
3189 55,
3190 Vec::new(),
3191 )
3192 .unwrap();
3193
3194 crate::write_frame(&mut client, &ping).await.unwrap();
3195 let response = crate::read_frame(&mut client).await.unwrap().unwrap();
3196
3197 assert_eq!(response.header.ty, FrameType::Pong);
3198 assert_eq!(response.header.channel, 0);
3199 assert_eq!(response.header.corr, 55);
3200 assert!(response.body.is_empty());
3201
3202 drop(client);
3203 server.await.unwrap().unwrap();
3204 }
3205
3206 #[tokio::test]
3207 async fn unauthenticated_connection_is_rejected_before_routing() {
3208 let (mut client, server_stream) = duplex(512);
3209 let (auth, _conn) = test_auth();
3210 let registry = Arc::new(Registry::default());
3211 let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
3212 Arc::clone(®istry),
3213 ))));
3214 let server = tokio::spawn(handle_connection(server_stream, router, auth));
3215 let ping = Frame::build(
3216 FrameType::Ping,
3217 Flags::new(false, Priority::Passive, false),
3218 0,
3219 0,
3220 66,
3221 Vec::new(),
3222 )
3223 .unwrap();
3224
3225 crate::write_frame(&mut client, &ping).await.unwrap();
3226 if let Ok(Ok(Some(frame))) =
3227 tokio::time::timeout(Duration::from_millis(200), crate::read_frame(&mut client)).await
3228 {
3229 panic!("unauthenticated frame reached router: {frame:?}");
3230 }
3231
3232 let err = server.await.unwrap().unwrap_err();
3233 assert!(matches!(err, ConnectionError::Auth(_)));
3234 assert_eq!(registry.active_registration_count().unwrap(), 0);
3235 }
3236
3237 #[tokio::test]
3238 async fn over_cap_peer_queues_for_a_slot_and_authenticates_when_one_frees() {
3239 let (mut first_client, first_server_stream) = duplex(2048);
3244 let (mut second_client, second_server_stream) = duplex(2048);
3245 let (auth, conn) = test_auth_with_limit(1);
3246 let registry = Arc::new(Registry::default());
3247 let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
3248 Arc::clone(®istry),
3249 ))));
3250
3251 let first_server = tokio::spawn(handle_connection(
3252 first_server_stream,
3253 Arc::clone(&router),
3254 auth.clone(),
3255 ));
3256
3257 let second_server = tokio::spawn(handle_connection(
3258 second_server_stream,
3259 Arc::clone(&router),
3260 auth.clone(),
3261 ));
3262
3263 tokio::time::sleep(Duration::from_millis(50)).await;
3265 assert!(
3266 !second_server.is_finished(),
3267 "queued peer must not be reset"
3268 );
3269
3270 authenticate(&mut first_client, &conn).await;
3273 authenticate(&mut second_client, &conn).await;
3274
3275 drop(first_client);
3276 drop(second_client);
3277 let _ = first_server.await;
3278 let _ = second_server.await;
3279 assert_eq!(registry.active_registration_count().unwrap(), 0);
3280 }
3281
3282 #[tokio::test]
3283 async fn over_cap_peer_is_rejected_when_no_slot_frees_within_deadline() {
3284 let (mut second_client, second_server_stream) = duplex(512);
3290 let (auth, conn) = test_auth_with_limit(1);
3291 let registry = Arc::new(Registry::default());
3292 let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
3293 Arc::clone(®istry),
3294 ))));
3295
3296 let held_slot = auth
3297 .unauthenticated
3298 .clone()
3299 .try_acquire_owned()
3300 .expect("sole pre-auth slot");
3301
3302 let second_server = tokio::spawn(handle_connection(
3303 second_server_stream,
3304 Arc::clone(&router),
3305 auth.clone(),
3306 ));
3307 let second_err = tokio::time::timeout(TEST_DEADLINE * 2, second_server)
3308 .await
3309 .expect("capacity reject should settle at the deadline")
3310 .expect("second connection task should not panic")
3311 .expect_err("queued peer must be rejected when no slot frees");
3312 drop(held_slot);
3313 assert!(matches!(
3314 second_err,
3315 ConnectionError::UnauthenticatedCapacity
3316 ));
3317 let mut closed = [0u8; 1];
3318 assert_eq!(
3319 second_client.read(&mut closed).await.unwrap(),
3320 0,
3321 "capacity-rejected peer should observe a closed stream"
3322 );
3323 assert_eq!(registry.active_registration_count().unwrap(), 0);
3324
3325 let (mut authed_client, authed_server_stream) = duplex(2048);
3326 let authed_server = tokio::spawn(handle_connection(
3327 authed_server_stream,
3328 Arc::clone(&router),
3329 auth,
3330 ));
3331 authenticate(&mut authed_client, &conn).await;
3332 let ping = Frame::build(
3333 FrameType::Ping,
3334 Flags::new(false, Priority::Passive, false),
3335 0,
3336 0,
3337 77,
3338 Vec::new(),
3339 )
3340 .unwrap();
3341 crate::write_frame(&mut authed_client, &ping).await.unwrap();
3342 let pong = crate::read_frame(&mut authed_client)
3343 .await
3344 .unwrap()
3345 .unwrap();
3346 assert_eq!(pong.header.ty, FrameType::Pong);
3347 assert_eq!(pong.header.channel, 0);
3348 assert_eq!(pong.header.corr, 77);
3349 assert_eq!(registry.active_registration_count().unwrap(), 0);
3350
3351 drop(authed_client);
3352 authed_server.await.unwrap().unwrap();
3353 }
3354
3355 #[tokio::test]
3356 async fn bind_ack_during_partial_frame_preserves_next_request() {
3357 use subc_control::ClientControlRequest;
3358 use subc_protocol::{
3359 manifest::{
3360 Concurrency, ExecutionMode, IdentityScope, ModuleManifest, ProviderRole, Tool,
3361 },
3362 session::{ModuleControlRequest, ModuleControlResponse},
3363 BindIdentity, ModuleHelloBody, RouteTarget,
3364 };
3365
3366 let mut configured_router = Router::with_default_self_handler();
3367 configured_router.register_backend(7, EchoBackend).unwrap();
3368 let router = Arc::new(configured_router);
3369 let (auth, conn) = test_auth();
3370 let (mut module, module_stream) = duplex(4096);
3371 let module_server = tokio::spawn(handle_connection(
3372 module_stream,
3373 Arc::clone(&router),
3374 auth.clone(),
3375 ));
3376 authenticate(&mut module, &conn).await;
3377 let manifest = ModuleManifest::builder("frame-test", "0.1.0")
3378 .protocol_ver(PROTOCOL_VERSION)
3379 .provides(vec![ProviderRole::ToolProvider {
3380 tools: vec![Tool {
3381 name: "read".into(),
3382 description: None,
3383 execution_mode: ExecutionMode::Pure,
3384 schema: serde_json::json!({"type": "object"}),
3385 }],
3386 identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
3387 concurrency: Concurrency::ModuleManaged,
3388 emits_push: true,
3389 sub_supervises: true,
3390 }])
3391 .build();
3392 let hello = Frame::build(
3393 FrameType::Hello,
3394 Flags::new(false, Priority::Passive, false),
3395 0,
3396 0,
3397 1,
3398 serde_json::to_vec(&ModuleHelloBody {
3399 module_capabilities: None,
3400 resume_token: None,
3401 manifest,
3402 protocol_ver: PROTOCOL_VERSION,
3403 control_ops: None,
3404 launch_nonce: None,
3405 })
3406 .unwrap(),
3407 )
3408 .unwrap();
3409 crate::write_frame(&mut module, &hello).await.unwrap();
3410 assert_eq!(
3411 read_frame(&mut module).await.unwrap().unwrap().header.ty,
3412 FrameType::HelloAck
3413 );
3414
3415 let (mut client, client_stream) = duplex(4096);
3416 let client_server = tokio::spawn(handle_connection(client_stream, router, auth));
3417 authenticate(&mut client, &conn).await;
3418 let open = Frame::build(
3419 FrameType::Request,
3420 Flags::new(false, Priority::Passive, false),
3421 0,
3422 0,
3423 2,
3424 serde_json::to_vec(&ClientControlRequest::RouteOpen {
3425 busy_refusals: None,
3426 target: RouteTarget::ToolProvider {
3427 module_id: "frame-test".into(),
3428 },
3429 identity: BindIdentity::new("unit", "session"),
3430 consumer_identity: None,
3431 consumer_capabilities: None,
3432 role_versions: None,
3433 admission_facts: None,
3434 scope: None,
3435 })
3436 .unwrap(),
3437 )
3438 .unwrap();
3439 crate::write_frame(&mut client, &open).await.unwrap();
3440 let bind = timeout(TEST_DEADLINE, read_frame(&mut module))
3441 .await
3442 .unwrap()
3443 .unwrap()
3444 .unwrap();
3445 assert!(matches!(
3446 serde_json::from_slice::<ModuleControlRequest>(&bind.body).unwrap(),
3447 ModuleControlRequest::RouteBind { .. }
3448 ));
3449
3450 let ping = request(7, 3, b"partial-frame-body");
3451 client.write_all(&ping.header.encode()).await.unwrap();
3452 tokio::time::sleep(Duration::from_millis(30)).await;
3454 let ack = Frame::build(
3455 FrameType::Response,
3456 Flags::new(false, Priority::Passive, false),
3457 0,
3458 0,
3459 bind.header.corr,
3460 serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap(),
3461 )
3462 .unwrap();
3463 crate::write_frame(&mut module, &ack).await.unwrap();
3464 let opened = timeout(TEST_DEADLINE, read_frame(&mut client))
3465 .await
3466 .unwrap()
3467 .unwrap();
3468 if opened.is_none() {
3469 panic!("client closed: {:?}", client_server.await);
3470 }
3471 let opened = opened.unwrap();
3472 assert_eq!(opened.header.corr, 2);
3473 client.write_all(&ping.body).await.unwrap();
3474 let pong = timeout(TEST_DEADLINE, read_frame(&mut client))
3475 .await
3476 .expect("partial frame must reach the router after the bind ack")
3477 .expect("frame must decode")
3478 .expect("connection must remain open");
3479 assert_eq!(pong.header.ty, FrameType::Response);
3480 assert_eq!(pong.header.corr, 3);
3481 assert_eq!(pong.body, ping.body);
3482 drop(client);
3483 drop(module);
3484 client_server.await.unwrap().unwrap();
3485 let _ = module_server.await.unwrap();
3486 }
3487
3488 #[tokio::test]
3489 async fn full_module_egress_health_probe_does_not_block_same_client_other_route() {
3490 use crate::ConnectionId;
3491 use subc_control::{ClientControlRequest, ClientControlResponse};
3492 use subc_protocol::{
3493 manifest::{
3494 Concurrency, ExecutionMode, IdentityScope, ModuleManifest, ProviderRole, Tool,
3495 },
3496 session::ModuleControlResponse,
3497 BindIdentity, ModuleHelloBody, RouteTarget,
3498 };
3499
3500 let probe_timeout = Duration::from_millis(100);
3501 let handler = Arc::new(
3502 ControlHandler::new(Arc::new(Registry::default()))
3503 .with_health_probe_timeout(probe_timeout),
3504 );
3505 let router = Arc::new(Router::with_control_handler(Arc::clone(&handler)));
3506 let hello = |name: &str| {
3507 Frame::build(
3508 FrameType::Hello,
3509 Flags::new(false, Priority::Passive, false),
3510 0,
3511 0,
3512 1,
3513 serde_json::to_vec(&ModuleHelloBody {
3514 module_capabilities: None,
3515 resume_token: None,
3516 manifest: ModuleManifest::builder(name, "0.1.0")
3517 .protocol_ver(PROTOCOL_VERSION)
3518 .provides(vec![ProviderRole::ToolProvider {
3519 tools: vec![Tool {
3520 name: "read".into(),
3521 description: None,
3522 execution_mode: ExecutionMode::Pure,
3523 schema: serde_json::json!({"type": "object"}),
3524 }],
3525 identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
3526 concurrency: Concurrency::ModuleManaged,
3527 emits_push: false,
3528 sub_supervises: false,
3529 }])
3530 .build(),
3531 protocol_ver: PROTOCOL_VERSION,
3532 control_ops: Some(vec!["health.check".to_owned()]),
3533 launch_nonce: None,
3534 })
3535 .unwrap(),
3536 )
3537 .unwrap()
3538 };
3539 let (blocked_tx, mut blocked_rx) = mpsc::channel(1);
3540 let blocked_ctx = RouteCtx {
3541 connection_id: ConnectionId::new(90001),
3542 egress: FrameSink::new(blocked_tx),
3543 };
3544 handler
3545 .handle_control_frame(&blocked_ctx, hello("blocked"))
3546 .await
3547 .unwrap();
3548 assert_eq!(
3549 blocked_rx.try_recv().unwrap().header.ty,
3550 FrameType::HelloAck
3551 );
3552 let filler = request(0, 99, b"queue filler");
3553 blocked_ctx.egress.try_send(filler.clone()).unwrap();
3554 assert!(
3555 blocked_ctx.egress.try_send(filler).is_err(),
3556 "module queue must actually be full"
3557 );
3558
3559 let (healthy_tx, mut healthy_rx) = mpsc::channel(8);
3560 let healthy_ctx = RouteCtx {
3561 connection_id: ConnectionId::new(90002),
3562 egress: FrameSink::new(healthy_tx),
3563 };
3564 handler
3565 .handle_control_frame(&healthy_ctx, hello("healthy"))
3566 .await
3567 .unwrap();
3568 assert_eq!(
3569 healthy_rx.try_recv().unwrap().header.ty,
3570 FrameType::HelloAck
3571 );
3572 let (auth, conn) = test_auth();
3573 let (mut client, client_stream) = duplex(4096);
3574 let client_server =
3575 tokio::spawn(handle_connection(client_stream, Arc::clone(&router), auth));
3576 authenticate(&mut client, &conn).await;
3577 let control_request = |corr, body: ClientControlRequest| {
3578 Frame::build(
3579 FrameType::Request,
3580 Flags::new(false, Priority::Interactive, false),
3581 0,
3582 0,
3583 corr,
3584 serde_json::to_vec(&body).unwrap(),
3585 )
3586 .unwrap()
3587 };
3588 crate::write_frame(
3589 &mut client,
3590 &control_request(
3591 2,
3592 ClientControlRequest::RouteOpen {
3593 busy_refusals: None,
3594 target: RouteTarget::ToolProvider {
3595 module_id: "healthy".into(),
3596 },
3597 identity: BindIdentity::new("unit", "session"),
3598 consumer_identity: None,
3599 consumer_capabilities: None,
3600 role_versions: None,
3601 admission_facts: None,
3602 scope: None,
3603 },
3604 ),
3605 )
3606 .await
3607 .unwrap();
3608 let bind = timeout(TEST_DEADLINE, healthy_rx.recv())
3609 .await
3610 .unwrap()
3611 .unwrap();
3612 handler
3613 .handle_control_frame(
3614 &healthy_ctx,
3615 Frame::build(
3616 FrameType::Response,
3617 Flags::new(false, Priority::Passive, false),
3618 0,
3619 0,
3620 bind.header.corr,
3621 serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap(),
3622 )
3623 .unwrap(),
3624 )
3625 .await
3626 .unwrap();
3627 let opened = timeout(TEST_DEADLINE, read_frame(&mut client))
3628 .await
3629 .unwrap()
3630 .unwrap()
3631 .unwrap();
3632 let (channel, epoch) =
3633 match serde_json::from_slice::<ClientControlResponse>(&opened.body).unwrap() {
3634 ClientControlResponse::RouteOpen {
3635 route_channel,
3636 route_epoch,
3637 ..
3638 } => (route_channel, route_epoch),
3639 other => panic!("expected a healthy module route, got {other:?}"),
3640 };
3641
3642 let probe = control_request(
3643 3,
3644 ClientControlRequest::SupervisorHealthProbe {
3645 module_id: "blocked".into(),
3646 },
3647 );
3648 let mut ping = request(channel, 4, b"healthy request");
3649 ping.header.epoch = epoch;
3650 crate::write_frame(&mut client, &probe).await.unwrap();
3651 crate::write_frame(&mut client, &ping).await.unwrap();
3652 timeout(probe_timeout + Duration::from_secs(1), async {
3653 let timed_out = read_frame(&mut client).await.unwrap().unwrap();
3654 assert_eq!(timed_out.header.corr, 3);
3655 assert_eq!(timed_out.header.ty, FrameType::Error);
3656 let error: ErrorBody = serde_json::from_slice(&timed_out.body).unwrap();
3657 assert_eq!(error.code, "module_timeout");
3658 let forwarded = healthy_rx.recv().await.unwrap();
3659 assert_eq!(forwarded.header.corr, ping.header.corr);
3660 assert_eq!(forwarded.body, ping.body);
3661 let reply = Frame::build(
3662 FrameType::Response,
3663 ping.header.flags,
3664 forwarded.header.channel,
3665 forwarded.header.epoch,
3666 forwarded.header.corr,
3667 b"healthy response".to_vec(),
3668 )
3669 .unwrap();
3670 router
3671 .route_for_connection(&healthy_ctx, reply)
3672 .await
3673 .unwrap();
3674 let pong = read_frame(&mut client).await.unwrap().unwrap();
3675 assert_eq!(pong.header.ty, FrameType::Response);
3676 assert_eq!(pong.header.channel, channel);
3677 assert_eq!(pong.header.epoch, epoch);
3678 assert_eq!(pong.header.corr, 4);
3679 assert_eq!(pong.body, b"healthy response");
3680 })
3681 .await
3682 .expect(
3683 "the same client's healthy route must answer within the probe deadline plus margin",
3684 );
3685 assert_eq!(
3686 blocked_rx.len(),
3687 1,
3688 "the blocked module must remain undrained"
3689 );
3690 assert_eq!(blocked_rx.try_recv().unwrap().header.corr, 99);
3691 assert!(
3692 blocked_rx.try_recv().is_err(),
3693 "a timed-out probe must not be enqueued later"
3694 );
3695 drop(client);
3696 client_server.await.unwrap().unwrap();
3697 }
3698
3699 #[tokio::test]
3700 async fn aborted_accept_does_not_end_listener() {
3701 let listener = Arc::new(TcpListener::bind("127.0.0.1:0").await.unwrap());
3702 let addr = listener.local_addr().unwrap();
3703 let (auth, conn) = test_auth();
3704 let mut attempts = 0;
3705 let server = tokio::spawn(serve_listener_with_accept(
3706 Some(addr),
3707 echo_router(),
3708 auth,
3709 move || {
3710 attempts += 1;
3711 let result = if attempts == 1 {
3712 Some(io::Error::from(io::ErrorKind::ConnectionAborted))
3713 } else {
3714 None
3715 };
3716 let listener = Arc::clone(&listener);
3717 async move {
3718 match result {
3719 Some(err) => Err(err),
3720 None => listener.accept().await,
3721 }
3722 }
3723 },
3724 ));
3725 let mut client = tokio::net::TcpStream::connect(addr).await.unwrap();
3726 authenticate(&mut client, &conn).await;
3727 let ping = Frame::build(
3728 FrameType::Ping,
3729 Flags::new(false, Priority::Passive, false),
3730 0,
3731 0,
3732 77,
3733 Vec::new(),
3734 )
3735 .unwrap();
3736 crate::write_frame(&mut client, &ping).await.unwrap();
3737 let pong = timeout(TEST_DEADLINE, read_frame(&mut client))
3738 .await
3739 .unwrap()
3740 .unwrap()
3741 .unwrap();
3742 assert_eq!(pong.header.ty, FrameType::Pong);
3743 assert!(
3744 !server.is_finished(),
3745 "a temporary accept failure must not stop the listener"
3746 );
3747 server.abort();
3748 }
3749
3750 #[tokio::test]
3751 async fn exhausted_accept_backs_off_then_serves_connection() {
3752 let listener = Arc::new(TcpListener::bind("127.0.0.1:0").await.unwrap());
3753 let addr = listener.local_addr().unwrap();
3754 let (auth, conn) = test_auth();
3755 let mut attempts = 0;
3756 let server = tokio::spawn(serve_listener_with_accept(
3757 Some(addr),
3758 echo_router(),
3759 auth,
3760 move || {
3761 attempts += 1;
3762 #[cfg(unix)]
3765 let emfile = rustix::io::Errno::MFILE.raw_os_error();
3766 #[cfg(windows)]
3767 let emfile = 10024;
3768 let error = (attempts == 1).then(|| io::Error::from_raw_os_error(emfile));
3769 let listener = Arc::clone(&listener);
3770 async move {
3771 match error {
3772 Some(err) => Err(err),
3773 None => listener.accept().await,
3774 }
3775 }
3776 },
3777 ));
3778 let started = Instant::now();
3779 let mut client = tokio::net::TcpStream::connect(addr).await.unwrap();
3780 authenticate(&mut client, &conn).await;
3781 assert!(
3782 started.elapsed() >= Duration::from_millis(50),
3783 "fd exhaustion must back off before retrying"
3784 );
3785 assert!(!server.is_finished());
3786 server.abort();
3787 }
3788
3789 #[tokio::test]
3790 async fn fatal_accept_error_still_stops_listener() {
3791 let (auth, _) = test_auth();
3792 let err = serve_listener_with_accept(None, echo_router(), auth, || async {
3793 Err(io::Error::from(io::ErrorKind::PermissionDenied))
3794 })
3795 .await
3796 .unwrap_err();
3797 assert!(
3798 matches!(err, ServerError::Accept { source, .. } if source.kind() == io::ErrorKind::PermissionDenied)
3799 );
3800 }
3801
3802 #[tokio::test]
3803 async fn serve_listeners_with_no_listeners_returns_typed_error() {
3804 let (auth, _conn) = test_auth();
3805 let err = serve_listeners(Vec::new(), echo_router(), auth)
3806 .await
3807 .expect_err("empty listener set must fail loudly");
3808 assert!(matches!(err, ServerError::NoListeners));
3809 }
3810
3811 #[tokio::test]
3812 async fn malformed_header_returns_typed_error_no_panic() {
3813 let (mut client, server_stream) = duplex(128);
3814 let (auth, conn) = test_auth();
3815 let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
3816 authenticate(&mut client, &conn).await;
3817 let mut header = [0u8; HEADER_LEN];
3818 header[4] = PROTOCOL_VERSION;
3819 header[5] = 250;
3820
3821 client.write_all(&header).await.unwrap();
3822 drop(client);
3823
3824 let err = server.await.unwrap().unwrap_err();
3825 assert!(matches!(
3826 err,
3827 ConnectionError::FrameIo(FrameIoError::DecodeHeader(DecodeError::UnknownFrameType {
3828 byte: 250
3829 }))
3830 ));
3831 }
3832
3833 #[tokio::test]
3834 async fn truncated_body_returns_typed_error_no_panic() {
3835 let (mut client, server_stream) = duplex(128);
3836 let (auth, conn) = test_auth();
3837 let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
3838 authenticate(&mut client, &conn).await;
3839 let frame = request(7, 8, b"abcd");
3840
3841 client.write_all(&frame.header.encode()).await.unwrap();
3842 client.write_all(b"ab").await.unwrap();
3843 drop(client);
3844
3845 let err = server.await.unwrap().unwrap_err();
3846 assert!(matches!(
3847 err,
3848 ConnectionError::FrameIo(FrameIoError::UnexpectedEof {
3849 stage: ReadStage::Body,
3850 expected: 4,
3851 actual: 2
3852 })
3853 ));
3854 }
3855
3856 #[tokio::test]
3857 async fn unknown_channel_is_returned_as_error_frame_and_connection_continues() {
3858 let (mut client, server_stream) = duplex(1024);
3859 let (auth, conn) = test_auth();
3860 let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
3861 authenticate(&mut client, &conn).await;
3862 let unknown = request(42, 10, b"lost");
3863 let known = request(7, 11, b"still-routes");
3864
3865 crate::write_frame(&mut client, &unknown).await.unwrap();
3866 crate::write_frame(&mut client, &known).await.unwrap();
3867
3868 let error = crate::read_frame(&mut client).await.unwrap().unwrap();
3869 assert_eq!(error.header.ty, FrameType::Error);
3870 assert_eq!(error.header.channel, 42);
3871 assert_eq!(error.header.corr, 10);
3872 let error_body: ErrorBody = serde_json::from_slice(&error.body).unwrap();
3873 assert_eq!(error_body.code, "unknown_channel");
3874
3875 let response = crate::read_frame(&mut client).await.unwrap().unwrap();
3876 assert_eq!(response.header.ty, FrameType::Response);
3877 assert_eq!(response.header.channel, 7);
3878 assert_eq!(response.header.corr, 11);
3879 assert_eq!(response.body, b"still-routes");
3880
3881 drop(client);
3882 server.await.unwrap().unwrap();
3883 }
3884
3885 mod audit_findings {
3886 use super::*;
3887 include!("server_audit_tests.rs");
3888 }
3889}