From bd33520da1a44d5e10557e5546292700c8cdf2d9 Mon Sep 17 00:00:00 2001 From: Ray Tien Date: Sat, 19 Sep 2026 08:57:13 +0800 Subject: [PATCH 1/9] feat: add TLS ALPN HTTP2 forwarding and isolated CONNECT streams Add opt-in h2c, bounded stream/request resources, independent per-stream idle and cancellation lifetimes, tracked H2 drivers, and local TLS/H2 regressions. Preserve HTTP1 forwarding and end-to-end origin TLS in CONNECT. --- .github/workflows/prepare-http2.yml | 31 ++ Cargo.toml | 6 +- src/config.rs | 207 ++++------ src/connection.rs | 490 +++++++++++------------- src/exchange.rs | 102 +++++ src/lib.rs | 5 +- src/protocol.rs | 54 +++ src/runtime.rs | 43 ++- src/tls.rs | 36 ++ src/transport.rs | 123 ++---- tests/http2.rs | 574 ++++++++++++++++++++++++++++ 11 files changed, 1164 insertions(+), 507 deletions(-) create mode 100644 .github/workflows/prepare-http2.yml create mode 100644 src/exchange.rs create mode 100644 src/protocol.rs create mode 100644 src/tls.rs create mode 100644 tests/http2.rs diff --git a/.github/workflows/prepare-http2.yml b/.github/workflows/prepare-http2.yml new file mode 100644 index 0000000..c78e547 --- /dev/null +++ b/.github/workflows/prepare-http2.yml @@ -0,0 +1,31 @@ +name: Prepare HTTP2 branch +on: + push: + branches: [feat/http2-proxy] + paths: [Cargo.toml, src/**, tests/**] +permissions: + contents: write +jobs: + prepare: + if: github.ref == 'refs/heads/feat/http2-proxy' + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - name: Normalize source and lock dependencies on this feature branch only + run: | + cargo generate-lockfile + cargo fmt --all + git config user.name 'github-actions[bot]' + git config user.email '41898282+github-actions[bot]@users.noreply.github.com' + git add Cargo.lock src tests + if ! git diff --cached --quiet; then + git commit -m 'build: lock HTTP2 TLS dependencies and format sources' + git push origin HEAD:feat/http2-proxy + fi + - run: cargo test --all-targets --locked + - run: cargo clippy --all-targets --locked -- -D warnings + - run: cargo build --release --locked diff --git a/Cargo.toml b/Cargo.toml index 39d5802..00613a4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,16 +16,20 @@ bytes = "1" clap = { version = "4", features = ["derive"] } env_logger = "0.11" http-body-util = "0.1" -hyper = { version = "1", features = ["client", "server", "http1"] } +hyper = { version = "1.11.1", features = ["client", "server", "http1", "http2"] } hyper-util = { version = "0.1", features = ["tokio"] } ipnet = "2" log = "0.4" regex = "1" +rustls-pemfile = "2" tokio = { version = "1", features = ["rt-multi-thread", "net", "io-util", "sync", "time", "signal", "macros"] } +tokio-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] } tokio-util = { version = "0.7", features = ["rt"] } [dev-dependencies] criterion = "0.5" +h2 = "0.4" +rcgen = "0.13" tempfile = "3" [[bench]] diff --git a/src/config.rs b/src/config.rs index 852cfbc..0315f42 100644 --- a/src/config.rs +++ b/src/config.rs @@ -32,6 +32,13 @@ pub struct Config { pub disable_via_header: bool, pub via_proxy_name: String, pub stat_host: Option, + pub http2: bool, + pub allow_h2c: bool, + pub max_concurrent_streams: u32, + pub max_inflight_requests: usize, + pub tls_cert: Option, + pub tls_key: Option, + pub tls_handshake_timeout: u64, } impl Default for Config { @@ -57,6 +64,13 @@ impl Default for Config { disable_via_header: false, via_proxy_name: "tinyproxy-rust".into(), stat_host: None, + http2: true, + allow_h2c: false, + max_concurrent_streams: 32, + max_inflight_requests: 256, + tls_cert: None, + tls_key: None, + tls_handshake_timeout: 10, } } } @@ -67,16 +81,13 @@ impl Config { let text = fs::read_to_string(path) .with_context(|| format!("Cannot read configuration: {}", path.display()))?; let mut config = Self::parse(&text)?; - // Resolve relative filter paths against the configuration, not the cwd. - if let Some(file) = &config.filter_file { - if Path::new(file).is_relative() { - config.filter_file = Some( - path.parent() - .unwrap_or_else(|| Path::new(".")) - .join(file) - .to_string_lossy() - .into_owned(), - ); + // All policy and TLS paths are relative to the configuration, not cwd. + for file in [&mut config.filter_file, &mut config.tls_cert, &mut config.tls_key] { + if let Some(value) = file { + if Path::new(value).is_relative() { + *value = path.parent().unwrap_or_else(|| Path::new(".")) + .join(&*value).to_string_lossy().into_owned(); + } } } Ok(config) @@ -87,43 +98,24 @@ impl Config { let mut saw_listen = false; let mut saw_connect_port = false; for (index, line) in text.lines().enumerate() { - let parse_line = || -> Result> { tokenize(line) }; - let args = parse_line().with_context(|| format!("Line {}", index + 1))?; - if args.is_empty() { - continue; - } - let apply = |config: &mut Self, - saw_listen: &mut bool, - saw_connect_port: &mut bool| - -> Result<()> { - ensure!( - args[0].bytes().all(|c| c.is_ascii_alphabetic()), - "Invalid directive; use Tinyproxy key/value syntax, not TOML" - ); + let args = tokenize(line).with_context(|| format!("Line {}", index + 1))?; + if args.is_empty() { continue; } + let apply = |config: &mut Self, saw_listen: &mut bool, saw_connect_port: &mut bool| -> Result<()> { + ensure!(args[0].starts_with(|c: char| c.is_ascii_alphabetic()) + && args[0].bytes().all(|c| c.is_ascii_alphanumeric()), + "Invalid directive; use Tinyproxy key/value syntax, not TOML"); let key = args[0].to_ascii_lowercase(); if key == "basicauth" { let (username, password) = match args.as_slice() { [_, user, pass] => (user.clone(), pass.clone()), - [_, legacy] => legacy - .split_once(':') + [_, legacy] => legacy.split_once(':') .map(|(user, pass)| (user.to_owned(), pass.to_owned())) .context("BasicAuth requires a username and password")?, _ => bail!("BasicAuth requires a username and password"), }; - ensure!( - !username.is_empty() && !password.is_empty() && !username.contains(':'), - "Invalid BasicAuth credentials" - ); - ensure!( - !config - .basic_auth - .iter() - .any(|auth| auth.username == username), - "Duplicate BasicAuth username" - ); - config - .basic_auth - .push(BasicAuthConfig { username, password }); + ensure!(!username.is_empty() && !password.is_empty() && !username.contains(':'), "Invalid BasicAuth credentials"); + ensure!(!config.basic_auth.iter().any(|auth| auth.username == username), "Duplicate BasicAuth username"); + config.basic_auth.push(BasicAuthConfig { username, password }); return Ok(()); } ensure!(args.len() == 2, "{} requires one value", args[0]); @@ -132,33 +124,17 @@ impl Config { "port" => config.port = value.parse().context("Invalid Port")?, "listen" => { let address = value.parse().context("Invalid Listen address")?; - if !*saw_listen { - config.listen_addresses.clear(); - *saw_listen = true; - } + if !*saw_listen { config.listen_addresses.clear(); *saw_listen = true; } config.listen_addresses.push(address); } - "bind" => { - config.bind_address = Some(value.parse().context("Invalid Bind address")?); - } + "bind" => config.bind_address = Some(value.parse().context("Invalid Bind address")?), "timeout" => config.timeout = value.parse().context("Invalid Timeout")?, - "headertimeout" => { - config.header_timeout = value.parse().context("Invalid HeaderTimeout")?; - } - "connecttimeout" => { - config.connect_timeout = value.parse().context("Invalid ConnectTimeout")?; - } - "shutdowntimeout" => { - config.shutdown_timeout = - value.parse().context("Invalid ShutdownTimeout")?; - } - "maxclients" => { - config.max_clients = value.parse().context("Invalid MaxClients")?; - } + "headertimeout" => config.header_timeout = value.parse().context("Invalid HeaderTimeout")?, + "connecttimeout" => config.connect_timeout = value.parse().context("Invalid ConnectTimeout")?, + "shutdowntimeout" => config.shutdown_timeout = value.parse().context("Invalid ShutdownTimeout")?, + "maxclients" => config.max_clients = value.parse().context("Invalid MaxClients")?, "loglevel" => config.log_level = value.clone(), - "allow" | "deny" => { - config.acl_rules.push((key == "allow", value.clone())); - } + "allow" | "deny" => config.acl_rules.push((key == "allow", value.clone())), "filter" => config.filter_file = Some(value.clone()), "filterurls" => config.filter_urls = parse_bool(value)?, "filterextended" => config.filter_extended = parse_bool(value)?, @@ -166,19 +142,20 @@ impl Config { "filterdefaultdeny" => config.filter_default_deny = parse_bool(value)?, "connectport" => { let port = value.parse().context("Invalid ConnectPort")?; - if !*saw_connect_port { - config.connect_ports.clear(); - *saw_connect_port = true; - } + if !*saw_connect_port { config.connect_ports.clear(); *saw_connect_port = true; } config.connect_ports.push(port); } "disableviaheader" => config.disable_via_header = parse_bool(value)?, "viaproxyname" => config.via_proxy_name = value.clone(), "stathost" => config.stat_host = Some(value.to_ascii_lowercase()), - _ => bail!( - "Unsupported directive: {} (see README compatibility table)", - args[0] - ), + "http2" => config.http2 = parse_bool(value)?, + "allowh2c" => config.allow_h2c = parse_bool(value)?, + "maxconcurrentstreams" => config.max_concurrent_streams = value.parse().context("Invalid MaxConcurrentStreams")?, + "maxinflightrequests" => config.max_inflight_requests = value.parse().context("Invalid MaxInflightRequests")?, + "tlscert" => config.tls_cert = Some(value.clone()), + "tlskey" => config.tls_key = Some(value.clone()), + "tlshandshaketimeout" => config.tls_handshake_timeout = value.parse().context("Invalid TLSHandshakeTimeout")?, + _ => bail!("Unsupported directive: {} (see README compatibility table)", args[0]), } Ok(()) }; @@ -186,10 +163,7 @@ impl Config { .with_context(|| format!("Line {}", index + 1))?; } if config.connect_ports.contains(&0) { - ensure!( - config.connect_ports.len() == 1, - "ConnectPort 0 cannot be combined with other ports" - ); + ensure!(config.connect_ports.len() == 1, "ConnectPort 0 cannot be combined with other ports"); config.connect_ports.clear(); } config.validate()?; @@ -197,50 +171,23 @@ impl Config { } pub fn validate(&self) -> Result<()> { - ensure!( - !self.listen_addresses.is_empty(), - "At least one Listen address is required" - ); - ensure!( - self.max_clients > 0 && self.max_clients <= 1_000_000, - "MaxClients must be in 1..=1000000" - ); - ensure!( - [ - self.timeout, - self.header_timeout, - self.connect_timeout, - self.shutdown_timeout - ] - .iter() - .all(|seconds| (1..=86400).contains(seconds)), - "Timeouts must be in 1..=86400 seconds" - ); - ensure!( - self.listen_addresses.iter().all(IpAddr::is_loopback) - || !self.acl_rules.is_empty() - || !self.basic_auth.is_empty(), - "Non-loopback Listen requires explicit Allow/Deny rules or BasicAuth" - ); - ensure!( - !self.via_proxy_name.is_empty() - && self - .via_proxy_name - .bytes() - .all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)), - "ViaProxyName must contain only letters, digits, dots, underscores or hyphens" - ); - self.log_level - .parse::() - .context("Invalid LogLevel")?; - ensure!( - !self.filter_default_deny || self.filter_file.is_some(), - "FilterDefaultDeny requires Filter" - ); - ensure!( - !self.connect_ports.contains(&0), - "Use an empty port list to disable CONNECT in the library API" - ); + ensure!(!self.listen_addresses.is_empty(), "At least one Listen address is required"); + ensure!((1..=1_000_000).contains(&self.max_clients), "MaxClients must be in 1..=1000000"); + ensure!((1..=1_000_000).contains(&self.max_inflight_requests), "MaxInflightRequests must be in 1..=1000000"); + ensure!((1..=1024).contains(&self.max_concurrent_streams), "MaxConcurrentStreams must be in 1..=1024"); + ensure!([self.timeout, self.header_timeout, self.connect_timeout, self.shutdown_timeout, self.tls_handshake_timeout] + .iter().all(|seconds| (1..=86400).contains(seconds)), "Timeouts must be in 1..=86400 seconds"); + ensure!(self.listen_addresses.iter().all(IpAddr::is_loopback) + || !self.acl_rules.is_empty() || !self.basic_auth.is_empty(), + "Non-loopback Listen requires explicit Allow/Deny rules or BasicAuth"); + ensure!(!self.via_proxy_name.is_empty() && self.via_proxy_name.bytes().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)), + "ViaProxyName must contain only letters, digits, dots, underscores or hyphens"); + self.log_level.parse::().context("Invalid LogLevel")?; + ensure!(!self.filter_default_deny || self.filter_file.is_some(), "FilterDefaultDeny requires Filter"); + ensure!(!self.connect_ports.contains(&0), "Use an empty port list to disable CONNECT in the library API"); + ensure!(self.tls_cert.is_some() == self.tls_key.is_some(), "TLSCert and TLSKey must be configured together"); + ensure!(!self.allow_h2c || self.http2, "AllowH2C requires HTTP2 Yes"); + ensure!(!self.allow_h2c || self.tls_cert.is_none(), "AllowH2C is only for plaintext listeners; TLS uses ALPN"); Ok(()) } } @@ -263,33 +210,19 @@ fn tokenize(line: &str) -> Result> { if let Some(delimiter) = quote { if c == delimiter { quote = None; - } else if c == '\\' - && chars - .peek() - .is_some_and(|next| *next == delimiter || *next == '\\') - { + } else if c == '\\' && chars.peek().is_some_and(|next| *next == delimiter || *next == '\\') { word.push(chars.next().expect("peeked character")); - } else { - word.push(c); - } + } else { word.push(c); } } else if c == '"' || c == '\'' { quote = Some(c); active = true; } else if c == '#' && !active { break; } else if c.is_whitespace() { - if active { - words.push(std::mem::take(&mut word)); - active = false; - } - } else { - word.push(c); - active = true; - } + if active { words.push(std::mem::take(&mut word)); active = false; } + } else { word.push(c); active = true; } } ensure!(quote.is_none(), "Unterminated quoted value"); - if active { - words.push(word); - } + if active { words.push(word); } Ok(words) } diff --git a/src/connection.rs b/src/connection.rs index 5105341..1ca2c42 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -1,17 +1,16 @@ -use crate::runtime::{ConnectionGuard, Runtime}; +use crate::exchange::{self, Body, BoxError, CancelOnDrop, Exchange}; +use crate::protocol::{self, BoxIo}; +use crate::runtime::{ConnectionGuard, Executor, Runtime}; use crate::transport::{self, Activity, ActivityIo}; -use anyhow::Result; +use anyhow::{ensure, Result}; use bytes::Bytes; -use http_body_util::{combinators::UnsyncBoxBody, BodyExt, Full}; +use http_body_util::{BodyExt, Full}; use hyper::body::Incoming; -use hyper::header::{ - HeaderMap, HeaderName, HeaderValue, CONNECTION, HOST, PROXY_AUTHENTICATE, VIA, -}; +use hyper::header::{HeaderMap, HeaderName, HeaderValue, CONNECTION, COOKIE, HOST, PROXY_AUTHENTICATE, VIA}; use hyper::service::service_fn; use hyper::{Method, Request, Response, StatusCode, Uri, Version}; use hyper_util::rt::{TokioIo, TokioTimer}; use std::convert::Infallible; -use std::error::Error; use std::net::SocketAddr; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; @@ -21,8 +20,6 @@ use tokio::net::TcpStream; use tokio::time::timeout; use tokio_util::sync::CancellationToken; -type BoxError = Box; -type Body = UnsyncBoxBody; type HttpResult = std::result::Result; struct Context { @@ -30,219 +27,235 @@ struct Context { guard: Arc, activity: Activity, cancelled: CancellationToken, - upgraded: AtomicBool, + http1_upgraded: AtomicBool, } -pub async fn serve( - mut stream: TcpStream, - address: SocketAddr, - runtime: Arc, - guard: Arc, -) -> Result<()> { +pub async fn serve(mut stream: TcpStream, address: SocketAddr, runtime: Arc, guard: Arc) -> Result<()> { + // Reject before TLS work; never send plaintext errors on a TLS/H2 listener. if !runtime.acl.is_allowed(address.ip()) { runtime.metrics.rejected.fetch_add(1, Ordering::Relaxed); - let _ = timeout( - Duration::from_secs(2), - stream.write_all( - b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", - ), - ) - .await; + if runtime.tls.is_none() && !runtime.config.allow_h2c { + let _ = timeout(Duration::from_secs(2), stream.write_all( + b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + )).await; + } return Ok(()); } + let negotiate = async { + let (h2, io): (bool, BoxIo) = if let Some(acceptor) = &runtime.tls { + let tls = timeout(Duration::from_secs(runtime.config.tls_handshake_timeout), acceptor.accept(stream)).await??; + let h2 = tls.get_ref().1.alpn_protocol() == Some(b"h2"); + if h2 { + let (detected, io) = timeout(Duration::from_secs(runtime.config.header_timeout), protocol::detect(Box::new(tls))).await??; + ensure!(detected, "HTTP/2 ALPN requires an HTTP/2 preface"); + (true, io) + } else { + // Absent ALPN means HTTP/1. Do not sniff and silently override it. + (false, Box::new(tls)) + } + } else if runtime.config.allow_h2c { + timeout(Duration::from_secs(runtime.config.header_timeout), protocol::detect(Box::new(stream))).await?? + } else { + (false, Box::new(stream)) + }; + Ok::<_, anyhow::Error>((h2, io)) + }; + let (h2, stream) = tokio::select! { + result = negotiate => result?, + _ = runtime.shutdown.cancelled() => return Ok(()), + _ = runtime.force_shutdown.cancelled() => return Ok(()), + }; + if h2 { runtime.metrics.http2_connections.fetch_add(1, Ordering::Relaxed); } let activity = Activity::new(Duration::from_secs(runtime.config.timeout)); - let io = TokioIo::new(ActivityIo::new( - stream, - activity.clone(), - Some(runtime.metrics.clone()), - )); + let io = TokioIo::new(ActivityIo::new(stream, activity.clone(), Some(runtime.metrics.clone()))); let context = Arc::new(Context { - runtime: runtime.clone(), - guard, - activity, - cancelled: CancellationToken::new(), - upgraded: AtomicBool::new(false), + runtime: runtime.clone(), guard, activity, + cancelled: CancellationToken::new(), http1_upgraded: AtomicBool::new(false), }); let service_context = context.clone(); - let service = service_fn(move |request| { + let service = service_fn(move |request: Request| { let context = service_context.clone(); async move { - let response = match handle(request, context).await { + let version = request.version(); + let mut response = match handle(request, context).await { Ok(response) => response, - Err((status, message)) => error_response(status, message), + Err((status, message)) => error_response(status, message, version), }; + *response.version_mut() = version; Ok::<_, Infallible>(response) } }); - let mut builder = hyper::server::conn::http1::Builder::new(); - builder - .timer(TokioTimer::new()) - .header_read_timeout(Duration::from_secs(runtime.config.header_timeout)) - .max_buf_size(16 * 1024) - .half_close(true); - let connection = builder.serve_connection(io, service).with_upgrades(); - tokio::pin!(connection); - let result = tokio::select! { - result = &mut connection => result.map_err(Into::into), - _ = context.activity.expired() => Ok(()), - _ = runtime.force_shutdown.cancelled() => Ok(()), - _ = runtime.shutdown.cancelled() => { - connection.as_mut().graceful_shutdown(); + // Both protocol drivers have the same graceful/forced shutdown contract. + macro_rules! drive { + ($connection:expr) => {{ + let connection = $connection; + tokio::pin!(connection); tokio::select! { - result = &mut connection => result.map_err(Into::into), + result = &mut connection => result.map_err(anyhow::Error::from), _ = context.activity.expired() => Ok(()), _ = runtime.force_shutdown.cancelled() => Ok(()), + _ = runtime.shutdown.cancelled() => { + connection.as_mut().graceful_shutdown(); + tokio::select! { + result = &mut connection => result.map_err(anyhow::Error::from), + _ = context.activity.expired() => Ok(()), + _ = runtime.force_shutdown.cancelled() => Ok(()), + } + } } - } - }; - if !context.upgraded.load(Ordering::Relaxed) { - context.cancelled.cancel(); + }}; } + let result = if h2 { + let executor = Executor { tasks: runtime.tasks.clone(), force_shutdown: runtime.force_shutdown.clone() }; + let mut builder = hyper::server::conn::http2::Builder::new(executor); + builder.timer(TokioTimer::new()) + .max_concurrent_streams(runtime.config.max_concurrent_streams) + .max_header_list_size(16 * 1024) + .header_table_size(4096) + .max_frame_size(16 * 1024) + .initial_stream_window_size(65535) + .initial_connection_window_size(1024 * 1024) + .max_send_buf_size(64 * 1024) + .max_pending_accept_reset_streams(20) + .max_local_error_reset_streams(100) + .adaptive_window(false); + // Ordinary CONNECT works without advertising RFC 8441 extended CONNECT. + drive!(builder.serve_connection(io, service)) + } else { + let mut builder = hyper::server::conn::http1::Builder::new(); + builder.timer(TokioTimer::new()) + .header_read_timeout(Duration::from_secs(runtime.config.header_timeout)) + .max_buf_size(16 * 1024).half_close(true); + drive!(builder.serve_connection(io, service).with_upgrades()) + }; + // An H2 CONNECT upgrades ONE stream, never ownership of the connection. + if h2 || !context.http1_upgraded.load(Ordering::Relaxed) { context.cancelled.cancel(); } result } -async fn handle( - mut request: Request, - context: Arc, -) -> HttpResult> { +async fn handle(request: Request, context: Arc) -> HttpResult> { let runtime = &context.runtime; runtime.metrics.requests.fetch_add(1, Ordering::Relaxed); if !runtime.auth.authenticate(request.headers()) { - runtime - .metrics - .auth_failures - .fetch_add(1, Ordering::Relaxed); - return Err(( - StatusCode::PROXY_AUTHENTICATION_REQUIRED, - "Proxy authentication required", - )); + runtime.metrics.auth_failures.fetch_add(1, Ordering::Relaxed); + return Err((StatusCode::PROXY_AUTHENTICATION_REQUIRED, "Proxy authentication required")); + } + if request.extensions().get::().is_some() { + return Err((StatusCode::NOT_IMPLEMENTED, "Extended CONNECT is not supported")); + } + if request.version() == Version::HTTP_2 { + validate_h2_headers(request.headers()).map_err(|m| (StatusCode::BAD_REQUEST, m))?; } let target = Target::parse(&request).map_err(|message| (StatusCode::BAD_REQUEST, message))?; let is_connect = request.method() == Method::CONNECT; - if !runtime - .filter - .is_allowed(&target.host, &target.url, is_connect) - { + if !runtime.filter.is_allowed(&target.host, &target.url, is_connect) { return Err((StatusCode::FORBIDDEN, "Blocked by filter")); } + if is_connect && !runtime.config.connect_ports.contains(&target.port) { + return Err((StatusCode::FORBIDDEN, "CONNECT port not allowed")); + } + let permit = runtime.requests.clone().try_acquire_owned().map_err(|_| { + runtime.metrics.requests_rejected.fetch_add(1, Ordering::Relaxed); + (StatusCode::SERVICE_UNAVAILABLE, "Proxy request capacity reached") + })?; + let state = Exchange::new(permit, context.guard.clone(), runtime.metrics.clone(), + context.cancelled.child_token(), Duration::from_secs(runtime.config.timeout)); + let mut lease = CancelOnDrop(Some(state.clone())); + let result = tokio::select! { + result = forward(request, target, context.clone(), state.clone()) => result, + _ = state.activity.expired() => Err((StatusCode::GATEWAY_TIMEOUT, "Request idle timeout")), + _ = state.cancelled.cancelled() => Err((StatusCode::BAD_GATEWAY, "Request cancelled")), + _ = runtime.force_shutdown.cancelled() => Err((StatusCode::SERVICE_UNAVAILABLE, "Proxy shutting down")), + }; + if result.is_ok() { lease.0 = None; } + result +} + +async fn forward(mut request: Request, target: Target, context: Arc, state: Arc) -> HttpResult> { + let runtime = &context.runtime; + let version = request.version(); + let is_connect = request.method() == Method::CONNECT; if !is_connect && runtime.config.stat_host.as_deref() == Some(target.host.as_str()) { if request.method() != Method::GET && request.method() != Method::HEAD { - return Err(( - StatusCode::METHOD_NOT_ALLOWED, - "Statistics require GET or HEAD", - )); + return Err((StatusCode::METHOD_NOT_ALLOWED, "Statistics require GET or HEAD")); } - return Ok(text_response( - StatusCode::OK, - runtime.metrics.to_html(), - "text/html; charset=utf-8", - )); + let mut response = text_response(StatusCode::OK, runtime.metrics.to_html(), "text/html; charset=utf-8"); + if request.method() == Method::HEAD { *response.body_mut() = empty_body(); } + return Ok(response.map(|body| exchange::track(body, state, true))); } if is_connect { - if !runtime.config.connect_ports.contains(&target.port) { - return Err((StatusCode::FORBIDDEN, "CONNECT port not allowed")); - } - // Validate hop-by-hop syntax before switching protocols. - strip_hop_by_hop(request.headers_mut()) - .map_err(|message| (StatusCode::BAD_REQUEST, message))?; + strip_hop_by_hop(request.headers_mut()).map_err(|m| (StatusCode::BAD_REQUEST, m))?; let target_stream = dial(&target, runtime).await?; let upgrade = hyper::upgrade::on(&mut request); - context.upgraded.store(true, Ordering::Relaxed); - let tunnel_context = context.clone(); + if version != Version::HTTP_2 { context.http1_upgraded.store(true, Ordering::Relaxed); } + let force = runtime.force_shutdown.clone(); runtime.tasks.spawn(async move { - let context = tunnel_context; let tunnel = async { let upgraded = upgrade.await?; - let mut client = TokioIo::new(upgraded); - let mut target = ActivityIo::new(target_stream, context.activity.clone(), None); - // Hyper's upgrade preserves bytes read beyond the CONNECT header. - // Tokio preserves half-close and finishes the remaining direction. + let mut client = ActivityIo::new(TokioIo::new(upgraded), state.activity.clone(), None); + let mut target = ActivityIo::new(target_stream, state.activity.clone(), None); copy_bidirectional(&mut client, &mut target).await?; Ok::<_, BoxError>(()) }; tokio::select! { _ = tunnel => {}, - _ = context.activity.expired() => {}, - _ = context.runtime.force_shutdown.cancelled() => {}, + _ = state.activity.expired() => {}, + _ = state.cancelled.cancelled() => {}, + _ = force.cancelled() => {}, } - context.cancelled.cancel(); + state.cancelled.cancel(); }); - let mut response = text_response(StatusCode::OK, String::new(), "text/plain"); - response.headers_mut().remove("content-length"); - response.headers_mut().remove("content-type"); - return Ok(response); + // No Content-Length or Transfer-Encoding on successful CONNECT. + return Ok(Response::new(empty_body())); } if request.headers().contains_key("upgrade") { return Err((StatusCode::NOT_IMPLEMENTED, "HTTP Upgrade is not supported")); } - strip_hop_by_hop(request.headers_mut()) - .map_err(|message| (StatusCode::BAD_REQUEST, message))?; + strip_hop_by_hop(request.headers_mut()).map_err(|m| (StatusCode::BAD_REQUEST, m))?; + if version == Version::HTTP_2 { + coalesce_cookies(request.headers_mut()).map_err(|m| (StatusCode::BAD_REQUEST, m))?; + } let target_stream = dial(&target, runtime).await?; request.headers_mut().insert(HOST, target.authority); - add_via(request.headers_mut(), runtime); + add_via(request.headers_mut(), runtime, version); *request.uri_mut() = target.path; *request.version_mut() = Version::HTTP_11; - - let io = TokioIo::new(ActivityIo::new( - target_stream, - context.activity.clone(), - None, - )); - let (mut sender, connection) = hyper::client::conn::http1::handshake(io) - .await + request.extensions_mut().clear(); + let request = request.map(|body| exchange::track(body, state.clone(), false)); + let io = TokioIo::new(ActivityIo::new(target_stream, state.activity.clone(), None)); + let (mut sender, connection) = hyper::client::conn::http1::handshake(io).await .map_err(|_| (StatusCode::BAD_GATEWAY, "Upstream handshake failed"))?; - let driver_context = context.clone(); + let driver_state = state.clone(); + let force = runtime.force_shutdown.clone(); runtime.tasks.spawn(async move { - // Keep the connection permit until this socket has also been released. - let _guard = driver_context.guard.clone(); tokio::select! { _ = connection => {}, - _ = driver_context.activity.expired() => {}, - _ = driver_context.cancelled.cancelled() => {}, - _ = driver_context.runtime.force_shutdown.cancelled() => {}, + _ = driver_state.activity.expired() => {}, + _ = driver_state.cancelled.cancelled() => {}, + _ = force.cancelled() => {}, } }); - let mut response = sender - .send_request(request) - .await + let mut response = sender.send_request(request).await .map_err(|_| (StatusCode::BAD_GATEWAY, "Upstream request failed"))?; if response.status() == StatusCode::SWITCHING_PROTOCOLS { return Err((StatusCode::BAD_GATEWAY, "Unexpected upstream upgrade")); } - strip_hop_by_hop(response.headers_mut()) - .map_err(|message| (StatusCode::BAD_GATEWAY, message))?; - add_via(response.headers_mut(), runtime); - Ok(response.map(|body| { - body.map_err(|error| -> BoxError { Box::new(error) }) - .boxed_unsync() - })) + let upstream_version = response.version(); + strip_hop_by_hop(response.headers_mut()).map_err(|m| (StatusCode::BAD_GATEWAY, m))?; + add_via(response.headers_mut(), runtime, upstream_version); + Ok(response.map(|body| exchange::track(body, state, true))) } async fn dial(target: &Target, runtime: &Runtime) -> HttpResult { - transport::connect( - &target.host, - target.port, - runtime.config.bind_address, - runtime.config.connect_timeout, - ) - .await - .map_err(|error| { - if error.kind() == std::io::ErrorKind::TimedOut { - (StatusCode::GATEWAY_TIMEOUT, "Upstream connection timed out") - } else { - (StatusCode::BAD_GATEWAY, "Upstream connection failed") - } - }) -} - -struct Target { - host: String, - port: u16, - authority: HeaderValue, - path: Uri, - url: String, + transport::connect(&target.host, target.port, runtime.config.bind_address, runtime.config.connect_timeout) + .await.map_err(|error| { + if error.kind() == std::io::ErrorKind::TimedOut { + (StatusCode::GATEWAY_TIMEOUT, "Upstream connection timed out") + } else { (StatusCode::BAD_GATEWAY, "Upstream connection failed") } + }) } +struct Target { host: String, port: u16, authority: HeaderValue, path: Uri, url: String } impl Target { fn parse(request: &Request) -> std::result::Result { let connect = request.method() == Method::CONNECT; @@ -250,158 +263,113 @@ impl Target { if connect && (uri.scheme().is_some() || uri.path_and_query().is_some()) { return Err("CONNECT requires host:port authority form"); } - if uri - .scheme_str() - .is_some_and(|scheme| !scheme.eq_ignore_ascii_case("http")) - { + if uri.scheme_str().is_some_and(|scheme| !scheme.eq_ignore_ascii_case("http")) { return Err("Use CONNECT for HTTPS destinations"); } - if request.headers().get_all(HOST).iter().count() > 1 { - return Err("Multiple Host headers are not allowed"); - } + if request.headers().get_all(HOST).iter().count() > 1 { return Err("Multiple Host headers are not allowed"); } let authority = if let Some(authority) = uri.authority() { authority.clone() } else { - if connect { - return Err("CONNECT requires an authority"); - } - request - .headers() - .get(HOST) - .and_then(|value| value.to_str().ok()) - .ok_or("Host header required")? - .parse::() + if connect { return Err("CONNECT requires an authority"); } + request.headers().get(HOST).and_then(|v| v.to_str().ok()) + .ok_or("Host header required")?.parse::() .map_err(|_| "Invalid Host header")? }; - if authority.as_str().contains('@') || authority.host().is_empty() { - return Err("Invalid destination authority"); - } + if authority.as_str().contains('@') || authority.host().is_empty() { return Err("Invalid destination authority"); } let raw = authority.as_str(); - let explicit_port = raw - .rsplit_once(':') - .filter(|(before, _)| !raw.starts_with('[') || before.ends_with(']')); + let explicit_port = raw.rsplit_once(':').filter(|(before, _)| !raw.starts_with('[') || before.ends_with(']')); let port = if let Some((_, port)) = explicit_port { - port.parse::() - .ok() - .filter(|port| *port > 0) - .ok_or("Invalid destination port")? - } else if connect { - return Err("CONNECT requires an explicit port"); - } else { - 80 - }; - let host = authority - .host() - .trim_start_matches('[') - .trim_end_matches(']') - .trim_end_matches('.') - .to_ascii_lowercase(); - if host.is_empty() { - return Err("Empty destination host"); + port.parse::().ok().filter(|port| *port > 0).ok_or("Invalid destination port")? + } else if connect { return Err("CONNECT requires an explicit port"); } else { 80 }; + // H2 :authority and Host cannot name different destinations. + if request.version() == Version::HTTP_2 { + if let Some(host) = request.headers().get(HOST) { + let host = host.to_str().map_err(|_| "Invalid Host header")? + .parse::().map_err(|_| "Invalid Host header")?; + if !host.host().eq_ignore_ascii_case(authority.host()) || host.port_u16().unwrap_or(80) != port { + return Err("Host disagrees with :authority"); + } + } } - let path = uri - .path_and_query() - .map(|path| path.as_str()) - .unwrap_or("/"); - if !connect - && !path.starts_with('/') - && !(path == "*" && request.method() == Method::OPTIONS) - { + let host = authority.host().trim_start_matches('[').trim_end_matches(']').trim_end_matches('.').to_ascii_lowercase(); + if host.is_empty() { return Err("Empty destination host"); } + let path = uri.path_and_query().map(|p| p.as_str()).unwrap_or("/"); + if !connect && !path.starts_with('/') && !(path == "*" && request.method() == Method::OPTIONS) { return Err("Invalid HTTP request target"); } Ok(Self { - host, - port, - authority: HeaderValue::from_str(raw).map_err(|_| "Invalid authority header")?, - path: path.parse().map_err(|_| "Invalid request path")?, - url: format!("http://{}{}", raw, path), + host, port, authority: HeaderValue::from_str(raw).map_err(|_| "Invalid authority header")?, + path: path.parse().map_err(|_| "Invalid request path")?, url: format!("http://{}{}", raw, path), }) } } -fn strip_hop_by_hop(headers: &mut HeaderMap) -> std::result::Result<(), &'static str> { - if headers.contains_key("content-length") && headers.contains_key("transfer-encoding") { - return Err("Ambiguous message framing"); +fn validate_h2_headers(headers: &HeaderMap) -> std::result::Result<(), &'static str> { + for name in ["connection", "proxy-connection", "keep-alive", "transfer-encoding", "upgrade"] { + if headers.contains_key(name) { return Err("Connection-specific field in HTTP/2"); } + } + for value in headers.get_all("te") { + if !value.as_bytes().eq_ignore_ascii_case(b"trailers") { return Err("HTTP/2 TE must be trailers"); } + } + Ok(()) +} + +/// RFC 9113 section 8.2.3 requires split Cookie fields to be joined using '; '. +fn coalesce_cookies(headers: &mut HeaderMap) -> std::result::Result<(), &'static str> { + if headers.get_all(COOKIE).iter().count() < 2 { return Ok(()); } + let mut joined = Vec::new(); + for (index, cookie) in headers.get_all(COOKIE).iter().enumerate() { + if index != 0 { joined.extend_from_slice(b"; "); } + joined.extend_from_slice(cookie.as_bytes()); } + let value = HeaderValue::from_bytes(&joined).map_err(|_| "Invalid Cookie")?; + headers.insert(COOKIE, value); + Ok(()) +} + +pub(crate) fn strip_hop_by_hop(headers: &mut HeaderMap) -> std::result::Result<(), &'static str> { + if headers.contains_key("content-length") && headers.contains_key("transfer-encoding") { return Err("Ambiguous message framing"); } let mut nominated = Vec::new(); for value in headers.get_all(CONNECTION) { - for token in value - .to_str() - .map_err(|_| "Invalid Connection header")? - .split(',') - { + for token in value.to_str().map_err(|_| "Invalid Connection header")?.split(',') { let token = token.trim(); - if token.is_empty() { - continue; - } - let name = - HeaderName::from_bytes(token.as_bytes()).map_err(|_| "Invalid Connection token")?; - if name == "content-length" || name == "transfer-encoding" { - return Err("Connection must not nominate message framing headers"); - } + if token.is_empty() { continue; } + let name = HeaderName::from_bytes(token.as_bytes()).map_err(|_| "Invalid Connection token")?; + if name == "content-length" || name == "transfer-encoding" { return Err("Connection must not nominate message framing headers"); } nominated.push(name); } } - for name in nominated { + for name in nominated { headers.remove(name); } + for name in ["connection", "proxy-connection", "keep-alive", "proxy-authorization", "proxy-authenticate", "te", "trailer", "transfer-encoding", "upgrade"] { headers.remove(name); } - for name in [ - "connection", - "proxy-connection", - "keep-alive", - "proxy-authorization", - "proxy-authenticate", - "te", - "trailer", - "transfer-encoding", - "upgrade", - ] { - headers.remove(name); - } - // Hyper decodes and re-encodes body framing. Never blindly relay raw bytes - // after the first HTTP request; only CONNECT uses a byte tunnel. Ok(()) } -fn add_via(headers: &mut HeaderMap, runtime: &Runtime) { +fn add_via(headers: &mut HeaderMap, runtime: &Runtime, version: Version) { if !runtime.config.disable_via_header { - let value = HeaderValue::from_str(&format!("1.1 {}", runtime.config.via_proxy_name)) - .expect("startup-validated ViaProxyName"); + let protocol = match version { Version::HTTP_2 => "2", Version::HTTP_10 => "1.0", _ => "1.1" }; + let value = HeaderValue::from_str(&format!("{} {}", protocol, runtime.config.via_proxy_name)).expect("startup-validated ViaProxyName"); headers.append(VIA, value); } } - +fn empty_body() -> Body { + Full::new(Bytes::new()).map_err(|never| -> BoxError { match never {} }).boxed_unsync() +} fn text_response(status: StatusCode, text: String, content_type: &'static str) -> Response { let length = text.len(); - let body = Full::new(Bytes::from(text)) - .map_err(|never| -> BoxError { match never {} }) - .boxed_unsync(); + let body = Full::new(Bytes::from(text)).map_err(|never| -> BoxError { match never {} }).boxed_unsync(); let mut response = Response::new(body); *response.status_mut() = status; - response - .headers_mut() - .insert("content-type", HeaderValue::from_static(content_type)); - response.headers_mut().insert( - "content-length", - HeaderValue::from_str(&length.to_string()).expect("valid length"), - ); + response.headers_mut().insert("content-type", HeaderValue::from_static(content_type)); + response.headers_mut().insert("content-length", HeaderValue::from_str(&length.to_string()).expect("valid length")); response } - -fn error_response(status: StatusCode, message: &'static str) -> Response { - let mut response = text_response( - status, - format!("{}\n", message), - "text/plain; charset=utf-8", - ); - response - .headers_mut() - .insert(CONNECTION, HeaderValue::from_static("close")); +fn error_response(status: StatusCode, message: &'static str, version: Version) -> Response { + let mut response = text_response(status, format!("{}\n", message), "text/plain; charset=utf-8"); + if version != Version::HTTP_2 { response.headers_mut().insert(CONNECTION, HeaderValue::from_static("close")); } if status == StatusCode::PROXY_AUTHENTICATION_REQUIRED { - response.headers_mut().insert( - PROXY_AUTHENTICATE, - HeaderValue::from_static("Basic realm=\"Tinyproxy\""), - ); + response.headers_mut().insert(PROXY_AUTHENTICATE, HeaderValue::from_static("Basic realm=\"Tinyproxy\"")); } response } diff --git a/src/exchange.rs b/src/exchange.rs new file mode 100644 index 0000000..4e83c55 --- /dev/null +++ b/src/exchange.rs @@ -0,0 +1,102 @@ +use crate::runtime::{ConnectionGuard, Metrics}; +use crate::transport::Activity; +use bytes::Bytes; +use http_body_util::{combinators::UnsyncBoxBody, BodyExt}; +use hyper::body::{Body as HttpBody, Frame, SizeHint}; +use std::error::Error; +use std::pin::Pin; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::task::{Context, Poll}; +use std::time::Duration; +use tokio::sync::OwnedSemaphorePermit; +use tokio_util::sync::CancellationToken; + +pub type BoxError = Box; +pub type Body = UnsyncBoxBody; + +/// One HTTP exchange or CONNECT stream. A busy sibling cannot extend this idle +/// deadline. Hold capacity until both response body and upstream task are gone. +pub struct Exchange { + pub activity: Activity, + pub cancelled: CancellationToken, + _permit: OwnedSemaphorePermit, + _connection: Arc, + metrics: Arc, +} + +impl Exchange { + pub fn new(permit: OwnedSemaphorePermit, connection: Arc, metrics: Arc, cancelled: CancellationToken, idle: Duration) -> Arc { + metrics.inflight.fetch_add(1, Ordering::Relaxed); + Arc::new(Self { activity: Activity::new(idle), cancelled, _permit: permit, _connection: connection, metrics }) + } +} + +impl Drop for Exchange { + fn drop(&mut self) { + self.cancelled.cancel(); + self.metrics.inflight.fetch_sub(1, Ordering::Relaxed); + } +} + +/// Dropping a reset/cancelled service future immediately stops its upstream. +/// Disarm only when ownership has moved to a response body or tunnel task. +pub struct CancelOnDrop(pub Option>); +impl Drop for CancelOnDrop { + fn drop(&mut self) { + if let Some(state) = &self.0 { + state.cancelled.cancel(); + } + } +} + +struct TrackedBody { + inner: Body, + state: Arc, + cancel_on_drop: bool, +} + +pub fn track(body: B, state: Arc, cancel_on_drop: bool) -> Body +where + B: HttpBody + Send + 'static, + B::Error: Into, +{ + TrackedBody { inner: body.map_err(Into::into).boxed_unsync(), state, cancel_on_drop }.boxed_unsync() +} + +impl HttpBody for TrackedBody { + type Data = Bytes; + type Error = BoxError; + fn poll_frame(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll, BoxError>>> { + let result = Pin::new(&mut self.inner).poll_frame(cx); + match result { + Poll::Ready(Some(Ok(mut frame))) => { + if frame.data_ref().is_some_and(|data| !data.is_empty()) { + self.state.activity.touch(); + } + // Trailers must not reintroduce proxy credentials, routing, or + // hop-by-hop fields after the initial header sanitization. + if let Some(trailers) = frame.trailers_mut() { + if crate::connection::strip_hop_by_hop(trailers).is_err() { + return Poll::Ready(Some(Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid HTTP trailers").into()))); + } + for name in ["host", "content-length", "authorization", "cookie"] { + trailers.remove(name); + } + } + Poll::Ready(Some(Ok(frame))) + } + other => other, + } + } + fn is_end_stream(&self) -> bool { self.inner.is_end_stream() } + fn size_hint(&self) -> SizeHint { self.inner.size_hint() } +} + +impl Drop for TrackedBody { + fn drop(&mut self) { + if self.cancel_on_drop { + self.state.cancelled.cancel(); + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 180ae7a..4f8ad7e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,10 +1,13 @@ -//! HTTP/1 forward proxy and CONNECT tunnel with startup-validated policy. +//! HTTP/1 and HTTP/2 forward proxy with startup-validated policy. pub mod acl; pub mod auth; pub mod config; pub mod connection; +mod exchange; pub mod filter; +mod protocol; pub mod runtime; pub mod server; +mod tls; pub mod transport; diff --git a/src/protocol.rs b/src/protocol.rs new file mode 100644 index 0000000..c459223 --- /dev/null +++ b/src/protocol.rs @@ -0,0 +1,54 @@ +use std::io; +use std::pin::Pin; +use std::task::{Context, Poll}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf}; + +const H2_PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; + +pub trait Io: AsyncRead + AsyncWrite + Unpin + Send {} +impl Io for T {} +pub type BoxIo = Box; + +/// Preserve every sniffed byte, including fragmented HTTP/2 prefaces. The caller +/// supplies a total deadline, not a per-byte deadline. This is not h2c Upgrade. +pub async fn detect(mut io: BoxIo) -> io::Result<(bool, BoxIo)> { + let mut prefix = Vec::with_capacity(H2_PREFACE.len()); + for expected in H2_PREFACE { + let actual = io.read_u8().await?; + prefix.push(actual); + if actual != *expected { + return Ok((false, Box::new(PrefixedIo { io, prefix, offset: 0 }))); + } + } + Ok((true, Box::new(PrefixedIo { io, prefix, offset: 0 }))) +} + +struct PrefixedIo { + io: BoxIo, + prefix: Vec, + offset: usize, +} + +impl AsyncRead for PrefixedIo { + fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll> { + if self.offset < self.prefix.len() && buf.remaining() > 0 { + let count = (self.prefix.len() - self.offset).min(buf.remaining()); + buf.put_slice(&self.prefix[self.offset..self.offset + count]); + self.offset += count; + return Poll::Ready(Ok(())); + } + Pin::new(&mut self.io).poll_read(cx, buf) + } +} + +impl AsyncWrite for PrefixedIo { + fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { + Pin::new(&mut self.io).poll_write(cx, buf) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } +} diff --git a/src/runtime.rs b/src/runtime.rs index 3d7d919..15e9129 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -1,9 +1,11 @@ use crate::{acl::AccessControl, auth::Authenticator, config::Config, filter::Filter}; use anyhow::Result; +use std::future::Future; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Instant; -use tokio::sync::OwnedSemaphorePermit; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; +use tokio_rustls::TlsAcceptor; use tokio_util::{sync::CancellationToken, task::TaskTracker}; #[derive(Default)] @@ -16,6 +18,9 @@ pub struct Metrics { pub auth_failures: AtomicU64, pub bytes_in: AtomicU64, pub bytes_out: AtomicU64, + pub inflight: AtomicU64, + pub requests_rejected: AtomicU64, + pub http2_connections: AtomicU64, } impl Metrics { @@ -30,6 +35,9 @@ impl Metrics { ("authentication_failures", &self.auth_failures), ("client_bytes_received", &self.bytes_in), ("client_bytes_sent", &self.bytes_out), + ("inflight_requests", &self.inflight), + ("requests_rejected_capacity", &self.requests_rejected), + ("http2_connections_opened", &self.http2_connections), ] { page.push_str(&format!("{} {}\n", name, value.load(Ordering::Relaxed))); } @@ -47,6 +55,8 @@ pub struct Runtime { pub tasks: TaskTracker, pub shutdown: CancellationToken, pub force_shutdown: CancellationToken, + pub requests: Arc, + pub tls: Option, } impl Runtime { @@ -56,6 +66,8 @@ impl Runtime { acl: AccessControl::new(&config)?, auth: Authenticator::new(&config), filter: Filter::new(&config)?, + tls: crate::tls::acceptor(&config)?, + requests: Arc::new(Semaphore::new(config.max_inflight_requests)), config, metrics: Arc::new(Metrics::default()), tasks: TaskTracker::new(), @@ -65,6 +77,28 @@ impl Runtime { } } +/// Hyper's HTTP/2 stream and upgrade drivers must also participate in draining. +#[derive(Clone)] +pub struct Executor { + pub tasks: TaskTracker, + pub force_shutdown: CancellationToken, +} +impl hyper::rt::Executor for Executor +where + F: Future + Send + 'static, + F::Output: Send, +{ + fn execute(&self, future: F) { + let force = self.force_shutdown.clone(); + self.tasks.spawn(async move { + tokio::select! { + _ = future => {}, + _ = force.cancelled() => {}, + } + }); + } +} + /// Shared by the HTTP connection, its upstream drivers, and any CONNECT tunnel. /// The final reference releases MaxClients, including after an HTTP upgrade. pub struct ConnectionGuard { @@ -77,14 +111,9 @@ impl ConnectionGuard { pub fn new(permit: OwnedSemaphorePermit, metrics: Arc) -> Self { metrics.opened.fetch_add(1, Ordering::Relaxed); metrics.active.fetch_add(1, Ordering::Relaxed); - Self { - _permit: permit, - metrics, - _started: Instant::now(), - } + Self { _permit: permit, metrics, _started: Instant::now() } } } - impl Drop for ConnectionGuard { fn drop(&mut self) { self.metrics.active.fetch_sub(1, Ordering::Relaxed); diff --git a/src/tls.rs b/src/tls.rs new file mode 100644 index 0000000..749a5fc --- /dev/null +++ b/src/tls.rs @@ -0,0 +1,36 @@ +use crate::config::Config; +use anyhow::{ensure, Context, Result}; +use std::fs::File; +use std::io::BufReader; +use std::sync::Arc; +use tokio_rustls::{rustls, TlsAcceptor}; + +/// Load once, before binding. TLS protects the proxy hop; origin TLS is never +/// intercepted. No client CA, certificate bypass, or TLS early data is enabled. +pub fn acceptor(config: &Config) -> Result> { + let (Some(cert), Some(key)) = (&config.tls_cert, &config.tls_key) else { + return Ok(None); + }; + let mut cert_reader = BufReader::new(File::open(cert).context("Cannot read TLSCert")?); + let certificates = rustls_pemfile::certs(&mut cert_reader) + .collect::>>() + .context("Invalid TLSCert PEM")?; + ensure!(!certificates.is_empty(), "TLSCert contains no certificates"); + let mut key_reader = BufReader::new(File::open(key).context("Cannot read TLSKey")?); + let private_key = rustls_pemfile::private_key(&mut key_reader) + .context("Invalid TLSKey PEM")? + .context("TLSKey contains no private key")?; + let provider = Arc::new(rustls::crypto::ring::default_provider()); + let mut server = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions()? + .with_no_client_auth() + .with_single_cert(certificates, private_key) + .context("TLS certificate/key validation failed")?; + server.alpn_protocols = if config.http2 { + vec![b"h2".to_vec(), b"http/1.1".to_vec()] + } else { + vec![b"http/1.1".to_vec()] + }; + server.max_early_data_size = 0; + Ok(Some(TlsAcceptor::from(Arc::new(server)))) +} diff --git a/src/transport.rs b/src/transport.rs index 1c0cbab..4257476 100644 --- a/src/transport.rs +++ b/src/transport.rs @@ -10,154 +10,77 @@ use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio::net::{lookup_host, TcpSocket, TcpStream}; use tokio::time::{sleep_until, timeout, Instant}; -struct ActivityState { - started: Instant, - last_millis: AtomicU64, -} +struct ActivityState { started: Instant, last_millis: AtomicU64 } #[derive(Clone)] -pub struct Activity { - state: Arc, - idle: Duration, -} +pub struct Activity { state: Arc, idle: Duration } impl Activity { pub fn new(idle: Duration) -> Self { - Self { - state: Arc::new(ActivityState { - started: Instant::now(), - last_millis: AtomicU64::new(0), - }), - idle, - } + Self { state: Arc::new(ActivityState { started: Instant::now(), last_millis: AtomicU64::new(0) }), idle } } - - fn touch(&self) { - let elapsed = self - .state - .started - .elapsed() - .as_millis() - .min(u64::MAX as u128) as u64; + pub(crate) fn touch(&self) { + let elapsed = self.state.started.elapsed().as_millis().min(u64::MAX as u128) as u64; self.state.last_millis.fetch_max(elapsed, Ordering::Relaxed); } - fn deadline(&self) -> Instant { - self.state.started - + Duration::from_millis(self.state.last_millis.load(Ordering::Relaxed)) - + self.idle + self.state.started + Duration::from_millis(self.state.last_millis.load(Ordering::Relaxed)) + self.idle } - - /// Progress in either direction resets idle time; this is not a maximum - /// connection lifetime. No timer is allocated or reset per byte transfer. + /// Progress in either direction resets idle time, not maximum lifetime. pub async fn expired(&self) { loop { sleep_until(self.deadline()).await; - if Instant::now() >= self.deadline() { - return; - } + if Instant::now() >= self.deadline() { return; } } } } -pub struct ActivityIo { - inner: T, - activity: Activity, - metrics: Option>, -} - +pub struct ActivityIo { inner: T, activity: Activity, metrics: Option> } impl ActivityIo { pub fn new(inner: T, activity: Activity, metrics: Option>) -> Self { - Self { - inner, - activity, - metrics, - } + Self { inner, activity, metrics } } } - impl AsyncRead for ActivityIo { - fn poll_read( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - buf: &mut ReadBuf<'_>, - ) -> Poll> { + fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll> { let before = buf.filled().len(); let result = Pin::new(&mut self.inner).poll_read(cx, buf); if let Poll::Ready(Ok(())) = &result { let count = buf.filled().len() - before; if count > 0 { self.activity.touch(); - if let Some(metrics) = &self.metrics { - metrics.bytes_in.fetch_add(count as u64, Ordering::Relaxed); - } + if let Some(metrics) = &self.metrics { metrics.bytes_in.fetch_add(count as u64, Ordering::Relaxed); } } } result } } - impl AsyncWrite for ActivityIo { - fn poll_write( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - buf: &[u8], - ) -> Poll> { + fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { let result = Pin::new(&mut self.inner).poll_write(cx, buf); if let Poll::Ready(Ok(count)) = &result { if *count > 0 { self.activity.touch(); - if let Some(metrics) = &self.metrics { - metrics - .bytes_out - .fetch_add(*count as u64, Ordering::Relaxed); - } + if let Some(metrics) = &self.metrics { metrics.bytes_out.fetch_add(*count as u64, Ordering::Relaxed); } } } result } - - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.inner).poll_flush(cx) - } - - fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(&mut self.inner).poll_shutdown(cx) - } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Pin::new(&mut self.inner).poll_flush(cx) } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Pin::new(&mut self.inner).poll_shutdown(cx) } } -pub async fn connect( - host: &str, - port: u16, - bind: Option, - seconds: u64, -) -> io::Result { +pub async fn connect(host: &str, port: u16, bind: Option, seconds: u64) -> io::Result { timeout(Duration::from_secs(seconds), async { - let Some(bind) = bind else { - return TcpStream::connect((host, port)).await; - }; + let Some(bind) = bind else { return TcpStream::connect((host, port)).await; }; let addresses = lookup_host((host, port)).await?; - let mut last_error = io::Error::new( - io::ErrorKind::AddrNotAvailable, - "No address matches Bind family", - ); + let mut last_error = io::Error::new(io::ErrorKind::AddrNotAvailable, "No address matches Bind family"); for address in addresses { - if address.is_ipv4() != bind.is_ipv4() { - continue; - } - let socket = if bind.is_ipv4() { - TcpSocket::new_v4()? - } else { - TcpSocket::new_v6()? - }; + if address.is_ipv4() != bind.is_ipv4() { continue; } + let socket = if bind.is_ipv4() { TcpSocket::new_v4()? } else { TcpSocket::new_v6()? }; socket.bind(SocketAddr::new(bind, 0))?; - match socket.connect(address).await { - Ok(stream) => return Ok(stream), - Err(error) => last_error = error, - } + match socket.connect(address).await { Ok(stream) => return Ok(stream), Err(error) => last_error = error } } Err(last_error) - }) - .await - .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "DNS/connect deadline exceeded"))? + }).await.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "DNS/connect deadline exceeded"))? } diff --git a/tests/http2.rs b/tests/http2.rs new file mode 100644 index 0000000..ef68237 --- /dev/null +++ b/tests/http2.rs @@ -0,0 +1,574 @@ +use anyhow::{ensure, Result}; +use bytes::Bytes; +use h2::client::SendRequest; +use http_body_util::{BodyExt, Full}; +use hyper::{body::Incoming, service::service_fn, Method, Request, Response, Version}; +use hyper_util::rt::TokioIo; +use std::convert::Infallible; +use std::net::SocketAddr; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use std::time::Duration; +use tinyproxy_rust::{config::Config, runtime::Metrics, server::ProxyServer}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::Notify; +use tokio::task::{JoinHandle, JoinSet}; +use tokio::time::{sleep, timeout}; +use tokio_rustls::{rustls, TlsConnector}; +use tokio_util::sync::CancellationToken; + +const WAIT: Duration = Duration::from_secs(5); + +struct Proxy { + address: SocketAddr, + shutdown: CancellationToken, + metrics: Arc, + task: JoinHandle>, +} +impl Proxy { + async fn new(config: Config) -> Result { + let proxy = ProxyServer::bind(config).await?; + let address = proxy.local_addresses()?[0]; + let shutdown = proxy.shutdown_token(); + let metrics = proxy.metrics(); + Ok(Self { address, shutdown, metrics, task: tokio::spawn(proxy.run()) }) + } + async fn stop(mut self) -> Result<()> { + self.shutdown.cancel(); + timeout(WAIT, &mut self.task).await???; + assert_eq!(self.metrics.active.load(Ordering::Relaxed), 0); + assert_eq!(self.metrics.inflight.load(Ordering::Relaxed), 0); + Ok(()) + } +} +impl Drop for Proxy { + fn drop(&mut self) { self.shutdown.cancel(); self.task.abort(); } +} +fn config() -> Config { + Config { port: 0, allow_h2c: true, shutdown_timeout: 1, ..Config::default() } +} + +struct Client { sender: SendRequest, driver: JoinHandle<()> } +impl Client { + async fn new(io: T) -> Result + where T: AsyncRead + AsyncWrite + Unpin + Send + 'static { + let (sender, connection) = h2::client::handshake(io).await?; + let driver = tokio::spawn(async move { let _ = connection.await; }); + Ok(Self { sender, driver }) + } + async fn plain(proxy: &Proxy) -> Result { Self::new(TcpStream::connect(proxy.address).await?).await } + async fn send(&self, request: Request<()>, end: bool) -> Result<(h2::client::ResponseFuture, h2::SendStream)> { + let mut sender = timeout(WAIT, self.sender.clone().ready()).await??; + Ok(sender.send_request(request, end)?) + } + async fn get(&self, uri: String) -> Result> { + let request = Request::builder().version(Version::HTTP_2).uri(uri).body(())?; + let (response, _) = self.send(request, true).await?; + Ok(timeout(WAIT, response).await??) + } + async fn tunnel(&self, target: SocketAddr) -> Result<(h2::SendStream, h2::RecvStream)> { + let request = Request::builder().version(Version::HTTP_2).method(Method::CONNECT) + .uri(target.to_string()).body(())?; + let (response, send) = self.send(request, false).await?; + let response = timeout(WAIT, response).await??; + ensure!(response.status() == 200, "CONNECT failed: {}", response.status()); + ensure!(!response.headers().contains_key("content-length")); + ensure!(!response.headers().contains_key("connection")); + Ok((send, response.into_body())) + } +} +impl Drop for Client { fn drop(&mut self) { self.driver.abort(); } } + +async fn collect(mut body: h2::RecvStream) -> Result> { + timeout(WAIT, async { + let mut result = Vec::new(); + while let Some(data) = body.data().await { + let data = data?; + let count = data.len(); + result.extend_from_slice(&data); + body.flow_control().release_capacity(count)?; + } + Ok(result) + }).await? +} +async fn header(io: &mut T) -> Result { + timeout(WAIT, async { + let mut bytes = Vec::new(); + while !bytes.ends_with(b"\r\n\r\n") { + bytes.push(io.read_u8().await?); + ensure!(bytes.len() < 65536); + } + Ok(String::from_utf8(bytes)?) + }).await? +} +async fn inflight(proxy: &Proxy, count: u64) -> Result<()> { + timeout(WAIT, async { + while proxy.metrics.inflight.load(Ordering::Relaxed) != count { sleep(Duration::from_millis(5)).await; } + }).await?; + Ok(()) +} + +struct Origin { + address: SocketAddr, + task: JoinHandle<()>, + blocked: Arc, + release: Arc, +} +impl Origin { + async fn new(label: &'static str) -> Result { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let address = listener.local_addr()?; + let blocked = Arc::new(Notify::new()); + let release = Arc::new(Notify::new()); + let started = blocked.clone(); + let gate = release.clone(); + let task = tokio::spawn(async move { + let mut connections = JoinSet::new(); + loop { + tokio::select! { + accepted = listener.accept() => { + let Ok((stream, _)) = accepted else { break; }; + let started = started.clone(); + let gate = gate.clone(); + connections.spawn(async move { + let service = service_fn(move |request: Request| { + let started = started.clone(); + let gate = gate.clone(); + async move { + let (parts, body) = request.into_parts(); + if parts.uri.path() == "/blocked" { started.notify_one(); gate.notified().await; } + let bytes = body.collect().await.unwrap().to_bytes(); + let text = if parts.uri.path() == "/echo" { bytes } else if parts.uri.path() == "/headers" { + let value = |name: &str| parts.headers.get(name).and_then(|v| v.to_str().ok()).unwrap_or("absent"); + Bytes::from(format!("{} {}\nhost={}\nproxy-auth={}\nauth={}\ncookie={}\ncookies={}\nvia={}", + parts.method, parts.uri, value("host"), value("proxy-authorization"), value("authorization"), + value("cookie"), parts.headers.get_all("cookie").iter().count(), value("via"))) + } else { Bytes::from_static(label.as_bytes()) }; + let response = Response::builder().header("set-cookie", "a=1").header("set-cookie", "b=2") + .header("connection", "x-hop").header("x-hop", "remove-me").body(Full::new(text)).unwrap(); + Ok::<_, Infallible>(response) + } + }); + let _ = hyper::server::conn::http1::Builder::new().serve_connection(TokioIo::new(stream), service).await; + }); + } + _ = connections.join_next(), if !connections.is_empty() => {}, + } + } + }); + Ok(Self { address, task, blocked, release }) + } + fn url(&self, path: &str) -> String { format!("http://{}{}", self.address, path) } +} +impl Drop for Origin { fn drop(&mut self) { self.task.abort(); } } + +struct Certificate { + _directory: tempfile::TempDir, + cert: String, + key: String, + der: rustls::pki_types::CertificateDer<'static>, +} +impl Certificate { + fn new() -> Result { + let generated = rcgen::generate_simple_self_signed(vec!["localhost".into()])?; + let directory = tempfile::tempdir()?; + let cert = directory.path().join("cert.pem"); + let key = directory.path().join("key.pem"); + std::fs::write(&cert, generated.cert.pem())?; + std::fs::write(&key, generated.key_pair.serialize_pem())?; + Ok(Self { _directory: directory, cert: cert.to_string_lossy().into_owned(), key: key.to_string_lossy().into_owned(), der: generated.cert.der().clone() }) + } + fn config(&self) -> Config { + Config { port: 0, tls_cert: Some(self.cert.clone()), tls_key: Some(self.key.clone()), shutdown_timeout: 1, ..Config::default() } + } + async fn connect(&self, proxy: &Proxy, alpn: &[&[u8]]) -> Result> { + let mut roots = rustls::RootCertStore::empty(); + roots.add(self.der.clone())?; + let mut client = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) + .with_safe_default_protocol_versions()?.with_root_certificates(roots).with_no_client_auth(); + client.alpn_protocols = alpn.iter().map(|p| p.to_vec()).collect(); + let connector = TlsConnector::from(Arc::new(client)); + let tcp = TcpStream::connect(proxy.address).await?; + Ok(timeout(WAIT, connector.connect("localhost".try_into()?, tcp)).await??) + } +} + +#[tokio::test] +async fn tls_alpn_negotiates_real_http2_and_checks_certificate() -> Result<()> { + let certificate = Certificate::new()?; + let proxy = Proxy::new(certificate.config()).await?; + let origin = Origin::new("tls-h2").await?; + let tls = certificate.connect(&proxy, &[b"h2", b"http/1.1"]).await?; + assert_eq!(tls.get_ref().1.alpn_protocol(), Some(b"h2".as_slice())); + let client = Client::new(tls).await?; + let response = client.get(origin.url("/")).await?; + assert_eq!(response.version(), Version::HTTP_2); + assert_eq!(collect(response.into_body()).await?, b"tls-h2"); + assert_eq!(proxy.metrics.http2_connections.load(Ordering::Relaxed), 1); + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn tls_supports_http1_alpn_and_no_alpn_fallback() -> Result<()> { + let certificate = Certificate::new()?; + let proxy = Proxy::new(certificate.config()).await?; + let origin = Origin::new("http1").await?; + for alpn in [vec![b"http/1.1".as_slice()], vec![]] { + let mut tls = certificate.connect(&proxy, &alpn).await?; + let request = format!("GET {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n", origin.url("/"), origin.address); + tls.write_all(request.as_bytes()).await?; + let head = header(&mut tls).await?; + assert!(head.starts_with("HTTP/1.1 200")); + let mut body = [0; 5]; + timeout(WAIT, tls.read_exact(&mut body)).await??; + assert_eq!(&body, b"http1"); + } + proxy.stop().await +} + +#[tokio::test] +async fn disabling_http2_excludes_it_from_alpn() -> Result<()> { + let certificate = Certificate::new()?; + let mut config = certificate.config(); + config.http2 = false; + let proxy = Proxy::new(config).await?; + let tls = certificate.connect(&proxy, &[b"h2", b"http/1.1"]).await?; + assert_eq!(tls.get_ref().1.alpn_protocol(), Some(b"http/1.1".as_slice())); + drop(tls); + proxy.stop().await +} + +#[tokio::test] +async fn unrelated_ca_cannot_authenticate_the_proxy() -> Result<()> { + let certificate = Certificate::new()?; + let unrelated = Certificate::new()?; + let proxy = Proxy::new(certificate.config()).await?; + assert!(unrelated.connect(&proxy, &[b"h2"]).await.is_err()); + proxy.stop().await +} + +#[tokio::test] +async fn h2c_is_explicit_and_http1_still_works_on_the_same_port() -> Result<()> { + let proxy = Proxy::new(config()).await?; + let origin = Origin::new("shared-port").await?; + let client = Client::plain(&proxy).await?; + assert_eq!(collect(client.get(origin.url("/")).await?.into_body()).await?, b"shared-port"); + let mut tcp = TcpStream::connect(proxy.address).await?; + tcp.write_all(format!("GET {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n", origin.url("/"), origin.address).as_bytes()).await?; + assert!(header(&mut tcp).await?.starts_with("HTTP/1.1 200")); + drop(tcp); + drop(client); + proxy.stop().await?; + let proxy = Proxy::new(Config { port: 0, ..Config::default() }).await?; + let client = Client::plain(&proxy).await?; + assert!(client.get(origin.url("/")).await.is_err()); + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn multiplexing_does_not_serialize_a_fast_request_behind_a_blocked_one() -> Result<()> { + let origin = Origin::new("ok").await?; + let proxy = Proxy::new(config()).await?; + let client = Client::plain(&proxy).await?; + let blocked = Request::builder().uri(origin.url("/blocked")).body(())?; + let (slow, _) = client.send(blocked, true).await?; + timeout(WAIT, origin.blocked.notified()).await?; + assert_eq!(collect(client.get(origin.url("/fast")).await?.into_body()).await?, b"ok"); + origin.release.notify_one(); + assert_eq!(collect(timeout(WAIT, slow).await??.into_body()).await?, b"ok"); + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn multiplexed_requests_route_to_distinct_origins() -> Result<()> { + let a = Origin::new("A").await?; + let b = Origin::new("B").await?; + let proxy = Proxy::new(config()).await?; + let client = Client::plain(&proxy).await?; + let (ra, rb) = tokio::join!(client.get(a.url("/")), client.get(b.url("/"))); + assert_eq!(collect(ra?.into_body()).await?, b"A"); + assert_eq!(collect(rb?.into_body()).await?, b"B"); + assert_eq!(proxy.metrics.opened.load(Ordering::Relaxed), 1); + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn h2_auth_is_per_stream_and_translation_preserves_http_semantics() -> Result<()> { + let mut config = config(); + config.basic_auth = Config::parse("BasicAuth user pass")?.basic_auth; + let proxy = Proxy::new(config).await?; + let origin = Origin::new("origin").await?; + let client = Client::plain(&proxy).await?; + let denied = client.get(origin.url("/")).await?; + assert_eq!(denied.status(), 407); + assert!(!denied.headers().contains_key("connection")); + collect(denied.into_body()).await?; + let request = Request::builder().uri(origin.url("/headers?q=1")) + .header("proxy-authorization", "Basic dXNlcjpwYXNz") + .header("authorization", "Bearer origin-token") + .header("cookie", "a=1").header("cookie", "b=2").body(())?; + let (response, _) = client.send(request, true).await?; + let response = timeout(WAIT, response).await??; + assert_eq!(response.status(), 200); + assert_eq!(response.headers().get_all("set-cookie").iter().count(), 2); + assert!(!response.headers().contains_key("connection")); + assert!(!response.headers().contains_key("x-hop")); + let body = String::from_utf8(collect(response.into_body()).await?)?; + assert!(body.contains("GET /headers?q=1")); + assert!(body.contains("proxy-auth=absent")); + assert!(body.contains("auth=Bearer origin-token")); + assert!(body.contains("cookie=a=1; b=2\ncookies=1")); + assert!(body.contains("via=2 tinyproxy-rust")); + assert_eq!(client.get(origin.url("/")).await?.status(), 407); + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn host_authority_conflicts_are_not_forwarded() -> Result<()> { + let origin = Origin::new("origin").await?; + let proxy = Proxy::new(config()).await?; + let client = Client::plain(&proxy).await?; + let request = Request::builder().uri(origin.url("/")).header("host", "different.invalid").body(())?; + let (response, _) = client.send(request, true).await?; + // The protocol library may reject earlier than the application layer. + if let Ok(response) = timeout(WAIT, response).await? { assert_eq!(response.status(), 400); } + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn large_h2_upload_and_response_cross_flow_control_windows() -> Result<()> { + let origin = Origin::new("echo").await?; + let proxy = Proxy::new(config()).await?; + let client = Client::plain(&proxy).await?; + let body = Bytes::from(vec![0x5a; 2 * 1024 * 1024]); + let request = Request::builder().method(Method::POST).uri(origin.url("/echo")) + .header("content-length", body.len()).body(())?; + let (response, mut send) = client.send(request, false).await?; + // h2 buffers test input; production uses bounded Hyper streaming bodies. + send.send_data(body.clone(), true)?; + let response = timeout(WAIT, response).await??; + assert_eq!(response.status(), 200); + assert_eq!(collect(response.into_body()).await?, body); + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn h2_connect_preserves_early_data_half_close_and_sibling_streams() -> Result<()> { + let a = TcpListener::bind("127.0.0.1:0").await?; + let b = TcpListener::bind("127.0.0.1:0").await?; + let aa = a.local_addr()?; + let bb = b.local_addr()?; + let mut config = config(); + config.connect_ports = vec![aa.port(), bb.port()]; + let proxy = Proxy::new(config).await?; + let client = Client::plain(&proxy).await?; + let request = Request::builder().method(Method::CONNECT).uri(aa.to_string()).body(())?; + let (response, mut send_a) = client.send(request, false).await?; + send_a.send_data(Bytes::from_static(b"early"), true)?; + let response = timeout(WAIT, response).await??; + assert_eq!(response.status(), 200); + let (mut up_a, _) = timeout(WAIT, a.accept()).await??; + let (mut send_b, recv_b) = client.tunnel(bb).await?; + let (mut up_b, _) = timeout(WAIT, b.accept()).await??; + let mut received = Vec::new(); + timeout(WAIT, up_a.read_to_end(&mut received)).await??; + assert_eq!(received, b"early"); + up_a.write_all(b"after-fin").await?; + up_a.shutdown().await?; + assert_eq!(collect(response.into_body()).await?, b"after-fin"); + send_b.send_data(Bytes::from_static(b"alive"), true)?; + received.clear(); + timeout(WAIT, up_b.read_to_end(&mut received)).await??; + assert_eq!(received, b"alive"); + up_b.write_all(b"sibling-ok").await?; + up_b.shutdown().await?; + assert_eq!(collect(recv_b).await?, b"sibling-ok"); + let origin = Origin::new("still-h2").await?; + assert_eq!(collect(client.get(origin.url("/")).await?.into_body()).await?, b"still-h2"); + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn global_request_budget_includes_connect_and_recovers_after_reset() -> Result<()> { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let target = listener.local_addr()?; + let mut config = config(); + config.connect_ports = vec![target.port()]; + config.max_inflight_requests = 1; + let proxy = Proxy::new(config).await?; + let origin = Origin::new("recovered").await?; + let client = Client::plain(&proxy).await?; + let (mut send, recv) = client.tunnel(target).await?; + let (mut upstream, _) = timeout(WAIT, listener.accept()).await??; + assert_eq!(client.get(origin.url("/")).await?.status(), 503); + assert_eq!(proxy.metrics.inflight.load(Ordering::Relaxed), 1); + send.send_reset(h2::Reason::CANCEL); + drop(recv); + assert!(timeout(WAIT, upstream.read_u8()).await?.is_err()); + inflight(&proxy, 0).await?; + assert_eq!(collect(client.get(origin.url("/")).await?.into_body()).await?, b"recovered"); + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn reset_before_response_headers_closes_the_upstream_socket() -> Result<()> { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let proxy = Proxy::new(config()).await?; + let client = Client::plain(&proxy).await?; + let request = Request::builder().uri(format!("http://{}/", listener.local_addr()?)).body(())?; + let (response, mut send) = client.send(request, true).await?; + let (mut upstream, _) = timeout(WAIT, listener.accept()).await??; + header(&mut upstream).await?; + send.send_reset(h2::Reason::CANCEL); + assert!(timeout(WAIT, response).await?.is_err()); + assert!(timeout(WAIT, upstream.read_u8()).await?.is_err()); + inflight(&proxy, 0).await?; + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn busy_sibling_does_not_keep_an_idle_tunnel_alive() -> Result<()> { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let target = listener.local_addr()?; + let mut config = config(); + config.connect_ports = vec![target.port()]; + config.timeout = 1; + let proxy = Proxy::new(config).await?; + let client = Client::plain(&proxy).await?; + let (_idle_send, mut idle_recv) = client.tunnel(target).await?; + let (mut idle_upstream, _) = timeout(WAIT, listener.accept()).await??; + let (mut active_send, mut active_recv) = client.tunnel(target).await?; + let (mut active_upstream, _) = timeout(WAIT, listener.accept()).await??; + for _ in 0..6 { + sleep(Duration::from_millis(250)).await; + active_send.send_data(Bytes::from_static(b"a"), false)?; + assert_eq!(timeout(WAIT, active_upstream.read_u8()).await??, b'a'); + active_upstream.write_all(b"b").await?; + let data = timeout(WAIT, active_recv.data()).await?.transpose()?.unwrap(); + assert_eq!(data, b"b".as_slice()); + active_recv.flow_control().release_capacity(data.len())?; + } + assert!(timeout(WAIT, idle_upstream.read_u8()).await?.is_err()); + let end = timeout(WAIT, idle_recv.data()).await?; + assert!(end.is_none() || end.is_some_and(|data| data.is_err() || data.is_ok_and(|b| b.is_empty()))); + inflight(&proxy, 1).await?; + active_send.send_reset(h2::Reason::CANCEL); + drop(active_recv); + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn max_concurrent_streams_is_advertised_and_enforced() -> Result<()> { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let target = listener.local_addr()?; + let mut config = config(); + config.max_concurrent_streams = 1; + config.connect_ports = vec![target.port()]; + let proxy = Proxy::new(config).await?; + let client = Client::plain(&proxy).await?; + let (mut send, recv) = client.tunnel(target).await?; + let (_upstream, _) = timeout(WAIT, listener.accept()).await??; + // Server settings have arrived by the successful CONNECT response. + assert!(timeout(Duration::from_millis(100), client.sender.clone().ready()).await.is_err()); + send.send_reset(h2::Reason::CANCEL); + drop(recv); + timeout(WAIT, client.sender.clone().ready()).await??; + drop(client); + proxy.stop().await +} + +#[tokio::test] +async fn graceful_goaway_drains_existing_connect_stream() -> Result<()> { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let target = listener.local_addr()?; + let mut config = config(); + config.connect_ports = vec![target.port()]; + config.shutdown_timeout = 3; + let proxy = Proxy::new(config).await?; + let client = Client::plain(&proxy).await?; + let (mut send, recv) = client.tunnel(target).await?; + let (mut upstream, _) = timeout(WAIT, listener.accept()).await??; + proxy.shutdown.cancel(); + sleep(Duration::from_millis(50)).await; + send.send_data(Bytes::from_static(b"finish"), true)?; + let mut request = Vec::new(); + timeout(WAIT, upstream.read_to_end(&mut request)).await??; + assert_eq!(request, b"finish"); + upstream.write_all(b"drained").await?; + upstream.shutdown().await?; + assert_eq!(collect(recv).await?, b"drained"); + proxy.stop().await +} + +#[tokio::test] +async fn partial_h2_preface_has_a_total_deadline() -> Result<()> { + let mut config = config(); + config.header_timeout = 1; + config.timeout = 30; + let proxy = Proxy::new(config).await?; + let mut tcp = TcpStream::connect(proxy.address).await?; + tcp.write_all(b"PRI ").await?; + sleep(Duration::from_millis(600)).await; + tcp.write_all(b"*").await?; + assert!(timeout(Duration::from_secs(2), tcp.read_u8()).await?.is_err()); + proxy.stop().await +} + +#[tokio::test] +async fn tls_handshake_deadline_releases_connection_capacity() -> Result<()> { + let certificate = Certificate::new()?; + let mut config = certificate.config(); + config.tls_handshake_timeout = 1; + let proxy = Proxy::new(config).await?; + let mut tcp = TcpStream::connect(proxy.address).await?; + assert!(timeout(Duration::from_secs(3), tcp.read_u8()).await?.is_err()); + proxy.stop().await +} + +#[test] +fn http2_tls_configuration_rejects_inconsistent_or_unbounded_settings() -> Result<()> { + for text in ["MaxConcurrentStreams 0", "MaxConcurrentStreams 1025", "MaxInflightRequests 0", "TLSCert cert.pem", "TLSKey key.pem", "HTTP2 No\nAllowH2C Yes", "TLSHandshakeTimeout 0", "TLSCert a\nTLSKey b\nAllowH2C Yes"] { + assert!(Config::parse(text).is_err(), "accepted invalid configuration: {text}"); + } + let config = Config::parse("HTTP2 Yes\nAllowH2C Yes\nMaxConcurrentStreams 8\nMaxInflightRequests 32")?; + assert!(config.http2 && config.allow_h2c); + assert_eq!(config.max_concurrent_streams, 8); + assert_eq!(config.max_inflight_requests, 32); + Ok(()) +} + +#[tokio::test] +async fn tls_files_are_validated_before_binding() -> Result<()> { + let certificate = Certificate::new()?; + let unrelated = Certificate::new()?; + let mut config = certificate.config(); + config.tls_key = Some(unrelated.key.clone()); + assert!(ProxyServer::bind(config).await.is_err()); + let mut config = certificate.config(); + config.tls_cert = Some("/nonexistent/tinyproxy-test-cert.pem".into()); + assert!(ProxyServer::bind(config).await.is_err()); + Ok(()) +} + +#[test] +fn tls_paths_resolve_relative_to_configuration() -> Result<()> { + let directory = tempfile::tempdir()?; + let path = directory.path().join("proxy.conf"); + std::fs::write(&path, "TLSCert cert.pem\nTLSKey key.pem\n")?; + let config = Config::from_file(&path)?; + assert_eq!(config.tls_cert.as_deref(), directory.path().join("cert.pem").to_str()); + assert_eq!(config.tls_key.as_deref(), directory.path().join("key.pem").to_str()); + Ok(()) +} From 246961759cf32450874a225787baacc2b0382046 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 19 Sep 2026 00:57:32 +0000 Subject: [PATCH 2/9] build: lock HTTP2 TLS dependencies and format sources --- Cargo.lock | 354 ++++++++++++++++++++++++++++++++++++++++++-- src/config.rs | 208 ++++++++++++++++++++------ src/connection.rs | 363 ++++++++++++++++++++++++++++++++++++---------- src/exchange.rs | 42 +++++- src/protocol.rs | 30 +++- src/runtime.rs | 6 +- src/transport.rs | 110 +++++++++++--- tests/http2.rs | 261 ++++++++++++++++++++++++++------- 8 files changed, 1154 insertions(+), 220 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 49267b4..3626bca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -53,7 +53,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -64,7 +64,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -121,6 +121,16 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" +[[package]] +name = "cc" +version = "1.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -298,6 +308,12 @@ dependencies = [ "thiserror", ] +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + [[package]] name = "either" version = "1.18.0" @@ -327,6 +343,12 @@ dependencies = [ "log", ] +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + [[package]] name = "errno" version = "0.3.14" @@ -334,7 +356,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -343,6 +365,18 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "find-msvc-tools" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "futures-channel" version = "0.3.34" @@ -394,6 +428,17 @@ dependencies = [ "slab", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -405,6 +450,25 @@ dependencies = [ "r-efi", ] +[[package]] +name = "h2" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "half" version = "2.7.1" @@ -416,6 +480,12 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "heck" version = "0.5.0" @@ -483,6 +553,7 @@ dependencies = [ "bytes", "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", @@ -508,6 +579,16 @@ dependencies = [ "tokio", ] +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + [[package]] name = "ipnet" version = "2.12.2" @@ -522,7 +603,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" dependencies = [ "hermit-abi", "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -626,9 +707,15 @@ checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "num-traits" version = "0.2.19" @@ -656,6 +743,16 @@ version = "11.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64", + "serde_core", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -705,6 +802,12 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -749,6 +852,19 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "rcgen" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75e669e5202259b5314d1ea5397316ad400819437857b90861765f24c4cf80a2" +dependencies = [ + "pem", + "ring", + "rustls-pki-types", + "time", + "yasna", +] + [[package]] name = "regex" version = "1.13.1" @@ -778,6 +894,20 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rustix" version = "1.1.5" @@ -788,7 +918,50 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pemfile" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -849,6 +1022,12 @@ dependencies = [ "zmij", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -878,7 +1057,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -887,6 +1066,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -916,10 +1101,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -942,6 +1127,25 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + [[package]] name = "tinyproxy-rust" version = "1.11.0" @@ -952,14 +1156,18 @@ dependencies = [ "clap", "criterion", "env_logger", + "h2", "http-body-util", "hyper", "hyper-util", "ipnet", "log", + "rcgen", "regex", + "rustls-pemfile", "tempfile", "tokio", + "tokio-rustls", "tokio-util", ] @@ -986,7 +1194,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1000,6 +1208,16 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "tokio-rustls" +version = "0.26.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-util" version = "0.7.19" @@ -1010,10 +1228,30 @@ dependencies = [ "futures-core", "futures-sink", "futures-util", + "libc", "pin-project-lite", "tokio", ] +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + [[package]] name = "try-lock" version = "0.2.5" @@ -1026,6 +1264,12 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "utf8parse" version = "0.2.2" @@ -1118,7 +1362,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -1127,6 +1371,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -1136,6 +1389,79 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "yasna" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" +dependencies = [ + "time", +] + [[package]] name = "zerocopy" version = "0.8.57" @@ -1156,6 +1482,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + [[package]] name = "zmij" version = "1.0.23" diff --git a/src/config.rs b/src/config.rs index 0315f42..dfdc0d3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -82,11 +82,19 @@ impl Config { .with_context(|| format!("Cannot read configuration: {}", path.display()))?; let mut config = Self::parse(&text)?; // All policy and TLS paths are relative to the configuration, not cwd. - for file in [&mut config.filter_file, &mut config.tls_cert, &mut config.tls_key] { + for file in [ + &mut config.filter_file, + &mut config.tls_cert, + &mut config.tls_key, + ] { if let Some(value) = file { if Path::new(value).is_relative() { - *value = path.parent().unwrap_or_else(|| Path::new(".")) - .join(&*value).to_string_lossy().into_owned(); + *value = path + .parent() + .unwrap_or_else(|| Path::new(".")) + .join(&*value) + .to_string_lossy() + .into_owned(); } } } @@ -99,23 +107,42 @@ impl Config { let mut saw_connect_port = false; for (index, line) in text.lines().enumerate() { let args = tokenize(line).with_context(|| format!("Line {}", index + 1))?; - if args.is_empty() { continue; } - let apply = |config: &mut Self, saw_listen: &mut bool, saw_connect_port: &mut bool| -> Result<()> { - ensure!(args[0].starts_with(|c: char| c.is_ascii_alphabetic()) - && args[0].bytes().all(|c| c.is_ascii_alphanumeric()), - "Invalid directive; use Tinyproxy key/value syntax, not TOML"); + if args.is_empty() { + continue; + } + let apply = |config: &mut Self, + saw_listen: &mut bool, + saw_connect_port: &mut bool| + -> Result<()> { + ensure!( + args[0].starts_with(|c: char| c.is_ascii_alphabetic()) + && args[0].bytes().all(|c| c.is_ascii_alphanumeric()), + "Invalid directive; use Tinyproxy key/value syntax, not TOML" + ); let key = args[0].to_ascii_lowercase(); if key == "basicauth" { let (username, password) = match args.as_slice() { [_, user, pass] => (user.clone(), pass.clone()), - [_, legacy] => legacy.split_once(':') + [_, legacy] => legacy + .split_once(':') .map(|(user, pass)| (user.to_owned(), pass.to_owned())) .context("BasicAuth requires a username and password")?, _ => bail!("BasicAuth requires a username and password"), }; - ensure!(!username.is_empty() && !password.is_empty() && !username.contains(':'), "Invalid BasicAuth credentials"); - ensure!(!config.basic_auth.iter().any(|auth| auth.username == username), "Duplicate BasicAuth username"); - config.basic_auth.push(BasicAuthConfig { username, password }); + ensure!( + !username.is_empty() && !password.is_empty() && !username.contains(':'), + "Invalid BasicAuth credentials" + ); + ensure!( + !config + .basic_auth + .iter() + .any(|auth| auth.username == username), + "Duplicate BasicAuth username" + ); + config + .basic_auth + .push(BasicAuthConfig { username, password }); return Ok(()); } ensure!(args.len() == 2, "{} requires one value", args[0]); @@ -124,15 +151,29 @@ impl Config { "port" => config.port = value.parse().context("Invalid Port")?, "listen" => { let address = value.parse().context("Invalid Listen address")?; - if !*saw_listen { config.listen_addresses.clear(); *saw_listen = true; } + if !*saw_listen { + config.listen_addresses.clear(); + *saw_listen = true; + } config.listen_addresses.push(address); } - "bind" => config.bind_address = Some(value.parse().context("Invalid Bind address")?), + "bind" => { + config.bind_address = Some(value.parse().context("Invalid Bind address")?) + } "timeout" => config.timeout = value.parse().context("Invalid Timeout")?, - "headertimeout" => config.header_timeout = value.parse().context("Invalid HeaderTimeout")?, - "connecttimeout" => config.connect_timeout = value.parse().context("Invalid ConnectTimeout")?, - "shutdowntimeout" => config.shutdown_timeout = value.parse().context("Invalid ShutdownTimeout")?, - "maxclients" => config.max_clients = value.parse().context("Invalid MaxClients")?, + "headertimeout" => { + config.header_timeout = value.parse().context("Invalid HeaderTimeout")? + } + "connecttimeout" => { + config.connect_timeout = value.parse().context("Invalid ConnectTimeout")? + } + "shutdowntimeout" => { + config.shutdown_timeout = + value.parse().context("Invalid ShutdownTimeout")? + } + "maxclients" => { + config.max_clients = value.parse().context("Invalid MaxClients")? + } "loglevel" => config.log_level = value.clone(), "allow" | "deny" => config.acl_rules.push((key == "allow", value.clone())), "filter" => config.filter_file = Some(value.clone()), @@ -142,7 +183,10 @@ impl Config { "filterdefaultdeny" => config.filter_default_deny = parse_bool(value)?, "connectport" => { let port = value.parse().context("Invalid ConnectPort")?; - if !*saw_connect_port { config.connect_ports.clear(); *saw_connect_port = true; } + if !*saw_connect_port { + config.connect_ports.clear(); + *saw_connect_port = true; + } config.connect_ports.push(port); } "disableviaheader" => config.disable_via_header = parse_bool(value)?, @@ -150,12 +194,24 @@ impl Config { "stathost" => config.stat_host = Some(value.to_ascii_lowercase()), "http2" => config.http2 = parse_bool(value)?, "allowh2c" => config.allow_h2c = parse_bool(value)?, - "maxconcurrentstreams" => config.max_concurrent_streams = value.parse().context("Invalid MaxConcurrentStreams")?, - "maxinflightrequests" => config.max_inflight_requests = value.parse().context("Invalid MaxInflightRequests")?, + "maxconcurrentstreams" => { + config.max_concurrent_streams = + value.parse().context("Invalid MaxConcurrentStreams")? + } + "maxinflightrequests" => { + config.max_inflight_requests = + value.parse().context("Invalid MaxInflightRequests")? + } "tlscert" => config.tls_cert = Some(value.clone()), "tlskey" => config.tls_key = Some(value.clone()), - "tlshandshaketimeout" => config.tls_handshake_timeout = value.parse().context("Invalid TLSHandshakeTimeout")?, - _ => bail!("Unsupported directive: {} (see README compatibility table)", args[0]), + "tlshandshaketimeout" => { + config.tls_handshake_timeout = + value.parse().context("Invalid TLSHandshakeTimeout")? + } + _ => bail!( + "Unsupported directive: {} (see README compatibility table)", + args[0] + ), } Ok(()) }; @@ -163,7 +219,10 @@ impl Config { .with_context(|| format!("Line {}", index + 1))?; } if config.connect_ports.contains(&0) { - ensure!(config.connect_ports.len() == 1, "ConnectPort 0 cannot be combined with other ports"); + ensure!( + config.connect_ports.len() == 1, + "ConnectPort 0 cannot be combined with other ports" + ); config.connect_ports.clear(); } config.validate()?; @@ -171,23 +230,68 @@ impl Config { } pub fn validate(&self) -> Result<()> { - ensure!(!self.listen_addresses.is_empty(), "At least one Listen address is required"); - ensure!((1..=1_000_000).contains(&self.max_clients), "MaxClients must be in 1..=1000000"); - ensure!((1..=1_000_000).contains(&self.max_inflight_requests), "MaxInflightRequests must be in 1..=1000000"); - ensure!((1..=1024).contains(&self.max_concurrent_streams), "MaxConcurrentStreams must be in 1..=1024"); - ensure!([self.timeout, self.header_timeout, self.connect_timeout, self.shutdown_timeout, self.tls_handshake_timeout] - .iter().all(|seconds| (1..=86400).contains(seconds)), "Timeouts must be in 1..=86400 seconds"); - ensure!(self.listen_addresses.iter().all(IpAddr::is_loopback) - || !self.acl_rules.is_empty() || !self.basic_auth.is_empty(), - "Non-loopback Listen requires explicit Allow/Deny rules or BasicAuth"); - ensure!(!self.via_proxy_name.is_empty() && self.via_proxy_name.bytes().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)), - "ViaProxyName must contain only letters, digits, dots, underscores or hyphens"); - self.log_level.parse::().context("Invalid LogLevel")?; - ensure!(!self.filter_default_deny || self.filter_file.is_some(), "FilterDefaultDeny requires Filter"); - ensure!(!self.connect_ports.contains(&0), "Use an empty port list to disable CONNECT in the library API"); - ensure!(self.tls_cert.is_some() == self.tls_key.is_some(), "TLSCert and TLSKey must be configured together"); + ensure!( + !self.listen_addresses.is_empty(), + "At least one Listen address is required" + ); + ensure!( + (1..=1_000_000).contains(&self.max_clients), + "MaxClients must be in 1..=1000000" + ); + ensure!( + (1..=1_000_000).contains(&self.max_inflight_requests), + "MaxInflightRequests must be in 1..=1000000" + ); + ensure!( + (1..=1024).contains(&self.max_concurrent_streams), + "MaxConcurrentStreams must be in 1..=1024" + ); + ensure!( + [ + self.timeout, + self.header_timeout, + self.connect_timeout, + self.shutdown_timeout, + self.tls_handshake_timeout + ] + .iter() + .all(|seconds| (1..=86400).contains(seconds)), + "Timeouts must be in 1..=86400 seconds" + ); + ensure!( + self.listen_addresses.iter().all(IpAddr::is_loopback) + || !self.acl_rules.is_empty() + || !self.basic_auth.is_empty(), + "Non-loopback Listen requires explicit Allow/Deny rules or BasicAuth" + ); + ensure!( + !self.via_proxy_name.is_empty() + && self + .via_proxy_name + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)), + "ViaProxyName must contain only letters, digits, dots, underscores or hyphens" + ); + self.log_level + .parse::() + .context("Invalid LogLevel")?; + ensure!( + !self.filter_default_deny || self.filter_file.is_some(), + "FilterDefaultDeny requires Filter" + ); + ensure!( + !self.connect_ports.contains(&0), + "Use an empty port list to disable CONNECT in the library API" + ); + ensure!( + self.tls_cert.is_some() == self.tls_key.is_some(), + "TLSCert and TLSKey must be configured together" + ); ensure!(!self.allow_h2c || self.http2, "AllowH2C requires HTTP2 Yes"); - ensure!(!self.allow_h2c || self.tls_cert.is_none(), "AllowH2C is only for plaintext listeners; TLS uses ALPN"); + ensure!( + !self.allow_h2c || self.tls_cert.is_none(), + "AllowH2C is only for plaintext listeners; TLS uses ALPN" + ); Ok(()) } } @@ -210,19 +314,33 @@ fn tokenize(line: &str) -> Result> { if let Some(delimiter) = quote { if c == delimiter { quote = None; - } else if c == '\\' && chars.peek().is_some_and(|next| *next == delimiter || *next == '\\') { + } else if c == '\\' + && chars + .peek() + .is_some_and(|next| *next == delimiter || *next == '\\') + { word.push(chars.next().expect("peeked character")); - } else { word.push(c); } + } else { + word.push(c); + } } else if c == '"' || c == '\'' { quote = Some(c); active = true; } else if c == '#' && !active { break; } else if c.is_whitespace() { - if active { words.push(std::mem::take(&mut word)); active = false; } - } else { word.push(c); active = true; } + if active { + words.push(std::mem::take(&mut word)); + active = false; + } + } else { + word.push(c); + active = true; + } } ensure!(quote.is_none(), "Unterminated quoted value"); - if active { words.push(word); } + if active { + words.push(word); + } Ok(words) } diff --git a/src/connection.rs b/src/connection.rs index 1ca2c42..dc9d16e 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -6,7 +6,9 @@ use anyhow::{ensure, Result}; use bytes::Bytes; use http_body_util::{BodyExt, Full}; use hyper::body::Incoming; -use hyper::header::{HeaderMap, HeaderName, HeaderValue, CONNECTION, COOKIE, HOST, PROXY_AUTHENTICATE, VIA}; +use hyper::header::{ + HeaderMap, HeaderName, HeaderValue, CONNECTION, COOKIE, HOST, PROXY_AUTHENTICATE, VIA, +}; use hyper::service::service_fn; use hyper::{Method, Request, Response, StatusCode, Uri, Version}; use hyper_util::rt::{TokioIo, TokioTimer}; @@ -30,23 +32,40 @@ struct Context { http1_upgraded: AtomicBool, } -pub async fn serve(mut stream: TcpStream, address: SocketAddr, runtime: Arc, guard: Arc) -> Result<()> { +pub async fn serve( + mut stream: TcpStream, + address: SocketAddr, + runtime: Arc, + guard: Arc, +) -> Result<()> { // Reject before TLS work; never send plaintext errors on a TLS/H2 listener. if !runtime.acl.is_allowed(address.ip()) { runtime.metrics.rejected.fetch_add(1, Ordering::Relaxed); if runtime.tls.is_none() && !runtime.config.allow_h2c { - let _ = timeout(Duration::from_secs(2), stream.write_all( - b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" - )).await; + let _ = timeout( + Duration::from_secs(2), + stream.write_all( + b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ), + ) + .await; } return Ok(()); } let negotiate = async { let (h2, io): (bool, BoxIo) = if let Some(acceptor) = &runtime.tls { - let tls = timeout(Duration::from_secs(runtime.config.tls_handshake_timeout), acceptor.accept(stream)).await??; + let tls = timeout( + Duration::from_secs(runtime.config.tls_handshake_timeout), + acceptor.accept(stream), + ) + .await??; let h2 = tls.get_ref().1.alpn_protocol() == Some(b"h2"); if h2 { - let (detected, io) = timeout(Duration::from_secs(runtime.config.header_timeout), protocol::detect(Box::new(tls))).await??; + let (detected, io) = timeout( + Duration::from_secs(runtime.config.header_timeout), + protocol::detect(Box::new(tls)), + ) + .await??; ensure!(detected, "HTTP/2 ALPN requires an HTTP/2 preface"); (true, io) } else { @@ -54,7 +73,11 @@ pub async fn serve(mut stream: TcpStream, address: SocketAddr, runtime: Arc return Ok(()), _ = runtime.force_shutdown.cancelled() => return Ok(()), }; - if h2 { runtime.metrics.http2_connections.fetch_add(1, Ordering::Relaxed); } + if h2 { + runtime + .metrics + .http2_connections + .fetch_add(1, Ordering::Relaxed); + } let activity = Activity::new(Duration::from_secs(runtime.config.timeout)); - let io = TokioIo::new(ActivityIo::new(stream, activity.clone(), Some(runtime.metrics.clone()))); + let io = TokioIo::new(ActivityIo::new( + stream, + activity.clone(), + Some(runtime.metrics.clone()), + )); let context = Arc::new(Context { - runtime: runtime.clone(), guard, activity, - cancelled: CancellationToken::new(), http1_upgraded: AtomicBool::new(false), + runtime: runtime.clone(), + guard, + activity, + cancelled: CancellationToken::new(), + http1_upgraded: AtomicBool::new(false), }); let service_context = context.clone(); let service = service_fn(move |request: Request| { @@ -106,9 +141,13 @@ pub async fn serve(mut stream: TcpStream, address: SocketAddr, runtime: Arc, context: Arc) -> HttpResult let runtime = &context.runtime; runtime.metrics.requests.fetch_add(1, Ordering::Relaxed); if !runtime.auth.authenticate(request.headers()) { - runtime.metrics.auth_failures.fetch_add(1, Ordering::Relaxed); - return Err((StatusCode::PROXY_AUTHENTICATION_REQUIRED, "Proxy authentication required")); + runtime + .metrics + .auth_failures + .fetch_add(1, Ordering::Relaxed); + return Err(( + StatusCode::PROXY_AUTHENTICATION_REQUIRED, + "Proxy authentication required", + )); } if request.extensions().get::().is_some() { - return Err((StatusCode::NOT_IMPLEMENTED, "Extended CONNECT is not supported")); + return Err(( + StatusCode::NOT_IMPLEMENTED, + "Extended CONNECT is not supported", + )); } if request.version() == Version::HTTP_2 { validate_h2_headers(request.headers()).map_err(|m| (StatusCode::BAD_REQUEST, m))?; } let target = Target::parse(&request).map_err(|message| (StatusCode::BAD_REQUEST, message))?; let is_connect = request.method() == Method::CONNECT; - if !runtime.filter.is_allowed(&target.host, &target.url, is_connect) { + if !runtime + .filter + .is_allowed(&target.host, &target.url, is_connect) + { return Err((StatusCode::FORBIDDEN, "Blocked by filter")); } if is_connect && !runtime.config.connect_ports.contains(&target.port) { return Err((StatusCode::FORBIDDEN, "CONNECT port not allowed")); } let permit = runtime.requests.clone().try_acquire_owned().map_err(|_| { - runtime.metrics.requests_rejected.fetch_add(1, Ordering::Relaxed); - (StatusCode::SERVICE_UNAVAILABLE, "Proxy request capacity reached") + runtime + .metrics + .requests_rejected + .fetch_add(1, Ordering::Relaxed); + ( + StatusCode::SERVICE_UNAVAILABLE, + "Proxy request capacity reached", + ) })?; - let state = Exchange::new(permit, context.guard.clone(), runtime.metrics.clone(), - context.cancelled.child_token(), Duration::from_secs(runtime.config.timeout)); + let state = Exchange::new( + permit, + context.guard.clone(), + runtime.metrics.clone(), + context.cancelled.child_token(), + Duration::from_secs(runtime.config.timeout), + ); let mut lease = CancelOnDrop(Some(state.clone())); let result = tokio::select! { result = forward(request, target, context.clone(), state.clone()) => result, @@ -167,32 +233,51 @@ async fn handle(request: Request, context: Arc) -> HttpResult _ = state.cancelled.cancelled() => Err((StatusCode::BAD_GATEWAY, "Request cancelled")), _ = runtime.force_shutdown.cancelled() => Err((StatusCode::SERVICE_UNAVAILABLE, "Proxy shutting down")), }; - if result.is_ok() { lease.0 = None; } + if result.is_ok() { + lease.0 = None; + } result } -async fn forward(mut request: Request, target: Target, context: Arc, state: Arc) -> HttpResult> { +async fn forward( + mut request: Request, + target: Target, + context: Arc, + state: Arc, +) -> HttpResult> { let runtime = &context.runtime; let version = request.version(); let is_connect = request.method() == Method::CONNECT; if !is_connect && runtime.config.stat_host.as_deref() == Some(target.host.as_str()) { if request.method() != Method::GET && request.method() != Method::HEAD { - return Err((StatusCode::METHOD_NOT_ALLOWED, "Statistics require GET or HEAD")); + return Err(( + StatusCode::METHOD_NOT_ALLOWED, + "Statistics require GET or HEAD", + )); + } + let mut response = text_response( + StatusCode::OK, + runtime.metrics.to_html(), + "text/html; charset=utf-8", + ); + if request.method() == Method::HEAD { + *response.body_mut() = empty_body(); } - let mut response = text_response(StatusCode::OK, runtime.metrics.to_html(), "text/html; charset=utf-8"); - if request.method() == Method::HEAD { *response.body_mut() = empty_body(); } return Ok(response.map(|body| exchange::track(body, state, true))); } if is_connect { strip_hop_by_hop(request.headers_mut()).map_err(|m| (StatusCode::BAD_REQUEST, m))?; let target_stream = dial(&target, runtime).await?; let upgrade = hyper::upgrade::on(&mut request); - if version != Version::HTTP_2 { context.http1_upgraded.store(true, Ordering::Relaxed); } + if version != Version::HTTP_2 { + context.http1_upgraded.store(true, Ordering::Relaxed); + } let force = runtime.force_shutdown.clone(); runtime.tasks.spawn(async move { let tunnel = async { let upgraded = upgrade.await?; - let mut client = ActivityIo::new(TokioIo::new(upgraded), state.activity.clone(), None); + let mut client = + ActivityIo::new(TokioIo::new(upgraded), state.activity.clone(), None); let mut target = ActivityIo::new(target_stream, state.activity.clone(), None); copy_bidirectional(&mut client, &mut target).await?; Ok::<_, BoxError>(()) @@ -223,7 +308,8 @@ async fn forward(mut request: Request, target: Target, context: Arc, target: Target, context: Arc {}, } }); - let mut response = sender.send_request(request).await + let mut response = sender + .send_request(request) + .await .map_err(|_| (StatusCode::BAD_GATEWAY, "Upstream request failed"))?; if response.status() == StatusCode::SWITCHING_PROTOCOLS { return Err((StatusCode::BAD_GATEWAY, "Unexpected upstream upgrade")); @@ -247,15 +335,29 @@ async fn forward(mut request: Request, target: Target, context: Arc HttpResult { - transport::connect(&target.host, target.port, runtime.config.bind_address, runtime.config.connect_timeout) - .await.map_err(|error| { - if error.kind() == std::io::ErrorKind::TimedOut { - (StatusCode::GATEWAY_TIMEOUT, "Upstream connection timed out") - } else { (StatusCode::BAD_GATEWAY, "Upstream connection failed") } - }) + transport::connect( + &target.host, + target.port, + runtime.config.bind_address, + runtime.config.connect_timeout, + ) + .await + .map_err(|error| { + if error.kind() == std::io::ErrorKind::TimedOut { + (StatusCode::GATEWAY_TIMEOUT, "Upstream connection timed out") + } else { + (StatusCode::BAD_GATEWAY, "Upstream connection failed") + } + }) } -struct Target { host: String, port: u16, authority: HeaderValue, path: Uri, url: String } +struct Target { + host: String, + port: u16, + authority: HeaderValue, + path: Uri, + url: String, +} impl Target { fn parse(request: &Request) -> std::result::Result { let connect = request.method() == Method::CONNECT; @@ -263,63 +365,117 @@ impl Target { if connect && (uri.scheme().is_some() || uri.path_and_query().is_some()) { return Err("CONNECT requires host:port authority form"); } - if uri.scheme_str().is_some_and(|scheme| !scheme.eq_ignore_ascii_case("http")) { + if uri + .scheme_str() + .is_some_and(|scheme| !scheme.eq_ignore_ascii_case("http")) + { return Err("Use CONNECT for HTTPS destinations"); } - if request.headers().get_all(HOST).iter().count() > 1 { return Err("Multiple Host headers are not allowed"); } + if request.headers().get_all(HOST).iter().count() > 1 { + return Err("Multiple Host headers are not allowed"); + } let authority = if let Some(authority) = uri.authority() { authority.clone() } else { - if connect { return Err("CONNECT requires an authority"); } - request.headers().get(HOST).and_then(|v| v.to_str().ok()) - .ok_or("Host header required")?.parse::() + if connect { + return Err("CONNECT requires an authority"); + } + request + .headers() + .get(HOST) + .and_then(|v| v.to_str().ok()) + .ok_or("Host header required")? + .parse::() .map_err(|_| "Invalid Host header")? }; - if authority.as_str().contains('@') || authority.host().is_empty() { return Err("Invalid destination authority"); } + if authority.as_str().contains('@') || authority.host().is_empty() { + return Err("Invalid destination authority"); + } let raw = authority.as_str(); - let explicit_port = raw.rsplit_once(':').filter(|(before, _)| !raw.starts_with('[') || before.ends_with(']')); + let explicit_port = raw + .rsplit_once(':') + .filter(|(before, _)| !raw.starts_with('[') || before.ends_with(']')); let port = if let Some((_, port)) = explicit_port { - port.parse::().ok().filter(|port| *port > 0).ok_or("Invalid destination port")? - } else if connect { return Err("CONNECT requires an explicit port"); } else { 80 }; + port.parse::() + .ok() + .filter(|port| *port > 0) + .ok_or("Invalid destination port")? + } else if connect { + return Err("CONNECT requires an explicit port"); + } else { + 80 + }; // H2 :authority and Host cannot name different destinations. if request.version() == Version::HTTP_2 { if let Some(host) = request.headers().get(HOST) { - let host = host.to_str().map_err(|_| "Invalid Host header")? - .parse::().map_err(|_| "Invalid Host header")?; - if !host.host().eq_ignore_ascii_case(authority.host()) || host.port_u16().unwrap_or(80) != port { + let host = host + .to_str() + .map_err(|_| "Invalid Host header")? + .parse::() + .map_err(|_| "Invalid Host header")?; + if !host.host().eq_ignore_ascii_case(authority.host()) + || host.port_u16().unwrap_or(80) != port + { return Err("Host disagrees with :authority"); } } } - let host = authority.host().trim_start_matches('[').trim_end_matches(']').trim_end_matches('.').to_ascii_lowercase(); - if host.is_empty() { return Err("Empty destination host"); } + let host = authority + .host() + .trim_start_matches('[') + .trim_end_matches(']') + .trim_end_matches('.') + .to_ascii_lowercase(); + if host.is_empty() { + return Err("Empty destination host"); + } let path = uri.path_and_query().map(|p| p.as_str()).unwrap_or("/"); - if !connect && !path.starts_with('/') && !(path == "*" && request.method() == Method::OPTIONS) { + if !connect + && !path.starts_with('/') + && !(path == "*" && request.method() == Method::OPTIONS) + { return Err("Invalid HTTP request target"); } Ok(Self { - host, port, authority: HeaderValue::from_str(raw).map_err(|_| "Invalid authority header")?, - path: path.parse().map_err(|_| "Invalid request path")?, url: format!("http://{}{}", raw, path), + host, + port, + authority: HeaderValue::from_str(raw).map_err(|_| "Invalid authority header")?, + path: path.parse().map_err(|_| "Invalid request path")?, + url: format!("http://{}{}", raw, path), }) } } fn validate_h2_headers(headers: &HeaderMap) -> std::result::Result<(), &'static str> { - for name in ["connection", "proxy-connection", "keep-alive", "transfer-encoding", "upgrade"] { - if headers.contains_key(name) { return Err("Connection-specific field in HTTP/2"); } + for name in [ + "connection", + "proxy-connection", + "keep-alive", + "transfer-encoding", + "upgrade", + ] { + if headers.contains_key(name) { + return Err("Connection-specific field in HTTP/2"); + } } for value in headers.get_all("te") { - if !value.as_bytes().eq_ignore_ascii_case(b"trailers") { return Err("HTTP/2 TE must be trailers"); } + if !value.as_bytes().eq_ignore_ascii_case(b"trailers") { + return Err("HTTP/2 TE must be trailers"); + } } Ok(()) } /// RFC 9113 section 8.2.3 requires split Cookie fields to be joined using '; '. fn coalesce_cookies(headers: &mut HeaderMap) -> std::result::Result<(), &'static str> { - if headers.get_all(COOKIE).iter().count() < 2 { return Ok(()); } + if headers.get_all(COOKIE).iter().count() < 2 { + return Ok(()); + } let mut joined = Vec::new(); for (index, cookie) in headers.get_all(COOKIE).iter().enumerate() { - if index != 0 { joined.extend_from_slice(b"; "); } + if index != 0 { + joined.extend_from_slice(b"; "); + } joined.extend_from_slice(cookie.as_bytes()); } let value = HeaderValue::from_bytes(&joined).map_err(|_| "Invalid Cookie")?; @@ -328,19 +484,42 @@ fn coalesce_cookies(headers: &mut HeaderMap) -> std::result::Result<(), &'static } pub(crate) fn strip_hop_by_hop(headers: &mut HeaderMap) -> std::result::Result<(), &'static str> { - if headers.contains_key("content-length") && headers.contains_key("transfer-encoding") { return Err("Ambiguous message framing"); } + if headers.contains_key("content-length") && headers.contains_key("transfer-encoding") { + return Err("Ambiguous message framing"); + } let mut nominated = Vec::new(); for value in headers.get_all(CONNECTION) { - for token in value.to_str().map_err(|_| "Invalid Connection header")?.split(',') { + for token in value + .to_str() + .map_err(|_| "Invalid Connection header")? + .split(',') + { let token = token.trim(); - if token.is_empty() { continue; } - let name = HeaderName::from_bytes(token.as_bytes()).map_err(|_| "Invalid Connection token")?; - if name == "content-length" || name == "transfer-encoding" { return Err("Connection must not nominate message framing headers"); } + if token.is_empty() { + continue; + } + let name = + HeaderName::from_bytes(token.as_bytes()).map_err(|_| "Invalid Connection token")?; + if name == "content-length" || name == "transfer-encoding" { + return Err("Connection must not nominate message framing headers"); + } nominated.push(name); } } - for name in nominated { headers.remove(name); } - for name in ["connection", "proxy-connection", "keep-alive", "proxy-authorization", "proxy-authenticate", "te", "trailer", "transfer-encoding", "upgrade"] { + for name in nominated { + headers.remove(name); + } + for name in [ + "connection", + "proxy-connection", + "keep-alive", + "proxy-authorization", + "proxy-authenticate", + "te", + "trailer", + "transfer-encoding", + "upgrade", + ] { headers.remove(name); } Ok(()) @@ -348,28 +527,54 @@ pub(crate) fn strip_hop_by_hop(headers: &mut HeaderMap) -> std::result::Result<( fn add_via(headers: &mut HeaderMap, runtime: &Runtime, version: Version) { if !runtime.config.disable_via_header { - let protocol = match version { Version::HTTP_2 => "2", Version::HTTP_10 => "1.0", _ => "1.1" }; - let value = HeaderValue::from_str(&format!("{} {}", protocol, runtime.config.via_proxy_name)).expect("startup-validated ViaProxyName"); + let protocol = match version { + Version::HTTP_2 => "2", + Version::HTTP_10 => "1.0", + _ => "1.1", + }; + let value = + HeaderValue::from_str(&format!("{} {}", protocol, runtime.config.via_proxy_name)) + .expect("startup-validated ViaProxyName"); headers.append(VIA, value); } } fn empty_body() -> Body { - Full::new(Bytes::new()).map_err(|never| -> BoxError { match never {} }).boxed_unsync() + Full::new(Bytes::new()) + .map_err(|never| -> BoxError { match never {} }) + .boxed_unsync() } fn text_response(status: StatusCode, text: String, content_type: &'static str) -> Response { let length = text.len(); - let body = Full::new(Bytes::from(text)).map_err(|never| -> BoxError { match never {} }).boxed_unsync(); + let body = Full::new(Bytes::from(text)) + .map_err(|never| -> BoxError { match never {} }) + .boxed_unsync(); let mut response = Response::new(body); *response.status_mut() = status; - response.headers_mut().insert("content-type", HeaderValue::from_static(content_type)); - response.headers_mut().insert("content-length", HeaderValue::from_str(&length.to_string()).expect("valid length")); + response + .headers_mut() + .insert("content-type", HeaderValue::from_static(content_type)); + response.headers_mut().insert( + "content-length", + HeaderValue::from_str(&length.to_string()).expect("valid length"), + ); response } fn error_response(status: StatusCode, message: &'static str, version: Version) -> Response { - let mut response = text_response(status, format!("{}\n", message), "text/plain; charset=utf-8"); - if version != Version::HTTP_2 { response.headers_mut().insert(CONNECTION, HeaderValue::from_static("close")); } + let mut response = text_response( + status, + format!("{}\n", message), + "text/plain; charset=utf-8", + ); + if version != Version::HTTP_2 { + response + .headers_mut() + .insert(CONNECTION, HeaderValue::from_static("close")); + } if status == StatusCode::PROXY_AUTHENTICATION_REQUIRED { - response.headers_mut().insert(PROXY_AUTHENTICATE, HeaderValue::from_static("Basic realm=\"Tinyproxy\"")); + response.headers_mut().insert( + PROXY_AUTHENTICATE, + HeaderValue::from_static("Basic realm=\"Tinyproxy\""), + ); } response } diff --git a/src/exchange.rs b/src/exchange.rs index 4e83c55..09f973d 100644 --- a/src/exchange.rs +++ b/src/exchange.rs @@ -26,9 +26,21 @@ pub struct Exchange { } impl Exchange { - pub fn new(permit: OwnedSemaphorePermit, connection: Arc, metrics: Arc, cancelled: CancellationToken, idle: Duration) -> Arc { + pub fn new( + permit: OwnedSemaphorePermit, + connection: Arc, + metrics: Arc, + cancelled: CancellationToken, + idle: Duration, + ) -> Arc { metrics.inflight.fetch_add(1, Ordering::Relaxed); - Arc::new(Self { activity: Activity::new(idle), cancelled, _permit: permit, _connection: connection, metrics }) + Arc::new(Self { + activity: Activity::new(idle), + cancelled, + _permit: permit, + _connection: connection, + metrics, + }) } } @@ -61,13 +73,21 @@ where B: HttpBody + Send + 'static, B::Error: Into, { - TrackedBody { inner: body.map_err(Into::into).boxed_unsync(), state, cancel_on_drop }.boxed_unsync() + TrackedBody { + inner: body.map_err(Into::into).boxed_unsync(), + state, + cancel_on_drop, + } + .boxed_unsync() } impl HttpBody for TrackedBody { type Data = Bytes; type Error = BoxError; - fn poll_frame(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll, BoxError>>> { + fn poll_frame( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll, BoxError>>> { let result = Pin::new(&mut self.inner).poll_frame(cx); match result { Poll::Ready(Some(Ok(mut frame))) => { @@ -78,7 +98,11 @@ impl HttpBody for TrackedBody { // hop-by-hop fields after the initial header sanitization. if let Some(trailers) = frame.trailers_mut() { if crate::connection::strip_hop_by_hop(trailers).is_err() { - return Poll::Ready(Some(Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid HTTP trailers").into()))); + return Poll::Ready(Some(Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "Invalid HTTP trailers", + ) + .into()))); } for name in ["host", "content-length", "authorization", "cookie"] { trailers.remove(name); @@ -89,8 +113,12 @@ impl HttpBody for TrackedBody { other => other, } } - fn is_end_stream(&self) -> bool { self.inner.is_end_stream() } - fn size_hint(&self) -> SizeHint { self.inner.size_hint() } + fn is_end_stream(&self) -> bool { + self.inner.is_end_stream() + } + fn size_hint(&self) -> SizeHint { + self.inner.size_hint() + } } impl Drop for TrackedBody { diff --git a/src/protocol.rs b/src/protocol.rs index c459223..0c8206d 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -17,10 +17,24 @@ pub async fn detect(mut io: BoxIo) -> io::Result<(bool, BoxIo)> { let actual = io.read_u8().await?; prefix.push(actual); if actual != *expected { - return Ok((false, Box::new(PrefixedIo { io, prefix, offset: 0 }))); + return Ok(( + false, + Box::new(PrefixedIo { + io, + prefix, + offset: 0, + }), + )); } } - Ok((true, Box::new(PrefixedIo { io, prefix, offset: 0 }))) + Ok(( + true, + Box::new(PrefixedIo { + io, + prefix, + offset: 0, + }), + )) } struct PrefixedIo { @@ -30,7 +44,11 @@ struct PrefixedIo { } impl AsyncRead for PrefixedIo { - fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll> { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { if self.offset < self.prefix.len() && buf.remaining() > 0 { let count = (self.prefix.len() - self.offset).min(buf.remaining()); buf.put_slice(&self.prefix[self.offset..self.offset + count]); @@ -42,7 +60,11 @@ impl AsyncRead for PrefixedIo { } impl AsyncWrite for PrefixedIo { - fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { Pin::new(&mut self.io).poll_write(cx, buf) } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { diff --git a/src/runtime.rs b/src/runtime.rs index 15e9129..14d3d0e 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -111,7 +111,11 @@ impl ConnectionGuard { pub fn new(permit: OwnedSemaphorePermit, metrics: Arc) -> Self { metrics.opened.fetch_add(1, Ordering::Relaxed); metrics.active.fetch_add(1, Ordering::Relaxed); - Self { _permit: permit, metrics, _started: Instant::now() } + Self { + _permit: permit, + metrics, + _started: Instant::now(), + } } } impl Drop for ConnectionGuard { diff --git a/src/transport.rs b/src/transport.rs index 4257476..e8efdac 100644 --- a/src/transport.rs +++ b/src/transport.rs @@ -10,77 +10,145 @@ use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio::net::{lookup_host, TcpSocket, TcpStream}; use tokio::time::{sleep_until, timeout, Instant}; -struct ActivityState { started: Instant, last_millis: AtomicU64 } +struct ActivityState { + started: Instant, + last_millis: AtomicU64, +} #[derive(Clone)] -pub struct Activity { state: Arc, idle: Duration } +pub struct Activity { + state: Arc, + idle: Duration, +} impl Activity { pub fn new(idle: Duration) -> Self { - Self { state: Arc::new(ActivityState { started: Instant::now(), last_millis: AtomicU64::new(0) }), idle } + Self { + state: Arc::new(ActivityState { + started: Instant::now(), + last_millis: AtomicU64::new(0), + }), + idle, + } } pub(crate) fn touch(&self) { - let elapsed = self.state.started.elapsed().as_millis().min(u64::MAX as u128) as u64; + let elapsed = self + .state + .started + .elapsed() + .as_millis() + .min(u64::MAX as u128) as u64; self.state.last_millis.fetch_max(elapsed, Ordering::Relaxed); } fn deadline(&self) -> Instant { - self.state.started + Duration::from_millis(self.state.last_millis.load(Ordering::Relaxed)) + self.idle + self.state.started + + Duration::from_millis(self.state.last_millis.load(Ordering::Relaxed)) + + self.idle } /// Progress in either direction resets idle time, not maximum lifetime. pub async fn expired(&self) { loop { sleep_until(self.deadline()).await; - if Instant::now() >= self.deadline() { return; } + if Instant::now() >= self.deadline() { + return; + } } } } -pub struct ActivityIo { inner: T, activity: Activity, metrics: Option> } +pub struct ActivityIo { + inner: T, + activity: Activity, + metrics: Option>, +} impl ActivityIo { pub fn new(inner: T, activity: Activity, metrics: Option>) -> Self { - Self { inner, activity, metrics } + Self { + inner, + activity, + metrics, + } } } impl AsyncRead for ActivityIo { - fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll> { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { let before = buf.filled().len(); let result = Pin::new(&mut self.inner).poll_read(cx, buf); if let Poll::Ready(Ok(())) = &result { let count = buf.filled().len() - before; if count > 0 { self.activity.touch(); - if let Some(metrics) = &self.metrics { metrics.bytes_in.fetch_add(count as u64, Ordering::Relaxed); } + if let Some(metrics) = &self.metrics { + metrics.bytes_in.fetch_add(count as u64, Ordering::Relaxed); + } } } result } } impl AsyncWrite for ActivityIo { - fn poll_write(mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll> { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &[u8], + ) -> Poll> { let result = Pin::new(&mut self.inner).poll_write(cx, buf); if let Poll::Ready(Ok(count)) = &result { if *count > 0 { self.activity.touch(); - if let Some(metrics) = &self.metrics { metrics.bytes_out.fetch_add(*count as u64, Ordering::Relaxed); } + if let Some(metrics) = &self.metrics { + metrics + .bytes_out + .fetch_add(*count as u64, Ordering::Relaxed); + } } } result } - fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Pin::new(&mut self.inner).poll_flush(cx) } - fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { Pin::new(&mut self.inner).poll_shutdown(cx) } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_shutdown(cx) + } } -pub async fn connect(host: &str, port: u16, bind: Option, seconds: u64) -> io::Result { +pub async fn connect( + host: &str, + port: u16, + bind: Option, + seconds: u64, +) -> io::Result { timeout(Duration::from_secs(seconds), async { - let Some(bind) = bind else { return TcpStream::connect((host, port)).await; }; + let Some(bind) = bind else { + return TcpStream::connect((host, port)).await; + }; let addresses = lookup_host((host, port)).await?; - let mut last_error = io::Error::new(io::ErrorKind::AddrNotAvailable, "No address matches Bind family"); + let mut last_error = io::Error::new( + io::ErrorKind::AddrNotAvailable, + "No address matches Bind family", + ); for address in addresses { - if address.is_ipv4() != bind.is_ipv4() { continue; } - let socket = if bind.is_ipv4() { TcpSocket::new_v4()? } else { TcpSocket::new_v6()? }; + if address.is_ipv4() != bind.is_ipv4() { + continue; + } + let socket = if bind.is_ipv4() { + TcpSocket::new_v4()? + } else { + TcpSocket::new_v6()? + }; socket.bind(SocketAddr::new(bind, 0))?; - match socket.connect(address).await { Ok(stream) => return Ok(stream), Err(error) => last_error = error } + match socket.connect(address).await { + Ok(stream) => return Ok(stream), + Err(error) => last_error = error, + } } Err(last_error) - }).await.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "DNS/connect deadline exceeded"))? + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "DNS/connect deadline exceeded"))? } diff --git a/tests/http2.rs b/tests/http2.rs index ef68237..5a7391d 100644 --- a/tests/http2.rs +++ b/tests/http2.rs @@ -32,7 +32,12 @@ impl Proxy { let address = proxy.local_addresses()?[0]; let shutdown = proxy.shutdown_token(); let metrics = proxy.metrics(); - Ok(Self { address, shutdown, metrics, task: tokio::spawn(proxy.run()) }) + Ok(Self { + address, + shutdown, + metrics, + task: tokio::spawn(proxy.run()), + }) } async fn stop(mut self) -> Result<()> { self.shutdown.cancel(); @@ -43,42 +48,77 @@ impl Proxy { } } impl Drop for Proxy { - fn drop(&mut self) { self.shutdown.cancel(); self.task.abort(); } + fn drop(&mut self) { + self.shutdown.cancel(); + self.task.abort(); + } } fn config() -> Config { - Config { port: 0, allow_h2c: true, shutdown_timeout: 1, ..Config::default() } + Config { + port: 0, + allow_h2c: true, + shutdown_timeout: 1, + ..Config::default() + } } -struct Client { sender: SendRequest, driver: JoinHandle<()> } +struct Client { + sender: SendRequest, + driver: JoinHandle<()>, +} impl Client { async fn new(io: T) -> Result - where T: AsyncRead + AsyncWrite + Unpin + Send + 'static { + where + T: AsyncRead + AsyncWrite + Unpin + Send + 'static, + { let (sender, connection) = h2::client::handshake(io).await?; - let driver = tokio::spawn(async move { let _ = connection.await; }); + let driver = tokio::spawn(async move { + let _ = connection.await; + }); Ok(Self { sender, driver }) } - async fn plain(proxy: &Proxy) -> Result { Self::new(TcpStream::connect(proxy.address).await?).await } - async fn send(&self, request: Request<()>, end: bool) -> Result<(h2::client::ResponseFuture, h2::SendStream)> { + async fn plain(proxy: &Proxy) -> Result { + Self::new(TcpStream::connect(proxy.address).await?).await + } + async fn send( + &self, + request: Request<()>, + end: bool, + ) -> Result<(h2::client::ResponseFuture, h2::SendStream)> { let mut sender = timeout(WAIT, self.sender.clone().ready()).await??; Ok(sender.send_request(request, end)?) } async fn get(&self, uri: String) -> Result> { - let request = Request::builder().version(Version::HTTP_2).uri(uri).body(())?; + let request = Request::builder() + .version(Version::HTTP_2) + .uri(uri) + .body(())?; let (response, _) = self.send(request, true).await?; Ok(timeout(WAIT, response).await??) } async fn tunnel(&self, target: SocketAddr) -> Result<(h2::SendStream, h2::RecvStream)> { - let request = Request::builder().version(Version::HTTP_2).method(Method::CONNECT) - .uri(target.to_string()).body(())?; + let request = Request::builder() + .version(Version::HTTP_2) + .method(Method::CONNECT) + .uri(target.to_string()) + .body(())?; let (response, send) = self.send(request, false).await?; let response = timeout(WAIT, response).await??; - ensure!(response.status() == 200, "CONNECT failed: {}", response.status()); + ensure!( + response.status() == 200, + "CONNECT failed: {}", + response.status() + ); ensure!(!response.headers().contains_key("content-length")); ensure!(!response.headers().contains_key("connection")); Ok((send, response.into_body())) } } -impl Drop for Client { fn drop(&mut self) { self.driver.abort(); } } +impl Drop for Client { + fn drop(&mut self) { + self.driver.abort(); + } +} async fn collect(mut body: h2::RecvStream) -> Result> { timeout(WAIT, async { @@ -90,7 +130,8 @@ async fn collect(mut body: h2::RecvStream) -> Result> { body.flow_control().release_capacity(count)?; } Ok(result) - }).await? + }) + .await? } async fn header(io: &mut T) -> Result { timeout(WAIT, async { @@ -100,12 +141,16 @@ async fn header(io: &mut T) -> Result { ensure!(bytes.len() < 65536); } Ok(String::from_utf8(bytes)?) - }).await? + }) + .await? } async fn inflight(proxy: &Proxy, count: u64) -> Result<()> { timeout(WAIT, async { - while proxy.metrics.inflight.load(Ordering::Relaxed) != count { sleep(Duration::from_millis(5)).await; } - }).await?; + while proxy.metrics.inflight.load(Ordering::Relaxed) != count { + sleep(Duration::from_millis(5)).await; + } + }) + .await?; Ok(()) } @@ -157,11 +202,22 @@ impl Origin { } } }); - Ok(Self { address, task, blocked, release }) + Ok(Self { + address, + task, + blocked, + release, + }) + } + fn url(&self, path: &str) -> String { + format!("http://{}{}", self.address, path) + } +} +impl Drop for Origin { + fn drop(&mut self) { + self.task.abort(); } - fn url(&self, path: &str) -> String { format!("http://{}{}", self.address, path) } } -impl Drop for Origin { fn drop(&mut self) { self.task.abort(); } } struct Certificate { _directory: tempfile::TempDir, @@ -177,16 +233,35 @@ impl Certificate { let key = directory.path().join("key.pem"); std::fs::write(&cert, generated.cert.pem())?; std::fs::write(&key, generated.key_pair.serialize_pem())?; - Ok(Self { _directory: directory, cert: cert.to_string_lossy().into_owned(), key: key.to_string_lossy().into_owned(), der: generated.cert.der().clone() }) + Ok(Self { + _directory: directory, + cert: cert.to_string_lossy().into_owned(), + key: key.to_string_lossy().into_owned(), + der: generated.cert.der().clone(), + }) } fn config(&self) -> Config { - Config { port: 0, tls_cert: Some(self.cert.clone()), tls_key: Some(self.key.clone()), shutdown_timeout: 1, ..Config::default() } + Config { + port: 0, + tls_cert: Some(self.cert.clone()), + tls_key: Some(self.key.clone()), + shutdown_timeout: 1, + ..Config::default() + } } - async fn connect(&self, proxy: &Proxy, alpn: &[&[u8]]) -> Result> { + async fn connect( + &self, + proxy: &Proxy, + alpn: &[&[u8]], + ) -> Result> { let mut roots = rustls::RootCertStore::empty(); roots.add(self.der.clone())?; - let mut client = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) - .with_safe_default_protocol_versions()?.with_root_certificates(roots).with_no_client_auth(); + let mut client = rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions()? + .with_root_certificates(roots) + .with_no_client_auth(); client.alpn_protocols = alpn.iter().map(|p| p.to_vec()).collect(); let connector = TlsConnector::from(Arc::new(client)); let tcp = TcpStream::connect(proxy.address).await?; @@ -217,7 +292,11 @@ async fn tls_supports_http1_alpn_and_no_alpn_fallback() -> Result<()> { let origin = Origin::new("http1").await?; for alpn in [vec![b"http/1.1".as_slice()], vec![]] { let mut tls = certificate.connect(&proxy, &alpn).await?; - let request = format!("GET {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n", origin.url("/"), origin.address); + let request = format!( + "GET {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n", + origin.url("/"), + origin.address + ); tls.write_all(request.as_bytes()).await?; let head = header(&mut tls).await?; assert!(head.starts_with("HTTP/1.1 200")); @@ -235,7 +314,10 @@ async fn disabling_http2_excludes_it_from_alpn() -> Result<()> { config.http2 = false; let proxy = Proxy::new(config).await?; let tls = certificate.connect(&proxy, &[b"h2", b"http/1.1"]).await?; - assert_eq!(tls.get_ref().1.alpn_protocol(), Some(b"http/1.1".as_slice())); + assert_eq!( + tls.get_ref().1.alpn_protocol(), + Some(b"http/1.1".as_slice()) + ); drop(tls); proxy.stop().await } @@ -254,14 +336,29 @@ async fn h2c_is_explicit_and_http1_still_works_on_the_same_port() -> Result<()> let proxy = Proxy::new(config()).await?; let origin = Origin::new("shared-port").await?; let client = Client::plain(&proxy).await?; - assert_eq!(collect(client.get(origin.url("/")).await?.into_body()).await?, b"shared-port"); + assert_eq!( + collect(client.get(origin.url("/")).await?.into_body()).await?, + b"shared-port" + ); let mut tcp = TcpStream::connect(proxy.address).await?; - tcp.write_all(format!("GET {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n", origin.url("/"), origin.address).as_bytes()).await?; + tcp.write_all( + format!( + "GET {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n", + origin.url("/"), + origin.address + ) + .as_bytes(), + ) + .await?; assert!(header(&mut tcp).await?.starts_with("HTTP/1.1 200")); drop(tcp); drop(client); proxy.stop().await?; - let proxy = Proxy::new(Config { port: 0, ..Config::default() }).await?; + let proxy = Proxy::new(Config { + port: 0, + ..Config::default() + }) + .await?; let client = Client::plain(&proxy).await?; assert!(client.get(origin.url("/")).await.is_err()); drop(client); @@ -276,9 +373,15 @@ async fn multiplexing_does_not_serialize_a_fast_request_behind_a_blocked_one() - let blocked = Request::builder().uri(origin.url("/blocked")).body(())?; let (slow, _) = client.send(blocked, true).await?; timeout(WAIT, origin.blocked.notified()).await?; - assert_eq!(collect(client.get(origin.url("/fast")).await?.into_body()).await?, b"ok"); + assert_eq!( + collect(client.get(origin.url("/fast")).await?.into_body()).await?, + b"ok" + ); origin.release.notify_one(); - assert_eq!(collect(timeout(WAIT, slow).await??.into_body()).await?, b"ok"); + assert_eq!( + collect(timeout(WAIT, slow).await??.into_body()).await?, + b"ok" + ); drop(client); proxy.stop().await } @@ -308,10 +411,13 @@ async fn h2_auth_is_per_stream_and_translation_preserves_http_semantics() -> Res assert_eq!(denied.status(), 407); assert!(!denied.headers().contains_key("connection")); collect(denied.into_body()).await?; - let request = Request::builder().uri(origin.url("/headers?q=1")) + let request = Request::builder() + .uri(origin.url("/headers?q=1")) .header("proxy-authorization", "Basic dXNlcjpwYXNz") .header("authorization", "Bearer origin-token") - .header("cookie", "a=1").header("cookie", "b=2").body(())?; + .header("cookie", "a=1") + .header("cookie", "b=2") + .body(())?; let (response, _) = client.send(request, true).await?; let response = timeout(WAIT, response).await??; assert_eq!(response.status(), 200); @@ -334,10 +440,15 @@ async fn host_authority_conflicts_are_not_forwarded() -> Result<()> { let origin = Origin::new("origin").await?; let proxy = Proxy::new(config()).await?; let client = Client::plain(&proxy).await?; - let request = Request::builder().uri(origin.url("/")).header("host", "different.invalid").body(())?; + let request = Request::builder() + .uri(origin.url("/")) + .header("host", "different.invalid") + .body(())?; let (response, _) = client.send(request, true).await?; // The protocol library may reject earlier than the application layer. - if let Ok(response) = timeout(WAIT, response).await? { assert_eq!(response.status(), 400); } + if let Ok(response) = timeout(WAIT, response).await? { + assert_eq!(response.status(), 400); + } drop(client); proxy.stop().await } @@ -348,8 +459,11 @@ async fn large_h2_upload_and_response_cross_flow_control_windows() -> Result<()> let proxy = Proxy::new(config()).await?; let client = Client::plain(&proxy).await?; let body = Bytes::from(vec![0x5a; 2 * 1024 * 1024]); - let request = Request::builder().method(Method::POST).uri(origin.url("/echo")) - .header("content-length", body.len()).body(())?; + let request = Request::builder() + .method(Method::POST) + .uri(origin.url("/echo")) + .header("content-length", body.len()) + .body(())?; let (response, mut send) = client.send(request, false).await?; // h2 buffers test input; production uses bounded Hyper streaming bodies. send.send_data(body.clone(), true)?; @@ -370,7 +484,10 @@ async fn h2_connect_preserves_early_data_half_close_and_sibling_streams() -> Res config.connect_ports = vec![aa.port(), bb.port()]; let proxy = Proxy::new(config).await?; let client = Client::plain(&proxy).await?; - let request = Request::builder().method(Method::CONNECT).uri(aa.to_string()).body(())?; + let request = Request::builder() + .method(Method::CONNECT) + .uri(aa.to_string()) + .body(())?; let (response, mut send_a) = client.send(request, false).await?; send_a.send_data(Bytes::from_static(b"early"), true)?; let response = timeout(WAIT, response).await??; @@ -392,7 +509,10 @@ async fn h2_connect_preserves_early_data_half_close_and_sibling_streams() -> Res up_b.shutdown().await?; assert_eq!(collect(recv_b).await?, b"sibling-ok"); let origin = Origin::new("still-h2").await?; - assert_eq!(collect(client.get(origin.url("/")).await?.into_body()).await?, b"still-h2"); + assert_eq!( + collect(client.get(origin.url("/")).await?.into_body()).await?, + b"still-h2" + ); drop(client); proxy.stop().await } @@ -415,7 +535,10 @@ async fn global_request_budget_includes_connect_and_recovers_after_reset() -> Re drop(recv); assert!(timeout(WAIT, upstream.read_u8()).await?.is_err()); inflight(&proxy, 0).await?; - assert_eq!(collect(client.get(origin.url("/")).await?.into_body()).await?, b"recovered"); + assert_eq!( + collect(client.get(origin.url("/")).await?.into_body()).await?, + b"recovered" + ); drop(client); proxy.stop().await } @@ -425,7 +548,9 @@ async fn reset_before_response_headers_closes_the_upstream_socket() -> Result<() let listener = TcpListener::bind("127.0.0.1:0").await?; let proxy = Proxy::new(config()).await?; let client = Client::plain(&proxy).await?; - let request = Request::builder().uri(format!("http://{}/", listener.local_addr()?)).body(())?; + let request = Request::builder() + .uri(format!("http://{}/", listener.local_addr()?)) + .body(())?; let (response, mut send) = client.send(request, true).await?; let (mut upstream, _) = timeout(WAIT, listener.accept()).await??; header(&mut upstream).await?; @@ -455,13 +580,18 @@ async fn busy_sibling_does_not_keep_an_idle_tunnel_alive() -> Result<()> { active_send.send_data(Bytes::from_static(b"a"), false)?; assert_eq!(timeout(WAIT, active_upstream.read_u8()).await??, b'a'); active_upstream.write_all(b"b").await?; - let data = timeout(WAIT, active_recv.data()).await?.transpose()?.unwrap(); + let data = timeout(WAIT, active_recv.data()) + .await? + .transpose()? + .unwrap(); assert_eq!(data, b"b".as_slice()); active_recv.flow_control().release_capacity(data.len())?; } assert!(timeout(WAIT, idle_upstream.read_u8()).await?.is_err()); let end = timeout(WAIT, idle_recv.data()).await?; - assert!(end.is_none() || end.is_some_and(|data| data.is_err() || data.is_ok_and(|b| b.is_empty()))); + assert!( + end.is_none() || end.is_some_and(|data| data.is_err() || data.is_ok_and(|b| b.is_empty())) + ); inflight(&proxy, 1).await?; active_send.send_reset(h2::Reason::CANCEL); drop(active_recv); @@ -481,7 +611,11 @@ async fn max_concurrent_streams_is_advertised_and_enforced() -> Result<()> { let (mut send, recv) = client.tunnel(target).await?; let (_upstream, _) = timeout(WAIT, listener.accept()).await??; // Server settings have arrived by the successful CONNECT response. - assert!(timeout(Duration::from_millis(100), client.sender.clone().ready()).await.is_err()); + assert!( + timeout(Duration::from_millis(100), client.sender.clone().ready()) + .await + .is_err() + ); send.send_reset(h2::Reason::CANCEL); drop(recv); timeout(WAIT, client.sender.clone().ready()).await??; @@ -522,7 +656,9 @@ async fn partial_h2_preface_has_a_total_deadline() -> Result<()> { tcp.write_all(b"PRI ").await?; sleep(Duration::from_millis(600)).await; tcp.write_all(b"*").await?; - assert!(timeout(Duration::from_secs(2), tcp.read_u8()).await?.is_err()); + assert!(timeout(Duration::from_secs(2), tcp.read_u8()) + .await? + .is_err()); proxy.stop().await } @@ -533,16 +669,31 @@ async fn tls_handshake_deadline_releases_connection_capacity() -> Result<()> { config.tls_handshake_timeout = 1; let proxy = Proxy::new(config).await?; let mut tcp = TcpStream::connect(proxy.address).await?; - assert!(timeout(Duration::from_secs(3), tcp.read_u8()).await?.is_err()); + assert!(timeout(Duration::from_secs(3), tcp.read_u8()) + .await? + .is_err()); proxy.stop().await } #[test] fn http2_tls_configuration_rejects_inconsistent_or_unbounded_settings() -> Result<()> { - for text in ["MaxConcurrentStreams 0", "MaxConcurrentStreams 1025", "MaxInflightRequests 0", "TLSCert cert.pem", "TLSKey key.pem", "HTTP2 No\nAllowH2C Yes", "TLSHandshakeTimeout 0", "TLSCert a\nTLSKey b\nAllowH2C Yes"] { - assert!(Config::parse(text).is_err(), "accepted invalid configuration: {text}"); + for text in [ + "MaxConcurrentStreams 0", + "MaxConcurrentStreams 1025", + "MaxInflightRequests 0", + "TLSCert cert.pem", + "TLSKey key.pem", + "HTTP2 No\nAllowH2C Yes", + "TLSHandshakeTimeout 0", + "TLSCert a\nTLSKey b\nAllowH2C Yes", + ] { + assert!( + Config::parse(text).is_err(), + "accepted invalid configuration: {text}" + ); } - let config = Config::parse("HTTP2 Yes\nAllowH2C Yes\nMaxConcurrentStreams 8\nMaxInflightRequests 32")?; + let config = + Config::parse("HTTP2 Yes\nAllowH2C Yes\nMaxConcurrentStreams 8\nMaxInflightRequests 32")?; assert!(config.http2 && config.allow_h2c); assert_eq!(config.max_concurrent_streams, 8); assert_eq!(config.max_inflight_requests, 32); @@ -568,7 +719,13 @@ fn tls_paths_resolve_relative_to_configuration() -> Result<()> { let path = directory.path().join("proxy.conf"); std::fs::write(&path, "TLSCert cert.pem\nTLSKey key.pem\n")?; let config = Config::from_file(&path)?; - assert_eq!(config.tls_cert.as_deref(), directory.path().join("cert.pem").to_str()); - assert_eq!(config.tls_key.as_deref(), directory.path().join("key.pem").to_str()); + assert_eq!( + config.tls_cert.as_deref(), + directory.path().join("cert.pem").to_str() + ); + assert_eq!( + config.tls_key.as_deref(), + directory.path().join("key.pem").to_str() + ); Ok(()) } From 1f9b5dce3d6395be5dd5c4ab92bd3b44bdfdbc45 Mon Sep 17 00:00:00 2001 From: Ray Tien Date: Sat, 19 Sep 2026 08:58:54 +0800 Subject: [PATCH 3/9] docs: document native HTTP2 TLS scope and resource limits --- README.md | 290 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 175 insertions(+), 115 deletions(-) diff --git a/README.md b/README.md index 6669231..8a39912 100644 --- a/README.md +++ b/README.md @@ -2,14 +2,14 @@ [![CI](https://github.com/Ray0907/tinyproxy-rust/actions/workflows/ci.yml/badge.svg)](https://github.com/Ray0907/tinyproxy-rust/actions/workflows/ci.yml) -A small HTTP/1 forward proxy and HTTPS CONNECT tunnel, written in Rust. +A small HTTP/1 and HTTP/2 forward proxy and HTTPS CONNECT tunnel, written in Rust. +Hyper handles HTTP framing and streaming; Tokio handles tunnels; Rustls protects +optional TLS listeners. One executable, with no database or external service. -The hardening implementation uses Hyper for HTTP message parsing and streaming, -and Tokio for TCP tunnels. It is **not a complete drop-in replacement** for C -Tinyproxy. Unsupported directives fail at startup instead of being silently -accepted. This project has not yet demonstrated a performance advantage over C -Tinyproxy; the included Criterion benchmarks are microbenchmarks, not proxy -throughput comparisons. +This is **not a complete drop-in replacement** for C Tinyproxy. Unsupported +directives fail at startup rather than being silently accepted. There is no +measured performance-superiority claim; Criterion benchmarks are microbenchmarks, +not proxy-throughput comparisons. ## Build and run @@ -26,26 +26,22 @@ curl --proxy http://127.0.0.1:8888 http://example.com/ curl --proxy http://127.0.0.1:8888 https://example.com/ ``` -The binary stays in the foreground. `-d` / `--foreground` explicitly selects the -same behavior. `--debug` initializes the logger once. `-v` / `--version` displays -the package version. An unreadable or missing configuration is an error, not a -request to start an unauthenticated listener with defaults. - -Run as an unprivileged user under a service manager. SIGINT and, on Unix, -SIGTERM stop new accepts, drain active work, and force-close remaining sockets -after `ShutdownTimeout`. This implementation does not fork, change users, -write PID files, or implement chroot. Existing configurations containing those -directives must be migrated explicitly. +The binary stays in the foreground; `-d` / `--foreground` explicitly selects that +behavior. `--debug` initializes logging once. `-v` / `--version` prints the package +version. Unreadable or missing configuration is an error. Run as an unprivileged +user under a service manager. SIGINT and, on Unix, SIGTERM stop new accepts, +drain active work, and force-close remaining work after `ShutdownTimeout`. ## Minimal configuration -The syntax is Tinyproxy-style key/value lines, **not TOML**. Quoted values and -comments beginning with `#` at a token boundary are supported. +Tinyproxy-style key/value lines, **not TOML**. Quoted values and comments beginning +with `#` at a token boundary are supported. ```conf Listen 127.0.0.1 Port 8888 MaxClients 100 +MaxInflightRequests 256 Timeout 600 HeaderTimeout 30 ConnectTimeout 30 @@ -54,54 +50,142 @@ ConnectPort 443 LogLevel Info ``` -The default listener is loopback only. Listening on a non-loopback address -requires explicit ACL rules or BasicAuth. `Allow all` is an explicit public -access choice; do not use it on an Internet-accessible unauthenticated proxy. -`Bind` sets the **outgoing** source IP and never changes the listener. - -Authentication can contain multiple users: +The default listener is loopback only. A non-loopback listener requires explicit +ACL rules or BasicAuth. `Allow all` is an explicit public-access choice; do not use +it for an Internet-accessible unauthenticated proxy. `Bind` sets the **outgoing** +source IP and does not change the listening address. ```conf BasicAuth alice "a password with spaces" BasicAuth bob another-password ``` -The old Rust `BasicAuth user:password` syntax is also accepted. Missing fields, -empty credentials, duplicate usernames, and malformed lines are rejected. -Configuration errors include line numbers without printing credential values. +Original-style and old Rust `BasicAuth user:password` syntax are accepted. +Multiple users are supported. Empty credentials, duplicate usernames, missing +fields, malformed ACLs and invalid filter files fail startup. Errors include line +numbers without printing credential values. Policies are compiled once and shared. + +## Native HTTP/2 and TLS + +The proxy can negotiate **HTTP/2 between client and proxy**, including multiple +HTTP requests and independent CONNECT tunnels on one connection. Every stream is +individually authenticated and filtered. H2 multiplexing, HPACK and flow control +are handled by Hyper/h2, not a custom frame parser. + +TLS is enabled by configuring both certificate and key. Paths are relative to the +configuration file. The same listening addresses become TLS-only: this is not an +automatic plaintext/TLS port detector. The example assumes a certificate valid for +`localhost`; use your actual proxy hostname and certificate in deployment. + +```conf +Listen 127.0.0.1 +Port 8888 +TLSCert certs/proxy-cert.pem +TLSKey certs/proxy-key.pem +TLSHandshakeTimeout 10 +HTTP2 Yes +MaxConcurrentStreams 32 +MaxInflightRequests 256 +ConnectPort 443 +``` + +Use curl 8.1.0+ with HTTP/2 support (`curl -V`): -**Basic authentication does not encrypt the client-to-proxy hop.** Use it only -on a trusted network or through an independently protected transport. HTTPS -through CONNECT protects the destination TLS session; it does not turn this -proxy's listening socket into a TLS listener. +```sh +curl -v --proxy-http2 \ + --proxy https://localhost:8888 \ + --proxy-cacert config/certs/proxy-cert.pem \ + https://example.com/ +``` + +The client verifies the proxy certificate; do not substitute `--proxy-insecure`. +`--proxy-http2` negotiates the **proxy hop**, unlike `--http2`, which concerns the +destination. Clients offering only `http/1.1`, or no ALPN, can still use HTTP/1 +on the TLS listener. `HTTP2 No` advertises only HTTP/1.1. TLS early data is disabled. + +Cleartext HTTP/2 prior knowledge is separately opt-in: + +```conf +HTTP2 Yes +AllowH2C Yes +``` + +It shares the plaintext listener with HTTP/1. This is for trusted local clients or +an independently secured transport; BasicAuth is **not encrypted** on this hop. +`AllowH2C` cannot be combined with TLS settings or `HTTP2 No`. HTTP/1.1 +`Upgrade: h2c` is not implemented. The standard curl `--proxy-http2` option applies +to HTTPS proxies, not h2c proxy connections. + +### What HTTP/2 support does and does not mean -## Supported configuration and compatibility +| Hop / feature | Support | +| --- | --- | +| Client to proxy, HTTP/1.1 | Plaintext by default, or optional TLS | +| Client to proxy, HTTP/2 | TLS + ALPN; opt-in cleartext prior knowledge | +| Ordinary HTTP request forwarding to origin | HTTP/1.1 streaming; H2 client requests are translated | +| CONNECT over HTTP/2 | One TCP tunnel per H2 stream; independent half-close, reset and idle lifetime | +| HTTPS origin HTTP/2 inside CONNECT | Negotiated end-to-end by client and origin; payload is opaque to the proxy | +| Automatic H2 origin connection pools | Not implemented | +| Extended CONNECT / WebSocket RFC 8441, server push, HTTP/3 | Not implemented or advertised | + +This is not TLS interception. Absolute `https://` forwarding is rejected: clients +must use CONNECT for HTTPS origins. Ordinary HTTP Upgrade/WebSocket forwarding is +not implemented either. WebSocket traffic already inside CONNECT remains opaque. + +### Bounded resources and lifecycle + +`MaxClients` limits client TCP connections, including TLS handshakes and upgraded +HTTP/1 tunnels. `MaxConcurrentStreams` is advertised for **each H2 connection**. +`MaxInflightRequests` limits active HTTP exchanges/CONNECT streams **across the +whole process**, including HTTP/1. Excess application requests receive 503 without +an unbounded wait queue. Capacity remains held until response/tunnel and upstream +work are released. These limits are not requests-per-second rate limiting. + +Each exchange has an independent progress-based `Timeout`. Traffic on a sibling +stream cannot keep an idle tunnel alive. RST_STREAM cancels that stream's work, +not the entire client connection. Graceful H2 shutdown sends GOAWAY and drains +existing work before forced termination. Hyper's stream/upgrade drivers are tracked. + +H2 limits: 16 KiB decoded header-list limit, 4 KiB HPACK table, 16 KiB inbound +frame size, 65,535-byte initial stream receive window, 1 MiB connection receive +window, 64 KiB per-stream send buffer, and explicit pending/local-reset limits. +Adaptive receive-window growth is disabled. These are protocol/application limits, +**not a promised RSS bound**: TCP, TLS and library buffers also consume memory. + +`HeaderTimeout` bounds HTTP/1 header reads and initial H2 preface detection. +**There is no separate per-header-block deadline for fragmented H2 HEADERS / +CONTINUATION after the preface**; a byte-active peer may still tie up connection +resources. The reset and size limits are not a complete DoS defense. Do not expose +this trusted-client proxy as an unauthenticated public service. + +## Supported configuration | Directives | Behavior | | --- | --- | -| `Listen`, `Port` | Repeatable listening addresses; loopback by default. Port 0 is useful for embedded tests. | -| `Bind` | Outbound source IP, including address-family matching. | -| `Allow`, `Deny` | IP/CIDR, `all`, or `*`. First matching rule wins; unmatched clients are denied when any rules exist. Hostname ACLs are not supported. IPv4-mapped clients are normalized. | -| `BasicAuth` | Multiple username/password pairs; checked on every HTTP request. | -| `ConnectPort` | First explicit directive replaces defaults `[443, 563]`; repeat to add ports. A lone `ConnectPort 0` disables CONNECT. Mixing 0 and real ports is an error. | -| `Timeout` | Idle timeout in seconds, reset by actual I/O progress in either direction; not a maximum tunnel lifetime. | -| `HeaderTimeout` | Total time to receive a request header, in seconds; trickling bytes does not reset it. | -| `ConnectTimeout` | Combined DNS resolution and TCP connect deadline, in seconds. | -| `ShutdownTimeout` | Grace period before remaining connections are force-closed. | -| `MaxClients` | Connection limit, retained for the full CONNECT tunnel lifetime. | -| `Filter`, `FilterURLs`, `FilterExtended`, `FilterCaseSensitive`, `FilterDefaultDeny` | See filtering below. | -| `ViaProxyName`, `DisableViaHeader` | Append the proxy's Via value, preserving prior Via entries, unless disabled. | -| `StatHost` | Exact destination-host match for an authenticated GET/HEAD HTML statistics page. | -| `LogLevel` | Rust log levels such as Error, Warn, Info, Debug, Trace, and Off. | - -All other directives are rejected. In particular, upstream proxy chaining, -reverse/transparent modes, `Anonymous`, `AddHeader`, custom error pages, -`User`/`Group`, `PidFile`, `LogFile`/`Syslog`, and legacy child-process settings -are **not implemented**. Previous helper functions and configuration fields -that did not participate in actual forwarding have been removed rather than -advertised as working features. - -### Filtering +| `Listen`, `Port` | Repeatable IP listening addresses; loopback by default. Port 0 supports embedded tests. | +| `Bind` | Outbound source IP, with address-family matching. | +| `Allow`, `Deny` | Ordered IP/CIDR, `all`, `*`; first match wins, unmatched denied when rules exist. IPv4-mapped clients normalized. No hostname ACLs. | +| `BasicAuth` | Multiple users, checked on every request/stream. | +| `ConnectPort` | First explicit value replaces defaults `[443, 563]`. Repeat to add ports; a lone 0 disables CONNECT. | +| `Timeout` | Per-connection and per-exchange idle timeout, seconds; not maximum connection age. | +| `HeaderTimeout`, `ConnectTimeout` | Header/preface and combined DNS/TCP-connect deadlines, seconds. | +| `ShutdownTimeout` | Grace period before forced shutdown, seconds. | +| `MaxClients` | Client TCP connection budget. | +| `HTTP2`, `AllowH2C` | Default Yes / No; H2 requires TLS or explicit h2c. | +| `MaxConcurrentStreams` | H2 streams per connection; default 32, range 1..=1024. | +| `MaxInflightRequests` | Global active-exchange budget; default 256. | +| `TLSCert`, `TLSKey` | PEM certificate chain and matching private key, loaded and validated before binding. No automatic certificate issuance/reload. | +| `TLSHandshakeTimeout` | Total TLS handshake deadline, default 10 seconds. | +| `Filter`, `FilterURLs`, `FilterExtended`, `FilterCaseSensitive`, `FilterDefaultDeny` | See below. | +| `ViaProxyName`, `DisableViaHeader` | Append Via with the received hop's HTTP version, unless disabled. | +| `StatHost` | Exact host match for authenticated GET/HEAD statistics, including H2/in-flight counters. | +| `LogLevel` | Error, Warn, Info, Debug, Trace, Off. | + +Other directives are rejected, including upstream proxy chaining, reverse / +transparent modes, Anonymous/AddHeader, custom error pages, User/Group, PID/log +files, syslog, and legacy child-process settings. No fork/chroot is performed. + +### Filtering and HTTP semantics ```conf Filter "blocked-domains.txt" @@ -110,43 +194,25 @@ FilterExtended No FilterCaseSensitive No ``` -Relative filter paths resolve against the configuration's directory. Policies -are loaded and compiled once before sockets are bound. Missing files and invalid -regular expressions are startup errors; invalid expressions are not converted -to permissive literal rules. Changes require a restart; hot reload is not yet -implemented. - -With `FilterURLs No`, filtering still operates, but uses the destination host. -With `FilterExtended No`, lines such as `example.com` or `.example.com` match -the domain and its subdomains, not `notexample.com` or `example.com.evil.test`. -With `FilterURLs Yes`, literal rules are substring matches against the HTTP URL. -`FilterExtended Yes` selects Rust regular expressions; this is **not POSIX BRE/ERE -syntax compatibility**. `FilterDefaultDeny Yes` makes matching rules an allowlist. -By default, matching rules are blocked. - -CONNECT is always filtered by its authority host, never by an imagined HTTPS -URL path. The encrypted request contents are not inspected. - -## HTTP and connection behavior - -HTTP requests are parsed and forwarded individually, including successive -requests to different origins over one client connection. Bodies remain -streaming. Direct-origin requests use origin-form paths with a Host header -derived from the chosen authority. Absolute `https://` forwarding is rejected; -clients must use CONNECT rather than accidentally sending plaintext to a TLS -port. HTTP Upgrade/WebSocket forwarding is not yet supported. - -Proxy credentials and hop-by-hop headers are consumed at the proxy boundary; -ordinary origin `Authorization`, multiple `Set-Cookie` fields, and end-to-end -headers are preserved. Hyper owns body framing instead of converting all -headers into a single-value string map. Request headers are bounded by a 16 KiB -connection buffer and a total read deadline. - -CONNECT uses Tokio's bidirectional copy, including half-close handling and -bytes buffered beyond the initial CONNECT header. HTTP connections, upstream -drivers, and upgraded tunnels are tracked during shutdown. Counters use atomics; -wire-byte counters refer to the client-facing socket, including HTTP headers, -not solely response payloads. +Relative filter paths resolve against the configuration directory. Missing files +or invalid regexes fail startup. Changes require restart; hot reload is pending. +`FilterURLs No` filters hosts. With `FilterExtended No`, `example.com` and +`.example.com` match the domain and subdomains, not `notexample.com` or +`example.com.evil.test`. With `FilterURLs Yes`, literal rules match substrings of +HTTP URLs. `FilterExtended Yes` uses Rust regex, not POSIX BRE/ERE syntax. +`FilterDefaultDeny Yes` turns the list into an allowlist. CONNECT always filters +its authority host, never an imagined HTTPS URL path. + +Proxy credentials and hop-by-hop headers are consumed in both directions. +Ordinary origin Authorization and repeated Set-Cookie fields are preserved. +HTTP/2 Cookie fields are joined with `; ` for HTTP/1 forwarding. H2 Host/authority +conflicts are rejected. Sensitive/routing/hop-by-hop fields cannot be smuggled in +forwarded trailers. Bodies stream rather than being buffered in full. + +Metrics count client-facing HTTP bytes after TLS decryption, including framing, +not solely body bytes and not TLS handshake/ciphertext overhead. Initial protocol +sniffed bytes are replayed to the counted stream. Logging intentionally excludes +raw URLs, headers and credentials. ## Verification @@ -158,31 +224,25 @@ cargo build --release --locked cargo bench --locked ``` -Regression tests use local sockets and ephemeral ports, not public Internet -endpoints. They cover configuration failure modes, credentials and hop-by-hop -headers, repeated requests, origin selection, domain filters, chunked and large -uploads, Expect/100-continue, conflicting Content-Length values, early CONNECT -data, half-close, connection limits, slow headers, and shutdown. - -A passing test suite is not a comprehensive security audit or evidence that -all HTTP edge cases are covered. Cross-implementation differential tests, -fuzzing, prolonged load tests, and controlled end-to-end performance comparisons -remain follow-up work. +Tests use local sockets, ephemeral ports, and generated test-only certificates; +no public Internet origins. Coverage includes HTTP/1 regressions, H2 multiplexing, +TLS validation/fallback, stream isolation, flow control, cancellation, capacity, +preface/handshake deadlines and graceful draining. Consult current CI results for +which platforms/checks actually passed. A green suite is not a security audit, +comprehensive conformance claim, or throughput comparison. ## Security boundaries and remaining work -This is a trusted-client forward proxy, not a sandbox or a complete SSRF/DLP -boundary. Client ACLs constrain who connects; they do not restrict resolved -destination IPs. Allowed clients can reach private/loopback destinations and -allowed CONNECT ports unless separately restricted by the network. DNS rebinding -protection, destination-IP policy, TLS listeners, rate limiting, and constant-time -authentication are not provided by this revision. Setting a proxy environment -variable also does not force an untrusted program to use the proxy. - -Next priorities are end-to-end benchmarks against pinned C Tinyproxy versions, -additional protocol/adversarial tests, measured HTTP connection pooling, -transactional policy reload, and simpler deployment packages. No external service -or database is required by the current executable. +For trusted clients, not a sandbox or complete SSRF/DLP boundary. Source ACLs do +not constrain resolved destination IPs. Allowed clients can reach private / +loopback services unless network policy prevents this. DNS rebinding protection, +destination-IP rules, rate limiting, constant-time authentication, transactional +reload, mutual TLS, and origin connection pooling remain pending. Configuring a +proxy environment variable does not force untrusted software to use the proxy. + +Future performance work requires controlled benchmarks against pinned C Tinyproxy +versions, including latency, errors, memory and content correctness. HTTP/2 support +alone does not demonstrate higher throughput or lower latency. ## License From 4578efb77c6fa80977a296b535db21ebf1e46860 Mon Sep 17 00:00:00 2001 From: Ray Tien Date: Sat, 19 Sep 2026 09:03:15 +0800 Subject: [PATCH 4/9] fix: handle HTTP2 reset EOF without leaking half-open upstreams Use a bounded H2-only relay that observes upgrade writer reset errors without inserting bytes or disturbing valid half-close. Correct the stream-limit regression to assert actual wire dispatch, not h2 readiness. --- .github/workflows/prepare-http2.yml | 93 +++++++++++++++++++++++++++-- src/h2_tunnel.rs | 53 ++++++++++++++++ src/lib.rs | 1 + 3 files changed, 142 insertions(+), 5 deletions(-) create mode 100644 src/h2_tunnel.rs diff --git a/.github/workflows/prepare-http2.yml b/.github/workflows/prepare-http2.yml index c78e547..ba5d9c0 100644 --- a/.github/workflows/prepare-http2.yml +++ b/.github/workflows/prepare-http2.yml @@ -2,9 +2,12 @@ name: Prepare HTTP2 branch on: push: branches: [feat/http2-proxy] - paths: [Cargo.toml, src/**, tests/**] + paths: [Cargo.toml, src/**, tests/**, .github/workflows/prepare-http2.yml] permissions: contents: write +concurrency: + group: prepare-http2 + cancel-in-progress: true jobs: prepare: if: github.ref == 'refs/heads/feat/http2-proxy' @@ -15,15 +18,95 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy - - name: Normalize source and lock dependencies on this feature branch only + - name: Apply reviewed reset integration and regression corrections + run: | + python3 - <<'PY' + from pathlib import Path + p = Path('src/connection.rs') + s = p.read_text() + old = 'copy_bidirectional(&mut client, &mut target).await?;' + if 'crate::h2_tunnel::relay' not in s: + assert s.count(old) == 1 + s = s.replace(old, '''if version == Version::HTTP_2 { + crate::h2_tunnel::relay(client, target).await?; + } else { + copy_bidirectional(&mut client, &mut target).await?; + }''') + p.write_text(s) + p = Path('tests/http2.rs') + s = p.read_text() + old = ' request: Request<()>,\n end: bool,' + if old in s: + s = s.replace(old, ' mut request: Request<()>,\n end: bool,') + old = ' Ok(sender.send_request(request, end)?)' + assert s.count(old) == 1 + s = s.replace(old, ' *request.version_mut() = Version::HTTP_2;\n' + old) + begin = s.index('#[tokio::test]\nasync fn max_concurrent_streams_is_advertised_and_enforced') + end = s.index('#[tokio::test]', begin + 1) + s = s[:begin] + '''#[tokio::test] + async fn max_concurrent_streams_is_advertised_and_enforced() -> Result<()> { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let target = listener.local_addr()?; + let mut config = config(); + config.max_concurrent_streams = 1; + config.connect_ports = vec![target.port()]; + let proxy = Proxy::new(config).await?; + let origin = Origin::new("after-capacity").await?; + let client = Client::plain(&proxy).await?; + let (mut send, recv) = client.tunnel(target).await?; + let (_upstream, _) = timeout(WAIT, listener.accept()).await??; + assert_eq!(client.sender.current_max_send_streams(), 1); + // h2 allows a pending request to be created; ready() alone is not + // proof of an available wire stream. Assert observable dispatch. + let request = Request::builder().uri(origin.url("/")).body(())?; + let (mut response, _) = client.send(request, true).await?; + assert!(timeout(Duration::from_millis(100), &mut response).await.is_err()); + assert_eq!(proxy.metrics.requests.load(Ordering::Relaxed), 1); + send.send_reset(h2::Reason::CANCEL); + drop(recv); + assert_eq!(collect(timeout(WAIT, response).await??.into_body()).await?, b"after-capacity"); + drop(client); + proxy.stop().await + } + + ''' + s[end:] + if 'h2_reset_after_half_close_releases_idle_upstream' not in s: + s += ''' + #[tokio::test] + async fn h2_reset_after_half_close_releases_idle_upstream() -> Result<()> { + for reason in [h2::Reason::CANCEL, h2::Reason::NO_ERROR] { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let target = listener.local_addr()?; + let mut config = config(); + config.connect_ports = vec![target.port()]; + let proxy = Proxy::new(config).await?; + let client = Client::plain(&proxy).await?; + let (mut send, recv) = client.tunnel(target).await?; + let (mut upstream, _) = timeout(WAIT, listener.accept()).await??; + send.send_data(Bytes::new(), true)?; + assert!(timeout(WAIT, upstream.read_u8()).await?.is_err()); + // Normal END_STREAM must retain the response direction. + assert_eq!(proxy.metrics.inflight.load(Ordering::Relaxed), 1); + send.send_reset(reason); + drop(recv); + // Do NOT close the idle upstream: reset itself must free it. + inflight(&proxy, 0).await?; + drop(client); + proxy.stop().await?; + } + Ok(()) + } + ''' + p.write_text(s) + PY + - name: Normalize and commit only reviewed source files on the feature branch run: | - cargo generate-lockfile cargo fmt --all git config user.name 'github-actions[bot]' git config user.email '41898282+github-actions[bot]@users.noreply.github.com' - git add Cargo.lock src tests + git add src tests if ! git diff --cached --quiet; then - git commit -m 'build: lock HTTP2 TLS dependencies and format sources' + git commit -m 'fix: release reset H2 tunnels and verify stream capacity on the wire' git push origin HEAD:feat/http2-proxy fi - run: cargo test --all-targets --locked diff --git a/src/h2_tunnel.rs b/src/h2_tunnel.rs new file mode 100644 index 0000000..2e0a3c3 --- /dev/null +++ b/src/h2_tunnel.rs @@ -0,0 +1,53 @@ +//! Half-close-safe relay for Hyper's HTTP/2 CONNECT upgrade adapter. +use std::io; +use std::time::Duration; +use tokio::io::{copy, split, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::time::{interval_at, Instant, MissedTickBehavior}; + +/// Hyper 1.11 maps received CANCEL/NO_ERROR resets to read EOF. Its upgrade +/// writer, however, exposes the reset through poll_flush. A plain bidirectional +/// copy can therefore mistake RST_STREAM for END_STREAM and retain an idle TCP +/// socket indefinitely. Check the writer every 250ms without sending bytes. +/// +/// This is deliberately restricted to the H2 upgrade adapter. Normal TCP/H1 +/// tunnels still use Tokio copy_bidirectional. Independent copying preserves +/// real half-close; a reset error aborts both directions. The outer exchange +/// enforces idle/forced-shutdown deadlines. The tick does not count as activity. +pub async fn relay(client: C, target: T) -> io::Result<(u64, u64)> +where + C: AsyncRead + AsyncWrite + Unpin, + T: AsyncRead + AsyncWrite + Unpin, +{ + let (mut client_read, mut client_write) = split(client); + let (mut target_read, mut target_write) = split(target); + let upload = async { + let count = copy(&mut client_read, &mut target_write).await?; + target_write.shutdown().await?; + Ok::<_, io::Error>(count) + }; + let download = async { + let period = Duration::from_millis(250); + let mut check = interval_at(Instant::now() + period, period); + check.set_missed_tick_behavior(MissedTickBehavior::Skip); + let mut buffer = [0u8; 8192]; + let mut count = 0u64; + loop { + tokio::select! { + read = target_read.read(&mut buffer) => { + let size = read?; + if size == 0 { + client_write.shutdown().await?; + return Ok::<_, io::Error>(count); + } + client_write.write_all(&buffer[..size]).await?; + count += size as u64; + } + _ = check.tick() => { + // Also observes remote resets when target_read is idle. + client_write.flush().await?; + } + } + } + }; + tokio::try_join!(upload, download) +} diff --git a/src/lib.rs b/src/lib.rs index 4f8ad7e..f0bc36a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,7 @@ pub mod config; pub mod connection; mod exchange; pub mod filter; +mod h2_tunnel; mod protocol; pub mod runtime; pub mod server; From eca324491aacb01218214c3d28f79c7e08ee210c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 19 Sep 2026 01:03:38 +0000 Subject: [PATCH 5/9] fix: release reset H2 tunnels and verify stream capacity on the wire --- src/connection.rs | 6 +++++- tests/http2.rs | 49 +++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 46 insertions(+), 9 deletions(-) diff --git a/src/connection.rs b/src/connection.rs index dc9d16e..d01df3e 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -279,7 +279,11 @@ async fn forward( let mut client = ActivityIo::new(TokioIo::new(upgraded), state.activity.clone(), None); let mut target = ActivityIo::new(target_stream, state.activity.clone(), None); - copy_bidirectional(&mut client, &mut target).await?; + if version == Version::HTTP_2 { + crate::h2_tunnel::relay(client, target).await?; + } else { + copy_bidirectional(&mut client, &mut target).await?; + } Ok::<_, BoxError>(()) }; tokio::select! { diff --git a/tests/http2.rs b/tests/http2.rs index 5a7391d..4e5c5fc 100644 --- a/tests/http2.rs +++ b/tests/http2.rs @@ -82,10 +82,11 @@ impl Client { } async fn send( &self, - request: Request<()>, + mut request: Request<()>, end: bool, ) -> Result<(h2::client::ResponseFuture, h2::SendStream)> { let mut sender = timeout(WAIT, self.sender.clone().ready()).await??; + *request.version_mut() = Version::HTTP_2; Ok(sender.send_request(request, end)?) } async fn get(&self, uri: String) -> Result> { @@ -607,18 +608,25 @@ async fn max_concurrent_streams_is_advertised_and_enforced() -> Result<()> { config.max_concurrent_streams = 1; config.connect_ports = vec![target.port()]; let proxy = Proxy::new(config).await?; + let origin = Origin::new("after-capacity").await?; let client = Client::plain(&proxy).await?; let (mut send, recv) = client.tunnel(target).await?; let (_upstream, _) = timeout(WAIT, listener.accept()).await??; - // Server settings have arrived by the successful CONNECT response. - assert!( - timeout(Duration::from_millis(100), client.sender.clone().ready()) - .await - .is_err() - ); + assert_eq!(client.sender.current_max_send_streams(), 1); + // h2 allows a pending request to be created; ready() alone is not + // proof of an available wire stream. Assert observable dispatch. + let request = Request::builder().uri(origin.url("/")).body(())?; + let (mut response, _) = client.send(request, true).await?; + assert!(timeout(Duration::from_millis(100), &mut response) + .await + .is_err()); + assert_eq!(proxy.metrics.requests.load(Ordering::Relaxed), 1); send.send_reset(h2::Reason::CANCEL); drop(recv); - timeout(WAIT, client.sender.clone().ready()).await??; + assert_eq!( + collect(timeout(WAIT, response).await??.into_body()).await?, + b"after-capacity" + ); drop(client); proxy.stop().await } @@ -729,3 +737,28 @@ fn tls_paths_resolve_relative_to_configuration() -> Result<()> { ); Ok(()) } + +#[tokio::test] +async fn h2_reset_after_half_close_releases_idle_upstream() -> Result<()> { + for reason in [h2::Reason::CANCEL, h2::Reason::NO_ERROR] { + let listener = TcpListener::bind("127.0.0.1:0").await?; + let target = listener.local_addr()?; + let mut config = config(); + config.connect_ports = vec![target.port()]; + let proxy = Proxy::new(config).await?; + let client = Client::plain(&proxy).await?; + let (mut send, recv) = client.tunnel(target).await?; + let (mut upstream, _) = timeout(WAIT, listener.accept()).await??; + send.send_data(Bytes::new(), true)?; + assert!(timeout(WAIT, upstream.read_u8()).await?.is_err()); + // Normal END_STREAM must retain the response direction. + assert_eq!(proxy.metrics.inflight.load(Ordering::Relaxed), 1); + send.send_reset(reason); + drop(recv); + // Do NOT close the idle upstream: reset itself must free it. + inflight(&proxy, 0).await?; + drop(client); + proxy.stop().await?; + } + Ok(()) +} From 48f0eb729632cff6a5c6052ccd522a028e9c5dd8 Mon Sep 17 00:00:00 2001 From: Ray Tien Date: Sat, 19 Sep 2026 09:04:44 +0800 Subject: [PATCH 6/9] test: exercise TLS HTTP2 proxy and CONNECT with a real curl client --- scripts/test_curl_proxy.py | 142 +++++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 scripts/test_curl_proxy.py diff --git a/scripts/test_curl_proxy.py b/scripts/test_curl_proxy.py new file mode 100644 index 0000000..5d13683 --- /dev/null +++ b/scripts/test_curl_proxy.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Offline curl interoperability test; generates throwaway TLS credentials. + +Run after cargo build --release: + python3 scripts/test_curl_proxy.py --curl /usr/bin/curl +Requires Python 3.10+, openssl, and curl 8.1+ compiled with HTTP2 support. +No certificate verification is disabled and no Internet origin is contacted. +""" +from __future__ import annotations + +import argparse +import http.server +import os +from pathlib import Path +import re +import ssl +import subprocess +import tempfile +import threading +import time + +PAYLOAD = b"tinyproxy-curl-ok" + + +class Origin(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def do_GET(self) -> None: + leaked = self.headers.get("Proxy-Authorization") is not None + body = b"proxy-credentials-leaked" if leaked else PAYLOAD + self.send_response(500 if leaked else 200) + self.send_header("Content-Type", "text/plain") + self.send_header("Content-Length", str(len(body))) + self.send_header("Connection", "close") + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: object) -> None: + pass + + +def run(command: list[str], seconds: float = 15) -> subprocess.CompletedProcess[str]: + return subprocess.run(command, text=True, capture_output=True, timeout=seconds, check=True) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", default="target/release/tinyproxy-rust") + parser.add_argument("--curl", default="curl") + args = parser.parse_args() + binary = str(Path(args.binary).resolve(strict=True)) + version = run([args.curl, "--version"]).stdout + if "HTTP2" not in version: + raise RuntimeError("curl must be built with HTTP2 support") + print(version.splitlines()[0], flush=True) + + with tempfile.TemporaryDirectory(prefix="tinyproxy-curl-") as directory: + root = Path(directory) + certificate = root / "cert.pem" + key = root / "key.pem" + run([ + "openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", + "-keyout", str(key), "-out", str(certificate), "-days", "1", + "-subj", "/CN=localhost", "-addext", "subjectAltName=DNS:localhost", + ]) + key.chmod(0o600) + plain = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Origin) + secure = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Origin) + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(str(certificate), str(key)) + context.set_alpn_protocols(["http/1.1"]) + secure.socket = context.wrap_socket(secure.socket, server_side=True) + servers = [plain, secure] + for server in servers: + server.daemon_threads = True + threading.Thread(target=server.serve_forever, daemon=True).start() + + configuration = root / "proxy.conf" + configuration.write_text( + "Listen 127.0.0.1\nPort 0\nTLSCert cert.pem\nTLSKey key.pem\n" + "HTTP2 Yes\nShutdownTimeout 1\nBasicAuth test-user test-password\n" + f"ConnectPort {plain.server_port}\nConnectPort {secure.server_port}\n", + encoding="utf-8", + ) + log_path = root / "proxy.log" + process: subprocess.Popen[bytes] | None = None + try: + with log_path.open("wb") as logs: + environment = dict(os.environ, RUST_LOG="info", RUST_LOG_STYLE="never") + process = subprocess.Popen( + [binary, "-c", str(configuration)], stdout=logs, stderr=logs, env=environment, + ) + deadline = time.monotonic() + 10 + while True: + match = re.search(r"Listening on 127\.0\.0\.1:(\d+)", log_path.read_text(errors="replace")) + if match: + port = int(match.group(1)) + break + if process.poll() is not None or time.monotonic() >= deadline: + raise RuntimeError("proxy did not start: " + log_path.read_text(errors="replace")) + time.sleep(0.02) + + common = [ + args.curl, "--silent", "--show-error", "--fail", "--max-time", "10", + "--noproxy", "", "--proxy", f"https://localhost:{port}", + "--proxy-cacert", str(certificate), "--cacert", str(certificate), + "--proxy-user", "test-user:test-password", "--write-out", "\n%{http_code} %{http_version}", + ] + http_url = f"http://localhost:{plain.server_port}/" + https_url = f"https://localhost:{secure.server_port}/" + cases = [ + ("HTTP2 forwarding over verified TLS", ["--proxy-http2", http_url], "2"), + ("HTTP2 CONNECT to verified HTTPS origin", ["--proxy-http2", https_url], "1.1"), + ("HTTP2 CONNECT to plaintext TCP origin", ["--proxy-http2", "--proxytunnel", http_url], "1.1"), + ("HTTP1 HTTPS-proxy fallback", [http_url], "1.1"), + ] + for name, arguments, expected_version in cases: + result = run(common + arguments) + expected = PAYLOAD.decode() + f"\n200 {expected_version}" + if result.stdout != expected: + raise AssertionError(f"{name}: unexpected result {result.stdout!r}") + print(f"PASS: {name}", flush=True) + process.terminate() + process.wait(timeout=5) + if process.returncode != 0: + raise RuntimeError(f"proxy shutdown failed: {process.returncode}") + print("PASS: graceful proxy process shutdown", flush=True) + finally: + if process is not None and process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + for server in servers: + server.shutdown() + server.server_close() + + +if __name__ == "__main__": + main() From 859b06df4c09f06ad6da9b3b91d57a870069a581 Mon Sep 17 00:00:00 2001 From: Ray Tien Date: Sat, 19 Sep 2026 09:06:10 +0800 Subject: [PATCH 7/9] style: finalize configuration path iterator and verify HTTP2 build --- .github/workflows/prepare-http2.yml | 102 ++++++---------------------- 1 file changed, 21 insertions(+), 81 deletions(-) diff --git a/.github/workflows/prepare-http2.yml b/.github/workflows/prepare-http2.yml index ba5d9c0..399f745 100644 --- a/.github/workflows/prepare-http2.yml +++ b/.github/workflows/prepare-http2.yml @@ -2,7 +2,7 @@ name: Prepare HTTP2 branch on: push: branches: [feat/http2-proxy] - paths: [Cargo.toml, src/**, tests/**, .github/workflows/prepare-http2.yml] + paths: [.github/workflows/prepare-http2.yml] permissions: contents: write concurrency: @@ -18,97 +18,37 @@ jobs: - uses: dtolnay/rust-toolchain@stable with: components: rustfmt, clippy - - name: Apply reviewed reset integration and regression corrections + - name: Normalize the configuration iterator run: | python3 - <<'PY' from pathlib import Path - p = Path('src/connection.rs') + p = Path('src/config.rs') s = p.read_text() - old = 'copy_bidirectional(&mut client, &mut target).await?;' - if 'crate::h2_tunnel::relay' not in s: - assert s.count(old) == 1 - s = s.replace(old, '''if version == Version::HTTP_2 { - crate::h2_tunnel::relay(client, target).await?; - } else { - copy_bidirectional(&mut client, &mut target).await?; - }''') - p.write_text(s) - p = Path('tests/http2.rs') - s = p.read_text() - old = ' request: Request<()>,\n end: bool,' - if old in s: - s = s.replace(old, ' mut request: Request<()>,\n end: bool,') - old = ' Ok(sender.send_request(request, end)?)' - assert s.count(old) == 1 - s = s.replace(old, ' *request.version_mut() = Version::HTTP_2;\n' + old) - begin = s.index('#[tokio::test]\nasync fn max_concurrent_streams_is_advertised_and_enforced') - end = s.index('#[tokio::test]', begin + 1) - s = s[:begin] + '''#[tokio::test] - async fn max_concurrent_streams_is_advertised_and_enforced() -> Result<()> { - let listener = TcpListener::bind("127.0.0.1:0").await?; - let target = listener.local_addr()?; - let mut config = config(); - config.max_concurrent_streams = 1; - config.connect_ports = vec![target.port()]; - let proxy = Proxy::new(config).await?; - let origin = Origin::new("after-capacity").await?; - let client = Client::plain(&proxy).await?; - let (mut send, recv) = client.tunnel(target).await?; - let (_upstream, _) = timeout(WAIT, listener.accept()).await??; - assert_eq!(client.sender.current_max_send_streams(), 1); - // h2 allows a pending request to be created; ready() alone is not - // proof of an available wire stream. Assert observable dispatch. - let request = Request::builder().uri(origin.url("/")).body(())?; - let (mut response, _) = client.send(request, true).await?; - assert!(timeout(Duration::from_millis(100), &mut response).await.is_err()); - assert_eq!(proxy.metrics.requests.load(Ordering::Relaxed), 1); - send.send_reset(h2::Reason::CANCEL); - drop(recv); - assert_eq!(collect(timeout(WAIT, response).await??.into_body()).await?, b"after-capacity"); - drop(client); - proxy.stop().await - } - + if 'for file in [' in s: + start = s.index(' for file in [') + end = s.index(' Ok(config)', start) + s = s[:start] + ''' for value in [ + &mut config.filter_file, + &mut config.tls_cert, + &mut config.tls_key, + ].into_iter().flatten() { + if Path::new(value).is_relative() { + *value = path.parent().unwrap_or_else(|| Path::new(".")) + .join(&*value).to_string_lossy().into_owned(); + } + } ''' + s[end:] - if 'h2_reset_after_half_close_releases_idle_upstream' not in s: - s += ''' - #[tokio::test] - async fn h2_reset_after_half_close_releases_idle_upstream() -> Result<()> { - for reason in [h2::Reason::CANCEL, h2::Reason::NO_ERROR] { - let listener = TcpListener::bind("127.0.0.1:0").await?; - let target = listener.local_addr()?; - let mut config = config(); - config.connect_ports = vec![target.port()]; - let proxy = Proxy::new(config).await?; - let client = Client::plain(&proxy).await?; - let (mut send, recv) = client.tunnel(target).await?; - let (mut upstream, _) = timeout(WAIT, listener.accept()).await??; - send.send_data(Bytes::new(), true)?; - assert!(timeout(WAIT, upstream.read_u8()).await?.is_err()); - // Normal END_STREAM must retain the response direction. - assert_eq!(proxy.metrics.inflight.load(Ordering::Relaxed), 1); - send.send_reset(reason); - drop(recv); - // Do NOT close the idle upstream: reset itself must free it. - inflight(&proxy, 0).await?; - drop(client); - proxy.stop().await?; - } - Ok(()) - } - ''' - p.write_text(s) + p.write_text(s) PY - - name: Normalize and commit only reviewed source files on the feature branch - run: | cargo fmt --all git config user.name 'github-actions[bot]' git config user.email '41898282+github-actions[bot]@users.noreply.github.com' - git add src tests + git add src/config.rs if ! git diff --cached --quiet; then - git commit -m 'fix: release reset H2 tunnels and verify stream capacity on the wire' + git commit -m 'style: flatten optional configuration paths' git push origin HEAD:feat/http2-proxy fi - - run: cargo test --all-targets --locked - run: cargo clippy --all-targets --locked -- -D warnings + - run: cargo test --all-targets --locked - run: cargo build --release --locked + - run: python3 scripts/test_curl_proxy.py --curl /usr/bin/curl From 2a7d65c90f8e25d0ff4c3a2f425e65490c9c494c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 19 Sep 2026 01:06:24 +0000 Subject: [PATCH 8/9] style: flatten optional configuration paths --- src/config.rs | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/config.rs b/src/config.rs index dfdc0d3..8731acb 100644 --- a/src/config.rs +++ b/src/config.rs @@ -82,20 +82,21 @@ impl Config { .with_context(|| format!("Cannot read configuration: {}", path.display()))?; let mut config = Self::parse(&text)?; // All policy and TLS paths are relative to the configuration, not cwd. - for file in [ + for value in [ &mut config.filter_file, &mut config.tls_cert, &mut config.tls_key, - ] { - if let Some(value) = file { - if Path::new(value).is_relative() { - *value = path - .parent() - .unwrap_or_else(|| Path::new(".")) - .join(&*value) - .to_string_lossy() - .into_owned(); - } + ] + .into_iter() + .flatten() + { + if Path::new(value).is_relative() { + *value = path + .parent() + .unwrap_or_else(|| Path::new(".")) + .join(&*value) + .to_string_lossy() + .into_owned(); } } Ok(config) From 66722d46be59ad63653b286bd046f7c20dd4c1a9 Mon Sep 17 00:00:00 2001 From: Ray Tien Date: Sat, 19 Sep 2026 09:07:43 +0800 Subject: [PATCH 9/9] ci: verify HTTP2 on Linux and macOS with real curl interoperability Remove the temporary feature-branch preparation workflow; retain only read-only checks. Add a TLS configuration example and ignore deployment private keys. Run all regressions, Clippy, release build and config checks. --- .github/workflows/ci.yml | 10 +++++- .github/workflows/prepare-http2.yml | 54 ----------------------------- config/certs/.gitignore | 3 ++ config/http2-tls.conf.example | 25 +++++++++++++ 4 files changed, 37 insertions(+), 55 deletions(-) delete mode 100644 .github/workflows/prepare-http2.yml create mode 100644 config/certs/.gitignore create mode 100644 config/http2-tls.conf.example diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1fce0f6..1666ad4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,7 +24,12 @@ jobs: components: rustfmt - run: cargo fmt --all -- --check test: - runs-on: ubuntu-latest + name: test (${{ matrix.os }}) + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + runs-on: ${{ matrix.os }} timeout-minutes: 15 steps: - uses: actions/checkout@v4 @@ -37,3 +42,6 @@ jobs: - run: cargo clippy --all-targets --locked -- -D warnings - run: cargo build --release --locked - run: ./target/release/tinyproxy-rust --check -c config/tinyproxy-rust.conf + - name: Verify TLS and HTTP2 interoperability with curl + if: runner.os == 'Linux' + run: python3 scripts/test_curl_proxy.py --curl /usr/bin/curl diff --git a/.github/workflows/prepare-http2.yml b/.github/workflows/prepare-http2.yml deleted file mode 100644 index 399f745..0000000 --- a/.github/workflows/prepare-http2.yml +++ /dev/null @@ -1,54 +0,0 @@ -name: Prepare HTTP2 branch -on: - push: - branches: [feat/http2-proxy] - paths: [.github/workflows/prepare-http2.yml] -permissions: - contents: write -concurrency: - group: prepare-http2 - cancel-in-progress: true -jobs: - prepare: - if: github.ref == 'refs/heads/feat/http2-proxy' - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - uses: actions/checkout@v4 - - uses: dtolnay/rust-toolchain@stable - with: - components: rustfmt, clippy - - name: Normalize the configuration iterator - run: | - python3 - <<'PY' - from pathlib import Path - p = Path('src/config.rs') - s = p.read_text() - if 'for file in [' in s: - start = s.index(' for file in [') - end = s.index(' Ok(config)', start) - s = s[:start] + ''' for value in [ - &mut config.filter_file, - &mut config.tls_cert, - &mut config.tls_key, - ].into_iter().flatten() { - if Path::new(value).is_relative() { - *value = path.parent().unwrap_or_else(|| Path::new(".")) - .join(&*value).to_string_lossy().into_owned(); - } - } - ''' + s[end:] - p.write_text(s) - PY - cargo fmt --all - git config user.name 'github-actions[bot]' - git config user.email '41898282+github-actions[bot]@users.noreply.github.com' - git add src/config.rs - if ! git diff --cached --quiet; then - git commit -m 'style: flatten optional configuration paths' - git push origin HEAD:feat/http2-proxy - fi - - run: cargo clippy --all-targets --locked -- -D warnings - - run: cargo test --all-targets --locked - - run: cargo build --release --locked - - run: python3 scripts/test_curl_proxy.py --curl /usr/bin/curl diff --git a/config/certs/.gitignore b/config/certs/.gitignore new file mode 100644 index 0000000..6630d37 --- /dev/null +++ b/config/certs/.gitignore @@ -0,0 +1,3 @@ +# Deployment certificates and private keys are never repository assets. +* +!.gitignore diff --git a/config/http2-tls.conf.example b/config/http2-tls.conf.example new file mode 100644 index 0000000..470a697 --- /dev/null +++ b/config/http2-tls.conf.example @@ -0,0 +1,25 @@ +# Optional TLS-only HTTP/1 + HTTP/2 listener. +# Copy to your own configuration and supply a certificate/key for the proxy +# hostname. Relative paths are resolved from this file's directory. +# This example is loopback-only and does not expose a public proxy. +Listen 127.0.0.1 +Port 8888 + +TLSCert certs/proxy-cert.pem +TLSKey certs/proxy-key.pem +TLSHandshakeTimeout 10 +HTTP2 Yes + +MaxClients 100 +MaxConcurrentStreams 32 +MaxInflightRequests 256 +Timeout 600 +HeaderTimeout 30 +ConnectTimeout 30 +ShutdownTimeout 5 +ConnectPort 443 +LogLevel Info + +# For remote clients, configure specific Allow/Deny rules and/or BasicAuth +# before changing Listen. Protect the key and configuration permissions. +# Do not enable AllowH2C here: TLS uses ALPN, not plaintext protocol detection.