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
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
//! # Product OS : Proxy
//!
//! `product-os-proxy` is a high-performance, feature-rich MITM (man-in-the-middle) proxy server
//! built on top of the Rust async ecosystem. It provides powerful traffic interception, modification,
//! and tunneling capabilities through VPN or Tor networks.

#![warn(missing_docs)]
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::missing_panics_doc)]

//!
//! ## Features
//!
//! - **MITM Proxying**: Intercept and modify HTTP/HTTPS traffic with custom middleware
//! - **WebSocket Support**: Handle WebSocket connections with custom message processing
//! - **TLS Certificate Authority**: Automatic certificate generation for HTTPS interception
//! - **Content Decoding**: Support for gzip, brotli, deflate, and zstd compression (with `decoder` feature)
//! - **VPN Tunneling**: Route proxy traffic through VPN connections (with `vpn` feature)
//! - **Tor Network**: Route traffic through the Tor network (with `tor` feature)
//! - **HTTP/2 Support**: Full HTTP/2 protocol support (with `http2` feature)
//! - **Custom Middleware**: Implement custom request/response handlers
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use product_os_proxy::{Proxy, ProxyMiddleware};
//! use product_os_proxy::NetworkProxy;
//!
//! #[tokio::main]
//! async fn main() {
//!     // Create proxy configuration
//!     let config = NetworkProxy {
//!         // ... configuration ...
//!         # network: product_os_proxy::NetworkProxyNetwork {
//!         #     secure: true,
//!         #     host: "127.0.0.1".to_string(),
//!         #     port: 8080,
//!         #     listen_all_interfaces: false,
//!         #     allow_insecure: false,
//!         #     insecure_port: 0,
//!         # },
//!         # certificate_authority: None,
//!         # compression: product_os_proxy::NetworkProxyCompression::None,
//!         # custom_requester: false,
//!         # enable_tunnel: false,
//!         # ..Default::default()
//!     };
//!
//!     // Create and start proxy
//!     let mut proxy = Proxy::new(config);
//!     proxy.run().await.expect("proxy startup");
//! }
//! ```
//!
//! ## Custom Middleware
//!
//! Implement custom request/response handling by creating a middleware:
//!
//! ```rust,no_run
//! use product_os_proxy::ProxyMiddleware;
//! use product_os_server::{ProductOSMiddlewareAsync, BeforeResult};
//! use std::sync::Arc;
//!
//! // Your custom middleware implementation
//! struct MyMiddleware;
//! impl product_os_server::ProductOSMiddleware for MyMiddleware {}
//!
//! #[async_trait::async_trait]
//! impl ProductOSMiddlewareAsync for MyMiddleware {
//!     async fn before(&self, request: product_os_http::Request<product_os_http_body::BodyBytes>)
//!         -> BeforeResult {
//!         // Inspect or modify request
//!         BeforeResult::Result(request)
//!     }
//!     
//!     async fn after(&self, response: product_os_http::Response<product_os_http_body::BodyBytes>,
//!                    request_data: product_os_server::RequestData)
//!         -> product_os_http::Response<product_os_http_body::BodyBytes> {
//!         // Inspect or modify response
//!         response
//!     }
//!     
//!     // ... implement other required methods ...
//!     # async fn success(&self, response: product_os_http::Response<product_os_http_body::BodyBytes>,
//!     #                  request_data: product_os_server::RequestData)
//!     #     -> product_os_http::Response<product_os_http_body::BodyBytes> { response }
//!     # async fn failure(&self, response: product_os_http::Response<product_os_http_body::BodyBytes>,
//!     #                  request_data: product_os_server::RequestData)
//!     #     -> product_os_http::Response<product_os_http_body::BodyBytes> { response }
//!     # async fn error(&self) -> product_os_http::Response<product_os_http_body::BodyBytes> {
//!     #     product_os_http::Response::new(product_os_http_body::BodyBytes::empty())
//!     # }
//!     # async fn before_product_os_response(&self, request: product_os_http::Request<product_os_http_body::BodyBytes>)
//!     #     -> BeforeResult { BeforeResult::Result(request) }
//!     # async fn after_product_os_response(&self, response: product_os_request::ProductOSResponse<product_os_http_body::BodyBytes>,
//!     #                                    request_data: product_os_server::RequestData)
//!     #     -> product_os_http::Response<product_os_http_body::BodyBytes> {
//!     #     product_os_http::Response::new(product_os_http_body::BodyBytes::empty())
//!     # }
//! }
//!
//! // Use your middleware
//! let middleware = ProxyMiddleware::new(Arc::new(MyMiddleware));
//! # let config = product_os_proxy::NetworkProxy {
//! #     network: product_os_proxy::NetworkProxyNetwork {
//! #         secure: true,
//! #         host: "127.0.0.1".to_string(),
//! #         port: 8080,
//! #         listen_all_interfaces: false,
//! #         allow_insecure: false,
//! #         insecure_port: 0,
//! #     },
//! #     certificate_authority: None,
//! #     compression: product_os_proxy::NetworkProxyCompression::None,
//! #     custom_requester: false,
//! #     enable_tunnel: false,
//! #     ..Default::default()
//! # };
//! let mut proxy = product_os_proxy::Proxy::new(config);
//! proxy.set_middleware(Some(middleware));
//! ```
//!
//! ## Certificate Authority Setup
//!
//! For HTTPS interception, you need to generate and trust a CA certificate.
//! Use [`Proxy::generate_certificate_authority`] for an in-memory CA, or
//! [`Proxy::load_or_create_managed_certificate_authority`] for a persistent managed CA:
//!
//! ```rust,no_run
//! use product_os_proxy::Proxy;
//!
//! // Generate a new in-memory CA certificate
//! let certs = Proxy::generate_certificate_authority(None);
//!
//! // Or load/create a persistent managed CA on disk
//! let managed = Proxy::load_or_create_managed_certificate_authority(None).unwrap();
//!
//! // Or load existing certificate from files
//! let certs = Proxy::generate_certificate_authority(
//!     Some(("path/to/cert.pem".to_string(), "path/to/key.pem".to_string()))
//! );
//! ```
//!
//! **Security Warning**: Clients must be configured to trust the CA certificate, or certificate
//! errors must be explicitly ignored. Never share your CA private key.
//!
//! ## Feature Flags
//!
//! - `default`: Enables `decoder`, `rcgen_ca`, `rustls_client`, and `http2`
//! - `decoder`: HTTP content encoding/decoding support (gzip, brotli, etc.)
//! - `http2`: HTTP/2 protocol support
//! - `rcgen_ca`: Certificate authority using rcgen (recommended)
//! - `rustls_client`: TLS client using rustls (recommended)
//! - `tor`: Route traffic through Tor network
//! - `vpn`: Route traffic through VPN connections
//! - `vendored_openssl`: Use vendored OpenSSL build
//!
//! ## Architecture
//!
//! The proxy operates as a MITM proxy that:
//! 1. Accepts incoming client connections
//! 2. Intercepts CONNECT requests for HTTPS traffic
//! 3. Generates temporary certificates signed by the CA
//! 4. Establishes TLS connections with clients
//! 5. Forwards requests through optional VPN/Tor tunnels
//! 6. Applies middleware transformations
//! 7. Returns responses to clients
//!
//! ## Thread Safety
//!
//! The `Proxy` struct is not `Send` or `Sync` by design, as it manages mutable state.
//! However, the underlying proxy implementation uses `Arc` for shared state and can handle
//! multiple concurrent connections safely.

use std::sync::Arc;

use async_trait::async_trait;
#[cfg(feature = "rustls_client")]
use hyper_rustls::HttpsConnector;
use hyper_util::client::legacy::connect::HttpConnector;
use parking_lot::Mutex;
#[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
use product_os_server::ServerConfig;

use product_os_capabilities::{RegistryService, Service};

#[cfg(feature = "rcgen_ca")]
use crate::mitm::certificate_authority::RcgenAuthority;
#[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
use crate::proxy_middleware::DefaultAsyncMiddleware;
use product_os_security::certificates::{Certificates, CertificatesFormat};
use product_os_security::RandomGeneratorTemplate;
#[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
use product_os_utilities::ProductOSError;

#[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
type ProxyClient = HttpsConnector<HttpConnector>;
#[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
type ProxyCa = RcgenAuthority;

#[cfg(not(all(feature = "rustls_client", feature = "rcgen_ca")))]
type ProxyClient = HttpConnector;
#[cfg(not(all(feature = "rustls_client", feature = "rcgen_ca")))]
type ProxyCa = ();

#[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
mod ca;

mod config;
mod error;
mod mitm;
mod proxy_middleware;

pub use crate::config::{
    NetworkProxy, NetworkProxyCSPManipulators, NetworkProxyCertificateAuthority,
    NetworkProxyCertificateAuthorityFiles, NetworkProxyCertificateAuthorityManaged,
    NetworkProxyCertificateAuthorityTrust, NetworkProxyCompression, NetworkProxyHeaderManipulators,
    NetworkProxyManipulatorAction, NetworkProxyNetwork, NetworkProxyOnMissingTrust,
    NetworkProxyTrustTarget, NetworkProxyTunnel, TunnelType,
};
pub use crate::error::ProxyError;

#[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
pub use crate::ca::{
    active_https_self_test, active_platform_https_self_test, build_setup_prompt,
    default_browser_trust_targets, ensure_ca_trust, load_certificate_authority, manual_trust_steps,
    needs_reinstall, probe_connect_host, probe_trust_report, run_cert_guide_wizard,
    run_post_startup_active_probe, run_startup_trust_guide, session_trust_targets,
    strict_all_trusted, system_trust_install_command, trust_status_str, wait_for_proxy_ready,
    CaServeMiddleware, CaSetupPrompt, CaTrustReport, CaTrustSetup, EnsureTrustOptions,
    EnsureTrustResult, LoadedCa, TargetInstallResult, TargetTrustStatus, TrustInstaller,
    TrustProbe, TrustStatus, CA_PEM_PATH, CA_SETUP_PATH,
};

/// Proxy state enumeration representing the lifecycle of the proxy server.
///
/// The proxy transitions through these states during its lifecycle:
/// `Uninitialized` → `Initialized` → `Started` → `StopRequested` → `Stopped`
pub use crate::mitm::ProxyState;

/// Middleware wrapper for handling HTTP requests and responses in the proxy pipeline.
///
/// See the [crate-level documentation](crate) for usage examples.
pub use crate::proxy_middleware::ProxyMiddleware;

/// Main proxy server struct that manages the lifecycle and configuration of the MITM proxy.
///
/// The `Proxy` struct provides a high-level interface for creating and managing a
/// man-in-the-middle proxy server. It handles:
/// - Certificate authority management for HTTPS interception
/// - Middleware pipeline for request/response transformation
/// - Optional VPN/Tor tunneling
/// - Graceful startup and shutdown
///
/// # Examples
///
/// ```no_run
/// use product_os_proxy::Proxy;
/// use product_os_proxy::NetworkProxy;
///
/// # async fn example() {
/// let config = NetworkProxy {
///     // ... configuration ...
///     # network: product_os_proxy::NetworkProxyNetwork {
///     #     secure: true,
///     #     host: "127.0.0.1".to_string(),
///     #     port: 8080,
///     #     listen_all_interfaces: false,
///     #     allow_insecure: false,
///     #     insecure_port: 0,
///     # },
///     # certificate_authority: None,
///     # compression: product_os_proxy::NetworkProxyCompression::None,
///     # custom_requester: false,
///     # enable_tunnel: false,
///     # ..Default::default()
/// };
///
/// let mut proxy = Proxy::new(config);
/// proxy.run().await;
/// # }
/// ```
///
/// # Thread Safety
///
/// `Proxy` is neither `Send` nor `Sync` as it manages mutable state. Use it within
/// a single async task. The internal proxy implementation is thread-safe and handles
/// concurrent connections.
pub struct Proxy {
    key: String,

    config: crate::config::NetworkProxy,
    vpn_config: Option<product_os_vpn::VPN>,

    middleware: Option<ProxyMiddleware>,
    #[allow(dead_code, clippy::struct_field_names)]
    underlying_proxy:
        Option<Arc<mitm::Proxy<ProxyClient, ProxyCa, ProxyMiddleware, ProxyMiddleware>>>,
    /// `JoinHandle` for the server task, so callers can await it after `halt()` if desired.
    server_task: Option<tokio::task::JoinHandle<Result<(), String>>>,
}

impl Proxy {
    /// Creates a new proxy instance with the given configuration.
    ///
    /// This constructor initializes the proxy with a unique key and assigns random ports
    /// if they are set to 0 in the configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - Network proxy configuration including host, port, TLS settings, and tunneling options
    ///
    /// # Returns
    ///
    /// A new `Proxy` instance in the uninitialized state
    ///
    /// # Examples
    ///
    /// ```
    /// use product_os_proxy::Proxy;
    /// use product_os_proxy::NetworkProxy;
    ///
    /// let config = NetworkProxy {
    ///     # network: product_os_proxy::NetworkProxyNetwork {
    ///     #     secure: true,
    ///     #     host: "127.0.0.1".to_string(),
    ///     #     port: 0, // Random port will be assigned
    ///     #     listen_all_interfaces: false,
    ///     #     allow_insecure: false,
    ///     #     insecure_port: 0,
    ///     # },
    ///     # certificate_authority: None,
    ///     # compression: product_os_proxy::NetworkProxyCompression::None,
    ///     # custom_requester: false,
    ///     # enable_tunnel: false,
    ///     # ..Default::default()
    /// };
    ///
    /// let proxy = Proxy::new(config);
    /// assert!(proxy.get_port() > 0); // Port was assigned
    /// ```
    #[must_use]
    pub fn new(mut config: crate::config::NetworkProxy) -> Self {
        config.apply_timeout_defaults();
        let mut random_generator = product_os_security::RandomGenerator::new(None);
        let key = random_generator.get_random_string(10);

        // Define the proxy port if set to zero
        if config.network.port == 0 {
            config.network.port = u16::try_from(random_generator.get_random_usize(1025, 65535))
                .expect("random port must fit in u16");
        }

        if config.network.insecure_port == 0 {
            loop {
                let insecure_port = u16::try_from(random_generator.get_random_usize(1025, 65535))
                    .expect("random port must fit in u16");
                if insecure_port != config.network.port {
                    config.network.insecure_port = insecure_port;
                    break;
                }
            }
        }

        Self {
            key,
            config,
            vpn_config: None,
            middleware: None,
            underlying_proxy: None,
            server_task: None,
        }
    }

    /// Sets the middleware to be used for request/response processing.
    ///
    /// Middleware allows you to intercept, inspect, and modify HTTP requests and responses
    /// as they flow through the proxy. Pass `None` to use the default pass-through middleware.
    ///
    /// # Arguments
    ///
    /// * `middleware` - Optional middleware instance, or `None` for default behavior
    ///
    /// # Examples
    ///
    /// ```
    /// use product_os_proxy::{Proxy, ProxyMiddleware};
    /// use product_os_server::ProductOSMiddlewareAsync;
    /// use std::sync::Arc;
    ///
    /// # let config = product_os_proxy::NetworkProxy {
    /// #     network: product_os_proxy::NetworkProxyNetwork {
    /// #         secure: true,
    /// #         host: "127.0.0.1".to_string(),
    /// #         port: 8080,
    /// #         listen_all_interfaces: false,
    /// #         allow_insecure: false,
    /// #         insecure_port: 0,
    /// #     },
    /// #     certificate_authority: None,
    /// #     compression: product_os_proxy::NetworkProxyCompression::None,
    /// #     custom_requester: false,
    /// #     enable_tunnel: false,
    /// #     ..Default::default()
    /// # };
    /// let mut proxy = Proxy::new(config);
    ///
    /// // Set custom middleware
    /// // let my_middleware = ProxyMiddleware::new(Arc::new(MyMiddleware));
    /// // proxy.set_middleware(Some(my_middleware));
    ///
    /// // Or use default
    /// proxy.set_middleware(None);
    /// ```
    pub fn set_middleware(&mut self, middleware: Option<ProxyMiddleware>) {
        self.middleware = middleware;
    }

    /// Sets the VPN configuration for tunneling proxy traffic.
    ///
    /// When VPN tunneling is enabled in the proxy configuration, all outbound traffic
    /// will be routed through the specified VPN connection.
    ///
    /// # Arguments
    ///
    /// * `vpn_config` - Optional VPN configuration, or `None` to disable VPN tunneling
    ///
    /// # Note
    ///
    /// This requires the `vpn` feature to be enabled.
    ///
    /// # Examples
    ///
    /// ```
    /// use product_os_proxy::Proxy;
    ///
    /// # let config = product_os_proxy::NetworkProxy {
    /// #     network: product_os_proxy::NetworkProxyNetwork {
    /// #         secure: true,
    /// #         host: "127.0.0.1".to_string(),
    /// #         port: 8080,
    /// #         listen_all_interfaces: false,
    /// #         allow_insecure: false,
    /// #         insecure_port: 0,
    /// #     },
    /// #     certificate_authority: None,
    /// #     compression: product_os_proxy::NetworkProxyCompression::None,
    /// #     custom_requester: false,
    /// #     enable_tunnel: false,
    /// #     ..Default::default()
    /// # };
    /// let mut proxy = Proxy::new(config);
    /// proxy.set_vpn_config(None);
    /// ```
    pub fn set_vpn_config(&mut self, vpn_config: Option<product_os_vpn::VPN>) {
        self.vpn_config = vpn_config;
    }

    /// Starts the proxy server.
    ///
    /// Initializes and starts the proxy server in the background via `tokio::spawn`.
    /// It performs the following operations:
    /// 1. Loads or generates TLS certificates
    /// 2. Configures the proxy builder with all settings
    /// 3. Sets up VPN or Tor tunneling if enabled
    /// 4. Starts accepting connections on the configured port
    ///
    /// The proxy runs in a spawned task, but this method waits until startup has definitively
    /// succeeded before returning.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Certificate authority configuration or files are not provided
    /// - Tor client fails to initialize (with `tor` feature)
    /// - Proxy builder fails to build
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use product_os_proxy::Proxy;
    ///
    /// # async fn example() -> Result<(), product_os_utilities::ProductOSError> {
    /// # let config = product_os_proxy::NetworkProxy {
    /// #     network: product_os_proxy::NetworkProxyNetwork {
    /// #         secure: true,
    /// #         host: "127.0.0.1".to_string(),
    /// #         port: 8080,
    /// #         listen_all_interfaces: false,
    /// #         allow_insecure: false,
    /// #         insecure_port: 0,
    /// #     },
    /// #     certificate_authority: None,
    /// #     compression: product_os_proxy::NetworkProxyCompression::None,
    /// #     custom_requester: false,
    /// #     enable_tunnel: false,
    /// #     ..Default::default()
    /// # };
    /// let mut proxy = Proxy::new(config);
    /// proxy.run().await?;
    /// // Proxy is now running in the background
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
    #[allow(clippy::unused_async, clippy::too_many_lines)]
    pub async fn run(&mut self) -> Result<(), ProductOSError> {
        let mut config = product_os_server::ServerConfig::new();
        config.network = product_os_server::Network {
            protocol: if self.config.network.secure {
                "https".to_string()
            } else {
                "http".to_string()
            },
            secure: self.config.network.secure,
            host: self.config.network.host.clone(),
            port: self.config.network.port,
            listen_all_interfaces: self.config.network.listen_all_interfaces,
            allow_insecure: self.config.network.allow_insecure,
            insecure_port: self.config.network.insecure_port,
            insecure_use_different_port: false,
            insecure_force_secure: false,
            connect_info: false,
        };

        let cert_config = self
            .config
            .certificate_authority
            .clone()
            .ok_or_else(|| ProductOSError::from(ProxyError::NoCertificateAuthority))?;

        let loaded_ca = crate::ca::load_certificate_authority(&cert_config)?;

        if let Some(trust) = &cert_config.trust {
            if let Some(managed_config) = loaded_ca.to_managed_config() {
                if let Ok(managed) =
                    product_os_security::certificates::ManagedCa::load_or_create(&managed_config)
                {
                    if let Err(e) = crate::ca::run_startup_trust_guide(
                        &managed,
                        trust,
                        &self.config.network.host,
                        self.config.network.port,
                    )
                    .await
                    {
                        tracing::warn!("startup CA trust guide failed: {e:?}");
                    }
                }
            }
        }

        let post_startup_trust = cert_config.trust.clone();
        let post_startup_cert_paths = (loaded_ca.cert_path.clone(), loaded_ca.key_path.clone());
        let post_startup_host = self.config.network.host.clone();
        let post_startup_port = self.config.network.port;

        let certificates = loaded_ca.certificates.clone();

        let socket_address = ServerConfig::get_socket_address(
            self.config.network.host.as_str(),
            self.config.network.port,
            self.config.network.listen_all_interfaces,
        );

        let base_middleware = self
            .middleware
            .clone()
            .unwrap_or_else(|| ProxyMiddleware::new(Arc::new(DefaultAsyncMiddleware::new())));

        let serve_endpoint = cert_config
            .managed
            .as_ref()
            .is_some_and(|m| m.serve_cert_endpoint);

        let http_handler = if serve_endpoint {
            let inner = base_middleware.middleware_handler();
            ProxyMiddleware::new(Arc::new(crate::ca::CaServeMiddleware::new(
                inner,
                loaded_ca.cert_pem.clone(),
                self.config.network.host.clone(),
                self.config.network.port,
            )))
        } else {
            base_middleware
        };

        let mut proxy_builder = mitm::Proxy::https_builder()
            .use_address(socket_address)
            .use_certificate_authority(certificates.clone())
            .use_compression(self.config.compression)
            .use_rustls_client({
                match mitm::rustls::crypto::ring::default_provider().install_default() {
                    Ok(()) => mitm::rustls::crypto::ring::default_provider(),
                    Err(existing) => existing.as_ref().clone(),
                }
            })?
            .use_http_handler(http_handler);

        if self.config.connect_timeout > 0 {
            proxy_builder = proxy_builder.use_connect_timeout(self.config.connect_timeout);
        }
        if self.config.request_timeout > 0 {
            proxy_builder = proxy_builder.use_request_timeout(self.config.request_timeout);
        }

        if self.config.custom_requester {
            proxy_builder = proxy_builder
                .use_custom_requester(product_os_request::ProductOSRequestClient::new());
        }

        if self.config.enable_tunnel {
            match self.config.tunnel_settings.tunnel_type {
                crate::config::TunnelType::Tor => {
                    #[cfg(feature = "tor")]
                    {
                        tracing::info!("Enabling Tor");
                        proxy_builder = proxy_builder.use_tor_client().await.map_err(|e| {
                            ProductOSError::from(ProxyError::TorBootstrapFailed(format!("{e:?}")))
                        })?;
                    }
                    #[cfg(not(feature = "tor"))]
                    {
                        return Err(ProductOSError::from(ProxyError::TorFeatureDisabled));
                    }
                }
                crate::config::TunnelType::Vpn => {
                    #[cfg(feature = "vpn")]
                    {
                        match &self.vpn_config {
                            None => return Err(ProductOSError::from(ProxyError::VpnConfigMissing)),
                            Some(vpn_conf) => {
                                proxy_builder = proxy_builder.use_vpn_client(vpn_conf.clone());
                            }
                        }
                    }
                    #[cfg(not(feature = "vpn"))]
                    {
                        return Err(ProductOSError::from(ProxyError::VpnFeatureDisabled));
                    }
                }
            }
        }

        let proxy = proxy_builder
            .build()
            .map_err(|e| ProductOSError::from(ProxyError::BuildFailed(format!("{e:?}"))))?;

        self.underlying_proxy = Some(Arc::new(proxy));

        let port = self.config.network.port;

        if let Some(proxy) = &self.underlying_proxy {
            let proxy_clone = proxy.clone();
            let (started_tx, started_rx) = tokio::sync::oneshot::channel();

            tracing::info!("Starting SSL Proxy server on port: {}", port);
            let handle = tokio::spawn(async move {
                let result = proxy_clone.start_with_signal(Some(started_tx)).await;
                match result {
                    Ok(()) => {
                        tracing::info!("SSL Proxy server stopped cleanly on port: {}", port);
                        Ok(())
                    }
                    Err(e) => {
                        let message = e.to_string();
                        tracing::error!(
                            "SSL Proxy server exited with error on port {}: {}",
                            port,
                            message
                        );
                        Err(message)
                    }
                }
            });
            match started_rx.await {
                Ok(Ok(())) => {
                    tracing::info!("SSL Proxy server started successfully on port: {}", port);
                    self.server_task = Some(handle);
                }
                Ok(Err(message)) => {
                    let _ = handle.await;
                    self.underlying_proxy = None;
                    return Err(ProductOSError::from(ProxyError::StartupFailed(message)));
                }
                Err(_) => {
                    let task_result = handle.await.ok().and_then(Result::err);
                    self.underlying_proxy = None;
                    let message = task_result.unwrap_or_else(|| {
                        "proxy startup task ended before signaling readiness".to_string()
                    });
                    return Err(ProductOSError::from(ProxyError::StartupFailed(message)));
                }
            }

            if let Some(trust) = post_startup_trust {
                if trust.active_https_probe {
                    if let (Some(cert_path), Some(key_path)) = post_startup_cert_paths {
                        let managed_config = crate::ca::LoadedCa {
                            cert_path: Some(cert_path),
                            key_path: Some(key_path),
                            certificates: certificates.clone(),
                            cert_pem: Vec::new(),
                        }
                        .to_managed_config();
                        tokio::spawn(async move {
                            if let Some(managed_config) = managed_config {
                                if let Ok(managed) =
                                    product_os_security::certificates::ManagedCa::load_or_create(
                                        &managed_config,
                                    )
                                {
                                    let _ = crate::ca::run_post_startup_active_probe(
                                        &managed,
                                        &trust,
                                        &post_startup_host,
                                        post_startup_port,
                                    )
                                    .await;
                                }
                            }
                        });
                    }
                }
            }
        }

        Ok(())
    }

    /// Stops the running proxy server gracefully.
    ///
    /// Requests the proxy to stop accepting new connections and shut down.
    /// It waits for the proxy to complete its shutdown sequence.
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If the proxy was successfully stopped
    /// * `Err(ProductOSError)` - If the proxy was not running or could not be stopped
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The proxy was never started (no underlying proxy exists)
    /// - The proxy is not in a running state
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use product_os_proxy::Proxy;
    ///
    /// # async fn example() -> Result<(), product_os_utilities::ProductOSError> {
    /// # let config = product_os_proxy::NetworkProxy {
    /// #     network: product_os_proxy::NetworkProxyNetwork {
    /// #         secure: true,
    /// #         host: "127.0.0.1".to_string(),
    /// #         port: 8080,
    /// #         listen_all_interfaces: false,
    /// #         allow_insecure: false,
    /// #         insecure_port: 0,
    /// #     },
    /// #     certificate_authority: None,
    /// #     compression: product_os_proxy::NetworkProxyCompression::None,
    /// #     custom_requester: false,
    /// #     enable_tunnel: false,
    /// #     ..Default::default()
    /// # };
    /// let mut proxy = Proxy::new(config);
    /// proxy.run().await?;
    ///
    /// // Stop the proxy
    /// proxy.halt().await?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
    pub async fn halt(&mut self) -> Result<(), ProductOSError> {
        match &self.underlying_proxy {
            None => Err(ProductOSError::from(ProxyError::NoUnderlyingProxy)),
            Some(proxy) => {
                let proxy_clone = proxy.clone();
                let port = self.config.network.port;

                tracing::info!("Stopping SSL Proxy server on port: {}", port);
                proxy_clone.stop().await?;
                // Wait for the server task to finish exiting
                if let Some(handle) = self.server_task.take() {
                    match handle.await {
                        Ok(Ok(())) => {}
                        Ok(Err(message)) => {
                            self.underlying_proxy = None;
                            return Err(ProductOSError::from(ProxyError::StartupFailed(message)));
                        }
                        Err(err) => {
                            self.underlying_proxy = None;
                            return Err(ProductOSError::from(ProxyError::StartupFailed(
                                err.to_string(),
                            )));
                        }
                    }
                }
                self.underlying_proxy = None;
                Ok(())
            }
        }
    }

    /// Restarts the proxy server.
    ///
    /// This is a convenience method that stops the proxy and then starts it again.
    /// It performs a graceful shutdown followed by reinitialization.
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If the proxy was successfully restarted
    /// * `Err(ProductOSError)` - If the proxy could not be stopped or started
    ///
    /// # Errors
    ///
    /// Returns an error if the proxy was not running or if the restart sequence fails.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use product_os_proxy::Proxy;
    ///
    /// # async fn example() -> Result<(), product_os_utilities::ProductOSError> {
    /// # let config = product_os_proxy::NetworkProxy {
    /// #     network: product_os_proxy::NetworkProxyNetwork {
    /// #         secure: true,
    /// #         host: "127.0.0.1".to_string(),
    /// #         port: 8080,
    /// #         listen_all_interfaces: false,
    /// #         allow_insecure: false,
    /// #         insecure_port: 0,
    /// #     },
    /// #     certificate_authority: None,
    /// #     compression: product_os_proxy::NetworkProxyCompression::None,
    /// #     custom_requester: false,
    /// #     enable_tunnel: false,
    /// #     ..Default::default()
    /// # };
    /// let mut proxy = Proxy::new(config);
    /// proxy.run().await?;
    ///
    /// // Restart to apply new configuration
    /// proxy.rerun().await?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
    pub async fn rerun(&mut self) -> Result<(), ProductOSError> {
        self.halt().await?;
        self.run().await
    }

    /// Returns the current state of the proxy server.
    ///
    /// # Returns
    ///
    /// The current [`ProxyState`], which can be:
    /// - `Uninitialized` - Proxy was created but never started
    /// - `Initialized` - Proxy is built but not yet accepting connections
    /// - `Started` - Proxy is running and accepting connections
    /// - `StopRequested` - Stop has been requested but not yet completed
    /// - `Stopped` - Proxy has been stopped
    ///
    /// # Examples
    ///
    /// ```
    /// use product_os_proxy::{Proxy, ProxyState};
    ///
    /// # let config = product_os_proxy::NetworkProxy {
    /// #     network: product_os_proxy::NetworkProxyNetwork {
    /// #         secure: true,
    /// #         host: "127.0.0.1".to_string(),
    /// #         port: 8080,
    /// #         listen_all_interfaces: false,
    /// #         allow_insecure: false,
    /// #         insecure_port: 0,
    /// #     },
    /// #     certificate_authority: None,
    /// #     compression: product_os_proxy::NetworkProxyCompression::None,
    /// #     custom_requester: false,
    /// #     enable_tunnel: false,
    /// #     ..Default::default()
    /// # };
    /// let proxy = Proxy::new(config);
    /// assert_eq!(proxy.get_state(), ProxyState::Uninitialized);
    /// ```
    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
    #[must_use]
    pub fn get_state(&self) -> ProxyState {
        match &self.underlying_proxy {
            None => ProxyState::Uninitialized,
            Some(proxy) => proxy.get_state(),
        }
    }

    /// Returns the current state of the proxy (always `Uninitialized` without TLS features).
    #[cfg(not(all(feature = "rustls_client", feature = "rcgen_ca")))]
    #[must_use]
    pub fn get_state(&self) -> ProxyState {
        ProxyState::Uninitialized
    }

    /// Returns a reference to the proxy configuration.
    ///
    /// This allows inspection of the current proxy settings without taking ownership.
    ///
    /// # Returns
    ///
    /// A reference to the [`NetworkProxy`] configuration
    ///
    /// # Examples
    ///
    /// ```
    /// use product_os_proxy::Proxy;
    ///
    /// # let config = product_os_proxy::NetworkProxy {
    /// #     network: product_os_proxy::NetworkProxyNetwork {
    /// #         secure: true,
    /// #         host: "127.0.0.1".to_string(),
    /// #         port: 8080,
    /// #         listen_all_interfaces: false,
    /// #         allow_insecure: false,
    /// #         insecure_port: 0,
    /// #     },
    /// #     certificate_authority: None,
    /// #     compression: product_os_proxy::NetworkProxyCompression::None,
    /// #     custom_requester: false,
    /// #     enable_tunnel: false,
    /// #     ..Default::default()
    /// # };
    /// let proxy = Proxy::new(config);
    /// let config = proxy.get_config();
    /// println!("Proxy host: {}", config.network.host);
    /// ```
    #[must_use]
    pub fn get_config(&self) -> &crate::config::NetworkProxy {
        &self.config
    }

    /// Returns the port the proxy is configured to listen on.
    ///
    /// # Returns
    ///
    /// The TCP port number (1025-65535) that the proxy will bind to
    ///
    /// # Examples
    ///
    /// ```
    /// use product_os_proxy::Proxy;
    ///
    /// # let config = product_os_proxy::NetworkProxy {
    /// #     network: product_os_proxy::NetworkProxyNetwork {
    /// #         secure: true,
    /// #         host: "127.0.0.1".to_string(),
    /// #         port: 8080,
    /// #         listen_all_interfaces: false,
    /// #         allow_insecure: false,
    /// #         insecure_port: 0,
    /// #     },
    /// #     certificate_authority: None,
    /// #     compression: product_os_proxy::NetworkProxyCompression::None,
    /// #     custom_requester: false,
    /// #     enable_tunnel: false,
    /// #     ..Default::default()
    /// # };
    /// let proxy = Proxy::new(config);
    /// println!("Proxy listening on port: {}", proxy.get_port());
    /// ```
    #[must_use]
    pub fn get_port(&self) -> u16 {
        self.config.network.port
    }

    #[cfg(test)]
    #[must_use]
    /// Test-only accessor for middleware (avoids making the field pub).
    pub fn test_middleware(&self) -> &Option<ProxyMiddleware> {
        &self.middleware
    }

    #[cfg(test)]
    #[must_use]
    /// Test-only accessor for `vpn_config` (avoids making the field pub).
    pub fn test_vpn_config(&self) -> &Option<product_os_vpn::VPN> {
        &self.vpn_config
    }

    /// Generates or loads a Certificate Authority for HTTPS interception.
    ///
    /// This static method creates a new CA certificate that can be used to sign
    /// temporary certificates for intercepted HTTPS connections.
    ///
    /// # Arguments
    ///
    /// * `cert_path` - Optional tuple of (`certificate_file`, `key_file`) paths.
    ///   - `None` - Generates a new self-signed CA certificate
    ///   - `Some((cert, key))` - Loads existing certificate and private key from files
    ///
    /// # Returns
    ///
    /// A [`Certificates`] instance containing the CA certificate and private key
    ///
    /// # Security Warning
    ///
    /// The generated or loaded CA certificate must be trusted by clients for HTTPS
    /// interception to work. Never share the private key. Store it securely.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use product_os_proxy::Proxy;
    ///
    /// // Generate new in-memory CA
    /// let ca = Proxy::generate_certificate_authority(None);
    ///
    /// // Or load/create a managed CA on disk
    /// let managed = Proxy::load_or_create_managed_certificate_authority(None).unwrap();
    ///
    /// // Or load existing CA
    /// let ca = Proxy::generate_certificate_authority(
    ///     Some(("ca.pem".to_string(), "ca-key.pem".to_string()))
    /// );
    /// ```
    #[must_use]
    pub fn generate_certificate_authority(cert_path: Option<(String, String)>) -> Certificates {
        match cert_path {
            None => Certificates::new_ca_with_profile(
                &product_os_security::certificates::CaProfile::development(),
                Some(CertificatesFormat::Pkcs8),
            ),
            Some((cert_file, key_file)) => {
                Certificates::new_ca_from_file(cert_file, key_file, None)
            }
        }
    }

    /// Load or create a managed Certificate Authority backed by on-disk storage.
    ///
    /// When `storage_path` is `None`, the default managed CA storage directory is used.
    pub fn load_or_create_managed_certificate_authority(
        storage_path: Option<std::path::PathBuf>,
    ) -> Result<LoadedCa, ProductOSError> {
        let ca_config = crate::config::NetworkProxyCertificateAuthority {
            managed: Some(crate::config::NetworkProxyCertificateAuthorityManaged {
                enabled: true,
                storage_path: storage_path.map(|path| path.display().to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };
        crate::ca::load_certificate_authority(&ca_config)
    }
}

#[async_trait]
impl Service for Proxy {
    async fn register(&self, _service: Arc<dyn Service>) -> RegistryService {
        tracing::warn!("Proxy requires mutable registration via register_mut");
        RegistryService {
            identifier: "Proxy".to_string(),
            key: self.key.clone(),
            kind: "Proxy".to_string(),
            active: false,
            enabled: false,
            created_at: Default::default(),
            updated_at: Default::default(),
            service: None,
            service_mut: None,
        }
    }

    async fn register_mut(&self, service: Arc<Mutex<dyn Service>>) -> RegistryService {
        RegistryService {
            identifier: "Proxy".to_string(),
            key: self.key.clone(),
            kind: "Proxy".to_string(),
            active: false,
            enabled: false,
            created_at: Default::default(),
            updated_at: Default::default(),
            service: None,
            service_mut: Some(service),
        }
    }

    fn identifier(&self) -> String {
        "Proxy".to_string()
    }

    fn key(&self) -> String {
        self.key.clone()
    }

    fn is_enabled(&self) -> bool {
        self.config.enable
    }

    fn is_active(&self) -> bool {
        // Proxy is active if it's in Started state
        matches!(self.get_state(), ProxyState::Started)
    }

    async fn status(&self) -> Result<(), ()> {
        if matches!(self.get_state(), ProxyState::Started) {
            Ok(())
        } else {
            Err(())
        }
    }

    async fn init_service(&self) -> Result<(), ()> {
        // Initialization is done in new(), so this is a no-op
        Ok(())
    }

    async fn start(&self) -> Result<(), ()> {
        // Proxy requires mutable access to start
        Err(())
    }

    async fn stop(&self) -> Result<(), ()> {
        // Proxy requires mutable access to stop
        Err(())
    }

    async fn restart(&self) -> Result<(), ()> {
        // Proxy requires mutable access to restart
        Err(())
    }

    async fn init_service_mut(&mut self) -> Result<(), ()> {
        // Initialization is done in new(), so this is a no-op
        Ok(())
    }

    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
    async fn start_mut(&mut self) -> Result<(), ()> {
        self.run().await.map_err(|e| {
            tracing::error!("Failed to start proxy: {:?}", e);
        })
    }

    #[cfg(not(all(feature = "rustls_client", feature = "rcgen_ca")))]
    async fn start_mut(&mut self) -> Result<(), ()> {
        tracing::error!("Proxy requires rustls_client and rcgen_ca features to run");
        Err(())
    }

    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
    async fn stop_mut(&mut self) -> Result<(), ()> {
        match self.halt().await {
            Ok(()) => Ok(()),
            Err(_) => Err(()),
        }
    }

    #[cfg(not(all(feature = "rustls_client", feature = "rcgen_ca")))]
    async fn stop_mut(&mut self) -> Result<(), ()> {
        Err(())
    }

    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
    async fn restart_mut(&mut self) -> Result<(), ()> {
        match self.rerun().await {
            Ok(()) => Ok(()),
            Err(_) => Err(()),
        }
    }

    #[cfg(not(all(feature = "rustls_client", feature = "rcgen_ca")))]
    async fn restart_mut(&mut self) -> Result<(), ()> {
        Err(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{
        NetworkProxy, NetworkProxyCertificateAuthority, NetworkProxyCertificateAuthorityManaged,
        NetworkProxyCompression, NetworkProxyNetwork, NetworkProxyTunnel, TunnelType,
    };
    use tempfile::TempDir;

    /// Helper function to create a basic test configuration
    fn create_test_config() -> NetworkProxy {
        NetworkProxy {
            enable: true,
            network: NetworkProxyNetwork {
                secure: true,
                host: "127.0.0.1".to_string(),
                port: 0, // Random port will be assigned
                listen_all_interfaces: false,
                allow_insecure: false,
                insecure_port: 0,
            },
            certificate_authority: None, // Tests won't actually start the proxy
            compression: NetworkProxyCompression::None,
            custom_requester: false,
            enable_tunnel: false,
            ..Default::default()
        }
    }

    fn create_managed_test_config() -> (NetworkProxy, TempDir) {
        let dir = tempfile::tempdir().expect("temp dir");
        let mut config = create_test_config();
        config.certificate_authority = Some(NetworkProxyCertificateAuthority {
            managed: Some(NetworkProxyCertificateAuthorityManaged {
                enabled: true,
                storage_path: Some(dir.path().display().to_string()),
                ..Default::default()
            }),
            ..Default::default()
        });
        (config, dir)
    }

    #[test]
    fn test_proxy_new_creates_instance() {
        let config = create_test_config();
        let proxy = Proxy::new(config);

        // Verify that proxy was created and has a key
        let key = proxy.key();
        assert!(!key.is_empty());
        assert_eq!(key.len(), 10);
    }

    #[test]
    fn test_proxy_new_assigns_random_port_when_zero() {
        let config = create_test_config();
        let proxy = Proxy::new(config);

        // Port should be assigned a random value between 1025 and 65535
        let port = proxy.get_port();
        assert!(port >= 1025);
        assert_ne!(port, proxy.get_config().network.insecure_port);
    }

    #[test]
    fn test_proxy_new_preserves_explicit_port() {
        let mut config = create_test_config();
        config.network.port = 8080;
        let proxy = Proxy::new(config);

        assert_eq!(proxy.get_port(), 8080);
    }

    #[test]
    fn test_proxy_get_config_returns_reference() {
        let config = create_test_config();
        let proxy = Proxy::new(config);

        let retrieved_config = proxy.get_config();
        assert_eq!(retrieved_config.network.host, "127.0.0.1");
        assert!(retrieved_config.network.secure);
    }

    #[test]
    fn test_proxy_get_state_uninitialized() {
        let config = create_test_config();
        let proxy = Proxy::new(config);

        // Before run() is called, proxy should be uninitialized
        assert_eq!(proxy.get_state(), ProxyState::Uninitialized);
    }

    #[test]
    fn test_proxy_set_middleware() {
        let config = create_test_config();
        let mut proxy = Proxy::new(config);

        let middleware = ProxyMiddleware::new(Arc::new(DefaultAsyncMiddleware::new()));
        proxy.set_middleware(Some(middleware));

        // Middleware should be set
        assert!(proxy.test_middleware().is_some());
    }

    #[test]
    fn test_proxy_set_middleware_none() {
        let config = create_test_config();
        let mut proxy = Proxy::new(config);

        proxy.set_middleware(None);

        // Middleware should be None
        assert!(proxy.test_middleware().is_none());
    }

    #[test]
    fn test_proxy_set_vpn_config() {
        let config = create_test_config();
        let mut proxy = Proxy::new(config);

        proxy.set_vpn_config(None);

        // VPN config should be None
        assert!(proxy.test_vpn_config().is_none());
    }

    #[tokio::test]
    async fn test_proxy_halt_without_underlying_proxy_returns_error() {
        let config = create_test_config();
        let mut proxy = Proxy::new(config);

        // Calling halt before run should return an error
        let result = proxy.halt().await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_proxy_rerun_without_underlying_proxy_returns_error() {
        let config = create_test_config();
        let mut proxy = Proxy::new(config);

        // Calling rerun before run should return an error
        let result = proxy.rerun().await;
        assert!(result.is_err());
    }

    #[test]
    fn test_proxy_generate_certificate_authority_with_none() {
        let certs = Proxy::generate_certificate_authority(None);

        // Should generate new certificates
        assert!(!certs.certificates.is_empty());
    }

    #[test]
    fn test_proxy_middleware_new() {
        let middleware_handler = Arc::new(DefaultAsyncMiddleware::new());
        let _middleware = ProxyMiddleware::new(middleware_handler);
        // Successfully created without panic - the constructor validated the Arc<dyn ...> input
    }

    #[test]
    fn test_proxy_middleware_default() {
        let _middleware = ProxyMiddleware::default();
        // Successfully created default middleware without panic
    }

    #[test]
    fn test_proxy_state_enum_equality() {
        assert_eq!(ProxyState::Uninitialized, ProxyState::Uninitialized);
        assert_eq!(ProxyState::Initialized, ProxyState::Initialized);
        assert_eq!(ProxyState::Started, ProxyState::Started);
        assert_eq!(ProxyState::StopRequested, ProxyState::StopRequested);
        assert_eq!(ProxyState::Stopped, ProxyState::Stopped);

        assert_ne!(ProxyState::Uninitialized, ProxyState::Initialized);
    }

    #[test]
    fn test_proxy_state_enum_clone() {
        let state = ProxyState::Started;
        let cloned = state;
        assert_eq!(state, cloned);
    }

    #[test]
    fn test_proxy_service_trait_identifier() {
        let config = create_test_config();
        let proxy = Proxy::new(config);

        assert_eq!(proxy.identifier(), "Proxy");
    }

    #[test]
    fn test_proxy_service_trait_key() {
        let config = create_test_config();
        let proxy = Proxy::new(config);

        let key = proxy.key();
        assert_eq!(key.len(), 10);
    }

    #[tokio::test]
    async fn test_proxy_service_trait_status_requires_running_proxy() {
        let config = create_test_config();
        let proxy = Proxy::new(config);

        let result = proxy.status().await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_proxy_service_trait_register_mut() {
        let config = create_test_config();
        let proxy = Proxy::new(config);
        let proxy_arc = Arc::new(Mutex::new(proxy));

        let config2 = create_test_config();
        let proxy2 = Proxy::new(config2);

        let registry = proxy2.register_mut(proxy_arc).await;

        assert_eq!(registry.identifier, "Proxy");
        assert_eq!(registry.kind, "Proxy");
        assert!(!registry.active);
        assert!(!registry.enabled);
    }

    #[test]
    fn test_proxy_service_trait_is_enabled_respects_config() {
        let mut config = create_test_config();
        config.enable = false;
        let proxy = Proxy::new(config);
        assert!(!proxy.is_enabled());

        let proxy = Proxy::new(create_test_config());
        assert!(proxy.is_enabled());
    }

    #[test]
    fn test_default_async_middleware_new() {
        let _middleware = DefaultAsyncMiddleware::new();
        // Successfully created without panic
    }

    // Test that ProxyState implements Debug
    #[test]
    fn test_proxy_state_debug() {
        let state = ProxyState::Started;
        let debug_str = format!("{state:?}");
        assert!(debug_str.contains("Started"));
    }

    // Test that ProxyState implements PartialEq
    #[test]
    fn test_proxy_state_partial_eq() {
        assert!(ProxyState::Started == ProxyState::Started);
        assert!(ProxyState::Started != ProxyState::Stopped);
    }

    /// Integration test: bind real listener, start proxy, send HTTP request through it to a mock upstream.
    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
    #[tokio::test]
    async fn test_proxy_integration_forward_http_request() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;
        use tokio::net::TcpStream;

        let proxy_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let proxy_port = proxy_listener.local_addr().unwrap().port();

        let certs = Proxy::generate_certificate_authority(None);
        let proxy = mitm::Proxy::https_builder()
            .use_listener(proxy_listener)
            .use_certificate_authority(certs)
            .use_rustls_client({
                match mitm::rustls::crypto::ring::default_provider().install_default() {
                    Ok(()) => mitm::rustls::crypto::ring::default_provider(),
                    Err(existing) => existing.as_ref().clone(),
                }
            })
            .expect("rustls client config")
            .use_http_handler(ProxyMiddleware::default())
            .build()
            .unwrap();
        let proxy = Arc::new(proxy);

        let proxy_clone = proxy.clone();
        tokio::spawn(async move {
            let _ = proxy_clone.start().await;
        });

        tokio::time::sleep(std::time::Duration::from_millis(150)).await;

        let upstream_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let upstream_port = upstream_listener.local_addr().unwrap().port();

        let upstream_handle = tokio::spawn(async move {
            let (mut stream, _) = upstream_listener.accept().await.unwrap();
            let response = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK";
            let _ = stream.write_all(response).await;
            let _ = stream.flush().await;
        });

        let mut client = TcpStream::connect((std::net::IpAddr::from([127, 0, 0, 1]), proxy_port))
            .await
            .unwrap();
        let request = format!(
            "GET http://127.0.0.1:{upstream_port}/ HTTP/1.1\r\nHost: 127.0.0.1:{upstream_port}\r\n\r\n"
        );
        client.write_all(request.as_bytes()).await.unwrap();
        client.flush().await.unwrap();

        let mut buf = vec![0u8; 1024];
        let n = client.read(&mut buf).await.unwrap();
        let response = String::from_utf8_lossy(&buf[..n]);
        assert!(
            response.contains("200 OK"),
            "expected 200 OK in response, got: {response}"
        );

        let _ = proxy.stop().await;
        let _ = upstream_handle.await;
    }

    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
    #[tokio::test]
    async fn test_proxy_run_waits_for_real_startup() {
        let (config, _dir) = create_managed_test_config();
        let mut proxy = Proxy::new(config);

        proxy.run().await.expect("proxy run");
        assert_eq!(proxy.get_state(), ProxyState::Started);
        assert!(proxy.status().await.is_ok());

        wait_for_proxy_ready("127.0.0.1", proxy.get_port())
            .await
            .expect("proxy ready");

        proxy.halt().await.expect("proxy halt");
        assert_eq!(proxy.get_state(), ProxyState::Uninitialized);
    }

    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
    #[tokio::test]
    async fn test_proxy_run_surfaces_bind_failure() {
        use tokio::net::TcpListener;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();

        let (mut config, _dir) = create_managed_test_config();
        config.network.port = port;
        config.network.insecure_port = port + 1;

        let mut proxy = Proxy::new(config);
        let err = proxy.run().await.expect_err("bind should fail");
        assert!(format!("{err}").contains("proxy startup failed"));
        assert_eq!(proxy.get_state(), ProxyState::Uninitialized);
    }

    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca"))]
    #[tokio::test]
    async fn test_proxy_rerun_performs_real_restart() {
        let (config, _dir) = create_managed_test_config();
        let mut proxy = Proxy::new(config);

        proxy.run().await.expect("first start");
        let port = proxy.get_port();
        proxy.rerun().await.expect("restart");
        assert_eq!(proxy.get_port(), port);
        assert_eq!(proxy.get_state(), ProxyState::Started);
        wait_for_proxy_ready("127.0.0.1", port)
            .await
            .expect("proxy ready after rerun");
        proxy.halt().await.expect("halt after rerun");
    }

    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca", not(feature = "vpn")))]
    #[tokio::test]
    async fn test_proxy_run_rejects_vpn_tunnel_when_feature_disabled() {
        let (mut config, _dir) = create_managed_test_config();
        config.enable_tunnel = true;
        config.tunnel_settings = NetworkProxyTunnel {
            tunnel_type: TunnelType::Vpn,
            ..Default::default()
        };

        let mut proxy = Proxy::new(config);
        let err = proxy
            .run()
            .await
            .expect_err("vpn feature should be required");
        assert!(format!("{err}").contains("'vpn' feature"));
    }

    #[cfg(all(feature = "rustls_client", feature = "rcgen_ca", feature = "vpn"))]
    #[tokio::test]
    async fn test_proxy_run_rejects_missing_vpn_config() {
        let (mut config, _dir) = create_managed_test_config();
        config.enable_tunnel = true;
        config.tunnel_settings = NetworkProxyTunnel {
            tunnel_type: TunnelType::Vpn,
            ..Default::default()
        };

        let mut proxy = Proxy::new(config);
        let err = proxy
            .run()
            .await
            .expect_err("vpn config should be required");
        assert!(format!("{err}").contains("no VPN config"));
    }

    #[test]
    fn test_load_or_create_managed_certificate_authority_returns_paths() {
        let dir = tempfile::tempdir().expect("temp dir");
        let loaded =
            Proxy::load_or_create_managed_certificate_authority(Some(dir.path().to_path_buf()))
                .expect("managed CA");
        assert!(loaded.cert_path.is_some());
        assert!(loaded.key_path.is_some());
    }
}