ntex 4.0.0-beta.17

Framework for composable network services
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
use std::{error::Error as StdError, fmt, net, rc::Rc};

use base64::{Engine, engine::general_purpose::STANDARD as base64};
#[cfg(feature = "cookie")]
use coo_kie::{Cookie, CookieJar};
use serde::Serialize;
use urly::Url;

use crate::error::Error;
use crate::http::error::HttpError;
use crate::http::header::{self, HeaderMap, HeaderName, HeaderValue};
use crate::http::{ConnectionType, Method, Version, body::Body};
use crate::{Cfg, PipelineBinding, time::Millis, util::Bytes, util::Stream};

use super::error::{ClientError, InvalidUrl};
use super::{ClientConfig, ClientResponse, ServiceRequest, ServiceResponse};

/// An HTTP client request builder.
///
/// Builder methods configure the request and the `send*` methods consume it,
/// send the request, and return a [`ClientResponse`].
///
/// ```rust
/// use ntex::client::Client;
///
/// #[ntex::main]
/// async fn main() {
///    let response = Client::new()
///         .get("http://www.rust-lang.org") // <- Create request builder
///         .header("User-Agent", "ntex::web")
///         .send()                          // <- Send http request
///         .await;
///
///    response.and_then(|response| {   // <- server http response
///         println!("Response: {:?}", response);
///         Ok(())
///    });
/// }
/// ```
pub struct ClientRequest {
    request: ServiceRequest,
    svc: PipelineBinding<ServiceRequest, ServiceResponse, Error<ClientError>>,
    err: Option<ClientError>,
    cfg: Cfg<ClientConfig>,
    #[cfg(feature = "cookie")]
    cookies: Option<CookieJar>,
}

impl ClientRequest {
    /// Create new client request builder.
    pub(super) fn new<U>(
        method: Method,
        uri: U,
        cfg: Cfg<ClientConfig>,
        svc: PipelineBinding<ServiceRequest, ServiceResponse, Error<ClientError>>,
    ) -> Self
    where
        Url: TryFrom<U>,
        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
    {
        ClientRequest {
            svc,
            cfg,
            request: ServiceRequest::new(),
            err: None,
            #[cfg(feature = "cookie")]
            cookies: None,
        }
        .method(method)
        .uri(uri)
    }

    /// Sets the request URI.
    ///
    /// URI conversion errors are stored and returned by the next `send*` call.
    #[inline]
    #[must_use]
    pub fn uri<U>(mut self, uri: U) -> Self
    where
        Url: TryFrom<U>,
        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
    {
        match Url::try_from(uri) {
            Ok(uri) => self.request.head.uri = uri,
            Err(e) => self.err = Some(e.into().into()),
        }
        self
    }

    /// Returns the request URI.
    pub fn get_uri(&self) -> &Url {
        &self.request.head.uri
    }

    #[must_use]
    /// Sets the server socket address.
    ///
    /// This address is used instead of resolving the URI host name.
    pub fn address(mut self, addr: net::SocketAddr) -> Self {
        self.request.addr = Some(addr);
        self
    }

    /// Sets the request method.
    #[inline]
    #[must_use]
    pub fn method(mut self, method: Method) -> Self {
        self.request.head.method = method;
        self
    }

    #[inline]
    #[must_use]
    /// Returns the request method.
    pub fn get_method(&self) -> &Method {
        &self.request.head.method
    }

    /// Sets the request HTTP version.
    ///
    /// By default, the version is selected from the negotiated transport
    /// protocol.
    #[inline]
    #[must_use]
    pub fn version(mut self, version: Version) -> Self {
        self.request.head.version = version;
        self
    }

    #[inline]
    /// Returns the request HTTP version.
    pub fn get_version(&self) -> &Version {
        &self.request.head.version
    }

    #[inline]
    /// Returns the request headers.
    pub fn headers(&self) -> &HeaderMap {
        &self.request.head.headers
    }

    #[inline]
    /// Returns mutable access to the request headers.
    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        &mut self.request.head.headers
    }

    #[must_use]
    /// Append a header.
    ///
    /// The header is appended to any existing values with the same name. Use
    /// [`set_header`](Self::set_header) to replace existing values.
    ///
    /// Header conversion errors are stored and returned by the next `send*`
    /// call.
    ///
    /// ```rust
    /// use ntex::{http, client::Client};
    ///
    /// #[ntex::main]
    /// async fn main() {
    ///     let req = Client::new()
    ///         .get("http://www.rust-lang.org")
    ///         .header("X-TEST", "value")
    ///         .header(http::header::CONTENT_TYPE, "application/json");
    /// }
    /// ```
    pub fn header<K, V>(mut self, key: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
    {
        match HeaderName::try_from(key) {
            Ok(key) => match HeaderValue::try_from(value) {
                Ok(value) => self.request.head.headers.append(key, value),
                Err(e) => self.err = Some(ClientError::Http(e.into())),
            },
            Err(e) => self.err = Some(ClientError::Http(e.into())),
        }
        self
    }

    #[must_use]
    /// Inserts a header, replacing existing values with the same name.
    ///
    /// Header conversion errors are stored and returned by the next `send*`
    /// call.
    pub fn set_header<K, V>(mut self, key: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
    {
        match HeaderName::try_from(key) {
            Ok(key) => match HeaderValue::try_from(value) {
                Ok(value) => self.request.head.headers.insert(key, value),
                Err(e) => self.err = Some(ClientError::Http(e.into())),
            },
            Err(e) => self.err = Some(ClientError::Http(e.into())),
        }
        self
    }

    #[must_use]
    /// Inserts a header if the request does not already contain one with the
    /// same name.
    ///
    /// Header conversion errors are stored and returned by the next `send*`
    /// call.
    pub fn set_header_if_none<K, V>(mut self, key: K, value: V) -> Self
    where
        HeaderName: TryFrom<K>,
        HeaderValue: TryFrom<V>,
        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
    {
        match HeaderName::try_from(key) {
            Ok(key) => {
                if !self.request.head.headers.contains_key(&key) {
                    match HeaderValue::try_from(value) {
                        Ok(value) => self.request.head.headers.insert(key, value),
                        Err(e) => self.err = Some(ClientError::Http(e.into())),
                    }
                }
            }
            Err(e) => self.err = Some(ClientError::Http(e.into())),
        }
        self
    }

    #[inline]
    #[must_use]
    /// Sets the request connection type.
    ///
    /// See [`RequestHead::set_connection_type()`](crate::http::RequestHead::set_connection_type)
    /// for how repeated calls are resolved.
    pub fn set_connection_type(mut self, ctype: ConnectionType) -> Self {
        self.request.head.set_connection_type(ctype);
        self
    }

    /// Prevents an HTTP/1 connection from returning to the connection pool.
    ///
    /// This setting affects only HTTP/1 connections.
    #[inline]
    #[must_use]
    pub fn force_close(mut self) -> Self {
        self.request.head.set_connection_type(ConnectionType::Close);
        self
    }

    /// Sets the request content type.
    ///
    /// Header conversion errors are stored and returned by the next `send*`
    /// call.
    #[inline]
    #[must_use]
    pub fn content_type<V>(mut self, value: V) -> Self
    where
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
    {
        match HeaderValue::try_from(value) {
            Ok(value) => self
                .request
                .head
                .headers
                .insert(header::CONTENT_TYPE, value),
            Err(e) => self.err = Some(ClientError::Http(e.into())),
        }
        self
    }

    /// Sets the request content length.
    #[inline]
    #[must_use]
    pub fn content_length(self, len: u64) -> Self {
        self.set_header(header::CONTENT_LENGTH, len)
    }

    #[must_use]
    /// Sets the HTTP basic authentication header.
    ///
    /// Replaces any existing `Authorization` header, including a client default.
    pub fn basic_auth<U>(self, username: U, password: Option<&str>) -> Self
    where
        U: fmt::Display,
    {
        let auth = match password {
            Some(password) => format!("{username}:{password}"),
            None => format!("{username}:"),
        };
        self.set_header(
            header::AUTHORIZATION,
            format!("Basic {}", base64.encode(auth)),
        )
    }

    #[must_use]
    /// Sets the HTTP bearer authentication header.
    ///
    /// Replaces any existing `Authorization` header, including a client default.
    pub fn bearer_auth<T>(self, token: T) -> Self
    where
        T: fmt::Display,
    {
        self.set_header(header::AUTHORIZATION, format!("Bearer {token}"))
    }

    #[must_use]
    #[cfg(feature = "cookie")]
    /// Set a cookie.
    ///
    /// ```rust
    /// use coo_kie as cookie;
    /// use ntex::client::Client;
    ///
    /// #[ntex::main]
    /// async fn main() {
    ///     let resp = Client::new().get("https://www.rust-lang.org")
    ///         .cookie(
    ///             cookie::Cookie::build(("name", "value"))
    ///                 .domain("www.rust-lang.org")
    ///                 .path("/")
    ///                 .secure(true)
    ///                 .http_only(true)
    ///          )
    ///          .send()
    ///          .await;
    ///
    ///     println!("Response: {:?}", resp);
    /// }
    /// ```
    pub fn cookie<C>(mut self, cookie: C) -> Self
    where
        C: Into<Cookie<'static>>,
    {
        if let Some(cookies) = &mut self.cookies {
            cookies.add(cookie.into());
        } else {
            let mut jar = CookieJar::new();
            jar.add(cookie.into());
            self.cookies = Some(jar);
        }
        self
    }

    #[must_use]
    /// Disables automatic decompression of the response body.
    pub fn no_decompress(mut self) -> Self {
        self.request.response_decompress = false;
        self
    }

    #[must_use]
    /// Sets the response-header timeout for this request.
    ///
    /// This overrides the client-wide timeout. The timeout covers receiving the
    /// response head after the request has been sent. A zero duration disables
    /// the timeout for this request.
    ///
    /// The client-wide default is 5 seconds.
    pub fn timeout<T: Into<Millis>>(mut self, timeout: T) -> Self {
        self.request.timeout = Some(timeout.into());
        self
    }

    #[must_use]
    /// Applies `f` to this builder when `value` is `true`.
    pub fn if_true<F>(self, value: bool, f: F) -> Self
    where
        F: FnOnce(ClientRequest) -> ClientRequest,
    {
        if value { f(self) } else { self }
    }

    #[must_use]
    /// Applies `f` and the contained value to this builder when `value` is
    /// [`Some`].
    pub fn if_some<T, F>(self, value: Option<T>, f: F) -> Self
    where
        F: FnOnce(T, ClientRequest) -> ClientRequest,
    {
        if let Some(val) = value { f(val, self) } else { self }
    }

    /// Serializes `query` and replaces the query component of the request URI.
    ///
    /// Serialization errors are stored and returned by the next `send*` call.
    #[must_use]
    pub fn query<T: Serialize>(mut self, query: &T) -> Self {
        let query = match serde_urlencoded::to_string(query) {
            Ok(query) => query,
            Err(err) => {
                self.err = Some(ClientError::Error(Rc::new(err)));
                return self;
            }
        };

        self.request.head.uri.set_query(Some(&query));
        self
    }
}

impl ClientRequest {
    /// Sends the request with `body`.
    pub async fn send_body<B>(mut self, body: B) -> Result<ClientResponse, Error<ClientError>>
    where
        B: Into<Body>,
    {
        self.prep_for_sending()?;
        *self.request.body() = body.into();
        self.svc.call(self.request).await.map(Into::into)
    }

    /// Serializes `value` as JSON and sends the request.
    pub async fn send_json<T: Serialize>(
        mut self,
        value: &T,
    ) -> Result<ClientResponse, Error<ClientError>> {
        self.prep_for_sending()?;
        self.request.set_json(value)?;
        self.svc.call(self.request).await.map(Into::into)
    }

    /// Serializes `value` as a URL-encoded form and sends the request.
    pub async fn send_form<T: Serialize>(
        mut self,
        value: &T,
    ) -> Result<ClientResponse, Error<ClientError>> {
        self.prep_for_sending()?;
        self.request.set_form(value)?;
        self.svc.call(self.request).await.map(Into::into)
    }

    /// Sends the request with a streaming body.
    pub async fn send_stream<T, E>(
        mut self,
        stream: T,
    ) -> Result<ClientResponse, Error<ClientError>>
    where
        T: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
        E: StdError + 'static,
    {
        self.prep_for_sending()?;
        self.request.set_stream(stream);
        self.svc.call(self.request).await.map(Into::into)
    }

    /// Sends the request with an empty body.
    pub async fn send(mut self) -> Result<ClientResponse, Error<ClientError>> {
        self.prep_for_sending()?;
        self.svc.call(self.request).await.map(Into::into)
    }

    fn prep_for_sending(&mut self) -> Result<(), Error<ClientError>> {
        self.prep_for_sending_inner()
            .map_err(|e| e.with_service(self.cfg.service()))
    }

    fn prep_for_sending_inner(&mut self) -> Result<(), Error<ClientError>> {
        if let Some(e) = self.err.take() {
            return Err(e.into());
        }

        // validate uri
        let uri = &self.request.head.uri;
        if uri.host().is_none() {
            return Err(ClientError::from(InvalidUrl::MissingHost).into());
        }
        match uri.scheme_str() {
            Some("http" | "ws" | "https" | "wss") => (),
            Some(_) => return Err(ClientError::from(InvalidUrl::UnknownScheme).into()),
            None => return Err(ClientError::from(InvalidUrl::MissingScheme).into()),
        }

        // set cookies, appended to an existing `Cookie` header
        #[cfg(feature = "cookie")]
        {
            if let Some(ref jar) = self.cookies {
                let headers = &mut self.request.head.headers;
                let mut cookie = headers
                    .get(header::COOKIE)
                    .map(|v| v.as_bytes().to_vec())
                    .unwrap_or_default();
                for c in jar.iter() {
                    crate::http::helpers::push_cookie(&mut cookie, c.name(), c.value());
                }
                if let Ok(val) = HeaderValue::from_bytes(&cookie) {
                    headers.insert(header::COOKIE, val);
                }
            }
        }

        #[cfg(feature = "compress")]
        if self.request.response_decompress
            && !self
                .request
                .head
                .headers
                .contains_key(&header::ACCEPT_ENCODING)
        {
            const COMPRESSION: HeaderValue = HeaderValue::from_static("gzip, deflate");
            self.request
                .head
                .headers
                .insert(header::ACCEPT_ENCODING, COMPRESSION);
        }

        Ok(())
    }
}

impl fmt::Debug for ClientRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "\nClientRequest {:?} {}:{}",
            self.request.head.version, self.request.head.method, self.request.head.uri
        )?;
        writeln!(f, "  headers:")?;
        for (key, val) in &self.request.head.headers {
            if key == header::AUTHORIZATION {
                writeln!(f, "    {key:?}: <REDACTED>")?;
            } else {
                writeln!(f, "    {key:?}: {val:?}")?;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{SharedCfg, client::Client};

    struct InvalidQuery;

    impl Serialize for InvalidQuery {
        fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error>
        where
            S: serde::Serializer,
        {
            Err(serde::ser::Error::custom("invalid query"))
        }
    }

    #[crate::rt_test]
    async fn test_debug() {
        let request = Client::new().get("/").header("x-test", "111");
        let repr = format!("{request:?}");
        assert!(repr.contains("ClientRequest"));
        assert!(repr.contains("x-test"));
    }

    #[crate::rt_test]
    async fn test_basics() {
        let mut req = Client::new()
            .put("/")
            .version(Version::HTTP_2)
            .header(header::DATE, "data")
            .content_type("plain/text")
            .if_true(true, |req| req.header(header::SERVER, "awc"))
            .if_true(false, |req| req.header(header::EXPECT, "awc"))
            .if_some(Some("server"), |val, req| {
                req.header(header::USER_AGENT, val)
            })
            .if_some(Option::<&str>::None, |_, req| {
                req.header(header::ALLOW, "1")
            })
            .content_length(100);
        assert!(req.headers().contains_key(header::CONTENT_TYPE));
        assert!(req.headers().contains_key(header::DATE));
        assert!(req.headers().contains_key(header::SERVER));
        assert!(req.headers().contains_key(header::USER_AGENT));
        assert!(!req.headers().contains_key(header::ALLOW));
        assert!(!req.headers().contains_key(header::EXPECT));
        assert_eq!(req.request.head.version, Version::HTTP_2);
        assert_eq!(req.get_version(), &Version::HTTP_2);
        assert_eq!(req.get_method(), Method::PUT);
        let _ = req.headers_mut();
        let _ = req.send_body("").await;
    }

    #[cfg(feature = "cookie")]
    #[crate::rt_test]
    async fn cookies_extend_cookie_header() {
        use coo_kie::Cookie;

        fn cookie_header(req: &mut ClientRequest) -> String {
            req.prep_for_sending_inner().unwrap();
            let val = req.request.head.headers.get(header::COOKIE).unwrap();
            val.to_str().unwrap().to_string()
        }

        let mut req = Client::new()
            .get("http://localhost/")
            .cookie(Cookie::build(("c1", "v1")))
            .cookie(Cookie::build(("c2", "v2")));
        let cookie = cookie_header(&mut req);
        let mut cookies: Vec<_> = cookie.split("; ").collect();
        cookies.sort_unstable();
        assert_eq!(cookies, ["c1=v1", "c2=v2"]);

        let mut req = Client::new()
            .get("http://localhost/")
            .header(header::COOKIE, "c0=v0")
            .cookie(Cookie::build(("c1", "v1")));
        assert_eq!(cookie_header(&mut req), "c0=v0; c1=v1");
    }

    #[crate::rt_test]
    async fn test_client_header() {
        let req = Client::builder()
            .build(
                SharedCfg::new("H").add(
                    ClientConfig::new()
                        .set_header(header::CONTENT_TYPE, "111")
                        .unwrap(),
                ),
            )
            .get("/");

        assert_eq!(
            req.request
                .head
                .headers
                .get(header::CONTENT_TYPE)
                .unwrap()
                .to_str()
                .unwrap(),
            "111"
        );
    }

    #[crate::rt_test]
    async fn test_client_header_override() {
        let req = Client::builder()
            .build(
                SharedCfg::new("H").add(
                    ClientConfig::new()
                        .set_header(header::CONTENT_TYPE, "111")
                        .unwrap(),
                ),
            )
            .get("/")
            .set_header(header::CONTENT_TYPE, "222");

        assert_eq!(
            req.request
                .head
                .headers
                .get(header::CONTENT_TYPE)
                .unwrap()
                .to_str()
                .unwrap(),
            "222"
        );
    }

    #[crate::rt_test]
    async fn client_basic_auth() {
        let req = Client::new()
            .get("/")
            .basic_auth("username", Some("password"));
        assert_eq!(
            req.request
                .head
                .headers
                .get(header::AUTHORIZATION)
                .unwrap()
                .to_str()
                .unwrap(),
            "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
        );

        let req = Client::new().get("/").basic_auth("username", None);
        assert_eq!(
            req.request
                .head
                .headers
                .get(header::AUTHORIZATION)
                .unwrap()
                .to_str()
                .unwrap(),
            "Basic dXNlcm5hbWU6"
        );
    }

    #[crate::rt_test]
    async fn client_bearer_auth() {
        let req = Client::new().get("/").bearer_auth("someS3cr3tAutht0k3n");
        assert_eq!(
            req.request
                .head
                .headers
                .get(header::AUTHORIZATION)
                .unwrap()
                .to_str()
                .unwrap(),
            "Bearer someS3cr3tAutht0k3n"
        );
    }

    #[crate::rt_test]
    async fn client_auth_replaces_header() {
        let client = Client::builder().build(
            SharedCfg::new("TEST").add(ClientConfig::new().set_bearer_auth("token").unwrap()),
        );
        let req = client
            .get("/")
            .basic_auth("username", Some("password"))
            .content_length(1)
            .content_length(2);
        let headers = &req.request.head.headers;
        let auth: Vec<_> = headers
            .get_all(header::AUTHORIZATION)
            .map(|v| v.to_str().unwrap())
            .collect();
        assert_eq!(auth, ["Basic dXNlcm5hbWU6cGFzc3dvcmQ="]);
        let len: Vec<_> = headers
            .get_all(header::CONTENT_LENGTH)
            .map(|v| v.to_str().unwrap())
            .collect();
        assert_eq!(len, ["2"]);

        let req = Client::new()
            .get("/")
            .basic_auth("a", None)
            .bearer_auth("b");
        assert_eq!(
            req.request
                .head
                .headers
                .get_all(header::AUTHORIZATION)
                .count(),
            1
        );

        let cfg = ClientConfig::new()
            .set_basic_auth("a", None)
            .unwrap()
            .set_bearer_auth("b")
            .unwrap();
        assert_eq!(cfg.headers().get_all(header::AUTHORIZATION).count(), 1);
    }

    #[crate::rt_test]
    async fn client_invalid_url() {
        let req = Client::new().get("http://local host/");
        assert!(matches!(
            req.err,
            Some(ClientError::Url(InvalidUrl::Parse(_)))
        ));
        let err = req.send().await.unwrap_err();
        assert!(matches!(
            err.into_error(),
            ClientError::Url(InvalidUrl::Parse(_))
        ));

        let req = Client::new().get("/").header("bad header", "1");
        assert!(matches!(req.err, Some(ClientError::Http(_))));
    }

    #[crate::rt_test]
    async fn client_query() {
        let req = Client::new()
            .get("/")
            .query(&[("key1", "val1"), ("key2", "val2")]);
        assert_eq!(req.get_uri().query().unwrap(), "key1=val1&key2=val2");

        let req = Client::new().get("/").query(&InvalidQuery);
        assert!(matches!(req.err, Some(ClientError::Error(_))));

        // uri without path
        let req = Client::new().get("http://localhost").query(&[("k", "v")]);
        assert!(req.err.is_none());
        assert_eq!(req.get_uri(), "http://localhost/?k=v");

        // existing query is replaced, path is preserved
        let req = Client::new()
            .get("http://localhost/p?a=1")
            .query(&[("k", "v")]);
        assert_eq!(req.get_uri(), "http://localhost/p?k=v");
    }

    #[crate::rt_test]
    async fn client_invalid_headers() {
        let bad_value = "a\nb";
        for req in [
            Client::new().get("/").header("x-test", bad_value),
            Client::new().get("/").set_header("bad header", "1"),
            Client::new().get("/").set_header("x-test", bad_value),
            Client::new().get("/").set_header_if_none("bad header", "1"),
            Client::new()
                .get("/")
                .set_header_if_none("x-test", bad_value),
            Client::new().get("/").content_type(bad_value),
        ] {
            assert!(matches!(req.err, Some(ClientError::Http(_))), "{req:?}");
            let err = req.send().await.unwrap_err();
            assert!(matches!(err.into_error(), ClientError::Http(_)));
        }

        // an existing header is not replaced and its new value is not validated
        let req = Client::new()
            .get("/")
            .header("x-test", "1")
            .set_header_if_none("x-test", bad_value);
        assert!(req.err.is_none());
        assert_eq!(req.headers().get("x-test").unwrap(), "1");
    }

    #[crate::rt_test]
    async fn client_url_validation() {
        for (url, expected) in [
            ("/path", "missing-host"),
            ("//localhost:8080/", "missing-scheme"),
            ("localhost:8080", "missing-host"),
            ("ftp://localhost/", "unknown-scheme"),
        ] {
            let err = Client::new().get(url).send().await.unwrap_err();
            let kind = match err.into_error() {
                ClientError::Url(InvalidUrl::MissingHost) => "missing-host",
                ClientError::Url(InvalidUrl::MissingScheme) => "missing-scheme",
                ClientError::Url(InvalidUrl::UnknownScheme) => "unknown-scheme",
                err => panic!("{url}: {err:?}"),
            };
            assert_eq!(kind, expected, "{url}");
        }
    }

    #[crate::rt_test]
    async fn test_debug_redacts_authorization() {
        let req = Client::new()
            .get("http://localhost/")
            .basic_auth("user", Some("secret"))
            .address("127.0.0.1:1".parse().unwrap());
        assert_eq!(req.request.addr, Some("127.0.0.1:1".parse().unwrap()));
        let repr = format!("{req:?}");
        assert!(repr.contains("\"authorization\": <REDACTED>"), "{repr}");
        assert!(!repr.contains("Basic"), "{repr}");
    }
}