delopay 0.3.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
//! Proxy resolution: deciding **once**, at [`build()`][crate::DelopayBuilder::build]
//! time, whether this client's traffic goes through an HTTP `CONNECT` proxy.
//!
//! Every request this SDK issues goes to `base_url`'s host (see
//! `Inner::send_raw`, which always builds `format!("{base_url}{path}")`), so the
//! proxy decision is stable for the life of the client. Resolving it once means
//! the transport can hold one concrete, pre-built connector instead of
//! dispatching per request.
//!
//! # Failure policy
//!
//! `build()` returns `Delopay`, not `Result<Delopay>`, and changing that would
//! be a breaking API change. So a proxy that is *configured but unusable* is
//! captured here as [`ProxySetup::Invalid`] and surfaced as a transport error
//! on **every** request. Falling back to a direct connection would be a
//! security failure: an operator who set `HTTPS_PROXY` (or called `.proxy()`)
//! may be relying on that proxy for egress control, and silently bypassing it
//! would send traffic somewhere they forbade.
//!
//! # Credentials
//!
//! A proxy URL may embed `http://user:pass@host:3128`. Nothing in this module
//! ever puts the userinfo — or the derived `Proxy-Authorization` value — into a
//! `Debug` rendering, a `Display` rendering, or an error message. The only
//! proxy text that escapes is the `display` field of [`ProxySetup::Tunnel`],
//! which is the authority with any userinfo stripped.

use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt;

use http::Uri;
use http::header::HeaderValue;
use hyper_util::client::proxy::matcher::{Intercept, Matcher};

/// How the builder was told to pick a proxy. Three states, not two booleans:
/// "read the environment", "use exactly this", and "never proxy" are mutually
/// exclusive, and a pair of `bool`s could encode nonsense combinations.
#[derive(Clone, Default)]
pub(crate) enum ProxyMode {
    /// Read `HTTPS_PROXY`/`HTTP_PROXY`/`ALL_PROXY`/`NO_PROXY` (the default).
    #[default]
    Env,
    /// Use this proxy URL, ignoring the environment entirely.
    Explicit(String),
    /// Never proxy, ignoring the environment entirely.
    Disabled,
}

// Hand-written: `Explicit` holds a URL that may embed `user:pass@`, and
// `DelopayBuilder`'s `Debug` prints this. Deriving would leak the credentials
// into any `{:?}` of a builder.
impl fmt::Debug for ProxyMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProxyMode::Env => f.write_str("Env"),
            ProxyMode::Explicit(_) => f.write_str("Explicit(<redacted>)"),
            ProxyMode::Disabled => f.write_str("Disabled"),
        }
    }
}

/// The resolved decision, handed to the transport at construction.
pub(crate) enum ProxySetup {
    /// Connect straight to the origin.
    Direct,
    /// Tunnel through an HTTP proxy with `CONNECT`.
    Tunnel {
        /// The proxy's own URI (`http://host:port/`), userinfo already stripped
        /// out into `auth` by `hyper_util`'s matcher.
        uri: Uri,
        /// A ready-made `Proxy-Authorization: Basic ...` value, if the proxy
        /// URL carried credentials.
        auth: Option<HeaderValue>,
        /// `host:port`, safe to print. Never contains userinfo.
        display: Box<str>,
    },
    /// A proxy was asked for but cannot be used. Every request must fail with
    /// this error rather than quietly going direct.
    Invalid(ProxyConfigError),
}

/// A proxy was configured but could not be turned into a usable connector.
///
/// The message is built only from a fixed vocabulary plus the URL *scheme*,
/// which `hyper_util`'s parser restricts to a known allow-list
/// (`http`/`https`/`socks4`/`socks4a`/`socks5`/`socks5h`). No user-supplied
/// host, userinfo or password can reach it.
#[derive(Debug, Clone)]
pub(crate) struct ProxyConfigError {
    detail: Cow<'static, str>,
}

impl ProxyConfigError {
    fn new(detail: impl Into<Cow<'static, str>>) -> Self {
        Self {
            detail: detail.into(),
        }
    }
}

impl fmt::Display for ProxyConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid proxy configuration: {}", self.detail)
    }
}

impl StdError for ProxyConfigError {}

/// The proxy-related environment, read once.
///
/// These are exactly the variables `hyper_util`'s `Matcher::from_env()` reads,
/// captured into a value so the decision logic below is a pure function of its
/// inputs. That matters for testing: Rust runs a binary's tests on parallel
/// threads, `std::env::set_var` is process-global (and `unsafe` in edition
/// 2024), so env-mutating tests interfere with each other and with the rest of
/// the suite. With the environment read here and nowhere else, every test can
/// drive `resolve_env` with a literal `EnvProxy` instead.
#[derive(Debug, Default, Clone)]
pub(crate) struct EnvProxy {
    pub all: String,
    pub http: String,
    pub https: String,
    pub no: String,
    /// `REQUEST_METHOD` is set: this process is a CGI script, where `HTTP_PROXY`
    /// is attacker-controlled (it comes from the client's `Proxy:` header).
    /// curl, `hyper_util` and everything else disable proxying entirely here.
    pub is_cgi: bool,
}

impl EnvProxy {
    fn from_env() -> Self {
        Self {
            all: first_env(&["ALL_PROXY", "all_proxy"]),
            http: first_env(&["HTTP_PROXY", "http_proxy"]),
            https: first_env(&["HTTPS_PROXY", "https_proxy"]),
            no: first_env(&["NO_PROXY", "no_proxy"]),
            is_cgi: std::env::var_os("REQUEST_METHOD").is_some(),
        }
    }

    /// Whether *some* proxy variable applies to a destination with this scheme.
    /// Mirrors `hyper_util`'s precedence: the scheme-specific variable, falling
    /// back to `ALL_PROXY`.
    fn configured_for(&self, scheme: Option<&str>) -> bool {
        let specific = match scheme {
            Some("https") => &self.https,
            Some("http") => &self.http,
            _ => return false,
        };
        !specific.is_empty() || !self.all.is_empty()
    }
}

fn first_env(names: &[&str]) -> String {
    for name in names {
        if let Ok(val) = std::env::var(name) {
            return val;
        }
    }
    String::new()
}

/// Resolve `mode` against the destination `base_url`.
pub(crate) fn resolve(mode: &ProxyMode, base_url: &str) -> ProxySetup {
    match mode {
        ProxyMode::Disabled => ProxySetup::Direct,
        ProxyMode::Explicit(url) => resolve_explicit(url, base_url),
        ProxyMode::Env => resolve_env(&EnvProxy::from_env(), base_url),
    }
}

/// `.proxy(url)`: use exactly this proxy. The environment — including
/// `NO_PROXY` — is not consulted, and anything unusable is an error, never a
/// silent direct connection.
fn resolve_explicit(proxy_url: &str, base_url: &str) -> ProxySetup {
    let Some(dst) = destination(base_url) else {
        return ProxySetup::Invalid(ProxyConfigError::new(
            "a proxy was requested but the API base URL is not an absolute \
             http:// or https:// URL, so no connection can be made through it",
        ));
    };

    match Matcher::builder().all(proxy_url).build().intercept(&dst) {
        Some(intercept) => from_intercept(&intercept),
        // `Matcher` reports every rejection the same way — `None`. Because the
        // caller named a proxy explicitly, `None` can only mean the value was
        // unusable, so it is an error rather than "no proxy".
        None => ProxySetup::Invalid(ProxyConfigError::new(
            "the proxy URL could not be parsed; expected something like \
             http://host:port or http://user:pass@host:port",
        )),
    }
}

/// Default mode: honour the environment, exactly as curl and `hyper_util` do.
fn resolve_env(env: &EnvProxy, base_url: &str) -> ProxySetup {
    if env.is_cgi {
        return ProxySetup::Direct;
    }

    let Some(dst) = destination(base_url) else {
        // Nothing to match against. Going direct is right: no proxy was
        // *requested* here, and a base URL this malformed fails at request
        // construction anyway, with a clearer error than anything we'd invent.
        return ProxySetup::Direct;
    };

    // `NO_PROXY` is checked first, before the proxy variables are validated at
    // all. An operator who excludes a host has said "do not proxy this" — that
    // must hold even when some other proxy variable is unparseable, otherwise a
    // stray newline in `HTTPS_PROXY` turns an explicit bypass into a total
    // outage. A placeholder proxy stands in so the only thing under test here
    // is the exclusion list.
    let excluded = Matcher::builder()
        .all("http://placeholder.invalid:1")
        .no(env.no.as_str())
        .build()
        .intercept(&dst)
        .is_none();
    if excluded {
        return ProxySetup::Direct;
    }

    let matcher = Matcher::builder()
        .all(env.all.as_str())
        .http(env.http.as_str())
        .https(env.https.as_str())
        .no(env.no.as_str())
        .build();

    if let Some(intercept) = matcher.intercept(&dst) {
        return from_intercept(&intercept);
    }

    // No intercept. Three different things look identical from here, and they
    // do not deserve the same outcome:
    //
    //   1. no proxy variable is set at all      -> direct, obviously
    //   2. `NO_PROXY` excludes this host        -> direct, deliberately
    //   3. a variable is set but is garbage     -> must NOT go direct
    //
    // (1) is a plain lookup. (2) and (3) are separated by re-running the match
    // with the exclusion list dropped: if the proxy is usable, the `None` came
    // from `NO_PROXY` and the bypass was asked for.
    if !env.configured_for(dst.scheme_str()) {
        return ProxySetup::Direct;
    }

    let without_exclusions = Matcher::builder()
        .all(env.all.as_str())
        .http(env.http.as_str())
        .https(env.https.as_str())
        .build();

    if without_exclusions.intercept(&dst).is_some() {
        ProxySetup::Direct
    } else {
        ProxySetup::Invalid(ProxyConfigError::new(
            "a proxy environment variable is set but could not be parsed; \
             expected something like http://host:port",
        ))
    }
}

/// Parse the API base URL into the destination the matcher matches against.
fn destination(base_url: &str) -> Option<Uri> {
    let uri: Uri = base_url.parse().ok()?;
    // `Matcher::intercept` needs both to decide anything.
    uri.host()?;
    uri.scheme_str()?;
    Some(uri)
}

/// Turn a matched proxy into a connector recipe, rejecting schemes this
/// transport cannot actually speak.
fn from_intercept(intercept: &Intercept) -> ProxySetup {
    let uri = intercept.uri();

    match uri.scheme_str() {
        Some("http") => {}
        // A `https://` proxy needs TLS *to the proxy itself*, which would mean
        // a second TLS layer under the tunnel; SOCKS is a different protocol
        // entirely. Neither is wired up, and pretending otherwise would either
        // hang or silently misroute, so both are refused loudly.
        Some(other) => {
            return ProxySetup::Invalid(ProxyConfigError::new(format!(
                "proxy scheme `{other}` is not supported; only http:// proxies \
                 (HTTP CONNECT tunnelling) are"
            )));
        }
        None => {
            return ProxySetup::Invalid(ProxyConfigError::new(
                "the proxy URL has no scheme; expected http://host:port",
            ));
        }
    }

    ProxySetup::Tunnel {
        uri: uri.clone(),
        auth: intercept.basic_auth().cloned(),
        display: sanitized_authority(uri),
    }
}

/// The printable form of a proxy URI: `host:port`, never userinfo.
///
/// `hyper_util`'s parser already moves `user:pass@` out of the URI and into the
/// auth header, so this is belt-and-braces — but it is cheap, and it is the one
/// place a credential could otherwise reach a log line.
fn sanitized_authority(uri: &Uri) -> Box<str> {
    match uri.authority() {
        Some(authority) => {
            let s = authority.as_str();
            match s.split_once('@') {
                Some((_userinfo, host_port)) => host_port.into(),
                None => s.into(),
            }
        }
        None => "<unknown>".into(),
    }
}

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

    const HTTPS_DST: &str = "https://api.delopay.net";
    const HTTP_DST: &str = "http://api.delopay.net";

    /// The proxy `host:port` a setup resolved to, or `None` for a direct
    /// connection. Panics on `Invalid` so a test that expected a decision
    /// never silently reads one off a misconfiguration.
    fn proxy_of(setup: &ProxySetup) -> Option<&str> {
        match setup {
            ProxySetup::Direct => None,
            ProxySetup::Tunnel { display, .. } => Some(display),
            ProxySetup::Invalid(e) => panic!("expected a decision, got {e}"),
        }
    }

    fn env(https: &str, no: &str) -> EnvProxy {
        EnvProxy {
            https: https.to_string(),
            no: no.to_string(),
            ..EnvProxy::default()
        }
    }

    #[test]
    fn no_proxy_wins_over_an_unparseable_proxy_variable() {
        // A sourced env file leaves a stray newline in HTTPS_PROXY, and the
        // operator has explicitly excluded this host. The exclusion must hold:
        // previously the unparseable value was validated first, so every
        // request failed and a host the operator believed was exempt went
        // completely dark.
        let setup = resolve_env(
            &env(" http://corp-egress:3128\n", "api.delopay.net"),
            HTTPS_DST,
        );
        assert!(
            matches!(setup, ProxySetup::Direct),
            "NO_PROXY must bypass before the proxy value is validated"
        );
    }

    #[test]
    fn an_unparseable_proxy_variable_still_fails_when_the_host_is_not_excluded() {
        // The other half: with no exclusion covering this host, a garbage value
        // must NOT silently fall back to a direct connection.
        let setup = resolve_env(
            &env(" http://corp-egress:3128\n", "other.example"),
            HTTPS_DST,
        );
        assert!(
            matches!(setup, ProxySetup::Invalid(_)),
            "a garbage proxy value must fail closed, never fall back to direct"
        );
    }

    #[test]
    fn env_https_proxy_is_used_for_an_https_base_url() {
        let setup = resolve_env(&env("http://corp-egress:3128", ""), HTTPS_DST);
        assert_eq!(proxy_of(&setup), Some("corp-egress:3128"));
    }

    #[test]
    fn env_all_proxy_covers_both_schemes() {
        let e = EnvProxy {
            all: "http://corp-egress:3128".into(),
            ..EnvProxy::default()
        };
        assert_eq!(
            proxy_of(&resolve_env(&e, HTTPS_DST)),
            Some("corp-egress:3128")
        );
        assert_eq!(
            proxy_of(&resolve_env(&e, HTTP_DST)),
            Some("corp-egress:3128")
        );
    }

    #[test]
    fn env_http_proxy_does_not_capture_https_traffic() {
        // `HTTP_PROXY` names the proxy for *http* destinations only. Treating it
        // as a catch-all would route TLS traffic somewhere the operator never
        // nominated.
        let e = EnvProxy {
            http: "http://corp-egress:3128".into(),
            ..EnvProxy::default()
        };
        assert_eq!(proxy_of(&resolve_env(&e, HTTPS_DST)), None);
        assert_eq!(
            proxy_of(&resolve_env(&e, HTTP_DST)),
            Some("corp-egress:3128")
        );
    }

    #[test]
    fn no_proxy_exclusion_bypasses_the_proxy_for_a_matching_host() {
        let setup = resolve_env(&env("http://corp-egress:3128", "delopay.net"), HTTPS_DST);
        assert_eq!(
            proxy_of(&setup),
            None,
            "NO_PROXY listed the destination's domain, so it must go direct"
        );
    }

    #[test]
    fn no_proxy_exclusion_does_not_bypass_a_non_matching_host() {
        // The other half of the pair: without this, an implementation that
        // treated *any* non-empty `NO_PROXY` as "bypass everything" would still
        // pass the test above.
        let setup = resolve_env(&env("http://corp-egress:3128", "example.com"), HTTPS_DST);
        assert_eq!(proxy_of(&setup), Some("corp-egress:3128"));
    }

    #[test]
    fn no_environment_at_all_means_direct() {
        assert_eq!(
            proxy_of(&resolve_env(&EnvProxy::default(), HTTPS_DST)),
            None
        );
    }

    #[test]
    fn cgi_environment_disables_proxying() {
        let e = EnvProxy {
            https: "http://corp-egress:3128".into(),
            is_cgi: true,
            ..EnvProxy::default()
        };
        assert_eq!(proxy_of(&resolve_env(&e, HTTPS_DST)), None);
    }

    #[test]
    fn an_unparseable_env_proxy_is_an_error_not_a_direct_connection() {
        // The security-critical case: the operator asked for egress through a
        // proxy and fat-fingered it. Going direct would send traffic straight
        // past the control they configured.
        let setup = resolve_env(&env("::not a proxy::", ""), HTTPS_DST);
        assert!(
            matches!(setup, ProxySetup::Invalid(_)),
            "a set-but-broken proxy variable must not degrade to a direct connection"
        );
    }

    #[test]
    fn explicit_proxy_overrides_the_environment() {
        // `.proxy()` is resolved without consulting `EnvProxy` at all, which is
        // what makes it an override. Exercised through `resolve` (not
        // `resolve_explicit`) so the dispatch is covered too.
        let setup = resolve(
            &ProxyMode::Explicit("http://explicit-proxy:8080".into()),
            HTTPS_DST,
        );
        assert_eq!(proxy_of(&setup), Some("explicit-proxy:8080"));
    }

    #[test]
    fn explicit_proxy_ignores_no_proxy() {
        // An explicit `.proxy()` call is documented as ignoring the
        // environment; `NO_PROXY` is part of the environment.
        let setup = resolve_explicit("http://explicit-proxy:8080", HTTPS_DST);
        assert_eq!(proxy_of(&setup), Some("explicit-proxy:8080"));
    }

    #[test]
    fn no_proxy_mode_overrides_the_environment() {
        assert_eq!(proxy_of(&resolve(&ProxyMode::Disabled, HTTPS_DST)), None);
    }

    #[test]
    fn an_explicit_but_malformed_proxy_url_is_an_error_not_a_direct_connection() {
        let setup = resolve_explicit("not a url at all", HTTPS_DST);
        assert!(
            matches!(setup, ProxySetup::Invalid(_)),
            "an explicit proxy that cannot be used must never fall back to direct"
        );
    }

    #[test]
    fn a_socks_proxy_is_refused_rather_than_tunnelled_over() {
        // `hyper_util`'s matcher happily parses `socks5://`, but this transport
        // speaks only HTTP CONNECT. Accepting it would send a CONNECT request
        // to a SOCKS port.
        let setup = resolve_explicit("socks5://corp-egress:1080", HTTPS_DST);
        match setup {
            ProxySetup::Invalid(e) => assert!(e.to_string().contains("socks5")),
            _ => panic!("a socks proxy must be refused"),
        }
    }

    #[test]
    fn an_https_proxy_is_refused_rather_than_connected_to_in_cleartext() {
        let setup = resolve_explicit("https://corp-egress:3128", HTTPS_DST);
        assert!(matches!(setup, ProxySetup::Invalid(_)));
    }

    #[test]
    fn an_unusable_base_url_with_an_explicit_proxy_is_an_error() {
        let setup = resolve_explicit("http://corp-egress:3128", "not a url");
        assert!(matches!(setup, ProxySetup::Invalid(_)));
    }

    #[test]
    fn proxy_credentials_survive_as_auth_but_never_as_text() {
        let setup = resolve_explicit("http://alice:hunter2@corp-egress:3128", HTTPS_DST);
        match setup {
            ProxySetup::Tunnel { uri, auth, display } => {
                assert!(
                    auth.is_some(),
                    "credentials in the URL must become a Proxy-Authorization value"
                );
                assert_eq!(&*display, "corp-egress:3128");
                assert!(!uri.to_string().contains("hunter2"));
                assert!(!format!("{uri:?}").contains("alice"));
            }
            _ => panic!("expected a tunnel"),
        }
    }

    #[test]
    fn a_credential_free_proxy_carries_no_auth() {
        // Companion to the test above: without this, an implementation that
        // attached a bogus `Proxy-Authorization` to every request would pass.
        let setup = resolve_explicit("http://corp-egress:3128", HTTPS_DST);
        match setup {
            ProxySetup::Tunnel { auth, .. } => assert!(auth.is_none()),
            _ => panic!("expected a tunnel"),
        }
    }

    #[test]
    fn proxy_mode_debug_redacts_the_url() {
        let mode = ProxyMode::Explicit("http://alice:hunter2@corp-egress:3128".into());
        let formatted = format!("{mode:?}");
        assert!(
            !formatted.contains("hunter2") && !formatted.contains("alice"),
            "ProxyMode's Debug output must not contain proxy credentials: {formatted}"
        );
    }

    #[test]
    fn sanitized_authority_strips_userinfo() {
        // `hyper_util` strips it first, so drive the helper directly — this is
        // the guard that stays honest if that ever changes.
        let uri: Uri = "http://alice:hunter2@corp-egress:3128/".parse().unwrap();
        assert_eq!(&*sanitized_authority(&uri), "corp-egress:3128");
    }

    #[test]
    fn config_error_text_carries_no_credentials() {
        let setup = resolve_explicit("ftp://alice:hunter2@corp-egress:21", HTTPS_DST);
        match setup {
            ProxySetup::Invalid(e) => {
                let text = format!("{e} {e:?}");
                assert!(
                    !text.contains("hunter2") && !text.contains("alice"),
                    "a proxy error must not echo the URL back: {text}"
                );
            }
            _ => panic!("an ftp proxy must be refused"),
        }
    }
}