1use 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#[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 pub fn with_proxy(mut self, proxy: ProxyConfig) -> Self {
36 self.proxy = proxy;
37 self
38 }
39
40 pub fn with_tls(mut self, tls: TlsConfig) -> Self {
42 self.tls = tls;
43 self
44 }
45
46 pub fn with_network_status_policy(mut self, policy: NetworkStatusPolicy) -> Self {
49 self.network_status_policy = policy;
50 self
51 }
52
53 pub fn proxy(&self) -> &ProxyConfig {
55 &self.proxy
56 }
57
58 pub fn tls(&self) -> &TlsConfig {
60 &self.tls
61 }
62
63 pub fn network_status_policy(&self) -> NetworkStatusPolicy {
65 self.network_status_policy
66 }
67
68 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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
111#[non_exhaustive]
112pub enum NetworkStatusPolicy {
113 #[default]
115 Ignore,
116 PauseOnUnavailable,
122}
123
124#[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 pub fn direct() -> Self {
141 Self::default()
142 }
143
144 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 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 pub fn is_direct(&self) -> bool {
200 self.endpoint.is_none()
201 }
202
203 pub fn endpoint(&self) -> Option<&str> {
205 self.endpoint
206 .as_ref()
207 .map(|proxy| proxy.normalized_url.as_str())
208 }
209
210 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#[derive(Clone)]
243pub struct ProxyBasicAuth {
244 pub(crate) encoded: Arc<str>,
245}
246
247impl ProxyBasicAuth {
248 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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
289#[non_exhaustive]
290pub enum RootCertificateMode {
291 #[default]
292 Append,
294 Replace,
296}
297
298#[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 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 pub fn with_client_identity(mut self, identity: ClientIdentity) -> Self {
333 self.identity = Some(identity);
334 self
335 }
336
337 pub fn root_mode(&self) -> RootCertificateMode {
339 self.root_mode
340 }
341
342 pub fn custom_root_count(&self) -> usize {
344 self.roots.len()
345 }
346
347 pub fn client_identity(&self) -> Option<&ClientIdentity> {
349 self.identity.as_ref()
350 }
351}
352
353#[derive(Clone)]
355pub struct ClientIdentity {
356 pub(crate) certified_key: Arc<CertifiedKey>,
357}
358
359impl ClientIdentity {
360 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 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}