Skip to main content

hyprstream_rpc/transport/
zmtp_quic.rs

1//! ZMTP 3.1 over QUIC transport implementation.
2//!
3//! This module implements ZMTP (ZeroMQ Message Transport Protocol) version 3.1
4//! running over QUIC streams. QUIC provides TLS 1.3 encryption at the transport
5//! layer, so the ZMTP handshake uses the NULL mechanism (CurveZMQ not needed).
6//!
7//! # Protocol Mapping
8//!
9//! ```text
10//! TCP connection     → QUIC connection (+ TLS 1.3)
11//! TCP byte stream    → Single QUIC bidirectional stream (ordered, reliable)
12//! ZMTP greeting      → Sent as first 64 bytes on the QUIC stream
13//! ZMTP handshake     → NULL mechanism (TLS handles encryption)
14//! ZMTP message frames → Identical framing on the QUIC stream
15//! ```
16//!
17//! # ZMTP Frame Format
18//!
19//! ```text
20//! Flags (1 byte):
21//!   Bit 0 (LSB): MORE — 1 if more frames follow, 0 if last frame
22//!   Bit 1:       LONG — 1 if size is 8-byte uint64, 0 if size is 1-byte uint8
23//!   Bit 2:       COMMAND — 1 = command frame, 0 = message frame
24//!   Bits 3-7:    Reserved (must be 0)
25//!
26//! Size:
27//!   LONG=0: 1 byte  (uint8, frames 0–255 bytes)
28//!   LONG=1: 8 bytes (uint64 big-endian, frames up to 2^64 bytes)
29//!
30//! Body: exactly `size` bytes
31//! ```
32
33use anyhow::{anyhow, bail, ensure, Result};
34use bytes::Bytes;
35use std::net::SocketAddr;
36use std::rc::Rc;
37use std::sync::Arc;
38use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf};
39use tokio::sync::Notify;
40use tracing::{debug, error, trace};
41
42// Re-export pure framing types from zmtp_framing (single source of truth).
43use crate::zmtp_framing;
44pub use crate::zmtp_framing::{
45    ZmqSocketType, GREETING_SIZE, MECHANISM_NULL, ZMTP_VERSION_MAJOR, ZMTP_VERSION_MINOR,
46};
47
48/// ALPN protocol identifier for ZMTP over QUIC.
49pub const ALPN_ZMTP3: &[u8] = b"zmtp3";
50
51/// A parsed ZMTP frame (with `Bytes` data for async I/O efficiency).
52#[derive(Debug, Clone)]
53pub struct ZmtpFrame {
54    pub more: bool,
55    pub command: bool,
56    pub data: Bytes,
57}
58
59#[cfg(test)]
60impl ZmtpFrame {
61    /// Convert from the owned framing type.
62    fn from_owned(f: zmtp_framing::ZmtpFrame) -> Self {
63        Self {
64            more: f.more,
65            command: f.command,
66            data: Bytes::from(f.data),
67        }
68    }
69}
70
71/// A parsed ZMTP command (with `Bytes` body for async I/O efficiency).
72#[derive(Debug, Clone)]
73pub struct ZmtpCommand {
74    pub name: String,
75    pub body: Bytes,
76}
77
78impl ZmtpCommand {
79    /// Convert from the owned framing type.
80    fn from_owned(c: zmtp_framing::ZmtpCommand) -> Self {
81        Self {
82            name: c.name,
83            body: Bytes::from(c.body),
84        }
85    }
86}
87
88/// ZMTP 3.1 framing over a byte stream.
89///
90/// Transport-only — no socket type semantics. Socket semantics live in
91/// QuicReq/QuicRep/etc.
92pub struct ZmtpStream<S> {
93    stream: S,
94}
95
96impl<S: AsyncRead + AsyncWrite + Unpin> ZmtpStream<S> {
97    /// Create a new ZMTP stream wrapper.
98    pub fn new(stream: S) -> Self {
99        Self { stream }
100    }
101
102    /// Perform ZMTP greeting + NULL mechanism handshake.
103    ///
104    /// # Arguments
105    ///
106    /// * `socket_type` - The ZMQ socket type (sent in READY metadata)
107    /// * `is_server` - Whether this side is the server (affects READY order)
108    ///
109    /// # NULL Handshake Sequence (RFC 37)
110    ///
111    /// 1. Both sides send 64-byte greeting (can overlap)
112    /// 2. Both sides read and validate peer greeting
113    /// 3. CLIENT sends READY command first
114    /// 4. Server reads client READY, validates, then sends READY
115    pub async fn handshake(&mut self, socket_type: ZmqSocketType, is_server: bool) -> Result<()> {
116        // 1. Build and send greeting (delegates to zmtp_framing)
117        let greeting = zmtp_framing::build_greeting();
118        self.stream.write_all(&greeting).await?;
119
120        // 2. Read peer greeting
121        let mut peer_greeting = [0u8; GREETING_SIZE];
122        self.stream.read_exact(&mut peer_greeting).await?;
123        zmtp_framing::validate_greeting(&peer_greeting)?;
124
125        // 3. Asymmetric READY exchange (RFC 37: client sends first)
126        let ready_metadata = zmtp_framing::build_ready_metadata(socket_type);
127
128        if !is_server {
129            self.send_command("READY", &ready_metadata).await?;
130            let cmd = self.recv_command().await?;
131            zmtp_framing::validate_ready_command(&zmtp_framing::ZmtpCommand {
132                name: cmd.name.clone(),
133                body: cmd.body.to_vec(),
134            })?;
135        } else {
136            let cmd = self.recv_command().await?;
137            zmtp_framing::validate_ready_command(&zmtp_framing::ZmtpCommand {
138                name: cmd.name.clone(),
139                body: cmd.body.to_vec(),
140            })?;
141            self.send_command("READY", &ready_metadata).await?;
142        }
143
144        debug!(socket_type = ?socket_type, is_server, "ZMTP handshake complete");
145        Ok(())
146    }
147
148    /// Receive one ZMTP frame (message or command).
149    pub async fn recv_frame(&mut self) -> Result<ZmtpFrame> {
150        // Read flags byte
151        let mut flags_buf = [0u8; 1];
152        self.stream.read_exact(&mut flags_buf).await?;
153        let flags = flags_buf[0];
154
155        let more = (flags & 0x01) != 0;
156        let long = (flags & 0x02) != 0;
157        let command = (flags & 0x04) != 0;
158
159        // Validate reserved bits
160        ensure!(
161            flags & 0xF8 == 0,
162            "ZMTP frame has reserved bits set: 0x{:02X}",
163            flags
164        );
165
166        // Read size
167        let size: usize = if long {
168            let mut buf = [0u8; 8];
169            self.stream.read_exact(&mut buf).await?;
170            let raw_size = u64::from_be_bytes(buf);
171            ensure!(
172                raw_size <= crate::zmtp_framing::MAX_FRAME_SIZE as u64,
173                "frame size {} exceeds maximum {}",
174                raw_size,
175                crate::zmtp_framing::MAX_FRAME_SIZE
176            );
177            raw_size as usize
178        } else {
179            let mut buf = [0u8; 1];
180            self.stream.read_exact(&mut buf).await?;
181            buf[0] as usize
182        };
183
184        // Read body
185        let mut data = vec![0u8; size];
186        self.stream.read_exact(&mut data).await?;
187
188        trace!(more, command, size, "Received ZMTP frame");
189
190        Ok(ZmtpFrame {
191            more,
192            command,
193            data: Bytes::from(data),
194        })
195    }
196
197    /// Receive a command frame specifically (validates COMMAND bit set, MORE=0).
198    pub async fn recv_command(&mut self) -> Result<ZmtpCommand> {
199        let frame = self.recv_frame().await?;
200
201        ensure!(frame.command, "Expected command frame, got message frame");
202        ensure!(!frame.more, "Command frames must have MORE=0");
203
204        ZmtpCommand::parse(&frame.data)
205    }
206
207    /// Send a ZMTP command frame (COMMAND bit set, MORE=0).
208    ///
209    /// Delegates to `zmtp_framing::encode_command` for single source of truth.
210    pub async fn send_command(&mut self, name: &str, body: &[u8]) -> Result<()> {
211        let encoded = crate::zmtp_framing::encode_command(name, body);
212        self.stream.write_all(&encoded).await?;
213        trace!(name, body_len = body.len(), "Sent ZMTP command");
214        Ok(())
215    }
216
217    /// Send one ZMTP message frame (COMMAND=0).
218    ///
219    /// Delegates to `zmtp_framing::encode_frame` for single source of truth.
220    pub async fn send_frame(&mut self, more: bool, data: &[u8]) -> Result<()> {
221        let encoded = crate::zmtp_framing::encode_frame(more, false, data);
222        self.stream.write_all(&encoded).await?;
223        trace!(more, size = data.len(), "Sent ZMTP frame");
224        Ok(())
225    }
226
227    /// Send one ZMQ multipart message using ZMTP flags.
228    pub async fn send_multipart(&mut self, parts: &[Bytes]) -> Result<()> {
229        for (i, part) in parts.iter().enumerate() {
230            let more = i < parts.len() - 1;
231            self.send_frame(more, part).await?;
232        }
233        trace!(num_parts = parts.len(), "Sent multipart message");
234        Ok(())
235    }
236
237    /// Receive one ZMQ multipart message, assembling frames via MORE flag.
238    pub async fn recv_multipart(&mut self) -> Result<Multipart> {
239        let mut parts = Vec::new();
240
241        loop {
242            let frame = self.recv_frame().await?;
243
244            // Message frames shouldn't have COMMAND bit set
245            if frame.command {
246                bail!("Received unexpected command frame in message stream");
247            }
248
249            let more = frame.more;
250            parts.push(frame.data);
251
252            if !more {
253                break;
254            }
255        }
256
257        trace!(num_parts = parts.len(), "Received multipart message");
258        Ok(Multipart { parts })
259    }
260}
261
262// Greeting, metadata, and command functions are now in crate::zmtp_framing.
263// ZmtpStream delegates to those pure functions for encoding/decoding.
264
265impl ZmtpCommand {
266    /// Parse a command from frame body data.
267    pub fn parse(data: &[u8]) -> Result<Self> {
268        let owned = zmtp_framing::ZmtpCommand::parse(data)?;
269        Ok(Self::from_owned(owned))
270    }
271}
272
273/// ZMQ multipart message (owned).
274#[derive(Debug, Clone, Default)]
275pub struct Multipart {
276    /// Message parts.
277    pub parts: Vec<Bytes>,
278}
279
280impl Multipart {
281    /// Create an empty multipart message.
282    pub fn new() -> Self {
283        Self { parts: Vec::new() }
284    }
285
286    /// Create a multipart message from parts.
287    pub fn from_parts(parts: Vec<Bytes>) -> Self {
288        Self { parts }
289    }
290
291    /// Add a part to the message.
292    pub fn push(&mut self, part: Bytes) {
293        self.parts.push(part);
294    }
295
296    /// Check if empty.
297    pub fn is_empty(&self) -> bool {
298        self.parts.is_empty()
299    }
300
301    /// Get number of parts.
302    pub fn len(&self) -> usize {
303        self.parts.len()
304    }
305}
306
307// ============================================================================
308// QUIC Socket Types (server-side)
309// ============================================================================
310
311fn owned_quic_server_config(tls: rustls::ServerConfig) -> Result<quinn::ServerConfig> {
312    crate::transport::pq_provider::validate_internal_mesh_crypto_provider(tls.crypto_provider())?;
313    Ok(quinn::ServerConfig::with_crypto(Arc::new(
314        quinn::crypto::rustls::QuicServerConfig::try_from(tls)?,
315    )))
316}
317
318fn owned_quic_client_config(tls: rustls::ClientConfig) -> Result<quinn::ClientConfig> {
319    crate::transport::pq_provider::validate_internal_mesh_crypto_provider(tls.crypto_provider())?;
320    Ok(quinn::ClientConfig::new(Arc::new(
321        quinn::crypto::rustls::QuicClientConfig::try_from(tls)?,
322    )))
323}
324
325/// Server-side REP socket over QUIC.
326///
327/// Accepts QUIC connections; each connection carries one ZmtpStream for ZMTP exchange.
328/// QuicRep enforces the REP state machine (recv then send alternation).
329pub struct QuicRep {
330    endpoint: quinn::Endpoint,
331}
332
333impl QuicRep {
334    /// Bind a QUIC REP socket to the given address.
335    ///
336    /// # Arguments
337    ///
338    /// * `addr` - Socket address to bind to
339    /// * `tls` - TLS server configuration
340    pub fn bind(addr: SocketAddr, tls: rustls::ServerConfig) -> Result<Self> {
341        let endpoint = quinn::Endpoint::server(owned_quic_server_config(tls)?, addr)?;
342
343        Ok(Self { endpoint })
344    }
345
346    /// Get the local address this socket is bound to.
347    pub fn local_addr(&self) -> Result<SocketAddr> {
348        self.endpoint
349            .local_addr()
350            .map_err(|e| anyhow!("Failed to get local address: {}", e))
351    }
352
353    /// Accept loop: accepts incoming connections and handles them.
354    ///
355    /// Each incoming QUIC connection can have multiple bidi streams, each
356    /// representing one REQ/REP exchange.
357    ///
358    /// # Arguments
359    ///
360    /// * `handler` - Async function to handle each request
361    /// * `shutdown` - Shutdown signal
362    pub async fn accept_loop<H, Fut>(&self, handler: H, shutdown: Arc<Notify>) -> Result<()>
363    where
364        H: Fn(Multipart) -> Fut + Clone + Send + 'static,
365        Fut: std::future::Future<Output = Result<Multipart>> + Send,
366    {
367        loop {
368            tokio::select! {
369                Some(incoming) = self.endpoint.accept() => {
370                    let handler = handler.clone();
371                    tokio::spawn(async move {
372                        match incoming.await {
373                            Ok(conn) => {
374                                if let Err(e) = Self::handle_connection(conn, handler).await {
375                                    error!("Connection error: {}", e);
376                                }
377                            }
378                            Err(e) => {
379                                error!("Incoming connection failed: {}", e);
380                            }
381                        }
382                    });
383                }
384                _ = shutdown.notified() => {
385                    debug!("QUIC accept loop shutting down");
386                    break;
387                }
388            }
389        }
390
391        // Graceful shutdown: wait for connections to drain
392        self.endpoint.wait_idle().await;
393        Ok(())
394    }
395
396    /// Accept loop for RequestService handlers.
397    ///
398    /// This variant handles the full envelope processing pipeline:
399    /// 1. ZMTP handshake
400    /// 2. SignedEnvelope verification
401    /// 3. Service handle_request dispatch
402    /// 4. Signed response serialization
403    ///
404    /// Uses `spawn_local` because `RequestService` is `?Send`.
405    ///
406    /// # Arguments
407    ///
408    /// * `service` - RequestService implementation (wrapped in Rc)
409    /// * `server_pubkey` - Server's Ed25519 verifying key
410    /// * `signing_key` - Server's Ed25519 signing key
411    /// * `nonce_cache` - Nonce cache for replay protection (wrapped in Arc)
412    /// * `shutdown` - Shutdown signal
413    pub async fn accept_loop_service<S>(
414        &self,
415        service: Rc<S>,
416        server_pubkey: ed25519_dalek::VerifyingKey,
417        signing_key: ed25519_dalek::SigningKey,
418        nonce_cache: Arc<crate::envelope::InMemoryNonceCache>,
419        shutdown: Arc<Notify>,
420    ) -> Result<()>
421    where
422        S: crate::service::RequestService + 'static,
423    {
424        loop {
425            tokio::select! {
426                Some(incoming) = self.endpoint.accept() => {
427                    let service = Rc::clone(&service);
428                    let nonce_cache = Arc::clone(&nonce_cache);
429                    let signing_key = signing_key.clone();  // Clone before spawn
430
431                    // Use spawn_local because RequestService is ?Send
432                    tokio::task::spawn_local(async move {
433                        match incoming.await {
434                            Ok(conn) => {
435                                if let Err(e) = Self::handle_connection_service(
436                                    conn,
437                                    service,
438                                    server_pubkey,
439                                    signing_key,
440                                    nonce_cache,
441                                ).await {
442                                    error!("Connection error: {}", e);
443                                }
444                            }
445                            Err(e) => {
446                                error!("Incoming connection failed: {}", e);
447                            }
448                        }
449                    });
450                }
451                _ = shutdown.notified() => {
452                    debug!("QUIC accept loop shutting down");
453                    break;
454                }
455            }
456        }
457
458        // Graceful shutdown: wait for connections to drain
459        self.endpoint.wait_idle().await;
460        Ok(())
461    }
462
463    async fn handle_connection_service<S>(
464        conn: quinn::Connection,
465        service: Rc<S>,
466        server_pubkey: ed25519_dalek::VerifyingKey,
467        signing_key: ed25519_dalek::SigningKey,
468        nonce_cache: Arc<crate::envelope::InMemoryNonceCache>,
469    ) -> Result<()>
470    where
471        S: crate::service::RequestService + 'static,
472    {
473        let remote = conn.remote_address();
474        debug!(?remote, "QUIC connection established");
475
476        loop {
477            // Accept bidi streams from this connection (one per REQ/REP exchange)
478            match conn.accept_bi().await {
479                Ok((send, recv)) => {
480                    let service = Rc::clone(&service);
481                    let nonce_cache = Arc::clone(&nonce_cache);
482                    let signing_key = signing_key.clone(); // Clone before spawn
483
484                    tokio::task::spawn_local(async move {
485                        if let Err(e) = Self::handle_stream_service(
486                            send,
487                            recv,
488                            service,
489                            server_pubkey,
490                            signing_key,
491                            nonce_cache,
492                        )
493                        .await
494                        {
495                            debug!("Stream error: {}", e);
496                        }
497                    });
498                }
499                Err(quinn::ConnectionError::ApplicationClosed(_)) => {
500                    debug!(?remote, "Connection closed by peer");
501                    break;
502                }
503                Err(e) => {
504                    debug!(?remote, "Connection error: {}", e);
505                    break;
506                }
507            }
508        }
509
510        Ok(())
511    }
512
513    async fn handle_stream_service<S>(
514        send: quinn::SendStream,
515        recv: quinn::RecvStream,
516        service: Rc<S>,
517        _server_pubkey: ed25519_dalek::VerifyingKey,
518        signing_key: ed25519_dalek::SigningKey,
519        nonce_cache: Arc<crate::envelope::InMemoryNonceCache>,
520    ) -> Result<()>
521    where
522        S: crate::service::RequestService + 'static,
523    {
524        let mut stream = ZmtpStream::new(QuicStream { send, recv });
525
526        // ZMTP handshake (server side)
527        stream.handshake(ZmqSocketType::Rep, true).await?;
528
529        // Receive request (single-frame: SignedEnvelope bytes)
530        let request = stream.recv_multipart().await?;
531        if request.parts.is_empty() {
532            return Err(anyhow!("empty request"));
533        }
534
535        let raw_bytes = &request.parts[0];
536
537        // Process through envelope pipeline.
538        // AnySigner: per-service keys mean each client signs with its own key,
539        // not a shared root key. The envelope signature is still verified — we
540        // just don't pin it to the server's own key. JWT claims + Casbin handle
541        // authorization.
542        // subsecond::call wraps dispatch for hot-patching during dev
543        // INV-2 (#1042): this legacy ZMTP entry point terminates a QUIC
544        // stream — an untrusted carrier even on a loopback address.
545        let response_bytes = subsecond::call(|| {
546            crate::service::dispatch::process_request(
547                raw_bytes,
548                &*service,
549                EnvelopeVerification::AnySigner,
550                &signing_key,
551                &nonce_cache,
552                crate::transport::carrier::CarrierContext::quic(),
553            )
554        })
555        .await?;
556
557        // Send response
558        let response = Multipart {
559            parts: vec![Bytes::from(response_bytes)],
560        };
561        stream.send_multipart(&response.parts).await?;
562
563        // Signal end of response. Any streaming pump was already spawned inside
564        // process_request (#186).
565        stream.stream.send.finish()?;
566
567        Ok(())
568    }
569
570    async fn handle_connection<H, Fut>(conn: quinn::Connection, handler: H) -> Result<()>
571    where
572        H: Fn(Multipart) -> Fut + Send + Clone + 'static,
573        Fut: std::future::Future<Output = Result<Multipart>> + Send,
574    {
575        let remote = conn.remote_address();
576        debug!(?remote, "QUIC connection established");
577
578        loop {
579            // Accept bidi streams from this connection (one per REQ/REP exchange)
580            match conn.accept_bi().await {
581                Ok((send, recv)) => {
582                    let handler = handler.clone();
583                    tokio::spawn(async move {
584                        if let Err(e) = Self::handle_stream(send, recv, handler).await {
585                            debug!("Stream error: {}", e);
586                        }
587                    });
588                }
589                Err(quinn::ConnectionError::ApplicationClosed(_)) => {
590                    debug!(?remote, "Connection closed by peer");
591                    break;
592                }
593                Err(e) => {
594                    debug!(?remote, "Connection error: {}", e);
595                    break;
596                }
597            }
598        }
599
600        Ok(())
601    }
602
603    async fn handle_stream<H, Fut>(
604        send: quinn::SendStream,
605        recv: quinn::RecvStream,
606        handler: H,
607    ) -> Result<()>
608    where
609        H: Fn(Multipart) -> Fut + Send,
610        Fut: std::future::Future<Output = Result<Multipart>> + Send,
611    {
612        let mut stream = ZmtpStream::new(QuicStream { send, recv });
613
614        // Perform ZMTP handshake as server
615        stream.handshake(ZmqSocketType::Rep, true).await?;
616
617        // REP: receive request, send reply (each request gets its own stream)
618        let request = match stream.recv_multipart().await {
619            Ok(msg) => msg,
620            Err(e) => {
621                // Stream closed is normal at end of request
622                if e.downcast_ref::<std::io::Error>()
623                    .is_some_and(|io_err| io_err.kind() == std::io::ErrorKind::UnexpectedEof)
624                {
625                    return Ok(());
626                }
627                return Err(e);
628            }
629        };
630
631        // Process request
632        let response = handler(request).await?;
633
634        // Send reply
635        stream.send_multipart(&response.parts).await?;
636
637        Ok(())
638    }
639}
640
641/// Client-side REQ socket over QUIC.
642///
643/// Opens one connection; each request opens a new bidi stream (ZMTP semantics).
644#[allow(dead_code)] // endpoint held to keep connection alive
645pub struct QuicReq {
646    conn: quinn::Connection,
647    endpoint: quinn::Endpoint,
648}
649
650impl QuicReq {
651    /// Connect to a QUIC REP server.
652    ///
653    /// # Arguments
654    ///
655    /// * `addr` - Server address
656    /// * `server_name` - Server hostname for TLS validation
657    /// * `tls` - TLS client configuration
658    pub async fn connect(
659        addr: SocketAddr,
660        server_name: &str,
661        tls: rustls::ClientConfig,
662    ) -> Result<Self> {
663        let mut endpoint = quinn::Endpoint::client("[::]:0".parse()?)?;
664        endpoint.set_default_client_config(owned_quic_client_config(tls)?);
665
666        let conn = endpoint
667            .connect(addr, server_name)?
668            .await
669            .map_err(|e| anyhow!("QUIC connection failed: {}", e))?;
670
671        Ok(Self { conn, endpoint })
672    }
673
674    /// Send request, receive reply. Each call opens a new bidi stream.
675    ///
676    /// QuicReq enforces REQ semantics: send then recv, one at a time.
677    pub async fn request(&self, msg: &Multipart) -> Result<Multipart> {
678        let (send, recv) = self.conn.open_bi().await?;
679
680        let mut stream = ZmtpStream::new(QuicStream { send, recv });
681        stream.handshake(ZmqSocketType::Req, false).await?;
682
683        // Send request
684        stream.send_multipart(&msg.parts).await?;
685
686        // Signal end of request (important for REP to know we're done)
687        stream.stream.send.finish()?;
688
689        // Receive reply
690        let response = stream.recv_multipart().await?;
691
692        Ok(response)
693    }
694
695    /// Close the connection.
696    pub fn close(&self) {
697        self.conn.close(0u32.into(), b"client closing");
698    }
699}
700
701impl Drop for QuicReq {
702    fn drop(&mut self) {
703        self.close();
704        // Endpoint will be cleaned up when dropped
705    }
706}
707
708// ============================================================================
709// PUB/SUB Socket Types
710// ============================================================================
711
712/// Server-side XPUB socket over QUIC.
713///
714/// Accepts subscriber connections; routes publications by topic prefix.
715/// Uses tokio::broadcast per topic for fan-out.
716pub struct QuicXPub {
717    endpoint: quinn::Endpoint,
718    /// Topic prefix → broadcast sender; subscribers hold receivers
719    topics: Arc<dashmap::DashMap<Vec<u8>, tokio::sync::broadcast::Sender<Bytes>>>,
720}
721
722impl QuicXPub {
723    /// Bind a QUIC XPUB socket to the given address.
724    pub fn bind(addr: SocketAddr, tls: rustls::ServerConfig) -> Result<Self> {
725        let endpoint = quinn::Endpoint::server(owned_quic_server_config(tls)?, addr)?;
726
727        Ok(Self {
728            endpoint,
729            topics: Arc::new(dashmap::DashMap::new()),
730        })
731    }
732
733    /// Get the local address this socket is bound to.
734    pub fn local_addr(&self) -> Result<SocketAddr> {
735        self.endpoint
736            .local_addr()
737            .map_err(|e| anyhow!("Failed to get local address: {}", e))
738    }
739
740    /// Publish a message to all subscribers matching the topic prefix.
741    ///
742    /// If no subscribers exist for this topic, the message is dropped.
743    pub fn publish(&self, topic: &[u8], data: Bytes) {
744        // Find all matching topic prefixes and send to their broadcast channels
745        for entry in self.topics.iter() {
746            let (prefix, sender) = entry.pair();
747            if topic.starts_with(prefix) {
748                // Ignore send errors (no active receivers)
749                let _ = sender.send(data.clone());
750            }
751        }
752    }
753
754    /// Accept loop: accepts incoming subscriber connections.
755    pub async fn accept_loop(&self, shutdown: Arc<Notify>) -> Result<()> {
756        loop {
757            tokio::select! {
758                Some(incoming) = self.endpoint.accept() => {
759                    let topics = Arc::clone(&self.topics);
760                    tokio::spawn(async move {
761                        match incoming.await {
762                            Ok(conn) => {
763                                if let Err(e) = Self::handle_subscriber(conn, topics).await {
764                                    debug!("Subscriber connection error: {}", e);
765                                }
766                            }
767                            Err(e) => {
768                                debug!("Incoming subscriber connection failed: {}", e);
769                            }
770                        }
771                    });
772                }
773                _ = shutdown.notified() => {
774                    debug!("XPUB accept loop shutting down");
775                    break;
776                }
777            }
778        }
779
780        self.endpoint.wait_idle().await;
781        Ok(())
782    }
783
784    async fn handle_subscriber(
785        conn: quinn::Connection,
786        topics: Arc<dashmap::DashMap<Vec<u8>, tokio::sync::broadcast::Sender<Bytes>>>,
787    ) -> Result<()> {
788        let remote = conn.remote_address();
789        debug!(?remote, "XPUB subscriber connection established");
790
791        // Accept bidi streams (one per subscription)
792        loop {
793            match conn.accept_bi().await {
794                Ok((send, recv)) => {
795                    let topics = Arc::clone(&topics);
796                    tokio::spawn(async move {
797                        if let Err(e) = Self::handle_subscription(send, recv, topics).await {
798                            debug!("Subscription error: {}", e);
799                        }
800                    });
801                }
802                Err(quinn::ConnectionError::ApplicationClosed(_)) => {
803                    debug!(?remote, "Subscriber disconnected");
804                    break;
805                }
806                Err(e) => {
807                    debug!(?remote, "Subscriber connection error: {}", e);
808                    break;
809                }
810            }
811        }
812
813        Ok(())
814    }
815
816    async fn handle_subscription(
817        send: quinn::SendStream,
818        recv: quinn::RecvStream,
819        topics: Arc<dashmap::DashMap<Vec<u8>, tokio::sync::broadcast::Sender<Bytes>>>,
820    ) -> Result<()> {
821        let mut stream = ZmtpStream::new(QuicStream { send, recv });
822
823        // Perform ZMTP handshake as server (XPUB)
824        stream.handshake(ZmqSocketType::XPub, true).await?;
825
826        // For simplicity: read one SUBSCRIBE command, then forward messages
827        // Real implementation would track multiple subscriptions per connection
828        let cmd = stream.recv_command().await?;
829
830        if cmd.name != "SUBSCRIBE" {
831            bail!("Expected SUBSCRIBE command, got {}", cmd.name);
832        }
833
834        let topic_prefix = cmd.body.to_vec();
835        debug!(topic = ?std::str::from_utf8(&topic_prefix), "Subscriber subscribed");
836
837        // Get or create broadcast channel for this topic
838        let sender = topics
839            .entry(topic_prefix.clone())
840            .or_insert_with(|| {
841                let (tx, _rx) = tokio::sync::broadcast::channel(256);
842                tx
843            })
844            .clone();
845
846        // Subscribe and forward messages to this stream
847        let mut rx = sender.subscribe();
848        loop {
849            tokio::select! {
850                msg = rx.recv() => {
851                    match msg {
852                        Ok(data) => {
853                            // Send as multipart: [topic, data]
854                            let parts = vec![Bytes::copy_from_slice(&topic_prefix), data];
855                            if stream.send_multipart(&parts).await.is_err() {
856                                break;
857                            }
858                        }
859                        Err(_) => break,
860                    }
861                }
862                // Also check for incoming commands (e.g., CANCEL)
863                cmd = stream.recv_command() => {
864                    match cmd {
865                        Ok(c) if c.name == "CANCEL" => {
866                            debug!(topic = ?std::str::from_utf8(&c.body), "Subscriber unsubscribed");
867                            break;
868                        }
869                        Ok(c) => {
870                            debug!("Unexpected command: {}", c.name);
871                        }
872                        Err(_) => break,
873                    }
874                }
875            }
876        }
877
878        // Clean up topic entry if no receivers remain
879        if sender.receiver_count() == 0 {
880            topics.remove(&topic_prefix);
881        }
882
883        Ok(())
884    }
885}
886
887/// Client-side SUB socket over QUIC.
888///
889/// Connects to QuicXPub; sends ZMTP subscription commands.
890#[allow(dead_code)] // endpoint held to keep connection alive
891pub struct QuicSub {
892    conn: quinn::Connection,
893    endpoint: quinn::Endpoint,
894}
895
896impl QuicSub {
897    /// Connect to a QUIC XPUB server.
898    pub async fn connect(
899        addr: SocketAddr,
900        server_name: &str,
901        tls: rustls::ClientConfig,
902    ) -> Result<Self> {
903        let mut endpoint = quinn::Endpoint::client("[::]:0".parse()?)?;
904        endpoint.set_default_client_config(owned_quic_client_config(tls)?);
905
906        let conn = endpoint
907            .connect(addr, server_name)?
908            .await
909            .map_err(|e| anyhow!("QUIC connection failed: {}", e))?;
910
911        Ok(Self { conn, endpoint })
912    }
913
914    /// Subscribe to a topic prefix.
915    ///
916    /// Returns a receiver for messages matching this prefix.
917    pub async fn subscribe(
918        &self,
919        prefix: &[u8],
920    ) -> Result<tokio::sync::broadcast::Receiver<Bytes>> {
921        let (send, recv_stream) = self.conn.open_bi().await?;
922        let mut stream = ZmtpStream::new(QuicStream {
923            send,
924            recv: recv_stream,
925        });
926
927        // Perform ZMTP handshake as client (SUB)
928        stream.handshake(ZmqSocketType::Sub, false).await?;
929
930        // Send SUBSCRIBE command
931        stream.send_command("SUBSCRIBE", prefix).await?;
932
933        // Create a broadcast channel to forward received messages
934        let (tx, rx) = tokio::sync::broadcast::channel(256);
935
936        // Spawn a task to receive messages and forward them
937        tokio::spawn(async move {
938            while let Ok(msg) = stream.recv_multipart().await {
939                // parts[0] = topic prefix, parts[1] = data payload
940                let data = msg.parts.get(1).or_else(|| msg.parts.first());
941                if let Some(data) = data {
942                    let _ = tx.send(data.clone());
943                }
944            }
945        });
946
947        Ok(rx)
948    }
949
950    /// Unsubscribe from a topic prefix.
951    pub async fn unsubscribe(&self, prefix: &[u8]) -> Result<()> {
952        let (send, recv) = self.conn.open_bi().await?;
953        let mut stream = ZmtpStream::new(QuicStream { send, recv });
954
955        // Perform ZMTP handshake as client (SUB)
956        stream.handshake(ZmqSocketType::Sub, false).await?;
957
958        // Send CANCEL command
959        stream.send_command("CANCEL", prefix).await?;
960
961        Ok(())
962    }
963
964    /// Close the connection.
965    pub fn close(&self) {
966        self.conn.close(0u32.into(), b"subscriber closing");
967    }
968}
969
970impl Drop for QuicSub {
971    fn drop(&mut self) {
972        self.close();
973        // Endpoint will be cleaned up when dropped
974    }
975}
976
977// ============================================================================
978// PUSH/PULL Socket Types
979// ============================================================================
980
981/// PUSH socket: opens connection, sends frames on a persistent bidi stream.
982#[allow(dead_code)] // endpoint held to keep connection alive
983pub struct QuicPush {
984    conn: quinn::Connection,
985    endpoint: quinn::Endpoint,
986}
987
988impl QuicPush {
989    /// Connect to a QUIC PULL server.
990    pub async fn connect(
991        addr: SocketAddr,
992        server_name: &str,
993        tls: rustls::ClientConfig,
994    ) -> Result<Self> {
995        let mut endpoint = quinn::Endpoint::client("[::]:0".parse()?)?;
996        endpoint.set_default_client_config(owned_quic_client_config(tls)?);
997
998        let conn = endpoint
999            .connect(addr, server_name)?
1000            .await
1001            .map_err(|e| anyhow!("QUIC connection failed: {}", e))?;
1002
1003        Ok(Self { conn, endpoint })
1004    }
1005
1006    /// Send a message to the PULL socket.
1007    pub async fn send(&self, msg: &Multipart) -> Result<()> {
1008        let (send, recv) = self.conn.open_bi().await?;
1009
1010        let mut stream = ZmtpStream::new(QuicStream { send, recv });
1011        stream.handshake(ZmqSocketType::Push, false).await?;
1012        stream.send_multipart(&msg.parts).await?;
1013        stream.stream.send.finish()?;
1014
1015        Ok(())
1016    }
1017
1018    /// Close the connection.
1019    pub fn close(&self) {
1020        self.conn.close(0u32.into(), b"push closing");
1021    }
1022}
1023
1024impl Drop for QuicPush {
1025    fn drop(&mut self) {
1026        self.close();
1027        // Endpoint will be cleaned up when dropped
1028    }
1029}
1030
1031/// PULL socket: accepts connections from multiple PUSHers, fans in to single receiver.
1032pub struct QuicPull {
1033    endpoint: quinn::Endpoint,
1034    /// Incoming frames from all PUSH connections forwarded here
1035    tx: tokio::sync::mpsc::UnboundedSender<Multipart>,
1036    /// Receiver for messages (exposed to user)
1037    rx: Option<tokio::sync::mpsc::UnboundedReceiver<Multipart>>,
1038}
1039
1040impl QuicPull {
1041    /// Bind a QUIC PULL socket to the given address.
1042    pub fn bind(addr: SocketAddr, tls: rustls::ServerConfig) -> Result<Self> {
1043        let endpoint = quinn::Endpoint::server(owned_quic_server_config(tls)?, addr)?;
1044        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
1045
1046        Ok(Self {
1047            endpoint,
1048            tx,
1049            rx: Some(rx),
1050        })
1051    }
1052
1053    /// Get the local address this socket is bound to.
1054    pub fn local_addr(&self) -> Result<SocketAddr> {
1055        self.endpoint
1056            .local_addr()
1057            .map_err(|e| anyhow!("Failed to get local address: {}", e))
1058    }
1059
1060    /// Receive the next message.
1061    pub async fn recv(&mut self) -> Option<Multipart> {
1062        self.rx.as_mut()?.recv().await
1063    }
1064
1065    /// Accept loop: accepts incoming push connections.
1066    pub async fn accept_loop(&self, shutdown: Arc<Notify>) -> Result<()> {
1067        loop {
1068            tokio::select! {
1069                Some(incoming) = self.endpoint.accept() => {
1070                    let tx = self.tx.clone();
1071                    tokio::spawn(async move {
1072                        match incoming.await {
1073                            Ok(conn) => {
1074                                if let Err(e) = Self::handle_pusher(conn, tx).await {
1075                                    debug!("Pusher connection error: {}", e);
1076                                }
1077                            }
1078                            Err(e) => {
1079                                debug!("Incoming pusher connection failed: {}", e);
1080                            }
1081                        }
1082                    });
1083                }
1084                _ = shutdown.notified() => {
1085                    debug!("PULL accept loop shutting down");
1086                    break;
1087                }
1088            }
1089        }
1090
1091        self.endpoint.wait_idle().await;
1092        Ok(())
1093    }
1094
1095    async fn handle_pusher(
1096        conn: quinn::Connection,
1097        tx: tokio::sync::mpsc::UnboundedSender<Multipart>,
1098    ) -> Result<()> {
1099        let remote = conn.remote_address();
1100        debug!(?remote, "Pusher connection established");
1101
1102        // Accept bidi streams (one per message)
1103        loop {
1104            match conn.accept_bi().await {
1105                Ok((send, recv)) => {
1106                    let tx = tx.clone();
1107                    tokio::spawn(async move {
1108                        let mut stream = ZmtpStream::new(QuicStream { send, recv });
1109                        if stream.handshake(ZmqSocketType::Pull, true).await.is_err() {
1110                            return;
1111                        }
1112                        if let Ok(msg) = stream.recv_multipart().await {
1113                            let _ = tx.send(msg);
1114                        }
1115                    });
1116                }
1117                Err(quinn::ConnectionError::ApplicationClosed(_)) => {
1118                    debug!(?remote, "Pusher disconnected");
1119                    break;
1120                }
1121                Err(e) => {
1122                    debug!(?remote, "Pusher connection error: {}", e);
1123                    break;
1124                }
1125            }
1126        }
1127
1128        Ok(())
1129    }
1130}
1131
1132/// Wrapper for Quinn bidi stream to implement AsyncRead/AsyncWrite.
1133struct QuicStream {
1134    send: quinn::SendStream,
1135    recv: quinn::RecvStream,
1136}
1137
1138impl AsyncRead for QuicStream {
1139    fn poll_read(
1140        mut self: std::pin::Pin<&mut Self>,
1141        cx: &mut std::task::Context<'_>,
1142        buf: &mut ReadBuf<'_>,
1143    ) -> std::task::Poll<std::io::Result<()>> {
1144        std::pin::Pin::new(&mut self.recv).poll_read(cx, buf)
1145    }
1146}
1147
1148impl AsyncWrite for QuicStream {
1149    fn poll_write(
1150        mut self: std::pin::Pin<&mut Self>,
1151        cx: &mut std::task::Context<'_>,
1152        buf: &[u8],
1153    ) -> std::task::Poll<std::io::Result<usize>> {
1154        std::pin::Pin::new(&mut self.send)
1155            .poll_write(cx, buf)
1156            .map_err(std::io::Error::other)
1157    }
1158
1159    fn poll_flush(
1160        mut self: std::pin::Pin<&mut Self>,
1161        cx: &mut std::task::Context<'_>,
1162    ) -> std::task::Poll<std::io::Result<()>> {
1163        std::pin::Pin::new(&mut self.send)
1164            .poll_flush(cx)
1165            .map_err(std::io::Error::other)
1166    }
1167
1168    fn poll_shutdown(
1169        mut self: std::pin::Pin<&mut Self>,
1170        cx: &mut std::task::Context<'_>,
1171    ) -> std::task::Poll<std::io::Result<()>> {
1172        std::pin::Pin::new(&mut self.send)
1173            .poll_shutdown(cx)
1174            .map_err(std::io::Error::other)
1175    }
1176}
1177
1178// ============================================================================
1179// QuicServiceLoop - QUIC Transport Service Loop
1180// ============================================================================
1181
1182/// Service loop for hosting RequestService over QUIC transport.
1183///
1184/// This struct wraps a `QuicRep` socket and a `RequestService` implementation,
1185/// running the QUIC accept loop in a dedicated thread with its own tokio runtime.
1186///
1187/// # Threading Model
1188///
1189/// `RequestService` is `#[async_trait(?Send)]` - handlers are not `Send`. This requires:
1190/// - Single-threaded runtime (`new_current_thread`)
1191/// - `LocalSet` for non-Send futures
1192/// - `spawn_local` instead of `tokio::spawn`
1193/// - Service wrapped in `Rc<S>` (not `Arc<S>`)
1194///
1195/// # Usage
1196///
1197/// ```ignore
1198/// use hyprstream_rpc::transport::zmtp_quic::{QuicRep, QuicServiceLoop};
1199/// use hyprstream_rpc::service::spawner::{Spawnable, DualSpawnable};
1200///
1201/// let (tls, cert_der) = server_tls_self_signed("hyprstream.local")?;
1202/// let quic_rep = QuicRep::bind(addr, tls)?;
1203/// let service = MyService::new();
1204///
1205/// let quic_loop = QuicServiceLoop::new(quic_rep, service, cert_der);
1206///
1207/// // Use with DualSpawnable to run alongside ZMQ:
1208/// let dual = DualSpawnable::new(zmq_loop, quic_loop);
1209/// Ok(Box::new(dual))
1210/// ```
1211pub struct QuicServiceLoop<S>
1212where
1213    S: crate::service::RequestService + Send + Sync + 'static,
1214{
1215    rep: QuicRep,
1216    service: S,
1217    /// Server leaf certificate DER bytes — used to pin the registered QUIC
1218    /// endpoint (self-signed, so clients pin the SHA-256 rather than CA-validate).
1219    cert_der: Vec<u8>,
1220    /// Service name
1221    name: String,
1222    /// QUIC endpoint address
1223    addr: SocketAddr,
1224}
1225
1226impl<S> QuicServiceLoop<S>
1227where
1228    S: crate::service::RequestService + Send + Sync + 'static,
1229{
1230    /// Create a new QUIC service loop.
1231    pub fn new(rep: QuicRep, service: S, cert_der: Vec<u8>) -> Result<Self> {
1232        let addr = rep.local_addr()?;
1233        let name = service.name().to_owned();
1234        Ok(Self {
1235            rep,
1236            service,
1237            cert_der,
1238            name,
1239            addr,
1240        })
1241    }
1242
1243    /// Get the QUIC endpoint address.
1244    pub fn local_addr(&self) -> SocketAddr {
1245        self.addr
1246    }
1247}
1248
1249impl<S> crate::service::Spawnable for QuicServiceLoop<S>
1250where
1251    S: crate::service::RequestService + Send + Sync + 'static,
1252{
1253    fn name(&self) -> &str {
1254        &self.name
1255    }
1256
1257    fn registrations(
1258        &self,
1259    ) -> Vec<(
1260        crate::registry::SocketKind,
1261        crate::transport::TransportConfig,
1262    )> {
1263        // Register the QUIC endpoint *pinned* by the self-signed leaf cert's
1264        // SHA-256 — a plain (WebPki) registration would make clients CA-validate
1265        // a self-signed cert and fail.
1266        let pin = crate::transport::quinn_transport::cert_sha256(&self.cert_der);
1267        vec![(
1268            crate::registry::SocketKind::Rep,
1269            crate::transport::TransportConfig::quic_pinned(self.addr, "hyprstream.local", pin),
1270        )]
1271    }
1272
1273    fn run(
1274        self: Box<Self>,
1275        shutdown: Arc<Notify>,
1276        on_ready: Option<tokio::sync::oneshot::Sender<()>>,
1277    ) -> crate::error::Result<()> {
1278        let rt = tokio::runtime::Builder::new_current_thread()
1279            .enable_all()
1280            .build()
1281            .map_err(|e| crate::error::RpcError::Other(format!("runtime build: {}", e)))?;
1282
1283        let local = tokio::task::LocalSet::new();
1284
1285        local.block_on(&rt, async move {
1286            let service = Rc::new(self.service);
1287            let server_pubkey = service.signing_key().verifying_key();
1288            let signing_key = service.signing_key();
1289            let nonce_cache = Arc::new(crate::envelope::InMemoryNonceCache::new());
1290
1291            // Signal ready
1292            if let Some(tx) = on_ready {
1293                let _ = tx.send(());
1294            }
1295
1296            // Run accept loop
1297            if let Err(e) = self
1298                .rep
1299                .accept_loop_service(service, server_pubkey, signing_key, nonce_cache, shutdown)
1300                .await
1301            {
1302                tracing::error!("QUIC accept loop error: {}", e);
1303            }
1304        });
1305
1306        Ok(())
1307    }
1308}
1309
1310/// Compute SHA-256 hash of certificate for browser `serverCertificateHashes` (base64).
1311pub fn cert_hash(cert_der: &[u8]) -> String {
1312    use base64::Engine;
1313    use sha2::{Digest, Sha256};
1314    let hash = Sha256::digest(cert_der);
1315    base64::engine::general_purpose::STANDARD.encode(hash)
1316}
1317
1318// ============================================================================
1319// TLS Helpers
1320// ============================================================================
1321
1322/// Generate a self-signed TLS certificate for development/testing.
1323///
1324/// Returns (ServerConfig, cert_der_bytes).
1325pub fn server_tls_self_signed(name: &str) -> Result<(rustls::ServerConfig, Vec<u8>)> {
1326    let cert_key = rcgen::generate_simple_self_signed(vec![name.to_owned()])?;
1327
1328    let cert_der = cert_key.cert.der().to_vec();
1329    let key_der = rustls::pki_types::PrivatePkcs8KeyDer::from(cert_key.key_pair.serialize_der());
1330
1331    let mut cfg = rustls::ServerConfig::builder_with_provider(
1332        crate::transport::pq_provider::internal_mesh_crypto_provider(),
1333    )
1334    .with_safe_default_protocol_versions()?
1335    .with_no_client_auth()
1336    .with_single_cert(vec![cert_der.clone().into()], key_der.into())?;
1337
1338    cfg.alpn_protocols = vec![ALPN_ZMTP3.to_vec()];
1339
1340    Ok((cfg, cert_der))
1341}
1342
1343/// Create a TLS client config that pins a specific server certificate.
1344///
1345/// Use this for self-signed certificates where you don't want to trust
1346/// the system CA store.
1347pub fn client_tls_pinned(cert_der: &[u8]) -> Result<rustls::ClientConfig> {
1348    let mut root_store = rustls::RootCertStore::empty();
1349    root_store.add(rustls::pki_types::CertificateDer::from_slice(cert_der))?;
1350
1351    let cfg = rustls::ClientConfig::builder_with_provider(
1352        crate::transport::pq_provider::internal_mesh_crypto_provider(),
1353    )
1354    .with_safe_default_protocol_versions()?
1355    .with_root_certificates(root_store)
1356    .with_no_client_auth();
1357
1358    let mut cfg = cfg;
1359    cfg.alpn_protocols = vec![ALPN_ZMTP3.to_vec()];
1360
1361    Ok(cfg)
1362}
1363
1364/// Create a TLS client config that trusts system root certificates.
1365pub fn client_tls_system_roots() -> Result<rustls::ClientConfig> {
1366    let mut root_store = rustls::RootCertStore::empty();
1367    root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
1368
1369    let cfg = rustls::ClientConfig::builder_with_provider(
1370        crate::transport::pq_provider::internal_mesh_crypto_provider(),
1371    )
1372    .with_safe_default_protocol_versions()?
1373    .with_root_certificates(root_store)
1374    .with_no_client_auth();
1375
1376    let mut cfg = cfg;
1377    cfg.alpn_protocols = vec![ALPN_ZMTP3.to_vec()];
1378
1379    Ok(cfg)
1380}
1381
1382// ============================================================================
1383// Request Processing Helper
1384// ============================================================================
1385
1386/// Envelope verification mode for `process_request`.
1387///
1388/// Two modes exist for different transport security models:
1389///
1390/// - **FixedSigner**: ZMQ (internal service-to-service) — envelope signer must match
1391///   known `server_pubkey` for mutual authentication. Peers pre-share keys.
1392/// - **AnySigner**: WebTransport (external browser clients) — any valid Ed25519 signer
1393///   accepted. TLS 1.3 provides transport-layer authentication.
1394///
1395/// Both modes share: timestamp window (5 min), nonce replay protection, JWT claims
1396/// verification. The only difference is step 1 of 4 in the verification pipeline.
1397pub use crate::envelope::EnvelopeVerification;
1398
1399// process_request moved to crate::service::dispatch (#148) — transport-neutral
1400// dispatch core, shared by RequestLoop / WebTransport / LocalServiceBridge.
1401
1402// ============================================================================
1403// Tests
1404// ============================================================================
1405
1406#[cfg(test)]
1407#[allow(clippy::unwrap_used, clippy::expect_used)]
1408mod tests {
1409    use super::*;
1410    use crate::zmtp_framing::{build_greeting, build_ready_metadata, validate_greeting};
1411    use quinn::crypto::rustls::HandshakeData;
1412
1413    #[test]
1414    fn test_greeting_format() {
1415        let greeting = build_greeting();
1416
1417        // Check size
1418        assert_eq!(greeting.len(), GREETING_SIZE);
1419
1420        // Check signature
1421        assert_eq!(greeting[0], 0xFF);
1422        assert!(greeting[1..9].iter().all(|&b| b == 0));
1423        assert_eq!(greeting[9], 0x7F);
1424
1425        // Check version
1426        assert_eq!(greeting[10], ZMTP_VERSION_MAJOR);
1427        assert_eq!(greeting[11], ZMTP_VERSION_MINOR);
1428
1429        // Check mechanism
1430        assert_eq!(&greeting[12..16], b"NULL");
1431
1432        // Check as-server (must be 0x00 for NULL mechanism)
1433        assert_eq!(greeting[32], 0x00);
1434    }
1435
1436    #[test]
1437    fn test_greeting_roundtrip() {
1438        let greeting = build_greeting();
1439        validate_greeting(&greeting).expect("greeting should validate");
1440    }
1441
1442    #[test]
1443    fn test_greeting_rejects_wrong_version() {
1444        let mut greeting = build_greeting();
1445        greeting[10] = 99; // Wrong major version
1446
1447        let result = validate_greeting(&greeting);
1448        assert!(result.is_err());
1449        assert!(result.unwrap_err().to_string().contains("version mismatch"));
1450    }
1451
1452    #[test]
1453    fn test_greeting_rejects_wrong_mechanism() {
1454        let mut greeting = build_greeting();
1455        greeting[12..16].copy_from_slice(b"CURV");
1456
1457        let result = validate_greeting(&greeting);
1458        assert!(result.is_err());
1459        assert!(result
1460            .unwrap_err()
1461            .to_string()
1462            .contains("mechanism mismatch"));
1463    }
1464
1465    #[test]
1466    fn test_ready_metadata_encoding() {
1467        let metadata = build_ready_metadata(ZmqSocketType::Rep);
1468
1469        // Parse it back
1470        assert!(!metadata.is_empty());
1471
1472        // First byte is name length
1473        let name_len = metadata[0] as usize;
1474        assert_eq!(name_len, 11); // "Socket-Type"
1475
1476        // Name follows
1477        let name = std::str::from_utf8(&metadata[1..1 + name_len]).unwrap();
1478        assert_eq!(name, "Socket-Type");
1479
1480        // Then 4-byte value length
1481        let value_len_start = 1 + name_len;
1482        let value_len = u32::from_be_bytes([
1483            metadata[value_len_start],
1484            metadata[value_len_start + 1],
1485            metadata[value_len_start + 2],
1486            metadata[value_len_start + 3],
1487        ]) as usize;
1488        assert_eq!(value_len, 3); // "REP"
1489
1490        // Value follows
1491        let value =
1492            std::str::from_utf8(&metadata[value_len_start + 4..value_len_start + 4 + value_len])
1493                .unwrap();
1494        assert_eq!(value, "REP");
1495    }
1496
1497    #[test]
1498    fn test_tls_self_signed_generates_valid_cert() {
1499        let (config, cert_der) = server_tls_self_signed("test.local").unwrap();
1500
1501        // Check ALPN is set
1502        assert!(config.alpn_protocols.iter().any(|p| p == ALPN_ZMTP3));
1503
1504        // Check cert is non-empty
1505        assert!(!cert_der.is_empty());
1506    }
1507
1508    #[test]
1509    fn test_client_tls_pinned_accepts_matching_cert() {
1510        let (_server_config, cert_der) = server_tls_self_signed("test.local").unwrap();
1511
1512        // Should succeed
1513        let client_config = client_tls_pinned(&cert_der);
1514        assert!(client_config.is_ok());
1515
1516        // Check ALPN is set
1517        let config = client_config.unwrap();
1518        assert!(config.alpn_protocols.iter().any(|p| p == ALPN_ZMTP3));
1519    }
1520
1521    #[tokio::test]
1522    async fn zmtp_live_handshake_negotiates_x25519mlkem768() {
1523        let (server_tls, cert_der) = server_tls_self_signed("localhost").unwrap();
1524        let server = QuicRep::bind("127.0.0.1:0".parse().unwrap(), server_tls).unwrap();
1525        let addr = server.local_addr().unwrap();
1526        let endpoint = server.endpoint.clone();
1527
1528        let accepted = tokio::spawn(async move {
1529            let connection = endpoint
1530                .accept()
1531                .await
1532                .expect("incoming zmtp connection")
1533                .await
1534                .expect("complete zmtp handshake");
1535            connection
1536                .handshake_data()
1537                .expect("completed quinn connection has handshake data")
1538                .downcast::<HandshakeData>()
1539                .expect("quinn rustls handshake data")
1540                .negotiated_key_exchange_group
1541        });
1542
1543        let client = QuicReq::connect(addr, "localhost", client_tls_pinned(&cert_der).unwrap())
1544            .await
1545            .unwrap();
1546        let client_group = client
1547            .conn
1548            .handshake_data()
1549            .expect("completed quinn connection has handshake data")
1550            .downcast::<HandshakeData>()
1551            .expect("quinn rustls handshake data")
1552            .negotiated_key_exchange_group;
1553
1554        assert_eq!(client_group, rustls::NamedGroup::X25519MLKEM768);
1555        assert_eq!(accepted.await.unwrap(), rustls::NamedGroup::X25519MLKEM768);
1556    }
1557
1558    #[tokio::test]
1559    async fn zmtp_internal_mesh_rejects_classical_only_peer() {
1560        let err = QuicReq::connect(
1561            "127.0.0.1:9".parse().unwrap(),
1562            "localhost",
1563            classical_client_config(),
1564        )
1565        .await
1566        .err()
1567        .expect("public REQ seam must reject classical config before dialing");
1568        assert!(err
1569            .to_string()
1570            .contains("owned-mesh crypto policy mismatch"));
1571    }
1572
1573    fn classical_client_config() -> rustls::ClientConfig {
1574        let mut config = rustls::ClientConfig::builder_with_provider(Arc::new(
1575            rustls::crypto::ring::default_provider(),
1576        ))
1577        .with_safe_default_protocol_versions()
1578        .unwrap()
1579        .with_root_certificates(rustls::RootCertStore::empty())
1580        .with_no_client_auth();
1581        config.alpn_protocols = vec![ALPN_ZMTP3.to_vec()];
1582        config
1583    }
1584
1585    fn classical_server_config() -> rustls::ServerConfig {
1586        let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()]).unwrap();
1587        let key = rustls::pki_types::PrivatePkcs8KeyDer::from(cert.key_pair.serialize_der());
1588        let mut config = rustls::ServerConfig::builder_with_provider(Arc::new(
1589            rustls::crypto::ring::default_provider(),
1590        ))
1591        .with_safe_default_protocol_versions()
1592        .unwrap()
1593        .with_no_client_auth()
1594        .with_single_cert(vec![cert.cert.der().clone()], key.into())
1595        .unwrap();
1596        config.alpn_protocols = vec![ALPN_ZMTP3.to_vec()];
1597        config
1598    }
1599
1600    fn assert_owned_policy_error<T>(result: Result<T>, seam: &str) {
1601        let err = result
1602            .err()
1603            .unwrap_or_else(|| panic!("{seam} accepted classical config"));
1604        assert!(
1605            err.to_string()
1606                .contains("owned-mesh crypto policy mismatch"),
1607            "{seam} returned the wrong error: {err}"
1608        );
1609    }
1610
1611    #[test]
1612    fn zmtp_rep_rejects_classical_only_config_before_bind() {
1613        let err = QuicRep::bind("127.0.0.1:0".parse().unwrap(), classical_server_config())
1614            .err()
1615            .expect("public REP seam must reject classical config before bind");
1616        assert!(err
1617            .to_string()
1618            .contains("owned-mesh crypto policy mismatch"));
1619    }
1620
1621    #[tokio::test]
1622    async fn all_owned_zmtp_socket_families_reject_classical_configs() {
1623        let bind_addr = "127.0.0.1:0".parse().unwrap();
1624        assert_owned_policy_error(
1625            QuicXPub::bind(bind_addr, classical_server_config()),
1626            "XPUB bind",
1627        );
1628        assert_owned_policy_error(
1629            QuicPull::bind(bind_addr, classical_server_config()),
1630            "PULL bind",
1631        );
1632
1633        let dial_addr = "127.0.0.1:9".parse().unwrap();
1634        assert_owned_policy_error(
1635            QuicSub::connect(dial_addr, "localhost", classical_client_config()).await,
1636            "SUB connect",
1637        );
1638        assert_owned_policy_error(
1639            QuicPush::connect(dial_addr, "localhost", classical_client_config()).await,
1640            "PUSH connect",
1641        );
1642    }
1643
1644    #[test]
1645    fn test_command_parse() {
1646        let data = b"\x05READY\x00\x00\x00\x03foo";
1647        let cmd = ZmtpCommand::parse(data).unwrap();
1648
1649        assert_eq!(cmd.name, "READY");
1650        assert_eq!(cmd.body.as_ref(), b"\x00\x00\x00\x03foo");
1651    }
1652
1653    #[test]
1654    fn test_command_parse_empty_name() {
1655        let data = b"";
1656        let result = ZmtpCommand::parse(data);
1657        assert!(result.is_err());
1658    }
1659
1660    #[test]
1661    fn test_multipart() {
1662        let mut msg = Multipart::new();
1663        assert!(msg.is_empty());
1664        assert_eq!(msg.len(), 0);
1665
1666        msg.push(Bytes::from("part1"));
1667        msg.push(Bytes::from("part2"));
1668
1669        assert!(!msg.is_empty());
1670        assert_eq!(msg.len(), 2);
1671    }
1672
1673    // ========================================================================
1674    // Frame encoding/decoding tests
1675    // ========================================================================
1676
1677    /// Encode a ZMTP frame to bytes (delegates to zmtp_framing).
1678    fn encode_frame_for_test(more: bool, command: bool, data: &[u8]) -> Vec<u8> {
1679        zmtp_framing::encode_frame(more, command, data)
1680    }
1681
1682    /// Decode a ZMTP frame from bytes (delegates to zmtp_framing).
1683    fn decode_frame_for_test(buf: &[u8]) -> Result<(ZmtpFrame, usize)> {
1684        let (owned, consumed) = zmtp_framing::decode_frame(buf)?;
1685        Ok((ZmtpFrame::from_owned(owned), consumed))
1686    }
1687
1688    #[test]
1689    fn test_frame_short_encode_decode() {
1690        // Frame <=255 bytes: short format
1691        let data = vec![0x42u8; 100];
1692        let encoded = encode_frame_for_test(false, false, &data);
1693        let (decoded, consumed) = decode_frame_for_test(&encoded).unwrap();
1694
1695        assert_eq!(consumed, encoded.len());
1696        assert!(!decoded.more);
1697        assert!(!decoded.command);
1698        assert_eq!(decoded.data.as_ref(), data.as_slice());
1699    }
1700
1701    #[test]
1702    fn test_frame_long_encode_decode() {
1703        // Frame >255 bytes: long format
1704        let data = vec![0xABu8; 500];
1705        let encoded = encode_frame_for_test(false, false, &data);
1706        let (decoded, consumed) = decode_frame_for_test(&encoded).unwrap();
1707
1708        assert_eq!(consumed, encoded.len());
1709        assert!(!decoded.more);
1710        assert!(!decoded.command);
1711        assert_eq!(decoded.data.as_ref(), data.as_slice());
1712
1713        // Long frame should have 8-byte size
1714        assert_eq!(encoded[0] & 0x02, 0x02); // LONG bit set
1715    }
1716
1717    #[test]
1718    fn test_frame_more_flag() {
1719        let data = b"test";
1720        let encoded_more = encode_frame_for_test(true, false, data);
1721        let encoded_last = encode_frame_for_test(false, false, data);
1722
1723        let (decoded_more, _) = decode_frame_for_test(&encoded_more).unwrap();
1724        let (decoded_last, _) = decode_frame_for_test(&encoded_last).unwrap();
1725
1726        assert!(decoded_more.more);
1727        assert!(!decoded_last.more);
1728    }
1729
1730    #[test]
1731    fn test_command_frame_flags() {
1732        let data = b"READY";
1733        let encoded = encode_frame_for_test(false, true, data);
1734        let (decoded, _) = decode_frame_for_test(&encoded).unwrap();
1735
1736        assert!(decoded.command);
1737        assert!(!decoded.more); // Commands are always single-frame
1738    }
1739
1740    #[test]
1741    fn test_command_rejects_more_flag() {
1742        // Per RFC 37, command frames must have MORE=0
1743        let data = b"READY";
1744        let encoded = encode_frame_for_test(true, true, data); // Invalid: MORE=1 for command
1745        let (decoded, _) = decode_frame_for_test(&encoded).unwrap();
1746
1747        // The decode should succeed, but this would be rejected by higher-level validation
1748        assert!(decoded.command);
1749        assert!(decoded.more); // Invalid state
1750    }
1751
1752    #[test]
1753    fn test_ready_metadata_roundtrip() {
1754        let metadata = zmtp_framing::build_ready_metadata(ZmqSocketType::Rep);
1755
1756        // Parse the metadata
1757        let name_len = metadata[0] as usize;
1758        let name = std::str::from_utf8(&metadata[1..1 + name_len]).unwrap();
1759
1760        let value_len_start = 1 + name_len;
1761        let value_len = u32::from_be_bytes([
1762            metadata[value_len_start],
1763            metadata[value_len_start + 1],
1764            metadata[value_len_start + 2],
1765            metadata[value_len_start + 3],
1766        ]) as usize;
1767        let value =
1768            std::str::from_utf8(&metadata[value_len_start + 4..value_len_start + 4 + value_len])
1769                .unwrap();
1770
1771        // Build again for REQ
1772        let metadata_req = zmtp_framing::build_ready_metadata(ZmqSocketType::Req);
1773        let name_len_req = metadata_req[0] as usize;
1774        let value_len_start_req = 1 + name_len_req;
1775        let value_len_req = u32::from_be_bytes([
1776            metadata_req[value_len_start_req],
1777            metadata_req[value_len_start_req + 1],
1778            metadata_req[value_len_start_req + 2],
1779            metadata_req[value_len_start_req + 3],
1780        ]) as usize;
1781        let value_req = std::str::from_utf8(
1782            &metadata_req[value_len_start_req + 4..value_len_start_req + 4 + value_len_req],
1783        )
1784        .unwrap();
1785
1786        assert_eq!(name, "Socket-Type");
1787        assert_eq!(value, "REP");
1788        assert_eq!(value_req, "REQ");
1789    }
1790
1791    #[test]
1792    fn test_subscribe_command() {
1793        // SUBSCRIBE command: body is topic prefix
1794        let topic = b"my.topic";
1795        let cmd = ZmtpCommand {
1796            name: "SUBSCRIBE".to_owned(),
1797            body: Bytes::copy_from_slice(topic),
1798        };
1799
1800        assert_eq!(cmd.name, "SUBSCRIBE");
1801        assert_eq!(cmd.body.as_ref(), topic);
1802    }
1803
1804    #[test]
1805    fn test_cancel_command() {
1806        // CANCEL command: body is topic prefix
1807        let topic = b"my.topic";
1808        let cmd = ZmtpCommand {
1809            name: "CANCEL".to_owned(),
1810            body: Bytes::copy_from_slice(topic),
1811        };
1812
1813        assert_eq!(cmd.name, "CANCEL");
1814        assert_eq!(cmd.body.as_ref(), topic);
1815    }
1816
1817    #[test]
1818    fn test_multipart_roundtrip() {
1819        // Test multipart message encoding
1820        let parts: Vec<Bytes> = vec![
1821            Bytes::from("identity"),
1822            Bytes::from("delimiter"),
1823            Bytes::from("payload"),
1824        ];
1825
1826        // Encode all parts
1827        let mut encoded = Vec::new();
1828        for (i, part) in parts.iter().enumerate() {
1829            let more = i < parts.len() - 1;
1830            encoded.extend(encode_frame_for_test(more, false, part));
1831        }
1832
1833        // Decode and verify
1834        let mut offset = 0;
1835        let mut decoded_parts = Vec::new();
1836        for _expected in &parts {
1837            let (frame, consumed) = decode_frame_for_test(&encoded[offset..]).unwrap();
1838            decoded_parts.push(frame.data);
1839            offset += consumed;
1840        }
1841
1842        assert_eq!(decoded_parts, parts);
1843    }
1844
1845    // ========================================================================
1846    // ZmtpStream tests (using in-memory duplex streams)
1847    // ========================================================================
1848
1849    #[test]
1850    fn test_zmtpstream_from_split() {
1851        // Create in-memory duplex streams for testing
1852        let (client_stream, server_stream) = tokio::io::duplex(8192);
1853
1854        // This test verifies the constructor exists and works
1855        // Full handshake tests would require async runtime
1856        let _client_stream = client_stream;
1857        let _server_stream = server_stream;
1858    }
1859}