mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-12-04 13:56:23 +01:00
HTTP/2 on the client side (#797)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e82ffc53ad
commit
4d38a482f6
20 files changed
+1375
-126
No files matched your search
@@ -41,6 +41,11 @@ elapsedHeadersMs: number | null,
|
||||
* Milliseconds from `started_at` to the end of the response.
|
||||
*/
|
||||
elapsedMs: number | null, error: string | null,
|
||||
/**
|
||||
* The client gave up before the response ended, by resetting its HTTP/2 stream or closing
|
||||
* the connection. Not an error.
|
||||
*/
|
||||
cancelled: boolean,
|
||||
/**
|
||||
* The id of the Yaak request this flow was last saved as.
|
||||
*/
|
||||
|
||||
+13
-1
@@ -163,6 +163,10 @@ recording: boolean,
|
||||
* The system proxy turns on as the engine starts.
|
||||
*/
|
||||
systemProxyAtLaunch: boolean,
|
||||
/**
|
||||
* The HTTP versions offered to clients.
|
||||
*/
|
||||
httpVersion: HttpVersion,
|
||||
/**
|
||||
* Why the engine last failed to start, until it starts.
|
||||
*/
|
||||
@@ -175,6 +179,12 @@ otherOwner: OtherOwner | null, };
|
||||
|
||||
export type GlobalAction = "recording_toggle" | "flows_clear";
|
||||
|
||||
/**
|
||||
* The HTTP versions offered to clients in intercepted HTTPS. Upstream, the engine speaks
|
||||
* whichever the server picks either way.
|
||||
*/
|
||||
export type HttpVersion = "auto" | "http1Only";
|
||||
|
||||
export type ListActionsRequest = Record<string, never>;
|
||||
|
||||
export type ListActionsResponse = { actions: Array<[ActionInvocation, ActionMetadata]>, };
|
||||
@@ -222,7 +232,7 @@ export type ProxyStatePayload = { state: ProxyState, };
|
||||
|
||||
export type RpcEventSchema = { flows_cleared: FlowsClearedPayload, model_write: ModelPayload, proxy_state_changed: ProxyStatePayload, };
|
||||
|
||||
export type RpcSchema = { execute_action: [ActionInvocation, boolean], format_body: [FormatBodyRequest, string], list_actions: [ListActionsRequest, ListActionsResponse], list_flows: [FlowFilter, ListFlowsResponse], set_recording: [SetRecordingRequest, boolean], set_system_proxy_at_launch: [SetSystemProxyAtLaunchRequest, boolean], app_icon: [AppIconRequest, string | null], ca_status: [CaStatusRequest, CaStatus], ca_trust: [CaTrustRequest, CaStatus], clear_flows: [ClearFlowsRequest, number], export_har: [ExportHarRequest, number], filter_body: [FilterBodyRequest, FilterBodyResponse], get_flow_body: [GetFlowBodyRequest, GetFlowBodyResponse], get_proxy_state: [GetProxyStateRequest, GetProxyStateResponse], list_workspaces: [ListWorkspacesRequest, ListWorkspacesResponse], preview_save: [PreviewSaveRequest, SavePreview], save_flow: [SaveFlowToYaakRequest, SavedFlow], system_proxy_set: [SystemProxySetRequest, SystemProxyStatus], system_proxy_status: [SystemProxyStatusRequest, SystemProxyStatus], take_over: [TakeOverRequest, boolean], };
|
||||
export type RpcSchema = { execute_action: [ActionInvocation, boolean], format_body: [FormatBodyRequest, string], list_actions: [ListActionsRequest, ListActionsResponse], list_flows: [FlowFilter, ListFlowsResponse], set_recording: [SetRecordingRequest, boolean], set_system_proxy_at_launch: [SetSystemProxyAtLaunchRequest, boolean], set_http_version: [SetHttpVersionRequest, HttpVersion], app_icon: [AppIconRequest, string | null], ca_status: [CaStatusRequest, CaStatus], ca_trust: [CaTrustRequest, CaStatus], clear_flows: [ClearFlowsRequest, number], export_har: [ExportHarRequest, number], filter_body: [FilterBodyRequest, FilterBodyResponse], get_flow_body: [GetFlowBodyRequest, GetFlowBodyResponse], get_proxy_state: [GetProxyStateRequest, GetProxyStateResponse], list_workspaces: [ListWorkspacesRequest, ListWorkspacesResponse], preview_save: [PreviewSaveRequest, SavePreview], save_flow: [SaveFlowToYaakRequest, SavedFlow], system_proxy_set: [SystemProxySetRequest, SystemProxyStatus], system_proxy_status: [SystemProxyStatusRequest, SystemProxyStatus], take_over: [TakeOverRequest, boolean], };
|
||||
|
||||
export type SaveFlowToYaakRequest = { flowId: string, workspaceId: string, folderId?: string,
|
||||
/**
|
||||
@@ -272,6 +282,8 @@ export type ServiceProxy = {
|
||||
*/
|
||||
name: string, http: ProxySetting, https: ProxySetting, };
|
||||
|
||||
export type SetHttpVersionRequest = { httpVersion: HttpVersion, };
|
||||
|
||||
export type SetRecordingRequest = { enabled: boolean, };
|
||||
|
||||
export type SetSystemProxyAtLaunchRequest = { enabled: boolean, };
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- The client gave up on the flow, by resetting its HTTP/2 stream or closing the connection.
|
||||
ALTER TABLE flows ADD COLUMN cancelled BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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:?}");
|
||||
}
|
||||
|
||||
@@ -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")?,
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -67,6 +67,7 @@ async fn route(req: Request<Incoming>) -> Result<Response<Full<Bytes>>, Infallib
|
||||
.header("content-encoding", "gzip")
|
||||
.body(Full::new(Bytes::new()))
|
||||
.unwrap(),
|
||||
"/hang" => std::future::pending().await,
|
||||
// XML that only its body says is XML
|
||||
"/xml-as-text" => Response::builder()
|
||||
.header("content-type", "text/plain")
|
||||
@@ -106,8 +107,12 @@ async fn wait_for_flow(ctx: &ProxyCtx, url: &str) -> Flow {
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn flow_is_stored_with_its_bodies() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings =
|
||||
ProxySettings { port: 0, capture_body_limit: CAPTURE_LIMIT, system_proxy_at_launch: false };
|
||||
let settings = ProxySettings {
|
||||
port: 0,
|
||||
capture_body_limit: CAPTURE_LIMIT,
|
||||
system_proxy_at_launch: false,
|
||||
..Default::default()
|
||||
};
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
|
||||
let (events, _event_rx) = RpcEventEmitter::new();
|
||||
@@ -174,8 +179,12 @@ async fn flow_is_stored_with_its_bodies() {
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn early_response_keeps_request_totals() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings =
|
||||
ProxySettings { port: 0, capture_body_limit: CAPTURE_LIMIT, system_proxy_at_launch: false };
|
||||
let settings = ProxySettings {
|
||||
port: 0,
|
||||
capture_body_limit: CAPTURE_LIMIT,
|
||||
system_proxy_at_launch: false,
|
||||
..Default::default()
|
||||
};
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
|
||||
let (events, _event_rx) = RpcEventEmitter::new();
|
||||
@@ -204,11 +213,84 @@ async fn rpc(ctx: &ProxyCtx, cmd: &str, payload: Value) -> Result<Value, String>
|
||||
yaak_proxy_lib::build_router().dispatch(cmd, payload, ctx).await.map_err(|e| e.message)
|
||||
}
|
||||
|
||||
/// A request the client gives up on is stored as cancelled, not as an error.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn cancelled_flow_is_not_an_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() };
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
|
||||
let (events, _event_rx) = RpcEventEmitter::new();
|
||||
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
|
||||
ctx.start().unwrap();
|
||||
let port = ctx.port().unwrap();
|
||||
|
||||
let upstream = spawn_upstream().await;
|
||||
let client = reqwest::Client::builder()
|
||||
.proxy(reqwest::Proxy::all(format!("http://127.0.0.1:{port}")).unwrap())
|
||||
.timeout(Duration::from_millis(300))
|
||||
.build()
|
||||
.unwrap();
|
||||
let url = format!("http://{upstream}/hang");
|
||||
assert!(client.get(&url).send().await.unwrap_err().is_timeout());
|
||||
|
||||
let flow = wait_for_flow(&ctx, &url).await;
|
||||
assert!(flow.cancelled);
|
||||
assert_eq!((flow.error, flow.status), (None, None));
|
||||
assert!(flow.elapsed_ms.is_some());
|
||||
}
|
||||
|
||||
/// `http1Only` is saved and reaches the running engine: the next connection from a client that
|
||||
/// offers HTTP/2 speaks HTTP/1.1, and `auto` brings HTTP/2 back.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn http_version_setting_applies_to_new_connections() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings = ProxySettings { port: 0, system_proxy_at_launch: false, ..Default::default() };
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
|
||||
let (events, _event_rx) = RpcEventEmitter::new();
|
||||
let ctx = ProxyCtx::new(dir.path(), events).unwrap();
|
||||
ctx.start().unwrap();
|
||||
let port = ctx.port().unwrap();
|
||||
let ca = std::fs::read(dir.path().join("ca/ca.pem")).unwrap();
|
||||
// Nothing listens there, so each flow is a 502, but its client side is spoken all the same.
|
||||
let closed = TcpListener::bind("127.0.0.1:0").await.unwrap().local_addr().unwrap().port();
|
||||
|
||||
let mut sent = 0;
|
||||
let mut client_version = async || {
|
||||
sent += 1;
|
||||
// A client of its own, so a connection of its own.
|
||||
let client = reqwest::Client::builder()
|
||||
.proxy(reqwest::Proxy::all(format!("http://127.0.0.1:{port}")).unwrap())
|
||||
.add_root_certificate(reqwest::Certificate::from_pem(&ca).unwrap())
|
||||
.build()
|
||||
.unwrap();
|
||||
let url = format!("https://localhost:{closed}/{sent}");
|
||||
assert_eq!(client.get(&url).send().await.unwrap().status(), 502);
|
||||
wait_for_flow(&ctx, &url).await.client_http_version
|
||||
};
|
||||
|
||||
assert_eq!(client_version().await, "HTTP/2");
|
||||
let set = rpc(&ctx, "set_http_version", json!({"httpVersion": "http1Only"})).await.unwrap();
|
||||
assert_eq!(set, json!("http1Only"));
|
||||
assert_eq!(rpc(&ctx, "get_proxy_state", json!({})).await.unwrap()["httpVersion"], "http1Only");
|
||||
assert_eq!(client_version().await, "HTTP/1.1");
|
||||
|
||||
rpc(&ctx, "set_http_version", json!({"httpVersion": "auto"})).await.unwrap();
|
||||
assert_eq!(client_version().await, "HTTP/2");
|
||||
let saved = ProxySettings::load(&dir.path().join("settings.json")).unwrap();
|
||||
assert_eq!(saved.http_version, yaak_proxy_lib::settings::HttpVersion::Auto);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn body_rpcs() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let settings =
|
||||
ProxySettings { port: 0, capture_body_limit: CAPTURE_LIMIT, system_proxy_at_launch: false };
|
||||
let settings = ProxySettings {
|
||||
port: 0,
|
||||
capture_body_limit: CAPTURE_LIMIT,
|
||||
system_proxy_at_launch: false,
|
||||
..Default::default()
|
||||
};
|
||||
settings.save(&dir.path().join("settings.json")).unwrap();
|
||||
|
||||
let (events, _event_rx) = RpcEventEmitter::new();
|
||||
@@ -225,6 +307,7 @@ async fn body_rpcs() {
|
||||
"configuredPort": 0,
|
||||
"recording": true,
|
||||
"systemProxyAtLaunch": false,
|
||||
"httpVersion": "auto",
|
||||
"startError": null,
|
||||
"otherOwner": null,
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user