Skip to main content

soth_mitm/
builder.rs

1use std::sync::Arc;
2
3use crate::ca::CertificateAuthority;
4use crate::config::MitmConfig;
5use crate::errors::MitmError;
6use crate::handler::InterceptHandler;
7use crate::metrics::ProxyMetricsStore;
8use crate::proxy::MitmProxy;
9
10/// Builder for constructing a [`MitmProxy`] instance.
11///
12/// Supply a validated [`MitmConfig`] and an [`InterceptHandler`] implementation,
13/// optionally attach a pre-generated [`CertificateAuthority`], then call
14/// [`build`](Self::build) to produce a ready-to-run proxy.
15pub struct MitmProxyBuilder<H: InterceptHandler> {
16    config: MitmConfig,
17    handler: H,
18    ca: Option<CertificateAuthority>,
19}
20
21impl<H: InterceptHandler> MitmProxyBuilder<H> {
22    /// Creates a new builder with the given configuration and handler.
23    pub fn new(config: MitmConfig, handler: H) -> Self {
24        Self {
25            config,
26            handler,
27            ca: None,
28        }
29    }
30
31    /// Attaches a pre-generated CA for TLS interception.
32    ///
33    /// If omitted, the proxy will load or generate a CA from the paths
34    /// specified in [`TlsConfig`](crate::TlsConfig).
35    pub fn with_ca(mut self, ca: CertificateAuthority) -> Self {
36        self.ca = Some(ca);
37        self
38    }
39
40    /// Validates the config and builds the [`MitmProxy`].
41    pub fn build(self) -> Result<MitmProxy<H>, MitmError> {
42        self.config.validate()?;
43        Ok(MitmProxy::new(
44            self.config,
45            Arc::new(self.handler),
46            self.ca,
47            Arc::new(ProxyMetricsStore::default()),
48        ))
49    }
50}