delopay 0.20.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
//! End-to-end proxy tests: a real `CONNECT` proxy, a real mock API server, and
//! the real `Delopay` client wired between them.
//!
//! The point of this file is that "proxy support" is a *fact*, not a claim. The
//! decision logic is unit-tested in `src/http/proxy.rs`; here the bytes actually
//! move. Every test that expects proxying asserts on connections the proxy
//! itself accepted, so a regression that quietly connected straight to the
//! origin — which is the dangerous failure, since an operator may be relying on
//! the proxy for egress control — fails the test instead of passing it.
#![cfg(feature = "client")]

use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use delopay::{Delopay, DelopayError};
use serde_json::json;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// A running `CONNECT` proxy, plus what it observed.
struct TestProxy {
    addr: SocketAddr,
    /// Incremented on every accepted TCP connection, *before* anything is
    /// parsed. This is the evidence that traffic went through the proxy rather
    /// than around it.
    connections: Arc<AtomicUsize>,
    /// The `CONNECT` request heads seen, verbatim.
    heads: Arc<std::sync::Mutex<Vec<String>>>,
}

impl TestProxy {
    fn url(&self) -> String {
        format!("http://{}", self.addr)
    }

    fn connections(&self) -> usize {
        self.connections.load(Ordering::SeqCst)
    }

    fn heads(&self) -> Vec<String> {
        self.heads.lock().unwrap().clone()
    }

    /// The `host:port` from each `CONNECT` request line.
    fn connect_targets(&self) -> Vec<String> {
        self.heads()
            .iter()
            .map(|head| {
                let line = head.lines().next().unwrap_or_default();
                let mut parts = line.split_whitespace();
                assert_eq!(
                    parts.next(),
                    Some("CONNECT"),
                    "not a CONNECT request: {head}"
                );
                parts.next().unwrap_or_default().to_string()
            })
            .collect()
    }
}

/// Start a minimal HTTP `CONNECT` proxy on an ephemeral loopback port.
///
/// It does exactly what a corporate egress proxy does for TLS traffic: read the
/// `CONNECT host:port` request, dial that host, answer `200 Connection
/// Established`, and then blindly relay bytes in both directions. It never
/// inspects or rewrites the tunnelled stream, so whatever the SDK sends is what
/// the origin receives.
async fn start_proxy() -> TestProxy {
    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let connections = Arc::new(AtomicUsize::new(0));
    let heads = Arc::new(std::sync::Mutex::new(Vec::new()));

    let accepted = connections.clone();
    let seen = heads.clone();
    tokio::spawn(async move {
        loop {
            let Ok((client, _)) = listener.accept().await else {
                return;
            };
            accepted.fetch_add(1, Ordering::SeqCst);
            let seen = seen.clone();
            tokio::spawn(async move {
                let _ = serve_connect(client, seen).await;
            });
        }
    });

    TestProxy {
        addr,
        connections,
        heads,
    }
}

async fn serve_connect(
    mut client: TcpStream,
    heads: Arc<std::sync::Mutex<Vec<String>>>,
) -> std::io::Result<()> {
    // Read exactly up to the end of the request head. Anything after it belongs
    // to the tunnel, so it is forwarded rather than parsed.
    let mut buf = Vec::new();
    let head_end = loop {
        let mut chunk = [0u8; 1024];
        let n = client.read(&mut chunk).await?;
        if n == 0 {
            return Ok(());
        }
        buf.extend_from_slice(&chunk[..n]);
        if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
            break i + 4;
        }
        if buf.len() > 16 * 1024 {
            return Ok(());
        }
    };

    let head = String::from_utf8_lossy(&buf[..head_end]).into_owned();
    let target = head
        .lines()
        .next()
        .and_then(|line| line.split_whitespace().nth(1))
        .unwrap_or_default()
        .to_string();
    heads.lock().unwrap().push(head);

    let Ok(mut upstream) = TcpStream::connect(&target).await else {
        client
            .write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
            .await?;
        return Ok(());
    };

    client
        .write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n")
        .await?;

    // A well-behaved client waits for the 200 before sending, but forward any
    // early bytes rather than dropping them on the floor.
    if head_end < buf.len() {
        upstream.write_all(&buf[head_end..]).await?;
    }

    tokio::io::copy_bidirectional(&mut client, &mut upstream)
        .await
        .map(|_| ())
}

/// `host:port` of a `http://host:port` URL.
fn authority_of(url: &str) -> String {
    url.trim_start_matches("http://")
        .trim_end_matches('/')
        .to_string()
}

async fn mount_payment(server: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/payments/pay_1"))
        .and(header("api-key", "snd_test"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "payment_id": "pay_1", "merchant_id": "mer_1",
            "status": "succeeded", "amount": 1999, "currency": "EUR"
        })))
        .mount(server)
        .await;
}

#[tokio::test]
async fn a_request_reaches_the_api_through_a_real_connect_proxy() {
    let server = MockServer::start().await;
    mount_payment(&server).await;
    let proxy = start_proxy().await;

    let payment = Delopay::builder("snd_test")
        .base_url(server.uri())
        .proxy(proxy.url())
        .build()
        .payments()
        .retrieve("pay_1")
        .await
        .expect("the request must complete through the proxy");

    // 1. The API really answered, through the tunnel.
    assert_eq!(payment.payment_id, "pay_1");
    assert_eq!(payment.amount, 1999);

    // 2. The proxy was really traversed. Without this the test would pass just
    //    as happily if `.proxy()` were a no-op and the client connected direct.
    assert_eq!(
        proxy.connections(),
        1,
        "the proxy must have accepted exactly one connection; 0 means traffic \
         went direct and bypassed it entirely"
    );

    // 3. And it was traversed *for this destination* — the CONNECT names the
    //    mock server, so the tunnel was not opened to somewhere else.
    assert_eq!(proxy.connect_targets(), vec![authority_of(&server.uri())]);

    // 4. The request the origin saw is a normal, unmangled API call.
    let received = server.received_requests().await.unwrap();
    assert_eq!(received.len(), 1);
    assert_eq!(received[0].url.path(), "/payments/pay_1");
}

#[tokio::test]
async fn no_proxy_connects_directly_and_never_touches_the_proxy() {
    // The control for the test above: same wiring, proxying switched off. It
    // pins the proxy's connection counter as a real signal rather than
    // something that happens to be 1 whatever the client does.
    let server = MockServer::start().await;
    mount_payment(&server).await;
    let proxy = start_proxy().await;

    let payment = Delopay::builder("snd_test")
        .base_url(server.uri())
        .no_proxy()
        .build()
        .payments()
        .retrieve("pay_1")
        .await
        .unwrap();

    assert_eq!(payment.payment_id, "pay_1");
    assert_eq!(
        proxy.connections(),
        0,
        "no_proxy() must not open a connection to the proxy"
    );
    assert_eq!(server.received_requests().await.unwrap().len(), 1);
}

#[tokio::test]
async fn proxy_credentials_are_sent_to_the_proxy_and_not_to_the_origin() {
    let server = MockServer::start().await;
    mount_payment(&server).await;
    let proxy = start_proxy().await;

    // `Basic YWxpY2U6aHVudGVyMg==` is base64("alice:hunter2").
    let proxy_url = format!("http://alice:hunter2@{}", proxy.addr);

    Delopay::builder("snd_test")
        .base_url(server.uri())
        .proxy(proxy_url)
        .build()
        .payments()
        .retrieve("pay_1")
        .await
        .unwrap();

    let head = proxy.heads().pop().expect("the proxy saw a CONNECT");
    assert!(
        head.contains("Proxy-Authorization: Basic YWxpY2U6aHVudGVyMg=="),
        "credentials in the proxy URL must reach the proxy: {head}"
    );

    // They must stop there. The origin is a different trust domain.
    let received = server.received_requests().await.unwrap();
    let forwarded = format!("{:?}", received[0].headers);
    assert!(
        !forwarded.to_lowercase().contains("proxy-authorization"),
        "proxy credentials must not be forwarded to the API: {forwarded}"
    );
}

// ---------------------------------------------------------------------------
// Environment-driven proxying, end to end.
//
// `HTTPS_PROXY` has to actually be set in the process that builds the client,
// and `std::env::set_var` is both process-global (so it corrupts the other
// tests running on sibling threads) and `unsafe` in edition 2024, which this
// crate forbids. So the client is built in a *child* process instead: the
// parent re-executes this same test binary with the variables supplied through
// `Command::env`, which is safe and affects nothing else. The parent keeps the
// mock server and the proxy, and therefore keeps the evidence.
// ---------------------------------------------------------------------------

/// Env var the child reads to find the mock API. Its absence is a hard error in
/// the child, so a mis-wired parent shows up as a failure, not a silent pass.
const CHILD_BASE_URL: &str = "DELOPAY_TEST_BASE_URL";

/// Run `probe` in a child process with `env` applied, and assert it passed.
async fn run_child(probe: &'static str, env: Vec<(String, String)>) {
    let exe = std::env::current_exe().unwrap();
    let output = tokio::task::spawn_blocking(move || {
        let mut cmd = std::process::Command::new(exe);
        cmd.args(["--exact", probe, "--ignored", "--nocapture"]);
        // Start from a known-empty proxy environment. Without this, a developer
        // machine or CI runner that already exports (say) `NO_PROXY` would
        // change what these tests measure.
        for name in [
            "ALL_PROXY",
            "all_proxy",
            "HTTP_PROXY",
            "http_proxy",
            "HTTPS_PROXY",
            "https_proxy",
            "NO_PROXY",
            "no_proxy",
            "REQUEST_METHOD",
        ] {
            cmd.env_remove(name);
        }
        for (k, v) in env {
            cmd.env(k, v);
        }
        cmd.output().unwrap()
    })
    .await
    .unwrap();

    assert!(
        output.status.success(),
        "child probe `{probe}` failed:\n--- stdout ---\n{}\n--- stderr ---\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
}

/// Not a test on its own — the body the two env tests below execute in a child
/// process. `#[ignore]` keeps it out of a normal `cargo test` run; it is only
/// reached via `--ignored --exact`.
#[tokio::test]
#[ignore = "run only as a child process by the env-proxy tests"]
async fn child_retrieves_a_payment_with_ambient_proxy_settings() {
    let base_url = std::env::var(CHILD_BASE_URL)
        .expect("the parent test must pass the mock server URL to the child");

    // No `.proxy()` and no `.no_proxy()`: this is the default, environment-
    // reading path under test.
    let payment = Delopay::builder("snd_test")
        .base_url(base_url)
        .build()
        .payments()
        .retrieve("pay_1")
        .await
        .expect("the child's request must succeed");

    assert_eq!(payment.payment_id, "pay_1");
}

#[tokio::test]
async fn https_proxy_env_var_is_honoured_by_default() {
    let server = MockServer::start().await;
    mount_payment(&server).await;
    let proxy = start_proxy().await;

    run_child(
        "child_retrieves_a_payment_with_ambient_proxy_settings",
        vec![
            (CHILD_BASE_URL.to_string(), server.uri()),
            ("HTTPS_PROXY".to_string(), proxy.url()),
            // The mock server is plain HTTP, so `HTTP_PROXY` is the variable
            // that applies to it. Setting both proves the pair is read; the
            // NO_PROXY test below proves neither is hard-coded.
            ("HTTP_PROXY".to_string(), proxy.url()),
        ],
    )
    .await;

    assert_eq!(
        proxy.connections(),
        1,
        "with HTTP_PROXY/HTTPS_PROXY set, the client must route through the proxy"
    );
    assert_eq!(proxy.connect_targets(), vec![authority_of(&server.uri())]);
    assert_eq!(server.received_requests().await.unwrap().len(), 1);
}

#[tokio::test]
async fn no_proxy_env_var_excludes_a_matching_host() {
    let server = MockServer::start().await;
    mount_payment(&server).await;
    let proxy = start_proxy().await;

    run_child(
        "child_retrieves_a_payment_with_ambient_proxy_settings",
        vec![
            (CHILD_BASE_URL.to_string(), server.uri()),
            ("HTTPS_PROXY".to_string(), proxy.url()),
            ("HTTP_PROXY".to_string(), proxy.url()),
            // Same proxy configuration as the test above — only this line
            // differs, so it is the only thing that can explain the different
            // outcome.
            ("NO_PROXY".to_string(), "127.0.0.1".to_string()),
        ],
    )
    .await;

    assert_eq!(
        proxy.connections(),
        0,
        "NO_PROXY listed the destination, so the proxy must be bypassed"
    );
    assert_eq!(server.received_requests().await.unwrap().len(), 1);
}

#[tokio::test]
async fn an_unusable_explicit_proxy_fails_the_request_rather_than_bypassing_it() {
    // The security property, end to end and through the public API: when the
    // caller named a proxy that cannot be used, the SDK must not quietly reach
    // the origin some other way.
    let server = MockServer::start().await;
    mount_payment(&server).await;

    let err = Delopay::builder("snd_test")
        .base_url(server.uri())
        // Syntactically valid, but this transport speaks HTTP CONNECT only.
        .proxy("socks5://127.0.0.1:1080")
        .build()
        .payments()
        .retrieve("pay_1")
        .await
        .expect_err("an unusable proxy must fail the request");

    match &err {
        DelopayError::Transport(e) => {
            let text = e.to_string();
            assert!(text.contains("proxy"), "unhelpful error: {text}");
        }
        other => panic!("expected a transport error, got {other:?}"),
    }

    assert_eq!(
        server.received_requests().await.unwrap().len(),
        0,
        "traffic must never reach the origin when the requested proxy is unusable"
    );
}