HTTP/2 on the client side (#797)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Gregory SchierandClaude Opus 5.5 authored and GitHub committed 2026-10-30 00:31:49 -07:00
1 parent e82ffc53ad
commit 4d38a482f6
20 files changed
+1375 -126

No files matched your search

+37 -3
View File
@@ -37,8 +37,10 @@ pub async fn read_body(
) -> Result<DecodedBody, String> {
let raw = read_raw_body(blobs, &flow.id, body)?;
let stored_size = raw.len();
// A response that failed after its headers ended short on the wire.
let cut = body == FlowBody::Response && flow.status.is_some() && flow.error.is_some();
// A response that failed or was cancelled after its headers ended short on the wire.
let cut = body == FlowBody::Response
&& flow.status.is_some()
&& (flow.error.is_some() || flow.cancelled);
let wire_truncated = flow.truncated(body) || cut;
let encoding =
ContentEncoding::from_header(find_header(flow.headers(body), "content-encoding"));
@@ -90,7 +92,39 @@ mod tests {
let request = read_body(&blobs, &cut, FlowBody::Request, 1024).await.unwrap();
assert!(!request.truncated);
// With no headers there was never a response body to cut.
let refused = Flow { status: None, ..cut };
let refused = Flow { status: None, ..cut.clone() };
assert!(!read_body(&blobs, &refused, FlowBody::Response, 1024).await.unwrap().truncated);
// The client cancelling partway through cuts it short the same way.
let cancelled = Flow { error: None, cancelled: true, ..cut };
let body = read_body(&blobs, &cancelled, FlowBody::Response, 1024).await.unwrap();
assert_eq!((body.data.as_slice(), body.truncated), (&b"{\"rows\": ["[..], true));
}
#[tokio::test]
async fn cancelled_gzip_response_keeps_what_decoded() {
use std::io::Write;
let (_db, blobs, _rx) = yaak_models::init_in_memory().unwrap();
let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
gzip.write_all(&[b'z'; 4096]).unwrap();
let gzip = gzip.finish().unwrap();
let mut writer =
BodyChunkWriter::new(blobs.clone(), Flow::body_id("fl_gz", FlowBody::Response));
writer.write(&gzip[..gzip.len() / 2]).unwrap();
writer.finish().unwrap();
let flow = Flow {
id: "fl_gz".into(),
status: Some(200),
cancelled: true,
response_headers: vec![crate::models::ProxyHeader {
name: "content-encoding".into(),
value: "gzip".into(),
}],
..Default::default()
};
let body = read_body(&blobs, &flow, FlowBody::Response, 8192).await.unwrap();
assert!(body.truncated);
assert_eq!(body.decode_error, None);
}
}
+3
View File
@@ -140,6 +140,7 @@ mod tests {
ALTER TABLE flows DROP COLUMN client_name;
ALTER TABLE flows DROP COLUMN client_bundle_id;
ALTER TABLE flows DROP COLUMN client_path;
ALTER TABLE flows DROP COLUMN cancelled;
INSERT INTO flows (id, url, method) VALUES ('fl_old', 'https://example.com', 'GET');",
)
.unwrap();
@@ -150,6 +151,7 @@ mod tests {
assert_eq!(flows.len(), 1);
assert_eq!((flows[0].id.as_str(), flows[0].saved_request_id.as_deref()), ("fl_old", None));
assert_eq!((flows[0].client_pid, flows[0].client_name.as_deref()), (None, None));
assert!(!flows[0].cancelled);
}
#[test]
@@ -194,6 +196,7 @@ mod tests {
"client_name",
"client_bundle_id",
"client_path",
"cancelled",
] {
assert!(flow_columns.contains(&column.to_string()), "{column} in {flow_columns:?}");
}
+48 -2
View File
@@ -23,7 +23,7 @@ use crate::db::ProxyQueryManager;
use crate::macos::{SystemProxyBackend, SystemProxyStatus};
use crate::models::{Flow, FlowBody, FlowIden, ModelPayload, ProxyHeader, find_header};
use crate::save::{ClientDb, SaveFlowRequest, SaveFlowResponse, WorkspaceSummary};
use crate::settings::ProxySettings;
use crate::settings::{HttpVersion, ProxySettings};
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use chrono::{DateTime, Utc};
@@ -169,6 +169,7 @@ impl ProxyCtx {
.map_err(|e| format!("Failed to load proxy CA: {e}"))?;
let mut config = ProxyConfig::new(port.unwrap_or(settings.port), Arc::new(ca));
config.capture_body_limit = settings.capture_body_limit;
config.http2 = settings.http_version == HttpVersion::Auto;
// Filled once the engine has bound, since the lookup matches sockets by its port.
let attribution_slot: Arc<OnceLock<Attribution>> = Arc::new(OnceLock::new());
let slot = attribution_slot.clone();
@@ -404,6 +405,20 @@ impl ProxyCtx {
settings.save(&self.settings_path())
}
/// The HTTP versions offered to clients, saved in `settings.json` and applied to the running
/// engine's next connections.
pub fn set_http_version(&self, version: HttpVersion) -> Result<(), String> {
let mut settings = self.settings()?;
settings.http_version = version;
settings.save(&self.settings_path())?;
if let Ok(handle) = self.handle.lock()
&& let Some(handle) = handle.as_ref()
{
handle.set_http2(version == HttpVersion::Auto);
}
Ok(())
}
/// Intercepts again the hosts passed through after clients rejected the CA, as they no
/// longer will once it is trusted.
pub fn forget_passthrough(&self) {
@@ -646,6 +661,8 @@ pub struct GetProxyStateResponse {
pub recording: bool,
/// The system proxy turns on as the engine starts.
pub system_proxy_at_launch: bool,
/// The HTTP versions offered to clients.
pub http_version: HttpVersion,
/// Why the engine last failed to start, until it starts.
pub start_error: Option<String>,
/// Another process that owns the engine, such as the CLI daemon. While one does, this app
@@ -680,6 +697,13 @@ pub struct SetSystemProxyAtLaunchRequest {
pub enabled: bool,
}
#[derive(Deserialize, TS)]
#[ts(export, export_to = "gen_rpc.ts")]
#[serde(rename_all = "camelCase")]
pub struct SetHttpVersionRequest {
pub http_version: HttpVersion,
}
#[derive(Deserialize, TS)]
#[ts(export, export_to = "gen_rpc.ts")]
pub struct AppIconRequest {
@@ -874,6 +898,7 @@ async fn get_proxy_state(
configured_port: settings.port,
recording: ctx.recording(),
system_proxy_at_launch: settings.system_proxy_at_launch,
http_version: settings.http_version,
start_error: ctx.start_error(),
other_owner,
})
@@ -894,6 +919,11 @@ fn set_system_proxy_at_launch(
Ok(req.enabled)
}
fn set_http_version(ctx: &ProxyCtx, req: SetHttpVersionRequest) -> Result<HttpVersion, RpcError> {
ctx.set_http_version(req.http_version).map_err(rpc_error)?;
Ok(req.http_version)
}
async fn take_over(ctx: ProxyCtx, _req: TakeOverRequest) -> Result<bool, RpcError> {
ctx.take_over().await.map_err(rpc_error)?;
Ok(true)
@@ -1218,12 +1248,27 @@ fn run_event_loop(rx: std::sync::mpsc::Receiver<ProxyEvent>, sink: FlowSink) {
write_body_chunk(&mut f.response_body, &data);
}
}
ProxyEvent::ResponseBodyComplete { id, size, truncated, elapsed_ms, error } => {
ProxyEvent::ResponseBodyComplete {
id,
size,
truncated,
elapsed_ms,
error,
cancelled,
} => {
if let Some(mut f) = in_flight.remove(&id) {
f.flow.response_size = size as i64;
f.flow.response_truncated = truncated;
f.flow.elapsed_ms = Some(clamp_ms(elapsed_ms));
f.flow.error = error;
f.flow.cancelled = cancelled;
finish_flow(&db, &events, &attribution, f);
}
}
ProxyEvent::Cancelled { id, elapsed_ms } => {
if let Some(mut f) = in_flight.remove(&id) {
f.flow.elapsed_ms = Some(clamp_ms(elapsed_ms));
f.flow.cancelled = true;
finish_flow(&db, &events, &attribution, f);
}
}
@@ -1306,6 +1351,7 @@ define_rpc! {
list_flows(flows::FlowFilter) -> ListFlowsResponse,
set_recording(SetRecordingRequest) -> bool,
set_system_proxy_at_launch(SetSystemProxyAtLaunchRequest) -> bool,
set_http_version(SetHttpVersionRequest) -> HttpVersion,
}
async_commands {
app_icon(AppIconRequest) -> Option<String>,
@@ -53,6 +53,9 @@ pub struct Flow {
/// Milliseconds from `started_at` to the end of the response.
pub elapsed_ms: Option<i32>,
pub error: Option<String>,
/// The client gave up before the response ended, by resetting its HTTP/2 stream or closing
/// the connection. Not an error.
pub cancelled: bool,
/// The id of the Yaak request this flow was last saved as.
pub saved_request_id: Option<String>,
/// The process that opened the client connection, where the platform can tell (macOS).
@@ -155,6 +158,7 @@ impl UpsertModelInfo for Flow {
(ElapsedHeadersMs, self.elapsed_headers_ms.into()),
(ElapsedMs, self.elapsed_ms.into()),
(Error, self.error.into()),
(Cancelled, self.cancelled.into()),
(SavedRequestId, self.saved_request_id.into()),
(ClientPid, self.client_pid.into()),
(ClientName, self.client_name.into()),
@@ -183,6 +187,7 @@ impl UpsertModelInfo for Flow {
FlowIden::ElapsedHeadersMs,
FlowIden::ElapsedMs,
FlowIden::Error,
FlowIden::Cancelled,
FlowIden::SavedRequestId,
FlowIden::ClientPid,
FlowIden::ClientName,
@@ -218,6 +223,7 @@ impl UpsertModelInfo for Flow {
elapsed_headers_ms: r.get("elapsed_headers_ms")?,
elapsed_ms: r.get("elapsed_ms")?,
error: r.get("error")?,
cancelled: added_column(r, "cancelled")?.unwrap_or_default(),
saved_request_id: added_column(r, "saved_request_id")?,
client_pid: added_column(r, "client_pid")?,
client_name: added_column(r, "client_name")?,
+39 -3
View File
@@ -1,5 +1,6 @@
use serde::{Deserialize, Serialize};
use std::path::Path;
use ts_rs::TS;
use yaak_proxy::DEFAULT_CAPTURE_BODY_LIMIT;
/// `settings.json` in the proxy data directory. Missing keys take their defaults.
@@ -14,6 +15,8 @@ pub struct ProxySettings {
pub system_proxy_at_launch: bool,
/// Bytes of each request and response body stored per flow.
pub capture_body_limit: usize,
/// The HTTP versions offered to clients in intercepted HTTPS.
pub http_version: HttpVersion,
}
impl Default for ProxySettings {
@@ -22,10 +25,24 @@ impl Default for ProxySettings {
port: 9090,
system_proxy_at_launch: true,
capture_body_limit: DEFAULT_CAPTURE_BODY_LIMIT,
http_version: HttpVersion::Auto,
}
}
}
/// The HTTP versions offered to clients in intercepted HTTPS. Upstream, the engine speaks
/// whichever the server picks either way.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, TS)]
#[serde(rename_all = "camelCase")]
#[ts(export, export_to = "gen_rpc.ts")]
pub enum HttpVersion {
/// HTTP/2 or HTTP/1.1, as the client prefers.
#[default]
Auto,
/// HTTP/1.1 alone, for clients that misbehave on HTTP/2.
Http1Only,
}
impl ProxySettings {
/// The settings at `path`, or the defaults when there is no file.
pub fn load(path: &Path) -> Result<Self, String> {
@@ -70,8 +87,12 @@ mod tests {
fn round_trip() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
let settings =
ProxySettings { port: 8080, system_proxy_at_launch: false, capture_body_limit: 1024 };
let settings = ProxySettings {
port: 8080,
system_proxy_at_launch: false,
capture_body_limit: 1024,
http_version: HttpVersion::Http1Only,
};
settings.save(&path).unwrap();
assert_eq!(ProxySettings::load(&path).unwrap(), settings);
@@ -79,10 +100,25 @@ mod tests {
serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
assert_eq!(
json,
serde_json::json!({"port": 8080, "systemProxyAtLaunch": false, "captureBodyLimit": 1024})
serde_json::json!({
"port": 8080,
"systemProxyAtLaunch": false,
"captureBodyLimit": 1024,
"httpVersion": "http1Only",
})
);
}
#[test]
fn http_version_defaults_to_auto() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
std::fs::write(&path, r#"{"port": 8888}"#).unwrap();
assert_eq!(ProxySettings::load(&path).unwrap().http_version, HttpVersion::Auto);
std::fs::write(&path, r#"{"httpVersion": "auto"}"#).unwrap();
assert_eq!(ProxySettings::load(&path).unwrap().http_version, HttpVersion::Auto);
}
#[test]
fn the_earlier_system_proxy_key_carries_over() {
let dir = tempfile::tempdir().unwrap();