Skip to main content

dustnet_server/
lib.rs

1#![forbid(unsafe_code)]
2// Remote clients choose every byte this server frames and every path it is
3// asked to serve, so an operation
4// that can panic on out-of-range input is a denial of service against every
5// other connection the process is holding. Denied in non-test builds only:
6// tests assert on known-good values, where `unwrap` is the clearer spelling.
7#![cfg_attr(
8    not(test),
9    deny(
10        clippy::indexing_slicing,
11        clippy::unwrap_used,
12        clippy::expect_used,
13        clippy::panic
14    )
15)]
16
17//! Bounded, plugin-free static ATP server.
18
19mod certs;
20pub mod include;
21pub mod input;
22mod live_watch;
23pub mod session;
24mod transport;
25
26use std::collections::HashMap;
27use std::net::IpAddr;
28use std::path::{Component, Path, PathBuf};
29use std::sync::{Arc, Mutex};
30use std::time::Duration;
31
32use dustnet_core::protocol::frame::{MessageType, RawFrame, allocate_frame_body};
33use dustnet_core::protocol::message::{
34    ErrorMessage, GetMessage, HelloMessage, InputMessage, PageFlags, PageMessage, SubscribeMessage,
35    SubscribeMode, UpdateMessage, WelcomeMessage,
36};
37use dustnet_core::protocol::{
38    MAX_PAGE_MESSAGE_SIZE, MAX_WASM_MODULE_SIZE, PROTOCOL_VERSION, ProtocolError,
39    SUPPORTED_CAPABILITIES,
40};
41use tokio::io::AsyncReadExt;
42use tokio::sync::{mpsc, watch};
43
44use crate::live_watch::{
45    ChangeSource, LiveGeneration, LiveWatcher, ManualChangeSource, NotifyChangeSource,
46    WatchRegistry,
47};
48use crate::transport::{AtpListener, AtpServerStream};
49
50/// Default server-wide connection ceiling.
51///
52/// An idle connection costs memory; a TLS handshake costs CPU. Holding
53/// connections open is therefore the cheaper side of the trade, and the number
54/// that used to sit here reflected the old per-connection subscription polling
55/// rather than any protocol limit. Operators can raise or lower it with
56/// `--max-connections`; note that the process also needs an `RLIMIT_NOFILE`
57/// above this value, which the OS will not grant on our behalf (see
58/// `docs/guides/production-support.md`).
59pub const DEFAULT_MAX_CONNECTIONS: usize = 2048;
60
61/// Default per-source-IP connection ceiling.
62pub const DEFAULT_MAX_CONNECTIONS_PER_IP: usize = 4;
63const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
64const READ_TIMEOUT: Duration = Duration::from_secs(30);
65const WRITE_TIMEOUT: Duration = Duration::from_secs(10);
66const DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
67const MAX_SUBSCRIPTIONS_PER_CONNECTION: usize = 16;
68const MAX_SERVER_SUBSCRIPTION_BYTES: usize = 128 * 1024 * 1024;
69
70#[derive(Clone, Debug)]
71pub(crate) struct SubscriptionBudget {
72    state: Arc<Mutex<SubscriptionBudgetState>>,
73}
74
75#[derive(Debug)]
76struct SubscriptionBudgetState {
77    used: usize,
78    limit: usize,
79}
80
81impl SubscriptionBudget {
82    pub(crate) fn new(limit: usize) -> Self {
83        Self {
84            state: Arc::new(Mutex::new(SubscriptionBudgetState { used: 0, limit })),
85        }
86    }
87
88    pub(crate) fn reserve(&self, requested: usize) -> Result<SubscriptionLease, ProtocolError> {
89        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
90        let next = state
91            .used
92            .checked_add(requested)
93            .ok_or(ProtocolError::ResourceExhausted { requested })?;
94        if next > state.limit {
95            let (used, limit) = (state.used, state.limit);
96            drop(state);
97            // Every refusal is logged, not the first or one per connection.
98            // A refusal is the server silently declining to deliver a live
99            // update someone asked for, and an operator who sees a stalled
100            // region has no other way to find out that is what happened.
101            tracing::warn!(
102                requested,
103                used,
104                limit,
105                "live update refused: subscription budget exhausted"
106            );
107            return Err(ProtocolError::ResourceExhausted { requested });
108        }
109        state.used = next;
110        drop(state);
111        Ok(SubscriptionLease {
112            budget: self.clone(),
113            amount: requested,
114        })
115    }
116
117    /// Bytes currently reserved for retained subscription content.
118    ///
119    /// Exposed so an operator can see budget pressure before it becomes a
120    /// stalled live region rather than after.
121    pub(crate) fn used(&self) -> usize {
122        self.state
123            .lock()
124            .unwrap_or_else(|error| error.into_inner())
125            .used
126    }
127
128    /// The server-wide ceiling `used` is measured against.
129    fn limit(&self) -> usize {
130        self.state
131            .lock()
132            .unwrap_or_else(|error| error.into_inner())
133            .limit
134    }
135}
136
137#[derive(Debug)]
138pub(crate) struct SubscriptionLease {
139    budget: SubscriptionBudget,
140    amount: usize,
141}
142
143impl SubscriptionLease {
144    fn try_resize(&mut self, requested: usize) -> Result<(), ProtocolError> {
145        let mut state = self
146            .budget
147            .state
148            .lock()
149            .unwrap_or_else(|error| error.into_inner());
150        let without_self = state.used.saturating_sub(self.amount);
151        let next = without_self
152            .checked_add(requested)
153            .ok_or(ProtocolError::ResourceExhausted { requested })?;
154        if next > state.limit {
155            return Err(ProtocolError::ResourceExhausted { requested });
156        }
157        state.used = next;
158        self.amount = requested;
159        Ok(())
160    }
161
162    fn ensure_at_least(&mut self, requested: usize) -> Result<(), ProtocolError> {
163        if requested > self.amount {
164            self.try_resize(requested)?;
165        }
166        Ok(())
167    }
168
169    pub(crate) fn shrink_to(&mut self, requested: usize) {
170        debug_assert!(requested <= self.amount);
171        let mut state = self
172            .budget
173            .state
174            .lock()
175            .unwrap_or_else(|error| error.into_inner());
176        state.used -= self.amount - requested;
177        self.amount = requested;
178    }
179}
180
181impl Drop for SubscriptionLease {
182    fn drop(&mut self) {
183        let mut state = self
184            .budget
185            .state
186            .lock()
187            .unwrap_or_else(|error| error.into_inner());
188        state.used = state.used.saturating_sub(self.amount);
189    }
190}
191
192#[derive(Clone, Copy, Debug, Eq, PartialEq)]
193pub(crate) enum ServerAllocationSite {
194    Backing,
195    Path,
196    Region,
197    Content,
198    StaticBody,
199    WatchEntry,
200    WakeSlots,
201}
202
203#[cfg(test)]
204struct AllocationRejectionGuard;
205
206#[cfg(test)]
207impl AllocationRejectionGuard {
208    fn at(site: ServerAllocationSite, owner: u64) -> Self {
209        REJECT_ALLOCATION_SITE.with(|rejected| rejected.set(Some((site, owner))));
210        Self
211    }
212}
213
214#[cfg(test)]
215impl Drop for AllocationRejectionGuard {
216    fn drop(&mut self) {
217        REJECT_ALLOCATION_SITE.with(|rejected| rejected.set(None));
218    }
219}
220
221#[cfg(test)]
222thread_local! {
223    static REJECT_ALLOCATION_SITE: std::cell::Cell<Option<(ServerAllocationSite, u64)>> = const {
224        std::cell::Cell::new(None)
225    };
226}
227
228#[cfg(test)]
229pub(crate) fn reject_allocation_at(site: ServerAllocationSite, owner: u64) -> bool {
230    REJECT_ALLOCATION_SITE.with(|rejected| rejected.get() == Some((site, owner)))
231}
232
233#[cfg(not(test))]
234pub(crate) fn reject_allocation_at(_site: ServerAllocationSite, _owner: u64) -> bool {
235    false
236}
237
238fn reject_subscription_backing_allocation() -> bool {
239    reject_allocation_at(ServerAllocationSite::Backing, 0)
240}
241
242struct StaticSubscription {
243    region: String,
244    mode: SubscribeMode,
245    /// This connection's last successfully sent generation.
246    ///
247    /// Not "the file's previous version": under `SubscribeMode::Delta` the
248    /// suffix is computed against what *this* subscriber last received, and it
249    /// advances only after a send succeeds. A subscriber that misses a
250    /// generation therefore finds `strip_prefix` failing on the next one and
251    /// falls back to a complete replace, resynchronising itself without any
252    /// separate recovery path. Sharing the read must not disturb that, which is
253    /// why the baseline stays per-subscription while only the text is shared.
254    baseline: Arc<LiveGeneration>,
255    updates: watch::Receiver<Arc<LiveGeneration>>,
256    _metadata_lease: SubscriptionLease,
257}
258
259fn subscription_owner_key(path: &str, region: &str) -> u64 {
260    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
261    for byte in path
262        .bytes()
263        .chain(std::iter::once(0xff))
264        .chain(region.bytes())
265    {
266        hash ^= u64::from(byte);
267        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
268    }
269    hash
270}
271
272fn try_subscription_storage() -> Result<Vec<StaticSubscription>, ProtocolError> {
273    let requested = MAX_SUBSCRIPTIONS_PER_CONNECTION
274        .checked_mul(std::mem::size_of::<StaticSubscription>())
275        .ok_or(ProtocolError::ResourceExhausted {
276            requested: usize::MAX,
277        })?;
278    if reject_subscription_backing_allocation() {
279        return Err(ProtocolError::ResourceExhausted { requested });
280    }
281    let mut subscriptions = Vec::new();
282    subscriptions
283        .try_reserve_exact(MAX_SUBSCRIPTIONS_PER_CONNECTION)
284        .map_err(|_| ProtocolError::ResourceExhausted { requested })?;
285    Ok(subscriptions)
286}
287
288/// Configuration for a static server. Construction validates the site root.
289pub struct StaticServerConfig {
290    root: PathBuf,
291    listener: AtpListener,
292    max_connections: usize,
293    max_connections_per_ip: usize,
294    read_timeout: Duration,
295    resolver: Option<Arc<dyn crate::include::IncludeResolver>>,
296    input_handler: Option<Arc<dyn crate::input::InputHandler>>,
297    session_resolver: Option<Arc<dyn crate::session::SessionResolver>>,
298}
299
300impl StaticServerConfig {
301    fn new(root: PathBuf, listener: AtpListener) -> Result<Self, ProtocolError> {
302        let metadata = std::fs::metadata(&root)?;
303        if !metadata.is_dir() {
304            return Err(ProtocolError::Io(std::io::Error::new(
305                std::io::ErrorKind::InvalidInput,
306                "static site root is not a directory",
307            )));
308        }
309        // Canonicalise once, here, rather than on every request. Blocking at
310        // bind time is free; blocking on a runtime worker per GET is not.
311        let root = std::fs::canonicalize(&root)?;
312        Ok(Self {
313            root,
314            listener,
315            max_connections: DEFAULT_MAX_CONNECTIONS,
316            max_connections_per_ip: DEFAULT_MAX_CONNECTIONS_PER_IP,
317            read_timeout: READ_TIMEOUT,
318            resolver: None,
319            input_handler: None,
320            session_resolver: None,
321        })
322    }
323
324    /// Install a resolver for `[include]` placeholders.
325    ///
326    /// Absent by default, and `dustnetd` never sets one: a server without a
327    /// resolver serves authored AML unchanged, so an `[include]` travels to the
328    /// client and renders as nothing. Setting one is what lets a page carry
329    /// generated content, and it is the only way this server produces markup it
330    /// did not read from a file.
331    pub fn with_include_resolver(
332        mut self,
333        resolver: Arc<dyn crate::include::IncludeResolver>,
334    ) -> Self {
335        self.resolver = Some(resolver);
336        self
337    }
338
339    /// Install a handler for form submissions.
340    ///
341    /// Absent by default, and `dustnetd` never sets one: without a handler
342    /// `INPUT` is refused with 405, which is what this server did before
343    /// handlers existed. Installing one is what lets a site accept a
344    /// submission, and it is the only way this server changes anything on disk.
345    pub fn with_input_handler(mut self, handler: Arc<dyn crate::input::InputHandler>) -> Self {
346        self.input_handler = Some(handler);
347        self
348    }
349
350    /// Install a resolver that turns a session token into an identity.
351    ///
352    /// Without one every request is anonymous, whatever token it carries.
353    /// Installing one is what makes a site able to know who is asking — and the
354    /// token goes no further than this resolver: handlers are told the identity.
355    pub fn with_session_resolver(
356        mut self,
357        resolver: Arc<dyn crate::session::SessionResolver>,
358    ) -> Self {
359        self.session_resolver = Some(resolver);
360        self
361    }
362
363    /// Bind a plaintext development server. The listener enforces loopback-only use.
364    pub async fn bind_plaintext_loopback(
365        root: PathBuf,
366        address: &str,
367        port: u16,
368    ) -> Result<Self, ProtocolError> {
369        Self::new(root, AtpListener::bind_plain(address, port).await?)
370    }
371
372    /// Bind a TLS 1.3 static server using PEM certificate and private-key files.
373    pub async fn bind_tls(
374        root: PathBuf,
375        address: &str,
376        port: u16,
377        certificate: &str,
378        private_key: &str,
379    ) -> Result<Self, ProtocolError> {
380        Self::new(
381            root,
382            AtpListener::bind_tls(address, port, certificate, private_key).await?,
383        )
384    }
385
386    /// Return the listener address, including an OS-selected port when port zero was requested.
387    pub fn local_addr(&self) -> Result<std::net::SocketAddr, ProtocolError> {
388        self.listener.local_addr()
389    }
390
391    /// Override the idle read deadline.
392    ///
393    /// Exposed for tests only. The keepalive behaviour this guards is defined
394    /// by a 30-second deadline, and a test that waited it out honestly would
395    /// dominate the suite's runtime; shortening the deadline lets the same
396    /// behaviour be proven in milliseconds.
397    #[doc(hidden)]
398    pub fn with_read_timeout(mut self, read_timeout: Duration) -> Self {
399        self.read_timeout = read_timeout;
400        self
401    }
402
403    /// Override the connection ceilings.
404    ///
405    /// The right ceiling depends on the operator's machine — chiefly its
406    /// `RLIMIT_NOFILE`, which this process cannot raise for itself under the
407    /// workspace's `forbid(unsafe_code)`. Both values are clamped to at least
408    /// one, and the per-IP ceiling is clamped to the global one: a per-IP limit
409    /// above the global limit does not describe a reachable state.
410    pub fn with_connection_limits(mut self, global: usize, per_ip: usize) -> Self {
411        self.max_connections = global.max(1);
412        self.max_connections_per_ip = per_ip.max(1).min(self.max_connections);
413        self
414    }
415
416    #[doc(hidden)]
417    pub async fn bind_self_signed_for_tests(
418        root: PathBuf,
419        address: &str,
420        port: u16,
421    ) -> Result<Self, ProtocolError> {
422        Self::new(root, AtpListener::bind_self_signed(address, port).await?)
423    }
424}
425
426/// Production ATP server with no custom-handler or plugin surface.
427pub struct StaticServer {
428    config: Option<StaticServerConfig>,
429    shutdown_tx: watch::Sender<bool>,
430    shutdown_rx: watch::Receiver<bool>,
431    subscription_budget: SubscriptionBudget,
432}
433
434impl StaticServer {
435    pub fn new(config: StaticServerConfig) -> Self {
436        let (shutdown_tx, shutdown_rx) = watch::channel(false);
437        Self {
438            config: Some(config),
439            shutdown_tx,
440            shutdown_rx,
441            subscription_budget: SubscriptionBudget::new(MAX_SERVER_SUBSCRIPTION_BYTES),
442        }
443    }
444
445    /// Bytes of live-region content currently retained, and the server-wide
446    /// ceiling they are measured against.
447    ///
448    /// Budget exhaustion shows up to a user as a live region that quietly stops
449    /// updating. Every refusal is logged, and this is the counter that lets an
450    /// operator watch the pressure build beforehand instead of diagnosing it
451    /// afterwards.
452    pub fn subscription_memory(&self) -> (usize, usize) {
453        (
454            self.subscription_budget.used(),
455            self.subscription_budget.limit(),
456        )
457    }
458
459    pub fn shutdown_handle(&self) -> watch::Sender<bool> {
460        self.shutdown_tx.clone()
461    }
462
463    pub async fn run(&mut self) -> Result<(), ProtocolError> {
464        let config = self.config.take().ok_or_else(|| {
465            ProtocolError::InvalidMessage("static server may only be run once".into())
466        })?;
467        let root = Arc::new(config.root);
468        let resolver = config.resolver;
469        let input_handler = config.input_handler;
470        let session_resolver = config.session_resolver;
471        let semaphore = Arc::new(tokio::sync::Semaphore::new(config.max_connections));
472
473        // One reader for the whole server. Every connection subscribing to a
474        // path shares its reads; a file changes once and is read once, however
475        // many viewers are watching it.
476        let (events_tx, events_rx) = mpsc::channel(256);
477        let source: Box<dyn ChangeSource> = match NotifyChangeSource::new(events_tx) {
478            Some(source) => Box::new(source),
479            // Losing filesystem notification costs latency, not correctness:
480            // the registry's reconcile sweep serves every watched file on its
481            // own. Refusing to start would be a worse trade.
482            None => Box::new(ManualChangeSource),
483        };
484        let (registry, watcher) =
485            WatchRegistry::new(self.subscription_budget.clone(), source, events_rx);
486        let registry_shutdown = self.shutdown_rx.clone();
487        let registry_task = tokio::spawn(registry.run(registry_shutdown));
488        let max_connections_per_ip = config.max_connections_per_ip;
489        let read_timeout = config.read_timeout;
490        let per_ip = Arc::new(Mutex::new(HashMap::<IpAddr, usize>::new()));
491        let subscription_budget = self.subscription_budget.clone();
492        let mut tasks = tokio::task::JoinSet::new();
493        tracing::info!(
494            address = %config.listener.local_addr()?,
495            max_connections = config.max_connections,
496            max_connections_per_ip = config.max_connections_per_ip,
497            "static ATP server listening"
498        );
499
500        loop {
501            tokio::select! {
502                changed = self.shutdown_rx.changed() => {
503                    if changed.is_err() || *self.shutdown_rx.borrow() { break; }
504                }
505                accepted = config.listener.accept_pending() => {
506                    let pending = accepted?;
507                    let Ok(permit) = semaphore.clone().try_acquire_owned() else {
508                        tracing::warn!(peer = %pending.peer_addr(), "global connection limit reached");
509                        continue;
510                    };
511                    let peer_ip = pending.peer_addr().ip();
512                    {
513                        let mut counts = per_ip.lock().unwrap_or_else(|p| p.into_inner());
514                        let count = counts.entry(peer_ip).or_default();
515                        if *count >= max_connections_per_ip {
516                            tracing::warn!(peer_ip = %peer_ip, "per-IP connection limit reached");
517                            continue;
518                        }
519                        *count += 1;
520                    }
521                    let root = root.clone();
522                    let resolver = resolver.clone();
523                    let input_handler = input_handler.clone();
524                    let session_resolver = session_resolver.clone();
525                    let counts = per_ip.clone();
526                    let subscription_budget = subscription_budget.clone();
527                    let connection_shutdown = self.shutdown_rx.clone();
528                    let watcher = watcher.clone();
529                    let peer = pending.peer_addr();
530                    tasks.spawn(async move {
531                        let _permit = permit;
532                        // Logged for every connection, not only failing ones.
533                        // Without this the log answers "why can nobody
534                        // connect?" but not "is anyone connected?", which is
535                        // the question an operator actually has first.
536                        tracing::info!(peer = %peer, "connection accepted");
537                        match tokio::time::timeout(HANDSHAKE_TIMEOUT, pending.handshake()).await {
538                            Ok(Ok(stream)) => {
539                                match serve_connection(
540                                    stream,
541                                    ConnectionContext {
542                                        root: &root,
543                                        resolver: resolver.as_deref(),
544                                        input_handler: input_handler.as_deref(),
545                                        session_resolver: session_resolver.as_deref(),
546                                        peer: peer.ip(),
547                                    },
548                                    subscription_budget,
549                                    watcher,
550                                    read_timeout,
551                                    connection_shutdown,
552                                )
553                                .await
554                                {
555                                    Ok(()) => tracing::info!(peer = %peer, "connection closed"),
556                                    Err(error) => tracing::warn!(
557                                        peer = %peer,
558                                        error = %error,
559                                        "connection closed with an error"
560                                    ),
561                                }
562                            }
563                            Ok(Err(error)) => tracing::warn!(
564                                peer = %peer,
565                                error = %error,
566                                "handshake failed"
567                            ),
568                            // Previously silent: a client that connected and
569                            // then said nothing left no trace at all.
570                            Err(_) => tracing::warn!(
571                                peer = %peer,
572                                timeout = ?HANDSHAKE_TIMEOUT,
573                                "handshake deadline reached"
574                            ),
575                        }
576                        let mut counts = counts.lock().unwrap_or_else(|p| p.into_inner());
577                        if let Some(count) = counts.get_mut(&peer_ip) {
578                            *count = count.saturating_sub(1);
579                            if *count == 0 { counts.remove(&peer_ip); }
580                        }
581                    });
582                }
583            }
584        }
585
586        let drain = async { while tasks.join_next().await.is_some() {} };
587        if tokio::time::timeout(DRAIN_TIMEOUT, drain).await.is_err() {
588            tasks.abort_all();
589            tracing::warn!("graceful shutdown deadline reached");
590        }
591        // The registry observes the same shutdown signal and holds no client
592        // sockets, so joining it is bounded by its own loop, not by any peer.
593        registry_task.abort();
594        Ok(())
595    }
596}
597
598async fn serve_connection(
599    mut stream: AtpServerStream,
600    site: ConnectionContext<'_>,
601    subscription_budget: SubscriptionBudget,
602    watcher: LiveWatcher,
603    read_timeout: Duration,
604    mut shutdown: watch::Receiver<bool>,
605) -> Result<(), ProtocolError> {
606    // Retained subscription-table growth must be settled before the first response. Once an
607    // initial UPDATE is on the wire, installing its matching entry is allocation-free.
608    let mut subscriptions = try_subscription_storage()?;
609    let hello_frame = recv(&mut stream, HANDSHAKE_TIMEOUT).await?;
610    if hello_frame.msg_type != MessageType::Hello {
611        return Err(ProtocolError::InvalidMessage("HELLO required".into()));
612    }
613    let hello_text = std::str::from_utf8(&hello_frame.body)
614        .map_err(|_| ProtocolError::InvalidMessage("HELLO is not UTF-8".into()))?;
615    let hello = HelloMessage::parse(hello_text)?;
616    if hello.protocol_version != PROTOCOL_VERSION {
617        send_error(&mut stream, 505, "unsupported ATP version").await?;
618        return Ok(());
619    }
620    let capabilities = hello
621        .capabilities
622        .into_iter()
623        .filter(|capability| SUPPORTED_CAPABILITIES.contains(&capability.as_str()))
624        .collect();
625    let welcome = WelcomeMessage {
626        protocol_version: PROTOCOL_VERSION.into(),
627        server: Some(format!("dustnetd/{}", env!("CARGO_PKG_VERSION"))),
628        site_name: None,
629        capabilities,
630    };
631    tracing::debug!(
632        version = %hello.protocol_version,
633        capabilities = ?welcome.capabilities,
634        "negotiated"
635    );
636    send(
637        &mut stream,
638        RawFrame {
639            msg_type: MessageType::Welcome,
640            flags: 0,
641            body: welcome.serialize()?.into_bytes(),
642        },
643    )
644    .await?;
645
646    // No per-connection timer. 2048 connections each holding a 250ms interval
647    // is roughly eight thousand timer wakeups a second before any work happens;
648    // the registry wakes a connection only when a file it watches has actually
649    // changed. Capacity one, because a pending wake already says everything a
650    // second one would.
651    let (wake_tx, mut wake_rx) = mpsc::channel::<()>(1);
652    let idle = tokio::time::sleep(read_timeout);
653    tokio::pin!(idle);
654    loop {
655        tokio::select! {
656            received = stream.recv_frame() => {
657                let frame = received?;
658                idle.as_mut().reset(tokio::time::Instant::now() + read_timeout);
659                // Per-request detail sits at debug: one line per request is the
660                // right amount of information when diagnosing a site and far
661                // too much at two thousand connections, so the level is what
662                // separates them rather than a sampling rule. Messages that
663                // carry no detail worth naming are logged here; the rest log
664                // themselves where their fields are already parsed.
665                if matches!(
666                    frame.msg_type,
667                    MessageType::Ping | MessageType::Bye | MessageType::Input
668                ) {
669                    tracing::debug!(message = ?frame.msg_type, "request");
670                }
671                match frame.msg_type {
672                    MessageType::Get => serve_get(&mut stream, site, frame).await?,
673                    MessageType::Input => serve_input(&mut stream, site, frame).await?,
674                    MessageType::Subscribe => {
675                        if subscriptions.len() >= MAX_SUBSCRIPTIONS_PER_CONNECTION {
676                            return Err(ProtocolError::InvalidMessage(
677                                "subscription limit reached".into(),
678                            ));
679                        } else {
680                            subscriptions.push(serve_subscription(
681                                &mut stream,
682                                site.root,
683                                frame,
684                                &watcher,
685                                &wake_tx,
686                                &subscription_budget,
687                            ).await?);
688                        }
689                    }
690                    MessageType::Unsubscribe => {
691                        tracing::debug!(
692                            released = subscriptions.len(),
693                            "UNSUBSCRIBE"
694                        );
695                        subscriptions.clear();
696                    }
697                    // The idle deadline above was already reset by this frame
698                    // arriving; that reset is the whole point of PING. PONG
699                    // exists so the client can distinguish a live server from
700                    // a black-holed socket that is silently absorbing writes.
701                    MessageType::Ping => {
702                        send(
703                            &mut stream,
704                            RawFrame {
705                                msg_type: MessageType::Pong,
706                                flags: 0,
707                                body: Vec::new(),
708                            },
709                        )
710                        .await?
711                    }
712                    MessageType::Bye => {
713                        send(
714                            &mut stream,
715                            RawFrame {
716                                msg_type: MessageType::ServerBye,
717                                flags: 0,
718                                body: Vec::new(),
719                            },
720                        )
721                        .await?;
722                        return Ok(());
723                    }
724                    _ => {
725                        return Err(ProtocolError::InvalidMessage(
726                            "unexpected client message".into(),
727                        ));
728                    }
729                }
730            }
731            Some(()) = wake_rx.recv(), if !subscriptions.is_empty() => {
732                flush_subscriptions(&mut stream, &mut subscriptions).await?;
733            }
734            _ = &mut idle => return Err(ProtocolError::Timeout),
735            // Without this arm no connection observes shutdown, so a single
736            // idle client guarantees the drain deadline expires and every task
737            // is aborted. Leaving voluntarily turns DRAIN_TIMEOUT back into the
738            // backstop it is meant to be — which matters far more at 2048
739            // connections than at 64.
740            changed = shutdown.changed() => {
741                if changed.is_err() || *shutdown.borrow() {
742                    let _ = send(
743                        &mut stream,
744                        RawFrame {
745                            msg_type: MessageType::ServerBye,
746                            flags: 0,
747                            body: Vec::new(),
748                        },
749                    )
750                    .await;
751                    return Ok(());
752                }
753            }
754        }
755    }
756}
757
758/// What a connection needs to answer a request: where the site lives, the
759/// optional hooks that let it generate content and accept submissions, and who
760/// the peer is.
761///
762/// Bundled because they all travel together for the life of a connection. The
763/// hooks are `None`-by-default policy; `peer` is the one piece of per-connection
764/// state, and it is here rather than threaded separately because a submission
765/// cannot be rate-limited per source without it.
766#[derive(Clone, Copy)]
767struct ConnectionContext<'a> {
768    root: &'a Path,
769    resolver: Option<&'a dyn crate::include::IncludeResolver>,
770    input_handler: Option<&'a dyn crate::input::InputHandler>,
771    session_resolver: Option<&'a dyn crate::session::SessionResolver>,
772    /// The peer's address. Given to a submission handler for abuse control, and
773    /// deliberately **not** to the include resolver: rendering a page has no
774    /// business knowing where the reader is.
775    peer: std::net::IpAddr,
776}
777
778async fn serve_get(
779    stream: &mut AtpServerStream,
780    site: ConnectionContext<'_>,
781    frame: RawFrame,
782) -> Result<(), ProtocolError> {
783    let text = std::str::from_utf8(&frame.body)
784        .map_err(|_| ProtocolError::InvalidMessage("GET is not UTF-8".into()))?;
785    let get = GetMessage::parse(text)?;
786    tracing::debug!(path = %get.path, "GET");
787    // The token is resolved here and only the identity travels on. Nothing
788    // below this line sees the token, which is the point of `crate::session`.
789    let identity = resolve_identity(site.session_resolver, get.session.as_deref());
790    serve_path(
791        stream,
792        site.root,
793        site.resolver,
794        &get.path,
795        get.query.as_deref(),
796        identity.as_deref(),
797        Vec::new(),
798        false,
799    )
800    .await
801}
802
803/// Serve one path, resolving includes if a resolver is installed.
804///
805/// Shared by GET and by an accepted submission, which is the point: a page
806/// looks the same whether it was asked for or arrived at by submitting a form,
807/// because it is produced by the same code.
808/// Turn a presented token into an identity, or `None`.
809///
810/// `None` covers no token, no resolver, and a token the resolver did not
811/// recognise. Collapsing those is deliberate: a caller that could tell them
812/// apart would be an oracle for whether a token had ever existed.
813fn resolve_identity(
814    resolver: Option<&dyn crate::session::SessionResolver>,
815    token: Option<&str>,
816) -> Option<String> {
817    resolver?.identity(token?)
818}
819
820#[allow(clippy::too_many_arguments)]
821async fn serve_path(
822    stream: &mut AtpServerStream,
823    root: &Path,
824    resolver: Option<&dyn crate::include::IncludeResolver>,
825    request_path: &str,
826    query: Option<&str>,
827    identity: Option<&str>,
828    session_directives: Vec<dustnet_core::session::SessionDirective>,
829    // Whether the PAGE should name the path it is. Set for a submission, whose
830    // answer is often a different page from the one submitted to, and unset for
831    // a GET, where the client already knows.
832    announce_location: bool,
833) -> Result<(), ProtocolError> {
834    let path = resolve_path(root, request_path).await?;
835    let limit = if path
836        .extension()
837        .is_some_and(|extension| extension == "wasm")
838    {
839        MAX_WASM_MODULE_SIZE
840    } else {
841        MAX_PAGE_MESSAGE_SIZE
842    };
843    let file = match tokio::fs::File::open(&path).await {
844        Ok(file) => file,
845        Err(_) => {
846            tracing::debug!(path = %request_path, "404 not found");
847            send_error(stream, 404, "not found").await?;
848            return Ok(());
849        }
850    };
851    let metadata = match file.metadata().await {
852        Ok(metadata) if metadata.is_file() && metadata.len() <= limit as u64 => metadata,
853        _ => {
854            send_error(stream, 404, "not found").await?;
855            return Ok(());
856        }
857    };
858    let owner_key = subscription_owner_key(request_path, "");
859    let body = read_static_body(file, metadata.len() as usize, owner_key).await?;
860    if path
861        .extension()
862        .is_some_and(|extension| extension == "wasm")
863    {
864        send(
865            stream,
866            RawFrame {
867                msg_type: MessageType::Resource,
868                flags: 0,
869                body,
870            },
871        )
872        .await
873    } else {
874        let content = String::from_utf8(body)
875            .map_err(|_| ProtocolError::InvalidMessage("AML file is not UTF-8".into()))?;
876
877        // Substitute [include] placeholders before anything reads the content.
878        // `has_live_regions` in particular must see the resolved page: a
879        // resolver may emit a [live] region, and a flag computed from the
880        // authored source would leave the client never subscribing to it.
881        let content = match resolver {
882            Some(resolver) => {
883                let request = crate::include::IncludeRequest {
884                    path: request_path,
885                    query,
886                    identity,
887                };
888                let resolved = crate::include::resolve_page(&content, resolver, &request)?;
889                // A resolver can produce more than a page may carry. Refuse
890                // rather than truncate: half a page of stories is a worse
891                // answer than an error naming the cause.
892                if resolved.len() > MAX_PAGE_MESSAGE_SIZE {
893                    tracing::warn!(
894                        path = %request_path,
895                        bytes = resolved.len(),
896                        limit = MAX_PAGE_MESSAGE_SIZE,
897                        "resolved page exceeds the page limit"
898                    );
899                    send_error(stream, 500, "resolved page too large").await?;
900                    return Ok(());
901                }
902                resolved
903            }
904            None => content,
905        };
906
907        let has_live_regions = content.contains("[live");
908        // Asked of the stream, not assumed: attaching a `Path` a client never
909        // negotiated makes the frame unsendable, so an older client would get
910        // no page at all instead of the page it has always got.
911        let announced = (announce_location && stream.supports_page_path()).then(|| match query {
912            Some(query) => format!("{request_path}?{query}"),
913            None => request_path.to_string(),
914        });
915        let page = PageMessage {
916            content,
917            flags: PageFlags {
918                cacheable: true,
919                has_live_regions,
920                ..PageFlags::default()
921            },
922            path: announced,
923            session_directives,
924        };
925        let (body, flags) = page.encode_body()?;
926        send(
927            stream,
928            RawFrame {
929                msg_type: MessageType::Page,
930                flags,
931                body,
932            },
933        )
934        .await
935    }
936}
937
938/// Handle a form submission.
939///
940/// Without a handler this is the 405 it always was, so a server that installs
941/// none behaves exactly as it did before submissions were possible.
942///
943/// An accepted submission answers with the target *page*, not a redirect: a
944/// REDIRECT may carry no metadata, so it cannot also issue the session a login
945/// grants, and it would cost a second round trip. The page is rendered through
946/// the same `serve_path` a GET uses, so there is one path that generates a page
947/// whether or not a submission preceded it.
948///
949/// Because the answer may be a different page from the one submitted to, it
950/// names itself: the PAGE carries a `Path`, and the client adopts it as its
951/// location. That is what makes a login land on the front page rather than
952/// leaving the person on `/login` with the front page drawn on it, one reload
953/// away from the form they just completed.
954async fn serve_input(
955    stream: &mut AtpServerStream,
956    site: ConnectionContext<'_>,
957    frame: RawFrame,
958) -> Result<(), ProtocolError> {
959    let Some(handler) = site.input_handler else {
960        send_error(stream, 405, "server accepts no form submissions").await?;
961        return Ok(());
962    };
963
964    let text = std::str::from_utf8(&frame.body)
965        .map_err(|_| ProtocolError::InvalidMessage("INPUT is not UTF-8".into()))?;
966    // `InputMessage::parse` enforces MAX_INPUT_MESSAGE_SIZE, so the body is
967    // bounded before anything here allocates from it.
968    let input = InputMessage::parse(text)?;
969
970    let (path, query) = crate::input::split_query(&input.path);
971    let fields = crate::input::FormFields::parse(&input.form_data);
972    tracing::debug!(path, fields = fields.len(), "INPUT");
973
974    let identity = resolve_identity(site.session_resolver, input.session.as_deref());
975    let request = crate::input::InputRequest {
976        path,
977        query,
978        fields: &fields,
979        identity: identity.as_deref(),
980        peer: site.peer,
981    };
982
983    match handler.handle(&request) {
984        crate::input::InputOutcome::Render {
985            path,
986            query,
987            session,
988        } => {
989            tracing::info!(%path, "submission accepted");
990            // Revoke here, not in the handler: a handler is told the identity
991            // and not the token, so it cannot name its own session to end it.
992            // Doing it here ends exactly the session that was presented.
993            if session.clears()
994                && let (Some(resolver), Some(token)) =
995                    (site.session_resolver, input.session.as_deref())
996            {
997                resolver.revoke(token);
998            }
999            // The response is rendered for whoever holds the session *after*
1000            // the handler ran, not before it. Where a handler granted one, the
1001            // token it issued is resolved through the same `SessionResolver` a
1002            // GET would use — so a login answers with the logged-in page
1003            // instead of showing the logged-out nav for one page, and it does
1004            // so without taking the handler's word about who it authenticated:
1005            // the resolver is still the only thing that turns a token into a
1006            // name, and it refuses one that is unknown, expired or revoked.
1007            let identity = match (site.session_resolver, session.token()) {
1008                (Some(resolver), Some(granted)) => resolver.identity(granted),
1009                _ => identity,
1010            };
1011            serve_path(
1012                stream,
1013                site.root,
1014                site.resolver,
1015                &path,
1016                query.as_deref(),
1017                identity.as_deref(),
1018                session.into_directives(),
1019                true,
1020            )
1021            .await
1022        }
1023        crate::input::InputOutcome::Rejected(reason) => {
1024            // Logged at the same level as an acceptance. A submission refused
1025            // is as much a thing an operator wants to see as one taken.
1026            // Logged in full, sent trimmed: the operator wants the diagnostic
1027            // and the reader wants a sentence they can actually see.
1028            tracing::info!(path, reason = %reason, "submission refused");
1029            send_error(stream, 400, &crate::input::short_reason(&reason)).await?;
1030            Ok(())
1031        }
1032    }
1033}
1034
1035async fn read_static_body(
1036    mut file: tokio::fs::File,
1037    expected_len: usize,
1038    owner_key: u64,
1039) -> Result<Vec<u8>, ProtocolError> {
1040    let requested = expected_len
1041        .checked_add(1)
1042        .ok_or(ProtocolError::ResourceExhausted {
1043            requested: usize::MAX,
1044        })?;
1045    if reject_allocation_at(ServerAllocationSite::StaticBody, owner_key) {
1046        return Err(ProtocolError::ResourceExhausted { requested });
1047    }
1048    let mut body = allocate_frame_body(requested)?;
1049    let mut filled = 0;
1050    loop {
1051        let Some(unfilled) = body.get_mut(filled..) else {
1052            break;
1053        };
1054        if unfilled.is_empty() {
1055            break;
1056        }
1057        let read = file.read(unfilled).await?;
1058        if read == 0 {
1059            break;
1060        }
1061        filled += read;
1062    }
1063    if filled > expected_len {
1064        return Err(ProtocolError::InvalidMessage(
1065            "static file changed while it was being read".into(),
1066        ));
1067    }
1068    body.truncate(filled);
1069    Ok(body)
1070}
1071
1072async fn serve_subscription(
1073    stream: &mut AtpServerStream,
1074    root: &Path,
1075    frame: RawFrame,
1076    watcher: &LiveWatcher,
1077    wake: &mpsc::Sender<()>,
1078    budget: &SubscriptionBudget,
1079) -> Result<StaticSubscription, ProtocolError> {
1080    let text = std::str::from_utf8(&frame.body)
1081        .map_err(|_| ProtocolError::InvalidMessage("SUBSCRIBE is not UTF-8".into()))?;
1082    let subscription = SubscribeMessage::parse(text)?;
1083    tracing::debug!(
1084        path = %subscription.path,
1085        region = %subscription.region,
1086        mode = ?subscription.mode,
1087        "SUBSCRIBE"
1088    );
1089    let owner_key = subscription_owner_key(&subscription.path, &subscription.region);
1090    let resolved_path = resolve_path(root, &subscription.path).await?;
1091    let metadata_bytes = resolved_path
1092        .as_os_str()
1093        .len()
1094        .checked_add(subscription.region.len())
1095        .ok_or(ProtocolError::ResourceExhausted {
1096            requested: usize::MAX,
1097        })?;
1098    let mut metadata_lease = budget.reserve(metadata_bytes)?;
1099    let path = try_owned_subscription_path(&resolved_path, owner_key)?;
1100    let region = try_owned_subscription_string(
1101        &subscription.region,
1102        ServerAllocationSite::Region,
1103        owner_key,
1104    )?;
1105    let retained_metadata_bytes =
1106        path.capacity()
1107            .checked_add(region.capacity())
1108            .ok_or(ProtocolError::ResourceExhausted {
1109                requested: usize::MAX,
1110            })?;
1111    metadata_lease.try_resize(retained_metadata_bytes)?;
1112    let metadata = tokio::fs::metadata(&path).await?;
1113    if !metadata.is_file() {
1114        return Err(ProtocolError::InvalidMessage(
1115            "invalid live update file".into(),
1116        ));
1117    }
1118
1119    // Attaching reads the file only if it has moved since anyone last read it,
1120    // so a reconnecting subscriber is never handed a staler generation than the
1121    // moment it asked, and a second subscriber to a live path costs a stat.
1122    let attached = watcher
1123        .attach(
1124            try_owned_subscription_path(&path, owner_key)?,
1125            wake.clone(),
1126            owner_key,
1127        )
1128        .await?;
1129
1130    // The initial value is always a complete replace: the subscriber has no
1131    // baseline to append to yet.
1132    UpdateMessage::validate_update_parts(&region, attached.current.text.len())?;
1133    let candidate = StaticSubscription {
1134        region,
1135        mode: subscription.mode,
1136        baseline: attached.current,
1137        updates: attached.updates,
1138        _metadata_lease: metadata_lease,
1139    };
1140    send_update(stream, &candidate.region, &candidate.baseline.text, false).await?;
1141    Ok(candidate)
1142}
1143
1144/// Send every subscription whatever it has not yet seen.
1145///
1146/// Called when the registry wakes this connection. The wake carries no payload,
1147/// so this reconciles all of the connection's subscriptions by pointer identity
1148/// — which is why a dropped wake is harmless: a full wake channel already means
1149/// "you have unhandled work".
1150///
1151/// Every failure here is either terminal for the connection or permanent for
1152/// this generation. That is deliberate. The old 250ms tick let a failure be a
1153/// `continue` that would be retried a quarter-second later; without a tick, a
1154/// retryable failure skipped here would never be retried at all. Retryable
1155/// failures now live in the watcher's read path, where the reconcile timer is
1156/// the retry.
1157async fn flush_subscriptions(
1158    stream: &mut AtpServerStream,
1159    subscriptions: &mut [StaticSubscription],
1160) -> Result<(), ProtocolError> {
1161    for subscription in subscriptions {
1162        // Clone out of the guard in its own scope: holding a `watch::Ref`
1163        // across the await below would block the registry's `send_replace` and
1164        // deadlock the whole fan-out.
1165        let next = {
1166            let guard = subscription.updates.borrow();
1167            Arc::clone(&guard)
1168        };
1169        if Arc::ptr_eq(&next, &subscription.baseline) {
1170            continue;
1171        }
1172        let (wire_content, delta) = if subscription.mode == SubscribeMode::Delta {
1173            match next.text.strip_prefix(&subscription.baseline.text) {
1174                Some(suffix) => (suffix, true),
1175                None => (next.text.as_str(), false),
1176            }
1177        } else {
1178            (next.text.as_str(), false)
1179        };
1180        // Permanent for this generation, not transient: the region name is
1181        // fixed and the content will not shrink on a retry.
1182        if UpdateMessage::validate_update_parts(&subscription.region, wire_content.len()).is_err() {
1183            tracing::warn!(
1184                region = %subscription.region,
1185                bytes = wire_content.len(),
1186                "live update not sent: body exceeds the maximum update size"
1187            );
1188            subscription.baseline = next;
1189            continue;
1190        }
1191        send_update(stream, &subscription.region, wire_content, delta).await?;
1192        // Advances only after a successful send, so a subscriber that missed a
1193        // generation resynchronises on the next one.
1194        subscription.baseline = next;
1195    }
1196    Ok(())
1197}
1198
1199fn try_owned_subscription_path(path: &Path, owner_key: u64) -> Result<PathBuf, ProtocolError> {
1200    let requested = path.as_os_str().len();
1201    if reject_allocation_at(ServerAllocationSite::Path, owner_key) {
1202        return Err(ProtocolError::ResourceExhausted { requested });
1203    }
1204    let mut owned = PathBuf::new();
1205    owned
1206        .try_reserve_exact(requested)
1207        .map_err(|_| ProtocolError::ResourceExhausted { requested })?;
1208    owned.push(path);
1209    Ok(owned)
1210}
1211
1212fn try_owned_subscription_string(
1213    value: &str,
1214    site: ServerAllocationSite,
1215    owner_key: u64,
1216) -> Result<String, ProtocolError> {
1217    let requested = value.len();
1218    if reject_allocation_at(site, owner_key) {
1219        return Err(ProtocolError::ResourceExhausted { requested });
1220    }
1221    let mut owned = String::new();
1222    owned
1223        .try_reserve_exact(requested)
1224        .map_err(|_| ProtocolError::ResourceExhausted { requested })?;
1225    owned.push_str(value);
1226    Ok(owned)
1227}
1228
1229pub(crate) async fn read_subscription_content(
1230    path: &Path,
1231    expected_len: usize,
1232    owner_key: u64,
1233    lease: &mut SubscriptionLease,
1234) -> Result<String, ProtocolError> {
1235    let requested = expected_len
1236        .checked_add(1)
1237        .ok_or(ProtocolError::ResourceExhausted {
1238            requested: usize::MAX,
1239        })?;
1240    if reject_allocation_at(ServerAllocationSite::Content, owner_key) {
1241        return Err(ProtocolError::ResourceExhausted { requested });
1242    }
1243    let mut bytes = Vec::new();
1244    bytes
1245        .try_reserve_exact(requested)
1246        .map_err(|_| ProtocolError::ResourceExhausted { requested })?;
1247    bytes.resize(requested, 0);
1248    let mut file = tokio::fs::File::open(path).await?;
1249    let mut filled = 0;
1250    loop {
1251        let Some(unfilled) = bytes.get_mut(filled..) else {
1252            break;
1253        };
1254        if unfilled.is_empty() {
1255            break;
1256        }
1257        let read = file.read(unfilled).await?;
1258        if read == 0 {
1259            break;
1260        }
1261        filled += read;
1262    }
1263    if filled > expected_len {
1264        return Err(ProtocolError::InvalidMessage(
1265            "live update changed while it was being read".into(),
1266        ));
1267    }
1268    let Some(read_bytes) = bytes.get(..filled) else {
1269        return Err(ProtocolError::InvalidMessage(
1270            "live update read past its own buffer".into(),
1271        ));
1272    };
1273    let text = std::str::from_utf8(read_bytes)
1274        .map_err(|_| ProtocolError::InvalidMessage("live update is not UTF-8".into()))?;
1275    let mut content = String::new();
1276    content
1277        .try_reserve_exact(filled)
1278        .map_err(|_| ProtocolError::ResourceExhausted { requested: filled })?;
1279    content.push_str(text);
1280    let read_peak = bytes.capacity().checked_add(content.capacity()).ok_or(
1281        ProtocolError::ResourceExhausted {
1282            requested: usize::MAX,
1283        },
1284    )?;
1285    lease.ensure_at_least(read_peak)?;
1286    Ok(content)
1287}
1288
1289/// Map a request path onto a candidate file path without touching the disk.
1290///
1291/// Purely lexical: no syscall, so it is safe to run on a runtime worker. It
1292/// establishes nothing about whether the result is inside the site root —
1293/// symlinks are resolved by `resolve_path`, which is the only function that may
1294/// conclude a path is safe to serve.
1295fn resolve_path_lexical(root: &Path, request: &str) -> Result<PathBuf, ProtocolError> {
1296    let relative = request.trim_start_matches('/');
1297    let mut result = root.to_path_buf();
1298    for component in Path::new(relative).components() {
1299        match component {
1300            Component::Normal(part) => result.push(part),
1301            Component::CurDir => {}
1302            _ => return Err(ProtocolError::InvalidMessage("invalid static path".into())),
1303        }
1304    }
1305    if request.ends_with('/') || relative.is_empty() {
1306        result.push("index.aml");
1307    }
1308    if result.extension().is_none() {
1309        result.set_extension("aml");
1310    }
1311    Ok(result)
1312}
1313
1314/// Resolve a request path to a file path that is proven to live inside `root`.
1315///
1316/// `root` must already be canonical; `StaticServerConfig::new` canonicalises it
1317/// once at bind time, where blocking costs nothing. This used to canonicalise
1318/// the root again on every request and probe `Path::exists` first — three
1319/// synchronous filesystem calls on a runtime worker thread for every GET and
1320/// every SUBSCRIBE, which is a hard ceiling on concurrent connections. One
1321/// async call replaces all three: `canonicalize` already fails for a path that
1322/// does not exist, so the probe was only ever telling us what it would tell us.
1323///
1324/// A path that does not resolve is returned unchanged rather than rejected. It
1325/// is not an escape attempt, it is a miss, and the caller's `open` turns it into
1326/// the 404 it always was.
1327async fn resolve_path(root: &Path, request: &str) -> Result<PathBuf, ProtocolError> {
1328    let candidate = resolve_path_lexical(root, request)?;
1329    let Ok(canonical) = tokio::fs::canonicalize(&candidate).await else {
1330        return Ok(candidate);
1331    };
1332    if !canonical.starts_with(root) {
1333        return Err(ProtocolError::InvalidMessage(
1334            "static path escapes the configured site root".into(),
1335        ));
1336    }
1337    Ok(canonical)
1338}
1339
1340async fn recv(stream: &mut AtpServerStream, timeout: Duration) -> Result<RawFrame, ProtocolError> {
1341    tokio::time::timeout(timeout, stream.recv_frame())
1342        .await
1343        .map_err(|_| ProtocolError::Timeout)?
1344}
1345
1346async fn send(stream: &mut AtpServerStream, frame: RawFrame) -> Result<(), ProtocolError> {
1347    send_with_timeout(stream, &frame, WRITE_TIMEOUT).await
1348}
1349
1350/// Send an UPDATE from its parts under the same write deadline as any other
1351/// frame, so `stalled_frame_write_is_bounded` still covers the fan-out path.
1352async fn send_update_with_timeout(
1353    stream: &mut AtpServerStream,
1354    region: &str,
1355    content: &str,
1356    delta: bool,
1357    timeout: Duration,
1358) -> Result<(), ProtocolError> {
1359    tokio::time::timeout(timeout, stream.send_update_parts(region, content, delta))
1360        .await
1361        .map_err(|_| ProtocolError::Timeout)?
1362}
1363
1364async fn send_update(
1365    stream: &mut AtpServerStream,
1366    region: &str,
1367    content: &str,
1368    delta: bool,
1369) -> Result<(), ProtocolError> {
1370    send_update_with_timeout(stream, region, content, delta, WRITE_TIMEOUT).await
1371}
1372
1373async fn send_with_timeout(
1374    stream: &mut AtpServerStream,
1375    frame: &RawFrame,
1376    timeout: Duration,
1377) -> Result<(), ProtocolError> {
1378    tokio::time::timeout(timeout, stream.send_frame(frame))
1379        .await
1380        .map_err(|_| ProtocolError::Timeout)?
1381}
1382
1383async fn send_error(
1384    stream: &mut AtpServerStream,
1385    code: u16,
1386    message: &str,
1387) -> Result<(), ProtocolError> {
1388    let error = ErrorMessage {
1389        code,
1390        message: Some(message.into()),
1391    };
1392    send(
1393        stream,
1394        RawFrame {
1395            msg_type: MessageType::Error,
1396            flags: 0,
1397            body: error.serialize()?.into_bytes(),
1398        },
1399    )
1400    .await
1401}
1402
1403#[cfg(test)]
1404mod tests {
1405    use super::*;
1406    use dustnet_core::protocol::frame::{allocate_frame_body, decode_header, encode_frame};
1407    use dustnet_core::protocol::message::UpdateFlags;
1408    use tokio::io::{AsyncReadExt, AsyncWriteExt};
1409    use tokio::net::TcpStream;
1410
1411    /// A subscription with no real watcher behind it, for tests that only care
1412    /// about the table that holds them.
1413    fn placeholder_subscription(region: String, budget: &SubscriptionBudget) -> StaticSubscription {
1414        let (updates, receiver) =
1415            watch::channel(live_watch::LiveGeneration::empty_for_tests(budget).unwrap());
1416        // The sender must outlive the receiver for `borrow` to stay valid.
1417        std::mem::forget(updates);
1418        let baseline = {
1419            let guard = receiver.borrow();
1420            Arc::clone(&guard)
1421        };
1422        StaticSubscription {
1423            region,
1424            mode: SubscribeMode::Replace,
1425            baseline,
1426            updates: receiver,
1427            _metadata_lease: budget.reserve(0).unwrap(),
1428        }
1429    }
1430
1431    #[test]
1432    fn static_subscription_backing_rejection_precedes_connection_state() {
1433        let rejection = AllocationRejectionGuard::at(ServerAllocationSite::Backing, 0);
1434        assert!(matches!(
1435            try_subscription_storage(),
1436            Err(ProtocolError::ResourceExhausted { .. })
1437        ));
1438        drop(rejection);
1439        let mut subscriptions = try_subscription_storage().unwrap();
1440        assert!(subscriptions.is_empty());
1441        let capacity = subscriptions.capacity();
1442        let allocation = subscriptions.as_ptr();
1443        let budget = SubscriptionBudget::new(1024);
1444        for index in 0..MAX_SUBSCRIPTIONS_PER_CONNECTION {
1445            subscriptions.push(placeholder_subscription(format!("region-{index}"), &budget));
1446        }
1447        assert_eq!(subscriptions.capacity(), capacity);
1448        assert_eq!(subscriptions.as_ptr(), allocation);
1449    }
1450
1451    /// Canonicalise a tempdir for use as a site root.
1452    ///
1453    /// Production canonicalises the root once in `StaticServerConfig::new`, and
1454    /// `resolve_path` relies on that. Tests that drive `serve_subscription` and
1455    /// `poll_subscriptions` directly bypass the config, so they must establish
1456    /// the same invariant — on macOS a tempdir is `/var/...` whose canonical
1457    /// form is `/private/var/...`, and comparing the two rejects every path.
1458    fn site_root(directory: &tempfile::TempDir) -> PathBuf {
1459        std::fs::canonicalize(directory.path()).unwrap()
1460    }
1461
1462    struct RawClient(TcpStream);
1463
1464    impl RawClient {
1465        async fn connect(address: std::net::SocketAddr) -> Self {
1466            Self(TcpStream::connect(address).await.unwrap())
1467        }
1468
1469        async fn send(&mut self, frame: RawFrame) {
1470            self.0
1471                .write_all(&encode_frame(&frame).unwrap())
1472                .await
1473                .unwrap();
1474        }
1475
1476        async fn send_fragmented(&mut self, frame: RawFrame) {
1477            for byte in encode_frame(&frame).unwrap() {
1478                self.0.write_all(&[byte]).await.unwrap();
1479                tokio::task::yield_now().await;
1480            }
1481        }
1482
1483        async fn receive(&mut self) -> RawFrame {
1484            let mut header = [0_u8; dustnet_core::protocol::HEADER_SIZE];
1485            self.0.read_exact(&mut header).await.unwrap();
1486            let (length, msg_type, flags) = decode_header(&header).unwrap();
1487            let mut body = allocate_frame_body(length as usize).unwrap();
1488            self.0.read_exact(&mut body).await.unwrap();
1489            RawFrame {
1490                msg_type,
1491                flags,
1492                body,
1493            }
1494        }
1495
1496        async fn handshake(&mut self) {
1497            self.send(RawFrame {
1498                msg_type: MessageType::Hello,
1499                flags: 0,
1500                body: b"HELLO/0.2\nCapabilities: live-updates\n".to_vec(),
1501            })
1502            .await;
1503            assert_eq!(self.receive().await.msg_type, MessageType::Welcome);
1504        }
1505    }
1506
1507    fn subscription_frame(mode: SubscribeMode) -> RawFrame {
1508        let mode = if mode == SubscribeMode::Delta {
1509            "Mode: delta\n"
1510        } else {
1511            ""
1512        };
1513        RawFrame {
1514            msg_type: MessageType::Subscribe,
1515            flags: 0,
1516            body: format!("SUBSCRIBE /ticker.aml\nRegion: ticker\n{mode}").into_bytes(),
1517        }
1518    }
1519
1520    async fn negotiated_server_pair() -> (AtpServerStream, RawClient) {
1521        let listener = AtpListener::bind_plain("127.0.0.1", 0).await.unwrap();
1522        let address = listener.local_addr().unwrap();
1523        let mut client = RawClient::connect(address).await;
1524        let pending = listener.accept_pending().await.unwrap();
1525        let mut server = pending.handshake().await.unwrap();
1526        client
1527            .send(RawFrame {
1528                msg_type: MessageType::Hello,
1529                flags: 0,
1530                body: b"HELLO/0.2\nCapabilities: live-updates\n".to_vec(),
1531            })
1532            .await;
1533        assert_eq!(
1534            server.recv_frame().await.unwrap().msg_type,
1535            MessageType::Hello
1536        );
1537        send(
1538            &mut server,
1539            RawFrame {
1540                msg_type: MessageType::Welcome,
1541                flags: 0,
1542                body: b"WELCOME/0.2\nCapabilities: live-updates\n".to_vec(),
1543            },
1544        )
1545        .await
1546        .unwrap();
1547        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
1548        (server, client)
1549    }
1550
1551    /// A registry running in the background with intervals short enough that a
1552    /// file change is observed promptly.
1553    ///
1554    /// The change source observes nothing on purpose: reconciliation alone must
1555    /// serve every watched file, so driving these tests through it also proves
1556    /// the fallback path the real watcher degrades to.
1557    fn test_watcher(budget: &SubscriptionBudget) -> (LiveWatcher, watch::Sender<bool>) {
1558        let (events_tx, events_rx) = mpsc::channel(64);
1559        // Hold the sender open for the registry's lifetime.
1560        std::mem::forget(events_tx);
1561        let (registry, watcher) =
1562            WatchRegistry::new(budget.clone(), Box::new(ManualChangeSource), events_rx);
1563        let (shutdown_tx, shutdown_rx) = watch::channel(false);
1564        tokio::spawn(
1565            registry
1566                .with_intervals(Duration::from_millis(1), Duration::from_millis(5))
1567                .run(shutdown_rx),
1568        );
1569        (watcher, shutdown_tx)
1570    }
1571
1572    async fn subscribe_for_test(
1573        server: &mut AtpServerStream,
1574        root: &Path,
1575        watcher: &LiveWatcher,
1576        budget: &SubscriptionBudget,
1577        mode: SubscribeMode,
1578    ) -> Result<(StaticSubscription, mpsc::Receiver<()>), ProtocolError> {
1579        let (wake_tx, wake_rx) = mpsc::channel(1);
1580        let subscription = serve_subscription(
1581            server,
1582            root,
1583            subscription_frame(mode),
1584            watcher,
1585            &wake_tx,
1586            budget,
1587        )
1588        .await?;
1589        Ok((subscription, wake_rx))
1590    }
1591
1592    /// Wait for a wake, then flush. Mirrors the connection loop's own arm.
1593    async fn wake_and_flush(
1594        server: &mut AtpServerStream,
1595        subscriptions: &mut [StaticSubscription],
1596        wake: &mut mpsc::Receiver<()>,
1597    ) -> Result<(), ProtocolError> {
1598        let _ = tokio::time::timeout(Duration::from_secs(2), wake.recv()).await;
1599        flush_subscriptions(server, subscriptions).await
1600    }
1601
1602    #[tokio::test]
1603    async fn static_subscription_complete_body_limit_and_release_are_exact() {
1604        let directory = tempfile::tempdir().unwrap();
1605        let path = directory.path().join("ticker.aml");
1606        let prefix = "UPDATE \n\n".len() + "ticker".len();
1607        let exact = "x".repeat(dustnet_core::protocol::MAX_LIVE_UPDATE_SIZE - prefix);
1608        std::fs::write(&path, &exact).unwrap();
1609        let budget = SubscriptionBudget::new(8 * dustnet_core::protocol::MAX_LIVE_UPDATE_SIZE);
1610        let (watcher, _shutdown) = test_watcher(&budget);
1611        let (mut server, mut client) = negotiated_server_pair().await;
1612
1613        let (subscription, _wake) = subscribe_for_test(
1614            &mut server,
1615            &site_root(&directory),
1616            &watcher,
1617            &budget,
1618            SubscribeMode::Replace,
1619        )
1620        .await
1621        .unwrap();
1622        let update = client.receive().await;
1623        assert_eq!(
1624            update.body.len(),
1625            dustnet_core::protocol::MAX_LIVE_UPDATE_SIZE,
1626            "a body at exactly the limit must still be sent"
1627        );
1628        assert_eq!(subscription.baseline.text, exact);
1629        // The subscription itself now retains only its region; the content is
1630        // charged once by the generation it shares.
1631        assert!(
1632            budget.used() >= subscription.region.capacity(),
1633            "the subscription retains its region; the content is charged once \
1634             by the generation it shares"
1635        );
1636        drop(subscription);
1637
1638        // A file one byte too large cannot be framed for any subscriber, so it
1639        // must never be published at all. Asserting that it never appears is
1640        // the property; asserting *when* the registry notices would be a race.
1641        let oversize = "x".repeat(exact.len() + 1);
1642        std::fs::write(&path, &oversize).unwrap();
1643        for _ in 0..5 {
1644            if let Ok((subscription, _wake)) = subscribe_for_test(
1645                &mut server,
1646                &site_root(&directory),
1647                &watcher,
1648                &budget,
1649                SubscribeMode::Replace,
1650            )
1651            .await
1652            {
1653                assert_ne!(
1654                    subscription.baseline.text, oversize,
1655                    "a file too large to frame must never reach a subscriber"
1656                );
1657                let _ = tokio::time::timeout(Duration::from_millis(50), client.receive()).await;
1658            }
1659            tokio::time::sleep(Duration::from_millis(20)).await;
1660        }
1661    }
1662
1663    #[tokio::test]
1664    async fn subscription_owner_keyed_allocation_rejection_rolls_back_every_candidate() {
1665        let directory = tempfile::tempdir().unwrap();
1666        std::fs::write(directory.path().join("ticker.aml"), "first").unwrap();
1667        let owner = subscription_owner_key("/ticker.aml", "ticker");
1668        for site in [ServerAllocationSite::Path, ServerAllocationSite::Region] {
1669            let budget = SubscriptionBudget::new(1024 * 1024);
1670            let (watcher, _shutdown) = test_watcher(&budget);
1671            let (mut server, mut client) = negotiated_server_pair().await;
1672            let rejection = AllocationRejectionGuard::at(site, owner);
1673            assert!(
1674                matches!(
1675                    subscribe_for_test(
1676                        &mut server,
1677                        &site_root(&directory),
1678                        &watcher,
1679                        &budget,
1680                        SubscribeMode::Delta,
1681                    )
1682                    .await,
1683                    Err(ProtocolError::ResourceExhausted { .. })
1684                ),
1685                "{site:?} must refuse the subscription"
1686            );
1687            drop(rejection);
1688            assert_eq!(budget.used(), 0, "candidate leaked at {site:?}");
1689            assert!(
1690                tokio::time::timeout(Duration::from_millis(20), client.receive())
1691                    .await
1692                    .is_err(),
1693                "a refused subscription must not have sent anything"
1694            );
1695        }
1696    }
1697
1698    #[tokio::test]
1699    async fn initial_subscription_send_failure_drops_complete_candidate() {
1700        let directory = tempfile::tempdir().unwrap();
1701        std::fs::write(directory.path().join("ticker.aml"), "first").unwrap();
1702        let budget = SubscriptionBudget::new(1024 * 1024);
1703        let (watcher, _shutdown) = test_watcher(&budget);
1704        let (mut server, _client) = negotiated_server_pair().await;
1705        assert!(
1706            server
1707                .send_frame(&RawFrame {
1708                    msg_type: MessageType::Update,
1709                    flags: 0,
1710                    body: b"invalid".to_vec(),
1711                })
1712                .await
1713                .is_err()
1714        );
1715
1716        let attempt = subscribe_for_test(
1717            &mut server,
1718            &site_root(&directory),
1719            &watcher,
1720            &budget,
1721            SubscribeMode::Delta,
1722        )
1723        .await;
1724        assert!(
1725            attempt.is_err(),
1726            "a poisoned stream must fail the subscribe"
1727        );
1728        drop(attempt);
1729        // The per-connection lease is returned; the shared generation is
1730        // released once the registry reaps an entry nobody is listening to.
1731        let deadline = std::time::Instant::now() + Duration::from_secs(2);
1732        while budget.used() != 0 {
1733            assert!(
1734                std::time::Instant::now() < deadline,
1735                "a failed subscribe leaked {} bytes",
1736                budget.used()
1737            );
1738            tokio::time::sleep(Duration::from_millis(5)).await;
1739        }
1740    }
1741
1742    /// The property the old polling test protected, restated for a shared read:
1743    /// a subscriber's delta baseline advances only on a successful send, so a
1744    /// missed generation resynchronises itself instead of corrupting the
1745    /// subscriber's view.
1746    #[tokio::test]
1747    async fn shared_generation_pressure_preserves_the_delta_baseline() {
1748        let directory = tempfile::tempdir().unwrap();
1749        let path = directory.path().join("ticker.aml");
1750        std::fs::write(&path, "first").unwrap();
1751        let budget = SubscriptionBudget::new(1024 * 1024);
1752        let (watcher, _shutdown) = test_watcher(&budget);
1753        let (mut server, mut client) = negotiated_server_pair().await;
1754        let (subscription, mut wake) = subscribe_for_test(
1755            &mut server,
1756            &site_root(&directory),
1757            &watcher,
1758            &budget,
1759            SubscribeMode::Delta,
1760        )
1761        .await
1762        .unwrap();
1763        let _ = client.receive().await;
1764        let mut subscriptions = vec![subscription];
1765
1766        // An unsendable file must not advance anyone's baseline.
1767        let prefix = "UPDATE \n\n".len() + subscriptions[0].region.len();
1768        std::fs::write(
1769            &path,
1770            "x".repeat(dustnet_core::protocol::MAX_LIVE_UPDATE_SIZE - prefix + 1),
1771        )
1772        .unwrap();
1773        tokio::time::sleep(Duration::from_millis(50)).await;
1774        flush_subscriptions(&mut server, &mut subscriptions)
1775            .await
1776            .unwrap();
1777        assert_eq!(subscriptions[0].baseline.text, "first");
1778        assert!(
1779            tokio::time::timeout(Duration::from_millis(50), client.receive())
1780                .await
1781                .is_err(),
1782            "an unsendable generation must produce no wire traffic"
1783        );
1784
1785        // A sendable successor resumes deltas from the preserved baseline.
1786        std::fs::write(&path, "first-second").unwrap();
1787        wake_and_flush(&mut server, &mut subscriptions, &mut wake)
1788            .await
1789            .unwrap();
1790        let update = client.receive().await;
1791        assert_eq!(update.flags, UpdateFlags { delta: true }.to_bits());
1792        assert_eq!(
1793            UpdateMessage::parse(std::str::from_utf8(&update.body).unwrap())
1794                .unwrap()
1795                .content,
1796            "-second",
1797            "the delta must be computed against what this subscriber last saw"
1798        );
1799        assert_eq!(subscriptions[0].baseline.text, "first-second");
1800
1801        // A flush with nothing new sends nothing.
1802        flush_subscriptions(&mut server, &mut subscriptions)
1803            .await
1804            .unwrap();
1805        assert!(
1806            tokio::time::timeout(Duration::from_millis(50), client.receive())
1807                .await
1808                .is_err()
1809        );
1810
1811        // Divergent content falls back to a complete replace.
1812        std::fs::write(&path, "replacement").unwrap();
1813        wake_and_flush(&mut server, &mut subscriptions, &mut wake)
1814            .await
1815            .unwrap();
1816        let update = client.receive().await;
1817        assert_eq!(update.flags, 0, "a divergent value is a full replace");
1818        assert_eq!(
1819            UpdateMessage::parse(std::str::from_utf8(&update.body).unwrap())
1820                .unwrap()
1821                .content,
1822            "replacement"
1823        );
1824        assert_eq!(subscriptions[0].baseline.text, "replacement");
1825    }
1826
1827    /// The claim the whole change exists to make, at the connection level: two
1828    /// connections watching one path are served by one read, and each still
1829    /// gets the encoding its own subscription asked for. Sharing the read must
1830    /// not collapse into sharing the message.
1831    #[tokio::test]
1832    async fn two_connections_share_one_read_with_independent_modes() {
1833        let directory = tempfile::tempdir().unwrap();
1834        let path = directory.path().join("ticker.aml");
1835        std::fs::write(&path, "first").unwrap();
1836        let budget = SubscriptionBudget::new(1024 * 1024);
1837        let (watcher, _shutdown) = test_watcher(&budget);
1838
1839        let (mut delta_server, mut delta_client) = negotiated_server_pair().await;
1840        let (delta_subscription, mut delta_wake) = subscribe_for_test(
1841            &mut delta_server,
1842            &site_root(&directory),
1843            &watcher,
1844            &budget,
1845            SubscribeMode::Delta,
1846        )
1847        .await
1848        .unwrap();
1849        let _ = delta_client.receive().await;
1850
1851        let (mut replace_server, mut replace_client) = negotiated_server_pair().await;
1852        let (replace_subscription, mut replace_wake) = subscribe_for_test(
1853            &mut replace_server,
1854            &site_root(&directory),
1855            &watcher,
1856            &budget,
1857            SubscribeMode::Replace,
1858        )
1859        .await
1860        .unwrap();
1861        let _ = replace_client.receive().await;
1862
1863        assert!(
1864            Arc::ptr_eq(&delta_subscription.baseline, &replace_subscription.baseline),
1865            "both connections must be looking at the very same generation"
1866        );
1867        let shared = budget.used();
1868
1869        let mut delta_subscriptions = vec![delta_subscription];
1870        let mut replace_subscriptions = vec![replace_subscription];
1871        std::fs::write(&path, "first-second").unwrap();
1872
1873        wake_and_flush(&mut delta_server, &mut delta_subscriptions, &mut delta_wake)
1874            .await
1875            .unwrap();
1876        wake_and_flush(
1877            &mut replace_server,
1878            &mut replace_subscriptions,
1879            &mut replace_wake,
1880        )
1881        .await
1882        .unwrap();
1883
1884        let delta_update = delta_client.receive().await;
1885        assert_eq!(delta_update.flags, UpdateFlags { delta: true }.to_bits());
1886        assert_eq!(
1887            UpdateMessage::parse(std::str::from_utf8(&delta_update.body).unwrap())
1888                .unwrap()
1889                .content,
1890            "-second",
1891            "the delta subscriber gets a suffix"
1892        );
1893
1894        let replace_update = replace_client.receive().await;
1895        assert_eq!(replace_update.flags, 0);
1896        assert_eq!(
1897            UpdateMessage::parse(std::str::from_utf8(&replace_update.body).unwrap())
1898                .unwrap()
1899                .content,
1900            "first-second",
1901            "the replace subscriber gets the whole value, from the same read"
1902        );
1903
1904        assert!(
1905            Arc::ptr_eq(
1906                &delta_subscriptions[0].baseline,
1907                &replace_subscriptions[0].baseline
1908            ),
1909            "one read served both subscribers"
1910        );
1911        // Two subscribers of one path cost one copy of its content, so the
1912        // second subscriber adds only its own region.
1913        assert!(
1914            budget.used() < shared + "first-second".len() * 2,
1915            "content appears to have been charged per subscriber"
1916        );
1917    }
1918
1919    #[tokio::test]
1920    async fn read_and_send_failures_preserve_the_delta_baseline() {
1921        let directory = tempfile::tempdir().unwrap();
1922        let path = directory.path().join("ticker.aml");
1923        std::fs::write(&path, "first").unwrap();
1924        let budget = SubscriptionBudget::new(1024 * 1024);
1925        let (watcher, _shutdown) = test_watcher(&budget);
1926        let (mut server, mut client) = negotiated_server_pair().await;
1927        let (subscription, _wake) = subscribe_for_test(
1928            &mut server,
1929            &site_root(&directory),
1930            &watcher,
1931            &budget,
1932            SubscribeMode::Delta,
1933        )
1934        .await
1935        .unwrap();
1936        let _ = client.receive().await;
1937        let mut subscriptions = vec![subscription];
1938
1939        // A file that is not UTF-8 cannot be published at all.
1940        std::fs::write(&path, [0xff, 0xfe]).unwrap();
1941        tokio::time::sleep(Duration::from_millis(50)).await;
1942        flush_subscriptions(&mut server, &mut subscriptions)
1943            .await
1944            .unwrap();
1945        assert_eq!(subscriptions[0].baseline.text, "first");
1946
1947        // A send failure must leave the baseline where it was, so the missed
1948        // generation is re-sent rather than skipped.
1949        std::fs::write(&path, "first-after-failure").unwrap();
1950        tokio::time::sleep(Duration::from_millis(50)).await;
1951        assert!(
1952            server
1953                .send_frame(&RawFrame {
1954                    msg_type: MessageType::Update,
1955                    flags: 0,
1956                    body: b"invalid".to_vec(),
1957                })
1958                .await
1959                .is_err()
1960        );
1961        assert!(
1962            flush_subscriptions(&mut server, &mut subscriptions)
1963                .await
1964                .is_err()
1965        );
1966        assert_eq!(subscriptions[0].baseline.text, "first");
1967        drop(client);
1968    }
1969
1970    #[tokio::test]
1971    async fn static_subscription_polls_delta_and_unsubscribe_stops_updates() {
1972        let directory = tempfile::tempdir().unwrap();
1973        let live_path = directory.path().join("ticker.aml");
1974        std::fs::write(&live_path, "first").unwrap();
1975        let config = StaticServerConfig::bind_plaintext_loopback(
1976            directory.path().to_path_buf(),
1977            "127.0.0.1",
1978            0,
1979        )
1980        .await
1981        .unwrap();
1982        let address = config.local_addr().unwrap();
1983        let mut server = StaticServer::new(config);
1984        let shutdown = server.shutdown_handle();
1985        let task = tokio::spawn(async move { server.run().await });
1986
1987        let mut client = RawClient::connect(address).await;
1988        client.handshake().await;
1989        client
1990            .send(RawFrame {
1991                msg_type: MessageType::Subscribe,
1992                flags: 0,
1993                body: b"SUBSCRIBE /ticker.aml\nRegion: ticker\nMode: delta\n".to_vec(),
1994            })
1995            .await;
1996        let initial = client.receive().await;
1997        assert_eq!(initial.msg_type, MessageType::Update);
1998        assert_eq!(initial.flags, 0);
1999        assert!(String::from_utf8(initial.body).unwrap().ends_with("first"));
2000
2001        std::fs::write(&live_path, "first-second").unwrap();
2002        let changed = tokio::time::timeout(Duration::from_secs(2), client.receive())
2003            .await
2004            .unwrap();
2005        assert_eq!(changed.flags, 1);
2006        assert!(
2007            String::from_utf8(changed.body)
2008                .unwrap()
2009                .ends_with("-second")
2010        );
2011
2012        client
2013            .send(RawFrame {
2014                msg_type: MessageType::Unsubscribe,
2015                flags: 0,
2016                body: Vec::new(),
2017            })
2018            .await;
2019        std::fs::write(&live_path, "first-second-third").unwrap();
2020        assert!(
2021            tokio::time::timeout(Duration::from_millis(700), client.receive())
2022                .await
2023                .is_err()
2024        );
2025
2026        shutdown.send(true).unwrap();
2027        task.await.unwrap().unwrap();
2028    }
2029
2030    #[tokio::test]
2031    async fn reconnect_and_resubscribe_replays_current_content_then_resumes_deltas() {
2032        let directory = tempfile::tempdir().unwrap();
2033        let live_path = directory.path().join("ticker.aml");
2034        std::fs::write(&live_path, "first").unwrap();
2035        let config = StaticServerConfig::bind_plaintext_loopback(
2036            directory.path().to_path_buf(),
2037            "127.0.0.1",
2038            0,
2039        )
2040        .await
2041        .unwrap();
2042        let address = config.local_addr().unwrap();
2043        let mut server = StaticServer::new(config);
2044        let shutdown = server.shutdown_handle();
2045        let task = tokio::spawn(async move { server.run().await });
2046
2047        let subscribe = || RawFrame {
2048            msg_type: MessageType::Subscribe,
2049            flags: 0,
2050            body: b"SUBSCRIBE /ticker.aml\nRegion: ticker\nMode: delta\n".to_vec(),
2051        };
2052
2053        let mut first = RawClient::connect(address).await;
2054        first.handshake().await;
2055        first.send(subscribe()).await;
2056        let initial = first.receive().await;
2057        assert_eq!(initial.msg_type, MessageType::Update);
2058        assert_eq!(initial.flags, 0);
2059        assert_eq!(
2060            UpdateMessage::parse(std::str::from_utf8(&initial.body).unwrap())
2061                .unwrap()
2062                .content,
2063            "first"
2064        );
2065        drop(first);
2066
2067        std::fs::write(&live_path, "first-while-disconnected").unwrap();
2068        let mut reconnected = RawClient::connect(address).await;
2069        reconnected.handshake().await;
2070        reconnected.send(subscribe()).await;
2071        let replay = reconnected.receive().await;
2072        assert_eq!(replay.msg_type, MessageType::Update);
2073        assert_eq!(replay.flags, 0, "a replay is a complete current value");
2074        assert_eq!(
2075            UpdateMessage::parse(std::str::from_utf8(&replay.body).unwrap())
2076                .unwrap()
2077                .content,
2078            "first-while-disconnected"
2079        );
2080
2081        std::fs::write(&live_path, "first-while-disconnected-after").unwrap();
2082        let changed = tokio::time::timeout(Duration::from_secs(2), reconnected.receive())
2083            .await
2084            .expect("reconnected subscription did not resume polling");
2085        assert_eq!(changed.msg_type, MessageType::Update);
2086        assert_eq!(changed.flags, UpdateFlags { delta: true }.to_bits());
2087        assert_eq!(
2088            UpdateMessage::parse(std::str::from_utf8(&changed.body).unwrap())
2089                .unwrap()
2090                .content,
2091            "-after"
2092        );
2093
2094        drop(reconnected);
2095        shutdown.send(true).unwrap();
2096        task.await.unwrap().unwrap();
2097    }
2098
2099    #[tokio::test]
2100    async fn stalled_frame_body_read_is_bounded() {
2101        let listener = AtpListener::bind_plain("127.0.0.1", 0).await.unwrap();
2102        let address = listener.local_addr().unwrap();
2103        let mut client = TcpStream::connect(address).await.unwrap();
2104        let pending = listener.accept_pending().await.unwrap();
2105        let mut server_stream = pending.handshake().await.unwrap();
2106        let encoded = encode_frame(&RawFrame {
2107            msg_type: MessageType::Hello,
2108            flags: 0,
2109            body: b"HELLO/0.2\n".to_vec(),
2110        })
2111        .unwrap();
2112
2113        client
2114            .write_all(&encoded[..dustnet_core::protocol::HEADER_SIZE + 1])
2115            .await
2116            .unwrap();
2117        let result = recv(&mut server_stream, Duration::from_millis(50)).await;
2118        assert!(matches!(result, Err(ProtocolError::Timeout)));
2119    }
2120
2121    #[tokio::test]
2122    async fn stalled_frame_write_is_bounded() {
2123        let listener = AtpListener::bind_plain("127.0.0.1", 0).await.unwrap();
2124        let address = listener.local_addr().unwrap();
2125        let mut client = TcpStream::connect(address).await.unwrap();
2126        let pending = listener.accept_pending().await.unwrap();
2127        let mut server_stream = pending.handshake().await.unwrap();
2128
2129        client
2130            .write_all(
2131                &encode_frame(&RawFrame {
2132                    msg_type: MessageType::Hello,
2133                    flags: 0,
2134                    body: b"HELLO/0.2\nCapabilities: live-updates\n".to_vec(),
2135                })
2136                .unwrap(),
2137            )
2138            .await
2139            .unwrap();
2140        assert_eq!(
2141            recv(&mut server_stream, Duration::from_secs(1))
2142                .await
2143                .unwrap()
2144                .msg_type,
2145            MessageType::Hello
2146        );
2147        send_with_timeout(
2148            &mut server_stream,
2149            &RawFrame {
2150                msg_type: MessageType::Welcome,
2151                flags: 0,
2152                body: b"WELCOME/0.2\nCapabilities: live-updates\n".to_vec(),
2153            },
2154            Duration::from_secs(1),
2155        )
2156        .await
2157        .unwrap();
2158
2159        // Never read from the peer. Repeated maximum-sized live updates fill
2160        // the kernel send window, after which the same timeout wrapper used by
2161        // production must bound the pending write.
2162        let update = UpdateMessage {
2163            region: "ticker".into(),
2164            content: "x".repeat(dustnet_core::protocol::MAX_LIVE_UPDATE_SIZE - 64),
2165            flags: UpdateFlags::default(),
2166        };
2167        let frame = RawFrame {
2168            msg_type: MessageType::Update,
2169            flags: 0,
2170            body: update.serialize().unwrap().into_bytes(),
2171        };
2172        let mut timed_out = false;
2173        for _ in 0..128 {
2174            match send_with_timeout(&mut server_stream, &frame, Duration::from_millis(50)).await {
2175                Err(ProtocolError::Timeout) => {
2176                    timed_out = true;
2177                    break;
2178                }
2179                Ok(()) => {}
2180                Err(error) => panic!("unexpected write failure: {error}"),
2181            }
2182        }
2183        assert!(timed_out, "peer receive window accepted more than 128 MiB");
2184    }
2185
2186    #[tokio::test]
2187    async fn plaintext_configuration_rejects_non_loopback_binding() {
2188        let directory = tempfile::tempdir().unwrap();
2189        let result = StaticServerConfig::bind_plaintext_loopback(
2190            directory.path().to_path_buf(),
2191            "0.0.0.0",
2192            0,
2193        )
2194        .await;
2195        assert!(result.is_err());
2196    }
2197
2198    #[tokio::test]
2199    async fn invalid_tls_handshake_is_closed_without_stopping_the_listener() {
2200        let directory = tempfile::tempdir().unwrap();
2201        let config = StaticServerConfig::bind_self_signed_for_tests(
2202            directory.path().to_path_buf(),
2203            "127.0.0.1",
2204            0,
2205        )
2206        .await
2207        .unwrap();
2208        let address = config.local_addr().unwrap();
2209        let mut server = StaticServer::new(config);
2210        let shutdown = server.shutdown_handle();
2211        let task = tokio::spawn(async move { server.run().await });
2212
2213        let mut invalid = TcpStream::connect(address).await.unwrap();
2214        invalid.write_all(b"not a TLS handshake").await.unwrap();
2215        invalid.shutdown().await.unwrap();
2216        let mut alert = Vec::new();
2217        tokio::time::timeout(Duration::from_secs(2), invalid.read_to_end(&mut alert))
2218            .await
2219            .expect("invalid handshakes must be bounded")
2220            .unwrap();
2221        assert!(!alert.is_empty(), "rustls should return a TLS alert");
2222
2223        // A rejected handshake must not poison the accept loop.
2224        let second = TcpStream::connect(address).await.unwrap();
2225        assert_eq!(second.peer_addr().unwrap(), address);
2226        drop(second);
2227
2228        shutdown.send(true).unwrap();
2229        task.await.unwrap().unwrap();
2230    }
2231
2232    #[tokio::test]
2233    async fn silent_tls_handshake_is_closed_at_the_production_deadline() {
2234        let directory = tempfile::tempdir().unwrap();
2235        let config = StaticServerConfig::bind_self_signed_for_tests(
2236            directory.path().to_path_buf(),
2237            "127.0.0.1",
2238            0,
2239        )
2240        .await
2241        .unwrap();
2242        let address = config.local_addr().unwrap();
2243        let mut server = StaticServer::new(config);
2244        let shutdown = server.shutdown_handle();
2245        let task = tokio::spawn(async move { server.run().await });
2246
2247        let started = std::time::Instant::now();
2248        let mut silent = TcpStream::connect(address).await.unwrap();
2249        let mut received = Vec::new();
2250        tokio::time::timeout(
2251            HANDSHAKE_TIMEOUT + Duration::from_secs(2),
2252            silent.read_to_end(&mut received),
2253        )
2254        .await
2255        .expect("silent TLS handshake must be closed at the configured deadline")
2256        .unwrap();
2257        assert!(
2258            started.elapsed() >= HANDSHAKE_TIMEOUT / 2,
2259            "the listener closed materially before its configured handshake timeout: {:?}",
2260            started.elapsed()
2261        );
2262        assert!(received.is_empty());
2263
2264        shutdown.send(true).unwrap();
2265        task.await.unwrap().unwrap();
2266    }
2267
2268    #[tokio::test]
2269    async fn fragmented_frames_are_read_completely_and_missing_files_are_bounded_errors() {
2270        let directory = tempfile::tempdir().unwrap();
2271        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
2272        let config = StaticServerConfig::bind_plaintext_loopback(
2273            directory.path().to_path_buf(),
2274            "127.0.0.1",
2275            0,
2276        )
2277        .await
2278        .unwrap();
2279        let address = config.local_addr().unwrap();
2280        let mut server = StaticServer::new(config);
2281        let shutdown = server.shutdown_handle();
2282        let task = tokio::spawn(async move { server.run().await });
2283
2284        let mut client = RawClient::connect(address).await;
2285        client
2286            .send_fragmented(RawFrame {
2287                msg_type: MessageType::Hello,
2288                flags: 0,
2289                body: b"HELLO/0.2\n".to_vec(),
2290            })
2291            .await;
2292        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
2293
2294        client
2295            .send_fragmented(RawFrame {
2296                msg_type: MessageType::Get,
2297                flags: 0,
2298                body: b"GET /missing.aml\n".to_vec(),
2299            })
2300            .await;
2301        let response = client.receive().await;
2302        assert_eq!(response.msg_type, MessageType::Error);
2303        assert!(response.body.len() <= dustnet_core::protocol::MAX_CONTROL_MESSAGE_SIZE);
2304
2305        drop(client);
2306        shutdown.send(true).unwrap();
2307        task.await.unwrap().unwrap();
2308    }
2309
2310    fn hello_frame() -> RawFrame {
2311        RawFrame {
2312            msg_type: MessageType::Hello,
2313            flags: 0,
2314            body: b"HELLO/0.2\n".to_vec(),
2315        }
2316    }
2317
2318    /// A HELLO that offers both `sessions` and `page-path`, as the reference
2319    /// client does — the pair a login response needs, since it both issues a
2320    /// session and names the page it landed on.
2321    fn hello_frame_with_sessions_and_page_path() -> RawFrame {
2322        RawFrame {
2323            msg_type: MessageType::Hello,
2324            flags: 0,
2325            body: b"HELLO/0.2\nCapabilities: sessions,page-path\n".to_vec(),
2326        }
2327    }
2328
2329    /// A HELLO that offers the `sessions` capability.
2330    ///
2331    /// Needed by any test whose frames carry a session: the transport gates
2332    /// session-bearing frames on the negotiated capability, so a server cannot
2333    /// send `Set-Session` to a client that never said it understood sessions.
2334    /// A good property, and one a bare HELLO does not satisfy.
2335    fn hello_frame_with_sessions() -> RawFrame {
2336        RawFrame {
2337            msg_type: MessageType::Hello,
2338            flags: 0,
2339            body: b"HELLO/0.2\nCapabilities: sessions\n".to_vec(),
2340        }
2341    }
2342
2343    fn ping_frame() -> RawFrame {
2344        RawFrame {
2345            msg_type: MessageType::Ping,
2346            flags: 0,
2347            body: Vec::new(),
2348        }
2349    }
2350
2351    /// Spawn a server whose idle deadline is `read_timeout`, and return its
2352    /// address plus the handles needed to stop it.
2353    async fn server_with_read_timeout(
2354        directory: &std::path::Path,
2355        read_timeout: Duration,
2356    ) -> (
2357        std::net::SocketAddr,
2358        watch::Sender<bool>,
2359        tokio::task::JoinHandle<Result<(), ProtocolError>>,
2360    ) {
2361        let config =
2362            StaticServerConfig::bind_plaintext_loopback(directory.to_path_buf(), "127.0.0.1", 0)
2363                .await
2364                .unwrap()
2365                .with_read_timeout(read_timeout);
2366        let address = config.local_addr().unwrap();
2367        let mut server = StaticServer::new(config);
2368        let shutdown = server.shutdown_handle();
2369        let task = tokio::spawn(async move { server.run().await });
2370        (address, shutdown, task)
2371    }
2372
2373    /// Subscribing must not wait on the platform watcher.
2374    ///
2375    /// Registering an FSEvents watch was measured at 1.7 seconds. The registry
2376    /// is one task shared by every connection, so a blocking registration there
2377    /// stalls every other subscriber behind it — which is why the platform
2378    /// watcher lives on its own thread. Watch registration is only ever a
2379    /// latency optimisation, since reconciliation serves the file regardless,
2380    /// so a subscriber must never be waiting on it.
2381    #[tokio::test]
2382    async fn subscribing_is_not_delayed_by_watcher_registration() {
2383        let directory = tempfile::tempdir().unwrap();
2384        let (address, shutdown, task) =
2385            server_with_read_timeout(directory.path(), READ_TIMEOUT).await;
2386        // Created after the server bound, so this is the first watch of it.
2387        std::fs::write(directory.path().join("ticker.aml"), "initial content").unwrap();
2388
2389        let mut client = RawClient::connect(address).await;
2390        client.handshake().await;
2391        client
2392            .send(RawFrame {
2393                msg_type: MessageType::Subscribe,
2394                flags: 0,
2395                body: b"SUBSCRIBE /ticker\nRegion: my-region\n".to_vec(),
2396            })
2397            .await;
2398
2399        let started = std::time::Instant::now();
2400        let frame = tokio::time::timeout(Duration::from_secs(3), client.receive())
2401            .await
2402            .expect("an initial UPDATE must arrive");
2403        let elapsed = started.elapsed();
2404        assert_eq!(frame.msg_type, MessageType::Update);
2405        assert!(
2406            elapsed < Duration::from_millis(500),
2407            "the initial UPDATE took {elapsed:?}; subscribing appears to be \
2408             waiting on platform watch registration again"
2409        );
2410
2411        drop(client);
2412        shutdown.send(true).unwrap();
2413        task.await.unwrap().unwrap();
2414    }
2415
2416    #[tokio::test]
2417    async fn ping_is_answered_with_an_empty_pong() {
2418        let directory = tempfile::tempdir().unwrap();
2419        let (address, shutdown, task) =
2420            server_with_read_timeout(directory.path(), READ_TIMEOUT).await;
2421
2422        let mut client = RawClient::connect(address).await;
2423        client.handshake().await;
2424        client.send(ping_frame()).await;
2425        let pong = tokio::time::timeout(Duration::from_secs(2), client.receive())
2426            .await
2427            .expect("PONG must arrive");
2428        assert_eq!(pong.msg_type, MessageType::Pong);
2429        assert_eq!(pong.flags, 0);
2430        assert!(pong.body.is_empty(), "PONG carries no body");
2431
2432        drop(client);
2433        shutdown.send(true).unwrap();
2434        task.await.unwrap().unwrap();
2435    }
2436
2437    /// The control for the test below: without PING the deadline really does
2438    /// close the connection. Without this, a keepalive test could pass against
2439    /// a server that had simply stopped enforcing any deadline at all.
2440    #[tokio::test]
2441    async fn a_silent_connection_is_closed_at_the_idle_deadline() {
2442        let directory = tempfile::tempdir().unwrap();
2443        let deadline = Duration::from_millis(300);
2444        let (address, shutdown, task) = server_with_read_timeout(directory.path(), deadline).await;
2445
2446        let mut client = RawClient::connect(address).await;
2447        client.handshake().await;
2448
2449        let mut byte = [0_u8; 1];
2450        let started = std::time::Instant::now();
2451        let result = tokio::time::timeout(deadline * 10, client.0.read(&mut byte))
2452            .await
2453            .expect("a silent connection must be closed at the deadline");
2454        assert!(matches!(result, Ok(0) | Err(_)));
2455        assert!(
2456            started.elapsed() >= deadline / 2,
2457            "the connection closed before the deadline could have elapsed"
2458        );
2459
2460        shutdown.send(true).unwrap();
2461        task.await.unwrap().unwrap();
2462    }
2463
2464    /// PING exists to reset that deadline. Pinging at a third of it keeps a
2465    /// connection alive well past the point where the control above dies.
2466    #[tokio::test]
2467    async fn pinging_holds_a_connection_open_past_the_idle_deadline() {
2468        let directory = tempfile::tempdir().unwrap();
2469        let deadline = Duration::from_millis(300);
2470        let (address, shutdown, task) = server_with_read_timeout(directory.path(), deadline).await;
2471
2472        let mut client = RawClient::connect(address).await;
2473        client.handshake().await;
2474
2475        // Four deadlines' worth of wall clock, pinged at a third of each.
2476        for _ in 0..12 {
2477            tokio::time::sleep(deadline / 3).await;
2478            client.send(ping_frame()).await;
2479            let pong = tokio::time::timeout(Duration::from_secs(2), client.receive())
2480                .await
2481                .expect("the connection must still be open");
2482            assert_eq!(pong.msg_type, MessageType::Pong);
2483        }
2484
2485        drop(client);
2486        shutdown.send(true).unwrap();
2487        task.await.unwrap().unwrap();
2488    }
2489
2490    /// A PING sent while a request is outstanding must not be mistaken for the
2491    /// response, and must not poison the connection state machine.
2492    #[tokio::test]
2493    async fn ping_does_not_disturb_an_in_flight_request() {
2494        let directory = tempfile::tempdir().unwrap();
2495        std::fs::write(directory.path().join("index.aml"), "hello").unwrap();
2496        let (address, shutdown, task) =
2497            server_with_read_timeout(directory.path(), READ_TIMEOUT).await;
2498
2499        let mut client = RawClient::connect(address).await;
2500        client.handshake().await;
2501        client
2502            .send(RawFrame {
2503                msg_type: MessageType::Get,
2504                flags: 0,
2505                body: b"GET /\n".to_vec(),
2506            })
2507            .await;
2508        client.send(ping_frame()).await;
2509
2510        // Both replies must arrive, and the PAGE must not have been displaced.
2511        let mut seen_page = false;
2512        let mut seen_pong = false;
2513        for _ in 0..2 {
2514            let frame = tokio::time::timeout(Duration::from_secs(2), client.receive())
2515                .await
2516                .expect("both replies must arrive");
2517            match frame.msg_type {
2518                MessageType::Page => seen_page = true,
2519                MessageType::Pong => seen_pong = true,
2520                other => panic!("unexpected {other:?}"),
2521            }
2522        }
2523        assert!(seen_page && seen_pong);
2524
2525        drop(client);
2526        shutdown.send(true).unwrap();
2527        task.await.unwrap().unwrap();
2528    }
2529
2530    #[tokio::test]
2531    async fn fifth_simultaneous_connection_from_one_ip_is_rejected() {
2532        let directory = tempfile::tempdir().unwrap();
2533        let config = StaticServerConfig::bind_plaintext_loopback(
2534            directory.path().to_path_buf(),
2535            "127.0.0.1",
2536            0,
2537        )
2538        .await
2539        .unwrap();
2540        let address = config.local_addr().unwrap();
2541        let mut server = StaticServer::new(config);
2542        let shutdown = server.shutdown_handle();
2543        let task = tokio::spawn(async move { server.run().await });
2544
2545        let mut admitted = Vec::new();
2546        for _ in 0..DEFAULT_MAX_CONNECTIONS_PER_IP {
2547            let mut client = RawClient::connect(address).await;
2548            client.handshake().await;
2549            admitted.push(client);
2550        }
2551
2552        let mut rejected = TcpStream::connect(address).await.unwrap();
2553        rejected
2554            .write_all(
2555                &encode_frame(&RawFrame {
2556                    msg_type: MessageType::Hello,
2557                    flags: 0,
2558                    body: b"HELLO/0.2\n".to_vec(),
2559                })
2560                .unwrap(),
2561            )
2562            .await
2563            .ok();
2564        let mut byte = [0_u8; 1];
2565        let result = tokio::time::timeout(Duration::from_secs(1), rejected.read(&mut byte))
2566            .await
2567            .expect("over-limit connection must be closed promptly");
2568        assert!(matches!(result, Ok(0) | Err(_)));
2569
2570        drop(rejected);
2571        drop(admitted);
2572        shutdown.send(true).unwrap();
2573        task.await.unwrap().unwrap();
2574    }
2575
2576    #[tokio::test]
2577    async fn global_connection_limit_rejects_a_concurrent_flood() {
2578        let directory = tempfile::tempdir().unwrap();
2579        let config = StaticServerConfig::bind_plaintext_loopback(
2580            directory.path().to_path_buf(),
2581            "127.0.0.1",
2582            0,
2583        )
2584        .await
2585        .unwrap()
2586        .with_connection_limits(3, 4);
2587        let address = config.local_addr().unwrap();
2588        let mut server = StaticServer::new(config);
2589        let shutdown = server.shutdown_handle();
2590        let task = tokio::spawn(async move { server.run().await });
2591
2592        let mut admitted = Vec::new();
2593        for _ in 0..3 {
2594            let mut client = RawClient::connect(address).await;
2595            client.handshake().await;
2596            admitted.push(client);
2597        }
2598
2599        let mut rejected = RawClient::connect(address).await;
2600        rejected
2601            .send(RawFrame {
2602                msg_type: MessageType::Hello,
2603                flags: 0,
2604                body: b"HELLO/0.2\n".to_vec(),
2605            })
2606            .await;
2607        let mut byte = [0_u8; 1];
2608        let result = tokio::time::timeout(Duration::from_secs(1), rejected.0.read(&mut byte))
2609            .await
2610            .expect("globally over-limit connection must close promptly");
2611        assert!(matches!(result, Ok(0) | Err(_)));
2612
2613        drop(rejected);
2614        drop(admitted);
2615        shutdown.send(true).unwrap();
2616        task.await.unwrap().unwrap();
2617    }
2618
2619    #[tokio::test]
2620    async fn malformed_tls_material_is_rejected_before_serving() {
2621        let directory = tempfile::tempdir().unwrap();
2622        let certificate = directory.path().join("certificate.pem");
2623        let private_key = directory.path().join("private-key.pem");
2624        std::fs::write(&certificate, "not a certificate").unwrap();
2625        std::fs::write(&private_key, "not a private key").unwrap();
2626        #[cfg(unix)]
2627        {
2628            use std::os::unix::fs::PermissionsExt;
2629            std::fs::set_permissions(&certificate, std::fs::Permissions::from_mode(0o600)).unwrap();
2630            std::fs::set_permissions(&private_key, std::fs::Permissions::from_mode(0o600)).unwrap();
2631        }
2632
2633        let result = StaticServerConfig::bind_tls(
2634            directory.path().to_path_buf(),
2635            "127.0.0.1",
2636            0,
2637            certificate.to_str().unwrap(),
2638            private_key.to_str().unwrap(),
2639        )
2640        .await;
2641        assert!(matches!(result, Err(ProtocolError::Tls(_))));
2642    }
2643
2644    /// The test above only proves shutdown finishes inside the drain deadline —
2645    /// which it did even when every task had to be aborted. This one proves the
2646    /// connections leave voluntarily, so the deadline is a backstop rather than
2647    /// the normal path. That distinction is what makes 2048 connections
2648    /// survivable: aborting 2048 tasks is very different from joining them.
2649    #[tokio::test]
2650    async fn idle_connections_leave_voluntarily_well_inside_the_drain_deadline() {
2651        let directory = tempfile::tempdir().unwrap();
2652        let (address, shutdown, task) =
2653            server_with_read_timeout(directory.path(), READ_TIMEOUT).await;
2654
2655        let mut clients = Vec::new();
2656        for _ in 0..DEFAULT_MAX_CONNECTIONS_PER_IP {
2657            let mut client = RawClient::connect(address).await;
2658            client.handshake().await;
2659            clients.push(client);
2660        }
2661
2662        let started = std::time::Instant::now();
2663        shutdown.send(true).unwrap();
2664        task.await.unwrap().unwrap();
2665        let elapsed = started.elapsed();
2666
2667        assert!(
2668            elapsed < DRAIN_TIMEOUT / 2,
2669            "shutdown took {elapsed:?}, which suggests connections were aborted \
2670             at the drain deadline rather than leaving on their own"
2671        );
2672        drop(clients);
2673    }
2674
2675    /// A per-IP ceiling above the global ceiling does not describe a reachable
2676    /// state, and zero would refuse every connection including the operator's
2677    /// own health check.
2678    #[tokio::test]
2679    async fn connection_limits_are_clamped_to_a_reachable_range() {
2680        let directory = tempfile::tempdir().unwrap();
2681        let config = || async {
2682            StaticServerConfig::bind_plaintext_loopback(
2683                directory.path().to_path_buf(),
2684                "127.0.0.1",
2685                0,
2686            )
2687            .await
2688            .unwrap()
2689        };
2690
2691        let zeroed = config().await.with_connection_limits(0, 0);
2692        assert_eq!(zeroed.max_connections, 1, "zero would refuse every client");
2693        assert_eq!(zeroed.max_connections_per_ip, 1);
2694
2695        let inverted = config().await.with_connection_limits(4, 100);
2696        assert_eq!(inverted.max_connections, 4);
2697        assert_eq!(
2698            inverted.max_connections_per_ip, 4,
2699            "a per-IP ceiling above the global ceiling is not a reachable state"
2700        );
2701
2702        let ordinary = config().await.with_connection_limits(2048, 4);
2703        assert_eq!(ordinary.max_connections, 2048);
2704        assert_eq!(ordinary.max_connections_per_ip, 4);
2705    }
2706
2707    #[tokio::test]
2708    async fn shutdown_is_bounded_with_an_idle_client() {
2709        let directory = tempfile::tempdir().unwrap();
2710        let config = StaticServerConfig::bind_plaintext_loopback(
2711            directory.path().to_path_buf(),
2712            "127.0.0.1",
2713            0,
2714        )
2715        .await
2716        .unwrap();
2717        let address = config.local_addr().unwrap();
2718        let mut server = StaticServer::new(config);
2719        let shutdown = server.shutdown_handle();
2720        let task = tokio::spawn(async move { server.run().await });
2721
2722        let mut client = RawClient::connect(address).await;
2723        client.handshake().await;
2724        shutdown.send(true).unwrap();
2725
2726        tokio::time::timeout(DRAIN_TIMEOUT + Duration::from_secs(2), task)
2727            .await
2728            .expect("shutdown exceeded its drain deadline")
2729            .unwrap()
2730            .unwrap();
2731        drop(client);
2732    }
2733
2734    #[cfg(unix)]
2735    #[tokio::test]
2736    async fn symlinks_cannot_escape_static_root() {
2737        use std::os::unix::fs::symlink;
2738        let root = tempfile::tempdir().unwrap();
2739        let canonical_root = std::fs::canonicalize(root.path()).unwrap();
2740        let outside = tempfile::NamedTempFile::new().unwrap();
2741        symlink(outside.path(), root.path().join("escape.aml")).unwrap();
2742        assert!(resolve_path(&canonical_root, "/escape.aml").await.is_err());
2743    }
2744
2745    /// The lexical half must not touch the disk, so it can run on a runtime
2746    /// worker. A traversal attempt is rejected before any syscall.
2747    #[test]
2748    fn lexical_resolution_rejects_traversal_without_touching_the_disk() {
2749        let root = Path::new("/nonexistent-root");
2750        assert!(resolve_path_lexical(root, "/../escape.aml").is_err());
2751        assert_eq!(
2752            resolve_path_lexical(root, "/page").unwrap(),
2753            root.join("page.aml"),
2754            "a bare name gains the .aml extension"
2755        );
2756        assert_eq!(
2757            resolve_path_lexical(root, "/").unwrap(),
2758            root.join("index.aml"),
2759            "a directory request resolves to its index"
2760        );
2761    }
2762
2763    /// A miss is a 404, not an escape. Regression guard for the removed
2764    /// `Path::exists` probe.
2765    #[tokio::test]
2766    async fn a_missing_file_resolves_without_error() {
2767        let root = tempfile::tempdir().unwrap();
2768        let canonical_root = std::fs::canonicalize(root.path()).unwrap();
2769        let resolved = resolve_path(&canonical_root, "/absent.aml").await.unwrap();
2770        assert_eq!(resolved, canonical_root.join("absent.aml"));
2771    }
2772
2773    #[tokio::test]
2774    async fn static_resource_read_is_fallible_and_returns_only_filled_bytes() {
2775        let file = tempfile::NamedTempFile::new().unwrap();
2776        std::fs::write(file.path(), b"wasm").unwrap();
2777        let opened = tokio::fs::File::open(file.path()).await.unwrap();
2778        let body = read_static_body(opened, 8, 41).await.unwrap();
2779        assert_eq!(body, b"wasm");
2780
2781        let opened = tokio::fs::File::open(file.path()).await.unwrap();
2782        let _rejection = AllocationRejectionGuard::at(ServerAllocationSite::StaticBody, 41);
2783        assert!(matches!(
2784            read_static_body(opened, 4, 41).await,
2785            Err(ProtocolError::ResourceExhausted { requested: 5 })
2786        ));
2787    }
2788
2789    #[tokio::test]
2790    async fn static_resource_growth_after_metadata_is_rejected() {
2791        let file = tempfile::NamedTempFile::new().unwrap();
2792        std::fs::write(file.path(), b"old").unwrap();
2793        let opened = tokio::fs::File::open(file.path()).await.unwrap();
2794        std::fs::write(file.path(), b"new content").unwrap();
2795        assert!(matches!(
2796            read_static_body(opened, 3, 42).await,
2797            Err(ProtocolError::InvalidMessage(_))
2798        ));
2799    }
2800
2801    /// A resolver's content reaches the wire, and the placeholder does not.
2802    ///
2803    /// The unit tests in `include` cover substitution; this covers the wiring,
2804    /// which is the part that can silently not happen — a resolver configured
2805    /// but never consulted would leave every page looking exactly like the
2806    /// no-resolver case.
2807    #[tokio::test]
2808    async fn a_configured_resolver_substitutes_includes_on_the_wire() {
2809        struct Stories;
2810        impl crate::include::IncludeResolver for Stories {
2811            fn resolve(
2812                &self,
2813                name: &str,
2814                request: &crate::include::IncludeRequest<'_>,
2815            ) -> Option<Vec<dustnet_core::scanner::Token>> {
2816                assert_eq!(request.path, "/index.aml");
2817                (name == "links").then(|| {
2818                    vec![
2819                        dustnet_core::scanner::Token::OpenTag {
2820                            name: "text".into(),
2821                            attributes: Vec::new(),
2822                            self_closing: false,
2823                        },
2824                        dustnet_core::scanner::Token::Text("a generated story".into()),
2825                        dustnet_core::scanner::Token::CloseTag {
2826                            name: "text".into(),
2827                        },
2828                    ]
2829                })
2830            }
2831        }
2832
2833        let directory = tempfile::tempdir().unwrap();
2834        std::fs::write(
2835            directory.path().join("index.aml"),
2836            r#"[page mode=document][include name="links" /][/page]"#,
2837        )
2838        .unwrap();
2839        let config = StaticServerConfig::bind_plaintext_loopback(
2840            directory.path().to_path_buf(),
2841            "127.0.0.1",
2842            0,
2843        )
2844        .await
2845        .unwrap()
2846        .with_include_resolver(Arc::new(Stories));
2847        let address = config.local_addr().unwrap();
2848        let mut server = StaticServer::new(config);
2849        let shutdown = server.shutdown_handle();
2850        let task = tokio::spawn(async move { server.run().await });
2851
2852        let mut client = RawClient::connect(address).await;
2853        client
2854            .send(RawFrame {
2855                msg_type: MessageType::Hello,
2856                flags: 0,
2857                body: b"HELLO/0.2\n".to_vec(),
2858            })
2859            .await;
2860        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
2861        client
2862            .send(RawFrame {
2863                msg_type: MessageType::Get,
2864                flags: 0,
2865                body: b"GET /index.aml\n".to_vec(),
2866            })
2867            .await;
2868
2869        let response = client.receive().await;
2870        assert_eq!(response.msg_type, MessageType::Page);
2871        let body = String::from_utf8(response.body).unwrap();
2872        assert!(body.contains("a generated story"), "{body}");
2873        assert!(
2874            !body.contains("include"),
2875            "the placeholder survived: {body}"
2876        );
2877
2878        drop(client);
2879        shutdown.send(true).unwrap();
2880        task.await.unwrap().unwrap();
2881    }
2882
2883    /// Without a resolver the server is byte-for-byte what it was: the include
2884    /// travels to the client, which renders it as nothing. This is the
2885    /// assertion that `dustnetd` has not quietly become dynamic.
2886    #[tokio::test]
2887    async fn without_a_resolver_includes_are_served_verbatim() {
2888        let source = r#"[page mode=document][include name="links" /][/page]"#;
2889        let directory = tempfile::tempdir().unwrap();
2890        std::fs::write(directory.path().join("index.aml"), source).unwrap();
2891        let config = StaticServerConfig::bind_plaintext_loopback(
2892            directory.path().to_path_buf(),
2893            "127.0.0.1",
2894            0,
2895        )
2896        .await
2897        .unwrap();
2898        let address = config.local_addr().unwrap();
2899        let mut server = StaticServer::new(config);
2900        let shutdown = server.shutdown_handle();
2901        let task = tokio::spawn(async move { server.run().await });
2902
2903        let mut client = RawClient::connect(address).await;
2904        client
2905            .send(RawFrame {
2906                msg_type: MessageType::Hello,
2907                flags: 0,
2908                body: b"HELLO/0.2\n".to_vec(),
2909            })
2910            .await;
2911        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
2912        client
2913            .send(RawFrame {
2914                msg_type: MessageType::Get,
2915                flags: 0,
2916                body: b"GET /index.aml\n".to_vec(),
2917            })
2918            .await;
2919
2920        let response = client.receive().await;
2921        assert_eq!(response.msg_type, MessageType::Page);
2922        assert_eq!(String::from_utf8(response.body).unwrap(), source);
2923
2924        drop(client);
2925        shutdown.send(true).unwrap();
2926        task.await.unwrap().unwrap();
2927    }
2928
2929    /// Without a handler, INPUT is refused exactly as it was before
2930    /// submissions were possible. This is the assertion that `dustnetd` has
2931    /// not quietly gained a write path.
2932    #[tokio::test]
2933    async fn without_a_handler_input_is_still_refused() {
2934        let directory = tempfile::tempdir().unwrap();
2935        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
2936        let config = StaticServerConfig::bind_plaintext_loopback(
2937            directory.path().to_path_buf(),
2938            "127.0.0.1",
2939            0,
2940        )
2941        .await
2942        .unwrap();
2943        let address = config.local_addr().unwrap();
2944        let mut server = StaticServer::new(config);
2945        let shutdown = server.shutdown_handle();
2946        let task = tokio::spawn(async move { server.run().await });
2947
2948        let mut client = RawClient::connect(address).await;
2949        client.send(hello_frame()).await;
2950        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
2951        client
2952            .send(RawFrame {
2953                msg_type: MessageType::Input,
2954                flags: 0,
2955                body: b"INPUT /index\nForm: a=b\n".to_vec(),
2956            })
2957            .await;
2958
2959        let response = client.receive().await;
2960        assert_eq!(response.msg_type, MessageType::Error);
2961        let body = String::from_utf8(response.body).unwrap();
2962        assert!(body.contains("405"), "{body}");
2963
2964        drop(client);
2965        shutdown.send(true).unwrap();
2966        task.await.unwrap().unwrap();
2967    }
2968
2969    /// An accepted submission answers with the page itself, and the handler
2970    /// sees the fields and the action's query.
2971    ///
2972    /// A page rather than a redirect because `validate_redirect_body` requires
2973    /// an absolute `atp://` target — the client parses it rather than resolving
2974    /// it — and a server does not know its own public hostname.
2975    #[tokio::test]
2976    async fn an_accepted_submission_answers_with_the_page() {
2977        struct Accepts;
2978        impl crate::input::InputHandler for Accepts {
2979            fn handle(
2980                &self,
2981                request: &crate::input::InputRequest<'_>,
2982            ) -> crate::input::InputOutcome {
2983                assert_eq!(request.path, "/index");
2984                assert_eq!(request.query, Some("reply=7"));
2985                assert_eq!(request.fields.get("body"), Some("hello world"));
2986                crate::input::InputOutcome::render("/index")
2987            }
2988        }
2989
2990        let directory = tempfile::tempdir().unwrap();
2991        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
2992        let config = StaticServerConfig::bind_plaintext_loopback(
2993            directory.path().to_path_buf(),
2994            "127.0.0.1",
2995            0,
2996        )
2997        .await
2998        .unwrap()
2999        .with_input_handler(Arc::new(Accepts));
3000        let address = config.local_addr().unwrap();
3001        let mut server = StaticServer::new(config);
3002        let shutdown = server.shutdown_handle();
3003        let task = tokio::spawn(async move { server.run().await });
3004
3005        let mut client = RawClient::connect(address).await;
3006        client.send(hello_frame()).await;
3007        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3008        client
3009            .send(RawFrame {
3010                msg_type: MessageType::Input,
3011                flags: 0,
3012                body: b"INPUT /index?reply=7\nForm: body=hello+world\n".to_vec(),
3013            })
3014            .await;
3015
3016        let response = client.receive().await;
3017        assert_eq!(response.msg_type, MessageType::Page);
3018        assert_eq!(String::from_utf8(response.body).unwrap(), "[page][/page]");
3019
3020        drop(client);
3021        shutdown.send(true).unwrap();
3022        task.await.unwrap().unwrap();
3023    }
3024
3025    /// A refusal reaches the person who submitted, with the handler's reason.
3026    #[tokio::test]
3027    async fn a_refused_submission_returns_the_reason() {
3028        struct Refuses;
3029        impl crate::input::InputHandler for Refuses {
3030            fn handle(&self, _: &crate::input::InputRequest<'_>) -> crate::input::InputOutcome {
3031                crate::input::InputOutcome::Rejected("a title is required".into())
3032            }
3033        }
3034
3035        let directory = tempfile::tempdir().unwrap();
3036        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
3037        let config = StaticServerConfig::bind_plaintext_loopback(
3038            directory.path().to_path_buf(),
3039            "127.0.0.1",
3040            0,
3041        )
3042        .await
3043        .unwrap()
3044        .with_input_handler(Arc::new(Refuses));
3045        let address = config.local_addr().unwrap();
3046        let mut server = StaticServer::new(config);
3047        let shutdown = server.shutdown_handle();
3048        let task = tokio::spawn(async move { server.run().await });
3049
3050        let mut client = RawClient::connect(address).await;
3051        client.send(hello_frame()).await;
3052        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3053        client
3054            .send(RawFrame {
3055                msg_type: MessageType::Input,
3056                flags: 0,
3057                body: b"INPUT /index\nForm: title=\n".to_vec(),
3058            })
3059            .await;
3060
3061        let response = client.receive().await;
3062        assert_eq!(response.msg_type, MessageType::Error);
3063        let body = String::from_utf8(response.body).unwrap();
3064        assert!(body.contains("400"), "{body}");
3065        assert!(body.contains("a title is required"), "{body}");
3066
3067        drop(client);
3068        shutdown.send(true).unwrap();
3069        task.await.unwrap().unwrap();
3070    }
3071
3072    /// The token is resolved once and only the identity travels on. This is the
3073    /// property `crate::session` exists for, so it is asserted rather than
3074    /// described: the include resolver is handed the username and has no way to
3075    /// reach the token that produced it.
3076    #[tokio::test]
3077    async fn handlers_receive_an_identity_and_never_the_token() {
3078        use std::sync::atomic::{AtomicBool, Ordering};
3079        static SAW_IDENTITY: AtomicBool = AtomicBool::new(false);
3080
3081        struct Sessions;
3082        impl crate::session::SessionResolver for Sessions {
3083            fn identity(&self, token: &str) -> Option<String> {
3084                (token == "the-secret-token").then(|| "dusty".to_string())
3085            }
3086        }
3087
3088        struct Renders;
3089        impl crate::include::IncludeResolver for Renders {
3090            fn resolve(
3091                &self,
3092                _name: &str,
3093                request: &crate::include::IncludeRequest<'_>,
3094            ) -> Option<Vec<dustnet_core::scanner::Token>> {
3095                assert_eq!(request.identity, Some("dusty"));
3096                SAW_IDENTITY.store(true, Ordering::SeqCst);
3097                Some(vec![dustnet_core::scanner::Token::Text(
3098                    request.identity.unwrap_or("anonymous").to_string(),
3099                )])
3100            }
3101        }
3102
3103        let directory = tempfile::tempdir().unwrap();
3104        std::fs::write(
3105            directory.path().join("index.aml"),
3106            r#"[page mode=document][include name="who" /][/page]"#,
3107        )
3108        .unwrap();
3109        let config = StaticServerConfig::bind_plaintext_loopback(
3110            directory.path().to_path_buf(),
3111            "127.0.0.1",
3112            0,
3113        )
3114        .await
3115        .unwrap()
3116        .with_include_resolver(Arc::new(Renders))
3117        .with_session_resolver(Arc::new(Sessions));
3118        let address = config.local_addr().unwrap();
3119        let mut server = StaticServer::new(config);
3120        let shutdown = server.shutdown_handle();
3121        let task = tokio::spawn(async move { server.run().await });
3122
3123        let mut client = RawClient::connect(address).await;
3124        client.send(hello_frame_with_sessions()).await;
3125        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3126        client
3127            .send(RawFrame {
3128                msg_type: MessageType::Get,
3129                flags: 0,
3130                body: b"GET /index.aml\nSession: the-secret-token\n".to_vec(),
3131            })
3132            .await;
3133
3134        let response = client.receive().await;
3135        assert_eq!(response.msg_type, MessageType::Page);
3136        let body = String::from_utf8(response.body).unwrap();
3137        assert!(SAW_IDENTITY.load(Ordering::SeqCst), "resolver never ran");
3138        assert!(body.contains("dusty"), "{body}");
3139        assert!(
3140            !body.contains("the-secret-token"),
3141            "the token reached the page: {body}"
3142        );
3143
3144        drop(client);
3145        shutdown.send(true).unwrap();
3146        task.await.unwrap().unwrap();
3147    }
3148
3149    /// An unrecognised token is indistinguishable from none. Anything else is
3150    /// an oracle for whether a token ever existed.
3151    #[tokio::test]
3152    async fn an_unrecognised_token_is_anonymous() {
3153        struct NoSessions;
3154        impl crate::session::SessionResolver for NoSessions {
3155            fn identity(&self, _token: &str) -> Option<String> {
3156                None
3157            }
3158        }
3159
3160        struct Renders;
3161        impl crate::include::IncludeResolver for Renders {
3162            fn resolve(
3163                &self,
3164                _name: &str,
3165                request: &crate::include::IncludeRequest<'_>,
3166            ) -> Option<Vec<dustnet_core::scanner::Token>> {
3167                Some(vec![dustnet_core::scanner::Token::Text(
3168                    request.identity.unwrap_or("anonymous").to_string(),
3169                )])
3170            }
3171        }
3172
3173        let directory = tempfile::tempdir().unwrap();
3174        std::fs::write(
3175            directory.path().join("index.aml"),
3176            r#"[page mode=document][include name="who" /][/page]"#,
3177        )
3178        .unwrap();
3179        let config = StaticServerConfig::bind_plaintext_loopback(
3180            directory.path().to_path_buf(),
3181            "127.0.0.1",
3182            0,
3183        )
3184        .await
3185        .unwrap()
3186        .with_include_resolver(Arc::new(Renders))
3187        .with_session_resolver(Arc::new(NoSessions));
3188        let address = config.local_addr().unwrap();
3189        let mut server = StaticServer::new(config);
3190        let shutdown = server.shutdown_handle();
3191        let task = tokio::spawn(async move { server.run().await });
3192
3193        let mut client = RawClient::connect(address).await;
3194        client.send(hello_frame_with_sessions()).await;
3195        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3196        client
3197            .send(RawFrame {
3198                msg_type: MessageType::Get,
3199                flags: 0,
3200                body: b"GET /index.aml\nSession: bogus\n".to_vec(),
3201            })
3202            .await;
3203
3204        let body = String::from_utf8(client.receive().await.body).unwrap();
3205        assert!(body.contains("anonymous"), "{body}");
3206
3207        drop(client);
3208        shutdown.send(true).unwrap();
3209        task.await.unwrap().unwrap();
3210    }
3211
3212    /// A handler granting a session gets its directive onto the wire, with the
3213    /// session flag set so the client parses the metadata block.
3214    #[tokio::test]
3215    async fn an_accepted_submission_can_issue_a_session() {
3216        struct Logs;
3217        impl crate::input::InputHandler for Logs {
3218            fn handle(
3219                &self,
3220                request: &crate::input::InputRequest<'_>,
3221            ) -> crate::input::InputOutcome {
3222                assert!(request.peer.is_loopback(), "peer should be loopback");
3223                crate::input::InputOutcome::render("/index").with_session(
3224                    crate::session::SessionChange::set("issued-token", "/", 1_900_000_000),
3225                )
3226            }
3227        }
3228
3229        let directory = tempfile::tempdir().unwrap();
3230        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
3231        let config = StaticServerConfig::bind_plaintext_loopback(
3232            directory.path().to_path_buf(),
3233            "127.0.0.1",
3234            0,
3235        )
3236        .await
3237        .unwrap()
3238        .with_input_handler(Arc::new(Logs));
3239        let address = config.local_addr().unwrap();
3240        let mut server = StaticServer::new(config);
3241        let shutdown = server.shutdown_handle();
3242        let task = tokio::spawn(async move { server.run().await });
3243
3244        let mut client = RawClient::connect(address).await;
3245        client.send(hello_frame_with_sessions()).await;
3246        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3247        client
3248            .send(RawFrame {
3249                msg_type: MessageType::Input,
3250                flags: 0,
3251                body: b"INPUT /login\nForm: name=dusty\n".to_vec(),
3252            })
3253            .await;
3254
3255        let response = client.receive().await;
3256        assert_eq!(response.msg_type, MessageType::Page);
3257        assert_eq!(response.flags & 0x08, 0x08, "session flag should be set");
3258        let body = String::from_utf8(response.body).unwrap();
3259        assert!(body.contains("Set-Session: issued-token"), "{body}");
3260
3261        drop(client);
3262        shutdown.send(true).unwrap();
3263        task.await.unwrap().unwrap();
3264    }
3265
3266    /// The page answering a login is rendered for the identity the login just
3267    /// granted, not the anonymous one that asked for it. Without this the
3268    /// response carries `Set-Session` and a logged-out nav bar in the same
3269    /// frame, which reads to the person who just typed their password as a
3270    /// login that did not work.
3271    #[tokio::test]
3272    async fn a_granted_session_renders_the_response_for_its_new_identity() {
3273        struct Sessions;
3274        impl crate::session::SessionResolver for Sessions {
3275            fn identity(&self, token: &str) -> Option<String> {
3276                (token == "issued-token").then(|| "dusty".to_string())
3277            }
3278        }
3279
3280        struct Authenticates;
3281        impl crate::input::InputHandler for Authenticates {
3282            fn handle(
3283                &self,
3284                request: &crate::input::InputRequest<'_>,
3285            ) -> crate::input::InputOutcome {
3286                // The submission itself is anonymous: nobody presents a token
3287                // when logging in. This is what makes the assertion below a
3288                // real one.
3289                assert_eq!(request.identity, None);
3290                crate::input::InputOutcome::render("/index").with_session(
3291                    crate::session::SessionChange::set("issued-token", "/", 1_900_000_000),
3292                )
3293            }
3294        }
3295
3296        struct Nav;
3297        impl crate::include::IncludeResolver for Nav {
3298            fn resolve(
3299                &self,
3300                _name: &str,
3301                request: &crate::include::IncludeRequest<'_>,
3302            ) -> Option<Vec<dustnet_core::scanner::Token>> {
3303                Some(vec![dustnet_core::scanner::Token::Text(
3304                    request.identity.unwrap_or("login").to_string(),
3305                )])
3306            }
3307        }
3308
3309        let directory = tempfile::tempdir().unwrap();
3310        std::fs::write(
3311            directory.path().join("index.aml"),
3312            r#"[page mode=document][include name="header" /][/page]"#,
3313        )
3314        .unwrap();
3315        let config = StaticServerConfig::bind_plaintext_loopback(
3316            directory.path().to_path_buf(),
3317            "127.0.0.1",
3318            0,
3319        )
3320        .await
3321        .unwrap()
3322        .with_include_resolver(Arc::new(Nav))
3323        .with_input_handler(Arc::new(Authenticates))
3324        .with_session_resolver(Arc::new(Sessions));
3325        let address = config.local_addr().unwrap();
3326        let mut server = StaticServer::new(config);
3327        let shutdown = server.shutdown_handle();
3328        let task = tokio::spawn(async move { server.run().await });
3329
3330        let mut client = RawClient::connect(address).await;
3331        client.send(hello_frame_with_sessions()).await;
3332        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3333        client
3334            .send(RawFrame {
3335                msg_type: MessageType::Input,
3336                flags: 0,
3337                body: b"INPUT /login\nForm: name=dusty&password=hunter2\n".to_vec(),
3338            })
3339            .await;
3340
3341        let response = client.receive().await;
3342        assert_eq!(response.msg_type, MessageType::Page);
3343        let body = String::from_utf8(response.body).unwrap();
3344        assert!(body.contains("Set-Session: issued-token"), "{body}");
3345        assert!(
3346            body.contains("dusty"),
3347            "the login response should be rendered as dusty: {body}"
3348        );
3349
3350        drop(client);
3351        shutdown.send(true).unwrap();
3352        task.await.unwrap().unwrap();
3353    }
3354
3355    /// A token the resolver does not recognise is anonymous even when a handler
3356    /// is the thing that issued it. The resolver stays the only authority on
3357    /// who a token belongs to — a handler cannot render a page as someone by
3358    /// claiming to have granted them a session.
3359    #[tokio::test]
3360    async fn a_granted_token_the_resolver_rejects_renders_anonymously() {
3361        struct RefusesEverything;
3362        impl crate::session::SessionResolver for RefusesEverything {
3363            fn identity(&self, _token: &str) -> Option<String> {
3364                None
3365            }
3366        }
3367
3368        struct Claims;
3369        impl crate::input::InputHandler for Claims {
3370            fn handle(&self, _: &crate::input::InputRequest<'_>) -> crate::input::InputOutcome {
3371                crate::input::InputOutcome::render("/index").with_session(
3372                    crate::session::SessionChange::set("forged", "/", 1_900_000_000),
3373                )
3374            }
3375        }
3376
3377        struct Nav;
3378        impl crate::include::IncludeResolver for Nav {
3379            fn resolve(
3380                &self,
3381                _name: &str,
3382                request: &crate::include::IncludeRequest<'_>,
3383            ) -> Option<Vec<dustnet_core::scanner::Token>> {
3384                Some(vec![dustnet_core::scanner::Token::Text(
3385                    request.identity.unwrap_or("anonymous").to_string(),
3386                )])
3387            }
3388        }
3389
3390        let directory = tempfile::tempdir().unwrap();
3391        std::fs::write(
3392            directory.path().join("index.aml"),
3393            r#"[page mode=document][include name="header" /][/page]"#,
3394        )
3395        .unwrap();
3396        let config = StaticServerConfig::bind_plaintext_loopback(
3397            directory.path().to_path_buf(),
3398            "127.0.0.1",
3399            0,
3400        )
3401        .await
3402        .unwrap()
3403        .with_include_resolver(Arc::new(Nav))
3404        .with_input_handler(Arc::new(Claims))
3405        .with_session_resolver(Arc::new(RefusesEverything));
3406        let address = config.local_addr().unwrap();
3407        let mut server = StaticServer::new(config);
3408        let shutdown = server.shutdown_handle();
3409        let task = tokio::spawn(async move { server.run().await });
3410
3411        let mut client = RawClient::connect(address).await;
3412        client.send(hello_frame_with_sessions()).await;
3413        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3414        client
3415            .send(RawFrame {
3416                msg_type: MessageType::Input,
3417                flags: 0,
3418                body: b"INPUT /login\nForm: name=dusty\n".to_vec(),
3419            })
3420            .await;
3421
3422        let response = client.receive().await;
3423        assert_eq!(response.msg_type, MessageType::Page);
3424        let body = String::from_utf8(response.body).unwrap();
3425        assert!(body.contains("anonymous"), "{body}");
3426
3427        drop(client);
3428        shutdown.send(true).unwrap();
3429        task.await.unwrap().unwrap();
3430    }
3431
3432    /// A submission's answer names the page it actually is. Without this the
3433    /// client keeps the path it submitted to as its location, so a login shows
3434    /// the front page but reloads back into the login form.
3435    #[tokio::test]
3436    async fn an_accepted_submission_names_the_page_it_answers_with() {
3437        struct SendsElsewhere;
3438        impl crate::input::InputHandler for SendsElsewhere {
3439            fn handle(&self, _: &crate::input::InputRequest<'_>) -> crate::input::InputOutcome {
3440                crate::input::InputOutcome::render("/index")
3441            }
3442        }
3443
3444        let directory = tempfile::tempdir().unwrap();
3445        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
3446        let config = StaticServerConfig::bind_plaintext_loopback(
3447            directory.path().to_path_buf(),
3448            "127.0.0.1",
3449            0,
3450        )
3451        .await
3452        .unwrap()
3453        .with_input_handler(Arc::new(SendsElsewhere));
3454        let address = config.local_addr().unwrap();
3455        let mut server = StaticServer::new(config);
3456        let shutdown = server.shutdown_handle();
3457        let task = tokio::spawn(async move { server.run().await });
3458
3459        let mut client = RawClient::connect(address).await;
3460        client.send(hello_frame_with_sessions_and_page_path()).await;
3461        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3462        client
3463            .send(RawFrame {
3464                msg_type: MessageType::Input,
3465                flags: 0,
3466                body: b"INPUT /login\nForm: name=dusty\n".to_vec(),
3467            })
3468            .await;
3469
3470        let response = client.receive().await;
3471        assert_eq!(response.msg_type, MessageType::Page);
3472        assert_eq!(response.flags & 0x04, 0x04, "path flag should be set");
3473        let body = String::from_utf8(response.body).unwrap();
3474        assert!(body.starts_with("Path: /index\n"), "{body}");
3475
3476        drop(client);
3477        shutdown.send(true).unwrap();
3478        task.await.unwrap().unwrap();
3479    }
3480
3481    /// A submission's answer carries the query too. A comment posted on a story
3482    /// is answered with that story, and a location that dropped the `item`
3483    /// would reload as the front page.
3484    #[tokio::test]
3485    async fn a_named_page_keeps_its_query() {
3486        struct SendsToAStory;
3487        impl crate::input::InputHandler for SendsToAStory {
3488            fn handle(&self, _: &crate::input::InputRequest<'_>) -> crate::input::InputOutcome {
3489                crate::input::InputOutcome::render_query("/index", "item=12")
3490            }
3491        }
3492
3493        let directory = tempfile::tempdir().unwrap();
3494        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
3495        let config = StaticServerConfig::bind_plaintext_loopback(
3496            directory.path().to_path_buf(),
3497            "127.0.0.1",
3498            0,
3499        )
3500        .await
3501        .unwrap()
3502        .with_input_handler(Arc::new(SendsToAStory));
3503        let address = config.local_addr().unwrap();
3504        let mut server = StaticServer::new(config);
3505        let shutdown = server.shutdown_handle();
3506        let task = tokio::spawn(async move { server.run().await });
3507
3508        let mut client = RawClient::connect(address).await;
3509        client.send(hello_frame_with_sessions_and_page_path()).await;
3510        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3511        client
3512            .send(RawFrame {
3513                msg_type: MessageType::Input,
3514                flags: 0,
3515                body: b"INPUT /index\nForm: text=hello\n".to_vec(),
3516            })
3517            .await;
3518
3519        let response = client.receive().await;
3520        assert_eq!(response.msg_type, MessageType::Page);
3521        let body = String::from_utf8(response.body).unwrap();
3522        assert!(body.starts_with("Path: /index?item=12\n"), "{body}");
3523
3524        drop(client);
3525        shutdown.send(true).unwrap();
3526        task.await.unwrap().unwrap();
3527    }
3528
3529    /// A client that never offered `page-path` still gets its page. The
3530    /// capability gate refuses a frame needing a capability the peer did not
3531    /// negotiate, so a server that attached the field regardless would answer
3532    /// an older client with nothing at all.
3533    #[tokio::test]
3534    async fn a_client_without_the_capability_gets_an_unnamed_page() {
3535        struct SendsElsewhere;
3536        impl crate::input::InputHandler for SendsElsewhere {
3537            fn handle(&self, _: &crate::input::InputRequest<'_>) -> crate::input::InputOutcome {
3538                crate::input::InputOutcome::render("/index")
3539            }
3540        }
3541
3542        let directory = tempfile::tempdir().unwrap();
3543        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
3544        let config = StaticServerConfig::bind_plaintext_loopback(
3545            directory.path().to_path_buf(),
3546            "127.0.0.1",
3547            0,
3548        )
3549        .await
3550        .unwrap()
3551        .with_input_handler(Arc::new(SendsElsewhere));
3552        let address = config.local_addr().unwrap();
3553        let mut server = StaticServer::new(config);
3554        let shutdown = server.shutdown_handle();
3555        let task = tokio::spawn(async move { server.run().await });
3556
3557        let mut client = RawClient::connect(address).await;
3558        client.send(hello_frame()).await;
3559        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3560        client
3561            .send(RawFrame {
3562                msg_type: MessageType::Input,
3563                flags: 0,
3564                body: b"INPUT /login\nForm: name=dusty\n".to_vec(),
3565            })
3566            .await;
3567
3568        let response = client.receive().await;
3569        assert_eq!(response.msg_type, MessageType::Page);
3570        assert_eq!(response.flags & 0x04, 0, "path flag must not be set");
3571        let body = String::from_utf8(response.body).unwrap();
3572        assert!(!body.contains("Path: "), "{body}");
3573        assert!(body.starts_with("[page]"), "{body}");
3574
3575        drop(client);
3576        shutdown.send(true).unwrap();
3577        task.await.unwrap().unwrap();
3578    }
3579
3580    /// A GET is answered without a `Path`. The client asked for that path and
3581    /// already knows it; spending the bytes on every page to say so again would
3582    /// be a field that only ever repeats the request.
3583    #[tokio::test]
3584    async fn a_get_is_not_named() {
3585        let directory = tempfile::tempdir().unwrap();
3586        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
3587        let config = StaticServerConfig::bind_plaintext_loopback(
3588            directory.path().to_path_buf(),
3589            "127.0.0.1",
3590            0,
3591        )
3592        .await
3593        .unwrap();
3594        let address = config.local_addr().unwrap();
3595        let mut server = StaticServer::new(config);
3596        let shutdown = server.shutdown_handle();
3597        let task = tokio::spawn(async move { server.run().await });
3598
3599        let mut client = RawClient::connect(address).await;
3600        client.send(hello_frame_with_sessions_and_page_path()).await;
3601        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3602        client
3603            .send(RawFrame {
3604                msg_type: MessageType::Get,
3605                flags: 0,
3606                body: b"GET /index.aml\n".to_vec(),
3607            })
3608            .await;
3609
3610        let response = client.receive().await;
3611        assert_eq!(response.msg_type, MessageType::Page);
3612        assert_eq!(response.flags & 0x04, 0, "a GET needs no Path");
3613
3614        drop(client);
3615        shutdown.send(true).unwrap();
3616        task.await.unwrap().unwrap();
3617    }
3618
3619    /// A resolver can produce more than a page may carry. The server refuses
3620    /// rather than truncating: half a page is a worse answer than an error
3621    /// naming the cause, and a silently truncated page is malformed AML.
3622    #[tokio::test]
3623    async fn an_oversized_resolved_page_is_refused_not_truncated() {
3624        struct Floods;
3625        impl crate::include::IncludeResolver for Floods {
3626            fn resolve(
3627                &self,
3628                _name: &str,
3629                _request: &crate::include::IncludeRequest<'_>,
3630            ) -> Option<Vec<dustnet_core::scanner::Token>> {
3631                // Comfortably past MAX_PAGE_MESSAGE_SIZE once serialized.
3632                Some(vec![dustnet_core::scanner::Token::Text(
3633                    "x".repeat(MAX_PAGE_MESSAGE_SIZE + 1024),
3634                )])
3635            }
3636        }
3637
3638        let directory = tempfile::tempdir().unwrap();
3639        std::fs::write(
3640            directory.path().join("index.aml"),
3641            r#"[page mode=document][include name="flood" /][/page]"#,
3642        )
3643        .unwrap();
3644        let config = StaticServerConfig::bind_plaintext_loopback(
3645            directory.path().to_path_buf(),
3646            "127.0.0.1",
3647            0,
3648        )
3649        .await
3650        .unwrap()
3651        .with_include_resolver(Arc::new(Floods));
3652        let address = config.local_addr().unwrap();
3653        let mut server = StaticServer::new(config);
3654        let shutdown = server.shutdown_handle();
3655        let task = tokio::spawn(async move { server.run().await });
3656
3657        let mut client = RawClient::connect(address).await;
3658        client.send(hello_frame()).await;
3659        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
3660        client
3661            .send(RawFrame {
3662                msg_type: MessageType::Get,
3663                flags: 0,
3664                body: b"GET /index.aml\n".to_vec(),
3665            })
3666            .await;
3667
3668        let response = client.receive().await;
3669        assert_eq!(response.msg_type, MessageType::Error);
3670        let body = String::from_utf8(response.body).unwrap();
3671        assert!(body.contains("500"), "{body}");
3672        assert!(
3673            body.len() <= dustnet_core::protocol::MAX_CONTROL_MESSAGE_SIZE,
3674            "the refusal itself must stay bounded"
3675        );
3676
3677        drop(client);
3678        shutdown.send(true).unwrap();
3679        task.await.unwrap().unwrap();
3680    }
3681}