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_with_accept(listener.local_addr().ok(), router, auth, || {
340 listener.accept()
341 })
342 .await
343}
344
345async fn serve_listener_with_accept<A, F>(
346 local_addr: Option<SocketAddr>,
347 router: Arc<Router>,
348 auth: ServerAuth,
349 mut accept: A,
350) -> Result<(), ServerError>
351where
352 A: FnMut() -> F,
353 F: std::future::Future<Output = io::Result<(tokio::net::TcpStream, SocketAddr)>>,
354{
355 loop {
356 let (stream, peer_addr) = match accept().await {
357 Ok(accepted) => accepted,
358 Err(source) => {
359 let kind = source.kind();
360 let exhausted = accept_resource_exhausted(&source);
364 if matches!(
365 kind,
366 io::ErrorKind::ConnectionAborted
367 | io::ErrorKind::ConnectionReset
368 | io::ErrorKind::Interrupted
369 ) || exhausted
370 {
371 warn!(?local_addr, error = %source, "temporary TCP accept failure");
372 if exhausted {
373 tokio::time::sleep(Duration::from_millis(75)).await;
374 }
375 continue;
376 }
377 return Err(ServerError::Accept { local_addr, source });
378 }
379 };
380 let accepted_at = Instant::now();
381 if let Err(source) = stream.set_nodelay(true) {
397 warn!(?peer_addr, error = %source, "could not disable Nagle on accepted connection");
398 }
399 debug!(?peer_addr, ?local_addr, "accepted subc TCP connection");
400 let router = Arc::clone(&router);
401 let auth = auth.clone();
402 tokio::spawn(async move {
403 let _ = handle_accepted_connection(stream, router, auth, peer_addr, accepted_at).await;
404 });
405 }
406}
407
408#[cfg_attr(not(unix), allow(dead_code))]
409fn temporary_accept_failure(source: &io::Error) -> bool {
410 matches!(
411 source.kind(),
412 io::ErrorKind::ConnectionAborted
413 | io::ErrorKind::ConnectionReset
414 | io::ErrorKind::Interrupted
415 ) || accept_resource_exhausted(source)
416}
417
418fn accept_resource_exhausted(error: &io::Error) -> bool {
419 #[cfg(unix)]
424 {
425 use rustix::io::Errno;
426 let exhausted = [Errno::NFILE, Errno::MFILE, Errno::NOBUFS];
427 error
428 .raw_os_error()
429 .is_some_and(|code| exhausted.iter().any(|e| e.raw_os_error() == code))
430 }
431 #[cfg(windows)]
432 {
433 matches!(error.raw_os_error(), Some(10024 | 10055))
434 }
435 #[cfg(not(any(unix, windows)))]
436 {
437 let _ = error;
438 false
439 }
440}
441
442pub async fn serve_local_listener(
449 bound: crate::local_listener::BoundLocalListener,
450 router: Arc<Router>,
451 auth: ServerAuth,
452) -> Result<(), ServerError> {
453 match bound {
454 #[cfg(unix)]
455 crate::local_listener::BoundLocalListener::Unix { listener, path } => {
456 serve_unix_local(listener, path, router, auth).await
457 }
458 #[cfg(windows)]
459 crate::local_listener::BoundLocalListener::Windows {
460 pipe_name,
461 first_instance,
462 } => serve_pipe_local(pipe_name, first_instance, router, auth).await,
463 #[allow(unreachable_patterns)]
465 _ => Err(ServerError::NoListeners),
466 }
467}
468
469#[cfg(unix)]
470async fn serve_unix_local(
471 listener: std::os::unix::net::UnixListener,
472 path: std::path::PathBuf,
473 router: Arc<Router>,
474 auth: ServerAuth,
475) -> Result<(), ServerError> {
476 let _release = SocketFileRelease(path.clone());
479 listener
480 .set_nonblocking(true)
481 .map_err(|source| local_accept_error(&path, source))?;
482 let listener = tokio::net::UnixListener::from_std(listener)
483 .map_err(|source| local_accept_error(&path, source))?;
484 loop {
485 let (stream, _addr) = match listener.accept().await {
486 Ok(accepted) => accepted,
487 Err(source) if temporary_accept_failure(&source) => {
488 warn!(error = %source, "temporary local-socket accept failure");
489 if accept_resource_exhausted(&source) {
490 tokio::time::sleep(Duration::from_millis(75)).await;
491 }
492 continue;
493 }
494 Err(source) => return Err(local_accept_error(&path, source)),
495 };
496 let (peer, diagnostic_pid) =
497 subc_os::local_peer::capture_unix_peer_with_diagnostic_pid(&stream);
498 let opener = diagnostic_pid.map(subc_os::local_peer::DiagnosticProcess::capture);
499 let router = Arc::clone(&router);
500 let auth = auth.clone();
501 tokio::spawn(async move {
502 let _ = handle_accepted_local_connection(stream, router, auth, peer, opener).await;
503 });
504 }
505}
506
507#[cfg(unix)]
508fn local_accept_error(endpoint: &std::path::Path, source: io::Error) -> ServerError {
509 ServerError::LocalAccept {
510 endpoint: endpoint.display().to_string(),
511 source,
512 }
513}
514
515#[cfg(unix)]
516struct SocketFileRelease(std::path::PathBuf);
517
518#[cfg(unix)]
519impl Drop for SocketFileRelease {
520 fn drop(&mut self) {
521 crate::local_listener::remove_unix_socket(&self.0);
522 }
523}
524
525#[cfg(windows)]
526async fn serve_pipe_local(
527 pipe_name: String,
528 first_instance: Option<tokio::net::windows::named_pipe::NamedPipeServer>,
529 router: Arc<Router>,
530 auth: ServerAuth,
531) -> Result<(), ServerError> {
532 let mut free = first_instance;
536 loop {
537 let server = match free.take() {
538 Some(server) => server,
539 None => create_pipe_instance(&pipe_name)?,
540 };
541 if let Err(source) = server.connect().await {
546 if temporary_accept_failure(&source) {
547 continue;
548 }
549 return Err(ServerError::LocalAccept {
550 endpoint: pipe_name.clone(),
551 source,
552 });
553 }
554 free = Some(create_pipe_instance(&pipe_name)?);
557 let router = Arc::clone(&router);
558 let auth = auth.clone();
559 let (peer, diagnostic_pid) =
562 match subc_os::local_peer::capture_pipe_client_with_diagnostic_pid(&server) {
563 Ok(capture) => capture,
564 Err(error) => {
565 warn!(%error, "refused a non-local named-pipe client on the local endpoint");
566 continue;
567 }
568 };
569 let opener = Some(subc_os::local_peer::DiagnosticProcess::capture(
570 diagnostic_pid,
571 ));
572 tokio::spawn(async move {
573 let _ = handle_accepted_local_connection(server, router, auth, peer, opener).await;
574 });
575 }
576}
577
578#[cfg(windows)]
579fn create_pipe_instance(
580 pipe_name: &str,
581) -> Result<tokio::net::windows::named_pipe::NamedPipeServer, ServerError> {
582 crate::local_listener::create_named_pipe_end(pipe_name).map_err(|source| {
583 ServerError::LocalAccept {
584 endpoint: pipe_name.to_owned(),
585 source,
586 }
587 })
588}
589
590async fn handle_accepted_local_connection<S>(
593 stream: S,
594 router: Arc<Router>,
595 auth: ServerAuth,
596 peer: subc_os::local_peer::CapturedPeer,
597 opener: Option<subc_os::local_peer::DiagnosticProcess>,
598) -> Result<(), ConnectionError>
599where
600 S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
601{
602 let result =
603 handle_connection_with_peer(stream, router, auth, LocalOrigin::Local, Some(peer), opener)
604 .await;
605 if let Err(error) = &result {
606 debug!(error = %error, "local-endpoint connection ended");
607 }
608 result
609}
610
611#[derive(Debug, Clone)]
614pub(crate) enum LocalOrigin {
615 Tcp,
616 Local,
617 RegistrationChannel(Arc<crate::supervise::RegistrationSpawn>),
618}
619
620pub async fn serve_listeners(
622 listeners: Vec<TcpListener>,
623 router: Arc<Router>,
624 auth: ServerAuth,
625) -> Result<(), ServerError> {
626 if listeners.is_empty() {
627 return Err(ServerError::NoListeners);
628 }
629 router.install_registration_service(auth.clone());
630
631 let (tx, mut rx) = mpsc::channel(listeners.len());
632 let mut accept_tasks = AbortTasksOnDrop::default();
633 for listener in listeners {
634 let router = Arc::clone(&router);
635 let auth = auth.clone();
636 let tx = tx.clone();
637 accept_tasks.push(tokio::spawn(async move {
638 let result = serve_listener(listener, router, auth).await;
639 let _ = tx.send(result).await;
640 }));
641 }
642 drop(tx);
643
644 rx.recv().await.unwrap_or(Ok(()))
645}
646
647#[derive(Default)]
648struct AbortTasksOnDrop {
649 handles: Vec<JoinHandle<()>>,
650}
651
652impl AbortTasksOnDrop {
653 fn push(&mut self, handle: JoinHandle<()>) {
654 self.handles.push(handle);
655 }
656}
657
658impl Drop for AbortTasksOnDrop {
659 fn drop(&mut self) {
660 for handle in &self.handles {
661 if !handle.is_finished() {
662 handle.abort();
663 }
664 }
665 }
666}
667
668#[derive(Debug)]
669enum ConnectionLoopExit {
670 PeerClosed,
671 CloseRequested(CloseReason),
672}
673
674#[derive(Default)]
675struct ConnectionTasks {
676 routes: JoinSet<Result<(), RouterError>>,
677 privileged: JoinSet<Result<(), RouterError>>,
678 activity: JoinSet<Result<(), RouterError>>,
679}
680
681impl ConnectionTasks {
682 async fn shutdown(&mut self) {
683 self.activity.abort_all();
684 self.routes.shutdown().await;
685 self.privileged.shutdown().await;
686 self.activity.shutdown().await;
688 }
689}
690
691pub async fn handle_connection<S>(
700 stream: S,
701 router: Arc<Router>,
702 auth: ServerAuth,
703) -> Result<(), ConnectionError>
704where
705 S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
706{
707 handle_connection_with_origin(stream, router, auth, LocalOrigin::Tcp).await
708}
709
710pub(crate) async fn handle_connection_with_origin<S>(
713 stream: S,
714 router: Arc<Router>,
715 auth: ServerAuth,
716 origin: LocalOrigin,
717) -> Result<(), ConnectionError>
718where
719 S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
720{
721 handle_connection_with_peer(stream, router, auth, origin, None, None).await
722}
723
724fn clone_tcp_socket(stream: &tokio::net::TcpStream) -> io::Result<std::net::TcpStream> {
725 #[cfg(unix)]
726 let socket = {
727 use std::os::fd::AsFd;
728 stream.as_fd().try_clone_to_owned()?
729 };
730 #[cfg(windows)]
731 let socket = {
732 use std::os::windows::io::AsSocket;
733 stream.as_socket().try_clone_to_owned()?
734 };
735 Ok(socket.into())
736}
737
738struct ShutdownTcpOnDrop(std::net::TcpStream);
739
740impl Drop for ShutdownTcpOnDrop {
741 fn drop(&mut self) {
742 let _ = self.0.shutdown(std::net::Shutdown::Both);
745 }
746}
747
748async fn handle_connection_with_peer<S>(
749 mut stream: S,
750 router: Arc<Router>,
751 auth: ServerAuth,
752 origin: LocalOrigin,
753 peer: Option<subc_os::local_peer::CapturedPeer>,
754 opener: Option<subc_os::local_peer::DiagnosticProcess>,
755) -> Result<(), ConnectionError>
756where
757 S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
758{
759 let channel_spawn = match &origin {
760 LocalOrigin::RegistrationChannel(spawn) => Some(spawn.clone()),
761 _ => None,
762 };
763 struct RetireRegistration(Option<Arc<crate::supervise::RegistrationSpawn>>);
764 impl Drop for RetireRegistration {
765 fn drop(&mut self) {
766 if let Some(spawn) = &self.0 {
767 spawn.retire_registration_channel();
768 }
769 }
770 }
771 let _registration_lifetime = RetireRegistration(channel_spawn.clone());
772 let channel_closed = async {
773 match &channel_spawn {
774 Some(spawn) => spawn.wait_closed().await,
775 None => std::future::pending().await,
776 }
777 };
778 tokio::pin!(channel_closed);
779 let endpoints = (&stream as &dyn Any)
782 .downcast_ref::<tokio::net::TcpStream>()
783 .and_then(|tcp| tcp.local_addr().ok().zip(tcp.peer_addr().ok()));
784 let permit = if channel_spawn.is_some() {
806 None
807 } else {
808 Some(tokio::select! {
809 _ = &mut channel_closed => return Ok(()),
810 result = tokio::time::timeout(auth.deadline, auth.unauthenticated.clone().acquire_owned()) => match result {
811 Ok(Ok(permit)) => permit,
812 Ok(Err(_)) | Err(_) => {
813 let _ = stream.shutdown().await;
814 return Err(ConnectionError::UnauthenticatedCapacity);
815 }
816 }
817 })
818 };
819 let handshake_budget = channel_spawn.as_ref().map_or(auth.deadline, |spawn| {
820 spawn
821 .deadline()
822 .saturating_duration_since(tokio::time::Instant::now())
823 });
824 let authenticated = tokio::select! {
825 _ = &mut channel_closed => { let _ = stream.shutdown().await; return Ok(()); },
826 result = authenticate_server(
827 &mut stream,
828 auth.key.as_ref(),
829 &auth.daemon_id,
830 auth.daemon_ver.as_ref(),
831 handshake_budget,
832 ) => result.map_err(ConnectionError::Auth)?,
833 };
834 drop(permit);
835
836 let _tcp_shutdown = (&stream as &dyn Any)
839 .downcast_ref::<tokio::net::TcpStream>()
840 .map(|tcp| clone_tcp_socket(tcp).map(ShutdownTcpOnDrop))
841 .transpose()
842 .map_err(|err| ConnectionError::FrameIo(FrameIoError::Io(err)))?;
843
844 let mut connection = router.begin_connection();
845 let connection_id = connection.id();
846 if let LocalOrigin::RegistrationChannel(spawn) = &origin {
847 spawn.bind(connection_id);
848 }
849 router.record_caller_endpoints(connection_id, endpoints);
850 use crate::control::RouteOpenerConnection;
851 match &origin {
852 LocalOrigin::Local => {
853 router.record_local_connection(connection_id);
854 router.record_route_opener(connection_id, RouteOpenerConnection::Local(opener));
855 }
856 LocalOrigin::Tcp => router.record_route_opener(connection_id, RouteOpenerConnection::Tcp),
857 LocalOrigin::RegistrationChannel(_) => {}
858 }
859 if let Some(peer) = peer {
860 router.record_captured_peer(connection_id, peer);
861 }
862 let _connected_client = (authenticated.role != WATCHDOG_CLIENT_ROLE)
877 .then(|| auth.connected_clients.open(connection_id));
878 let close_receiver = connection.take_close_receiver();
879 debug!(
880 connection_id = connection_id.get(),
881 "subc authenticated connection opened"
882 );
883
884 let (read_half, write_half) = tokio::io::split(stream);
885 let mut read_half = BufReader::new(read_half);
889 let (egress, rx) = connection_egress();
890 let delivery_guard = ClientDeliveryGuard(egress.clone());
891 let writer = tokio::spawn(drain_writer(write_half, rx));
892
893 let ctx = RouteCtx {
894 connection_id,
895 egress: egress.clone(),
896 };
897
898 let mut tasks = ConnectionTasks::default();
899 let registration_expired = async {
900 match &channel_spawn {
901 Some(spawn) => spawn.registration_expired().await,
902 None => std::future::pending().await,
903 }
904 };
905 let loop_result = tokio::select! {
906 _ = registration_expired => Ok(ConnectionLoopExit::CloseRequested(CloseReason::new("registration_timeout", "module did not complete HELLO before its spawn deadline"))),
907 _ = &mut channel_closed => Ok(ConnectionLoopExit::CloseRequested(CloseReason::new("registration_channel_closed", "the supervised launch ended"))),
908 result = connection_loop(
909 &mut read_half,
910 Arc::clone(&router),
911 ctx.clone(),
912 close_receiver,
913 &mut tasks,
914 origin,
915 ) => result,
916 };
917
918 if let Some(spawn) = &channel_spawn {
923 spawn.retire_registration_channel();
924 }
925 drop(delivery_guard);
926 tasks.shutdown().await;
936
937 drop(ctx);
938 drop(egress);
939 drop(connection);
940
941 let close_reason = match &loop_result {
942 Ok(ConnectionLoopExit::CloseRequested(reason)) => Some(reason.to_string()),
943 Ok(ConnectionLoopExit::PeerClosed) | Err(_) => None,
944 };
945 let writer_result = finish_connection_writer(writer, connection_id.get()).await;
946
947 let result = if let Some(reason) = close_reason.as_deref() {
948 match writer_result {
949 Some(Ok(Ok(()))) | None => Ok(()),
950 Some(Ok(Err(writer_err))) => {
951 debug!(
952 connection_id = connection_id.get(),
953 close_reason = reason,
954 writer_error = %writer_err,
955 "writer failed after requested connection close"
956 );
957 Ok(())
958 }
959 Some(Err(join_err)) => {
960 warn!(
961 connection_id = connection_id.get(),
962 close_reason = reason,
963 join_error = %join_err,
964 "writer task join failed after requested connection close"
965 );
966 Ok(())
967 }
968 }
969 } else {
970 match (loop_result, writer_result) {
971 (Err(loop_err), Some(Ok(Ok(()))) | None) => Err(loop_err),
972 (Err(loop_err), Some(Ok(Err(writer_err)))) => {
973 warn!(
974 connection_id = connection_id.get(),
975 writer_error = %writer_err,
976 "writer failed while closing after connection error"
977 );
978 Err(loop_err)
979 }
980 (Err(loop_err), Some(Err(join_err))) => {
981 warn!(
982 connection_id = connection_id.get(),
983 join_error = %join_err,
984 "writer task join failed while closing after connection error"
985 );
986 Err(loop_err)
987 }
988 (Ok(ConnectionLoopExit::PeerClosed), Some(Ok(Ok(()))) | None) => Ok(()),
989 (Ok(ConnectionLoopExit::PeerClosed), Some(Ok(Err(writer_err)))) => {
990 Err(ConnectionError::FrameIo(writer_err))
991 }
992 (Ok(ConnectionLoopExit::PeerClosed), Some(Err(join_err))) => Err(join_err),
993 (Ok(ConnectionLoopExit::CloseRequested(_)), _) => {
994 unreachable!("close requests are handled before normal writer result matching")
995 }
996 }
997 };
998
999 match &result {
1000 Ok(()) => {
1001 if let Some(reason) = close_reason.as_deref() {
1002 debug!(
1003 connection_id = connection_id.get(),
1004 close_reason = reason,
1005 "subc connection closed by request"
1006 );
1007 } else {
1008 debug!(
1009 connection_id = connection_id.get(),
1010 "subc connection closed"
1011 );
1012 }
1013 }
1014 Err(err) => debug!(
1015 connection_id = connection_id.get(),
1016 error = %err,
1017 "subc connection exited with error"
1018 ),
1019 }
1020
1021 result
1022}
1023
1024async fn finish_connection_writer(
1025 mut writer: JoinHandle<Result<(), FrameIoError>>,
1026 connection_id: u64,
1027) -> Option<Result<Result<(), FrameIoError>, ConnectionError>> {
1028 match timeout(CLOSE_DRAIN_GRACE, &mut writer).await {
1031 Ok(result) => Some(result.map_err(ConnectionError::WriterTask)),
1032 Err(_) => {
1033 warn!(
1034 connection_id,
1035 grace = ?CLOSE_DRAIN_GRACE,
1036 "connection writer did not drain during teardown; aborting writer task"
1037 );
1038 writer.abort();
1039 let _ = writer.await;
1040 None
1041 }
1042 }
1043}
1044
1045#[cfg(all(test, unix))]
1046pub(crate) fn config_test_connection_loop(
1047 router: Arc<Router>,
1048) -> (
1049 crate::ConnectionId,
1050 tokio::io::DuplexStream,
1051 JoinHandle<Result<(), ConnectionError>>,
1052) {
1053 let mut connection = router.begin_connection();
1054 let id = connection.id();
1055 let close = connection.take_close_receiver();
1056 router.record_local_connection(id);
1057 let (client, server) = tokio::io::duplex(64 * 1024);
1058 let (mut read, mut write) = tokio::io::split(server);
1059 let (sender, mut outgoing) = tokio::sync::mpsc::channel::<crate::router::OutboundFrame>(8);
1060 let ctx = RouteCtx {
1061 connection_id: id,
1062 egress: crate::FrameSink::new(sender),
1063 };
1064 let writer = tokio::spawn(async move {
1065 while let Some(mut outbound) = outgoing.recv().await {
1066 if crate::write_frame(&mut write, &outbound.frame)
1067 .await
1068 .is_err()
1069 || tokio::io::AsyncWriteExt::flush(&mut write).await.is_err()
1070 {
1071 break;
1072 }
1073 if let Some(flushed) = outbound.flushed.take() {
1074 let _ = flushed.send(());
1075 }
1076 }
1077 });
1078 let task = tokio::spawn(async move {
1079 let mut tasks = ConnectionTasks::default();
1080 let result = connection_loop(
1081 &mut read,
1082 router,
1083 ctx.clone(),
1084 close,
1085 &mut tasks,
1086 LocalOrigin::Local,
1087 )
1088 .await;
1089 tasks.shutdown().await;
1090 drop(ctx);
1091 drop(connection);
1092 writer.abort();
1093 let _ = writer.await;
1094 result.map(|_| ())
1095 });
1096 (id, client, task)
1097}
1098
1099async fn connection_loop<R>(
1100 read_half: &mut R,
1101 router: Arc<Router>,
1102 ctx: RouteCtx,
1103 mut close_receiver: ConnectionCloseReceiver,
1104 tasks: &mut ConnectionTasks,
1105 origin: LocalOrigin,
1106) -> Result<ConnectionLoopExit, ConnectionError>
1107where
1108 R: AsyncRead + Unpin,
1109{
1110 let ConnectionTasks {
1111 routes: route_open_tasks,
1112 privileged: privileged_tasks,
1113 activity: activity_tasks,
1114 } = tasks;
1115 loop {
1116 while let Some(result) = activity_tasks.try_join_next() {
1117 finish_route_open_task(result)?;
1118 }
1119 while let Some(result) = privileged_tasks.try_join_next() {
1120 finish_route_open_task(result)?;
1121 }
1122 while let Some(result) = route_open_tasks.try_join_next() {
1123 finish_route_open_task(result)?;
1124 }
1125
1126 let read = read_frame(&mut *read_half);
1129 tokio::pin!(read);
1130 let frame = loop {
1131 tokio::select! {
1132 close = &mut close_receiver => {
1133 return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1134 }
1135 result = route_open_tasks.join_next(), if !route_open_tasks.is_empty() => {
1136 finish_route_open_task(
1137 result.expect("a non-empty route.open JoinSet has a next task")
1138 )?;
1139 }
1140 result = activity_tasks.join_next(), if !activity_tasks.is_empty() => {
1141 finish_route_open_task(result.expect("non-empty activity task set"))?;
1142 }
1143 result = privileged_tasks.join_next(), if !privileged_tasks.is_empty() => {
1144 finish_route_open_task(result.expect("non-empty privileged task set"))?;
1145 }
1146 result = &mut read => {
1147 break match result.map_err(ConnectionError::FrameIo)? {
1148 Some(frame) => frame,
1149 None => return Ok(ConnectionLoopExit::PeerClosed),
1150 };
1151 }
1152 }
1153 };
1154
1155 if ctx.egress.ingress_terminal() {
1158 return Ok(ConnectionLoopExit::PeerClosed);
1159 }
1160 let first = ctx.egress.first_ingress_frame();
1161 if frame.header.channel == 0 && frame.header.ty == subc_protocol::FrameType::Goodbye {
1162 activity_tasks.shutdown().await;
1163 }
1164 if let LocalOrigin::RegistrationChannel(spawn) = &origin {
1165 let hello = frame.header.ty == subc_protocol::FrameType::Hello;
1166 if (!spawn.registered() && !hello) || (spawn.registered() && hello) {
1167 ctx.egress.terminate_ingress();
1168 spawn.retire_registration_channel();
1169 return Ok(ConnectionLoopExit::PeerClosed);
1170 }
1171 }
1172
1173 if matches!(origin, LocalOrigin::Local)
1174 && frame.header.ty == subc_protocol::FrameType::Hello
1175 {
1176 ctx.egress.terminate_ingress();
1181 let refusal = crate::control::control_error_frame(
1182 &frame,
1183 crate::local_listener::LOCAL_ENDPOINT_CLIENTS_ONLY,
1184 "the local endpoint serves clients only; modules register over TCP",
1185 )
1186 .map_err(ConnectionError::Router)?;
1187 let send_result = tokio::select! {
1191 close = &mut close_receiver => {
1192 return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1193 }
1194 result = router.observe_connection_wait(&ctx, "reply_egress", send_refusal(&ctx.egress, refusal)) => result,
1195 };
1196 send_result.map_err(ConnectionError::Router)?;
1197 return Ok(ConnectionLoopExit::PeerClosed);
1198 }
1199
1200 if frame.header.channel == 0
1201 && frame.header.ty == subc_protocol::FrameType::Request
1202 && serde_json::from_slice::<serde_json::Value>(&frame.body)
1203 .ok()
1204 .is_some_and(|body| {
1205 matches!(
1206 body["op"].as_str(),
1207 Some(
1208 subc_control::ops::ACTIVITY_RECORD
1209 | subc_control::ops::ACTIVITY_QUERY
1210 | subc_control::ops::ACTIVITY_SUBSCRIBE
1211 )
1212 )
1213 })
1214 {
1215 if activity_tasks.len() >= 128 {
1218 let response = crate::control::control_error_frame(
1219 &frame,
1220 subc_control::ACTIVITY_UNAVAILABLE,
1221 "activity queue full",
1222 )
1223 .map_err(ConnectionError::Router)?;
1224 let send_result = tokio::select! {
1225 close = &mut close_receiver => {
1226 return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1227 }
1228 result = router.observe_connection_wait(&ctx, "reply_egress", ctx.egress.send(response)) => result,
1229 };
1230 send_result.map_err(ConnectionError::Router)?;
1231 } else {
1232 let reservation = router.reserve_activity_subscription(&ctx, &frame);
1235 let task_router = Arc::clone(&router);
1236 let task_ctx = ctx.clone();
1237 activity_tasks.spawn(async move {
1238 let _reservation = reservation;
1239 route_open_tail(task_router, task_ctx, frame, Instant::now(), first).await
1240 });
1241 }
1242 continue;
1243 }
1244
1245 if let Some(target_module_id) = router.route_open_target(&frame) {
1246 while let Some(result) = route_open_tasks.try_join_next() {
1250 finish_route_open_task(result)?;
1251 }
1252
1253 if route_open_tasks.len() >= MAX_PENDING_ROUTE_OPENS_PER_CONNECTION {
1254 let refusal = router
1257 .route_open_capacity_refusal(
1258 &ctx,
1259 &frame,
1260 &target_module_id,
1261 route_open_tasks.len(),
1262 MAX_PENDING_ROUTE_OPENS_PER_CONNECTION,
1263 )
1264 .map_err(ConnectionError::Router)?;
1265 let send_result = tokio::select! {
1266 close = &mut close_receiver => {
1267 return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1268 }
1269 result = router.observe_connection_wait(&ctx, "reply_egress", ctx.egress.send(refusal)) => result,
1270 };
1271 send_result.map_err(ConnectionError::Router)?;
1272 continue;
1273 }
1274
1275 let task_router = Arc::clone(&router);
1276 let task_ctx = ctx.clone();
1277 let dispatch_started_at = Instant::now();
1280 route_open_tasks.spawn(async move {
1281 route_open_tail(task_router, task_ctx, frame, dispatch_started_at, first).await
1282 });
1283 continue;
1284 }
1285
1286 if router.defers_config_approval(&frame) || router.defers_privileged_control(&ctx, &frame) {
1287 let reservation = match router.reserve_config_approval(&ctx, &frame) {
1288 Ok(reservation) => reservation,
1289 Err(error) => {
1290 ctx.egress
1291 .send(
1292 crate::control::control_error_body_frame(
1293 &frame,
1294 subc_protocol::ErrorBody {
1295 code: error.code,
1296 message: error.detail,
1297 detail: None,
1298 },
1299 )
1300 .map_err(ConnectionError::Router)?,
1301 )
1302 .await
1303 .map_err(ConnectionError::Router)?;
1304 continue;
1305 }
1306 };
1307 let task_router = Arc::clone(&router);
1310 let task_ctx = ctx.clone();
1311 let started = Instant::now();
1312 privileged_tasks.spawn(async move {
1313 let _reservation = reservation;
1316 route_open_tail(task_router, task_ctx, frame, started, first).await
1317 });
1318 continue;
1319 }
1320
1321 let route_result = tokio::select! {
1324 close = &mut close_receiver => {
1325 return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1326 }
1327 result = router.route_for_connection_ingress(&ctx, frame, None, first) => result,
1328 };
1329
1330 if let Err(err) = route_result {
1331 if let Some(error_frame) = err.to_error_frame() {
1332 warn!(
1333 connection_id = ctx.connection_id.get(),
1334 error = %err,
1335 "routing failure recovered with ERROR frame"
1336 );
1337 let send_result = tokio::select! {
1338 close = &mut close_receiver => {
1339 return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1340 }
1341 result = router.observe_connection_wait(&ctx, "reply_egress", ctx.egress.send(error_frame)) => result,
1342 };
1343 send_result.map_err(ConnectionError::Router)?;
1344 } else {
1345 debug!(
1346 connection_id = ctx.connection_id.get(),
1347 error = %err,
1348 "fatal routing failure"
1349 );
1350 return Err(ConnectionError::Router(err));
1351 }
1352 }
1353 }
1354}
1355
1356async fn send_refusal(sink: &FrameSink, frame: crate::Frame) -> Result<(), RouterError> {
1359 #[cfg(unix)]
1360 {
1361 sink.send_flushed(frame).await
1362 }
1363 #[cfg(not(unix))]
1364 {
1365 sink.send(frame).await
1366 }
1367}
1368
1369async fn route_open_tail(
1370 router: Arc<Router>,
1371 ctx: RouteCtx,
1372 frame: crate::Frame,
1373 dispatch_started_at: Instant,
1374 first: bool,
1375) -> Result<(), RouterError> {
1376 match router
1377 .route_for_connection_ingress(&ctx, frame, Some(dispatch_started_at), first)
1378 .await
1379 {
1380 Ok(()) => Ok(()),
1381 Err(err) => {
1382 let Some(error_frame) = err.to_error_frame() else {
1383 return Err(err);
1384 };
1385 warn!(
1386 connection_id = ctx.connection_id.get(),
1387 error = %err,
1388 "routing failure recovered with ERROR frame"
1389 );
1390 router
1391 .observe_connection_wait(&ctx, "reply_egress", ctx.egress.send(error_frame))
1392 .await
1393 }
1394 }
1395}
1396
1397fn finish_route_open_task(
1398 result: Result<Result<(), RouterError>, tokio::task::JoinError>,
1399) -> Result<(), ConnectionError> {
1400 match result {
1401 Ok(Ok(())) => Ok(()),
1402 Ok(Err(err)) => Err(ConnectionError::Router(err)),
1403 Err(err) => Err(ConnectionError::Router(RouterError::backend(
1404 0,
1405 0,
1406 format!("route.open task failed: {err}"),
1407 ))),
1408 }
1409}
1410
1411fn close_reason(
1412 result: Result<CloseReason, tokio::sync::oneshot::error::RecvError>,
1413) -> CloseReason {
1414 result.unwrap_or_else(|_| {
1415 CloseReason::new(
1416 "close_registry_dropped",
1417 "connection close registration was dropped without a reason",
1418 )
1419 })
1420}
1421
1422pub(crate) fn connection_egress() -> (FrameSink, mpsc::Receiver<crate::router::OutboundFrame>) {
1426 let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(CONNECTION_EGRESS_FRAME_CAP);
1427 (
1428 FrameSink::with_byte_budget(tx, CONNECTION_EGRESS_BYTE_BUDGET),
1429 rx,
1430 )
1431}
1432
1433async fn drain_writer<W>(
1434 write_half: W,
1435 mut rx: mpsc::Receiver<crate::router::OutboundFrame>,
1436) -> Result<(), FrameIoError>
1437where
1438 W: AsyncWrite + Unpin,
1439{
1440 let mut writer = BufWriter::new(write_half);
1441 while let Some(outbound) = rx.recv().await {
1442 write_outbound(&mut writer, outbound).await?;
1443 while let Ok(outbound) = rx.try_recv() {
1444 write_outbound(&mut writer, outbound).await?;
1445 }
1446 writer.flush().await.map_err(FrameIoError::Io)?;
1447 }
1448 writer.flush().await.map_err(FrameIoError::Io)?;
1449 Ok(())
1450}
1451
1452async fn write_outbound<W>(
1459 writer: &mut BufWriter<W>,
1460 outbound: crate::router::OutboundFrame,
1461) -> Result<(), FrameIoError>
1462where
1463 W: AsyncWrite + Unpin,
1464{
1465 const SLOW_REPLY_QUEUE: Duration = Duration::from_millis(1000);
1466 let queued = outbound.enqueued_at.elapsed();
1467 let charge = outbound.charge;
1470 if let Some(charge) = &charge {
1471 charge.taken_by_writer();
1472 }
1473 let frame = outbound.frame;
1474 if frame.header.channel == 0 && queued >= SLOW_REPLY_QUEUE {
1475 let write_started = std::time::Instant::now();
1476 let result = write_frame(writer, &frame).await;
1477 tracing::warn!(
1478 corr = frame.header.corr,
1479 queued_ms = queued.as_millis() as u64,
1480 write_ms = write_started.elapsed().as_millis() as u64,
1481 "slow control reply write"
1482 );
1483 result?;
1484 } else {
1485 write_frame(writer, &frame).await?;
1486 }
1487 if let Some(flushed) = outbound.flushed {
1488 writer.flush().await.map_err(FrameIoError::Io)?;
1489 let _ = flushed.send(());
1490 }
1491 Ok(())
1492}
1493
1494#[cfg(all(test, unix))]
1495#[tokio::test]
1496async fn shutdown_notice_ack_waits_for_socket_flush() {
1497 let (socket, mut peer) = tokio::io::duplex(1);
1498 let (tx, rx) = mpsc::channel(1);
1499 let sink = FrameSink::new(tx);
1500 let writer = tokio::spawn(drain_writer(socket, rx));
1501 let frame = crate::Frame::build(
1502 subc_protocol::FrameType::Push,
1503 subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
1504 0,
1505 0,
1506 0,
1507 b"notice".to_vec(),
1508 )
1509 .unwrap();
1510 let send = sink.send_flushed(frame);
1511 tokio::pin!(send);
1512 assert!(
1513 timeout(Duration::from_millis(20), &mut send).await.is_err(),
1514 "queueing bytes is not a socket flush acknowledgement"
1515 );
1516 let (sent, received) = timeout(Duration::from_secs(1), async {
1517 tokio::join!(&mut send, read_frame(&mut peer))
1518 })
1519 .await
1520 .unwrap();
1521 sent.unwrap();
1522 assert_eq!(received.unwrap().unwrap().body, b"notice");
1523 writer.abort();
1524}
1525
1526#[derive(Debug)]
1527pub enum ServerError {
1528 NoListeners,
1529 Accept {
1530 local_addr: Option<SocketAddr>,
1531 source: io::Error,
1532 },
1533 LocalAccept {
1536 endpoint: String,
1537 source: io::Error,
1538 },
1539}
1540
1541impl fmt::Display for ServerError {
1542 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1543 match self {
1544 Self::NoListeners => write!(f, "no TCP listeners were provided"),
1545 Self::Accept { local_addr, source } => match local_addr {
1546 Some(addr) => write!(f, "failed to accept TCP connection on {addr}: {source}"),
1547 None => write!(f, "failed to accept TCP connection: {source}"),
1548 },
1549 Self::LocalAccept { endpoint, source } => {
1550 write!(f, "local endpoint {endpoint} failed: {source}")
1551 }
1552 }
1553 }
1554}
1555
1556impl Error for ServerError {
1557 fn source(&self) -> Option<&(dyn Error + 'static)> {
1558 match self {
1559 Self::Accept { source, .. } | Self::LocalAccept { source, .. } => Some(source),
1560 Self::NoListeners => None,
1561 }
1562 }
1563}
1564
1565#[derive(Debug)]
1566pub enum ConnectionError {
1567 Auth(AuthError),
1568 UnauthenticatedCapacity,
1569 FrameIo(FrameIoError),
1570 Router(RouterError),
1571 WriterTask(tokio::task::JoinError),
1572}
1573
1574impl ConnectionError {
1575 fn is_quiet_reject(&self) -> bool {
1576 matches!(self, Self::Auth(_) | Self::UnauthenticatedCapacity)
1577 }
1578
1579 fn pre_auth_reject_stage(&self) -> Option<PreAuthRejectStage> {
1580 match self {
1581 Self::UnauthenticatedCapacity => Some(PreAuthRejectStage::WaitingForHandshakeSlot),
1582 Self::Auth(AuthError::Timeout { .. }) => Some(PreAuthRejectStage::HandshakeDeadline),
1583 Self::Auth(
1584 AuthError::InvalidClientAuth
1585 | AuthError::InvalidServerProof
1586 | AuthError::DaemonIdMismatch,
1587 ) => Some(PreAuthRejectStage::InvalidProof),
1588 Self::Auth(AuthError::MessageTooLarge { .. } | AuthError::JsonDecode { .. }) => {
1589 Some(PreAuthRejectStage::MalformedMessage)
1590 }
1591 Self::Auth(AuthError::UnexpectedEof { .. }) => Some(PreAuthRejectStage::PeerClosed),
1592 Self::Auth(AuthError::Io { source, .. })
1593 if matches!(
1594 source.kind(),
1595 io::ErrorKind::BrokenPipe
1596 | io::ErrorKind::ConnectionAborted
1597 | io::ErrorKind::ConnectionReset
1598 | io::ErrorKind::UnexpectedEof
1599 ) =>
1600 {
1601 Some(PreAuthRejectStage::PeerClosed)
1602 }
1603 Self::Auth(_) => Some(PreAuthRejectStage::OtherAuthenticationFailure),
1604 Self::FrameIo(_) | Self::Router(_) | Self::WriterTask(_) => None,
1605 }
1606 }
1607
1608 fn auth_stage(&self) -> Option<AuthStage> {
1609 match self {
1610 Self::Auth(
1611 AuthError::Io { stage, .. }
1612 | AuthError::Timeout { stage, .. }
1613 | AuthError::UnexpectedEof { stage, .. }
1614 | AuthError::MessageTooLarge { stage, .. }
1615 | AuthError::JsonEncode { stage, .. }
1616 | AuthError::JsonDecode { stage, .. },
1617 ) => Some(*stage),
1618 Self::Auth(
1619 AuthError::Random(_)
1620 | AuthError::KeyTooShort { .. }
1621 | AuthError::InvalidServerProof
1622 | AuthError::DaemonIdMismatch
1623 | AuthError::InvalidClientAuth,
1624 )
1625 | Self::UnauthenticatedCapacity
1626 | Self::FrameIo(_)
1627 | Self::Router(_)
1628 | Self::WriterTask(_) => None,
1629 }
1630 }
1631}
1632
1633impl fmt::Display for ConnectionError {
1634 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1635 match self {
1636 Self::Auth(err) => write!(f, "connection auth failed: {err}"),
1637 Self::UnauthenticatedCapacity => write!(
1638 f,
1639 "too many concurrent unauthenticated subc TCP connections"
1640 ),
1641 Self::FrameIo(err) => write!(f, "frame connection error: {err}"),
1642 Self::Router(err) => write!(f, "router connection error: {err}"),
1643 Self::WriterTask(err) => write!(f, "connection writer task failed: {err}"),
1644 }
1645 }
1646}
1647
1648impl Error for ConnectionError {
1649 fn source(&self) -> Option<&(dyn Error + 'static)> {
1650 match self {
1651 Self::Auth(err) => Some(err),
1652 Self::FrameIo(err) => Some(err),
1653 Self::Router(err) => Some(err),
1654 Self::WriterTask(err) => Some(err),
1655 Self::UnauthenticatedCapacity => None,
1656 }
1657 }
1658}
1659
1660#[cfg(all(test, unix))]
1661#[path = "server/peer_liveness_test.rs"]
1662mod peer_liveness_test;
1663
1664#[cfg(test)]
1665mod tests {
1666 use std::{
1667 future::Future,
1668 pin::Pin,
1669 sync::atomic::{AtomicUsize, Ordering},
1670 task::{Context, Poll},
1671 };
1672
1673 use super::*;
1674 use serde::{de::DeserializeOwned, Serialize};
1675 use subc_protocol::{
1676 DecodeError, ErrorBody, Flags, FrameType, Priority, HEADER_LEN, PROTOCOL_VERSION,
1677 };
1678 use tokio::io::{duplex, AsyncReadExt, AsyncWriteExt, ReadBuf};
1679
1680 use subc_transport::{
1681 authenticate_client, compute_proof, ClientAuth, ClientHello, ConnectionInfo, Endpoint,
1682 ServerProof, CLIENT_AUTH_DOMAIN, NONCE_LEN, SCHEMA_VERSION,
1683 };
1684
1685 use crate::{ControlHandler, EchoBackend, Frame, ReadStage, Registry};
1686
1687 const TEST_DEADLINE: Duration = Duration::from_secs(2);
1688 const TEST_DAEMON_VER: &str = "test-subc-server";
1689
1690 #[test]
1694 fn egress_budget_is_the_published_delivered_frame_limit() {
1695 assert_eq!(
1696 CONNECTION_EGRESS_BYTE_BUDGET,
1697 subc_protocol::MAX_DELIVERED_FRAME_LEN
1698 );
1699 }
1700
1701 struct ObservedStream {
1702 inner: tokio::io::DuplexStream,
1703 write_blocked: Arc<tokio::sync::Notify>,
1704 dropped: Arc<AtomicUsize>,
1705 read_error: Option<tokio::sync::oneshot::Receiver<()>>,
1706 }
1707
1708 impl AsyncRead for ObservedStream {
1709 fn poll_read(
1710 mut self: Pin<&mut Self>,
1711 cx: &mut Context<'_>,
1712 buf: &mut ReadBuf<'_>,
1713 ) -> Poll<io::Result<()>> {
1714 if let Some(receiver) = self.read_error.as_mut() {
1715 match Pin::new(receiver).poll(cx) {
1716 Poll::Ready(Ok(())) => {
1717 self.read_error = None;
1718 return Poll::Ready(Err(io::ErrorKind::ConnectionReset.into()));
1719 }
1720 Poll::Ready(Err(_)) => self.read_error = None,
1721 Poll::Pending => {}
1722 }
1723 }
1724 Pin::new(&mut self.inner).poll_read(cx, buf)
1725 }
1726 }
1727
1728 impl AsyncWrite for ObservedStream {
1729 fn poll_write(
1730 mut self: Pin<&mut Self>,
1731 cx: &mut Context<'_>,
1732 buf: &[u8],
1733 ) -> Poll<io::Result<usize>> {
1734 let result = Pin::new(&mut self.inner).poll_write(cx, buf);
1735 if result.is_pending() {
1736 self.write_blocked.notify_one();
1737 }
1738 result
1739 }
1740
1741 fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1742 Pin::new(&mut self.inner).poll_flush(cx)
1743 }
1744
1745 fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1746 Pin::new(&mut self.inner).poll_shutdown(cx)
1747 }
1748 }
1749
1750 impl Drop for ObservedStream {
1751 fn drop(&mut self) {
1752 self.dropped.fetch_add(1, Ordering::SeqCst);
1753 }
1754 }
1755
1756 struct BlockedWriterConnection {
1757 client: tokio::io::DuplexStream,
1758 server: JoinHandle<Result<(), ConnectionError>>,
1759 stream_dropped: Arc<AtomicUsize>,
1760 read_error: Option<tokio::sync::oneshot::Sender<()>>,
1761 router: Arc<Router>,
1762 }
1763
1764 impl BlockedWriterConnection {
1765 async fn new() -> Self {
1766 let (mut client, inner) = duplex(256);
1767 let write_blocked = Arc::new(tokio::sync::Notify::new());
1768 let stream_dropped = Arc::new(AtomicUsize::new(0));
1769 let (read_error, receiver) = tokio::sync::oneshot::channel();
1770 let stream = ObservedStream {
1771 inner,
1772 write_blocked: Arc::clone(&write_blocked),
1773 dropped: Arc::clone(&stream_dropped),
1774 read_error: Some(receiver),
1775 };
1776 let (auth, conn) = test_auth();
1777 let router = echo_router();
1778 let server = tokio::spawn(handle_connection(stream, Arc::clone(&router), auth));
1779 authenticate(&mut client, &conn).await;
1780
1781 let _ = timeout(Duration::ZERO, write_blocked.notified()).await;
1784 write_frame(&mut client, &request(7, 1, &[b'x'; 1024]))
1785 .await
1786 .unwrap();
1787 timeout(TEST_DEADLINE, write_blocked.notified())
1788 .await
1789 .expect("writer should block on the unread echo reply");
1790 assert!(!server.is_finished());
1791 assert_eq!(stream_dropped.load(Ordering::SeqCst), 0);
1792 Self {
1793 client,
1794 server,
1795 stream_dropped,
1796 read_error: Some(read_error),
1797 router,
1798 }
1799 }
1800
1801 async fn finish(&mut self) -> Result<(), ConnectionError> {
1802 let started = tokio::time::Instant::now();
1803 let result = timeout(CLOSE_DRAIN_GRACE + Duration::from_secs(1), &mut self.server)
1804 .await
1805 .expect("connection teardown exceeded writer drain grace plus margin")
1806 .expect("connection task should not panic");
1807 assert!(started.elapsed() >= CLOSE_DRAIN_GRACE);
1808 assert_eq!(
1809 self.stream_dropped.load(Ordering::SeqCst),
1810 1,
1811 "writer must release its stream half before teardown completes"
1812 );
1813 result
1814 }
1815
1816 fn request_close(&self) {
1817 assert!(self.router.forwarding().request_connection_close(
1819 crate::registry::ConnectionId::new(1),
1820 CloseReason::new("test_close", "test requested close"),
1821 ));
1822 }
1823 }
1824
1825 #[tokio::test(start_paused = true)]
1826 async fn peer_eof_bounds_blocked_writer_teardown() {
1827 let mut connection = BlockedWriterConnection::new().await;
1828 connection.client.shutdown().await.unwrap();
1831 connection.finish().await.unwrap();
1832 }
1833
1834 #[tokio::test]
1835 async fn tcp_teardown_sends_eof_while_another_endpoint_copy_is_open() {
1836 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1837 let mut peer = tokio::net::TcpStream::connect(listener.local_addr().unwrap())
1838 .await
1839 .unwrap();
1840 let (stream, _) = listener.accept().await.unwrap();
1841 let inherited_copy = clone_tcp_socket(&stream).unwrap();
1844 let (auth, conn) = test_auth();
1845 let router = echo_router();
1846 let server = tokio::spawn(handle_connection(stream, Arc::clone(&router), auth));
1847 authenticate(&mut peer, &conn).await;
1848 write_frame(&mut peer, &request(7, 1, b"ready"))
1849 .await
1850 .unwrap();
1851 read_frame(&mut peer).await.unwrap().unwrap();
1852 assert!(router.forwarding().request_connection_close(
1853 crate::registry::ConnectionId::new(1),
1854 CloseReason::new("test_close", "test requested close"),
1855 ));
1856 timeout(TEST_DEADLINE, server)
1857 .await
1858 .unwrap()
1859 .unwrap()
1860 .unwrap();
1861 let mut byte = [0];
1862 assert_eq!(
1863 timeout(TEST_DEADLINE, peer.read(&mut byte))
1864 .await
1865 .expect("teardown must send EOF without waiting for inherited descriptors")
1866 .unwrap(),
1867 0,
1868 );
1869 drop(inherited_copy);
1870 }
1871
1872 #[tokio::test(start_paused = true)]
1873 async fn read_error_bounds_blocked_writer_teardown() {
1874 let mut connection = BlockedWriterConnection::new().await;
1875 connection.read_error.take().unwrap().send(()).unwrap();
1876 let error = connection.finish().await.unwrap_err();
1877 assert!(matches!(
1878 error,
1879 ConnectionError::FrameIo(FrameIoError::Io(error))
1880 if error.kind() == io::ErrorKind::ConnectionReset
1881 ));
1882 }
1883
1884 #[tokio::test(start_paused = true)]
1885 async fn close_requested_bounds_blocked_writer_teardown() {
1886 let mut connection = BlockedWriterConnection::new().await;
1887 connection.request_close();
1888 connection.finish().await.unwrap();
1889 }
1890
1891 #[tokio::test(start_paused = true)]
1892 async fn close_requested_flushes_queued_reply_before_grace() {
1893 let mut connection = BlockedWriterConnection::new().await;
1894 connection.request_close();
1895 let started = tokio::time::Instant::now();
1896 let reply = timeout(CLOSE_DRAIN_GRACE, read_frame(&mut connection.client))
1897 .await
1898 .expect("queued reply should flush before the grace expires")
1899 .unwrap()
1900 .unwrap();
1901 assert_eq!(reply.body, vec![b'x'; 1024]);
1902 timeout(CLOSE_DRAIN_GRACE, &mut connection.server)
1903 .await
1904 .unwrap()
1905 .unwrap()
1906 .unwrap();
1907 assert!(started.elapsed() < CLOSE_DRAIN_GRACE);
1908 assert_eq!(connection.stream_dropped.load(Ordering::SeqCst), 1);
1909 }
1910
1911 #[tokio::test]
1916 async fn stale_queued_control_reply_logs_slow_reply_write() {
1917 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
1918 let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(4);
1919 let reply = Frame::build_with_version(
1920 PROTOCOL_VERSION,
1921 FrameType::Error,
1922 Flags::new(false, Priority::Interactive, false),
1923 0,
1924 0,
1925 7,
1926 serde_json::to_vec(&ErrorBody {
1927 code: "test".into(),
1928 message: "reply".into(),
1929 detail: None,
1930 })
1931 .expect("body encodes"),
1932 )
1933 .expect("frame builds");
1934 tx.send(crate::router::OutboundFrame {
1935 frame: reply,
1936 enqueued_at: std::time::Instant::now() - Duration::from_millis(1500),
1937 flushed: None,
1938 charge: None,
1939 })
1940 .await
1941 .expect("queued");
1942 drop(tx);
1943 let (write_half, mut read_half) = duplex(64 * 1024);
1944 drain_writer(write_half, rx).await.expect("writer drains");
1945 let mut sink = Vec::new();
1946 read_half.read_to_end(&mut sink).await.expect("read");
1947 assert!(!sink.is_empty(), "frame reached the socket");
1948 let captured = crate::router::test_log::captured_logs(&logs);
1949 assert!(
1950 captured.contains("slow control reply write") && captured.contains("corr=7"),
1951 "expected slow reply WARN naming corr, got: {captured}"
1952 );
1953 let queued_ms: u64 = captured
1954 .split("queued_ms=")
1955 .nth(1)
1956 .and_then(|s| s.split_whitespace().next())
1957 .and_then(|s| s.parse().ok())
1958 .expect("queued_ms present");
1959 assert!(
1960 queued_ms >= 1500,
1961 "queued_ms reflects residency: {queued_ms}"
1962 );
1963 }
1964
1965 #[tokio::test]
1969 async fn fresh_control_and_stale_data_frames_log_nothing() {
1970 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
1971 let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(4);
1972 let control = Frame::build_with_version(
1973 PROTOCOL_VERSION,
1974 FrameType::Error,
1975 Flags::new(false, Priority::Interactive, false),
1976 0,
1977 0,
1978 8,
1979 serde_json::to_vec(&ErrorBody {
1980 code: "test".into(),
1981 message: "fresh".into(),
1982 detail: None,
1983 })
1984 .expect("body encodes"),
1985 )
1986 .expect("frame builds");
1987 tx.send(crate::router::OutboundFrame {
1988 frame: control,
1989 enqueued_at: std::time::Instant::now(),
1990 flushed: None,
1991 charge: None,
1992 })
1993 .await
1994 .expect("queued");
1995 let data = Frame::build_with_version(
1996 PROTOCOL_VERSION,
1997 FrameType::Error,
1998 Flags::new(false, Priority::Interactive, false),
1999 9,
2000 1,
2001 9,
2002 serde_json::to_vec(&ErrorBody {
2003 code: "test".into(),
2004 message: "data".into(),
2005 detail: None,
2006 })
2007 .expect("body encodes"),
2008 )
2009 .expect("frame builds");
2010 tx.send(crate::router::OutboundFrame {
2011 frame: data,
2012 enqueued_at: std::time::Instant::now() - Duration::from_millis(5000),
2013 flushed: None,
2014 charge: None,
2015 })
2016 .await
2017 .expect("queued");
2018 drop(tx);
2019 let (write_half, _read_half) = duplex(64 * 1024);
2020 drain_writer(write_half, rx).await.expect("writer drains");
2021 let captured = crate::router::test_log::captured_logs(&logs);
2022 assert!(
2023 !captured.contains("slow control reply write"),
2024 "no WARN for fresh control or stale data frames, got: {captured}"
2025 );
2026 }
2027
2028 struct CountingReader {
2029 bytes: Vec<u8>,
2030 offset: usize,
2031 first_read_end: Option<usize>,
2032 reads: Arc<AtomicUsize>,
2033 }
2034
2035 impl CountingReader {
2036 fn new(bytes: Vec<u8>, first_read_end: Option<usize>) -> (Self, Arc<AtomicUsize>) {
2037 let reads = Arc::new(AtomicUsize::new(0));
2038 (
2039 Self {
2040 bytes,
2041 offset: 0,
2042 first_read_end,
2043 reads: Arc::clone(&reads),
2044 },
2045 reads,
2046 )
2047 }
2048 }
2049
2050 impl AsyncRead for CountingReader {
2051 fn poll_read(
2052 mut self: Pin<&mut Self>,
2053 _cx: &mut Context<'_>,
2054 buf: &mut ReadBuf<'_>,
2055 ) -> Poll<io::Result<()>> {
2056 self.reads.fetch_add(1, Ordering::Relaxed);
2057 let available = self.bytes.len().saturating_sub(self.offset);
2058 let first_read_remaining = self
2059 .first_read_end
2060 .filter(|end| self.offset < *end)
2061 .map_or(available, |end| end - self.offset);
2062 let count = available.min(first_read_remaining).min(buf.remaining());
2063 let end = self.offset + count;
2064 buf.put_slice(&self.bytes[self.offset..end]);
2065 self.offset = end;
2066 Poll::Ready(Ok(()))
2067 }
2068 }
2069
2070 fn encode_frames(frames: &[Frame]) -> Vec<u8> {
2071 let mut bytes = Vec::new();
2072 for frame in frames {
2073 bytes.extend_from_slice(&frame.header.encode());
2074 bytes.extend_from_slice(&frame.body);
2075 }
2076 bytes
2077 }
2078
2079 async fn read_frames<R>(reader: &mut R, count: usize) -> Vec<Frame>
2080 where
2081 R: AsyncRead + Unpin,
2082 {
2083 let mut frames = Vec::with_capacity(count);
2084 for _ in 0..count {
2085 frames.push(read_frame(reader).await.unwrap().unwrap());
2086 }
2087 frames
2088 }
2089
2090 fn request(channel: u16, corr: u64, body: &[u8]) -> Frame {
2091 Frame::build(
2092 FrameType::Request,
2093 Flags::new(true, Priority::Interactive, false),
2094 channel,
2095 0,
2096 corr,
2097 body.to_vec(),
2098 )
2099 .unwrap()
2100 }
2101
2102 fn echo_router() -> Arc<Router> {
2103 let mut router = Router::with_default_self_handler();
2104 router.register_backend(7, EchoBackend).unwrap();
2105 router.register_backend(9, EchoBackend).unwrap();
2106 Arc::new(router)
2107 }
2108
2109 fn test_auth() -> (ServerAuth, ConnectionInfo) {
2110 test_auth_with_limit(4)
2111 }
2112
2113 fn test_auth_with_limit(max_unauthenticated: usize) -> (ServerAuth, ConnectionInfo) {
2114 test_auth_with_deadline_and_limit(TEST_DEADLINE, max_unauthenticated)
2115 }
2116
2117 fn test_auth_with_deadline_and_limit(
2118 deadline: Duration,
2119 max_unauthenticated: usize,
2120 ) -> (ServerAuth, ConnectionInfo) {
2121 let key = vec![0x42; 32];
2122 let daemon_id = [0x24; 16];
2123 let conn = ConnectionInfo {
2124 schema: SCHEMA_VERSION,
2125 wire_version: None,
2126 endpoints: vec![Endpoint {
2127 host: "127.0.0.1".to_owned(),
2128 port: 1,
2129 }],
2130 key: key.clone(),
2131 daemon_id,
2132 pid: std::process::id(),
2133 daemon_ver: TEST_DAEMON_VER.to_owned(),
2134 };
2135 (
2136 ServerAuth::with_limits(
2137 key,
2138 daemon_id,
2139 TEST_DAEMON_VER,
2140 deadline,
2141 max_unauthenticated,
2142 ),
2143 conn,
2144 )
2145 }
2146
2147 async fn authenticate<S>(stream: &mut S, conn: &ConnectionInfo)
2148 where
2149 S: AsyncRead + AsyncWrite + Unpin,
2150 {
2151 authenticate_client(stream, conn, TEST_DEADLINE)
2152 .await
2153 .expect("test client should authenticate")
2154 }
2155
2156 async fn write_auth_message<S, T>(stream: &mut S, value: &T)
2157 where
2158 S: AsyncWrite + Unpin,
2159 T: Serialize,
2160 {
2161 let body = serde_json::to_vec(value).expect("auth message encodes");
2162 stream
2163 .write_all(&(body.len() as u32).to_le_bytes())
2164 .await
2165 .expect("auth message length writes");
2166 stream
2167 .write_all(&body)
2168 .await
2169 .expect("auth message body writes");
2170 }
2171
2172 async fn read_auth_message<S, T>(stream: &mut S) -> T
2173 where
2174 S: AsyncRead + Unpin,
2175 T: DeserializeOwned,
2176 {
2177 let mut length = [0; 4];
2178 stream
2179 .read_exact(&mut length)
2180 .await
2181 .expect("auth message length reads");
2182 let mut body = vec![0; u32::from_le_bytes(length) as usize];
2183 stream
2184 .read_exact(&mut body)
2185 .await
2186 .expect("auth message body reads");
2187 serde_json::from_slice(&body).expect("auth message decodes")
2188 }
2189
2190 async fn send_wrong_key_client_auth<S>(stream: &mut S, conn: &ConnectionInfo)
2191 where
2192 S: AsyncRead + AsyncWrite + Unpin,
2193 {
2194 let hello = ClientHello {
2195 client_nonce: [0x57; NONCE_LEN],
2196 role: "client".to_owned(),
2197 };
2198 write_auth_message(stream, &hello).await;
2199 let proof: ServerProof = read_auth_message(stream).await;
2200 let mut wrong_key = conn.key.clone();
2201 wrong_key[0] ^= 0xff;
2202 let client_auth = ClientAuth {
2203 client_auth: compute_proof(
2204 &wrong_key,
2205 CLIENT_AUTH_DOMAIN,
2206 &hello.client_nonce,
2207 &proof.server_nonce,
2208 &conn.daemon_id,
2209 ),
2210 };
2211 write_auth_message(stream, &client_auth).await;
2212 }
2213
2214 fn assert_pre_auth_log(logs: &Arc<std::sync::Mutex<Vec<u8>>>, stage: &str, port: u16) {
2215 let captured = crate::router::test_log::captured_logs(logs);
2216 assert!(
2217 captured.contains(&format!("stage=\"{stage}\"")),
2218 "expected rejection stage {stage}, got: {captured}"
2219 );
2220 assert!(
2221 captured.contains(&format!("peer_addr=127.0.0.1:{port}")),
2222 "expected peer address, got: {captured}"
2223 );
2224 assert!(
2225 captured.contains("elapsed_ms=") && captured.contains("suppressed_since_last="),
2226 "expected elapsed time and suppression count, got: {captured}"
2227 );
2228 assert!(
2229 !captured.contains("WARN"),
2230 "pre-auth rejection must not be logged as a warning: {captured}"
2231 );
2232 }
2233
2234 #[tokio::test]
2235 async fn logs_handshake_deadline_pre_auth_rejection() {
2236 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2237 let deadline = Duration::from_millis(60);
2238 let (auth, _) = test_auth_with_deadline_and_limit(deadline, 4);
2239 let (client, server_stream) = duplex(512);
2240 let port = 41001;
2241 let server = handle_accepted_connection(
2242 server_stream,
2243 echo_router(),
2244 auth,
2245 SocketAddr::from(([127, 0, 0, 1], port)),
2246 Instant::now(),
2247 );
2248
2249 let error = tokio::time::timeout(deadline * 3, server)
2250 .await
2251 .expect("idle handshake should end at its deadline")
2252 .expect_err("idle handshake must be rejected");
2253 drop(client);
2254 assert!(matches!(
2255 error,
2256 ConnectionError::Auth(AuthError::Timeout {
2257 stage: AuthStage::ClientHello,
2258 ..
2259 })
2260 ));
2261 let captured = crate::router::test_log::captured_logs(&logs);
2262 assert!(
2263 captured.contains("reason=\"handshake_deadline_expired\""),
2264 "{captured}"
2265 );
2266 assert_pre_auth_log(&logs, "handshake_deadline", port);
2267 }
2268
2269 #[tokio::test]
2270 async fn logs_invalid_client_proof_pre_auth_rejection() {
2271 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2272 let (auth, conn) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2273 let (mut client, server_stream) = duplex(512);
2274 let port = 41002;
2275 let server = handle_accepted_connection(
2276 server_stream,
2277 echo_router(),
2278 auth,
2279 SocketAddr::from(([127, 0, 0, 1], port)),
2280 Instant::now(),
2281 );
2282
2283 let (error, ()) = tokio::join!(server, send_wrong_key_client_auth(&mut client, &conn));
2284 assert!(matches!(
2285 error,
2286 Err(ConnectionError::Auth(AuthError::InvalidClientAuth))
2287 ));
2288 let captured = crate::router::test_log::captured_logs(&logs);
2289 assert!(
2290 captured.contains("reason=\"client_proof_mismatch\""),
2291 "{captured}"
2292 );
2293 assert_pre_auth_log(&logs, "client_authentication", port);
2294 }
2295
2296 #[tokio::test]
2297 async fn logs_malformed_pre_auth_message() {
2298 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2299 let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2300 let (mut client, server_stream) = duplex(512);
2301 let port = 41003;
2302 let server = handle_accepted_connection(
2303 server_stream,
2304 echo_router(),
2305 auth,
2306 SocketAddr::from(([127, 0, 0, 1], port)),
2307 Instant::now(),
2308 );
2309 let send_malformed_message = async {
2310 let body = b"{";
2311 client
2312 .write_all(&(body.len() as u32).to_le_bytes())
2313 .await
2314 .expect("message length writes");
2315 client.write_all(body).await.expect("message body writes");
2316 };
2317
2318 let (error, ()) = tokio::join!(server, send_malformed_message);
2319 assert!(matches!(
2320 error,
2321 Err(ConnectionError::Auth(AuthError::JsonDecode {
2322 stage: AuthStage::ClientHello,
2323 ..
2324 }))
2325 ));
2326 let captured = crate::router::test_log::captured_logs(&logs);
2327 assert!(
2328 captured.contains("reason=\"malformed_or_oversized_message\""),
2329 "{captured}"
2330 );
2331 assert_pre_auth_log(&logs, "malformed_message", port);
2332 }
2333
2334 #[tokio::test]
2335 async fn logs_peer_close_during_handshake() {
2336 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2337 let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2338 let (client, server_stream) = duplex(512);
2339 let port = 41004;
2340 drop(client);
2341
2342 let error = handle_accepted_connection(
2343 server_stream,
2344 echo_router(),
2345 auth,
2346 SocketAddr::from(([127, 0, 0, 1], port)),
2347 Instant::now(),
2348 )
2349 .await
2350 .expect_err("closed peer must be rejected");
2351 assert!(matches!(
2352 error,
2353 ConnectionError::Auth(AuthError::UnexpectedEof {
2354 stage: AuthStage::ClientHello,
2355 actual: 0,
2356 ..
2357 })
2358 ));
2359 let captured = crate::router::test_log::captured_logs(&logs);
2360 assert!(
2361 captured.contains("reason=\"peer_closed_before_authentication_completed\""),
2362 "{captured}"
2363 );
2364 assert_pre_auth_log(&logs, "peer_closed", port);
2365 }
2366
2367 #[tokio::test]
2371 async fn each_listener_rate_limits_its_own_rejection_logs() {
2372 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2373 for port in [41011, 41012] {
2374 let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2375 let (client, server_stream) = duplex(512);
2376 drop(client);
2377 handle_accepted_connection(
2378 server_stream,
2379 echo_router(),
2380 auth,
2381 SocketAddr::from(([127, 0, 0, 1], port)),
2382 Instant::now(),
2383 )
2384 .await
2385 .expect_err("closed peer must be rejected");
2386 }
2387 let captured = crate::router::test_log::captured_logs(&logs);
2388 for port in [41011, 41012] {
2389 assert!(
2390 captured.contains(&format!("127.0.0.1:{port}")),
2391 "listener on port {port} logged nothing: {captured}"
2392 );
2393 }
2394 }
2395
2396 #[tokio::test]
2397 async fn logs_unauthenticated_capacity_rejection() {
2398 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2399 let deadline = Duration::from_millis(60);
2400 let (auth, _) = test_auth_with_deadline_and_limit(deadline, 1);
2401 let held_slot = auth
2402 .unauthenticated
2403 .clone()
2404 .try_acquire_owned()
2405 .expect("the only pre-auth slot is available");
2406 let (client, server_stream) = duplex(512);
2407 let port = 41005;
2408 let server = handle_accepted_connection(
2409 server_stream,
2410 echo_router(),
2411 auth,
2412 SocketAddr::from(([127, 0, 0, 1], port)),
2413 Instant::now(),
2414 );
2415
2416 let error = tokio::time::timeout(deadline * 3, server)
2417 .await
2418 .expect("queued connection should end at the capacity deadline")
2419 .expect_err("connection without a free slot must be rejected");
2420 drop(held_slot);
2421 drop(client);
2422 assert!(matches!(error, ConnectionError::UnauthenticatedCapacity));
2423 let captured = crate::router::test_log::captured_logs(&logs);
2424 assert!(
2425 captured.contains("reason=\"capacity_wait_timed_out\""),
2426 "{captured}"
2427 );
2428 assert_pre_auth_log(&logs, "waiting_for_handshake_slot", port);
2429 }
2430
2431 #[test]
2432 fn pre_auth_rejection_limiter_suppresses_bursts_and_reports_count() {
2433 let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2434 let limiter = PreAuthRejectLimiter::new();
2435 let capacity = ConnectionError::UnauthenticatedCapacity;
2436 let handshake_timeout = ConnectionError::Auth(AuthError::Timeout {
2437 stage: AuthStage::ClientHello,
2438 deadline: Duration::from_millis(200),
2439 });
2440 let peer_addr = SocketAddr::from(([127, 0, 0, 1], 41006));
2441
2442 log_pre_auth_rejection(
2443 &capacity,
2444 peer_addr,
2445 Duration::from_millis(1),
2446 Duration::ZERO,
2447 &limiter,
2448 );
2449 for _ in 0..4 {
2450 log_pre_auth_rejection(
2451 &capacity,
2452 peer_addr,
2453 Duration::from_millis(2),
2454 Duration::from_millis(100),
2455 &limiter,
2456 );
2457 }
2458 log_pre_auth_rejection(
2459 &handshake_timeout,
2460 peer_addr,
2461 Duration::from_millis(3),
2462 Duration::from_millis(100),
2463 &limiter,
2464 );
2465 log_pre_auth_rejection(
2466 &capacity,
2467 peer_addr,
2468 Duration::from_millis(4),
2469 Duration::from_secs(1),
2470 &limiter,
2471 );
2472
2473 let captured = crate::router::test_log::captured_logs(&logs);
2474 assert_eq!(
2475 captured
2476 .matches("subc TCP connection rejected before routing")
2477 .count(),
2478 3,
2479 "one line per stage in a burst, then a later capacity line: {captured}"
2480 );
2481 assert!(
2482 captured.contains("suppressed_since_last=4"),
2483 "later capacity line should report the four hidden rejects: {captured}"
2484 );
2485 assert!(
2486 captured.contains("stage=\"handshake_deadline\""),
2487 "{captured}"
2488 );
2489 }
2490
2491 #[tokio::test]
2492 async fn buffered_frame_reader_coalesces_reads_and_preserves_short_reads() {
2493 let frames = vec![
2494 request(7, 1, b"first"),
2495 request(9, 2, b"second"),
2496 request(7, 3, b"third"),
2497 request(9, 4, b"fourth"),
2498 ];
2499 let bytes = encode_frames(&frames);
2500
2501 let (mut direct, direct_reads) = CountingReader::new(bytes.clone(), None);
2502 assert_eq!(read_frames(&mut direct, frames.len()).await, frames);
2503 assert_eq!(direct_reads.load(Ordering::Relaxed), frames.len() * 3);
2504
2505 let (buffered_source, buffered_reads) = CountingReader::new(bytes, None);
2506 let mut buffered = BufReader::new(buffered_source);
2507 assert_eq!(read_frames(&mut buffered, frames.len()).await, frames);
2508 assert_eq!(buffered_reads.load(Ordering::Relaxed), 1);
2509
2510 let split_frame = request(7, 5, b"split-body");
2511 let split_bytes = encode_frames(std::slice::from_ref(&split_frame));
2512 let (split_source, split_reads) = CountingReader::new(split_bytes, Some(10));
2513 let mut split_reader = BufReader::new(split_source);
2514 assert_eq!(
2515 read_frame(&mut split_reader).await.unwrap(),
2516 Some(split_frame)
2517 );
2518 assert_eq!(split_reads.load(Ordering::Relaxed), 2);
2519 }
2520
2521 #[tokio::test]
2522 async fn interleaved_channels_on_one_stream_demux_byte_identically_after_auth() {
2523 let (mut client, server_stream) = duplex(4096);
2524 let (auth, conn) = test_auth();
2525 let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
2526 authenticate(&mut client, &conn).await;
2527 let frames = [
2528 request(7, 1, b"chan7-first\0opaque"),
2529 request(9, 2, b"chan9-middle-{json?}"),
2530 request(7, 3, b"chan7-second\xffbytes"),
2531 ];
2532
2533 for frame in &frames {
2534 crate::write_frame(&mut client, frame).await.unwrap();
2535 }
2536
2537 for expected in &frames {
2538 let response = crate::read_frame(&mut client).await.unwrap().unwrap();
2539 assert_eq!(response.header.ty, FrameType::Response);
2540 assert_eq!(response.header.channel, expected.header.channel);
2541 assert_eq!(response.header.corr, expected.header.corr);
2542 assert_eq!(response.body, expected.body);
2543 }
2544
2545 drop(client);
2546 server.await.unwrap().unwrap();
2547 }
2548
2549 #[tokio::test]
2550 async fn channel_zero_goes_to_subc_self_handler_after_auth() {
2551 let (mut client, server_stream) = duplex(512);
2552 let (auth, conn) = test_auth();
2553 let server = tokio::spawn(handle_connection(
2554 server_stream,
2555 Arc::new(Router::with_default_self_handler()),
2556 auth,
2557 ));
2558 authenticate(&mut client, &conn).await;
2559 let ping = Frame::build(
2560 FrameType::Ping,
2561 Flags::new(false, Priority::Passive, false),
2562 0,
2563 0,
2564 55,
2565 Vec::new(),
2566 )
2567 .unwrap();
2568
2569 crate::write_frame(&mut client, &ping).await.unwrap();
2570 let response = crate::read_frame(&mut client).await.unwrap().unwrap();
2571
2572 assert_eq!(response.header.ty, FrameType::Pong);
2573 assert_eq!(response.header.channel, 0);
2574 assert_eq!(response.header.corr, 55);
2575 assert!(response.body.is_empty());
2576
2577 drop(client);
2578 server.await.unwrap().unwrap();
2579 }
2580
2581 #[tokio::test]
2582 async fn unauthenticated_connection_is_rejected_before_routing() {
2583 let (mut client, server_stream) = duplex(512);
2584 let (auth, _conn) = test_auth();
2585 let registry = Arc::new(Registry::default());
2586 let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
2587 Arc::clone(®istry),
2588 ))));
2589 let server = tokio::spawn(handle_connection(server_stream, router, auth));
2590 let ping = Frame::build(
2591 FrameType::Ping,
2592 Flags::new(false, Priority::Passive, false),
2593 0,
2594 0,
2595 66,
2596 Vec::new(),
2597 )
2598 .unwrap();
2599
2600 crate::write_frame(&mut client, &ping).await.unwrap();
2601 if let Ok(Ok(Some(frame))) =
2602 tokio::time::timeout(Duration::from_millis(200), crate::read_frame(&mut client)).await
2603 {
2604 panic!("unauthenticated frame reached router: {frame:?}");
2605 }
2606
2607 let err = server.await.unwrap().unwrap_err();
2608 assert!(matches!(err, ConnectionError::Auth(_)));
2609 assert_eq!(registry.active_registration_count().unwrap(), 0);
2610 }
2611
2612 #[tokio::test]
2613 async fn over_cap_peer_queues_for_a_slot_and_authenticates_when_one_frees() {
2614 let (mut first_client, first_server_stream) = duplex(2048);
2619 let (mut second_client, second_server_stream) = duplex(2048);
2620 let (auth, conn) = test_auth_with_limit(1);
2621 let registry = Arc::new(Registry::default());
2622 let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
2623 Arc::clone(®istry),
2624 ))));
2625
2626 let first_server = tokio::spawn(handle_connection(
2627 first_server_stream,
2628 Arc::clone(&router),
2629 auth.clone(),
2630 ));
2631
2632 let second_server = tokio::spawn(handle_connection(
2633 second_server_stream,
2634 Arc::clone(&router),
2635 auth.clone(),
2636 ));
2637
2638 tokio::time::sleep(Duration::from_millis(50)).await;
2640 assert!(
2641 !second_server.is_finished(),
2642 "queued peer must not be reset"
2643 );
2644
2645 authenticate(&mut first_client, &conn).await;
2648 authenticate(&mut second_client, &conn).await;
2649
2650 drop(first_client);
2651 drop(second_client);
2652 let _ = first_server.await;
2653 let _ = second_server.await;
2654 assert_eq!(registry.active_registration_count().unwrap(), 0);
2655 }
2656
2657 #[tokio::test]
2658 async fn over_cap_peer_is_rejected_when_no_slot_frees_within_deadline() {
2659 let (mut second_client, second_server_stream) = duplex(512);
2665 let (auth, conn) = test_auth_with_limit(1);
2666 let registry = Arc::new(Registry::default());
2667 let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
2668 Arc::clone(®istry),
2669 ))));
2670
2671 let held_slot = auth
2672 .unauthenticated
2673 .clone()
2674 .try_acquire_owned()
2675 .expect("sole pre-auth slot");
2676
2677 let second_server = tokio::spawn(handle_connection(
2678 second_server_stream,
2679 Arc::clone(&router),
2680 auth.clone(),
2681 ));
2682 let second_err = tokio::time::timeout(TEST_DEADLINE * 2, second_server)
2683 .await
2684 .expect("capacity reject should settle at the deadline")
2685 .expect("second connection task should not panic")
2686 .expect_err("queued peer must be rejected when no slot frees");
2687 drop(held_slot);
2688 assert!(matches!(
2689 second_err,
2690 ConnectionError::UnauthenticatedCapacity
2691 ));
2692 let mut closed = [0u8; 1];
2693 assert_eq!(
2694 second_client.read(&mut closed).await.unwrap(),
2695 0,
2696 "capacity-rejected peer should observe a closed stream"
2697 );
2698 assert_eq!(registry.active_registration_count().unwrap(), 0);
2699
2700 let (mut authed_client, authed_server_stream) = duplex(2048);
2701 let authed_server = tokio::spawn(handle_connection(
2702 authed_server_stream,
2703 Arc::clone(&router),
2704 auth,
2705 ));
2706 authenticate(&mut authed_client, &conn).await;
2707 let ping = Frame::build(
2708 FrameType::Ping,
2709 Flags::new(false, Priority::Passive, false),
2710 0,
2711 0,
2712 77,
2713 Vec::new(),
2714 )
2715 .unwrap();
2716 crate::write_frame(&mut authed_client, &ping).await.unwrap();
2717 let pong = crate::read_frame(&mut authed_client)
2718 .await
2719 .unwrap()
2720 .unwrap();
2721 assert_eq!(pong.header.ty, FrameType::Pong);
2722 assert_eq!(pong.header.channel, 0);
2723 assert_eq!(pong.header.corr, 77);
2724 assert_eq!(registry.active_registration_count().unwrap(), 0);
2725
2726 drop(authed_client);
2727 authed_server.await.unwrap().unwrap();
2728 }
2729
2730 #[tokio::test]
2731 async fn bind_ack_during_partial_frame_preserves_next_request() {
2732 use subc_control::ClientControlRequest;
2733 use subc_protocol::{
2734 manifest::{
2735 Concurrency, ExecutionMode, IdentityScope, ModuleManifest, ProviderRole, Tool,
2736 },
2737 session::{ModuleControlRequest, ModuleControlResponse},
2738 BindIdentity, ModuleHelloBody, RouteTarget,
2739 };
2740
2741 let mut configured_router = Router::with_default_self_handler();
2742 configured_router.register_backend(7, EchoBackend).unwrap();
2743 let router = Arc::new(configured_router);
2744 let (auth, conn) = test_auth();
2745 let (mut module, module_stream) = duplex(4096);
2746 let module_server = tokio::spawn(handle_connection(
2747 module_stream,
2748 Arc::clone(&router),
2749 auth.clone(),
2750 ));
2751 authenticate(&mut module, &conn).await;
2752 let manifest = ModuleManifest::builder("frame-test", "0.1.0")
2753 .protocol_ver(PROTOCOL_VERSION)
2754 .provides(vec![ProviderRole::ToolProvider {
2755 tools: vec![Tool {
2756 name: "read".into(),
2757 description: None,
2758 execution_mode: ExecutionMode::Pure,
2759 schema: serde_json::json!({"type": "object"}),
2760 }],
2761 identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
2762 concurrency: Concurrency::ModuleManaged,
2763 emits_push: true,
2764 sub_supervises: true,
2765 }])
2766 .build();
2767 let hello = Frame::build(
2768 FrameType::Hello,
2769 Flags::new(false, Priority::Passive, false),
2770 0,
2771 0,
2772 1,
2773 serde_json::to_vec(&ModuleHelloBody {
2774 manifest,
2775 protocol_ver: PROTOCOL_VERSION,
2776 control_ops: None,
2777 launch_nonce: None,
2778 })
2779 .unwrap(),
2780 )
2781 .unwrap();
2782 crate::write_frame(&mut module, &hello).await.unwrap();
2783 assert_eq!(
2784 read_frame(&mut module).await.unwrap().unwrap().header.ty,
2785 FrameType::HelloAck
2786 );
2787
2788 let (mut client, client_stream) = duplex(4096);
2789 let client_server = tokio::spawn(handle_connection(client_stream, router, auth));
2790 authenticate(&mut client, &conn).await;
2791 let open = Frame::build(
2792 FrameType::Request,
2793 Flags::new(false, Priority::Passive, false),
2794 0,
2795 0,
2796 2,
2797 serde_json::to_vec(&ClientControlRequest::RouteOpen {
2798 busy_refusals: None,
2799 target: RouteTarget::ToolProvider {
2800 module_id: "frame-test".into(),
2801 },
2802 identity: BindIdentity::new("unit", "session"),
2803 consumer_identity: None,
2804 consumer_capabilities: None,
2805 role_versions: None,
2806 admission_facts: None,
2807 scope: None,
2808 })
2809 .unwrap(),
2810 )
2811 .unwrap();
2812 crate::write_frame(&mut client, &open).await.unwrap();
2813 let bind = timeout(TEST_DEADLINE, read_frame(&mut module))
2814 .await
2815 .unwrap()
2816 .unwrap()
2817 .unwrap();
2818 assert!(matches!(
2819 serde_json::from_slice::<ModuleControlRequest>(&bind.body).unwrap(),
2820 ModuleControlRequest::RouteBind { .. }
2821 ));
2822
2823 let ping = request(7, 3, b"partial-frame-body");
2824 client.write_all(&ping.header.encode()).await.unwrap();
2825 tokio::time::sleep(Duration::from_millis(30)).await;
2827 let ack = Frame::build(
2828 FrameType::Response,
2829 Flags::new(false, Priority::Passive, false),
2830 0,
2831 0,
2832 bind.header.corr,
2833 serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap(),
2834 )
2835 .unwrap();
2836 crate::write_frame(&mut module, &ack).await.unwrap();
2837 let opened = timeout(TEST_DEADLINE, read_frame(&mut client))
2838 .await
2839 .unwrap()
2840 .unwrap();
2841 if opened.is_none() {
2842 panic!("client closed: {:?}", client_server.await);
2843 }
2844 let opened = opened.unwrap();
2845 assert_eq!(opened.header.corr, 2);
2846 client.write_all(&ping.body).await.unwrap();
2847 let pong = timeout(TEST_DEADLINE, read_frame(&mut client))
2848 .await
2849 .expect("partial frame must reach the router after the bind ack")
2850 .expect("frame must decode")
2851 .expect("connection must remain open");
2852 assert_eq!(pong.header.ty, FrameType::Response);
2853 assert_eq!(pong.header.corr, 3);
2854 assert_eq!(pong.body, ping.body);
2855 drop(client);
2856 drop(module);
2857 client_server.await.unwrap().unwrap();
2858 let _ = module_server.await.unwrap();
2859 }
2860
2861 #[tokio::test]
2862 async fn full_module_egress_health_probe_does_not_block_same_client_other_route() {
2863 use crate::ConnectionId;
2864 use subc_control::{ClientControlRequest, ClientControlResponse};
2865 use subc_protocol::{
2866 manifest::{
2867 Concurrency, ExecutionMode, IdentityScope, ModuleManifest, ProviderRole, Tool,
2868 },
2869 session::ModuleControlResponse,
2870 BindIdentity, ModuleHelloBody, RouteTarget,
2871 };
2872
2873 let probe_timeout = Duration::from_millis(100);
2874 let handler = Arc::new(
2875 ControlHandler::new(Arc::new(Registry::default()))
2876 .with_health_probe_timeout(probe_timeout),
2877 );
2878 let router = Arc::new(Router::with_control_handler(Arc::clone(&handler)));
2879 let hello = |name: &str| {
2880 Frame::build(
2881 FrameType::Hello,
2882 Flags::new(false, Priority::Passive, false),
2883 0,
2884 0,
2885 1,
2886 serde_json::to_vec(&ModuleHelloBody {
2887 manifest: ModuleManifest::builder(name, "0.1.0")
2888 .protocol_ver(PROTOCOL_VERSION)
2889 .provides(vec![ProviderRole::ToolProvider {
2890 tools: vec![Tool {
2891 name: "read".into(),
2892 description: None,
2893 execution_mode: ExecutionMode::Pure,
2894 schema: serde_json::json!({"type": "object"}),
2895 }],
2896 identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
2897 concurrency: Concurrency::ModuleManaged,
2898 emits_push: false,
2899 sub_supervises: false,
2900 }])
2901 .build(),
2902 protocol_ver: PROTOCOL_VERSION,
2903 control_ops: Some(vec!["health.check".to_owned()]),
2904 launch_nonce: None,
2905 })
2906 .unwrap(),
2907 )
2908 .unwrap()
2909 };
2910 let (blocked_tx, mut blocked_rx) = mpsc::channel(1);
2911 let blocked_ctx = RouteCtx {
2912 connection_id: ConnectionId::new(90001),
2913 egress: FrameSink::new(blocked_tx),
2914 };
2915 handler
2916 .handle_control_frame(&blocked_ctx, hello("blocked"))
2917 .await
2918 .unwrap();
2919 assert_eq!(
2920 blocked_rx.try_recv().unwrap().header.ty,
2921 FrameType::HelloAck
2922 );
2923 let filler = request(0, 99, b"queue filler");
2924 blocked_ctx.egress.try_send(filler.clone()).unwrap();
2925 assert!(
2926 blocked_ctx.egress.try_send(filler).is_err(),
2927 "module queue must actually be full"
2928 );
2929
2930 let (healthy_tx, mut healthy_rx) = mpsc::channel(8);
2931 let healthy_ctx = RouteCtx {
2932 connection_id: ConnectionId::new(90002),
2933 egress: FrameSink::new(healthy_tx),
2934 };
2935 handler
2936 .handle_control_frame(&healthy_ctx, hello("healthy"))
2937 .await
2938 .unwrap();
2939 assert_eq!(
2940 healthy_rx.try_recv().unwrap().header.ty,
2941 FrameType::HelloAck
2942 );
2943 let (auth, conn) = test_auth();
2944 let (mut client, client_stream) = duplex(4096);
2945 let client_server =
2946 tokio::spawn(handle_connection(client_stream, Arc::clone(&router), auth));
2947 authenticate(&mut client, &conn).await;
2948 let control_request = |corr, body: ClientControlRequest| {
2949 Frame::build(
2950 FrameType::Request,
2951 Flags::new(false, Priority::Interactive, false),
2952 0,
2953 0,
2954 corr,
2955 serde_json::to_vec(&body).unwrap(),
2956 )
2957 .unwrap()
2958 };
2959 crate::write_frame(
2960 &mut client,
2961 &control_request(
2962 2,
2963 ClientControlRequest::RouteOpen {
2964 busy_refusals: None,
2965 target: RouteTarget::ToolProvider {
2966 module_id: "healthy".into(),
2967 },
2968 identity: BindIdentity::new("unit", "session"),
2969 consumer_identity: None,
2970 consumer_capabilities: None,
2971 role_versions: None,
2972 admission_facts: None,
2973 scope: None,
2974 },
2975 ),
2976 )
2977 .await
2978 .unwrap();
2979 let bind = timeout(TEST_DEADLINE, healthy_rx.recv())
2980 .await
2981 .unwrap()
2982 .unwrap();
2983 handler
2984 .handle_control_frame(
2985 &healthy_ctx,
2986 Frame::build(
2987 FrameType::Response,
2988 Flags::new(false, Priority::Passive, false),
2989 0,
2990 0,
2991 bind.header.corr,
2992 serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap(),
2993 )
2994 .unwrap(),
2995 )
2996 .await
2997 .unwrap();
2998 let opened = timeout(TEST_DEADLINE, read_frame(&mut client))
2999 .await
3000 .unwrap()
3001 .unwrap()
3002 .unwrap();
3003 let (channel, epoch) =
3004 match serde_json::from_slice::<ClientControlResponse>(&opened.body).unwrap() {
3005 ClientControlResponse::RouteOpen {
3006 route_channel,
3007 route_epoch,
3008 ..
3009 } => (route_channel, route_epoch),
3010 other => panic!("expected a healthy module route, got {other:?}"),
3011 };
3012
3013 let probe = control_request(
3014 3,
3015 ClientControlRequest::SupervisorHealthProbe {
3016 module_id: "blocked".into(),
3017 },
3018 );
3019 let mut ping = request(channel, 4, b"healthy request");
3020 ping.header.epoch = epoch;
3021 crate::write_frame(&mut client, &probe).await.unwrap();
3022 crate::write_frame(&mut client, &ping).await.unwrap();
3023 timeout(probe_timeout + Duration::from_secs(1), async {
3024 let timed_out = read_frame(&mut client).await.unwrap().unwrap();
3025 assert_eq!(timed_out.header.corr, 3);
3026 assert_eq!(timed_out.header.ty, FrameType::Error);
3027 let error: ErrorBody = serde_json::from_slice(&timed_out.body).unwrap();
3028 assert_eq!(error.code, "module_timeout");
3029 let forwarded = healthy_rx.recv().await.unwrap();
3030 assert_eq!(forwarded.header.corr, ping.header.corr);
3031 assert_eq!(forwarded.body, ping.body);
3032 let reply = Frame::build(
3033 FrameType::Response,
3034 ping.header.flags,
3035 forwarded.header.channel,
3036 forwarded.header.epoch,
3037 forwarded.header.corr,
3038 b"healthy response".to_vec(),
3039 )
3040 .unwrap();
3041 router
3042 .route_for_connection(&healthy_ctx, reply)
3043 .await
3044 .unwrap();
3045 let pong = read_frame(&mut client).await.unwrap().unwrap();
3046 assert_eq!(pong.header.ty, FrameType::Response);
3047 assert_eq!(pong.header.channel, channel);
3048 assert_eq!(pong.header.epoch, epoch);
3049 assert_eq!(pong.header.corr, 4);
3050 assert_eq!(pong.body, b"healthy response");
3051 })
3052 .await
3053 .expect(
3054 "the same client's healthy route must answer within the probe deadline plus margin",
3055 );
3056 assert_eq!(
3057 blocked_rx.len(),
3058 1,
3059 "the blocked module must remain undrained"
3060 );
3061 assert_eq!(blocked_rx.try_recv().unwrap().header.corr, 99);
3062 assert!(
3063 blocked_rx.try_recv().is_err(),
3064 "a timed-out probe must not be enqueued later"
3065 );
3066 drop(client);
3067 client_server.await.unwrap().unwrap();
3068 }
3069
3070 #[tokio::test]
3071 async fn aborted_accept_does_not_end_listener() {
3072 let listener = Arc::new(TcpListener::bind("127.0.0.1:0").await.unwrap());
3073 let addr = listener.local_addr().unwrap();
3074 let (auth, conn) = test_auth();
3075 let mut attempts = 0;
3076 let server = tokio::spawn(serve_listener_with_accept(
3077 Some(addr),
3078 echo_router(),
3079 auth,
3080 move || {
3081 attempts += 1;
3082 let result = if attempts == 1 {
3083 Some(io::Error::from(io::ErrorKind::ConnectionAborted))
3084 } else {
3085 None
3086 };
3087 let listener = Arc::clone(&listener);
3088 async move {
3089 match result {
3090 Some(err) => Err(err),
3091 None => listener.accept().await,
3092 }
3093 }
3094 },
3095 ));
3096 let mut client = tokio::net::TcpStream::connect(addr).await.unwrap();
3097 authenticate(&mut client, &conn).await;
3098 let ping = Frame::build(
3099 FrameType::Ping,
3100 Flags::new(false, Priority::Passive, false),
3101 0,
3102 0,
3103 77,
3104 Vec::new(),
3105 )
3106 .unwrap();
3107 crate::write_frame(&mut client, &ping).await.unwrap();
3108 let pong = timeout(TEST_DEADLINE, read_frame(&mut client))
3109 .await
3110 .unwrap()
3111 .unwrap()
3112 .unwrap();
3113 assert_eq!(pong.header.ty, FrameType::Pong);
3114 assert!(
3115 !server.is_finished(),
3116 "a temporary accept failure must not stop the listener"
3117 );
3118 server.abort();
3119 }
3120
3121 #[tokio::test]
3122 async fn exhausted_accept_backs_off_then_serves_connection() {
3123 let listener = Arc::new(TcpListener::bind("127.0.0.1:0").await.unwrap());
3124 let addr = listener.local_addr().unwrap();
3125 let (auth, conn) = test_auth();
3126 let mut attempts = 0;
3127 let server = tokio::spawn(serve_listener_with_accept(
3128 Some(addr),
3129 echo_router(),
3130 auth,
3131 move || {
3132 attempts += 1;
3133 #[cfg(unix)]
3136 let emfile = rustix::io::Errno::MFILE.raw_os_error();
3137 #[cfg(windows)]
3138 let emfile = 10024;
3139 let error = (attempts == 1).then(|| io::Error::from_raw_os_error(emfile));
3140 let listener = Arc::clone(&listener);
3141 async move {
3142 match error {
3143 Some(err) => Err(err),
3144 None => listener.accept().await,
3145 }
3146 }
3147 },
3148 ));
3149 let started = Instant::now();
3150 let mut client = tokio::net::TcpStream::connect(addr).await.unwrap();
3151 authenticate(&mut client, &conn).await;
3152 assert!(
3153 started.elapsed() >= Duration::from_millis(50),
3154 "fd exhaustion must back off before retrying"
3155 );
3156 assert!(!server.is_finished());
3157 server.abort();
3158 }
3159
3160 #[tokio::test]
3161 async fn fatal_accept_error_still_stops_listener() {
3162 let (auth, _) = test_auth();
3163 let err = serve_listener_with_accept(None, echo_router(), auth, || async {
3164 Err(io::Error::from(io::ErrorKind::PermissionDenied))
3165 })
3166 .await
3167 .unwrap_err();
3168 assert!(
3169 matches!(err, ServerError::Accept { source, .. } if source.kind() == io::ErrorKind::PermissionDenied)
3170 );
3171 }
3172
3173 #[tokio::test]
3174 async fn serve_listeners_with_no_listeners_returns_typed_error() {
3175 let (auth, _conn) = test_auth();
3176 let err = serve_listeners(Vec::new(), echo_router(), auth)
3177 .await
3178 .expect_err("empty listener set must fail loudly");
3179 assert!(matches!(err, ServerError::NoListeners));
3180 }
3181
3182 #[tokio::test]
3183 async fn malformed_header_returns_typed_error_no_panic() {
3184 let (mut client, server_stream) = duplex(128);
3185 let (auth, conn) = test_auth();
3186 let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
3187 authenticate(&mut client, &conn).await;
3188 let mut header = [0u8; HEADER_LEN];
3189 header[4] = PROTOCOL_VERSION;
3190 header[5] = 250;
3191
3192 client.write_all(&header).await.unwrap();
3193 drop(client);
3194
3195 let err = server.await.unwrap().unwrap_err();
3196 assert!(matches!(
3197 err,
3198 ConnectionError::FrameIo(FrameIoError::DecodeHeader(DecodeError::UnknownFrameType {
3199 byte: 250
3200 }))
3201 ));
3202 }
3203
3204 #[tokio::test]
3205 async fn truncated_body_returns_typed_error_no_panic() {
3206 let (mut client, server_stream) = duplex(128);
3207 let (auth, conn) = test_auth();
3208 let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
3209 authenticate(&mut client, &conn).await;
3210 let frame = request(7, 8, b"abcd");
3211
3212 client.write_all(&frame.header.encode()).await.unwrap();
3213 client.write_all(b"ab").await.unwrap();
3214 drop(client);
3215
3216 let err = server.await.unwrap().unwrap_err();
3217 assert!(matches!(
3218 err,
3219 ConnectionError::FrameIo(FrameIoError::UnexpectedEof {
3220 stage: ReadStage::Body,
3221 expected: 4,
3222 actual: 2
3223 })
3224 ));
3225 }
3226
3227 #[tokio::test]
3228 async fn unknown_channel_is_returned_as_error_frame_and_connection_continues() {
3229 let (mut client, server_stream) = duplex(1024);
3230 let (auth, conn) = test_auth();
3231 let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
3232 authenticate(&mut client, &conn).await;
3233 let unknown = request(42, 10, b"lost");
3234 let known = request(7, 11, b"still-routes");
3235
3236 crate::write_frame(&mut client, &unknown).await.unwrap();
3237 crate::write_frame(&mut client, &known).await.unwrap();
3238
3239 let error = crate::read_frame(&mut client).await.unwrap().unwrap();
3240 assert_eq!(error.header.ty, FrameType::Error);
3241 assert_eq!(error.header.channel, 42);
3242 assert_eq!(error.header.corr, 10);
3243 let error_body: ErrorBody = serde_json::from_slice(&error.body).unwrap();
3244 assert_eq!(error_body.code, "unknown_channel");
3245
3246 let response = crate::read_frame(&mut client).await.unwrap().unwrap();
3247 assert_eq!(response.header.ty, FrameType::Response);
3248 assert_eq!(response.header.channel, 7);
3249 assert_eq!(response.header.corr, 11);
3250 assert_eq!(response.body, b"still-routes");
3251
3252 drop(client);
3253 server.await.unwrap().unwrap();
3254 }
3255
3256 mod audit_findings {
3257 use super::*;
3258 include!("server_audit_tests.rs");
3259 }
3260}