Skip to main content

hyprstream_rpc/transport/
mod.rs

1//! Transport layer for RPC communication.
2//!
3//! This module provides:
4//! - `Transport` / `AsyncTransport` traits for generic transport abstraction
5//! - `TransportConfig` for unified endpoint configuration
6//! - Systemd socket activation support via `SystemdFd` variant
7//! - QUIC/WebTransport via `quinn_transport` (`QuinnRpcServer` + moq multiplex, #274)
8//! - Raw socket options via `sockopt` submodule
9
10pub mod carrier;
11#[cfg(not(target_arch = "wasm32"))]
12pub mod pq_provider;
13mod traits;
14pub mod zmtp_quic;
15#[cfg(not(target_arch = "wasm32"))]
16pub use pq_provider::{install_pq_crypto_provider, pq_crypto_provider};
17#[cfg(not(target_arch = "wasm32"))]
18pub mod backoff;
19#[cfg(not(target_arch = "wasm32"))]
20pub mod in_memory;
21#[cfg(not(target_arch = "wasm32"))]
22pub mod iroh_moq;
23#[cfg(not(target_arch = "wasm32"))]
24pub mod iroh_rpc;
25#[cfg(not(target_arch = "wasm32"))]
26pub mod iroh_substrate;
27#[cfg(not(target_arch = "wasm32"))]
28pub mod iroh_transport;
29#[cfg(not(target_arch = "wasm32"))]
30pub mod lazy_iroh;
31#[cfg(not(target_arch = "wasm32"))]
32pub mod lazy_quinn;
33#[cfg(not(target_arch = "wasm32"))]
34pub mod lazy_uds;
35#[cfg(not(target_arch = "wasm32"))]
36/// CONNECT-time authentication + tenant binding for the `/moq` WebTransport
37/// plane (#1153).
38pub mod moq_connect_auth;
39#[cfg(not(target_arch = "wasm32"))]
40/// Inside-carrier Ed25519 + ML-DSA-65 challenge/response admission for the
41/// iroh `moql` ALPN (#1027).
42pub mod moql_admission;
43#[cfg(not(target_arch = "wasm32"))]
44pub mod quinn_transport;
45#[cfg(not(target_arch = "wasm32"))]
46pub mod rpc_session;
47#[cfg(not(target_arch = "wasm32"))]
48pub mod uds_server;
49#[cfg(not(target_arch = "wasm32"))]
50pub mod uds_session;
51
52use std::net::SocketAddr;
53use std::os::unix::io::RawFd;
54use std::path::PathBuf;
55
56pub use crate::transport_traits::{PublishSink, Signer, Transport};
57
58/// Socket bind mode for transport configuration.
59///
60/// Controls whether a socket binds to an endpoint (standalone server)
61/// or connects to it (worker behind a load balancer).
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
63pub enum BindMode {
64    /// Socket binds to the endpoint (default, standalone mode).
65    #[default]
66    Bind,
67    /// Socket connects to the endpoint (worker behind ROUTER/DEALER LB).
68    Connect,
69}
70
71/// Transport endpoint configuration.
72///
73/// # Examples
74///
75/// ```
76/// use hyprstream_rpc::transport::TransportConfig;
77///
78/// // In-process endpoint
79/// let inproc = TransportConfig::inproc("hyprstream/registry");
80/// ```
81#[derive(Debug, Clone, PartialEq, Eq)]
82pub struct TransportConfig {
83    /// Endpoint type (inproc, IPC, systemd FD)
84    pub endpoint: EndpointType,
85
86    /// Socket bind mode (Bind or Connect).
87    /// Workers behind a ROUTER/DEALER load balancer use Connect.
88    pub bind_mode: BindMode,
89}
90
91/// How a QUIC client authenticates the **channel** to the server it dials.
92///
93/// # This is channel auth, not identity auth
94///
95/// Peer *identity* ("which node is this") is established at the **application
96/// layer** — every response is a signed COSE `SignedEnvelope` verified against
97/// the peer's published keys (the DID-doc `#mesh` verification method / JWKS).
98/// That works identically on native and in WASM, because it is our code, not the
99/// browser's TLS stack. This type only decides how the *TLS channel* is
100/// authenticated (confidentiality + anti-active-MITM); it is defence in depth,
101/// not the trust root (#185).
102///
103/// Channel auth is a small lattice of independent requirements, not a fixed set
104/// of modes, so it is a validated struct rather than an enum of combinations:
105///   - `require_web_pki` — the leaf must chain to a system-trusted CA and match
106///     `server_name` (public peers, dialed by hostname).
107///   - `accept_cert_hashes` — a **set** of acceptable leaf-cert SHA-256s. A set
108///     (not one hash) so cert rotation can overlap (`{current, next}`) and
109///     load-balanced endpoints with distinct certs work. The resolver / DID doc
110///     supplies these — they are directory-distributed pins, not trust-on-first-
111///     use. (For browsers this is the *only* knob the WebTransport API exposes.)
112///
113/// The verifier ANDs the active requirements. At least one must be active —
114/// `{web_pki: false, hashes: []}` is no auth and is rejected at construction.
115///
116/// RFC 7250 raw-public-key binding (bind the channel to the published key
117/// directly, so native QUIC reuses the identity key instead of a cert hash) is
118/// tracked in #200; it is channel hygiene, not an identity requirement (identity
119/// is app-layer regardless). iroh already does it natively.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct QuicServerAuth {
122    require_web_pki: bool,
123    accept_cert_hashes: Vec<[u8; 32]>,
124}
125
126impl QuicServerAuth {
127    /// WebPKI / CA-chain validation only (public, CA-fronted peer).
128    pub fn web_pki() -> Self {
129        Self {
130            require_web_pki: true,
131            accept_cert_hashes: Vec::new(),
132        }
133    }
134
135    /// Pin the leaf cert to one of `hashes` (SHA-256), no CA requirement — the
136    /// self-signed internal-mesh model. Errors if `hashes` is empty.
137    pub fn pinned(hashes: Vec<[u8; 32]>) -> anyhow::Result<Self> {
138        anyhow::ensure!(
139            !hashes.is_empty(),
140            "QuicServerAuth::pinned requires >= 1 cert hash"
141        );
142        Ok(Self {
143            require_web_pki: false,
144            accept_cert_hashes: hashes,
145        })
146    }
147
148    /// WebPKI validation **and** the leaf must be one of `hashes` — defence in
149    /// depth against CA mis-issuance (HPKP-style). Errors if `hashes` is empty.
150    pub fn web_pki_pinned(hashes: Vec<[u8; 32]>) -> anyhow::Result<Self> {
151        anyhow::ensure!(
152            !hashes.is_empty(),
153            "QuicServerAuth::web_pki_pinned requires >= 1 cert hash"
154        );
155        Ok(Self {
156            require_web_pki: true,
157            accept_cert_hashes: hashes,
158        })
159    }
160
161    /// Whether CA-chain validation is required.
162    pub fn require_web_pki(&self) -> bool {
163        self.require_web_pki
164    }
165
166    /// The set of accepted leaf-cert SHA-256 pins (empty => no pin requirement).
167    pub fn accept_cert_hashes(&self) -> &[[u8; 32]] {
168        &self.accept_cert_hashes
169    }
170}
171
172/// Endpoint type (without encryption config)
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub enum EndpointType {
175    /// In-process endpoint (zero-copy, same process).
176    ///
177    /// Format: `inproc://hyprstream/service`
178    Inproc { endpoint: String },
179
180    /// Unix domain socket (IPC) endpoint.
181    ///
182    /// Format: `ipc:///path/to/socket`
183    Ipc { path: PathBuf },
184
185    /// Systemd socket activation endpoint.
186    ///
187    /// Used when systemd passes a pre-bound file descriptor to the service.
188    /// The `fd` is used for server-side binding,
189    /// while `client_path` provides the IPC path for clients to connect.
190    SystemdFd {
191        /// Pre-bound file descriptor from systemd
192        fd: RawFd,
193        /// IPC path for client connections
194        client_path: PathBuf,
195    },
196
197    /// QUIC transport endpoint (ZMTP 3.1 over QUIC).
198    ///
199    /// Provides TLS 1.3 encryption built into the transport layer.
200    /// ZMTP handshake uses NULL mechanism since QUIC already provides
201    /// wire confidentiality.
202    ///
203    /// Format: `quic://hostname:port`
204    Quic {
205        /// Socket address to bind (server) or connect (client)
206        addr: SocketAddr,
207        /// Server hostname — used as the WebPKI validation name (`WebPki`) and
208        /// the TLS SNI. Ignored by `Pinned` (which dials by IP and matches the
209        /// cert hash).
210        server_name: String,
211        /// How the client authenticates this server (WebPKI, cert-hash pin, or
212        /// — later — RFC 7250 raw key). Public material only.
213        auth: QuicServerAuth,
214    },
215
216    /// iroh transport endpoint (RPC over `ALPN_HYPRSTREAM_RPC`).
217    ///
218    /// The optional NAT-traversing dial. Unlike QUIC's channel-only cert pin,
219    /// iroh binds the connection to the peer's `EndpointId` (its Ed25519 public
220    /// key), authenticating only the carrier endpoint, not application identity. All
221    /// fields are serializable primitives so `TransportConfig` stays
222    /// `Clone + Eq` and wire-publishable (a DID-doc `service` entry).
223    ///
224    /// Format: `iroh://{hex node_id}`
225    Iroh {
226        /// Peer's iroh `EndpointId` = its Ed25519 public key (32 bytes).
227        node_id: [u8; 32],
228        /// Known direct socket addresses for hole-punching / direct dial.
229        direct_addrs: Vec<SocketAddr>,
230        /// Optional relay URL for NAT traversal when no direct path exists.
231        relay_url: Option<String>,
232    },
233}
234
235impl TransportConfig {
236    /// Create an in-process endpoint configuration.
237    pub fn inproc(endpoint: impl Into<String>) -> Self {
238        Self {
239            endpoint: EndpointType::Inproc {
240                endpoint: endpoint.into(),
241            },
242            bind_mode: BindMode::Bind,
243        }
244    }
245
246    /// Create an IPC (Unix domain socket) endpoint configuration.
247    pub fn ipc(path: impl Into<PathBuf>) -> Self {
248        Self {
249            endpoint: EndpointType::Ipc { path: path.into() },
250            bind_mode: BindMode::Bind,
251        }
252    }
253
254    /// Create a systemd socket activation endpoint.
255    ///
256    /// # Arguments
257    ///
258    /// * `fd` - Pre-bound file descriptor from systemd
259    /// * `client_path` - IPC path for client connections
260    pub fn systemd_fd(fd: RawFd, client_path: impl Into<PathBuf>) -> Self {
261        Self {
262            endpoint: EndpointType::SystemdFd {
263                fd,
264                client_path: client_path.into(),
265            },
266            bind_mode: BindMode::Bind,
267        }
268    }
269
270    /// Create a QUIC transport endpoint.
271    ///
272    /// # Arguments
273    ///
274    /// * `addr` - Socket address to bind (server) or connect (client)
275    /// * `server_name` - Server hostname for TLS certificate validation
276    pub fn quic(addr: SocketAddr, server_name: impl Into<String>) -> Self {
277        Self {
278            endpoint: EndpointType::Quic {
279                addr,
280                server_name: server_name.into(),
281                auth: QuicServerAuth::web_pki(),
282            },
283            bind_mode: BindMode::Bind,
284        }
285    }
286
287    /// Create a client QUIC endpoint that pins the server's self-signed cert by
288    /// its SHA-256 fingerprint. This is the dial target the resolver/`dial()`
289    /// produce for an internal-mesh RPC peer (dialed by IP).
290    pub fn quic_pinned(
291        addr: SocketAddr,
292        server_name: impl Into<String>,
293        cert_hash: [u8; 32],
294    ) -> Self {
295        Self {
296            endpoint: EndpointType::Quic {
297                addr,
298                server_name: server_name.into(),
299                // In-module: construct directly (a one-element set is always valid).
300                auth: QuicServerAuth {
301                    require_web_pki: false,
302                    accept_cert_hashes: vec![cert_hash],
303                },
304            },
305            bind_mode: BindMode::Connect,
306        }
307    }
308
309    /// Create a client QUIC endpoint with an explicit channel-auth policy
310    /// (used by the DID-doc service-entry codec, which may produce any of
311    /// WebPKI / Pinned / WebPKI+pin).
312    pub fn quic_with_auth(
313        addr: SocketAddr,
314        server_name: impl Into<String>,
315        auth: QuicServerAuth,
316    ) -> Self {
317        Self {
318            endpoint: EndpointType::Quic {
319                addr,
320                server_name: server_name.into(),
321                auth,
322            },
323            bind_mode: BindMode::Connect,
324        }
325    }
326
327    /// Create a client iroh endpoint dialing the peer identified by `node_id`
328    /// (its `EndpointId` / Ed25519 public key), with optional direct addresses
329    /// and relay URL for NAT traversal.
330    pub fn iroh(
331        node_id: [u8; 32],
332        direct_addrs: Vec<SocketAddr>,
333        relay_url: Option<String>,
334    ) -> Self {
335        Self {
336            endpoint: EndpointType::Iroh {
337                node_id,
338                direct_addrs,
339                relay_url,
340            },
341            bind_mode: BindMode::Connect,
342        }
343    }
344
345    /// Set bind mode to Connect (for workers behind a load balancer).
346    pub fn with_connect_mode(mut self) -> Self {
347        self.bind_mode = BindMode::Connect;
348        self
349    }
350
351    /// Get the bind mode.
352    pub fn bind_mode(&self) -> BindMode {
353        self.bind_mode
354    }
355
356    /// Parse an endpoint string into a TransportConfig.
357    ///
358    /// Supports:
359    /// - `inproc://name` → `TransportConfig::Inproc`
360    /// - `ipc:///path/to/socket` → `TransportConfig::Ipc`
361    ///
362    /// # Example
363    ///
364    /// ```
365    /// use hyprstream_rpc::transport::TransportConfig;
366    ///
367    /// let config = TransportConfig::from_endpoint("inproc://hyprstream/registry");
368    /// assert_eq!(config.endpoint_string(), "inproc://hyprstream/registry");
369    /// ```
370    pub fn from_endpoint(endpoint: &str) -> Self {
371        let endpoint_type = if let Some(name) = endpoint.strip_prefix("inproc://") {
372            EndpointType::Inproc {
373                endpoint: name.to_owned(),
374            }
375        } else if let Some(path) = endpoint.strip_prefix("ipc://") {
376            EndpointType::Ipc {
377                path: PathBuf::from(path),
378            }
379        } else if endpoint.contains("://") {
380            // Unknown scheme — fail-closed: misrouting to inproc would yield a
381            // cryptic "no in-process service registered" error at dial time.
382            // Networked transports (quic://, iroh://, tcp://) are obtained via
383            // the application-owned RpcClientProvider, not from_endpoint().
384            panic!(
385                "TransportConfig::from_endpoint: unknown scheme in '{endpoint}'; \
386                 use an RpcClientProvider for networked transports"
387            );
388        } else {
389            // Bare name (no scheme) — defaults to inproc
390            EndpointType::Inproc {
391                endpoint: endpoint.to_owned(),
392            }
393        };
394
395        Self {
396            endpoint: endpoint_type,
397            bind_mode: BindMode::Bind,
398        }
399    }
400
401    /// Get the endpoint string for this configuration.
402    ///
403    /// For `SystemdFd`, returns the client IPC path.
404    /// For `Quic`, returns a descriptive string (not a connectable endpoint).
405    pub fn endpoint_string(&self) -> String {
406        match &self.endpoint {
407            EndpointType::Inproc { endpoint } => format!("inproc://{endpoint}"),
408            EndpointType::Ipc { path } => format!("ipc://{}", path.display()),
409            EndpointType::SystemdFd { client_path, .. } => {
410                format!("ipc://{}", client_path.display())
411            }
412            EndpointType::Quic {
413                addr, server_name, ..
414            } => {
415                format!("quic://{server_name}:{addr}")
416            }
417            EndpointType::Iroh { node_id, .. } => {
418                let hex: String = node_id.iter().map(|b| format!("{b:02x}")).collect();
419                format!("iroh://{hex}")
420            }
421        }
422    }
423
424    /// Get the WebTransport URL for QUIC endpoints.
425    ///
426    /// Returns `https://{server_name}:{port}` for QUIC endpoints, `None` otherwise.
427    pub fn quic_webtransport_url(&self) -> Option<String> {
428        match &self.endpoint {
429            EndpointType::Quic {
430                addr, server_name, ..
431            } => Some(format!("https://{}:{}", server_name, addr.port())),
432            _ => None,
433        }
434    }
435
436    /// Check if this is a systemd-activated endpoint.
437    pub fn is_systemd_activated(&self) -> bool {
438        matches!(&self.endpoint, EndpointType::SystemdFd { .. })
439    }
440
441    /// Check if this is a QUIC endpoint.
442    pub fn is_quic(&self) -> bool {
443        matches!(&self.endpoint, EndpointType::Quic { .. })
444    }
445
446    /// Build an RFC 9728 resource URL from a QUIC endpoint.
447    ///
448    /// Returns `https://{server_name}/{path}`, matching the format used
449    /// by `QuicSharedConfig::for_service()`. The port is omitted because
450    /// resource URLs are identity tokens (used as JWT audience), not
451    /// connection endpoints — clients discover actual ports via the
452    /// endpoint registry.
453    ///
454    /// Returns `None` if this is not a QUIC endpoint.
455    pub fn quic_resource_url(&self, path: &str) -> Option<String> {
456        match &self.endpoint {
457            EndpointType::Quic { server_name, .. } => {
458                Some(format!("https://{}/{}", server_name, path))
459            }
460            _ => None,
461        }
462    }
463}
464
465impl EndpointType {
466    /// Whether this endpoint class forbids cleartext request envelopes.
467    ///
468    /// iroh and cross-host QUIC/WebTransport are untrusted carriers for RPC
469    /// envelope confidentiality. Loopback QUIC is treated as local test/dev
470    /// plumbing; same-process and same-host UDS remain cleartext-allowed.
471    pub fn forbids_cleartext_envelope(&self) -> bool {
472        match self {
473            // QUIC and iroh are untrusted carriers for RPC envelope
474            // confidentiality — cleartext forbidden unconditionally. A loopback
475            // QUIC address is NOT evidence the bytes stay inside the trust
476            // boundary (it can terminate at a proxy/tunnel), so it gets no
477            // exemption; genuinely-local trusted RPC uses inproc or UDS. Any
478            // hermetic test that needs cleartext must use an explicit trusted
479            // transport (inproc/UDS), never a loopback-QUIC address heuristic.
480            EndpointType::Iroh { .. } | EndpointType::Quic { .. } => true,
481            EndpointType::Inproc { .. }
482            | EndpointType::Ipc { .. }
483            | EndpointType::SystemdFd { .. } => false,
484        }
485    }
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491
492    /// INV-2 (ADR #1023) carrier classification matrix: which `EndpointType`s
493    /// forbid a cleartext request envelope. Untrusted network carriers (iroh,
494    /// QUIC incl. loopback, relay-carried) MUST forbid; genuinely-local trusted
495    /// carriers (inproc, UDS, systemd-activated UDS) permit. Loopback QUIC gets
496    /// NO exemption — a loopback address is not evidence the bytes stay inside
497    /// the trust boundary (it can terminate at a proxy/tunnel).
498    #[test]
499    #[allow(clippy::unwrap_used)]
500    fn inv2_carrier_classification_matrix() {
501        // Untrusted network carriers → forbid cleartext.
502        assert!(
503            EndpointType::Iroh {
504                node_id: [0u8; 32],
505                direct_addrs: vec![],
506                relay_url: None,
507            }
508            .forbids_cleartext_envelope(),
509            "iroh is an untrusted carrier"
510        );
511        assert!(
512            EndpointType::Iroh {
513                node_id: [0u8; 32],
514                direct_addrs: vec![],
515                relay_url: Some("https://relay.example".into()),
516            }
517            .forbids_cleartext_envelope(),
518            "relay-carried iroh is an untrusted carrier"
519        );
520        // Non-loopback QUIC → forbid.
521        assert!(
522            EndpointType::Quic {
523                addr: "10.0.0.1:4433".parse().unwrap(),
524                server_name: "x".into(),
525                auth: QuicServerAuth::web_pki(),
526            }
527            .forbids_cleartext_envelope(),
528            "cross-host QUIC is an untrusted carrier"
529        );
530        // Loopback QUIC → STILL forbid (no address-heuristic exemption).
531        assert!(
532            EndpointType::Quic {
533                addr: "127.0.0.1:4433".parse().unwrap(),
534                server_name: "x".into(),
535                auth: QuicServerAuth::web_pki(),
536            }
537            .forbids_cleartext_envelope(),
538            "loopback QUIC must NOT be exempt — it can terminate at a proxy/tunnel"
539        );
540        // Trusted same-host carriers → permit cleartext (ban must not widen).
541        assert!(
542            !EndpointType::Inproc {
543                endpoint: "hyprstream/x".into()
544            }
545            .forbids_cleartext_envelope(),
546            "inproc is trusted"
547        );
548        assert!(
549            !EndpointType::Ipc {
550                path: "/tmp/x.sock".into()
551            }
552            .forbids_cleartext_envelope(),
553            "UDS/ipc is trusted"
554        );
555        assert!(
556            !EndpointType::SystemdFd {
557                fd: 5,
558                client_path: "/run/hyprstream/x.sock".into(),
559            }
560            .forbids_cleartext_envelope(),
561            "systemd-activated UDS is trusted"
562        );
563    }
564
565    #[test]
566    fn test_inproc_endpoint() {
567        let config = TransportConfig::inproc("hyprstream/registry");
568        assert_eq!(config.endpoint_string(), "inproc://hyprstream/registry");
569        assert_eq!(config.endpoint_string(), "inproc://hyprstream/registry");
570        assert!(!config.is_systemd_activated());
571    }
572
573    #[test]
574    fn test_ipc_endpoint() {
575        let config = TransportConfig::ipc("/tmp/hyprstream.sock");
576        assert_eq!(config.endpoint_string(), "ipc:///tmp/hyprstream.sock");
577        assert!(!config.is_systemd_activated());
578    }
579
580    #[test]
581    fn test_systemd_fd_endpoint() {
582        let config = TransportConfig::systemd_fd(5, "/run/hyprstream/policy.sock");
583        assert_eq!(
584            config.endpoint_string(),
585            "ipc:///run/hyprstream/policy.sock"
586        );
587        assert!(config.is_systemd_activated());
588    }
589
590    #[test]
591    fn test_quic_endpoint() {
592        use std::net::{IpAddr, Ipv4Addr};
593
594        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 4433);
595        let config = TransportConfig::quic(addr, "hyprstream.local");
596        assert!(config
597            .endpoint_string()
598            .starts_with("quic://hyprstream.local:"));
599        assert!(config.is_quic());
600        assert!(!config.is_systemd_activated());
601    }
602}