mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-28 19:22:39 +01:00
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>
This commit is contained in:
1 parent
649549482c
commit
ea288ec074
14 files changed
+889
-106
No files matched your search
@@ -3226,8 +3226,8 @@ const STOPPED_MID_STREAM: &str = "Yaak Proxy stopped before the stream ended";
|
||||
/// Why a tunnel still open when the engine stopped ended.
|
||||
const STOPPED_MID_TUNNEL: &str = "Yaak Proxy stopped before the connection closed";
|
||||
|
||||
/// Why a failed handshake's flow can't be saved as a request.
|
||||
pub(crate) const NOT_A_REQUEST: &str = "The TLS handshake failed before any request was sent";
|
||||
/// Why a failed handshake's or connection's flow can't be saved as a request.
|
||||
pub(crate) const NOT_A_REQUEST: &str = "The connection failed before any request was sent";
|
||||
|
||||
/// The error of a flow recording a client's refusal of the proxy's certificate.
|
||||
const REJECTED_CERTIFICATE: &str = "Certificate rejected by the app";
|
||||
@@ -3729,6 +3729,43 @@ impl FlowSink {
|
||||
graphql_scan: None,
|
||||
});
|
||||
}
|
||||
// No tunnel and no handshake: a failed connection, of the one event.
|
||||
ProxyEvent::ConnectFailed {
|
||||
id: _,
|
||||
started_at,
|
||||
authority,
|
||||
connection,
|
||||
client_addr,
|
||||
error,
|
||||
elapsed_ms,
|
||||
} => {
|
||||
if !recording.lock().map(|r| r.was_on_at(started_at)).unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
attribution.begin(connection, client_addr);
|
||||
let flow = Flow {
|
||||
id: Flow::generate_id(),
|
||||
started_at: DateTime::<Utc>::from(started_at).naive_utc(),
|
||||
url: format!("https://{authority}"),
|
||||
client_http_version: "HTTP/1.1".to_string(),
|
||||
client_addr: Some(client_addr.to_string()),
|
||||
elapsed_ms: Some(clamp_ms(elapsed_ms)),
|
||||
error: Some(error),
|
||||
..Default::default()
|
||||
};
|
||||
self.finish_flow(InFlight {
|
||||
flow,
|
||||
connection,
|
||||
request_body: None,
|
||||
response_body: None,
|
||||
persisted: false,
|
||||
cleared: false,
|
||||
next_seq: 0,
|
||||
dirty: false,
|
||||
last_write: None,
|
||||
graphql_scan: None,
|
||||
});
|
||||
}
|
||||
ProxyEvent::StreamStart { id, kind } => {
|
||||
if let Some(f) = in_flight.get_mut(&id) {
|
||||
let kind = StreamKind::from(kind);
|
||||
|
||||
@@ -229,7 +229,8 @@ impl Flow {
|
||||
}
|
||||
}
|
||||
|
||||
/// A client's failed TLS handshake, recorded without a request: nothing to save or replay.
|
||||
/// A client's failed TLS handshake, or a server that could not be reached, recorded without
|
||||
/// a request: nothing to save or replay.
|
||||
pub fn is_handshake_only(&self) -> bool {
|
||||
self.method.is_empty()
|
||||
}
|
||||
|
||||
@@ -933,15 +933,21 @@ async fn the_decrypt_list_reaches_the_cli_that_owns_the_engine() {
|
||||
let list = rpc(&app, "set_decrypt_list", json!({"entries": ["*"]})).await.unwrap();
|
||||
assert_eq!(list["entries"][0], json!({"entry": "*", "builtIn": false}));
|
||||
|
||||
// Decrypted, the request is a flow of its own: a 502, as nothing listens there.
|
||||
// Decrypted, the request is a flow of its own: a 502, as the server hangs up on its TLS.
|
||||
let ca = std::fs::read(dir.path().join("ca/ca.pem")).unwrap();
|
||||
let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap().port();
|
||||
let hangs_up = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = hangs_up.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
drop(hangs_up.accept().await.unwrap());
|
||||
}
|
||||
});
|
||||
let client = reqwest::Client::builder()
|
||||
.proxy(reqwest::Proxy::all(format!("http://127.0.0.1:{}", cli.port().unwrap())).unwrap())
|
||||
.add_root_certificate(reqwest::Certificate::from_pem(&ca).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
let url = format!("https://localhost:{closed}/forwarded");
|
||||
let url = format!("https://localhost:{port}/forwarded");
|
||||
assert_eq!(client.get(&url).send().await.unwrap().status(), 502);
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
|
||||
@@ -169,7 +169,7 @@ async fn a_refused_handshake_is_one_flow_per_address() {
|
||||
assert!(rejected.elapsed_ms.is_some(), "ended, not pending");
|
||||
// No request was sent, so there is none to save.
|
||||
let preview = rpc(&ctx, "preview_save", json!({"flowId": rejected.id})).await;
|
||||
assert!(preview.unwrap_err().starts_with("The TLS handshake failed"));
|
||||
assert!(preview.unwrap_err().starts_with("The connection failed"));
|
||||
|
||||
// Passed through from now on, naming the refusal.
|
||||
let _tunnel = open_tunnel(&ctx, &target).await;
|
||||
@@ -241,6 +241,55 @@ async fn a_refused_handshake_is_one_flow_per_address() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A server the engine can't reach fails the CONNECT, and is one failed flow: no tunnel, no
|
||||
/// refused handshake, nothing to reconnect or save.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_unreachable_server_is_one_failed_flow() {
|
||||
// Everything is tunnelled, so a tunnel would be recorded, and kept to reconnect.
|
||||
let (_dir, ctx, _events) = started(&[]);
|
||||
let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap();
|
||||
let mut tcp = TcpStream::connect(("127.0.0.1", ctx.port().unwrap())).await.unwrap();
|
||||
let connect = format!("CONNECT {closed} HTTP/1.1\r\nHost: {closed}\r\n\r\n");
|
||||
tcp.write_all(connect.as_bytes()).await.unwrap();
|
||||
let mut head = Vec::new();
|
||||
while !head.ends_with(b"\r\n\r\n") {
|
||||
head.push(tcp.read_u8().await.unwrap());
|
||||
}
|
||||
assert!(head.starts_with(b"HTTP/1.1 502"), "{}", String::from_utf8_lossy(&head));
|
||||
|
||||
let url = format!("https://{closed}");
|
||||
let failed = wait_for(&ctx, "failed", |f| f.url == url).await;
|
||||
assert_eq!(failed.method, "");
|
||||
assert!(failed.error.as_deref().unwrap().starts_with("Connection refused: "), "{failed:?}");
|
||||
assert!(failed.elapsed_ms.is_some(), "ended, not pending");
|
||||
assert_eq!(failed.status, None);
|
||||
assert!(!failed.tunnelled);
|
||||
assert_eq!((failed.tunnel_reason, failed.tls_rejected.as_deref()), (None, None));
|
||||
assert_eq!(failed.client_addr, Some(tcp.local_addr().unwrap().to_string()));
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(flows(&ctx).len(), 1, "one flow");
|
||||
|
||||
let ids = |listed: Value| -> Vec<Value> {
|
||||
listed["flows"].as_array().unwrap().iter().map(|f| f["id"].clone()).collect()
|
||||
};
|
||||
let errors = rpc(&ctx, "list_flows", json!({"query": "@is:error"})).await.unwrap();
|
||||
assert_eq!(ids(errors), vec![json!(failed.id)]);
|
||||
for query in ["@is:encrypted", "@is:rejected"] {
|
||||
let listed = rpc(&ctx, "list_flows", json!({"query": query})).await.unwrap();
|
||||
assert!(ids(listed).is_empty(), "{query}");
|
||||
}
|
||||
|
||||
// Listed now, a tunnel to it would be decrypted on a reconnect; there is none.
|
||||
let saved = rpc(&ctx, "edit_decrypt_list", json!({"add": ["127.0.0.1"]})).await.unwrap();
|
||||
assert_eq!(saved["stillEncrypted"], 0);
|
||||
assert!(reconnectable(&ctx, json!({})).await.is_empty());
|
||||
assert!(reconnectable(&ctx, json!({"flowId": failed.id})).await.is_empty());
|
||||
let passthrough = rpc(&ctx, "list_passthrough", json!({})).await.unwrap();
|
||||
assert_eq!(passthrough["addresses"], json!([]));
|
||||
let preview = rpc(&ctx, "preview_save", json!({"flowId": failed.id})).await;
|
||||
assert!(preview.unwrap_err().starts_with("The connection failed"));
|
||||
}
|
||||
|
||||
/// Open tunnels are kept whether or not flows are recorded; saving the list closes none of
|
||||
/// them but counts those it would decrypt, and reconnecting closes them by flow, by entry or
|
||||
/// all at once.
|
||||
|
||||
@@ -281,8 +281,15 @@ async fn http_version_setting_applies_to_new_connections() {
|
||||
ctx.start().unwrap();
|
||||
let port = ctx.port().unwrap();
|
||||
let ca = std::fs::read(dir.path().join("ca/ca.pem")).unwrap();
|
||||
// Nothing listens there, so each flow is a 502, but its client side is spoken all the same.
|
||||
let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap().port();
|
||||
// The server hangs up on its TLS, so each flow is a 502, but its client side is spoken all
|
||||
// the same.
|
||||
let hangs_up = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let server = hangs_up.local_addr().unwrap().port();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
drop(hangs_up.accept().await.unwrap());
|
||||
}
|
||||
});
|
||||
|
||||
let mut sent = 0;
|
||||
let mut client_version = async || {
|
||||
@@ -293,7 +300,7 @@ async fn http_version_setting_applies_to_new_connections() {
|
||||
.add_root_certificate(reqwest::Certificate::from_pem(&ca).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
let url = format!("https://localhost:{closed}/{sent}");
|
||||
let url = format!("https://localhost:{server}/{sent}");
|
||||
assert_eq!(client.get(&url).send().await.unwrap().status(), 502);
|
||||
wait_for_flow(&ctx, &url).await.client_http_version
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user