Skip to main content

ntex/client/
request.rs

1use std::{error::Error as StdError, fmt, net, rc::Rc};
2
3use base64::{Engine, engine::general_purpose::STANDARD as base64};
4#[cfg(feature = "cookie")]
5use coo_kie::{Cookie, CookieJar};
6use serde::Serialize;
7use urly::Url;
8
9use crate::error::Error;
10use crate::http::error::HttpError;
11use crate::http::header::{self, HeaderMap, HeaderName, HeaderValue};
12use crate::http::{ConnectionType, Method, Version, body::Body};
13use crate::{Cfg, PipelineBinding, time::Millis, util::Bytes, util::Stream};
14
15use super::error::{ClientError, InvalidUrl};
16use super::{ClientConfig, ClientResponse, ServiceRequest, ServiceResponse};
17
18/// An HTTP client request builder.
19///
20/// Builder methods configure the request and the `send*` methods consume it,
21/// send the request, and return a [`ClientResponse`].
22///
23/// ```rust
24/// use ntex::client::Client;
25///
26/// #[ntex::main]
27/// async fn main() {
28///    let response = Client::new()
29///         .get("http://www.rust-lang.org") // <- Create request builder
30///         .header("User-Agent", "ntex::web")
31///         .send()                          // <- Send http request
32///         .await;
33///
34///    response.and_then(|response| {   // <- server http response
35///         println!("Response: {:?}", response);
36///         Ok(())
37///    });
38/// }
39/// ```
40pub struct ClientRequest {
41    request: ServiceRequest,
42    svc: PipelineBinding<ServiceRequest, ServiceResponse, Error<ClientError>>,
43    err: Option<ClientError>,
44    cfg: Cfg<ClientConfig>,
45    #[cfg(feature = "cookie")]
46    cookies: Option<CookieJar>,
47}
48
49impl ClientRequest {
50    /// Create new client request builder.
51    pub(super) fn new<U>(
52        method: Method,
53        uri: U,
54        cfg: Cfg<ClientConfig>,
55        svc: PipelineBinding<ServiceRequest, ServiceResponse, Error<ClientError>>,
56    ) -> Self
57    where
58        Url: TryFrom<U>,
59        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
60    {
61        ClientRequest {
62            svc,
63            cfg,
64            request: ServiceRequest::new(),
65            err: None,
66            #[cfg(feature = "cookie")]
67            cookies: None,
68        }
69        .method(method)
70        .uri(uri)
71    }
72
73    /// Sets the request URI.
74    ///
75    /// URI conversion errors are stored and returned by the next `send*` call.
76    #[inline]
77    #[must_use]
78    pub fn uri<U>(mut self, uri: U) -> Self
79    where
80        Url: TryFrom<U>,
81        <Url as TryFrom<U>>::Error: Into<InvalidUrl>,
82    {
83        match Url::try_from(uri) {
84            Ok(uri) => self.request.head.uri = uri,
85            Err(e) => self.err = Some(e.into().into()),
86        }
87        self
88    }
89
90    /// Returns the request URI.
91    pub fn get_uri(&self) -> &Url {
92        &self.request.head.uri
93    }
94
95    #[must_use]
96    /// Sets the server socket address.
97    ///
98    /// This address is used instead of resolving the URI host name. Pooled
99    /// connections are reused only by requests with the same URI authority
100    /// and the same address, so requests to one host with different
101    /// addresses, or without one, never share a connection.
102    pub fn address(mut self, addr: net::SocketAddr) -> Self {
103        self.request.addr = Some(addr);
104        self
105    }
106
107    /// Sets the request method.
108    #[inline]
109    #[must_use]
110    pub fn method(mut self, method: Method) -> Self {
111        self.request.head.method = method;
112        self
113    }
114
115    #[inline]
116    #[must_use]
117    /// Returns the request method.
118    pub fn get_method(&self) -> &Method {
119        &self.request.head.method
120    }
121
122    /// Sets the request HTTP version.
123    ///
124    /// The version does not select the transport protocol. On an HTTP/1
125    /// connection, `HTTP/1.0` is sent as requested and any other version is
126    /// sent as `HTTP/1.1`. An HTTP/2 connection always uses `HTTP/2`.
127    ///
128    /// An `HTTP/1.0` request closes the connection after the response unless
129    /// keep-alive is requested, and a streaming body needs a `Content-Length`
130    /// header because chunked coding is not available.
131    #[inline]
132    #[must_use]
133    pub fn version(mut self, version: Version) -> Self {
134        self.request.head.version = version;
135        self
136    }
137
138    #[inline]
139    /// Returns the request HTTP version.
140    pub fn get_version(&self) -> &Version {
141        &self.request.head.version
142    }
143
144    #[inline]
145    /// Returns the request headers.
146    pub fn headers(&self) -> &HeaderMap {
147        &self.request.head.headers
148    }
149
150    #[inline]
151    /// Returns mutable access to the request headers.
152    pub fn headers_mut(&mut self) -> &mut HeaderMap {
153        &mut self.request.head.headers
154    }
155
156    #[must_use]
157    /// Append a header.
158    ///
159    /// The header is appended to any existing values with the same name. Use
160    /// [`set_header`](Self::set_header) to replace existing values.
161    ///
162    /// Header conversion errors are stored and returned by the next `send*`
163    /// call.
164    ///
165    /// ```rust
166    /// use ntex::{http, client::Client};
167    ///
168    /// #[ntex::main]
169    /// async fn main() {
170    ///     let req = Client::new()
171    ///         .get("http://www.rust-lang.org")
172    ///         .header("X-TEST", "value")
173    ///         .header(http::header::CONTENT_TYPE, "application/json");
174    /// }
175    /// ```
176    pub fn header<K, V>(mut self, key: K, value: V) -> Self
177    where
178        HeaderName: TryFrom<K>,
179        HeaderValue: TryFrom<V>,
180        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
181        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
182    {
183        match HeaderName::try_from(key) {
184            Ok(key) => match HeaderValue::try_from(value) {
185                Ok(value) => self.request.head.headers.append(key, value),
186                Err(e) => self.err = Some(ClientError::Http(e.into())),
187            },
188            Err(e) => self.err = Some(ClientError::Http(e.into())),
189        }
190        self
191    }
192
193    #[must_use]
194    /// Inserts a header, replacing existing values with the same name.
195    ///
196    /// Header conversion errors are stored and returned by the next `send*`
197    /// call.
198    pub fn set_header<K, V>(mut self, key: K, value: V) -> Self
199    where
200        HeaderName: TryFrom<K>,
201        HeaderValue: TryFrom<V>,
202        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
203        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
204    {
205        match HeaderName::try_from(key) {
206            Ok(key) => match HeaderValue::try_from(value) {
207                Ok(value) => self.request.head.headers.insert(key, value),
208                Err(e) => self.err = Some(ClientError::Http(e.into())),
209            },
210            Err(e) => self.err = Some(ClientError::Http(e.into())),
211        }
212        self
213    }
214
215    #[must_use]
216    /// Inserts a header if the request does not already contain one with the
217    /// same name.
218    ///
219    /// Header conversion errors are stored and returned by the next `send*`
220    /// call.
221    pub fn set_header_if_none<K, V>(mut self, key: K, value: V) -> Self
222    where
223        HeaderName: TryFrom<K>,
224        HeaderValue: TryFrom<V>,
225        <HeaderName as TryFrom<K>>::Error: Into<HttpError>,
226        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
227    {
228        match HeaderName::try_from(key) {
229            Ok(key) => {
230                if !self.request.head.headers.contains_key(&key) {
231                    match HeaderValue::try_from(value) {
232                        Ok(value) => self.request.head.headers.insert(key, value),
233                        Err(e) => self.err = Some(ClientError::Http(e.into())),
234                    }
235                }
236            }
237            Err(e) => self.err = Some(ClientError::Http(e.into())),
238        }
239        self
240    }
241
242    #[inline]
243    #[must_use]
244    /// Sets the request connection type.
245    ///
246    /// See [`RequestHead::set_connection_type()`](crate::http::RequestHead::set_connection_type)
247    /// for how repeated calls are resolved. On HTTP/1 connections, the `close`,
248    /// `keep-alive` and `upgrade` options of a `Connection` header set with
249    /// [`header`](Self::header) are applied the same way. HTTP/2 connections
250    /// ignore the connection type.
251    pub fn set_connection_type(mut self, ctype: ConnectionType) -> Self {
252        self.request.head.set_connection_type(ctype);
253        self
254    }
255
256    /// Prevents an HTTP/1 connection from returning to the connection pool.
257    ///
258    /// This setting affects only HTTP/1 connections.
259    #[inline]
260    #[must_use]
261    pub fn force_close(mut self) -> Self {
262        self.request.head.set_connection_type(ConnectionType::Close);
263        self
264    }
265
266    /// Sets the request content type.
267    ///
268    /// Header conversion errors are stored and returned by the next `send*`
269    /// call.
270    #[inline]
271    #[must_use]
272    pub fn content_type<V>(mut self, value: V) -> Self
273    where
274        HeaderValue: TryFrom<V>,
275        <HeaderValue as TryFrom<V>>::Error: Into<HttpError>,
276    {
277        match HeaderValue::try_from(value) {
278            Ok(value) => self
279                .request
280                .head
281                .headers
282                .insert(header::CONTENT_TYPE, value),
283            Err(e) => self.err = Some(ClientError::Http(e.into())),
284        }
285        self
286    }
287
288    /// Sets the request content length.
289    ///
290    /// A streaming body (see [`send_stream`](Self::send_stream)) is sent with
291    /// this length instead of chunked coding on HTTP/1 connections. Sending
292    /// fails if the stream ends early or produces more data. A body with a known
293    /// size is sent with its actual size and this value is ignored.
294    #[inline]
295    #[must_use]
296    pub fn content_length(self, len: u64) -> Self {
297        self.set_header(header::CONTENT_LENGTH, len)
298    }
299
300    #[must_use]
301    /// Sets the HTTP basic authentication header.
302    ///
303    /// Replaces any existing `Authorization` header, including a client default.
304    pub fn basic_auth<U>(self, username: U, password: Option<&str>) -> Self
305    where
306        U: fmt::Display,
307    {
308        let auth = match password {
309            Some(password) => format!("{username}:{password}"),
310            None => format!("{username}:"),
311        };
312        self.set_header(
313            header::AUTHORIZATION,
314            format!("Basic {}", base64.encode(auth)),
315        )
316    }
317
318    #[must_use]
319    /// Sets the HTTP bearer authentication header.
320    ///
321    /// Replaces any existing `Authorization` header, including a client default.
322    pub fn bearer_auth<T>(self, token: T) -> Self
323    where
324        T: fmt::Display,
325    {
326        self.set_header(header::AUTHORIZATION, format!("Bearer {token}"))
327    }
328
329    #[must_use]
330    #[cfg(feature = "cookie")]
331    /// Set a cookie.
332    ///
333    /// When the request is sent, all cookies and every raw `Cookie` header
334    /// value are merged into a single `Cookie` header.
335    ///
336    /// ```rust
337    /// use coo_kie as cookie;
338    /// use ntex::client::Client;
339    ///
340    /// #[ntex::main]
341    /// async fn main() {
342    ///     let resp = Client::new().get("https://www.rust-lang.org")
343    ///         .cookie(
344    ///             cookie::Cookie::build(("name", "value"))
345    ///                 .domain("www.rust-lang.org")
346    ///                 .path("/")
347    ///                 .secure(true)
348    ///                 .http_only(true)
349    ///          )
350    ///          .send()
351    ///          .await;
352    ///
353    ///     println!("Response: {:?}", resp);
354    /// }
355    /// ```
356    pub fn cookie<C>(mut self, cookie: C) -> Self
357    where
358        C: Into<Cookie<'static>>,
359    {
360        if let Some(cookies) = &mut self.cookies {
361            cookies.add(cookie.into());
362        } else {
363            let mut jar = CookieJar::new();
364            jar.add(cookie.into());
365            self.cookies = Some(jar);
366        }
367        self
368    }
369
370    #[must_use]
371    /// Disables automatic decompression of the response body.
372    pub fn no_decompress(mut self) -> Self {
373        self.request.response_decompress = false;
374        self
375    }
376
377    #[must_use]
378    /// Sets the response-header timeout for this request.
379    ///
380    /// This overrides the client-wide timeout. The timeout covers receiving the
381    /// response head after the request has been sent. It does not cover waiting
382    /// for a pooled connection, connecting, sending the request body, or
383    /// reading the response body; use
384    /// [`MessageBody::timeout`](super::MessageBody::timeout) or
385    /// [`JsonBody::timeout`](super::JsonBody::timeout) for the body.
386    /// A zero duration disables only this timeout for this request.
387    ///
388    /// The client-wide default is 5 seconds.
389    pub fn timeout<T: Into<Millis>>(mut self, timeout: T) -> Self {
390        self.request.timeout = Some(timeout.into());
391        self
392    }
393
394    #[must_use]
395    /// Applies `f` to this builder when `value` is `true`.
396    pub fn if_true<F>(self, value: bool, f: F) -> Self
397    where
398        F: FnOnce(ClientRequest) -> ClientRequest,
399    {
400        if value { f(self) } else { self }
401    }
402
403    #[must_use]
404    /// Applies `f` and the contained value to this builder when `value` is
405    /// [`Some`].
406    pub fn if_some<T, F>(self, value: Option<T>, f: F) -> Self
407    where
408        F: FnOnce(T, ClientRequest) -> ClientRequest,
409    {
410        if let Some(val) = value { f(val, self) } else { self }
411    }
412
413    /// Serializes `query` and replaces the query component of the request URI.
414    ///
415    /// Serialization errors, and a resulting URI longer than 65535 bytes, are
416    /// stored and returned by the next `send*` call.
417    #[must_use]
418    pub fn query<T: Serialize>(mut self, query: &T) -> Self {
419        let query = match serde_urlencoded::to_string(query) {
420            Ok(query) => query,
421            Err(err) => {
422                self.err = Some(ClientError::Error(Rc::new(err)));
423                return self;
424            }
425        };
426
427        match urly::Builder::from(self.request.head.uri.clone())
428            .query(&query)
429            .build()
430        {
431            Ok(uri) => self.request.head.uri = uri,
432            Err(e) => self.err = Some(InvalidUrl::Parse(e).into()),
433        }
434        self
435    }
436}
437
438impl ClientRequest {
439    /// Sends the request with `body`.
440    pub fn send_body<B>(
441        mut self,
442        body: B,
443    ) -> impl Future<Output = Result<ClientResponse, Error<ClientError>>>
444    where
445        B: Into<Body>,
446    {
447        let res = self
448            .prep_for_sending()
449            .map(|()| *self.request.body() = body.into());
450        self.dispatch(res)
451    }
452
453    /// Serializes `value` as JSON and sends the request.
454    pub fn send_json<T: Serialize>(
455        mut self,
456        value: &T,
457    ) -> impl Future<Output = Result<ClientResponse, Error<ClientError>>> {
458        let res = self
459            .prep_for_sending()
460            .and_then(|()| self.request.set_json(value).map_err(Into::into));
461        self.dispatch(res)
462    }
463
464    /// Serializes `value` as a URL-encoded form and sends the request.
465    pub fn send_form<T: Serialize>(
466        mut self,
467        value: &T,
468    ) -> impl Future<Output = Result<ClientResponse, Error<ClientError>>> {
469        let res = self
470            .prep_for_sending()
471            .and_then(|()| self.request.set_form(value).map_err(Into::into));
472        self.dispatch(res)
473    }
474
475    /// Sends the request with a streaming body.
476    pub fn send_stream<T, E>(
477        mut self,
478        stream: T,
479    ) -> impl Future<Output = Result<ClientResponse, Error<ClientError>>>
480    where
481        T: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
482        E: StdError + 'static,
483    {
484        let res = self
485            .prep_for_sending()
486            .map(|()| self.request.set_stream(stream));
487        self.dispatch(res)
488    }
489
490    /// Sends the request with an empty body.
491    pub fn send(mut self) -> impl Future<Output = Result<ClientResponse, Error<ClientError>>> {
492        let res = self.prep_for_sending();
493        self.dispatch(res)
494    }
495
496    // The request is prepared when `send*()` is called, only the service call
497    // is stored in the returned future
498    fn dispatch(
499        self,
500        res: Result<(), Error<ClientError>>,
501    ) -> impl Future<Output = Result<ClientResponse, Error<ClientError>>> {
502        let call = res.map(|()| self.svc.call_static(self.request));
503        async move { call?.await.map(Into::into) }
504    }
505
506    fn prep_for_sending(&mut self) -> Result<(), Error<ClientError>> {
507        self.prep_for_sending_inner()
508            .map_err(|e| e.with_service(self.cfg.service()))
509    }
510
511    fn prep_for_sending_inner(&mut self) -> Result<(), Error<ClientError>> {
512        if let Some(e) = self.err.take() {
513            return Err(e.into());
514        }
515
516        // validate uri
517        let uri = &self.request.head.uri;
518        if uri.host().is_none() {
519            return Err(ClientError::from(InvalidUrl::MissingHost).into());
520        }
521        match uri.scheme_str() {
522            Some("http" | "ws" | "https" | "wss") => (),
523            Some(_) => return Err(ClientError::from(InvalidUrl::UnknownScheme).into()),
524            None => return Err(ClientError::from(InvalidUrl::MissingScheme).into()),
525        }
526
527        // set cookies, merged with all existing `Cookie` headers into a single header
528        #[cfg(feature = "cookie")]
529        {
530            if let Some(ref jar) = self.cookies {
531                let headers = &mut self.request.head.headers;
532                let mut cookie = Vec::new();
533                for v in headers.get_all(header::COOKIE) {
534                    if !v.is_empty() {
535                        if !cookie.is_empty() {
536                            cookie.extend_from_slice(b"; ");
537                        }
538                        cookie.extend_from_slice(v.as_bytes());
539                    }
540                }
541                for c in jar.iter() {
542                    crate::http::helpers::push_cookie(&mut cookie, c.name(), c.value());
543                }
544                if let Ok(val) = HeaderValue::from_bytes(&cookie) {
545                    headers.insert(header::COOKIE, val);
546                }
547            }
548        }
549
550        #[cfg(feature = "compress")]
551        if self.request.response_decompress
552            && !self
553                .request
554                .head
555                .headers
556                .contains_key(&header::ACCEPT_ENCODING)
557        {
558            const COMPRESSION: HeaderValue = HeaderValue::from_static("gzip, deflate, zstd");
559            self.request
560                .head
561                .headers
562                .insert(header::ACCEPT_ENCODING, COMPRESSION);
563        }
564
565        Ok(())
566    }
567}
568
569impl fmt::Debug for ClientRequest {
570    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571        writeln!(
572            f,
573            "\nClientRequest {:?} {}:{}",
574            self.request.head.version, self.request.head.method, self.request.head.uri
575        )?;
576        writeln!(f, "  headers:")?;
577        for (key, val) in &self.request.head.headers {
578            if key == header::AUTHORIZATION {
579                writeln!(f, "    {key:?}: <REDACTED>")?;
580            } else {
581                writeln!(f, "    {key:?}: {val:?}")?;
582            }
583        }
584        Ok(())
585    }
586}
587
588#[cfg(test)]
589mod tests {
590    use super::*;
591    use crate::{SharedCfg, client::Client};
592
593    struct InvalidQuery;
594
595    impl Serialize for InvalidQuery {
596        fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error>
597        where
598            S: serde::Serializer,
599        {
600            Err(serde::ser::Error::custom("invalid query"))
601        }
602    }
603
604    /// STATEMENT: Request debug output identifies the request and its ordinary headers.
605    ///
606    /// HOW:
607    /// - Format a request carrying a custom header and check both the type name and header name appear.
608    #[crate::rt_test]
609    async fn test_debug() {
610        let request = Client::new().get("/").header("x-test", "111");
611        let repr = format!("{request:?}");
612        assert!(repr.contains("ClientRequest"));
613        assert!(repr.contains("x-test"));
614    }
615
616    /// STATEMENT: Request builders apply method, version, headers, and conditional transformations.
617    ///
618    /// HOW:
619    /// - Build an HTTP/2 PUT with true/false and present/absent conditions and inspect which headers were added.
620    /// - Check method/version accessors and exercise mutable headers and body sending.
621    #[crate::rt_test]
622    async fn test_basics() {
623        let mut req = Client::new()
624            .put("/")
625            .version(Version::HTTP_2)
626            .header(header::DATE, "data")
627            .content_type("plain/text")
628            .if_true(true, |req| req.header(header::SERVER, "awc"))
629            .if_true(false, |req| req.header(header::EXPECT, "awc"))
630            .if_some(Some("server"), |val, req| {
631                req.header(header::USER_AGENT, val)
632            })
633            .if_some(Option::<&str>::None, |_, req| {
634                req.header(header::ALLOW, "1")
635            })
636            .content_length(100);
637        assert!(req.headers().contains_key(header::CONTENT_TYPE));
638        assert!(req.headers().contains_key(header::DATE));
639        assert!(req.headers().contains_key(header::SERVER));
640        assert!(req.headers().contains_key(header::USER_AGENT));
641        assert!(!req.headers().contains_key(header::ALLOW));
642        assert!(!req.headers().contains_key(header::EXPECT));
643        assert_eq!(req.request.head.version, Version::HTTP_2);
644        assert_eq!(req.get_version(), &Version::HTTP_2);
645        assert_eq!(req.get_method(), Method::PUT);
646        let _ = req.headers_mut();
647        let _ = req.send_body("").await;
648    }
649
650    /// STATEMENT: Request cookies combine with one another and with every preexisting `Cookie` header into a single header.
651    ///
652    /// HOW:
653    /// - Prepare requests with two builder cookies and with a raw header plus one cookie, then compare header entries.
654    /// - Add three raw `Cookie` headers, one empty, plus a builder cookie, and check that a single header joins all non-empty values in order.
655    #[cfg(feature = "cookie")]
656    #[crate::rt_test]
657    async fn cookies_extend_cookie_header() {
658        use coo_kie::Cookie;
659
660        fn cookie_header(req: &mut ClientRequest) -> String {
661            req.prep_for_sending_inner().unwrap();
662            let val = req.request.head.headers.get(header::COOKIE).unwrap();
663            val.to_str().unwrap().to_string()
664        }
665
666        let mut req = Client::new()
667            .get("http://localhost/")
668            .cookie(Cookie::build(("c1", "v1")))
669            .cookie(Cookie::build(("c2", "v2")));
670        let cookie = cookie_header(&mut req);
671        let mut cookies: Vec<_> = cookie.split("; ").collect();
672        cookies.sort_unstable();
673        assert_eq!(cookies, ["c1=v1", "c2=v2"]);
674
675        let mut req = Client::new()
676            .get("http://localhost/")
677            .header(header::COOKIE, "c0=v0")
678            .cookie(Cookie::build(("c1", "v1")));
679        assert_eq!(cookie_header(&mut req), "c0=v0; c1=v1");
680
681        let mut req = Client::new()
682            .get("http://localhost/")
683            .header(header::COOKIE, "a=1")
684            .header(header::COOKIE, "")
685            .header(header::COOKIE, "b=2; c=3")
686            .cookie(Cookie::build(("c1", "v1")));
687        assert_eq!(cookie_header(&mut req), "a=1; b=2; c=3; c1=v1");
688        assert_eq!(req.headers().get_all(header::COOKIE).count(), 1);
689    }
690
691    /// STATEMENT: Every value of a multi-value client default header is copied into new requests.
692    ///
693    /// HOW:
694    /// - Configure two default `Accept` values and check that a new request carries both, in order.
695    /// - Replace them with `set_header` and check that only the request value remains.
696    #[crate::rt_test]
697    async fn test_client_multi_value_default_header() {
698        let client = Client::builder().build(
699            SharedCfg::new("H").add(
700                ClientConfig::new()
701                    .set_header(header::ACCEPT, "text/html")
702                    .unwrap()
703                    .set_header(header::ACCEPT, "text/plain")
704                    .unwrap(),
705            ),
706        );
707        let req = client.get("/");
708        let accept: Vec<_> = req.headers().get_all(header::ACCEPT).collect();
709        assert_eq!(accept, ["text/html", "text/plain"]);
710
711        let req = client.get("/").set_header(header::ACCEPT, "*/*");
712        let accept: Vec<_> = req.headers().get_all(header::ACCEPT).collect();
713        assert_eq!(accept, ["*/*"]);
714    }
715
716    /// STATEMENT: Client-wide default headers are copied into new requests.
717    ///
718    /// HOW:
719    /// - Configure a default content type, construct a request, and compare its stored header.
720    #[crate::rt_test]
721    async fn test_client_header() {
722        let req = Client::builder()
723            .build(
724                SharedCfg::new("H").add(
725                    ClientConfig::new()
726                        .set_header(header::CONTENT_TYPE, "111")
727                        .unwrap(),
728                ),
729            )
730            .get("/");
731
732        assert_eq!(
733            req.request
734                .head
735                .headers
736                .get(header::CONTENT_TYPE)
737                .unwrap()
738                .to_str()
739                .unwrap(),
740            "111"
741        );
742    }
743
744    /// STATEMENT: Request-specific header replacement overrides a client default.
745    ///
746    /// HOW:
747    /// - Configure a default content type, replace it on a request, and check the new value.
748    #[crate::rt_test]
749    async fn test_client_header_override() {
750        let req = Client::builder()
751            .build(
752                SharedCfg::new("H").add(
753                    ClientConfig::new()
754                        .set_header(header::CONTENT_TYPE, "111")
755                        .unwrap(),
756                ),
757            )
758            .get("/")
759            .set_header(header::CONTENT_TYPE, "222");
760
761        assert_eq!(
762            req.request
763                .head
764                .headers
765                .get(header::CONTENT_TYPE)
766                .unwrap()
767                .to_str()
768                .unwrap(),
769            "222"
770        );
771    }
772
773    /// STATEMENT: Request Basic authentication supports both supplied and omitted passwords.
774    ///
775    /// HOW:
776    /// - Build both credential forms and compare their complete encoded authorization values.
777    #[crate::rt_test]
778    async fn client_basic_auth() {
779        let req = Client::new()
780            .get("/")
781            .basic_auth("username", Some("password"));
782        assert_eq!(
783            req.request
784                .head
785                .headers
786                .get(header::AUTHORIZATION)
787                .unwrap()
788                .to_str()
789                .unwrap(),
790            "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
791        );
792
793        let req = Client::new().get("/").basic_auth("username", None);
794        assert_eq!(
795            req.request
796                .head
797                .headers
798                .get(header::AUTHORIZATION)
799                .unwrap()
800                .to_str()
801                .unwrap(),
802            "Basic dXNlcm5hbWU6"
803        );
804    }
805
806    /// STATEMENT: Request bearer authentication constructs the expected authorization value.
807    ///
808    /// HOW:
809    /// - Set a bearer token on a request and compare the resulting header.
810    #[crate::rt_test]
811    async fn client_bearer_auth() {
812        let req = Client::new().get("/").bearer_auth("someS3cr3tAutht0k3n");
813        assert_eq!(
814            req.request
815                .head
816                .headers
817                .get(header::AUTHORIZATION)
818                .unwrap()
819                .to_str()
820                .unwrap(),
821            "Bearer someS3cr3tAutht0k3n"
822        );
823    }
824
825    /// STATEMENT: Authentication and content-length setters replace prior values rather than append duplicates.
826    ///
827    /// HOW:
828    /// - Override client authentication, repeat length setters, and switch authentication schemes.
829    /// - Check resulting values and single-header counts for both requests and client configuration.
830    #[crate::rt_test]
831    async fn client_auth_replaces_header() {
832        let client = Client::builder().build(
833            SharedCfg::new("TEST").add(ClientConfig::new().set_bearer_auth("token").unwrap()),
834        );
835        let req = client
836            .get("/")
837            .basic_auth("username", Some("password"))
838            .content_length(1)
839            .content_length(2);
840        let headers = &req.request.head.headers;
841        let auth: Vec<_> = headers
842            .get_all(header::AUTHORIZATION)
843            .map(|v| v.to_str().unwrap())
844            .collect();
845        assert_eq!(auth, ["Basic dXNlcm5hbWU6cGFzc3dvcmQ="]);
846        let len: Vec<_> = headers
847            .get_all(header::CONTENT_LENGTH)
848            .map(|v| v.to_str().unwrap())
849            .collect();
850        assert_eq!(len, ["2"]);
851
852        let req = Client::new()
853            .get("/")
854            .basic_auth("a", None)
855            .bearer_auth("b");
856        assert_eq!(
857            req.request
858                .head
859                .headers
860                .get_all(header::AUTHORIZATION)
861                .count(),
862            1
863        );
864
865        let cfg = ClientConfig::new()
866            .set_basic_auth("a", None)
867            .unwrap()
868            .set_bearer_auth("b")
869            .unwrap();
870        assert_eq!(cfg.headers().get_all(header::AUTHORIZATION).count(), 1);
871    }
872
873    /// STATEMENT: Request construction errors are retained and returned when sending.
874    ///
875    /// HOW:
876    /// - Build a malformed URL, inspect its stored parse error, and verify sending returns that category.
877    /// - Build an invalid header and check it is stored as an HTTP error.
878    #[crate::rt_test]
879    async fn client_invalid_url() {
880        let req = Client::new().get("http://local host/");
881        assert!(matches!(
882            req.err,
883            Some(ClientError::Url(InvalidUrl::Parse(_)))
884        ));
885        let err = req.send().await.unwrap_err();
886        assert!(matches!(
887            err.into_error(),
888            ClientError::Url(InvalidUrl::Parse(_))
889        ));
890
891        let req = Client::new().get("/").header("bad header", "1");
892        assert!(matches!(req.err, Some(ClientError::Http(_))));
893    }
894
895    /// STATEMENT: Query serialization replaces an existing query while preserving the URL path and surfacing errors.
896    ///
897    /// HOW:
898    /// - Serialize pairs into relative, pathless, and already-queried URLs and compare the results.
899    /// - Use a failing serializer and check the request stores its error.
900    #[crate::rt_test]
901    async fn client_query() {
902        let req = Client::new()
903            .get("/")
904            .query(&[("key1", "val1"), ("key2", "val2")]);
905        assert_eq!(req.get_uri().query().unwrap(), "key1=val1&key2=val2");
906
907        let req = Client::new().get("/").query(&InvalidQuery);
908        assert!(matches!(req.err, Some(ClientError::Error(_))));
909
910        // uri without path
911        let req = Client::new().get("http://localhost").query(&[("k", "v")]);
912        assert!(req.err.is_none());
913        assert_eq!(req.get_uri(), "http://localhost/?k=v");
914
915        // existing query is replaced, path is preserved
916        let req = Client::new()
917            .get("http://localhost/p?a=1")
918            .query(&[("k", "v")]);
919        assert_eq!(req.get_uri(), "http://localhost/p?k=v");
920    }
921
922    /// STATEMENT: A query that makes the URI too long is returned as an error by `send` instead of panicking.
923    ///
924    /// HOW:
925    /// - Set a query value that makes `http://localhost/p?k=...` exactly 65535 bytes and check it is applied.
926    /// - Set a value one byte longer and check the URI is unchanged and the stored error is `TooLong`.
927    /// - Send the oversized request and check it fails with the same URL parse error.
928    #[crate::rt_test]
929    async fn client_query_too_long() {
930        let prefix = "http://localhost/p?k=".len();
931        let value = "a".repeat(65_535 - prefix);
932        let req = Client::new()
933            .get("http://localhost/p?a=1")
934            .query(&[("k", &value)]);
935        assert!(req.err.is_none());
936        assert_eq!(req.get_uri().as_str().len(), 65_535);
937
938        let value = "a".repeat(65_536 - prefix);
939        let req = Client::new()
940            .get("http://localhost/p?a=1")
941            .query(&[("k", &value)]);
942        assert_eq!(req.get_uri(), "http://localhost/p?a=1");
943        assert!(matches!(
944            &req.err,
945            Some(ClientError::Url(InvalidUrl::Parse(e))) if e.kind() == urly::ErrorKind::TooLong
946        ));
947        let err = req.send().await.unwrap_err();
948        assert!(matches!(
949            err.into_error(),
950            ClientError::Url(InvalidUrl::Parse(e)) if e.kind() == urly::ErrorKind::TooLong
951        ));
952    }
953
954    /// STATEMENT: Header builders reject invalid input except when an existing conditional header makes replacement unnecessary.
955    ///
956    /// HOW:
957    /// - Try malformed names and values across header setters and verify stored and send-time HTTP errors.
958    /// - Attempt conditional replacement of an existing header with an invalid value and check the original survives.
959    #[crate::rt_test]
960    async fn client_invalid_headers() {
961        let bad_value = "a\nb";
962        for req in [
963            Client::new().get("/").header("x-test", bad_value),
964            Client::new().get("/").set_header("bad header", "1"),
965            Client::new().get("/").set_header("x-test", bad_value),
966            Client::new().get("/").set_header_if_none("bad header", "1"),
967            Client::new()
968                .get("/")
969                .set_header_if_none("x-test", bad_value),
970            Client::new().get("/").content_type(bad_value),
971        ] {
972            assert!(matches!(req.err, Some(ClientError::Http(_))), "{req:?}");
973            let err = req.send().await.unwrap_err();
974            assert!(matches!(err.into_error(), ClientError::Http(_)));
975        }
976
977        // an existing header is not replaced and its new value is not validated
978        let req = Client::new()
979            .get("/")
980            .header("x-test", "1")
981            .set_header_if_none("x-test", bad_value);
982        assert!(req.err.is_none());
983        assert_eq!(req.headers().get("x-test").unwrap(), "1");
984    }
985
986    /// STATEMENT: Sending rejects URLs with missing host, missing scheme, or unsupported scheme distinctly.
987    ///
988    /// HOW:
989    /// - Send relative, scheme-relative, authority-like, and FTP URLs and compare their URL error classifications.
990    #[crate::rt_test]
991    async fn client_url_validation() {
992        for (url, expected) in [
993            ("/path", "missing-host"),
994            ("//localhost:8080/", "missing-scheme"),
995            ("localhost:8080", "missing-host"),
996            ("ftp://localhost/", "unknown-scheme"),
997        ] {
998            let err = Client::new().get(url).send().await.unwrap_err();
999            let kind = match err.into_error() {
1000                ClientError::Url(InvalidUrl::MissingHost) => "missing-host",
1001                ClientError::Url(InvalidUrl::MissingScheme) => "missing-scheme",
1002                ClientError::Url(InvalidUrl::UnknownScheme) => "unknown-scheme",
1003                err => panic!("{url}: {err:?}"),
1004            };
1005            assert_eq!(kind, expected, "{url}");
1006        }
1007    }
1008
1009    /// STATEMENT: Request debug output redacts authorization while retaining an explicit connection address.
1010    ///
1011    /// HOW:
1012    /// - Build an authenticated request with an address override and check the address and redacted debug representation.
1013    #[crate::rt_test]
1014    async fn test_debug_redacts_authorization() {
1015        let req = Client::new()
1016            .get("http://localhost/")
1017            .basic_auth("user", Some("secret"))
1018            .address("127.0.0.1:1".parse().unwrap());
1019        assert_eq!(req.request.addr, Some("127.0.0.1:1".parse().unwrap()));
1020        let repr = format!("{req:?}");
1021        assert!(repr.contains("\"authorization\": <REDACTED>"), "{repr}");
1022        assert!(!repr.contains("Basic"), "{repr}");
1023    }
1024}