product-os-proxy 0.0.19

Product OS : Proxy builds on the work of hudsucker, taking it to the next level with a man-in-the-middle proxy server that can tunnel traffic through a VPN utilising Product OS : VPN.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
//! Builder pattern for constructing a [`Proxy`] instance.
//!
//! The [`ProxyBuilder`] provides a fluent API for configuring all aspects of the
//! proxy server before starting it. This includes:
//!
//! - Network binding (address or listener)
//! - TLS client configuration (rustls)
//! - Certificate authority for MITM interception
//! - HTTP and WebSocket handlers (middleware)
//! - Compression settings
//! - Optional VPN and Tor tunneling
//!
//! # Examples
//!
//! ```ignore
//! let proxy = Proxy::https_builder()
//!     .use_address(addr)
//!     .use_certificate_authority(certificates)
//!     .use_rustls_client(crypto_provider)
//!     .use_http_handler(middleware)
//!     .build()?;
//! ```

use crate::{mitm::Proxy, ProxyMiddleware};

#[cfg(feature = "rustls_client")]
use crate::mitm::rustls;

#[cfg(feature = "rustls_client")]
use crate::mitm::rustls::{
    client::{
        danger::{HandshakeSignatureValid, ServerCertVerified},
        WebPkiServerVerifier,
    },
    DigitallySignedStruct, RootCertStore, SignatureScheme,
};

#[cfg(feature = "rcgen_ca")]
use crate::mitm::certificate_authority::RcgenAuthority;

#[cfg(any(feature = "rustls_client", feature = "rcgen_ca"))]
use rustls_pki_types::CertificateDer;
#[cfg(feature = "rustls_client")]
use rustls_pki_types::{IpAddr, Ipv4Addr, Ipv6Addr, ServerName, UnixTime};

use tokio::net::TcpListener;
use tokio::sync::watch;
use tokio_tungstenite::Connector;

use crate::config::NetworkProxyCompression;
use product_os_http_body::BodyBytes;
use product_os_request::ProductOSRequestClient;
use product_os_security::certificates::Certificates;
use product_os_utilities::ProductOSError;

#[cfg(feature = "rustls_client")]
use hyper_rustls::HttpsConnector;
use hyper_util::{
    client::legacy::{connect::HttpConnector, Client},
    rt::TokioExecutor,
};

use std::fmt::Debug;
use std::{net::SocketAddr, sync::Arc, time::Duration};

use super::ProxyState;

/// Internal enum representing either a socket address or a pre-bound listener.
///
/// This allows the proxy to be configured with either:
/// - A socket address to bind to when starting
/// - A pre-bound `TcpListener` for more control over the binding process
#[derive(Debug)]
#[allow(dead_code)]
pub(crate) enum AddrOrListener {
    Addr(SocketAddr),
    Listener(TcpListener),
}

/// Builder for constructing a [`Proxy`] instance with a fluent API.
///
/// All configuration options return `Self`, allowing method chaining.
/// Call [`build()`](ProxyBuilder::build) to finalize the configuration
/// and create a [`Proxy`] instance.
///
/// # Type Parameters
///
/// * `C` - HTTP connector type (e.g., `HttpsConnector<HttpConnector>`)
/// * `CA` - Certificate authority type (e.g., [`RcgenAuthority`])
/// * `H` - HTTP handler type (e.g., [`ProxyMiddleware`])
/// * `W` - WebSocket handler type (e.g., [`ProxyMiddleware`])
pub struct ProxyBuilder<C, CA, H, W> {
    address_or_listener: Result<AddrOrListener, ProductOSError>,
    ca: Result<CA, ProductOSError>,
    client: Result<Client<C, BodyBytes>, ProductOSError>,
    websocket_connector: Option<Connector>,

    http_handler: H,
    websocket_handler: W,

    compression: NetworkProxyCompression,
    certificates: Certificates,
    custom_requester: Option<ProductOSRequestClient>,
    connect_timeout_ms: Option<u64>,
    request_timeout_ms: Option<u64>,

    #[cfg(feature = "tor")]
    tor_client: Option<arti_client::TorClient<tor_rtcompat::PreferredRuntime>>,
    #[cfg(feature = "vpn")]
    vpn_client: Option<product_os_vpn::ProductOSVPN>,
}

#[allow(dead_code)]
impl<CA, H, W> ProxyBuilder<HttpConnector, CA, H, W> {
    /// Configures the proxy to use a plain HTTP client (no TLS for outbound connections).
    pub fn use_http_client(self) -> Self {
        let mut http = HttpConnector::new();
        if let Some(ms) = self.connect_timeout_ms {
            http.set_connect_timeout(Some(Duration::from_millis(ms)));
        }

        Self {
            address_or_listener: self.address_or_listener,
            ca: self.ca,
            client: Ok(Client::builder(TokioExecutor::new())
                .http1_title_case_headers(true)
                .http1_preserve_header_case(true)
                .build(http)),
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }
}

#[cfg(feature = "rustls_client")]
#[derive(Debug)]
struct CustomCertificateVerifier {
    certifier: Arc<WebPkiServerVerifier>,
}

#[cfg(feature = "rustls_client")]
impl CustomCertificateVerifier {
    /// Creates a new verifier with the default web PKI root certificates.
    pub fn new() -> Result<Self, ProductOSError> {
        let mut root_store = RootCertStore::empty();
        root_store.roots = webpki_roots::TLS_SERVER_ROOTS.to_vec();

        let certifier_builder = WebPkiServerVerifier::builder(Arc::new(root_store));
        let certifier = certifier_builder.build().map_err(|e| {
            ProductOSError::GenericError(format!("Failed to build certificate verifier: {e:?}"))
        })?;

        Ok(Self { certifier })
    }
}

#[cfg(feature = "rustls_client")]
impl rustls::client::danger::ServerCertVerifier for CustomCertificateVerifier {
    fn verify_server_cert(
        &self,
        end_entity: &CertificateDer<'_>,
        intermediates: &[CertificateDer<'_>],
        server_name: &ServerName<'_>,
        ocsp_response: &[u8],
        now: UnixTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        match server_name {
            ServerName::DnsName(name) => match name.to_lowercase_owned().as_ref() {
                "localhost" => Ok(ServerCertVerified::assertion()),
                _ => self.certifier.verify_server_cert(
                    end_entity,
                    intermediates,
                    server_name,
                    ocsp_response,
                    now,
                ),
            },
            ServerName::IpAddress(ip) => {
                let v4_localhost = Ipv4Addr::from(core::net::Ipv4Addr::LOCALHOST);
                let v6_localhost = Ipv6Addr::from(core::net::Ipv6Addr::LOCALHOST);

                match ip {
                    IpAddr::V4(ip) => {
                        if ip.eq(&v4_localhost) {
                            Ok(ServerCertVerified::assertion())
                        } else {
                            self.certifier.verify_server_cert(
                                end_entity,
                                intermediates,
                                server_name,
                                ocsp_response,
                                now,
                            )
                        }
                    }
                    IpAddr::V6(ip) => {
                        if ip.eq(&v6_localhost) {
                            Ok(ServerCertVerified::assertion())
                        } else {
                            self.certifier.verify_server_cert(
                                end_entity,
                                intermediates,
                                server_name,
                                ocsp_response,
                                now,
                            )
                        }
                    }
                }
            }
            _ => self.certifier.verify_server_cert(
                end_entity,
                intermediates,
                server_name,
                ocsp_response,
                now,
            ),
        }
    }

    fn verify_tls12_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.certifier.verify_tls12_signature(message, cert, dss)
    }

    fn verify_tls13_signature(
        &self,
        message: &[u8],
        cert: &CertificateDer<'_>,
        dss: &DigitallySignedStruct,
    ) -> Result<HandshakeSignatureValid, rustls::Error> {
        self.certifier.verify_tls13_signature(message, cert, dss)
    }

    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
        self.certifier.supported_verify_schemes()
    }
}

#[cfg(feature = "rustls_client")]
impl<CA, H, W> ProxyBuilder<HttpsConnector<HttpConnector>, CA, H, W> {
    /// Configures the proxy to use a rustls-based HTTPS client.
    ///
    /// This sets up TLS for outbound connections from the proxy to target servers.
    /// The client is configured with a custom certificate verifier that allows
    /// localhost connections without valid certificates.
    ///
    /// # Arguments
    ///
    /// * `provider` - The cryptographic provider to use (e.g., `ring::default_provider()`)
    ///
    /// # Feature Flag
    ///
    /// Requires the `rustls_client` feature.
    #[cfg(feature = "rustls_client")]
    pub fn use_rustls_client(
        self,
        provider: rustls::crypto::CryptoProvider,
    ) -> Result<Self, ProductOSError> {
        match rustls::ClientConfig::builder_with_provider(Arc::new(provider))
            .with_safe_default_protocol_versions()
        {
            Ok(config) => {
                let verifier = CustomCertificateVerifier::new()?;
                let rustls_config = config
                    .dangerous()
                    .with_custom_certificate_verifier(Arc::new(verifier))
                    .with_no_client_auth();

                let mut http = HttpConnector::new();
                // Required when using wrap_connector (build() does this automatically).
                // Without it, HttpConnector rejects https:// URIs before rustls can upgrade.
                http.enforce_http(false);
                if let Some(ms) = self.connect_timeout_ms {
                    http.set_connect_timeout(Some(Duration::from_millis(ms)));
                }
                let https = hyper_rustls::HttpsConnectorBuilder::new()
                    .with_tls_config(rustls_config.clone())
                    .https_or_http()
                    .enable_all_versions()
                    .wrap_connector(http);

                Ok(Self {
                    address_or_listener: self.address_or_listener,
                    ca: self.ca,
                    client: Ok(Client::builder(TokioExecutor::new())
                        .http1_title_case_headers(true)
                        .http1_preserve_header_case(true)
                        .build(https)),
                    websocket_connector: Some(Connector::Rustls(Arc::new(rustls_config))),
                    http_handler: self.http_handler,
                    websocket_handler: self.websocket_handler,
                    compression: self.compression,
                    certificates: self.certificates,
                    custom_requester: self.custom_requester,
                    connect_timeout_ms: self.connect_timeout_ms,
                    request_timeout_ms: self.request_timeout_ms,
                    #[cfg(feature = "tor")]
                    tor_client: self.tor_client,
                    #[cfg(feature = "vpn")]
                    vpn_client: self.vpn_client,
                })
            }
            Err(e) => Ok(Self {
                address_or_listener: self.address_or_listener,
                ca: self.ca,
                client: Err(ProductOSError::GenericError(e.to_string())),
                websocket_connector: None,
                http_handler: self.http_handler,
                websocket_handler: self.websocket_handler,
                compression: self.compression,
                certificates: self.certificates,
                custom_requester: self.custom_requester,
                connect_timeout_ms: self.connect_timeout_ms,
                request_timeout_ms: self.request_timeout_ms,
                #[cfg(feature = "tor")]
                tor_client: self.tor_client,
                #[cfg(feature = "vpn")]
                vpn_client: self.vpn_client,
            }),
        }
    }
}

#[cfg(feature = "rcgen_ca")]
impl<C, H, W> ProxyBuilder<C, RcgenAuthority, H, W> {
    /// Configures the proxy to use the given certificates as a certificate authority.
    ///
    /// The certificates are used to sign dynamically-generated TLS certificates
    /// for intercepted HTTPS connections.
    ///
    /// # Arguments
    ///
    /// * `certificates` - A [`Certificates`] instance containing the CA cert and private key
    ///
    /// # Errors
    ///
    /// If the certificates cannot be parsed, the error is deferred and will be
    /// returned when [`build()`](ProxyBuilder::build) is called.
    #[allow(clippy::needless_pass_by_value)]
    pub fn use_certificate_authority(self, certificates: Certificates) -> Self {
        let private = certificates.private.clone();
        let certs = certificates.certificates.clone();

        let ca_result = (|| -> Result<RcgenAuthority, ProductOSError> {
            let key_pair =
                rcgen::KeyPair::try_from(&rustls_pki_types::PrivatePkcs8KeyDer::from(private))
                    .map_err(|e| {
                        ProductOSError::GenericError(format!("Error getting private key: {e:?}"))
                    })?;

            let first_cert = certs
                .first()
                .ok_or_else(|| ProductOSError::GenericError("No certificates provided".into()))?
                .to_owned();

            let cert_params = rcgen::CertificateParams::from_ca_cert_der(
                &rustls_pki_types::CertificateDer::from(first_cert),
            )
            .map_err(|e| {
                ProductOSError::GenericError(format!("Error getting public key params: {e:?}"))
            })?;

            let cert = cert_params.self_signed(&key_pair).map_err(|e| {
                ProductOSError::GenericError(format!("Error self-signing certificate: {e:?}"))
            })?;

            Ok(RcgenAuthority::new(key_pair, cert, 1_000))
        })();

        Self {
            address_or_listener: self.address_or_listener,
            ca: ca_result,
            client: self.client,
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }
}

impl<C, CA> ProxyBuilder<C, CA, ProxyMiddleware, ProxyMiddleware> {
    /// Sets the HTTP handler (middleware) for request/response processing.
    ///
    /// # Arguments
    ///
    /// * `http_handler` - The middleware to use for HTTP traffic
    pub fn use_http_handler(self, http_handler: ProxyMiddleware) -> Self {
        Self {
            address_or_listener: self.address_or_listener,
            ca: self.ca,
            client: self.client,
            websocket_connector: self.websocket_connector,
            http_handler,
            websocket_handler: self.websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }

    /// Sets the WebSocket handler for message processing.
    ///
    /// # Arguments
    ///
    /// * `websocket_handler` - The middleware to use for WebSocket traffic
    #[allow(dead_code)]
    pub fn use_websocket_handler(self, websocket_handler: ProxyMiddleware) -> Self {
        Self {
            address_or_listener: self.address_or_listener,
            ca: self.ca,
            client: self.client,
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }

    /// Creates a new default builder.
    ///
    /// All fields start in an unconfigured state. You must configure at least
    /// an address, certificate authority, and client before calling [`build()`](ProxyBuilder::build).
    pub fn new() -> Self {
        ProxyBuilder::default()
    }
}

impl<C, CA, H, W> ProxyBuilder<C, CA, H, W> {
    /// Sets the socket address for the proxy to bind to.
    ///
    /// # Arguments
    ///
    /// * `address` - The socket address (IP + port) to listen on
    pub fn use_address(self, address: SocketAddr) -> Self {
        Self {
            address_or_listener: Ok(AddrOrListener::Addr(address)),
            ca: self.ca,
            client: self.client,
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }

    /// Sets a pre-bound TCP listener for the proxy.
    ///
    /// Use this when you need control over the binding process (e.g., for
    /// testing or when the listener is obtained from another source).
    ///
    /// # Arguments
    ///
    /// * `listener` - A pre-bound `TcpListener`
    #[allow(dead_code)]
    pub fn use_listener(self, listener: TcpListener) -> Self {
        Self {
            address_or_listener: Ok(AddrOrListener::Listener(listener)),
            ca: self.ca,
            client: self.client,
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }

    /// Sets a custom WebSocket connector for outbound WebSocket connections.
    ///
    /// # Arguments
    ///
    /// * `connector` - The WebSocket connector to use
    #[allow(dead_code)]
    pub fn use_custom_websocket_connector(self, connector: Connector) -> Self {
        Self {
            address_or_listener: self.address_or_listener,
            ca: self.ca,
            client: self.client,
            websocket_connector: Some(connector),
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }

    /// Sets a custom HTTP requester for outbound requests.
    ///
    /// When set, the proxy will use this requester instead of the default
    /// hyper client for making HTTP requests.
    ///
    /// # Arguments
    ///
    /// * `requester` - The custom HTTP requester to use
    pub fn use_custom_requester(self, requester: ProductOSRequestClient) -> Self {
        Self {
            address_or_listener: self.address_or_listener,
            ca: self.ca,
            client: self.client,
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: Some(requester),
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }

    /// Sets the compression mode for outbound requests.
    ///
    /// This controls the `Accept-Encoding` header sent with proxied requests.
    ///
    /// # Arguments
    ///
    /// * `compression` - The compression mode (None, Gzip, or Brotli)
    pub fn use_compression(self, compression: NetworkProxyCompression) -> Self {
        Self {
            address_or_listener: self.address_or_listener,
            ca: self.ca,
            client: self.client,
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }

    /// Sets the connection timeout for outbound requests (milliseconds).
    ///
    /// When set, the HTTP connector will fail if the TCP connection is not
    /// established within this duration.
    pub fn use_connect_timeout(self, ms: u64) -> Self {
        Self {
            address_or_listener: self.address_or_listener,
            ca: self.ca,
            client: self.client,
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: Some(ms),
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }

    /// Sets the request timeout for outbound requests (milliseconds).
    ///
    /// When set, each request will be cancelled if the full response is not
    /// received within this duration.
    pub fn use_request_timeout(self, ms: u64) -> Self {
        Self {
            address_or_listener: self.address_or_listener,
            ca: self.ca,
            client: self.client,
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: Some(ms),
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }

    /// Sets a custom hyper client for outbound connections.
    ///
    /// # Arguments
    ///
    /// * `client` - The hyper client to use
    #[allow(dead_code)]
    pub fn use_custom_client(self, client: Client<C, BodyBytes>) -> Self {
        Self {
            address_or_listener: self.address_or_listener,
            ca: self.ca,
            client: Ok(client),
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        }
    }

    /// Configures a Tor client for routing traffic through the Tor network.
    ///
    /// This creates and bootstraps a Tor client that will be used for all
    /// outbound connections when the `tor` feature is enabled.
    ///
    /// # Returns
    ///
    /// * `Ok(Self)` - Tor client was successfully created
    /// * `Err(ProductOSError)` - Tor client failed to bootstrap
    ///
    /// # Feature Flag
    ///
    /// Requires the `tor` feature.
    #[cfg(feature = "tor")]
    pub async fn use_tor_client(self) -> Result<Self, ProductOSError> {
        let config = arti_client::TorClientConfig::default();

        match arti_client::TorClient::builder()
            .config(config)
            .bootstrap_behavior(arti_client::BootstrapBehavior::OnDemand)
            .create_bootstrapped()
            .await
        {
            Ok(client) => Ok(Self {
                address_or_listener: self.address_or_listener,
                ca: self.ca,
                client: self.client,
                websocket_connector: self.websocket_connector,
                http_handler: self.http_handler,
                websocket_handler: self.websocket_handler,
                compression: self.compression,
                certificates: self.certificates,
                custom_requester: self.custom_requester,
                connect_timeout_ms: self.connect_timeout_ms,
                request_timeout_ms: self.request_timeout_ms,
                #[cfg(feature = "tor")]
                tor_client: Some(client),
                #[cfg(feature = "vpn")]
                vpn_client: self.vpn_client,
            }),
            Err(e) => Err(ProductOSError::GenericError(e.to_string())),
        }
    }

    /// Configures a VPN client for routing traffic through a VPN connection.
    ///
    /// # Arguments
    ///
    /// * `vpn_conf` - VPN configuration to connect with
    ///
    /// # Feature Flag
    ///
    /// Requires the `vpn` feature.
    #[cfg(feature = "vpn")]
    pub fn use_vpn_client(self, vpn_conf: product_os_vpn::VPNConfig) -> Self {
        let mut vpn_client = product_os_vpn::ProductOSVPN::new(vpn_conf);

        #[allow(deprecated)]
        let vpn_result = match vpn_client.connect_sync() {
            product_os_vpn::Status::CONNECTED => {
                tracing::info!("Successfully connected to VPN");
                Some(vpn_client)
            }
            product_os_vpn::Status::CONNECTING => {
                tracing::warn!("VPN still connecting, storing client");
                Some(vpn_client)
            }
            product_os_vpn::Status::FAILED => {
                tracing::warn!("Failed to connect to VPN; not storing client");
                None
            }
            product_os_vpn::Status::ERROR(e) => {
                tracing::warn!("Error connecting to VPN: {:?}; not storing client", e);
                None
            }
            product_os_vpn::Status::DISCONNECTED => {
                tracing::warn!("Disconnected from VPN early; not storing client");
                None
            }
        };

        Self {
            address_or_listener: self.address_or_listener,
            ca: self.ca,
            client: self.client,
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            compression: self.compression,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            connect_timeout_ms: self.connect_timeout_ms,
            request_timeout_ms: self.request_timeout_ms,
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: vpn_result,
        }
    }

    /// Builds the [`Proxy`] from the accumulated configuration.
    ///
    /// This validates that all required fields have been configured and
    /// constructs the final `Proxy` instance.
    ///
    /// # Returns
    ///
    /// * `Ok(Proxy)` - All configuration was valid
    /// * `Err(ProductOSError)` - A required field was missing or invalid
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No address or listener was configured
    /// - No certificate authority was configured
    /// - No HTTP client was configured
    pub fn build(self) -> Result<Proxy<C, CA, H, W>, ProductOSError> {
        let address_or_listener = self.address_or_listener?;
        let client = self.client?;
        let certificate_authority = self.ca?;

        let (shutdown_tx, shutdown_rx) = watch::channel(false);

        Ok(Proxy {
            address_or_listener: std::sync::Mutex::new(Some(address_or_listener)),
            ca: Arc::new(certificate_authority),
            client,
            websocket_connector: self.websocket_connector,
            http_handler: self.http_handler,
            websocket_handler: self.websocket_handler,
            certificates: self.certificates,
            custom_requester: self.custom_requester,
            compression: self.compression,
            request_timeout_ms: self.request_timeout_ms,
            server: None,
            shutdown_tx,
            shutdown_rx,
            state: Arc::new(std::sync::atomic::AtomicU8::new(
                ProxyState::Initialized.to_u8(),
            )),
            stopped_notify: Arc::new(tokio::sync::Notify::new()),
            #[cfg(feature = "tor")]
            tor_client: self.tor_client,
            #[cfg(feature = "vpn")]
            vpn_client: self.vpn_client,
        })
    }
}

impl<C, CA> Default for ProxyBuilder<C, CA, ProxyMiddleware, ProxyMiddleware> {
    fn default() -> Self {
        Self {
            address_or_listener: Err(ProductOSError::GenericError(String::from(
                "No address or listener defined yet",
            ))),
            ca: Err(ProductOSError::GenericError(String::from(
                "No certificate authority defined yet",
            ))),
            client: Err(ProductOSError::GenericError(String::from(
                "No client defined yet",
            ))),
            websocket_connector: None,

            http_handler: ProxyMiddleware::default(),
            websocket_handler: ProxyMiddleware::default(),

            certificates: Certificates {
                certificates: Vec::new(),
                private: Vec::new(),
                format: product_os_security::certificates::CertificatesFormat::Pem,
            },
            custom_requester: None,
            compression: NetworkProxyCompression::None,
            connect_timeout_ms: None,
            request_timeout_ms: None,

            #[cfg(feature = "tor")]
            tor_client: None,
            #[cfg(feature = "vpn")]
            vpn_client: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mitm::certificate_authority::RcgenAuthority;

    #[test]
    fn test_proxy_builder_build_fails_without_address() {
        let builder = ProxyBuilder::<
            HttpsConnector<HttpConnector>,
            RcgenAuthority,
            ProxyMiddleware,
            ProxyMiddleware,
        >::new();
        // Only set up client and CA, not address
        // build() should fail because no address was configured
        let result = builder.build();
        match result {
            Err(err) => assert!(
                format!("{err}").contains("address"),
                "Error should mention address, got: {err}"
            ),
            Ok(_) => panic!("Expected build to fail without address"),
        }
    }

    #[test]
    fn test_proxy_builder_build_fails_without_ca() {
        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
        let builder = ProxyBuilder::<
            HttpsConnector<HttpConnector>,
            RcgenAuthority,
            ProxyMiddleware,
            ProxyMiddleware,
        >::new()
        .use_address(addr);
        // No CA or client configured
        let result = builder.build();
        assert!(result.is_err());
    }

    #[test]
    fn test_proxy_builder_build_fails_without_client() {
        let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
        let certs = Certificates::new_ca(
            vec![],
            Some(vec!["test-ca".to_string()]),
            None,
            None,
            None,
            None,
        );
        let builder = ProxyBuilder::<
            HttpsConnector<HttpConnector>,
            RcgenAuthority,
            ProxyMiddleware,
            ProxyMiddleware,
        >::new()
        .use_address(addr)
        .use_certificate_authority(certs);
        // No client configured
        let result = builder.build();
        match result {
            Err(err) => assert!(
                format!("{err}").contains("client"),
                "Error should mention client, got: {err}"
            ),
            Ok(_) => panic!("Expected build to fail without client"),
        }
    }

    #[test]
    fn test_proxy_builder_use_address() {
        let addr: SocketAddr = "127.0.0.1:9090".parse().unwrap();
        let builder = ProxyBuilder::<
            HttpsConnector<HttpConnector>,
            RcgenAuthority,
            ProxyMiddleware,
            ProxyMiddleware,
        >::new()
        .use_address(addr);
        assert!(builder.address_or_listener.is_ok());
    }

    #[test]
    fn test_proxy_builder_use_compression() {
        let builder = ProxyBuilder::<
            HttpsConnector<HttpConnector>,
            RcgenAuthority,
            ProxyMiddleware,
            ProxyMiddleware,
        >::new()
        .use_compression(NetworkProxyCompression::Gzip);
        assert!(matches!(builder.compression, NetworkProxyCompression::Gzip));
    }

    #[tokio::test]
    async fn test_proxy_builder_use_listener() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let builder = ProxyBuilder::<
            HttpsConnector<HttpConnector>,
            RcgenAuthority,
            ProxyMiddleware,
            ProxyMiddleware,
        >::new()
        .use_listener(listener);
        assert!(builder.address_or_listener.is_ok());
    }

    #[test]
    fn test_proxy_builder_default() {
        let builder = ProxyBuilder::<
            HttpsConnector<HttpConnector>,
            RcgenAuthority,
            ProxyMiddleware,
            ProxyMiddleware,
        >::default();
        assert!(builder.address_or_listener.is_err());
        assert!(builder.ca.is_err());
        assert!(builder.client.is_err());
        assert!(builder.websocket_connector.is_none());
        assert!(builder.custom_requester.is_none());
        assert!(matches!(builder.compression, NetworkProxyCompression::None));
    }
}