Skip to main content

open_net/api/
network_config.rs

1//! Immutable network policy used as an engine default or overridden per client.
2//!
3//! The current release applies this policy to WebSocket clients; it does not create HTTP executors.
4//! Credentials and certificates are supplied in memory. A client-specific
5//! policy replaces engine defaults, including TLS settings, and remains
6//! immutable for that client's lifetime.
7
8use crate::error::NetError;
9use base64::Engine;
10use rustls::pki_types::pem::PemObject;
11use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
12use rustls::sign::CertifiedKey;
13use std::fmt;
14use std::sync::Arc;
15use tokio_tungstenite::tungstenite::http::Uri;
16
17const MAX_PEM_BYTES: usize = 1024 * 1024;
18const MAX_CERTIFICATES: usize = 128;
19
20/// Proxy, TLS, and network-status policy; defaults to direct connections and WebPKI roots.
21///
22/// Use [`crate::OpenNet::new_with_network_config`] for the engine default or
23/// [`crate::OpenNet::create_ws_client_with_network_config`] for a client override.
24/// Passing `NetworkConfig::default()` explicitly selects direct connections and
25/// the built-in trust roots; clone an existing value when changing one setting.
26#[derive(Clone, Debug, Default)]
27pub struct NetworkConfig {
28    pub(crate) proxy: ProxyConfig,
29    pub(crate) tls: TlsConfig,
30    pub(crate) network_status_policy: NetworkStatusPolicy,
31}
32
33impl NetworkConfig {
34    /// Replaces the proxy policy.
35    pub fn with_proxy(mut self, proxy: ProxyConfig) -> Self {
36        self.proxy = proxy;
37        self
38    }
39
40    /// Replaces the TLS policy.
41    pub fn with_tls(mut self, tls: TlsConfig) -> Self {
42        self.tls = tls;
43        self
44    }
45
46    /// Selects how connections respond to network-monitor state changes.
47    /// The default is [`NetworkStatusPolicy::Ignore`].
48    pub fn with_network_status_policy(mut self, policy: NetworkStatusPolicy) -> Self {
49        self.network_status_policy = policy;
50        self
51    }
52
53    /// Returns the current proxy policy by reference without exposing credentials.
54    pub fn proxy(&self) -> &ProxyConfig {
55        &self.proxy
56    }
57
58    /// Returns the current TLS policy by reference.
59    pub fn tls(&self) -> &TlsConfig {
60        &self.tls
61    }
62
63    /// Returns the policy used when monitor reachability changes.
64    pub fn network_status_policy(&self) -> NetworkStatusPolicy {
65        self.network_status_policy
66    }
67
68    /// Validates this configuration without creating connections, runtimes, or
69    /// background tasks. Trust roots and client identity are checked here;
70    /// policy interactions with reconnect budgets are checked by the connector.
71    pub fn validate(&self) -> Result<(), NetError> {
72        if self
73            .proxy
74            .endpoint
75            .as_ref()
76            .is_some_and(|proxy| proxy.host.is_empty() || proxy.port == 0)
77        {
78            return Err(NetError::config(
79                "proxy.url",
80                "requires a host and nonzero port",
81            ));
82        }
83        if self.tls.roots.len() > MAX_CERTIFICATES
84            || (self.tls.root_mode == RootCertificateMode::Replace && self.tls.roots.is_empty())
85        {
86            return Err(NetError::config(
87                "tls.root_certificates",
88                "replacement roots must be nonempty and bounded",
89            ));
90        }
91        let mut roots = rustls::RootCertStore::empty();
92        for certificate in &self.tls.roots {
93            roots.add(certificate.clone()).map_err(|_| {
94                NetError::config("tls.root_certificates", "invalid root certificate")
95            })?;
96        }
97        if let Some(identity) = &self.tls.identity {
98            identity.certified_key.keys_match().map_err(|_| {
99                NetError::config(
100                    "tls.client_identity.private_key",
101                    "private key does not match certificate",
102                )
103            })?;
104        }
105        Ok(())
106    }
107}
108
109/// Controls whether local reachability participates in WebSocket connection control.
110#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
111#[non_exhaustive]
112pub enum NetworkStatusPolicy {
113    /// Preserve existing behavior and rely on heartbeats and transport errors.
114    #[default]
115    Ignore,
116    /// Invalidate active connections and pause attempts while the monitor reports
117    /// unavailable, retaining eligible connection intent for later recovery.
118    /// Recovery remains bounded by the reconnect policy's elapsed-time budget;
119    /// connections using this policy must configure
120    /// `ReconnectPolicy::max_elapsed` as `Some(...)`.
121    PauseOnUnavailable,
122}
123
124/// Explicit proxy routing. Defaults to direct connections and never reads proxy environment variables.
125#[derive(Clone, Default)]
126pub struct ProxyConfig {
127    pub(crate) endpoint: Option<ProxyEndpoint>,
128}
129
130#[derive(Clone)]
131pub(crate) struct ProxyEndpoint {
132    pub(crate) host: String,
133    pub(crate) port: u16,
134    pub(crate) auth: Option<ProxyBasicAuth>,
135    normalized_url: String,
136}
137
138impl ProxyConfig {
139    /// Selects direct connections without consulting proxy environment variables.
140    pub fn direct() -> Self {
141        Self::default()
142    }
143
144    /// Routes `ws` and `wss` targets through an HTTP CONNECT tunnel.
145    ///
146    /// Accepts only `http://host[:port]`; credentials must be supplied separately.
147    /// A plain HTTP proxy does not encrypt Basic credentials, even for `wss` targets.
148    pub fn http_connect(url: &str, auth: Option<ProxyBasicAuth>) -> Result<Self, NetError> {
149        if url.len() > 2048 || url.contains('#') {
150            return Err(NetError::config("proxy.url", "requires a valid HTTP CONNECT URL with a nonzero port and no credentials, path, query, or fragment"));
151        }
152        let uri: Uri = url.parse().map_err(|_| NetError::config("proxy.url", "requires a valid HTTP CONNECT URL with a nonzero port and no credentials, path, query, or fragment"))?;
153        let authority = uri.authority().ok_or(NetError::config("proxy.url", "requires a valid HTTP CONNECT URL with a nonzero port and no credentials, path, query, or fragment"))?;
154        if uri.scheme_str() != Some("http")
155            || authority.as_str().contains('@')
156            || uri
157                .path_and_query()
158                .is_some_and(|path| path.as_str() != "/")
159        {
160            return Err(NetError::config("proxy.url", "requires a valid HTTP CONNECT URL with a nonzero port and no credentials, path, query, or fragment"));
161        }
162        let host = authority.host();
163        if normalize_host(host).is_empty() {
164            return Err(NetError::config("proxy.url", "requires a valid HTTP CONNECT URL with a nonzero port and no credentials, path, query, or fragment"));
165        }
166        if host.starts_with('[') && normalize_host(host).parse::<std::net::Ipv6Addr>().is_err() {
167            return Err(NetError::config("proxy.url", "requires a valid HTTP CONNECT URL with a nonzero port and no credentials, path, query, or fragment"));
168        }
169        // Authority::port() is also None for malformed numeric ports; distinguish
170        // an omitted port from an explicitly invalid one before applying port 80.
171        let suffix = authority
172            .as_str()
173            .strip_prefix(host)
174            .ok_or(NetError::config("proxy.url", "requires a valid HTTP CONNECT URL with a nonzero port and no credentials, path, query, or fragment"))?;
175        let port = match suffix {
176            "" => 80,
177            value => {
178                let digits = value.strip_prefix(':').ok_or(NetError::config("proxy.url", "requires a valid HTTP CONNECT URL with a nonzero port and no credentials, path, query, or fragment"))?;
179                if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
180                    return Err(NetError::config("proxy.url", "requires a valid HTTP CONNECT URL with a nonzero port and no credentials, path, query, or fragment"));
181                }
182                digits.parse::<u16>().map_err(|_| NetError::config("proxy.url", "requires a valid HTTP CONNECT URL with a nonzero port and no credentials, path, query, or fragment"))?
183            }
184        };
185        if port == 0 {
186            return Err(NetError::config("proxy.url", "requires a valid HTTP CONNECT URL with a nonzero port and no credentials, path, query, or fragment"));
187        }
188        Ok(Self {
189            endpoint: Some(ProxyEndpoint {
190                host: normalize_host(host).to_owned(),
191                port,
192                auth,
193                normalized_url: format!("http://{}:{port}", host.to_ascii_lowercase()),
194            }),
195        })
196    }
197
198    /// Returns `true` when connections bypass a proxy.
199    pub fn is_direct(&self) -> bool {
200        self.endpoint.is_none()
201    }
202
203    /// Returns the credential-free normalized HTTP proxy URL, or `None` for direct mode.
204    pub fn endpoint(&self) -> Option<&str> {
205        self.endpoint
206            .as_ref()
207            .map(|proxy| proxy.normalized_url.as_str())
208    }
209
210    /// Returns whether proxy credentials are configured.
211    pub fn is_authenticated(&self) -> bool {
212        self.endpoint
213            .as_ref()
214            .is_some_and(|proxy| proxy.auth.is_some())
215    }
216}
217
218impl fmt::Debug for ProxyConfig {
219    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
220        formatter
221            .debug_struct("ProxyConfig")
222            .field(
223                "mode",
224                &if self.endpoint.is_some() {
225                    "HttpConnect"
226                } else {
227                    "Direct"
228                },
229            )
230            .field(
231                "authenticated",
232                &self
233                    .endpoint
234                    .as_ref()
235                    .is_some_and(|proxy| proxy.auth.is_some()),
236            )
237            .finish()
238    }
239}
240
241/// ASCII Basic proxy credentials; `Debug` output always redacts the secret.
242#[derive(Clone)]
243pub struct ProxyBasicAuth {
244    pub(crate) encoded: Arc<str>,
245}
246
247impl ProxyBasicAuth {
248    /// Rejects non-ASCII/control characters and colons in usernames. Passwords
249    /// may contain ordinary colons; each component is limited to 4096 bytes.
250    pub fn new(username: &str, password: &str) -> Result<Self, NetError> {
251        if username.len() > 4096
252            || username.contains(':')
253            || username
254                .bytes()
255                .any(|byte| !byte.is_ascii() || byte.is_ascii_control())
256        {
257            return Err(NetError::config(
258                "proxy.username",
259                "must be at most 4096 ASCII bytes without control characters or a colon",
260            ));
261        }
262        if password.len() > 4096
263            || password
264                .bytes()
265                .any(|byte| !byte.is_ascii() || byte.is_ascii_control())
266        {
267            return Err(NetError::config(
268                "proxy.password",
269                "must be at most 4096 ASCII bytes without control characters",
270            ));
271        }
272        let credentials = format!("{username}:{password}");
273        Ok(Self {
274            encoded: base64::engine::general_purpose::STANDARD
275                .encode(credentials)
276                .into(),
277        })
278    }
279}
280
281impl fmt::Debug for ProxyBasicAuth {
282    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
283        formatter.write_str("ProxyBasicAuth([redacted])")
284    }
285}
286
287/// Defines how supplied CA certificates combine with built-in WebPKI roots.
288#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
289#[non_exhaustive]
290pub enum RootCertificateMode {
291    #[default]
292    /// Append custom roots to the built-in WebPKI roots.
293    Append,
294    /// Replace built-in roots with the custom set.
295    Replace,
296}
297
298/// Strict server-certificate validation with optional client authentication.
299#[derive(Clone, Default)]
300pub struct TlsConfig {
301    pub(crate) roots: Vec<CertificateDer<'static>>,
302    pub(crate) root_mode: RootCertificateMode,
303    pub(crate) identity: Option<ClientIdentity>,
304}
305
306impl fmt::Debug for TlsConfig {
307    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
308        formatter
309            .debug_struct("TlsConfig")
310            .field("custom_certificate_count", &self.roots.len())
311            .field("root_mode", &self.root_mode)
312            .field("client_identity_configured", &self.identity.is_some())
313            .finish()
314    }
315}
316
317impl TlsConfig {
318    /// Replaces the custom CA bundle and selects its trust mode. Accepts one to
319    /// 128 PEM certificates with a total size of at most 1 MiB; malformed,
320    /// mismatched, or trailing non-whitespace blocks are rejected.
321    pub fn with_root_certificates(
322        mut self,
323        pem: impl AsRef<[u8]>,
324        mode: RootCertificateMode,
325    ) -> Result<Self, NetError> {
326        self.roots = parse_certificates(pem.as_ref(), "tls.root_certificates")?;
327        self.root_mode = mode;
328        Ok(self)
329    }
330
331    /// Configures a client certificate identity.
332    pub fn with_client_identity(mut self, identity: ClientIdentity) -> Self {
333        self.identity = Some(identity);
334        self
335    }
336
337    /// Returns how custom roots are combined with built-in roots.
338    pub fn root_mode(&self) -> RootCertificateMode {
339        self.root_mode
340    }
341
342    /// Returns the number of custom roots, excluding built-in WebPKI roots.
343    pub fn custom_root_count(&self) -> usize {
344        self.roots.len()
345    }
346
347    /// Returns the configured client identity, if any.
348    pub fn client_identity(&self) -> Option<&ClientIdentity> {
349        self.identity.as_ref()
350    }
351}
352
353/// A validated client certificate chain and its matching PKCS#8 private key.
354#[derive(Clone)]
355pub struct ClientIdentity {
356    pub(crate) certified_key: Arc<CertifiedKey>,
357}
358
359impl ClientIdentity {
360    /// Loads a PEM certificate chain and exactly one unencrypted PKCS#8 key.
361    /// Each input is limited to 1 MiB and the chain to 128 certificates.
362    pub fn from_pem(
363        certificates: impl AsRef<[u8]>,
364        private_key: impl AsRef<[u8]>,
365    ) -> Result<Self, NetError> {
366        let certificates =
367            parse_certificates(certificates.as_ref(), "tls.client_identity.certificates")?;
368        let blocks = strict_pem_blocks(
369            private_key.as_ref(),
370            "PRIVATE KEY",
371            "tls.client_identity.private_key",
372        )?;
373        if blocks.len() != 1 {
374            return Err(NetError::config(
375                "tls.client_identity.private_key",
376                "requires one valid PKCS#8 private key matching the certificate",
377            ));
378        }
379        let block = blocks.first().ok_or(NetError::config(
380            "tls.client_identity.private_key",
381            "requires one valid PKCS#8 private key matching the certificate",
382        ))?;
383        let key = PrivatePkcs8KeyDer::from_pem_slice(block).map_err(|_| {
384            NetError::config(
385                "tls.client_identity.private_key",
386                "requires one valid PKCS#8 private key matching the certificate",
387            )
388        })?;
389        let certified_key = CertifiedKey::from_der(
390            certificates,
391            PrivateKeyDer::Pkcs8(key),
392            &crate::module::tls::local_provider(),
393        )
394        .map_err(|_| {
395            NetError::config(
396                "tls.client_identity.private_key",
397                "requires one valid PKCS#8 private key matching the certificate",
398            )
399        })?;
400        certified_key.keys_match().map_err(|_| {
401            NetError::config(
402                "tls.client_identity.private_key",
403                "requires one valid PKCS#8 private key matching the certificate",
404            )
405        })?;
406        Ok(Self {
407            certified_key: Arc::new(certified_key),
408        })
409    }
410
411    /// Returns the number of certificates in the validated client chain.
412    /// Returns the number of certificates in the validated chain.
413    pub fn certificate_count(&self) -> usize {
414        self.certified_key.cert.len()
415    }
416}
417
418impl fmt::Debug for ClientIdentity {
419    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
420        formatter
421            .debug_struct("ClientIdentity")
422            .field("certificate_count", &self.certified_key.cert.len())
423            .field("private_key", &"[redacted]")
424            .finish()
425    }
426}
427
428pub(crate) fn normalize_host(host: &str) -> &str {
429    host.strip_prefix('[')
430        .and_then(|host| host.strip_suffix(']'))
431        .unwrap_or(host)
432}
433
434fn parse_certificates(pem: &[u8], field: &str) -> Result<Vec<CertificateDer<'static>>, NetError> {
435    let blocks = strict_pem_blocks(pem, "CERTIFICATE", field)?;
436    let mut certificates = Vec::new();
437    certificates
438        .try_reserve(blocks.len())
439        .map_err(|_| NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?;
440    let mut validation = rustls::RootCertStore::empty();
441    for block in blocks {
442        let cert = CertificateDer::from_pem_slice(block).map_err(|_| NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?;
443        validation
444            .add(cert.clone())
445            .map_err(|_| NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?;
446        certificates.push(cert);
447    }
448    Ok(certificates)
449}
450
451fn strict_pem_blocks<'a>(
452    pem: &'a [u8],
453    label: &str,
454    field: &str,
455) -> Result<Vec<&'a [u8]>, NetError> {
456    if pem.is_empty() || pem.len() > MAX_PEM_BYTES {
457        return Err(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"));
458    }
459    let mut remaining = std::str::from_utf8(pem)
460        .map_err(|_| NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?
461        .trim();
462    let begin = format!("-----BEGIN {label}-----");
463    let end = format!("-----END {label}-----");
464    let mut blocks = Vec::new();
465    while !remaining.is_empty() {
466        if blocks.len() == MAX_CERTIFICATES || !remaining.starts_with(&begin) {
467            return Err(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"));
468        }
469        let boundary = remaining
470            .find(&end)
471            .and_then(|index| index.checked_add(end.len()))
472            .ok_or(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?;
473        let block = remaining.get(..boundary).ok_or(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?;
474        if block
475            .get(begin.len()..)
476            .ok_or(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?
477            .contains("-----BEGIN ")
478        {
479            return Err(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"));
480        }
481        blocks.try_reserve(1).map_err(|_| NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?;
482        blocks.push(block.as_bytes());
483        remaining = remaining
484            .get(boundary..)
485            .ok_or(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?
486            .trim();
487    }
488    if blocks.is_empty() {
489        return Err(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"));
490    }
491    Ok(blocks)
492}