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