Skip to main content

hyprstream_rpc/
dial.rs

1//! The `dial()` factory: the single place transport choice is made.
2//!
3//! Today transport selection leaks into generated client code, which hardcodes
4//! `ZmqConnection::new(...)`. Per the A1 addressing spike, that decision belongs
5//! in exactly one place: [`dial`] takes a resolved [`TransportConfig`] and
6//! returns a ready [`Arc<dyn RpcClient>`], erasing the concrete transport behind
7//! the object-safe client trait (`Transport` itself is not object-safe — it has
8//! `Sub`/`Pub` associated types — so erasure happens at the `RpcClient` layer).
9//!
10//! # Inproc dial table
11//!
12//! `inproc://` names resolve through a process-local registry mapping a name to
13//! a co-located service's [`IrohRequestProcessor`]. The registry — not the
14//! [`TransportConfig`] — holds the live handle: a `TransportConfig` is
15//! `Clone + Eq` and wire-publishable (DiscoveryService), so an `Arc<dyn
16//! IrohRequestProcessor>` cannot live inside it. Naming (resolver →
17//! `TransportConfig`) and handles (registry → processor) stay separate; `dial()`
18//! is where they meet.
19//!
20//! # Construction is synchronous; transports connect lazily
21//!
22//! `dial()` is sync and does no I/O — the inproc arm only looks up an existing
23//! processor. Networked transports (quinn/iroh/moq) connect lazily on first
24//! `send()` (cached like `ZmqConnection`), so dialing never blocks and the
25//! `inventory`-registered sync factory pattern is preserved. Those arms land in
26//! a follow-up increment of #151(a); ZMQ ipc/systemd endpoints stay on the
27//! existing codegen path during the transition.
28
29use std::collections::HashMap;
30use std::sync::{Arc, OnceLock, Weak};
31
32use anyhow::{anyhow, bail, Result};
33use parking_lot::RwLock;
34
35use crate::crypto::hybrid_kem::KemTrustStore;
36use crate::crypto::VerifyingKey;
37use crate::rpc_client::{RpcClient, RpcClientImpl};
38use crate::transport::in_memory::InMemoryTransport;
39use crate::transport::rpc_session::IrohRequestProcessor;
40use crate::transport::{EndpointType, TransportConfig};
41use crate::transport_traits::Signer;
42
43/// Process-local map of inproc endpoint name → co-located request processor.
44///
45/// Entries are `Weak`: the registry is a *lookup index*, not the owner. The
46/// service spawn site retains the strong `Arc` for the service's lifetime, so
47/// dropping the service (e.g. on shutdown) automatically tears down its bridge
48/// thread AND leaves a dead `Weak` here that self-evicts on the next lookup —
49/// no leak-by-forgotten-unregister, and no strong ref pinning a bridge thread
50/// past shutdown.
51type InprocRegistry = RwLock<HashMap<String, Weak<dyn IrohRequestProcessor>>>;
52
53static INPROC_REGISTRY: OnceLock<InprocRegistry> = OnceLock::new();
54
55fn registry() -> &'static InprocRegistry {
56    INPROC_REGISTRY.get_or_init(|| RwLock::new(HashMap::new()))
57}
58
59/// Register a co-located service's request processor under an `inproc://` name.
60///
61/// Called at service spawn. The `name` is the endpoint without the scheme
62/// (e.g. `hyprstream/registry` for `inproc://hyprstream/registry`). The caller
63/// MUST retain `processor` (the strong `Arc`) for as long as the service should
64/// be dialable — the registry only holds a `Weak`.
65///
66/// Overwriting a name whose service is still live is almost always a bug
67/// (name-squatting / double-spawn); it is logged loudly. Existing dialed
68/// clients keep the processor they captured; only future dials see the new one.
69pub fn register_inproc(name: impl Into<String>, processor: &Arc<dyn IrohRequestProcessor>) {
70    let name = name.into();
71    let mut map = registry().write();
72    if map.get(&name).is_some_and(|w| w.strong_count() > 0) {
73        tracing::warn!(
74            endpoint = %name,
75            "register_inproc: overwriting a still-live in-process service registration"
76        );
77    }
78    map.insert(name, Arc::downgrade(processor));
79}
80
81/// Explicitly drop a name's registration (best-effort; dead entries also
82/// self-evict on lookup once the service's strong `Arc` is gone).
83pub fn unregister_inproc(name: &str) {
84    registry().write().remove(name);
85}
86
87/// Look up a co-located service's processor by inproc name, upgrading the
88/// `Weak`. A stale (dead-service) entry is pruned in passing.
89pub fn lookup_inproc(name: &str) -> Option<Arc<dyn IrohRequestProcessor>> {
90    let mut map = registry().write();
91    match map.get(name).and_then(Weak::upgrade) {
92        Some(arc) => Some(arc),
93        None => {
94            // Present-but-dead → evict; absent → no-op.
95            map.remove(name);
96            None
97        }
98    }
99}
100
101/// Dial a resolved [`TransportConfig`], returning a ready RPC client.
102///
103/// `server_verifying_key` is the destination's response-verification key.
104/// `None` does NOT disable signature verification — the response is still
105/// cryptographically verified against the key embedded in its envelope; `None`
106/// only declines to pin *which* identity that key must be. Network callers
107/// should supply an independently resolved application response key. In
108/// particular, iroh NodeId/EndpointId is only reach/path integrity and can
109/// never fill this parameter.
110///
111/// **For `inproc://` there is no transport-level peer authentication** (it is a
112/// function call into a registry-resolved processor), so `None` is *discouraged*
113/// on the inproc path: without it, a name-squatting registration could be dialed
114/// without detection. Callers SHOULD pass the resolved service verifying key for
115/// inproc. (The codegen wire-up will thread the resolver-supplied key through;
116/// see #151(a) follow-up.)
117pub fn dial<S>(
118    target: &TransportConfig,
119    signer: S,
120    server_verifying_key: Option<VerifyingKey>,
121    token: Option<String>,
122) -> Result<Arc<dyn RpcClient>>
123where
124    S: Signer + 'static,
125{
126    dial_with_kem_store(target, signer, server_verifying_key, token, None)
127}
128
129/// Dial with an anchored `#mesh-kem` recipient trust store for carriers that
130/// forbid cleartext request envelopes.
131pub fn dial_with_kem_store<S>(
132    target: &TransportConfig,
133    signer: S,
134    server_verifying_key: Option<VerifyingKey>,
135    token: Option<String>,
136    request_kem_store: Option<Arc<dyn KemTrustStore>>,
137) -> Result<Arc<dyn RpcClient>>
138where
139    S: Signer + 'static,
140{
141    dial_with_crypto_stores(
142        target,
143        signer,
144        server_verifying_key,
145        token,
146        request_kem_store,
147        None,
148    )
149}
150
151/// Dial with both request-confidentiality and response-authentication anchors.
152/// Network response confidentiality requires both stores; absence remains a
153/// fail-closed runtime error at the shared client chokepoint.
154pub fn dial_with_crypto_stores<S>(
155    target: &TransportConfig,
156    signer: S,
157    server_verifying_key: Option<VerifyingKey>,
158    token: Option<String>,
159    request_kem_store: Option<Arc<dyn KemTrustStore>>,
160    response_pq_store: Option<Arc<dyn crate::envelope::PqTrustStore>>,
161) -> Result<Arc<dyn RpcClient>>
162where
163    S: Signer + 'static,
164{
165    let token_provider = token.map(|token| {
166        Arc::new(move || Some(token.clone())) as Arc<dyn Fn() -> Option<String> + Send + Sync>
167    });
168    dial_with_crypto_stores_and_token_provider(
169        target,
170        signer,
171        server_verifying_key,
172        token_provider,
173        request_kem_store,
174        response_pq_store,
175    )
176}
177
178/// Dial with a JWT provider evaluated for each request, so long-lived clients
179/// observe credential renewal without rebuilding their transport.
180pub fn dial_with_token_provider<S>(
181    target: &TransportConfig,
182    signer: S,
183    server_verifying_key: Option<VerifyingKey>,
184    token_provider: Option<Arc<dyn Fn() -> Option<String> + Send + Sync>>,
185) -> Result<Arc<dyn RpcClient>>
186where
187    S: Signer + 'static,
188{
189    dial_with_crypto_stores_and_token_provider(
190        target,
191        signer,
192        server_verifying_key,
193        token_provider,
194        None,
195        None,
196    )
197}
198
199/// The provider form of the crypto-bound dial. A missing JWT remains missing;
200/// this API does not manufacture clearance from the caller's signing key.
201pub fn dial_with_crypto_stores_and_token_provider<S>(
202    target: &TransportConfig,
203    signer: S,
204    server_verifying_key: Option<VerifyingKey>,
205    token_provider: Option<Arc<dyn Fn() -> Option<String> + Send + Sync>>,
206    request_kem_store: Option<Arc<dyn KemTrustStore>>,
207    response_pq_store: Option<Arc<dyn crate::envelope::PqTrustStore>>,
208) -> Result<Arc<dyn RpcClient>>
209where
210    S: Signer + 'static,
211{
212    /// Wrap a built transport as an `RpcClient`, applying the optional default
213    /// JWT (CA-signed trust cert included in request envelopes) if present.
214    fn build_client<S2, T2>(
215        signer: S2,
216        transport: T2,
217        vk: Option<VerifyingKey>,
218        token_provider: Option<Arc<dyn Fn() -> Option<String> + Send + Sync>>,
219        request_kem_store: Option<Arc<dyn KemTrustStore>>,
220        response_pq_store: Option<Arc<dyn crate::envelope::PqTrustStore>>,
221    ) -> Arc<dyn RpcClient>
222    where
223        S2: Signer + 'static,
224        T2: crate::transport_traits::Transport + 'static,
225    {
226        let rpc = RpcClientImpl::new(signer, transport, vk);
227        let rpc = match request_kem_store {
228            Some(store) => rpc.with_request_kem_store(store),
229            None => rpc,
230        };
231        let rpc = match response_pq_store {
232            Some(store) => rpc.with_response_pq_store(store),
233            None => rpc,
234        };
235        let rpc = match token_provider {
236            Some(provider) => rpc.with_token_provider(move || provider()),
237            None => rpc,
238        };
239        Arc::new(rpc) as Arc<dyn RpcClient>
240    }
241
242    // Matched exhaustively on purpose: this is the one place transport choice is
243    // made, so a newly-added EndpointType variant MUST be a compile error here
244    // rather than silently falling through to a runtime bail.
245    match &target.endpoint {
246        EndpointType::Inproc { endpoint } => {
247            let processor = lookup_inproc(endpoint).ok_or_else(|| {
248                anyhow!("no in-process service registered for inproc endpoint '{endpoint}'")
249            })?;
250            let transport = InMemoryTransport::new(processor);
251            Ok(build_client(
252                signer,
253                transport,
254                server_verifying_key,
255                token_provider,
256                request_kem_store,
257                response_pq_store,
258            ))
259        }
260        EndpointType::Quic {
261            addr,
262            server_name,
263            auth,
264        } => {
265            // SECURITY (#185): QUIC channel auth (WebPKI / cert-hash pin) binds the
266            // *channel*, not the peer's DID identity. Identity is established at the
267            // application layer — the response signature is verified against the
268            // envelope-embedded key even when `server_verifying_key` is `None`,
269            // just not *pinned* to an expected identity. For a networked peer,
270            // prefer passing the resolver-known key; note (debug) when we can't.
271            if server_verifying_key.is_none() {
272                tracing::debug!(
273                    %addr,
274                    "dial: networked QUIC peer with no expected verifying key — \
275                     response identity unpinned (channel-level auth only, #185)"
276                );
277            }
278            let transport = crate::transport::lazy_quinn::LazyQuinnTransport::new(
279                *addr,
280                server_name.clone(),
281                auth.clone(),
282            );
283            Ok(build_client(
284                signer,
285                transport,
286                server_verifying_key,
287                token_provider,
288                request_kem_store,
289                response_pq_store,
290            ))
291        }
292        EndpointType::Iroh {
293            node_id,
294            direct_addrs,
295            relay_url,
296        } => {
297            // Discovery may publish only the NodeId. LazyIrohTransport gives its
298            // N0-enabled endpoint that empty-hints address under a bounded connect
299            // timeout; NodeId never replaces the independent authority below.
300            let response_key = server_verifying_key.ok_or_else(|| {
301                anyhow!(
302                    "dial(): iroh reach has no independently resolved application response key; \
303                     NodeId/EndpointId cannot select response identity (#1031)"
304                )
305            })?;
306            let transport = crate::transport::lazy_iroh::LazyIrohTransport::new(
307                *node_id,
308                direct_addrs.clone(),
309                relay_url.clone(),
310            );
311            Ok(build_client(
312                signer,
313                transport,
314                Some(response_key),
315                token_provider,
316                request_kem_store,
317                response_pq_store,
318            ))
319        }
320        // Same-host `ipc` plane: connect a UdsSession (RPC plane) at the socket
321        // path. systemd socket-activation is the same client-side dial — the fd
322        // is the *server's* pre-bound listener; clients connect by `client_path`.
323        // UDS has no transport-level peer identity; the app-layer SignedEnvelope
324        // is the authentication (a `None` server_verifying_key leaves the
325        // response identity unpinned but still signature-verified). Socket perms
326        // + SO_PEERCRED are daemon-owned defense-in-depth (#207).
327        EndpointType::Ipc { path } => {
328            let transport = crate::transport::lazy_uds::LazyUdsTransport::new(path.clone());
329            Ok(build_client(
330                signer,
331                transport,
332                server_verifying_key,
333                token_provider,
334                request_kem_store,
335                response_pq_store,
336            ))
337        }
338        EndpointType::SystemdFd { client_path, .. } => {
339            let transport = crate::transport::lazy_uds::LazyUdsTransport::new(client_path.clone());
340            Ok(build_client(
341                signer,
342                transport,
343                server_verifying_key,
344                token_provider,
345                request_kem_store,
346                response_pq_store,
347            ))
348        }
349    }
350}
351
352/// The URL path the daemon's `web_transport_quinn` server dispatches to the moq
353/// streaming plane (default path → RPC). Both server and client use this.
354pub const MOQ_PATH: &str = "/moq";
355
356/// The URL path the daemon's `web_transport_quinn` server dispatches to the 9P
357/// export plane (H1b / #765): the QUIC path-mux sibling of H1a's `/9p` axum
358/// WebSocket endpoint, for the cert-pinned self-signed mesh. A WebTransport
359/// session whose CONNECT URL path is this is handed to the injected 9P handler
360/// (see [`crate::transport::quinn_transport`]); the mount ticket rides
361/// `Tattach.uname`, not the URL, since the session is already cert-pinned.
362pub const NINEP_PATH: &str = "/9p";
363
364/// A dialed moq streaming session, erased over the concrete transport.
365///
366/// [`dial_stream`] returns this so a caller can dial the streaming plane over
367/// either quinn/WebTransport (`/moq` path-dispatch) **or** iroh (the `moql`
368/// ALPN) and hand the result straight to `moq_net::Client::connect`, which is
369/// generic over `web_transport_trait::Session`. The two underlying session
370/// types (`web_transport_quinn::Session` / `web_transport_iroh::Session`) do not
371/// share a concrete type, so this enum dispatches at the `connect` call.
372pub enum MoqStreamSession {
373    /// quinn / WebTransport `/moq` session (#274).
374    Quinn(web_transport_quinn::Session),
375    /// iroh `moql`-ALPN session (#282).
376    Iroh(web_transport_iroh::Session),
377}
378
379impl MoqStreamSession {
380    /// Run the moq-lite handshake over this session, returning the live
381    /// `moq_net::Session`. Dispatches to the concrete transport's `connect`.
382    pub async fn connect_moq(
383        self,
384        client: &moq_net::Client,
385    ) -> std::result::Result<moq_net::Session, moq_net::Error> {
386        match self {
387            MoqStreamSession::Quinn(s) => client.connect(s).await,
388            MoqStreamSession::Iroh(s) => client.connect(s).await,
389        }
390    }
391}
392
393/// Dial the moq streaming plane for a network-routable reach, returning a live
394/// [`web_transport_quinn::Session`] (#274).
395///
396/// The sibling of [`dial`] for the *streaming* plane: it dials the `/moq` path
397/// over `web_transport_quinn` (the server path-dispatches `/moq` → moq, default
398/// → RPC), reusing [`crate::transport::quinn_transport`]'s connect + cert-pin
399/// helpers. The returned session is handed straight to `moq_net::Client::connect`.
400///
401/// Only the **network-routable** transports are dialable here. `Ipc` / `Inproc`
402/// / `SystemdFd` are same-host endpoints resolved from LOCAL config — never from
403/// a wire-published reach — so they are rejected: a co-located client must use
404/// the same-host UDS fast path instead of dialing.
405pub async fn dial_stream(target: &TransportConfig) -> Result<MoqStreamSession> {
406    use crate::transport::quinn_transport::{
407        connect_pinned_hashes_path, connect_webpki_path, verify_peer_cert_pinned,
408    };
409    match &target.endpoint {
410        EndpointType::Quic {
411            addr,
412            server_name,
413            auth,
414        } => {
415            let pins = auth.accept_cert_hashes();
416            let session = if auth.require_web_pki() {
417                // WebPKI (optionally + pin): validate via system roots + SNI.
418                let session = connect_webpki_path(server_name, addr.port(), MOQ_PATH).await?;
419                if !pins.is_empty() {
420                    // Defence in depth (#185): also require the leaf to be pinned.
421                    verify_peer_cert_pinned(&session, pins)?;
422                }
423                session
424            } else {
425                // Self-signed mesh: pin the leaf by its SHA-256 (dial by IP).
426                if pins.is_empty() {
427                    bail!("dial_stream(): pinned QUIC reach has no cert hashes — not dialable");
428                }
429                connect_pinned_hashes_path(*addr, pins, MOQ_PATH).await?
430            };
431            Ok(MoqStreamSession::Quinn(session))
432        }
433        EndpointType::Iroh {
434            node_id,
435            direct_addrs,
436            relay_url,
437        } => {
438            // #357: dial-by-node_id-alone is now supported — when no direct addrs
439            // or relay are supplied, the shared client endpoint's pkarr / n0 DNS
440            // discovery (`presets::N0`) resolves the routable addresses from the
441            // `EndpointId`. This is the S2 native-peer direct path (the wire
442            // `IrohReach` carries only the node_id). When the resolver *does*
443            // supply direct addrs / a relay, they are used as hints to skip /
444            // accelerate discovery (faster than waiting on pkarr).
445            //
446            // #282: dial the iroh `moql` ALPN from the shared process-wide client
447            // endpoint (the SAME endpoint the daemon's inbound iroh substrate
448            // listens on, installed once at startup), then wrap the iroh
449            // Connection as a `web_transport_iroh::Session` for moq-net.
450            // EndpointId verification provides target/path integrity only; the
451            // per-Frame chained-HMAC envelope (§7.5) remains the independent
452            // application-layer integrity check the subscriber verifies.
453            let session = dial_iroh_moq(node_id, direct_addrs, relay_url).await?;
454            Ok(MoqStreamSession::Iroh(session))
455        }
456        EndpointType::Ipc { .. } | EndpointType::SystemdFd { .. } | EndpointType::Inproc { .. } => {
457            bail!(
458                "dial_stream(): same-host endpoint ({:?}) is resolved from local \
459                 config, not dialed from the wire — use the UDS fast path",
460                target.endpoint
461            )
462        }
463    }
464}
465
466/// Dial the iroh `moql` (moq-lite) ALPN to `node_id` and wrap the connection as
467/// a `web_transport_iroh::Session` ready for `moq_net::Client::connect`.
468///
469/// Uses the process-wide client iroh endpoint installed at startup
470/// ([`crate::transport::lazy_iroh::install_iroh_client_endpoint`]) — the same
471/// install-once dialer the RPC plane's `LazyIrohTransport` uses, so the streaming
472/// dial reuses the carrier address and bound sockets. Mirrors
473/// [`crate::transport::iroh_substrate::IrohSubstrate::connect`].
474async fn dial_iroh_moq(
475    node_id: &[u8; 32],
476    direct_addrs: &[std::net::SocketAddr],
477    relay_url: &Option<String>,
478) -> Result<web_transport_iroh::Session> {
479    let endpoint = crate::transport::lazy_iroh::iroh_client_endpoint().ok_or_else(|| {
480        anyhow!(
481            "dial_stream(): no iroh client endpoint installed — call \
482             install_iroh_client_endpoint() at startup before dialing iroh streams"
483        )
484    })?;
485
486    let conn = dial_iroh_moq_from_endpoint(endpoint, node_id, direct_addrs, relay_url).await?;
487    Ok(web_transport_iroh::Session::raw(conn))
488}
489
490/// Dial from an explicitly owned endpoint, returning the raw `moql` connection.
491///
492/// Tests use this primitive so a runtime-bound endpoint never leaks into the
493/// process-global production slot. The caller owns the endpoint for the full
494/// connection lifecycle. The raw connection lets the #1027 admission exchange
495/// consume the first bi stream before the session is wrapped.
496async fn dial_iroh_moq_from_endpoint(
497    endpoint: iroh::Endpoint,
498    node_id: &[u8; 32],
499    direct_addrs: &[std::net::SocketAddr],
500    relay_url: &Option<String>,
501) -> Result<iroh::endpoint::Connection> {
502    use crate::transport::iroh_substrate::ALPN_MOQ_LITE;
503    use iroh::{EndpointAddr, EndpointId, TransportAddr};
504
505    let id = EndpointId::from_bytes(node_id).map_err(|e| anyhow!("invalid iroh node_id: {e}"))?;
506    let mut transport_addrs: Vec<TransportAddr> = direct_addrs
507        .iter()
508        .copied()
509        .map(TransportAddr::Ip)
510        .collect();
511    if let Some(url) = relay_url {
512        let relay = url
513            .parse()
514            .map_err(|e| anyhow!("invalid iroh relay_url '{url}': {e}"))?;
515        transport_addrs.push(TransportAddr::Relay(relay));
516    }
517    let addr = EndpointAddr::from_parts(id, transport_addrs);
518
519    let conn = endpoint
520        .connect(addr, ALPN_MOQ_LITE)
521        .await
522        .map_err(|e| anyhow!("iroh moql connect: {e}"))?;
523    Ok(conn)
524}
525
526/// #1027: dial the moq streaming plane over iroh `moql` and run the
527/// inside-carrier admission challenge/response
528/// ([`crate::transport::moql_admission`]) BEFORE returning the session. The
529/// returned session is admitted: the server has verified the proof against its
530/// current accepted Ed25519 + ML-DSA-65 state and scoped the session to the
531/// resolved tenant.
532///
533/// Admission is the iroh-carrier path only; the quinn `/moq` plane
534/// authenticates at CONNECT time ([`crate::transport::moq_connect_auth`]).
535/// Same-host endpoints are rejected exactly as in [`dial_stream`].
536pub async fn dial_stream_authenticated(
537    target: &TransportConfig,
538    proof: &crate::transport::moql_admission::MoqlAdmissionProof,
539) -> Result<MoqStreamSession> {
540    match &target.endpoint {
541        EndpointType::Iroh {
542            node_id,
543            direct_addrs,
544            relay_url,
545        } => {
546            let endpoint =
547                crate::transport::lazy_iroh::iroh_client_endpoint().ok_or_else(|| {
548                    anyhow!(
549                        "dial_stream_authenticated(): no iroh client endpoint installed — call \
550                     install_iroh_client_endpoint() at startup before dialing iroh streams"
551                    )
552                })?;
553            let client_carrier_node_id = *endpoint.id().as_bytes();
554            let conn =
555                dial_iroh_moq_from_endpoint(endpoint, node_id, direct_addrs, relay_url).await?;
556            crate::transport::moql_admission::prove_moql_admission(
557                &conn,
558                proof,
559                client_carrier_node_id,
560                crate::transport::moql_admission::DEFAULT_ADMISSION_TIMEOUT,
561            )
562            .await
563            .map_err(|e| anyhow!("moql admission proof failed: {e}"))?;
564            Ok(MoqStreamSession::Iroh(web_transport_iroh::Session::raw(
565                conn,
566            )))
567        }
568        EndpointType::Quic { .. } => {
569            bail!(
570                "dial_stream_authenticated(): #1027 admission is the iroh `moql` path; \
571                 the quinn `/moq` plane authenticates at CONNECT time (#1153)"
572            )
573        }
574        EndpointType::Ipc { .. } | EndpointType::SystemdFd { .. } | EndpointType::Inproc { .. } => {
575            bail!(
576                "dial_stream_authenticated(): same-host endpoint ({:?}) is resolved from local \
577                 config, not dialed from the wire — use the UDS fast path",
578                target.endpoint
579            )
580        }
581    }
582}
583
584#[cfg(test)]
585#[allow(clippy::unwrap_used, clippy::expect_used)]
586mod tests {
587    use super::*;
588    use crate::crypto::SigningKey;
589    use crate::signer::LocalSigner;
590    use crate::transport::rpc_session::from_fn;
591    use crate::transport::QuicServerAuth;
592    use bytes::Bytes;
593    use rand::rngs::OsRng;
594
595    fn test_signer() -> LocalSigner {
596        LocalSigner::new(SigningKey::generate(&mut OsRng))
597    }
598
599    fn echo() -> Arc<dyn IrohRequestProcessor> {
600        Arc::new(from_fn(|r: Bytes| async move { Ok(r) }))
601    }
602
603    #[test]
604    fn register_lookup_unregister() {
605        let name = "test/dial/register_lookup_unregister";
606        assert!(lookup_inproc(name).is_none());
607        let proc = echo();
608        register_inproc(name, &proc);
609        assert!(lookup_inproc(name).is_some());
610        unregister_inproc(name);
611        assert!(lookup_inproc(name).is_none());
612    }
613
614    #[test]
615    fn lookup_self_evicts_when_service_dropped() {
616        let name = "test/dial/self_evict";
617        let proc = echo();
618        register_inproc(name, &proc);
619        assert!(lookup_inproc(name).is_some());
620        // Service shuts down: drop the only strong ref. The Weak in the
621        // registry is now dead and must not resolve (and is pruned).
622        drop(proc);
623        assert!(
624            lookup_inproc(name).is_none(),
625            "dead-service entry must not resolve"
626        );
627    }
628
629    #[test]
630    fn dial_inproc_resolves_registered_processor() {
631        let name = "test/dial/dial_inproc_resolves";
632        let proc = echo();
633        register_inproc(name, &proc);
634
635        let cfg = TransportConfig::inproc(name);
636        let client = dial(&cfg, test_signer(), None, None);
637        assert!(
638            client.is_ok(),
639            "dialing a registered inproc endpoint must succeed"
640        );
641
642        unregister_inproc(name);
643    }
644
645    #[test]
646    fn dial_inproc_unregistered_errors() {
647        let cfg = TransportConfig::inproc("test/dial/never_registered");
648        let err = dial(&cfg, test_signer(), None, None);
649        assert!(
650            err.is_err(),
651            "dialing an unregistered inproc endpoint must error"
652        );
653    }
654
655    #[test]
656    fn dial_ipc_builds_lazy_client() {
657        // ipc dial builds a lazy UdsSession client — sync, no I/O, connects on
658        // first send (the socket need not exist yet at dial() time).
659        let cfg = TransportConfig::ipc("/tmp/hyprstream-test-dial.sock");
660        let client = dial(&cfg, test_signer(), None, None);
661        assert!(
662            client.is_ok(),
663            "ipc dial must build a lazy client without connecting"
664        );
665    }
666
667    #[test]
668    fn dial_systemd_fd_builds_lazy_client() {
669        // systemd socket-activation: client dials the client_path via UDS.
670        let cfg = TransportConfig::systemd_fd(7, "/tmp/hyprstream-test-systemd.sock");
671        let client = dial(&cfg, test_signer(), None, None);
672        assert!(
673            client.is_ok(),
674            "systemd-fd dial must build a lazy client via client_path"
675        );
676    }
677
678    #[test]
679    fn dial_quic_webpki_builds_client() {
680        // Plain `quic()` = WebPKI/CA validation — a valid auth policy, so dial()
681        // builds a (lazy, not-yet-connected) client.
682        let cfg = TransportConfig::quic("127.0.0.1:9999".parse().unwrap(), "localhost");
683        let client = dial(&cfg, test_signer(), None, None);
684        assert!(
685            client.is_ok(),
686            "WebPKI QUIC dial must build a client without connecting"
687        );
688    }
689
690    #[test]
691    fn dial_quic_pinned_builds_client() {
692        // Cert-hash-pinned QUIC: builds a lazy client — sync, no I/O.
693        let cfg =
694            TransportConfig::quic_pinned("127.0.0.1:9999".parse().unwrap(), "localhost", [7u8; 32]);
695        let client = dial(&cfg, test_signer(), None, None);
696        assert!(
697            client.is_ok(),
698            "pinned QUIC dial must build a client without connecting"
699        );
700    }
701
702    #[test]
703    fn dial_quic_web_pki_pinned_builds_client() {
704        // WebPKI + pin (defence in depth): builds a lazy client.
705        let cfg = TransportConfig {
706            endpoint: EndpointType::Quic {
707                addr: "127.0.0.1:9999".parse().unwrap(),
708                server_name: "localhost".to_owned(),
709                auth: QuicServerAuth::web_pki_pinned(vec![[9u8; 32]]).unwrap(),
710            },
711            bind_mode: crate::transport::BindMode::Connect,
712        };
713        let client = dial(&cfg, test_signer(), None, None);
714        assert!(client.is_ok(), "WebPKI+pin QUIC dial must build a client");
715    }
716
717    #[test]
718    fn quic_server_auth_rejects_no_requirement() {
719        assert!(
720            QuicServerAuth::pinned(vec![]).is_err(),
721            "empty pin set is no auth"
722        );
723        assert!(
724            QuicServerAuth::web_pki_pinned(vec![]).is_err(),
725            "empty pin set is no auth"
726        );
727        assert!(QuicServerAuth::web_pki().require_web_pki());
728    }
729
730    #[test]
731    fn dial_stream_iroh_node_id_alone_requires_installed_endpoint() {
732        // #357: dial-by-node_id-alone is supported (pkarr / n0 DNS discovery
733        // resolves addresses from the EndpointId on the shared client endpoint),
734        // so an iroh reach with no direct addrs / relay is no longer rejected
735        // up-front. With no client endpoint installed, the dial still fails — but
736        // because the shared dialer is missing, not because reachability is absent.
737        let cfg = TransportConfig::iroh([1u8; 32], Vec::new(), None);
738        let err = match futures::executor::block_on(dial_stream(&cfg)) {
739            Ok(_) => panic!("dial must fail with no installed iroh client endpoint"),
740            Err(e) => e,
741        };
742        assert!(
743            err.to_string()
744                .contains("no iroh client endpoint installed"),
745            "expected an install-endpoint error (node_id-alone is dialable once an \
746             endpoint is installed); got: {err}"
747        );
748    }
749
750    #[test]
751    fn rpc_iroh_node_id_alone_builds_lazy_transport_but_never_uses_node_as_authority() {
752        let response_signer = SigningKey::generate(&mut OsRng);
753        let cfg = TransportConfig::iroh([0x19; 32], Vec::new(), None);
754
755        assert!(
756            dial(
757                &cfg,
758                test_signer(),
759                Some(response_signer.verifying_key()),
760                None
761            )
762            .is_ok(),
763            "an empty-hints NodeId must reach LazyIrohTransport for bounded N0 discovery"
764        );
765        assert!(
766            dial(&cfg, test_signer(), None, None).is_err(),
767            "NodeId must not be repurposed as an application response key"
768        );
769    }
770
771    #[test]
772    fn iroh_node_equality_never_selects_or_changes_application_response_key() {
773        let response_signer = SigningKey::generate(&mut OsRng);
774        let response_key = response_signer.verifying_key();
775        let equal_to_response_key = response_key.to_bytes();
776        let unrelated_reach = SigningKey::generate(&mut OsRng).verifying_key().to_bytes();
777
778        for node_id in [equal_to_response_key, unrelated_reach] {
779            let cfg = TransportConfig::iroh(
780                node_id,
781                Vec::new(),
782                Some("https://relay.example".to_owned()),
783            );
784            assert!(
785                dial(&cfg, test_signer(), None, None).is_err(),
786                "NodeId equality must not mint a response-verification key"
787            );
788            assert!(
789                dial(&cfg, test_signer(), Some(response_key), None).is_ok(),
790                "separately resolved response proof must remain valid regardless of NodeId mismatch"
791            );
792        }
793    }
794
795    /// The real carrier dial uses a runtime-owned endpoint and leaves the global
796    /// slot untouched. With no fresh session proof, the server then refuses the
797    /// anonymous MoQ handshake rather than exposing broadcasts.
798    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
799    async fn dial_stream_iroh_moql_anonymous_refused_without_global_leak() -> Result<()> {
800        use crate::transport::iroh_moq::IrohMoqProtocolHandler;
801        use crate::transport::iroh_substrate::{IrohSubstrate, NoopHandler};
802        use moq_net::Client;
803        use rand::RngCore;
804
805        fn fresh_key() -> [u8; 32] {
806            let mut k = [0u8; 32];
807            rand::thread_rng().fill_bytes(&mut k);
808            k
809        }
810
811        let moq_handler = IrohMoqProtocolHandler::new();
812        let server =
813            IrohSubstrate::new_test(fresh_key(), moq_handler, NoopHandler::new("rpc")).await?;
814        let server_id: [u8; 32] = *server.endpoint_id().as_bytes();
815        let direct: Vec<std::net::SocketAddr> =
816            server.endpoint().bound_sockets().into_iter().collect();
817
818        // ── Client: runtime-owned endpoint, never installed globally ──────────
819        let client = IrohSubstrate::new_test(
820            fresh_key(),
821            NoopHandler::new("c-moq"),
822            NoopHandler::new("c-rpc"),
823        )
824        .await?;
825        assert!(
826            crate::transport::lazy_iroh::iroh_client_endpoint().is_none(),
827            "unit tests must not inherit a process-global runtime-bound endpoint"
828        );
829
830        // Exercise the same carrier dial primitive from the isolated endpoint.
831        let cfg = TransportConfig::iroh(server_id, direct, None);
832        let session = match &cfg.endpoint {
833            EndpointType::Iroh {
834                node_id,
835                direct_addrs,
836                relay_url,
837            } => MoqStreamSession::Iroh(web_transport_iroh::Session::raw(
838                dial_iroh_moq_from_endpoint(
839                    client.endpoint().clone(),
840                    node_id,
841                    direct_addrs,
842                    relay_url,
843                )
844                .await?,
845            )),
846            other => panic!("expected iroh endpoint, got {other:?}"),
847        };
848        assert!(
849            matches!(session, MoqStreamSession::Iroh(_)),
850            "must be an iroh session"
851        );
852
853        let moq_client = Client::new();
854        let handshake = session.connect_moq(&moq_client).await;
855        assert!(handshake.is_err(), "anonymous MoQ carrier must fail closed");
856
857        client.shutdown().await?;
858        server.shutdown().await?;
859        assert!(
860            crate::transport::lazy_iroh::iroh_client_endpoint().is_none(),
861            "isolated carrier test must leave global endpoint state untouched"
862        );
863        Ok(())
864    }
865}