1use 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#[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 pub fn with_proxy(mut self, proxy: ProxyConfig) -> Self {
37 self.proxy = proxy;
38 self
39 }
40
41 pub fn with_tls(mut self, tls: TlsConfig) -> Self {
43 self.tls = tls;
44 self
45 }
46
47 pub fn with_network_status_policy(mut self, policy: NetworkStatusPolicy) -> Self {
50 self.network_status_policy = policy;
51 self
52 }
53
54 pub fn proxy(&self) -> &ProxyConfig {
56 &self.proxy
57 }
58
59 pub fn tls(&self) -> &TlsConfig {
61 &self.tls
62 }
63
64 pub fn network_status_policy(&self) -> NetworkStatusPolicy {
66 self.network_status_policy
67 }
68
69 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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
108#[non_exhaustive]
109pub enum NetworkStatusPolicy {
110 #[default]
112 Ignore,
113 PauseOnUnavailable,
119}
120
121#[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 pub fn direct() -> Self {
138 Self::default()
139 }
140
141 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 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 pub fn is_direct(&self) -> bool {
197 self.endpoint.is_none()
198 }
199
200 pub fn endpoint(&self) -> Option<&str> {
202 self.endpoint
203 .as_ref()
204 .map(|proxy| proxy.normalized_url.as_str())
205 }
206
207 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#[derive(Clone)]
240pub struct ProxyBasicAuth {
241 pub(crate) encoded: Arc<str>,
242}
243
244impl ProxyBasicAuth {
245 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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
286#[non_exhaustive]
287pub enum RootCertificateMode {
288 #[default]
289 Append,
291 Replace,
293}
294
295#[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 pub fn with_crypto_provider(mut self, provider: Arc<CryptoProvider>) -> Self {
323 self.provider = Some(provider);
324 self
325 }
326
327 pub fn crypto_provider(&self) -> Option<&Arc<CryptoProvider>> {
329 self.provider.as_ref()
330 }
331
332 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 pub fn with_client_identity(mut self, identity: ClientIdentity) -> Self {
347 self.identity = Some(identity);
348 self
349 }
350
351 pub fn root_mode(&self) -> RootCertificateMode {
353 self.root_mode
354 }
355
356 pub fn custom_root_count(&self) -> usize {
358 self.roots.len()
359 }
360
361 pub fn client_identity(&self) -> Option<&ClientIdentity> {
363 self.identity.as_ref()
364 }
365}
366
367pub 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 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 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}