aws-smithy-http-client 1.5.0

HTTP client abstractions for generated smithy clients
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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! Proxy behavior contracts shared by the legacy and partitioned connection pools.
//!
//! Each contract is backend-neutral and has an explicit runner for every client
//! implementation that must preserve the behavior.

#![cfg(feature = "default-client")]

mod common {
    #[allow(dead_code)]
    pub(crate) mod client;
    #[cfg(all(
        feature = "wire-mock",
        any(feature = "rustls-ring", feature = "s2n-tls")
    ))]
    #[allow(dead_code)]
    pub(crate) mod h2;
    pub(crate) mod proxy;
    #[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
    pub(crate) mod tls;
}

use aws_smithy_http_client::proxy::ProxyConfig;
#[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
use aws_smithy_http_client::tls;
use aws_smithy_runtime_api::box_error::BoxError;
#[cfg(any(
    feature = "rustls-aws-lc",
    feature = "rustls-aws-lc-fips",
    feature = "rustls-ring",
    feature = "s2n-tls"
))]
use aws_smithy_runtime_api::client::dns::{
    DnsFuture, ResolveDns, ResolveDnsError, SharedDnsResolver,
};
use aws_smithy_runtime_api::client::http::{HttpConnector, SharedHttpClient, SharedHttpConnector};
use aws_smithy_runtime_api::client::orchestrator::HttpRequest;
#[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
use common::client::HttpsClientBackend;
use common::client::{
    self as test_client, BackendConfig, HttpClientBackend, HyperUtilLegacyPool,
    PartitionedConnectionPool,
};
#[cfg(all(
    feature = "wire-mock",
    any(feature = "rustls-ring", feature = "s2n-tls")
))]
use common::h2::{
    H2ConnectionPlan, H2ConnectionScript, H2Event, H2Response, H2StreamScript, H2TestServer,
};
use common::proxy::{basic_authorization, MockHttpServer};
#[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
use common::proxy::{MockConnectProxy, MockTlsOrigin};
#[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
use common::tls as test_tls;
use http_1x::{Response, StatusCode};
use http_body_util::BodyExt;
use std::future::Future;
use std::time::Duration;

struct TestClient {
    _client: SharedHttpClient,
    connector: SharedHttpConnector,
}

fn http_client(backend: &dyn HttpClientBackend, config: BackendConfig) -> TestClient {
    let client = backend.build(config);
    let connector = test_client::connector(&client);
    TestClient {
        _client: client,
        connector,
    }
}

fn proxy_backend_config(proxy_config: ProxyConfig) -> BackendConfig {
    BackendConfig {
        proxy_config: Some(proxy_config),
        ..Default::default()
    }
}

#[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
fn https_client(
    backend: &dyn HttpsClientBackend,
    config: BackendConfig,
    provider: tls::Provider,
    tls_context: tls::TlsContext,
) -> TestClient {
    let client = backend.build_https(config, provider, tls_context);
    let connector = test_client::connector(&client);
    TestClient {
        _client: client,
        connector,
    }
}

async fn send_request(
    client: &TestClient,
    request: HttpRequest,
) -> Result<(StatusCode, String), BoxError> {
    let response = client.connector.call(request).await?;
    let status = StatusCode::from_u16(response.status().as_u16())?;
    let body = response.into_body().collect().await?.to_bytes();
    Ok((status, String::from_utf8(body.to_vec())?))
}

async fn get(client: &TestClient, uri: &str) -> Result<(StatusCode, String), BoxError> {
    send_request(client, HttpRequest::get(uri)?).await
}

#[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
#[derive(Clone, Debug)]
struct FailingDns;

#[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
impl ResolveDns for FailingDns {
    fn resolve_dns<'a>(&'a self, name: &'a str) -> DnsFuture<'a> {
        DnsFuture::ready(Err(ResolveDnsError::new(std::io::Error::other(format!(
            "intentional DNS failure for {name}"
        )))))
    }
}

#[cfg(all(
    feature = "wire-mock",
    any(feature = "rustls-ring", feature = "s2n-tls")
))]
async fn h2_forward_proxy_applies_configured_authentication(
    backend: &dyn HttpsClientBackend,
    provider: tls::Provider,
) {
    let server = H2TestServer::builder()
        .connections(H2ConnectionPlan::queue([H2ConnectionScript::new().route(
            "/protected",
            H2StreamScript::respond(H2Response::ok("authenticated over H2")),
        )]))
        .start()
        .await
        .expect("H2 forward proxy should start");
    let config = ProxyConfig::http(server.url("/"))
        .expect("valid proxy URI")
        .with_basic_auth("h2user", "h2pass");
    let client = https_client(
        backend,
        proxy_backend_config(config),
        provider,
        test_tls::SERVER_IDENTITY.client_context(),
    );

    assert_eq!(
        (StatusCode::OK, "authenticated over H2".to_string()),
        get(&client, "http://origin.test/protected")
            .await
            .expect("H2 forward-proxy request should succeed")
    );
    let expected = basic_authorization("h2user", "h2pass");
    let authorization = server.events().into_iter().find_map(|event| match event {
        H2Event::StreamAccepted {
            path,
            proxy_authorization,
            ..
        } if path == "/protected" => proxy_authorization,
        _ => None,
    });
    assert_eq!(Some(expected), authorization);

    drop(client);
    server
        .shutdown()
        .await
        .expect("clean H2 forward-proxy shutdown");
}

#[cfg(all(feature = "wire-mock", feature = "rustls-ring"))]
#[tokio::test]
async fn test_h2_forward_proxy_auth_with_rustls_and_hyper_util_legacy_pool() {
    h2_forward_proxy_applies_configured_authentication(
        &HyperUtilLegacyPool,
        tls::Provider::rustls(tls::rustls_provider::CryptoMode::Ring),
    )
    .await;
}

#[cfg(all(feature = "wire-mock", feature = "rustls-ring"))]
#[tokio::test]
async fn test_h2_forward_proxy_auth_with_rustls_and_partitioned_connection_pool() {
    h2_forward_proxy_applies_configured_authentication(
        &PartitionedConnectionPool,
        tls::Provider::rustls(tls::rustls_provider::CryptoMode::Ring),
    )
    .await;
}

#[cfg(all(feature = "wire-mock", feature = "s2n-tls"))]
#[tokio::test]
async fn test_h2_forward_proxy_auth_with_s2n_tls_and_hyper_util_legacy_pool() {
    h2_forward_proxy_applies_configured_authentication(&HyperUtilLegacyPool, tls::Provider::S2nTls)
        .await;
}

#[cfg(all(feature = "wire-mock", feature = "s2n-tls"))]
#[tokio::test]
async fn test_h2_forward_proxy_auth_with_s2n_tls_and_partitioned_connection_pool() {
    h2_forward_proxy_applies_configured_authentication(
        &PartitionedConnectionPool,
        tls::Provider::S2nTls,
    )
    .await;
}

#[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
async fn https_proxy_dns_failure_remains_retryable_io(
    backend: &dyn HttpsClientBackend,
    provider: tls::Provider,
) {
    let client = https_client(
        backend,
        BackendConfig {
            proxy_config: Some(
                ProxyConfig::all("http://proxy.invalid:8080").expect("valid proxy URI"),
            ),
            dns_resolver: Some(SharedDnsResolver::new(FailingDns)),
            ..Default::default()
        },
        provider,
        tls::TlsContext::default(),
    );

    let error = test_client::send_request(
        &client.connector,
        HttpRequest::get("https://origin.test/protected").expect("valid request"),
    )
    .await
    .expect_err("proxy DNS failure must fail the request");
    assert!(
        error.is_io(),
        "HTTPS proxy DNS failure should remain retryable I/O, got {error:?}"
    );
}

#[cfg(feature = "rustls-ring")]
#[tokio::test]
async fn test_https_proxy_dns_failure_with_rustls_and_hyper_util_legacy_pool() {
    https_proxy_dns_failure_remains_retryable_io(
        &HyperUtilLegacyPool,
        tls::Provider::rustls(tls::rustls_provider::CryptoMode::Ring),
    )
    .await;
}

#[cfg(feature = "rustls-ring")]
#[tokio::test]
async fn test_https_proxy_dns_failure_with_rustls_and_partitioned_connection_pool() {
    https_proxy_dns_failure_remains_retryable_io(
        &PartitionedConnectionPool,
        tls::Provider::rustls(tls::rustls_provider::CryptoMode::Ring),
    )
    .await;
}

#[cfg(feature = "s2n-tls")]
#[tokio::test]
async fn test_https_proxy_dns_failure_with_s2n_tls_and_hyper_util_legacy_pool() {
    https_proxy_dns_failure_remains_retryable_io(&HyperUtilLegacyPool, tls::Provider::S2nTls).await;
}

#[cfg(feature = "s2n-tls")]
#[tokio::test]
async fn test_https_proxy_dns_failure_with_s2n_tls_and_partitioned_connection_pool() {
    https_proxy_dns_failure_remains_retryable_io(&PartitionedConnectionPool, tls::Provider::S2nTls)
        .await;
}

#[allow(clippy::await_holding_lock)]
async fn with_env_vars<F, Fut, R>(vars: &[(&str, &str)], test: F) -> R
where
    F: FnOnce() -> Fut,
    Fut: Future<Output = R>,
{
    static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _guard = ENV_MUTEX.lock().expect("environment lock is not poisoned");
    let previous: Vec<_> = vars
        .iter()
        .map(|(name, _)| (*name, std::env::var(name)))
        .collect();

    for (name, value) in vars {
        std::env::set_var(name, value);
    }
    let result = test().await;
    for (name, value) in previous {
        match value {
            Ok(value) => std::env::set_var(name, value),
            Err(_) => std::env::remove_var(name),
        }
    }
    result
}

async fn http_forward_proxy_uses_absolute_form(backend: &dyn HttpClientBackend) {
    let proxy = MockHttpServer::new(|request| {
        assert_eq!("GET", request.method);
        assert_eq!("http://api.example.com/v1/data", request.uri);
        assert_eq!(
            Some(&"api.example.com".to_string()),
            request.headers.get("host")
        );
        Response::builder()
            .status(StatusCode::OK)
            .body("proxied".to_string())
            .expect("valid response")
    })
    .await;
    let config = ProxyConfig::http(format!("http://{}", proxy.addr())).expect("valid proxy");
    let client = http_client(backend, proxy_backend_config(config));

    assert_eq!(
        (StatusCode::OK, "proxied".to_string()),
        get(&client, "http://api.example.com/v1/data")
            .await
            .expect("proxy request succeeds")
    );
    assert_eq!(1, proxy.requests().len());
}

#[tokio::test]
async fn test_http_forward_proxy_uses_absolute_form_with_hyper_util_legacy_pool() {
    http_forward_proxy_uses_absolute_form(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_http_forward_proxy_uses_absolute_form_with_partitioned_connection_pool() {
    http_forward_proxy_uses_absolute_form(&PartitionedConnectionPool).await;
}

#[cfg(any(
    feature = "rustls-aws-lc",
    feature = "rustls-aws-lc-fips",
    feature = "rustls-ring",
    feature = "s2n-tls"
))]
async fn custom_dns_resolver_is_used_for_proxy_connections(backend: &dyn HttpClientBackend) {
    const PROXY_HOST: &str = "proxy.test";

    let proxy = MockHttpServer::with_response(StatusCode::OK, "proxied through custom DNS").await;
    let resolver = proxy.dns_resolver(PROXY_HOST);
    let proxy_config = ProxyConfig::http(format!("http://{PROXY_HOST}:{}", proxy.addr().port()))
        .expect("valid proxy URI");
    let client = http_client(
        backend,
        BackendConfig {
            dns_resolver: Some(SharedDnsResolver::new(resolver.clone())),
            ..proxy_backend_config(proxy_config)
        },
    );

    assert_eq!(
        (StatusCode::OK, "proxied through custom DNS".to_string()),
        get(&client, "http://origin.test/custom-dns-proxy")
            .await
            .expect("proxy request succeeds")
    );
    assert_eq!(vec![PROXY_HOST.to_string()], resolver.lookups());
    assert_eq!(
        "http://origin.test/custom-dns-proxy",
        proxy.requests()[0].uri
    );
}

#[cfg(any(
    feature = "rustls-aws-lc",
    feature = "rustls-aws-lc-fips",
    feature = "rustls-ring",
    feature = "s2n-tls"
))]
#[tokio::test]
async fn test_custom_dns_resolver_is_used_for_proxy_connections_with_hyper_util_legacy_pool() {
    custom_dns_resolver_is_used_for_proxy_connections(&HyperUtilLegacyPool).await;
}

#[cfg(any(
    feature = "rustls-aws-lc",
    feature = "rustls-aws-lc-fips",
    feature = "rustls-ring",
    feature = "s2n-tls"
))]
#[tokio::test]
async fn test_custom_dns_resolver_is_used_for_proxy_connections_with_partitioned_connection_pool() {
    custom_dns_resolver_is_used_for_proxy_connections(&PartitionedConnectionPool).await;
}

async fn configured_proxy_authentication_is_applied(backend: &dyn HttpClientBackend) {
    let proxy = MockHttpServer::with_auth_validation("testuser", "testpass").await;
    let config = ProxyConfig::http(format!("http://{}", proxy.addr()))
        .expect("valid proxy")
        .with_basic_auth("testuser", "testpass");
    let client = http_client(backend, proxy_backend_config(config));

    assert_eq!(
        (StatusCode::OK, "authenticated".to_string()),
        get(&client, "http://service.test/protected")
            .await
            .expect("authenticated proxy request succeeds")
    );
    assert_eq!(
        Some(&basic_authorization("testuser", "testpass")),
        proxy.requests()[0].headers.get("proxy-authorization")
    );
}

#[tokio::test]
async fn test_configured_proxy_authentication_with_hyper_util_legacy_pool() {
    configured_proxy_authentication_is_applied(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_configured_proxy_authentication_with_partitioned_connection_pool() {
    configured_proxy_authentication_is_applied(&PartitionedConnectionPool).await;
}

async fn caller_proxy_authorization_is_preserved(backend: &dyn HttpClientBackend) {
    let caller_authorization = basic_authorization("caller", "credentials");
    let expected = caller_authorization.clone();
    let proxy = MockHttpServer::new(move |request| {
        assert_eq!(Some(&expected), request.headers.get("proxy-authorization"));
        Response::builder()
            .status(StatusCode::OK)
            .body("caller authorization".to_string())
            .expect("valid response")
    })
    .await;
    let config = ProxyConfig::http(format!("http://{}", proxy.addr()))
        .expect("valid proxy")
        .with_basic_auth("configured", "credentials");
    let client = http_client(backend, proxy_backend_config(config));
    let mut request = HttpRequest::get("http://service.test/caller-auth").expect("valid request");
    request
        .headers_mut()
        .insert("proxy-authorization", caller_authorization);

    assert_eq!(
        (StatusCode::OK, "caller authorization".to_string()),
        send_request(&client, request)
            .await
            .expect("caller authorization request succeeds")
    );
}

#[tokio::test]
async fn test_caller_proxy_authorization_is_preserved_with_hyper_util_legacy_pool() {
    caller_proxy_authorization_is_preserved(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_caller_proxy_authorization_is_preserved_with_partitioned_connection_pool() {
    caller_proxy_authorization_is_preserved(&PartitionedConnectionPool).await;
}

async fn proxy_url_authentication_is_applied(backend: &dyn HttpClientBackend) {
    let proxy = MockHttpServer::with_auth_validation("urluser", "urlpass").await;
    let config =
        ProxyConfig::http(format!("http://urluser:urlpass@{}", proxy.addr())).expect("valid proxy");
    let client = http_client(backend, proxy_backend_config(config));

    assert_eq!(
        StatusCode::OK,
        get(&client, "http://service.test/url-auth")
            .await
            .expect("URL-authenticated request succeeds")
            .0
    );
    assert_eq!(
        Some(&basic_authorization("urluser", "urlpass")),
        proxy.requests()[0].headers.get("proxy-authorization")
    );
}

#[tokio::test]
async fn test_proxy_url_authentication_with_hyper_util_legacy_pool() {
    proxy_url_authentication_is_applied(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_proxy_url_authentication_with_partitioned_connection_pool() {
    proxy_url_authentication_is_applied(&PartitionedConnectionPool).await;
}

async fn proxy_url_authentication_precedes_configured_authentication(
    backend: &dyn HttpClientBackend,
) {
    let proxy = MockHttpServer::with_auth_validation("urluser", "urlpass").await;
    let config = ProxyConfig::http(format!("http://urluser:urlpass@{}", proxy.addr()))
        .expect("valid proxy")
        .with_basic_auth("configured", "credentials");
    let client = http_client(backend, proxy_backend_config(config));

    assert_eq!(
        StatusCode::OK,
        get(&client, "http://service.test/auth-precedence")
            .await
            .expect("proxy request succeeds")
            .0
    );
    assert_eq!(
        Some(&basic_authorization("urluser", "urlpass")),
        proxy.requests()[0].headers.get("proxy-authorization")
    );
}

#[tokio::test]
async fn test_proxy_url_authentication_precedence_with_hyper_util_legacy_pool() {
    proxy_url_authentication_precedes_configured_authentication(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_proxy_url_authentication_precedence_with_partitioned_connection_pool() {
    proxy_url_authentication_precedes_configured_authentication(&PartitionedConnectionPool).await;
}

async fn environment_proxy_is_used(backend: &dyn HttpClientBackend) {
    let proxy = MockHttpServer::with_response(StatusCode::OK, "environment proxy").await;
    let proxy_uri = format!("http://{}", proxy.addr());
    with_env_vars(
        &[
            ("HTTP_PROXY", &proxy_uri),
            ("NO_PROXY", "localhost,127.0.0.1"),
        ],
        || async {
            let client = http_client(backend, proxy_backend_config(ProxyConfig::from_env()));
            assert_eq!(
                (StatusCode::OK, "environment proxy".to_string()),
                get(&client, "http://service.test/environment")
                    .await
                    .expect("environment proxy request succeeds")
            );
        },
    )
    .await;
    assert_eq!("http://service.test/environment", proxy.requests()[0].uri);
}

#[tokio::test]
async fn test_environment_proxy_with_hyper_util_legacy_pool() {
    environment_proxy_is_used(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_environment_proxy_with_partitioned_connection_pool() {
    environment_proxy_is_used(&PartitionedConnectionPool).await;
}

async fn no_proxy_bypasses_proxy(backend: &dyn HttpClientBackend) {
    let proxy = MockHttpServer::with_response(StatusCode::OK, "unexpected proxy").await;
    let origin = MockHttpServer::with_response(StatusCode::OK, "direct").await;
    let config = ProxyConfig::http(format!("http://{}", proxy.addr()))
        .expect("valid proxy")
        .no_proxy("127.0.0.1");
    let client = http_client(backend, proxy_backend_config(config));

    assert_eq!(
        (StatusCode::OK, "direct".to_string()),
        get(&client, &format!("http://{}/bypass", origin.addr()))
            .await
            .expect("direct request succeeds")
    );
    assert!(proxy.requests().is_empty());
    assert_eq!("/bypass", origin.requests()[0].uri);
}

#[tokio::test]
async fn test_no_proxy_bypass_with_hyper_util_legacy_pool() {
    no_proxy_bypasses_proxy(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_no_proxy_bypass_with_partitioned_connection_pool() {
    no_proxy_bypasses_proxy(&PartitionedConnectionPool).await;
}

async fn disabled_proxy_uses_direct_origin_form(backend: &dyn HttpClientBackend) {
    let origin = MockHttpServer::with_response(StatusCode::OK, "direct").await;
    let client = http_client(backend, proxy_backend_config(ProxyConfig::disabled()));

    assert_eq!(
        (StatusCode::OK, "direct".to_string()),
        get(&client, &format!("http://{}/direct", origin.addr()))
            .await
            .expect("direct request succeeds")
    );
    assert_eq!("/direct", origin.requests()[0].uri);
}

#[tokio::test]
async fn test_disabled_proxy_uses_direct_origin_form_with_hyper_util_legacy_pool() {
    disabled_proxy_uses_direct_origin_form(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_disabled_proxy_uses_direct_origin_form_with_partitioned_connection_pool() {
    disabled_proxy_uses_direct_origin_form(&PartitionedConnectionPool).await;
}

async fn https_only_proxy_bypasses_http(backend: &dyn HttpClientBackend) {
    let proxy = MockHttpServer::with_response(StatusCode::OK, "unexpected proxy").await;
    let origin = MockHttpServer::with_response(StatusCode::OK, "direct HTTP").await;
    let config =
        ProxyConfig::https(format!("http://{}", proxy.addr())).expect("valid proxy configuration");
    let client = http_client(backend, proxy_backend_config(config));

    assert_eq!(
        (StatusCode::OK, "direct HTTP".to_string()),
        get(&client, &format!("http://{}/http-only", origin.addr()))
            .await
            .expect("direct HTTP request succeeds")
    );
    assert!(proxy.requests().is_empty());
}

#[tokio::test]
async fn test_https_only_proxy_bypasses_http_with_hyper_util_legacy_pool() {
    https_only_proxy_bypasses_http(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_https_only_proxy_bypasses_http_with_partitioned_connection_pool() {
    https_only_proxy_bypasses_http(&PartitionedConnectionPool).await;
}

async fn all_traffic_proxy_forwards_http(backend: &dyn HttpClientBackend) {
    let proxy = MockHttpServer::with_response(StatusCode::OK, "all traffic").await;
    let config = ProxyConfig::all(format!("http://{}", proxy.addr())).expect("valid proxy");
    let client = http_client(backend, proxy_backend_config(config));

    assert_eq!(
        (StatusCode::OK, "all traffic".to_string()),
        get(&client, "http://service.test/all")
            .await
            .expect("all-traffic proxy request succeeds")
    );
    assert_eq!("http://service.test/all", proxy.requests()[0].uri);
}

#[tokio::test]
async fn test_all_traffic_proxy_forwards_http_with_hyper_util_legacy_pool() {
    all_traffic_proxy_forwards_http(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_all_traffic_proxy_forwards_http_with_partitioned_connection_pool() {
    all_traffic_proxy_forwards_http(&PartitionedConnectionPool).await;
}

async fn unreachable_proxy_fails(backend: &dyn HttpClientBackend) {
    let config = ProxyConfig::http("http://127.0.0.1:1").expect("valid proxy");
    let client = http_client(backend, proxy_backend_config(config));
    assert!(
        get(&client, "http://service.test/unreachable")
            .await
            .is_err(),
        "an unreachable proxy must fail the request"
    );
}

#[tokio::test]
async fn test_unreachable_proxy_fails_with_hyper_util_legacy_pool() {
    unreachable_proxy_fails(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_unreachable_proxy_fails_with_partitioned_connection_pool() {
    unreachable_proxy_fails(&PartitionedConnectionPool).await;
}

async fn incorrect_proxy_authentication_returns_407(backend: &dyn HttpClientBackend) {
    let proxy = MockHttpServer::with_auth_validation("correct", "password").await;
    let config = ProxyConfig::http(format!("http://{}", proxy.addr()))
        .expect("valid proxy")
        .with_basic_auth("wrong", "credentials");
    let client = http_client(backend, proxy_backend_config(config));

    assert_eq!(
        StatusCode::PROXY_AUTHENTICATION_REQUIRED,
        get(&client, "http://service.test/denied")
            .await
            .expect("proxy response is returned")
            .0
    );
    assert_eq!(
        Some(&basic_authorization("wrong", "credentials")),
        proxy.requests()[0].headers.get("proxy-authorization")
    );
}

#[tokio::test]
async fn test_incorrect_proxy_authentication_returns_407_with_hyper_util_legacy_pool() {
    incorrect_proxy_authentication_returns_407(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_incorrect_proxy_authentication_returns_407_with_partitioned_connection_pool() {
    incorrect_proxy_authentication_returns_407(&PartitionedConnectionPool).await;
}

async fn disabled_proxy_overrides_environment(backend: &dyn HttpClientBackend) {
    let proxy = MockHttpServer::with_response(StatusCode::OK, "unexpected proxy").await;
    let origin = MockHttpServer::with_response(StatusCode::OK, "direct").await;
    let proxy_uri = format!("http://{}", proxy.addr());
    with_env_vars(&[("HTTP_PROXY", &proxy_uri)], || async {
        let client = http_client(backend, proxy_backend_config(ProxyConfig::disabled()));
        assert_eq!(
            (StatusCode::OK, "direct".to_string()),
            get(&client, &format!("http://{}/disabled", origin.addr()))
                .await
                .expect("direct request succeeds")
        );
    })
    .await;
    assert!(proxy.requests().is_empty());
    assert_eq!("/disabled", origin.requests()[0].uri);
}

#[tokio::test]
async fn test_disabled_proxy_overrides_environment_with_hyper_util_legacy_pool() {
    disabled_proxy_overrides_environment(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_disabled_proxy_overrides_environment_with_partitioned_connection_pool() {
    disabled_proxy_overrides_environment(&PartitionedConnectionPool).await;
}

async fn idle_proxy_connection_is_evicted(backend: &dyn HttpClientBackend) {
    let proxy = MockHttpServer::with_response(StatusCode::OK, "proxied").await;
    let config = ProxyConfig::http(format!("http://{}", proxy.addr())).expect("valid proxy");
    let client = http_client(
        backend,
        BackendConfig {
            pool_idle_timeout: Some(Duration::from_millis(100)),
            ..proxy_backend_config(config)
        },
    );

    assert_eq!(
        StatusCode::OK,
        get(&client, "http://service.test/idle")
            .await
            .expect("proxy request succeeds")
            .0
    );
    assert_eq!(1, proxy.connection_count());

    tokio::time::timeout(Duration::from_secs(2), async {
        while proxy.connection_count() != 0 {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("idle proxy connection should close");
}

#[tokio::test]
async fn test_idle_proxy_connection_is_evicted_with_hyper_util_legacy_pool() {
    idle_proxy_connection_is_evicted(&HyperUtilLegacyPool).await;
}

#[tokio::test]
async fn test_idle_proxy_connection_is_evicted_with_partitioned_connection_pool() {
    idle_proxy_connection_is_evicted(&PartitionedConnectionPool).await;
}

#[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
async fn https_connect_uses_authority_form_and_authentication(
    backend: &dyn HttpsClientBackend,
    provider: tls::Provider,
) {
    let expected = basic_authorization("connectuser", "connectpass");
    let expected_for_handler = expected.clone();
    let proxy = MockHttpServer::new(move |request| {
        assert_eq!("CONNECT", request.method);
        assert_eq!("secure.example.com:443", request.uri);
        assert_eq!(
            Some(&expected_for_handler),
            request.headers.get("proxy-authorization")
        );
        Response::builder()
            .status(StatusCode::BAD_REQUEST)
            .body("tunnel rejected".to_string())
            .expect("valid response")
    })
    .await;
    let config = ProxyConfig::all(format!("http://{}", proxy.addr()))
        .expect("valid proxy")
        .with_basic_auth("connectuser", "connectpass");
    let client = https_client(
        backend,
        proxy_backend_config(config),
        provider,
        tls::TlsContext::default(),
    );

    assert!(
        get(&client, "https://secure.example.com/private")
            .await
            .is_err(),
        "a rejected CONNECT request must fail"
    );
    assert_eq!(1, proxy.requests().len());
}

#[cfg(feature = "rustls-ring")]
#[tokio::test]
async fn test_https_connect_form_and_auth_with_rustls_and_hyper_util_legacy_pool() {
    https_connect_uses_authority_form_and_authentication(
        &HyperUtilLegacyPool,
        tls::Provider::rustls(tls::rustls_provider::CryptoMode::Ring),
    )
    .await;
}

#[cfg(feature = "rustls-ring")]
#[tokio::test]
async fn test_https_connect_form_and_auth_with_rustls_and_partitioned_connection_pool() {
    https_connect_uses_authority_form_and_authentication(
        &PartitionedConnectionPool,
        tls::Provider::rustls(tls::rustls_provider::CryptoMode::Ring),
    )
    .await;
}

#[cfg(feature = "s2n-tls")]
#[tokio::test]
async fn test_https_connect_form_and_auth_with_s2n_tls_and_hyper_util_legacy_pool() {
    https_connect_uses_authority_form_and_authentication(
        &HyperUtilLegacyPool,
        tls::Provider::S2nTls,
    )
    .await;
}

#[cfg(feature = "s2n-tls")]
#[tokio::test]
async fn test_https_connect_form_and_auth_with_s2n_tls_and_partitioned_connection_pool() {
    https_connect_uses_authority_form_and_authentication(
        &PartitionedConnectionPool,
        tls::Provider::S2nTls,
    )
    .await;
}

#[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
async fn https_connect_without_authentication_is_rejected(
    backend: &dyn HttpsClientBackend,
    provider: tls::Provider,
) {
    let proxy = MockHttpServer::new(|request| {
        assert_eq!("CONNECT", request.method);
        assert_eq!("secure.example.com:443", request.uri);
        assert!(!request.headers.contains_key("proxy-authorization"));
        Response::builder()
            .status(StatusCode::PROXY_AUTHENTICATION_REQUIRED)
            .body("authentication required".to_string())
            .expect("valid response")
    })
    .await;
    let config = ProxyConfig::all(format!("http://{}", proxy.addr())).expect("valid proxy");
    let client = https_client(
        backend,
        proxy_backend_config(config),
        provider,
        tls::TlsContext::default(),
    );

    assert!(
        get(&client, "https://secure.example.com/private")
            .await
            .is_err(),
        "a 407 CONNECT response must fail"
    );
    assert_eq!(1, proxy.requests().len());
}

#[cfg(feature = "rustls-ring")]
#[tokio::test]
async fn test_https_connect_without_auth_with_rustls_and_hyper_util_legacy_pool() {
    https_connect_without_authentication_is_rejected(
        &HyperUtilLegacyPool,
        tls::Provider::rustls(tls::rustls_provider::CryptoMode::Ring),
    )
    .await;
}

#[cfg(feature = "rustls-ring")]
#[tokio::test]
async fn test_https_connect_without_auth_with_rustls_and_partitioned_connection_pool() {
    https_connect_without_authentication_is_rejected(
        &PartitionedConnectionPool,
        tls::Provider::rustls(tls::rustls_provider::CryptoMode::Ring),
    )
    .await;
}

#[cfg(feature = "s2n-tls")]
#[tokio::test]
async fn test_https_connect_without_auth_with_s2n_tls_and_hyper_util_legacy_pool() {
    https_connect_without_authentication_is_rejected(&HyperUtilLegacyPool, tls::Provider::S2nTls)
        .await;
}

#[cfg(feature = "s2n-tls")]
#[tokio::test]
async fn test_https_connect_without_auth_with_s2n_tls_and_partitioned_connection_pool() {
    https_connect_without_authentication_is_rejected(
        &PartitionedConnectionPool,
        tls::Provider::S2nTls,
    )
    .await;
}

#[cfg(any(feature = "rustls-ring", feature = "s2n-tls"))]
async fn tunneled_https_request_uses_origin_form(
    backend: &dyn HttpsClientBackend,
    provider: tls::Provider,
) {
    let origin = MockTlsOrigin::new("tunneled response").await;
    let authorization = basic_authorization("connectuser", "connectpass");
    let proxy = MockConnectProxy::relay_to(origin.addr(), Some(authorization.clone())).await;
    let config = ProxyConfig::all(format!("http://{}", proxy.addr()))
        .expect("valid proxy")
        .with_basic_auth("connectuser", "connectpass");
    let client = https_client(
        backend,
        proxy_backend_config(config),
        provider,
        test_tls::SERVER_IDENTITY.client_context(),
    );
    let target = format!("https://localhost:{}/inside?value=1", origin.addr().port());

    assert_eq!(
        (StatusCode::OK, "tunneled response".to_string()),
        get(&client, &target)
            .await
            .expect("tunneled HTTPS request succeeds")
    );

    let proxy_requests = proxy.requests();
    assert_eq!(1, proxy_requests.len());
    assert_eq!("CONNECT", proxy_requests[0].method);
    assert_eq!(
        format!("localhost:{}", origin.addr().port()),
        proxy_requests[0].uri
    );
    assert_eq!(
        Some(&authorization),
        proxy_requests[0].headers.get("proxy-authorization")
    );

    let origin_requests = origin.requests();
    assert_eq!(1, origin_requests.len());
    assert_eq!("GET", origin_requests[0].method);
    assert_eq!("/inside?value=1", origin_requests[0].uri);
    assert!(
        !origin_requests[0]
            .headers
            .contains_key("proxy-authorization"),
        "proxy credentials must not cross the CONNECT tunnel"
    );
}

#[cfg(feature = "rustls-ring")]
#[tokio::test]
async fn test_tunneled_https_origin_form_with_rustls_and_hyper_util_legacy_pool() {
    tunneled_https_request_uses_origin_form(
        &HyperUtilLegacyPool,
        tls::Provider::rustls(tls::rustls_provider::CryptoMode::Ring),
    )
    .await;
}

#[cfg(feature = "rustls-ring")]
#[tokio::test]
async fn test_tunneled_https_origin_form_with_rustls_and_partitioned_connection_pool() {
    tunneled_https_request_uses_origin_form(
        &PartitionedConnectionPool,
        tls::Provider::rustls(tls::rustls_provider::CryptoMode::Ring),
    )
    .await;
}

#[cfg(feature = "s2n-tls")]
#[tokio::test]
async fn test_tunneled_https_origin_form_with_s2n_tls_and_hyper_util_legacy_pool() {
    tunneled_https_request_uses_origin_form(&HyperUtilLegacyPool, tls::Provider::S2nTls).await;
}

#[cfg(feature = "s2n-tls")]
#[tokio::test]
async fn test_tunneled_https_origin_form_with_s2n_tls_and_partitioned_connection_pool() {
    tunneled_https_request_uses_origin_form(&PartitionedConnectionPool, tls::Provider::S2nTls)
        .await;
}