Skip to main content

subc_daemon/
server.rs

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