Skip to main content

subc_daemon/
server.rs

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
33/// Bytes (envelope header plus body) one connection's egress queue may hold
34/// before a module-to-client enqueue must wait for room.
35///
36/// Sized for a client that is slow but still reading: one connection can
37/// multiplex many token streams, and at roughly 200-byte frames (21-byte header
38/// plus body) 4 MiB is about 19,000 queued frames, i.e. thousands of frames on
39/// each of several routes, enough to ride out a pause of seconds. It is also the
40/// most a stuck client can make the daemon hold for it: 4 MiB per connection,
41/// so even 128 stuck connections stay near 512 MiB rather than growing without
42/// bound. A single frame larger than the whole budget is still admitted into an
43/// empty queue on send paths that do not check its size first.
44///
45/// The router, however, refuses a module-to-client frame whose header-plus-body
46/// size exceeds the client connection's budget before queueing it, so the budget
47/// is also the largest module-to-client frame the daemon delivers. Modules read
48/// that limit from `subc_protocol::MAX_DELIVERED_FRAME_LEN`, so the budget is
49/// defined as that constant; giving it a different value would make the
50/// published limit wrong.
51pub const CONNECTION_EGRESS_BYTE_BUDGET: usize = subc_protocol::MAX_DELIVERED_FRAME_LEN;
52/// Let a reading client drain a short fanout burst, but never park a module's
53/// frame reader for more than 250 ms. The atomic backlog age is measured from
54/// the enqueue time of the frame the writer is on, or of the frame that made
55/// the queue non-empty. A blocked writer makes that age the stopped-reader
56/// signal; between frames it may be one frame older than the true head, which
57/// is acceptable for this bounded grace and avoids a lock on every frame.
58pub const CONNECTION_EGRESS_STALL_GRACE: Duration = Duration::from_millis(250);
59/// Frame-count backstop for the same queue (the tokio channel's capacity).
60/// The byte budget is the real bound; this one only matters for floods of tiny
61/// or empty frames, which cost bookkeeping per frame rather than bytes. 32,768
62/// frames times 128 bytes is exactly the 4 MiB budget, so for any mean frame of
63/// 128 bytes or more the byte budget binds first; below that (for example
64/// 21-byte empty frames, of which 4 MiB would be almost 200,000) the count
65/// does. The channel allocates slots lazily, so a large capacity costs nothing
66/// until it is used.
67pub const CONNECTION_EGRESS_FRAME_CAP: usize = 32 * 1024;
68/// A pending `route.open` holds one reserved slot in the connection's egress
69/// queue until its module answers, and its response is sent outside the byte
70/// budget. Eight concurrent opens per connection keep a reconnect burst
71/// parallel while bounding both the reserved slots and the bytes that bypass
72/// the budget.
73pub const MAX_PENDING_ROUTE_OPENS_PER_CONNECTION: usize = 8;
74/// A reconnect herd may spread one target's opens over many client connections.
75/// Two safe per-connection bursts retain useful parallelism without restoring
76/// the hundreds-of-binds fanout that serial dispatch used to suppress.
77pub(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);
80// Sized for the restart-herd shape: after a daemon bounce, every live client
81// connection plus all supervised children re-dial within the same second
82// (~120+ observed on the 2026-07-14 fleet). Handshakes are cheap loopback
83// HMAC exchanges; the deadline, not the permit count, is the DoS bound.
84pub 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
88/// A connection's writer can outlive its reader while draining. Wake module
89/// deliveries when the reader exits, including task cancellation or a panic.
90struct 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/// Rate-limit state for pre-authentication rejection logs, owned by one
159/// `ServerAuth` so each listener (and each test) counts only its own rejects.
160#[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// Report accumulated rejects on the next allowed line instead of running a timer task.
176#[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/// Authentication material and DoS bounds applied before a TCP connection may
269/// reach the frame router.
270#[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    // Production limits are deliberately not config-routed: loosening pre-auth DoS posture changes attack surface.
297    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
332/// Serve an already-bound TCP listener. Each accepted connection gets its own
333/// async task so concurrent clients do not block the accept loop.
334pub 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                // Aborted/reset connections and interrupted syscalls affect one accept only.
361                // File-descriptor or socket-buffer exhaustion needs a short backoff to avoid spinning;
362                // other errors may mean the listener itself is unusable.
363                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        // Every route frame is a discrete message whose reply the peer is waiting
382        // for, so there is never a later write for Nagle to coalesce with -- it can
383        // only hold a frame back until an ACK arrives.
384        //
385        // MEASURED: no effect on this transport. A 50-sample-per-arm sweep from
386        // 1 to 32 KiB over the full client->daemon->module->client path showed a
387        // flat 0.28-0.38ms p50 with no step at any buffer boundary, because a
388        // loopback ACK returns in microseconds and never reaches the delayed-ACK
389        // timer that makes Nagle expensive on a real network. Kept anyway: it is
390        // one syscall at accept, it removes the mechanism rather than relying on
391        // loopback staying fast, and Windows loopback was not part of that sweep.
392        // Do not cite it as a latency fix -- the measurement says it is not one.
393        //
394        // Failure is not fatal: the connection works, and refusing to serve a
395        // client over a socket option would be worse than anything it saves.
396        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    // ENFILE/EMFILE/ENOBUFS by name rather than number: the numbers differ by
420    // platform (ENOBUFS is 55 on macOS and 105 on Linux, and each number means
421    // something unrelated on the other), so a literal list misclassifies.
422    // Winsock: WSAEMFILE and WSAENOBUFS.
423    #[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
442/// Serve this daemon's local endpoint (a Unix-domain socket, or a Windows named
443/// pipe) until its accept loop fails.
444///
445/// Every connection gets the same key handshake, frame format and router as a
446/// TCP client, so a client's bytes are identical either way. What differs is
447/// that this endpoint serves clients only: a HELLO that would register a module
448/// is refused with [`crate::local_listener::LOCAL_ENDPOINT_CLIENTS_ONLY`]. A
449/// peer read failure costs that one connection; a failure to accept at all ends
450/// the loop, because a local listener that cannot accept is no longer an
451/// endpoint.
452pub 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        // The variants above exist only on their own platform.
468        #[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    // The socket file is removed when this future ends, whether it returns or is
481    // dropped during shutdown, so a later daemon start finds no leftover.
482    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    // The end a client may connect to. An end exists whenever the loop is not
536    // accepting one, because Win32 refuses a client that finds none, and no
537    // other task accepts ends here.
538    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        // Overlapped I/O: the accepted end is AsyncRead and AsyncWrite, so a
545        // connection's reader and writer never wait for each other. A
546        // synchronous handle would, and the daemon's reply would sit behind the
547        // reader's pending read while the client waited for that reply.
548        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        // The next end is made before this one is served, so a client that
558        // arrives while this one is being served still finds an end.
559        free = Some(create_pipe_instance(&pipe_name)?);
560        let router = Arc::clone(&router);
561        let auth = auth.clone();
562        // Refuse network clients before observing a process or reading a byte.
563        // The pipe's PIPE_REJECT_REMOTE_CLIENTS flag is the first gate.
564        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
587/// Run one local-endpoint connection: the same handshake as TCP, with the
588/// clients-only rule attached after it.
589async 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/// Where a connection came in. The local endpoint serves clients only, because
607/// a module registers over TCP, where the daemon can tell a launched process
608/// apart by the launch nonce in its HELLO.
609#[derive(Debug, Clone, Copy, PartialEq, Eq)]
610pub(crate) enum LocalOrigin {
611    Tcp,
612    Local,
613}
614
615/// Serve all already-bound loopback TCP listeners until one accept loop fails.
616pub 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
625    let (tx, mut rx) = mpsc::channel(listeners.len());
626    let mut accept_tasks = AbortTasksOnDrop::default();
627    for listener in listeners {
628        let router = Arc::clone(&router);
629        let auth = auth.clone();
630        let tx = tx.clone();
631        accept_tasks.push(tokio::spawn(async move {
632            let result = serve_listener(listener, router, auth).await;
633            let _ = tx.send(result).await;
634        }));
635    }
636    drop(tx);
637
638    rx.recv().await.unwrap_or(Ok(()))
639}
640
641#[derive(Default)]
642struct AbortTasksOnDrop {
643    handles: Vec<JoinHandle<()>>,
644}
645
646impl AbortTasksOnDrop {
647    fn push(&mut self, handle: JoinHandle<()>) {
648        self.handles.push(handle);
649    }
650}
651
652impl Drop for AbortTasksOnDrop {
653    fn drop(&mut self) {
654        for handle in &self.handles {
655            if !handle.is_finished() {
656                handle.abort();
657            }
658        }
659    }
660}
661
662#[derive(Debug)]
663enum ConnectionLoopExit {
664    PeerClosed,
665    CloseRequested(CloseReason),
666}
667
668/// Run the authenticated frame read -> route loop for one connection.
669///
670/// Every accepted TCP connection must complete the key-auth prelude before any
671/// envelope bytes are read by the router. Outbound frames flow through a bounded
672/// [`FrameSink`] drained by one writer task. Inbound dispatch remains serial for
673/// every frame except `route.open`, activity operations and privileged requests;
674/// their bind, file and operator waits run in connection-owned tasks so
675/// unrelated frames can keep flowing.
676pub async fn handle_connection<S>(
677    stream: S,
678    router: Arc<Router>,
679    auth: ServerAuth,
680) -> Result<(), ConnectionError>
681where
682    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
683{
684    handle_connection_with_origin(stream, router, auth, LocalOrigin::Tcp).await
685}
686
687/// [`handle_connection`] for one endpoint kind: `origin` decides whether a
688/// module HELLO is refused before it can register.
689pub(crate) async fn handle_connection_with_origin<S>(
690    stream: S,
691    router: Arc<Router>,
692    auth: ServerAuth,
693    origin: LocalOrigin,
694) -> Result<(), ConnectionError>
695where
696    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
697{
698    handle_connection_with_peer(stream, router, auth, origin, None).await
699}
700
701async fn handle_connection_with_peer<S>(
702    mut stream: S,
703    router: Arc<Router>,
704    auth: ServerAuth,
705    origin: LocalOrigin,
706    peer: Option<subc_os::local_peer::CapturedPeer>,
707) -> Result<(), ConnectionError>
708where
709    S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
710{
711    // Capture only socket facts here. Process-table lookup happens lazily on a
712    // blocking thread when privileged dispatch needs a caller description.
713    let endpoints = (&stream as &dyn Any)
714        .downcast_ref::<tokio::net::TcpStream>()
715        .and_then(|tcp| tcp.local_addr().ok().zip(tcp.peer_addr().ok()));
716    // Over-cap connections WAIT for a handshake slot (bounded by the auth deadline)
717    // instead of being reset. A restart herd — every client and supervised child
718    // re-dialing the fresh daemon at once — otherwise loses supervised modules to
719    // the permit lottery: each reset burns a module restart-budget slot, and a
720    // module that treats auth failure as fatal can exhaust its budget into
721    // state=failed within the boot window (2026-07-14 aft outage). On loopback
722    // with the pre-auth HMAC deadline, a bounded queue is strictly safer than a
723    // reset.
724    //
725    // Pre-auth time is governed by TWO deliberately separate budgets: the queue
726    // wait below is bounded by `auth.deadline`, and `authenticate_server` then
727    // starts a FRESH `auth.deadline` for the handshake itself. Total pre-auth
728    // occupancy per connection is therefore up to 2x the configured deadline.
729    // This is intentional, not an accounting slip: charging queue time against
730    // the handshake budget would hand a herd-queued supervised module a
731    // near-zero handshake window under CPU saturation, recreating the fatal
732    // auth-failure -> restart-budget-burn path this queue exists to prevent.
733    // On a loopback-only, key-authenticated listener the doubled bound is a
734    // per-connection occupancy cost, not a meaningful DoS surface.
735    let permit =
736        match tokio::time::timeout(auth.deadline, auth.unauthenticated.clone().acquire_owned())
737            .await
738        {
739            Ok(Ok(permit)) => permit,
740            Ok(Err(_)) | Err(_) => {
741                let _ = stream.shutdown().await;
742                return Err(ConnectionError::UnauthenticatedCapacity);
743            }
744        };
745
746    let authenticated = authenticate_server(
747        &mut stream,
748        auth.key.as_ref(),
749        &auth.daemon_id,
750        auth.daemon_ver.as_ref(),
751        auth.deadline,
752    )
753    .await
754    .map_err(ConnectionError::Auth)?;
755    drop(permit);
756
757    let mut connection = router.begin_connection();
758    let connection_id = connection.id();
759    router.record_caller_endpoints(connection_id, endpoints);
760    if matches!(origin, LocalOrigin::Local) {
761        router.record_local_connection(connection_id);
762    }
763    if let Some(peer) = peer {
764        router.record_captured_peer(connection_id, peer);
765    }
766    // `authenticated.role` is CLIENT-SUPPLIED and unverified -- the handshake
767    // proves possession of the connection key, nothing about who is calling. So
768    // this exclusion is safe ONLY while the role decides a reporting question and
769    // never an authorization one: the watchdog's own loopback probe would
770    // otherwise inflate the very count it exists to sanity-check.
771    //
772    // The consequence of it being unverified, stated so nobody has to rediscover
773    // it: ANY client holding the key can claim this role and omit itself from
774    // `connected_clients`. That is a gauge a caller can lie to, and it is
775    // acceptable because the gauge informs an operator rather than gating
776    // anything. IF A ROLE IS EVER USED TO DECIDE ADMISSION, CAPACITY, OR PRIVILEGE,
777    // this stops being safe and the role must be attested rather than declared --
778    // the daemon already has the mechanism for that in the spawn-nonce path used
779    // for module identity.
780    let _connected_client = (authenticated.role != WATCHDOG_CLIENT_ROLE)
781        .then(|| auth.connected_clients.open(connection_id));
782    let close_receiver = connection.take_close_receiver();
783    debug!(
784        connection_id = connection_id.get(),
785        "subc authenticated connection opened"
786    );
787
788    let (read_half, write_half) = tokio::io::split(stream);
789    // Authentication is complete before this buffer can read ahead. The connection loop
790    // retains a partial frame read across completed route.open tasks; dropping the read
791    // happens only when a frame finishes or the connection ends.
792    let mut read_half = BufReader::new(read_half);
793    let (egress, rx) = connection_egress();
794    let delivery_guard = ClientDeliveryGuard(egress.clone());
795    let writer = tokio::spawn(drain_writer(write_half, rx));
796
797    let ctx = RouteCtx {
798        connection_id,
799        egress: egress.clone(),
800    };
801
802    let mut route_open_tasks = JoinSet::new();
803    let mut privileged_tasks = JoinSet::new();
804    let loop_result = connection_loop(
805        &mut read_half,
806        Arc::clone(&router),
807        ctx.clone(),
808        close_receiver,
809        &mut route_open_tasks,
810        &mut privileged_tasks,
811        origin,
812    )
813    .await;
814
815    drop(delivery_guard);
816    // Every in-flight route.open must have FINISHED before `connection` drops,
817    // because that drop runs the forwarding cleanup for this id, and cleanup is
818    // also where the id's closing mark is lifted. Dropping a JoinSet only
819    // requests abort: a task already running on another worker keeps going
820    // until its next await, and could commit a route for this connection after
821    // cleanup has cleared it, with nothing left to refuse it and nothing to
822    // clean it up. shutdown() aborts and then waits.
823    route_open_tasks.shutdown().await;
824    // Abort held approvals and wait for their withdrawal guards before lifting
825    // this connection's cleanup state or removing its caller endpoints.
826    privileged_tasks.shutdown().await;
827
828    drop(ctx);
829    drop(egress);
830    drop(connection);
831
832    let close_reason = match &loop_result {
833        Ok(ConnectionLoopExit::CloseRequested(reason)) => Some(reason.to_string()),
834        Ok(ConnectionLoopExit::PeerClosed) | Err(_) => None,
835    };
836    let writer_result = finish_connection_writer(writer, connection_id.get()).await;
837
838    let result = if let Some(reason) = close_reason.as_deref() {
839        match writer_result {
840            Some(Ok(Ok(()))) | None => Ok(()),
841            Some(Ok(Err(writer_err))) => {
842                debug!(
843                    connection_id = connection_id.get(),
844                    close_reason = reason,
845                    writer_error = %writer_err,
846                    "writer failed after requested connection close"
847                );
848                Ok(())
849            }
850            Some(Err(join_err)) => {
851                warn!(
852                    connection_id = connection_id.get(),
853                    close_reason = reason,
854                    join_error = %join_err,
855                    "writer task join failed after requested connection close"
856                );
857                Ok(())
858            }
859        }
860    } else {
861        match (loop_result, writer_result) {
862            (Err(loop_err), Some(Ok(Ok(()))) | None) => Err(loop_err),
863            (Err(loop_err), Some(Ok(Err(writer_err)))) => {
864                warn!(
865                    connection_id = connection_id.get(),
866                    writer_error = %writer_err,
867                    "writer failed while closing after connection error"
868                );
869                Err(loop_err)
870            }
871            (Err(loop_err), Some(Err(join_err))) => {
872                warn!(
873                    connection_id = connection_id.get(),
874                    join_error = %join_err,
875                    "writer task join failed while closing after connection error"
876                );
877                Err(loop_err)
878            }
879            (Ok(ConnectionLoopExit::PeerClosed), Some(Ok(Ok(()))) | None) => Ok(()),
880            (Ok(ConnectionLoopExit::PeerClosed), Some(Ok(Err(writer_err)))) => {
881                Err(ConnectionError::FrameIo(writer_err))
882            }
883            (Ok(ConnectionLoopExit::PeerClosed), Some(Err(join_err))) => Err(join_err),
884            (Ok(ConnectionLoopExit::CloseRequested(_)), _) => {
885                unreachable!("close requests are handled before normal writer result matching")
886            }
887        }
888    };
889
890    match &result {
891        Ok(()) => {
892            if let Some(reason) = close_reason.as_deref() {
893                debug!(
894                    connection_id = connection_id.get(),
895                    close_reason = reason,
896                    "subc connection closed by request"
897                );
898            } else {
899                debug!(
900                    connection_id = connection_id.get(),
901                    "subc connection closed"
902                );
903            }
904        }
905        Err(err) => debug!(
906            connection_id = connection_id.get(),
907            error = %err,
908            "subc connection exited with error"
909        ),
910    }
911
912    result
913}
914
915async fn finish_connection_writer(
916    mut writer: JoinHandle<Result<(), FrameIoError>>,
917    connection_id: u64,
918) -> Option<Result<Result<(), FrameIoError>, ConnectionError>> {
919    // Even after inbound EOF or an error, the peer may keep its receive side
920    // open without reading. Give queued frames the same grace on every exit.
921    match timeout(CLOSE_DRAIN_GRACE, &mut writer).await {
922        Ok(result) => Some(result.map_err(ConnectionError::WriterTask)),
923        Err(_) => {
924            warn!(
925                connection_id,
926                grace = ?CLOSE_DRAIN_GRACE,
927                "connection writer did not drain during teardown; aborting writer task"
928            );
929            writer.abort();
930            let _ = writer.await;
931            None
932        }
933    }
934}
935
936async fn connection_loop<R>(
937    read_half: &mut R,
938    router: Arc<Router>,
939    ctx: RouteCtx,
940    mut close_receiver: ConnectionCloseReceiver,
941    route_open_tasks: &mut JoinSet<Result<(), RouterError>>,
942    privileged_tasks: &mut JoinSet<Result<(), RouterError>>,
943    origin: LocalOrigin,
944) -> Result<ConnectionLoopExit, ConnectionError>
945where
946    R: AsyncRead + Unpin,
947{
948    let mut activity_tasks = JoinSet::new();
949    loop {
950        while let Some(result) = activity_tasks.try_join_next() {
951            finish_route_open_task(result)?;
952        }
953        while let Some(result) = privileged_tasks.try_join_next() {
954            finish_route_open_task(result)?;
955        }
956        while let Some(result) = route_open_tasks.try_join_next() {
957            finish_route_open_task(result)?;
958        }
959
960        // Keep the same read future when a route.open completes: read_frame owns
961        // partial header/body buffers that would be lost if that future were dropped.
962        let read = read_frame(&mut *read_half);
963        tokio::pin!(read);
964        let frame = loop {
965            tokio::select! {
966                close = &mut close_receiver => {
967                    return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
968                }
969                result = route_open_tasks.join_next(), if !route_open_tasks.is_empty() => {
970                    finish_route_open_task(
971                        result.expect("a non-empty route.open JoinSet has a next task")
972                    )?;
973                }
974                result = activity_tasks.join_next(), if !activity_tasks.is_empty() => {
975                    finish_route_open_task(result.expect("non-empty activity task set"))?;
976                }
977                result = privileged_tasks.join_next(), if !privileged_tasks.is_empty() => {
978                    finish_route_open_task(result.expect("non-empty privileged task set"))?;
979                }
980                result = &mut read => {
981                    break match result.map_err(ConnectionError::FrameIo)? {
982                        Some(frame) => frame,
983                        None => return Ok(ConnectionLoopExit::PeerClosed),
984                    };
985                }
986            }
987        };
988
989        if origin == LocalOrigin::Local && frame.header.ty == subc_protocol::FrameType::Hello {
990            // A module registers over TCP only. Refusing here, before the router
991            // sees the frame, is what guarantees the local endpoint leaves no
992            // registration, catalog entry or route behind, whatever the HELLO
993            // carries.
994            let refusal = crate::control::control_error_frame(
995                &frame,
996                crate::local_listener::LOCAL_ENDPOINT_CLIENTS_ONLY,
997                "the local endpoint serves clients only; modules register over TCP",
998            )
999            .map_err(ConnectionError::Router)?;
1000            // The connection ends as soon as the refusal is sent, so the bytes
1001            // must reach the socket first: a client that has not yet read its
1002            // reply would otherwise see only the end of the stream.
1003            let send_result = tokio::select! {
1004                close = &mut close_receiver => {
1005                    return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1006                }
1007                result = send_refusal(&ctx.egress, refusal) => result,
1008            };
1009            send_result.map_err(ConnectionError::Router)?;
1010            return Ok(ConnectionLoopExit::PeerClosed);
1011        }
1012
1013        if frame.header.channel == 0
1014            && frame.header.ty == subc_protocol::FrameType::Request
1015            && serde_json::from_slice::<serde_json::Value>(&frame.body)
1016                .ok()
1017                .is_some_and(|body| {
1018                    matches!(
1019                        body["op"].as_str(),
1020                        Some(
1021                            subc_control::ops::ACTIVITY_RECORD
1022                                | subc_control::ops::ACTIVITY_QUERY
1023                                | subc_control::ops::ACTIVITY_SUBSCRIBE
1024                        )
1025                    )
1026                })
1027        {
1028            // Bound outstanding activity tasks as well as the disk queue,
1029            // so the reader never waits for either capacity when the disk stalls.
1030            if activity_tasks.len() >= 128 {
1031                let response = crate::control::control_error_frame(
1032                    &frame,
1033                    subc_control::ACTIVITY_UNAVAILABLE,
1034                    "activity queue full",
1035                )
1036                .map_err(ConnectionError::Router)?;
1037                let send_result = tokio::select! {
1038                    close = &mut close_receiver => {
1039                        return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1040                    }
1041                    result = ctx.egress.send(response) => result,
1042                };
1043                send_result.map_err(ConnectionError::Router)?;
1044            } else {
1045                let task_router = Arc::clone(&router);
1046                let task_ctx = ctx.clone();
1047                activity_tasks.spawn(async move {
1048                    route_open_tail(task_router, task_ctx, frame, Instant::now()).await
1049                });
1050            }
1051            continue;
1052        }
1053
1054        if let Some(target_module_id) = router.route_open_target(&frame) {
1055            // A task can finish while the reader is waiting for the next frame.
1056            // Reap it before checking admission so completed work never occupies
1057            // one of the deliberately scarce connection slots.
1058            while let Some(result) = route_open_tasks.try_join_next() {
1059                finish_route_open_task(result)?;
1060            }
1061
1062            if route_open_tasks.len() >= MAX_PENDING_ROUTE_OPENS_PER_CONNECTION {
1063                // Never wait for capacity here: doing so would recreate the same
1064                // reader head-of-line stall with a smaller constant.
1065                let refusal = router
1066                    .route_open_capacity_refusal(
1067                        &ctx,
1068                        &frame,
1069                        &target_module_id,
1070                        route_open_tasks.len(),
1071                        MAX_PENDING_ROUTE_OPENS_PER_CONNECTION,
1072                    )
1073                    .map_err(ConnectionError::Router)?;
1074                let send_result = tokio::select! {
1075                    close = &mut close_receiver => {
1076                        return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1077                    }
1078                    result = ctx.egress.send(refusal) => result,
1079                };
1080                send_result.map_err(ConnectionError::Router)?;
1081                continue;
1082            }
1083
1084            let task_router = Arc::clone(&router);
1085            let task_ctx = ctx.clone();
1086            // Start slow-dispatch timing before spawn so it covers the task's
1087            // full scheduler and handler lifetime, as inline timing did.
1088            let dispatch_started_at = Instant::now();
1089            route_open_tasks.spawn(async move {
1090                route_open_tail(task_router, task_ctx, frame, dispatch_started_at).await
1091            });
1092            continue;
1093        }
1094
1095        if router.defers_privileged_control(&ctx, &frame) {
1096            let task_router = Arc::clone(&router);
1097            let task_ctx = ctx.clone();
1098            let started = Instant::now();
1099            privileged_tasks
1100                .spawn(async move { route_open_tail(task_router, task_ctx, frame, started).await });
1101            continue;
1102        }
1103
1104        // Other frames still route serially: routing can backpressure reads,
1105        // and a connection close cancels the in-progress route.
1106        let route_result = tokio::select! {
1107            close = &mut close_receiver => {
1108                return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1109            }
1110            result = router.route_for_connection(&ctx, frame) => result,
1111        };
1112
1113        if let Err(err) = route_result {
1114            if let Some(error_frame) = err.to_error_frame() {
1115                warn!(
1116                    connection_id = ctx.connection_id.get(),
1117                    error = %err,
1118                    "routing failure recovered with ERROR frame"
1119                );
1120                let send_result = tokio::select! {
1121                    close = &mut close_receiver => {
1122                        return Ok(ConnectionLoopExit::CloseRequested(close_reason(close)));
1123                    }
1124                    result = ctx.egress.send(error_frame) => result,
1125                };
1126                send_result.map_err(ConnectionError::Router)?;
1127            } else {
1128                debug!(
1129                    connection_id = ctx.connection_id.get(),
1130                    error = %err,
1131                    "fatal routing failure"
1132                );
1133                return Err(ConnectionError::Router(err));
1134            }
1135        }
1136    }
1137}
1138
1139/// Send one frame so that a connection ending immediately afterwards still
1140/// delivers it: on Unix, wait for the writer's flush acknowledgement; elsewhere
1141/// queue it, because those writers carry no acknowledgement.
1142async fn send_refusal(sink: &FrameSink, frame: crate::Frame) -> Result<(), RouterError> {
1143    // The flush acknowledgement comes from the writer's `write_frame`, which
1144    // only the Unix builds expose; on Windows the refusal is queued for the pipe
1145    // writer instead.
1146    #[cfg(unix)]
1147    {
1148        sink.send_flushed(frame).await
1149    }
1150    #[cfg(not(unix))]
1151    {
1152        sink.send(frame).await
1153    }
1154}
1155
1156async fn route_open_tail(
1157    router: Arc<Router>,
1158    ctx: RouteCtx,
1159    frame: crate::Frame,
1160    dispatch_started_at: Instant,
1161) -> Result<(), RouterError> {
1162    match router
1163        .route_for_connection_started(&ctx, frame, Some(dispatch_started_at))
1164        .await
1165    {
1166        Ok(()) => Ok(()),
1167        Err(err) => {
1168            let Some(error_frame) = err.to_error_frame() else {
1169                return Err(err);
1170            };
1171            warn!(
1172                connection_id = ctx.connection_id.get(),
1173                error = %err,
1174                "routing failure recovered with ERROR frame"
1175            );
1176            ctx.egress.send(error_frame).await
1177        }
1178    }
1179}
1180
1181fn finish_route_open_task(
1182    result: Result<Result<(), RouterError>, tokio::task::JoinError>,
1183) -> Result<(), ConnectionError> {
1184    match result {
1185        Ok(Ok(())) => Ok(()),
1186        Ok(Err(err)) => Err(ConnectionError::Router(err)),
1187        Err(err) => Err(ConnectionError::Router(RouterError::backend(
1188            0,
1189            0,
1190            format!("route.open task failed: {err}"),
1191        ))),
1192    }
1193}
1194
1195fn close_reason(
1196    result: Result<CloseReason, tokio::sync::oneshot::error::RecvError>,
1197) -> CloseReason {
1198    result.unwrap_or_else(|_| {
1199        CloseReason::new(
1200            "close_registry_dropped",
1201            "connection close registration was dropped without a reason",
1202        )
1203    })
1204}
1205
1206/// The outbound queue for one daemon connection: a sink bounded by
1207/// [`CONNECTION_EGRESS_BYTE_BUDGET`] and [`CONNECTION_EGRESS_FRAME_CAP`], and
1208/// the receiver its writer drains.
1209pub(crate) fn connection_egress() -> (FrameSink, mpsc::Receiver<crate::router::OutboundFrame>) {
1210    let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(CONNECTION_EGRESS_FRAME_CAP);
1211    (
1212        FrameSink::with_byte_budget(tx, CONNECTION_EGRESS_BYTE_BUDGET),
1213        rx,
1214    )
1215}
1216
1217async fn drain_writer<W>(
1218    write_half: W,
1219    mut rx: mpsc::Receiver<crate::router::OutboundFrame>,
1220) -> Result<(), FrameIoError>
1221where
1222    W: AsyncWrite + Unpin,
1223{
1224    let mut writer = BufWriter::new(write_half);
1225    while let Some(outbound) = rx.recv().await {
1226        write_outbound(&mut writer, outbound).await?;
1227        while let Ok(outbound) = rx.try_recv() {
1228            write_outbound(&mut writer, outbound).await?;
1229        }
1230        writer.flush().await.map_err(FrameIoError::Io)?;
1231    }
1232    writer.flush().await.map_err(FrameIoError::Io)?;
1233    Ok(())
1234}
1235
1236/// Reply-path half of slow-control diagnosis: a channel-0 reply that sat in
1237/// the writer queue past the threshold is reported with its queue residency
1238/// and its own write duration separated, because "writer task not scheduled"
1239/// and "socket write blocked" are different defects and the sum hides which.
1240/// Data-plane frames are exempt: their latency is the client's own flow
1241/// control, and logging them would drown the control signal in bulk traffic.
1242async fn write_outbound<W>(
1243    writer: &mut BufWriter<W>,
1244    outbound: crate::router::OutboundFrame,
1245) -> Result<(), FrameIoError>
1246where
1247    W: AsyncWrite + Unpin,
1248{
1249    const SLOW_REPLY_QUEUE: Duration = Duration::from_millis(1000);
1250    let queued = outbound.enqueued_at.elapsed();
1251    // Held until this frame has been written, then dropped at the end of this
1252    // function, which gives its bytes back to the connection's egress budget.
1253    let charge = outbound.charge;
1254    if let Some(charge) = &charge {
1255        charge.taken_by_writer();
1256    }
1257    let frame = outbound.frame;
1258    if frame.header.channel == 0 && queued >= SLOW_REPLY_QUEUE {
1259        let write_started = std::time::Instant::now();
1260        let result = write_frame(writer, &frame).await;
1261        tracing::warn!(
1262            corr = frame.header.corr,
1263            queued_ms = queued.as_millis() as u64,
1264            write_ms = write_started.elapsed().as_millis() as u64,
1265            "slow control reply write"
1266        );
1267        result?;
1268    } else {
1269        write_frame(writer, &frame).await?;
1270    }
1271    if let Some(flushed) = outbound.flushed {
1272        writer.flush().await.map_err(FrameIoError::Io)?;
1273        let _ = flushed.send(());
1274    }
1275    Ok(())
1276}
1277
1278#[cfg(all(test, unix))]
1279#[tokio::test]
1280async fn shutdown_notice_ack_waits_for_socket_flush() {
1281    let (socket, mut peer) = tokio::io::duplex(1);
1282    let (tx, rx) = mpsc::channel(1);
1283    let sink = FrameSink::new(tx);
1284    let writer = tokio::spawn(drain_writer(socket, rx));
1285    let frame = crate::Frame::build(
1286        subc_protocol::FrameType::Push,
1287        subc_protocol::Flags::new(false, subc_protocol::Priority::Interactive, false),
1288        0,
1289        0,
1290        0,
1291        b"notice".to_vec(),
1292    )
1293    .unwrap();
1294    let send = sink.send_flushed(frame);
1295    tokio::pin!(send);
1296    assert!(
1297        timeout(Duration::from_millis(20), &mut send).await.is_err(),
1298        "queueing bytes is not a socket flush acknowledgement"
1299    );
1300    let (sent, received) = timeout(Duration::from_secs(1), async {
1301        tokio::join!(&mut send, read_frame(&mut peer))
1302    })
1303    .await
1304    .unwrap();
1305    sent.unwrap();
1306    assert_eq!(received.unwrap().unwrap().body, b"notice");
1307    writer.abort();
1308}
1309
1310#[derive(Debug)]
1311pub enum ServerError {
1312    NoListeners,
1313    Accept {
1314        local_addr: Option<SocketAddr>,
1315        source: io::Error,
1316    },
1317    /// The local endpoint (a Unix-domain socket or a named pipe) could not be
1318    /// created or could not accept.
1319    LocalAccept {
1320        endpoint: String,
1321        source: io::Error,
1322    },
1323}
1324
1325impl fmt::Display for ServerError {
1326    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1327        match self {
1328            Self::NoListeners => write!(f, "no TCP listeners were provided"),
1329            Self::Accept { local_addr, source } => match local_addr {
1330                Some(addr) => write!(f, "failed to accept TCP connection on {addr}: {source}"),
1331                None => write!(f, "failed to accept TCP connection: {source}"),
1332            },
1333            Self::LocalAccept { endpoint, source } => {
1334                write!(f, "local endpoint {endpoint} failed: {source}")
1335            }
1336        }
1337    }
1338}
1339
1340impl Error for ServerError {
1341    fn source(&self) -> Option<&(dyn Error + 'static)> {
1342        match self {
1343            Self::Accept { source, .. } | Self::LocalAccept { source, .. } => Some(source),
1344            Self::NoListeners => None,
1345        }
1346    }
1347}
1348
1349#[derive(Debug)]
1350pub enum ConnectionError {
1351    Auth(AuthError),
1352    UnauthenticatedCapacity,
1353    FrameIo(FrameIoError),
1354    Router(RouterError),
1355    WriterTask(tokio::task::JoinError),
1356}
1357
1358impl ConnectionError {
1359    fn is_quiet_reject(&self) -> bool {
1360        matches!(self, Self::Auth(_) | Self::UnauthenticatedCapacity)
1361    }
1362
1363    fn pre_auth_reject_stage(&self) -> Option<PreAuthRejectStage> {
1364        match self {
1365            Self::UnauthenticatedCapacity => Some(PreAuthRejectStage::WaitingForHandshakeSlot),
1366            Self::Auth(AuthError::Timeout { .. }) => Some(PreAuthRejectStage::HandshakeDeadline),
1367            Self::Auth(
1368                AuthError::InvalidClientAuth
1369                | AuthError::InvalidServerProof
1370                | AuthError::DaemonIdMismatch,
1371            ) => Some(PreAuthRejectStage::InvalidProof),
1372            Self::Auth(AuthError::MessageTooLarge { .. } | AuthError::JsonDecode { .. }) => {
1373                Some(PreAuthRejectStage::MalformedMessage)
1374            }
1375            Self::Auth(AuthError::UnexpectedEof { .. }) => Some(PreAuthRejectStage::PeerClosed),
1376            Self::Auth(AuthError::Io { source, .. })
1377                if matches!(
1378                    source.kind(),
1379                    io::ErrorKind::BrokenPipe
1380                        | io::ErrorKind::ConnectionAborted
1381                        | io::ErrorKind::ConnectionReset
1382                        | io::ErrorKind::UnexpectedEof
1383                ) =>
1384            {
1385                Some(PreAuthRejectStage::PeerClosed)
1386            }
1387            Self::Auth(_) => Some(PreAuthRejectStage::OtherAuthenticationFailure),
1388            Self::FrameIo(_) | Self::Router(_) | Self::WriterTask(_) => None,
1389        }
1390    }
1391
1392    fn auth_stage(&self) -> Option<AuthStage> {
1393        match self {
1394            Self::Auth(
1395                AuthError::Io { stage, .. }
1396                | AuthError::Timeout { stage, .. }
1397                | AuthError::UnexpectedEof { stage, .. }
1398                | AuthError::MessageTooLarge { stage, .. }
1399                | AuthError::JsonEncode { stage, .. }
1400                | AuthError::JsonDecode { stage, .. },
1401            ) => Some(*stage),
1402            Self::Auth(
1403                AuthError::Random(_)
1404                | AuthError::KeyTooShort { .. }
1405                | AuthError::InvalidServerProof
1406                | AuthError::DaemonIdMismatch
1407                | AuthError::InvalidClientAuth,
1408            )
1409            | Self::UnauthenticatedCapacity
1410            | Self::FrameIo(_)
1411            | Self::Router(_)
1412            | Self::WriterTask(_) => None,
1413        }
1414    }
1415}
1416
1417impl fmt::Display for ConnectionError {
1418    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1419        match self {
1420            Self::Auth(err) => write!(f, "connection auth failed: {err}"),
1421            Self::UnauthenticatedCapacity => write!(
1422                f,
1423                "too many concurrent unauthenticated subc TCP connections"
1424            ),
1425            Self::FrameIo(err) => write!(f, "frame connection error: {err}"),
1426            Self::Router(err) => write!(f, "router connection error: {err}"),
1427            Self::WriterTask(err) => write!(f, "connection writer task failed: {err}"),
1428        }
1429    }
1430}
1431
1432impl Error for ConnectionError {
1433    fn source(&self) -> Option<&(dyn Error + 'static)> {
1434        match self {
1435            Self::Auth(err) => Some(err),
1436            Self::FrameIo(err) => Some(err),
1437            Self::Router(err) => Some(err),
1438            Self::WriterTask(err) => Some(err),
1439            Self::UnauthenticatedCapacity => None,
1440        }
1441    }
1442}
1443
1444#[cfg(test)]
1445mod tests {
1446    use std::{
1447        future::Future,
1448        pin::Pin,
1449        sync::atomic::{AtomicUsize, Ordering},
1450        task::{Context, Poll},
1451    };
1452
1453    use super::*;
1454    use serde::{de::DeserializeOwned, Serialize};
1455    use subc_protocol::{
1456        DecodeError, ErrorBody, Flags, FrameType, Priority, HEADER_LEN, PROTOCOL_VERSION,
1457    };
1458    use tokio::io::{duplex, AsyncReadExt, AsyncWriteExt, ReadBuf};
1459
1460    use subc_transport::{
1461        authenticate_client, compute_proof, ClientAuth, ClientHello, ConnectionInfo, Endpoint,
1462        ServerProof, CLIENT_AUTH_DOMAIN, NONCE_LEN, SCHEMA_VERSION,
1463    };
1464
1465    use crate::{ControlHandler, EchoBackend, Frame, ReadStage, Registry};
1466
1467    const TEST_DEADLINE: Duration = Duration::from_secs(2);
1468    const TEST_DAEMON_VER: &str = "test-subc-server";
1469
1470    /// Modules size their replies against the published limit, and the router
1471    /// refuses any module frame over the egress budget, so the two must be the
1472    /// same number. This fails if the budget is ever given its own value.
1473    #[test]
1474    fn egress_budget_is_the_published_delivered_frame_limit() {
1475        assert_eq!(
1476            CONNECTION_EGRESS_BYTE_BUDGET,
1477            subc_protocol::MAX_DELIVERED_FRAME_LEN
1478        );
1479    }
1480
1481    struct ObservedStream {
1482        inner: tokio::io::DuplexStream,
1483        write_blocked: Arc<tokio::sync::Notify>,
1484        dropped: Arc<AtomicUsize>,
1485        read_error: Option<tokio::sync::oneshot::Receiver<()>>,
1486    }
1487
1488    impl AsyncRead for ObservedStream {
1489        fn poll_read(
1490            mut self: Pin<&mut Self>,
1491            cx: &mut Context<'_>,
1492            buf: &mut ReadBuf<'_>,
1493        ) -> Poll<io::Result<()>> {
1494            if let Some(receiver) = self.read_error.as_mut() {
1495                match Pin::new(receiver).poll(cx) {
1496                    Poll::Ready(Ok(())) => {
1497                        self.read_error = None;
1498                        return Poll::Ready(Err(io::ErrorKind::ConnectionReset.into()));
1499                    }
1500                    Poll::Ready(Err(_)) => self.read_error = None,
1501                    Poll::Pending => {}
1502                }
1503            }
1504            Pin::new(&mut self.inner).poll_read(cx, buf)
1505        }
1506    }
1507
1508    impl AsyncWrite for ObservedStream {
1509        fn poll_write(
1510            mut self: Pin<&mut Self>,
1511            cx: &mut Context<'_>,
1512            buf: &[u8],
1513        ) -> Poll<io::Result<usize>> {
1514            let result = Pin::new(&mut self.inner).poll_write(cx, buf);
1515            if result.is_pending() {
1516                self.write_blocked.notify_one();
1517            }
1518            result
1519        }
1520
1521        fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1522            Pin::new(&mut self.inner).poll_flush(cx)
1523        }
1524
1525        fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
1526            Pin::new(&mut self.inner).poll_shutdown(cx)
1527        }
1528    }
1529
1530    impl Drop for ObservedStream {
1531        fn drop(&mut self) {
1532            self.dropped.fetch_add(1, Ordering::SeqCst);
1533        }
1534    }
1535
1536    struct BlockedWriterConnection {
1537        client: tokio::io::DuplexStream,
1538        server: JoinHandle<Result<(), ConnectionError>>,
1539        stream_dropped: Arc<AtomicUsize>,
1540        read_error: Option<tokio::sync::oneshot::Sender<()>>,
1541        router: Arc<Router>,
1542    }
1543
1544    impl BlockedWriterConnection {
1545        async fn new() -> Self {
1546            let (mut client, inner) = duplex(256);
1547            let write_blocked = Arc::new(tokio::sync::Notify::new());
1548            let stream_dropped = Arc::new(AtomicUsize::new(0));
1549            let (read_error, receiver) = tokio::sync::oneshot::channel();
1550            let stream = ObservedStream {
1551                inner,
1552                write_blocked: Arc::clone(&write_blocked),
1553                dropped: Arc::clone(&stream_dropped),
1554                read_error: Some(receiver),
1555            };
1556            let (auth, conn) = test_auth();
1557            let router = echo_router();
1558            let server = tokio::spawn(handle_connection(stream, Arc::clone(&router), auth));
1559            authenticate(&mut client, &conn).await;
1560
1561            // Ignore any backpressure observed during authentication. The echo
1562            // reply is larger than the duplex capacity and the client never reads it.
1563            let _ = timeout(Duration::ZERO, write_blocked.notified()).await;
1564            write_frame(&mut client, &request(7, 1, &[b'x'; 1024]))
1565                .await
1566                .unwrap();
1567            timeout(TEST_DEADLINE, write_blocked.notified())
1568                .await
1569                .expect("writer should block on the unread echo reply");
1570            assert!(!server.is_finished());
1571            assert_eq!(stream_dropped.load(Ordering::SeqCst), 0);
1572            Self {
1573                client,
1574                server,
1575                stream_dropped,
1576                read_error: Some(read_error),
1577                router,
1578            }
1579        }
1580
1581        async fn finish(&mut self) -> Result<(), ConnectionError> {
1582            let started = tokio::time::Instant::now();
1583            let result = timeout(CLOSE_DRAIN_GRACE + Duration::from_secs(1), &mut self.server)
1584                .await
1585                .expect("connection teardown exceeded writer drain grace plus margin")
1586                .expect("connection task should not panic");
1587            assert!(started.elapsed() >= CLOSE_DRAIN_GRACE);
1588            assert_eq!(
1589                self.stream_dropped.load(Ordering::SeqCst),
1590                1,
1591                "writer must release its stream half before teardown completes"
1592            );
1593            result
1594        }
1595
1596        fn request_close(&self) {
1597            // Each fixture owns a fresh router, so its only connection has ID 1.
1598            assert!(self.router.forwarding().request_connection_close(
1599                crate::registry::ConnectionId::new(1),
1600                CloseReason::new("test_close", "test requested close"),
1601            ));
1602        }
1603    }
1604
1605    #[tokio::test(start_paused = true)]
1606    async fn peer_eof_bounds_blocked_writer_teardown() {
1607        let mut connection = BlockedWriterConnection::new().await;
1608        // Half-close only the client-to-server direction: the unread receive
1609        // buffer must stay alive so the server's writer cannot finish naturally.
1610        connection.client.shutdown().await.unwrap();
1611        connection.finish().await.unwrap();
1612    }
1613
1614    #[tokio::test(start_paused = true)]
1615    async fn read_error_bounds_blocked_writer_teardown() {
1616        let mut connection = BlockedWriterConnection::new().await;
1617        connection.read_error.take().unwrap().send(()).unwrap();
1618        let error = connection.finish().await.unwrap_err();
1619        assert!(matches!(
1620            error,
1621            ConnectionError::FrameIo(FrameIoError::Io(error))
1622                if error.kind() == io::ErrorKind::ConnectionReset
1623        ));
1624    }
1625
1626    #[tokio::test(start_paused = true)]
1627    async fn close_requested_bounds_blocked_writer_teardown() {
1628        let mut connection = BlockedWriterConnection::new().await;
1629        connection.request_close();
1630        connection.finish().await.unwrap();
1631    }
1632
1633    #[tokio::test(start_paused = true)]
1634    async fn close_requested_flushes_queued_reply_before_grace() {
1635        let mut connection = BlockedWriterConnection::new().await;
1636        connection.request_close();
1637        let started = tokio::time::Instant::now();
1638        let reply = timeout(CLOSE_DRAIN_GRACE, read_frame(&mut connection.client))
1639            .await
1640            .expect("queued reply should flush before the grace expires")
1641            .unwrap()
1642            .unwrap();
1643        assert_eq!(reply.body, vec![b'x'; 1024]);
1644        timeout(CLOSE_DRAIN_GRACE, &mut connection.server)
1645            .await
1646            .unwrap()
1647            .unwrap()
1648            .unwrap();
1649        assert!(started.elapsed() < CLOSE_DRAIN_GRACE);
1650        assert_eq!(connection.stream_dropped.load(Ordering::SeqCst), 1);
1651    }
1652
1653    /// Reply-path stamp, slow polarity: a channel-0 reply whose queue residency
1654    /// exceeds the threshold must produce the slow-control-reply-write WARN with
1655    /// queued_ms reflecting the residency. Uses a backdated stamp rather than a
1656    /// real stall so the test is fast and deterministic.
1657    #[tokio::test]
1658    async fn stale_queued_control_reply_logs_slow_reply_write() {
1659        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
1660        let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(4);
1661        let reply = Frame::build_with_version(
1662            PROTOCOL_VERSION,
1663            FrameType::Error,
1664            Flags::new(false, Priority::Interactive, false),
1665            0,
1666            0,
1667            7,
1668            serde_json::to_vec(&ErrorBody {
1669                code: "test".into(),
1670                message: "reply".into(),
1671                detail: None,
1672            })
1673            .expect("body encodes"),
1674        )
1675        .expect("frame builds");
1676        tx.send(crate::router::OutboundFrame {
1677            frame: reply,
1678            enqueued_at: std::time::Instant::now() - Duration::from_millis(1500),
1679            flushed: None,
1680            charge: None,
1681        })
1682        .await
1683        .expect("queued");
1684        drop(tx);
1685        let (write_half, mut read_half) = duplex(64 * 1024);
1686        drain_writer(write_half, rx).await.expect("writer drains");
1687        let mut sink = Vec::new();
1688        read_half.read_to_end(&mut sink).await.expect("read");
1689        assert!(!sink.is_empty(), "frame reached the socket");
1690        let captured = crate::router::test_log::captured_logs(&logs);
1691        assert!(
1692            captured.contains("slow control reply write") && captured.contains("corr=7"),
1693            "expected slow reply WARN naming corr, got: {captured}"
1694        );
1695        let queued_ms: u64 = captured
1696            .split("queued_ms=")
1697            .nth(1)
1698            .and_then(|s| s.split_whitespace().next())
1699            .and_then(|s| s.parse().ok())
1700            .expect("queued_ms present");
1701        assert!(
1702            queued_ms >= 1500,
1703            "queued_ms reflects residency: {queued_ms}"
1704        );
1705    }
1706
1707    /// Fast polarity: a promptly-drained control reply and a stale DATA-PLANE
1708    /// frame must both stay silent — the WARN is channel-0-only by design, and
1709    /// a healthy queue must add zero log volume.
1710    #[tokio::test]
1711    async fn fresh_control_and_stale_data_frames_log_nothing() {
1712        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::WARN);
1713        let (tx, rx) = mpsc::channel::<crate::router::OutboundFrame>(4);
1714        let control = Frame::build_with_version(
1715            PROTOCOL_VERSION,
1716            FrameType::Error,
1717            Flags::new(false, Priority::Interactive, false),
1718            0,
1719            0,
1720            8,
1721            serde_json::to_vec(&ErrorBody {
1722                code: "test".into(),
1723                message: "fresh".into(),
1724                detail: None,
1725            })
1726            .expect("body encodes"),
1727        )
1728        .expect("frame builds");
1729        tx.send(crate::router::OutboundFrame {
1730            frame: control,
1731            enqueued_at: std::time::Instant::now(),
1732            flushed: None,
1733            charge: None,
1734        })
1735        .await
1736        .expect("queued");
1737        let data = Frame::build_with_version(
1738            PROTOCOL_VERSION,
1739            FrameType::Error,
1740            Flags::new(false, Priority::Interactive, false),
1741            9,
1742            1,
1743            9,
1744            serde_json::to_vec(&ErrorBody {
1745                code: "test".into(),
1746                message: "data".into(),
1747                detail: None,
1748            })
1749            .expect("body encodes"),
1750        )
1751        .expect("frame builds");
1752        tx.send(crate::router::OutboundFrame {
1753            frame: data,
1754            enqueued_at: std::time::Instant::now() - Duration::from_millis(5000),
1755            flushed: None,
1756            charge: None,
1757        })
1758        .await
1759        .expect("queued");
1760        drop(tx);
1761        let (write_half, _read_half) = duplex(64 * 1024);
1762        drain_writer(write_half, rx).await.expect("writer drains");
1763        let captured = crate::router::test_log::captured_logs(&logs);
1764        assert!(
1765            !captured.contains("slow control reply write"),
1766            "no WARN for fresh control or stale data frames, got: {captured}"
1767        );
1768    }
1769
1770    struct CountingReader {
1771        bytes: Vec<u8>,
1772        offset: usize,
1773        first_read_end: Option<usize>,
1774        reads: Arc<AtomicUsize>,
1775    }
1776
1777    impl CountingReader {
1778        fn new(bytes: Vec<u8>, first_read_end: Option<usize>) -> (Self, Arc<AtomicUsize>) {
1779            let reads = Arc::new(AtomicUsize::new(0));
1780            (
1781                Self {
1782                    bytes,
1783                    offset: 0,
1784                    first_read_end,
1785                    reads: Arc::clone(&reads),
1786                },
1787                reads,
1788            )
1789        }
1790    }
1791
1792    impl AsyncRead for CountingReader {
1793        fn poll_read(
1794            mut self: Pin<&mut Self>,
1795            _cx: &mut Context<'_>,
1796            buf: &mut ReadBuf<'_>,
1797        ) -> Poll<io::Result<()>> {
1798            self.reads.fetch_add(1, Ordering::Relaxed);
1799            let available = self.bytes.len().saturating_sub(self.offset);
1800            let first_read_remaining = self
1801                .first_read_end
1802                .filter(|end| self.offset < *end)
1803                .map_or(available, |end| end - self.offset);
1804            let count = available.min(first_read_remaining).min(buf.remaining());
1805            let end = self.offset + count;
1806            buf.put_slice(&self.bytes[self.offset..end]);
1807            self.offset = end;
1808            Poll::Ready(Ok(()))
1809        }
1810    }
1811
1812    fn encode_frames(frames: &[Frame]) -> Vec<u8> {
1813        let mut bytes = Vec::new();
1814        for frame in frames {
1815            bytes.extend_from_slice(&frame.header.encode());
1816            bytes.extend_from_slice(&frame.body);
1817        }
1818        bytes
1819    }
1820
1821    async fn read_frames<R>(reader: &mut R, count: usize) -> Vec<Frame>
1822    where
1823        R: AsyncRead + Unpin,
1824    {
1825        let mut frames = Vec::with_capacity(count);
1826        for _ in 0..count {
1827            frames.push(read_frame(reader).await.unwrap().unwrap());
1828        }
1829        frames
1830    }
1831
1832    fn request(channel: u16, corr: u64, body: &[u8]) -> Frame {
1833        Frame::build(
1834            FrameType::Request,
1835            Flags::new(true, Priority::Interactive, false),
1836            channel,
1837            0,
1838            corr,
1839            body.to_vec(),
1840        )
1841        .unwrap()
1842    }
1843
1844    fn echo_router() -> Arc<Router> {
1845        let mut router = Router::with_default_self_handler();
1846        router.register_backend(7, EchoBackend).unwrap();
1847        router.register_backend(9, EchoBackend).unwrap();
1848        Arc::new(router)
1849    }
1850
1851    fn test_auth() -> (ServerAuth, ConnectionInfo) {
1852        test_auth_with_limit(4)
1853    }
1854
1855    fn test_auth_with_limit(max_unauthenticated: usize) -> (ServerAuth, ConnectionInfo) {
1856        test_auth_with_deadline_and_limit(TEST_DEADLINE, max_unauthenticated)
1857    }
1858
1859    fn test_auth_with_deadline_and_limit(
1860        deadline: Duration,
1861        max_unauthenticated: usize,
1862    ) -> (ServerAuth, ConnectionInfo) {
1863        let key = vec![0x42; 32];
1864        let daemon_id = [0x24; 16];
1865        let conn = ConnectionInfo {
1866            schema: SCHEMA_VERSION,
1867            wire_version: None,
1868            endpoints: vec![Endpoint {
1869                host: "127.0.0.1".to_owned(),
1870                port: 1,
1871            }],
1872            key: key.clone(),
1873            daemon_id,
1874            pid: std::process::id(),
1875            daemon_ver: TEST_DAEMON_VER.to_owned(),
1876        };
1877        (
1878            ServerAuth::with_limits(
1879                key,
1880                daemon_id,
1881                TEST_DAEMON_VER,
1882                deadline,
1883                max_unauthenticated,
1884            ),
1885            conn,
1886        )
1887    }
1888
1889    async fn authenticate<S>(stream: &mut S, conn: &ConnectionInfo)
1890    where
1891        S: AsyncRead + AsyncWrite + Unpin,
1892    {
1893        authenticate_client(stream, conn, TEST_DEADLINE)
1894            .await
1895            .expect("test client should authenticate")
1896    }
1897
1898    async fn write_auth_message<S, T>(stream: &mut S, value: &T)
1899    where
1900        S: AsyncWrite + Unpin,
1901        T: Serialize,
1902    {
1903        let body = serde_json::to_vec(value).expect("auth message encodes");
1904        stream
1905            .write_all(&(body.len() as u32).to_le_bytes())
1906            .await
1907            .expect("auth message length writes");
1908        stream
1909            .write_all(&body)
1910            .await
1911            .expect("auth message body writes");
1912    }
1913
1914    async fn read_auth_message<S, T>(stream: &mut S) -> T
1915    where
1916        S: AsyncRead + Unpin,
1917        T: DeserializeOwned,
1918    {
1919        let mut length = [0; 4];
1920        stream
1921            .read_exact(&mut length)
1922            .await
1923            .expect("auth message length reads");
1924        let mut body = vec![0; u32::from_le_bytes(length) as usize];
1925        stream
1926            .read_exact(&mut body)
1927            .await
1928            .expect("auth message body reads");
1929        serde_json::from_slice(&body).expect("auth message decodes")
1930    }
1931
1932    async fn send_wrong_key_client_auth<S>(stream: &mut S, conn: &ConnectionInfo)
1933    where
1934        S: AsyncRead + AsyncWrite + Unpin,
1935    {
1936        let hello = ClientHello {
1937            client_nonce: [0x57; NONCE_LEN],
1938            role: "client".to_owned(),
1939        };
1940        write_auth_message(stream, &hello).await;
1941        let proof: ServerProof = read_auth_message(stream).await;
1942        let mut wrong_key = conn.key.clone();
1943        wrong_key[0] ^= 0xff;
1944        let client_auth = ClientAuth {
1945            client_auth: compute_proof(
1946                &wrong_key,
1947                CLIENT_AUTH_DOMAIN,
1948                &hello.client_nonce,
1949                &proof.server_nonce,
1950                &conn.daemon_id,
1951            ),
1952        };
1953        write_auth_message(stream, &client_auth).await;
1954    }
1955
1956    fn assert_pre_auth_log(logs: &Arc<std::sync::Mutex<Vec<u8>>>, stage: &str, port: u16) {
1957        let captured = crate::router::test_log::captured_logs(logs);
1958        assert!(
1959            captured.contains(&format!("stage=\"{stage}\"")),
1960            "expected rejection stage {stage}, got: {captured}"
1961        );
1962        assert!(
1963            captured.contains(&format!("peer_addr=127.0.0.1:{port}")),
1964            "expected peer address, got: {captured}"
1965        );
1966        assert!(
1967            captured.contains("elapsed_ms=") && captured.contains("suppressed_since_last="),
1968            "expected elapsed time and suppression count, got: {captured}"
1969        );
1970        assert!(
1971            !captured.contains("WARN"),
1972            "pre-auth rejection must not be logged as a warning: {captured}"
1973        );
1974    }
1975
1976    #[tokio::test]
1977    async fn logs_handshake_deadline_pre_auth_rejection() {
1978        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
1979        let deadline = Duration::from_millis(60);
1980        let (auth, _) = test_auth_with_deadline_and_limit(deadline, 4);
1981        let (client, server_stream) = duplex(512);
1982        let port = 41001;
1983        let server = handle_accepted_connection(
1984            server_stream,
1985            echo_router(),
1986            auth,
1987            SocketAddr::from(([127, 0, 0, 1], port)),
1988            Instant::now(),
1989        );
1990
1991        let error = tokio::time::timeout(deadline * 3, server)
1992            .await
1993            .expect("idle handshake should end at its deadline")
1994            .expect_err("idle handshake must be rejected");
1995        drop(client);
1996        assert!(matches!(
1997            error,
1998            ConnectionError::Auth(AuthError::Timeout {
1999                stage: AuthStage::ClientHello,
2000                ..
2001            })
2002        ));
2003        let captured = crate::router::test_log::captured_logs(&logs);
2004        assert!(
2005            captured.contains("reason=\"handshake_deadline_expired\""),
2006            "{captured}"
2007        );
2008        assert_pre_auth_log(&logs, "handshake_deadline", port);
2009    }
2010
2011    #[tokio::test]
2012    async fn logs_invalid_client_proof_pre_auth_rejection() {
2013        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2014        let (auth, conn) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2015        let (mut client, server_stream) = duplex(512);
2016        let port = 41002;
2017        let server = handle_accepted_connection(
2018            server_stream,
2019            echo_router(),
2020            auth,
2021            SocketAddr::from(([127, 0, 0, 1], port)),
2022            Instant::now(),
2023        );
2024
2025        let (error, ()) = tokio::join!(server, send_wrong_key_client_auth(&mut client, &conn));
2026        assert!(matches!(
2027            error,
2028            Err(ConnectionError::Auth(AuthError::InvalidClientAuth))
2029        ));
2030        let captured = crate::router::test_log::captured_logs(&logs);
2031        assert!(
2032            captured.contains("reason=\"client_proof_mismatch\""),
2033            "{captured}"
2034        );
2035        assert_pre_auth_log(&logs, "client_authentication", port);
2036    }
2037
2038    #[tokio::test]
2039    async fn logs_malformed_pre_auth_message() {
2040        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2041        let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2042        let (mut client, server_stream) = duplex(512);
2043        let port = 41003;
2044        let server = handle_accepted_connection(
2045            server_stream,
2046            echo_router(),
2047            auth,
2048            SocketAddr::from(([127, 0, 0, 1], port)),
2049            Instant::now(),
2050        );
2051        let send_malformed_message = async {
2052            let body = b"{";
2053            client
2054                .write_all(&(body.len() as u32).to_le_bytes())
2055                .await
2056                .expect("message length writes");
2057            client.write_all(body).await.expect("message body writes");
2058        };
2059
2060        let (error, ()) = tokio::join!(server, send_malformed_message);
2061        assert!(matches!(
2062            error,
2063            Err(ConnectionError::Auth(AuthError::JsonDecode {
2064                stage: AuthStage::ClientHello,
2065                ..
2066            }))
2067        ));
2068        let captured = crate::router::test_log::captured_logs(&logs);
2069        assert!(
2070            captured.contains("reason=\"malformed_or_oversized_message\""),
2071            "{captured}"
2072        );
2073        assert_pre_auth_log(&logs, "malformed_message", port);
2074    }
2075
2076    #[tokio::test]
2077    async fn logs_peer_close_during_handshake() {
2078        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2079        let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2080        let (client, server_stream) = duplex(512);
2081        let port = 41004;
2082        drop(client);
2083
2084        let error = handle_accepted_connection(
2085            server_stream,
2086            echo_router(),
2087            auth,
2088            SocketAddr::from(([127, 0, 0, 1], port)),
2089            Instant::now(),
2090        )
2091        .await
2092        .expect_err("closed peer must be rejected");
2093        assert!(matches!(
2094            error,
2095            ConnectionError::Auth(AuthError::UnexpectedEof {
2096                stage: AuthStage::ClientHello,
2097                actual: 0,
2098                ..
2099            })
2100        ));
2101        let captured = crate::router::test_log::captured_logs(&logs);
2102        assert!(
2103            captured.contains("reason=\"peer_closed_before_authentication_completed\""),
2104            "{captured}"
2105        );
2106        assert_pre_auth_log(&logs, "peer_closed", port);
2107    }
2108
2109    // Rejection-log rate limits belong to one listener. A process-wide limiter
2110    // let one listener's rejects silence another's for a second, which hid the
2111    // second listener's first rejection entirely.
2112    #[tokio::test]
2113    async fn each_listener_rate_limits_its_own_rejection_logs() {
2114        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2115        for port in [41011, 41012] {
2116            let (auth, _) = test_auth_with_deadline_and_limit(Duration::from_millis(200), 4);
2117            let (client, server_stream) = duplex(512);
2118            drop(client);
2119            handle_accepted_connection(
2120                server_stream,
2121                echo_router(),
2122                auth,
2123                SocketAddr::from(([127, 0, 0, 1], port)),
2124                Instant::now(),
2125            )
2126            .await
2127            .expect_err("closed peer must be rejected");
2128        }
2129        let captured = crate::router::test_log::captured_logs(&logs);
2130        for port in [41011, 41012] {
2131            assert!(
2132                captured.contains(&format!("127.0.0.1:{port}")),
2133                "listener on port {port} logged nothing: {captured}"
2134            );
2135        }
2136    }
2137
2138    #[tokio::test]
2139    async fn logs_unauthenticated_capacity_rejection() {
2140        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2141        let deadline = Duration::from_millis(60);
2142        let (auth, _) = test_auth_with_deadline_and_limit(deadline, 1);
2143        let held_slot = auth
2144            .unauthenticated
2145            .clone()
2146            .try_acquire_owned()
2147            .expect("the only pre-auth slot is available");
2148        let (client, server_stream) = duplex(512);
2149        let port = 41005;
2150        let server = handle_accepted_connection(
2151            server_stream,
2152            echo_router(),
2153            auth,
2154            SocketAddr::from(([127, 0, 0, 1], port)),
2155            Instant::now(),
2156        );
2157
2158        let error = tokio::time::timeout(deadline * 3, server)
2159            .await
2160            .expect("queued connection should end at the capacity deadline")
2161            .expect_err("connection without a free slot must be rejected");
2162        drop(held_slot);
2163        drop(client);
2164        assert!(matches!(error, ConnectionError::UnauthenticatedCapacity));
2165        let captured = crate::router::test_log::captured_logs(&logs);
2166        assert!(
2167            captured.contains("reason=\"capacity_wait_timed_out\""),
2168            "{captured}"
2169        );
2170        assert_pre_auth_log(&logs, "waiting_for_handshake_slot", port);
2171    }
2172
2173    #[test]
2174    fn pre_auth_rejection_limiter_suppresses_bursts_and_reports_count() {
2175        let (logs, _guard) = crate::router::test_log::log_capture(tracing::Level::INFO);
2176        let limiter = PreAuthRejectLimiter::new();
2177        let capacity = ConnectionError::UnauthenticatedCapacity;
2178        let handshake_timeout = ConnectionError::Auth(AuthError::Timeout {
2179            stage: AuthStage::ClientHello,
2180            deadline: Duration::from_millis(200),
2181        });
2182        let peer_addr = SocketAddr::from(([127, 0, 0, 1], 41006));
2183
2184        log_pre_auth_rejection(
2185            &capacity,
2186            peer_addr,
2187            Duration::from_millis(1),
2188            Duration::ZERO,
2189            &limiter,
2190        );
2191        for _ in 0..4 {
2192            log_pre_auth_rejection(
2193                &capacity,
2194                peer_addr,
2195                Duration::from_millis(2),
2196                Duration::from_millis(100),
2197                &limiter,
2198            );
2199        }
2200        log_pre_auth_rejection(
2201            &handshake_timeout,
2202            peer_addr,
2203            Duration::from_millis(3),
2204            Duration::from_millis(100),
2205            &limiter,
2206        );
2207        log_pre_auth_rejection(
2208            &capacity,
2209            peer_addr,
2210            Duration::from_millis(4),
2211            Duration::from_secs(1),
2212            &limiter,
2213        );
2214
2215        let captured = crate::router::test_log::captured_logs(&logs);
2216        assert_eq!(
2217            captured
2218                .matches("subc TCP connection rejected before routing")
2219                .count(),
2220            3,
2221            "one line per stage in a burst, then a later capacity line: {captured}"
2222        );
2223        assert!(
2224            captured.contains("suppressed_since_last=4"),
2225            "later capacity line should report the four hidden rejects: {captured}"
2226        );
2227        assert!(
2228            captured.contains("stage=\"handshake_deadline\""),
2229            "{captured}"
2230        );
2231    }
2232
2233    #[tokio::test]
2234    async fn buffered_frame_reader_coalesces_reads_and_preserves_short_reads() {
2235        let frames = vec![
2236            request(7, 1, b"first"),
2237            request(9, 2, b"second"),
2238            request(7, 3, b"third"),
2239            request(9, 4, b"fourth"),
2240        ];
2241        let bytes = encode_frames(&frames);
2242
2243        let (mut direct, direct_reads) = CountingReader::new(bytes.clone(), None);
2244        assert_eq!(read_frames(&mut direct, frames.len()).await, frames);
2245        assert_eq!(direct_reads.load(Ordering::Relaxed), frames.len() * 3);
2246
2247        let (buffered_source, buffered_reads) = CountingReader::new(bytes, None);
2248        let mut buffered = BufReader::new(buffered_source);
2249        assert_eq!(read_frames(&mut buffered, frames.len()).await, frames);
2250        assert_eq!(buffered_reads.load(Ordering::Relaxed), 1);
2251
2252        let split_frame = request(7, 5, b"split-body");
2253        let split_bytes = encode_frames(std::slice::from_ref(&split_frame));
2254        let (split_source, split_reads) = CountingReader::new(split_bytes, Some(10));
2255        let mut split_reader = BufReader::new(split_source);
2256        assert_eq!(
2257            read_frame(&mut split_reader).await.unwrap(),
2258            Some(split_frame)
2259        );
2260        assert_eq!(split_reads.load(Ordering::Relaxed), 2);
2261    }
2262
2263    #[tokio::test]
2264    async fn interleaved_channels_on_one_stream_demux_byte_identically_after_auth() {
2265        let (mut client, server_stream) = duplex(4096);
2266        let (auth, conn) = test_auth();
2267        let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
2268        authenticate(&mut client, &conn).await;
2269        let frames = [
2270            request(7, 1, b"chan7-first\0opaque"),
2271            request(9, 2, b"chan9-middle-{json?}"),
2272            request(7, 3, b"chan7-second\xffbytes"),
2273        ];
2274
2275        for frame in &frames {
2276            crate::write_frame(&mut client, frame).await.unwrap();
2277        }
2278
2279        for expected in &frames {
2280            let response = crate::read_frame(&mut client).await.unwrap().unwrap();
2281            assert_eq!(response.header.ty, FrameType::Response);
2282            assert_eq!(response.header.channel, expected.header.channel);
2283            assert_eq!(response.header.corr, expected.header.corr);
2284            assert_eq!(response.body, expected.body);
2285        }
2286
2287        drop(client);
2288        server.await.unwrap().unwrap();
2289    }
2290
2291    #[tokio::test]
2292    async fn channel_zero_goes_to_subc_self_handler_after_auth() {
2293        let (mut client, server_stream) = duplex(512);
2294        let (auth, conn) = test_auth();
2295        let server = tokio::spawn(handle_connection(
2296            server_stream,
2297            Arc::new(Router::with_default_self_handler()),
2298            auth,
2299        ));
2300        authenticate(&mut client, &conn).await;
2301        let ping = Frame::build(
2302            FrameType::Ping,
2303            Flags::new(false, Priority::Passive, false),
2304            0,
2305            0,
2306            55,
2307            Vec::new(),
2308        )
2309        .unwrap();
2310
2311        crate::write_frame(&mut client, &ping).await.unwrap();
2312        let response = crate::read_frame(&mut client).await.unwrap().unwrap();
2313
2314        assert_eq!(response.header.ty, FrameType::Pong);
2315        assert_eq!(response.header.channel, 0);
2316        assert_eq!(response.header.corr, 55);
2317        assert!(response.body.is_empty());
2318
2319        drop(client);
2320        server.await.unwrap().unwrap();
2321    }
2322
2323    #[tokio::test]
2324    async fn unauthenticated_connection_is_rejected_before_routing() {
2325        let (mut client, server_stream) = duplex(512);
2326        let (auth, _conn) = test_auth();
2327        let registry = Arc::new(Registry::default());
2328        let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
2329            Arc::clone(&registry),
2330        ))));
2331        let server = tokio::spawn(handle_connection(server_stream, router, auth));
2332        let ping = Frame::build(
2333            FrameType::Ping,
2334            Flags::new(false, Priority::Passive, false),
2335            0,
2336            0,
2337            66,
2338            Vec::new(),
2339        )
2340        .unwrap();
2341
2342        crate::write_frame(&mut client, &ping).await.unwrap();
2343        if let Ok(Ok(Some(frame))) =
2344            tokio::time::timeout(Duration::from_millis(200), crate::read_frame(&mut client)).await
2345        {
2346            panic!("unauthenticated frame reached router: {frame:?}");
2347        }
2348
2349        let err = server.await.unwrap().unwrap_err();
2350        assert!(matches!(err, ConnectionError::Auth(_)));
2351        assert_eq!(registry.active_registration_count().unwrap(), 0);
2352    }
2353
2354    #[tokio::test]
2355    async fn over_cap_peer_queues_for_a_slot_and_authenticates_when_one_frees() {
2356        // Restart-herd contract: an over-cap pre-auth connection WAITS (bounded by
2357        // the auth deadline) instead of being reset. When the slot-holder finishes,
2358        // the queued peer must complete a normal handshake — the 2026-07-14 aft
2359        // outage was exactly a supervised child being reset out of this lottery.
2360        let (mut first_client, first_server_stream) = duplex(2048);
2361        let (mut second_client, second_server_stream) = duplex(2048);
2362        let (auth, conn) = test_auth_with_limit(1);
2363        let registry = Arc::new(Registry::default());
2364        let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
2365            Arc::clone(&registry),
2366        ))));
2367
2368        let first_server = tokio::spawn(handle_connection(
2369            first_server_stream,
2370            Arc::clone(&router),
2371            auth.clone(),
2372        ));
2373
2374        let second_server = tokio::spawn(handle_connection(
2375            second_server_stream,
2376            Arc::clone(&router),
2377            auth.clone(),
2378        ));
2379
2380        // The second peer must still be pending (not reset) while the slot is held.
2381        tokio::time::sleep(Duration::from_millis(50)).await;
2382        assert!(
2383            !second_server.is_finished(),
2384            "queued peer must not be reset"
2385        );
2386
2387        // First peer completes its handshake, freeing the slot; the queued second
2388        // peer then authenticates normally.
2389        authenticate(&mut first_client, &conn).await;
2390        authenticate(&mut second_client, &conn).await;
2391
2392        drop(first_client);
2393        drop(second_client);
2394        let _ = first_server.await;
2395        let _ = second_server.await;
2396        assert_eq!(registry.active_registration_count().unwrap(), 0);
2397    }
2398
2399    #[tokio::test]
2400    async fn over_cap_peer_is_rejected_when_no_slot_frees_within_deadline() {
2401        // The deadline stays the DoS bound: if no slot frees, the queued peer is
2402        // rejected at the deadline with a closed stream. The slot is held DIRECTLY
2403        // (not by another connection) so nothing can free it mid-test — a squatting
2404        // connection's own auth deadline would release the slot at exactly the
2405        // waiter's timeout, making the outcome racy.
2406        let (mut second_client, second_server_stream) = duplex(512);
2407        let (auth, conn) = test_auth_with_limit(1);
2408        let registry = Arc::new(Registry::default());
2409        let router = Arc::new(Router::with_control_handler(Arc::new(ControlHandler::new(
2410            Arc::clone(&registry),
2411        ))));
2412
2413        let held_slot = auth
2414            .unauthenticated
2415            .clone()
2416            .try_acquire_owned()
2417            .expect("sole pre-auth slot");
2418
2419        let second_server = tokio::spawn(handle_connection(
2420            second_server_stream,
2421            Arc::clone(&router),
2422            auth.clone(),
2423        ));
2424        let second_err = tokio::time::timeout(TEST_DEADLINE * 2, second_server)
2425            .await
2426            .expect("capacity reject should settle at the deadline")
2427            .expect("second connection task should not panic")
2428            .expect_err("queued peer must be rejected when no slot frees");
2429        drop(held_slot);
2430        assert!(matches!(
2431            second_err,
2432            ConnectionError::UnauthenticatedCapacity
2433        ));
2434        let mut closed = [0u8; 1];
2435        assert_eq!(
2436            second_client.read(&mut closed).await.unwrap(),
2437            0,
2438            "capacity-rejected peer should observe a closed stream"
2439        );
2440        assert_eq!(registry.active_registration_count().unwrap(), 0);
2441
2442        let (mut authed_client, authed_server_stream) = duplex(2048);
2443        let authed_server = tokio::spawn(handle_connection(
2444            authed_server_stream,
2445            Arc::clone(&router),
2446            auth,
2447        ));
2448        authenticate(&mut authed_client, &conn).await;
2449        let ping = Frame::build(
2450            FrameType::Ping,
2451            Flags::new(false, Priority::Passive, false),
2452            0,
2453            0,
2454            77,
2455            Vec::new(),
2456        )
2457        .unwrap();
2458        crate::write_frame(&mut authed_client, &ping).await.unwrap();
2459        let pong = crate::read_frame(&mut authed_client)
2460            .await
2461            .unwrap()
2462            .unwrap();
2463        assert_eq!(pong.header.ty, FrameType::Pong);
2464        assert_eq!(pong.header.channel, 0);
2465        assert_eq!(pong.header.corr, 77);
2466        assert_eq!(registry.active_registration_count().unwrap(), 0);
2467
2468        drop(authed_client);
2469        authed_server.await.unwrap().unwrap();
2470    }
2471
2472    #[tokio::test]
2473    async fn bind_ack_during_partial_frame_preserves_next_request() {
2474        use subc_control::ClientControlRequest;
2475        use subc_protocol::{
2476            manifest::{
2477                Concurrency, ExecutionMode, IdentityScope, ModuleManifest, ProviderRole, Tool,
2478            },
2479            session::{ModuleControlRequest, ModuleControlResponse},
2480            BindIdentity, ModuleHelloBody, RouteTarget,
2481        };
2482
2483        let mut configured_router = Router::with_default_self_handler();
2484        configured_router.register_backend(7, EchoBackend).unwrap();
2485        let router = Arc::new(configured_router);
2486        let (auth, conn) = test_auth();
2487        let (mut module, module_stream) = duplex(4096);
2488        let module_server = tokio::spawn(handle_connection(
2489            module_stream,
2490            Arc::clone(&router),
2491            auth.clone(),
2492        ));
2493        authenticate(&mut module, &conn).await;
2494        let manifest = ModuleManifest::builder("frame-test", "0.1.0")
2495            .protocol_ver(PROTOCOL_VERSION)
2496            .provides(vec![ProviderRole::ToolProvider {
2497                tools: vec![Tool {
2498                    name: "read".into(),
2499                    description: None,
2500                    execution_mode: ExecutionMode::Pure,
2501                    schema: serde_json::json!({"type": "object"}),
2502                }],
2503                identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
2504                concurrency: Concurrency::ModuleManaged,
2505                emits_push: true,
2506                sub_supervises: true,
2507            }])
2508            .build();
2509        let hello = Frame::build(
2510            FrameType::Hello,
2511            Flags::new(false, Priority::Passive, false),
2512            0,
2513            0,
2514            1,
2515            serde_json::to_vec(&ModuleHelloBody {
2516                manifest,
2517                protocol_ver: PROTOCOL_VERSION,
2518                control_ops: None,
2519                launch_nonce: None,
2520            })
2521            .unwrap(),
2522        )
2523        .unwrap();
2524        crate::write_frame(&mut module, &hello).await.unwrap();
2525        assert_eq!(
2526            read_frame(&mut module).await.unwrap().unwrap().header.ty,
2527            FrameType::HelloAck
2528        );
2529
2530        let (mut client, client_stream) = duplex(4096);
2531        let client_server = tokio::spawn(handle_connection(client_stream, router, auth));
2532        authenticate(&mut client, &conn).await;
2533        let open = Frame::build(
2534            FrameType::Request,
2535            Flags::new(false, Priority::Passive, false),
2536            0,
2537            0,
2538            2,
2539            serde_json::to_vec(&ClientControlRequest::RouteOpen {
2540                target: RouteTarget::ToolProvider {
2541                    module_id: "frame-test".into(),
2542                },
2543                identity: BindIdentity::new(std::env::current_dir().unwrap(), "unit", "session"),
2544                consumer_identity: None,
2545                consumer_capabilities: None,
2546                role_versions: None,
2547                admission_facts: None,
2548                scope: None,
2549            })
2550            .unwrap(),
2551        )
2552        .unwrap();
2553        crate::write_frame(&mut client, &open).await.unwrap();
2554        let bind = timeout(TEST_DEADLINE, read_frame(&mut module))
2555            .await
2556            .unwrap()
2557            .unwrap()
2558            .unwrap();
2559        assert!(matches!(
2560            serde_json::from_slice::<ModuleControlRequest>(&bind.body).unwrap(),
2561            ModuleControlRequest::RouteBind { .. }
2562        ));
2563
2564        let ping = request(7, 3, b"partial-frame-body");
2565        client.write_all(&ping.header.encode()).await.unwrap();
2566        // Give the connection reader time to consume the header while the bind is pending.
2567        tokio::time::sleep(Duration::from_millis(30)).await;
2568        let ack = Frame::build(
2569            FrameType::Response,
2570            Flags::new(false, Priority::Passive, false),
2571            0,
2572            0,
2573            bind.header.corr,
2574            serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap(),
2575        )
2576        .unwrap();
2577        crate::write_frame(&mut module, &ack).await.unwrap();
2578        let opened = timeout(TEST_DEADLINE, read_frame(&mut client))
2579            .await
2580            .unwrap()
2581            .unwrap();
2582        if opened.is_none() {
2583            panic!("client closed: {:?}", client_server.await);
2584        }
2585        let opened = opened.unwrap();
2586        assert_eq!(opened.header.corr, 2);
2587        client.write_all(&ping.body).await.unwrap();
2588        let pong = timeout(TEST_DEADLINE, read_frame(&mut client))
2589            .await
2590            .expect("partial frame must reach the router after the bind ack")
2591            .expect("frame must decode")
2592            .expect("connection must remain open");
2593        assert_eq!(pong.header.ty, FrameType::Response);
2594        assert_eq!(pong.header.corr, 3);
2595        assert_eq!(pong.body, ping.body);
2596        drop(client);
2597        drop(module);
2598        client_server.await.unwrap().unwrap();
2599        let _ = module_server.await.unwrap();
2600    }
2601
2602    #[tokio::test]
2603    async fn full_module_egress_health_probe_does_not_block_same_client_other_route() {
2604        use crate::ConnectionId;
2605        use subc_control::{ClientControlRequest, ClientControlResponse};
2606        use subc_protocol::{
2607            manifest::{
2608                Concurrency, ExecutionMode, IdentityScope, ModuleManifest, ProviderRole, Tool,
2609            },
2610            session::ModuleControlResponse,
2611            BindIdentity, ModuleHelloBody, RouteTarget,
2612        };
2613
2614        let probe_timeout = Duration::from_millis(100);
2615        let handler = Arc::new(
2616            ControlHandler::new(Arc::new(Registry::default()))
2617                .with_health_probe_timeout(probe_timeout),
2618        );
2619        let router = Arc::new(Router::with_control_handler(Arc::clone(&handler)));
2620        let hello = |name: &str| {
2621            Frame::build(
2622                FrameType::Hello,
2623                Flags::new(false, Priority::Passive, false),
2624                0,
2625                0,
2626                1,
2627                serde_json::to_vec(&ModuleHelloBody {
2628                    manifest: ModuleManifest::builder(name, "0.1.0")
2629                        .protocol_ver(PROTOCOL_VERSION)
2630                        .provides(vec![ProviderRole::ToolProvider {
2631                            tools: vec![Tool {
2632                                name: "read".into(),
2633                                description: None,
2634                                execution_mode: ExecutionMode::Pure,
2635                                schema: serde_json::json!({"type": "object"}),
2636                            }],
2637                            identity_scope: vec![IdentityScope::Project, IdentityScope::Session],
2638                            concurrency: Concurrency::ModuleManaged,
2639                            emits_push: false,
2640                            sub_supervises: false,
2641                        }])
2642                        .build(),
2643                    protocol_ver: PROTOCOL_VERSION,
2644                    control_ops: Some(vec!["health.check".to_owned()]),
2645                    launch_nonce: None,
2646                })
2647                .unwrap(),
2648            )
2649            .unwrap()
2650        };
2651        let (blocked_tx, mut blocked_rx) = mpsc::channel(1);
2652        let blocked_ctx = RouteCtx {
2653            connection_id: ConnectionId::new(90001),
2654            egress: FrameSink::new(blocked_tx),
2655        };
2656        handler
2657            .handle_control_frame(&blocked_ctx, hello("blocked"))
2658            .await
2659            .unwrap();
2660        assert_eq!(
2661            blocked_rx.try_recv().unwrap().header.ty,
2662            FrameType::HelloAck
2663        );
2664        let filler = request(0, 99, b"queue filler");
2665        blocked_ctx.egress.try_send(filler.clone()).unwrap();
2666        assert!(
2667            blocked_ctx.egress.try_send(filler).is_err(),
2668            "module queue must actually be full"
2669        );
2670
2671        let (healthy_tx, mut healthy_rx) = mpsc::channel(8);
2672        let healthy_ctx = RouteCtx {
2673            connection_id: ConnectionId::new(90002),
2674            egress: FrameSink::new(healthy_tx),
2675        };
2676        handler
2677            .handle_control_frame(&healthy_ctx, hello("healthy"))
2678            .await
2679            .unwrap();
2680        assert_eq!(
2681            healthy_rx.try_recv().unwrap().header.ty,
2682            FrameType::HelloAck
2683        );
2684        let (auth, conn) = test_auth();
2685        let (mut client, client_stream) = duplex(4096);
2686        let client_server =
2687            tokio::spawn(handle_connection(client_stream, Arc::clone(&router), auth));
2688        authenticate(&mut client, &conn).await;
2689        let control_request = |corr, body: ClientControlRequest| {
2690            Frame::build(
2691                FrameType::Request,
2692                Flags::new(false, Priority::Interactive, false),
2693                0,
2694                0,
2695                corr,
2696                serde_json::to_vec(&body).unwrap(),
2697            )
2698            .unwrap()
2699        };
2700        crate::write_frame(
2701            &mut client,
2702            &control_request(
2703                2,
2704                ClientControlRequest::RouteOpen {
2705                    target: RouteTarget::ToolProvider {
2706                        module_id: "healthy".into(),
2707                    },
2708                    identity: BindIdentity::new(
2709                        std::env::current_dir().unwrap(),
2710                        "unit",
2711                        "session",
2712                    ),
2713                    consumer_identity: None,
2714                    consumer_capabilities: None,
2715                    role_versions: None,
2716                    admission_facts: None,
2717                    scope: None,
2718                },
2719            ),
2720        )
2721        .await
2722        .unwrap();
2723        let bind = timeout(TEST_DEADLINE, healthy_rx.recv())
2724            .await
2725            .unwrap()
2726            .unwrap();
2727        handler
2728            .handle_control_frame(
2729                &healthy_ctx,
2730                Frame::build(
2731                    FrameType::Response,
2732                    Flags::new(false, Priority::Passive, false),
2733                    0,
2734                    0,
2735                    bind.header.corr,
2736                    serde_json::to_vec(&ModuleControlResponse::RouteBindAck {}).unwrap(),
2737                )
2738                .unwrap(),
2739            )
2740            .await
2741            .unwrap();
2742        let opened = timeout(TEST_DEADLINE, read_frame(&mut client))
2743            .await
2744            .unwrap()
2745            .unwrap()
2746            .unwrap();
2747        let (channel, epoch) =
2748            match serde_json::from_slice::<ClientControlResponse>(&opened.body).unwrap() {
2749                ClientControlResponse::RouteOpen {
2750                    route_channel,
2751                    route_epoch,
2752                } => (route_channel, route_epoch),
2753                other => panic!("expected a healthy module route, got {other:?}"),
2754            };
2755
2756        let probe = control_request(
2757            3,
2758            ClientControlRequest::SupervisorHealthProbe {
2759                module_id: "blocked".into(),
2760            },
2761        );
2762        let mut ping = request(channel, 4, b"healthy request");
2763        ping.header.epoch = epoch;
2764        crate::write_frame(&mut client, &probe).await.unwrap();
2765        crate::write_frame(&mut client, &ping).await.unwrap();
2766        timeout(probe_timeout + Duration::from_secs(1), async {
2767            let timed_out = read_frame(&mut client).await.unwrap().unwrap();
2768            assert_eq!(timed_out.header.corr, 3);
2769            assert_eq!(timed_out.header.ty, FrameType::Error);
2770            let error: ErrorBody = serde_json::from_slice(&timed_out.body).unwrap();
2771            assert_eq!(error.code, "module_timeout");
2772            let forwarded = healthy_rx.recv().await.unwrap();
2773            assert_eq!(forwarded.header.corr, ping.header.corr);
2774            assert_eq!(forwarded.body, ping.body);
2775            let reply = Frame::build(
2776                FrameType::Response,
2777                ping.header.flags,
2778                forwarded.header.channel,
2779                forwarded.header.epoch,
2780                forwarded.header.corr,
2781                b"healthy response".to_vec(),
2782            )
2783            .unwrap();
2784            router
2785                .route_for_connection(&healthy_ctx, reply)
2786                .await
2787                .unwrap();
2788            let pong = read_frame(&mut client).await.unwrap().unwrap();
2789            assert_eq!(pong.header.ty, FrameType::Response);
2790            assert_eq!(pong.header.channel, channel);
2791            assert_eq!(pong.header.epoch, epoch);
2792            assert_eq!(pong.header.corr, 4);
2793            assert_eq!(pong.body, b"healthy response");
2794        })
2795        .await
2796        .expect(
2797            "the same client's healthy route must answer within the probe deadline plus margin",
2798        );
2799        assert_eq!(
2800            blocked_rx.len(),
2801            1,
2802            "the blocked module must remain undrained"
2803        );
2804        assert_eq!(blocked_rx.try_recv().unwrap().header.corr, 99);
2805        assert!(
2806            blocked_rx.try_recv().is_err(),
2807            "a timed-out probe must not be enqueued later"
2808        );
2809        drop(client);
2810        client_server.await.unwrap().unwrap();
2811    }
2812
2813    #[tokio::test]
2814    async fn aborted_accept_does_not_end_listener() {
2815        let listener = Arc::new(TcpListener::bind("127.0.0.1:0").await.unwrap());
2816        let addr = listener.local_addr().unwrap();
2817        let (auth, conn) = test_auth();
2818        let mut attempts = 0;
2819        let server = tokio::spawn(serve_listener_with_accept(
2820            Some(addr),
2821            echo_router(),
2822            auth,
2823            move || {
2824                attempts += 1;
2825                let result = if attempts == 1 {
2826                    Some(io::Error::from(io::ErrorKind::ConnectionAborted))
2827                } else {
2828                    None
2829                };
2830                let listener = Arc::clone(&listener);
2831                async move {
2832                    match result {
2833                        Some(err) => Err(err),
2834                        None => listener.accept().await,
2835                    }
2836                }
2837            },
2838        ));
2839        let mut client = tokio::net::TcpStream::connect(addr).await.unwrap();
2840        authenticate(&mut client, &conn).await;
2841        let ping = Frame::build(
2842            FrameType::Ping,
2843            Flags::new(false, Priority::Passive, false),
2844            0,
2845            0,
2846            77,
2847            Vec::new(),
2848        )
2849        .unwrap();
2850        crate::write_frame(&mut client, &ping).await.unwrap();
2851        let pong = timeout(TEST_DEADLINE, read_frame(&mut client))
2852            .await
2853            .unwrap()
2854            .unwrap()
2855            .unwrap();
2856        assert_eq!(pong.header.ty, FrameType::Pong);
2857        assert!(
2858            !server.is_finished(),
2859            "a temporary accept failure must not stop the listener"
2860        );
2861        server.abort();
2862    }
2863
2864    #[tokio::test]
2865    async fn exhausted_accept_backs_off_then_serves_connection() {
2866        let listener = Arc::new(TcpListener::bind("127.0.0.1:0").await.unwrap());
2867        let addr = listener.local_addr().unwrap();
2868        let (auth, conn) = test_auth();
2869        let mut attempts = 0;
2870        let server = tokio::spawn(serve_listener_with_accept(
2871            Some(addr),
2872            echo_router(),
2873            auth,
2874            move || {
2875                attempts += 1;
2876                // The platform's "too many open files" code: EMFILE on Unix,
2877                // WSAEMFILE on Windows. A bare 24 is ERROR_BAD_LENGTH on Windows.
2878                #[cfg(unix)]
2879                let emfile = rustix::io::Errno::MFILE.raw_os_error();
2880                #[cfg(windows)]
2881                let emfile = 10024;
2882                let error = (attempts == 1).then(|| io::Error::from_raw_os_error(emfile));
2883                let listener = Arc::clone(&listener);
2884                async move {
2885                    match error {
2886                        Some(err) => Err(err),
2887                        None => listener.accept().await,
2888                    }
2889                }
2890            },
2891        ));
2892        let started = Instant::now();
2893        let mut client = tokio::net::TcpStream::connect(addr).await.unwrap();
2894        authenticate(&mut client, &conn).await;
2895        assert!(
2896            started.elapsed() >= Duration::from_millis(50),
2897            "fd exhaustion must back off before retrying"
2898        );
2899        assert!(!server.is_finished());
2900        server.abort();
2901    }
2902
2903    #[tokio::test]
2904    async fn fatal_accept_error_still_stops_listener() {
2905        let (auth, _) = test_auth();
2906        let err = serve_listener_with_accept(None, echo_router(), auth, || async {
2907            Err(io::Error::from(io::ErrorKind::PermissionDenied))
2908        })
2909        .await
2910        .unwrap_err();
2911        assert!(
2912            matches!(err, ServerError::Accept { source, .. } if source.kind() == io::ErrorKind::PermissionDenied)
2913        );
2914    }
2915
2916    #[tokio::test]
2917    async fn serve_listeners_with_no_listeners_returns_typed_error() {
2918        let (auth, _conn) = test_auth();
2919        let err = serve_listeners(Vec::new(), echo_router(), auth)
2920            .await
2921            .expect_err("empty listener set must fail loudly");
2922        assert!(matches!(err, ServerError::NoListeners));
2923    }
2924
2925    #[tokio::test]
2926    async fn malformed_header_returns_typed_error_no_panic() {
2927        let (mut client, server_stream) = duplex(128);
2928        let (auth, conn) = test_auth();
2929        let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
2930        authenticate(&mut client, &conn).await;
2931        let mut header = [0u8; HEADER_LEN];
2932        header[4] = PROTOCOL_VERSION;
2933        header[5] = 250;
2934
2935        client.write_all(&header).await.unwrap();
2936        drop(client);
2937
2938        let err = server.await.unwrap().unwrap_err();
2939        assert!(matches!(
2940            err,
2941            ConnectionError::FrameIo(FrameIoError::DecodeHeader(DecodeError::UnknownFrameType {
2942                byte: 250
2943            }))
2944        ));
2945    }
2946
2947    #[tokio::test]
2948    async fn truncated_body_returns_typed_error_no_panic() {
2949        let (mut client, server_stream) = duplex(128);
2950        let (auth, conn) = test_auth();
2951        let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
2952        authenticate(&mut client, &conn).await;
2953        let frame = request(7, 8, b"abcd");
2954
2955        client.write_all(&frame.header.encode()).await.unwrap();
2956        client.write_all(b"ab").await.unwrap();
2957        drop(client);
2958
2959        let err = server.await.unwrap().unwrap_err();
2960        assert!(matches!(
2961            err,
2962            ConnectionError::FrameIo(FrameIoError::UnexpectedEof {
2963                stage: ReadStage::Body,
2964                expected: 4,
2965                actual: 2
2966            })
2967        ));
2968    }
2969
2970    #[tokio::test]
2971    async fn unknown_channel_is_returned_as_error_frame_and_connection_continues() {
2972        let (mut client, server_stream) = duplex(1024);
2973        let (auth, conn) = test_auth();
2974        let server = tokio::spawn(handle_connection(server_stream, echo_router(), auth));
2975        authenticate(&mut client, &conn).await;
2976        let unknown = request(42, 10, b"lost");
2977        let known = request(7, 11, b"still-routes");
2978
2979        crate::write_frame(&mut client, &unknown).await.unwrap();
2980        crate::write_frame(&mut client, &known).await.unwrap();
2981
2982        let error = crate::read_frame(&mut client).await.unwrap().unwrap();
2983        assert_eq!(error.header.ty, FrameType::Error);
2984        assert_eq!(error.header.channel, 42);
2985        assert_eq!(error.header.corr, 10);
2986        let error_body: ErrorBody = serde_json::from_slice(&error.body).unwrap();
2987        assert_eq!(error_body.code, "unknown_channel");
2988
2989        let response = crate::read_frame(&mut client).await.unwrap().unwrap();
2990        assert_eq!(response.header.ty, FrameType::Response);
2991        assert_eq!(response.header.channel, 7);
2992        assert_eq!(response.header.corr, 11);
2993        assert_eq!(response.body, b"still-routes");
2994
2995        drop(client);
2996        server.await.unwrap().unwrap();
2997    }
2998}