#![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};
struct TestProxy {
addr: SocketAddr,
connections: Arc<AtomicUsize>,
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()
}
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()
}
}
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<()> {
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?;
if head_end < buf.len() {
upstream.write_all(&buf[head_end..]).await?;
}
tokio::io::copy_bidirectional(&mut client, &mut upstream)
.await
.map(|_| ())
}
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");
assert_eq!(payment.payment_id, "pay_1");
assert_eq!(payment.amount, 1999);
assert_eq!(
proxy.connections(),
1,
"the proxy must have accepted exactly one connection; 0 means traffic \
went direct and bypassed it entirely"
);
assert_eq!(proxy.connect_targets(), vec![authority_of(&server.uri())]);
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() {
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;
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}"
);
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}"
);
}
const CHILD_BASE_URL: &str = "DELOPAY_TEST_BASE_URL";
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"]);
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),
);
}
#[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");
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()),
("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()),
("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() {
let server = MockServer::start().await;
mount_payment(&server).await;
let err = Delopay::builder("snd_test")
.base_url(server.uri())
.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"
);
}