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