foxy-io 0.3.4

A configuration-driven and hyper-extensible HTTP proxy library
Documentation
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

#[cfg(test)]
mod tests {
    use crate::{
        HttpMethod, ProxyRequest, ProxyResponse,
        RequestContext, ResponseContext, ProxyError, FilterType,
        Filter, Router, Route
    };
    use crate::core::ProxyCore;
    use crate::config::{Config, ConfigProvider, ConfigError};
    use crate::security::{SecurityProvider, SecurityStage};
    use async_trait::async_trait;
    use std::sync::Arc;
    use tokio::sync::RwLock;
    use std::time::Duration;
    use serde_json::Value;
    use std::collections::HashMap;

    #[test]
    fn test_http_method_from() {
        assert_eq!(HttpMethod::from(&reqwest::Method::GET), HttpMethod::Get);
        assert_eq!(HttpMethod::from(&reqwest::Method::POST), HttpMethod::Post);
        assert_eq!(HttpMethod::from(&reqwest::Method::PUT), HttpMethod::Put);
        assert_eq!(HttpMethod::from(&reqwest::Method::DELETE), HttpMethod::Delete);
        assert_eq!(HttpMethod::from(&reqwest::Method::HEAD), HttpMethod::Head);
        assert_eq!(HttpMethod::from(&reqwest::Method::OPTIONS), HttpMethod::Options);
        assert_eq!(HttpMethod::from(&reqwest::Method::PATCH), HttpMethod::Patch);
        assert_eq!(HttpMethod::from(&reqwest::Method::TRACE), HttpMethod::Trace);
        assert_eq!(HttpMethod::from(&reqwest::Method::CONNECT), HttpMethod::Connect);
    }

    #[test]
    fn test_http_method_to_string() {
        assert_eq!(HttpMethod::Get.to_string(), "GET");
        assert_eq!(HttpMethod::Post.to_string(), "POST");
        assert_eq!(HttpMethod::Put.to_string(), "PUT");
        assert_eq!(HttpMethod::Delete.to_string(), "DELETE");
        assert_eq!(HttpMethod::Head.to_string(), "HEAD");
        assert_eq!(HttpMethod::Options.to_string(), "OPTIONS");
        assert_eq!(HttpMethod::Patch.to_string(), "PATCH");
        assert_eq!(HttpMethod::Trace.to_string(), "TRACE");
        assert_eq!(HttpMethod::Connect.to_string(), "CONNECT");
    }

    #[test]
    fn test_request_context() {
        let mut context = RequestContext::default();

        // Test attribute manipulation
        context.attributes.insert("key1".to_string(), serde_json::json!("value1"));
        context.attributes.insert("key2".to_string(), serde_json::json!(42));

        assert_eq!(context.attributes.get("key1").unwrap(), &serde_json::json!("value1"));
        assert_eq!(context.attributes.get("key2").unwrap(), &serde_json::json!(42));
    }

    #[test]
    fn test_response_context() {
        let mut context = ResponseContext::default();

        // Test attribute manipulation
        context.attributes.insert("key1".to_string(), serde_json::json!("value1"));
        context.attributes.insert("key2".to_string(), serde_json::json!(42));

        assert_eq!(context.attributes.get("key1").unwrap(), &serde_json::json!("value1"));
        assert_eq!(context.attributes.get("key2").unwrap(), &serde_json::json!(42));
    }

    #[tokio::test]
    async fn test_proxy_request() {
        let context = Arc::new(RwLock::new(RequestContext::default()));
        let request = ProxyRequest {
            method: HttpMethod::Get,
            path: "/test".to_string(),
            query: Some("param=value".to_string()),
            headers: reqwest::header::HeaderMap::new(),
            body: reqwest::Body::from(Vec::new()),
            context: context.clone(),
            custom_target: Option::Some("http://test.co.za".to_string()),
        };

        // Test context manipulation
        {
            let mut ctx = request.context.write().await;
            ctx.attributes.insert("test".to_string(), serde_json::json!("value"));
        }

        let ctx = request.context.read().await;
        assert_eq!(ctx.attributes.get("test").unwrap(), &serde_json::json!("value"));
    }

    #[tokio::test]
    async fn test_proxy_response() {
        let context = Arc::new(RwLock::new(ResponseContext::default()));
        let response = ProxyResponse {
            status: 200,
            headers: reqwest::header::HeaderMap::new(),
            body: reqwest::Body::from(Vec::new()),
            context: context.clone(),
        };

        // Test context manipulation
        {
            let mut ctx = response.context.write().await;
            ctx.attributes.insert("test".to_string(), serde_json::json!("value"));
        }

        let ctx = response.context.read().await;
        assert_eq!(ctx.attributes.get("test").unwrap(), &serde_json::json!("value"));
    }

    // Mock implementations for testing
    #[derive(Debug)]
    struct MockConfigProvider {
        values: HashMap<String, Value>,
    }

    impl MockConfigProvider {
        fn new() -> Self {
            let mut values = HashMap::new();
            values.insert("proxy.timeout".to_string(), Value::Number(30.into()));
            Self { values }
        }

        fn with_value<T: Into<Value>>(mut self, key: &str, value: T) -> Self {
            self.values.insert(key.to_string(), value.into());
            self
        }
    }

    impl ConfigProvider for MockConfigProvider {
        fn has(&self, key: &str) -> bool {
            self.values.contains_key(key)
        }

        fn provider_name(&self) -> &str {
            "mock"
        }

        fn get_raw(&self, key: &str) -> Result<Option<Value>, ConfigError> {
            Ok(self.values.get(key).cloned())
        }
    }

    #[derive(Debug)]
    struct MockRouter {
        routes: Vec<Route>,
        should_fail: bool,
    }

    impl MockRouter {
        fn new() -> Self {
            Self {
                routes: Vec::new(),
                should_fail: false,
            }
        }

        fn with_route(mut self, route: Route) -> Self {
            self.routes.push(route);
            self
        }

        fn with_failure(mut self) -> Self {
            self.should_fail = true;
            self
        }
    }

    #[async_trait]
    impl Router for MockRouter {
        async fn route(&self, _request: &ProxyRequest) -> Result<Route, ProxyError> {
            if self.should_fail {
                return Err(ProxyError::RoutingError("Mock routing failure".to_string()));
            }

            if let Some(route) = self.routes.first() {
                Ok(route.clone())
            } else {
                Err(ProxyError::RoutingError("No routes configured".to_string()))
            }
        }

        async fn get_routes(&self) -> Vec<Route> {
            self.routes.clone()
        }

        async fn add_route(&self, _route: Route) -> Result<(), ProxyError> {
            Ok(())
        }

        async fn remove_route(&self, _route_id: &str) -> Result<(), ProxyError> {
            Ok(())
        }
    }

    #[derive(Debug)]
    struct MockFilter {
        name: String,
        filter_type: FilterType,
        should_fail: bool,
        modify_request: bool,
        modify_response: bool,
    }

    impl MockFilter {
        fn new(name: &str, filter_type: FilterType) -> Self {
            Self {
                name: name.to_string(),
                filter_type,
                should_fail: false,
                modify_request: false,
                modify_response: false,
            }
        }

        fn with_failure(mut self) -> Self {
            self.should_fail = true;
            self
        }

        fn with_request_modification(mut self) -> Self {
            self.modify_request = true;
            self
        }

        fn with_response_modification(mut self) -> Self {
            self.modify_response = true;
            self
        }
    }

    #[async_trait]
    impl Filter for MockFilter {
        fn filter_type(&self) -> FilterType {
            self.filter_type
        }

        fn name(&self) -> &str {
            &self.name
        }

        async fn pre_filter(&self, request: ProxyRequest) -> Result<ProxyRequest, ProxyError> {
            if self.should_fail {
                return Err(ProxyError::FilterError("Mock filter failure".to_string()));
            }

            if self.modify_request {
                let mut ctx = request.context.write().await;
                ctx.attributes.insert("filter_applied".to_string(), Value::String(self.name.clone()));
            }

            Ok(request)
        }

        async fn post_filter(&self, _request: ProxyRequest, response: ProxyResponse) -> Result<ProxyResponse, ProxyError> {
            if self.should_fail {
                return Err(ProxyError::FilterError("Mock filter failure".to_string()));
            }

            if self.modify_response {
                let mut ctx = response.context.write().await;
                ctx.attributes.insert("filter_applied".to_string(), Value::String(self.name.clone()));
            }

            Ok(response)
        }
    }

    #[derive(Debug)]
    struct MockSecurityProvider {
        name: String,
        pre_failure: bool,
        post_failure: bool,
    }

    impl MockSecurityProvider {
        fn new(name: &str) -> Self {
            Self {
                name: name.to_string(),
                pre_failure: false,
                post_failure: false,
            }
        }

        fn with_pre_failure(mut self) -> Self {
            self.pre_failure = true;
            self
        }

        fn with_post_failure(mut self) -> Self {
            self.post_failure = true;
            self
        }
    }

    #[async_trait]
    impl SecurityProvider for MockSecurityProvider {
        fn stage(&self) -> SecurityStage {
            SecurityStage::Both
        }

        fn name(&self) -> &str {
            &self.name
        }

        async fn pre(&self, request: ProxyRequest) -> Result<ProxyRequest, ProxyError> {
            if self.pre_failure {
                Err(ProxyError::SecurityError("Mock security pre-auth failure".to_string()))
            } else {
                Ok(request)
            }
        }

        async fn post(&self, _request: ProxyRequest, response: ProxyResponse) -> Result<ProxyResponse, ProxyError> {
            if self.post_failure {
                Err(ProxyError::SecurityError("Mock security post-auth failure".to_string()))
            } else {
                Ok(response)
            }
        }
    }

    // Tests for ProxyError enum
    #[tokio::test]
    async fn test_proxy_error_display() {
        // Create a mock reqwest error by making a request to an invalid URL
        let client = reqwest::Client::new();
        let result = client.get("http://invalid-url-that-does-not-exist.invalid").send().await;
        let client_error = ProxyError::ClientError(result.unwrap_err());
        assert!(client_error.to_string().contains("HTTP client error"));

        let timeout_error = ProxyError::Timeout(Duration::from_secs(30));
        assert!(timeout_error.to_string().contains("request timed out"));

        let routing_error = ProxyError::RoutingError("No route found".to_string());
        assert_eq!(routing_error.to_string(), "routing error: No route found");

        let filter_error = ProxyError::FilterError("Filter failed".to_string());
        assert_eq!(filter_error.to_string(), "filter error: Filter failed");

        let config_error = ProxyError::ConfigError("Invalid config".to_string());
        assert_eq!(config_error.to_string(), "configuration error: Invalid config");

        let security_error = ProxyError::SecurityError("Auth failed".to_string());
        assert_eq!(security_error.to_string(), "security error: Auth failed");

        let other_error = ProxyError::Other("Generic error".to_string());
        assert_eq!(other_error.to_string(), "Generic error");
    }

    #[test]
    fn test_proxy_error_from_io_error() {
        let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
        let proxy_error = ProxyError::from(io_error);
        assert!(proxy_error.to_string().contains("IO error"));
    }

    // Tests for FilterType enum
    #[test]
    fn test_filter_type_equality() {
        assert_eq!(FilterType::Pre, FilterType::Pre);
        assert_eq!(FilterType::Post, FilterType::Post);
        assert_eq!(FilterType::Both, FilterType::Both);

        assert_ne!(FilterType::Pre, FilterType::Post);
        assert_ne!(FilterType::Pre, FilterType::Both);
        assert_ne!(FilterType::Post, FilterType::Both);
    }

    #[test]
    fn test_filter_type_debug() {
        assert_eq!(format!("{:?}", FilterType::Pre), "Pre");
        assert_eq!(format!("{:?}", FilterType::Post), "Post");
        assert_eq!(format!("{:?}", FilterType::Both), "Both");
    }

    // Tests for ProxyRequest cloning
    #[tokio::test]
    async fn test_proxy_request_clone() {
        let original = ProxyRequest {
            method: HttpMethod::Post,
            path: "/api/test".to_string(),
            query: Some("param=value".to_string()),
            headers: {
                let mut headers = reqwest::header::HeaderMap::new();
                headers.insert("content-type", "application/json".parse().unwrap());
                headers
            },
            body: reqwest::Body::from("original body"),
            context: Arc::new(RwLock::new(RequestContext::default())),
            custom_target: Some("http://example.com".to_string()),
        };

        let cloned = original.clone();

        // Verify all fields are cloned correctly
        assert_eq!(cloned.method, original.method);
        assert_eq!(cloned.path, original.path);
        assert_eq!(cloned.query, original.query);
        assert_eq!(cloned.headers, original.headers);
        assert_eq!(cloned.custom_target, original.custom_target);

        // Context should be the same Arc
        assert!(Arc::ptr_eq(&cloned.context, &original.context));

        // Body is cloned but we can't easily test its content since it's streaming
        // The important thing is that the clone operation succeeds
    }

    // Tests for RequestContext
    #[test]
    fn test_request_context_default() {
        let context = RequestContext::default();
        assert!(context.client_ip.is_none());
        assert!(context.start_time.is_none());
        assert!(context.attributes.is_empty());
    }

    #[test]
    fn test_request_context_with_data() {
        let mut context = RequestContext::default();
        context.client_ip = Some("192.168.1.1".to_string());
        context.start_time = Some(std::time::Instant::now());
        context.attributes.insert("user_id".to_string(), Value::String("123".to_string()));

        assert_eq!(context.client_ip.as_ref().unwrap(), "192.168.1.1");
        assert!(context.start_time.is_some());
        assert_eq!(context.attributes.get("user_id").unwrap(), &Value::String("123".to_string()));
    }

    // Tests for ResponseContext
    #[test]
    fn test_response_context_default() {
        let context = ResponseContext::default();
        assert!(context.receive_time.is_none());
        assert!(context.attributes.is_empty());
    }

    #[test]
    fn test_response_context_with_data() {
        let mut context = ResponseContext::default();
        context.receive_time = Some(std::time::Instant::now());
        context.attributes.insert("response_size".to_string(), Value::Number(1024.into()));

        assert!(context.receive_time.is_some());
        assert_eq!(context.attributes.get("response_size").unwrap(), &Value::Number(1024.into()));
    }

    // Tests for Route struct
    #[test]
    fn test_route_creation() {
        let route = Route {
            id: "test-route".to_string(),
            target_base_url: "http://example.com".to_string(),
            path_pattern: "/api/*".to_string(),
            filters: None,
        };

        assert_eq!(route.id, "test-route");
        assert_eq!(route.target_base_url, "http://example.com");
        assert_eq!(route.path_pattern, "/api/*");
        assert!(route.filters.is_none());
    }

    #[test]
    fn test_route_with_filters() {
        let filter = Arc::new(MockFilter::new("test-filter", FilterType::Pre));
        let route = Route {
            id: "test-route".to_string(),
            target_base_url: "http://example.com".to_string(),
            path_pattern: "/api/*".to_string(),
            filters: Some(vec![filter.clone()]),
        };

        assert!(route.filters.is_some());
        let filters = route.filters.unwrap();
        assert_eq!(filters.len(), 1);
        assert_eq!(filters[0].name(), "test-filter");
    }

    // Tests for ProxyCore
    #[tokio::test]
    async fn test_proxy_core_creation() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new());

        let proxy_core = ProxyCore::new(config.clone(), router).await;
        assert!(proxy_core.is_ok());

        let core = proxy_core.unwrap();
        assert!(Arc::ptr_eq(&core.config, &config));
    }

    #[tokio::test]
    async fn test_proxy_core_creation_with_custom_timeout() {
        let config_provider = MockConfigProvider::new()
            .with_value("proxy.timeout", 60);
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new());

        let proxy_core = ProxyCore::new(config, router).await;
        assert!(proxy_core.is_ok());
    }

    #[tokio::test]
    async fn test_proxy_core_add_global_filter() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new());
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        let filter = Arc::new(MockFilter::new("global-filter", FilterType::Both));
        proxy_core.add_global_filter(filter.clone()).await;

        let filters = proxy_core.global_filters.read().await;
        assert_eq!(filters.len(), 1);
        assert_eq!(filters[0].name(), "global-filter");
    }

    #[tokio::test]
    async fn test_proxy_core_multiple_global_filters() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new());
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        let filter1 = Arc::new(MockFilter::new("filter-1", FilterType::Pre));
        let filter2 = Arc::new(MockFilter::new("filter-2", FilterType::Post));

        proxy_core.add_global_filter(filter1).await;
        proxy_core.add_global_filter(filter2).await;

        let filters = proxy_core.global_filters.read().await;
        assert_eq!(filters.len(), 2);
        assert_eq!(filters[0].name(), "filter-1");
        assert_eq!(filters[1].name(), "filter-2");
    }

    // Helper function to create a test request
    fn create_test_request(method: HttpMethod, path: &str) -> ProxyRequest {
        ProxyRequest {
            method,
            path: path.to_string(),
            query: None,
            headers: reqwest::header::HeaderMap::new(),
            body: reqwest::Body::from(Vec::new()),
            context: Arc::new(RwLock::new(RequestContext::default())),
            custom_target: Some("http://test.example.com".to_string()),
        }
    }

    // Tests for Mock implementations
    #[tokio::test]
    async fn test_mock_router_success() {
        let route = Route {
            id: "test-route".to_string(),
            target_base_url: "http://example.com".to_string(),
            path_pattern: "/api/*".to_string(),
            filters: None,
        };

        let router = MockRouter::new().with_route(route.clone());
        let request = create_test_request(HttpMethod::Get, "/api/users");

        let result = router.route(&request).await;
        assert!(result.is_ok());

        let returned_route = result.unwrap();
        assert_eq!(returned_route.id, route.id);
        assert_eq!(returned_route.target_base_url, route.target_base_url);
    }

    #[tokio::test]
    async fn test_mock_router_failure() {
        let router = MockRouter::new().with_failure();
        let request = create_test_request(HttpMethod::Get, "/api/users");

        let result = router.route(&request).await;
        assert!(result.is_err());

        if let Err(ProxyError::RoutingError(msg)) = result {
            assert_eq!(msg, "Mock routing failure");
        } else {
            panic!("Expected RoutingError");
        }
    }

    #[tokio::test]
    async fn test_mock_router_no_routes() {
        let router = MockRouter::new();
        let request = create_test_request(HttpMethod::Get, "/api/users");

        let result = router.route(&request).await;
        assert!(result.is_err());

        if let Err(ProxyError::RoutingError(msg)) = result {
            assert_eq!(msg, "No routes configured");
        } else {
            panic!("Expected RoutingError");
        }
    }

    // Tests for Filter trait implementations
    #[tokio::test]
    async fn test_mock_filter_pre_filter_success() {
        let filter = MockFilter::new("test-filter", FilterType::Pre);
        let request = create_test_request(HttpMethod::Get, "/test");

        let result = filter.pre_filter(request).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_mock_filter_pre_filter_failure() {
        let filter = MockFilter::new("test-filter", FilterType::Pre).with_failure();
        let request = create_test_request(HttpMethod::Get, "/test");

        let result = filter.pre_filter(request).await;
        assert!(result.is_err());

        if let Err(ProxyError::FilterError(msg)) = result {
            assert_eq!(msg, "Mock filter failure");
        } else {
            panic!("Expected FilterError");
        }
    }

    #[tokio::test]
    async fn test_mock_filter_pre_filter_with_modification() {
        let filter = MockFilter::new("test-filter", FilterType::Pre)
            .with_request_modification();
        let request = create_test_request(HttpMethod::Get, "/test");

        let result = filter.pre_filter(request).await;
        assert!(result.is_ok());

        let modified_request = result.unwrap();
        let ctx = modified_request.context.read().await;
        assert_eq!(
            ctx.attributes.get("filter_applied").unwrap(),
            &Value::String("test-filter".to_string())
        );
    }

    #[tokio::test]
    async fn test_mock_filter_post_filter_success() {
        let filter = MockFilter::new("test-filter", FilterType::Post);
        let request = create_test_request(HttpMethod::Get, "/test");
        let response = ProxyResponse {
            status: 200,
            headers: reqwest::header::HeaderMap::new(),
            body: reqwest::Body::from(Vec::new()),
            context: Arc::new(RwLock::new(ResponseContext::default())),
        };

        let result = filter.post_filter(request, response).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_mock_filter_post_filter_failure() {
        let filter = MockFilter::new("test-filter", FilterType::Post).with_failure();
        let request = create_test_request(HttpMethod::Get, "/test");
        let response = ProxyResponse {
            status: 200,
            headers: reqwest::header::HeaderMap::new(),
            body: reqwest::Body::from(Vec::new()),
            context: Arc::new(RwLock::new(ResponseContext::default())),
        };

        let result = filter.post_filter(request, response).await;
        assert!(result.is_err());

        if let Err(ProxyError::FilterError(msg)) = result {
            assert_eq!(msg, "Mock filter failure");
        } else {
            panic!("Expected FilterError");
        }
    }

    #[tokio::test]
    async fn test_mock_filter_post_filter_with_modification() {
        let filter = MockFilter::new("test-filter", FilterType::Post)
            .with_response_modification();
        let request = create_test_request(HttpMethod::Get, "/test");
        let response = ProxyResponse {
            status: 200,
            headers: reqwest::header::HeaderMap::new(),
            body: reqwest::Body::from(Vec::new()),
            context: Arc::new(RwLock::new(ResponseContext::default())),
        };

        let result = filter.post_filter(request, response).await;
        assert!(result.is_ok());

        let modified_response = result.unwrap();
        let ctx = modified_response.context.read().await;
        assert_eq!(
            ctx.attributes.get("filter_applied").unwrap(),
            &Value::String("test-filter".to_string())
        );
    }

    #[test]
    fn test_mock_filter_properties() {
        let filter = MockFilter::new("test-filter", FilterType::Both);
        assert_eq!(filter.name(), "test-filter");
        assert_eq!(filter.filter_type(), FilterType::Both);
    }

    // Tests for Router trait implementations
    #[tokio::test]
    async fn test_mock_router_get_routes() {
        let route1 = Route {
            id: "route-1".to_string(),
            target_base_url: "http://example1.com".to_string(),
            path_pattern: "/api/*".to_string(),
            filters: None,
        };
        let route2 = Route {
            id: "route-2".to_string(),
            target_base_url: "http://example2.com".to_string(),
            path_pattern: "/v2/*".to_string(),
            filters: None,
        };

        let router = MockRouter::new()
            .with_route(route1.clone())
            .with_route(route2.clone());

        let routes = router.get_routes().await;
        assert_eq!(routes.len(), 2);
        assert_eq!(routes[0].id, "route-1");
        assert_eq!(routes[1].id, "route-2");
    }

    #[tokio::test]
    async fn test_mock_router_add_remove_route() {
        let router = MockRouter::new();
        let route = Route {
            id: "test-route".to_string(),
            target_base_url: "http://example.com".to_string(),
            path_pattern: "/test/*".to_string(),
            filters: None,
        };

        // Test add_route
        let result = router.add_route(route).await;
        assert!(result.is_ok());

        // Test remove_route
        let result = router.remove_route("test-route").await;
        assert!(result.is_ok());
    }

    // Tests for ProxyCore::process_request - Error scenarios
    #[tokio::test]
    async fn test_proxy_core_process_request_security_pre_auth_failure() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new());
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        // Add a security provider that will fail
        let security_provider = Arc::new(MockSecurityProvider::new("test-security").with_pre_failure());
        proxy_core.add_security_provider(security_provider).await;

        let request = create_test_request(HttpMethod::Get, "/test");

        let result = proxy_core.process_request(
            request,
            #[cfg(feature = "opentelemetry")]
            None,
        ).await;

        assert!(result.is_err());
        if let Err(ProxyError::SecurityError(msg)) = result {
            assert_eq!(msg, "test-security: security error: Mock security pre-auth failure");
        } else {
            panic!("Expected SecurityError");
        }
    }

    #[tokio::test]
    async fn test_proxy_core_process_request_global_pre_filter_failure() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new().with_route(Route {
            id: "test-route".to_string(),
            target_base_url: "http://example.com".to_string(),
            path_pattern: "/test/*".to_string(),
            filters: None,
        }));
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        // Add a global filter that will fail
        let filter = Arc::new(MockFilter::new("failing-filter", FilterType::Pre).with_failure());
        proxy_core.add_global_filter(filter).await;

        let request = create_test_request(HttpMethod::Get, "/test");

        let result = proxy_core.process_request(
            request,
            #[cfg(feature = "opentelemetry")]
            None,
        ).await;

        assert!(result.is_err());
        if let Err(ProxyError::FilterError(msg)) = result {
            assert_eq!(msg, "Mock filter failure");
        } else {
            panic!("Expected FilterError");
        }
    }

    #[tokio::test]
    async fn test_proxy_core_process_request_routing_failure() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new().with_failure());
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        let request = create_test_request(HttpMethod::Get, "/test");

        let result = proxy_core.process_request(
            request,
            #[cfg(feature = "opentelemetry")]
            None,
        ).await;

        assert!(result.is_err());
        if let Err(ProxyError::RoutingError(msg)) = result {
            assert_eq!(msg, "Mock routing failure");
        } else {
            panic!("Expected RoutingError");
        }
    }

    #[tokio::test]
    async fn test_proxy_core_process_request_route_pre_filter_failure() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());

        // Create a route with a failing filter
        let failing_filter = Arc::new(MockFilter::new("route-filter", FilterType::Pre).with_failure());
        let route = Route {
            id: "test-route".to_string(),
            target_base_url: "http://example.com".to_string(),
            path_pattern: "/test/*".to_string(),
            filters: Some(vec![failing_filter]),
        };

        let router = Arc::new(MockRouter::new().with_route(route));
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        let request = create_test_request(HttpMethod::Get, "/test");

        let result = proxy_core.process_request(
            request,
            #[cfg(feature = "opentelemetry")]
            None,
        ).await;

        assert!(result.is_err());
        if let Err(ProxyError::FilterError(msg)) = result {
            assert_eq!(msg, "Mock filter failure");
        } else {
            panic!("Expected FilterError");
        }
    }

    #[tokio::test]
    async fn test_proxy_core_process_request_custom_target() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new().with_route(Route {
            id: "test-route".to_string(),
            target_base_url: "http://original.com".to_string(),
            path_pattern: "/test/*".to_string(),
            filters: None,
        }));
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        let mut request = create_test_request(HttpMethod::Get, "/test");
        request.custom_target = Some("http://custom.com".to_string());

        // This test will fail at the HTTP request stage since we're not mocking the HTTP client
        // But it will test the custom target logic
        let result = proxy_core.process_request(
            request,
            #[cfg(feature = "opentelemetry")]
            None,
        ).await;

        // We expect this to fail with a client error since we can't actually make HTTP requests
        assert!(result.is_err());
        // The error should be a client error, not a routing error
        assert!(matches!(result.unwrap_err(), ProxyError::ClientError(_)));
    }

    #[tokio::test]
    async fn test_proxy_core_process_request_with_query_string() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new().with_route(Route {
            id: "test-route".to_string(),
            target_base_url: "http://example.com".to_string(),
            path_pattern: "/test/*".to_string(),
            filters: None,
        }));
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        let mut request = create_test_request(HttpMethod::Get, "/test");
        request.query = Some("param1=value1&param2=value2".to_string());

        let result = proxy_core.process_request(
            request,
            #[cfg(feature = "opentelemetry")]
            None,
        ).await;

        // Should fail with client error since we can't make real HTTP requests
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ProxyError::ClientError(_)));
    }

    #[tokio::test]
    async fn test_proxy_core_process_request_timeout_from_context() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new().with_route(Route {
            id: "test-route".to_string(),
            target_base_url: "http://example.com".to_string(),
            path_pattern: "/test/*".to_string(),
            filters: None,
        }));
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        let request = create_test_request(HttpMethod::Get, "/test");

        // Set a custom timeout in the request context
        {
            let mut ctx = request.context.write().await;
            ctx.attributes.insert("timeout_ms".to_string(), Value::Number(1000.into()));
        }

        let result = proxy_core.process_request(
            request,
            #[cfg(feature = "opentelemetry")]
            None,
        ).await;

        // Should fail with client error since we can't make real HTTP requests
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), ProxyError::ClientError(_)));
    }

    #[tokio::test]
    async fn test_proxy_core_process_request_route_post_filter_failure() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());

        // Create a route with a failing post filter
        let failing_filter = Arc::new(MockFilter::new("route-post-filter", FilterType::Post).with_failure());
        let route = Route {
            id: "test-route".to_string(),
            target_base_url: "http://httpbin.org".to_string(), // Use a real endpoint
            path_pattern: "/test/*".to_string(),
            filters: Some(vec![failing_filter]),
        };

        let router = Arc::new(MockRouter::new().with_route(route));
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        let request = create_test_request(HttpMethod::Get, "/get");

        let result = proxy_core.process_request(
            request,
            #[cfg(feature = "opentelemetry")]
            None,
        ).await;

        // This might succeed or fail depending on network, but if it gets to post-filter stage
        // and the filter fails, we should get a FilterError
        if let Err(ProxyError::FilterError(msg)) = result {
            assert_eq!(msg, "Mock filter failure");
        } else {
            // If it fails earlier (e.g., network), that's also acceptable for this test
            assert!(result.is_err());
        }
    }

    #[tokio::test]
    async fn test_proxy_core_process_request_global_post_filter_failure() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new().with_route(Route {
            id: "test-route".to_string(),
            target_base_url: "http://httpbin.org".to_string(),
            path_pattern: "/test/*".to_string(),
            filters: None,
        }));
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        // Add a global post filter that will fail
        let filter = Arc::new(MockFilter::new("failing-post-filter", FilterType::Post).with_failure());
        proxy_core.add_global_filter(filter).await;

        let request = create_test_request(HttpMethod::Get, "/get");

        let result = proxy_core.process_request(
            request,
            #[cfg(feature = "opentelemetry")]
            None,
        ).await;

        // This might succeed or fail depending on network, but if it gets to post-filter stage
        // and the filter fails, we should get a FilterError
        if let Err(ProxyError::FilterError(msg)) = result {
            assert_eq!(msg, "Mock filter failure");
        } else {
            // If it fails earlier (e.g., network), that's also acceptable for this test
            assert!(result.is_err());
        }
    }

    #[tokio::test]
    async fn test_proxy_core_process_request_security_post_auth_failure() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new().with_route(Route {
            id: "test-route".to_string(),
            target_base_url: "http://httpbin.org".to_string(),
            path_pattern: "/test/*".to_string(),
            filters: None,
        }));
        let proxy_core = ProxyCore::new(config, router).await.unwrap();

        // Add a security provider that will fail post-auth
        let security_provider = Arc::new(MockSecurityProvider::new("test-security").with_post_failure());
        proxy_core.add_security_provider(security_provider).await;

        let request = create_test_request(HttpMethod::Get, "/get");

        let result = proxy_core.process_request(
            request,
            #[cfg(feature = "opentelemetry")]
            None,
        ).await;

        // This might succeed or fail depending on network, but if it gets to post-auth stage
        // and the security provider fails, we should get a SecurityError
        if let Err(ProxyError::SecurityError(msg)) = result {
            assert!(msg.contains("Mock security post-auth failure"));
        } else {
            // If it fails earlier (e.g., network), that's also acceptable for this test
            assert!(result.is_err());
        }
    }

    #[test]
    fn test_proxy_error_from_config_error() {
        let config_error = crate::config::error::ConfigError::ParseError("Invalid format".to_string());
        let proxy_error = ProxyError::from(config_error);
        assert!(proxy_error.to_string().contains("configuration error"));
        assert!(proxy_error.to_string().contains("Invalid format"));
    }

    #[test]
    fn test_proxy_error_from_globset_error() {
        // Create a globset error by using invalid pattern
        let glob_result = globset::Glob::new("[");
        assert!(glob_result.is_err());
        let globset_error = glob_result.unwrap_err();
        let proxy_error = ProxyError::from(globset_error);
        assert!(proxy_error.to_string().contains("security error"));
    }

    #[test]
    fn test_proxy_error_from_jwt_error() {
        let jwt_error = jsonwebtoken::errors::Error::from(jsonwebtoken::errors::ErrorKind::InvalidToken);
        let proxy_error = ProxyError::from(jwt_error);
        assert!(proxy_error.to_string().contains("security error"));
    }

    #[test]
    fn test_http_method_from_unsupported_method() {
        // Test the default case for unsupported HTTP methods
        let custom_method = reqwest::Method::from_bytes(b"CUSTOM").unwrap();
        let http_method = HttpMethod::from(&custom_method);
        assert_eq!(http_method, HttpMethod::Get); // Should default to GET
    }

    #[test]
    fn test_http_method_into_reqwest() {
        assert_eq!(reqwest::Method::from(HttpMethod::Get), reqwest::Method::GET);
        assert_eq!(reqwest::Method::from(HttpMethod::Post), reqwest::Method::POST);
        assert_eq!(reqwest::Method::from(HttpMethod::Put), reqwest::Method::PUT);
        assert_eq!(reqwest::Method::from(HttpMethod::Delete), reqwest::Method::DELETE);
        assert_eq!(reqwest::Method::from(HttpMethod::Head), reqwest::Method::HEAD);
        assert_eq!(reqwest::Method::from(HttpMethod::Options), reqwest::Method::OPTIONS);
        assert_eq!(reqwest::Method::from(HttpMethod::Patch), reqwest::Method::PATCH);
        assert_eq!(reqwest::Method::from(HttpMethod::Trace), reqwest::Method::TRACE);
        assert_eq!(reqwest::Method::from(HttpMethod::Connect), reqwest::Method::CONNECT);
    }

    #[test]
    fn test_filter_type_is_methods() {
        assert!(FilterType::Pre.is_pre());
        assert!(!FilterType::Pre.is_post());
        assert!(!FilterType::Pre.is_both());

        assert!(!FilterType::Post.is_pre());
        assert!(FilterType::Post.is_post());
        assert!(!FilterType::Post.is_both());

        assert!(FilterType::Both.is_pre());
        assert!(FilterType::Both.is_post());
        assert!(FilterType::Both.is_both());
    }

    #[tokio::test]
    async fn test_proxy_core_with_security_chain_config_error() {
        let config_provider = MockConfigProvider::new()
            .with_value("proxy.security_chain", Value::String("invalid".to_string()));
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new());

        // This should still succeed but log a warning and use empty security chain
        let proxy_core = ProxyCore::new(config, router).await;
        assert!(proxy_core.is_ok());
    }

    #[tokio::test]
    async fn test_proxy_core_with_no_security_chain_config() {
        let config_provider = MockConfigProvider::new();
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new());

        let proxy_core = ProxyCore::new(config, router).await;
        assert!(proxy_core.is_ok());
    }

    #[tokio::test]
    async fn test_proxy_core_client_builder_error() {
        // Test with an invalid timeout value that might cause client builder to fail
        let config_provider = MockConfigProvider::new()
            .with_value("proxy.timeout", Value::Number(u64::MAX.into()));
        let config = Arc::new(Config::builder().with_provider(config_provider).build());
        let router = Arc::new(MockRouter::new());

        // This might succeed or fail depending on the reqwest client's validation
        let proxy_core = ProxyCore::new(config, router).await;
        // We can't easily force a client builder error, so we just ensure it doesn't panic
        assert!(proxy_core.is_ok() || proxy_core.is_err());
    }

    #[test]
    fn test_route_clone() {
        let filter = Arc::new(MockFilter::new("test-filter", FilterType::Pre));
        let route = Route {
            id: "test-route".to_string(),
            target_base_url: "http://example.com".to_string(),
            path_pattern: "/api/*".to_string(),
            filters: Some(vec![filter.clone()]),
        };

        let cloned_route = route.clone();
        assert_eq!(cloned_route.id, route.id);
        assert_eq!(cloned_route.target_base_url, route.target_base_url);
        assert_eq!(cloned_route.path_pattern, route.path_pattern);
        assert!(cloned_route.filters.is_some());
        assert_eq!(cloned_route.filters.as_ref().unwrap().len(), 1);
    }

    #[test]
    fn test_request_context_clone() {
        let mut context = RequestContext::default();
        context.client_ip = Some("192.168.1.1".to_string());
        context.start_time = Some(std::time::Instant::now());
        context.attributes.insert("key".to_string(), Value::String("value".to_string()));

        let cloned = context.clone();
        assert_eq!(cloned.client_ip, context.client_ip);
        assert_eq!(cloned.attributes, context.attributes);
        // start_time should be cloned but we can't easily test Instant equality
        assert!(cloned.start_time.is_some());
    }

    #[test]
    fn test_response_context_clone() {
        let mut context = ResponseContext::default();
        context.receive_time = Some(std::time::Instant::now());
        context.attributes.insert("key".to_string(), Value::String("value".to_string()));

        let cloned = context.clone();
        assert_eq!(cloned.attributes, context.attributes);
        // receive_time should be cloned but we can't easily test Instant equality
        assert!(cloned.receive_time.is_some());
    }
}