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::client::Resumption;
12use rustls::pki_types::pem::PemObject;
13use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
14use rustls::sign::{CertifiedKey, SingleCertAndKey};
15use std::fmt;
16use std::sync::Arc;
17use tokio_tungstenite::tungstenite::http::Uri;
18
19const MAX_PEM_BYTES: usize = 1024 * 1024;
20const MAX_CERTIFICATES: usize = 128;
21
22/// Proxy, TLS, and network-status policy; defaults to direct connections and WebPKI roots.
23///
24/// Use [`crate::OpenNet::new_with_network_config`] for the engine default or
25/// [`crate::OpenNet::create_ws_client_with_network_config`] for a client override.
26/// Passing `NetworkConfig::default()` explicitly selects direct connections and
27/// the built-in trust roots; clone an existing value when changing one setting.
28#[derive(Clone, Debug, Default)]
29pub struct NetworkConfig {
30    pub(crate) proxy: ProxyConfig,
31    pub(crate) tls: TlsConfig,
32    pub(crate) network_status_policy: NetworkStatusPolicy,
33}
34
35impl NetworkConfig {
36    /// Replaces the proxy policy.
37    pub fn with_proxy(mut self, proxy: ProxyConfig) -> Self {
38        self.proxy = proxy;
39        self
40    }
41
42    /// Replaces the target WSS TLS policy. HTTPS proxy TLS is configured
43    /// independently on [`ProxyConfig::https_connect`].
44    pub fn with_tls(mut self, tls: TlsConfig) -> Self {
45        self.tls = tls;
46        self
47    }
48
49    /// Selects how connections respond to network-monitor state changes.
50    /// The default is [`NetworkStatusPolicy::Ignore`].
51    pub fn with_network_status_policy(mut self, policy: NetworkStatusPolicy) -> Self {
52        self.network_status_policy = policy;
53        self
54    }
55
56    /// Returns the current proxy policy by reference without exposing credentials.
57    pub fn proxy(&self) -> &ProxyConfig {
58        &self.proxy
59    }
60
61    /// Returns the target WSS TLS policy by reference.
62    pub fn tls(&self) -> &TlsConfig {
63        &self.tls
64    }
65
66    /// Returns the policy used when monitor reachability changes.
67    pub fn network_status_policy(&self) -> NetworkStatusPolicy {
68        self.network_status_policy
69    }
70
71    /// Validates this configuration without creating connections, runtimes, or
72    /// background tasks. Trust roots and client identity are checked here;
73    /// policy interactions with reconnect budgets are checked by the connector.
74    pub fn validate(&self) -> Result<(), NetError> {
75        self.proxy.validate()?;
76        self.tls.validate_for(TlsRole::Target)
77    }
78}
79
80/// Controls whether local reachability participates in WebSocket connection control.
81#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
82#[non_exhaustive]
83pub enum NetworkStatusPolicy {
84    /// Preserve existing behavior and rely on heartbeats and transport errors.
85    #[default]
86    Ignore,
87    /// Invalidate active connections and pause attempts while the monitor reports
88    /// unavailable, retaining eligible connection intent for later recovery.
89    /// Recovery remains bounded by the reconnect policy's elapsed-time budget;
90    /// connections using this policy must configure
91    /// `ReconnectPolicy::max_elapsed` as `Some(...)`.
92    PauseOnUnavailable,
93}
94
95/// Explicit proxy routing. Defaults to direct connections and never reads proxy environment variables.
96#[derive(Clone, Default)]
97pub struct ProxyConfig {
98    pub(crate) endpoint: Option<ProxyEndpoint>,
99}
100
101#[derive(Clone)]
102pub(crate) struct ProxyEndpoint {
103    pub(crate) host: String,
104    pub(crate) port: u16,
105    pub(crate) auth: Option<ProxyBasicAuth>,
106    pub(crate) transport: ProxyTransport,
107    pub(crate) auth_transport_policy: ProxyAuthTransportPolicy,
108    normalized_url: String,
109}
110
111#[derive(Clone)]
112pub(crate) enum ProxyTransport {
113    Http,
114    Https(TlsConfig),
115}
116
117/// Controls whether proxy credentials may be sent without TLS to the proxy.
118///
119/// Target `wss` encryption starts after CONNECT and does not protect HTTP proxy
120/// authentication. Localhost and private-network proxies receive no exemption.
121#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
122#[non_exhaustive]
123pub enum ProxyAuthTransportPolicy {
124    /// Reject authentication unless the connection to the proxy uses TLS.
125    #[default]
126    RequireTls,
127    /// Explicitly permit Basic credentials on a plaintext HTTP connection.
128    AllowPlaintext,
129}
130
131impl ProxyConfig {
132    /// Selects direct connections without consulting proxy environment variables.
133    pub fn direct() -> Self {
134        Self::default()
135    }
136
137    /// Routes `ws` and `wss` targets through an HTTP CONNECT tunnel.
138    ///
139    /// Accepts only `http://host[:port]`; credentials must be supplied separately.
140    /// Authentication is rejected before any network activity. Use
141    /// [`Self::https_connect`] to protect credentials, or explicitly opt in with
142    /// [`Self::http_connect_with_auth_policy`] and
143    /// [`ProxyAuthTransportPolicy::AllowPlaintext`].
144    pub fn http_connect(url: &str, auth: Option<ProxyBasicAuth>) -> Result<Self, NetError> {
145        Self::http_connect_with_auth_policy(url, auth, ProxyAuthTransportPolicy::RequireTls)
146    }
147
148    /// Routes targets through an HTTP CONNECT tunnel using the explicit
149    /// authentication transport policy.
150    ///
151    /// `AllowPlaintext` permits credentials to be sent without encryption,
152    /// including when the target uses `wss`. This is an explicit compatibility
153    /// exception; prefer [`Self::https_connect`].
154    pub fn http_connect_with_auth_policy(
155        url: &str,
156        auth: Option<ProxyBasicAuth>,
157        policy: ProxyAuthTransportPolicy,
158    ) -> Result<Self, NetError> {
159        Self::connect(url, auth, ProxyTransport::Http, policy)
160    }
161
162    /// Establishes TLS to an HTTPS proxy before sending HTTP/1.1 CONNECT.
163    ///
164    /// Accepts only `https://host[:port]`, with port 443 by default. Proxy
165    /// certificates are validated against the URL host using `proxy_tls`.
166    /// Proxy roots, client identity, and explicit provider are independent of
167    /// [`NetworkConfig::with_tls`]. Failure never falls back to plaintext.
168    /// For `ws` targets, only the client-to-proxy connection is encrypted.
169    pub fn https_connect(
170        url: &str,
171        auth: Option<ProxyBasicAuth>,
172        proxy_tls: TlsConfig,
173    ) -> Result<Self, NetError> {
174        Self::connect(
175            url,
176            auth,
177            ProxyTransport::Https(proxy_tls),
178            ProxyAuthTransportPolicy::RequireTls,
179        )
180    }
181
182    fn connect(
183        url: &str,
184        auth: Option<ProxyBasicAuth>,
185        transport: ProxyTransport,
186        auth_transport_policy: ProxyAuthTransportPolicy,
187    ) -> Result<Self, NetError> {
188        let (scheme, default_port) = match &transport {
189            ProxyTransport::Http => ("http", 80),
190            ProxyTransport::Https(_) => ("https", 443),
191        };
192        let invalid_url = || {
193            NetError::config(
194                "proxy.url",
195                "requires a CONNECT URL with the constructor's scheme, a nonzero port, and no credentials, path, query, or fragment",
196            )
197        };
198        if url.len() > 2048 || url.contains('#') {
199            return Err(invalid_url());
200        }
201        let uri: Uri = url.parse().map_err(|_| invalid_url())?;
202        let authority = uri.authority().ok_or_else(invalid_url)?;
203        if uri.scheme_str() != Some(scheme)
204            || authority.as_str().contains('@')
205            || uri
206                .path_and_query()
207                .is_some_and(|path| path.as_str() != "/")
208        {
209            return Err(invalid_url());
210        }
211        let host = authority.host();
212        if normalize_host(host).is_empty() {
213            return Err(invalid_url());
214        }
215        if host.starts_with('[') && normalize_host(host).parse::<std::net::Ipv6Addr>().is_err() {
216            return Err(invalid_url());
217        }
218        // Authority::port() is also None for malformed numeric ports; distinguish
219        // an omitted port from an explicitly invalid one before applying a default.
220        let suffix = authority
221            .as_str()
222            .strip_prefix(host)
223            .ok_or_else(invalid_url)?;
224        let port = match suffix {
225            "" => default_port,
226            value => {
227                let digits = value.strip_prefix(':').ok_or_else(invalid_url)?;
228                if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
229                    return Err(invalid_url());
230                }
231                digits.parse::<u16>().map_err(|_| invalid_url())?
232            }
233        };
234        if port == 0 {
235            return Err(invalid_url());
236        }
237        let config = Self {
238            endpoint: Some(ProxyEndpoint {
239                host: normalize_host(host).to_owned(),
240                port,
241                auth,
242                transport,
243                auth_transport_policy,
244                normalized_url: format!("{scheme}://{}:{port}", host.to_ascii_lowercase()),
245            }),
246        };
247        config.validate_auth_transport()?;
248        if let Some(tls) = config.proxy_tls() {
249            tls.validate_material_for(TlsRole::Proxy)?;
250        }
251        Ok(config)
252    }
253
254    pub(crate) fn validate(&self) -> Result<(), NetError> {
255        self.validate_auth_transport()?;
256        if let Some(tls) = self.proxy_tls() {
257            tls.validate_for(TlsRole::Proxy)?;
258        }
259        Ok(())
260    }
261
262    /// Recheck the credential policy without loading certificates or private keys.
263    /// Safe to call immediately before each connection attempt.
264    pub(crate) fn validate_auth_transport(&self) -> Result<(), NetError> {
265        let Some(proxy) = &self.endpoint else {
266            return Ok(());
267        };
268        if proxy.host.is_empty() || proxy.port == 0 {
269            return Err(NetError::config(
270                "proxy.url",
271                "requires a host and nonzero port",
272            ));
273        }
274        match &proxy.transport {
275            ProxyTransport::Http
276                if proxy.auth.is_some()
277                    && proxy.auth_transport_policy == ProxyAuthTransportPolicy::RequireTls =>
278            {
279                Err(NetError::config(
280                    "proxy.auth_transport_policy",
281                    "Basic authentication requires HTTPS; plaintext HTTP requires explicit AllowPlaintext",
282                ))
283            }
284            ProxyTransport::Http | ProxyTransport::Https(_) => Ok(()),
285        }
286    }
287
288    /// Returns `true` when connections bypass a proxy.
289    pub fn is_direct(&self) -> bool {
290        self.endpoint.is_none()
291    }
292
293    /// Returns the credential-free normalized HTTP or HTTPS proxy URL, or `None`
294    /// for direct mode.
295    pub fn endpoint(&self) -> Option<&str> {
296        self.endpoint
297            .as_ref()
298            .map(|proxy| proxy.normalized_url.as_str())
299    }
300
301    /// Returns whether proxy credentials are configured.
302    pub fn is_authenticated(&self) -> bool {
303        self.endpoint
304            .as_ref()
305            .is_some_and(|proxy| proxy.auth.is_some())
306    }
307
308    /// Returns the independent TLS configuration for an HTTPS proxy.
309    /// Direct connections and plaintext HTTP proxies return `None`.
310    pub fn proxy_tls(&self) -> Option<&TlsConfig> {
311        match &self.endpoint.as_ref()?.transport {
312            ProxyTransport::Http => None,
313            ProxyTransport::Https(tls) => Some(tls),
314        }
315    }
316
317    /// Returns the configured proxy authentication transport policy, or `None`
318    /// for direct connections. HTTPS proxies always require TLS.
319    pub fn auth_transport_policy(&self) -> Option<ProxyAuthTransportPolicy> {
320        self.endpoint
321            .as_ref()
322            .map(|proxy| proxy.auth_transport_policy)
323    }
324}
325
326impl fmt::Debug for ProxyConfig {
327    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
328        formatter
329            .debug_struct("ProxyConfig")
330            .field(
331                "mode",
332                &match self.endpoint.as_ref().map(|endpoint| &endpoint.transport) {
333                    None => "Direct",
334                    Some(ProxyTransport::Http) => "HttpConnect",
335                    Some(ProxyTransport::Https(_)) => "HttpsConnect",
336                },
337            )
338            .field("auth_transport_policy", &self.auth_transport_policy())
339            .field("proxy_tls", &self.proxy_tls())
340            .field(
341                "authenticated",
342                &self
343                    .endpoint
344                    .as_ref()
345                    .is_some_and(|proxy| proxy.auth.is_some()),
346            )
347            .finish()
348    }
349}
350
351/// ASCII Basic proxy credentials; `Debug` output always redacts the secret.
352#[derive(Clone)]
353pub struct ProxyBasicAuth {
354    pub(crate) encoded: Arc<str>,
355}
356
357impl ProxyBasicAuth {
358    /// Rejects non-ASCII/control characters and colons in usernames. Passwords
359    /// may contain ordinary colons; each component is limited to 4096 bytes.
360    pub fn new(username: &str, password: &str) -> Result<Self, NetError> {
361        if username.len() > 4096
362            || username.contains(':')
363            || username
364                .bytes()
365                .any(|byte| !byte.is_ascii() || byte.is_ascii_control())
366        {
367            return Err(NetError::config(
368                "proxy.username",
369                "must be at most 4096 ASCII bytes without control characters or a colon",
370            ));
371        }
372        if password.len() > 4096
373            || password
374                .bytes()
375                .any(|byte| !byte.is_ascii() || byte.is_ascii_control())
376        {
377            return Err(NetError::config(
378                "proxy.password",
379                "must be at most 4096 ASCII bytes without control characters",
380            ));
381        }
382        let credentials = format!("{username}:{password}");
383        Ok(Self {
384            encoded: base64::engine::general_purpose::STANDARD
385                .encode(credentials)
386                .into(),
387        })
388    }
389}
390
391impl fmt::Debug for ProxyBasicAuth {
392    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
393        formatter.write_str("ProxyBasicAuth([redacted])")
394    }
395}
396
397/// Defines how supplied CA certificates combine with built-in WebPKI roots.
398#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
399#[non_exhaustive]
400pub enum RootCertificateMode {
401    #[default]
402    /// Append custom roots to the built-in WebPKI roots.
403    Append,
404    /// Replace built-in roots with the custom set.
405    Replace,
406}
407
408/// Strict server-certificate validation with optional client authentication.
409#[derive(Clone, Default)]
410pub struct TlsConfig {
411    pub(crate) provider: Option<Arc<CryptoProvider>>,
412    pub(crate) roots: Vec<CertificateDer<'static>>,
413    pub(crate) root_mode: RootCertificateMode,
414    pub(crate) identity: Option<ClientIdentity>,
415}
416
417#[derive(Clone, Copy)]
418pub(crate) enum TlsRole {
419    Target,
420    Proxy,
421}
422
423impl TlsRole {
424    fn field(self, name: &str) -> String {
425        match self {
426            Self::Target => format!("tls.{name}"),
427            Self::Proxy => format!("proxy.tls.{name}"),
428        }
429    }
430}
431
432impl fmt::Debug for TlsConfig {
433    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
434        formatter
435            .debug_struct("TlsConfig")
436            .field("crypto_provider_configured", &self.provider.is_some())
437            .field("custom_certificate_count", &self.roots.len())
438            .field("root_mode", &self.root_mode)
439            .field("client_identity_configured", &self.identity.is_some())
440            .finish()
441    }
442}
443
444impl TlsConfig {
445    /// Selects this TLS layer's rustls cryptography without changing global state.
446    ///
447    /// Takes precedence over the application's process default.
448    /// The provider also loads and validates this layer's private key when the
449    /// network configuration is validated or compiled. Proxy and target TLS do
450    /// not inherit each other's explicit provider or client identity.
451    pub fn with_crypto_provider(mut self, provider: Arc<CryptoProvider>) -> Self {
452        self.provider = Some(provider);
453        self
454    }
455
456    /// Returns the explicitly selected provider, if any, without resolving defaults.
457    pub fn crypto_provider(&self) -> Option<&Arc<CryptoProvider>> {
458        self.provider.as_ref()
459    }
460
461    /// Replaces the custom CA bundle and selects its trust mode. Accepts one to
462    /// 128 PEM certificates with a total size of at most 1 MiB; malformed,
463    /// mismatched, or trailing non-whitespace blocks are rejected.
464    pub fn with_root_certificates(
465        mut self,
466        pem: impl AsRef<[u8]>,
467        mode: RootCertificateMode,
468    ) -> Result<Self, NetError> {
469        self.roots = parse_certificates(pem.as_ref(), "tls.root_certificates")?;
470        self.root_mode = mode;
471        Ok(self)
472    }
473
474    /// Configures a client certificate identity.
475    pub fn with_client_identity(mut self, identity: ClientIdentity) -> Self {
476        self.identity = Some(identity);
477        self
478    }
479
480    /// Returns how custom roots are combined with built-in roots.
481    pub fn root_mode(&self) -> RootCertificateMode {
482        self.root_mode
483    }
484
485    /// Returns the number of custom roots, excluding built-in WebPKI roots.
486    pub fn custom_root_count(&self) -> usize {
487        self.roots.len()
488    }
489
490    /// Returns the configured client identity, if any.
491    pub fn client_identity(&self) -> Option<&ClientIdentity> {
492        self.identity.as_ref()
493    }
494
495    pub(crate) fn validate_for(&self, role: TlsRole) -> Result<(), NetError> {
496        self.validate_material_for(role)?;
497        if let Some(identity) = &self.identity {
498            let provider = self.provider_for(role)?;
499            identity.compile_for(&provider, role)?;
500        }
501        Ok(())
502    }
503
504    fn validate_material_for(&self, role: TlsRole) -> Result<(), NetError> {
505        if self.roots.len() > MAX_CERTIFICATES
506            || (self.root_mode == RootCertificateMode::Replace && self.roots.is_empty())
507        {
508            return Err(NetError::config(
509                role.field("root_certificates"),
510                "replacement roots must be nonempty and bounded",
511            ));
512        }
513        let mut roots = rustls::RootCertStore::empty();
514        for certificate in &self.roots {
515            roots.add(certificate.clone()).map_err(|_| {
516                NetError::config(role.field("root_certificates"), "invalid root certificate")
517            })?;
518        }
519        Ok(())
520    }
521
522    fn provider_for(&self, role: TlsRole) -> Result<Arc<CryptoProvider>, NetError> {
523        crate::module::tls::select_provider(self.provider.as_ref()).map_err(|_| {
524            NetError::config(
525                role.field("provider"),
526                "configure a rustls CryptoProvider or install an application process default",
527            )
528        })
529    }
530
531    pub(crate) fn compile_for(&self, role: TlsRole) -> Result<Arc<rustls::ClientConfig>, NetError> {
532        self.validate_material_for(role)?;
533        let provider = self.provider_for(role)?;
534        let identity = self
535            .identity
536            .as_ref()
537            .map(|identity| identity.compile_for(&provider, role))
538            .transpose()?;
539        let mut roots =
540            crate::module::tls::root_store(self.root_mode == RootCertificateMode::Append);
541        for root in &self.roots {
542            roots.add(root.clone()).map_err(|_| {
543                NetError::config(role.field("root_certificates"), "invalid root certificate")
544            })?;
545        }
546        let builder = rustls::ClientConfig::builder_with_provider(provider)
547            .with_safe_default_protocol_versions()
548            .map_err(|_| {
549                NetError::config(
550                    role.field("provider"),
551                    "provider does not support the required TLS protocol versions",
552                )
553            })?
554            .with_root_certificates(roots);
555        let mut tls = match identity {
556            Some(identity) => {
557                builder.with_client_cert_resolver(Arc::new(SingleCertAndKey::from(identity)))
558            }
559            None => builder.with_no_client_auth(),
560        };
561        // CONNECT and WebSocket Upgrade use HTTP/1.1. Keep target ALPN behavior
562        // unchanged and prevent the proxy from selecting unsupported HTTP/2.
563        tls.alpn_protocols = match role {
564            TlsRole::Target => Vec::new(),
565            TlsRole::Proxy => vec![b"http/1.1".to_vec()],
566        };
567        tls.resumption = Resumption::disabled();
568        tls.enable_early_data = false;
569        Ok(Arc::new(tls))
570    }
571}
572
573/// Parsed certificate material, validated cryptographically by the selected provider.
574pub struct ClientIdentity {
575    certificates: Vec<CertificateDer<'static>>,
576    private_key: PrivatePkcs8KeyDer<'static>,
577}
578
579impl Clone for ClientIdentity {
580    fn clone(&self) -> Self {
581        Self {
582            certificates: self.certificates.clone(),
583            private_key: self.private_key.clone_key(),
584        }
585    }
586}
587
588impl ClientIdentity {
589    /// Loads a PEM certificate chain and exactly one unencrypted PKCS#8 key.
590    /// Each input is limited to 1 MiB and the chain to 128 certificates.
591    /// This parses the PEM material without selecting cryptography. Key loading
592    /// and certificate/key matching happen during [`NetworkConfig::validate`]
593    /// and client construction, using the client's final provider.
594    pub fn from_pem(
595        certificates: impl AsRef<[u8]>,
596        private_key: impl AsRef<[u8]>,
597    ) -> Result<Self, NetError> {
598        let certificates =
599            parse_certificates(certificates.as_ref(), "tls.client_identity.certificates")?;
600        let blocks = strict_pem_blocks(
601            private_key.as_ref(),
602            "PRIVATE KEY",
603            "tls.client_identity.private_key",
604        )?;
605        if blocks.len() != 1 {
606            return Err(NetError::config(
607                "tls.client_identity.private_key",
608                "requires one valid PKCS#8 private key matching the certificate",
609            ));
610        }
611        let block = blocks.first().ok_or(NetError::config(
612            "tls.client_identity.private_key",
613            "requires one valid PKCS#8 private key matching the certificate",
614        ))?;
615        let key = PrivatePkcs8KeyDer::from_pem_slice(block).map_err(|_| {
616            NetError::config(
617                "tls.client_identity.private_key",
618                "requires one valid PKCS#8 private key matching the certificate",
619            )
620        })?;
621        Ok(Self {
622            certificates,
623            private_key: key,
624        })
625    }
626
627    fn compile_for(
628        &self,
629        provider: &CryptoProvider,
630        role: TlsRole,
631    ) -> Result<Arc<CertifiedKey>, NetError> {
632        let certified_key = CertifiedKey::from_der(
633            self.certificates.clone(),
634            PrivateKeyDer::Pkcs8(self.private_key.clone_key()),
635            provider,
636        )
637        .map_err(|_| {
638            NetError::config(
639                role.field("client_identity.private_key"),
640                "requires one valid PKCS#8 private key matching the certificate",
641            )
642        })?;
643        certified_key.keys_match().map_err(|_| {
644            NetError::config(
645                role.field("client_identity.private_key"),
646                "requires one valid PKCS#8 private key matching the certificate",
647            )
648        })?;
649        Ok(Arc::new(certified_key))
650    }
651
652    /// Returns the number of certificates in the parsed client chain.
653    pub fn certificate_count(&self) -> usize {
654        self.certificates.len()
655    }
656}
657
658impl fmt::Debug for ClientIdentity {
659    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
660        formatter
661            .debug_struct("ClientIdentity")
662            .field("certificate_count", &self.certificates.len())
663            .field("private_key", &"[redacted]")
664            .finish()
665    }
666}
667
668pub(crate) fn normalize_host(host: &str) -> &str {
669    host.strip_prefix('[')
670        .and_then(|host| host.strip_suffix(']'))
671        .unwrap_or(host)
672}
673
674fn parse_certificates(pem: &[u8], field: &str) -> Result<Vec<CertificateDer<'static>>, NetError> {
675    let blocks = strict_pem_blocks(pem, "CERTIFICATE", field)?;
676    let mut certificates = Vec::new();
677    certificates
678        .try_reserve(blocks.len())
679        .map_err(|_| NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?;
680    let mut validation = rustls::RootCertStore::empty();
681    for block in blocks {
682        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"))?;
683        validation
684            .add(cert.clone())
685            .map_err(|_| NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?;
686        certificates.push(cert);
687    }
688    Ok(certificates)
689}
690
691fn strict_pem_blocks<'a>(
692    pem: &'a [u8],
693    label: &str,
694    field: &str,
695) -> Result<Vec<&'a [u8]>, NetError> {
696    if pem.is_empty() || pem.len() > MAX_PEM_BYTES {
697        return Err(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"));
698    }
699    let mut remaining = std::str::from_utf8(pem)
700        .map_err(|_| NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?
701        .trim();
702    let begin = format!("-----BEGIN {label}-----");
703    let end = format!("-----END {label}-----");
704    let mut blocks = Vec::new();
705    while !remaining.is_empty() {
706        if blocks.len() == MAX_CERTIFICATES || !remaining.starts_with(&begin) {
707            return Err(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"));
708        }
709        let boundary = remaining
710            .find(&end)
711            .and_then(|index| index.checked_add(end.len()))
712            .ok_or(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?;
713        let block = remaining.get(..boundary).ok_or(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?;
714        if block
715            .get(begin.len()..)
716            .ok_or(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?
717            .contains("-----BEGIN ")
718        {
719            return Err(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"));
720        }
721        blocks.try_reserve(1).map_err(|_| NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?;
722        blocks.push(block.as_bytes());
723        remaining = remaining
724            .get(boundary..)
725            .ok_or(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"))?
726            .trim();
727    }
728    if blocks.is_empty() {
729        return Err(NetError::config(field, "requires a nonempty bounded PEM bundle containing only valid blocks of the requested type"));
730    }
731    Ok(blocks)
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737
738    type TestResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
739
740    #[test]
741    fn network_validation_rechecks_plaintext_authentication_policy() -> TestResult {
742        let mut proxy = ProxyConfig::http_connect("http://localhost:8080", None)?;
743        let endpoint = proxy.endpoint.as_mut().ok_or("proxy endpoint missing")?;
744        // Model an internal caller bypassing the checked public constructor.
745        endpoint.auth = Some(ProxyBasicAuth::new("test-user", "test-password")?);
746        let invalid = NetworkConfig::default().with_proxy(proxy);
747        let error = invalid
748            .validate()
749            .err()
750            .ok_or("network validation accepted plaintext authentication")?;
751        assert_eq!(
752            error.config_error().map(|detail| detail.field()),
753            Some("proxy.auth_transport_policy")
754        );
755        Ok(())
756    }
757
758    #[test]
759    fn tls_validation_and_compilation_report_their_own_role() -> TestResult {
760        let tls = TlsConfig {
761            root_mode: RootCertificateMode::Replace,
762            ..TlsConfig::default()
763        };
764        for (role, field) in [
765            (TlsRole::Target, "tls.root_certificates"),
766            (TlsRole::Proxy, "proxy.tls.root_certificates"),
767        ] {
768            for result in [tls.validate_for(role), tls.compile_for(role).map(|_| ())] {
769                let error = result.err().ok_or("empty replacement roots accepted")?;
770                assert_eq!(
771                    error.config_error().map(|detail| detail.field()),
772                    Some(field)
773                );
774            }
775        }
776        let mut provider = (*crate::module::tls::local_provider()).clone();
777        provider.cipher_suites.clear();
778        let tls = TlsConfig::default().with_crypto_provider(Arc::new(provider));
779        for (role, field) in [
780            (TlsRole::Target, "tls.provider"),
781            (TlsRole::Proxy, "proxy.tls.provider"),
782        ] {
783            let error = tls
784                .compile_for(role)
785                .err()
786                .ok_or("provider without cipher suites accepted")?;
787            assert_eq!(
788                error.config_error().map(|detail| detail.field()),
789                Some(field)
790            );
791        }
792        Ok(())
793    }
794
795    #[test]
796    fn compiled_tls_layers_keep_independent_providers_and_protocols() -> TestResult {
797        let proxy_provider = crate::module::tls::local_provider();
798        let target_provider = crate::module::tls::local_provider();
799        let proxy = TlsConfig::default()
800            .with_crypto_provider(Arc::clone(&proxy_provider))
801            .compile_for(TlsRole::Proxy)?;
802        let target = TlsConfig::default()
803            .with_crypto_provider(Arc::clone(&target_provider))
804            .compile_for(TlsRole::Target)?;
805        assert!(Arc::ptr_eq(proxy.crypto_provider(), &proxy_provider));
806        assert!(Arc::ptr_eq(target.crypto_provider(), &target_provider));
807        assert_eq!(proxy.alpn_protocols, vec![b"http/1.1".to_vec()]);
808        assert!(target.alpn_protocols.is_empty());
809        assert!(!proxy.enable_early_data && !target.enable_early_data);
810        assert!(proxy.enable_sni && target.enable_sni);
811        Ok(())
812    }
813
814    #[test]
815    fn proxy_policy_checks_do_not_reload_keys_and_compilation_loads_once() -> TestResult {
816        use std::sync::atomic::{AtomicUsize, Ordering};
817
818        static KEY_LOADS: AtomicUsize = AtomicUsize::new(0);
819        #[derive(Debug)]
820        struct CountKeys;
821        impl rustls::crypto::KeyProvider for CountKeys {
822            fn load_private_key(
823                &self,
824                key: PrivateKeyDer<'static>,
825            ) -> Result<Arc<dyn rustls::sign::SigningKey>, rustls::Error> {
826                KEY_LOADS.fetch_add(1, Ordering::SeqCst);
827                rustls_openssl::default_provider()
828                    .key_provider
829                    .load_private_key(key)
830            }
831        }
832        static COUNT_KEYS: CountKeys = CountKeys;
833        let mut provider = rustls_openssl::default_provider();
834        provider.key_provider = &COUNT_KEYS;
835        let proxy = ProxyConfig::https_connect(
836            "https://localhost",
837            Some(ProxyBasicAuth::new("test-user", "test-password")?),
838            TlsConfig::default()
839                .with_crypto_provider(Arc::new(provider))
840                .with_client_identity(ClientIdentity::from_pem(
841                    include_bytes!("../test_fixtures/network/client.pem"),
842                    include_bytes!("../test_fixtures/network/client-key.pem"),
843                )?),
844        )?;
845        proxy.validate_auth_transport()?;
846        proxy.validate_auth_transport()?;
847        assert_eq!(KEY_LOADS.load(Ordering::SeqCst), 0);
848        proxy
849            .proxy_tls()
850            .ok_or("proxy TLS configuration missing")?
851            .compile_for(TlsRole::Proxy)?;
852        assert_eq!(KEY_LOADS.load(Ordering::SeqCst), 1);
853        Ok(())
854    }
855}