mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-12-02 21:14:15 +01:00
Proxy GUI pass (#793)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
96ab0a8a60
commit
e82ffc53ad
73 files changed
+6003
-1257
No files matched your search
@@ -5,8 +5,8 @@ use hyper::service::service_fn;
|
||||
use hyper_util::rt::TokioIo;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
use crate::Engine;
|
||||
use crate::request::handle_request;
|
||||
use crate::{ClientConn, Engine};
|
||||
|
||||
pub(crate) async fn serve_http1<S, F, Fut>(io: S, handler: F) -> Result<(), hyper::Error>
|
||||
where
|
||||
@@ -26,7 +26,8 @@ where
|
||||
|
||||
pub(crate) async fn handle_connection(
|
||||
stream: tokio::net::TcpStream,
|
||||
client: ClientConn,
|
||||
engine: Arc<Engine>,
|
||||
) -> Result<(), hyper::Error> {
|
||||
serve_http1(stream, move |req| handle_request(req, engine.clone())).await
|
||||
serve_http1(stream, move |req| handle_request(req, client, engine.clone())).await
|
||||
}
|
||||
@@ -42,8 +42,15 @@ pub struct ProxyConfig {
|
||||
pub capture_body_limit: usize,
|
||||
/// Roots trusted for upstream TLS in addition to the platform's.
|
||||
pub upstream_root_certs: Vec<CertificateDer<'static>>,
|
||||
/// Runs on a blocking thread as each client connection is accepted, with the connection's
|
||||
/// number and the client's address, before anything is read from it, so the client is
|
||||
/// still there to be looked up. The connection waits for it.
|
||||
pub on_accept: Option<AcceptHook>,
|
||||
}
|
||||
|
||||
/// See [`ProxyConfig::on_accept`].
|
||||
pub type AcceptHook = Arc<dyn Fn(u64, SocketAddr) + Send + Sync>;
|
||||
|
||||
impl ProxyConfig {
|
||||
pub fn new(port: u16, ca: Arc<CaStore>) -> Self {
|
||||
Self {
|
||||
@@ -51,6 +58,7 @@ impl ProxyConfig {
|
||||
ca,
|
||||
capture_body_limit: DEFAULT_CAPTURE_BODY_LIMIT,
|
||||
upstream_root_certs: Vec::new(),
|
||||
on_accept: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -69,6 +77,10 @@ pub enum ProxyEvent {
|
||||
url: String,
|
||||
/// Version spoken by the client.
|
||||
http_version: String,
|
||||
/// The client connection the request came on, numbered from 1 for each run.
|
||||
connection: u64,
|
||||
/// The client's end of that connection, to find the app that opened it.
|
||||
client_addr: SocketAddr,
|
||||
},
|
||||
RequestHeader {
|
||||
id: u64,
|
||||
@@ -149,6 +161,13 @@ impl ProxyHandle {
|
||||
self.event_rx.take()
|
||||
}
|
||||
|
||||
/// Forgets the hosts passed through after clients rejected the CA, so they are intercepted
|
||||
/// again, as once the CA is trusted.
|
||||
pub fn forget_passthrough(&self) {
|
||||
self.engine.passthrough.lock().unwrap().clear();
|
||||
self.engine.handshake_failures.lock().unwrap().clear();
|
||||
}
|
||||
|
||||
/// Handshake failures counted toward passing `addr` (`host:port`) through, and whether it
|
||||
/// already is. For tests that must wait for the engine to record a failure.
|
||||
#[doc(hidden)]
|
||||
@@ -169,11 +188,19 @@ impl Drop for ProxyHandle {
|
||||
}
|
||||
}
|
||||
|
||||
/// The client connection a request came on.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct ClientConn {
|
||||
connection: u64,
|
||||
addr: SocketAddr,
|
||||
}
|
||||
|
||||
pub(crate) struct Engine {
|
||||
ca: Arc<CaStore>,
|
||||
capture_body_limit: usize,
|
||||
events: std_mpsc::Sender<ProxyEvent>,
|
||||
next_id: AtomicU64,
|
||||
next_connection: AtomicU64,
|
||||
http_client: Client<HttpConnector, BoxBody>,
|
||||
upstream_tls: Arc<ClientConfig>,
|
||||
upstream_tls_h1: Arc<ClientConfig>,
|
||||
@@ -251,6 +278,7 @@ pub fn start_proxy(config: ProxyConfig) -> Result<ProxyHandle, String> {
|
||||
capture_body_limit: config.capture_body_limit,
|
||||
events: event_tx,
|
||||
next_id: AtomicU64::new(1),
|
||||
next_connection: AtomicU64::new(1),
|
||||
http_client: Client::builder(TokioExecutor::new()).build_http(),
|
||||
upstream_tls: upstream_tls_config(&roots, &[b"h2", b"http/1.1"])?,
|
||||
upstream_tls_h1: upstream_tls_config(&roots, &[b"http/1.1"])?,
|
||||
@@ -260,6 +288,7 @@ pub fn start_proxy(config: ProxyConfig) -> Result<ProxyHandle, String> {
|
||||
});
|
||||
|
||||
let port = config.port;
|
||||
let on_accept = config.on_accept;
|
||||
let handle_engine = engine.clone();
|
||||
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
|
||||
let (ready_tx, ready_rx) = std_mpsc::channel();
|
||||
@@ -289,10 +318,19 @@ pub fn start_proxy(config: ProxyConfig) -> Result<ProxyHandle, String> {
|
||||
loop {
|
||||
tokio::select! {
|
||||
result = listener.accept() => match result {
|
||||
Ok((stream, _)) => {
|
||||
Ok((stream, addr)) => {
|
||||
let engine = engine.clone();
|
||||
let client = ClientConn {
|
||||
connection: engine.next_connection.fetch_add(1, Ordering::Relaxed),
|
||||
addr,
|
||||
};
|
||||
let on_accept = on_accept.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = handle_connection(stream, engine).await {
|
||||
if let Some(hook) = on_accept {
|
||||
let (connection, addr) = (client.connection, client.addr);
|
||||
let _ = tokio::task::spawn_blocking(move || hook(connection, addr)).await;
|
||||
}
|
||||
if let Err(e) = handle_connection(stream, client, engine).await {
|
||||
log::debug!("Client connection error: {e}");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@ use tokio_rustls::{LazyConfigAcceptor, TlsConnector};
|
||||
use crate::body::{CaptureBody, Direction};
|
||||
use crate::connection::serve_http1;
|
||||
use crate::tunnel::{Rewind, splice, tunnel};
|
||||
use crate::{Engine, ProxyEvent};
|
||||
use crate::{ClientConn, Engine, ProxyEvent};
|
||||
|
||||
pub(crate) type BoxBody = http_body_util::combinators::BoxBody<Bytes, hyper::Error>;
|
||||
type BoxError = Box<dyn Error + Send + Sync>;
|
||||
@@ -67,7 +67,12 @@ struct Flow {
|
||||
}
|
||||
|
||||
impl Flow {
|
||||
fn begin(engine: Arc<Engine>, req: &Request<Incoming>, url: String) -> Self {
|
||||
fn begin(
|
||||
engine: Arc<Engine>,
|
||||
client: ClientConn,
|
||||
req: &Request<Incoming>,
|
||||
url: String,
|
||||
) -> Self {
|
||||
let flow = Self { id: engine.next_flow_id(), start: Instant::now(), engine };
|
||||
flow.engine.emit(ProxyEvent::RequestStart {
|
||||
id: flow.id,
|
||||
@@ -75,6 +80,8 @@ impl Flow {
|
||||
method: req.method().to_string(),
|
||||
url,
|
||||
http_version: version_str(req.version()),
|
||||
connection: client.connection,
|
||||
client_addr: client.addr,
|
||||
});
|
||||
for (name, value) in req.headers() {
|
||||
flow.engine.emit(ProxyEvent::RequestHeader {
|
||||
@@ -147,16 +154,17 @@ fn bad_gateway(body: String) -> Response<BoxBody> {
|
||||
|
||||
pub(crate) async fn handle_request(
|
||||
mut req: Request<Incoming>,
|
||||
client: ClientConn,
|
||||
engine: Arc<Engine>,
|
||||
) -> Result<Response<BoxBody>, Infallible> {
|
||||
if req.method() == Method::CONNECT {
|
||||
return Ok(handle_connect(req, engine));
|
||||
return Ok(handle_connect(req, client, engine));
|
||||
}
|
||||
|
||||
// Some clients send a bare path (`POST /api`) as they would to the server itself.
|
||||
let from_host = req.uri().authority().is_none();
|
||||
let rejected = if from_host { url_from_host(&mut req, &engine).err() } else { None };
|
||||
let flow = Flow::begin(engine.clone(), &req, req.uri().to_string());
|
||||
let flow = Flow::begin(engine.clone(), client, &req, req.uri().to_string());
|
||||
if let Some((status, error)) = rejected {
|
||||
return Ok(flow.reject(status, error));
|
||||
}
|
||||
@@ -220,7 +228,11 @@ struct Target {
|
||||
addr: String,
|
||||
}
|
||||
|
||||
fn handle_connect(req: Request<Incoming>, engine: Arc<Engine>) -> Response<BoxBody> {
|
||||
fn handle_connect(
|
||||
req: Request<Incoming>,
|
||||
client: ClientConn,
|
||||
engine: Arc<Engine>,
|
||||
) -> Response<BoxBody> {
|
||||
let Some(authority) = req.uri().authority().cloned() else {
|
||||
return Response::builder()
|
||||
.status(StatusCode::BAD_REQUEST)
|
||||
@@ -240,7 +252,7 @@ fn handle_connect(req: Request<Incoming>, engine: Arc<Engine>) -> Response<BoxBo
|
||||
authority: if port == 443 { host.clone() } else { format!("{host}:{port}") },
|
||||
addr: format!("{host}:{port}"),
|
||||
};
|
||||
if let Err(e) = intercept(upgraded, target, engine).await {
|
||||
if let Err(e) = intercept(upgraded, target, client, engine).await {
|
||||
debug!("Tunnel to {host}:{port} ended: {}", error_chain(e.as_ref()));
|
||||
}
|
||||
});
|
||||
@@ -248,7 +260,12 @@ fn handle_connect(req: Request<Incoming>, engine: Arc<Engine>) -> Response<BoxBo
|
||||
Response::new(text_body(Bytes::new()))
|
||||
}
|
||||
|
||||
async fn intercept<S>(mut client: S, target: Target, engine: Arc<Engine>) -> Result<(), BoxError>
|
||||
async fn intercept<S>(
|
||||
mut client: S,
|
||||
target: Target,
|
||||
conn: ClientConn,
|
||||
engine: Arc<Engine>,
|
||||
) -> Result<(), BoxError>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
@@ -308,7 +325,7 @@ where
|
||||
|
||||
let tls = Rewind::new(Bytes::from(buf), tls);
|
||||
let target = Arc::new(Target { server_name, ..target });
|
||||
serve_http1(tls, move |req| forward_https(req, target.clone(), engine.clone())).await?;
|
||||
serve_http1(tls, move |req| forward_https(req, target.clone(), conn, engine.clone())).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -395,11 +412,12 @@ async fn connect_upstream(
|
||||
async fn forward_https(
|
||||
mut req: Request<Incoming>,
|
||||
target: Arc<Target>,
|
||||
client: ClientConn,
|
||||
engine: Arc<Engine>,
|
||||
) -> Result<Response<BoxBody>, Infallible> {
|
||||
let path = req.uri().path_and_query().map(|pq| pq.to_string()).unwrap_or_else(|| "/".into());
|
||||
let url = format!("https://{}{path}", target.authority);
|
||||
let flow = Flow::begin(engine.clone(), &req, url.clone());
|
||||
let flow = Flow::begin(engine.clone(), client, &req, url.clone());
|
||||
|
||||
let client_upgrade: Option<OnUpgrade> =
|
||||
req.headers().contains_key(UPGRADE).then(|| hyper::upgrade::on(&mut req));
|
||||
|
||||
Reference in new issue
Block a user