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