Skip to content

Commit cdf5d89

Browse files
committed
fix(sandbox,podman): fall back across validated addresses in proxied CONNECT
The direct path hands TcpStream::connect the whole validated address list and it falls back across them, but the validated-IP CONNECT path attempted only the first address, so a dual-stack destination could fail through the corporate proxy even when a later validated address was reachable. connect_via_validated tries each validated address in order under one aggregate CONNECT_HANDSHAKE_TIMEOUT budget, returning the first success; when every attempt fails the error names the attempt count and carries the last failure. An empty address list is rejected up front. Adds regressions for first-fails/second-succeeds fallback (asserting both CONNECT request lines), the aggregate all-addresses failure message, and the empty-list rejection. Signed-off-by: Philippe Martin <[email protected]>
1 parent 32930c2 commit cdf5d89

2 files changed

Lines changed: 157 additions & 23 deletions

File tree

‎crates/openshell-supervisor-network/src/proxy.rs‎

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -2975,20 +2975,19 @@ async fn dial_upstream(
29752975
if let Some(cfg) = upstream_proxy.as_ref() {
29762976
return match cfg.decision(host_lc, port, addrs) {
29772977
upstream_proxy::ProxyDecision::Proxy(endpoint) => {
2978-
let target = if cfg.connect_by_hostname() {
2979-
upstream_proxy::ConnectTarget::Hostname
2978+
if cfg.connect_by_hostname() {
2979+
upstream_proxy::connect_via(
2980+
endpoint,
2981+
host_lc,
2982+
port,
2983+
upstream_proxy::ConnectTarget::Hostname,
2984+
)
2985+
.await
29802986
} else {
2981-
// First validated address, matching the order-of-attempt
2982-
// the direct path's `TcpStream::connect` uses.
2983-
let ip = addrs.first().map(SocketAddr::ip).ok_or_else(|| {
2984-
std::io::Error::new(
2985-
std::io::ErrorKind::InvalidInput,
2986-
format!("no validated addresses to CONNECT to for {host_lc}"),
2987-
)
2988-
})?;
2989-
upstream_proxy::ConnectTarget::Ip(ip)
2990-
};
2991-
upstream_proxy::connect_via(endpoint, host_lc, port, target).await
2987+
// Try every validated address in order, matching the
2988+
// fallback the direct path's `TcpStream::connect` does.
2989+
upstream_proxy::connect_via_validated(endpoint, host_lc, port, addrs).await
2990+
}
29922991
}
29932992
upstream_proxy::ProxyDecision::Direct(direct_addrs) => {
29942993
Ok(upstream_proxy::PrefixedStream::without_prefix(

‎crates/openshell-supervisor-network/src/upstream_proxy.rs‎

Lines changed: 145 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -646,6 +646,67 @@ pub async fn connect_via(
646646
})?
647647
}
648648

649+
/// Open a validated-IP CONNECT tunnel, trying each validated address in
650+
/// order until one succeeds.
651+
///
652+
/// The direct-dial path hands `TcpStream::connect` the whole validated list
653+
/// and it falls back across addresses; this is the proxied equivalent, so a
654+
/// dual-stack destination whose first validated address is unreachable
655+
/// through the corporate proxy still connects via a later one. All attempts
656+
/// share one aggregate handshake budget ([`CONNECT_HANDSHAKE_TIMEOUT`]),
657+
/// matching the single-attempt paths.
658+
///
659+
/// # Errors
660+
///
661+
/// Returns an error when `addrs` is empty, when every attempt fails (the
662+
/// last attempt's error, annotated with the attempt count when there were
663+
/// several), or when the aggregate budget expires.
664+
pub async fn connect_via_validated(
665+
endpoint: &ProxyEndpoint,
666+
host: &str,
667+
port: u16,
668+
addrs: &[SocketAddr],
669+
) -> std::io::Result<PrefixedStream> {
670+
if addrs.is_empty() {
671+
return Err(IoError::new(
672+
ErrorKind::InvalidInput,
673+
format!("no validated addresses to CONNECT to for {host}"),
674+
));
675+
}
676+
tokio::time::timeout(CONNECT_HANDSHAKE_TIMEOUT, async {
677+
let mut last_err = None;
678+
for addr in addrs {
679+
match connect_via_inner(endpoint, host, port, ConnectTarget::Ip(addr.ip())).await {
680+
Ok(stream) => return Ok(stream),
681+
Err(err) => last_err = Some(err),
682+
}
683+
}
684+
// `addrs` is non-empty, so at least one attempt recorded an error.
685+
let last = last_err.expect("at least one CONNECT attempt");
686+
if addrs.len() > 1 {
687+
Err(IoError::new(
688+
last.kind(),
689+
format!(
690+
"CONNECT failed for all {} validated addresses of {host}; last: {last}",
691+
addrs.len()
692+
),
693+
))
694+
} else {
695+
Err(last)
696+
}
697+
})
698+
.await
699+
.map_err(|_| {
700+
IoError::new(
701+
ErrorKind::TimedOut,
702+
format!(
703+
"upstream proxy {} CONNECT handshake timed out",
704+
endpoint.display_addr()
705+
),
706+
)
707+
})?
708+
}
709+
649710
async fn connect_via_inner(
650711
endpoint: &ProxyEndpoint,
651712
host: &str,
@@ -1164,17 +1225,9 @@ mod tests {
11641225
let addr = listener.local_addr().unwrap();
11651226
let handle = tokio::spawn(async move {
11661227
let (mut socket, _) = listener.accept().await.unwrap();
1167-
let mut buf = vec![0u8; 4096];
1168-
let mut used = 0;
1169-
loop {
1170-
let n = socket.read(&mut buf[used..]).await.unwrap();
1171-
used += n;
1172-
if n == 0 || buf[..used].windows(4).any(|w| w == b"\r\n\r\n") {
1173-
break;
1174-
}
1175-
}
1228+
let request = read_request(&mut socket).await;
11761229
socket.write_all(response.as_bytes()).await.unwrap();
1177-
String::from_utf8_lossy(&buf[..used]).into_owned()
1230+
request
11781231
});
11791232
(addr, handle)
11801233
}
@@ -1213,6 +1266,88 @@ mod tests {
12131266
assert!(request.contains("Proxy-Authorization: Basic dXNlcjpwYXNz\r\n"));
12141267
}
12151268

1269+
/// Read one request's header block from a fake-proxy socket.
1270+
async fn read_request(socket: &mut TcpStream) -> String {
1271+
let mut buf = vec![0u8; 4096];
1272+
let mut used = 0;
1273+
loop {
1274+
let n = socket.read(&mut buf[used..]).await.unwrap();
1275+
used += n;
1276+
if n == 0 || buf[..used].windows(4).any(|w| w == b"\r\n\r\n") {
1277+
break;
1278+
}
1279+
}
1280+
String::from_utf8_lossy(&buf[..used]).into_owned()
1281+
}
1282+
1283+
#[tokio::test]
1284+
async fn connect_via_validated_falls_back_across_validated_addresses() {
1285+
// The direct path tries every validated address; the proxied path
1286+
// must too, or a dual-stack destination whose first address is
1287+
// unreachable through the proxy fails needlessly.
1288+
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1289+
let addr = listener.local_addr().unwrap();
1290+
let handle = tokio::spawn(async move {
1291+
// First attempt: refuse the tunnel.
1292+
let (mut refused, _) = listener.accept().await.unwrap();
1293+
let first = read_request(&mut refused).await;
1294+
refused
1295+
.write_all(b"HTTP/1.1 502 Bad Gateway\r\n\r\n")
1296+
.await
1297+
.unwrap();
1298+
drop(refused);
1299+
// Second attempt: establish it.
1300+
let (mut accepted, _) = listener.accept().await.unwrap();
1301+
let second = read_request(&mut accepted).await;
1302+
accepted
1303+
.write_all(b"HTTP/1.1 200 Connection established\r\n\r\n")
1304+
.await
1305+
.unwrap();
1306+
(first, second, accepted)
1307+
});
1308+
1309+
let endpoint = endpoint_for(addr, None);
1310+
let addrs = [sock("192.0.2.1", 443), sock("192.0.2.2", 443)];
1311+
let stream = connect_via_validated(&endpoint, "api.example.com", 443, &addrs)
1312+
.await
1313+
.unwrap();
1314+
let (first, second, _accepted) = handle.await.unwrap();
1315+
drop(stream);
1316+
assert!(
1317+
first.starts_with("CONNECT 192.0.2.1:443 HTTP/1.1\r\n"),
1318+
"{first}"
1319+
);
1320+
assert!(
1321+
second.starts_with("CONNECT 192.0.2.2:443 HTTP/1.1\r\n"),
1322+
"{second}"
1323+
);
1324+
}
1325+
1326+
#[tokio::test]
1327+
async fn connect_via_validated_reports_failure_across_all_addresses() {
1328+
let (addr, _handle) = fake_proxy("HTTP/1.1 502 Bad Gateway\r\n\r\n").await;
1329+
let endpoint = endpoint_for(addr, None);
1330+
// Only the first attempt gets a response; the second finds the
1331+
// listener gone, and the aggregate error must say both were tried.
1332+
let addrs = [sock("192.0.2.1", 443), sock("192.0.2.2", 443)];
1333+
let err = connect_via_validated(&endpoint, "api.example.com", 443, &addrs)
1334+
.await
1335+
.unwrap_err();
1336+
assert!(
1337+
err.to_string().contains("all 2 validated addresses"),
1338+
"{err}"
1339+
);
1340+
}
1341+
1342+
#[tokio::test]
1343+
async fn connect_via_validated_rejects_empty_address_list() {
1344+
let endpoint = endpoint_for(sock("127.0.0.1", 3128), None);
1345+
let err = connect_via_validated(&endpoint, "api.example.com", 443, &[])
1346+
.await
1347+
.unwrap_err();
1348+
assert_eq!(err.kind(), ErrorKind::InvalidInput);
1349+
}
1350+
12161351
#[tokio::test]
12171352
async fn connect_via_sends_hostname_on_operator_opt_in() {
12181353
let (addr, handle) = fake_proxy("HTTP/1.1 200 Connection established\r\n\r\n").await;

0 commit comments

Comments
 (0)