delopay 0.4.0

Official Rust SDK for the DeloPay payments API
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! The hyper-backed [`Transport`] implementation.
//!
//! Deliberately named `hyper_backend` rather than `hyper`: a module called
//! `hyper` would shadow the `hyper` crate inside this crate's paths, exactly
//! as [`crate::core`] shadows the built-in `core`.
//!
//! Everything the previous reqwest backend got for free — user agent,
//! per-request timeout, query-string serialization — is done explicitly here.
//! That is the point: it is a handful of lines, and it removes `url`, `idna`
//! and the ICU4X stack that reqwest pulled in only to normalize IDNA hostnames
//! this SDK never sends.

use std::error::Error as StdError;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use bytes::Bytes;
use http::header::{CONTENT_TYPE, USER_AGENT};
use http_body_util::{BodyExt, Full, Limited};
use hyper::Request;
use hyper_rustls::{ConfigBuilderExt, HttpsConnector};
use hyper_util::client::legacy::Client;
use hyper_util::client::legacy::connect::HttpConnector;
use hyper_util::client::legacy::connect::proxy::Tunnel;
use hyper_util::rt::TokioExecutor;

use crate::http::proxy::{ProxyConfigError, ProxySetup};
use crate::http::transport::{
    HttpMethod, RawRequest, RawResponse, Transport, TransportError, TransportErrorKind,
};

/// Hard cap on how many response bytes are buffered, in bytes (10 MiB).
///
/// Neither reqwest nor the previous backend bounded this: `resp.bytes()` would
/// happily buffer whatever the peer sent, so a compromised or malfunctioning
/// endpoint could drive the SDK to OOM. Every DeloPay response is a small JSON
/// document — the largest realistic payload is a maximum-page list envelope,
/// which is orders of magnitude below this — so 10 MiB is far above any
/// legitimate response while still bounding memory per in-flight request.
const MAX_RESPONSE_BYTES: usize = 10 * 1024 * 1024;

type DirectClient = Client<HttpsConnector<HttpConnector>, Full<Bytes>>;
type ProxiedClient = Client<HttpsConnector<Tunnel<HttpConnector>>, Full<Bytes>>;

/// The connector stack, chosen once at construction.
///
/// Two concrete `Client`s rather than one client over a boxed/`Service`-based
/// dispatcher: the proxy decision is fixed for the life of a client (see
/// [`crate::http::proxy`]), so nothing has to be decided per request, and a
/// `match` here is far less machinery than a hand-written `Service<Uri>`.
enum Backend {
    Direct(DirectClient),
    Proxied(ProxiedClient),
    /// A proxy was configured but is unusable. Kept as a variant, rather than
    /// degrading to `Direct`, so the failure is loud: see the failure-policy
    /// note in [`crate::http::proxy`].
    Misconfigured(ProxyConfigError),
}

pub(crate) struct HyperTransport {
    backend: Backend,
    /// `host:port` of the proxy in use, for `Debug` only. Never userinfo.
    proxy: Option<Box<str>>,
    timeout: Duration,
    user_agent: &'static str,
}

// Hand-written: `Client`'s own `Debug` is opaque anyway, and the fields worth
// seeing are the ones this type adds.
//
// Security-relevant: a proxy URL can embed `http://user:pass@host:3128`. Only
// the pre-sanitized `proxy` string (host and port) is printed — never the
// userinfo, and never the `Proxy-Authorization` header value, which is not
// stored on this type at all (it lives inside the `Tunnel` connector).
impl fmt::Debug for HyperTransport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let proxy: &dyn fmt::Debug = match (&self.backend, &self.proxy) {
            (Backend::Misconfigured(_), _) => &"<invalid>",
            (_, Some(host_port)) => host_port,
            (_, None) => &Option::<&str>::None,
        };
        f.debug_struct("HyperTransport")
            .field("timeout", &self.timeout)
            .field("user_agent", &self.user_agent)
            .field("proxy", proxy)
            .finish_non_exhaustive()
    }
}

/// The TLS configuration, built identically for the direct and proxied paths.
///
/// Shared deliberately: the explicit `ring` provider and `with_webpki_roots()`
/// must not drift between the two, or routing through a proxy would silently
/// change the SDK's trust anchors or crypto backend.
fn tls_config() -> rustls::ClientConfig {
    // The crypto provider is passed explicitly rather than relying on
    // `CryptoProvider::install_default()`. Installing a default mutates
    // process-global state, which a library must never do: it would fight
    // whatever provider the consuming application chose, and it fails
    // outright if one is already installed. Being explicit also pins the
    // provider to `ring` — reqwest silently changed its default provider
    // between minor versions, which is part of why this backend exists.
    rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
        .with_safe_default_protocol_versions()
        .expect("the ring provider supports rustls' default protocol versions")
        .with_webpki_roots()
        .with_no_client_auth()
}

impl HyperTransport {
    pub(crate) fn new(timeout: Duration, user_agent: &'static str, proxy: ProxySetup) -> Self {
        let (backend, proxy_display) = match proxy {
            ProxySetup::Direct => {
                // `https_or_http` (not `https_only`): the integration suite
                // talks plain HTTP to a local mock server, and `base_url`
                // overrides are documented as accepting a local dev server.
                let https = hyper_rustls::HttpsConnectorBuilder::new()
                    .with_tls_config(tls_config())
                    .https_or_http()
                    .enable_http1()
                    .build();
                (
                    Backend::Direct(Client::builder(TokioExecutor::new()).build(https)),
                    None,
                )
            }
            ProxySetup::Tunnel { uri, auth, display } => {
                // The tunnel sits *under* TLS: `Tunnel` opens a TCP connection
                // to the proxy and issues `CONNECT host:port`, then the rustls
                // layer above completes the handshake with the origin through
                // it. The proxy therefore never sees plaintext for an https
                // destination, and certificates are still validated against the
                // origin's name, not the proxy's.
                let mut tunnel = Tunnel::new(uri, HttpConnector::new());
                if let Some(auth) = auth {
                    // `with_auth` marks the header value sensitive, so hyper
                    // will not print it in its own diagnostics either.
                    tunnel = tunnel.with_auth(auth);
                }
                let https = hyper_rustls::HttpsConnectorBuilder::new()
                    .with_tls_config(tls_config())
                    .https_or_http()
                    .enable_http1()
                    .wrap_connector(tunnel);
                (
                    Backend::Proxied(Client::builder(TokioExecutor::new()).build(https)),
                    Some(display),
                )
            }
            ProxySetup::Invalid(err) => (Backend::Misconfigured(err), None),
        };

        Self {
            backend,
            proxy: proxy_display,
            timeout,
            user_agent,
        }
    }

    /// Build the wire request. Fallible only through URI/header validation,
    /// which is request construction, hence `TransportErrorKind::Request`.
    fn build(&self, req: &RawRequest<'_>) -> Result<Request<Full<Bytes>>, TransportError> {
        let url = append_query(req.url, req.query);

        let mut builder = Request::builder()
            .method(method_of(req.method))
            .uri(url)
            // reqwest set this via `ClientBuilder::user_agent`; hyper sends no
            // user agent at all unless told to, so it is set per request here.
            .header(USER_AGENT, self.user_agent);

        for (k, v) in req.headers {
            builder = builder.header(*k, *v);
        }

        let body = match req.body {
            Some(bytes) => {
                builder =
                    builder.header(CONTENT_TYPE, req.content_type.unwrap_or("application/json"));
                Full::new(Bytes::copy_from_slice(bytes))
            }
            None => Full::new(Bytes::new()),
        };

        builder.body(body).map_err(|e| TransportError {
            kind: TransportErrorKind::Request,
            source: Box::new(e),
        })
    }
}

fn method_of(m: HttpMethod) -> http::Method {
    match m {
        HttpMethod::Get => http::Method::GET,
        HttpMethod::Post => http::Method::POST,
        HttpMethod::Put => http::Method::PUT,
        HttpMethod::Patch => http::Method::PATCH,
        HttpMethod::Delete => http::Method::DELETE,
    }
}

/// Percent-encode one byte string for `application/x-www-form-urlencoded`.
///
/// This is **not** [`crate::core::encoding::encode_segment`], which encodes a
/// URL *path* segment: that one preserves `~` and percent-encodes spaces as
/// `%20`, both wrong here. The form-urlencoded serializer keeps only
/// `A-Z a-z 0-9 * - . _`, writes a space as `+`, and percent-encodes every
/// other byte — matching what `serde_urlencoded` (and therefore the previous
/// `reqwest` `.query()` call) put on the wire.
fn encode_form_component(s: &str, out: &mut String) {
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'*' | b'-' | b'.' | b'_' => {
                out.push(b as char);
            }
            b' ' => out.push('+'),
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
}

/// Append `query` to `url` as a query string, mirroring `reqwest`'s
/// `RequestBuilder::query`: an empty parameter list leaves the URL untouched,
/// and an existing query string is extended rather than replaced.
fn append_query(url: &str, query: &[(&str, String)]) -> String {
    if query.is_empty() {
        return url.to_string();
    }
    let mut out = String::with_capacity(url.len() + query.len() * 16);
    out.push_str(url);
    out.push(if url.contains('?') { '&' } else { '?' });
    for (i, (k, v)) in query.iter().enumerate() {
        if i > 0 {
            out.push('&');
        }
        encode_form_component(k, &mut out);
        out.push('=');
        encode_form_component(v, &mut out);
    }
    out
}

/// The response body exceeded [`MAX_RESPONSE_BYTES`].
#[derive(Debug)]
struct ResponseTooLarge {
    limit: usize,
}

impl fmt::Display for ResponseTooLarge {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "response body exceeded the {}-byte client-side limit",
            self.limit
        )
    }
}

impl StdError for ResponseTooLarge {}

/// Walk an error's source chain looking for the underlying [`hyper::Error`].
///
/// `hyper_util`'s legacy client only exposes `is_connect()`; the protocol-level
/// detail lives one or two links down the chain.
fn hyper_error_of<'a>(err: &'a (dyn StdError + 'static)) -> Option<&'a hyper::Error> {
    let mut cursor = err.source();
    while let Some(e) = cursor {
        if let Some(h) = e.downcast_ref::<hyper::Error>() {
            return Some(h);
        }
        cursor = e.source();
    }
    None
}

fn classify(err: &hyper_util::client::legacy::Error) -> TransportErrorKind {
    // No connection could be established: always safe to retry an idempotent
    // request, because nothing reached the server.
    if err.is_connect() {
        return TransportErrorKind::Connect;
    }
    if let Some(h) = hyper_error_of(err) {
        if h.is_timeout() {
            return TransportErrorKind::Timeout;
        }
        // Protocol-level failures while issuing the request or reading the
        // status line. `reqwest` reported these as `is_request()`, so they map
        // to `Request` to keep the retry classification identical.
        if h.is_parse() || h.is_incomplete_message() || h.is_canceled() || h.is_closed() {
            return TransportErrorKind::Request;
        }
    }
    TransportErrorKind::Other
}

impl Transport for HyperTransport {
    fn execute<'a>(
        &'a self,
        req: RawRequest<'a>,
    ) -> std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<RawResponse, TransportError>> + Send + 'a>,
    > {
        // A proxy was asked for and cannot be used. Fail here, before anything
        // is sent, rather than falling back to a direct connection: the
        // operator may be relying on that proxy for egress control.
        // `TransportErrorKind::Other` is not retriable, which is right — the
        // configuration will not fix itself between attempts.
        if let Backend::Misconfigured(err) = &self.backend {
            let err = err.clone();
            return Box::pin(async move {
                Err(TransportError {
                    kind: TransportErrorKind::Other,
                    source: Box::new(err),
                })
            });
        }

        // Build eagerly so the returned future borrows nothing from `req`.
        let built = self.build(&req);

        Box::pin(async move {
            let built = built?;

            let exchange = async {
                let sent = match &self.backend {
                    Backend::Direct(client) => client.request(built).await,
                    Backend::Proxied(client) => client.request(built).await,
                    // Already returned above, before the request was even
                    // built. Repeated rather than `unreachable!` so a future
                    // refactor that loses the early return degrades to the
                    // correct error instead of panicking inside a payment call.
                    Backend::Misconfigured(err) => {
                        return Err(TransportError {
                            kind: TransportErrorKind::Other,
                            source: Box::new(err.clone()),
                        });
                    }
                };
                let resp = sent.map_err(|e| TransportError {
                    kind: classify(&e),
                    source: Box::new(e),
                })?;

                let status = resp.status().as_u16();
                let headers = resp
                    .headers()
                    .iter()
                    .filter_map(|(k, v)| v.to_str().ok().map(|v| (k.as_str().into(), v.into())))
                    .collect();

                let limited = Limited::new(resp.into_body(), MAX_RESPONSE_BYTES);
                let body = match limited.collect().await {
                    Ok(collected) => collected.to_bytes().to_vec(),
                    // Over the cap: a deterministic, client-side rejection, not
                    // a flaky read, so it is reported on every status rather
                    // than degrading to an empty body below. `Body` (not
                    // `Other`) because it is a response-body failure and, like
                    // every body failure, must never be retried — a replay
                    // would re-issue a request whose first attempt already took
                    // effect and would deterministically blow the same cap.
                    Err(e)
                        if e.downcast_ref::<http_body_util::LengthLimitError>()
                            .is_some() =>
                    {
                        return Err(TransportError {
                            kind: TransportErrorKind::Body,
                            source: Box::new(ResponseTooLarge {
                                limit: MAX_RESPONSE_BYTES,
                            }),
                        });
                    }
                    // A 2xx whose body could not be read is a hard failure:
                    // there is nothing to deserialize, and `Body` is
                    // non-retriable so the successful request is not replayed.
                    Err(e) if (200..300).contains(&status) => {
                        return Err(TransportError {
                            kind: TransportErrorKind::Body,
                            source: e,
                        });
                    }
                    // Non-2xx: tolerate an unreadable body, as before. The
                    // status alone still yields a correctly typed API error.
                    Err(_) => Vec::new(),
                };

                Ok(RawResponse::new(status, headers, body))
            };

            // `reqwest::ClientBuilder::timeout` bounded the whole request,
            // including reading the body. `hyper-util` has no equivalent, so
            // the same envelope is imposed here.
            match tokio::time::timeout(self.timeout, exchange).await {
                Ok(result) => result,
                Err(elapsed) => Err(TransportError {
                    kind: TransportErrorKind::Timeout,
                    source: Box::new(elapsed),
                }),
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::proxy::{ProxyMode, resolve};

    fn direct_transport() -> HyperTransport {
        HyperTransport::new(
            Duration::from_secs(1),
            "delopay-rust/test",
            ProxySetup::Direct,
        )
    }

    fn encode(s: &str) -> String {
        let mut out = String::new();
        encode_form_component(s, &mut out);
        out
    }

    #[test]
    fn form_encoding_passes_unreserved_bytes() {
        assert_eq!(encode("abcXYZ019*-._"), "abcXYZ019*-._");
    }

    #[test]
    fn form_encoding_writes_space_as_plus() {
        // `%20` would also be accepted by most servers, but `+` is what
        // `serde_urlencoded` — and therefore the previous reqwest backend —
        // put on the wire, so this pins the byte-for-byte behavior.
        assert_eq!(encode("a b"), "a+b");
    }

    #[test]
    fn form_encoding_escapes_separators_and_plus() {
        // Without these three, a value containing `&` or `=` could forge extra
        // parameters, and a literal `+` would decode back as a space.
        assert_eq!(encode("a&b"), "a%26b");
        assert_eq!(encode("a=b"), "a%3Db");
        assert_eq!(encode("a+b"), "a%2Bb");
    }

    #[test]
    fn form_encoding_escapes_non_ascii_as_utf8_bytes() {
        assert_eq!(encode("é"), "%C3%A9");
        assert_eq!(encode("日"), "%E6%97%A5");
    }

    #[test]
    fn form_encoding_escapes_tilde_unlike_path_segments() {
        // The contrast with `core::encoding::encode_segment`, which keeps `~`
        // because it is unreserved in a path. In form-urlencoded it is not.
        assert_eq!(encode("~"), "%7E");
        assert_eq!(crate::core::encoding::encode_segment("~"), "~");
    }

    #[test]
    fn append_query_leaves_url_untouched_when_empty() {
        assert_eq!(
            append_query("https://api.test/payments", &[]),
            "https://api.test/payments"
        );
    }

    #[test]
    fn append_query_joins_pairs_with_ampersands() {
        assert_eq!(
            append_query(
                "https://api.test/payments/list",
                &[("limit", "10".to_string()), ("status", "succeeded".into())],
            ),
            "https://api.test/payments/list?limit=10&status=succeeded"
        );
    }

    #[test]
    fn append_query_extends_an_existing_query_string() {
        assert_eq!(
            append_query("https://api.test/x?a=1", &[("b", "2".to_string())]),
            "https://api.test/x?a=1&b=2"
        );
    }

    #[test]
    fn append_query_encodes_keys_and_values() {
        assert_eq!(
            append_query(
                "https://api.test/x",
                &[("a key", "a&b=c".to_string()), ("é", "d e".into())],
            ),
            "https://api.test/x?a+key=a%26b%3Dc&%C3%A9=d+e"
        );
    }

    #[test]
    fn built_request_carries_user_agent_and_no_content_type_without_a_body() {
        let transport = direct_transport();
        let headers = [("api-key", "prd_x")];
        let req = transport
            .build(&RawRequest {
                method: HttpMethod::Get,
                url: "https://api.test/payments",
                headers: &headers,
                query: &[],
                body: None,
                content_type: None,
            })
            .unwrap();

        assert_eq!(req.method(), http::Method::GET);
        assert_eq!(req.uri(), "https://api.test/payments");
        assert_eq!(req.headers()[USER_AGENT], "delopay-rust/test");
        assert_eq!(req.headers()["api-key"], "prd_x");
        assert!(
            !req.headers().contains_key(CONTENT_TYPE),
            "a body-less request must not claim a JSON content type"
        );
    }

    #[test]
    fn built_request_with_a_body_sets_json_content_type_and_query() {
        let transport = direct_transport();
        let req = transport
            .build(&RawRequest {
                method: HttpMethod::Post,
                url: "https://api.test/payments",
                headers: &[],
                query: &[("limit", "10".to_string())],
                body: Some(b"{\"amount\":1999}"),
                content_type: None,
            })
            .unwrap();

        assert_eq!(req.method(), http::Method::POST);
        assert_eq!(req.uri(), "https://api.test/payments?limit=10");
        assert_eq!(req.headers()[CONTENT_TYPE], "application/json");
    }

    #[test]
    fn an_explicit_content_type_overrides_the_json_default() {
        // The multipart upload path depends on this: a body labelled
        // `application/json` when it is actually form-data is unparseable
        // server-side, and the boundary lives only in this header.
        let transport = direct_transport();
        let req = transport
            .build(&RawRequest {
                method: HttpMethod::Post,
                url: "https://api.test/shops/m/s/logo",
                headers: &[],
                query: &[],
                body: Some(b"--bound\r\n"),
                content_type: Some("multipart/form-data; boundary=bound"),
            })
            .unwrap();

        assert_eq!(
            req.headers()[CONTENT_TYPE],
            "multipart/form-data; boundary=bound"
        );
        // Exactly one content-type header -- appending rather than replacing
        // would send both, and servers pick unpredictably.
        assert_eq!(req.headers().get_all(CONTENT_TYPE).iter().count(), 1);
    }

    #[test]
    fn built_request_maps_put_to_the_put_verb() {
        // `method_of` is the only place the SDK's `Put` meets hyper's `PUT`; a
        // mutation mapping it to POST would silently change wire semantics.
        let transport = direct_transport();
        let req = transport
            .build(&RawRequest {
                method: HttpMethod::Put,
                url: "https://api.test/payouts/po_1",
                headers: &[],
                query: &[],
                body: Some(b"{}"),
                content_type: None,
            })
            .unwrap();
        assert_eq!(req.method(), http::Method::PUT);
    }

    #[test]
    fn a_malformed_url_is_a_request_error_not_a_panic() {
        let transport = direct_transport();
        let err = transport
            .build(&RawRequest {
                method: HttpMethod::Get,
                url: "not a url",
                headers: &[],
                query: &[],
                body: None,
                content_type: None,
            })
            .unwrap_err();
        assert_eq!(err.kind, TransportErrorKind::Request);
        assert!(
            err.is_retriable(),
            "`Request` stays retriable, matching how reqwest classified it"
        );
    }

    #[test]
    fn response_too_large_error_names_the_limit() {
        let err = ResponseTooLarge {
            limit: MAX_RESPONSE_BYTES,
        };
        assert!(err.to_string().contains(&MAX_RESPONSE_BYTES.to_string()));
    }

    fn proxied_transport(proxy_url: &str) -> HyperTransport {
        HyperTransport::new(
            Duration::from_secs(1),
            "delopay-rust/test",
            resolve(
                &ProxyMode::Explicit(proxy_url.to_string()),
                "https://api.delopay.net",
            ),
        )
    }

    #[test]
    fn transport_debug_never_reveals_proxy_credentials() {
        // A proxy URL routinely carries `user:pass@`. `HyperTransport` is
        // reachable from a `{:?}` on anything holding it, so the credentials
        // must not be in that rendering — the same rule
        // `raw_request_debug_redacts_api_key` enforces for the API key.
        let transport = proxied_transport("http://alice:hunter2@corp-egress:3128");
        let formatted = format!("{transport:?}");

        assert!(
            !formatted.contains("hunter2"),
            "Debug output must not contain the proxy password: {formatted}"
        );
        assert!(
            !formatted.contains("alice"),
            "Debug output must not contain the proxy username: {formatted}"
        );
        // The base64 of `alice:hunter2` — i.e. the `Proxy-Authorization` value
        // itself, which must not leak in any encoding either.
        assert!(
            !formatted.contains("YWxpY2U6aHVudGVyMg=="),
            "Debug output must not contain the Proxy-Authorization value: {formatted}"
        );
        assert!(
            formatted.contains("corp-egress:3128"),
            "the proxy host and port stay visible, so operators can see where \
             traffic is going: {formatted}"
        );
    }

    #[test]
    fn transport_debug_reports_no_proxy_when_direct() {
        // Companion to the test above: without it, a `Debug` impl that simply
        // never printed a proxy would still pass the redaction assertions.
        let formatted = format!("{:?}", direct_transport());
        assert!(
            formatted.contains("proxy: None"),
            "a direct transport must say so: {formatted}"
        );
    }

    #[tokio::test]
    async fn a_misconfigured_proxy_fails_every_request_instead_of_going_direct() {
        // The security-critical behavior: the caller explicitly asked for a
        // proxy and it cannot be used. Connecting straight to the origin would
        // bypass whatever egress control that proxy enforces, so the request
        // must fail. Note the URL is syntactically fine but names a scheme this
        // transport cannot speak — no network access is involved.
        let transport = HyperTransport::new(
            Duration::from_secs(1),
            "delopay-rust/test",
            resolve(
                &ProxyMode::Explicit("socks5://corp-egress:1080".into()),
                "https://api.delopay.net",
            ),
        );

        let err = transport
            .execute(RawRequest {
                method: HttpMethod::Get,
                url: "https://api.delopay.net/payments",
                headers: &[],
                query: &[],
                body: None,
                content_type: None,
            })
            .await
            .expect_err("a request through an unusable proxy must not succeed");

        assert_eq!(err.kind, TransportErrorKind::Other);
        assert!(
            !err.is_retriable(),
            "a configuration error will not fix itself between attempts"
        );
        assert!(err.source.to_string().contains("proxy"));
    }

    #[test]
    fn a_misconfigured_proxy_is_visible_in_debug_without_leaking_the_url() {
        let transport = HyperTransport::new(
            Duration::from_secs(1),
            "delopay-rust/test",
            resolve(
                &ProxyMode::Explicit("socks5://alice:hunter2@corp-egress:1080".into()),
                "https://api.delopay.net",
            ),
        );
        let formatted = format!("{transport:?}");
        assert!(formatted.contains("<invalid>"), "{formatted}");
        assert!(!formatted.contains("hunter2"), "{formatted}");
    }
}