Skip to main content

alien_client_core/
request_utils.rs

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