dig_nat/dialer.rs
1//! The production [`Dialer`] — performs the real rustls **mTLS** dial to a reachable address and
2//! returns a [`PeerConnection`] whose remote `peer_id` has been verified.
3//!
4//! This is the single place transport detail lives: (happy-eyeballs) TCP connect → rustls client
5//! handshake presenting THIS node's certificate (mutual TLS) → the [`PeerIdPinningVerifier`]
6//! captures the peer's leaf cert, derives `peer_id = SHA-256(SPKI DER)`, and rejects the handshake
7//! unless it matches the [`PeerTarget::peer_id`] the caller asked for. On success the caller gets an
8//! authenticated, encrypted [`tokio_rustls::client::TlsStream`].
9//!
10//! ## IPv6-first, IPv4-fallback — delegated to `dig-ip` (CLAUDE.md §5.2)
11//!
12//! The family-selection + happy-eyeballs racing that used to live here is now the `dig-ip` crate's
13//! single ecosystem responsibility. [`MtlsDialer::dial`] aggregates a [`MethodOutcome`]'s candidate
14//! addresses into a [`dig_ip::PeerCandidates`] and calls [`dig_ip::connect`], handing it the local
15//! host's [`dig_ip::LocalStack`] and a closure that performs one candidate's raw TCP connect.
16//! `dig-ip` then dials over the **local∩peer family intersection** (never a family the local host or
17//! the peer lacks — its structural guarantee), IPv6-first with graceful IPv4 fallback. Once a TCP
18//! connection wins, the single mTLS handshake runs over it — the identity/cert behaviour below is
19//! unchanged; only the family selection + racing moved out. See `dig-ip`'s `SPEC.md`.
20
21use std::sync::Arc;
22
23use async_trait::async_trait;
24use dig_ip::{CandidateSource, DialConfig, LocalStack, PeerCandidates};
25use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName};
26use rustls::ClientConfig;
27use tokio::net::TcpStream;
28use tokio_rustls::TlsConnector;
29
30use crate::config::LocalIdentity;
31use crate::error::MethodError;
32use crate::method::{MethodOutcome, TraversalKind};
33use crate::mtls::{CapturedPeerId, PeerIdPinningVerifier};
34use crate::peer::{PeerConnection, PeerTarget};
35use crate::strategy::Dialer;
36
37/// Tuning for the happy-eyeballs candidate race: how long each candidate connect may take, and how
38/// long to wait before ALSO starting the next (lower-priority) candidate. A thin dig-nat-facing view
39/// of [`dig_ip::DialConfig`] (which the dial converts it into) so the public dialer API stays stable.
40#[derive(Debug, Clone, Copy)]
41pub struct HappyEyeballsConfig {
42 /// Hard timeout for a single candidate's connect attempt.
43 pub per_attempt_timeout: std::time::Duration,
44 /// Delay before starting the next candidate while the current one is still in flight (RFC 8305
45 /// "Connection Attempt Delay"). A small value (tens of ms) hedges a stalled IPv6 without racing
46 /// so hard that IPv4 routinely beats a viable IPv6.
47 pub stagger: std::time::Duration,
48}
49
50impl Default for HappyEyeballsConfig {
51 fn default() -> Self {
52 // RFC 8305 recommends a ~250ms connection-attempt delay; the per-attempt timeout is kept
53 // generous (the strategy's per-method timeout is the real outer bound).
54 HappyEyeballsConfig {
55 per_attempt_timeout: std::time::Duration::from_secs(10),
56 stagger: std::time::Duration::from_millis(250),
57 }
58 }
59}
60
61impl From<HappyEyeballsConfig> for DialConfig {
62 fn from(cfg: HappyEyeballsConfig) -> DialConfig {
63 DialConfig {
64 per_attempt_timeout: cfg.per_attempt_timeout,
65 attempt_delay: cfg.stagger,
66 }
67 }
68}
69
70/// Aggregate a traversal [`MethodOutcome`]'s dial addresses into a family-tagged
71/// [`dig_ip::PeerCandidates`] — the input `dig_ip::connect` filters by the local∩peer intersection.
72///
73/// The candidate ordering + IPv6-first preference is `dig-ip`'s job, so the addresses are added in
74/// the order the traversal produced them; `dig-ip` derives each family and orders IPv6-first. The
75/// [`CandidateSource`] tag is provenance/observability only (it never influences the intersection
76/// rule): a relay-coordinated or relayed endpoint is tagged [`CandidateSource::RelayIntroduction`],
77/// every direct/port-mapping endpoint the peer's advertised [`CandidateSource::ListenAddr`].
78pub fn candidates_from_outcome(outcome: &MethodOutcome) -> PeerCandidates {
79 let source = match outcome.kind {
80 TraversalKind::HolePunch | TraversalKind::Relayed => CandidateSource::RelayIntroduction,
81 TraversalKind::Direct
82 | TraversalKind::Upnp
83 | TraversalKind::NatPmp
84 | TraversalKind::Pcp => CandidateSource::ListenAddr,
85 };
86 let mut candidates = PeerCandidates::new();
87 candidates.extend(outcome.dial_addrs.iter().copied(), source);
88 candidates
89}
90
91/// The production mTLS dialer. Holds this node's [`LocalIdentity`] (its client certificate for
92/// mutual TLS) and builds a fresh pinning verifier per dial. The candidate race is tuned by
93/// [`MtlsDialer::happy_eyeballs`], and the local stack it dials from by [`MtlsDialer::local_stack`].
94#[derive(Debug, Clone)]
95pub struct MtlsDialer {
96 identity: LocalIdentity,
97 happy_eyeballs: HappyEyeballsConfig,
98 /// The local host's address-family capability used to filter the dial (`dig-ip`'s G1 gate).
99 /// `None` = probe the real host per dial via [`LocalStack::cached`]; `Some` pins a deterministic
100 /// stack (used by tests to exercise the intersection matrix without a host dependency).
101 local_stack: Option<LocalStack>,
102}
103
104impl MtlsDialer {
105 /// Build a dialer that authenticates as `identity` (presents its cert as the mTLS client cert),
106 /// using the default happy-eyeballs tuning and the real host's detected address-family stack.
107 pub fn new(identity: LocalIdentity) -> Self {
108 MtlsDialer {
109 identity,
110 happy_eyeballs: HappyEyeballsConfig::default(),
111 local_stack: None,
112 }
113 }
114
115 /// Override the happy-eyeballs (IPv6-first candidate race) tuning.
116 pub fn with_happy_eyeballs(mut self, config: HappyEyeballsConfig) -> Self {
117 self.happy_eyeballs = config;
118 self
119 }
120
121 /// Pin the local address-family stack the dial filters against, instead of probing the real host.
122 /// The dial NEVER attempts a family this stack lacks (`dig-ip`'s G1 guarantee) — this seam lets a
123 /// test drive the intersection deterministically (`LocalStack::from_flags`).
124 pub fn with_local_stack(mut self, stack: LocalStack) -> Self {
125 self.local_stack = Some(stack);
126 self
127 }
128
129 /// Construct the rustls [`ClientConfig`] for one dial: present our client cert, and verify the
130 /// server (peer) via the [`PeerIdPinningVerifier`] pinned to `expected` (the peer we want).
131 fn client_config(
132 &self,
133 expected: crate::identity::PeerId,
134 captured: CapturedPeerId,
135 ) -> Result<ClientConfig, String> {
136 let cert = CertificateDer::from(self.identity.cert_der.clone());
137 // `key_der` is `Zeroizing<Vec<u8>>` (#179 finding 4); `.to_vec()` copies the bytes out into
138 // a plain `Vec<u8>` for rustls (which takes ownership into its own `PrivateKeyDer`) — the
139 // `Zeroizing` original still scrubs itself on drop as normal.
140 let key = PrivateKeyDer::try_from(self.identity.key_der.to_vec())
141 .map_err(|e| format!("invalid private key: {e}"))?;
142
143 let verifier = Arc::new(PeerIdPinningVerifier::new(Some(expected), captured));
144 ClientConfig::builder()
145 .dangerous()
146 .with_custom_certificate_verifier(verifier)
147 .with_client_auth_cert(vec![cert], key)
148 .map_err(|e| format!("client cert config: {e}"))
149 }
150}
151
152#[async_trait]
153impl Dialer for MtlsDialer {
154 async fn dial(
155 &self,
156 peer: &PeerTarget,
157 outcome: &MethodOutcome,
158 ) -> Result<PeerConnection, MethodError> {
159 let kind = outcome.kind;
160
161 // Delegate family selection + racing to dig-ip: it dials only the local∩peer family
162 // intersection (never a family the local host or the peer lacks), IPv6-first with graceful
163 // IPv4 fallback. A disjoint pair fails immediately with `NoCommonFamily` — no doomed attempt
164 // that can only time out. The winning stream carries its own peer address, so `remote_addr`
165 // reflects the family actually used.
166 let local = self.local_stack.unwrap_or_else(LocalStack::cached);
167 let candidates = candidates_from_outcome(outcome);
168 let winner = dig_ip::connect(
169 &local,
170 &candidates,
171 self.happy_eyeballs.into(),
172 |addr| async move {
173 TcpStream::connect(addr)
174 .await
175 .map_err(|e| format!("tcp connect {addr}: {e}"))
176 },
177 )
178 .await
179 .map_err(|e| MethodError::failed(kind, e.to_string()))?;
180 let tcp = winner.conn;
181 let addr = winner.addr;
182
183 let captured = CapturedPeerId::default();
184 let config = self
185 .client_config(peer.peer_id, captured.clone())
186 .map_err(|e| MethodError::failed(kind, e))?;
187 let connector = TlsConnector::from(Arc::new(config));
188
189 // The server name is irrelevant to identity here (we verify by peer_id via the pinning
190 // verifier, not by hostname/CA), but rustls requires a syntactically valid SNI. A peer_id
191 // hex (64 chars) is not a valid DNS label (>63), so we use a fixed, well-formed placeholder.
192 let server_name = ServerName::try_from("peer.dig.invalid")
193 .map_err(|e| MethodError::failed(kind, format!("server name: {e}")))?;
194
195 let tls = connector
196 .connect(server_name, tcp)
197 .await
198 .map_err(|e| classify_tls_error(kind, &e))?;
199
200 // The pinning verifier already rejected a mismatch; this is the authenticated identity.
201 let verified = captured
202 .get()
203 .ok_or_else(|| MethodError::failed(kind, "peer presented no certificate"))?;
204
205 // Wrap the single mTLS byte stream in yamux so the caller can open many concurrent
206 // (range-)streams over it — the streaming-first, multiplexed transport is uniform across
207 // every traversal tier.
208 let session = crate::mux::PeerSession::client(tls);
209
210 Ok(PeerConnection {
211 peer_id: verified,
212 method: kind,
213 remote_addr: addr,
214 session,
215 })
216 }
217}
218
219/// Map a rustls handshake error to a [`MethodError`], surfacing a peer_id mismatch clearly (it
220/// arrives as a general error from the verifier).
221fn classify_tls_error(kind: TraversalKind, e: &std::io::Error) -> MethodError {
222 let msg = e.to_string();
223 MethodError::failed(kind, format!("mtls handshake: {msg}"))
224}