Skip to main content

alien_client_core/
request_utils.rs

1use crate::error::{ErrorData, Result};
2use crate::interceptor::{apply_response_hook, ResponseHook};
3use alien_error::{AlienError, Context, IntoAlienError};
4use async_trait::async_trait;
5use backon::{ExponentialBuilder, Retryable};
6use serde::de::DeserializeOwned;
7use std::time::Duration;
8
9/// Extract request body as string from a reqwest::Request if available
10fn extract_request_body_string(request: &reqwest::Request) -> Option<String> {
11    request
12        .body()
13        .and_then(|body| body.as_bytes())
14        .map(|bytes| String::from_utf8_lossy(bytes).into_owned())
15}
16
17/// JSON key under which the captured request body lives in an error's `context` snapshot. The
18/// `AlienErrorData` derive builds `context` from the raw field name, so this must match the
19/// `http_request_text` field of [`ErrorData::HttpResponseError`] verbatim. The redaction tests below
20/// serialize the whole chain and assert the secret is gone, so a drift here fails loudly.
21const HTTP_REQUEST_TEXT_CONTEXT_KEY: &str = "http_request_text";
22
23/// Strips the captured HTTP request body from every layer of an error chain.
24///
25/// Cloud "create" requests carry secrets in the request body (e.g. a DB master password). On a
26/// non-2xx response the transport records that body in [`ErrorData::HttpResponseError`], in both the
27/// typed payload and the `context` JSON snapshot. A non-internal `.context(...)` wrapper does not
28/// sanitize its source, and the source chain is serialized verbatim into durable state and status
29/// responses — so the body could leak.
30///
31/// This scrubs both representations across the head and full `source` chain, keeping status, response
32/// text, URL, and chain intact. Response text is kept deliberately: RDS / Cloud SQL / Flexible Server
33/// error bodies don't echo the submitted password back, so it stays as a diagnostic — a future caller
34/// wiring this to an API that *does* reflect request fields in its error responses would need to scrub
35/// that too. Order-independent: works whether the HTTP error is still the head (AWS: redaction before
36/// mapping) or already wrapped into the source (GCP/Azure: transport maps first). Apply to the raw
37/// transport result of any request whose body contains a secret.
38pub fn redact_request_body<T>(result: Result<T>) -> Result<T> {
39    result.map_err(|mut e| {
40        // Head: drop the body from the typed payload when the head itself is the HTTP error...
41        if let Some(ErrorData::HttpResponseError {
42            http_request_text, ..
43        }) = e.error.as_mut()
44        {
45            *http_request_text = None;
46        }
47        // ...and from the head's `context` snapshot.
48        scrub_request_body(e.context.as_mut());
49        // Walk the source chain (each layer is type-erased to `GenericError`, so its typed payload no
50        // longer holds the body — only its `context` snapshot can) and scrub every layer.
51        let mut layer = e.source.as_deref_mut();
52        while let Some(err) = layer {
53            scrub_request_body(err.context.as_mut());
54            layer = err.source.as_deref_mut();
55        }
56        e
57    })
58}
59
60/// Removes the captured request body from a single error's `context` snapshot, if present.
61fn scrub_request_body(context: Option<&mut serde_json::Value>) {
62    if let Some(serde_json::Value::Object(map)) = context {
63        map.remove(HTTP_REQUEST_TEXT_CONTEXT_KEY);
64    }
65}
66
67const HTTP_RESPONSE_TEXT_CONTEXT_KEY: &str = "http_response_text";
68const HTTP_STATUS_CONTEXT_KEY: &str = "http_status";
69
70/// Strips the body of a successful (2xx) response from every layer of an error chain.
71///
72/// Calls such as KMS Decrypt or Secrets Manager GetSecretValue answer with plaintext. If that
73/// answer cannot be parsed, the transport records it as the response text of an
74/// [`ErrorData::HttpResponseError`], and the chain is serialized into logs and durable state.
75/// Error responses (non-2xx) never carry the secret, so their text stays as a diagnostic.
76/// Apply to the raw transport result of any request whose success response holds a secret.
77pub fn redact_response_body<T>(result: Result<T>) -> Result<T> {
78    result.map_err(|mut e| {
79        let mut succeeded = false;
80        if let Some(ErrorData::HttpResponseError {
81            message,
82            http_status,
83            http_response_text,
84            ..
85        }) = e.error.as_mut()
86        {
87            if (200..300).contains(http_status) {
88                succeeded = true;
89                *http_response_text = None;
90                *message = withhold_parse_detail(message);
91            }
92        }
93        succeeded |= context_has_success_status(e.context.as_ref());
94        if succeeded {
95            e.message = withhold_parse_detail(&e.message);
96        }
97        scrub_success_response_body(e.context.as_mut());
98        let mut layer = e.source.as_deref_mut();
99        while let Some(err) = layer {
100            let layer_succeeded = succeeded || context_has_success_status(err.context.as_ref());
101            if layer_succeeded {
102                err.message = withhold_parse_detail(&err.message);
103            }
104            scrub_success_response_body(err.context.as_mut());
105            layer = err.source.as_deref_mut();
106        }
107        e
108    })
109}
110
111fn context_has_success_status(context: Option<&serde_json::Value>) -> bool {
112    context
113        .and_then(|context| context.get(HTTP_STATUS_CONTEXT_KEY))
114        .and_then(serde_json::Value::as_u64)
115        .is_some_and(|status| (200..300).contains(&status))
116}
117
118/// Parse failures of a success response read "Invalid JSON response at field 'x': <serde error>".
119/// The serde error quotes the offending value, which can be the secret itself, so only the field
120/// path is kept.
121fn withhold_parse_detail(message: &str) -> String {
122    for prefix in [
123        "Invalid JSON response at field '",
124        "Invalid XML response at field '",
125    ] {
126        if let Some(rest) = message.strip_prefix(prefix) {
127            let path = rest.split_once("': ").map_or("", |(path, _)| path);
128            return format!(
129                "{}{}': the response could not be parsed (details withheld because it can hold a secret)",
130                prefix, path
131            );
132        }
133    }
134    message.to_string()
135}
136
137fn scrub_success_response_body(context: Option<&mut serde_json::Value>) {
138    if let Some(serde_json::Value::Object(map)) = context {
139        if context_has_success_status(Some(&serde_json::Value::Object(map.clone()))) {
140            map.remove(HTTP_RESPONSE_TEXT_CONTEXT_KEY);
141            if let Some(serde_json::Value::String(message)) = map.get_mut("message") {
142                *message = withhold_parse_detail(message);
143            }
144        }
145    }
146}
147
148/// Redacts both bodies of a call whose request and success response hold secrets.
149pub fn redact_secret_bodies<T>(result: Result<T>) -> Result<T> {
150    redact_response_body(redact_request_body(result))
151}
152
153/// Helper to build request and extract body before sending
154fn build_and_extract_body(
155    builder: reqwest::RequestBuilder,
156) -> Result<(reqwest::Client, reqwest::Request, Option<String>)> {
157    let (client, req_result) = builder.build_split();
158    let request = req_result
159        .into_alien_error()
160        .context(ErrorData::HttpRequestFailed {
161            message: "Failed to build request".to_string(),
162        })?;
163
164    let body_string = extract_request_body_string(&request);
165    Ok((client, request, body_string))
166}
167
168/// Handle an HTTP response by checking status and parsing JSON on success
169pub async fn handle_json_response<T: DeserializeOwned>(
170    response: reqwest::Response,
171    request_body: Option<String>,
172) -> Result<T> {
173    let status = response.status();
174    let url = response.url().to_string();
175    let response_text =
176        response
177            .text()
178            .await
179            .into_alien_error()
180            .context(ErrorData::HttpRequestFailed {
181                message: "Failed to read response body".to_string(),
182            })?;
183
184    if !status.is_success() {
185        return Err(AlienError::new(ErrorData::HttpResponseError {
186            message: format!(
187                "Request failed with HTTP {}: {}",
188                status.as_u16(),
189                status.canonical_reason().unwrap_or("Unknown error")
190            ),
191            url,
192            http_status: status.as_u16(),
193            http_request_text: request_body,
194            http_response_text: Some(response_text),
195        }));
196    }
197
198    // Parse the JSON response using serde_path_to_error for better error messages
199    let jd = &mut serde_json::Deserializer::from_str(&response_text);
200    let parsed_response: T = serde_path_to_error::deserialize(jd).map_err(|err| {
201        AlienError::new(ErrorData::HttpResponseError {
202            message: format!(
203                "Invalid JSON response at field '{}': {}",
204                err.path(),
205                err.inner()
206            ),
207            url,
208            http_status: status.as_u16(),
209            http_request_text: request_body,
210            http_response_text: Some(response_text),
211        })
212    })?;
213
214    Ok(parsed_response)
215}
216
217/// Handle an HTTP response by checking status and parsing XML on success
218pub async fn handle_xml_response<T: DeserializeOwned>(
219    response: reqwest::Response,
220    request_body: Option<String>,
221) -> Result<T> {
222    let status = response.status();
223    let url = response.url().to_string();
224    let response_text =
225        response
226            .text()
227            .await
228            .into_alien_error()
229            .context(ErrorData::HttpRequestFailed {
230                message: "Failed to read response body".to_string(),
231            })?;
232
233    if !status.is_success() {
234        return Err(AlienError::new(ErrorData::HttpResponseError {
235            message: format!(
236                "Request failed with HTTP {}: {}",
237                status.as_u16(),
238                status.canonical_reason().unwrap_or("Unknown error")
239            ),
240            url,
241            http_status: status.as_u16(),
242            http_request_text: request_body,
243            http_response_text: Some(response_text),
244        }));
245    }
246
247    // Parse the XML response using serde_path_to_error for better error messages
248    let mut xml_deserializer = quick_xml::de::Deserializer::from_str(&response_text);
249    let parsed_response: T =
250        serde_path_to_error::deserialize(&mut xml_deserializer).map_err(|err| {
251            AlienError::new(ErrorData::HttpResponseError {
252                message: format!(
253                    "Invalid XML response at field '{}': {}",
254                    err.path(),
255                    err.inner()
256                ),
257                url,
258                http_status: status.as_u16(),
259                http_request_text: request_body,
260                http_response_text: Some(response_text),
261            })
262        })?;
263
264    Ok(parsed_response)
265}
266
267/// Handle an HTTP response by checking status without parsing the body
268pub async fn handle_no_response(
269    response: reqwest::Response,
270    request_body: Option<String>,
271) -> Result<()> {
272    let status = response.status();
273    let url = response.url().to_string();
274
275    if !status.is_success() {
276        let response_text =
277            response
278                .text()
279                .await
280                .into_alien_error()
281                .context(ErrorData::HttpRequestFailed {
282                    message: "Failed to read error response body".to_string(),
283                })?;
284        return Err(AlienError::new(ErrorData::HttpResponseError {
285            message: format!(
286                "Request failed with HTTP {}: {}",
287                status.as_u16(),
288                status.canonical_reason().unwrap_or("Unknown error")
289            ),
290            url,
291            http_status: status.as_u16(),
292            http_request_text: request_body,
293            http_response_text: Some(response_text),
294        }));
295    }
296
297    // A successful response can still carry a body, such as SQS response metadata.
298    // Consume it before returning so HTTP/1 connections can be reused. Native responses are
299    // discarded a chunk at a time rather than buffered.
300    #[cfg(not(target_arch = "wasm32"))]
301    {
302        let mut response = response;
303        while response
304            .chunk()
305            .await
306            .into_alien_error()
307            .context(ErrorData::HttpResponseBodyReadFailed {
308                http_status: status.as_u16(),
309            })?
310            .is_some()
311        {}
312    }
313    #[cfg(target_arch = "wasm32")]
314    response
315        .bytes()
316        .await
317        .into_alien_error()
318        .context(ErrorData::HttpResponseBodyReadFailed {
319            http_status: status.as_u16(),
320        })?;
321
322    Ok(())
323}
324
325/// Extension trait for `reqwest::RequestBuilder` to add JSON and XML response handling
326#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
327#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
328pub trait RequestBuilderExt {
329    /// Enable retries with an exponential back-off strategy.
330    ///
331    /// Example:
332    /// ```ignore
333    /// let obj: MyType = client
334    ///     .get("https://api.example.com/obj")
335    ///     .with_retry()                // <- enable retries
336    ///     .send_json()                // <- deserialize JSON body
337    ///     .await?;
338    /// ```
339    fn with_retry(self) -> RetriableRequestBuilder;
340
341    /// Send the request and parse the response as JSON
342    async fn send_json<T: DeserializeOwned + 'static>(self) -> Result<T>;
343
344    /// Send the request and parse the response as XML
345    async fn send_xml<T: DeserializeOwned + 'static>(self) -> Result<T>;
346
347    /// Send the request without parsing the response body
348    async fn send_no_response(self) -> Result<()>;
349
350    /// Send the request and return the raw response for custom handling
351    async fn send_raw(self) -> Result<reqwest::Response>;
352}
353
354/// The exponential back-off the cloud clients retry with unless a request overrides it: up to
355/// 3 retries, each delay up to 20s.
356pub fn default_retry_backoff() -> ExponentialBuilder {
357    let backoff = ExponentialBuilder::default()
358        .with_max_times(3)
359        .with_max_delay(Duration::from_secs(20))
360        .with_jitter();
361    // Mocked tests answer at once, so waiting between retries only adds time. The retries
362    // still happen, so every request a test expects is still sent.
363    if cfg!(feature = "no-retry-delay") {
364        backoff.with_min_delay(Duration::ZERO)
365    } else {
366        backoff
367    }
368}
369
370/// A `reqwest::RequestBuilder` wrapper that automatically retries failed
371/// requests using an exponential back-off strategy powered by the `backon`
372/// crate. Use [`RequestBuilderExt::with_retry`] to construct one.
373pub struct RetriableRequestBuilder {
374    inner: reqwest::RequestBuilder,
375    backoff: ExponentialBuilder,
376    retry_if: fn(&AlienError<ErrorData>) -> bool,
377    /// Runs on every response before it is read, for a request an interceptor matched.
378    response_hook: Option<ResponseHook>,
379}
380
381impl RetriableRequestBuilder {
382    /// Overrides the default back-off settings.
383    pub fn backoff(mut self, backoff: ExponentialBuilder) -> Self {
384        self.backoff = backoff;
385        self
386    }
387
388    /// Retries only the errors `retry_if` accepts, instead of every retryable one. For a request
389    /// that must not be sent twice once the service may have acted on it.
390    pub fn retry_only_when(mut self, retry_if: fn(&AlienError<ErrorData>) -> bool) -> Self {
391        self.retry_if = retry_if;
392        self
393    }
394
395    /// Determine if a given error is retry-able using the retryable field.
396    fn is_retryable_error(e: &AlienError<ErrorData>) -> bool {
397        e.retryable
398    }
399
400    /// Execute the request, applying retries, and parse the body as JSON.
401    pub async fn send_json<T: DeserializeOwned + Send + 'static>(self) -> Result<T> {
402        let backoff = self.backoff;
403        let retry_if = self.retry_if;
404        let builder = self.inner;
405        let response_hook = self.response_hook;
406
407        let retryable = move || {
408            let attempt_builder = builder.try_clone();
409            let response_hook = response_hook.clone();
410            async move {
411                let attempt_builder = attempt_builder.ok_or_else(|| {
412                    AlienError::new(ErrorData::GenericError {
413                        message: "Request retry preparation failed".into(),
414                    })
415                })?;
416
417                let (client, request, body_string) = build_and_extract_body(attempt_builder)?;
418                let new_builder = reqwest::RequestBuilder::from_parts(client, request);
419
420                #[cfg(target_arch = "wasm32")]
421                {
422                    let resp = new_builder.send().await.into_alien_error().context(
423                        ErrorData::HttpRequestFailed {
424                            message: "Network error during HTTP request".to_string(),
425                        },
426                    )?;
427                    let resp = apply_response_hook(response_hook.as_ref(), resp).await?;
428                    handle_json_response(resp, body_string).await
429                }
430                #[cfg(not(target_arch = "wasm32"))]
431                {
432                    let resp = new_builder.send().await.into_alien_error().context(
433                        ErrorData::HttpRequestFailed {
434                            message: "Network error during HTTP request".to_string(),
435                        },
436                    )?;
437                    let resp = apply_response_hook(response_hook.as_ref(), resp).await?;
438                    handle_json_response(resp, body_string).await
439                }
440            }
441        };
442
443        retryable.retry(backoff).when(retry_if).await
444    }
445
446    /// Execute the request, applying retries, and parse the body as XML.
447    pub async fn send_xml<T: DeserializeOwned + Send + 'static>(self) -> Result<T> {
448        let backoff = self.backoff;
449        let retry_if = self.retry_if;
450        let builder = self.inner;
451        let response_hook = self.response_hook;
452
453        let retryable = move || {
454            let attempt_builder = builder.try_clone();
455            let response_hook = response_hook.clone();
456            async move {
457                let attempt_builder = attempt_builder.ok_or_else(|| {
458                    AlienError::new(ErrorData::GenericError {
459                        message: "Request retry preparation failed".into(),
460                    })
461                })?;
462
463                let (client, request, body_string) = build_and_extract_body(attempt_builder)?;
464                let new_builder = reqwest::RequestBuilder::from_parts(client, request);
465
466                #[cfg(target_arch = "wasm32")]
467                {
468                    let resp = new_builder.send().await.into_alien_error().context(
469                        ErrorData::HttpRequestFailed {
470                            message: "Network error during HTTP request".to_string(),
471                        },
472                    )?;
473                    let resp = apply_response_hook(response_hook.as_ref(), resp).await?;
474                    handle_xml_response(resp, body_string).await
475                }
476                #[cfg(not(target_arch = "wasm32"))]
477                {
478                    let resp = new_builder.send().await.into_alien_error().context(
479                        ErrorData::HttpRequestFailed {
480                            message: "Network error during HTTP request".to_string(),
481                        },
482                    )?;
483                    let resp = apply_response_hook(response_hook.as_ref(), resp).await?;
484                    handle_xml_response(resp, body_string).await
485                }
486            }
487        };
488
489        retryable.retry(backoff).when(retry_if).await
490    }
491
492    /// Execute the request, applying retries, without parsing the response body.
493    pub async fn send_no_response(self) -> Result<()> {
494        let backoff = self.backoff;
495        let retry_if = self.retry_if;
496        let builder = self.inner;
497        let response_hook = self.response_hook;
498
499        let retryable = move || {
500            let attempt_builder = builder.try_clone();
501            let response_hook = response_hook.clone();
502            async move {
503                let attempt_builder = attempt_builder.ok_or_else(|| {
504                    AlienError::new(ErrorData::GenericError {
505                        message: "Request retry preparation failed".into(),
506                    })
507                })?;
508
509                let (client, request, body_string) = build_and_extract_body(attempt_builder)?;
510                let new_builder = reqwest::RequestBuilder::from_parts(client, request);
511
512                #[cfg(target_arch = "wasm32")]
513                {
514                    let resp = new_builder.send().await.into_alien_error().context(
515                        ErrorData::HttpRequestFailed {
516                            message: "Network error during HTTP request".to_string(),
517                        },
518                    )?;
519                    let resp = apply_response_hook(response_hook.as_ref(), resp).await?;
520                    handle_no_response(resp, body_string).await
521                }
522                #[cfg(not(target_arch = "wasm32"))]
523                {
524                    let resp = new_builder.send().await.into_alien_error().context(
525                        ErrorData::HttpRequestFailed {
526                            message: "Network error during HTTP request".to_string(),
527                        },
528                    )?;
529                    let resp = apply_response_hook(response_hook.as_ref(), resp).await?;
530                    handle_no_response(resp, body_string).await
531                }
532            }
533        };
534
535        retryable.retry(backoff).when(retry_if).await
536    }
537
538    /// Execute the request, applying retries, and return the raw response
539    pub async fn send_raw(self) -> Result<reqwest::Response> {
540        let backoff = self.backoff;
541        let retry_if = self.retry_if;
542        let builder = self.inner;
543        let response_hook = self.response_hook;
544
545        let retryable = move || {
546            let attempt_builder = builder.try_clone();
547            let response_hook = response_hook.clone();
548            async move {
549                let attempt_builder = attempt_builder.ok_or_else(|| {
550                    AlienError::new(ErrorData::GenericError {
551                        message: "Request retry preparation failed".into(),
552                    })
553                })?;
554
555                let (client, request, _body_string) = build_and_extract_body(attempt_builder)?;
556                let new_builder = reqwest::RequestBuilder::from_parts(client, request);
557
558                #[cfg(target_arch = "wasm32")]
559                {
560                    let resp = new_builder.send().await.into_alien_error().context(
561                        ErrorData::HttpRequestFailed {
562                            message: "Network error during HTTP request".to_string(),
563                        },
564                    )?;
565                    apply_response_hook(response_hook.as_ref(), resp).await
566                }
567                #[cfg(not(target_arch = "wasm32"))]
568                {
569                    let resp = new_builder.send().await.into_alien_error().context(
570                        ErrorData::HttpRequestFailed {
571                            message: "Network error during HTTP request".to_string(),
572                        },
573                    )?;
574                    apply_response_hook(response_hook.as_ref(), resp).await
575                }
576            }
577        };
578
579        retryable.retry(backoff).when(retry_if).await
580    }
581}
582
583#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
584#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
585impl RequestBuilderExt for reqwest::RequestBuilder {
586    fn with_retry(self) -> RetriableRequestBuilder {
587        RetriableRequestBuilder {
588            inner: self,
589            backoff: default_retry_backoff(),
590            retry_if: RetriableRequestBuilder::is_retryable_error,
591            response_hook: None,
592        }
593    }
594
595    async fn send_json<T: DeserializeOwned + 'static>(self) -> Result<T> {
596        let (client, request, body_string) = build_and_extract_body(self)?;
597        let builder = reqwest::RequestBuilder::from_parts(client, request);
598
599        #[cfg(target_arch = "wasm32")]
600        {
601            let resp =
602                builder
603                    .send()
604                    .await
605                    .into_alien_error()
606                    .context(ErrorData::HttpRequestFailed {
607                        message: "Network error during HTTP request".to_string(),
608                    })?;
609            handle_json_response(resp, body_string).await
610        }
611        #[cfg(not(target_arch = "wasm32"))]
612        {
613            let resp =
614                builder
615                    .send()
616                    .await
617                    .into_alien_error()
618                    .context(ErrorData::HttpRequestFailed {
619                        message: "Network error during HTTP request".to_string(),
620                    })?;
621            handle_json_response(resp, body_string).await
622        }
623    }
624
625    async fn send_xml<T: DeserializeOwned + 'static>(self) -> Result<T> {
626        let (client, request, body_string) = build_and_extract_body(self)?;
627        let builder = reqwest::RequestBuilder::from_parts(client, request);
628
629        #[cfg(target_arch = "wasm32")]
630        {
631            let resp =
632                builder
633                    .send()
634                    .await
635                    .into_alien_error()
636                    .context(ErrorData::HttpRequestFailed {
637                        message: "Network error during HTTP request".to_string(),
638                    })?;
639            handle_xml_response(resp, body_string).await
640        }
641        #[cfg(not(target_arch = "wasm32"))]
642        {
643            let resp =
644                builder
645                    .send()
646                    .await
647                    .into_alien_error()
648                    .context(ErrorData::HttpRequestFailed {
649                        message: "Network error during HTTP request".to_string(),
650                    })?;
651            handle_xml_response(resp, body_string).await
652        }
653    }
654
655    async fn send_no_response(self) -> Result<()> {
656        let (client, request, body_string) = build_and_extract_body(self)?;
657        let builder = reqwest::RequestBuilder::from_parts(client, request);
658
659        #[cfg(target_arch = "wasm32")]
660        {
661            let resp =
662                builder
663                    .send()
664                    .await
665                    .into_alien_error()
666                    .context(ErrorData::HttpRequestFailed {
667                        message: "Network error during HTTP request".to_string(),
668                    })?;
669            handle_no_response(resp, body_string).await
670        }
671        #[cfg(not(target_arch = "wasm32"))]
672        {
673            let resp =
674                builder
675                    .send()
676                    .await
677                    .into_alien_error()
678                    .context(ErrorData::HttpRequestFailed {
679                        message: "Network error during HTTP request".to_string(),
680                    })?;
681            handle_no_response(resp, body_string).await
682        }
683    }
684
685    async fn send_raw(self) -> Result<reqwest::Response> {
686        let (client, request, _body_string) = build_and_extract_body(self)?;
687        let builder = reqwest::RequestBuilder::from_parts(client, request);
688
689        #[cfg(target_arch = "wasm32")]
690        {
691            builder
692                .send()
693                .await
694                .into_alien_error()
695                .context(ErrorData::HttpRequestFailed {
696                    message: "Network error during HTTP request".to_string(),
697                })
698        }
699        #[cfg(not(target_arch = "wasm32"))]
700        {
701            builder
702                .send()
703                .await
704                .into_alien_error()
705                .context(ErrorData::HttpRequestFailed {
706                    message: "Network error during HTTP request".to_string(),
707                })
708        }
709    }
710}
711
712/// A request that passed the interceptor hook, carrying the hook its response goes through. It
713/// sends like a `reqwest::RequestBuilder` with [`RequestBuilderExt`].
714pub struct InterceptedRequestBuilder {
715    inner: reqwest::RequestBuilder,
716    response_hook: Option<ResponseHook>,
717}
718
719impl InterceptedRequestBuilder {
720    pub fn new(inner: reqwest::RequestBuilder, response_hook: Option<ResponseHook>) -> Self {
721        Self {
722            inner,
723            response_hook,
724        }
725    }
726
727    pub fn with_retry(self) -> RetriableRequestBuilder {
728        RetriableRequestBuilder {
729            response_hook: self.response_hook,
730            ..self.inner.with_retry()
731        }
732    }
733
734    pub async fn send_json<T: DeserializeOwned + 'static>(self) -> Result<T> {
735        let (resp, body_string) = self.send_once().await?;
736        handle_json_response(resp, body_string).await
737    }
738
739    pub async fn send_xml<T: DeserializeOwned + 'static>(self) -> Result<T> {
740        let (resp, body_string) = self.send_once().await?;
741        handle_xml_response(resp, body_string).await
742    }
743
744    pub async fn send_no_response(self) -> Result<()> {
745        let (resp, body_string) = self.send_once().await?;
746        handle_no_response(resp, body_string).await
747    }
748
749    pub async fn send_raw(self) -> Result<reqwest::Response> {
750        let (resp, _body_string) = self.send_once().await?;
751        Ok(resp)
752    }
753
754    /// The request without its response hook, for a caller that sends it another way.
755    pub fn build(self) -> reqwest::Result<reqwest::Request> {
756        self.inner.build()
757    }
758
759    /// The request and the hook its response must pass through, for a caller that sends it
760    /// another way and still runs the hook.
761    pub fn into_parts(self) -> (reqwest::RequestBuilder, Option<ResponseHook>) {
762        (self.inner, self.response_hook)
763    }
764
765    async fn send_once(self) -> Result<(reqwest::Response, Option<String>)> {
766        let (client, request, body_string) = build_and_extract_body(self.inner)?;
767        let resp = reqwest::RequestBuilder::from_parts(client, request)
768            .send()
769            .await
770            .into_alien_error()
771            .context(ErrorData::HttpRequestFailed {
772                message: "Network error during HTTP request".to_string(),
773            })?;
774        let resp = apply_response_hook(self.response_hook.as_ref(), resp).await?;
775        Ok((resp, body_string))
776    }
777}
778
779#[cfg(test)]
780mod tests {
781    use super::*;
782    use alien_error::ContextError;
783    use std::{
784        io::{BufRead, BufReader, Write},
785        net::TcpListener,
786        sync::{
787            atomic::{AtomicUsize, Ordering},
788            Arc,
789        },
790        thread,
791    };
792    use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
793
794    #[tokio::test]
795    async fn success_body_read_failure_does_not_replay_mutation() {
796        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
797            .await
798            .expect("listen");
799        let address = listener.local_addr().expect("address");
800        let requests = Arc::new(AtomicUsize::new(0));
801        let seen = requests.clone();
802        let server = tokio::spawn(async move {
803            loop {
804                let (mut stream, _) = listener.accept().await.expect("accept");
805                {
806                    let mut reader = tokio::io::BufReader::new(&mut stream);
807                    loop {
808                        let mut line = String::new();
809                        assert!(reader.read_line(&mut line).await.expect("request header") > 0);
810                        if line == "\r\n" {
811                            break;
812                        }
813                    }
814                }
815                let request = seen.fetch_add(1, Ordering::SeqCst);
816                let response = if request == 0 {
817                    &b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: close\r\n\r\nshort"[..]
818                } else {
819                    &b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"[..]
820                };
821                stream.write_all(response).await.expect("response");
822                stream.shutdown().await.expect("close response");
823            }
824        });
825        let error = reqwest::Client::builder()
826            .no_proxy()
827            .timeout(Duration::from_secs(5))
828            .build()
829            .expect("client")
830            .post(format!("http://{address}/mutation"))
831            .with_retry()
832            .backoff(
833                ExponentialBuilder::default()
834                    .with_min_delay(Duration::from_millis(1))
835                    .with_max_delay(Duration::from_millis(1))
836                    .with_max_times(2),
837            )
838            .send_no_response()
839            .await
840            .expect_err("truncated body must fail");
841        assert_eq!(requests.load(Ordering::SeqCst), 1, "mutation was replayed");
842        assert!(!error.retryable);
843        assert_eq!(error.code, "HTTP_RESPONSE_BODY_READ_FAILED");
844        assert!(matches!(
845            error.error,
846            Some(ErrorData::HttpResponseBodyReadFailed { http_status: 200 })
847        ));
848        server.abort();
849        assert!(server.await.expect_err("server stopped").is_cancelled());
850    }
851
852    #[tokio::test]
853    async fn rejects_truncated_success_response_body() {
854        let listener = TcpListener::bind("127.0.0.1:0").expect("listen");
855        let address = listener.local_addr().expect("address");
856        let server = thread::spawn(move || {
857            let (mut stream, _) = listener.accept().expect("accept");
858            {
859                let mut reader = BufReader::new(&mut stream);
860                loop {
861                    let mut line = String::new();
862                    assert!(reader.read_line(&mut line).expect("request header") > 0);
863                    if line == "\r\n" {
864                        break;
865                    }
866                }
867            }
868            stream
869                .write_all(
870                    b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\nConnection: close\r\n\r\nshort",
871                )
872                .expect("partial response");
873        });
874        let response = reqwest::Client::builder()
875            .no_proxy()
876            .timeout(Duration::from_secs(5))
877            .build()
878            .expect("client")
879            .get(format!("http://{address}/"))
880            .send()
881            .await
882            .expect("response headers");
883        assert_eq!(response.status(), reqwest::StatusCode::OK);
884        let error = handle_no_response(response, None)
885            .await
886            .expect_err("truncated body must fail");
887        assert_eq!(error.code, "HTTP_RESPONSE_BODY_READ_FAILED");
888        assert!(!error.retryable);
889        server.join().expect("server");
890    }
891
892    const SECRET: &str = "Sup3rSecret-MasterPassword!";
893
894    /// An `HttpResponseError` as the transport produces it for a failed create: its captured request
895    /// body carries the master password, in both the typed payload and the derived `context` snapshot.
896    fn http_error_with_secret_body() -> AlienError<ErrorData> {
897        AlienError::new(ErrorData::HttpResponseError {
898            message: "Request failed with HTTP 409: Conflict".to_string(),
899            url: "https://rds.amazonaws.com/".to_string(),
900            http_status: 409,
901            http_request_text: Some(format!(
902                "Action=CreateDBCluster&MasterUserPassword={SECRET}&Engine=aurora-postgresql"
903            )),
904            http_response_text: Some(
905                "<Error><Code>DBClusterAlreadyExists</Code></Error>".to_string(),
906            ),
907        })
908    }
909
910    /// AWS path: redaction runs while the HTTP error is still the head. The secret must not survive in
911    /// any serialized field — typed payload or `context` — while diagnostics are kept.
912    #[test]
913    fn redacts_request_body_when_http_error_is_head() {
914        // Precondition: the unredacted error genuinely carries the secret, so this test can fail.
915        let raw = serde_json::to_string(&http_error_with_secret_body()).unwrap();
916        assert!(raw.contains(SECRET), "fixture should carry the secret");
917
918        let err = redact_request_body::<()>(Err(http_error_with_secret_body())).unwrap_err();
919        let json = serde_json::to_string(&err).expect("serialize redacted error");
920        assert!(!json.contains(SECRET), "request body leaked: {json}");
921        // Non-secret diagnostics are retained.
922        assert!(json.contains("409"), "status dropped: {json}");
923        assert!(
924            json.contains("DBClusterAlreadyExists"),
925            "response text dropped: {json}"
926        );
927    }
928
929    /// GCP/Azure path: the transport maps the HTTP error to a non-internal head before redaction runs,
930    /// so the body now lives only in the `source` chain's `context`. The non-internal head does NOT
931    /// sanitize its source by itself (asserted as a precondition), so the whole-chain walk is
932    /// load-bearing here.
933    #[test]
934    fn redacts_request_body_when_http_error_is_wrapped_in_source() {
935        let wrapped = http_error_with_secret_body().context(ErrorData::RemoteResourceConflict {
936            resource_type: "DBCluster".to_string(),
937            resource_name: "stack-db".to_string(),
938            message: "already exists".to_string(),
939        });
940        let before = serde_json::to_string(&wrapped).unwrap();
941        assert!(
942            before.contains(SECRET),
943            "precondition: a non-internal head must NOT sanitize its source on its own"
944        );
945
946        let err = redact_request_body::<()>(Err(wrapped)).unwrap_err();
947        let json = serde_json::to_string(&err).expect("serialize redacted error");
948        assert!(
949            !json.contains(SECRET),
950            "request body leaked through source chain: {json}"
951        );
952        // The chain and its non-secret diagnostics are otherwise intact.
953        assert!(
954            json.contains("REMOTE_RESOURCE_CONFLICT"),
955            "head dropped: {json}"
956        );
957        assert!(
958            json.contains("DBClusterAlreadyExists"),
959            "response text dropped: {json}"
960        );
961    }
962
963    fn http_error_with_status(status: u16, response_text: &str) -> AlienError<ErrorData> {
964        AlienError::new(ErrorData::HttpResponseError {
965            message: "Invalid JSON response".to_string(),
966            url: "https://example.test/".to_string(),
967            http_status: status,
968            http_request_text: None,
969            http_response_text: Some(response_text.to_string()),
970        })
971    }
972
973    #[test]
974    fn redacts_the_body_of_an_unparsable_success_response() {
975        let wrapped = http_error_with_status(200, SECRET).context(ErrorData::GenericError {
976            message: "decrypt failed".to_string(),
977        });
978        let before = serde_json::to_string(&wrapped).unwrap();
979        assert!(before.contains(SECRET), "precondition: the chain holds it");
980
981        let err = redact_response_body::<()>(Err(wrapped)).unwrap_err();
982        let json = serde_json::to_string(&err).unwrap();
983        assert!(!json.contains(SECRET), "response body leaked: {json}");
984        assert!(json.contains("decrypt failed"), "chain dropped: {json}");
985
986        let head =
987            redact_response_body::<()>(Err(http_error_with_status(200, SECRET))).unwrap_err();
988        assert!(!serde_json::to_string(&head).unwrap().contains(SECRET));
989    }
990
991    #[derive(Debug, serde::Deserialize)]
992    #[allow(dead_code)]
993    struct DecryptResponse {
994        plaintext: String,
995    }
996
997    #[tokio::test]
998    async fn a_value_quoted_by_a_parse_error_does_not_reach_the_error_chain() {
999        let secret = "sentinel-parse-secret-value";
1000        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
1001            .await
1002            .expect("listen");
1003        let address = listener.local_addr().expect("address");
1004        let body = format!("\"{secret}\"");
1005        let server = tokio::spawn(async move {
1006            let (mut stream, _) = listener.accept().await.expect("accept");
1007            {
1008                let mut reader = tokio::io::BufReader::new(&mut stream);
1009                loop {
1010                    let mut line = String::new();
1011                    assert!(reader.read_line(&mut line).await.expect("request header") > 0);
1012                    if line == "\r\n" {
1013                        break;
1014                    }
1015                }
1016            }
1017            let response = format!(
1018                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
1019                body.len()
1020            );
1021            stream
1022                .write_all(response.as_bytes())
1023                .await
1024                .expect("response");
1025            stream.shutdown().await.expect("close response");
1026        });
1027        let response = reqwest::Client::builder()
1028            .no_proxy()
1029            .timeout(Duration::from_secs(5))
1030            .build()
1031            .unwrap()
1032            .get(format!("http://{address}/"))
1033            .send()
1034            .await
1035            .unwrap();
1036        let err = handle_json_response::<DecryptResponse>(response, None)
1037            .await
1038            .unwrap_err();
1039        server.abort();
1040        assert!(
1041            serde_json::to_string(&err).unwrap().contains(secret),
1042            "precondition: the parse error quotes the value"
1043        );
1044
1045        let wrapped = err.context(ErrorData::GenericError {
1046            message: "decrypt failed".to_string(),
1047        });
1048        let redacted = redact_response_body::<DecryptResponse>(Err(wrapped)).unwrap_err();
1049        let json = serde_json::to_string(&redacted).unwrap();
1050        assert!(!json.contains(secret), "parse message leaked: {json}");
1051        assert!(json.contains("decrypt failed"), "chain dropped: {json}");
1052        assert!(
1053            json.contains("Invalid JSON response at field"),
1054            "path dropped: {json}"
1055        );
1056    }
1057
1058    #[test]
1059    fn keeps_the_body_of_an_error_response() {
1060        let err = redact_response_body::<()>(Err(http_error_with_status(
1061            403,
1062            "AccessDeniedException: kms:Decrypt",
1063        )))
1064        .unwrap_err();
1065        let json = serde_json::to_string(&err).unwrap();
1066        assert!(json.contains("AccessDeniedException"), "{json}");
1067    }
1068}