Files
yaak-mountain-loop/crates/yaak-proxy/tests/own_fallback.rs
T
Gregory SchierandClaude Opus 5.5 ea288ec074 Yaak Proxy: dial the server before answering a CONNECT
The engine now opens the TCP connection to a CONNECT's server before it
answers. When the server can't be reached, the CONNECT gets a 502 (or a
504 on a timeout) and the client reports its own connection error, rather
than a 200 followed by a 502 inside the decrypted session or a silent
hang-up in a tunnel. The failure is recorded as one error flow.

The dialled connection is handed to the tunnel, or to the first upstream
connection of a decrypted one, so nothing is dialled twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 09:25:53 -07:00

108 lines
4.8 KiB
Rust

//! The engine's own upstream falling back to the system proxy, which is the engine. Its own test
//! binary, since the proxy is set for the whole process.
#![cfg(target_os = "macos")]
use std::ffi::{CString, c_void};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use tempfile::TempDir;
use tokio::io::{AsyncReadExt, AsyncWriteExt, copy_bidirectional};
use tokio::net::{TcpListener, TcpStream};
use yaak_proxy::{CaStore, ProxyConfig, start_proxy};
type NwObject = *mut c_void;
#[link(name = "Network", kind = "framework")]
unsafe extern "C" {
static _nw_privacy_context_default_context: NwObject;
fn nw_endpoint_create_host(host: *const i8, port: *const i8) -> NwObject;
fn nw_proxy_config_create_http_connect(endpoint: NwObject, tls: NwObject) -> NwObject;
fn nw_proxy_config_set_failover_allowed(proxy_config: NwObject, allowed: bool);
fn nw_privacy_context_add_proxy(privacy_context: NwObject, proxy_config: NwObject);
fn nw_release(obj: NwObject);
}
/// Points every Network.framework connection in the process at an HTTP CONNECT proxy on
/// `127.0.0.1:port`, as a system proxy would.
fn set_process_proxy(port: u16) {
let host = CString::new("127.0.0.1").unwrap();
let port = CString::new(port.to_string()).unwrap();
// SAFETY: each object created here is released once, after the context retains it.
unsafe {
let endpoint = nw_endpoint_create_host(host.as_ptr(), port.as_ptr());
let config = nw_proxy_config_create_http_connect(endpoint, std::ptr::null_mut());
nw_proxy_config_set_failover_allowed(config, true);
nw_privacy_context_add_proxy(_nw_privacy_context_default_context, config);
nw_release(config);
nw_release(endpoint);
}
}
async fn read_head(stream: &mut (impl AsyncReadExt + Unpin)) -> String {
let mut head = Vec::new();
while !head.ends_with(b"\r\n\r\n") {
head.push(stream.read_u8().await.unwrap());
}
String::from_utf8(head).unwrap()
}
/// A CONNECT is answered only once its server is reached, and on macOS the engine reaches port 80
/// through Network.framework, which falls back to the system proxy, the engine, when there is no
/// direct route. That fallback is a CONNECT of the engine's own, which dialling again would
/// repeat without end, so it is answered before any dial and refused once it is known to be the
/// engine's own. One `CONNECT` each, then the client gets a 502: for its CONNECT, and for a plain
/// request.
#[tokio::test(flavor = "multi_thread")]
async fn own_fallback_stops() {
const TARGET: &str = "yaak-proxy-own-fallback.invalid";
let dir = TempDir::new().unwrap();
let ca = Arc::new(CaStore::load_or_create(dir.path()).unwrap());
let proxy = start_proxy(ProxyConfig::new(0, ca)).unwrap();
let engine_port = proxy.port;
// Counts the CONNECTs on their way from Network.framework to the engine.
let gateway = TcpListener::bind("127.0.0.1:0").await.unwrap();
let gateway_port = gateway.local_addr().unwrap().port();
let connects = Arc::new(AtomicUsize::new(0));
let seen = connects.clone();
tokio::spawn(async move {
loop {
let (mut inbound, _) = gateway.accept().await.unwrap();
let seen = seen.clone();
tokio::spawn(async move {
let head = read_head(&mut inbound).await;
if head.starts_with("CONNECT ") {
seen.fetch_add(1, Ordering::SeqCst);
}
let mut engine = TcpStream::connect(("127.0.0.1", engine_port)).await.unwrap();
engine.write_all(head.as_bytes()).await.unwrap();
let _ = copy_bidirectional(&mut inbound, &mut engine).await;
});
}
});
set_process_proxy(gateway_port);
let mut tcp = TcpStream::connect(("127.0.0.1", engine_port)).await.unwrap();
let connect = format!("CONNECT {TARGET}:80 HTTP/1.1\r\nHost: {TARGET}:80\r\n\r\n");
tcp.write_all(connect.as_bytes()).await.unwrap();
let head = tokio::time::timeout(Duration::from_secs(10), read_head(&mut tcp))
.await
.expect("no answer to the CONNECT");
assert!(head.starts_with("HTTP/1.1 502"), "{head}");
// Give a runaway chain time to show.
tokio::time::sleep(Duration::from_secs(1)).await;
assert_eq!(connects.load(Ordering::SeqCst), 1);
let mut client = TcpStream::connect(("127.0.0.1", engine_port)).await.unwrap();
let request = format!("GET http://{TARGET}/ HTTP/1.1\r\nHost: {TARGET}\r\n\r\n");
client.write_all(request.as_bytes()).await.unwrap();
let head = tokio::time::timeout(Duration::from_secs(10), read_head(&mut client))
.await
.expect("no response");
assert!(head.starts_with("HTTP/1.1 502"), "{head}");
tokio::time::sleep(Duration::from_secs(1)).await;
assert_eq!(connects.load(Ordering::SeqCst), 2);
}