lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

websocket.rs (6959B)


      1 //! Byte I/O for a shared protocol session. Hosts own sockets; protocol adapters
      2 //! own sessions, destination authority, ingress budgets and exact publication.
      3 
      4 use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec};
      5 use core::{fmt, future::Future, net::IpAddr, pin::Pin, task::Context, time::Duration};
      6 
      7 /// Owned channel futures may cross threads. Browser implementations keep DOM
      8 /// objects in their origin-thread actor and return only safe message handles.
      9 /// This bound does not apply to application or browser session futures.
     10 pub type IoFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
     11 
     12 /// Bounded failures retain no provider errors, destinations or wire content.
     13 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
     14 #[non_exhaustive]
     15 pub enum Error {
     16     /// Explicit destination or ingress authority refused the effect.
     17     Policy,
     18     /// DNS, TCP, TLS or the WebSocket handshake could not complete.
     19     Unavailable,
     20     /// The original connection deadline elapsed.
     21     Timeout,
     22     /// The connection no longer admits I/O.
     23     Closed,
     24     /// The peer or caller supplied an invalid or oversized frame.
     25     Protocol,
     26     /// This host cannot perform the requested operation.
     27     Unsupported,
     28 }
     29 
     30 impl fmt::Display for Error {
     31     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
     32         formatter.write_str(match self {
     33             Self::Policy => "socket authority denied",
     34             Self::Unavailable => "socket connection unavailable",
     35             Self::Timeout => "socket connection deadline elapsed",
     36             Self::Closed => "socket connection closed",
     37             Self::Protocol => "socket frame refused",
     38             Self::Unsupported => "socket operation unsupported",
     39         })
     40     }
     41 }
     42 
     43 impl std::error::Error for Error {}
     44 
     45 /// Original close code and reason. Debug formatting omits peer text.
     46 #[derive(Clone, Eq, PartialEq)]
     47 pub struct CloseFrame {
     48     /// WebSocket close code.
     49     pub code: u16,
     50     /// Uninterpreted peer close reason.
     51     pub reason: String,
     52 }
     53 
     54 impl fmt::Debug for CloseFrame {
     55     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
     56         formatter
     57             .debug_struct("CloseFrame")
     58             .field("code", &self.code)
     59             .finish_non_exhaustive()
     60     }
     61 }
     62 
     63 /// Original message bytes; the host never parses or reserializes protocol data.
     64 #[derive(Clone, Eq, PartialEq)]
     65 #[non_exhaustive]
     66 pub enum Frame {
     67     /// UTF-8 message bytes, including original whitespace and member order.
     68     Text(String),
     69     /// Original binary message bytes.
     70     Binary(Vec<u8>),
     71     /// Native control frame; browsers do not expose this operation.
     72     Ping(Vec<u8>),
     73     /// Native control frame; browsers do not expose this operation.
     74     Pong(Vec<u8>),
     75     /// Peer close information, when available.
     76     Close(Option<CloseFrame>),
     77 }
     78 
     79 impl fmt::Debug for Frame {
     80     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
     81         formatter.write_str(match self {
     82             Self::Text(_) => "Frame::Text([redacted])",
     83             Self::Binary(_) => "Frame::Binary([redacted])",
     84             Self::Ping(_) => "Frame::Ping([redacted])",
     85             Self::Pong(_) => "Frame::Pong([redacted])",
     86             Self::Close(_) => "Frame::Close([redacted])",
     87         })
     88     }
     89 }
     90 
     91 /// One connection's original destination and revocable ingress authority.
     92 /// Implementations must not create fresh grants or reset a shared budget.
     93 pub trait Admission: Send + Sync {
     94     /// Checks each DNS result before any address is connected.
     95     fn permits_address(&self, address: IpAddr) -> bool;
     96     /// Checks read authority and registers the current reader for revocation.
     97     fn admitted_read(&self, context: &Context<'_>) -> bool;
     98     /// Checks write authority and registers the writer for revocation.
     99     fn admitted_write(&self, context: &Context<'_>) -> bool;
    100     /// Charges actual bytes, frame starts and data-message starts before decode.
    101     /// A refusal is sticky within this connection's original shared budget.
    102     fn charge(&self, bytes: usize, frames: usize, data_messages: usize) -> bool;
    103 }
    104 
    105 /// A concrete host connection. The shared protocol adapter owns serialization,
    106 /// session membership, reconnect policy and acknowledgement correlation.
    107 pub trait Socket: Send + Sync {
    108     /// Sends the original frame under the connection's frozen limits.
    109     fn send(&self, frame: Frame) -> IoFuture<'_, Result<(), Error>>;
    110     /// Receives one frame, or confirms the end of this connection's stream.
    111     fn receive(&self) -> IoFuture<'_, Result<Option<Frame>, Error>>;
    112     /// Closes this original connection; it never switches to a replacement.
    113     fn close(&self) -> IoFuture<'_, Result<(), Error>>;
    114 }
    115 
    116 /// Supplies concrete I/O to one existing protocol-session owner. Construction
    117 /// and unpolled connection futures must be inert. A failed or cancelled attempt
    118 /// must dispose its own socket and callbacks without authorizing a retry.
    119 pub trait Connector: fmt::Debug + Send + Sync {
    120     /// Whether the host exposes native ping/pong control frames.
    121     fn supports_ping(&self) -> bool;
    122     /// Revalidates the endpoint and every resolved address before I/O. Native
    123     /// hosts meter plaintext before framing; browser hosts must describe their
    124     /// actual platform admission boundary rather than claiming native controls.
    125     fn connect<'a>(
    126         &'a self,
    127         endpoint: &'a str,
    128         timeout: Duration,
    129         max_message_bytes: core::num::NonZeroUsize,
    130         admission: Arc<dyn Admission>,
    131     ) -> IoFuture<'a, Result<Arc<dyn Socket>, Error>>;
    132 }
    133 
    134 #[cfg(test)]
    135 mod tests {
    136     use super::*;
    137     use alloc::format;
    138 
    139     #[test]
    140     fn frame_diagnostics_never_retain_or_print_wire_credentials_or_peer_text() {
    141         let secret = "private_wire_value_that_must_not_appear";
    142         let close = CloseFrame {
    143             code: 1000,
    144             reason: secret.into(),
    145         };
    146         assert!(!format!("{close:?}").contains(secret));
    147         for frame in [
    148             Frame::Text(secret.into()),
    149             Frame::Binary(secret.as_bytes().into()),
    150             Frame::Ping(secret.as_bytes().into()),
    151             Frame::Pong(secret.as_bytes().into()),
    152             Frame::Close(Some(close)),
    153             Frame::Close(None),
    154         ] {
    155             let debug = format!("{frame:?}");
    156             assert!(!debug.contains(secret));
    157             assert!(debug.contains("[redacted]"));
    158             assert!(debug.len() < 64);
    159         }
    160     }
    161 
    162     #[test]
    163     fn io_failures_have_bounded_diagnostics_and_no_provider_error_chain() {
    164         use std::error::Error as _;
    165         for error in [
    166             Error::Policy,
    167             Error::Unavailable,
    168             Error::Timeout,
    169             Error::Closed,
    170             Error::Protocol,
    171             Error::Unsupported,
    172         ] {
    173             assert!(error.source().is_none());
    174             let text = format!("{error}");
    175             assert!(!text.is_empty() && text.len() < 64);
    176         }
    177     }
    178 }