alien-client-core 1.14.1

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use crate::error::{ErrorData, Result};
use alien_error::{AlienError, Context, IntoAlienError};
use async_trait::async_trait;
use backon::{ExponentialBuilder, Retryable};
use serde::de::DeserializeOwned;
use std::time::Duration;

/// Extract request body as string from a reqwest::Request if available
fn extract_request_body_string(request: &reqwest::Request) -> Option<String> {
    request
        .body()
        .and_then(|body| body.as_bytes())
        .map(|bytes| String::from_utf8_lossy(bytes).into_owned())
}

/// JSON key under which the captured request body lives in an error's `context` snapshot. The
/// `AlienErrorData` derive builds `context` from the raw field name, so this must match the
/// `http_request_text` field of [`ErrorData::HttpResponseError`] verbatim. The redaction tests below
/// serialize the whole chain and assert the secret is gone, so a drift here fails loudly.
const HTTP_REQUEST_TEXT_CONTEXT_KEY: &str = "http_request_text";

/// Strips the captured HTTP request body from every layer of an error chain.
///
/// Cloud "create" requests carry secrets in the request body (e.g. a DB master password). On a
/// non-2xx response the transport records that body in [`ErrorData::HttpResponseError`], in both the
/// typed payload and the `context` JSON snapshot. A non-internal `.context(...)` wrapper does not
/// sanitize its source, and the source chain is serialized verbatim into durable state and status
/// responses — so the body could leak.
///
/// This scrubs both representations across the head and full `source` chain, keeping status, response
/// text, URL, and chain intact. Response text is kept deliberately: RDS / Cloud SQL / Flexible Server
/// error bodies don't echo the submitted password back, so it stays as a diagnostic — a future caller
/// wiring this to an API that *does* reflect request fields in its error responses would need to scrub
/// that too. Order-independent: works whether the HTTP error is still the head (AWS: redaction before
/// mapping) or already wrapped into the source (GCP/Azure: transport maps first). Apply to the raw
/// transport result of any request whose body contains a secret.
pub fn redact_request_body<T>(result: Result<T>) -> Result<T> {
    result.map_err(|mut e| {
        // Head: drop the body from the typed payload when the head itself is the HTTP error...
        if let Some(ErrorData::HttpResponseError {
            http_request_text, ..
        }) = e.error.as_mut()
        {
            *http_request_text = None;
        }
        // ...and from the head's `context` snapshot.
        scrub_request_body(e.context.as_mut());
        // Walk the source chain (each layer is type-erased to `GenericError`, so its typed payload no
        // longer holds the body — only its `context` snapshot can) and scrub every layer.
        let mut layer = e.source.as_deref_mut();
        while let Some(err) = layer {
            scrub_request_body(err.context.as_mut());
            layer = err.source.as_deref_mut();
        }
        e
    })
}

/// Removes the captured request body from a single error's `context` snapshot, if present.
fn scrub_request_body(context: Option<&mut serde_json::Value>) {
    if let Some(serde_json::Value::Object(map)) = context {
        map.remove(HTTP_REQUEST_TEXT_CONTEXT_KEY);
    }
}

/// Helper to build request and extract body before sending
fn build_and_extract_body(
    builder: reqwest::RequestBuilder,
) -> Result<(reqwest::Client, reqwest::Request, Option<String>)> {
    let (client, req_result) = builder.build_split();
    let request = req_result
        .into_alien_error()
        .context(ErrorData::HttpRequestFailed {
            message: "Failed to build request".to_string(),
        })?;

    let body_string = extract_request_body_string(&request);
    Ok((client, request, body_string))
}

/// Handle an HTTP response by checking status and parsing JSON on success
pub async fn handle_json_response<T: DeserializeOwned>(
    response: reqwest::Response,
    request_body: Option<String>,
) -> Result<T> {
    let status = response.status();
    let url = response.url().to_string();
    let response_text =
        response
            .text()
            .await
            .into_alien_error()
            .context(ErrorData::HttpRequestFailed {
                message: "Failed to read response body".to_string(),
            })?;

    if !status.is_success() {
        return Err(AlienError::new(ErrorData::HttpResponseError {
            message: format!(
                "Request failed with HTTP {}: {}",
                status.as_u16(),
                status.canonical_reason().unwrap_or("Unknown error")
            ),
            url,
            http_status: status.as_u16(),
            http_request_text: request_body,
            http_response_text: Some(response_text),
        }));
    }

    // Parse the JSON response using serde_path_to_error for better error messages
    let jd = &mut serde_json::Deserializer::from_str(&response_text);
    let parsed_response: T = serde_path_to_error::deserialize(jd).map_err(|err| {
        AlienError::new(ErrorData::HttpResponseError {
            message: format!(
                "Invalid JSON response at field '{}': {}",
                err.path(),
                err.inner()
            ),
            url,
            http_status: status.as_u16(),
            http_request_text: request_body,
            http_response_text: Some(response_text),
        })
    })?;

    Ok(parsed_response)
}

/// Handle an HTTP response by checking status and parsing XML on success
pub async fn handle_xml_response<T: DeserializeOwned>(
    response: reqwest::Response,
    request_body: Option<String>,
) -> Result<T> {
    let status = response.status();
    let url = response.url().to_string();
    let response_text =
        response
            .text()
            .await
            .into_alien_error()
            .context(ErrorData::HttpRequestFailed {
                message: "Failed to read response body".to_string(),
            })?;

    if !status.is_success() {
        return Err(AlienError::new(ErrorData::HttpResponseError {
            message: format!(
                "Request failed with HTTP {}: {}",
                status.as_u16(),
                status.canonical_reason().unwrap_or("Unknown error")
            ),
            url,
            http_status: status.as_u16(),
            http_request_text: request_body,
            http_response_text: Some(response_text),
        }));
    }

    // Parse the XML response using serde_path_to_error for better error messages
    let mut xml_deserializer = quick_xml::de::Deserializer::from_str(&response_text);
    let parsed_response: T =
        serde_path_to_error::deserialize(&mut xml_deserializer).map_err(|err| {
            AlienError::new(ErrorData::HttpResponseError {
                message: format!(
                    "Invalid XML response at field '{}': {}",
                    err.path(),
                    err.inner()
                ),
                url,
                http_status: status.as_u16(),
                http_request_text: request_body,
                http_response_text: Some(response_text),
            })
        })?;

    Ok(parsed_response)
}

/// Handle an HTTP response by checking status without parsing the body
pub async fn handle_no_response(
    response: reqwest::Response,
    request_body: Option<String>,
) -> Result<()> {
    let status = response.status();
    let url = response.url().to_string();

    if !status.is_success() {
        let response_text =
            response
                .text()
                .await
                .into_alien_error()
                .context(ErrorData::HttpRequestFailed {
                    message: "Failed to read error response body".to_string(),
                })?;
        return Err(AlienError::new(ErrorData::HttpResponseError {
            message: format!(
                "Request failed with HTTP {}: {}",
                status.as_u16(),
                status.canonical_reason().unwrap_or("Unknown error")
            ),
            url,
            http_status: status.as_u16(),
            http_request_text: request_body,
            http_response_text: Some(response_text),
        }));
    }

    Ok(())
}

/// Extension trait for `reqwest::RequestBuilder` to add JSON and XML response handling
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait RequestBuilderExt {
    /// Enable retries with an exponential back-off strategy.
    ///
    /// Example:
    /// ```ignore
    /// let obj: MyType = client
    ///     .get("https://api.example.com/obj")
    ///     .with_retry()                // <- enable retries
    ///     .send_json()                // <- deserialize JSON body
    ///     .await?;
    /// ```
    fn with_retry(self) -> RetriableRequestBuilder;

    /// Send the request and parse the response as JSON
    async fn send_json<T: DeserializeOwned + 'static>(self) -> Result<T>;

    /// Send the request and parse the response as XML
    async fn send_xml<T: DeserializeOwned + 'static>(self) -> Result<T>;

    /// Send the request without parsing the response body
    async fn send_no_response(self) -> Result<()>;

    /// Send the request and return the raw response for custom handling
    async fn send_raw(self) -> Result<reqwest::Response>;
}

/// A `reqwest::RequestBuilder` wrapper that automatically retries failed
/// requests using an exponential back-off strategy powered by the `backon`
/// crate. Use [`RequestBuilderExt::with_retry`] to construct one.
pub struct RetriableRequestBuilder {
    inner: reqwest::RequestBuilder,
    backoff: ExponentialBuilder,
}

impl RetriableRequestBuilder {
    /// Overrides the default back-off settings.
    pub fn backoff(mut self, backoff: ExponentialBuilder) -> Self {
        self.backoff = backoff;
        self
    }

    /// Determine if a given error is retry-able using the retryable field.
    fn is_retryable_error(e: &AlienError<ErrorData>) -> bool {
        e.retryable
    }

    /// Creates a default exponential back-off (max 3 attempts, up to 20s).
    fn default_backoff() -> ExponentialBuilder {
        ExponentialBuilder::default()
            .with_max_times(3)
            .with_max_delay(Duration::from_secs(20))
            .with_jitter()
    }

    /// Execute the request, applying retries, and parse the body as JSON.
    pub async fn send_json<T: DeserializeOwned + Send + 'static>(self) -> Result<T> {
        let backoff = self.backoff;
        let builder = self.inner;

        let retryable = move || {
            let attempt_builder = builder.try_clone();
            async move {
                let attempt_builder = attempt_builder.ok_or_else(|| {
                    AlienError::new(ErrorData::GenericError {
                        message: "Request retry preparation failed".into(),
                    })
                })?;

                let (client, request, body_string) = build_and_extract_body(attempt_builder)?;
                let new_builder = reqwest::RequestBuilder::from_parts(client, request);

                #[cfg(target_arch = "wasm32")]
                {
                    let resp = new_builder.send().await.into_alien_error().context(
                        ErrorData::HttpRequestFailed {
                            message: "Network error during HTTP request".to_string(),
                        },
                    )?;
                    handle_json_response(resp, body_string).await
                }
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let resp = new_builder.send().await.into_alien_error().context(
                        ErrorData::HttpRequestFailed {
                            message: "Network error during HTTP request".to_string(),
                        },
                    )?;
                    handle_json_response(resp, body_string).await
                }
            }
        };

        retryable
            .retry(backoff)
            .when(Self::is_retryable_error)
            .await
    }

    /// Execute the request, applying retries, and parse the body as XML.
    pub async fn send_xml<T: DeserializeOwned + Send + 'static>(self) -> Result<T> {
        let backoff = self.backoff;
        let builder = self.inner;

        let retryable = move || {
            let attempt_builder = builder.try_clone();
            async move {
                let attempt_builder = attempt_builder.ok_or_else(|| {
                    AlienError::new(ErrorData::GenericError {
                        message: "Request retry preparation failed".into(),
                    })
                })?;

                let (client, request, body_string) = build_and_extract_body(attempt_builder)?;
                let new_builder = reqwest::RequestBuilder::from_parts(client, request);

                #[cfg(target_arch = "wasm32")]
                {
                    let resp = new_builder.send().await.into_alien_error().context(
                        ErrorData::HttpRequestFailed {
                            message: "Network error during HTTP request".to_string(),
                        },
                    )?;
                    handle_xml_response(resp, body_string).await
                }
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let resp = new_builder.send().await.into_alien_error().context(
                        ErrorData::HttpRequestFailed {
                            message: "Network error during HTTP request".to_string(),
                        },
                    )?;
                    handle_xml_response(resp, body_string).await
                }
            }
        };

        retryable
            .retry(backoff)
            .when(Self::is_retryable_error)
            .await
    }

    /// Execute the request, applying retries, without parsing the response body.
    pub async fn send_no_response(self) -> Result<()> {
        let backoff = self.backoff;
        let builder = self.inner;

        let retryable = move || {
            let attempt_builder = builder.try_clone();
            async move {
                let attempt_builder = attempt_builder.ok_or_else(|| {
                    AlienError::new(ErrorData::GenericError {
                        message: "Request retry preparation failed".into(),
                    })
                })?;

                let (client, request, body_string) = build_and_extract_body(attempt_builder)?;
                let new_builder = reqwest::RequestBuilder::from_parts(client, request);

                #[cfg(target_arch = "wasm32")]
                {
                    let resp = new_builder.send().await.into_alien_error().context(
                        ErrorData::HttpRequestFailed {
                            message: "Network error during HTTP request".to_string(),
                        },
                    )?;
                    handle_no_response(resp, body_string).await
                }
                #[cfg(not(target_arch = "wasm32"))]
                {
                    let resp = new_builder.send().await.into_alien_error().context(
                        ErrorData::HttpRequestFailed {
                            message: "Network error during HTTP request".to_string(),
                        },
                    )?;
                    handle_no_response(resp, body_string).await
                }
            }
        };

        retryable
            .retry(backoff)
            .when(Self::is_retryable_error)
            .await
    }

    /// Execute the request, applying retries, and return the raw response
    pub async fn send_raw(self) -> Result<reqwest::Response> {
        let backoff = self.backoff;
        let builder = self.inner;

        let retryable = move || {
            let attempt_builder = builder.try_clone();
            async move {
                let attempt_builder = attempt_builder.ok_or_else(|| {
                    AlienError::new(ErrorData::GenericError {
                        message: "Request retry preparation failed".into(),
                    })
                })?;

                let (client, request, _body_string) = build_and_extract_body(attempt_builder)?;
                let new_builder = reqwest::RequestBuilder::from_parts(client, request);

                #[cfg(target_arch = "wasm32")]
                {
                    new_builder.send().await.into_alien_error().context(
                        ErrorData::HttpRequestFailed {
                            message: "Network error during HTTP request".to_string(),
                        },
                    )
                }
                #[cfg(not(target_arch = "wasm32"))]
                {
                    new_builder.send().await.into_alien_error().context(
                        ErrorData::HttpRequestFailed {
                            message: "Network error during HTTP request".to_string(),
                        },
                    )
                }
            }
        };

        retryable
            .retry(backoff)
            .when(Self::is_retryable_error)
            .await
    }
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl RequestBuilderExt for reqwest::RequestBuilder {
    fn with_retry(self) -> RetriableRequestBuilder {
        RetriableRequestBuilder {
            inner: self,
            backoff: RetriableRequestBuilder::default_backoff(),
        }
    }

    async fn send_json<T: DeserializeOwned + 'static>(self) -> Result<T> {
        let (client, request, body_string) = build_and_extract_body(self)?;
        let builder = reqwest::RequestBuilder::from_parts(client, request);

        #[cfg(target_arch = "wasm32")]
        {
            let resp =
                builder
                    .send()
                    .await
                    .into_alien_error()
                    .context(ErrorData::HttpRequestFailed {
                        message: "Network error during HTTP request".to_string(),
                    })?;
            handle_json_response(resp, body_string).await
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let resp =
                builder
                    .send()
                    .await
                    .into_alien_error()
                    .context(ErrorData::HttpRequestFailed {
                        message: "Network error during HTTP request".to_string(),
                    })?;
            handle_json_response(resp, body_string).await
        }
    }

    async fn send_xml<T: DeserializeOwned + 'static>(self) -> Result<T> {
        let (client, request, body_string) = build_and_extract_body(self)?;
        let builder = reqwest::RequestBuilder::from_parts(client, request);

        #[cfg(target_arch = "wasm32")]
        {
            let resp =
                builder
                    .send()
                    .await
                    .into_alien_error()
                    .context(ErrorData::HttpRequestFailed {
                        message: "Network error during HTTP request".to_string(),
                    })?;
            handle_xml_response(resp, body_string).await
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let resp =
                builder
                    .send()
                    .await
                    .into_alien_error()
                    .context(ErrorData::HttpRequestFailed {
                        message: "Network error during HTTP request".to_string(),
                    })?;
            handle_xml_response(resp, body_string).await
        }
    }

    async fn send_no_response(self) -> Result<()> {
        let (client, request, body_string) = build_and_extract_body(self)?;
        let builder = reqwest::RequestBuilder::from_parts(client, request);

        #[cfg(target_arch = "wasm32")]
        {
            let resp =
                builder
                    .send()
                    .await
                    .into_alien_error()
                    .context(ErrorData::HttpRequestFailed {
                        message: "Network error during HTTP request".to_string(),
                    })?;
            handle_no_response(resp, body_string).await
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            let resp =
                builder
                    .send()
                    .await
                    .into_alien_error()
                    .context(ErrorData::HttpRequestFailed {
                        message: "Network error during HTTP request".to_string(),
                    })?;
            handle_no_response(resp, body_string).await
        }
    }

    async fn send_raw(self) -> Result<reqwest::Response> {
        let (client, request, _body_string) = build_and_extract_body(self)?;
        let builder = reqwest::RequestBuilder::from_parts(client, request);

        #[cfg(target_arch = "wasm32")]
        {
            builder
                .send()
                .await
                .into_alien_error()
                .context(ErrorData::HttpRequestFailed {
                    message: "Network error during HTTP request".to_string(),
                })
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            builder
                .send()
                .await
                .into_alien_error()
                .context(ErrorData::HttpRequestFailed {
                    message: "Network error during HTTP request".to_string(),
                })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alien_error::ContextError;

    const SECRET: &str = "Sup3rSecret-MasterPassword!";

    /// An `HttpResponseError` as the transport produces it for a failed create: its captured request
    /// body carries the master password, in both the typed payload and the derived `context` snapshot.
    fn http_error_with_secret_body() -> AlienError<ErrorData> {
        AlienError::new(ErrorData::HttpResponseError {
            message: "Request failed with HTTP 409: Conflict".to_string(),
            url: "https://rds.amazonaws.com/".to_string(),
            http_status: 409,
            http_request_text: Some(format!(
                "Action=CreateDBCluster&MasterUserPassword={SECRET}&Engine=aurora-postgresql"
            )),
            http_response_text: Some(
                "<Error><Code>DBClusterAlreadyExists</Code></Error>".to_string(),
            ),
        })
    }

    /// AWS path: redaction runs while the HTTP error is still the head. The secret must not survive in
    /// any serialized field — typed payload or `context` — while diagnostics are kept.
    #[test]
    fn redacts_request_body_when_http_error_is_head() {
        // Precondition: the unredacted error genuinely carries the secret, so this test can fail.
        let raw = serde_json::to_string(&http_error_with_secret_body()).unwrap();
        assert!(raw.contains(SECRET), "fixture should carry the secret");

        let err = redact_request_body::<()>(Err(http_error_with_secret_body())).unwrap_err();
        let json = serde_json::to_string(&err).expect("serialize redacted error");
        assert!(!json.contains(SECRET), "request body leaked: {json}");
        // Non-secret diagnostics are retained.
        assert!(json.contains("409"), "status dropped: {json}");
        assert!(
            json.contains("DBClusterAlreadyExists"),
            "response text dropped: {json}"
        );
    }

    /// GCP/Azure path: the transport maps the HTTP error to a non-internal head before redaction runs,
    /// so the body now lives only in the `source` chain's `context`. The non-internal head does NOT
    /// sanitize its source by itself (asserted as a precondition), so the whole-chain walk is
    /// load-bearing here.
    #[test]
    fn redacts_request_body_when_http_error_is_wrapped_in_source() {
        let wrapped = http_error_with_secret_body().context(ErrorData::RemoteResourceConflict {
            resource_type: "DBCluster".to_string(),
            resource_name: "stack-db".to_string(),
            message: "already exists".to_string(),
        });
        let before = serde_json::to_string(&wrapped).unwrap();
        assert!(
            before.contains(SECRET),
            "precondition: a non-internal head must NOT sanitize its source on its own"
        );

        let err = redact_request_body::<()>(Err(wrapped)).unwrap_err();
        let json = serde_json::to_string(&err).expect("serialize redacted error");
        assert!(
            !json.contains(SECRET),
            "request body leaked through source chain: {json}"
        );
        // The chain and its non-secret diagnostics are otherwise intact.
        assert!(
            json.contains("REMOTE_RESOURCE_CONFLICT"),
            "head dropped: {json}"
        );
        assert!(
            json.contains("DBClusterAlreadyExists"),
            "response text dropped: {json}"
        );
    }
}