1use std::net::SocketAddr;
4use std::sync::Arc;
5
6use bytes::Bytes;
7use http::Version;
8
9use crate::body::RequestBody;
10use crate::client::Client;
11use crate::error::Result;
12use crate::headers::Headers;
13use crate::redirect::RedirectPolicy;
14use crate::response::Response;
15use crate::retry::RetryPolicy;
16use crate::timeout::Timeout;
17use crate::trace::TraceObserver;
18
19use crate::auth::AuthScheme;
20#[cfg(feature = "proxy")]
21use crate::proxy::ProxyConfig;
22
23#[derive(Clone, PartialEq, Eq)]
31pub struct ResolvedTarget {
32 addresses: Arc<[SocketAddr]>,
33}
34
35impl ResolvedTarget {
36 pub fn new<I>(addresses: I) -> crate::Result<Self>
42 where
43 I: IntoIterator<Item = SocketAddr>,
44 {
45 let addresses: Vec<_> = addresses.into_iter().collect();
46 if addresses.is_empty() {
47 return Err(crate::Error::InvalidResolvedTarget(
48 "resolved destination set must not be empty".into(),
49 ));
50 }
51 Ok(Self {
52 addresses: addresses.into(),
53 })
54 }
55
56 #[must_use]
58 pub fn addresses(&self) -> &[SocketAddr] {
59 &self.addresses
60 }
61}
62
63impl std::fmt::Debug for ResolvedTarget {
64 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65 f.debug_struct("ResolvedTarget")
66 .field("address_count", &self.addresses.len())
67 .finish()
68 }
69}
70
71#[derive(Default, Clone)]
80pub struct TransportHints {
81 pub target: Option<Bytes>,
87 pub sni_hostname: Option<String>,
92 pub resolved_target: Option<ResolvedTarget>,
99 pub trace: Option<Arc<dyn TraceObserver>>,
106}
107
108impl std::fmt::Debug for TransportHints {
109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110 f.debug_struct("TransportHints")
111 .field("target", &self.target)
112 .field("sni_hostname", &self.sni_hostname)
113 .field("resolved_target", &self.resolved_target)
114 .field("trace", &self.trace.as_ref().map(|_| "..."))
115 .finish()
116 }
117}
118
119#[derive(Debug, Clone, Default)]
124#[allow(
125 clippy::large_enum_variant,
126 reason = "ProxyConfig is transient and cloning it is cheap; boxing adds unnecessary allocation"
127)]
128pub enum ProxyOverride {
129 #[default]
131 Inherit,
132 Direct,
134 #[cfg(feature = "proxy")]
136 Override(ProxyConfig),
137}
138
139pub(crate) struct RequestParts {
146 pub(crate) method: http::Method,
147 pub(crate) url: url::Url,
148 pub(crate) headers: Headers,
149 pub(crate) body: RequestBody,
150 pub(crate) version: Version,
151 pub(crate) timeout: Option<Timeout>,
152 pub(crate) redirect: Option<RedirectPolicy>,
153 pub(crate) auth: Option<AuthScheme>,
154 pub(crate) auth_disabled: bool,
155 pub(crate) decompress: Option<bool>,
156 pub(crate) max_decoded_body_size: Option<usize>,
157 pub(crate) max_decompression_ratio: Option<f64>,
158 pub(crate) proxy_override: ProxyOverride,
159 pub(crate) retry: Option<RetryPolicy>,
160 pub(crate) transport_hints: TransportHints,
161}
162
163impl RequestParts {
164 #[allow(
171 dead_code,
172 reason = "exhaustiveness anchor for RequestParts: guarantees new fields fail to compile even though live code uses retry_request"
173 )]
174 pub(crate) fn into_request(self) -> Request {
175 let RequestParts {
176 method,
177 url,
178 headers,
179 body,
180 version,
181 timeout,
182 redirect,
183 auth,
184 auth_disabled,
185 decompress,
186 max_decoded_body_size,
187 max_decompression_ratio,
188 proxy_override,
189 retry,
190 transport_hints,
191 } = self;
192 let mut request = Request::new(method, url);
193 *request.headers_mut() = headers;
194 request.set_body(body);
195 request.set_version(version);
196 request.set_timeout(timeout);
197 request.set_redirect(redirect);
198 request.set_auth(auth);
199 request.set_auth_disabled(auth_disabled);
200 request.set_decompress(decompress);
201 request.set_max_decoded_body_size(max_decoded_body_size);
202 request.set_max_decompression_ratio(max_decompression_ratio);
203 #[cfg(feature = "proxy")]
204 request.set_proxy_override(proxy_override);
205 #[cfg(not(feature = "proxy"))]
206 let _ = proxy_override;
207 request.set_retry(retry);
208 request.set_transport_hints(transport_hints);
209 request
210 }
211
212 pub(crate) fn retry_request(
226 &self,
227 attempt_timeout: Option<Timeout>,
228 ) -> crate::error::Result<Request> {
229 let replayed = self.body.try_clone_for_retry()?;
230 let mut request = Request::new(self.method.clone(), self.url.clone());
231 *request.headers_mut() = self.headers.clone();
232 request.set_body(replayed);
233 request.set_version(self.version);
234 request.set_timeout(attempt_timeout);
235 request.set_redirect(self.redirect.clone());
236 request.set_auth(self.auth.clone());
237 request.set_auth_disabled(self.auth_disabled);
238 request.set_decompress(self.decompress);
239 request.set_max_decoded_body_size(self.max_decoded_body_size);
240 request.set_max_decompression_ratio(self.max_decompression_ratio);
241 #[cfg(feature = "proxy")]
242 request.set_proxy_override(self.proxy_override.clone());
243 request.set_retry(self.retry.clone());
244 request.set_transport_hints(self.transport_hints.clone());
245 Ok(request)
246 }
247
248 pub(crate) fn shrink_total_deadline(
254 timeout: &Timeout,
255 elapsed: std::time::Duration,
256 ) -> Timeout {
257 let mut out = *timeout;
258 if let Some(total) = out.total {
259 out.total = Some(total.saturating_sub(elapsed));
260 }
261 out
262 }
263}
264
265pub struct Request {
274 method: http::Method,
275 url: url::Url,
276 headers: Headers,
277 body: RequestBody,
278 version: Version,
279 timeout: Option<Timeout>,
280 redirect: Option<RedirectPolicy>,
281 auth: Option<AuthScheme>,
282 auth_disabled: bool,
283 decompress: Option<bool>,
284 max_decoded_body_size: Option<usize>,
285 max_decompression_ratio: Option<f64>,
286 proxy_override: ProxyOverride,
288 retry: Option<RetryPolicy>,
290 transport_hints: TransportHints,
292}
293
294impl std::fmt::Debug for Request {
295 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296 f.debug_struct("Request")
297 .field("method", &self.method)
298 .field("url", &crate::redact::redact_url(&self.url))
299 .field("headers", &self.headers)
300 .field("body", &self.body)
301 .field("version", &self.version)
302 .field("timeout", &self.timeout)
303 .field("redirect", &self.redirect)
304 .field("auth", &self.auth)
305 .field("auth_disabled", &self.auth_disabled)
306 .field("decompress", &self.decompress)
307 .field("max_decoded_body_size", &self.max_decoded_body_size)
308 .field("max_decompression_ratio", &self.max_decompression_ratio)
309 .field("proxy_override", &self.proxy_override)
310 .field("retry", &self.retry)
311 .field("transport_hints", &self.transport_hints)
312 .finish()
313 }
314}
315
316impl Request {
317 pub(crate) fn new(method: http::Method, url: url::Url) -> Self {
319 Self {
320 method,
321 url,
322 headers: Headers::new(),
323 body: RequestBody::default(),
324 version: Version::HTTP_11,
325 timeout: None,
326 redirect: None,
327 auth: None,
328 auth_disabled: false,
329 decompress: None,
330 max_decoded_body_size: None,
331 max_decompression_ratio: None,
332 proxy_override: ProxyOverride::Inherit,
333 retry: None,
334 transport_hints: TransportHints::default(),
335 }
336 }
337
338 #[must_use]
340 pub fn method(&self) -> &http::Method {
341 &self.method
342 }
343
344 #[must_use]
346 pub fn url(&self) -> &url::Url {
347 &self.url
348 }
349
350 #[must_use]
352 pub fn headers(&self) -> &Headers {
353 &self.headers
354 }
355
356 pub fn headers_mut(&mut self) -> &mut Headers {
358 &mut self.headers
359 }
360
361 #[must_use]
363 pub fn body(&self) -> &RequestBody {
364 &self.body
365 }
366
367 pub fn set_body(&mut self, body: RequestBody) {
369 self.body = body;
370 }
371
372 #[must_use]
374 pub fn version(&self) -> Version {
375 self.version
376 }
377
378 pub fn set_version(&mut self, version: Version) {
380 self.version = version;
381 }
382
383 #[must_use]
385 pub fn timeout(&self) -> Option<&Timeout> {
386 self.timeout.as_ref()
387 }
388
389 pub fn set_timeout(&mut self, timeout: Option<Timeout>) {
391 self.timeout = timeout;
392 }
393
394 #[must_use]
396 pub fn redirect(&self) -> Option<&RedirectPolicy> {
397 self.redirect.as_ref()
398 }
399
400 pub fn set_redirect(&mut self, redirect: Option<RedirectPolicy>) {
402 self.redirect = redirect;
403 }
404
405 #[must_use]
407 pub fn auth(&self) -> Option<&AuthScheme> {
408 self.auth.as_ref()
409 }
410
411 pub fn set_auth(&mut self, auth: Option<AuthScheme>) {
413 self.auth = auth;
414 }
415
416 #[must_use]
418 pub fn is_auth_disabled(&self) -> bool {
419 self.auth_disabled
420 }
421
422 pub fn set_auth_disabled(&mut self, disabled: bool) {
424 self.auth_disabled = disabled;
425 }
426
427 #[must_use]
433 pub fn decompress(&self) -> Option<bool> {
434 self.decompress
435 }
436
437 pub fn set_decompress(&mut self, decompress: Option<bool>) {
439 self.decompress = decompress;
440 }
441
442 #[must_use]
446 pub fn max_decoded_body_size(&self) -> Option<usize> {
447 self.max_decoded_body_size
448 }
449
450 pub fn set_max_decoded_body_size(&mut self, max: Option<usize>) {
452 self.max_decoded_body_size = max;
453 }
454
455 #[must_use]
459 pub fn max_decompression_ratio(&self) -> Option<f64> {
460 self.max_decompression_ratio
461 }
462
463 pub fn set_max_decompression_ratio(&mut self, ratio: Option<f64>) {
465 self.max_decompression_ratio = ratio;
466 }
467
468 #[cfg(feature = "proxy")]
470 #[must_use]
471 pub fn proxy_override(&self) -> &ProxyOverride {
472 &self.proxy_override
473 }
474
475 #[cfg(feature = "proxy")]
477 pub fn set_proxy_override(&mut self, proxy: ProxyOverride) {
478 self.proxy_override = proxy;
479 }
480
481 #[must_use]
483 pub fn retry(&self) -> Option<&RetryPolicy> {
484 self.retry.as_ref()
485 }
486
487 pub fn set_retry(&mut self, retry: Option<RetryPolicy>) {
489 self.retry = retry;
490 }
491
492 #[must_use]
494 pub fn transport_hints(&self) -> &TransportHints {
495 &self.transport_hints
496 }
497
498 pub fn set_transport_hints(&mut self, hints: TransportHints) {
500 self.transport_hints = hints;
501 }
502
503 pub(crate) fn into_parts(self) -> RequestParts {
507 RequestParts {
508 method: self.method,
509 url: self.url,
510 headers: self.headers,
511 body: self.body,
512 version: self.version,
513 timeout: self.timeout,
514 redirect: self.redirect,
515 auth: self.auth,
516 auth_disabled: self.auth_disabled,
517 decompress: self.decompress,
518 max_decoded_body_size: self.max_decoded_body_size,
519 max_decompression_ratio: self.max_decompression_ratio,
520 proxy_override: self.proxy_override,
521 retry: self.retry,
522 transport_hints: self.transport_hints,
523 }
524 }
525}
526
527pub struct RequestBuilder {
529 client: Option<Client>,
530 method: http::Method,
531 url: url::Url,
532 headers: Headers,
533 body: RequestBody,
534 timeout: Option<Timeout>,
535 redirect: Option<RedirectPolicy>,
536 auth: Option<AuthScheme>,
537 auth_disabled: bool,
538 decompress: Option<bool>,
539 max_decoded_body_size: Option<usize>,
540 max_decompression_ratio: Option<f64>,
541 proxy_override: ProxyOverride,
542 retry: Option<RetryPolicy>,
543 transport_hints: TransportHints,
544 error: Option<crate::Error>,
545}
546
547impl RequestBuilder {
548 pub(crate) fn new(client: Client, method: http::Method, url: url::Url) -> Self {
550 Self {
551 client: Some(client),
552 method,
553 url,
554 headers: Headers::new(),
555 body: RequestBody::default(),
556 timeout: None,
557 redirect: None,
558 auth: None,
559 auth_disabled: false,
560 decompress: None,
561 max_decoded_body_size: None,
562 max_decompression_ratio: None,
563 proxy_override: ProxyOverride::Inherit,
564 retry: None,
565 transport_hints: TransportHints::default(),
566 error: None,
567 }
568 }
569
570 #[must_use]
572 pub fn header(mut self, name: &str, value: &str) -> Self {
573 if let Err(e) = self.headers.insert(name, value) {
574 if self.error.is_none() {
575 self.error = Some(e);
576 }
577 }
578 self
579 }
580
581 #[must_use]
583 pub fn headers(mut self, headers: Headers) -> Self {
584 self.headers = headers;
585 self
586 }
587
588 #[must_use]
590 pub fn query(mut self, key: &str, value: &str) -> Self {
591 self.url.query_pairs_mut().append_pair(key, value);
592 self
593 }
594
595 #[must_use]
597 pub fn body(mut self, body: impl Into<RequestBody>) -> Self {
598 self.body = body.into();
599 self
600 }
601
602 #[must_use]
604 pub fn bytes(self, data: impl Into<Bytes>) -> Self {
605 self.body(RequestBody::Bytes(data.into()))
606 }
607
608 #[cfg(feature = "json")]
622 pub fn json<T: serde::Serialize>(mut self, value: &T) -> Result<Self> {
623 let bytes = serde_json::to_vec(value)
624 .map_err(|_| crate::Error::JsonSerialize("failed to serialize JSON value".into()))?;
625 self.body = RequestBody::Bytes(Bytes::from(bytes));
626 if !self.headers.contains("content-type") {
627 self.headers.insert("content-type", "application/json")?;
628 }
629 Ok(self)
630 }
631
632 #[must_use]
638 pub fn timeout(mut self, timeout: Timeout) -> Self {
639 self.timeout = Some(timeout);
640 self
641 }
642
643 #[must_use]
648 pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
649 self.redirect = Some(policy);
650 self
651 }
652
653 #[must_use]
657 pub fn auth(mut self, auth: impl Into<AuthScheme>) -> Self {
658 self.auth = Some(auth.into());
659 self.auth_disabled = false;
660 self
661 }
662
663 #[must_use]
668 pub fn without_auth(mut self) -> Self {
669 self.auth_disabled = true;
670 self.auth = None;
671 self
672 }
673
674 #[cfg(feature = "proxy")]
678 #[must_use]
679 pub fn proxy(mut self, proxy: &crate::proxy::Proxy) -> Self {
680 self.proxy_override = ProxyOverride::Override(proxy.config());
681 self
682 }
683
684 #[cfg(feature = "proxy")]
689 #[must_use]
690 pub fn without_proxy(mut self) -> Self {
691 self.proxy_override = ProxyOverride::Direct;
692 self
693 }
694
695 #[must_use]
700 pub fn decompress(mut self, decompress: bool) -> Self {
701 self.decompress = Some(decompress);
702 self
703 }
704
705 #[must_use]
711 pub fn max_decoded_body_size(mut self, max: usize) -> Self {
712 self.max_decoded_body_size = Some(max);
713 self
714 }
715
716 #[must_use]
725 pub fn max_decompression_ratio(mut self, ratio: f64) -> Self {
726 assert!(
727 ratio.is_finite() && ratio > 0.0,
728 "max_decompression_ratio must be finite and positive, got {ratio}"
729 );
730 self.max_decompression_ratio = Some(ratio);
731 self
732 }
733
734 #[must_use]
739 pub fn retry(mut self, policy: RetryPolicy) -> Self {
740 self.retry = Some(policy);
741 self
742 }
743
744 #[must_use]
747 pub fn without_retry(mut self) -> Self {
748 self.retry = Some(RetryPolicy::default());
749 self
750 }
751
752 #[must_use]
757 pub fn transport_hints(mut self, hints: TransportHints) -> Self {
758 self.transport_hints = hints;
759 self
760 }
761
762 #[must_use]
769 pub fn resolved_addresses<I>(mut self, addresses: I) -> Self
770 where
771 I: IntoIterator<Item = SocketAddr>,
772 {
773 match ResolvedTarget::new(addresses) {
774 Ok(target) => self.transport_hints.resolved_target = Some(target),
775 Err(error) => {
776 if self.error.is_none() {
777 self.error = Some(error);
778 }
779 }
780 }
781 self
782 }
783
784 pub fn build(mut self) -> Result<Request> {
791 if let Some(e) = self.error.take() {
792 return Err(e);
793 }
794 if let Some(target) = &self.transport_hints.resolved_target {
795 let expected_port = self.url.port_or_known_default().ok_or_else(|| {
796 crate::Error::InvalidResolvedTarget(
797 "resolved destinations require an HTTP or HTTPS URL".into(),
798 )
799 })?;
800 if target
801 .addresses()
802 .iter()
803 .any(|address| address.port() != expected_port)
804 {
805 return Err(crate::Error::InvalidResolvedTarget(format!(
806 "all resolved destinations must use the URL's effective port {expected_port}"
807 )));
808 }
809 }
810 let request_target = self
811 .transport_hints
812 .target
813 .as_deref()
814 .unwrap_or_else(|| self.url.as_str().as_bytes());
815 self.headers
816 .validate_request_size(&self.method, request_target)?;
817 let mut req = Request::new(self.method, self.url);
818 req.headers = self.headers;
819 req.body = self.body;
820 req.timeout = self.timeout;
821 req.redirect = self.redirect;
822 req.auth = self.auth;
823 req.auth_disabled = self.auth_disabled;
824 req.decompress = self.decompress;
825 req.max_decoded_body_size = self.max_decoded_body_size;
826 req.max_decompression_ratio = self.max_decompression_ratio;
827 req.proxy_override = self.proxy_override;
828 req.retry = self.retry;
829 req.transport_hints = self.transport_hints;
830 Ok(req)
831 }
832
833 pub async fn send(self) -> Result<Response> {
839 let client = self.client.clone().ok_or_else(|| {
840 crate::Error::RequestBuild("no client associated with request builder".into())
841 })?;
842 let request = self.build()?;
843 Box::pin(client.send(request)).await
844 }
845}
846
847#[cfg(test)]
848mod tests {
849 use proptest::prelude::*;
850
851 use super::{Request, ResolvedTarget};
852 use crate::auth::{AuthScheme, BasicAuth};
853 use bytes::Bytes;
854 use std::net::SocketAddr;
855
856 proptest::proptest! {
857 #[test]
858 fn url_parse_round_trip(scheme in "https?", host in "[a-z]{2,10}\\.[a-z]{2,5}", path in "/[a-z]{0,20}") {
859 let url_str = format!("{scheme}://{host}{path}");
860 let parsed = url::Url::parse(&url_str).unwrap();
861 let serialized = parsed.to_string();
862 prop_assert_eq!(url_str, serialized);
863 }
864
865 #[test]
866 fn query_pairs_round_trip(key in "[a-z]{1,10}", value in "[a-z0-9]{1,20}") {
867 let mut url = url::Url::parse("http://example.com/").unwrap();
868 url.query_pairs_mut().append_pair(&key, &value);
869 let found = url.query_pairs().find(|(k, _)| k == &key).map(|(_, v)| v.into_owned());
870 prop_assert_eq!(found, Some(value));
871 }
872
873 #[test]
874 fn url_with_arbitrary_path(path in "/[a-zA-Z0-9._/-]{0,50}") {
875 let url_str = format!("http://example.com{path}");
876 let _ = url::Url::parse(&url_str);
878 }
879 }
880
881 #[test]
882 fn request_debug_redacts_secrets() {
883 let url = url::Url::parse("https://example.com/submit?api_key=top-secret-key").unwrap();
884 let mut req = Request::new(http::Method::POST, url);
885 req.headers_mut()
886 .insert("authorization", "Bearer bearer-secret-token")
887 .unwrap();
888 req.headers_mut()
889 .insert("cookie", "session=cookie-secret")
890 .unwrap();
891 req.set_body(crate::body::RequestBody::Bytes(Bytes::from(
892 "password=form-secret",
893 )));
894 req.set_auth(Some(AuthScheme::Basic(
895 BasicAuth::new("user", "auth-secret").unwrap(),
896 )));
897 let debug = format!("{req:?}");
898 for leaked in [
899 "top-secret-key",
900 "bearer-secret-token",
901 "cookie-secret",
902 "form-secret",
903 "auth-secret",
904 ] {
905 assert!(
906 !debug.contains(leaked),
907 "Request Debug must not leak {leaked:?}: {debug}"
908 );
909 }
910 assert!(debug.contains("example.com"), "keeps the host: {debug}");
912 assert!(debug.contains("POST"), "keeps the method: {debug}");
913 }
914
915 #[test]
916 fn resolved_target_rejects_empty_and_hides_addresses_in_debug() {
917 assert!(ResolvedTarget::new(Vec::<SocketAddr>::new()).is_err());
918 let target = ResolvedTarget::new(["127.0.0.1:443".parse().unwrap()]).unwrap();
919 let debug = format!("{target:?}");
920 assert!(debug.contains("address_count: 1"));
921 assert!(!debug.contains("127.0.0.1"));
922 }
923
924 #[test]
925 fn request_builder_validates_resolved_target_port() {
926 let client = crate::client::Client::new();
927 let request = client
928 .get("http://example.invalid/")
929 .unwrap()
930 .resolved_addresses(["127.0.0.1:80".parse().unwrap()])
931 .build()
932 .unwrap();
933 assert_eq!(
934 request
935 .transport_hints()
936 .resolved_target
937 .as_ref()
938 .unwrap()
939 .addresses()
940 .len(),
941 1
942 );
943
944 let error = client
945 .get("http://example.invalid/")
946 .unwrap()
947 .resolved_addresses(["127.0.0.1:443".parse().unwrap()])
948 .build()
949 .unwrap_err();
950 assert_eq!(error.kind(), "invalid_resolved_target");
951 }
952
953 #[cfg(feature = "json")]
954 #[test]
955 fn request_json_sets_default_content_type_and_replayable_body() {
956 let client = crate::client::Client::new();
957 let request = client
958 .post("http://example.invalid/")
959 .unwrap()
960 .json(&serde_json::json!({"key": "value"}))
961 .unwrap()
962 .build()
963 .unwrap();
964 assert_eq!(
965 request.headers().get("content-type").unwrap(),
966 "application/json"
967 );
968 assert!(request.body().is_replayable());
969
970 let request = client
971 .post("http://example.invalid/")
972 .unwrap()
973 .header("content-type", "application/vnd.api+json")
974 .json(&serde_json::json!([1, 2, 3]))
975 .unwrap()
976 .build()
977 .unwrap();
978 assert_eq!(
979 request.headers().get("content-type").unwrap(),
980 "application/vnd.api+json"
981 );
982 }
983}